mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-02 00:22:43 +08:00
move data conversion out of animation clip (#5922)
* move data conversion out of animation-clip * pre sample switch on skeletal anim comp
This commit is contained in:
@@ -355,7 +355,7 @@ export class AnimationState extends Playable {
|
||||
protected _curveLoaded = false;
|
||||
protected _ignoreIndex = InvalidIndex;
|
||||
|
||||
constructor (clip: AnimationClip, name?: string) {
|
||||
constructor (clip: AnimationClip, name = '') {
|
||||
super();
|
||||
this._clip = clip;
|
||||
this._name = name || (clip && clip.name);
|
||||
@@ -365,7 +365,7 @@ export class AnimationState extends Playable {
|
||||
return this._curveLoaded;
|
||||
}
|
||||
|
||||
public initialize (root: INode) {
|
||||
public initialize (root: INode, propertyCurves?: readonly IRuntimeCurve[]) {
|
||||
if (this._curveLoaded) { return; }
|
||||
this._curveLoaded = true;
|
||||
this._samplerSharedGroups.length = 0;
|
||||
@@ -383,7 +383,7 @@ export class AnimationState extends Playable {
|
||||
this.repeatCount = 1;
|
||||
}
|
||||
|
||||
const propertyCurves = clip.getPropertyCurves();
|
||||
if (!propertyCurves) { propertyCurves = clip.getPropertyCurves(); }
|
||||
for (let iPropertyCurve = 0; iPropertyCurve < propertyCurves.length; ++iPropertyCurve) {
|
||||
const propertyCurve = propertyCurves[iPropertyCurve];
|
||||
let samplerSharedGroup = this._samplerSharedGroups.find((value) => value.sampler === propertyCurve.sampler);
|
||||
|
||||
@@ -77,6 +77,9 @@ export class SkeletalAnimationComponent extends AnimationComponent {
|
||||
|
||||
@property({ type: [Socket] })
|
||||
public _sockets: Socket[] = [];
|
||||
|
||||
protected _enablePreSample = true;
|
||||
|
||||
protected _animMgr: JointsAnimationInfo = null!;
|
||||
|
||||
@property({
|
||||
@@ -91,6 +94,14 @@ export class SkeletalAnimationComponent extends AnimationComponent {
|
||||
this.rebuildSocketAnimations();
|
||||
}
|
||||
|
||||
set enablePreSample (val) {
|
||||
this._enablePreSample = val;
|
||||
this.clips = this._clips; // release old states
|
||||
}
|
||||
get enablePreSample () {
|
||||
return this._enablePreSample;
|
||||
}
|
||||
|
||||
protected _animInfo: IAnimInfo | null = null;
|
||||
|
||||
set frameID (fid: number) {
|
||||
@@ -124,7 +135,7 @@ export class SkeletalAnimationComponent extends AnimationComponent {
|
||||
}
|
||||
|
||||
public querySockets () {
|
||||
const animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip)).sort().reduce((acc, cur) =>
|
||||
const animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).data).sort().reduce((acc, cur) =>
|
||||
cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc), [] as string[]) || [];
|
||||
if (!animPaths.length) { return ['default animation clip missing/invalid']; }
|
||||
const out: string[] = [];
|
||||
@@ -169,7 +180,7 @@ export class SkeletalAnimationComponent extends AnimationComponent {
|
||||
}
|
||||
|
||||
protected _createState (clip: AnimationClip, name?: string) {
|
||||
return new SkeletalAnimationState(clip, name);
|
||||
return new SkeletalAnimationState(clip, name, this._enablePreSample);
|
||||
}
|
||||
|
||||
protected _doCreateState (clip: AnimationClip, name: string) {
|
||||
|
||||
@@ -28,15 +28,28 @@
|
||||
*/
|
||||
|
||||
import { Mat4, Quat, Vec3 } from '../math';
|
||||
import { DataPoolManager } from '../renderer/data-pool-manager';
|
||||
import { getClassName } from '../utils/js';
|
||||
import { AnimationClip, IObjectCurveData } from './animation-clip';
|
||||
import { IPropertyCurveData } from './animation-curve';
|
||||
import { AnimationClip, IObjectCurveData, IRuntimeCurve } from './animation-clip';
|
||||
import { AnimCurve, RatioSampler } from './animation-curve';
|
||||
import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier';
|
||||
|
||||
type CurveData = Vec3 | Quat;
|
||||
type ConvertedData = Record<string, {
|
||||
props: Record<string, IPropertyCurveData>;
|
||||
}>;
|
||||
type CurveData = Vec3 | Quat | Mat4;
|
||||
type ConvertedProps = Record<string, IPropertyCurve>;
|
||||
|
||||
interface IPropertyCurve {
|
||||
keys: number;
|
||||
values: CurveData[];
|
||||
}
|
||||
interface ISkeletalCurveInfo {
|
||||
curves: IRuntimeCurve[];
|
||||
frames: number;
|
||||
sample: number;
|
||||
}
|
||||
interface IConvertedData {
|
||||
info: ISkeletalCurveInfo;
|
||||
data: Record<string, ConvertedProps>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 骨骼动画数据转换中心。
|
||||
@@ -45,7 +58,12 @@ export class SkelAnimDataHub {
|
||||
|
||||
public static getOrExtract (clip: AnimationClip) {
|
||||
let data = SkelAnimDataHub.pool.get(clip);
|
||||
if (!data) { data = convertToSkeletalCurves(clip); SkelAnimDataHub.pool.set(clip, data); }
|
||||
if (!data || data.info.sample !== clip.sample) {
|
||||
// release outdated render data
|
||||
if (data) { (cc.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(clip); }
|
||||
data = convertToSkeletalCurves(clip);
|
||||
SkelAnimDataHub.pool.set(clip, data);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -53,75 +71,77 @@ export class SkelAnimDataHub {
|
||||
SkelAnimDataHub.pool.delete(clip);
|
||||
}
|
||||
|
||||
protected static pool = new Map<AnimationClip, ConvertedData>();
|
||||
protected static pool = new Map<AnimationClip, IConvertedData>();
|
||||
}
|
||||
|
||||
function convertToSkeletalCurves (clip: AnimationClip) {
|
||||
function convertToSkeletalCurves (clip: AnimationClip): IConvertedData {
|
||||
// tslint:disable-next-line: no-unused-expression
|
||||
clip.hash; // calculate hash before conversion
|
||||
const originalKeys = clip.keys;
|
||||
const convertedData: ConvertedData = {};
|
||||
const data: Record<string, ConvertedProps> = {};
|
||||
clip.curves.forEach((curve) => {
|
||||
if (!curve.valueAdapter &&
|
||||
isCustomTargetModifier(curve.modifiers[0], HierachyModifier) &&
|
||||
isPropertyModifier(curve.modifiers[1])) {
|
||||
const path = (curve.modifiers[0] as HierachyModifier).path;
|
||||
let cs = convertedData[path];
|
||||
if (!cs) { cs = convertedData[path] = { props: {} }; }
|
||||
let cs = data[path];
|
||||
if (!cs) { cs = data[path] = {}; }
|
||||
const property = curve.modifiers[1] as string;
|
||||
cs.props[property] = curve.data;
|
||||
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(convertedData)) {
|
||||
const props = convertedData[path] && convertedData[path].props;
|
||||
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, originalKeys, position);
|
||||
convertToUniformSample(clip, originalKeys, rotation);
|
||||
convertToUniformSample(clip, originalKeys, scale);
|
||||
convertToUniformSample(clip, position, frames);
|
||||
convertToUniformSample(clip, rotation, frames);
|
||||
convertToUniformSample(clip, scale, frames);
|
||||
// transform to world space
|
||||
convertToWorldSpace(convertedData, path, props);
|
||||
convertToWorldSpace(data, path, props);
|
||||
}
|
||||
return props._worldMatrix;
|
||||
},
|
||||
});
|
||||
}
|
||||
const values: number[] = new Array(Math.ceil(clip.sample * clip.duration / clip.speed) + 1);
|
||||
for (let i = 0; i < values.length; i++) { values[i] = i; }
|
||||
clip.curves = [{ // leave only frameID animation
|
||||
modifiers: [
|
||||
new HierachyModifier(''),
|
||||
new ComponentModifier(getClassName(cc.SkeletalAnimationComponent)),
|
||||
'frameID',
|
||||
],
|
||||
data: { keys: 0, values, interpolate: false },
|
||||
}];
|
||||
clip.keys = [values.map((_, i) => i * clip.speed / clip.sample)];
|
||||
clip.duration = clip.keys[0][values.length - 1];
|
||||
return convertedData;
|
||||
const values: number[] = new Array(frames); const ratios: number[] = new Array(frames);
|
||||
for (let i = 0; i < frames; i++) { values[i] = i; ratios[i] = i / (frames - 1); }
|
||||
const info: ISkeletalCurveInfo = {
|
||||
frames,
|
||||
sample: clip.sample,
|
||||
curves: [{
|
||||
curve: new AnimCurve({ values, interpolate: false }, (frames - 1) / clip.sample),
|
||||
modifiers: [
|
||||
new HierachyModifier(''),
|
||||
new ComponentModifier(getClassName(cc.SkeletalAnimationComponent)),
|
||||
'frameID',
|
||||
],
|
||||
sampler: new RatioSampler(ratios),
|
||||
}],
|
||||
};
|
||||
return { info, data };
|
||||
}
|
||||
|
||||
function convertToUniformSample (clip: AnimationClip, originalKeys: number[][], curve: IPropertyCurveData) {
|
||||
const keys = originalKeys[curve.keys]; curve.keys = 0;
|
||||
const len = clip.keys[0].length;
|
||||
const values: any[] = [];
|
||||
function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, frames: number) {
|
||||
const keys = clip.keys[curve.keys]; curve.keys = 0;
|
||||
const values: CurveData[] = [];
|
||||
if (!keys || keys.length === 1) {
|
||||
for (let i = 0; i < len; i++) {
|
||||
for (let i = 0; i < frames; i++) {
|
||||
values[i] = curve.values[0].clone(); // never forget to clone
|
||||
}
|
||||
} else {
|
||||
for (let i = 0, idx = 0; i < len; i++) {
|
||||
let time = i * clip.speed / clip.sample;
|
||||
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() as CurveData;
|
||||
const from = curve.values[idx - 1].clone() as any;
|
||||
from.lerp(curve.values[idx], (time - keys[idx - 1]) / (keys[idx] - keys[idx - 1]));
|
||||
values[i] = from;
|
||||
}
|
||||
@@ -129,7 +149,7 @@ function convertToUniformSample (clip: AnimationClip, originalKeys: number[][],
|
||||
curve.values = values;
|
||||
}
|
||||
|
||||
function convertToWorldSpace (convertedData: ConvertedData, path: string, props: IObjectCurveData) {
|
||||
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;
|
||||
@@ -138,9 +158,9 @@ function convertToWorldSpace (convertedData: ConvertedData, path: string, props:
|
||||
let pMatrix: Mat4[] | null = null;
|
||||
if (idx > 0) {
|
||||
const name = path.substring(0, idx);
|
||||
const data = convertedData[name];
|
||||
if (!data || !data.props) { console.warn('no data for parent bone?'); return; }
|
||||
pMatrix = data.props.worldMatrix.values;
|
||||
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++) {
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
import { SkinningModelComponent } from '../3d/framework/skinning-model-component';
|
||||
import { Mat4 } from '../math';
|
||||
import { INode } from '../utils/interfaces';
|
||||
import { IObjectCurveData } from './animation-clip';
|
||||
import { AnimationClip, IObjectCurveData } from './animation-clip';
|
||||
import { AnimCurve } from './animation-curve';
|
||||
import { AnimationState, ICurveInstance } from './animation-state';
|
||||
import { Socket } from './skeletal-animation-component';
|
||||
@@ -49,9 +49,21 @@ function isFrameIDCurve (modifiers: TargetModifier[]) {
|
||||
|
||||
export class SkeletalAnimationState extends AnimationState {
|
||||
|
||||
protected _preSample = true;
|
||||
|
||||
constructor (clip: AnimationClip, name = '', preSample = true) {
|
||||
super(clip, name);
|
||||
this._preSample = preSample;
|
||||
}
|
||||
|
||||
public initialize (root: INode) {
|
||||
SkelAnimDataHub.getOrExtract(this.clip);
|
||||
super.initialize(root);
|
||||
if (this._preSample) {
|
||||
const info = SkelAnimDataHub.getOrExtract(this.clip).info;
|
||||
super.initialize(root, info.curves);
|
||||
this.duration = (info.frames - 1) / info.sample; // last key
|
||||
} else {
|
||||
super.initialize(root);
|
||||
}
|
||||
}
|
||||
|
||||
public onPlay () {
|
||||
@@ -91,12 +103,12 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
const targetNode = root.getChildByPath(socket.path);
|
||||
if (!targetNode || !socket.target) { return null; }
|
||||
const targetPath = socket.path;
|
||||
const sourceData = SkelAnimDataHub.getOrExtract(this.clip);
|
||||
const sourceData = SkelAnimDataHub.getOrExtract(this.clip).data;
|
||||
// find lowest joint animation
|
||||
let animPath = targetPath;
|
||||
let source = sourceData[animPath];
|
||||
let animNode = targetNode;
|
||||
while (!source || !source.props) {
|
||||
while (!source) {
|
||||
const idx = animPath.lastIndexOf('/');
|
||||
animPath = animPath.substring(0, idx);
|
||||
source = sourceData[animPath];
|
||||
@@ -105,7 +117,7 @@ export class SkeletalAnimationState extends AnimationState {
|
||||
}
|
||||
// create animation data
|
||||
const data: IObjectCurveData = {
|
||||
matrix: { keys: 0, interpolate: false, values: source.props.worldMatrix.values.map((v) => v.clone()) },
|
||||
matrix: { keys: 0, interpolate: false, values: source.worldMatrix.values.map((v) => v.clone()) },
|
||||
};
|
||||
const matrix = data.matrix.values;
|
||||
// apply downstream default pose
|
||||
|
||||
@@ -190,19 +190,19 @@ export class JointsTexturePool {
|
||||
const hash = skeleton.hash ^ clip.hash;
|
||||
let texture: IJointsTextureHandle | null = this._textureBuffers.get(hash) || null;
|
||||
if (texture) { texture.refCount++; return texture; }
|
||||
const frames = clip.keys[0].length;
|
||||
const clipData = SkelAnimDataHub.getOrExtract(clip);
|
||||
const frames = clipData.info.frames;
|
||||
const bufSize = skeleton.joints.length * 12 * frames;
|
||||
const handle = this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
|
||||
if (!handle) { return null; }
|
||||
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1,
|
||||
skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle };
|
||||
const textureBuffer = new Float32Array(bufSize);
|
||||
const data = SkelAnimDataHub.getOrExtract(clip);
|
||||
for (let i = 0; i < skeleton.joints.length; i++) {
|
||||
const nodeData = data[skeleton.joints[i]];
|
||||
if (!nodeData || !nodeData.props) { continue; }
|
||||
const nodeData = clipData.data[skeleton.joints[i]];
|
||||
if (!nodeData) { continue; }
|
||||
const bindpose = skeleton.bindposes[i];
|
||||
const matrix = nodeData.props.worldMatrix.values;
|
||||
const matrix = nodeData.worldMatrix.values as Mat4[];
|
||||
for (let frame = 0; frame < frames; frame++) {
|
||||
const m = matrix[frame];
|
||||
Mat4.multiply(m4_1, m, bindpose);
|
||||
@@ -229,6 +229,8 @@ export class JointsTexturePool {
|
||||
if (res.value.skeletonHash === skeleton.hash) {
|
||||
res.value.readyToBeDeleted = true;
|
||||
this.releaseHandle(res.value, false);
|
||||
// delete handle refs immediately so new allocations with the same asset could work
|
||||
this._textureBuffers.delete(res.value.skeletonHash ^ res.value.clipHash);
|
||||
}
|
||||
res = it.next();
|
||||
}
|
||||
@@ -241,6 +243,8 @@ export class JointsTexturePool {
|
||||
if (res.value.clipHash === clip.hash) {
|
||||
res.value.readyToBeDeleted = true;
|
||||
this.releaseHandle(res.value, false);
|
||||
// delete handle refs immediately so new allocations with the same asset could work
|
||||
this._textureBuffers.delete(res.value.skeletonHash ^ res.value.clipHash);
|
||||
}
|
||||
res = it.next();
|
||||
}
|
||||
@@ -301,7 +305,7 @@ export class JointsAnimationInfo {
|
||||
}
|
||||
|
||||
public switchClip (info: IAnimInfo, clip: AnimationClip | null) {
|
||||
info.data[0] = clip ? clip.keys[0].length : 1;
|
||||
info.data[0] = clip ? SkelAnimDataHub.getOrExtract(clip).info.frames : 1;
|
||||
info.data[1] = 0;
|
||||
info.buffer.update(info.data);
|
||||
info.dirty = false;
|
||||
@@ -332,18 +336,18 @@ export class AnimatedBoundsInfo {
|
||||
perJointBounds = this.getBoneSpacePerJointBounds(mesh, skeleton);
|
||||
this._setPerJointBounds(mesh, skeleton, perJointBounds);
|
||||
}
|
||||
const frames = clip.keys[0].length;
|
||||
const clipData = SkelAnimDataHub.getOrExtract(clip);
|
||||
const frames = clipData.info.frames;
|
||||
for (let fid = 0; fid < frames; fid++) {
|
||||
list.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
|
||||
}
|
||||
const data = SkelAnimDataHub.getOrExtract(clip);
|
||||
const joints = skeleton.joints;
|
||||
// per frame bounding box
|
||||
for (let i = 0; i < joints.length; i++) {
|
||||
const nodeData = data[joints[i]];
|
||||
const nodeData = clipData.data[joints[i]];
|
||||
const bound = perJointBounds[i];
|
||||
if (!bound || !nodeData || !nodeData.props) { continue; }
|
||||
const matrix = nodeData.props.worldMatrix.values;
|
||||
if (!bound || !nodeData) { continue; }
|
||||
const matrix = nodeData.worldMatrix.values as Mat4[];
|
||||
for (let fid = 0; fid < frames; fid++) {
|
||||
const m = matrix[fid];
|
||||
const info = list[fid];
|
||||
|
||||
Reference in New Issue
Block a user