From c23b7bde62f8bde98677fcf8a08e166a65fbc7a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 11 Nov 2022 11:00:42 +0800 Subject: [PATCH] AnimationController: optimize status query methods, add layer count getter (#13323) --- .../marionette/animation-controller.ts | 25 +- cocos/animation/marionette/graph-eval.ts | 25 +- tests/animation/newgenanim.test.ts | 213 +++++++++++++++++- .../value-type-asymmetric-matchers.ts | 27 +++ 4 files changed, 270 insertions(+), 20 deletions(-) create mode 100644 tests/utils/matchers/value-type-asymmetric-matchers.ts diff --git a/cocos/animation/marionette/animation-controller.ts b/cocos/animation/marionette/animation-controller.ts index bddf996b45..0ca5ff547d 100644 --- a/cocos/animation/marionette/animation-controller.ts +++ b/cocos/animation/marionette/animation-controller.ts @@ -38,6 +38,15 @@ export class AnimationController extends Component { private _graphEval: AnimationGraphEval | null = null; + /** + * @zh 获取动画图的层级数量。如果控制器没有指定动画图,则返回 0。 + * @en Gets the count of layers in the animation graph. + * If no animation graph is specified, 0 is returned. + */ + public get layerCount () { + return this._graphEval?.layerCount ?? 0; + } + public __preload () { if (this.graph) { this._graphEval = new AnimationGraphEval(this.graph as AnimationGraph, this.node, this); @@ -99,8 +108,8 @@ export class AnimationController extends Component { * @zh 获取动画图实例中当前状态的运行状况。 * @en Gets the running status of the current state in the animation graph instance. * @param layer @en Index of the layer. @zh 层级索引。 - * @returns @en The running status of the current state. - * @zh 当前的状态运作状态对象。 + * @returns @en The running status of the current state. `null` is returned if current state is not a motion state. + * @zh 当前的状态运作状态对象。如果当前的状态不是动作状态,则返回 `null`。 */ public getCurrentStateStatus (layer: number) { const { _graphEval: graphEval } = this; @@ -113,7 +122,8 @@ export class AnimationController extends Component { * @en Gets the running status of all the animation clips added on the current state in the animation graph instance. * @param layer @en Index of the layer. @zh 层级索引。 * @returns @en Iterable to the animation clip statuses on current state. - * @zh 到动画剪辑运作状态的迭代器。 + * An empty iterable is returned if current state is not a motion state. + * @zh 到动画剪辑运作状态的迭代器。若当前状态不是动画状态,则返回一个空的迭代器。 */ public getCurrentClipStatuses (layer: number) { const { _graphEval: graphEval } = this; @@ -138,8 +148,8 @@ export class AnimationController extends Component { * @zh 获取动画图实例中下一个状态的运行状况。 * @en Gets the running status of the next state in the animation graph instance. * @param layer @en Index of the layer. @zh 层级索引。 - * @returns @en The running status of the next state. `null` is returned in case of no transition. - * @zh 下一状态运作状态对象,若未在进行过渡,则返回 `null`。 + * @returns @en The running status of the next state. `null` is returned in case of no transition or if next state is not a motion state. + * @zh 下一状态运作状态对象,若未在进行过渡或下一状态不是动画状态,则返回 `null`。 */ public getNextStateStatus (layer: number) { const { _graphEval: graphEval } = this; @@ -151,8 +161,9 @@ export class AnimationController extends Component { * @zh 获取动画图实例中下一个状态上添加的所有动画剪辑的运行状况。 * @en Gets the running status of all the animation clips added on the next state in the animation graph instance. * @param layer @en Index of the layer. @zh 层级索引。 - * @returns @en Iterable to the animation clip statuses on next state. An empty iterable is returned in case of no transition. - * @zh 到下一状态上包含的动画剪辑运作状态的迭代器,若未在进行过渡,则返回一个空的迭代器。 + * @returns @en Iterable to the animation clip statuses on next state. + * An empty iterable is returned in case of no transition or next state is not a motion state. + * @zh 到下一状态上包含的动画剪辑运作状态的迭代器,若未在进行过渡或下一状态不是动画状态,则返回一个空的迭代器。 */ public getNextClipStatuses (layer: number) { const { _graphEval: graphEval } = this; diff --git a/cocos/animation/marionette/graph-eval.ts b/cocos/animation/marionette/graph-eval.ts index c6fb1b56d6..de661ee95e 100644 --- a/cocos/animation/marionette/graph-eval.ts +++ b/cocos/animation/marionette/graph-eval.ts @@ -77,6 +77,10 @@ export class AnimationGraphEval { } } + public get layerCount () { + return this._layerEvaluations.length; + } + public update (deltaTime: number) { const { _blendBuffer: blendBuffer, @@ -127,7 +131,6 @@ export class AnimationGraphEval { } public getNextClipStatuses (layer: number): Iterable> { - assertIsNonNullable(this.getCurrentTransition(layer), '!!this.getCurrentTransition(layer)'); return this._layerEvaluations[layer].getNextClipStatuses(); } @@ -149,10 +152,12 @@ export class AnimationGraphEval { } public getLayerWeight (layerIndex: number) { + assertIsTrue(layerIndex >= 0 && layerIndex < this._layerEvaluations.length, `Invalid layer index`); return this._layerEvaluations[layerIndex].weight; } public setLayerWeight (layerIndex: number, weight: number) { + assertIsTrue(layerIndex >= 0 && layerIndex < this._layerEvaluations.length, `Invalid layer index`); this._layerEvaluations[layerIndex].weight = weight; } @@ -325,7 +330,7 @@ class LayerEval { const { _currentTransitionPath: currentTransitionPath } = this; if (currentTransitionPath.length !== 0) { const lastNode = currentTransitionPath[currentTransitionPath.length - 1]; - if (lastNode.to.kind !== NodeKind.animation) { + if (lastNode.to.kind !== NodeKind.animation && lastNode.to.kind !== NodeKind.empty) { return false; } const { @@ -348,19 +353,23 @@ class LayerEval { } public getNextStateStatus (): Readonly | null { - assertIsTrue( - this._currentTransitionToNode && this._currentTransitionToNode.kind !== NodeKind.empty, - 'There is no transition currently in layer.', - ); + if (!this._currentTransitionToNode + || this._currentTransitionToNode.kind === NodeKind.empty) { + return null; + } return this._currentTransitionToNode.getToPortStatus(); } public getNextClipStatuses (): Iterable { const { _currentTransitionPath: currentTransitionPath } = this; const nCurrentTransitionPath = currentTransitionPath.length; - assertIsTrue(nCurrentTransitionPath > 0, 'There is no transition currently in layer.'); + if (nCurrentTransitionPath === 0) { + return emptyClipStatusesIterable; + } const to = currentTransitionPath[nCurrentTransitionPath - 1].to; - assertIsTrue(to.kind === NodeKind.animation); + if (to.kind !== NodeKind.animation) { + return emptyClipStatusesIterable; + } return to.getClipStatuses(this._toWeight) ?? emptyClipStatusesIterable; } diff --git a/tests/animation/newgenanim.test.ts b/tests/animation/newgenanim.test.ts index bf736f200a..b625bd0f6b 100644 --- a/tests/animation/newgenanim.test.ts +++ b/tests/animation/newgenanim.test.ts @@ -1,7 +1,7 @@ import { lerp, Vec3, warnID } from '../../cocos/core'; import { AnimationBlend1D, AnimationBlend2D, Condition, InvalidTransitionError, VariableNotDefinedError, ClipMotion, AnimationBlendDirect, VariableType, AnimationMask } from '../../cocos/animation/marionette/asset-creation'; -import { AnimationGraph, StateMachine, Transition, isAnimationTransition, AnimationTransition, TransitionInterruptionSource } from '../../cocos/animation/marionette/animation-graph'; +import { AnimationGraph, StateMachine, Transition, isAnimationTransition, AnimationTransition, TransitionInterruptionSource, State } from '../../cocos/animation/marionette/animation-graph'; import { VariableTypeMismatchedError } from '../../cocos/animation/marionette/errors'; import { AnimationGraphEval, MotionStateStatus, ClipStatus } from '../../cocos/animation/marionette/graph-eval'; import { createGraphFromDescription } from '../../cocos/animation/marionette/__tmp__/graph-from-description'; @@ -27,6 +27,9 @@ import { TriggerResetMode } from '../../cocos/animation/marionette/variable'; import { MotionState } from '../../cocos/animation/marionette/motion-state'; import { Node, Component } from '../../cocos/scene-graph'; import * as maskTestHelper from './new-gen-anim/utils/mask-test-helper'; +import '../utils/matchers/value-type-asymmetric-matchers'; + +const DEFAULT_AROUND_NUM_DIGITS = 5; describe('NewGen Anim', () => { test('Defaults', () => { @@ -1977,7 +1980,7 @@ describe('NewGen Anim', () => { // Start Motion -> Empty updater.goto(FIRST_TIME_EMPTY_REST_TIME + MOTION_EXIT_CONDITION + 0.15); expectAnimationGraphEvalStatus(graphEval, [ - { current: { clip: clipMotion!.clip, weight: 1.0 - 0.15 / MOTION_TO_EMPTY_DURATION } }, + { current: { clip: clipMotion!.clip, weight: 1.0 - 0.15 / MOTION_TO_EMPTY_DURATION }, transition: {} }, ]); expect(node.position.x).toBeCloseTo(lerp( MOTION_SAMPLE_RESULT_AT(MOTION_EXIT_CONDITION + 0.15), // Layer 0 result @@ -1988,7 +1991,7 @@ describe('NewGen Anim', () => { // Step for a little while updater.step(0.06); expectAnimationGraphEvalStatus(graphEval, [ - { current: { clip: clipMotion!.clip, weight: 1.0 - 0.21 / MOTION_TO_EMPTY_DURATION } }, + { current: { clip: clipMotion!.clip, weight: 1.0 - 0.21 / MOTION_TO_EMPTY_DURATION }, transition: {} }, ]); expect(node.position.x).toBeCloseTo(lerp( MOTION_SAMPLE_RESULT_AT(MOTION_EXIT_CONDITION + 0.21), // Layer 0 result @@ -2044,7 +2047,7 @@ describe('NewGen Anim', () => { updater.goto(0.3 * 1.0 + 0.12); expectAnimationGraphEvalStatus(graphEval, [ { current: { clip: layer0Clip!.clip, weight: 1.0 } }, - { current: { clip: layer1Clip.clip, weight: 1.0 - 0.12 / 0.5 } }, + { current: { clip: layer1Clip.clip, weight: 1.0 - 0.12 / 0.5 }, transition: {} }, ]); expect(node.position.x).toBeCloseTo(1.3 * (1.0 - 0.12 / 0.5) + 0.6 * (0.12 / 0.5)); }); @@ -2751,12 +2754,15 @@ describe('NewGen Anim', () => { ]); }); - test('Layer weight get/set', () => { + test('Layer weight get/set, layer count', () => { const animationGraph = new AnimationGraph(); const layer0 = animationGraph.addLayer(); const layer1 = animationGraph.addLayer(); layer1.weight = 0.4; const { newGenAnim: animationController } = createAnimationGraphEval2(animationGraph, new Node()); + + expect(animationController.layerCount).toBe(2); + expect(animationController.getLayerWeight(0)).toBe(1.0); expect(animationController.getLayerWeight(1)).toBe(0.4); animationController.setLayerWeight(0, 0.2); @@ -2765,6 +2771,203 @@ describe('NewGen Anim', () => { expect(animationController.getLayerWeight(1)).toBe(0.3); }); + test('No graph is specified', () => { + const node = new Node(); + const animationController = node.addComponent(AnimationController) as AnimationController; + + // SPEC: if no graph is specified, the layer count would be 0. + expect(animationController.layerCount).toBe(0); + }); + + describe(`Status query methods`, () => { + describe(`If no transition is being performed`, () => { + /** + * ### SPEC + * + * If a layer ran into an state and there is no transition is performing: + * + * - `getCurrentTransition` returns null. + * - `getNextStateStatus` returns null. + * - `getNextClipStatuses` yields nothing. + * - If the state is a motion state: + * - `getCurrentStateStatus` returns the status of the state, where: + * - `.time` gives the transition time(absolute, in seconds). + * - `.duration` gives the transition duration. + * - `getCurrentClipStatuses` return the status of the clips containing in the state, where: + * - `.clip` gives the clip. + * - `.weight` gives the clip's contribution in whole layer. + * - Otherwise: + * - `getCurrentStateStatus` returns null. + * - `getCurrentClipStatuses` yields nothing. + */ + const _SPEC = undefined; + + const commonCheck1 = (controller: AnimationController) => { + expect(controller.getCurrentTransition(0)).toBeNull(); + expect(controller.getNextStateStatus(0)).toBeNull(); + expect([...controller.getNextClipStatuses(0)]).toHaveLength(0); + }; + + test(`Motion state`, () => { + const fixture = { + motion_duration: 2.0, + state_time: 0.1, + }; + + const graph = new AnimationGraph(); + const mainLayer = graph.addLayer(); + const motionState = mainLayer.stateMachine.addMotion(); + const clipMotion = motionState.motion = createEmptyClipMotion(fixture.motion_duration); + mainLayer.stateMachine.connect(mainLayer.stateMachine.entryState, motionState); + + const { newGenAnim, graphEval } = createAnimationGraphEval2(graph, new Node()); + const graphUpdater = new GraphUpdater(graphEval); + + graphUpdater.step(fixture.state_time); + expect(newGenAnim.getCurrentStateStatus(0)).toMatchObject({ + progress: expect.toBeAround(fixture.state_time / fixture.motion_duration, DEFAULT_AROUND_NUM_DIGITS), + }); + expect([...newGenAnim.getCurrentClipStatuses(0)]).toMatchObject({ + [0]: { + clip: clipMotion.clip, + weight: 1.0, + }, + }); + commonCheck1(newGenAnim); + }); + + test(`Empty state`, () => { + const graph = new AnimationGraph(); + const mainLayer = graph.addLayer(); + const emptyState = mainLayer.stateMachine.addEmpty(); + mainLayer.stateMachine.connect(mainLayer.stateMachine.entryState, emptyState); + + const { newGenAnim, graphEval } = createAnimationGraphEval2(graph, new Node()); + const graphUpdater = new GraphUpdater(graphEval); + + graphUpdater.step(0.2); + expect(newGenAnim.getCurrentStateStatus(0)).toBeNull(); + expect([...newGenAnim.getCurrentClipStatuses(0)]).toHaveLength(0); + commonCheck1(newGenAnim); + }); + + test(`Top level entry state`, () => { + const graph = new AnimationGraph(); + const mainLayer = graph.addLayer(); + const motionState = mainLayer.stateMachine.addMotion(); + motionState.motion = createEmptyClipMotion(1.23 /** ANY */); + mainLayer.stateMachine.connect(mainLayer.stateMachine.entryState, motionState); + + const { newGenAnim: controller } = createAnimationGraphEval2(graph, new Node()); + + // Before any evaluation + + expect(controller.getCurrentStateStatus(0)).toBe(null); + expect([...controller.getCurrentClipStatuses(0)]).toHaveLength(0); + expect(controller.getCurrentTransition(0)).toBe(null); + expect(controller.getNextStateStatus(0)).toBe(null); + expect([...controller.getNextClipStatuses(0)]).toHaveLength(0); + }); + }); + + describe(`If the layer is performing transition`, () => { + /** + * ### SPEC + * + * If a layer is performing a transition: + * + * - `getCurrentTransition` returns the status of the transition: + * - `.time` gives the transition time(absolute, in seconds). + * - `.duration` gives the transition duration. + * + * - `getCurrentStateStatus`(`getNextStateStatus`) returns: + * - the status of transition source(destination), if the transition source(destination) is a motion state. + * - null otherwise. + * + * - `getCurrentClipStatuses`(`getNextClipStatuses`) yields: + * - the status of clips containing in transition source(destination), if the transition source(destination) is a motion state. + * - nothing otherwise. + */ + const _SPEC = undefined; + + test('Ran into a transition(Motion -> Empty)', () => { + const fixture = { + motion_duration: 2.0, + transition_duration: 0.25, + eval_time: 0.1, + }; + + const graph = new AnimationGraph(); + const mainLayer = graph.addLayer(); + const motionState = mainLayer.stateMachine.addMotion(); + const clipMotion = motionState.motion = createEmptyClipMotion(fixture.motion_duration); + const emptyState = mainLayer.stateMachine.addEmpty(); + mainLayer.stateMachine.connect(mainLayer.stateMachine.entryState, motionState); + const m2e = mainLayer.stateMachine.connect(motionState, emptyState); + m2e.duration = fixture.transition_duration; + m2e.exitConditionEnabled = true; + m2e.exitCondition = 0.0; // Immediately start the transition. + + const { newGenAnim: controller, graphEval } = createAnimationGraphEval2(graph, new Node()); + const graphUpdater = new GraphUpdater(graphEval); + + graphUpdater.step(fixture.eval_time); + expect(controller.getCurrentStateStatus(0)).toMatchObject({ + progress: expect.toBeAround(fixture.eval_time / fixture.motion_duration, DEFAULT_AROUND_NUM_DIGITS), + }); + expect([...controller.getCurrentClipStatuses(0)]).toEqual(expect.arrayContaining([ + expect.objectContaining({ + clip: clipMotion.clip, + weight: expect.toBeAround(1.0 - fixture.eval_time / fixture.transition_duration, DEFAULT_AROUND_NUM_DIGITS), + }), + ])); + expect(controller.getCurrentTransition(0)).toMatchObject({ + time: expect.toBeAround(fixture.eval_time, DEFAULT_AROUND_NUM_DIGITS), + duration: fixture.transition_duration, + }); + expect(controller.getNextStateStatus(0)).toBeNull(); + expect([...controller.getNextClipStatuses(0)]).toHaveLength(0); + }); + + test('Ran into a transition(Empty -> Motion)', () => { + const fixture = { + motion_duration: 2.0, + transition_duration: 0.25, + eval_time: 0.1, + }; + + const graph = new AnimationGraph(); + const mainLayer = graph.addLayer(); + const motionState = mainLayer.stateMachine.addMotion(); + const clipMotion = motionState.motion = createEmptyClipMotion(fixture.motion_duration); + const emptyState = mainLayer.stateMachine.addEmpty(); + mainLayer.stateMachine.connect(mainLayer.stateMachine.entryState, emptyState); + const transition = mainLayer.stateMachine.connect(emptyState, motionState); + transition.duration = fixture.transition_duration; + const [transitionCondition] = transition.conditions = [new UnaryCondition()]; + transitionCondition.operator = UnaryCondition.Operator.TRUTHY; + transitionCondition.operand.value = true; + + const { newGenAnim: controller, graphEval } = createAnimationGraphEval2(graph, new Node()); + const graphUpdater = new GraphUpdater(graphEval); + + graphUpdater.step(fixture.eval_time); + expect(controller.getCurrentStateStatus(0)).toBeNull(); + expect([...controller.getCurrentClipStatuses(0)]).toHaveLength(0); + expect(controller.getCurrentTransition(0)).toMatchObject({ + time: expect.toBeAround(fixture.eval_time, DEFAULT_AROUND_NUM_DIGITS), + duration: fixture.transition_duration, + }); + expect([...controller.getNextClipStatuses(0)]).toEqual(expect.arrayContaining([ + expect.objectContaining({ + clip: clipMotion.clip, + weight: expect.toBeAround(fixture.eval_time / fixture.transition_duration, DEFAULT_AROUND_NUM_DIGITS), + }), + ])); + }); + }); + }); + describe('Interruption', () => { test('Interruptible', () => { const animationGraph = new AnimationGraph(); diff --git a/tests/utils/matchers/value-type-asymmetric-matchers.ts b/tests/utils/matchers/value-type-asymmetric-matchers.ts new file mode 100644 index 0000000000..d5300ee528 --- /dev/null +++ b/tests/utils/matchers/value-type-asymmetric-matchers.ts @@ -0,0 +1,27 @@ +export { }; + +// https://stackoverflow.com/a/53464807 +expect.extend({ + toBeAround(actual: number, expected: number, numDigits = 5) { + const pass = Math.abs(expected - actual) < Math.pow(10, -numDigits) / 2; + if (pass) { + return { + message: () => `expected ${actual} not to be around ${expected}`, + pass: true, + }; + } else { + return { + message: () => `expected ${actual} to be around ${expected}`, + pass: false, + } + } + }, +}); + +declare global { + namespace jest { + interface Expect { + toBeAround(expected: number, numDigits?: number): any; + } + } +} \ No newline at end of file