From f03df0bb391ea6520e7abfc40cb338f9a7e5aa31 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 16 Jul 2019 10:36:13 +0800 Subject: [PATCH] skeletal animation clip (#4882) --- cocos/3d/assets/material.ts | 3 +- cocos/3d/assets/skeleton.ts | 2 +- cocos/animation/animation-clip.ts | 50 ++++---- cocos/animation/animation-state.ts | 2 +- cocos/animation/index.ts | 1 + cocos/animation/skeletal-animation-clip.ts | 136 +++++++++++++++++++++ cocos/components/animation-component.ts | 4 - cocos/renderer/models/skinning-model.ts | 68 ++--------- 8 files changed, 178 insertions(+), 88 deletions(-) create mode 100644 cocos/animation/skeletal-animation-clip.ts diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts index b680a32990..38dc63e62c 100644 --- a/cocos/3d/assets/material.ts +++ b/cocos/3d/assets/material.ts @@ -404,7 +404,8 @@ export class Material extends Asset { } else if (val instanceof TextureBase) { const textureView: GFXTextureView | null = val.getGFXTextureView(); if (!textureView || !textureView.texture.width || !textureView.texture.height) { - console.warn(`material '${this._uuid}' received incomplete texture asset '${val._uuid}'`); return false; + // console.warn(`material '${this._uuid}' received incomplete texture asset '${val._uuid}'`); + return false; } pass.bindTextureView(binding, textureView); pass.bindSampler(binding, samplerLib.getSampler(cc.game._gfxDevice, val.getGFXSamplerInfo())); diff --git a/cocos/3d/assets/skeleton.ts b/cocos/3d/assets/skeleton.ts index 18682f5f07..606dd13c04 100644 --- a/cocos/3d/assets/skeleton.ts +++ b/cocos/3d/assets/skeleton.ts @@ -33,7 +33,7 @@ import { CCString } from '../../core/data/utils/attribute'; import { Mat4, Quat, Vec3 } from '../../core/value-types'; import { mat4 } from '../../core/vmath'; -interface IBindTRS { +export interface IBindTRS { position: Vec3; rotation: Quat; scale: Vec3; diff --git a/cocos/animation/animation-clip.ts b/cocos/animation/animation-clip.ts index c22836e2c3..dcafbe3eed 100644 --- a/cocos/animation/animation-clip.ts +++ b/cocos/animation/animation-clip.ts @@ -7,6 +7,7 @@ import { Asset, SpriteFrame } from '../assets'; import { ccclass, property } from '../core/data/class-decorator'; import { errorID } from '../core/platform/CCDebug'; import binarySearchEpsilon from '../core/utils/binary-search'; +import { Node } from '../scene-graph'; import { AnimCurve, IPropertyCurveData, RatioSampler } from './animation-curve'; import { WrapMode as AnimationWrapMode } from './types'; @@ -156,24 +157,24 @@ export class AnimationClip extends Asset { public events: IAnimationEventData[] = []; @property - private _duration = 0; + protected _duration = 0; @property - private _keys: number[][] = []; + protected _keys: number[][] = []; - private _ratioSamplers: RatioSampler[] = []; + protected _ratioSamplers: RatioSampler[] = []; - private _propertyCurves?: IPropertyCurve[]; + protected _propertyCurves?: IPropertyCurve[]; - private _runtimeEvents?: { + protected _runtimeEvents?: { ratios: number[]; eventGroups: IAnimationEventGroup[]; }; - private frameRate = 0; + protected frameRate = 0; @property - private _stepness = 0; + protected _stepness = 0; /** * 动画的周期。 @@ -198,17 +199,7 @@ export class AnimationClip extends Asset { } /** - * @private - */ - get propertyCurves (): ReadonlyArray { - if (!this._propertyCurves) { - this._createPropertyCurves(); - } - return this._propertyCurves!; - } - - /** - * @private + * @protected */ get eventGroups (): ReadonlyArray { if (!this._runtimeEvents) { @@ -218,14 +209,14 @@ export class AnimationClip extends Asset { } /** - * @private + * @protected */ get stepness () { return this._stepness; } /** - * @private + * @protected */ set stepness (value) { this._stepness = value; @@ -239,6 +230,13 @@ export class AnimationClip extends Asset { this.frameRate = this.sample; } + public getPropertyCurves (root: Node): ReadonlyArray { + if (!this._propertyCurves) { + this._createPropertyCurves(); + } + return this._propertyCurves!; + } + /** * 提交曲线数据的修改。 * 当你修改了 `this.curveDatas`、`this.keys` 或 `this.duration`时, @@ -251,7 +249,7 @@ export class AnimationClip extends Asset { /** * 提交事件数据的修改。 * 当你修改了 `this.events` 时,必须调用 `this.updateEventDatas()` 使修改生效。 - * @private + * @protected */ public updateEventDatas () { delete this._runtimeEvents; @@ -260,7 +258,7 @@ export class AnimationClip extends Asset { /** * Gets the event group shall be processed at specified ratio. * @param ratio The ratio. - * @private + * @protected */ public getEventGroupIndexAtRatio (ratio: number): number { if (!this._runtimeEvents) { @@ -272,13 +270,13 @@ export class AnimationClip extends Asset { /** * 返回本动画是否包含事件数据。 - * @private + * @protected */ public hasEvents () { return this.events.length !== 0; } - private _createPropertyCurves () { + protected _createPropertyCurves () { this._ratioSamplers = this._keys.map( (keys) => new RatioSampler( keys.map( @@ -317,7 +315,7 @@ export class AnimationClip extends Asset { this._applyStepness(); } - private _createRuntimeEvents () { + protected _createRuntimeEvents () { if (CC_EDITOR) { return; } @@ -347,7 +345,7 @@ export class AnimationClip extends Asset { }; } - private _applyStepness () { + protected _applyStepness () { if (!this._propertyCurves) { return; } diff --git a/cocos/animation/animation-state.ts b/cocos/animation/animation-state.ts index 48c3f85f1f..009dd17636 100644 --- a/cocos/animation/animation-state.ts +++ b/cocos/animation/animation-state.ts @@ -259,7 +259,7 @@ export class AnimationState extends Playable { this.repeatCount = 1; } - const propertyCurves = clip.propertyCurves; + const propertyCurves = clip.getPropertyCurves(this._targetNode); for (const propertyCurve of propertyCurves) { const targetNode = root.getChildByPath(propertyCurve.path); if (!targetNode) { diff --git a/cocos/animation/index.ts b/cocos/animation/index.ts index 7933ba455f..dbee23fde0 100644 --- a/cocos/animation/index.ts +++ b/cocos/animation/index.ts @@ -8,6 +8,7 @@ export { easing }; export * from './motion-path-helper'; export * from './animation-curve'; export * from './animation-clip'; +export * from './skeletal-animation-clip'; export * from './animation-manager'; export * from './animation-state'; export * from './cubic-spline-value'; diff --git a/cocos/animation/skeletal-animation-clip.ts b/cocos/animation/skeletal-animation-clip.ts new file mode 100644 index 0000000000..88d4da3349 --- /dev/null +++ b/cocos/animation/skeletal-animation-clip.ts @@ -0,0 +1,136 @@ + +/** + * @category animation + */ + +import { IBindTRS } from '../3d/assets/skeleton'; +import { SkinningModelComponent } from '../3d/framework/skinning-model-component'; +import { ccclass, property } from '../core/data/class-decorator'; +import { quat, vec3 } from '../core/vmath'; +import { Node } from '../scene-graph'; +import { AnimationClip, ICurveData, IObjectCurveData, IPropertyCurve } from './animation-clip'; +import { IPropertyCurveData } from './animation-curve'; + +/** + * 骨骼动画剪辑。 + */ +@ccclass('cc.SkeletalAnimationClip') +export class SkeletalAnimationClip extends AnimationClip { + + @property + public aggressiveCaching = true; + + protected _backedUp = false; + protected _backUpCurves: ICurveData = {}; + + public getPropertyCurves (root: Node): ReadonlyArray { + if (this.aggressiveCaching) { this._convertToSkeletalCurves(root); } + return super.getPropertyCurves(root); + } + + private _convertToUniformSample (curve: IPropertyCurveData) { + const keys = this._keys[curve.keys]; curve.keys = 0; + curve.values = [...Array(Math.ceil(this._duration * this.sample))].map((_, i) => { + if (!keys || keys.length === 1) { return curve.values[0].clone(); } // never forget to clone + let time = i / this.sample; + let idx = keys.findIndex((k) => k > time); + if (idx < 0) { idx = keys.length - 1; time = keys[idx]; } + else if (idx === 0) { idx = 1; } + const from = curve.values[idx - 1].clone(); + from.lerp(curve.values[idx], (time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])); + return from; + }); + } + + private _convertToWorldSpace (path: string, props: IObjectCurveData) { + const idx = path.lastIndexOf('/'); + if (idx < 0) { return; } + const name = path.substring(0, idx); + const data = this.curveDatas[name]; + if (!data || !data.props) { console.warn('no data for parent bone?'); return; } + const pPos = data.props.position.values; + const pRot = data.props.rotation.values; + const pScale = data.props.scale.values; + // parent is already in world space + const position = props.position.values; + const rotation = props.rotation.values; + const scale = props.scale.values; + // all props should have the same length now + for (let i = 0; i < position.length; i++) { + const parentT = pPos[i]; + const parentR = pRot[i]; + const parentS = pScale[i]; + const T = position[i]; + const R = rotation[i]; + const S = scale[i]; + vec3.multiply(T, T, parentS); + vec3.transformQuat(T, T, parentR); + vec3.add(T, T, parentT); + quat.multiply(R, parentR, R); + vec3.multiply(S, parentS, S); + } + } + + private _convertToSkeletalCurves (root: Node) { + // sort the keys to make sure parent bone always comes first + const paths = Object.keys(this.curveDatas).sort(); + if (!this._backedUp) { // only need to do these once + for (const path of paths) { + const nodeData = this.curveDatas[path]; + if (!nodeData.props) { continue; } + const { position, rotation, scale } = nodeData.props; + // fixed step pre-sample + this._convertToUniformSample(position); + this._convertToUniformSample(rotation); + this._convertToUniformSample(scale); + // turn off interpolation + position.interpolate = false; + rotation.interpolate = false; + scale.interpolate = false; + // transform to world space + this._convertToWorldSpace(path, nodeData.props); + } + this._backUpCurves = JSON.parse(JSON.stringify(this.curveDatas)); + this._keys = [[...Array(Math.ceil(this.sample * this._duration))].map((_, i) => i / this.sample)]; + this._backedUp = true; + } + // skeleton specific optimizations + const comps = root.getComponentsInChildren(SkinningModelComponent); + for (const path of paths) { + const nodeData = this.curveDatas[path]; + if (!nodeData.props) { continue; } + let bindpose: IBindTRS | null = null; + for (const comp of comps) { + const skeleton = comp.skeleton; + if (!skeleton) { continue; } + const idx = skeleton.joints.findIndex((j) => j === path); + if (idx < 0) { continue; } + bindpose = skeleton.bindTRS[idx]; + break; + } + if (!bindpose) { continue; } + const props = this._backUpCurves[path].props!; + const bPos = props.position.values; + const bRot = props.rotation.values; + const bScale = props.scale.values; + const position = nodeData.props.position.values; + const rotation = nodeData.props.rotation.values; + const scale = nodeData.props.scale.values; + for (let i = 0; i < position.length; i++) { + const backupT = bPos[i]; + const backupR = bRot[i]; + const backupS = bScale[i]; + const T = position[i]; + const R = rotation[i]; + const S = scale[i]; + vec3.multiply(T, bindpose.position, backupS); + vec3.transformQuat(T, T, backupR); + vec3.add(T, T, backupT); + quat.multiply(R, backupR, bindpose.rotation); + vec3.multiply(S, backupS, bindpose.scale); + } + } + } +} + +cc.SkeletalAnimationClip = SkeletalAnimationClip; diff --git a/cocos/components/animation-component.ts b/cocos/components/animation-component.ts index 836a41979b..c527f085bf 100644 --- a/cocos/components/animation-component.ts +++ b/cocos/components/animation-component.ts @@ -153,10 +153,6 @@ export class AnimationComponent extends Component implements IEventTarget { @property private _defaultClip: AnimationClip | null = null; - constructor () { - super(); - } - public onLoad () { this.clips = this._clips; } diff --git a/cocos/renderer/models/skinning-model.ts b/cocos/renderer/models/skinning-model.ts index c608748ed6..bc22b6e129 100644 --- a/cocos/renderer/models/skinning-model.ts +++ b/cocos/renderer/models/skinning-model.ts @@ -28,7 +28,6 @@ */ import { Skeleton } from '../../3d/assets/skeleton'; -import { LCA } from '../../3d/misc/utils'; import { Filter, PixelFormat, WrapMode } from '../../assets/asset-enum'; import { Texture2D } from '../../assets/texture-2d'; import { Mat4, Quat, Vec3 } from '../../core/value-types'; @@ -74,51 +73,10 @@ const _jointsFormat = { [JointsMediumType.RGBA32F]: PixelFormat.RGBA32F, }; -const v3_1 = new Vec3(); -const v3_2 = new Vec3(); const qt_0 = new Quat(); const qt_1 = new Quat(); -const qt_2 = new Quat(); const m4_1 = new Mat4(); const f4_1 = new Float32Array(4); -const SKINNING_INTERVAL = 1000 / 30; - -export class Joint { - public node: Node; - public position: Vec3 = new Vec3(); - public rotation: Quat = new Quat(); - public scale: Vec3 = new Vec3(1, 1, 1); - public parent: Joint | null = null; - protected _lastUpdate = -1; - constructor (node: Node) { this.node = node; } - public update () { - const totalFrames = cc.director.getTotalFrames(); - if (this._lastUpdate >= totalFrames) { return; } - this._lastUpdate = totalFrames; - - const parent = this.parent; - if (parent) { - parent.update(); - vec3.multiply(this.position, this.node.position, parent.scale); - vec3.transformQuat(this.position, this.position, parent.rotation); - vec3.add(this.position, this.position, parent.position); - quat.multiply(this.rotation, parent.rotation, this.node.rotation); - vec3.multiply(this.scale, parent.scale, this.node.scale); - } - } -} - -class JointManager { - public static get (node: Node, root: Node) { - let joint = JointManager._joints.get(node); - if (joint) { return joint; } - joint = new Joint(node); - if (node !== root && node.parent) { joint.parent = JointManager.get(node.parent, root); } - JointManager._joints.set(node, joint); - return joint; - } - protected static _joints: Map = new Map(); -} export class SkinningModel extends Model { // change here and cc-skinning.inc to use other skinning algorithms @@ -129,14 +87,12 @@ export class SkinningModel extends Model { } private _skeleton: Skeleton | null = null; - private _joints: Joint[] = []; + private _joints: Node[] = []; private _jointsMedium: IJointsInfo | null = null; - private _lastUpdate = 0; constructor (scene: RenderScene, node: Node) { super(scene, node); this._type = 'skinning'; - if (node.parent) { this._transform = node.parent; } } public bindSkeleton (skeleton: Skeleton | null) { @@ -187,10 +143,13 @@ export class SkinningModel extends Model { public updateUBOs () { if (!super.updateUBOs() || !this._skeleton) { return false; } - const now = cc.director.getCurrentTime(); - if (now - this._lastUpdate < SKINNING_INTERVAL) { return true; } - this._lastUpdate = now; - + /* */ + const len = this._joints.length; + for (let i = 0; i < len; ++i) { + const cur = this._joints[i]; + this.updateJointData(i, cur.position, cur.rotation, cur.scale); + } + /* * const len = this._joints.length; if (this._skeleton.bindTRS.length) { // TODO: pre-apply this into animation clip for (let i = 0; i < len; ++i) { @@ -212,24 +171,23 @@ export class SkinningModel extends Model { this.updateJointData(i, cur.position, cur.rotation, cur.scale); } } + /* */ this.commitJointData(); return true; } public resetSkinningTarget (skinningRoot: Node) { - // should be the hosting node of the controlling animation component - // here we are approximating with a specific LCA but it should work anyways - const root = LCA(this.node, skinningRoot); - if (!root || !this._skeleton) { return; } + if (!skinningRoot || !this._skeleton) { return; } + this._transform = skinningRoot.parent!; this._joints.length = 0; this._skeleton.joints.forEach((path) => { - const targetNode = skinningRoot.getChildByPath(path); + const targetNode = this._transform.getChildByPath(path); if (!targetNode) { console.warn(`Skinning target ${path} not found in scene graph.`); return; } - this._joints.push(JointManager.get(targetNode, root)); + this._joints.push(targetNode); }); }