mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-21 16:12:40 +08:00
AnimationCurve (#8409)
* AnimationCurve * Mark curve frame values as uniquelyReferenced * Adjust modules * Update * Manually implements KeyframeCurve.iterator * TargetPath * Update * Fix BUG * Fix * Add size track * Update * Fix size; unit tests * fix split animation (#24) * CCONB animation clip; Remove integer track/channel/curve * Optimize key shared curves * Remove keyframecurve.empty * Exotic animation * Fix unit tests * start/end -> left/right * Curve range rename * Easing methods * Fix untyped track * Fix * fix upgradUnTypedTracks (#26) * Rename .interpMode -> .interpolationMode RealInterpMode -> RealInterpolationMode QuaternionInterpMode -> QuaternionInterpolationMode ExtrapMode -> ExtrapolationMode .preExtrap -> .preExtrapolation .postExtrap -> .postExtrapolation QuaternionCurve -> QuatCurve QuaternionKeyframeValue -> QuatKeyframeValue * Update pre/post extrap * Optimize-1 * Optimize-2 * Eliminate for-of * Mark deprecateds * Hide RealKeyframeValue/QuatKeyframeValue Constructor * Fix quat keyframe value name * Error ID * Fix RealKeyframeValue editor extras * Elimanate for-of forEach Co-authored-by: zheng han <sunstar198941@gmail.com>
This commit is contained in:
committed by
GitHub
parent
eb06667bda
commit
6d10f68ef8
Vendored
+2
@@ -10,12 +10,14 @@
|
||||
"Chukong",
|
||||
"clampf",
|
||||
"COCOSPLAY",
|
||||
"coeff",
|
||||
"deinterleave",
|
||||
"deserialization",
|
||||
"deserialize",
|
||||
"deserializes",
|
||||
"earcut",
|
||||
"emscripten",
|
||||
"endregion",
|
||||
"eventify",
|
||||
"eventified",
|
||||
"forin",
|
||||
|
||||
@@ -1747,6 +1747,70 @@ animation not added or already removed
|
||||
|
||||
already-playing
|
||||
|
||||
### 3920
|
||||
|
||||
Current context does not allow root motion.
|
||||
|
||||
### 3921
|
||||
|
||||
You provided a ill-formed track path. The last component of track path should be property key, or the setter should not be empty.
|
||||
|
||||
### 3922
|
||||
|
||||
Seems like we have animation for %s but are missing its parent joint %s in animation?
|
||||
|
||||
### 3923
|
||||
|
||||
Root motion is ignored since root bone could not be located in animation.
|
||||
|
||||
### 3924
|
||||
|
||||
Root motion is ignored since the root bone could not be located in scene.
|
||||
|
||||
### 3925
|
||||
|
||||
Target of hierarchy path should be of type Node.
|
||||
|
||||
### 3926
|
||||
|
||||
Node "%s" has no path "%s".
|
||||
|
||||
### 3927
|
||||
|
||||
Target of component path should be of type Node.
|
||||
|
||||
### 3928
|
||||
|
||||
Node "%s" has no component "%s".
|
||||
|
||||
### 3929
|
||||
|
||||
Target object has no property "%s".
|
||||
|
||||
### 3930
|
||||
|
||||
Can not decide type for untyped track: runtime binding does not provide a getter.
|
||||
|
||||
### 3931
|
||||
|
||||
Can not decide type for untyped track: got a unsupported value from runtime binding.
|
||||
|
||||
### 3932
|
||||
|
||||
Common targets should only target Vectors/`Size`/`Color`.
|
||||
|
||||
### 3933
|
||||
|
||||
Each curve that has common target should be numeric curve and targets string property.
|
||||
|
||||
### 3934
|
||||
|
||||
Misconfigured legacy curve: the first keyframe value is number but others aren't.
|
||||
|
||||
### 3935
|
||||
|
||||
We don't currently support conversion of \`CubicSplineQuatValue\`.
|
||||
|
||||
### 4000
|
||||
|
||||
<!-- DEPRECATED -->
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
|
||||
import { Vec3, Quat } from '../../core/math';
|
||||
import { Node } from '../../core/scene-graph';
|
||||
import { AnimationState } from '../../core/animation/animation-state';
|
||||
import { IBoundTarget } from '../../core/animation/bound-target';
|
||||
import { RuntimeBinding } from '../../core/animation/tracks/track';
|
||||
|
||||
export class BlendStateBuffer {
|
||||
private _nodeBlendStates: Map<Node, NodeBlendState> = new Map();
|
||||
@@ -41,7 +40,7 @@ export class BlendStateBuffer {
|
||||
property: P,
|
||||
host: BlendStateWriterHost,
|
||||
constants: boolean,
|
||||
): Omit<BlendStateWriterInternal<P>, 'node' | 'property'> {
|
||||
): BlendStateWriter<P> {
|
||||
const propertyBlendState = this.ref(node, property);
|
||||
return new BlendStateWriterInternal<P>(
|
||||
node,
|
||||
@@ -89,7 +88,7 @@ export interface BlendStateWriterHost {
|
||||
readonly weight: number;
|
||||
}
|
||||
|
||||
class BlendStateWriterInternal<P extends BlendingProperty> implements IBoundTarget {
|
||||
class BlendStateWriterInternal<P extends BlendingProperty> implements RuntimeBinding {
|
||||
constructor (
|
||||
private _node: Node,
|
||||
private _property: P,
|
||||
@@ -124,7 +123,7 @@ class BlendStateWriterInternal<P extends BlendingProperty> implements IBoundTarg
|
||||
|
||||
export type BlendStateWriter<P extends BlendingProperty> = Omit<BlendStateWriterInternal<P>, 'node' | 'property'>;
|
||||
|
||||
type BlendingProperty = keyof NodeBlendState['_properties'];
|
||||
export type BlendingProperty = keyof NodeBlendState['_properties'];
|
||||
|
||||
type BlendingPropertyValue<P extends BlendingProperty> = NonNullable<NodeBlendState['_properties'][P]>['blendedValue'];
|
||||
|
||||
|
||||
@@ -27,41 +27,25 @@
|
||||
* @packageDocumentation
|
||||
* @module animation
|
||||
*/
|
||||
|
||||
import {
|
||||
clamp01, Mat4, Quat, Vec3,
|
||||
} from '../../core/math';
|
||||
import { DataPoolManager } from './data-pool-manager';
|
||||
import { AnimationClip, IObjectCurveData } from '../../core/animation/animation-clip';
|
||||
import { HierarchyPath, isCustomPath, isPropertyPath } from '../../core/animation/target-path';
|
||||
import type { AnimationClip } from '../../core/animation/animation-clip';
|
||||
import { legacyCC } from '../../core/global-exports';
|
||||
import { BAKE_SKELETON_CURVE_SYMBOL } from '../../core/animation/internal-symbols';
|
||||
|
||||
type CurveData = Vec3[] | Quat[] | Mat4[];
|
||||
type ConvertedProps = Record<string, IPropertyCurve>;
|
||||
|
||||
interface IPropertyCurve {
|
||||
keys: number;
|
||||
values: CurveData;
|
||||
}
|
||||
interface ISkeletalCurveInfo {
|
||||
frames: number;
|
||||
sample: number;
|
||||
}
|
||||
interface IConvertedData {
|
||||
info: ISkeletalCurveInfo;
|
||||
data: Record<string, ConvertedProps>;
|
||||
}
|
||||
type BakeData = ReturnType<AnimationClip[typeof BAKE_SKELETON_CURVE_SYMBOL]>;
|
||||
|
||||
/**
|
||||
* 骨骼动画数据转换中心。
|
||||
*/
|
||||
export class SkelAnimDataHub {
|
||||
public static getOrExtract (clip: AnimationClip) {
|
||||
public static getOrExtract (clip: AnimationClip): BakeData {
|
||||
let data = SkelAnimDataHub.pool.get(clip);
|
||||
if (!data || data.info.sample !== clip.sample) {
|
||||
if (!data || data.samples !== clip.sample) {
|
||||
// release outdated render data
|
||||
if (data) { (legacyCC.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(clip); }
|
||||
data = convertToSkeletalCurves(clip);
|
||||
const frames = Math.ceil(clip.sample * clip.duration) + 1;
|
||||
const step = clip.sample;
|
||||
data = clip[BAKE_SKELETON_CURVE_SYMBOL](0, step, frames);
|
||||
SkelAnimDataHub.pool.set(clip, data);
|
||||
}
|
||||
return data;
|
||||
@@ -71,99 +55,5 @@ export class SkelAnimDataHub {
|
||||
SkelAnimDataHub.pool.delete(clip);
|
||||
}
|
||||
|
||||
protected static pool = new Map<AnimationClip, IConvertedData>();
|
||||
}
|
||||
|
||||
function convertToSkeletalCurves (clip: AnimationClip): IConvertedData {
|
||||
const data: Record<string, ConvertedProps> = {};
|
||||
clip.curves.forEach((curve) => {
|
||||
if (!curve.valueAdapter
|
||||
&& isCustomPath(curve.modifiers[0], HierarchyPath)
|
||||
&& isPropertyPath(curve.modifiers[1])) {
|
||||
const { path } = curve.modifiers[0];
|
||||
let cs = data[path];
|
||||
if (!cs) { cs = data[path] = {}; }
|
||||
const property = curve.modifiers[1] as string;
|
||||
cs[property] = { values: curve.data.values, keys: curve.data.keys }; // don't use curve.data directly
|
||||
}
|
||||
});
|
||||
const frames = Math.ceil(clip.sample * clip.duration) + 1;
|
||||
// lazy eval the conversion due to memory-heavy ops
|
||||
// many animation paths may not be actually in-use
|
||||
for (const path of Object.keys(data)) {
|
||||
const props = data[path];
|
||||
if (!props) { continue; }
|
||||
Object.defineProperty(props, 'worldMatrix', {
|
||||
get: () => {
|
||||
if (!props._worldMatrix) {
|
||||
const { position, rotation, scale } = props;
|
||||
// fixed step pre-sample
|
||||
convertToUniformSample(clip, position, frames);
|
||||
convertToUniformSample(clip, rotation, frames);
|
||||
convertToUniformSample(clip, scale, frames);
|
||||
// transform to world space
|
||||
convertToWorldSpace(data, path, props);
|
||||
}
|
||||
return props._worldMatrix;
|
||||
},
|
||||
});
|
||||
}
|
||||
const info: ISkeletalCurveInfo = {
|
||||
frames,
|
||||
sample: clip.sample,
|
||||
};
|
||||
return { info, data };
|
||||
}
|
||||
|
||||
function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, frames: number) {
|
||||
const keys = clip.keys[curve.keys];
|
||||
const values: CurveData = [];
|
||||
if (!keys || keys.length === 1) {
|
||||
for (let i = 0; i < frames; i++) {
|
||||
values[i] = curve.values[0].clone(); // never forget to clone
|
||||
}
|
||||
} else {
|
||||
const isQuat = curve.values[0] instanceof Quat;
|
||||
for (let i = 0, idx = 0; i < frames; i++) {
|
||||
let time = i / clip.sample;
|
||||
while (keys[idx] <= time) { idx++; }
|
||||
if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } else if (idx === 0) { idx = 1; }
|
||||
const from = curve.values[idx - 1].clone();
|
||||
const denom = keys[idx] - keys[idx - 1];
|
||||
const ratio = denom ? clamp01((time - keys[idx - 1]) / denom) : 1;
|
||||
if (isQuat) {
|
||||
(from as Quat).slerp(curve.values[idx] as Quat, ratio);
|
||||
} else {
|
||||
(from as Vec3).lerp(curve.values[idx] as Vec3, ratio);
|
||||
}
|
||||
values[i] = from;
|
||||
}
|
||||
}
|
||||
curve.values = values;
|
||||
}
|
||||
|
||||
function convertToWorldSpace (convertedProps: Record<string, ConvertedProps>, path: string, props: IObjectCurveData) {
|
||||
const oPos = props.position.values;
|
||||
const oRot = props.rotation.values;
|
||||
const oScale = props.scale.values;
|
||||
const matrix = oPos.map(() => new Mat4());
|
||||
const idx = path.lastIndexOf('/');
|
||||
let pMatrix: Mat4[] | null = null;
|
||||
if (idx > 0) {
|
||||
const name = path.substring(0, idx);
|
||||
const data = convertedProps[name];
|
||||
if (!data) { console.warn('no data for parent bone?'); return; }
|
||||
pMatrix = data.worldMatrix.values as Mat4[];
|
||||
}
|
||||
// all props should have the same length now
|
||||
for (let i = 0; i < oPos.length; i++) {
|
||||
const oT = oPos[i];
|
||||
const oR = oRot[i];
|
||||
const oS = oScale[i];
|
||||
const m = matrix[i];
|
||||
Mat4.fromRTS(m, oR, oT, oS);
|
||||
if (pMatrix) { Mat4.multiply(m, pMatrix[i], m); }
|
||||
}
|
||||
Object.keys(props).forEach((k) => delete props[k]);
|
||||
props._worldMatrix = { keys: 0, interpolate: false, values: matrix };
|
||||
private static pool = new Map<AnimationClip, BakeData>();
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ import { SkinnedMeshRenderer } from '../skinned-mesh-renderer';
|
||||
import { Mat4, Quat, Vec3 } from '../../core/math';
|
||||
import { IAnimInfo, JointAnimationInfo } from './skeletal-animation-utils';
|
||||
import { Node } from '../../core/scene-graph/node';
|
||||
import { AnimationClip, IRuntimeCurve } from '../../core/animation/animation-clip';
|
||||
import { AnimationClip } from '../../core/animation/animation-clip';
|
||||
import { AnimationState } from '../../core/animation/animation-state';
|
||||
import { SkeletalAnimation, Socket } from './skeletal-animation';
|
||||
import { SkelAnimDataHub } from './skeletal-animation-data-hub';
|
||||
@@ -53,8 +53,6 @@ interface ISocketData {
|
||||
frames: ITransform[];
|
||||
}
|
||||
|
||||
const noCurves: IRuntimeCurve[] = [];
|
||||
|
||||
export class SkeletalAnimationState extends AnimationState {
|
||||
protected _frames = 1;
|
||||
|
||||
@@ -89,12 +87,13 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
}
|
||||
this._parent = root.getComponent('cc.SkeletalAnimation') as SkeletalAnimation;
|
||||
const baked = this._parent.useBakedAnimation;
|
||||
super.initialize(root, baked ? noCurves : undefined);
|
||||
this._doNotCreateEval = baked;
|
||||
super.initialize(root);
|
||||
this._curvesInited = !baked;
|
||||
const { info } = SkelAnimDataHub.getOrExtract(this.clip);
|
||||
this._frames = info.frames - 1;
|
||||
const { frames, samples } = SkelAnimDataHub.getOrExtract(this.clip);
|
||||
this._frames = frames - 1;
|
||||
this._animInfo = this._animInfoMgr.getData(root.uuid);
|
||||
this._bakedDuration = this._frames / info.sample; // last key
|
||||
this._bakedDuration = this._frames / samples; // last key
|
||||
}
|
||||
|
||||
public onPlay () {
|
||||
@@ -128,13 +127,13 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
if (!socket.target) { continue; }
|
||||
const clipData = SkelAnimDataHub.getOrExtract(this.clip);
|
||||
let animPath = socket.path;
|
||||
let source = clipData.data[animPath];
|
||||
let source = clipData.joints[animPath];
|
||||
let animNode = targetNode;
|
||||
let downstream: Mat4 | undefined;
|
||||
while (!source) {
|
||||
const idx = animPath.lastIndexOf('/');
|
||||
animPath = animPath.substring(0, idx);
|
||||
source = clipData.data[animPath];
|
||||
source = clipData.joints[animPath];
|
||||
if (animNode) {
|
||||
if (!downstream) { downstream = Mat4.identity(m4_2); }
|
||||
Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale);
|
||||
@@ -143,8 +142,8 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
}
|
||||
if (idx < 0) { break; }
|
||||
}
|
||||
const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[];
|
||||
const { frames } = clipData.info;
|
||||
const curveData: Mat4[] | undefined = source && source.transforms;
|
||||
const { frames } = clipData;
|
||||
const transforms: ITransform[] = [];
|
||||
for (let f = 0; f < frames; f++) {
|
||||
let mat: Mat4;
|
||||
@@ -176,7 +175,8 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
}
|
||||
}
|
||||
|
||||
private _sampleCurvesBaked (ratio: number) {
|
||||
private _sampleCurvesBaked (time: number) {
|
||||
const ratio = time / this.duration;
|
||||
const info = this._animInfo!;
|
||||
const curFrame = (ratio * this._frames + 0.5) | 0;
|
||||
if (curFrame === info.data[0]) { return; }
|
||||
|
||||
@@ -272,7 +272,7 @@ export class JointTexturePool {
|
||||
if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; }
|
||||
const { joints, bindposes } = skeleton;
|
||||
const clipData = SkelAnimDataHub.getOrExtract(clip);
|
||||
const { frames } = clipData.info;
|
||||
const { frames } = clipData;
|
||||
let textureBuffer: Float32Array = null!; let buildTexture = false;
|
||||
const jointCount = joints.length;
|
||||
if (!texture) {
|
||||
@@ -394,14 +394,14 @@ export class JointTexturePool {
|
||||
const clipData = SkelAnimDataHub.getOrExtract(clip);
|
||||
for (let j = 0; j < jointCount; j++) {
|
||||
let animPath = joints[j];
|
||||
let source = clipData.data[animPath];
|
||||
let source = clipData.joints[animPath];
|
||||
let animNode = skinningRoot.getChildByPath(animPath);
|
||||
let downstream: Mat4 | undefined;
|
||||
let correctionPath: string | undefined;
|
||||
while (!source) {
|
||||
const idx = animPath.lastIndexOf('/');
|
||||
animPath = animPath.substring(0, idx);
|
||||
source = clipData.data[animPath];
|
||||
source = clipData.joints[animPath];
|
||||
if (animNode) {
|
||||
if (!downstream) { downstream = new Mat4(); }
|
||||
Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale);
|
||||
@@ -447,7 +447,7 @@ export class JointTexturePool {
|
||||
}
|
||||
}
|
||||
animInfos.push({
|
||||
curveData: source && source.worldMatrix.values as Mat4[], downstream, bindposeIdx, bindposeCorrection,
|
||||
curveData: source && source.transforms, downstream, bindposeIdx, bindposeCorrection,
|
||||
});
|
||||
}
|
||||
return animInfos;
|
||||
|
||||
@@ -174,7 +174,7 @@ export class SkeletalAnimation extends Animation {
|
||||
}
|
||||
|
||||
public querySockets () {
|
||||
const animPaths = (this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).data).sort()
|
||||
const animPaths = (this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort()
|
||||
.reduce((acc, cur) => (cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc)), [] as string[])) || [];
|
||||
if (!animPaths.length) { return ['please specify a valid default animation clip first']; }
|
||||
const out: string[] = [];
|
||||
|
||||
@@ -45,7 +45,7 @@ export function binarySearch (array: number[], value: number) {
|
||||
* otherwise, a negative number that is the bitwise complement of the index of the next element that is large than the searched value or,
|
||||
* if there is no larger element(include the case that the array is empty), the bitwise complement of array's length.
|
||||
*/
|
||||
export function binarySearchEpsilon (array: number[], value: number, EPSILON = 1e-6) {
|
||||
export function binarySearchEpsilon (array: Readonly<ArrayLike<number>>, value: number, EPSILON = 1e-6) {
|
||||
let low = 0;
|
||||
let high = array.length - 1;
|
||||
let middle = high >>> 1;
|
||||
@@ -71,15 +71,15 @@ export function binarySearchEpsilon (array: number[], value: number, EPSILON = 1
|
||||
* otherwise, a negative number that is the bitwise complement of the index of the next element that is large than the searched value or,
|
||||
* if there is no larger element(include the case that the array is empty), the bitwise complement of array's length.
|
||||
*/
|
||||
export function binarySearchBy<T> (array: T[], value: T, lessThan: (lhs: T, rhs: T) => boolean) {
|
||||
export function binarySearchBy<T, U> (array: T[], value: U, lessThan: (lhs: T, rhs: U) => number) {
|
||||
let low = 0;
|
||||
let high = array.length - 1;
|
||||
let middle = high >>> 1;
|
||||
for (; low <= high; middle = (low + high) >>> 1) {
|
||||
const test = array[middle];
|
||||
if (lessThan(value, test)) {
|
||||
if (lessThan(test, value) < 0) {
|
||||
high = middle - 1;
|
||||
} else if (lessThan(test, value)) {
|
||||
} else if (lessThan(test, value) > 0) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
return middle;
|
||||
|
||||
+1028
-271
File diff suppressed because it is too large
Load Diff
@@ -36,67 +36,7 @@ import { bezierByTime, BezierControlPoints } from './bezier';
|
||||
import * as easing from './easing';
|
||||
import { ILerpable, isLerpable } from './types';
|
||||
import { legacyCC } from '../global-exports';
|
||||
|
||||
/**
|
||||
* 表示曲线值,曲线值可以是任意类型,但必须符合插值方式的要求。
|
||||
*/
|
||||
export type CurveValue = any;
|
||||
|
||||
/**
|
||||
* 表示曲线的目标对象。
|
||||
*/
|
||||
export type CurveTarget = Record<string, any>;
|
||||
|
||||
/**
|
||||
* 内置帧时间渐变方式名称。
|
||||
*/
|
||||
export type EasingMethodName = keyof (typeof easing);
|
||||
|
||||
/**
|
||||
* 帧时间渐变方式。可能为内置帧时间渐变方式的名称或贝塞尔控制点。
|
||||
*/
|
||||
export type EasingMethod = EasingMethodName | BezierControlPoints;
|
||||
|
||||
type LerpFunction<T = any> = (from: T, to: T, t: number, dt: number) => T;
|
||||
|
||||
type CompressedEasingMethods = Record<number, EasingMethod>;
|
||||
|
||||
/**
|
||||
* 曲线数据。
|
||||
*/
|
||||
export interface IPropertyCurveData {
|
||||
/**
|
||||
* 曲线使用的时间轴。
|
||||
* @see {AnimationClip.keys}
|
||||
*/
|
||||
keys: number;
|
||||
|
||||
/**
|
||||
* 曲线值。曲线值的数量应和 `keys` 所引用时间轴的帧数相同。
|
||||
*/
|
||||
values: CurveValue[];
|
||||
|
||||
/**
|
||||
* 曲线任意两帧时间的渐变方式。仅当 `easingMethods === undefined` 时本字段才生效。
|
||||
*/
|
||||
easingMethod?: EasingMethod;
|
||||
|
||||
/**
|
||||
* 描述了每一帧时间到下一帧时间之间的渐变方式。
|
||||
*/
|
||||
easingMethods?: EasingMethod[] | CompressedEasingMethods;
|
||||
|
||||
/**
|
||||
* 是否进行插值。
|
||||
* @default true
|
||||
*/
|
||||
interpolate?: boolean;
|
||||
|
||||
/**
|
||||
* For internal usage only.
|
||||
*/
|
||||
_arrayLength?: number;
|
||||
}
|
||||
import type * as legacy from './legacy-clip-data';
|
||||
|
||||
export class RatioSampler {
|
||||
public ratios: number[];
|
||||
@@ -138,14 +78,14 @@ export class AnimCurve {
|
||||
return controlPoints as BezierControlPoints;
|
||||
}
|
||||
|
||||
public types?: Array<(EasingMethod | null)> = undefined;
|
||||
public types?: Array<(legacy.LegacyEasingMethod | null)> = undefined;
|
||||
|
||||
public type?: EasingMethod | null = null;
|
||||
public type?: legacy.LegacyEasingMethod | null = null;
|
||||
|
||||
/**
|
||||
* The values of the keyframes. (y)
|
||||
*/
|
||||
private _values: CurveValue[] = [];
|
||||
private _values: legacy.LegacyCurveValue[] = [];
|
||||
|
||||
/**
|
||||
* Lerp function used. If undefined, no lerp is performed.
|
||||
@@ -156,13 +96,13 @@ export class AnimCurve {
|
||||
|
||||
private _array?: any[];
|
||||
|
||||
constructor (propertyCurveData: Omit<IPropertyCurveData, 'keys'>, duration: number) {
|
||||
constructor (propertyCurveData: Omit<legacy.LegacyClipCurveData, 'keys'>, duration: number) {
|
||||
this._duration = duration;
|
||||
|
||||
// Install values.
|
||||
this._values = propertyCurveData.values;
|
||||
|
||||
const getCurveType = (easingMethod: EasingMethod) => {
|
||||
const getCurveType = (easingMethod: legacy.LegacyEasingMethod) => {
|
||||
if (typeof easingMethod === 'string') {
|
||||
return easingMethod;
|
||||
} else if (Array.isArray(easingMethod)) {
|
||||
@@ -323,7 +263,7 @@ legacyCC.sampleAnimationCurve = sampleAnimationCurve;
|
||||
* @param type - If it's Array, then ratio will be computed with bezierByTime.
|
||||
* If it's string, then ratio will be computed with cc.easing function
|
||||
*/
|
||||
export function computeRatioByType (ratio: number, type: EasingMethod) {
|
||||
export function computeRatioByType (ratio: number, type: legacy.LegacyEasingMethod) {
|
||||
if (typeof type === 'string') {
|
||||
const func = easing[type];
|
||||
if (func) {
|
||||
@@ -389,7 +329,7 @@ const selectLerpFx = (() => {
|
||||
return (from: Quat, to: Quat, t: number, dt: number) => Quat.slerp(tempValue, from, to, t);
|
||||
}
|
||||
|
||||
return (value: any): LerpFunction<any> | undefined => {
|
||||
return (value: any): legacy.LegacyLerpFunction<any> | undefined => {
|
||||
if (value === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -30,18 +30,14 @@
|
||||
|
||||
import { EDITOR } from 'internal:constants';
|
||||
import { Node } from '../scene-graph/node';
|
||||
import { AnimationClip, IRuntimeCurve } from './animation-clip';
|
||||
import { AnimCurve, RatioSampler } from './animation-curve';
|
||||
import { createBoundTarget, createBufferedTarget, IBufferedTarget, IBoundTarget } from './bound-target';
|
||||
import { AnimationClip } from './animation-clip';
|
||||
import { Playable } from './playable';
|
||||
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
|
||||
import { HierarchyPath, evaluatePath, TargetPath } from './target-path';
|
||||
import { BlendStateBuffer, BlendStateWriter } from '../../3d/skeletal-animation/skeletal-animation-blending';
|
||||
import { legacyCC } from '../global-exports';
|
||||
import { ccenum } from '../value-types/enum';
|
||||
import { IValueProxyFactory } from './value-proxy';
|
||||
import { assertIsNonNullable, assertIsTrue } from '../data/utils/asserts';
|
||||
import { debug } from '../platform/debug';
|
||||
import { PoseOutput } from './pose-output';
|
||||
|
||||
/**
|
||||
* @en The event type supported by Animation
|
||||
@@ -82,81 +78,6 @@ export enum EventType {
|
||||
FINISHED = 'finished',
|
||||
}
|
||||
ccenum(EventType);
|
||||
export class ICurveInstance {
|
||||
public commonTargetIndex = -1;
|
||||
|
||||
private _curve: AnimCurve;
|
||||
private _boundTarget: IBoundTarget;
|
||||
private _curveDetail: Omit<IRuntimeCurve, 'sampler'>;
|
||||
private declare _shouldLerp: boolean;
|
||||
|
||||
constructor (
|
||||
runtimeCurve: Omit<IRuntimeCurve, 'sampler'>,
|
||||
target: any,
|
||||
boundTarget: IBoundTarget,
|
||||
) {
|
||||
this._curve = runtimeCurve.curve;
|
||||
this._curveDetail = runtimeCurve;
|
||||
|
||||
this._boundTarget = boundTarget;
|
||||
this._shouldLerp = runtimeCurve.curve.hasLerp();
|
||||
}
|
||||
|
||||
public applySample (ratio: number, index: number, inBetween: boolean, samplerResultCache, weight: number) {
|
||||
let value: any;
|
||||
if (!this._shouldLerp || !inBetween) {
|
||||
value = this._curve.valueAt(index);
|
||||
} else {
|
||||
value = this._curve.valueBetween(
|
||||
ratio,
|
||||
samplerResultCache.from,
|
||||
samplerResultCache.fromRatio,
|
||||
samplerResultCache.to,
|
||||
samplerResultCache.toRatio,
|
||||
);
|
||||
}
|
||||
this._setValue(value, weight);
|
||||
}
|
||||
|
||||
private _setValue (value: any, weight: number) {
|
||||
this._boundTarget.setValue(value);
|
||||
}
|
||||
|
||||
get propertyName () { return ''; }
|
||||
|
||||
get curveDetail () {
|
||||
return this._curveDetail;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The curves in ISamplerSharedGroup share a same keys.
|
||||
*/
|
||||
interface ISamplerSharedGroup {
|
||||
sampler: RatioSampler | null;
|
||||
curves: ICurveInstance[];
|
||||
samplerResultCache: {
|
||||
from: number;
|
||||
fromRatio: number;
|
||||
to: number;
|
||||
toRatio: number;
|
||||
};
|
||||
}
|
||||
|
||||
function makeSamplerSharedGroup (sampler: RatioSampler | null): ISamplerSharedGroup {
|
||||
return {
|
||||
sampler,
|
||||
curves: [],
|
||||
samplerResultCache: {
|
||||
from: 0,
|
||||
fromRatio: 0,
|
||||
to: 0,
|
||||
toRatio: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const InvalidIndex = -1;
|
||||
|
||||
/**
|
||||
* @en
|
||||
@@ -204,8 +125,6 @@ export class AnimationState extends Playable {
|
||||
set wrapMode (value: WrapMode) {
|
||||
this._wrapMode = value;
|
||||
|
||||
if (EDITOR && !legacyCC.GAME_VIEW) { return; }
|
||||
|
||||
// dynamic change wrapMode will need reset time to 0
|
||||
this.time = 0;
|
||||
|
||||
@@ -214,6 +133,8 @@ export class AnimationState extends Playable {
|
||||
} else {
|
||||
this.repeatCount = 1;
|
||||
}
|
||||
|
||||
this._clipEventEval?.setWrapMode(value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -331,7 +252,9 @@ export class AnimationState extends Playable {
|
||||
|
||||
set weight (value) {
|
||||
this._weight = value;
|
||||
this._blendStateWriterHost.weight = value;
|
||||
if (this._poseOutput) {
|
||||
this._poseOutput.weight = value;
|
||||
}
|
||||
}
|
||||
|
||||
public frameRate = 0;
|
||||
@@ -348,16 +271,7 @@ export class AnimationState extends Playable {
|
||||
|
||||
private _clip: AnimationClip;
|
||||
private _useSimpleProcess = false;
|
||||
private _samplerSharedGroups: ISamplerSharedGroup[] = [];
|
||||
private _target: Node | null = null;
|
||||
private _ignoreIndex = InvalidIndex;
|
||||
/**
|
||||
* May be `null` due to failed to initialize.
|
||||
*/
|
||||
private _commonTargetStatuses: (null | {
|
||||
target: IBufferedTarget;
|
||||
changed: boolean;
|
||||
})[] = [];
|
||||
private _wrapMode = WrapMode.Normal;
|
||||
private _repeatCount = 1;
|
||||
private _delay = 0.0;
|
||||
@@ -367,13 +281,10 @@ export class AnimationState extends Playable {
|
||||
* When set new time to animation state, we should ensure the frame at the specified time being played at next update.
|
||||
*/
|
||||
private _currentFramePlayed = false;
|
||||
private declare _name: string;
|
||||
private _name: string;
|
||||
private _lastIterations = NaN;
|
||||
private _lastWrapInfo: WrappedInfo | null = null;
|
||||
private _lastWrapInfoEvent: WrappedInfo | null = null;
|
||||
private _wrappedInfo = new WrappedInfo();
|
||||
private _blendStateBuffer: BlendStateBuffer | null = null;
|
||||
private _blendStateWriters: BlendStateWriter<any>[] = [];
|
||||
private _allowLastFrame = false;
|
||||
private _blendStateWriterHost = {
|
||||
weight: 0.0,
|
||||
@@ -381,8 +292,14 @@ export class AnimationState extends Playable {
|
||||
private declare _playbackRange: { min: number; max: number; };
|
||||
private _playbackDuration = 0.0;
|
||||
private _invDuration = 1.0;
|
||||
private _poseOutput: PoseOutput | null = null;
|
||||
private _weight = 0.0;
|
||||
private _clipHasEvent = false;
|
||||
private _clipEval: ReturnType<AnimationClip['createEvaluator']> | undefined;
|
||||
private _clipEventEval: ReturnType<AnimationClip['createEventEvaluator']> | undefined;
|
||||
/**
|
||||
* For internal usage. Really hack...
|
||||
*/
|
||||
protected _doNotCreateEval = false;
|
||||
|
||||
constructor (clip: AnimationClip, name = '') {
|
||||
super();
|
||||
@@ -405,12 +322,17 @@ export class AnimationState extends Playable {
|
||||
return this._curveLoaded;
|
||||
}
|
||||
|
||||
public initialize (root: Node, propertyCurves?: readonly IRuntimeCurve[]) {
|
||||
public initialize (root: Node) {
|
||||
if (this._curveLoaded) { return; }
|
||||
this._curveLoaded = true;
|
||||
this._destroyBlendStateWriters();
|
||||
this._samplerSharedGroups.length = 0;
|
||||
this._blendStateBuffer = legacyCC.director.getAnimationManager()?.blendState ?? null;
|
||||
if (this._poseOutput) {
|
||||
this._poseOutput.destroy();
|
||||
this._poseOutput = null;
|
||||
}
|
||||
if (this._clipEval) {
|
||||
// TODO: destroy?
|
||||
this._clipEval = undefined;
|
||||
}
|
||||
this._targetNode = root;
|
||||
const clip = this._clip;
|
||||
|
||||
@@ -423,106 +345,38 @@ export class AnimationState extends Playable {
|
||||
this._playbackRange.max = clip.duration;
|
||||
this._playbackDuration = clip.duration;
|
||||
|
||||
this._clipHasEvent = clip.hasEvents();
|
||||
|
||||
if ((this.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop) {
|
||||
this.repeatCount = Infinity;
|
||||
} else {
|
||||
this.repeatCount = 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the bound target. Especially optimized for skeletal case.
|
||||
*/
|
||||
const createBoundTargetOptimized = (
|
||||
rootTarget: any,
|
||||
path: TargetPath[],
|
||||
valueAdapter: IValueProxyFactory | undefined,
|
||||
isConstant: boolean,
|
||||
): IBoundTarget | null => {
|
||||
if (!clip.enableTrsBlending || !isTargetingTRS(path) || !this._blendStateBuffer) {
|
||||
return createBoundTarget(rootTarget, path, valueAdapter);
|
||||
} else {
|
||||
const targetNode = evaluatePath(rootTarget, ...path.slice(0, path.length - 1));
|
||||
if (targetNode !== null && targetNode instanceof Node) {
|
||||
const propertyName = path[path.length - 1] as 'position' | 'rotation' | 'scale' | 'eulerAngles';
|
||||
const blendStateWriter = this._blendStateBuffer.createWriter(
|
||||
targetNode,
|
||||
propertyName,
|
||||
this._blendStateWriterHost,
|
||||
isConstant,
|
||||
);
|
||||
this._blendStateWriters.push(blendStateWriter);
|
||||
return blendStateWriter;
|
||||
}
|
||||
if (!this._doNotCreateEval) {
|
||||
const pose = legacyCC.director.getAnimationManager()?.blendState ?? null;
|
||||
if (pose) {
|
||||
this._poseOutput = new PoseOutput(pose);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
this._commonTargetStatuses = clip.commonTargets.map((commonTarget, index) => {
|
||||
const boundTarget = createBoundTargetOptimized(root, commonTarget.modifiers, commonTarget.valueAdapter, false);
|
||||
if (!boundTarget) {
|
||||
return null;
|
||||
}
|
||||
const target = createBufferedTarget(boundTarget);
|
||||
if (target === null) {
|
||||
return null;
|
||||
} else {
|
||||
return {
|
||||
target,
|
||||
changed: false,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
if (!propertyCurves) {
|
||||
propertyCurves = clip.getPropertyCurves();
|
||||
this._clipEval = clip.createEvaluator({
|
||||
target: root,
|
||||
pose: this._poseOutput ?? undefined,
|
||||
});
|
||||
}
|
||||
for (let iPropertyCurve = 0; iPropertyCurve < propertyCurves.length; ++iPropertyCurve) {
|
||||
const propertyCurve = propertyCurves[iPropertyCurve];
|
||||
if (propertyCurve.curve.empty()) {
|
||||
continue;
|
||||
}
|
||||
let samplerSharedGroup = this._samplerSharedGroups.find((value) => value.sampler === propertyCurve.sampler);
|
||||
if (!samplerSharedGroup) {
|
||||
samplerSharedGroup = makeSamplerSharedGroup(propertyCurve.sampler);
|
||||
this._samplerSharedGroups.push(samplerSharedGroup);
|
||||
}
|
||||
|
||||
let rootTarget: any;
|
||||
if (typeof propertyCurve.commonTarget === 'undefined') {
|
||||
rootTarget = root;
|
||||
} else {
|
||||
const commonTargetStatus = this._commonTargetStatuses[propertyCurve.commonTarget];
|
||||
if (!commonTargetStatus) {
|
||||
continue;
|
||||
}
|
||||
rootTarget = commonTargetStatus.target.peek();
|
||||
}
|
||||
|
||||
const boundTarget = createBoundTargetOptimized(
|
||||
rootTarget,
|
||||
propertyCurve.modifiers,
|
||||
propertyCurve.valueAdapter,
|
||||
propertyCurve.curve.constant(),
|
||||
);
|
||||
|
||||
if (boundTarget === null) {
|
||||
// warn(`Failed to bind "${root.name}" to curve in clip ${clip.name}: ${err}`);
|
||||
} else {
|
||||
const curveInstance = new ICurveInstance(
|
||||
propertyCurve,
|
||||
rootTarget,
|
||||
boundTarget,
|
||||
);
|
||||
curveInstance.commonTargetIndex = propertyCurve.commonTarget ?? -1;
|
||||
samplerSharedGroup.curves.push(curveInstance);
|
||||
}
|
||||
if (!(EDITOR && !legacyCC.GAME_VIEW)) {
|
||||
this._clipEventEval = clip.createEventEvaluator(this._targetNode);
|
||||
}
|
||||
}
|
||||
|
||||
public destroy () {
|
||||
this._destroyBlendStateWriters();
|
||||
if (!this.isMotionless) {
|
||||
legacyCC.director.getAnimationManager().removeAnimation(this);
|
||||
}
|
||||
if (this._poseOutput) {
|
||||
this._poseOutput.destroy();
|
||||
this._poseOutput = null;
|
||||
}
|
||||
// TODO: destroy?
|
||||
this._clipEval = undefined!;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -595,22 +449,8 @@ export class AnimationState extends Playable {
|
||||
this.time = time || 0.0;
|
||||
|
||||
if (!EDITOR || legacyCC.GAME_VIEW) {
|
||||
this._lastWrapInfoEvent = null;
|
||||
this._ignoreIndex = InvalidIndex;
|
||||
|
||||
const info = this.getWrappedInfo(time, this._wrappedInfo);
|
||||
const direction = info.direction;
|
||||
let frameIndex = this._clip.getEventGroupIndexAtRatio(info.ratio);
|
||||
|
||||
// only ignore when time not on a frame index
|
||||
if (frameIndex < 0) {
|
||||
frameIndex = ~frameIndex - 1;
|
||||
|
||||
// if direction is inverse, then increase index
|
||||
if (direction < 0) { frameIndex += 1; }
|
||||
|
||||
this._ignoreIndex = frameIndex;
|
||||
}
|
||||
this._clipEventEval?.ignore(info.ratio, info.direction);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,7 +479,7 @@ export class AnimationState extends Playable {
|
||||
|
||||
public sample () {
|
||||
const info = this.getWrappedInfo(this.time, this._wrappedInfo);
|
||||
this._sampleCurves(info.ratio);
|
||||
this._sampleCurves(info.time);
|
||||
if (!EDITOR || legacyCC.GAME_VIEW) {
|
||||
this._sampleEvents(info);
|
||||
}
|
||||
@@ -670,69 +510,13 @@ export class AnimationState extends Playable {
|
||||
this.emit(EventType.PAUSE, this);
|
||||
}
|
||||
|
||||
protected _sampleCurves (ratio: number) {
|
||||
const weight = this.weight;
|
||||
|
||||
const commonTargetStatuses = this._commonTargetStatuses;
|
||||
// Before we sample, we pull values of common targets.
|
||||
for (let iCommonTarget = 0, length = commonTargetStatuses.length; iCommonTarget < length; ++iCommonTarget) {
|
||||
const commonTargetStatus = commonTargetStatuses[iCommonTarget];
|
||||
if (!commonTargetStatus) {
|
||||
continue;
|
||||
}
|
||||
commonTargetStatus.target.pull();
|
||||
commonTargetStatus.changed = false;
|
||||
protected _sampleCurves (time: number) {
|
||||
const { _poseOutput: poseOutput, _clipEval: clipEval } = this;
|
||||
if (poseOutput) {
|
||||
poseOutput.weight = this.weight;
|
||||
}
|
||||
|
||||
const samplerSharedGroups = this._samplerSharedGroups;
|
||||
samplerSharedGroups.forEach((samplerSharedGroup) => {
|
||||
const { sampler, samplerResultCache } = samplerSharedGroup;
|
||||
let index = 0;
|
||||
let lerpRequired = false;
|
||||
if (!sampler) {
|
||||
index = 0;
|
||||
} else {
|
||||
index = sampler.sample(ratio);
|
||||
if (index < 0) {
|
||||
index = ~index;
|
||||
if (index <= 0) {
|
||||
index = 0;
|
||||
} else if (index >= sampler.ratios.length) {
|
||||
index = sampler.ratios.length - 1;
|
||||
} else {
|
||||
lerpRequired = true;
|
||||
samplerResultCache.from = index - 1;
|
||||
samplerResultCache.fromRatio = sampler.ratios[samplerResultCache.from];
|
||||
samplerResultCache.to = index;
|
||||
samplerResultCache.toRatio = sampler.ratios[samplerResultCache.to];
|
||||
index = samplerResultCache.from;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const curves = samplerSharedGroup.curves;
|
||||
for (let iCurveInstance = 0, szCurves = curves.length;
|
||||
iCurveInstance < szCurves; ++iCurveInstance) {
|
||||
const curveInstance = curves[iCurveInstance];
|
||||
curveInstance.applySample(ratio, index, lerpRequired, samplerResultCache, weight);
|
||||
if (curveInstance.commonTargetIndex >= 0) {
|
||||
const commonTargetStatus = commonTargetStatuses[curveInstance.commonTargetIndex];
|
||||
if (commonTargetStatus) {
|
||||
commonTargetStatus.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// After sample, we push values of common targets.
|
||||
for (let iCommonTarget = 0, length = commonTargetStatuses.length; iCommonTarget < length; ++iCommonTarget) {
|
||||
const commonTargetStatus = commonTargetStatuses[iCommonTarget];
|
||||
if (!commonTargetStatus) {
|
||||
continue;
|
||||
}
|
||||
if (commonTargetStatus.changed) {
|
||||
commonTargetStatus.target.push();
|
||||
}
|
||||
if (clipEval) {
|
||||
clipEval.evaluate(time);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,13 +559,12 @@ export class AnimationState extends Playable {
|
||||
|
||||
let time = this.time % playbackDuration;
|
||||
if (time < 0.0) { time += playbackDuration; }
|
||||
const ratio = (playbackStart + time) * this._invDuration;
|
||||
this._sampleCurves(ratio);
|
||||
const realTime = playbackStart + time;
|
||||
const ratio = realTime * this._invDuration;
|
||||
this._sampleCurves(playbackStart + time);
|
||||
|
||||
if (!EDITOR || legacyCC.GAME_VIEW) {
|
||||
if (this._clipHasEvent) {
|
||||
this._sampleEvents(this.getWrappedInfo(this.time, this._wrappedInfo));
|
||||
}
|
||||
this._sampleEvents(this.getWrappedInfo(this.time, this._wrappedInfo));
|
||||
}
|
||||
|
||||
if (this._allowLastFrame) {
|
||||
@@ -797,9 +580,6 @@ export class AnimationState extends Playable {
|
||||
}
|
||||
}
|
||||
|
||||
private cache (frames: number) {
|
||||
}
|
||||
|
||||
private _needReverse (currentIterations: number) {
|
||||
const wrapMode = this.wrapMode;
|
||||
let needReverse = false;
|
||||
@@ -885,77 +665,11 @@ export class AnimationState extends Playable {
|
||||
}
|
||||
|
||||
private _sampleEvents (wrapInfo: WrappedInfo) {
|
||||
const length = this._clip.eventGroups.length;
|
||||
let direction = wrapInfo.direction;
|
||||
let eventIndex = this._clip.getEventGroupIndexAtRatio(wrapInfo.ratio);
|
||||
if (eventIndex < 0) {
|
||||
eventIndex = ~eventIndex - 1;
|
||||
// If direction is inverse, increase index.
|
||||
if (direction < 0) {
|
||||
eventIndex += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._ignoreIndex !== eventIndex) {
|
||||
this._ignoreIndex = InvalidIndex;
|
||||
}
|
||||
|
||||
wrapInfo.frameIndex = eventIndex;
|
||||
|
||||
if (!this._lastWrapInfoEvent) {
|
||||
this._fireEvent(eventIndex);
|
||||
this._lastWrapInfoEvent = new WrappedInfo(wrapInfo);
|
||||
return;
|
||||
}
|
||||
|
||||
const wrapMode = this.wrapMode;
|
||||
const currentIterations = wrapIterations(wrapInfo.iterations);
|
||||
|
||||
const lastWrappedInfo = this._lastWrapInfoEvent;
|
||||
let lastIterations = wrapIterations(lastWrappedInfo.iterations);
|
||||
let lastIndex = lastWrappedInfo.frameIndex;
|
||||
const lastDirection = lastWrappedInfo.direction;
|
||||
|
||||
const iterationsChanged = lastIterations !== -1 && currentIterations !== lastIterations;
|
||||
|
||||
if (lastIndex === eventIndex && iterationsChanged && length === 1) {
|
||||
this._fireEvent(0);
|
||||
} else if (lastIndex !== eventIndex || iterationsChanged) {
|
||||
direction = lastDirection;
|
||||
|
||||
do {
|
||||
if (lastIndex !== eventIndex) {
|
||||
if (direction === -1 && lastIndex === 0 && eventIndex > 0) {
|
||||
if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
|
||||
direction *= -1;
|
||||
} else {
|
||||
lastIndex = length;
|
||||
}
|
||||
lastIterations++;
|
||||
} else if (direction === 1 && lastIndex === length - 1 && eventIndex < length - 1) {
|
||||
if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
|
||||
direction *= -1;
|
||||
} else {
|
||||
lastIndex = -1;
|
||||
}
|
||||
lastIterations++;
|
||||
}
|
||||
|
||||
if (lastIndex === eventIndex) {
|
||||
break;
|
||||
}
|
||||
if (lastIterations > currentIterations) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lastIndex += direction;
|
||||
|
||||
legacyCC.director.getAnimationManager().pushDelayEvent(this._fireEvent, this, [lastIndex]);
|
||||
} while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
|
||||
}
|
||||
|
||||
this._lastWrapInfoEvent.set(wrapInfo);
|
||||
this._clipEventEval?.sample(
|
||||
wrapInfo.ratio,
|
||||
wrapInfo.direction,
|
||||
wrapInfo.iterations,
|
||||
);
|
||||
}
|
||||
|
||||
private _emit (type, state) {
|
||||
@@ -964,29 +678,6 @@ export class AnimationState extends Playable {
|
||||
}
|
||||
}
|
||||
|
||||
private _fireEvent (index: number) {
|
||||
if (!this._targetNode || !this._targetNode.isValid) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { eventGroups } = this._clip;
|
||||
if (index < 0 || index >= eventGroups.length || this._ignoreIndex === index) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventGroup = eventGroups[index];
|
||||
const components = this._targetNode.components;
|
||||
for (const event of eventGroup.events) {
|
||||
const { functionName } = event;
|
||||
for (const component of components) {
|
||||
const fx = component[functionName];
|
||||
if (typeof fx === 'function') {
|
||||
fx.apply(component, event.parameters);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _onReplayOrResume () {
|
||||
legacyCC.director.getAnimationManager().addAnimation(this);
|
||||
}
|
||||
@@ -994,49 +685,6 @@ export class AnimationState extends Playable {
|
||||
private _onPauseOrStop () {
|
||||
legacyCC.director.getAnimationManager().removeAnimation(this);
|
||||
}
|
||||
|
||||
private _destroyBlendStateWriters () {
|
||||
if (this._blendStateWriters.length) {
|
||||
assertIsNonNullable(this._blendStateBuffer);
|
||||
}
|
||||
for (let iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
|
||||
this._blendStateBuffer!.destroyWriter(this._blendStateWriters[iBlendStateWriter]);
|
||||
}
|
||||
this._blendStateWriters.length = 0;
|
||||
if (this._blendStateBuffer) {
|
||||
this._blendStateBuffer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isTargetingTRS (path: TargetPath[]) {
|
||||
let prs: string | undefined;
|
||||
if (path.length === 1 && typeof path[0] === 'string') {
|
||||
prs = path[0];
|
||||
} else if (path.length > 1) {
|
||||
for (let i = 0; i < path.length - 1; ++i) {
|
||||
if (!(path[i] instanceof HierarchyPath)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
prs = path[path.length - 1] as string;
|
||||
}
|
||||
switch (prs) {
|
||||
case 'position':
|
||||
case 'scale':
|
||||
case 'rotation':
|
||||
case 'eulerAngles':
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function wrapIterations (iterations: number) {
|
||||
if (iterations - (iterations | 0) === 0) {
|
||||
iterations -= 1;
|
||||
}
|
||||
return iterations | 0;
|
||||
}
|
||||
|
||||
legacyCC.AnimationState = AnimationState;
|
||||
|
||||
@@ -31,5 +31,12 @@
|
||||
export * from './target-path';
|
||||
export * from './value-proxy';
|
||||
export { UniformProxyFactory } from './value-proxy-factories/uniform';
|
||||
export { MorphWeightsValueProxy, MorphWeightsAllValueProxy } from './value-proxy-factories/morph-weights';
|
||||
export { MorphWeightValueProxy, MorphWeightsValueProxy, MorphWeightsAllValueProxy } from './value-proxy-factories/morph-weights';
|
||||
export * from './cubic-spline-value';
|
||||
export { Track, TrackPath } from './tracks/track';
|
||||
export { RealTrack } from './tracks/real-track';
|
||||
export { VectorTrack } from './tracks/vector-track';
|
||||
export { QuatTrack } from './tracks/quat-track';
|
||||
export { ColorTrack } from './tracks/color-track';
|
||||
export { SizeTrack } from './tracks/size-track';
|
||||
export { ObjectTrack } from './tracks/object-track';
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
/*
|
||||
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @packageDocumentation
|
||||
* @hidden
|
||||
*/
|
||||
|
||||
import { Color, Size, Vec2, Vec3, Vec4 } from '../math';
|
||||
import { IValueProxy, IValueProxyFactory } from './value-proxy';
|
||||
import { isPropertyPath, PropertyPath, TargetPath, evaluatePath } from './target-path';
|
||||
import { error } from '../platform/debug';
|
||||
|
||||
export interface IBoundTarget {
|
||||
setValue (value: any): void;
|
||||
getValue (): any;
|
||||
}
|
||||
|
||||
export interface IBufferedTarget extends IBoundTarget {
|
||||
peek(): any;
|
||||
pull(): void;
|
||||
push(): void;
|
||||
}
|
||||
|
||||
export function createBoundTarget (target: any, modifiers: TargetPath[], valueAdapter?: IValueProxyFactory): null | IBoundTarget {
|
||||
const lastPath = modifiers[modifiers.length - 1];
|
||||
if (modifiers.length !== 0 && isPropertyPath(lastPath) && !valueAdapter) {
|
||||
const resultTarget = evaluatePath(target, ...modifiers.slice(0, modifiers.length - 1));
|
||||
if (resultTarget === null) {
|
||||
return null;
|
||||
}
|
||||
return new PropertyAccessTarget(resultTarget, lastPath);
|
||||
} else if (!valueAdapter) {
|
||||
error(`Empty animation curve.`);
|
||||
return null;
|
||||
} else {
|
||||
const resultTarget = evaluatePath(target, ...modifiers);
|
||||
if (resultTarget === null) {
|
||||
return null;
|
||||
}
|
||||
const proxy = valueAdapter.forTarget(resultTarget);
|
||||
return new ProxyTarget(proxy);
|
||||
}
|
||||
}
|
||||
|
||||
export function createBufferedTarget (boundTarget: IBoundTarget): null | IBufferedTarget {
|
||||
if (boundTarget === null) {
|
||||
return null;
|
||||
}
|
||||
const value = boundTarget.getValue();
|
||||
const copyable = getBuiltinCopy(value);
|
||||
if (!copyable) {
|
||||
error(`Value is not copyable!`);
|
||||
return null;
|
||||
}
|
||||
const buffer = copyable.createBuffer();
|
||||
const copy = copyable.copy;
|
||||
return Object.assign(boundTarget, {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
peek: () => buffer,
|
||||
pull: () => {
|
||||
const value = boundTarget.getValue();
|
||||
copy(buffer, value);
|
||||
},
|
||||
push: () => {
|
||||
boundTarget.setValue(buffer);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
interface ICopyable {
|
||||
createBuffer: () => any;
|
||||
copy: (out: any, source: any) => any;
|
||||
}
|
||||
|
||||
function SizeCopy (out: Size, source: Size) {
|
||||
return out.set(source);
|
||||
}
|
||||
|
||||
const getBuiltinCopy = (() => {
|
||||
const map = new Map<Constructor, ICopyable>();
|
||||
map.set(Vec2, { createBuffer: () => new Vec2(), copy: Vec2.copy });
|
||||
map.set(Vec3, { createBuffer: () => new Vec3(), copy: Vec3.copy });
|
||||
map.set(Vec4, { createBuffer: () => new Vec4(), copy: Vec4.copy });
|
||||
map.set(Color, { createBuffer: () => new Color(), copy: Color.copy });
|
||||
map.set(Size, { createBuffer: () => new Size(), copy: SizeCopy });
|
||||
return (value: any) => map.get(value?.constructor);
|
||||
})();
|
||||
|
||||
class PropertyAccessTarget implements IBoundTarget {
|
||||
constructor (object: unknown, propertyName: string | number) {
|
||||
this._object = object;
|
||||
this._propertyName = propertyName;
|
||||
}
|
||||
|
||||
setValue (value: unknown): void {
|
||||
(this._object as any)[this._propertyName] = value;
|
||||
}
|
||||
|
||||
getValue () {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return (this._object as any)[this._propertyName];
|
||||
}
|
||||
|
||||
private _object: unknown;
|
||||
private _propertyName: string | number;
|
||||
}
|
||||
|
||||
class ProxyTarget implements IBoundTarget {
|
||||
constructor (proxy: IValueProxy) {
|
||||
this._proxy = proxy;
|
||||
}
|
||||
|
||||
setValue (value: any): void {
|
||||
this._proxy.set(value);
|
||||
}
|
||||
|
||||
getValue () {
|
||||
const { _proxy: proxy } = this;
|
||||
if (!proxy.get) {
|
||||
error(`Target doesn't provide a get method.`);
|
||||
return null;
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return proxy.get();
|
||||
}
|
||||
}
|
||||
|
||||
private _proxy: IValueProxy;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { approx } from '../../core/math/utils';
|
||||
|
||||
/**
|
||||
* Removes keys which are linear interpolations of surrounding keys.
|
||||
* @param keys Input keys.
|
||||
* @param values Input values.
|
||||
* @param maxDiff Max error.
|
||||
* @returns The new keys `keys` and new values `values`.
|
||||
*/
|
||||
export function removeLinearKeys (keys: number[], values: number[], maxDiff = 1e-3) {
|
||||
const nKeys = keys.length;
|
||||
|
||||
if (nKeys < 3) {
|
||||
return {
|
||||
keys: keys.slice(),
|
||||
values: values.slice(),
|
||||
};
|
||||
}
|
||||
|
||||
const removeFlags = new Array<boolean>(nKeys).fill(false);
|
||||
// We may choose to use different key selection policy?
|
||||
// http://nfrechette.github.io/2016/12/07/anim_compression_key_reduction/
|
||||
const iLastKey = nKeys - 1;
|
||||
for (let iKey = 1; iKey< iLastKey; ++iKey) {
|
||||
// Should we select previous non-removed key?
|
||||
const iPrevious = iKey - 1;
|
||||
const iNext = iKey + 1;
|
||||
const { [iPrevious]: previousKey, [iKey]: currentKey, [iNext]: nextKey } = keys;
|
||||
const { [iPrevious]: previousValue, [iKey]: currentValue, [iNext]: nextValue } = values;
|
||||
const alpha = (currentKey - previousKey) / (nextKey - previousKey);
|
||||
const expectedValue = (nextValue - previousValue) * alpha + previousValue;
|
||||
if (approx(expectedValue, currentValue, maxDiff)) {
|
||||
removeFlags[iKey] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return filterFromRemoveFlags(keys, values, removeFlags);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes trivial frames.
|
||||
* @param keys Input keys.
|
||||
* @param values Input values.
|
||||
* @param maxDiff Max error.
|
||||
* @returns The new keys `keys` and new values `values`.
|
||||
*/
|
||||
export function removeTrivialKeys (keys: number[], values: number[], maxDiff = 1e-3) {
|
||||
const nKeys = keys.length;
|
||||
|
||||
if (nKeys < 2) {
|
||||
return {
|
||||
keys: keys.slice(),
|
||||
values: values.slice(),
|
||||
};
|
||||
}
|
||||
|
||||
const removeFlags = new Array<boolean>(nKeys).fill(false);
|
||||
for (let iKey = 1; iKey< nKeys; ++iKey) {
|
||||
// Should we select previous non-removed key?
|
||||
const iPrevious = iKey - 1;
|
||||
const { [iPrevious]: previousValue, [iKey]: currentValue } = values;
|
||||
if (approx(previousValue, currentValue, maxDiff)) {
|
||||
removeFlags[iKey] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return filterFromRemoveFlags(keys, values, removeFlags);
|
||||
}
|
||||
|
||||
function filterFromRemoveFlags (keys: number[], values: number[], removeFlags: boolean[]) {
|
||||
const nKeys = keys.length;
|
||||
|
||||
const nRemovals = removeFlags.reduce((n, removeFlag) => removeFlag ? n + 1 : n, 0);
|
||||
if (!nRemovals) {
|
||||
return {
|
||||
keys: keys.slice(),
|
||||
values: values.slice(),
|
||||
};
|
||||
}
|
||||
|
||||
const nNewKeyframes = nKeys - nRemovals;
|
||||
const newKeys = new Array<number>(nNewKeyframes).fill(0.0);
|
||||
const newValues = new Array<number>(nNewKeyframes).fill(0.0);
|
||||
for (let iNewKeys = 0, iKey = 0; iKey < nKeys; ++iKey) {
|
||||
if (!removeFlags[iKey]) {
|
||||
newKeys[iNewKeys] = keys[iKey];
|
||||
newValues[iNewKeys] = values[iKey];
|
||||
++iNewKeys;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
keys: newKeys,
|
||||
values: newValues,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import { QuatCurve, RealCurve } from '../../curves';
|
||||
import { KeySharedQuatCurves, KeySharedRealCurves } from '../../curves/keys-shared-curves';
|
||||
import { ccclass, serializable } from '../../data/decorators';
|
||||
import { Quat, Vec2, Vec3, Vec4 } from '../../math';
|
||||
import { CLASS_NAME_PREFIX_ANIM } from '../define';
|
||||
import { QuatTrack } from '../tracks/quat-track';
|
||||
import { RealTrack } from '../tracks/real-track';
|
||||
import { Binder, RuntimeBinding, TrackBinding, trackBindingTag, TrackPath } from '../tracks/track';
|
||||
import { VectorTrack } from '../tracks/vector-track';
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}CompressedData`)
|
||||
export class CompressedData {
|
||||
public compressRealTrack (track: RealTrack) {
|
||||
const curve = track.channel.curve;
|
||||
const mayBeCompressed = KeySharedRealCurves.allowedForCurve(curve);
|
||||
if (!mayBeCompressed) {
|
||||
return false;
|
||||
}
|
||||
this._tracks.push({
|
||||
type: CompressedDataTrackType.FLOAT,
|
||||
binding: track[trackBindingTag],
|
||||
components: [this._addRealCurve(curve)],
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public compressVectorTrack (vectorTrack: VectorTrack) {
|
||||
const nComponents = vectorTrack.componentsCount;
|
||||
const channels = vectorTrack.channels();
|
||||
const mayBeCompressed = channels.every(({ curve }) => KeySharedRealCurves.allowedForCurve(curve));
|
||||
if (!mayBeCompressed) {
|
||||
return false;
|
||||
}
|
||||
const components = new Array<CompressedCurvePointer>(nComponents);
|
||||
for (let i = 0; i < nComponents; ++i) {
|
||||
const channel = channels[i];
|
||||
components[i] = this._addRealCurve(channel.curve);
|
||||
}
|
||||
this._tracks.push({
|
||||
type:
|
||||
nComponents === 2
|
||||
? CompressedDataTrackType.VEC2
|
||||
: nComponents === 3
|
||||
? CompressedDataTrackType.VEC3
|
||||
: CompressedDataTrackType.VEC4,
|
||||
binding: vectorTrack[trackBindingTag],
|
||||
components,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public compressQuatTrack (track: QuatTrack) {
|
||||
const curve = track.channel.curve;
|
||||
const mayBeCompressed = KeySharedQuatCurves.allowedForCurve(curve);
|
||||
if (!mayBeCompressed) {
|
||||
return false;
|
||||
}
|
||||
this._quatTracks.push({
|
||||
binding: track[trackBindingTag],
|
||||
pointer: this._addQuatCurve(curve),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public createEval (binder: Binder) {
|
||||
const compressedDataEvalStatus: CompressedDataEvalStatus = {
|
||||
keySharedCurvesEvalStatuses: [],
|
||||
trackEvalStatuses: [],
|
||||
keysSharedQuatCurvesEvalStatues: [],
|
||||
quatTrackEvalStatuses: [],
|
||||
};
|
||||
|
||||
const {
|
||||
keySharedCurvesEvalStatuses,
|
||||
trackEvalStatuses,
|
||||
keysSharedQuatCurvesEvalStatues,
|
||||
quatTrackEvalStatuses,
|
||||
} = compressedDataEvalStatus;
|
||||
|
||||
for (const curves of this._curves) {
|
||||
keySharedCurvesEvalStatuses.push({
|
||||
curves,
|
||||
result: new Array(curves.curveCount).fill(0.0),
|
||||
});
|
||||
}
|
||||
|
||||
for (const track of this._tracks) {
|
||||
const trackTarget = binder(track.binding);
|
||||
if (!trackTarget) {
|
||||
continue;
|
||||
}
|
||||
let immediate: CompressedTrackImmediate | undefined;
|
||||
switch (track.type) {
|
||||
default:
|
||||
case CompressedDataTrackType.FLOAT:
|
||||
break;
|
||||
case CompressedDataTrackType.VEC2:
|
||||
immediate = new Vec2();
|
||||
break;
|
||||
case CompressedDataTrackType.VEC3:
|
||||
immediate = new Vec3();
|
||||
break;
|
||||
case CompressedDataTrackType.VEC4:
|
||||
immediate = new Vec4();
|
||||
break;
|
||||
}
|
||||
trackEvalStatuses.push({
|
||||
type: track.type,
|
||||
target: trackTarget,
|
||||
curves: track.components,
|
||||
immediate,
|
||||
});
|
||||
}
|
||||
|
||||
for (const curves of this._quatCurves) {
|
||||
keysSharedQuatCurvesEvalStatues.push({
|
||||
curves,
|
||||
result: Array.from({ length: curves.curveCount }, () => new Quat()),
|
||||
});
|
||||
}
|
||||
|
||||
for (const track of this._quatTracks) {
|
||||
const trackTarget = binder(track.binding);
|
||||
if (!trackTarget) {
|
||||
continue;
|
||||
}
|
||||
quatTrackEvalStatuses.push({
|
||||
target: trackTarget,
|
||||
curve: track.pointer,
|
||||
});
|
||||
}
|
||||
|
||||
return new CompressedDataEvaluator(compressedDataEvalStatus);
|
||||
}
|
||||
|
||||
public collectAnimatedJoints () {
|
||||
const joints: string[] = [];
|
||||
|
||||
for (const track of this._tracks) {
|
||||
const trsPath = track.binding.parseTrsPath();
|
||||
if (trsPath) {
|
||||
joints.push(trsPath.node);
|
||||
}
|
||||
}
|
||||
|
||||
return joints;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _curves: KeySharedRealCurves[] = [];
|
||||
|
||||
@serializable
|
||||
private _tracks: CompressedTrack[] = [];
|
||||
|
||||
@serializable
|
||||
private _quatCurves: KeySharedQuatCurves[] = [];
|
||||
|
||||
@serializable
|
||||
private _quatTracks: CompressedQuatTrack[] = [];
|
||||
|
||||
private _addRealCurve (curve: RealCurve): CompressedCurvePointer {
|
||||
const times = Array.from(curve.times());
|
||||
let iKeySharedCurves = this._curves.findIndex((shared) => shared.matchCurve(curve));
|
||||
if (iKeySharedCurves < 0) {
|
||||
iKeySharedCurves = this._curves.length;
|
||||
const keySharedCurves = new KeySharedRealCurves(times);
|
||||
this._curves.push(keySharedCurves);
|
||||
}
|
||||
const iCurve = this._curves[iKeySharedCurves].curveCount;
|
||||
this._curves[iKeySharedCurves].addCurve(curve);
|
||||
return {
|
||||
shared: iKeySharedCurves,
|
||||
component: iCurve,
|
||||
};
|
||||
}
|
||||
|
||||
public _addQuatCurve (curve: QuatCurve): CompressedQuatCurvePointer {
|
||||
const times = Array.from(curve.times());
|
||||
let iKeySharedCurves = this._quatCurves.findIndex((shared) => shared.matchCurve(curve));
|
||||
if (iKeySharedCurves < 0) {
|
||||
iKeySharedCurves = this._quatCurves.length;
|
||||
const keySharedCurves = new KeySharedQuatCurves(times);
|
||||
this._quatCurves.push(keySharedCurves);
|
||||
}
|
||||
const iCurve = this._quatCurves[iKeySharedCurves].curveCount;
|
||||
this._quatCurves[iKeySharedCurves].addCurve(curve);
|
||||
return {
|
||||
shared: iKeySharedCurves,
|
||||
curve: iCurve,
|
||||
};
|
||||
}
|
||||
|
||||
public validate () {
|
||||
return this._tracks.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
export class CompressedDataEvaluator {
|
||||
constructor (compressedDataEvalStatus: CompressedDataEvalStatus) {
|
||||
this._compressedDataEvalStatus = compressedDataEvalStatus;
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
const {
|
||||
keySharedCurvesEvalStatuses,
|
||||
trackEvalStatuses: compressedTrackEvalStatuses,
|
||||
keysSharedQuatCurvesEvalStatues,
|
||||
quatTrackEvalStatuses,
|
||||
} = this._compressedDataEvalStatus;
|
||||
|
||||
const getPreEvaluated = (pointer: CompressedCurvePointer) => keySharedCurvesEvalStatuses[pointer.shared].result[pointer.component];
|
||||
|
||||
for (const { curves, result } of keySharedCurvesEvalStatuses) {
|
||||
curves.evaluate(time, result);
|
||||
}
|
||||
|
||||
for (const { type, target, immediate, curves } of compressedTrackEvalStatuses) {
|
||||
let value: unknown = immediate;
|
||||
switch (type) {
|
||||
default:
|
||||
break;
|
||||
case CompressedDataTrackType.FLOAT:
|
||||
value = getPreEvaluated(curves[0]);
|
||||
break;
|
||||
case CompressedDataTrackType.VEC2:
|
||||
Vec2.set(
|
||||
value as Vec2,
|
||||
getPreEvaluated(curves[0]),
|
||||
getPreEvaluated(curves[1]),
|
||||
);
|
||||
break;
|
||||
case CompressedDataTrackType.VEC3:
|
||||
Vec3.set(
|
||||
value as Vec3,
|
||||
getPreEvaluated(curves[0]),
|
||||
getPreEvaluated(curves[1]),
|
||||
getPreEvaluated(curves[2]),
|
||||
);
|
||||
break;
|
||||
case CompressedDataTrackType.VEC4:
|
||||
Vec4.set(
|
||||
value as Vec4,
|
||||
getPreEvaluated(curves[0]),
|
||||
getPreEvaluated(curves[1]),
|
||||
getPreEvaluated(curves[2]),
|
||||
getPreEvaluated(curves[4]),
|
||||
);
|
||||
break;
|
||||
}
|
||||
target.setValue(value);
|
||||
}
|
||||
|
||||
for (const { curves, result } of keysSharedQuatCurvesEvalStatues) {
|
||||
curves.evaluate(time, result);
|
||||
}
|
||||
|
||||
for (const { target, curve } of quatTrackEvalStatuses) {
|
||||
target.setValue(keysSharedQuatCurvesEvalStatues[curve.shared].result[curve.curve]);
|
||||
}
|
||||
}
|
||||
|
||||
private _compressedDataEvalStatus: CompressedDataEvalStatus;
|
||||
}
|
||||
|
||||
interface CompressedTrack {
|
||||
binding: TrackBinding;
|
||||
type: CompressedDataTrackType;
|
||||
components: CompressedCurvePointer[];
|
||||
}
|
||||
|
||||
interface CompressedQuatTrack {
|
||||
binding: TrackBinding;
|
||||
pointer: CompressedQuatCurvePointer;
|
||||
}
|
||||
|
||||
enum CompressedDataTrackType {
|
||||
FLOAT,
|
||||
VEC2,
|
||||
VEC3,
|
||||
VEC4,
|
||||
}
|
||||
|
||||
type CompressedTrackImmediate = Vec2 | Vec3 | Vec4;
|
||||
|
||||
interface CompressedDataEvalStatus {
|
||||
keySharedCurvesEvalStatuses: Array<{
|
||||
curves: KeySharedRealCurves;
|
||||
result: number[];
|
||||
}>;
|
||||
|
||||
trackEvalStatuses: Array<{
|
||||
type: CompressedDataTrackType;
|
||||
target: RuntimeBinding;
|
||||
immediate: CompressedTrackImmediate | undefined;
|
||||
curves: CompressedCurvePointer[];
|
||||
}>;
|
||||
|
||||
keysSharedQuatCurvesEvalStatues: Array<{
|
||||
curves: KeySharedQuatCurves;
|
||||
result: Quat[];
|
||||
}>;
|
||||
|
||||
quatTrackEvalStatuses: Array<{
|
||||
target: RuntimeBinding;
|
||||
curve: CompressedQuatCurvePointer;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface CompressedCurvePointer {
|
||||
shared: number;
|
||||
component: number;
|
||||
}
|
||||
|
||||
interface CompressedQuatCurvePointer {
|
||||
shared: number;
|
||||
curve: number;
|
||||
}
|
||||
@@ -112,16 +112,20 @@ function makeCubicSplineValueConstructor<T> (
|
||||
export const CubicSplineVec2Value = makeCubicSplineValueConstructor(
|
||||
'cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd,
|
||||
);
|
||||
|
||||
export type CubicSplineVec2Value = ICubicSplineValue<Vec2>;
|
||||
legacyCC.CubicSplineVec2Value = CubicSplineVec2Value;
|
||||
|
||||
export const CubicSplineVec3Value = makeCubicSplineValueConstructor(
|
||||
'cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd,
|
||||
);
|
||||
export type CubicSplineVec3Value = ICubicSplineValue<Vec3>;
|
||||
legacyCC.CubicSplineVec3Value = CubicSplineVec3Value;
|
||||
|
||||
export const CubicSplineVec4Value = makeCubicSplineValueConstructor(
|
||||
'cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd,
|
||||
);
|
||||
export type CubicSplineVec4Value = ICubicSplineValue<Vec4>;
|
||||
legacyCC.CubicSplineVec4Value = CubicSplineVec4Value;
|
||||
|
||||
export const CubicSplineQuatValue = makeCubicSplineValueConstructor(
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export const CLASS_NAME_PREFIX_ANIM = 'cc.animation.';
|
||||
|
||||
export const createEvalSymbol = Symbol('CreateEval');
|
||||
@@ -0,0 +1,543 @@
|
||||
import { EDITOR } from 'internal:constants';
|
||||
import { binarySearchEpsilon } from '../../algorithm/binary-search';
|
||||
import { ccclass, serializable } from '../../data/decorators';
|
||||
import { assertIsTrue } from '../../data/utils/asserts';
|
||||
import { Quat, Vec3 } from '../../math';
|
||||
import { error } from '../../platform/debug';
|
||||
import { CLASS_NAME_PREFIX_ANIM } from '../define';
|
||||
import { Binder, RuntimeBinding, TrackBinding, TrackPath } from '../tracks/track';
|
||||
|
||||
/**
|
||||
* Animation that:
|
||||
* - does not exposed by users;
|
||||
* - does not compatible with regular animation;
|
||||
* - non-editable;
|
||||
* - currently only generated imported from model file.
|
||||
*/
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticAnimation`)
|
||||
export class ExoticAnimation {
|
||||
public createEvaluator (binder: Binder) {
|
||||
return new ExoticTrsAnimationEvaluator(this._nodeAnimations, binder);
|
||||
}
|
||||
|
||||
public addNodeAnimation (path: string) {
|
||||
const nodeAnimation = new ExoticNodeAnimation(path);
|
||||
this._nodeAnimations.push(nodeAnimation);
|
||||
return nodeAnimation;
|
||||
}
|
||||
|
||||
public collectAnimatedJoints () {
|
||||
return Array.from(new Set(this._nodeAnimations.map(({ path }) => path)));
|
||||
}
|
||||
|
||||
public split (from: number, to: number) {
|
||||
if (!EDITOR) {
|
||||
// TODO: better handling
|
||||
error(`split() only valid in Editor.`);
|
||||
return this;
|
||||
}
|
||||
const newAnimation = new ExoticAnimation();
|
||||
newAnimation._nodeAnimations = this._nodeAnimations.map((nodeAnimation) => nodeAnimation.split(from, to));
|
||||
return newAnimation;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _nodeAnimations: ExoticNodeAnimation[] = [];
|
||||
}
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticNodeAnimation`)
|
||||
class ExoticNodeAnimation {
|
||||
constructor (path: string) {
|
||||
this._path = path;
|
||||
}
|
||||
|
||||
public createPosition (times: FloatArray, values: FloatArray) {
|
||||
this._position = new ExoticVec3Track(times, values);
|
||||
}
|
||||
|
||||
public createRotation (times: FloatArray, values: FloatArray) {
|
||||
this._rotation = new ExoticQuatTrack(times, values);
|
||||
}
|
||||
|
||||
public createScale (times: FloatArray, values: FloatArray) {
|
||||
this._scale = new ExoticVec3Track(times, values);
|
||||
}
|
||||
|
||||
public createEvaluator (binder: Binder) {
|
||||
return new ExoticNodeAnimationEvaluator(
|
||||
this._path,
|
||||
this._position,
|
||||
this._rotation,
|
||||
this._scale,
|
||||
binder,
|
||||
);
|
||||
}
|
||||
|
||||
public split (from: number, to: number) {
|
||||
if (!EDITOR) {
|
||||
// TODO: better handling
|
||||
error(`split() only valid in Editor.`);
|
||||
return this;
|
||||
}
|
||||
const newAnimation = new ExoticNodeAnimation(this._path);
|
||||
const {
|
||||
_position: position,
|
||||
_rotation: rotation,
|
||||
_scale: scale,
|
||||
} = this;
|
||||
if (position) {
|
||||
newAnimation._position = position.split(from, to);
|
||||
}
|
||||
if (rotation) {
|
||||
newAnimation._rotation = rotation.split(from, to);
|
||||
}
|
||||
if (scale) {
|
||||
newAnimation._scale = scale.split(from, to);
|
||||
}
|
||||
return newAnimation;
|
||||
}
|
||||
|
||||
get path () {
|
||||
return this._path;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _path = '';
|
||||
|
||||
@serializable
|
||||
private _position: ExoticVec3Track | null = null;
|
||||
|
||||
@serializable
|
||||
private _rotation: ExoticQuatTrack | null = null;
|
||||
|
||||
@serializable
|
||||
private _scale: ExoticVec3Track | null = null;
|
||||
}
|
||||
|
||||
interface ExoticTrackValues<TValue extends Vec3 | Quat> {
|
||||
get (index: number, resultValue: TValue): void;
|
||||
|
||||
lerp(prevIndex: number,
|
||||
nextIndex: number,
|
||||
ratio: number,
|
||||
prevValue: TValue,
|
||||
nextValue: TValue,
|
||||
resultValue: TValue): void;
|
||||
}
|
||||
|
||||
type MayBeQuantized = FloatArray | QuantizedFloatArray;
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticVec3TrackValues`)
|
||||
class ExoticVec3TrackValues implements ExoticTrackValues<Vec3> {
|
||||
constructor (values: FloatArray) {
|
||||
this._values = values;
|
||||
this._isQuantized = false;
|
||||
}
|
||||
|
||||
public quantize (type: QuantizationType) {
|
||||
assertIsTrue(!this._isQuantized);
|
||||
this._values = quantize(this._values as FloatArray, type);
|
||||
this._isQuantized = true;
|
||||
}
|
||||
|
||||
public get (index: number, resultValue: Vec3): void {
|
||||
const {
|
||||
_values: values,
|
||||
_isQuantized: isQuantized,
|
||||
} = this;
|
||||
if (isQuantized) {
|
||||
loadVec3FromQuantized(values as QuantizedFloatArray, index, resultValue);
|
||||
} else {
|
||||
Vec3.fromArray(resultValue, values as FloatArray, index * 3);
|
||||
}
|
||||
}
|
||||
|
||||
public lerp (
|
||||
prevIndex: number,
|
||||
nextIndex: number,
|
||||
ratio: number,
|
||||
prevValue: Vec3,
|
||||
nextValue: Vec3,
|
||||
resultValue: Vec3,
|
||||
): void {
|
||||
const {
|
||||
_values: values,
|
||||
_isQuantized: isQuantized,
|
||||
} = this;
|
||||
if (isQuantized) {
|
||||
loadVec3FromQuantized(values as QuantizedFloatArray, prevIndex, prevValue);
|
||||
loadVec3FromQuantized(values as QuantizedFloatArray, nextIndex, nextValue);
|
||||
} else {
|
||||
Vec3.fromArray(prevValue, values as FloatArray, prevIndex * 3);
|
||||
Vec3.fromArray(nextValue, values as FloatArray, nextIndex * 3);
|
||||
}
|
||||
Vec3.lerp(resultValue, prevValue, nextValue, ratio);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _values: MayBeQuantized;
|
||||
|
||||
@serializable
|
||||
private _isQuantized: boolean;
|
||||
}
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticVec3Track`)
|
||||
class ExoticVec3Track {
|
||||
constructor (times: FloatArray, values: FloatArray) {
|
||||
this._times = times;
|
||||
this._values = new ExoticVec3TrackValues(values);
|
||||
}
|
||||
|
||||
public createEvaluator () {
|
||||
return new ExoticTrackEvaluator<Vec3>(
|
||||
this._times,
|
||||
this._values,
|
||||
Vec3,
|
||||
);
|
||||
}
|
||||
|
||||
public split (from: number, to: number) {
|
||||
if (!EDITOR) {
|
||||
// TODO: better handling
|
||||
error(`split() only valid in Editor.`);
|
||||
return this;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _times: FloatArray;
|
||||
|
||||
@serializable
|
||||
private _values: ExoticVec3TrackValues;
|
||||
}
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticQuatTrackValues`)
|
||||
class ExoticQuatTrackValues implements ExoticTrackValues<Quat> {
|
||||
constructor (values: FloatArray) {
|
||||
this._values = values;
|
||||
this._isQuantized = false;
|
||||
}
|
||||
|
||||
public quantize (type: QuantizationType) {
|
||||
assertIsTrue(!this._isQuantized);
|
||||
this._values = quantize(this._values as FloatArray, type);
|
||||
this._isQuantized = true;
|
||||
}
|
||||
|
||||
public get (index: number, resultValue: Quat): void {
|
||||
const {
|
||||
_values: values,
|
||||
_isQuantized: isQuantized,
|
||||
} = this;
|
||||
if (isQuantized) {
|
||||
loadQuatFromQuantized(values as QuantizedFloatArray, index, resultValue);
|
||||
} else {
|
||||
Quat.fromArray(resultValue, values as FloatArray, index * 4);
|
||||
}
|
||||
}
|
||||
|
||||
public lerp (
|
||||
prevIndex: number,
|
||||
nextIndex: number,
|
||||
ratio: number,
|
||||
prevValue: Quat,
|
||||
nextValue: Quat,
|
||||
resultValue: Quat,
|
||||
): void {
|
||||
const {
|
||||
_values: values,
|
||||
_isQuantized: isQuantized,
|
||||
} = this;
|
||||
if (isQuantized) {
|
||||
loadQuatFromQuantized(values as QuantizedFloatArray, prevIndex, prevValue);
|
||||
loadQuatFromQuantized(values as QuantizedFloatArray, nextIndex, nextValue);
|
||||
} else {
|
||||
Quat.fromArray(prevValue, values as FloatArray, prevIndex * 4);
|
||||
Quat.fromArray(nextValue, values as FloatArray, nextIndex * 4);
|
||||
}
|
||||
Quat.slerp(resultValue, prevValue, nextValue, ratio);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _values: FloatArray | QuantizedFloatArray;
|
||||
|
||||
@serializable
|
||||
private _isQuantized: boolean;
|
||||
}
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ExoticQuatTrack`)
|
||||
class ExoticQuatTrack {
|
||||
constructor (times: FloatArray, values: FloatArray) {
|
||||
this._times = times;
|
||||
this._values = new ExoticQuatTrackValues(values);
|
||||
}
|
||||
|
||||
public createEvaluator () {
|
||||
return new ExoticTrackEvaluator<Quat>(
|
||||
this._times,
|
||||
this._values,
|
||||
Quat,
|
||||
);
|
||||
}
|
||||
|
||||
public split (from: number, to: number) {
|
||||
if (!EDITOR) {
|
||||
// TODO: better handling
|
||||
error(`split() only valid in Editor.`);
|
||||
return this;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _times: FloatArray;
|
||||
|
||||
@serializable
|
||||
private _values: ExoticQuatTrackValues;
|
||||
}
|
||||
|
||||
class ExoticTrsAnimationEvaluator {
|
||||
constructor (nodeAnimations: ExoticNodeAnimation[], binder: Binder) {
|
||||
this._nodeEvaluations = nodeAnimations.map((nodeAnimation) => nodeAnimation.createEvaluator(binder));
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
this._nodeEvaluations.forEach((nodeEvaluator) => {
|
||||
nodeEvaluator.evaluate(time);
|
||||
});
|
||||
}
|
||||
|
||||
private _nodeEvaluations: ExoticNodeAnimationEvaluator[];
|
||||
}
|
||||
|
||||
class ExoticNodeAnimationEvaluator {
|
||||
constructor (
|
||||
path: string,
|
||||
position: ExoticVec3Track | null,
|
||||
rotation: ExoticQuatTrack | null,
|
||||
scale: ExoticVec3Track | null,
|
||||
binder: Binder,
|
||||
) {
|
||||
if (position) {
|
||||
this._position = createExoticTrackEvaluationRecord(position, path, 'position', binder);
|
||||
}
|
||||
if (rotation) {
|
||||
this._rotation = createExoticTrackEvaluationRecord(rotation, path, 'rotation', binder);
|
||||
}
|
||||
if (scale) {
|
||||
this._scale = createExoticTrackEvaluationRecord(scale, path, 'scale', binder);
|
||||
}
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
if (this._position) {
|
||||
const value = this._position.evaluator.evaluate(time);
|
||||
this._position.runtimeBinding.setValue(value);
|
||||
}
|
||||
if (this._rotation) {
|
||||
const value = this._rotation.evaluator.evaluate(time);
|
||||
this._rotation.runtimeBinding.setValue(value);
|
||||
}
|
||||
if (this._scale) {
|
||||
const value = this._scale.evaluator.evaluate(time);
|
||||
this._scale.runtimeBinding.setValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
private _position: ExoticTrackEvaluationRecord<Vec3> | null = null;
|
||||
private _rotation: ExoticTrackEvaluationRecord<Quat> | null = null;
|
||||
private _scale: ExoticTrackEvaluationRecord<Vec3> | null = null;
|
||||
}
|
||||
|
||||
class ExoticTrackEvaluator<TValue extends Vec3 | Quat> {
|
||||
constructor (times: FloatArray, values: ExoticTrackValues<TValue>, ValueConstructor: new () => TValue) {
|
||||
this._times = times;
|
||||
this._values = values;
|
||||
this._prevValue = new ValueConstructor();
|
||||
this._nextValue = new ValueConstructor();
|
||||
this._resultValue = new ValueConstructor();
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
const {
|
||||
_times: times,
|
||||
_values: values,
|
||||
_resultValue: resultValue,
|
||||
} = this;
|
||||
|
||||
const nFrames = times.length;
|
||||
|
||||
if (nFrames === 0) {
|
||||
return resultValue;
|
||||
}
|
||||
|
||||
const inputSampleResult = sampleInput(times, time, this._inputSampleResultCache);
|
||||
if (inputSampleResult.just) {
|
||||
values.get(inputSampleResult.index, resultValue);
|
||||
} else {
|
||||
values.lerp(
|
||||
inputSampleResult.index,
|
||||
inputSampleResult.nextIndex,
|
||||
inputSampleResult.ratio,
|
||||
this._prevValue,
|
||||
this._nextValue,
|
||||
resultValue,
|
||||
);
|
||||
}
|
||||
|
||||
return resultValue;
|
||||
}
|
||||
|
||||
private _times: FloatArray;
|
||||
private _inputSampleResultCache: InputSampleResult = {
|
||||
just: false,
|
||||
index: -1,
|
||||
nextIndex: -1,
|
||||
ratio: 0.0,
|
||||
};
|
||||
private _values: ExoticTrackValues<TValue>;
|
||||
private _prevValue: TValue;
|
||||
private _nextValue: TValue;
|
||||
private _resultValue: TValue;
|
||||
}
|
||||
|
||||
interface ExoticTrackEvaluationRecord<TValue extends Vec3 | Quat> {
|
||||
runtimeBinding: RuntimeBinding;
|
||||
evaluator: ExoticTrackEvaluator<TValue>;
|
||||
}
|
||||
|
||||
interface InputSampleResult {
|
||||
just: boolean;
|
||||
index: number;
|
||||
nextIndex: number;
|
||||
ratio: number;
|
||||
}
|
||||
|
||||
function sampleInput (values: FloatArray, time: number, result: InputSampleResult) {
|
||||
const nFrames = values.length;
|
||||
assertIsTrue(nFrames !== 0);
|
||||
|
||||
const firstTime = values[0];
|
||||
const lastTime = values[nFrames - 1];
|
||||
if (time < firstTime) {
|
||||
result.just = true;
|
||||
result.index = 0;
|
||||
} else if (time > lastTime) {
|
||||
result.just = true;
|
||||
result.index = nFrames - 1;
|
||||
} else {
|
||||
const index = binarySearchEpsilon(values, time);
|
||||
if (index >= 0) {
|
||||
result.just = true;
|
||||
result.index = index;
|
||||
} else {
|
||||
const nextIndex = ~index;
|
||||
assertIsTrue(nextIndex !== 0 && nextIndex !== nFrames && nFrames > 1);
|
||||
const prevIndex = nextIndex - 1;
|
||||
const prevTime = values[prevIndex];
|
||||
const nextTime = values[nextIndex];
|
||||
const ratio = (time - values[prevIndex]) / (nextTime - prevTime);
|
||||
result.just = false;
|
||||
result.index = prevIndex;
|
||||
result.nextIndex = nextIndex;
|
||||
result.ratio = ratio;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
type UintArray = Uint8Array | Uint16Array | Uint32Array;
|
||||
|
||||
type FloatArray = Float32Array | Float64Array;
|
||||
|
||||
type UintArrayConstructor = Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor;
|
||||
|
||||
type IntArrayConstructor = Int8ArrayConstructor | Int16ArrayConstructor | Int32ArrayConstructor;
|
||||
|
||||
type QuantizationType = 'uint8' | 'uint16';
|
||||
|
||||
type QuantizationArrayConstructor = Uint8ArrayConstructor | Uint16ArrayConstructor;
|
||||
|
||||
const QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP: Record<QuantizationType, QuantizationArrayConstructor> = {
|
||||
uint8: Uint8Array,
|
||||
uint16: Uint16Array,
|
||||
};
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}QuantizedFloatArray`)
|
||||
class QuantizedFloatArray {
|
||||
@serializable
|
||||
public min!: number;
|
||||
|
||||
@serializable
|
||||
public extent!: number;
|
||||
|
||||
@serializable
|
||||
public values!: UintArray;
|
||||
|
||||
constructor (values: UintArray, extent: number, min = 0.0) {
|
||||
this.values = values;
|
||||
this.extent = extent;
|
||||
this.min = min;
|
||||
}
|
||||
}
|
||||
|
||||
function quantize (values: FloatArray, type: QuantizationType) {
|
||||
const TypedArrayViewConstructor = QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP[type];
|
||||
const MAX = 1 << TypedArrayViewConstructor.BYTES_PER_ELEMENT;
|
||||
let min = Number.POSITIVE_INFINITY;
|
||||
let max = Number.NEGATIVE_INFINITY;
|
||||
values.forEach((value) => {
|
||||
min = Math.min(value, min);
|
||||
max = Math.max(value, max);
|
||||
});
|
||||
const extent = max - min;
|
||||
// Should consider `extent === 0.0`.
|
||||
const normalized = TypedArrayViewConstructor.from(values, (value) => (value - min) / extent * MAX);
|
||||
return new QuantizedFloatArray(normalized, extent, min);
|
||||
}
|
||||
|
||||
function indexQuantized (quantized: QuantizedFloatArray, index: number) {
|
||||
const quantizedValue = quantized.values[index];
|
||||
const MAX_VALUE = 1 << quantized.values.BYTES_PER_ELEMENT;
|
||||
return quantizedValue / MAX_VALUE * quantized.extent + quantized.min;
|
||||
}
|
||||
|
||||
function createExoticTrackEvaluationRecord<T extends ExoticVec3Track | ExoticQuatTrack> (
|
||||
track: T,
|
||||
path: string,
|
||||
property: 'position' | 'scale' | 'rotation',
|
||||
binder: Binder,
|
||||
) {
|
||||
const trackBinding = new TrackBinding();
|
||||
trackBinding.path = new TrackPath().hierarchy(path).property(property);
|
||||
const runtimeBinding = binder(trackBinding);
|
||||
if (!runtimeBinding) {
|
||||
return null;
|
||||
}
|
||||
const evaluator = track.createEvaluator();
|
||||
return {
|
||||
runtimeBinding,
|
||||
evaluator,
|
||||
} as (T extends ExoticVec3Track ? ExoticTrackEvaluationRecord<Vec3> : ExoticTrackEvaluationRecord<Quat>);
|
||||
}
|
||||
|
||||
function loadVec3FromQuantized (values: QuantizedFloatArray, index: number, out: Vec3) {
|
||||
Vec3.set(
|
||||
out,
|
||||
indexQuantized(values, 3 * index + 0),
|
||||
indexQuantized(values, 3 * index + 1),
|
||||
indexQuantized(values, 3 * index + 2),
|
||||
);
|
||||
}
|
||||
|
||||
function loadQuatFromQuantized (values: QuantizedFloatArray, index: number, out: Quat) {
|
||||
Quat.set(
|
||||
out,
|
||||
indexQuantized(values, 4 * index + 0),
|
||||
indexQuantized(values, 4 * index + 1),
|
||||
indexQuantized(values, 4 * index + 2),
|
||||
indexQuantized(values, 4 * index + 3),
|
||||
);
|
||||
}
|
||||
@@ -41,7 +41,7 @@ legacyCC.easing = easing;
|
||||
export * from './bezier';
|
||||
export { easing };
|
||||
export * from './animation-curve';
|
||||
export * from './animation-clip';
|
||||
export { AnimationClip } from './animation-clip';
|
||||
export * from './animation-manager';
|
||||
export {
|
||||
AnimationState,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
export const BAKE_SKELETON_CURVE_SYMBOL = Symbol('BakeNodeCurves');
|
||||
@@ -0,0 +1,766 @@
|
||||
import { ComponentPath, HierarchyPath, isPropertyPath, TargetPath } from './target-path';
|
||||
import { IValueProxyFactory } from './value-proxy';
|
||||
import * as easing from './easing';
|
||||
import { BezierControlPoints } from './bezier';
|
||||
import { CompactValueTypeArray } from '../data/utils/compact-value-type-array';
|
||||
import { serializable } from '../data/decorators';
|
||||
import { AnimCurve, RatioSampler } from './animation-curve';
|
||||
import { QuatInterpolationMode, RealCurve, RealInterpolationMode, RealKeyframeValue, TangentWeightMode } from '../curves';
|
||||
import { assertIsTrue } from '../data/utils/asserts';
|
||||
import { Track, TrackPath } from './tracks/track';
|
||||
import { UntypedTrack } from './tracks/untyped-track';
|
||||
import { warn, warnID } from '../platform';
|
||||
import { RealTrack } from './tracks/real-track';
|
||||
import { Color, lerp, Quat, Size, Vec2, Vec3, Vec4 } from '../math';
|
||||
import { CubicSplineNumberValue, CubicSplineQuatValue, CubicSplineVec2Value, CubicSplineVec3Value, CubicSplineVec4Value } from './cubic-spline-value';
|
||||
import { ColorTrack } from './tracks/color-track';
|
||||
import { VectorTrack } from './tracks/vector-track';
|
||||
import { QuatTrack } from './tracks/quat-track';
|
||||
import { ObjectTrack } from './tracks/object-track';
|
||||
import { SizeTrack } from './tracks/size-track';
|
||||
import { EasingMethod } from '../curves/curve';
|
||||
|
||||
/**
|
||||
* 表示曲线值,曲线值可以是任意类型,但必须符合插值方式的要求。
|
||||
*/
|
||||
export type LegacyCurveValue = any;
|
||||
|
||||
/**
|
||||
* 表示曲线的目标对象。
|
||||
*/
|
||||
export type LegacyCurveTarget = Record<string, any>;
|
||||
|
||||
/**
|
||||
* 内置帧时间渐变方式名称。
|
||||
*/
|
||||
export type LegacyEasingMethodName = keyof (typeof easing);
|
||||
|
||||
/**
|
||||
* 帧时间渐变方式。可能为内置帧时间渐变方式的名称或贝塞尔控制点。
|
||||
*/
|
||||
export type LegacyEasingMethod = LegacyEasingMethodName | BezierControlPoints;
|
||||
|
||||
export type LegacyCompressedEasingMethods = Record<number, LegacyEasingMethod>;
|
||||
|
||||
export type LegacyLerpFunction<T = any> = (from: T, to: T, t: number, dt: number) => T;
|
||||
|
||||
export interface LegacyClipCurveData {
|
||||
/**
|
||||
* 曲线使用的时间轴。
|
||||
* @see {AnimationClip.keys}
|
||||
*/
|
||||
keys: number;
|
||||
|
||||
/**
|
||||
* 曲线值。曲线值的数量应和 `keys` 所引用时间轴的帧数相同。
|
||||
*/
|
||||
values: LegacyCurveValue[];
|
||||
|
||||
/**
|
||||
* 曲线任意两帧时间的渐变方式。仅当 `easingMethods === undefined` 时本字段才生效。
|
||||
*/
|
||||
easingMethod?: LegacyEasingMethod;
|
||||
|
||||
/**
|
||||
* 描述了每一帧时间到下一帧时间之间的渐变方式。
|
||||
*/
|
||||
easingMethods?: LegacyEasingMethod[] | LegacyCompressedEasingMethods;
|
||||
|
||||
/**
|
||||
* 是否进行插值。
|
||||
* @default true
|
||||
*/
|
||||
interpolate?: boolean;
|
||||
|
||||
/**
|
||||
* For internal usage only.
|
||||
*/
|
||||
_arrayLength?: number;
|
||||
}
|
||||
|
||||
export interface LegacyClipCurve {
|
||||
commonTarget?: number;
|
||||
|
||||
modifiers: TargetPath[];
|
||||
|
||||
valueAdapter?: IValueProxyFactory;
|
||||
|
||||
data: LegacyClipCurveData;
|
||||
}
|
||||
|
||||
export interface LegacyCommonTarget {
|
||||
modifiers: TargetPath[];
|
||||
valueAdapter?: IValueProxyFactory;
|
||||
}
|
||||
|
||||
export type LegacyMaybeCompactCurve = Omit<LegacyClipCurve, 'data'> & {
|
||||
data: Omit<LegacyClipCurveData, 'values'> & {
|
||||
values: any[] | CompactValueTypeArray;
|
||||
};
|
||||
};
|
||||
|
||||
export type LegacyMaybeCompactKeys = Array<number[] | CompactValueTypeArray>;
|
||||
|
||||
export type LegacyRuntimeCurve = Pick<LegacyClipCurve, 'modifiers' | 'valueAdapter' | 'commonTarget'> & {
|
||||
/**
|
||||
* 属性曲线。
|
||||
*/
|
||||
curve: AnimCurve;
|
||||
|
||||
/**
|
||||
* 曲线采样器。
|
||||
*/
|
||||
sampler: RatioSampler | null;
|
||||
}
|
||||
|
||||
// interface ConvertMap<TValue, TTrack> {
|
||||
// valueConstructor: Constructor<TValue>;
|
||||
// trackConstructor: Constructor<TTrack>;
|
||||
// properties: [keyof TValue, number][];
|
||||
// }
|
||||
|
||||
// const VECTOR_LIKE_CURVE_CONVERT_TABLE = [
|
||||
// {
|
||||
// valueConstructor: Size,
|
||||
// trackConstructor: SizeTrack,
|
||||
// properties: [['width', 0], ['height', 1]],
|
||||
// } as ConvertMap<Size, SizeTrack>,
|
||||
// {
|
||||
// valueConstructor: Color,
|
||||
// trackConstructor: ColorTrack,
|
||||
// properties: [['r', 0], ['g', 1], ['b', 2], ['a', 3]],
|
||||
// } as ConvertMap<Color, ColorTrack>,
|
||||
// ];
|
||||
|
||||
export class AnimationClipLegacyData {
|
||||
constructor (duration: number) {
|
||||
this._duration = duration;
|
||||
}
|
||||
|
||||
get keys () {
|
||||
return this._keys;
|
||||
}
|
||||
|
||||
set keys (value) {
|
||||
this._keys = value;
|
||||
}
|
||||
|
||||
get curves () {
|
||||
return this._curves;
|
||||
}
|
||||
|
||||
set curves (value) {
|
||||
this._curves = value;
|
||||
delete this._runtimeCurves;
|
||||
}
|
||||
|
||||
get commonTargets () {
|
||||
return this._commonTargets;
|
||||
}
|
||||
|
||||
set commonTargets (value) {
|
||||
this._commonTargets = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 此动画的数据。
|
||||
*/
|
||||
get data () {
|
||||
return this._data;
|
||||
}
|
||||
|
||||
public getPropertyCurves (): readonly LegacyRuntimeCurve[] {
|
||||
if (!this._runtimeCurves) {
|
||||
this._createPropertyCurves();
|
||||
}
|
||||
return this._runtimeCurves!;
|
||||
}
|
||||
|
||||
public toTracks () {
|
||||
const newTracks: Track[] = [];
|
||||
|
||||
const {
|
||||
keys: legacyKeys,
|
||||
curves: legacyCurves,
|
||||
commonTargets: legacyCommonTargets,
|
||||
} = this;
|
||||
|
||||
const convertTrackPath = (track: Track, modifiers: TargetPath[], valueAdapter: IValueProxyFactory | undefined) => {
|
||||
const trackPath = new TrackPath();
|
||||
for (const modifier of modifiers) {
|
||||
if (typeof modifier === 'string') {
|
||||
trackPath.property(modifier);
|
||||
} else if (typeof modifier === 'number') {
|
||||
trackPath.element(modifier);
|
||||
} else if (modifier instanceof HierarchyPath) {
|
||||
trackPath.hierarchy(modifier.path);
|
||||
} else if (modifier instanceof ComponentPath) {
|
||||
trackPath.component(modifier.component);
|
||||
} else {
|
||||
trackPath.customized(modifier);
|
||||
}
|
||||
}
|
||||
track.path = trackPath;
|
||||
track.proxy = valueAdapter;
|
||||
};
|
||||
|
||||
const untypedTracks = legacyCommonTargets.map((legacyCommonTarget) => {
|
||||
const track = new UntypedTrack();
|
||||
convertTrackPath(track, legacyCommonTarget.modifiers, legacyCommonTarget.valueAdapter);
|
||||
newTracks.push(track);
|
||||
return track;
|
||||
});
|
||||
|
||||
for (const legacyCurve of legacyCurves) {
|
||||
const legacyCurveData = legacyCurve.data;
|
||||
const legacyValues = legacyCurveData.values;
|
||||
if (legacyValues.length === 0) {
|
||||
// Legacy clip did not record type info.
|
||||
continue;
|
||||
}
|
||||
const legacyKeysIndex = legacyCurveData.keys;
|
||||
// Rule: negative index means single frame.
|
||||
const times = legacyKeysIndex < 0 ? [0.0] : legacyKeys[legacyCurveData.keys];
|
||||
const firstValue = legacyValues[0];
|
||||
// Rule: default to true.
|
||||
const interpolate = legacyCurveData.interpolate ?? true;
|
||||
// Rule: _arrayLength only used for morph target, internally.
|
||||
assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number');
|
||||
const legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length);
|
||||
|
||||
const installPathAndSetter = (track: Track) => {
|
||||
convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter);
|
||||
};
|
||||
|
||||
let legacyCommonTargetCurve: RealCurve | undefined;
|
||||
if (typeof legacyCurve.commonTarget === 'number') {
|
||||
// Rule: common targets should only target Vectors/`Size`/`Color`.
|
||||
if (!legacyValues.every((value) => typeof value === 'number')) {
|
||||
warnID(3932);
|
||||
continue;
|
||||
}
|
||||
// Rule: Each curve that has common target should be numeric curve and targets string property.
|
||||
if (legacyCurve.valueAdapter || legacyCurve.modifiers.length !== 1 || typeof legacyCurve.modifiers[0] !== 'string') {
|
||||
warnID(3933);
|
||||
continue;
|
||||
}
|
||||
const propertyName = legacyCurve.modifiers[0];
|
||||
const untypedTrack = untypedTracks[legacyCurve.commonTarget];
|
||||
const { curve } = untypedTrack.addChannel(propertyName);
|
||||
legacyCommonTargetCurve = curve;
|
||||
}
|
||||
|
||||
const convertCurve = () => {
|
||||
if (typeof firstValue === 'number') {
|
||||
if (!legacyValues.every((value) => typeof value === 'number')) {
|
||||
warnID(3934);
|
||||
return;
|
||||
}
|
||||
let realCurve: RealCurve;
|
||||
if (legacyCommonTargetCurve) {
|
||||
realCurve = legacyCommonTargetCurve;
|
||||
} else {
|
||||
const track = new RealTrack();
|
||||
installPathAndSetter(track);
|
||||
newTracks.push(track);
|
||||
realCurve = track.channel.curve;
|
||||
}
|
||||
const interpolationMethod = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
|
||||
realCurve.assignSorted(times, (legacyValues as number[]).map(
|
||||
(value) => ({ value, interpolationMode: interpolationMethod }),
|
||||
));
|
||||
legacyEasingMethodConverter.convert(realCurve);
|
||||
return;
|
||||
} else if (typeof firstValue === 'object') {
|
||||
switch (true) {
|
||||
default:
|
||||
break;
|
||||
case everyInstanceOf(legacyValues, Vec2):
|
||||
case everyInstanceOf(legacyValues, Vec3):
|
||||
case everyInstanceOf(legacyValues, Vec4): {
|
||||
type Vec4plus = Vec4[];
|
||||
type Vec3plus = (Vec3 | Vec4)[];
|
||||
type Vec2plus = (Vec2 | Vec3 | Vec4)[];
|
||||
const components = firstValue instanceof Vec2 ? 2 : firstValue instanceof Vec3 ? 3 : 4;
|
||||
const track = new VectorTrack();
|
||||
installPathAndSetter(track);
|
||||
track.componentsCount = components;
|
||||
const [{ curve: x }, { curve: y }, { curve: z }, { curve: w }] = track.channels();
|
||||
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
|
||||
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
|
||||
switch (components) {
|
||||
case 4:
|
||||
w.assignSorted(times, (legacyValues as Vec4plus).map((value) => valueToFrame(value.w)));
|
||||
legacyEasingMethodConverter.convert(w);
|
||||
// falls through
|
||||
case 3:
|
||||
z.assignSorted(times, (legacyValues as Vec3plus).map((value) => valueToFrame(value.z)));
|
||||
legacyEasingMethodConverter.convert(z);
|
||||
// falls through
|
||||
default:
|
||||
x.assignSorted(times, (legacyValues as Vec2plus).map((value) => valueToFrame(value.x)));
|
||||
legacyEasingMethodConverter.convert(x);
|
||||
y.assignSorted(times, (legacyValues as Vec2plus).map((value) => valueToFrame(value.y)));
|
||||
legacyEasingMethodConverter.convert(y);
|
||||
break;
|
||||
}
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case everyInstanceOf(legacyValues, Quat): {
|
||||
assertIsTrue(legacyEasingMethodConverter.nil);
|
||||
const track = new QuatTrack();
|
||||
installPathAndSetter(track);
|
||||
const interpolationMode = interpolate ? QuatInterpolationMode.SLERP : QuatInterpolationMode.CONSTANT;
|
||||
track.channel.curve.assignSorted(times, (legacyValues as Quat[]).map((value) => ({
|
||||
value: Quat.clone(value),
|
||||
interpolationMode,
|
||||
})));
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case everyInstanceOf(legacyValues, Color): {
|
||||
const track = new ColorTrack();
|
||||
installPathAndSetter(track);
|
||||
const [{ curve: r }, { curve: g }, { curve: b }, { curve: a }] = track.channels();
|
||||
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
|
||||
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
|
||||
r.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.r)));
|
||||
legacyEasingMethodConverter.convert(r);
|
||||
g.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.g)));
|
||||
legacyEasingMethodConverter.convert(g);
|
||||
b.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.b)));
|
||||
legacyEasingMethodConverter.convert(b);
|
||||
a.assignSorted(times, (legacyValues as Color[]).map((value) => valueToFrame(value.a)));
|
||||
legacyEasingMethodConverter.convert(a);
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case everyInstanceOf(legacyValues, Size): {
|
||||
const track = new SizeTrack();
|
||||
installPathAndSetter(track);
|
||||
const [{ curve: width }, { curve: height }] = track.channels();
|
||||
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
|
||||
const valueToFrame = (value: number): Partial<RealKeyframeValue> => ({ value, interpolationMode });
|
||||
width.assignSorted(times, (legacyValues as Size[]).map((value) => valueToFrame(value.width)));
|
||||
legacyEasingMethodConverter.convert(width);
|
||||
height.assignSorted(times, (legacyValues as Size[]).map((value) => valueToFrame(value.height)));
|
||||
legacyEasingMethodConverter.convert(height);
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case everyInstanceOf(legacyValues, CubicSplineNumberValue): {
|
||||
assertIsTrue(legacyEasingMethodConverter.nil);
|
||||
const track = new RealTrack();
|
||||
installPathAndSetter(track);
|
||||
const interpolationMode = interpolate ? RealInterpolationMode.CUBIC : RealInterpolationMode.CONSTANT;
|
||||
track.channel.curve.assignSorted(times, (legacyValues as CubicSplineNumberValue[]).map((value) => ({
|
||||
value: value.dataPoint,
|
||||
leftTangent: value.inTangent,
|
||||
rightTangent: value.outTangent,
|
||||
interpolationMode,
|
||||
})));
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case everyInstanceOf(legacyValues, CubicSplineVec2Value):
|
||||
case everyInstanceOf(legacyValues, CubicSplineVec3Value):
|
||||
case everyInstanceOf(legacyValues, CubicSplineVec4Value): {
|
||||
assertIsTrue(legacyEasingMethodConverter.nil);
|
||||
type Vec4plus = CubicSplineVec4Value[];
|
||||
type Vec3plus = (CubicSplineVec3Value | CubicSplineVec4Value)[];
|
||||
type Vec2plus = (CubicSplineVec2Value | CubicSplineVec3Value | CubicSplineVec4Value)[];
|
||||
const components = firstValue instanceof CubicSplineVec2Value ? 2 : firstValue instanceof CubicSplineVec3Value ? 3 : 4;
|
||||
const track = new VectorTrack();
|
||||
installPathAndSetter(track);
|
||||
track.componentsCount = components;
|
||||
const [x, y, z, w] = track.channels();
|
||||
const interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
|
||||
const valueToFrame = (value: number, inTangent: number, outTangent: number): Partial<RealKeyframeValue> => ({
|
||||
value,
|
||||
leftTangent: inTangent,
|
||||
rightTangent: outTangent,
|
||||
interpolationMode,
|
||||
});
|
||||
switch (components) {
|
||||
case 4:
|
||||
w.curve.assignSorted(times, (legacyValues as Vec4plus).map(
|
||||
(value) => valueToFrame(value.dataPoint.w, value.inTangent.w, value.outTangent.w),
|
||||
));
|
||||
// falls through
|
||||
case 3:
|
||||
z.curve.assignSorted(times, (legacyValues as Vec3plus).map(
|
||||
(value) => valueToFrame(value.dataPoint.z, value.inTangent.z, value.outTangent.z),
|
||||
));
|
||||
// falls through
|
||||
default:
|
||||
x.curve.assignSorted(times, (legacyValues as Vec2plus).map(
|
||||
(value) => valueToFrame(value.dataPoint.y, value.inTangent.y, value.outTangent.y),
|
||||
));
|
||||
y.curve.assignSorted(times, (legacyValues as Vec2plus).map(
|
||||
(value) => valueToFrame(value.dataPoint.x, value.inTangent.x, value.outTangent.x),
|
||||
));
|
||||
break;
|
||||
}
|
||||
newTracks.push(track);
|
||||
return;
|
||||
}
|
||||
case legacyValues.every((value) => value instanceof CubicSplineQuatValue): {
|
||||
warnID(3935);
|
||||
break;
|
||||
}
|
||||
} // End switch
|
||||
}
|
||||
|
||||
const objectTrack = new ObjectTrack();
|
||||
installPathAndSetter(objectTrack);
|
||||
objectTrack.channel.curve.assignSorted(times, legacyValues);
|
||||
newTracks.push(objectTrack);
|
||||
};
|
||||
|
||||
convertCurve();
|
||||
}
|
||||
|
||||
return newTracks;
|
||||
}
|
||||
|
||||
private _keys: number[][] = [];
|
||||
|
||||
private _curves: LegacyClipCurve[] = [];
|
||||
|
||||
private _commonTargets: LegacyCommonTarget[] = [];
|
||||
|
||||
private _ratioSamplers: RatioSampler[] = [];
|
||||
|
||||
private _runtimeCurves?: LegacyRuntimeCurve[];
|
||||
|
||||
private _data: Uint8Array | null = null;
|
||||
|
||||
private _duration: number;
|
||||
|
||||
protected _createPropertyCurves () {
|
||||
this._ratioSamplers = this._keys.map(
|
||||
(keys) => new RatioSampler(
|
||||
keys.map(
|
||||
(key) => key / this._duration,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
this._runtimeCurves = this._curves.map((targetCurve): LegacyRuntimeCurve => ({
|
||||
curve: new AnimCurve(targetCurve.data, this._duration),
|
||||
modifiers: targetCurve.modifiers,
|
||||
valueAdapter: targetCurve.valueAdapter,
|
||||
sampler: this._ratioSamplers[targetCurve.data.keys],
|
||||
commonTarget: targetCurve.commonTarget,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function everyInstanceOf<T> (array: unknown[], constructor: Constructor<T>): array is T[] {
|
||||
return array.every((element) => element instanceof constructor);
|
||||
}
|
||||
|
||||
// #region Legacy data structures prior to 1.2
|
||||
|
||||
export interface LegacyObjectCurveData {
|
||||
[propertyName: string]: LegacyClipCurveData;
|
||||
}
|
||||
|
||||
export interface LegacyComponentsCurveData {
|
||||
[componentName: string]: LegacyObjectCurveData;
|
||||
}
|
||||
|
||||
export interface LegacyNodeCurveData {
|
||||
props?: LegacyObjectCurveData;
|
||||
comps?: LegacyComponentsCurveData;
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
class LegacyEasingMethodConverter {
|
||||
constructor (legacyCurveData: LegacyClipCurveData, keyframesCount: number) {
|
||||
const { easingMethods } = legacyCurveData;
|
||||
if (Array.isArray(easingMethods)) {
|
||||
// Different
|
||||
this._easingMethods = easingMethods;
|
||||
} else if (easingMethods === undefined) {
|
||||
// Same
|
||||
this._easingMethods = new Array(keyframesCount).fill(legacyCurveData.easingMethod);
|
||||
} else {
|
||||
// Compressed as record
|
||||
this._easingMethods = Array.from({ length: keyframesCount }, (_, index) => easingMethods[index]);
|
||||
}
|
||||
}
|
||||
|
||||
get nil () {
|
||||
return !this._easingMethods || this._easingMethods.every((easingMethod) => easingMethod === null || easingMethod === undefined);
|
||||
}
|
||||
|
||||
public convert (curve: RealCurve) {
|
||||
const { _easingMethods: easingMethods } = this;
|
||||
if (!easingMethods) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nKeyframes = curve.keyFramesCount;
|
||||
if (curve.keyFramesCount < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(easingMethods)) {
|
||||
assertIsTrue(nKeyframes === easingMethods.length);
|
||||
}
|
||||
|
||||
const iLastKeyframe = nKeyframes - 1;
|
||||
for (let iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
|
||||
const easingMethod = easingMethods[iKeyframe];
|
||||
if (!easingMethod) {
|
||||
continue;
|
||||
}
|
||||
if (Array.isArray(easingMethod)) {
|
||||
// Time bezier points
|
||||
timeBezierToTangents(
|
||||
easingMethod,
|
||||
curve.getKeyframeTime(iKeyframe),
|
||||
curve.getKeyframeValue(iKeyframe),
|
||||
curve.getKeyframeTime(iKeyframe + 1),
|
||||
curve.getKeyframeValue(iKeyframe + 1),
|
||||
);
|
||||
} else {
|
||||
applyLegacyEasingMethodName(
|
||||
easingMethod,
|
||||
curve,
|
||||
iKeyframe,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _easingMethods: LegacyEasingMethod[] | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns Inserted keyframes count.
|
||||
*/
|
||||
function applyLegacyEasingMethodName (
|
||||
easingMethodName: LegacyEasingMethodName,
|
||||
curve: RealCurve,
|
||||
keyframeIndex: number,
|
||||
) {
|
||||
assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
|
||||
assertIsTrue(easingMethodName in easingMethodNameMap);
|
||||
const keyframeValue = curve.getKeyframeValue(keyframeIndex);
|
||||
const easingMethod = easingMethodNameMap[easingMethodName];
|
||||
if (easingMethod === EasingMethod.CONSTANT) {
|
||||
keyframeValue.interpolationMode = RealInterpolationMode.CONSTANT;
|
||||
} else {
|
||||
keyframeValue.interpolationMode = RealInterpolationMode.LINEAR;
|
||||
keyframeValue.easingMethod = easingMethod;
|
||||
}
|
||||
}
|
||||
|
||||
const easingMethodNameMap: Record<LegacyEasingMethodName, EasingMethod> = {
|
||||
constant: EasingMethod.CONSTANT,
|
||||
linear: EasingMethod.LINEAR,
|
||||
quadIn: EasingMethod.QUAD_IN,
|
||||
quadOut: EasingMethod.QUAD_OUT,
|
||||
quadInOut: EasingMethod.QUAD_IN_OUT,
|
||||
quadOutIn: EasingMethod.QUAD_OUT_IN,
|
||||
cubicIn: EasingMethod.CUBIC_IN,
|
||||
cubicOut: EasingMethod.CUBIC_OUT,
|
||||
cubicInOut: EasingMethod.CUBIC_IN_OUT,
|
||||
cubicOutIn: EasingMethod.CUBIC_OUT_IN,
|
||||
quartIn: EasingMethod.QUART_IN,
|
||||
quartOut: EasingMethod.QUART_OUT,
|
||||
quartInOut: EasingMethod.QUART_IN_OUT,
|
||||
quartOutIn: EasingMethod.QUART_OUT_IN,
|
||||
quintIn: EasingMethod.QUINT_IN,
|
||||
quintOut: EasingMethod.QUINT_OUT,
|
||||
quintInOut: EasingMethod.QUINT_IN_OUT,
|
||||
quintOutIn: EasingMethod.QUINT_OUT_IN,
|
||||
sineIn: EasingMethod.SINE_IN,
|
||||
sineOut: EasingMethod.SINE_OUT,
|
||||
sineInOut: EasingMethod.SINE_IN_OUT,
|
||||
sineOutIn: EasingMethod.SINE_OUT_IN,
|
||||
expoIn: EasingMethod.EXPO_IN,
|
||||
expoOut: EasingMethod.EXPO_OUT,
|
||||
expoInOut: EasingMethod.EXPO_IN_OUT,
|
||||
expoOutIn: EasingMethod.EXPO_OUT_IN,
|
||||
circIn: EasingMethod.CIRC_IN,
|
||||
circOut: EasingMethod.CIRC_OUT,
|
||||
circInOut: EasingMethod.CIRC_IN_OUT,
|
||||
circOutIn: EasingMethod.CIRC_OUT_IN,
|
||||
elasticIn: EasingMethod.ELASTIC_IN,
|
||||
elasticOut: EasingMethod.ELASTIC_OUT,
|
||||
elasticInOut: EasingMethod.ELASTIC_IN_OUT,
|
||||
elasticOutIn: EasingMethod.ELASTIC_OUT_IN,
|
||||
backIn: EasingMethod.BACK_IN,
|
||||
backOut: EasingMethod.BACK_OUT,
|
||||
backInOut: EasingMethod.BACK_IN_OUT,
|
||||
backOutIn: EasingMethod.BACK_OUT_IN,
|
||||
bounceIn: EasingMethod.BOUNCE_IN,
|
||||
bounceOut: EasingMethod.BOUNCE_OUT,
|
||||
bounceInOut: EasingMethod.BOUNCE_IN_OUT,
|
||||
bounceOutIn: EasingMethod.BOUNCE_OUT_IN,
|
||||
smooth: EasingMethod.SMOOTH,
|
||||
fade: EasingMethod.FADE,
|
||||
};
|
||||
|
||||
/**
|
||||
* Legacy curve uses time based bezier curve interpolation.
|
||||
* That's, interpolate time 'x'(time ratio between two frames, eg.[0, 1])
|
||||
* and then use the interpolated time to sample curve.
|
||||
* Now we need to compute the the end tangent of previous frame and the start tangent of the next frame.
|
||||
* @param timeBezierPoints Bezier points used for legacy time interpolation.
|
||||
* @param previousTime Time of the previous keyframe.
|
||||
* @param previousValue Value of the previous keyframe.
|
||||
* @param nextTime Time of the next keyframe.
|
||||
* @param nextValue Value of the next keyframe.
|
||||
*/
|
||||
export function timeBezierToTangents (
|
||||
timeBezierPoints: BezierControlPoints,
|
||||
previousTime: number,
|
||||
previousKeyframe: RealKeyframeValue,
|
||||
nextTime: number,
|
||||
nextKeyframe: RealKeyframeValue,
|
||||
) {
|
||||
const [p1X, p1Y, p2X, p2Y] = timeBezierPoints;
|
||||
const { value: previousValue } = previousKeyframe;
|
||||
const { value: nextValue } = nextKeyframe;
|
||||
const dValue = nextValue - previousValue;
|
||||
const dTime = nextTime - previousTime;
|
||||
const fx = 3 * dTime;
|
||||
const fy = 3 * dValue;
|
||||
const t1x = p1X * fx;
|
||||
const t1y = p1Y * fy;
|
||||
const t2x = (1.0 - p2X) * fx;
|
||||
const t2y = (1.0 - p2Y) * fy;
|
||||
const ONE_THIRD = 1.0 / 3.0;
|
||||
const previousTangent = t1y / t1x;
|
||||
const previousTangentWeight = Math.sqrt(t1x * t1x + t1y * t1y) * ONE_THIRD;
|
||||
const nextTangent = t2y / t2x;
|
||||
const nextTangentWeight = Math.sqrt(t2x * t2x + t2y * t2y) * ONE_THIRD;
|
||||
previousKeyframe.interpolationMode = RealInterpolationMode.CUBIC;
|
||||
previousKeyframe.tangentWeightMode = ensureRightTangentWeightMode(previousKeyframe.tangentWeightMode);
|
||||
previousKeyframe.rightTangent = previousTangent;
|
||||
previousKeyframe.rightTangentWeight = previousTangentWeight;
|
||||
nextKeyframe.tangentWeightMode = ensureLeftTangentWeightMode(nextKeyframe.tangentWeightMode);
|
||||
nextKeyframe.leftTangent = nextTangent;
|
||||
nextKeyframe.leftTangentWeight = nextTangentWeight;
|
||||
}
|
||||
|
||||
function ensureLeftTangentWeightMode (tangentWeightMode: TangentWeightMode) {
|
||||
if (tangentWeightMode === TangentWeightMode.NONE) {
|
||||
return TangentWeightMode.LEFT;
|
||||
} else if (tangentWeightMode === TangentWeightMode.RIGHT) {
|
||||
return TangentWeightMode.BOTH;
|
||||
} else {
|
||||
return tangentWeightMode;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureRightTangentWeightMode (tangentWeightMode: TangentWeightMode) {
|
||||
if (tangentWeightMode === TangentWeightMode.NONE) {
|
||||
return TangentWeightMode.RIGHT;
|
||||
} else if (tangentWeightMode === TangentWeightMode.LEFT) {
|
||||
return TangentWeightMode.BOTH;
|
||||
} else {
|
||||
return tangentWeightMode;
|
||||
}
|
||||
}
|
||||
|
||||
// #region TODO: convert power easing method
|
||||
|
||||
// type Powers = [number, number, number, number];
|
||||
|
||||
// const POWERS_QUAD_IN: Powers = [0.0, 0.0, 1.0, 0.0]; // k * k
|
||||
// const POWERS_QUAD_OUT: Powers = [0.0, 2.0, -1.0, 0.0]; // k * (2 - k)
|
||||
// const POWERS_CUBIC_IN: Powers = [0.0, 0.0, 0.0, 1.0]; // k * k * k
|
||||
// const POWERS_CUBIC_OUT: Powers = [0.0, 0.0, 0.0, 1.0]; // --k * k * k + 1
|
||||
// const BACK_S = 1.70158;
|
||||
// const POWERS_BACK_IN: Powers = [1.0, 0.0, -BACK_S, BACK_S + 1.0]; // k * k * ((s + 1) * k - s)
|
||||
// const POWERS_BACK_OUT: Powers = [1.0, 0.0, BACK_S, BACK_S + 1.0]; // k * k * ((s + 1) * k - s)
|
||||
// const POWERS_SMOOTH: Powers = [0.0, 0.0, 3.0, -2.0]; // k * k * (3 - 2 * k)
|
||||
|
||||
// function convertPowerMethod (curve: RealCurve, keyframeIndex: number, powers: Powers) {
|
||||
// assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
|
||||
// const nextKeyframeIndex = keyframeIndex + 1;
|
||||
// powerToTangents(
|
||||
// powers,
|
||||
// curve.getKeyframeTime(keyframeIndex),
|
||||
// curve.getKeyframeValue(keyframeIndex),
|
||||
// curve.getKeyframeTime(nextKeyframeIndex),
|
||||
// curve.getKeyframeValue(nextKeyframeIndex),
|
||||
// );
|
||||
// return 0;
|
||||
// };
|
||||
|
||||
// function convertInOutPowersMethod (curve: RealCurve, keyframeIndex: number, inPowers: Powers, outPowers: Powers) {
|
||||
// assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
|
||||
// const nextKeyframeIndex = keyframeIndex + 1;
|
||||
// const previousTime = curve.getKeyframeTime(keyframeIndex);
|
||||
// const nextTime = curve.getKeyframeTime(nextKeyframeIndex);
|
||||
// const previousKeyframeValue = curve.getKeyframeValue(keyframeIndex);
|
||||
// const nextKeyframeValue = curve.getKeyframeValue(nextKeyframeIndex);
|
||||
// const middleTime = previousTime + (nextTime - previousTime);
|
||||
// const middleValue = previousKeyframeValue.value + (nextKeyframeValue.value - previousKeyframeValue.value);
|
||||
// const middleKeyframeValue = curve.getKeyframeValue(curve.addKeyFrame(middleTime, middleValue));
|
||||
// powerToTangents(
|
||||
// inPowers,
|
||||
// previousTime,
|
||||
// previousKeyframeValue,
|
||||
// middleTime,
|
||||
// middleKeyframeValue,
|
||||
// );
|
||||
// powerToTangents(
|
||||
// outPowers,
|
||||
// middleTime,
|
||||
// middleKeyframeValue,
|
||||
// nextTime,
|
||||
// nextKeyframeValue,
|
||||
// );
|
||||
// return 1;
|
||||
// };
|
||||
|
||||
// function powerToTangents (
|
||||
// [a, b, c, d]: [number, number, number, number],
|
||||
// previousTime: number,
|
||||
// previousKeyframe: RealKeyframeValue,
|
||||
// nextTime: number,
|
||||
// nextKeyframe: RealKeyframeValue,
|
||||
// ) {
|
||||
// const bernstein = powerToBernstein([a, b, c, d]);
|
||||
// const { value: previousValue } = previousKeyframe;
|
||||
// const { value: nextValue } = nextKeyframe;
|
||||
// timeBezierToTangents(
|
||||
// [???????],
|
||||
// previousTime,
|
||||
// previousValue,
|
||||
// nextTime,
|
||||
// nextValue,
|
||||
// );
|
||||
// }
|
||||
|
||||
// function powerToBernstein ([p0, p1, p2, p3]: [number, number, number, number]) {
|
||||
// // https://stackoverflow.com/questions/33859199/convert-polynomial-curve-to-bezier-curve-control-points
|
||||
// // https://blog.demofox.org/2016/12/08/evaluating-polynomials-with-the-gpu-texture-sampler/
|
||||
// const m00 = p0;
|
||||
// const m01 = p1 / 3.0;
|
||||
// const m02 = p2 / 3.0;
|
||||
// const m03 = p3;
|
||||
// const m10 = m00 + m01;
|
||||
// const m11 = m01 + m02;
|
||||
// const m12 = m02 + m03;
|
||||
// const m20 = m10 + m11;
|
||||
// const m21 = m11 + m12;
|
||||
// const m30 = m20 + m21;
|
||||
// const bernstein = new Float64Array(4);
|
||||
// bernstein[0] = m00;
|
||||
// bernstein[1] = m10;
|
||||
// bernstein[2] = m20;
|
||||
// bernstein[3] = m30;
|
||||
// return bernstein;
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
@@ -0,0 +1,29 @@
|
||||
import { BlendStateBuffer, BlendingProperty, BlendStateWriter } from '../../3d/skeletal-animation/skeletal-animation-blending';
|
||||
import type { Node } from '../scene-graph';
|
||||
|
||||
export type Pose = BlendStateBuffer;
|
||||
|
||||
export class PoseOutput {
|
||||
public weight = 0.0;
|
||||
|
||||
constructor (pose: Pose) {
|
||||
this._pose = pose;
|
||||
}
|
||||
|
||||
public destroy () {
|
||||
for (let iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
|
||||
this._pose.destroyWriter(this._blendStateWriters[iBlendStateWriter]);
|
||||
}
|
||||
this._blendStateWriters.length = 0;
|
||||
}
|
||||
|
||||
public createPoseWriter (node: Node, property: BlendingProperty, constants: boolean) {
|
||||
const writer = this._pose.createWriter(node, property, this, constants);
|
||||
this._blendStateWriters.push(writer);
|
||||
return writer;
|
||||
}
|
||||
|
||||
private _pose: Pose;
|
||||
|
||||
private _blendStateWriters: BlendStateWriter<any>[] = [];
|
||||
}
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { Node } from '../scene-graph/node';
|
||||
import { warn } from '../platform/debug';
|
||||
import { warn, warnID } from '../platform/debug';
|
||||
|
||||
export type PropertyPath = string | number;
|
||||
|
||||
@@ -63,12 +63,12 @@ export class HierarchyPath implements ICustomTargetPath {
|
||||
|
||||
public get (target: Node) {
|
||||
if (!(target instanceof Node)) {
|
||||
warn(`Target of hierarchy path should be of type Node.`);
|
||||
warnID(3925);
|
||||
return null;
|
||||
}
|
||||
const result = target.getChildByPath(this.path);
|
||||
if (!result) {
|
||||
warn(`Node "${target.name}" has no path "${this.path}"`);
|
||||
warnID(3926, target.name, this.path);
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
@@ -86,40 +86,14 @@ export class ComponentPath implements ICustomTargetPath {
|
||||
|
||||
public get (target: Node) {
|
||||
if (!(target instanceof Node)) {
|
||||
warn(`Target of component path should be of type Node.`);
|
||||
warnID(3927);
|
||||
return null;
|
||||
}
|
||||
const result = target.getComponent(this.component);
|
||||
if (!result) {
|
||||
warn(`Node "${target.name}" has no component "${this.component}"`);
|
||||
warnID(3928, target.name, this.component);
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a sequence of paths, in order, from specified root.
|
||||
* @param root The root object.
|
||||
* @param path The path sequence.
|
||||
*/
|
||||
export function evaluatePath (root: any, ...paths: TargetPath[]) {
|
||||
let result = root;
|
||||
for (let iPath = 0; iPath < paths.length; ++iPath) {
|
||||
const path = paths[iPath];
|
||||
if (isPropertyPath(path)) {
|
||||
if (!(path in result)) {
|
||||
warn(`Target object has no property "${path}"`);
|
||||
return null;
|
||||
} else {
|
||||
result = result[path];
|
||||
}
|
||||
} else {
|
||||
result = path.get(result);
|
||||
}
|
||||
if (result === null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { RealCurve } from '../../curves';
|
||||
import { Color } from '../../math';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { Channel, RealChannel, RuntimeBinding, Track } from './track';
|
||||
import { maskIfEmpty } from './utils';
|
||||
|
||||
const CHANNEL_NAMES: ReadonlyArray<string> = ['Red', 'Green', 'Blue', 'Alpha'];
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ColorTrack`)
|
||||
export class ColorTrack extends Track {
|
||||
constructor () {
|
||||
super();
|
||||
this._channels = new Array(4) as ColorTrack['_channels'];
|
||||
for (let i = 0; i < this._channels.length; ++i) {
|
||||
const channel = new Channel<RealCurve>(new RealCurve());
|
||||
channel.name = CHANNEL_NAMES[i];
|
||||
this._channels[i] = channel;
|
||||
}
|
||||
}
|
||||
|
||||
public channels () {
|
||||
return this._channels;
|
||||
}
|
||||
|
||||
public [createEvalSymbol] () {
|
||||
return new ColorTrackEval(
|
||||
maskIfEmpty(this._channels[0].curve),
|
||||
maskIfEmpty(this._channels[1].curve),
|
||||
maskIfEmpty(this._channels[2].curve),
|
||||
maskIfEmpty(this._channels[3].curve),
|
||||
);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _channels: [RealChannel, RealChannel, RealChannel, RealChannel];
|
||||
}
|
||||
|
||||
export class ColorTrackEval {
|
||||
constructor (
|
||||
private _x: RealCurve | undefined,
|
||||
private _y: RealCurve | undefined,
|
||||
private _z: RealCurve | undefined,
|
||||
private _w: RealCurve | undefined,
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number, runtimeBinding: RuntimeBinding) {
|
||||
if ((!this._x || !this._y || !this._z || !this._w) && runtimeBinding.getValue) {
|
||||
Color.copy(this._result, runtimeBinding.getValue() as Color);
|
||||
}
|
||||
|
||||
if (this._x) {
|
||||
this._result.r = this._x.evaluate(time);
|
||||
}
|
||||
if (this._y) {
|
||||
this._result.g = this._y.evaluate(time);
|
||||
}
|
||||
if (this._z) {
|
||||
this._result.b = this._z.evaluate(time);
|
||||
}
|
||||
if (this._w) {
|
||||
this._result.a = this._w.evaluate(time);
|
||||
}
|
||||
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Color = new Color();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ccclass } from 'cc.decorator';
|
||||
import { ObjectCurve } from '../../curves';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { SingleChannelTrack } from './track';
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}ObjectTrack`)
|
||||
export class ObjectTrack<T> extends SingleChannelTrack<ObjectCurve<T>> {
|
||||
protected createCurve () {
|
||||
return new ObjectCurve<T>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { ccclass } from 'cc.decorator';
|
||||
import { QuatCurve } from '../../curves';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { SingleChannelTrack } from './track';
|
||||
import { Quat } from '../../math';
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}QuatTrack`)
|
||||
export class QuatTrack extends SingleChannelTrack<QuatCurve> {
|
||||
protected createCurve () {
|
||||
return new QuatCurve();
|
||||
}
|
||||
|
||||
public [createEvalSymbol] () {
|
||||
return new QuatTrackEval(this.channels()[0].curve);
|
||||
}
|
||||
}
|
||||
|
||||
export class QuatTrackEval {
|
||||
constructor (private _curve: QuatCurve) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
this._curve.evaluate(time, this._result);
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Quat = new Quat();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ccclass } from 'cc.decorator';
|
||||
import { RealCurve } from '../../curves';
|
||||
import { CLASS_NAME_PREFIX_ANIM } from '../define';
|
||||
import { SingleChannelTrack } from './track';
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}RealTrack`)
|
||||
export class RealTrack extends SingleChannelTrack<RealCurve> {
|
||||
protected createCurve () {
|
||||
return new RealCurve();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { RealCurve } from '../../curves';
|
||||
import { Size } from '../../math';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { Channel, RealChannel, RuntimeBinding, Track } from './track';
|
||||
import { maskIfEmpty } from './utils';
|
||||
|
||||
const CHANNEL_NAMES: ReadonlyArray<string> = ['Width', 'Height'];
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}SizeTrack`)
|
||||
export class SizeTrack extends Track {
|
||||
constructor () {
|
||||
super();
|
||||
this._channels = new Array(2) as SizeTrack['_channels'];
|
||||
for (let i = 0; i < this._channels.length; ++i) {
|
||||
const channel = new Channel<RealCurve>(new RealCurve());
|
||||
channel.name = CHANNEL_NAMES[i];
|
||||
this._channels[i] = channel;
|
||||
}
|
||||
}
|
||||
|
||||
public channels () {
|
||||
return this._channels;
|
||||
}
|
||||
|
||||
public [createEvalSymbol] () {
|
||||
return new SizeTrackEval(
|
||||
maskIfEmpty(this._channels[0].curve),
|
||||
maskIfEmpty(this._channels[1].curve),
|
||||
);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _channels: [RealChannel, RealChannel];
|
||||
}
|
||||
|
||||
export class SizeTrackEval {
|
||||
constructor (
|
||||
private _width: RealCurve | undefined,
|
||||
private _height: RealCurve | undefined,
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number, runtimeBinding: RuntimeBinding) {
|
||||
if ((!this._width || !this._height) && runtimeBinding.getValue) {
|
||||
const size = runtimeBinding.getValue() as Size;
|
||||
this._result.x = size.x;
|
||||
this._result.y = size.y;
|
||||
}
|
||||
|
||||
if (this._width) {
|
||||
this._result.width = this._width.evaluate(time);
|
||||
}
|
||||
if (this._height) {
|
||||
this._result.height = this._height.evaluate(time);
|
||||
}
|
||||
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Size = new Size();
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import { ccclass, serializable, uniquelyReferenced } from 'cc.decorator';
|
||||
import type { Component } from '../../components';
|
||||
import type { ObjectCurve, QuatCurve, RealCurve } from '../../curves';
|
||||
import { assertIsTrue } from '../../data/utils/asserts';
|
||||
import { error, errorID, warn, warnID } from '../../platform';
|
||||
import { Node } from '../../scene-graph';
|
||||
import { js } from '../../utils/js';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { PoseOutput } from '../pose-output';
|
||||
import { ComponentPath, HierarchyPath, isPropertyPath, TargetPath } from '../target-path';
|
||||
import { IValueProxyFactory } from '../value-proxy';
|
||||
import { Range } from './utils';
|
||||
|
||||
const normalizedFollowTag = Symbol('NormalizedFollow');
|
||||
|
||||
const parseTrsPathTag = Symbol('ConvertAsTrsPath');
|
||||
|
||||
export const trackBindingTag = Symbol('TrackBinding');
|
||||
|
||||
/**
|
||||
* A track describes the path of animate a target.
|
||||
* It's the basic unit of animation clip.
|
||||
*/
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}Track`)
|
||||
export class Track {
|
||||
get path () {
|
||||
return this._binding.path;
|
||||
}
|
||||
|
||||
set path (value) {
|
||||
this._binding.path = value;
|
||||
}
|
||||
|
||||
get proxy () {
|
||||
return this._binding.proxy;
|
||||
}
|
||||
|
||||
set proxy (value) {
|
||||
this._binding.proxy = value;
|
||||
}
|
||||
|
||||
get [trackBindingTag] () {
|
||||
return this._binding;
|
||||
}
|
||||
|
||||
public channels (): Iterable<Channel> {
|
||||
return [];
|
||||
}
|
||||
|
||||
public range (): Range {
|
||||
const range: Range = { min: Infinity, max: -Infinity };
|
||||
for (const channel of this.channels()) {
|
||||
range.min = Math.min(range.min, channel.curve.rangeMin);
|
||||
range.max = Math.max(range.max, channel.curve.rangeMax);
|
||||
}
|
||||
return range;
|
||||
}
|
||||
|
||||
public [createEvalSymbol] (runtimeBinding: RuntimeBinding): TrackEval {
|
||||
throw new Error(`No Impl`);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _binding = new TrackBinding();
|
||||
}
|
||||
|
||||
export interface TrackEval {
|
||||
/**
|
||||
* Evaluates the track.
|
||||
* @param time The time.
|
||||
*/
|
||||
evaluate(time: number, runtimeBinding: RuntimeBinding): unknown;
|
||||
}
|
||||
|
||||
export type Curve = RealCurve | QuatCurve | ObjectCurve<unknown>;
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}Channel`)
|
||||
export class Channel<T = Curve> {
|
||||
constructor (curve: T) {
|
||||
this._curve = curve;
|
||||
}
|
||||
|
||||
/**
|
||||
* Not used for now.
|
||||
*/
|
||||
public name = '';
|
||||
|
||||
get curve () {
|
||||
return this._curve;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _curve!: T;
|
||||
}
|
||||
|
||||
export type RealChannel = Channel<RealCurve>;
|
||||
|
||||
export type QuatChannel = Channel<QuatCurve>;
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}SingleChannelTrack`)
|
||||
export abstract class SingleChannelTrack<TCurve extends Curve> extends Track {
|
||||
constructor () {
|
||||
super();
|
||||
this._channel = new Channel<TCurve>(this.createCurve());
|
||||
}
|
||||
|
||||
get channel () {
|
||||
return this._channel;
|
||||
}
|
||||
|
||||
public channels (): Iterable<Channel<TCurve>> {
|
||||
return [this._channel];
|
||||
}
|
||||
|
||||
protected createCurve (): TCurve {
|
||||
throw new Error(`Not impl`);
|
||||
}
|
||||
|
||||
public [createEvalSymbol] (_runtimeBinding: RuntimeBinding): TrackEval {
|
||||
const { curve } = this._channel;
|
||||
return new SingleChannelTrackEval(curve);
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _channel: Channel<TCurve>;
|
||||
}
|
||||
|
||||
class SingleChannelTrackEval<TCurve extends Curve> implements TrackEval {
|
||||
constructor (private _curve: TCurve) {
|
||||
}
|
||||
|
||||
public evaluate (time: number) {
|
||||
return this._curve.evaluate(time);
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeBinding = {
|
||||
setValue(value: unknown): void;
|
||||
|
||||
getValue?(): unknown;
|
||||
};
|
||||
|
||||
export type Binder = (binding: TrackBinding) => undefined | RuntimeBinding;
|
||||
|
||||
export type TrsTrackPath = [HierarchyPath, 'position' | 'rotation' | 'scale' | 'eulerAngles'];
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}TrackPath`)
|
||||
class TrackPath {
|
||||
get length () {
|
||||
return this._paths.length;
|
||||
}
|
||||
|
||||
public property (name: string) {
|
||||
this._paths.push(name);
|
||||
return this;
|
||||
}
|
||||
|
||||
public element (index: number) {
|
||||
this._paths.push(index);
|
||||
return this;
|
||||
}
|
||||
|
||||
public hierarchy (nodePath: string) {
|
||||
this._paths.push(new HierarchyPath(nodePath));
|
||||
return this;
|
||||
}
|
||||
|
||||
public component<T extends Component> (constructor: Constructor<T> | string) {
|
||||
const path = new ComponentPath(typeof constructor === 'string' ? constructor : js.getClassName(constructor));
|
||||
this._paths.push(path);
|
||||
return this;
|
||||
}
|
||||
|
||||
public customized (resolver: CustomizedTrackPathResolver) {
|
||||
this._paths.push(resolver);
|
||||
return this;
|
||||
}
|
||||
|
||||
public append (...trackPaths: TrackPath[]) {
|
||||
const paths = this._paths.concat(...trackPaths.map((trackPath) => trackPath._paths));
|
||||
this._paths = paths;
|
||||
return this;
|
||||
}
|
||||
|
||||
public isPropertyAt (index: number) {
|
||||
return typeof (this._paths[index]) === 'string';
|
||||
}
|
||||
|
||||
public parsePropertyAt (index: number): string {
|
||||
return this._paths[index] as string;
|
||||
}
|
||||
|
||||
public isElementAt (index: number) {
|
||||
return typeof this._paths[index] === 'number';
|
||||
}
|
||||
|
||||
public parseElementAt (index: number): number {
|
||||
return this._paths[index] as number;
|
||||
}
|
||||
|
||||
public isHierarchyAt (index: number) {
|
||||
return this._paths[index] instanceof HierarchyPath;
|
||||
}
|
||||
|
||||
public parseHierarchyAt (index: number) {
|
||||
assertIsTrue(this.isHierarchyAt(index));
|
||||
return (this._paths[index] as HierarchyPath).path;
|
||||
}
|
||||
|
||||
public isComponentAt (index: number) {
|
||||
return this._paths[index] instanceof ComponentPath;
|
||||
}
|
||||
|
||||
public parseComponentAt (index: number) {
|
||||
assertIsTrue(this.isComponentAt(index));
|
||||
return (this._paths[index] as ComponentPath).component;
|
||||
}
|
||||
|
||||
public slice (beginIndex?: number, endIndex?: number) {
|
||||
const trackPath = new TrackPath();
|
||||
trackPath._paths = this._paths.slice(beginIndex, endIndex);
|
||||
return trackPath;
|
||||
}
|
||||
|
||||
public follow (object: unknown, beginIndex?: number, endIndex?: number) {
|
||||
beginIndex ??= 0;
|
||||
endIndex ??= this._paths.length;
|
||||
return this[normalizedFollowTag](object, beginIndex, endIndex, undefined, false);
|
||||
}
|
||||
|
||||
public [parseTrsPathTag] () {
|
||||
const { _paths: paths } = this;
|
||||
const nPaths = paths.length;
|
||||
|
||||
let iPath = 0;
|
||||
|
||||
let nodePath = '';
|
||||
for (; iPath < nPaths; ++iPath) {
|
||||
const path = paths[iPath];
|
||||
if (!(path instanceof HierarchyPath)) {
|
||||
break;
|
||||
} else if (!path.path) {
|
||||
continue;
|
||||
} else if (nodePath) {
|
||||
nodePath += `/${path.path}`;
|
||||
} else {
|
||||
nodePath = path.path;
|
||||
}
|
||||
}
|
||||
|
||||
if (iPath === nPaths) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let prs: 'position' | 'scale' | 'rotation' | 'eulerAngles';
|
||||
if (iPath !== nPaths - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (paths[iPath]) {
|
||||
case 'position':
|
||||
case 'scale':
|
||||
case 'rotation':
|
||||
case 'eulerAngles':
|
||||
prs = paths[iPath] as typeof prs;
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
return { node: nodePath, property: prs };
|
||||
}
|
||||
|
||||
public [normalizedFollowTag] (root: unknown, beginIndex: number, endIndex: number, poseOutput: PoseOutput | undefined, isConstant: boolean) {
|
||||
const { _paths: paths } = this;
|
||||
let result = root;
|
||||
for (let iPath = beginIndex; iPath < endIndex; ++iPath) {
|
||||
const path = paths[iPath];
|
||||
if (isPropertyPath(path)) {
|
||||
if (!(path in (result as any))) {
|
||||
warnID(3929, path);
|
||||
return null;
|
||||
} else {
|
||||
if (poseOutput && iPath === endIndex - 1 && result instanceof Node && isTrsPropertyName(path)) {
|
||||
const blendStateWriter = poseOutput.createPoseWriter(result, path, isConstant);
|
||||
return blendStateWriter;
|
||||
}
|
||||
result = (result as any)[path];
|
||||
}
|
||||
} else {
|
||||
result = path.get(result);
|
||||
}
|
||||
if (result === null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _paths: TargetPath[] = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Composite of track path and value proxy.
|
||||
* Not exposed to external. If there is any reason it should be exposed,
|
||||
* please redesign the public interfaces.
|
||||
*/
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}TrackBinding`)
|
||||
@uniquelyReferenced
|
||||
export class TrackBinding {
|
||||
@serializable
|
||||
public path: Readonly<TrackPath> = new TrackPath();
|
||||
|
||||
@serializable
|
||||
public proxy: IValueProxyFactory | undefined;
|
||||
|
||||
public parseTrsPath () {
|
||||
if (this.proxy) {
|
||||
return null;
|
||||
} else {
|
||||
return this.path[parseTrsPathTag]();
|
||||
}
|
||||
}
|
||||
|
||||
public createRuntimeBinding (target: unknown, poseOutput: PoseOutput | undefined, isConstant: boolean) {
|
||||
const { path, proxy } = this;
|
||||
const nPaths = path.length;
|
||||
const iLastPath = nPaths - 1;
|
||||
if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
|
||||
const lastPropertyKey = path.isPropertyAt(iLastPath)
|
||||
? path.parsePropertyAt(iLastPath)
|
||||
: path.parseElementAt(iLastPath);
|
||||
const resultTarget = path[normalizedFollowTag](target, 0, nPaths - 1, poseOutput, isConstant) as any;
|
||||
if (resultTarget === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
setValue: (value: unknown) => {
|
||||
resultTarget[lastPropertyKey] = value;
|
||||
},
|
||||
// eslint-disable-next-line arrow-body-style
|
||||
getValue: () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return resultTarget[lastPropertyKey];
|
||||
},
|
||||
};
|
||||
} else if (!proxy) {
|
||||
errorID(3921);
|
||||
return null;
|
||||
} else {
|
||||
const resultTarget = path[normalizedFollowTag](target, 0, nPaths, poseOutput, isConstant);
|
||||
if (resultTarget === null) {
|
||||
return null;
|
||||
}
|
||||
const runtimeProxy = proxy.forTarget(resultTarget);
|
||||
const binding: RuntimeBinding = {
|
||||
setValue: (value) => {
|
||||
runtimeProxy.set(value);
|
||||
},
|
||||
};
|
||||
const proxyGet = runtimeProxy.get;
|
||||
if (proxyGet) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
binding.getValue = () => proxyGet.call(runtimeProxy);
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isTrsPropertyName (name: string | number): name is 'position' | 'rotation' | 'scale' | 'eulerAngles' {
|
||||
return name === 'position' || name === 'rotation' || name === 'scale' || name === 'eulerAngles';
|
||||
}
|
||||
|
||||
interface CustomizedTrackPathResolver {
|
||||
get (target: unknown): unknown;
|
||||
}
|
||||
|
||||
export { TrackPath };
|
||||
@@ -0,0 +1,138 @@
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { RealCurve } from '../../curves';
|
||||
import { Color, Size, Vec2, Vec3, Vec4 } from '../../math';
|
||||
import { getError } from '../../platform';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { IValueProxyFactory } from '../value-proxy';
|
||||
import { ColorTrack, ColorTrackEval } from './color-track';
|
||||
import { SizeTrackEval } from './size-track';
|
||||
import { Channel, RealChannel, RuntimeBinding, Track, TrackPath } from './track';
|
||||
import { Vec2TrackEval, Vec3TrackEval, Vec4TrackEval, VectorTrack } from './vector-track';
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}UntypedTrackChannel`)
|
||||
class UntypedTrackChannel extends Channel<RealCurve> {
|
||||
@serializable
|
||||
public property = '';
|
||||
|
||||
constructor () {
|
||||
super(new RealCurve());
|
||||
}
|
||||
}
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}UntypedTrack`)
|
||||
export class UntypedTrack extends Track {
|
||||
@serializable
|
||||
private _channels: UntypedTrackChannel[] = [];
|
||||
|
||||
public channels () {
|
||||
return this._channels;
|
||||
}
|
||||
|
||||
public [createEvalSymbol] (runtimeBinding: RuntimeBinding) {
|
||||
if (!runtimeBinding.getValue) {
|
||||
throw new Error(getError(3930));
|
||||
}
|
||||
const trySearchCurve = (property: string) => this._channels.find((channel) => channel.property === property)?.curve;
|
||||
const value = runtimeBinding.getValue();
|
||||
switch (true) {
|
||||
default:
|
||||
throw new Error(getError(3931));
|
||||
case value instanceof Vec2:
|
||||
return new Vec2TrackEval(
|
||||
trySearchCurve('x'),
|
||||
trySearchCurve('y'),
|
||||
);
|
||||
case value instanceof Vec3:
|
||||
return new Vec3TrackEval(
|
||||
trySearchCurve('x'),
|
||||
trySearchCurve('y'),
|
||||
trySearchCurve('z'),
|
||||
);
|
||||
case value instanceof Vec4:
|
||||
return new Vec4TrackEval(
|
||||
trySearchCurve('x'),
|
||||
trySearchCurve('y'),
|
||||
trySearchCurve('z'),
|
||||
trySearchCurve('w'),
|
||||
);
|
||||
case value instanceof Color:
|
||||
// TODO: what if x, y, z, w?
|
||||
return new ColorTrackEval(
|
||||
trySearchCurve('r'),
|
||||
trySearchCurve('g'),
|
||||
trySearchCurve('b'),
|
||||
trySearchCurve('a'),
|
||||
);
|
||||
case value instanceof Size:
|
||||
return new SizeTrackEval(
|
||||
trySearchCurve('width'),
|
||||
trySearchCurve('height'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public addChannel (property: string): UntypedTrackChannel {
|
||||
const channel = new UntypedTrackChannel();
|
||||
channel.property = property;
|
||||
this._channels.push(channel);
|
||||
return channel;
|
||||
}
|
||||
|
||||
public upgrade (refine: UntypedTrackRefine): Track | null {
|
||||
const trySearchChannel = (property: string, outChannel: RealChannel) => {
|
||||
const untypedChannel = this.channels().find((channel) => channel.property === property);
|
||||
if (untypedChannel) {
|
||||
outChannel.name = untypedChannel.name;
|
||||
outChannel.curve.assignSorted(
|
||||
Array.from(untypedChannel.curve.times()),
|
||||
Array.from(untypedChannel.curve.values()),
|
||||
);
|
||||
}
|
||||
};
|
||||
const kind = refine(this.path, this.proxy);
|
||||
switch (kind) {
|
||||
default:
|
||||
break;
|
||||
case 'vec2': case 'vec3': case 'vec4': {
|
||||
const track = new VectorTrack();
|
||||
track.path = this.path;
|
||||
track.proxy = this.proxy;
|
||||
track.componentsCount = kind === 'vec2' ? 2 : kind === 'vec3' ? 3 : 4;
|
||||
const [x, y, z, w] = track.channels();
|
||||
switch (kind) {
|
||||
case 'vec4':
|
||||
trySearchChannel('w', w);
|
||||
// fall through
|
||||
case 'vec3':
|
||||
trySearchChannel('z', z);
|
||||
// fall through
|
||||
default:
|
||||
case 'vec2':
|
||||
trySearchChannel('x', x);
|
||||
trySearchChannel('y', y);
|
||||
}
|
||||
return track;
|
||||
}
|
||||
case 'color': {
|
||||
const track = new ColorTrack();
|
||||
const [r, g, b, a] = track.channels();
|
||||
trySearchChannel('r', r);
|
||||
trySearchChannel('g', g);
|
||||
trySearchChannel('b', b);
|
||||
trySearchChannel('a', a);
|
||||
// TODO: we need float-int conversion if xyzw
|
||||
trySearchChannel('x', r);
|
||||
trySearchChannel('y', g);
|
||||
trySearchChannel('z', b);
|
||||
trySearchChannel('w', a);
|
||||
return track;
|
||||
}
|
||||
case 'size':
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type UntypedTrackRefine = (path: Readonly<TrackPath>, proxy: IValueProxyFactory | undefined) => 'vec2' | 'vec3' | 'vec4' | 'color' | 'size';
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Curve } from './track';
|
||||
|
||||
export function maskIfEmpty<T extends Curve> (curve: T) {
|
||||
return curve.keyFramesCount === 0 ? undefined : curve;
|
||||
}
|
||||
|
||||
export interface Range {
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { ccclass, serializable } from 'cc.decorator';
|
||||
import { RealCurve } from '../../curves';
|
||||
import { Vec2, Vec3, Vec4 } from '../../math';
|
||||
import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define';
|
||||
import { Channel, RealChannel, RuntimeBinding, Track } from './track';
|
||||
import { maskIfEmpty } from './utils';
|
||||
|
||||
const CHANNEL_NAMES: ReadonlyArray<string> = ['X', 'Y', 'Z', 'W'];
|
||||
|
||||
@ccclass(`${CLASS_NAME_PREFIX_ANIM}VectorTrack`)
|
||||
export class VectorTrack extends Track {
|
||||
constructor () {
|
||||
super();
|
||||
this._channels = new Array(4) as VectorTrack['_channels'];
|
||||
for (let i = 0; i < this._channels.length; ++i) {
|
||||
const channel = new Channel<RealCurve>(new RealCurve());
|
||||
channel.name = CHANNEL_NAMES[i];
|
||||
this._channels[i] = channel;
|
||||
}
|
||||
}
|
||||
|
||||
get componentsCount () {
|
||||
return this._nComponents;
|
||||
}
|
||||
|
||||
set componentsCount (value) {
|
||||
this._nComponents = value;
|
||||
}
|
||||
|
||||
public channels () {
|
||||
return this._channels;
|
||||
}
|
||||
|
||||
public [createEvalSymbol] () {
|
||||
switch (this._nComponents) {
|
||||
default:
|
||||
case 2:
|
||||
return new Vec2TrackEval(
|
||||
maskIfEmpty(this._channels[0].curve),
|
||||
maskIfEmpty(this._channels[1].curve),
|
||||
);
|
||||
case 3:
|
||||
return new Vec3TrackEval(
|
||||
maskIfEmpty(this._channels[0].curve),
|
||||
maskIfEmpty(this._channels[1].curve),
|
||||
maskIfEmpty(this._channels[2].curve),
|
||||
);
|
||||
case 4:
|
||||
return new Vec4TrackEval(
|
||||
maskIfEmpty(this._channels[0].curve),
|
||||
maskIfEmpty(this._channels[1].curve),
|
||||
maskIfEmpty(this._channels[2].curve),
|
||||
maskIfEmpty(this._channels[3].curve),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _channels: [RealChannel, RealChannel, RealChannel, RealChannel];
|
||||
|
||||
@serializable
|
||||
private _nComponents: 2 | 3 | 4 = 4;
|
||||
}
|
||||
|
||||
export class Vec2TrackEval {
|
||||
constructor (private _x: RealCurve | undefined, private _y: RealCurve | undefined) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number, runtimeBinding: RuntimeBinding) {
|
||||
if ((!this._x || !this._y) && runtimeBinding.getValue) {
|
||||
Vec2.copy(this._result, runtimeBinding.getValue() as Vec2);
|
||||
}
|
||||
|
||||
if (this._x) {
|
||||
this._result.x = this._x.evaluate(time);
|
||||
}
|
||||
if (this._y) {
|
||||
this._result.y = this._y.evaluate(time);
|
||||
}
|
||||
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Vec2 = new Vec2();
|
||||
}
|
||||
|
||||
export class Vec3TrackEval {
|
||||
constructor (private _x: RealCurve | undefined, private _y: RealCurve | undefined, private _z: RealCurve | undefined) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number, runtimeBinding: RuntimeBinding) {
|
||||
if ((!this._x || !this._y || !this._z) && runtimeBinding.getValue) {
|
||||
Vec3.copy(this._result, runtimeBinding.getValue() as Vec3);
|
||||
}
|
||||
|
||||
if (this._x) {
|
||||
this._result.x = this._x.evaluate(time);
|
||||
}
|
||||
if (this._y) {
|
||||
this._result.y = this._y.evaluate(time);
|
||||
}
|
||||
if (this._z) {
|
||||
this._result.z = this._z.evaluate(time);
|
||||
}
|
||||
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Vec3 = new Vec3();
|
||||
}
|
||||
|
||||
export class Vec4TrackEval {
|
||||
constructor (
|
||||
private _x: RealCurve | undefined,
|
||||
private _y: RealCurve | undefined,
|
||||
private _z: RealCurve | undefined,
|
||||
private _w: RealCurve | undefined,
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
public evaluate (time: number, runtimeBinding: RuntimeBinding) {
|
||||
if ((!this._x || !this._y || !this._z || !this._w) && runtimeBinding.getValue) {
|
||||
Vec4.copy(this._result, runtimeBinding.getValue() as Vec4);
|
||||
}
|
||||
|
||||
if (this._x) {
|
||||
this._result.x = this._x.evaluate(time);
|
||||
}
|
||||
if (this._y) {
|
||||
this._result.y = this._y.evaluate(time);
|
||||
}
|
||||
if (this._z) {
|
||||
this._result.z = this._z.evaluate(time);
|
||||
}
|
||||
if (this._w) {
|
||||
this._result.w = this._w.evaluate(time);
|
||||
}
|
||||
|
||||
return this._result;
|
||||
}
|
||||
|
||||
private _result: Vec4 = new Vec4();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface CurveBase {
|
||||
readonly rangeMin: number;
|
||||
readonly rangeMax: number;
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
import { assertIsTrue } from '../data/utils/asserts';
|
||||
import { approx, lerp, pingPong, repeat } from '../math';
|
||||
import { KeyframeCurve } from './keyframe-curve';
|
||||
import { ccclass, serializable, uniquelyReferenced } from '../data/decorators';
|
||||
import { RealInterpolationMode, ExtrapolationMode, TangentWeightMode } from './real-curve-param';
|
||||
import { binarySearchEpsilon } from '../algorithm/binary-search';
|
||||
import { solveCubic } from './solve-cubic';
|
||||
import { EditorExtendable, EditorExtendableMixin } from '../data/editor-extendable';
|
||||
import { deserializeTag, editorExtrasTag, SerializationContext, SerializationInput, SerializationOutput, serializeTag } from '../data';
|
||||
import { DeserializationContext } from '../data/custom-serializable';
|
||||
import * as easing from '../animation/easing';
|
||||
|
||||
export { RealInterpolationMode, ExtrapolationMode, TangentWeightMode };
|
||||
|
||||
export enum EasingMethod {
|
||||
LINEAR,
|
||||
CONSTANT,
|
||||
QUAD_IN,
|
||||
QUAD_OUT,
|
||||
QUAD_IN_OUT,
|
||||
QUAD_OUT_IN,
|
||||
CUBIC_IN,
|
||||
CUBIC_OUT,
|
||||
CUBIC_IN_OUT,
|
||||
CUBIC_OUT_IN,
|
||||
QUART_IN,
|
||||
QUART_OUT,
|
||||
QUART_IN_OUT,
|
||||
QUART_OUT_IN,
|
||||
QUINT_IN,
|
||||
QUINT_OUT,
|
||||
QUINT_IN_OUT,
|
||||
QUINT_OUT_IN,
|
||||
SINE_IN,
|
||||
SINE_OUT,
|
||||
SINE_IN_OUT,
|
||||
SINE_OUT_IN,
|
||||
EXPO_IN,
|
||||
EXPO_OUT,
|
||||
EXPO_IN_OUT,
|
||||
EXPO_OUT_IN,
|
||||
CIRC_IN,
|
||||
CIRC_OUT,
|
||||
CIRC_IN_OUT,
|
||||
CIRC_OUT_IN,
|
||||
ELASTIC_IN,
|
||||
ELASTIC_OUT,
|
||||
ELASTIC_IN_OUT,
|
||||
ELASTIC_OUT_IN,
|
||||
BACK_IN,
|
||||
BACK_OUT,
|
||||
BACK_IN_OUT,
|
||||
BACK_OUT_IN,
|
||||
BOUNCE_IN,
|
||||
BOUNCE_OUT,
|
||||
BOUNCE_IN_OUT,
|
||||
BOUNCE_OUT_IN,
|
||||
SMOOTH,
|
||||
FADE,
|
||||
}
|
||||
|
||||
/**
|
||||
* View to a real frame value.
|
||||
* Note, the view may be invalidated due to keyframe change/add/remove.
|
||||
*/
|
||||
@ccclass('cc.RealKeyframeValue')
|
||||
@uniquelyReferenced
|
||||
class RealKeyframeValue extends EditorExtendable {
|
||||
constructor ({
|
||||
interpolationMode,
|
||||
tangentWeightMode,
|
||||
value,
|
||||
rightTangent,
|
||||
rightTangentWeight,
|
||||
leftTangent,
|
||||
leftTangentWeight,
|
||||
easingMethod,
|
||||
[editorExtrasTag]: editorExtras,
|
||||
}: Partial<RealKeyframeValue> = { }) {
|
||||
super();
|
||||
this.value = value ?? this.value;
|
||||
this.rightTangent = rightTangent ?? this.rightTangent;
|
||||
this.rightTangentWeight = rightTangentWeight ?? this.rightTangentWeight;
|
||||
this.leftTangent = leftTangent ?? this.leftTangent;
|
||||
this.leftTangentWeight = leftTangentWeight ?? this.leftTangentWeight;
|
||||
this.interpolationMode = interpolationMode ?? this.interpolationMode;
|
||||
this.tangentWeightMode = tangentWeightMode ?? this.tangentWeightMode;
|
||||
this.easingMethod = easingMethod ?? this.easingMethod;
|
||||
if (editorExtras) {
|
||||
this[editorExtrasTag] = editorExtras;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolation method used for this keyframe.
|
||||
*/
|
||||
@serializable
|
||||
public interpolationMode = RealInterpolationMode.LINEAR;
|
||||
|
||||
/**
|
||||
* Tangent weight mode.
|
||||
*/
|
||||
@serializable
|
||||
public tangentWeightMode = TangentWeightMode.NONE;
|
||||
|
||||
/**
|
||||
* Value of the keyframe.
|
||||
*/
|
||||
@serializable
|
||||
public value = 0.0;
|
||||
|
||||
/**
|
||||
* The (y component of) tangent of this keyframe
|
||||
* when it's used as starting point during cubic interpolation.
|
||||
* Meaningless otherwise.
|
||||
*/
|
||||
@serializable
|
||||
public rightTangent = 0.0;
|
||||
|
||||
/**
|
||||
* The x component tangent of this keyframe
|
||||
* when it's used as starting point during cubic interpolation.
|
||||
* Meaningless otherwise.
|
||||
*/
|
||||
@serializable
|
||||
public rightTangentWeight = 0.0;
|
||||
|
||||
/**
|
||||
* The (y component of) tangent of this keyframe
|
||||
* when it's used as ending point during cubic interpolation.
|
||||
* Meaningless otherwise.
|
||||
*/
|
||||
@serializable
|
||||
public leftTangent = 0.0;
|
||||
|
||||
/**
|
||||
* The x component of tangent of this keyframe
|
||||
* when it's used as starting point during cubic interpolation.
|
||||
* Meaningless otherwise.
|
||||
*/
|
||||
@serializable
|
||||
public leftTangentWeight = 0.0;
|
||||
|
||||
/**
|
||||
* @deprecated Reserved for backward compatibility. Will be removed in future.
|
||||
*/
|
||||
@serializable
|
||||
public easingMethod = EasingMethod.LINEAR;
|
||||
}
|
||||
|
||||
export type { RealKeyframeValue };
|
||||
|
||||
/**
|
||||
* The parameter describing a real keyframe value.
|
||||
* In the case of partial keyframe value,
|
||||
* each component of the keyframe value is taken from the parameter.
|
||||
* For unspecified components, default values are taken:
|
||||
* - Interpolation mode: linear
|
||||
* - Tangent weight mode: none
|
||||
* - Value/Tangents/Tangent weights: 0.0
|
||||
*/
|
||||
type RealKeyframeValueParameters = number | Partial<RealKeyframeValue>;
|
||||
|
||||
function createRealKeyframeValue (params: RealKeyframeValueParameters) {
|
||||
return new RealKeyframeValue(typeof params === 'number' ? { value: params } : params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Curve.
|
||||
*/
|
||||
@ccclass('cc.RealCurve')
|
||||
export class RealCurve extends KeyframeCurve<RealKeyframeValue> {
|
||||
/**
|
||||
* Gets or sets the operation should be taken
|
||||
* if input time is less than the time of first keyframe when evaluating this curve.
|
||||
* Defaults to `ExtrapolationMode.CLAMP`.
|
||||
*/
|
||||
@serializable
|
||||
public preExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP;
|
||||
|
||||
/**
|
||||
* Gets or sets the operation should be taken
|
||||
* if input time is greater than the time of last keyframe when evaluating this curve.
|
||||
* Defaults to `ExtrapolationMode.CLAMP`.
|
||||
*/
|
||||
@serializable
|
||||
public postExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP;
|
||||
|
||||
/**
|
||||
* Evaluates this curve at specified time.
|
||||
* @param time Input time.
|
||||
* @returns Result value.
|
||||
*/
|
||||
public evaluate (time: number): number {
|
||||
const {
|
||||
_times: times,
|
||||
_values: values,
|
||||
} = this;
|
||||
|
||||
const nFrames = times.length;
|
||||
|
||||
if (nFrames === 0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
const firstTime = times[0];
|
||||
const lastTime = times[nFrames - 1];
|
||||
if (time < firstTime) {
|
||||
// Underflow
|
||||
const { preExtrapolation } = this;
|
||||
const preValue = values[0];
|
||||
if (preExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
|
||||
return preValue.value;
|
||||
}
|
||||
switch (preExtrapolation) {
|
||||
case ExtrapolationMode.LINEAR:
|
||||
return linearTrend(firstTime, values[0].value, times[1], values[1].value, time);
|
||||
case ExtrapolationMode.LOOP:
|
||||
time = wrapRepeat(time, firstTime, lastTime);
|
||||
break;
|
||||
case ExtrapolationMode.PING_PONG:
|
||||
time = wrapPingPong(time, firstTime, lastTime);
|
||||
break;
|
||||
default:
|
||||
return preValue.value;
|
||||
}
|
||||
} else if (time > lastTime) {
|
||||
// Overflow
|
||||
const { postExtrapolation } = this;
|
||||
const preFrame = values[nFrames - 1];
|
||||
if (postExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
|
||||
return preFrame.value;
|
||||
}
|
||||
switch (postExtrapolation) {
|
||||
case ExtrapolationMode.LINEAR:
|
||||
return linearTrend(lastTime, preFrame.value, times[nFrames - 2], values[nFrames - 2].value, time);
|
||||
case ExtrapolationMode.LOOP:
|
||||
time = wrapRepeat(time, firstTime, lastTime);
|
||||
break;
|
||||
case ExtrapolationMode.PING_PONG:
|
||||
time = wrapPingPong(time, firstTime, lastTime);
|
||||
break;
|
||||
default:
|
||||
return preFrame.value;
|
||||
}
|
||||
}
|
||||
|
||||
const index = binarySearchEpsilon(times, time);
|
||||
if (index >= 0) {
|
||||
return values[index].value;
|
||||
}
|
||||
|
||||
const iNext = ~index;
|
||||
assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
|
||||
|
||||
const iPre = iNext - 1;
|
||||
const preTime = times[iPre];
|
||||
const preValue = values[iPre];
|
||||
const nextTime = times[iNext];
|
||||
const nextValue = values[iNext];
|
||||
assertIsTrue(nextTime > time && time > preTime);
|
||||
const dt = nextTime - preTime;
|
||||
|
||||
const ratio = (time - preTime) / dt;
|
||||
return evalBetweenTwoKeyFrames(preTime, preValue, nextTime, nextValue, ratio);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a keyframe into this curve.
|
||||
* @param time Time of the keyframe.
|
||||
* @param value Value of the keyframe.
|
||||
* @returns The index to the new keyframe.
|
||||
*/
|
||||
public addKeyFrame (time: number, value: RealKeyframeValueParameters): number {
|
||||
return super.addKeyFrame(time, createRealKeyframeValue(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param keyframes An iterable to keyframes. The keyframes should be sorted by their time.
|
||||
*/
|
||||
public assignSorted (keyframes: Iterable<[number, RealKeyframeValueParameters]>): void;
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param times Times array. Should be sorted.
|
||||
* @param values Values array. Corresponding to each time in `times`.
|
||||
*/
|
||||
public assignSorted (times: readonly number[], values: RealKeyframeValueParameters[]): void;
|
||||
|
||||
public assignSorted (
|
||||
times: Iterable<[number, RealKeyframeValueParameters]> | readonly number[],
|
||||
values?: readonly RealKeyframeValueParameters[],
|
||||
) {
|
||||
if (values !== undefined) {
|
||||
assertIsTrue(Array.isArray(times));
|
||||
this.setKeyframes(
|
||||
times.slice(),
|
||||
values.map((value) => createRealKeyframeValue(value)),
|
||||
);
|
||||
} else {
|
||||
const keyframes = Array.from(times as Iterable<[number, Partial<RealKeyframeValue>]>);
|
||||
this.setKeyframes(
|
||||
keyframes.map(([time]) => time),
|
||||
keyframes.map(([, value]) => createRealKeyframeValue(value)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if this curve is constant.
|
||||
* @param tolerance The tolerance.
|
||||
* @returns Whether it is constant.
|
||||
*/
|
||||
public isConstant (tolerance: number) {
|
||||
if (this._values.length <= 1) {
|
||||
return true;
|
||||
}
|
||||
const firstVal = this._values[0].value;
|
||||
return this._values.every((frame) => approx(frame.value, firstVal, tolerance));
|
||||
}
|
||||
|
||||
public [serializeTag] (output: SerializationOutput, context: SerializationContext) {
|
||||
if (!context.toCCON) {
|
||||
output.writeThis();
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
_times: times,
|
||||
_values: keyframeValues,
|
||||
} = this;
|
||||
|
||||
const nKeyframes = times.length;
|
||||
|
||||
const dataSize = 0
|
||||
+ OVERFLOW_BYTES + OVERFLOW_BYTES
|
||||
+ FRAME_COUNT_BYTES
|
||||
+ TIME_BYTES * nKeyframes
|
||||
+ REAL_KEY_FRAME_VALUE_MAX_SIZE * nKeyframes;
|
||||
|
||||
const dataView = new DataView(new ArrayBuffer(dataSize));
|
||||
let currentOffset = 0;
|
||||
|
||||
// Overflow operations
|
||||
dataView.setUint8(currentOffset, this.preExtrapolation); currentOffset += OVERFLOW_BYTES;
|
||||
dataView.setUint8(currentOffset, this.postExtrapolation); currentOffset += OVERFLOW_BYTES;
|
||||
|
||||
// Frame count
|
||||
dataView.setUint32(currentOffset, nKeyframes, true); currentOffset += FRAME_COUNT_BYTES;
|
||||
|
||||
// Times
|
||||
times.forEach((time, index) => dataView.setFloat32(currentOffset + TIME_BYTES * index, time, true));
|
||||
currentOffset += TIME_BYTES * nKeyframes;
|
||||
|
||||
// Frame values
|
||||
for (const keyframeValue of keyframeValues) {
|
||||
currentOffset = saveRealKeyFrameValue(dataView, keyframeValue, currentOffset);
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(dataView.buffer, 0, currentOffset);
|
||||
output.writeProperty('bytes', bytes);
|
||||
|
||||
const keyframeValueEditorExtras = keyframeValues.map((keyframeValue) => keyframeValue[editorExtrasTag]);
|
||||
if (keyframeValueEditorExtras.some((extras) => extras !== undefined)) {
|
||||
output.writeProperty(`keyframeValueEditorExtras`, keyframeValueEditorExtras);
|
||||
}
|
||||
}
|
||||
|
||||
public [deserializeTag] (input: SerializationInput, context: DeserializationContext) {
|
||||
if (!context.fromCCON) {
|
||||
input.readThis();
|
||||
return;
|
||||
}
|
||||
|
||||
const bytes = input.readProperty('bytes') as Uint8Array;
|
||||
|
||||
const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let currentOffset = 0;
|
||||
|
||||
// Overflow operations
|
||||
this.preExtrapolation = dataView.getUint8(currentOffset); currentOffset += OVERFLOW_BYTES;
|
||||
this.postExtrapolation = dataView.getUint8(currentOffset); currentOffset += OVERFLOW_BYTES;
|
||||
|
||||
// Frame count
|
||||
const nKeyframes = dataView.getUint32(currentOffset, true); currentOffset += FRAME_COUNT_BYTES;
|
||||
|
||||
// Times
|
||||
const times = Array.from({ length: nKeyframes },
|
||||
(_, index) => dataView.getFloat32(currentOffset + TIME_BYTES * index, true));
|
||||
currentOffset += TIME_BYTES * nKeyframes;
|
||||
|
||||
// Frame values
|
||||
const keyframeValues = new Array<RealKeyframeValue>(nKeyframes);
|
||||
for (let iKeyFrame = 0; iKeyFrame < nKeyframes; ++iKeyFrame) {
|
||||
const keyframeValue = createRealKeyframeValue({});
|
||||
currentOffset = loadRealKeyFrameValue(dataView, keyframeValue, currentOffset);
|
||||
keyframeValues[iKeyFrame] = keyframeValue;
|
||||
}
|
||||
|
||||
assertIsTrue(currentOffset === bytes.byteLength);
|
||||
|
||||
const keyframeValueEditorExtras = input.readProperty(`keyframeValueEditorExtras`) as unknown[];
|
||||
if (keyframeValueEditorExtras) {
|
||||
assertIsTrue(keyframeValueEditorExtras.length === nKeyframes);
|
||||
keyframeValueEditorExtras.forEach(
|
||||
(extras, index) => keyframeValues[index][editorExtrasTag] = extras,
|
||||
);
|
||||
}
|
||||
|
||||
this._times = times;
|
||||
this._values = keyframeValues;
|
||||
}
|
||||
}
|
||||
|
||||
const FLAGS_EASING_METHOD_BITS_START = 8;
|
||||
const FLAG_EASING_METHOD_MASK = 0xFF << FLAGS_EASING_METHOD_BITS_START; // 8-16 bits
|
||||
|
||||
enum KeyframeValueFlagMask {
|
||||
VALUE = 1 << 0,
|
||||
INTERPOLATION_MODE = 1 << 1,
|
||||
TANGENT_WEIGHT_MODE = 1 << 2,
|
||||
LEFT_TANGENT = 1 << 3,
|
||||
LEFT_TANGENT_WEIGHT = 1 << 4,
|
||||
RIGHT_TANGENT = 1 << 5,
|
||||
RIGHT_TANGENT_WEIGHT = 1 << 6,
|
||||
}
|
||||
|
||||
const OVERFLOW_BYTES = 1;
|
||||
const FRAME_COUNT_BYTES = 4;
|
||||
const TIME_BYTES = 4;
|
||||
const KEY_FRAME_VALUE_FLAGS_BYTES = 4;
|
||||
const VALUE_BYTES = 4;
|
||||
const INTERPOLATION_MODE_BYTES = 1;
|
||||
const TANGENT_WEIGHT_MODE_BYTES = 1;
|
||||
const LEFT_TANGENT_BYTES = 4;
|
||||
const LEFT_TANGENT_WEIGHT_BYTES = 4;
|
||||
const RIGHT_TANGENT_BYTES = 4;
|
||||
const RIGHT_TANGENT_WEIGHT_BYTES = 4;
|
||||
|
||||
const {
|
||||
interpolationMode: DEFAULT_INTERPOLATION_MODE,
|
||||
tangentWeightMode: DEFAULT_TANGENT_WEIGHT_MODE,
|
||||
leftTangent: DEFAULT_LEFT_TANGENT,
|
||||
leftTangentWeight: DEFAULT_LEFT_TANGENT_WEIGHT,
|
||||
rightTangent: DEFAULT_RIGHT_TANGENT,
|
||||
rightTangentWeight: DEFAULT_RIGHT_TANGENT_WEIGHT,
|
||||
} = createRealKeyframeValue({});
|
||||
|
||||
const REAL_KEY_FRAME_VALUE_MAX_SIZE = KEY_FRAME_VALUE_FLAGS_BYTES
|
||||
+ VALUE_BYTES
|
||||
+ INTERPOLATION_MODE_BYTES
|
||||
+ TANGENT_WEIGHT_MODE_BYTES
|
||||
+ LEFT_TANGENT_BYTES
|
||||
+ LEFT_TANGENT_WEIGHT_BYTES
|
||||
+ RIGHT_TANGENT_BYTES
|
||||
+ RIGHT_TANGENT_WEIGHT_BYTES
|
||||
+ 0;
|
||||
|
||||
function saveRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number) {
|
||||
let flags = 0;
|
||||
|
||||
let currentOffset = offset;
|
||||
|
||||
const pFlags = currentOffset; // Place holder for flags
|
||||
currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
|
||||
|
||||
const {
|
||||
value,
|
||||
interpolationMode,
|
||||
tangentWeightMode,
|
||||
rightTangent,
|
||||
rightTangentWeight,
|
||||
leftTangent,
|
||||
leftTangentWeight,
|
||||
easingMethod,
|
||||
} = keyframeValue;
|
||||
|
||||
dataView.setFloat32(currentOffset, value, true);
|
||||
currentOffset += VALUE_BYTES;
|
||||
|
||||
if (interpolationMode !== DEFAULT_INTERPOLATION_MODE) {
|
||||
flags |= KeyframeValueFlagMask.INTERPOLATION_MODE;
|
||||
dataView.setUint8(currentOffset, interpolationMode);
|
||||
currentOffset += INTERPOLATION_MODE_BYTES;
|
||||
}
|
||||
|
||||
if (tangentWeightMode !== DEFAULT_TANGENT_WEIGHT_MODE) {
|
||||
flags |= KeyframeValueFlagMask.TANGENT_WEIGHT_MODE;
|
||||
dataView.setUint8(currentOffset, tangentWeightMode);
|
||||
currentOffset += TANGENT_WEIGHT_MODE_BYTES;
|
||||
}
|
||||
|
||||
if (leftTangent !== DEFAULT_LEFT_TANGENT) {
|
||||
flags |= KeyframeValueFlagMask.LEFT_TANGENT;
|
||||
dataView.setFloat32(currentOffset, leftTangent, true);
|
||||
currentOffset += LEFT_TANGENT_BYTES;
|
||||
}
|
||||
|
||||
if (leftTangentWeight !== DEFAULT_LEFT_TANGENT_WEIGHT) {
|
||||
flags |= KeyframeValueFlagMask.LEFT_TANGENT_WEIGHT;
|
||||
dataView.setFloat32(currentOffset, leftTangentWeight, true);
|
||||
currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
|
||||
}
|
||||
|
||||
if (rightTangent !== DEFAULT_RIGHT_TANGENT) {
|
||||
flags |= KeyframeValueFlagMask.RIGHT_TANGENT;
|
||||
dataView.setFloat32(currentOffset, rightTangent, true);
|
||||
currentOffset += RIGHT_TANGENT_BYTES;
|
||||
}
|
||||
|
||||
if (rightTangentWeight !== DEFAULT_RIGHT_TANGENT_WEIGHT) {
|
||||
flags |= KeyframeValueFlagMask.RIGHT_TANGENT_WEIGHT;
|
||||
dataView.setFloat32(currentOffset, rightTangentWeight, true);
|
||||
currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
|
||||
}
|
||||
|
||||
flags |= (easingMethod << FLAGS_EASING_METHOD_BITS_START);
|
||||
|
||||
dataView.setUint32(pFlags, flags, true);
|
||||
|
||||
return currentOffset;
|
||||
}
|
||||
|
||||
function loadRealKeyFrameValue (dataView: DataView, keyframeValue: RealKeyframeValue, offset: number) {
|
||||
let currentOffset = offset;
|
||||
|
||||
const flags = dataView.getUint32(currentOffset, true);
|
||||
currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
|
||||
|
||||
keyframeValue.value = dataView.getFloat32(currentOffset, true);
|
||||
currentOffset += VALUE_BYTES;
|
||||
|
||||
if (flags & KeyframeValueFlagMask.INTERPOLATION_MODE) {
|
||||
keyframeValue.interpolationMode = dataView.getUint8(currentOffset);
|
||||
currentOffset += INTERPOLATION_MODE_BYTES;
|
||||
}
|
||||
|
||||
if (flags & KeyframeValueFlagMask.TANGENT_WEIGHT_MODE) {
|
||||
keyframeValue.tangentWeightMode = dataView.getUint8(currentOffset);
|
||||
currentOffset += TANGENT_WEIGHT_MODE_BYTES;
|
||||
}
|
||||
|
||||
if (flags & KeyframeValueFlagMask.LEFT_TANGENT) {
|
||||
keyframeValue.leftTangent = dataView.getFloat32(currentOffset, true);
|
||||
currentOffset += LEFT_TANGENT_BYTES;
|
||||
}
|
||||
|
||||
if (flags & KeyframeValueFlagMask.LEFT_TANGENT_WEIGHT) {
|
||||
keyframeValue.leftTangentWeight = dataView.getFloat32(currentOffset, true);
|
||||
currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
|
||||
}
|
||||
|
||||
if (flags & KeyframeValueFlagMask.RIGHT_TANGENT) {
|
||||
keyframeValue.rightTangent = dataView.getFloat32(currentOffset, true);
|
||||
currentOffset += RIGHT_TANGENT_BYTES;
|
||||
}
|
||||
|
||||
if (flags & KeyframeValueFlagMask.RIGHT_TANGENT_WEIGHT) {
|
||||
keyframeValue.rightTangentWeight = dataView.getFloat32(currentOffset, true);
|
||||
currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
|
||||
}
|
||||
|
||||
const easingMethod = ((flags & FLAG_EASING_METHOD_MASK) >> FLAGS_EASING_METHOD_BITS_START) as EasingMethod;
|
||||
keyframeValue.easingMethod = easingMethod;
|
||||
|
||||
return currentOffset;
|
||||
}
|
||||
|
||||
function wrapRepeat (time: number, prevTime: number, nextTime: number) {
|
||||
return prevTime + repeat(time - prevTime, nextTime - prevTime);
|
||||
}
|
||||
|
||||
function wrapPingPong (time: number, prevTime: number, nextTime: number) {
|
||||
return prevTime + pingPong(time - prevTime, nextTime - prevTime);
|
||||
}
|
||||
|
||||
function linearTrend (
|
||||
prevTime: number,
|
||||
prevValue: number,
|
||||
nextTime: number,
|
||||
nextValue: number,
|
||||
time: number,
|
||||
) {
|
||||
const slope = (nextValue - prevValue) / (nextTime - prevTime);
|
||||
return prevValue + (time - prevTime) * slope;
|
||||
}
|
||||
|
||||
function evalBetweenTwoKeyFrames (
|
||||
prevTime: number,
|
||||
prevValue: RealKeyframeValue,
|
||||
nextTime: number,
|
||||
nextValue: RealKeyframeValue,
|
||||
ratio: number,
|
||||
) {
|
||||
const dt = nextTime - prevTime;
|
||||
switch (prevValue.interpolationMode) {
|
||||
default:
|
||||
case RealInterpolationMode.CONSTANT:
|
||||
return prevValue.value;
|
||||
case RealInterpolationMode.LINEAR: {
|
||||
const transformedRatio = prevValue.easingMethod === EasingMethod.LINEAR
|
||||
? ratio
|
||||
: getEasingFn(prevValue.easingMethod)(ratio);
|
||||
return lerp(prevValue.value, nextValue.value, transformedRatio);
|
||||
}
|
||||
case RealInterpolationMode.CUBIC: {
|
||||
const ONE_THIRD = 1.0 / 3.0;
|
||||
const {
|
||||
rightTangent: prevTangent,
|
||||
rightTangentWeight: prevTangentWeightSpecified,
|
||||
} = prevValue;
|
||||
const prevTangentWeightEnabled = isRightTangentWeightEnabled(prevValue.tangentWeightMode);
|
||||
const {
|
||||
leftTangent: nextTangent,
|
||||
leftTangentWeight: nextTangentWeightSpecified,
|
||||
} = nextValue;
|
||||
const nextTangentWeightEnabled = isLeftTangentWeightEnabled(nextValue.tangentWeightMode);
|
||||
|
||||
if (!prevTangentWeightEnabled && !nextTangentWeightEnabled) {
|
||||
// Optimize for the case when both x components of tangents are 1.
|
||||
// See below.
|
||||
const p1 = prevValue.value + ONE_THIRD * prevTangent * dt;
|
||||
const p2 = nextValue.value - ONE_THIRD * nextTangent * dt;
|
||||
return bezierInterpolate(prevValue.value, p1, p2, nextValue.value, ratio);
|
||||
} else {
|
||||
let prevTangentWeight = 0.0;
|
||||
if (prevTangentWeightEnabled) {
|
||||
prevTangentWeight = prevTangentWeightSpecified;
|
||||
} else {
|
||||
const x = dt;
|
||||
const y = dt * prevTangent;
|
||||
prevTangentWeight = Math.sqrt(x * x + y * y) * ONE_THIRD;
|
||||
}
|
||||
const angle0 = Math.atan(prevTangent);
|
||||
const tx0 = Math.cos(angle0) * prevTangentWeight + prevTime;
|
||||
const ty0 = Math.sin(angle0) * prevTangentWeight + prevValue.value;
|
||||
|
||||
let nextTangentWeight = 0.0;
|
||||
if (nextTangentWeightEnabled) {
|
||||
nextTangentWeight = nextTangentWeightSpecified;
|
||||
} else {
|
||||
const x = dt;
|
||||
const y = dt * nextTangent;
|
||||
nextTangentWeight = Math.sqrt(x * x + y * y) * ONE_THIRD;
|
||||
}
|
||||
const angle1 = Math.atan(nextTangent);
|
||||
const tx1 = -Math.cos(angle1) * nextTangentWeight + nextTime;
|
||||
const ty1 = -Math.sin(angle1) * nextTangentWeight + nextValue.value;
|
||||
|
||||
const dx = dt;
|
||||
// Hermite to Bezier
|
||||
const u0x = (tx0 - prevTime) / dx;
|
||||
const u1x = (tx1 - prevTime) / dx;
|
||||
const u0y = ty0;
|
||||
const u1y = ty1;
|
||||
// Converts from Bernstein Basis to Power Basis.
|
||||
// Formula: [1, 0, 0, 0; -3, 3, 0, 0; 3, -6, 3, 0; -1, 3, -3, 1] * [p_0; p_1; p_2; p_3]
|
||||
// --------------------------------------
|
||||
// | Basis | Coeff
|
||||
// | t^3 | 3 * p_1 - p_0 - 3 * p_2 + p_3
|
||||
// | t^2 | 3 * p_0 - 6 * p_1 + 3 * p_2
|
||||
// | t^1 | 3 * p_1 - 3 * p_0
|
||||
// | t^0 | p_0
|
||||
// --------------------------------------
|
||||
// where: p_0 = 0, p_1 = u0x, p_2 = u1x, p_3 = 1
|
||||
// Especially, when both tangents are 1, we will have u0x = 1/3 and u1x = 2/3
|
||||
// and then: ratio = t, eg. the ratios are
|
||||
// 1-1 corresponding to param t. That's why we can do optimization like above.
|
||||
const coeff0 = 0.0; // 0
|
||||
const coeff1 = 3.0 * u0x; // 1
|
||||
const coeff2 = 3.0 * u1x - 6.0 * u0x; // -1
|
||||
const coeff3 = 3.0 * (u0x - u1x) + 1.0; // 1
|
||||
// Solves the param t from equation X(t) = ratio.
|
||||
const solutions = [0.0, 0.0, 0.0] as [number, number, number];
|
||||
const nSolutions = solveCubic(coeff0 - ratio, coeff1, coeff2, coeff3, solutions);
|
||||
const param = getParamFromCubicSolution(solutions, nSolutions, ratio);
|
||||
// Solves Y.
|
||||
const y = bezierInterpolate(prevValue.value, u0y, u1y, nextValue.value, param);
|
||||
return y;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isLeftTangentWeightEnabled (tangentWeightMode: TangentWeightMode) {
|
||||
return (tangentWeightMode & TangentWeightMode.LEFT) !== 0;
|
||||
}
|
||||
|
||||
function isRightTangentWeightEnabled (tangentWeightMode: TangentWeightMode) {
|
||||
return (tangentWeightMode & TangentWeightMode.RIGHT) !== 0;
|
||||
}
|
||||
|
||||
function bezierInterpolate (p0: number, p1: number, p2: number, p3: number, t: number) {
|
||||
const u = 1 - t;
|
||||
const coeff0 = u * u * u;
|
||||
const coeff1 = 3 * u * u * t;
|
||||
const coeff2 = 3 * u * t * t;
|
||||
const coeff3 = t * t * t;
|
||||
return coeff0 * p0 + coeff1 * p1 + coeff2 * p2 + coeff3 * p3;
|
||||
}
|
||||
|
||||
function getParamFromCubicSolution (solutions: readonly [number, number, number], solutionsCount: number, x: number) {
|
||||
let param = x;
|
||||
if (solutionsCount === 1) {
|
||||
param = solutions[0];
|
||||
} else {
|
||||
param = -Infinity;
|
||||
for (let iSolution = 0; iSolution < solutionsCount; ++iSolution) {
|
||||
const solution = solutions[iSolution];
|
||||
if (solution >= 0.0 && solution <= 1.0) {
|
||||
if (solution > param) {
|
||||
param = solution;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (param === -Infinity) {
|
||||
param = 0.0;
|
||||
}
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
||||
type EasingMethodFn = (k: number) => number;
|
||||
|
||||
const easingMethodFnMap: Record<EasingMethod, EasingMethodFn> = {
|
||||
[EasingMethod.CONSTANT]: easing.constant,
|
||||
[EasingMethod.LINEAR]: easing.linear,
|
||||
|
||||
[EasingMethod.QUAD_IN]: easing.quadIn,
|
||||
[EasingMethod.QUAD_OUT]: easing.quadOut,
|
||||
[EasingMethod.QUAD_IN_OUT]: easing.quadInOut,
|
||||
[EasingMethod.QUAD_OUT_IN]: easing.quadOutIn,
|
||||
[EasingMethod.CUBIC_IN]: easing.cubicIn,
|
||||
[EasingMethod.CUBIC_OUT]: easing.cubicOut,
|
||||
[EasingMethod.CUBIC_IN_OUT]: easing.cubicInOut,
|
||||
[EasingMethod.CUBIC_OUT_IN]: easing.cubicOutIn,
|
||||
[EasingMethod.QUART_IN]: easing.quartIn,
|
||||
[EasingMethod.QUART_OUT]: easing.quartOut,
|
||||
[EasingMethod.QUART_IN_OUT]: easing.quartInOut,
|
||||
[EasingMethod.QUART_OUT_IN]: easing.quartOutIn,
|
||||
[EasingMethod.QUINT_IN]: easing.quintIn,
|
||||
[EasingMethod.QUINT_OUT]: easing.quintOut,
|
||||
[EasingMethod.QUINT_IN_OUT]: easing.quintInOut,
|
||||
[EasingMethod.QUINT_OUT_IN]: easing.quintOutIn,
|
||||
[EasingMethod.SINE_IN]: easing.sineIn,
|
||||
[EasingMethod.SINE_OUT]: easing.sineOut,
|
||||
[EasingMethod.SINE_IN_OUT]: easing.sineInOut,
|
||||
[EasingMethod.SINE_OUT_IN]: easing.sineOutIn,
|
||||
[EasingMethod.EXPO_IN]: easing.expoIn,
|
||||
[EasingMethod.EXPO_OUT]: easing.expoOut,
|
||||
[EasingMethod.EXPO_IN_OUT]: easing.expoInOut,
|
||||
[EasingMethod.EXPO_OUT_IN]: easing.expoOutIn,
|
||||
[EasingMethod.CIRC_IN]: easing.circIn,
|
||||
[EasingMethod.CIRC_OUT]: easing.circOut,
|
||||
[EasingMethod.CIRC_IN_OUT]: easing.circInOut,
|
||||
[EasingMethod.CIRC_OUT_IN]: easing.circOutIn,
|
||||
[EasingMethod.ELASTIC_IN]: easing.elasticIn,
|
||||
[EasingMethod.ELASTIC_OUT]: easing.elasticOut,
|
||||
[EasingMethod.ELASTIC_IN_OUT]: easing.elasticInOut,
|
||||
[EasingMethod.ELASTIC_OUT_IN]: easing.elasticOutIn,
|
||||
[EasingMethod.BACK_IN]: easing.backIn,
|
||||
[EasingMethod.BACK_OUT]: easing.backOut,
|
||||
[EasingMethod.BACK_IN_OUT]: easing.backInOut,
|
||||
[EasingMethod.BACK_OUT_IN]: easing.backOutIn,
|
||||
[EasingMethod.BOUNCE_IN]: easing.bounceIn,
|
||||
[EasingMethod.BOUNCE_OUT]: easing.bounceOut,
|
||||
[EasingMethod.BOUNCE_IN_OUT]: easing.bounceInOut,
|
||||
[EasingMethod.BOUNCE_OUT_IN]: easing.bounceOutIn,
|
||||
[EasingMethod.SMOOTH]: easing.smooth,
|
||||
[EasingMethod.FADE]: easing.fade,
|
||||
};
|
||||
|
||||
function getEasingFn (easingMethod: EasingMethod): EasingMethodFn {
|
||||
assertIsTrue(easingMethod in easingMethodFnMap);
|
||||
return easingMethodFnMap[easingMethod];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export {
|
||||
RealCurve,
|
||||
RealInterpolationMode,
|
||||
ExtrapolationMode,
|
||||
TangentWeightMode,
|
||||
} from './curve';
|
||||
|
||||
export type {
|
||||
RealKeyframeValue,
|
||||
} from './curve';
|
||||
|
||||
export {
|
||||
QuatCurve,
|
||||
QuatInterpolationMode,
|
||||
} from './quat-curve';
|
||||
|
||||
export type {
|
||||
QuatKeyframeValue,
|
||||
} from './quat-curve';
|
||||
|
||||
export {
|
||||
ObjectCurve,
|
||||
} from './object-curve';
|
||||
|
||||
export type {
|
||||
ObjectCurveKeyframe,
|
||||
} from './object-curve';
|
||||
@@ -0,0 +1,216 @@
|
||||
import { binarySearchEpsilon } from '../algorithm/binary-search';
|
||||
import { ccclass, serializable } from '../data/decorators';
|
||||
import { assertIsTrue } from '../data/utils/asserts';
|
||||
import { approx } from '../math';
|
||||
import type { CurveBase } from './curve-base';
|
||||
|
||||
type KeyFrame<TKeyframeValue> = [number, TKeyframeValue];
|
||||
|
||||
/**
|
||||
* Curve.
|
||||
*/
|
||||
@ccclass('cc.KeyframeCurve')
|
||||
export class KeyframeCurve<TKeyframeValue> implements CurveBase, Iterable<KeyFrame<TKeyframeValue>> {
|
||||
/**
|
||||
* Gets the count of keyframes.
|
||||
*/
|
||||
get keyFramesCount () {
|
||||
return this._times.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the minimal time.
|
||||
*/
|
||||
get rangeMin () {
|
||||
return this._times[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the maximum time.
|
||||
*/
|
||||
get rangeMax () {
|
||||
return this._times[this._values.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator to keyframe pairs.
|
||||
*/
|
||||
[Symbol.iterator] () {
|
||||
let index = 0;
|
||||
return {
|
||||
next: (): IteratorResult<KeyFrame<TKeyframeValue>> => {
|
||||
if (index >= this._times.length) {
|
||||
return {
|
||||
done: true,
|
||||
value: undefined,
|
||||
};
|
||||
} else {
|
||||
const value: KeyFrame<TKeyframeValue> = [this._times[index], this._values[index]];
|
||||
++index;
|
||||
return {
|
||||
done: false,
|
||||
value,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator to keyframe pairs.
|
||||
*/
|
||||
public keyframes (): Iterable<KeyFrame<TKeyframeValue>> {
|
||||
return this;
|
||||
}
|
||||
|
||||
public times (): Iterable<number> {
|
||||
return this._times;
|
||||
}
|
||||
|
||||
public values (): Iterable<TKeyframeValue> {
|
||||
return this._values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the time of specified keyframe.
|
||||
* @param index Index to the keyframe.
|
||||
* @returns The keyframe 's time.
|
||||
*/
|
||||
public getKeyframeTime (index: number): number {
|
||||
return this._times[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of specified keyframe.
|
||||
* @param index Index to the keyframe.
|
||||
* @returns The keyframe 's value.
|
||||
*/
|
||||
public getKeyframeValue (index: number): TKeyframeValue {
|
||||
return this._values[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a keyframe into this curve.
|
||||
* @param time Time of the keyframe.
|
||||
* @param value Value of the keyframe.
|
||||
* @returns The index to the new keyframe.
|
||||
*/
|
||||
public addKeyFrame (time: number, keyframeValue: TKeyframeValue): number {
|
||||
return this._insertNewKeyframe(time, keyframeValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a keyframe from this curve.
|
||||
* @param index Index to the keyframe.
|
||||
*/
|
||||
public removeKeyframe (index: number) {
|
||||
this._times.splice(index, 1);
|
||||
this._values.splice(index, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for the keyframe at specified time.
|
||||
* @param time Time to search.
|
||||
* @returns Index to the keyframe or negative number if not found.
|
||||
*/
|
||||
public indexOfKeyframe (time: number) {
|
||||
return binarySearchEpsilon(this._times, time);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the time of a keyframe.
|
||||
* @param index Index to the keyframe.
|
||||
* @param time New time.
|
||||
*/
|
||||
public updateTime (index: number, time: number) {
|
||||
const value = this._values[index];
|
||||
this.removeKeyframe(index);
|
||||
this._insertNewKeyframe(time, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param keyframes An iterable to keyframes. The keyframes should be sorted by their time.
|
||||
*/
|
||||
public assignSorted (keyframes: Iterable<[number, TKeyframeValue]>): void;
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param times Times array. Should be sorted.
|
||||
* @param values Values array. Corresponding to each time in `times`.
|
||||
*/
|
||||
public assignSorted (times: readonly number[], values: TKeyframeValue[]): void;
|
||||
|
||||
public assignSorted (times: Iterable<[number, TKeyframeValue]> | readonly number[], values?: readonly TKeyframeValue[]) {
|
||||
if (values !== undefined) {
|
||||
assertIsTrue(Array.isArray(times));
|
||||
this.setKeyframes(
|
||||
times.slice(),
|
||||
values.slice(),
|
||||
);
|
||||
} else {
|
||||
const keyframes = Array.from(times as Iterable<[number, TKeyframeValue]>);
|
||||
this.setKeyframes(
|
||||
keyframes.map(([time]) => time),
|
||||
keyframes.map(([, value]) => value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all key frames.
|
||||
*/
|
||||
public clear () {
|
||||
this._times.length = 0;
|
||||
this._values.length = 0;
|
||||
}
|
||||
|
||||
protected searchKeyframe (time: number) {
|
||||
return binarySearchEpsilon(this._times, time);
|
||||
}
|
||||
|
||||
protected setKeyframes (times: number[], values: TKeyframeValue[]) {
|
||||
assertIsTrue(times.length === values.length);
|
||||
assertIsTrue(isSorted(times));
|
||||
this._times = times;
|
||||
this._values = values;
|
||||
}
|
||||
|
||||
private _insertNewKeyframe (time: number, value: TKeyframeValue) {
|
||||
const times = this._times;
|
||||
const values = this._values;
|
||||
const nFrames = times.length;
|
||||
|
||||
const index = binarySearchEpsilon(times, time);
|
||||
if (index >= 0) {
|
||||
return index;
|
||||
}
|
||||
const iNext = ~index;
|
||||
if (iNext === 0) {
|
||||
times.unshift(time);
|
||||
values.unshift(value);
|
||||
} else if (iNext === nFrames) {
|
||||
times.push(time);
|
||||
values.push(value);
|
||||
} else {
|
||||
assertIsTrue(nFrames > 1);
|
||||
times.splice(iNext - 1, 0, time);
|
||||
values.splice(iNext - 1, 0, value);
|
||||
}
|
||||
return iNext;
|
||||
}
|
||||
|
||||
// Times are always sorted and 1-1 correspond to values.
|
||||
@serializable
|
||||
protected _times: number[] = [];
|
||||
|
||||
@serializable
|
||||
protected _values: TKeyframeValue[] = [];
|
||||
}
|
||||
|
||||
function isSorted (values: number[]) {
|
||||
return values.every(
|
||||
(value, index, array) => index === 0
|
||||
|| value > array[index - 1] || approx(value, array[index - 1], 1e-6),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
import { binarySearchEpsilon } from '../algorithm/binary-search';
|
||||
import { ccclass, serializable } from '../data/decorators';
|
||||
import { assertIsTrue } from '../data/utils/asserts';
|
||||
import { approx, IQuatLike, lerp, Quat } from '../math';
|
||||
import { RealKeyframeValue, ExtrapolationMode, RealCurve } from './curve';
|
||||
import { QuatCurve, QuatInterpolationMode } from './quat-curve';
|
||||
import { RealInterpolationMode } from './real-curve-param';
|
||||
|
||||
const DEFAULT_EPSILON = 1e-5;
|
||||
|
||||
const DefaultFloatArray = Float32Array;
|
||||
|
||||
type DefaultFloatArray = InstanceType<typeof DefaultFloatArray>;
|
||||
|
||||
/**
|
||||
* Considering most of model animations are baked and most of its curves share same times,
|
||||
* we do not have to do time searching for many times.
|
||||
*/
|
||||
@ccclass('cc.KeySharedCurves')
|
||||
class KeysSharedCurves {
|
||||
/**
|
||||
* Only for internal(serialization) usage.
|
||||
*/
|
||||
constructor ();
|
||||
|
||||
constructor (times: number[]);
|
||||
|
||||
constructor (times?: number[]) {
|
||||
if (!times) {
|
||||
this._times = new DefaultFloatArray();
|
||||
return;
|
||||
}
|
||||
|
||||
const nKeyframes = times.length;
|
||||
|
||||
this._keyframesCount = nKeyframes;
|
||||
this._times = DefaultFloatArray.from(times);
|
||||
|
||||
if (nKeyframes > 1) {
|
||||
const EPSILON = 1e-6;
|
||||
let lastDiff = 0.0;
|
||||
let mayBeOptimized = false;
|
||||
for (let iFrame = 1; iFrame < nKeyframes; iFrame++) {
|
||||
const curDiff = times[iFrame] - times[iFrame - 1];
|
||||
if (iFrame === 1) {
|
||||
lastDiff = curDiff;
|
||||
} else if (Math.abs(curDiff - lastDiff) > EPSILON) {
|
||||
mayBeOptimized = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mayBeOptimized) {
|
||||
this._optimized = true;
|
||||
this._times = new DefaultFloatArray([this._times[0], this._times[1]]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get keyframesCount () {
|
||||
return this._keyframesCount;
|
||||
}
|
||||
|
||||
protected matchTimes (times: readonly number[], EPSILON = DEFAULT_EPSILON) {
|
||||
if (this._optimized) {
|
||||
const firstTime = this._times[0];
|
||||
const diff = this._times[1] - firstTime;
|
||||
return times.every(
|
||||
(t, iKeyframe) => approx(t, firstTime + diff * iKeyframe, EPSILON),
|
||||
);
|
||||
} else {
|
||||
return times.every(
|
||||
(t, iKeyframe) => approx(t, this._times[iKeyframe], EPSILON),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
protected getFirstTime () {
|
||||
return this._times[0];
|
||||
}
|
||||
|
||||
protected getLastTime () {
|
||||
if (!this._optimized) {
|
||||
return this._times[this._times.length - 1];
|
||||
} else {
|
||||
const diff = this._times[1] - this._times[0];
|
||||
return this._times[0] + diff * this._keyframesCount;
|
||||
}
|
||||
}
|
||||
|
||||
protected calculateLocation (time: number, out: TimeLocation) {
|
||||
const { _times: times, _optimized: optimized, keyframesCount: nKeyframes } = this;
|
||||
if (optimized) {
|
||||
const firstTime = times[0];
|
||||
const diff = times[1] - firstTime;
|
||||
const div = (time - firstTime) / diff;
|
||||
const previous = Math.floor(div);
|
||||
out.previous = previous;
|
||||
out.ratio = div - previous;
|
||||
} else {
|
||||
const index = binarySearchEpsilon(times, time);
|
||||
if (index >= 0) {
|
||||
// Exactly matched
|
||||
out.previous = index;
|
||||
out.ratio = 0.0;
|
||||
} else {
|
||||
const iNext = ~index;
|
||||
assertIsTrue(iNext >= 1 && iNext < nKeyframes);
|
||||
const iPrev = iNext - 1;
|
||||
const prevTime = times[iPrev];
|
||||
out.ratio = (time - prevTime) / (times[iNext] - prevTime);
|
||||
out.previous = iPrev;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _times: DefaultFloatArray;
|
||||
|
||||
@serializable
|
||||
private _optimized = false;
|
||||
|
||||
@serializable
|
||||
private _keyframesCount = 0;
|
||||
}
|
||||
|
||||
interface TimeLocation {
|
||||
previous: number;
|
||||
ratio: number;
|
||||
}
|
||||
|
||||
const globalLocation: TimeLocation = {
|
||||
previous: 0,
|
||||
ratio: 0,
|
||||
};
|
||||
|
||||
@ccclass('cc.KeySharedRealCurves')
|
||||
export class KeySharedRealCurves extends KeysSharedCurves {
|
||||
public static allowedForCurve (curve: RealCurve) {
|
||||
return curve.postExtrapolation === ExtrapolationMode.CLAMP
|
||||
&& curve.preExtrapolation === ExtrapolationMode.CLAMP
|
||||
&& Array.from(curve.values()).every((value) => value.interpolationMode === RealInterpolationMode.LINEAR);
|
||||
}
|
||||
|
||||
get curveCount () {
|
||||
return this._curves.length;
|
||||
}
|
||||
|
||||
public matchCurve (curve: RealCurve, EPSILON = DEFAULT_EPSILON) {
|
||||
if (curve.keyFramesCount !== this.keyframesCount) {
|
||||
return false;
|
||||
}
|
||||
const times = Array.from(curve.times());
|
||||
return super.matchTimes(times, EPSILON);
|
||||
}
|
||||
|
||||
public addCurve (curve: RealCurve) {
|
||||
assertIsTrue(curve.keyFramesCount === this.keyframesCount);
|
||||
this._curves.push({
|
||||
values: DefaultFloatArray.from(Array.from(curve.values()).map(({ value }) => value)),
|
||||
});
|
||||
}
|
||||
|
||||
public evaluate (time: number, values: number[]) {
|
||||
const {
|
||||
_curves: curves,
|
||||
keyframesCount: nKeyframes,
|
||||
} = this;
|
||||
|
||||
const nCurves = curves.length;
|
||||
assertIsTrue(values.length === nCurves);
|
||||
|
||||
if (nKeyframes === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstTime = super.getFirstTime();
|
||||
if (time <= firstTime) {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
values[iCurve] = this._curves[iCurve].values[0];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const lastTime = super.getLastTime();
|
||||
if (time >= lastTime) {
|
||||
const iLastFrame = nKeyframes - 1;
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
values[iCurve] = this._curves[iCurve].values[iLastFrame];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { previous, ratio } = super.calculateLocation(time, globalLocation);
|
||||
if (ratio !== 0.0) {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
const { values: curveValues } = this._curves[iCurve];
|
||||
values[iCurve] = lerp(curveValues[previous], curveValues[previous + 1], ratio);
|
||||
}
|
||||
} else {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
const { values: curveValues } = this._curves[iCurve];
|
||||
values[iCurve] = curveValues[previous];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _curves: {
|
||||
values: DefaultFloatArray;
|
||||
}[] = [];
|
||||
}
|
||||
|
||||
const cacheQuat1 = new Quat();
|
||||
const cacheQuat2 = new Quat();
|
||||
|
||||
@ccclass('cc.KeySharedQuatCurves')
|
||||
export class KeySharedQuatCurves extends KeysSharedCurves {
|
||||
public static allowedForCurve (curve: QuatCurve) {
|
||||
return curve.postExtrapolation === ExtrapolationMode.CLAMP
|
||||
&& curve.preExtrapolation === ExtrapolationMode.CLAMP
|
||||
&& Array.from(curve.values()).every((value) => value.interpolationMode === QuatInterpolationMode.SLERP);
|
||||
}
|
||||
|
||||
get curveCount () {
|
||||
return this._curves.length;
|
||||
}
|
||||
|
||||
public matchCurve (curve: QuatCurve, EPSILON = 1e-5) {
|
||||
if (curve.keyFramesCount !== this.keyframesCount) {
|
||||
return false;
|
||||
}
|
||||
const times = Array.from(curve.times());
|
||||
return super.matchTimes(times, EPSILON);
|
||||
}
|
||||
|
||||
public addCurve (curve: QuatCurve) {
|
||||
assertIsTrue(curve.keyFramesCount === this.keyframesCount);
|
||||
const values = new DefaultFloatArray(curve.keyFramesCount * 4);
|
||||
const nKeyframes = curve.keyFramesCount;
|
||||
for (let iKeyframe = 0; iKeyframe < nKeyframes; ++iKeyframe) {
|
||||
Quat.toArray(values, curve.getKeyframeValue(iKeyframe).value, 4 * iKeyframe);
|
||||
}
|
||||
this._curves.push({
|
||||
values,
|
||||
});
|
||||
}
|
||||
|
||||
public evaluate (time: number, values: IQuatLike[]) {
|
||||
const {
|
||||
_curves: curves,
|
||||
keyframesCount: nKeyframes,
|
||||
} = this;
|
||||
|
||||
const nCurves = curves.length;
|
||||
assertIsTrue(values.length === nCurves);
|
||||
|
||||
if (nKeyframes === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstTime = super.getFirstTime();
|
||||
if (time <= firstTime) {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
Quat.fromArray(values[iCurve], this._curves[iCurve].values, 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const lastTime = super.getLastTime();
|
||||
if (time >= lastTime) {
|
||||
const iLastFrame = nKeyframes - 1;
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
Quat.fromArray(values[iCurve], this._curves[iCurve].values, iLastFrame * 4);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const { previous, ratio } = super.calculateLocation(time, globalLocation);
|
||||
if (ratio !== 0.0) {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
const { values: curveValues } = this._curves[iCurve];
|
||||
const q1 = Quat.fromArray(cacheQuat1, curveValues, previous * 4);
|
||||
const q2 = Quat.fromArray(cacheQuat2, curveValues, (previous + 1) * 4);
|
||||
Quat.slerp(values[iCurve], q1, q2, ratio);
|
||||
}
|
||||
} else {
|
||||
for (let iCurve = 0; iCurve < nCurves; ++iCurve) {
|
||||
Quat.fromArray(values[iCurve], this._curves[iCurve].values, previous * 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@serializable
|
||||
private _curves: {
|
||||
values: DefaultFloatArray;
|
||||
}[] = [];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { ccclass } from '../data/decorators';
|
||||
import { clamp } from '../math';
|
||||
import { KeyframeCurve } from './keyframe-curve';
|
||||
|
||||
export type ObjectCurveKeyframe<T> = T;
|
||||
|
||||
@ccclass('cc.ObjectCurve')
|
||||
export class ObjectCurve<T> extends KeyframeCurve<ObjectCurveKeyframe<T>> {
|
||||
public evaluate (time: number) {
|
||||
const iSearch = this.searchKeyframe(time);
|
||||
if (iSearch >= 0) {
|
||||
return this._values[iSearch];
|
||||
}
|
||||
const iPrev = clamp((~iSearch) - 1, 0, this._values.length - 1);
|
||||
return this._values[iPrev];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { assertIsTrue } from '../data/utils/asserts';
|
||||
import { IQuatLike, pingPong, Quat, repeat } from '../math';
|
||||
import { KeyframeCurve } from './keyframe-curve';
|
||||
import { ExtrapolationMode } from './curve';
|
||||
import { binarySearchEpsilon } from '../algorithm/binary-search';
|
||||
import { ccclass, serializable, uniquelyReferenced } from '../data/decorators';
|
||||
import { deserializeTag, SerializationContext, SerializationInput, SerializationOutput, serializeTag } from '../data';
|
||||
import { DeserializationContext } from '../data/custom-serializable';
|
||||
|
||||
/**
|
||||
* View to a quaternion frame value.
|
||||
* Note, the view may be invalidated due to keyframe change/add/remove.
|
||||
*/
|
||||
@ccclass('cc.QuatKeyframeValue')
|
||||
@uniquelyReferenced
|
||||
class QuatKeyframeValue {
|
||||
/**
|
||||
* Interpolation method used for this keyframe.
|
||||
*/
|
||||
@serializable
|
||||
public interpolationMode: QuatInterpolationMode = QuatInterpolationMode.SLERP;
|
||||
|
||||
/**
|
||||
* Value of the keyframe.
|
||||
*/
|
||||
@serializable
|
||||
public value: IQuatLike = Quat.clone(Quat.IDENTITY);
|
||||
|
||||
constructor ({
|
||||
value,
|
||||
interpolationMode,
|
||||
}: Partial<QuatKeyframeValue> = {}) {
|
||||
// TODO: shall we normalize it?
|
||||
this.value = value ? Quat.clone(value) : this.value;
|
||||
this.interpolationMode = interpolationMode ?? this.interpolationMode;
|
||||
}
|
||||
}
|
||||
|
||||
export type { QuatKeyframeValue };
|
||||
|
||||
/**
|
||||
* The parameter describing a real keyframe value.
|
||||
* In the case of partial keyframe value,
|
||||
* each component of the keyframe value is taken from the parameter.
|
||||
* For unspecified components, default values are taken:
|
||||
* - Interpolation mode: slerp
|
||||
* - Value: Identity quaternion
|
||||
*/
|
||||
type QuatKeyframeValueParameters = Partial<QuatKeyframeValue>;
|
||||
|
||||
function createQuatKeyframeValue (params: QuatKeyframeValueParameters) {
|
||||
return new QuatKeyframeValue(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* The method used for interpolation between values of a keyframe and its next keyframe.
|
||||
*/
|
||||
export enum QuatInterpolationMode {
|
||||
/**
|
||||
* Perform spherical linear interpolation.
|
||||
*/
|
||||
SLERP,
|
||||
|
||||
/**
|
||||
* Always use the value from this keyframe.
|
||||
*/
|
||||
CONSTANT,
|
||||
|
||||
// #region TODO: Spherical Quadrangle Interpolation
|
||||
/**
|
||||
* TODO: Spherical Quadrangle Interpolation
|
||||
* - https://theory.org/software/qfa/writeup/node12.html
|
||||
* - http://digitalrune.github.io/DigitalRune-Documentation/html/58f74cca-83a3-5e9e-6d5d-63b09a723f90.htm
|
||||
*/
|
||||
// SQUAD,
|
||||
// #endregion
|
||||
}
|
||||
|
||||
/**
|
||||
* Quaternion curve.
|
||||
*/
|
||||
@ccclass('cc.QuatCurve')
|
||||
export class QuatCurve extends KeyframeCurve<QuatKeyframeValue> {
|
||||
/**
|
||||
* Gets or sets the operation should be taken
|
||||
* if input time is less than the time of first keyframe when evaluating this curve.
|
||||
* Defaults to `ExtrapolationMode.CLAMP`.
|
||||
*/
|
||||
@serializable
|
||||
public preExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP;
|
||||
|
||||
/**
|
||||
* Gets or sets the operation should be taken
|
||||
* if input time is greater than the time of last keyframe when evaluating this curve.
|
||||
* Defaults to `ExtrapolationMode.CLAMP`.
|
||||
*/
|
||||
@serializable
|
||||
public postExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP;
|
||||
|
||||
/**
|
||||
* Evaluates this curve at specified time.
|
||||
* @param time Input time.
|
||||
* @returns Result value.
|
||||
*/
|
||||
public evaluate (time: number, quat?: Quat): Quat {
|
||||
quat ??= new Quat();
|
||||
|
||||
const {
|
||||
_times: times,
|
||||
_values: values,
|
||||
postExtrapolation,
|
||||
preExtrapolation,
|
||||
} = this;
|
||||
const nFrames = times.length;
|
||||
|
||||
if (nFrames === 0) {
|
||||
return quat;
|
||||
}
|
||||
|
||||
const firstTime = times[0];
|
||||
const lastTime = times[nFrames - 1];
|
||||
if (time < firstTime) {
|
||||
// Underflow
|
||||
const preValue = values[0];
|
||||
switch (preExtrapolation) {
|
||||
case ExtrapolationMode.LOOP:
|
||||
time = firstTime + repeat(time - firstTime, lastTime - firstTime);
|
||||
break;
|
||||
case ExtrapolationMode.PING_PONG:
|
||||
time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
|
||||
break;
|
||||
case ExtrapolationMode.CLAMP:
|
||||
default:
|
||||
return Quat.copy(quat, preValue.value);
|
||||
}
|
||||
} else if (time > lastTime) {
|
||||
// Overflow
|
||||
const preValue = values[nFrames - 1];
|
||||
switch (postExtrapolation) {
|
||||
case ExtrapolationMode.LOOP:
|
||||
time = firstTime + repeat(time - firstTime, lastTime - firstTime);
|
||||
break;
|
||||
case ExtrapolationMode.PING_PONG:
|
||||
time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
|
||||
break;
|
||||
case ExtrapolationMode.CLAMP:
|
||||
default:
|
||||
return Quat.copy(quat, preValue.value);
|
||||
}
|
||||
}
|
||||
|
||||
const index = binarySearchEpsilon(times, time);
|
||||
if (index >= 0) {
|
||||
return Quat.copy(quat, values[index].value);
|
||||
}
|
||||
|
||||
const iNext = ~index;
|
||||
assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
|
||||
|
||||
const iPre = iNext - 1;
|
||||
const preTime = times[iPre];
|
||||
const preValue = values[iPre];
|
||||
const nextTime = times[iNext];
|
||||
const nextValue = values[iNext];
|
||||
assertIsTrue(nextTime > time && time > preTime);
|
||||
const dt = nextTime - preTime;
|
||||
|
||||
const ratio = (time - preTime) / dt;
|
||||
switch (preValue.interpolationMode) {
|
||||
default:
|
||||
case QuatInterpolationMode.CONSTANT:
|
||||
return Quat.copy(quat, preValue.value);
|
||||
case QuatInterpolationMode.SLERP:
|
||||
return Quat.slerp(quat, preValue.value, nextValue.value, ratio);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a keyframe into this curve.
|
||||
* @param time Time of the keyframe.
|
||||
* @param value Value of the keyframe.
|
||||
* @returns The index to the new keyframe.
|
||||
*/
|
||||
public addKeyFrame (time: number, value: QuatKeyframeValueParameters): number {
|
||||
const keyframeValue = new QuatKeyframeValue(value);
|
||||
return super.addKeyFrame(time, keyframeValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param keyframes An iterable to keyframes. The keyframes should be sorted by their time.
|
||||
*/
|
||||
public assignSorted (keyframes: Iterable<[number, QuatKeyframeValueParameters]>): void;
|
||||
|
||||
/**
|
||||
* Assigns all keyframes.
|
||||
* @param times Times array. Should be sorted.
|
||||
* @param values Values array. Corresponding to each time in `times`.
|
||||
*/
|
||||
public assignSorted (times: readonly number[], values: QuatKeyframeValueParameters[]): void;
|
||||
|
||||
public assignSorted (
|
||||
times: Iterable<[number, QuatKeyframeValueParameters]> | readonly number[],
|
||||
values?: readonly QuatKeyframeValueParameters[],
|
||||
) {
|
||||
if (values !== undefined) {
|
||||
assertIsTrue(Array.isArray(times));
|
||||
this.setKeyframes(
|
||||
times.slice(),
|
||||
values.map((value) => createQuatKeyframeValue(value)),
|
||||
);
|
||||
} else {
|
||||
const keyframes = Array.from(times as Iterable<[number, QuatKeyframeValueParameters]>);
|
||||
this.setKeyframes(
|
||||
keyframes.map(([time]) => time),
|
||||
keyframes.map(([, value]) => createQuatKeyframeValue(value)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public [serializeTag] (output: SerializationOutput, context: SerializationContext) {
|
||||
if (!context.toCCON) {
|
||||
output.writeThis();
|
||||
return;
|
||||
}
|
||||
|
||||
const {
|
||||
_times: times,
|
||||
_values: keyframeValues,
|
||||
} = this;
|
||||
|
||||
let interpolationModeRepeated = true;
|
||||
keyframeValues.forEach((keyframeValue, _index, [firstKeyframeValue]) => {
|
||||
// Values are unlikely to be unified.
|
||||
if (interpolationModeRepeated
|
||||
&& keyframeValue.interpolationMode !== firstKeyframeValue.interpolationMode) { interpolationModeRepeated = false; }
|
||||
});
|
||||
|
||||
const nKeyframes = times.length;
|
||||
|
||||
const nFrames = nKeyframes;
|
||||
const interpolationModesSize = INTERPOLATION_MODE_BYTES * (interpolationModeRepeated ? 1 : nFrames);
|
||||
|
||||
let dataSize = 0;
|
||||
dataSize += (
|
||||
FLAGS_BYTES
|
||||
+ FRAME_COUNT_BYTES
|
||||
+ TIME_BYTES * nFrames
|
||||
+ VALUE_BYTES * 4 * nFrames
|
||||
+ interpolationModesSize
|
||||
+ 0
|
||||
);
|
||||
|
||||
const dataView = new DataView(new ArrayBuffer(dataSize));
|
||||
let P = 0;
|
||||
|
||||
// Flags
|
||||
let flags = 0;
|
||||
if (interpolationModeRepeated) { flags |= KeyframeValueFlagMask.INTERPOLATION_MODE; }
|
||||
dataView.setUint32(P, flags, true); P += FLAGS_BYTES;
|
||||
|
||||
// Frame count
|
||||
dataView.setUint32(P, nFrames, true); P += FRAME_COUNT_BYTES;
|
||||
|
||||
// Times
|
||||
times.forEach((time, index) => dataView.setFloat32(P + TIME_BYTES * index, time, true));
|
||||
P += TIME_BYTES * nFrames;
|
||||
|
||||
keyframeValues.forEach(({ value: { x, y, z, w } }, index) => {
|
||||
const pQuat = P + VALUE_BYTES * 4 * index;
|
||||
dataView.setFloat32(pQuat + VALUE_BYTES * 0, x, true);
|
||||
dataView.setFloat32(pQuat + VALUE_BYTES * 1, y, true);
|
||||
dataView.setFloat32(pQuat + VALUE_BYTES * 2, z, true);
|
||||
dataView.setFloat32(pQuat + VALUE_BYTES * 3, w, true);
|
||||
});
|
||||
P += VALUE_BYTES * 4 * nFrames;
|
||||
|
||||
// Frame values
|
||||
const INTERPOLATION_MODES_START = P; P += interpolationModesSize;
|
||||
let pInterpolationMode = INTERPOLATION_MODES_START;
|
||||
keyframeValues.forEach(({ interpolationMode }) => {
|
||||
dataView.setUint8(pInterpolationMode, interpolationMode);
|
||||
|
||||
if (!interpolationModeRepeated) { pInterpolationMode += INTERPOLATION_MODE_BYTES; }
|
||||
});
|
||||
|
||||
const bytes = new Uint8Array(dataView.buffer);
|
||||
output.writeProperty('bytes', bytes);
|
||||
}
|
||||
|
||||
public [deserializeTag] (input: SerializationInput, context: DeserializationContext) {
|
||||
if (!context.fromCCON) {
|
||||
input.readThis();
|
||||
return;
|
||||
}
|
||||
|
||||
const bytes = input.readProperty('bytes') as Uint8Array;
|
||||
|
||||
const dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let P = 0;
|
||||
|
||||
// Flags
|
||||
const flags = dataView.getUint32(P, true); P += FLAGS_BYTES;
|
||||
const interpolationModeRepeated = flags & KeyframeValueFlagMask.INTERPOLATION_MODE;
|
||||
|
||||
// Frame count
|
||||
const nFrames = dataView.getUint32(P, true); P += FRAME_COUNT_BYTES;
|
||||
|
||||
// Times
|
||||
const times = Array.from({ length: nFrames },
|
||||
(_, index) => dataView.getFloat32(P + TIME_BYTES * index, true));
|
||||
P += TIME_BYTES * nFrames;
|
||||
|
||||
// Frame values
|
||||
const P_VALUES = P; P += VALUE_BYTES * 4 * nFrames;
|
||||
let pInterpolationModes = P;
|
||||
const keyframeValues = Array.from({ length: nFrames },
|
||||
(_, index) => {
|
||||
const pQuat = P_VALUES + VALUE_BYTES * 4 * index;
|
||||
const x = dataView.getFloat32(pQuat + VALUE_BYTES * 0, true);
|
||||
const y = dataView.getFloat32(pQuat + VALUE_BYTES * 1, true);
|
||||
const z = dataView.getFloat32(pQuat + VALUE_BYTES * 2, true);
|
||||
const w = dataView.getFloat32(pQuat + VALUE_BYTES * 3, true);
|
||||
const keyframeValue = createQuatKeyframeValue({
|
||||
value: { x, y, z, w },
|
||||
interpolationMode: dataView.getUint8(pInterpolationModes),
|
||||
});
|
||||
if (!interpolationModeRepeated) {
|
||||
pInterpolationModes += INTERPOLATION_MODE_BYTES;
|
||||
}
|
||||
return keyframeValue;
|
||||
});
|
||||
|
||||
this._times = times;
|
||||
this._values = keyframeValues;
|
||||
}
|
||||
}
|
||||
|
||||
enum KeyframeValueFlagMask {
|
||||
INTERPOLATION_MODE = 1 << 0,
|
||||
}
|
||||
|
||||
const FLAGS_BYTES = 1;
|
||||
const FRAME_COUNT_BYTES = 4;
|
||||
const TIME_BYTES = 4;
|
||||
const VALUE_BYTES = 4;
|
||||
const INTERPOLATION_MODE_BYTES = 1;
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* The method used for interpolation between values of a keyframe and its next keyframe.
|
||||
*/
|
||||
export enum RealInterpolationMode {
|
||||
/**
|
||||
* Perform linear interpolation.
|
||||
*/
|
||||
LINEAR,
|
||||
|
||||
/**
|
||||
* Always use the value from this keyframe.
|
||||
*/
|
||||
CONSTANT,
|
||||
|
||||
/**
|
||||
* Perform cubic(hermite) interpolation.
|
||||
*/
|
||||
CUBIC,
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies how to extrapolate the value
|
||||
* if input time is underflow(less than the the first frame time) or
|
||||
* overflow(greater than the last frame time) when evaluating an animation curve.
|
||||
*/
|
||||
export enum ExtrapolationMode {
|
||||
/**
|
||||
* Compute the result
|
||||
* according to the first two frame's linear trend in the case of underflow and
|
||||
* according to the last two frame's linear trend in the case of overflow.
|
||||
* If there are less than two frames, fallback to `CLAMP`.
|
||||
*/
|
||||
LINEAR,
|
||||
|
||||
/**
|
||||
* Use first frame's value in the case of underflow,
|
||||
* use last frame's value in the case of overflow.
|
||||
*/
|
||||
CLAMP,
|
||||
|
||||
/**
|
||||
* Before evaluation, repeatedly mapping the input time into the allowed range.
|
||||
*/
|
||||
LOOP,
|
||||
|
||||
/**
|
||||
* Before evaluation, mapping the input time into the allowed range like ping pong.
|
||||
*/
|
||||
PING_PONG,
|
||||
}
|
||||
|
||||
export enum TangentWeightMode {
|
||||
NONE = 0,
|
||||
|
||||
LEFT = 1,
|
||||
|
||||
RIGHT = 2,
|
||||
|
||||
BOTH = 1 | 2,
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// cSpell:words Cardano's irreducibilis
|
||||
|
||||
/**
|
||||
* Solve Cubic Equation using Cardano's formula.
|
||||
* The equation is formed from coeff0 + coeff1 * x + coeff2 * x^2 + coeff3 * x^3 = 0.
|
||||
* Modified from https://github.com/erich666/GraphicsGems/blob/master/gems/Roots3And4.c .
|
||||
*/
|
||||
export function solveCubic (coeff0: number, coeff1: number, coeff2: number, coeff3: number, solutions: [number, number, number]) {
|
||||
// normal form: x^3 + Ax^2 + Bx + C = 0
|
||||
const a = coeff2 / coeff3;
|
||||
const b = coeff1 / coeff3;
|
||||
const c = coeff0 / coeff3;
|
||||
|
||||
// substitute x = y - A/3 to eliminate quadric term:
|
||||
// x^3 +px + q = 0
|
||||
const sqrA = a * a;
|
||||
const p = 1.0 / 3.0 * (-1.0 / 3 * sqrA + b);
|
||||
const q = 1.0 / 2.0 * (2.0 / 27.0 * a * sqrA - 1.0 / 3 * a * b + c);
|
||||
|
||||
// use Cardano's formula
|
||||
const cubicP = p * p * p;
|
||||
const d = q * q + cubicP;
|
||||
|
||||
let nSolutions = 0;
|
||||
if (isZero(d)) {
|
||||
if (isZero(q)) { // one triple solution
|
||||
solutions[0] = 0;
|
||||
return 1;
|
||||
} else { // one single and one double solution
|
||||
const u = Math.cbrt(-q);
|
||||
solutions[0] = 2 * u;
|
||||
solutions[1] = -u;
|
||||
return 2;
|
||||
}
|
||||
} else if (d < 0) { // Casus irreducibilis: three real solutions
|
||||
const phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cubicP));
|
||||
const t = 2 * Math.sqrt(-p);
|
||||
|
||||
solutions[0] = t * Math.cos(phi);
|
||||
solutions[1] = -t * Math.cos(phi + Math.PI / 3);
|
||||
solutions[2] = -t * Math.cos(phi - Math.PI / 3);
|
||||
nSolutions = 3;
|
||||
} else { // one real solution
|
||||
const sqrtD = Math.sqrt(d);
|
||||
const u = Math.cbrt(sqrtD - q);
|
||||
const v = -Math.cbrt(sqrtD + q);
|
||||
solutions[0] = u + v;
|
||||
nSolutions = 1;
|
||||
}
|
||||
|
||||
const sub = 1.0 / 3 * a;
|
||||
for (let i = 0; i < nSolutions; ++i) {
|
||||
solutions[i] -= sub;
|
||||
}
|
||||
|
||||
return nSolutions;
|
||||
}
|
||||
|
||||
const EQN_EPS = 1e-9;
|
||||
|
||||
function isZero (x: number) {
|
||||
return x > -EQN_EPS && x < EQN_EPS;
|
||||
}
|
||||
@@ -39,7 +39,7 @@ export function assertIsNonNullable<T> (expr: T, message?: string): asserts expr
|
||||
* @param expr Testing expression.
|
||||
* @param message Optional message.
|
||||
*/
|
||||
export function assertIsTrue (expr: boolean, message?: string) {
|
||||
export function assertIsTrue (expr: unknown, message?: string): asserts expr {
|
||||
if (DEBUG && !expr) {
|
||||
throw new Error(`Assertion failed: ${message ?? '<no-message>'}`);
|
||||
}
|
||||
|
||||
+150
-106
@@ -30,19 +30,12 @@
|
||||
|
||||
import { CCClass } from '../data/class';
|
||||
import { clamp, inverseLerp, pingPong, repeat } from '../math/utils';
|
||||
import { Enum } from '../value-types/enum';
|
||||
import { WrapModeMask } from '../animation/types';
|
||||
import { ExtrapolationMode, RealCurve, RealInterpolationMode, RealKeyframeValue } from '../curves';
|
||||
import { ccclass, serializable } from '../data/decorators';
|
||||
|
||||
const LOOK_FORWARD = 3;
|
||||
|
||||
const WrapMode = Enum({
|
||||
Default: WrapModeMask.Default,
|
||||
Normal: WrapModeMask.Normal,
|
||||
Clamp: WrapModeMask.Clamp,
|
||||
Loop: WrapModeMask.Loop,
|
||||
PingPong: WrapModeMask.PingPong,
|
||||
});
|
||||
|
||||
/**
|
||||
* @en
|
||||
* A key frame in the curve.
|
||||
@@ -110,7 +103,11 @@ export function evalOptCurve (t: number, coefs: Float32Array | number[]) {
|
||||
* @zh
|
||||
* 描述一条曲线,其中每个相邻关键帧采用三次hermite插值计算。
|
||||
*/
|
||||
@ccclass('cc.AnimationCurve')
|
||||
export class AnimationCurve {
|
||||
@serializable
|
||||
private _curve!: RealCurve;
|
||||
|
||||
private static defaultKF: Keyframe[] = [{
|
||||
time: 0,
|
||||
value: 1,
|
||||
@@ -123,13 +120,42 @@ export class AnimationCurve {
|
||||
outTangent: 0,
|
||||
}];
|
||||
|
||||
/**
|
||||
* For internal usage only.
|
||||
* @internal
|
||||
*/
|
||||
get _internalCurve () {
|
||||
return this._curve;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
* The key frame of the curve.
|
||||
* @zh
|
||||
* 曲线的关键帧。
|
||||
*/
|
||||
public keyFrames: Keyframe[] | null;
|
||||
get keyFrames () {
|
||||
return Array.from(this._curve.keyframes()).map(([time, value]) => {
|
||||
const legacyKeyframe = new Keyframe();
|
||||
legacyKeyframe.time = time;
|
||||
legacyKeyframe.value = value.value;
|
||||
legacyKeyframe.inTangent = value.leftTangent;
|
||||
legacyKeyframe.outTangent = value.rightTangent;
|
||||
return legacyKeyframe;
|
||||
});
|
||||
}
|
||||
|
||||
set keyFrames (value) {
|
||||
this._curve.assignSorted(value.map((legacyCurve) => [
|
||||
legacyCurve.time,
|
||||
{
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: legacyCurve.value,
|
||||
leftTangent: legacyCurve.inTangent,
|
||||
rightTangent: legacyCurve.outTangent,
|
||||
},
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
@@ -137,7 +163,13 @@ export class AnimationCurve {
|
||||
* @zh
|
||||
* 当采样时间超出左端时采用的循环模式[[WrapMode]]。
|
||||
*/
|
||||
public preWrapMode: number = WrapMode.Loop;
|
||||
get preWrapMode () {
|
||||
return toLegacyWrapMode(this._curve.preExtrapolation);
|
||||
}
|
||||
|
||||
set preWrapMode (value) {
|
||||
this._curve.preExtrapolation = fromLegacyWrapMode(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @en
|
||||
@@ -145,7 +177,13 @@ export class AnimationCurve {
|
||||
* @zh
|
||||
* 当采样时间超出右端时采用的循环模式[[WrapMode]]。
|
||||
*/
|
||||
public postWrapMode: number = WrapMode.Clamp;
|
||||
get postWrapMode () {
|
||||
return toLegacyWrapMode(this._curve.postExtrapolation);
|
||||
}
|
||||
|
||||
set postWrapMode (value) {
|
||||
this._curve.postExtrapolation = fromLegacyWrapMode(value);
|
||||
}
|
||||
|
||||
private cachedKey: OptimizedKey;
|
||||
|
||||
@@ -153,8 +191,28 @@ export class AnimationCurve {
|
||||
* 构造函数。
|
||||
* @param keyFrames 关键帧。
|
||||
*/
|
||||
constructor (keyFrames: Keyframe[] | null = null) {
|
||||
this.keyFrames = keyFrames || ([] as Keyframe[]).concat(AnimationCurve.defaultKF);
|
||||
constructor (keyFrames: Keyframe[] | null | RealCurve = null) {
|
||||
if (keyFrames instanceof RealCurve) {
|
||||
this._curve = keyFrames;
|
||||
} else {
|
||||
const curve = new RealCurve();
|
||||
this._curve = curve;
|
||||
curve.preExtrapolation = ExtrapolationMode.LOOP;
|
||||
curve.postExtrapolation = ExtrapolationMode.CLAMP;
|
||||
if (!keyFrames) {
|
||||
curve.assignSorted([
|
||||
[0.0, { interpolationMode: RealInterpolationMode.CUBIC, value: 1.0 }],
|
||||
[1.0, { interpolationMode: RealInterpolationMode.CUBIC, value: 1.0 }],
|
||||
]);
|
||||
} else {
|
||||
curve.assignSorted(keyFrames.map((legacyKeyframe) => [legacyKeyframe.time, {
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: legacyKeyframe.value,
|
||||
leftTangent: legacyKeyframe.inTangent,
|
||||
rightTangent: legacyKeyframe.outTangent,
|
||||
}]));
|
||||
}
|
||||
}
|
||||
this.cachedKey = new OptimizedKey();
|
||||
}
|
||||
|
||||
@@ -165,11 +223,17 @@ export class AnimationCurve {
|
||||
* 添加一个关键帧。
|
||||
* @param keyFrame 关键帧。
|
||||
*/
|
||||
public addKey (keyFrame: Keyframe) {
|
||||
if (this.keyFrames == null) {
|
||||
this.keyFrames = [];
|
||||
public addKey (keyFrame: Keyframe | null) {
|
||||
if (!keyFrame) {
|
||||
this._curve.clear();
|
||||
} else {
|
||||
this._curve.addKeyFrame(keyFrame.time, {
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: keyFrame.value,
|
||||
leftTangent: keyFrame.inTangent,
|
||||
rightTangent: keyFrame.outTangent,
|
||||
});
|
||||
}
|
||||
this.keyFrames.push(keyFrame);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -177,57 +241,7 @@ export class AnimationCurve {
|
||||
* @param time
|
||||
*/
|
||||
public evaluate_slow (time: number) {
|
||||
let wrappedTime = time;
|
||||
const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
|
||||
const startTime = this.keyFrames![0].time;
|
||||
const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
|
||||
switch (wrapMode) {
|
||||
case WrapMode.Loop:
|
||||
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
|
||||
break;
|
||||
case WrapMode.PingPong:
|
||||
wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
|
||||
break;
|
||||
case WrapMode.Default:
|
||||
case WrapMode.Normal:
|
||||
case WrapMode.Clamp:
|
||||
wrappedTime = clamp(time, startTime, endTime);
|
||||
break;
|
||||
default:
|
||||
wrappedTime = clamp(time, startTime, endTime);
|
||||
break;
|
||||
}
|
||||
let preKFIndex = 0;
|
||||
if (wrappedTime > this.keyFrames![0].time) {
|
||||
if (wrappedTime >= this.keyFrames![this.keyFrames!.length - 1].time) {
|
||||
preKFIndex = this.keyFrames!.length - 2;
|
||||
} else {
|
||||
for (let i = 0; i < this.keyFrames!.length - 1; i++) {
|
||||
if (wrappedTime >= this.keyFrames![0].time && wrappedTime <= this.keyFrames![i + 1].time) {
|
||||
preKFIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const keyframe0 = this.keyFrames![preKFIndex];
|
||||
const keyframe1 = this.keyFrames![preKFIndex + 1];
|
||||
|
||||
const t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
|
||||
const dt = keyframe1.time - keyframe0.time;
|
||||
|
||||
const m0 = keyframe0.outTangent * dt;
|
||||
const m1 = keyframe1.inTangent * dt;
|
||||
|
||||
const t2 = t * t;
|
||||
const t3 = t2 * t;
|
||||
|
||||
const a = 2 * t3 - 3 * t2 + 1;
|
||||
const b = t3 - 2 * t2 + t;
|
||||
const c = t3 - t2;
|
||||
const d = -2 * t3 + 3 * t2;
|
||||
|
||||
return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value;
|
||||
return this._curve.evaluate(time);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -238,33 +252,32 @@ export class AnimationCurve {
|
||||
* @param time 时间。
|
||||
*/
|
||||
public evaluate (time: number) {
|
||||
const { cachedKey, _curve: curve } = this;
|
||||
const nKeyframes = curve.keyFramesCount;
|
||||
const lastKeyframeIndex = nKeyframes - 1;
|
||||
let wrappedTime = time;
|
||||
const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
|
||||
const startTime = this.keyFrames![0].time;
|
||||
const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
|
||||
switch (wrapMode) {
|
||||
case WrapMode.Loop:
|
||||
const extrapolationMode = time < 0 ? curve.preExtrapolation : curve.postExtrapolation;
|
||||
const startTime = curve.getKeyframeTime(0);
|
||||
const endTime = curve.getKeyframeTime(lastKeyframeIndex);
|
||||
switch (extrapolationMode) {
|
||||
case ExtrapolationMode.LOOP:
|
||||
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
|
||||
break;
|
||||
case WrapMode.PingPong:
|
||||
case ExtrapolationMode.PING_PONG:
|
||||
wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
|
||||
break;
|
||||
case WrapMode.Default:
|
||||
case WrapMode.Normal:
|
||||
case WrapMode.Clamp:
|
||||
wrappedTime = clamp(time, startTime, endTime);
|
||||
break;
|
||||
case ExtrapolationMode.CLAMP:
|
||||
default:
|
||||
wrappedTime = clamp(time, startTime, endTime);
|
||||
break;
|
||||
}
|
||||
if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) {
|
||||
return this.cachedKey.evaluate(wrappedTime);
|
||||
if (wrappedTime >= cachedKey.time && wrappedTime < cachedKey.endTime) {
|
||||
return cachedKey.evaluate(wrappedTime);
|
||||
}
|
||||
const leftIndex = this.findIndex(this.cachedKey, wrappedTime);
|
||||
const rightIndex = Math.min(leftIndex + 1, this.keyFrames!.length - 1);
|
||||
this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex);
|
||||
return this.cachedKey.evaluate(wrappedTime);
|
||||
const leftIndex = this.findIndex(cachedKey, wrappedTime);
|
||||
const rightIndex = Math.min(leftIndex + 1, lastKeyframeIndex);
|
||||
this.calcOptimizedKey(cachedKey, leftIndex, rightIndex);
|
||||
return cachedKey.evaluate(wrappedTime);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,22 +287,24 @@ export class AnimationCurve {
|
||||
* @param rightIndex
|
||||
*/
|
||||
public calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) {
|
||||
const lhs = this.keyFrames![leftIndex];
|
||||
const rhs = this.keyFrames![rightIndex];
|
||||
const lhsTime = this._curve.getKeyframeTime(leftIndex);
|
||||
const rhsTime = this._curve.getKeyframeTime(rightIndex);
|
||||
const { value: lhsValue, leftTangent: lhsOutTangent } = this._curve.getKeyframeValue(leftIndex);
|
||||
const { value: rhsValue, rightTangent: rhsInTangent } = this._curve.getKeyframeValue(rightIndex);
|
||||
optKey.index = leftIndex;
|
||||
optKey.time = lhs.time;
|
||||
optKey.endTime = rhs.time;
|
||||
optKey.time = lhsTime;
|
||||
optKey.endTime = rhsTime;
|
||||
|
||||
const dx = rhs.time - lhs.time;
|
||||
const dy = rhs.value - lhs.value;
|
||||
const dx = rhsTime - lhsTime;
|
||||
const dy = rhsValue - lhsValue;
|
||||
const length = 1 / (dx * dx);
|
||||
const d1 = lhs.outTangent * dx;
|
||||
const d2 = rhs.inTangent * dx;
|
||||
const d1 = lhsOutTangent * dx;
|
||||
const d2 = rhsInTangent * dx;
|
||||
|
||||
optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
|
||||
optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
|
||||
optKey.coefficient[2] = lhs.outTangent;
|
||||
optKey.coefficient[3] = lhs.value;
|
||||
optKey.coefficient[2] = lhsOutTangent;
|
||||
optKey.coefficient[3] = lhsValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -298,31 +313,33 @@ export class AnimationCurve {
|
||||
* @param t
|
||||
*/
|
||||
private findIndex (optKey: OptimizedKey, t: number) {
|
||||
const { _curve: curve } = this;
|
||||
const nKeyframes = curve.keyFramesCount;
|
||||
const cachedIndex = optKey.index;
|
||||
if (cachedIndex !== -1) {
|
||||
const cachedTime = this.keyFrames![cachedIndex].time;
|
||||
const cachedTime = curve.getKeyframeTime(cachedIndex);
|
||||
if (t > cachedTime) {
|
||||
for (let i = 0; i < LOOK_FORWARD; i++) {
|
||||
const currIndex = cachedIndex + i;
|
||||
if (currIndex + 1 < this.keyFrames!.length && this.keyFrames![currIndex + 1].time > t) {
|
||||
if (currIndex + 1 < nKeyframes && curve.getKeyframeTime(currIndex + 1) > t) {
|
||||
return currIndex;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < LOOK_FORWARD; i++) {
|
||||
const currIndex = cachedIndex - i;
|
||||
if (currIndex >= 0 && this.keyFrames![currIndex - 1].time <= t) {
|
||||
if (currIndex >= 0 && curve.getKeyframeTime(currIndex - 1) <= t) {
|
||||
return currIndex - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let left = 0;
|
||||
let right = this.keyFrames!.length;
|
||||
let right = nKeyframes;
|
||||
let mid;
|
||||
while (right - left > 1) {
|
||||
mid = Math.floor((left + right) / 2);
|
||||
if (this.keyFrames![mid].time >= t) {
|
||||
if (curve.getKeyframeTime(mid) >= t) {
|
||||
right = mid;
|
||||
} else {
|
||||
left = mid;
|
||||
@@ -332,8 +349,35 @@ export class AnimationCurve {
|
||||
}
|
||||
}
|
||||
|
||||
CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
|
||||
preWrapMode: WrapMode.Default,
|
||||
postWrapMode: WrapMode.Default,
|
||||
keyFrames: [],
|
||||
});
|
||||
function fromLegacyWrapMode (legacyWrapMode: WrapModeMask): ExtrapolationMode {
|
||||
switch (legacyWrapMode) {
|
||||
default:
|
||||
case WrapModeMask.Default:
|
||||
case WrapModeMask.Normal:
|
||||
case WrapModeMask.Clamp: return ExtrapolationMode.CLAMP;
|
||||
case WrapModeMask.PingPong: return ExtrapolationMode.PING_PONG;
|
||||
case WrapModeMask.Loop: return ExtrapolationMode.LOOP;
|
||||
}
|
||||
}
|
||||
|
||||
function toLegacyWrapMode (extrapolationMode: ExtrapolationMode): WrapModeMask {
|
||||
switch (extrapolationMode) {
|
||||
default:
|
||||
case ExtrapolationMode.LINEAR:
|
||||
case ExtrapolationMode.CLAMP: return WrapModeMask.Clamp;
|
||||
case ExtrapolationMode.PING_PONG: return WrapModeMask.PingPong;
|
||||
case ExtrapolationMode.LOOP: return WrapModeMask.Loop;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as but more effective than `new LegacyCurve()._internalCurve`.
|
||||
*/
|
||||
export function constructLegacyCurveAndConvert () {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.0, { interpolationMode: RealInterpolationMode.CUBIC, value: 1.0 }],
|
||||
[1.0, { interpolationMode: RealInterpolationMode.CUBIC, value: 1.0 }],
|
||||
]);
|
||||
return curve;
|
||||
}
|
||||
|
||||
@@ -61,3 +61,4 @@ export * from './scene-graph';
|
||||
export * from './components';
|
||||
export * from './builtin';
|
||||
export * from './animation';
|
||||
export * from './curves';
|
||||
|
||||
@@ -28,20 +28,20 @@
|
||||
* @hidden
|
||||
*/
|
||||
|
||||
import { ccclass, type, serializable, editable } from 'cc.decorator';
|
||||
import { ccclass, type, serializable, editable, formerlySerializedAs } from 'cc.decorator';
|
||||
import { EDITOR } from 'internal:constants';
|
||||
import { lerp } from '../../core/math';
|
||||
import { Enum } from '../../core/value-types';
|
||||
import { AnimationCurve } from '../../core/geometry';
|
||||
import { Texture2D, ImageAsset } from '../../core';
|
||||
import { AnimationCurve, constructLegacyCurveAndConvert } from '../../core/geometry/curve';
|
||||
import { Texture2D, ImageAsset, RealCurve } from '../../core';
|
||||
import { PixelFormat, Filter, WrapMode } from '../../core/assets/asset-enum';
|
||||
|
||||
const SerializableTable = EDITOR && [
|
||||
const SerializableTable = [
|
||||
['mode', 'constant', 'multiplier'],
|
||||
['mode', 'curve', 'multiplier'],
|
||||
['mode', 'curveMin', 'curveMax', 'multiplier'],
|
||||
['mode', 'spline', 'multiplier'],
|
||||
['mode', 'splineMin', 'splineMax', 'multiplier'],
|
||||
['mode', 'constantMin', 'constantMax', 'multiplier'],
|
||||
];
|
||||
] as const;
|
||||
|
||||
export const Mode = Enum({
|
||||
Constant: 0,
|
||||
@@ -63,20 +63,59 @@ export default class CurveRange {
|
||||
/**
|
||||
* @zh 当mode为Curve时,使用的曲线。
|
||||
*/
|
||||
@type(AnimationCurve)
|
||||
public curve = new AnimationCurve();
|
||||
@type(RealCurve)
|
||||
public spline = constructLegacyCurveAndConvert();
|
||||
|
||||
/**
|
||||
* @zh 当mode为TwoCurves时,使用的曲线下限。
|
||||
*/
|
||||
@type(AnimationCurve)
|
||||
public curveMin = new AnimationCurve();
|
||||
@type(RealCurve)
|
||||
public splineMin = constructLegacyCurveAndConvert();
|
||||
|
||||
/**
|
||||
* @zh 当mode为TwoCurves时,使用的曲线上限。
|
||||
*/
|
||||
@type(AnimationCurve)
|
||||
public curveMax = new AnimationCurve();
|
||||
@type(RealCurve)
|
||||
public splineMax = constructLegacyCurveAndConvert();
|
||||
|
||||
/**
|
||||
* @zh 当mode为Curve时,使用的曲线。
|
||||
* @deprecated Since V3.3. Use `spline` instead.
|
||||
*/
|
||||
get curve () {
|
||||
return this._curve;
|
||||
}
|
||||
|
||||
set curve (value) {
|
||||
this._curve = value;
|
||||
this.spline = value._internalCurve;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 当mode为TwoCurves时,使用的曲线下限。
|
||||
* @deprecated Since V3.3. Use `splineMin` instead.
|
||||
*/
|
||||
get curveMin () {
|
||||
return this._curveMin;
|
||||
}
|
||||
|
||||
set curveMin (value) {
|
||||
this._curveMin = value;
|
||||
this.splineMin = value._internalCurve;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 当mode为TwoCurves时,使用的曲线上限。
|
||||
* @deprecated Since V3.3. Use `splineMax` instead.
|
||||
*/
|
||||
get curveMax () {
|
||||
return this._curveMax;
|
||||
}
|
||||
|
||||
set curveMax (value) {
|
||||
this._curveMax = value;
|
||||
this.splineMax = value._internalCurve;
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 当mode为Constant时,曲线的值。
|
||||
@@ -112,12 +151,13 @@ export default class CurveRange {
|
||||
|
||||
public evaluate (time: number, rndRatio: number) {
|
||||
switch (this.mode) {
|
||||
default:
|
||||
case Mode.Constant:
|
||||
return this.constant;
|
||||
case Mode.Curve:
|
||||
return this.curve.evaluate(time) * this.multiplier;
|
||||
return this.spline.evaluate(time) * this.multiplier;
|
||||
case Mode.TwoCurves:
|
||||
return lerp(this.curveMin.evaluate(time), this.curveMax.evaluate(time), rndRatio) * this.multiplier;
|
||||
return lerp(this.splineMin.evaluate(time), this.splineMax.evaluate(time), rndRatio) * this.multiplier;
|
||||
case Mode.TwoConstants:
|
||||
return lerp(this.constantMin, this.constantMax, rndRatio);
|
||||
}
|
||||
@@ -125,6 +165,7 @@ export default class CurveRange {
|
||||
|
||||
public getMax (): number {
|
||||
switch (this.mode) {
|
||||
default:
|
||||
case Mode.Constant:
|
||||
return this.constant;
|
||||
case Mode.Curve:
|
||||
@@ -134,12 +175,16 @@ export default class CurveRange {
|
||||
case Mode.TwoCurves:
|
||||
return this.multiplier;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public _onBeforeSerialize (props) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return SerializableTable[this.mode];
|
||||
}
|
||||
|
||||
private _curve = new AnimationCurve(this.spline);
|
||||
private _curveMin = new AnimationCurve(this.splineMin);
|
||||
private _curveMax = new AnimationCurve(this.splineMax);
|
||||
}
|
||||
|
||||
function evaluateCurve (cr: CurveRange, time: number, index: number) {
|
||||
@@ -147,9 +192,9 @@ function evaluateCurve (cr: CurveRange, time: number, index: number) {
|
||||
case Mode.Constant:
|
||||
return cr.constant;
|
||||
case Mode.Curve:
|
||||
return cr.curve.evaluate(time) * cr.multiplier;
|
||||
return cr.spline.evaluate(time) * cr.multiplier;
|
||||
case Mode.TwoCurves:
|
||||
return index === 0 ? cr.curveMin.evaluate(time) * cr.multiplier : cr.curveMax.evaluate(time) * cr.multiplier;
|
||||
return index === 0 ? cr.splineMin.evaluate(time) * cr.multiplier : cr.splineMax.evaluate(time) * cr.multiplier;
|
||||
case Mode.TwoConstants:
|
||||
return index === 0 ? cr.constantMin : cr.constantMax;
|
||||
default:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
|
||||
export { AnimationClipLegacyData } from '../../cocos/core/animation/legacy-clip-data';
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
export {
|
||||
exoticAnimationTag,
|
||||
} from '../../cocos/core/animation/animation-clip';
|
||||
|
||||
export {
|
||||
ExoticAnimation,
|
||||
} from '../../cocos/core/animation/exotic-animation/exotic-animation';
|
||||
@@ -695,7 +695,7 @@ exports.methods = {
|
||||
const splitInfo = animInfo.splits[this.splitClipIndex];
|
||||
|
||||
if (!animInfo) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawClipUUID = this.animationNameToUUIDMap.get(animInfo.name);
|
||||
@@ -719,6 +719,7 @@ exports.methods = {
|
||||
|
||||
return {
|
||||
rawClipUUID,
|
||||
rawClipIndex: this.rawClipIndex,
|
||||
clipUUID,
|
||||
duration,
|
||||
fps,
|
||||
|
||||
@@ -333,19 +333,19 @@ const Elements = {
|
||||
const timeline = this.$.animationTime;
|
||||
timeline.addEventListener('change', this.onAnimationTimeChange.bind(this));
|
||||
timeline.addEventListener('transform', this.updateEventInfo.bind(this));
|
||||
}
|
||||
},
|
||||
},
|
||||
currentTime: {
|
||||
ready() {
|
||||
const currentTime = this.$.currentTime;
|
||||
currentTime.addEventListener('confirm', this.onAnimationTimeChange.bind(this));
|
||||
}
|
||||
},
|
||||
},
|
||||
timeCtrl: {
|
||||
ready() {
|
||||
this.$.timeCtrl.addEventListener('click', this.onTimeCtrlClick.bind(this));
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
exports.update = async function(assetList, metaList) {
|
||||
@@ -389,7 +389,7 @@ exports.ready = function() {
|
||||
|
||||
this.onEditClipInfoChanged = async (clipInfo) => {
|
||||
if (clipInfo) {
|
||||
await Editor.Message.request('scene', 'execute-model-preview-animation-operation', 'setEditClip', clipInfo.rawClipUUID);
|
||||
await Editor.Message.request('scene', 'execute-model-preview-animation-operation', 'setEditClip', clipInfo.rawClipUUID, clipInfo.rawClipIndex);
|
||||
this.setCurEditClipInfo(clipInfo);
|
||||
}
|
||||
};
|
||||
@@ -438,11 +438,11 @@ exports.close = function() {
|
||||
};
|
||||
|
||||
exports.methods = {
|
||||
async apply () {
|
||||
async apply() {
|
||||
// save animation event info
|
||||
await this.events.apply.call(this);
|
||||
},
|
||||
async refreshPreview () {
|
||||
async refreshPreview() {
|
||||
const panel = this;
|
||||
|
||||
// After await, the panel no longer exists
|
||||
@@ -497,7 +497,7 @@ exports.methods = {
|
||||
if (!name || !this.curEditClipInfo) {
|
||||
return;
|
||||
}
|
||||
switch(name) {
|
||||
switch (name) {
|
||||
case 'play':
|
||||
this.onPlayButtonClick();
|
||||
break;
|
||||
@@ -537,14 +537,14 @@ exports.methods = {
|
||||
this.events.update.call(this, eventInfos);
|
||||
},
|
||||
|
||||
async stopAnimation () {
|
||||
async stopAnimation() {
|
||||
if (!this.curEditClipInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Editor.Message.request('scene', 'execute-model-preview-animation-operation', 'stop');
|
||||
},
|
||||
async onPlayButtonClick () {
|
||||
async onPlayButtonClick() {
|
||||
if (!this.curEditClipInfo) {
|
||||
return;
|
||||
}
|
||||
@@ -564,7 +564,7 @@ exports.methods = {
|
||||
|
||||
this.isPreviewDataDirty = true;
|
||||
},
|
||||
async onAnimationTimeChange (event) {
|
||||
async onAnimationTimeChange(event) {
|
||||
event.stopPropagation();
|
||||
if (!this.curEditClipInfo) {
|
||||
return;
|
||||
@@ -582,7 +582,7 @@ exports.methods = {
|
||||
await Editor.Message.request('scene', 'execute-model-preview-animation-operation', 'setCurEditTime', curTime);
|
||||
},
|
||||
|
||||
onModelAnimationUpdate (time) {
|
||||
onModelAnimationUpdate(time) {
|
||||
if (!this.curEditClipInfo) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,605 @@
|
||||
import { SpriteFrame } from "../../cocos/2d/assets";
|
||||
import { math, RealInterpolationMode } from "../../cocos/core";
|
||||
import { AnimationClip, animation, BezierControlPoints, bezierByTime } from "../../cocos/core/animation";
|
||||
import { ColorTrack, IValueProxyFactory, RealTrack, Track, TrackPath, VectorTrack } from "../../cocos/core/animation/animation";
|
||||
import { LegacyClipCurve, LegacyCommonTarget, LegacyEasingMethod, timeBezierToTangents } from "../../cocos/core/animation/legacy-clip-data";
|
||||
import { ComponentPath, HierarchyPath, ICustomTargetPath, TargetPath } from "../../cocos/core/animation/target-path";
|
||||
import { RealChannel } from "../../cocos/core/animation/tracks/track";
|
||||
import { UntypedTrack } from "../../cocos/core/animation/tracks/untyped-track";
|
||||
import { EasingMethod, ExtrapolationMode, RealCurve, RealKeyframeValue, TangentWeightMode } from "../../cocos/core/curves/curve";
|
||||
import { createMultipleRealKeyframesWithoutTangent, createRealKeyframeValueLike } from "../curves/curve-test-utils";
|
||||
|
||||
class ValueProxyFactorFoo implements IValueProxyFactory {
|
||||
forTarget(_target: any): animation.IValueProxy {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
}
|
||||
|
||||
describe('Animation Clip Migration 3.x', () => {
|
||||
test(`Zero curve clip`, () => {
|
||||
const clip = createClipWithLegacyData({});
|
||||
expect(clip.tracksCount).toBe(0);
|
||||
});
|
||||
|
||||
describe(`Modifiers & proxies`, () => {
|
||||
test(`Empty path`, () => {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.1]],
|
||||
curves: [{ modifiers: [], data: { keys: 0, values: [0.2] } }],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
expect(Array.from(clip.tracks)[0].path.length).toBe(0);
|
||||
});
|
||||
|
||||
const TRACK_PATH_PROTOTYPE = TrackPath.prototype;
|
||||
|
||||
test.each([
|
||||
[`Property path`, {
|
||||
value: 'p',
|
||||
expected: 'p',
|
||||
is: TRACK_PATH_PROTOTYPE.isPropertyAt,
|
||||
parse: TRACK_PATH_PROTOTYPE.parsePropertyAt,
|
||||
}],
|
||||
[`Element path`, {
|
||||
value: 2,
|
||||
expected: 2,
|
||||
is: TRACK_PATH_PROTOTYPE.isPropertyAt,
|
||||
parse: TRACK_PATH_PROTOTYPE.parseElementAt,
|
||||
}],
|
||||
[`Hierarchy path`, {
|
||||
value: new HierarchyPath('foo'),
|
||||
expected: 'foo',
|
||||
is: TRACK_PATH_PROTOTYPE.isPropertyAt,
|
||||
parse: TRACK_PATH_PROTOTYPE.parseHierarchyAt,
|
||||
}],
|
||||
[`Component path`, {
|
||||
value: new ComponentPath('bar'),
|
||||
expected: 'bar',
|
||||
is: TRACK_PATH_PROTOTYPE.isPropertyAt,
|
||||
parse: TRACK_PATH_PROTOTYPE.parseComponentAt,
|
||||
}],
|
||||
] as [
|
||||
title: string, options: {
|
||||
value: TargetPath;
|
||||
expected: unknown;
|
||||
is: (index: number) => boolean;
|
||||
parse: (index: number) => unknown;
|
||||
}
|
||||
][])(`%s`, (_, { value, expected, is, parse }) => {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.1]],
|
||||
curves: [{ modifiers: [value], data: { keys: 0, values: [0.2] } }],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
const path = Array.from(clip.tracks)[0].path;
|
||||
expect(path.length).toBe(1);
|
||||
expect(is.call(path, 0));
|
||||
expect(parse.call(path, 0)).toBe(expected);
|
||||
});
|
||||
|
||||
test(`Customized path`, () => {
|
||||
// TODO
|
||||
});
|
||||
|
||||
test(`Compound path`, () => {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.1]],
|
||||
curves: [{ modifiers: [
|
||||
new HierarchyPath('foo'),
|
||||
new ComponentPath('bar'),
|
||||
'baz',
|
||||
1,
|
||||
], data: { keys: 0, values: [0.2] } }],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
const path = Array.from(clip.tracks)[0].path;
|
||||
expect(path.length).toBe(4);
|
||||
expect(path.isHierarchyAt(0));
|
||||
expect(path.parseHierarchyAt(0)).toBe('foo');
|
||||
expect(path.isComponentAt(1));
|
||||
expect(path.parseComponentAt(1)).toBe('bar');
|
||||
expect(path.isPropertyAt(2));
|
||||
expect(path.parsePropertyAt(2)).toBe('baz');
|
||||
expect(path.isElementAt(3));
|
||||
expect(path.parseElementAt(3)).toBe(1);
|
||||
});
|
||||
|
||||
test(`Value proxy`, () => {
|
||||
const valueProxy = new ValueProxyFactorFoo();
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.1]],
|
||||
curves: [{ modifiers: [], valueAdapter: valueProxy, data: { keys: 0, values: [0.2] } }],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
expect(Array.from(clip.tracks)[0].proxy).toBe(valueProxy);
|
||||
});
|
||||
});
|
||||
|
||||
describe(`Curves`, () => {
|
||||
|
||||
test(`Empty curve`, () => {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[]],
|
||||
curves: [{ modifiers: ['p'], data: { keys: 0, values: [] } }],
|
||||
});
|
||||
// We did not convert a empty curve since it's meaningless.
|
||||
expect(clip.tracksCount).toBe(0);
|
||||
});
|
||||
|
||||
interface RealLikeTrackTestOptions<TValueType, T extends Track> {
|
||||
valueType: NumberConstructor | { new (...args: number[]): TValueType };
|
||||
numberOfValueTypeComponents: number;
|
||||
expectedTrackType: { new (...args: any[]): T };
|
||||
numberFactor?: number;
|
||||
componentNames?: string[];
|
||||
}
|
||||
|
||||
describe.each([
|
||||
[`Numeric curves`, {
|
||||
valueType: Number,
|
||||
numberOfValueTypeComponents: 1,
|
||||
expectedTrackType: RealTrack,
|
||||
}],
|
||||
[`Vec2 curves`, {
|
||||
valueType: math.Vec2,
|
||||
numberOfValueTypeComponents: 2,
|
||||
expectedTrackType: VectorTrack,
|
||||
}],
|
||||
[`Vec3 curves`, {
|
||||
valueType: math.Vec3,
|
||||
numberOfValueTypeComponents: 3,
|
||||
expectedTrackType: VectorTrack,
|
||||
}],
|
||||
[`Vec4 curves`, {
|
||||
valueType: math.Vec4,
|
||||
numberOfValueTypeComponents: 4,
|
||||
expectedTrackType: VectorTrack,
|
||||
}],
|
||||
[`Color curves`, {
|
||||
valueType: math.Color,
|
||||
numberOfValueTypeComponents: 4,
|
||||
expectedTrackType: ColorTrack,
|
||||
numberFactor: 10,
|
||||
componentNames: ['r', 'g', 'b', 'a'],
|
||||
}],
|
||||
] as Array<[
|
||||
title: string,
|
||||
options: RealLikeTrackTestOptions<unknown, Track>,
|
||||
]>)(`%s`, (_, {
|
||||
valueType,
|
||||
numberOfValueTypeComponents,
|
||||
expectedTrackType,
|
||||
numberFactor = 0.1,
|
||||
componentNames,
|
||||
}) => {
|
||||
if (!componentNames) {
|
||||
componentNames = ['x', 'y', 'z', 'w'];
|
||||
}
|
||||
const times = [0.1, 0.2, 0.8];
|
||||
const nKeyframes = times.length;
|
||||
const genValueAt = (keyframeIndex: number, componentIndex: number) =>
|
||||
numberFactor * (keyframeIndex * numberOfValueTypeComponents + componentIndex);
|
||||
const values = Array.from(
|
||||
{ length: nKeyframes },
|
||||
(_, iKeyframe) => valueType === Number
|
||||
? genValueAt(iKeyframe, 0)
|
||||
: new valueType(...Array.from(
|
||||
{ length: numberOfValueTypeComponents },
|
||||
(_, iComponent) => genValueAt(iKeyframe, iComponent)),
|
||||
),
|
||||
);
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [times],
|
||||
curves: [{
|
||||
modifiers: ['p'],
|
||||
data: {
|
||||
keys: 0,
|
||||
values: values,
|
||||
interpolate: true,
|
||||
},
|
||||
}, {
|
||||
modifiers: ['p'],
|
||||
data: {
|
||||
keys: 0,
|
||||
values: values,
|
||||
interpolate: false,
|
||||
},
|
||||
}],
|
||||
});
|
||||
const INTERPOLATE_TRUE_CURVE_INDEX = 0;
|
||||
const INTERPOLATE_FALSE_CURVE_INDEX = 1;
|
||||
expect(clip.tracksCount).toBe(2);
|
||||
test.each([
|
||||
[true, [INTERPOLATE_TRUE_CURVE_INDEX, RealInterpolationMode.LINEAR]],
|
||||
[false, [INTERPOLATE_FALSE_CURVE_INDEX, RealInterpolationMode.CONSTANT]],
|
||||
])(`with .interpolate: %s`, (_interpolate, [trackIndex, interpolationMode]) => {
|
||||
const track = clip.getTrack(trackIndex);
|
||||
expect(track).toBeInstanceOf(expectedTrackType);
|
||||
const channels = Array.from(track.channels());
|
||||
if (expectedTrackType === VectorTrack) {
|
||||
expect((track as VectorTrack).componentsCount).toBe(numberOfValueTypeComponents);
|
||||
} else {
|
||||
expect(channels).toHaveLength(numberOfValueTypeComponents);
|
||||
}
|
||||
const getComponentNameOfChannel = (channelIndex: number) => {
|
||||
if (channelIndex >= componentNames.length) {
|
||||
throw new Error(`Unknown component name at channel ${channelIndex}`);
|
||||
} else {
|
||||
return componentNames[channelIndex];
|
||||
}
|
||||
};
|
||||
for (let iChannel = 0; iChannel < numberOfValueTypeComponents; ++iChannel) {
|
||||
const { curve } = channels[iChannel] as RealChannel;
|
||||
expect(curve.preExtrapolation).toBe(ExtrapolationMode.CLAMP);
|
||||
expect(curve.postExtrapolation).toBe(ExtrapolationMode.CLAMP);
|
||||
// Each curve's times are obtained from original times
|
||||
expect(Array.from(curve.times())).toStrictEqual(times);
|
||||
const valuesAtChannel = valueType === Number
|
||||
? values as number[]
|
||||
: values.map((value) => (value as Record<string, number>)[getComponentNameOfChannel(iChannel)]);
|
||||
expect(Array.from(curve.values())).toStrictEqual(valuesAtChannel.map((value) => createRealKeyframeValueLike({
|
||||
value,
|
||||
interpolationMode,
|
||||
})));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('Size curves', () => {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.0, 0.2, 0.8]],
|
||||
curves: [{
|
||||
modifiers: ['p'],
|
||||
data: {
|
||||
keys: 0,
|
||||
values: [
|
||||
new math.Size(10.8, -1.3),
|
||||
new math.Size(20, 50),
|
||||
new math.Size(30, 60),
|
||||
],
|
||||
},
|
||||
}],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
const track = clip.getTrack(0) as animation.SizeTrack;
|
||||
expect(track).toBeInstanceOf(animation.SizeTrack);
|
||||
const [{ curve: width }, { curve: height }] = track.channels();
|
||||
expect(Array.from(width.times())).toStrictEqual([0.0, 0.2, 0.8]);
|
||||
expect(Array.from(width.values())).toStrictEqual(
|
||||
createMultipleRealKeyframesWithoutTangent([10.8, 20, 30], RealInterpolationMode.LINEAR),
|
||||
);
|
||||
expect(Array.from(height.times())).toStrictEqual([0.0, 0.2, 0.8]);
|
||||
expect(Array.from(height.values())).toStrictEqual(
|
||||
createMultipleRealKeyframesWithoutTangent([-1.3, 50, 60], RealInterpolationMode.LINEAR),
|
||||
);
|
||||
});
|
||||
|
||||
test('Sprite frame curves', () => {
|
||||
const spriteFrames = [
|
||||
new SpriteFrame(),
|
||||
new SpriteFrame(),
|
||||
new SpriteFrame(),
|
||||
];
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[0.0, 0.2, 0.8]],
|
||||
curves: [{
|
||||
modifiers: ['p'],
|
||||
data: {
|
||||
keys: 0,
|
||||
values: spriteFrames,
|
||||
},
|
||||
}],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
const track = clip.getTrack(0) as animation.ObjectTrack<SpriteFrame>;
|
||||
expect(track).toBeInstanceOf(animation.ObjectTrack);
|
||||
const { curve } = track.channel;
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.0, 0.2, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual(spriteFrames);
|
||||
});
|
||||
});
|
||||
|
||||
test(`Common targets are converted into internal concept: UntypedTracks`, () => {
|
||||
const valueProxy = new ValueProxyFactorFoo();
|
||||
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [[1.2]],
|
||||
commonTargets: [{
|
||||
modifiers: ['p1'],
|
||||
}, {
|
||||
modifiers: ['p2'],
|
||||
valueAdapter: valueProxy,
|
||||
}],
|
||||
curves: [{
|
||||
commonTarget: 0,
|
||||
modifiers: ['x'],
|
||||
data: { keys: 0, values: [0.1] },
|
||||
}, {
|
||||
commonTarget: 0,
|
||||
modifiers: ['y'],
|
||||
data: { keys: 0, values: [0.2] },
|
||||
}, {
|
||||
commonTarget: 1,
|
||||
modifiers: ['z'],
|
||||
data: { keys: 0, values: [0.3] },
|
||||
}],
|
||||
});
|
||||
|
||||
expect(clip.tracksCount).toBe(2);
|
||||
const tracks = Array.from(clip.tracks);
|
||||
const [ track1, track2 ] = tracks as [UntypedTrack, UntypedTrack];
|
||||
|
||||
expect(track1).toBeInstanceOf(UntypedTrack);
|
||||
expect(track1.path.length).toBe(1);
|
||||
expect(track1.path.isPropertyAt(0)).toBe(true);
|
||||
expect(track1.path.parsePropertyAt(0)).toBe('p1');
|
||||
expect(track1.channels()).toHaveLength(2);
|
||||
expect(Array.from(track1.channels()[0].curve.keyframes())).toStrictEqual([[1.2, createRealKeyframeValueLike({ value: 0.1 })]]);
|
||||
expect(Array.from(track1.channels()[1].curve.keyframes())).toStrictEqual([[1.2, createRealKeyframeValueLike({ value: 0.2 })]]);
|
||||
|
||||
expect(track2).toBeInstanceOf(UntypedTrack);
|
||||
expect(track2.path.length).toBe(1);
|
||||
expect(track2.path.isPropertyAt(0)).toBe(true);
|
||||
expect(track2.path.parsePropertyAt(0)).toBe('p2');
|
||||
expect(track2.proxy).toBe(valueProxy);
|
||||
expect(track2.channels()).toHaveLength(1);
|
||||
expect(Array.from(track2.channels()[0].curve.keyframes())).toStrictEqual([[1.2, createRealKeyframeValueLike({ value: 0.3 })]]);
|
||||
});
|
||||
|
||||
describe(`Easing methods`, () => {
|
||||
function createClipWithEasingMethodsAndConvert (
|
||||
times: number[],
|
||||
values: number[],
|
||||
easingMethod: undefined | LegacyEasingMethod,
|
||||
easingMethods: undefined | LegacyEasingMethod[] | Record<number, LegacyEasingMethod>,
|
||||
interpolate = true,
|
||||
) {
|
||||
const clip = createClipWithLegacyData({
|
||||
times: [times],
|
||||
curves: [{
|
||||
modifiers: [],
|
||||
data: {
|
||||
keys: 0,
|
||||
values: values,
|
||||
easingMethod,
|
||||
easingMethods,
|
||||
interpolate,
|
||||
},
|
||||
}],
|
||||
});
|
||||
expect(clip.tracksCount).toBe(1);
|
||||
const track = Array.from(clip.tracks)[0] as RealTrack;
|
||||
expect(track).toBeInstanceOf(RealTrack);
|
||||
return track.channel.curve;
|
||||
}
|
||||
|
||||
test(`Easing methods: not specified`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.5],
|
||||
[1, 3, 5],
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.5]);
|
||||
expect(Array.from(curve.values())).toStrictEqual(createMultipleRealKeyframesWithoutTangent([1, 3, 5], RealInterpolationMode.LINEAR));
|
||||
});
|
||||
|
||||
describe(`Specified through ".easingMethod"`, () => {
|
||||
test(`null(linear)`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.8],
|
||||
[1, 3, 5],
|
||||
null,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual(createMultipleRealKeyframesWithoutTangent([1, 3, 5], RealInterpolationMode.LINEAR));
|
||||
});
|
||||
|
||||
test(`Time bezier`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.8],
|
||||
[1, 3, 5],
|
||||
[0.2, 0.3, 0.4, 0.5],
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.RIGHT,
|
||||
value: 1,
|
||||
rightTangent: 14.999999999999998,
|
||||
rightTangentWeight: 0.6013318551349163,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.BOTH,
|
||||
value: 3,
|
||||
leftTangent: 8.333333333333334,
|
||||
leftTangentWeight: 1.0071742649611337,
|
||||
rightTangent: 5.999999999999998,
|
||||
rightTangentWeight: 0.6082762530298218,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 5,
|
||||
tangentWeightMode: TangentWeightMode.LEFT,
|
||||
leftTangent: 3.3333333333333335,
|
||||
leftTangentWeight: 1.044030650891055,
|
||||
})]);
|
||||
});
|
||||
|
||||
test(`Easing method name: constant`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.8],
|
||||
[1, 3, 5],
|
||||
'constant',
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CONSTANT,
|
||||
value: 1,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CONSTANT,
|
||||
value: 3,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR, // Last frame never converted
|
||||
value: 5,
|
||||
})]);
|
||||
});
|
||||
|
||||
test(`Easing method name: linear`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.8],
|
||||
[1, 3, 5],
|
||||
'linear',
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 1,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 3,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 5,
|
||||
})]);
|
||||
});
|
||||
|
||||
test(`Easing method name: any other`, () => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.8],
|
||||
[1, 3, 5],
|
||||
'cubicInOut',
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.8]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 1,
|
||||
easingMethod: EasingMethod.CUBIC_IN_OUT,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 3,
|
||||
easingMethod: EasingMethod.CUBIC_IN_OUT,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR, // Last frame never converted
|
||||
value: 5,
|
||||
})]);
|
||||
});
|
||||
});
|
||||
|
||||
describe(`Specified through ".easingMethods"`, () => {
|
||||
test.each([
|
||||
[`Full array`, [null, [0.2, 0.3, 0.4, 0.5], null] as (LegacyEasingMethod | null)[]],
|
||||
[`Sparse array`, {
|
||||
1: [0.2, 0.3, 0.4, 0.5],
|
||||
} as Record<number, LegacyEasingMethod>],
|
||||
])(`%s`, (_, easingMethods) => {
|
||||
const curve = createClipWithEasingMethodsAndConvert(
|
||||
[0.1, 0.3, 0.5],
|
||||
[1, 3, 5],
|
||||
undefined,
|
||||
easingMethods,
|
||||
true,
|
||||
);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.3, 0.5]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 1,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.RIGHT,
|
||||
value: 3,
|
||||
rightTangent: 14.999999999999996,
|
||||
rightTangentWeight: 0.6013318551349163,
|
||||
}), createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 5,
|
||||
tangentWeightMode: TangentWeightMode.LEFT,
|
||||
leftTangent: 8.333333333333332,
|
||||
leftTangentWeight: 1.0071742649611337,
|
||||
})]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('Time bezier to tangent', () => {
|
||||
testTimeBezierCurveConversion({
|
||||
// t0: 0.0,
|
||||
// t1: 1.0,
|
||||
// v0: 0.0,
|
||||
// v1: 1.0,
|
||||
t0: 0.08333333333333333,
|
||||
v0: 3,
|
||||
t1: 0.18333333333333332,
|
||||
v1: 5,
|
||||
bezierPoints: [.04,.94,.53,.63],
|
||||
});
|
||||
|
||||
type TimeBezierTestCase = {
|
||||
t0: number;
|
||||
t1: number;
|
||||
v0: number;
|
||||
v1: number;
|
||||
bezierPoints: BezierControlPoints;
|
||||
};
|
||||
|
||||
function testTimeBezierCurveConversion (testCase: TimeBezierTestCase) {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[testCase.t0, ({
|
||||
value: testCase.v0,
|
||||
})],
|
||||
[testCase.t1, ({
|
||||
value: testCase.v1,
|
||||
})],
|
||||
]);
|
||||
timeBezierToTangents(
|
||||
testCase.bezierPoints,
|
||||
curve.getKeyframeTime(0),
|
||||
curve.getKeyframeValue(0),
|
||||
curve.getKeyframeTime(1),
|
||||
curve.getKeyframeValue(1),
|
||||
);
|
||||
|
||||
for (let inputRatio = 0.0; inputRatio <= 1.0; inputRatio += 0.01) {
|
||||
const ratio = bezierByTime(testCase.bezierPoints, inputRatio);
|
||||
const timeBezierResult = testCase.v0 + (testCase.v1 - testCase.v0) * ratio;
|
||||
const inputTime = testCase.t0 + inputRatio * (testCase.t1 - testCase.t0);
|
||||
const curveResult = curve.evaluate(inputTime);
|
||||
expect(timeBezierResult).toBeCloseTo(curveResult, 2);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function createClipWithLegacyData ({
|
||||
times,
|
||||
curves,
|
||||
commonTargets,
|
||||
}: {
|
||||
times?: number[][];
|
||||
curves?: LegacyClipCurve[];
|
||||
commonTargets?: LegacyCommonTarget[];
|
||||
}) {
|
||||
const clip = new AnimationClip();
|
||||
if (times) {
|
||||
clip.keys = times;
|
||||
}
|
||||
if (curves) {
|
||||
clip.curves = curves;
|
||||
}
|
||||
if (commonTargets) {
|
||||
clip.commonTargets = commonTargets;
|
||||
}
|
||||
clip.syncLegacyData();
|
||||
return clip;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { Node, RealKeyframeValue, Vec3 } from '../../cocos/core';
|
||||
import { ColorTrack, RealTrack, SizeTrack, TrackPath, VectorTrack } from '../../cocos/core/animation/animation';
|
||||
import { AnimationClip, searchForRootBonePathSymbol } from '../../cocos/core/animation/animation-clip';
|
||||
import { TargetPath } from '../../cocos/core/animation/target-path';
|
||||
|
||||
describe('Animation Clip', () => {
|
||||
describe('Evaluation', () => {
|
||||
describe('Ill-formed track path', () => {
|
||||
// test('Absent component', () => {
|
||||
// const errorMock = jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
// const clip = createClipWithPath([new ComponentPath('cc.MeshRenderer'), 'mesh']);
|
||||
// clip.createEvaluator({ target: new Node() });
|
||||
// expect(errorMock).toBeCalledTimes(1);
|
||||
// expect(errorMock.mock.calls[0][0]).toMatch(/ill-formed/i);
|
||||
// errorMock.mockRestore();
|
||||
// });
|
||||
|
||||
// test('Absent hierarchy', () => {
|
||||
// const errorMock = jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
// const clip = createClipWithPath([new HierarchyPath('/absent'), 'position']);
|
||||
// clip.createEvaluator({ target: new Node() });
|
||||
// expect(errorMock).toBeCalledTimes(1);
|
||||
// expect(errorMock.mock.calls[0][0]).toMatch(/ill-formed/i);
|
||||
// errorMock.mockRestore();
|
||||
// });
|
||||
|
||||
// test('Exception when bound', () => {
|
||||
// const errorMock = jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
// const clip = createClipWithPath(['property', 0]);
|
||||
// clip.createEvaluator({ target: new Node() });
|
||||
// expect(errorMock).toBeCalledTimes(1);
|
||||
// expect(errorMock.mock.calls[0][0]).toMatch(/ill-formed/i);
|
||||
// errorMock.mockRestore();
|
||||
// });
|
||||
|
||||
function createClipWithPath (path: TargetPath[]) {
|
||||
const clip = new AnimationClip();
|
||||
const track = new RealTrack();
|
||||
track.path = new TrackPath().hierarchy('Foo');
|
||||
clip.addTrack(track);
|
||||
return clip;
|
||||
}
|
||||
});
|
||||
|
||||
test('Root bone search', () => {
|
||||
function testWith(paths: string[]) {
|
||||
const clip = new AnimationClip();
|
||||
for (const path of paths) {
|
||||
const track = new VectorTrack();
|
||||
track.path = new TrackPath().hierarchy(path).property('position');
|
||||
clip.addTrack(track);
|
||||
}
|
||||
return clip[searchForRootBonePathSymbol]();
|
||||
}
|
||||
|
||||
expect(testWith([''])).toBe('');
|
||||
expect(testWith(['Root'])).toBe('Root');
|
||||
expect(testWith(['Root/Pelvis'])).toBe('Root/Pelvis');
|
||||
expect(testWith(['Root', 'Root/Pelvis'])).toBe('Root');
|
||||
expect(testWith(['Root', 'Root/Pelvis/Head'])).toBe('Root');
|
||||
expect(testWith(['Pelvis/Left Leg', 'Pelvis/Right Leg'])).toBe('');
|
||||
});
|
||||
|
||||
describe('Root motion', () => {
|
||||
const clip = new AnimationClip();
|
||||
clip.duration = 1.0;
|
||||
|
||||
const rootJointName = 'RootJoint';
|
||||
|
||||
const rootBoneTranslationTrack = new VectorTrack();
|
||||
{
|
||||
rootBoneTranslationTrack.componentsCount = 3;
|
||||
rootBoneTranslationTrack.path = new TrackPath().hierarchy(rootJointName).property('position');
|
||||
const [x, _y, _z] = rootBoneTranslationTrack.channels();
|
||||
x.curve.assignSorted([
|
||||
[0.4, ({ value: 0.4 })],
|
||||
[0.6, ({ value: 0.6 })],
|
||||
[0.8, ({ value: 0.8 })],
|
||||
]);
|
||||
}
|
||||
|
||||
clip.addTrack(rootBoneTranslationTrack);
|
||||
|
||||
const dummyRootNode = new Node();
|
||||
|
||||
const dummyRootJointNode = new Node(rootJointName);
|
||||
dummyRootNode.addChild(dummyRootJointNode);
|
||||
|
||||
const evaluation = clip.createEvaluator({
|
||||
target: dummyRootNode,
|
||||
pose: undefined,
|
||||
rootMotion: { },
|
||||
});
|
||||
|
||||
test('Never touch root joint', () => {
|
||||
dummyRootJointNode.setPosition(0.0, 0.0, 0.0);
|
||||
evaluation.evaluate(0.1);
|
||||
expect(Vec3.equals(dummyRootNode.position, new Vec3(0.0, 0.0, 0.0))).toBe(true);
|
||||
});
|
||||
|
||||
test('In same duration: Motion not changed', () => {
|
||||
dummyRootJointNode.setPosition(0.0, 0.0, 0.0);
|
||||
evaluation.evaluateRootMotion(0.2, 0.1);
|
||||
expect(Vec3.equals(dummyRootJointNode.position, new Vec3())).toBe(true);
|
||||
});
|
||||
|
||||
test('In same duration: Motion changed ', () => {
|
||||
dummyRootJointNode.setPosition(0.0, 0.0, 0.0);
|
||||
evaluation.evaluateRootMotion(0.5, 0.2);
|
||||
expect(Vec3.equals(dummyRootJointNode.position, new Vec3(0.2))).toBe(true);
|
||||
});
|
||||
|
||||
test('Motion extended to next duration ', () => {
|
||||
dummyRootJointNode.setPosition(0.0, 0.0, 0.0);
|
||||
evaluation.evaluateRootMotion(0.5, 0.7);
|
||||
expect(Vec3.equals(dummyRootJointNode.position, new Vec3(0.3))).toBe(true);
|
||||
});
|
||||
|
||||
test('Motion extended to next multiple duration ', () => {
|
||||
dummyRootJointNode.setPosition(0.0, 0.0, 0.0);
|
||||
evaluation.evaluateRootMotion(0.5, 3.2);
|
||||
expect(Vec3.equals(dummyRootJointNode.position, new Vec3(1.4))).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(`Tracks`, () => {
|
||||
test('Vector track', () => {
|
||||
const vectorTrack = new VectorTrack();
|
||||
expect(vectorTrack.channels()).toHaveLength(4);
|
||||
expect(vectorTrack.channels()[0].name).toBe('X');
|
||||
expect(vectorTrack.channels()[1].name).toBe('Y');
|
||||
expect(vectorTrack.channels()[2].name).toBe('Z');
|
||||
expect(vectorTrack.channels()[3].name).toBe('W');
|
||||
});
|
||||
|
||||
test('Color track', () => {
|
||||
const colorTrack = new ColorTrack();
|
||||
expect(colorTrack.channels()).toHaveLength(4);
|
||||
expect(colorTrack.channels()[0].name).toBe('Red');
|
||||
expect(colorTrack.channels()[1].name).toBe('Green');
|
||||
expect(colorTrack.channels()[2].name).toBe('Blue');
|
||||
expect(colorTrack.channels()[3].name).toBe('Alpha');
|
||||
});
|
||||
|
||||
test('Size track', () => {
|
||||
const sizeTrack = new SizeTrack();
|
||||
expect(sizeTrack.channels()).toHaveLength(2);
|
||||
expect(sizeTrack.channels()[0].name).toBe('Width');
|
||||
expect(sizeTrack.channels()[1].name).toBe('Height');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { js, Node, Component, Vec3 } from '../../cocos/core';
|
||||
import { js, Node, Component, Vec3, RealKeyframeValue } from '../../cocos/core';
|
||||
import { AnimationClip, AnimationState, AnimationManager } from '../../cocos/core/animation';
|
||||
import { ComponentPath, HierarchyPath } from '../../cocos/core/animation/animation';
|
||||
import { ComponentPath, HierarchyPath, IValueProxyFactory, VectorTrack } from '../../cocos/core/animation/animation';
|
||||
import { ccclass } from 'cc.decorator';
|
||||
|
||||
test('Common target', () => {
|
||||
@@ -115,6 +115,84 @@ test('Common targets that modify eulerAngles', () => {
|
||||
mockInstance.mockRestore();
|
||||
});
|
||||
|
||||
describe('Custom track setter', () => {
|
||||
class Target {
|
||||
public setValue(value: Target['_value']) { Vec3.copy(this._value, value); }
|
||||
public getValue() { return this._value; }
|
||||
private _value = { x: 0, y: 0, z: 0 };
|
||||
}
|
||||
|
||||
const valueProxyWithOnlySet: IValueProxyFactory = {
|
||||
forTarget: (target: Target) => {
|
||||
return {
|
||||
set: (value: Target['_value']) => { target.setValue(value) },
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const valueProxyWithGetSet: IValueProxyFactory = {
|
||||
forTarget: (target: Target) => {
|
||||
return {
|
||||
set: (value: Target['_value']) => { target.setValue(value) },
|
||||
get: () => target.getValue(),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
test('get() got not called if non of channels is empty', () => {
|
||||
const target = new Target();
|
||||
const mockGetValue = target.getValue = jest.fn(target.getValue);
|
||||
const mockSetValue = target.setValue = jest.fn(target.setValue);
|
||||
|
||||
const track = new VectorTrack();
|
||||
track.proxy = valueProxyWithGetSet;
|
||||
track.channels().forEach(({ curve }) => {
|
||||
curve.assignSorted([[0.0, ({ value: 0.0 })]]);
|
||||
});
|
||||
|
||||
const clip = new AnimationClip();
|
||||
clip.addTrack(track);
|
||||
const clipEval = clip.createEvaluator({
|
||||
target,
|
||||
});
|
||||
clipEval.evaluate(0.0);
|
||||
expect(mockGetValue).not.toBeCalled();
|
||||
expect(mockSetValue).toBeCalled();
|
||||
});
|
||||
|
||||
test('get() got called if any of channels is empty', () => {
|
||||
const target = new Target();
|
||||
const mockGetValue = target.getValue = jest.fn(target.getValue);
|
||||
const mockSetValue = target.setValue = jest.fn(target.setValue);
|
||||
|
||||
const track = new VectorTrack();
|
||||
track.proxy = valueProxyWithGetSet;
|
||||
const clip = new AnimationClip();
|
||||
clip.addTrack(track);
|
||||
const clipEval = clip.createEvaluator({
|
||||
target,
|
||||
});
|
||||
clipEval.evaluate(0.0);
|
||||
expect(mockGetValue).toBeCalled();
|
||||
expect(mockSetValue).toBeCalled();
|
||||
});
|
||||
|
||||
test('If get() is not defined, the default channel value would be used', () => {
|
||||
const target = new Target();
|
||||
const mockSetValue = target.setValue = jest.fn(target.setValue);
|
||||
|
||||
const track = new VectorTrack();
|
||||
track.proxy = valueProxyWithOnlySet;
|
||||
const clip = new AnimationClip();
|
||||
clip.addTrack(track);
|
||||
const clipEval = clip.createEvaluator({
|
||||
target,
|
||||
});
|
||||
clipEval.evaluate(0.0);
|
||||
expect(mockSetValue).toBeCalled();
|
||||
});
|
||||
});
|
||||
|
||||
test('animation state', () => {
|
||||
const animationManager = new AnimationManager();
|
||||
const mockInstance = jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
|
||||
import { AnimCurve, RatioSampler, sampleAnimationCurve } from '../../cocos/core/animation/animation-curve';
|
||||
import { ComponentPath, TargetPath, HierarchyPath } from '../../cocos/core/animation/target-path';
|
||||
import { Node } from '../../cocos/core/scene-graph';
|
||||
import { createBoundTarget } from '../../cocos/core/animation/bound-target';
|
||||
|
||||
test('sample from animation curve', () => {
|
||||
const curve = new AnimCurve({
|
||||
values: [0, 1, 2, 3],
|
||||
}, 1);
|
||||
const sampler = new RatioSampler([
|
||||
0, 0.3, 0.6, 1.0
|
||||
]);
|
||||
|
||||
expect(sampleAnimationCurve(curve, sampler, 0)).toBe(0);
|
||||
expect(sampleAnimationCurve(curve, sampler, 0.3)).toBe(1);
|
||||
expect(sampleAnimationCurve(curve, sampler, 0.6)).toBe(2);
|
||||
expect(sampleAnimationCurve(curve, sampler, 1.0)).toBe(3);
|
||||
});
|
||||
|
||||
test('Erroneous target path', () => {;
|
||||
expect(createBoundTarget(new Node("TestNode"), [new ComponentPath('cc.MeshRenderer'), 'position'])).toBeNull();
|
||||
expect(createBoundTarget(new Node("TestNode"), [new HierarchyPath('/absent'), 'position'])).toBeNull();
|
||||
expect(createBoundTarget(Object.create(null), ['property', 0])).toBeNull();
|
||||
expect(createBoundTarget([], [1, 0])).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
|
||||
import { removeLinearKeys, removeTrivialKeys } from '../../cocos/core/animation/compression';
|
||||
|
||||
describe('Curve compression', () => {
|
||||
describe('Remove linear keys', () => {
|
||||
test('Curves with only zero/one/two keys are not effected', () => {
|
||||
expect(runRemoveLinearKeys([], [])).toBeRemovedWith([]);
|
||||
expect(runRemoveLinearKeys([0.3], [0.4])).toBeRemovedWith([]);
|
||||
expect(runRemoveLinearKeys([0.3, 0.4], [4.0, 5.0])).toBeRemovedWith([]);
|
||||
});
|
||||
|
||||
test('Linear', () => {
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5], [3.0, 4.0, 5.0])).toBeRemovedWith([1]);
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5, 0.7], [3.0, 4.0, 5.0, 10.0])).toBeRemovedWith([1]);
|
||||
});
|
||||
|
||||
test('Successive linear', () => {
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5, 0.6], [3.0, 4.0, 5.0, 6.0])).toBeRemovedWith([1, 2]);
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5, 0.6, 0.7], [3.0, 4.0, 5.0, 6.0, 10.0])).toBeRemovedWith([1, 2]);
|
||||
});
|
||||
|
||||
test('Max error', () => {
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5], [3.0, 4.0002, 5.0], 1e-3)).toBeRemovedWith([1]);
|
||||
expect(runRemoveLinearKeys([0.3, 0.4, 0.5], [3.0, 4.002, 5.0], 1e-3)).toBeRemovedWith([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Remove trivial keys', () => {
|
||||
test('Zero/One length', () => {
|
||||
expect(runRemoveTrivialKeys([], [])).toBeRemovedWith([]);
|
||||
expect(runRemoveTrivialKeys([0.3], [0.4])).toBeRemovedWith([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
type CompressionResult = ReturnType<typeof runCompression>;
|
||||
|
||||
function runCompression<TArgs extends any[]>(
|
||||
keys: number[],
|
||||
values: number[],
|
||||
fn: (keys: number[], values: number[], ...args: TArgs) => { keys: number[], values: number[] },
|
||||
...args: TArgs
|
||||
) {
|
||||
const { keys: newKeys, values: newValues } = fn(keys, values, ...args);
|
||||
return {
|
||||
keys, values,
|
||||
newKeys, newValues,
|
||||
};
|
||||
}
|
||||
|
||||
function runRemoveLinearKeys (keys: number[], values: number[], maxError?: number) {
|
||||
return runCompression(
|
||||
keys,
|
||||
values,
|
||||
removeLinearKeys,
|
||||
maxError,
|
||||
);
|
||||
}
|
||||
|
||||
function runRemoveTrivialKeys (keys: number[], values: number[], maxError?: number) {
|
||||
return runCompression(
|
||||
keys,
|
||||
values,
|
||||
removeTrivialKeys,
|
||||
maxError,
|
||||
);
|
||||
}
|
||||
|
||||
expect.extend({
|
||||
toBeRemovedWith(received: CompressionResult, removals: number[]): jest.CustomMatcherResult {
|
||||
const { keys, values, newKeys, newValues } = received;
|
||||
const actualRemovals = keys.map((_, index) => index).filter((index) => !newKeys.includes(keys[index]));
|
||||
return {
|
||||
pass: actualRemovals.length === removals.length &&
|
||||
actualRemovals.every((actualRemoval, index) => actualRemoval === removals[index]),
|
||||
message: () =>
|
||||
`Expected removals: ${removals.join(', ')}\n` +
|
||||
`Actual removals: ${actualRemovals.join(', ')}`,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
declare global {
|
||||
namespace jest {
|
||||
interface Matchers<R> {
|
||||
toBeRemovedWith(expected: number[]): CustomMatcherResult
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,27 +117,27 @@ describe('Mesh Renderer', () => {
|
||||
// }
|
||||
// });
|
||||
|
||||
function createMeshRenderer (): MeshRenderer {
|
||||
const node = new Node();
|
||||
const meshRenderer = node.addComponent(MeshRenderer);
|
||||
// @ts-expect-error Error
|
||||
return meshRenderer;
|
||||
}
|
||||
// function createMeshRenderer (): MeshRenderer {
|
||||
// const node = new Node();
|
||||
// const meshRenderer = node.addComponent(MeshRenderer);
|
||||
// // @ts-expect-error Error
|
||||
// return meshRenderer;
|
||||
// }
|
||||
|
||||
function createMeshWithShapeCounts (shapesCounts: number[]): Mesh {
|
||||
const mesh = new Mesh();
|
||||
mesh.struct.morph = {
|
||||
subMeshMorphs: shapesCounts.map((shapeCount) => {
|
||||
return {
|
||||
targets: Array.from({ length: shapeCount }, (_, index) => {
|
||||
return {
|
||||
displacements: [],
|
||||
};
|
||||
}),
|
||||
attributes: [],
|
||||
};
|
||||
}),
|
||||
};
|
||||
return mesh;
|
||||
}
|
||||
// function createMeshWithShapeCounts (shapesCounts: number[]): Mesh {
|
||||
// const mesh = new Mesh();
|
||||
// mesh.struct.morph = {
|
||||
// subMeshMorphs: shapesCounts.map((shapeCount) => {
|
||||
// return {
|
||||
// targets: Array.from({ length: shapeCount }, (_, index) => {
|
||||
// return {
|
||||
// displacements: [],
|
||||
// };
|
||||
// }),
|
||||
// attributes: [],
|
||||
// };
|
||||
// }),
|
||||
// };
|
||||
// return mesh;
|
||||
// }
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
import { WrapModeMask } from '../../../cocos/core/animation/types';
|
||||
import { ExtrapolationMode, RealCurve, RealInterpolationMode, RealKeyframeValue, TangentWeightMode } from '../../../cocos/core/curves';
|
||||
import { AnimationCurve, Keyframe } from '../../../cocos/core/geometry/curve';
|
||||
|
||||
describe('geometry.AnimationCurve', () => {
|
||||
describe('Constructor', () => {
|
||||
test('new AnimationCurve()', () => {
|
||||
const curve = new AnimationCurve();
|
||||
expect(curve.keyFrames).toStrictEqual([
|
||||
createLegacyKeyframe({ time: 0.0, value: 1.0 }),
|
||||
createLegacyKeyframe({ time: 1.0, value: 1.0 }),
|
||||
] as Keyframe[]);
|
||||
});
|
||||
|
||||
test('new AnimationCurve(keyframes)', () => {
|
||||
const curve = new AnimationCurve([
|
||||
createLegacyKeyframe({ time: 2.0, value: 8.0, inTangent: -3.3, outTangent: 1.75 }),
|
||||
createLegacyKeyframe({ time: 3.0, value: 9.0, inTangent: 4.2, outTangent: -7.1 }),
|
||||
]);
|
||||
expect(curve.keyFrames).toStrictEqual([
|
||||
createLegacyKeyframe({ time: 2.0, value: 8.0, inTangent: -3.3, outTangent: 1.75 }),
|
||||
createLegacyKeyframe({ time: 3.0, value: 9.0, inTangent: 4.2, outTangent: -7.1 }),
|
||||
] as Keyframe[]);
|
||||
});
|
||||
|
||||
test('new AnimationCurve(realCurve)(INTERNAL)', () => {
|
||||
const realCurve = new RealCurve();
|
||||
realCurve.assignSorted([
|
||||
// Non weighted tangent
|
||||
[0.1, ({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: 0.1,
|
||||
leftTangent: 0.2,
|
||||
rightTangent: 0.3,
|
||||
})],
|
||||
// Non cubic keyframe
|
||||
[0.2, ({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 0.1,
|
||||
})],
|
||||
// Weighted tangent
|
||||
[0.3, ({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: 0.1,
|
||||
leftTangent: 0.2,
|
||||
rightTangent: 0.3,
|
||||
tangentWeightMode: TangentWeightMode.RIGHT,
|
||||
leftTangentWeight: 0.4,
|
||||
rightTangentWeight: 0.5,
|
||||
})],
|
||||
]);
|
||||
|
||||
const geometryCurve = new AnimationCurve(realCurve);
|
||||
expect(geometryCurve.keyFrames).toStrictEqual([
|
||||
createLegacyKeyframe({ time: 0.1, value: 0.1, inTangent: 0.2, outTangent: 0.3 }),
|
||||
createLegacyKeyframe({ time: 0.2, value: 0.1, inTangent: 0.0, outTangent: 0.0 }),
|
||||
createLegacyKeyframe({ time: 0.3, value: 0.1, inTangent: 0.2, outTangent: 0.3 }),
|
||||
] as Keyframe[]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ extrapolationMode: ExtrapolationMode.LOOP, expected: WrapModeMask.Loop },
|
||||
{ extrapolationMode: ExtrapolationMode.PING_PONG, expected: WrapModeMask.PingPong },
|
||||
{ extrapolationMode: ExtrapolationMode.CLAMP, expected: WrapModeMask.Clamp },
|
||||
{ extrapolationMode: ExtrapolationMode.LINEAR, expected: WrapModeMask.Clamp },
|
||||
])(`new AnimationCurve(realCurve)(INTERNAL): conversion of extrapolation mode $extrapolationMode`, ({ extrapolationMode, expected }) => {
|
||||
const realCurve = new RealCurve();
|
||||
realCurve.preExtrapolation = extrapolationMode;
|
||||
realCurve.postExtrapolation = extrapolationMode;
|
||||
const geometryCurve = new AnimationCurve(realCurve);
|
||||
expect(geometryCurve.preWrapMode).toStrictEqual(expected);
|
||||
expect(geometryCurve.postWrapMode).toStrictEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ wrapMode: WrapModeMask.Clamp, extrapolationMode: ExtrapolationMode.CLAMP, },
|
||||
{ wrapMode: WrapModeMask.Loop, extrapolationMode: ExtrapolationMode.LOOP, },
|
||||
{ wrapMode: WrapModeMask.PingPong, extrapolationMode: ExtrapolationMode.PING_PONG, },
|
||||
])(`Wrap mode $wrapMode`, ({ wrapMode, extrapolationMode }) => {
|
||||
const curve = new AnimationCurve();
|
||||
|
||||
curve.preWrapMode = wrapMode;
|
||||
expect(curve.preWrapMode).toStrictEqual(wrapMode);
|
||||
expect(curve._internalCurve.preExtrapolation).toStrictEqual(extrapolationMode);
|
||||
|
||||
curve.postWrapMode = wrapMode;
|
||||
expect(curve.postWrapMode).toStrictEqual(wrapMode);
|
||||
expect(curve._internalCurve.postExtrapolation).toStrictEqual(extrapolationMode);
|
||||
});
|
||||
|
||||
test(`Add key`, () => {
|
||||
const curve = new AnimationCurve();
|
||||
|
||||
// Clear
|
||||
curve.addKey(null);
|
||||
expect(curve.keyFrames).toStrictEqual([]);
|
||||
|
||||
curve.addKey(createLegacyKeyframe({
|
||||
time: 0.1,
|
||||
value: 0.2,
|
||||
inTangent: 0.3,
|
||||
outTangent: 0.4,
|
||||
}));
|
||||
expect(curve.keyFrames).toStrictEqual([createLegacyKeyframe({
|
||||
time: 0.1,
|
||||
value: 0.2,
|
||||
inTangent: 0.3,
|
||||
outTangent: 0.4,
|
||||
})]);
|
||||
|
||||
// Clear again
|
||||
curve.addKey(null);
|
||||
expect(curve.keyFrames).toStrictEqual([]);
|
||||
});
|
||||
|
||||
test('Keyframes', () => {
|
||||
const curve = new AnimationCurve();
|
||||
|
||||
curve.keyFrames = [createLegacyKeyframe({
|
||||
time: 0.1,
|
||||
value: 0.2,
|
||||
inTangent: 0.3,
|
||||
outTangent: 0.4,
|
||||
}), createLegacyKeyframe({
|
||||
time: 0.5,
|
||||
value: 0.6,
|
||||
inTangent: 0.7,
|
||||
outTangent: 0.8,
|
||||
})];
|
||||
|
||||
expect(curve.keyFrames).toStrictEqual([createLegacyKeyframe({
|
||||
time: 0.1,
|
||||
value: 0.2,
|
||||
inTangent: 0.3,
|
||||
outTangent: 0.4,
|
||||
}), createLegacyKeyframe({
|
||||
time: 0.5,
|
||||
value: 0.6,
|
||||
inTangent: 0.7,
|
||||
outTangent: 0.8,
|
||||
})]);
|
||||
|
||||
curve._internalCurve.clear();
|
||||
expect(curve.keyFrames).toStrictEqual([]);
|
||||
|
||||
curve._internalCurve.assignSorted([
|
||||
// Non weighted tangent
|
||||
[0.1, ({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: 0.1,
|
||||
leftTangent: 0.2,
|
||||
rightTangent: 0.3,
|
||||
})],
|
||||
// Non cubic keyframe
|
||||
[0.2, ({
|
||||
interpolationMode: RealInterpolationMode.LINEAR,
|
||||
value: 0.1,
|
||||
})],
|
||||
// Weighted tangent
|
||||
[0.3, ({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
value: 0.1,
|
||||
leftTangent: 0.2,
|
||||
rightTangent: 0.3,
|
||||
tangentWeightMode: TangentWeightMode.RIGHT,
|
||||
leftTangentWeight: 0.4,
|
||||
rightTangentWeight: 0.5,
|
||||
})],
|
||||
]);
|
||||
expect(curve.keyFrames).toStrictEqual([
|
||||
createLegacyKeyframe({ time: 0.1, value: 0.1, inTangent: 0.2, outTangent: 0.3 }),
|
||||
createLegacyKeyframe({ time: 0.2, value: 0.1, inTangent: 0.0, outTangent: 0.0 }),
|
||||
createLegacyKeyframe({ time: 0.3, value: 0.1, inTangent: 0.2, outTangent: 0.3 }),
|
||||
] as Keyframe[]);
|
||||
});
|
||||
});
|
||||
|
||||
function createLegacyKeyframe ({
|
||||
time,
|
||||
value,
|
||||
inTangent = 0.0,
|
||||
outTangent = 0.0,
|
||||
}: {
|
||||
time: number,
|
||||
value: number;
|
||||
inTangent?: number;
|
||||
outTangent?: number;
|
||||
}) {
|
||||
const keyFrame = new Keyframe();
|
||||
keyFrame.time = time;
|
||||
keyFrame.value = value;
|
||||
keyFrame.inTangent = inTangent;
|
||||
keyFrame.outTangent = outTangent;
|
||||
return keyFrame;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { EasingMethod, RealCurve, RealInterpolationMode, RealKeyframeValue, TangentWeightMode } from "../../cocos/core/curves/curve";
|
||||
|
||||
export function createRealKeyframeValueLike (value: Partial<RealKeyframeValue>): RealKeyframeValue {
|
||||
const curve = new RealCurve();
|
||||
// return {
|
||||
// interpolationMode: RealInterpolationMode.LINEAR,
|
||||
// tangentWeightMode: TangentWeightMode.NONE,
|
||||
// value: 0.0,
|
||||
// leftTangent: 0.0,
|
||||
// leftTangentWeight: 0.0,
|
||||
// rightTangent: 0.0,
|
||||
// rightTangentWeight: 0.0,
|
||||
// easingMethod: EasingMethod.LINEAR,
|
||||
// ...value,
|
||||
// };
|
||||
return curve.getKeyframeValue(curve.addKeyFrame(0.0, value));
|
||||
}
|
||||
|
||||
export function createMultipleRealKeyframesWithoutTangent (values: number[], interpolationMode: RealInterpolationMode): RealKeyframeValue[] {
|
||||
return values.map((value) => {
|
||||
return createRealKeyframeValueLike({
|
||||
value,
|
||||
interpolationMode,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { editorExtrasTag, toRadian } from '../../cocos/core';
|
||||
import { RealCurve, RealInterpolationMode } from '../../cocos/core/curves';
|
||||
import { EasingMethod, RealKeyframeValue } from '../../cocos/core/curves/curve';
|
||||
import { ExtrapolationMode, TangentWeightMode } from '../../cocos/core/curves/real-curve-param';
|
||||
import { createRealKeyframeValueLike } from './curve-test-utils';
|
||||
import { serializeAndDeserialize } from './serialize-and-deserialize-curve';
|
||||
|
||||
describe('Curve', () => {
|
||||
test('assign sorted', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [
|
||||
realKeyframeWithoutTangent(0.4),
|
||||
realKeyframeWithoutTangent(0.5),
|
||||
realKeyframeWithoutTangent(0.6),
|
||||
]);
|
||||
|
||||
// Assign empty(keys, values)
|
||||
curve.assignSorted([], []);
|
||||
expect(curve.keyFramesCount).toBe(0);
|
||||
|
||||
// Assign empty(frames)
|
||||
curve.assignSorted([]);
|
||||
expect(curve.keyFramesCount).toBe(0);
|
||||
|
||||
// Assign(keys, values), values can be number of partial RealKeyframeValue
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [-3.6, { value: 2.7 }, { value: 3.8, interpolationMode: RealInterpolationMode.CUBIC }]);
|
||||
expect(Array.from(curve.times())).toStrictEqual([0.1, 0.2, 0.3]);
|
||||
expect(Array.from(curve.values())).toStrictEqual([
|
||||
createRealKeyframeValueLike({ value: -3.6 }),
|
||||
createRealKeyframeValueLike({ value: 2.7 }),
|
||||
createRealKeyframeValueLike({ value: 3.8, interpolationMode: RealInterpolationMode.CUBIC }),
|
||||
]);
|
||||
|
||||
// The count of keys and values should be same, if not, the behavior is undefined.
|
||||
// In test mode, assertion error would be thrown.
|
||||
expect(() => curve.assignSorted([0.1, 0.2], [])).toThrow();
|
||||
|
||||
// Keys should be sorted, if not, the behavior is undefined.
|
||||
// In test mode, assertion error would be thrown.
|
||||
expect(() => curve.assignSorted(
|
||||
[0.2, 0.1],
|
||||
[realKeyframeWithoutTangent(0.4), realKeyframeWithoutTangent(0.5)],
|
||||
)).toThrow();
|
||||
expect(() => curve.assignSorted([
|
||||
[0.2, realKeyframeWithoutTangent(0.4)],
|
||||
[0.1, realKeyframeWithoutTangent(0.5)],
|
||||
])).toThrow();
|
||||
});
|
||||
|
||||
describe('serialization', () => {
|
||||
test('Normal', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [
|
||||
({ value: 0.4, rightTangent: 0.0, leftTangent: 0.0, interpolationMode: RealInterpolationMode.CONSTANT }),
|
||||
({ value: 0.5, rightTangent: 0.0, leftTangent: 0.0, interpolationMode: RealInterpolationMode.LINEAR }),
|
||||
({
|
||||
value: 0.6,
|
||||
rightTangent: 0.487,
|
||||
rightTangentWeight: 0.2,
|
||||
leftTangent: 0.4598,
|
||||
leftTangentWeight: 0.32,
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.BOTH,
|
||||
easingMethod: EasingMethod.QUAD_OUT,
|
||||
[editorExtrasTag]: { 'foo': 'bar' },
|
||||
}),
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, RealCurve), curve);
|
||||
});
|
||||
|
||||
test('Optimized for linear curve', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [
|
||||
realKeyframeWithoutTangent(0.4),
|
||||
realKeyframeWithoutTangent(0.5),
|
||||
realKeyframeWithoutTangent(0.6),
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, RealCurve), curve);
|
||||
});
|
||||
|
||||
test('Optimized for constant curve', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [
|
||||
realKeyframeWithoutTangent(0.4, RealInterpolationMode.CONSTANT),
|
||||
realKeyframeWithoutTangent(0.5, RealInterpolationMode.CONSTANT),
|
||||
realKeyframeWithoutTangent(0.6, RealInterpolationMode.CONSTANT),
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, RealCurve), curve);
|
||||
});
|
||||
});
|
||||
|
||||
test('Default keyframe value', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.addKeyFrame(0, {});
|
||||
const keyframeValue = curve.getKeyframeValue(0);
|
||||
expect(keyframeValue.value).toBe(0.0);
|
||||
expect(keyframeValue.interpolationMode).toBe(RealInterpolationMode.LINEAR);
|
||||
expect(keyframeValue.rightTangent).toBe(0.0);
|
||||
expect(keyframeValue.rightTangentWeight).toBe(0.0);
|
||||
expect(keyframeValue.leftTangent).toBe(0.0);
|
||||
expect(keyframeValue.leftTangentWeight).toBe(0.0);
|
||||
expect(keyframeValue.easingMethod).toBe(EasingMethod.LINEAR);
|
||||
});
|
||||
|
||||
describe('Evaluation', () => {
|
||||
test('Empty curve', () => {
|
||||
const curve = new RealCurve();
|
||||
expect(curve.evaluate(12.34)).toBe(0.0);
|
||||
});
|
||||
|
||||
test('Interpolation mode: constant', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.2, createRealKeyframeValueLike({ value: 0.7, interpolationMode: RealInterpolationMode.CONSTANT, })],
|
||||
[0.4, createRealKeyframeValueLike({ value: 0.8, interpolationMode: RealInterpolationMode.LINEAR, })],
|
||||
]);
|
||||
expect(curve.evaluate(0.28)).toBe(0.7);
|
||||
});
|
||||
|
||||
test('Interpolation mode: linear', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.2, createRealKeyframeValueLike({ value: 0.7, interpolationMode: RealInterpolationMode.LINEAR, })],
|
||||
[0.4, createRealKeyframeValueLike({ value: 0.8, interpolationMode: RealInterpolationMode.CONSTANT, })],
|
||||
]);
|
||||
expect(curve.evaluate(0.28)).toBeCloseTo(0.74);
|
||||
});
|
||||
|
||||
test('Interpolation mode: cubic; Both weights are unused', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.2, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.NONE,
|
||||
value: 0.7,
|
||||
rightTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
[0.4, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.NONE,
|
||||
value: 0.8,
|
||||
leftTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
]);
|
||||
expect(curve.evaluate(0.28)).toBeCloseTo(0.74074, 5);
|
||||
});
|
||||
|
||||
test('Interpolation mode: cubic; Start weight is used', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.2, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.RIGHT,
|
||||
value: 0.7,
|
||||
rightTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
[0.4, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.NONE,
|
||||
value: 0.8,
|
||||
leftTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
]);
|
||||
expect(curve.evaluate(0.28)).toBeCloseTo(0.73799, 5);
|
||||
});
|
||||
|
||||
test('Interpolation mode: cubic; End weight is used', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([
|
||||
[0.2, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.NONE,
|
||||
value: 0.7,
|
||||
rightTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
[0.4, createRealKeyframeValueLike({
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
tangentWeightMode: TangentWeightMode.LEFT,
|
||||
value: 0.8,
|
||||
leftTangent: Math.tan(toRadian(30.0)),
|
||||
})],
|
||||
]);
|
||||
expect(curve.evaluate(0.28)).toBeCloseTo(0.74229, 5);
|
||||
});
|
||||
|
||||
test('Extrapolation mode: clamp', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.preExtrapolation = ExtrapolationMode.CLAMP;
|
||||
curve.postExtrapolation = ExtrapolationMode.CLAMP;
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
]);
|
||||
// Fall back to clamp
|
||||
expect(curve.evaluate(0.05)).toBeCloseTo(5.0);
|
||||
expect(curve.evaluate(0.46)).toBeCloseTo(5.0);
|
||||
});
|
||||
|
||||
test('Extrapolation mode: linear', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.preExtrapolation = ExtrapolationMode.LINEAR;
|
||||
curve.postExtrapolation = ExtrapolationMode.LINEAR;
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
[0.3, ({ value: 3.14 })],
|
||||
]);
|
||||
expect(curve.evaluate(0.05)).toBeCloseTo(7.79);
|
||||
expect(curve.evaluate(-102.4)).toBeCloseTo(1913.36);
|
||||
expect(curve.evaluate(0.46)).toBeCloseTo(0.164);
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
]);
|
||||
// Fall back to clamp
|
||||
expect(curve.evaluate(0.05)).toBeCloseTo(5.0);
|
||||
expect(curve.evaluate(0.46)).toBeCloseTo(5.0);
|
||||
});
|
||||
|
||||
test('Extrapolation mode: loop', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.preExtrapolation = ExtrapolationMode.LOOP;
|
||||
curve.postExtrapolation = ExtrapolationMode.LOOP;
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
[0.36, ({ value: 3.14 })],
|
||||
]);
|
||||
expect(curve.evaluate(-2.7)).toBeCloseTo(curve.evaluate(0.34));
|
||||
expect(curve.evaluate(4.6)).toBeCloseTo(curve.evaluate(0.28));
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
]);
|
||||
// Fall back to clamp
|
||||
expect(curve.evaluate(0.05)).toBeCloseTo(5.0);
|
||||
expect(curve.evaluate(0.46)).toBeCloseTo(5.0);
|
||||
});
|
||||
|
||||
test('Extrapolation mode: ping-pong', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.preExtrapolation = ExtrapolationMode.PING_PONG;
|
||||
curve.postExtrapolation = ExtrapolationMode.PING_PONG;
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
[0.36, ({ value: 3.14 })],
|
||||
]);
|
||||
expect(curve.evaluate(-2.7)).toBeCloseTo(curve.evaluate(0.22));
|
||||
expect(curve.evaluate(4.6)).toBeCloseTo(curve.evaluate(0.28));
|
||||
expect(curve.evaluate(4.77)).toBeCloseTo(curve.evaluate(0.29));
|
||||
|
||||
curve.assignSorted([
|
||||
[0.2, ({ value: 5.0 })],
|
||||
]);
|
||||
// Fall back to clamp
|
||||
expect(curve.evaluate(0.05)).toBeCloseTo(5.0);
|
||||
expect(curve.evaluate(0.46)).toBeCloseTo(5.0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function realKeyframeWithoutTangent (value: number, interpolationMode: RealInterpolationMode = RealInterpolationMode.LINEAR): Partial<RealKeyframeValue> {
|
||||
return createRealKeyframeValueLike({
|
||||
value,
|
||||
interpolationMode,
|
||||
});
|
||||
}
|
||||
|
||||
function compareCurves (left: RealCurve, right: RealCurve, numDigits = 2) {
|
||||
expect(left.keyFramesCount).toBe(right.keyFramesCount);
|
||||
for (let iKeyframe = 0; iKeyframe < left.keyFramesCount; ++iKeyframe) {
|
||||
expect(left.getKeyframeTime(iKeyframe)).toBeCloseTo(right.getKeyframeTime(iKeyframe), numDigits);
|
||||
const leftKeyframeValue = left.getKeyframeValue(iKeyframe);
|
||||
const rightKeyframeValue = right.getKeyframeValue(iKeyframe);
|
||||
expect(leftKeyframeValue.value).toBeCloseTo(rightKeyframeValue.value, numDigits);
|
||||
expect(leftKeyframeValue.rightTangent).toBeCloseTo(rightKeyframeValue.rightTangent, numDigits);
|
||||
expect(leftKeyframeValue.rightTangentWeight).toBeCloseTo(rightKeyframeValue.rightTangentWeight, numDigits);
|
||||
expect(leftKeyframeValue.leftTangent).toBeCloseTo(rightKeyframeValue.leftTangent, numDigits);
|
||||
expect(leftKeyframeValue.leftTangentWeight).toBeCloseTo(rightKeyframeValue.leftTangentWeight, numDigits);
|
||||
expect(leftKeyframeValue.interpolationMode).toStrictEqual(rightKeyframeValue.interpolationMode);
|
||||
expect(leftKeyframeValue.easingMethod).toStrictEqual(rightKeyframeValue.easingMethod);
|
||||
expect(leftKeyframeValue[editorExtrasTag]).toStrictEqual(rightKeyframeValue[editorExtrasTag]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
|
||||
import { ExtrapolationMode, RealCurve, RealInterpolationMode } from '../../cocos/core/curves/curve';
|
||||
import { KeySharedQuatCurves, KeySharedRealCurves } from '../../cocos/core/curves/keys-shared-curves';
|
||||
import { QuatCurve, QuatInterpolationMode } from '../../cocos/core/curves/quat-curve';
|
||||
import { Quat } from '../../cocos/core/math';
|
||||
|
||||
describe('Keys shared real curves', () => {
|
||||
test('Enabling', () => {
|
||||
{
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([[0.1, ({
|
||||
value: 0.1,
|
||||
})]]);
|
||||
expect(KeySharedRealCurves.allowedForCurve(curve)).toBe(true);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([[0.1, ({
|
||||
value: 0.1,
|
||||
})]]);
|
||||
curve.postExtrapolation = ExtrapolationMode.LOOP;
|
||||
expect(KeySharedRealCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([[0.1, ({
|
||||
value: 0.1,
|
||||
})]]);
|
||||
curve.preExtrapolation = ExtrapolationMode.LOOP;
|
||||
expect(KeySharedRealCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([[0.1, ({
|
||||
value: 0.1,
|
||||
interpolationMode: RealInterpolationMode.CUBIC,
|
||||
})]]);
|
||||
expect(KeySharedRealCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('Composite', () => {
|
||||
const curves1 = new KeySharedRealCurves([0.1, 0.7, 0.8]);
|
||||
|
||||
const curveMatched = new RealCurve();
|
||||
curveMatched.assignSorted([0.1, 0.7, 0.8], Array.from({ length: 3 }, () => ({ value: 0.1 })));
|
||||
expect(curves1.matchCurve(curveMatched)).toBe(true);
|
||||
|
||||
const curveNonMatched = new RealCurve();
|
||||
curveNonMatched.assignSorted([0.1, 0.3, 0.8], Array.from({ length: 3 }, () => ({ value: 0.1 })));
|
||||
expect(curves1.matchCurve(curveNonMatched)).toBe(false);
|
||||
});
|
||||
|
||||
test('Composite (may be baked)', () => {
|
||||
const curves1 = new KeySharedRealCurves([0.1, 0.2, 0.3]);
|
||||
|
||||
const curveMatched = new RealCurve();
|
||||
curveMatched.assignSorted([0.1, 0.2, 0.3], Array.from({ length: 3 }, () => ({ value: 0.1 })));
|
||||
expect(curves1.matchCurve(curveMatched)).toBe(true);
|
||||
|
||||
const curveNonMatched = new RealCurve();
|
||||
curveNonMatched.assignSorted([0.2, 0.3, 0.4], Array.from({ length: 3 }, () => ({ value: 0.1 })));
|
||||
expect(curves1.matchCurve(curveNonMatched)).toBe(false);
|
||||
});
|
||||
|
||||
test('Evaluate', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.7, 0.8], Array.from({ length: 3 }, (_, index) => ({ value: index + 1 })));
|
||||
|
||||
const curves = new KeySharedRealCurves(Array.from(curve.times()));
|
||||
curves.addCurve(curve);
|
||||
const values = [0.0];
|
||||
const resetAndEval = (time: number) => {
|
||||
values[0] = NaN;
|
||||
curves.evaluate(time, values);
|
||||
};
|
||||
|
||||
resetAndEval(0.0);
|
||||
expect(values[0]).toBeCloseTo(1.0);
|
||||
|
||||
resetAndEval(0.81);
|
||||
expect(values[0]).toBeCloseTo(3.0);
|
||||
|
||||
resetAndEval(0.7);
|
||||
expect(values[0]).toBeCloseTo(2.0);
|
||||
|
||||
resetAndEval(0.73);
|
||||
expect(values[0]).toBeCloseTo(2.3);
|
||||
});
|
||||
|
||||
test('Evaluate optimized keys', () => {
|
||||
const curve = new RealCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], Array.from({ length: 3 }, (_, index) => ({ value: index + 1 })));
|
||||
|
||||
const curves = new KeySharedRealCurves(Array.from(curve.times()));
|
||||
curves.addCurve(curve);
|
||||
const values = [0.0];
|
||||
const resetAndEval = (time: number) => {
|
||||
values[0] = NaN;
|
||||
curves.evaluate(time, values);
|
||||
};
|
||||
|
||||
resetAndEval(0.0);
|
||||
expect(values[0]).toBeCloseTo(1.0);
|
||||
|
||||
resetAndEval(0.31);
|
||||
expect(values[0]).toBeCloseTo(3.0);
|
||||
|
||||
resetAndEval(0.2);
|
||||
expect(values[0]).toBeCloseTo(2.0);
|
||||
|
||||
resetAndEval(0.25);
|
||||
expect(values[0]).toBeCloseTo(2.5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Keys shared quaternion curves', () => {
|
||||
test('Enabling', () => {
|
||||
{
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([[0.1, {
|
||||
interpolationMode: QuatInterpolationMode.SLERP,
|
||||
value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 },
|
||||
}]]);
|
||||
expect(KeySharedQuatCurves.allowedForCurve(curve)).toBe(true);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([[0.1, {
|
||||
value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 },
|
||||
}]]);
|
||||
curve.postExtrapolation = ExtrapolationMode.LOOP;
|
||||
expect(KeySharedQuatCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([[0.1, {
|
||||
value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 },
|
||||
}]]);
|
||||
curve.preExtrapolation = ExtrapolationMode.LOOP;
|
||||
expect(KeySharedQuatCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
|
||||
{
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([[0.1, {
|
||||
value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 },
|
||||
interpolationMode: QuatInterpolationMode.CONSTANT,
|
||||
}]]);
|
||||
expect(KeySharedQuatCurves.allowedForCurve(curve)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('Composite', () => {
|
||||
const curves1 = new KeySharedQuatCurves([0.1, 0.7, 0.8]);
|
||||
|
||||
const curveMatched = new QuatCurve();
|
||||
curveMatched.assignSorted([0.1, 0.7, 0.8], Array.from({ length: 3 }, () =>
|
||||
({ value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 } })));
|
||||
expect(curves1.matchCurve(curveMatched)).toBe(true);
|
||||
|
||||
const curveNonMatched = new QuatCurve();
|
||||
curveNonMatched.assignSorted([0.1, 0.3, 0.8], Array.from({ length: 3 }, () =>
|
||||
({ value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 } })));
|
||||
expect(curves1.matchCurve(curveNonMatched)).toBe(false);
|
||||
});
|
||||
|
||||
test('Composite (may be baked)', () => {
|
||||
const curves1 = new KeySharedQuatCurves([0.1, 0.2, 0.3]);
|
||||
|
||||
const curveMatched = new QuatCurve();
|
||||
curveMatched.assignSorted([0.1, 0.2, 0.3], Array.from({ length: 3 }, () =>
|
||||
({ value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 } })));
|
||||
expect(curves1.matchCurve(curveMatched)).toBe(true);
|
||||
|
||||
const curveNonMatched = new QuatCurve();
|
||||
curveNonMatched.assignSorted([0.2, 0.3, 0.4], Array.from({ length: 3 }, () =>
|
||||
({ value: { x: -0.542, y: -0.688, z: 0.199, w: -0.439 } })));
|
||||
expect(curves1.matchCurve(curveNonMatched)).toBe(false);
|
||||
});
|
||||
|
||||
const quaternions = [
|
||||
new Quat(-0.542, -0.688 -0.439, 0.199),
|
||||
new Quat(-0.403, 0.723, -0.545, -0.135),
|
||||
new Quat(0.658, 0.422, 0.455, 0.427),
|
||||
];
|
||||
|
||||
test('Evaluate', () => {
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([0.1, 0.7, 0.8], Array.from({ length: 3 }, (_, index) =>
|
||||
({ value: Quat.clone(quaternions[index]) })));
|
||||
|
||||
const curves = new KeySharedQuatCurves(Array.from(curve.times()));
|
||||
curves.addCurve(curve);
|
||||
const values = [new Quat()];
|
||||
const resetAndEval = (time: number) => {
|
||||
Quat.set(values[0], NaN, NaN, NaN, NaN);
|
||||
curves.evaluate(time, values);
|
||||
};
|
||||
|
||||
resetAndEval(0.0);
|
||||
expect(Quat.equals(values[0], quaternions[0])).toBe(true);
|
||||
|
||||
resetAndEval(0.81);
|
||||
expect(Quat.equals(values[0], quaternions[2])).toBe(true);
|
||||
|
||||
resetAndEval(0.7);
|
||||
expect(Quat.equals(values[0], quaternions[1])).toBe(true);
|
||||
|
||||
resetAndEval(0.73);
|
||||
expect(Quat.equals(values[0], Quat.slerp(new Quat(), quaternions[1], quaternions[2], 0.3))).toBe(true);
|
||||
});
|
||||
|
||||
test('Evaluate optimized keys', () => {
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], Array.from({ length: 3 }, (_, index) =>
|
||||
({ value: Quat.clone(quaternions[index]) })));
|
||||
|
||||
const curves = new KeySharedQuatCurves(Array.from(curve.times()));
|
||||
curves.addCurve(curve);
|
||||
const values = [new Quat()];
|
||||
const resetAndEval = (time: number) => {
|
||||
Quat.set(values[0], NaN, NaN, NaN, NaN);
|
||||
curves.evaluate(time, values);
|
||||
};
|
||||
|
||||
resetAndEval(0.0);
|
||||
expect(Quat.equals(values[0], quaternions[0])).toBe(true);
|
||||
|
||||
resetAndEval(0.31);
|
||||
expect(Quat.equals(values[0], quaternions[2])).toBe(true);
|
||||
|
||||
resetAndEval(0.2);
|
||||
expect(Quat.equals(values[0], quaternions[1])).toBe(true);
|
||||
|
||||
resetAndEval(0.25);
|
||||
expect(Quat.equals(values[0], Quat.slerp(new Quat(), quaternions[1], quaternions[2], 0.5))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
|
||||
import { Quat, QuatCurve, QuatInterpolationMode } from '../../cocos/core';
|
||||
import { serializeAndDeserialize } from './serialize-and-deserialize-curve';
|
||||
|
||||
describe('Curve', () => {
|
||||
test('Evaluate an empty curve', () => {
|
||||
const curve = new QuatCurve();
|
||||
expect(curve.evaluate(12.34)).toStrictEqual(Quat.IDENTITY);
|
||||
});
|
||||
|
||||
describe('serialization', () => {
|
||||
test('Normal', () => {
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([0.1, 0.2, 0.3], [
|
||||
{ value: { x: 0.1, y: 0.2, z: 0.3, w: 0.4 }, interpolationMode: QuatInterpolationMode.CONSTANT },
|
||||
{ value: { x: 0.5, y: -0.6, z: 0.7, w: 0.8 }, interpolationMode: QuatInterpolationMode.SLERP },
|
||||
{ value: { x: 0.9, y: 0.1, z: 0.11, w: 0.12 }, interpolationMode: QuatInterpolationMode.CONSTANT },
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, QuatCurve), curve);
|
||||
});
|
||||
|
||||
test('Optimized for linear curve', () => {
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([0.1, 0.2], [
|
||||
{ value: { x: 0.1, y: 0.2, z: 0.3, w: 0.4 }, interpolationMode: QuatInterpolationMode.SLERP },
|
||||
{ value: { x: 0.5, y: -0.6, z: 0.7, w: 0.8 }, interpolationMode: QuatInterpolationMode.SLERP },
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, QuatCurve), curve);
|
||||
});
|
||||
|
||||
test('Optimized for constant curve', () => {
|
||||
const curve = new QuatCurve();
|
||||
curve.assignSorted([0.1, 0.2], [
|
||||
{ value: { x: 0.1, y: 0.2, z: 0.3, w: 0.4 }, interpolationMode: QuatInterpolationMode.CONSTANT },
|
||||
{ value: { x: 0.5, y: -0.6, z: 0.7, w: 0.8 }, interpolationMode: QuatInterpolationMode.CONSTANT },
|
||||
]);
|
||||
compareCurves(serializeAndDeserialize(curve, QuatCurve), curve);
|
||||
});
|
||||
});
|
||||
|
||||
test('Default keyframe value', () => {
|
||||
const curve = new QuatCurve();
|
||||
const keyframeValue = curve.getKeyframeValue(curve.addKeyFrame(0.0, {}));
|
||||
expect(Quat.equals(keyframeValue.value, Quat.IDENTITY)).toBe(true);
|
||||
expect(keyframeValue.interpolationMode).toBe(QuatInterpolationMode.SLERP);
|
||||
});
|
||||
});
|
||||
|
||||
function compareCurves (left: QuatCurve, right: QuatCurve, numDigits = 2) {
|
||||
expect(left.keyFramesCount).toBe(right.keyFramesCount);
|
||||
for (let iKeyframe = 0; iKeyframe < left.keyFramesCount; ++iKeyframe) {
|
||||
expect(left.getKeyframeTime(iKeyframe)).toBeCloseTo(right.getKeyframeTime(iKeyframe), numDigits);
|
||||
const leftKeyframeValue = left.getKeyframeValue(iKeyframe);
|
||||
const rightKeyframeValue = right.getKeyframeValue(iKeyframe);
|
||||
expect(leftKeyframeValue.value.x).toBeCloseTo(rightKeyframeValue.value.x, numDigits);
|
||||
expect(leftKeyframeValue.value.y).toBeCloseTo(rightKeyframeValue.value.y, numDigits);
|
||||
expect(leftKeyframeValue.value.z).toBeCloseTo(rightKeyframeValue.value.z, numDigits);
|
||||
expect(leftKeyframeValue.value.w).toBeCloseTo(rightKeyframeValue.value.w, numDigits);
|
||||
expect(leftKeyframeValue.interpolationMode).toStrictEqual(rightKeyframeValue.interpolationMode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
|
||||
import { deserializeTag, SerializationInput, SerializationOutput, serializeTag } from '../../cocos/core';
|
||||
import type { RealCurve } from '../../cocos/core/curves/curve';
|
||||
import type { QuatCurve } from '../../cocos/core/curves/quat-curve';
|
||||
|
||||
export function serializeAndDeserialize<T extends RealCurve | QuatCurve> (curve: T, CurveConstructor: new () => T) {
|
||||
class CurveOutput implements SerializationOutput, SerializationInput {
|
||||
public readProperty(name: string): unknown {
|
||||
return this._properties[name];
|
||||
}
|
||||
|
||||
public writeProperty (name: string, value: unknown) {
|
||||
this._properties[name] = value;
|
||||
}
|
||||
|
||||
public readThis(): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
public readSuper(): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
public writeThis(): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
public writeSuper(): void {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
private _properties: Record<string, unknown> = {};
|
||||
}
|
||||
const curveOutput = new CurveOutput();
|
||||
curve[serializeTag](curveOutput, { root: curve, toCCON: true, customArguments: {} });
|
||||
const newCurve = new CurveConstructor();
|
||||
newCurve[deserializeTag](curveOutput, { fromCCON: true });
|
||||
return newCurve;
|
||||
}
|
||||
Reference in New Issue
Block a user