From 4304c057455731e0cfa288304daaa48933c49bce 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, 12 May 2023 13:45:55 +0800 Subject: [PATCH] Complementarily implement pose graph (#14952) * Implement pose graph * Add test for query output node's input/outputs * Fix isWellFormedInputKey() * Tweak * Use `Map` instead of `shellTag` * Rename XNode -> PureValueNode * Rename node input manager and node input options --- cocos/animation/marionette/asset-creation.ts | 6 +- .../marionette/pose-graph/decorator/input.ts | 60 ++ .../marionette/pose-graph/decorator/node.ts | 54 ++ .../foundation/authoring/enter-node-info.ts | 10 + .../foundation/authoring/input-authoring.ts | 460 +++++++++++ .../foundation/authoring/node-authoring.ts | 97 +++ .../pose-graph/foundation/errors.ts | 13 + .../pose-graph/foundation/node-shell.ts | 230 ++++++ .../pose-graph/foundation/pose-graph-node.ts | 31 + .../pose-graph/foundation/type-system.ts | 15 + .../pose-graph/graph-output-node.ts | 24 + .../marionette/pose-graph/instantiation.ts | 340 +++++++- .../marionette/pose-graph/op/index.ts | 4 + .../marionette/pose-graph/op/internal.ts | 212 +++++ .../marionette/pose-graph/pose-graph.ts | 132 ++- .../marionette/pose-graph/pose-node.ts | 15 +- .../marionette/pose-graph/pure-value-node.ts | 50 ++ .../state-machine/state-machine-eval.ts | 2 +- editor/exports/new-gen-anim.ts | 2 + .../src/marionette/pose-graph-editor-api.ts | 77 ++ editor/src/marionette/visit.ts | 15 + scripts/native-pack-tool/package-lock.json | 2 +- tests/animation/new-gen-anim/event.test.ts | 2 +- .../pose-graph/pose-graph-authoring.test.ts | 770 ++++++++++++++++++ .../pose-graph/pose-graph-runtime.test.ts | 301 +++++++ .../pose-graph/top-level-pose-node.test.ts | 30 + .../new-gen-anim/pose-graph/utils/additive.ts | 48 ++ .../new-gen-anim/pose-graph/utils/misc.ts | 83 ++ tests/animation/new-gen-anim/utils/factory.ts | 42 +- 29 files changed, 3068 insertions(+), 59 deletions(-) create mode 100644 cocos/animation/marionette/pose-graph/decorator/input.ts create mode 100644 cocos/animation/marionette/pose-graph/decorator/node.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/authoring/enter-node-info.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/errors.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/node-shell.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/pose-graph-node.ts create mode 100644 cocos/animation/marionette/pose-graph/foundation/type-system.ts create mode 100644 cocos/animation/marionette/pose-graph/graph-output-node.ts create mode 100644 cocos/animation/marionette/pose-graph/op/index.ts create mode 100644 cocos/animation/marionette/pose-graph/op/internal.ts create mode 100644 cocos/animation/marionette/pose-graph/pure-value-node.ts create mode 100644 editor/src/marionette/pose-graph-editor-api.ts create mode 100644 tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts create mode 100644 tests/animation/new-gen-anim/pose-graph/pose-graph-runtime.test.ts create mode 100644 tests/animation/new-gen-anim/pose-graph/top-level-pose-node.test.ts create mode 100644 tests/animation/new-gen-anim/pose-graph/utils/additive.ts create mode 100644 tests/animation/new-gen-anim/pose-graph/utils/misc.ts diff --git a/cocos/animation/marionette/asset-creation.ts b/cocos/animation/marionette/asset-creation.ts index 03bb666c63..fa6494c930 100644 --- a/cocos/animation/marionette/asset-creation.ts +++ b/cocos/animation/marionette/asset-creation.ts @@ -40,5 +40,9 @@ export { VariableType } from './parametric'; export { BindableNumber, BindableBoolean } from './parametric'; export { AnimationMask } from './animation-mask'; export { AnimationGraphVariant } from './animation-graph-variant'; + export type { PoseGraph } from './pose-graph/pose-graph'; -export type { PoseNode } from './pose-graph/pose-node'; \ No newline at end of file + +export * from './pose-graph/op/index' +export type { EnterNodeInfo } from './pose-graph/foundation/authoring/enter-node-info'; + diff --git a/cocos/animation/marionette/pose-graph/decorator/input.ts b/cocos/animation/marionette/pose-graph/decorator/input.ts new file mode 100644 index 0000000000..9ee44060d9 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/decorator/input.ts @@ -0,0 +1,60 @@ +/* eslint-disable @typescript-eslint/ban-types */ + +import { error, js } from '../../../../core'; +import { PoseGraphNodeInputMappingOptions, globalPoseGraphNodeInputManager } from '../foundation/authoring/input-authoring'; +import { PoseGraphType } from '../foundation/type-system'; +import { PoseNode } from '../pose-node'; +import { PureValueNode } from '../pure-value-node'; + +export type { PoseGraphNodeInputMappingOptions }; + +/** + * @zh + * 生成一个属性装饰器,将要装饰的属性映射为一或多项姿势图结点输入。 + * @en + * Generates a property decorator, which maps the decorating property + * as one or more pose graph node inputs. + * + * @param options @zh 结点输入映射选项。 @en Node input mapping options. + * @returns @zh 装饰器。 @en The decorator. + * + * @note + * + * @zh 生成的装饰器对要装饰的属性所属的类有要求: + * - 如果结点输入选项中指定了输入类型为姿势,则所属类必须是 `PoseNode` 的子类。 + * - 否则,所属类必须是 `PoseNode` 或 `PureValueNode` 的子类。 + * 如果所属类不符合要求,此装饰器无效。 + * + * 如果要装饰的属性 **不是** 数组属性,则该属性将映射为一项输入; + * 否则,该属性的每个元素都将映射为一项输入。 + * + * @en The generated has requirements on the class to which the decorating property belongs: + * - If the node input option specifies that the input type is pose, then the belonging class should be subclass of `PoseNode`. + * - Otherwise, the belonging class should be subclass of either `PoseNode` or `PureValueNode`. + * The decorator takes no effect if the belonging class does not fulfill the requirements. + * + * If the decorating property is **NOT** an array, the property will be mapped as an input. + * Otherwise, each element of the property will be mapped as an input. + */ +export function input (options: PoseGraphNodeInputMappingOptions): PropertyDecorator { + return (target, propertyKey) => { + if (typeof propertyKey !== 'string') { + error(`@input can be only applied to string-named fields.`); + return; + } + const targetConstructor = target.constructor; + if (options.type === PoseGraphType.POSE) { + if (!js.isChildClassOf(targetConstructor, PoseNode)) { + error(`@input specifying pose input can be only applied to fields of subclasses of PoseNode.`); + return; + } + } + if ( + !js.isChildClassOf(targetConstructor, PoseNode) + && !js.isChildClassOf(targetConstructor, PureValueNode)) { + error(`@input can be only applied to fields of subclasses of PoseNode or PureValueNode.`); + return; + } + globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(targetConstructor, propertyKey, options); + }; +} diff --git a/cocos/animation/marionette/pose-graph/decorator/node.ts b/cocos/animation/marionette/pose-graph/decorator/node.ts new file mode 100644 index 0000000000..086efeb402 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/decorator/node.ts @@ -0,0 +1,54 @@ +import { error, js } from '../../../../core'; +import { PoseGraphNode } from '../foundation/pose-graph-node'; + +import { + PoseGraphCreateNodeFactory, + PoseGraphNodeEditorMetadata, + PoseGraphNodeAppearanceOptions, + getOrCreateNodeEditorMetadata, +} from '../foundation/authoring/node-authoring'; + +export type { + PoseGraphCreateNodeContext, + PoseGraphCreateNodeEntry, + PoseGraphCreateNodeFactory, + PoseGraphNodeEditorMetadata, + PoseGraphNodeAppearanceOptions, +} from '../foundation/authoring/node-authoring'; + +function makeNodeEditorMetadataModifier (edit: (metadata: PoseGraphNodeEditorMetadata) => void): ClassDecorator { + return (target) => { + if (!checkDecoratingClass(target)) { + return; + } + const metadata = getOrCreateNodeEditorMetadata(target); + edit(metadata); + }; +} + +export const poseGraphNodeMenu = (menu: string) => makeNodeEditorMetadataModifier((metadata) => { + metadata.menu = menu; +}); + +export const poseGraphCreateNodeFactory = (factory: PoseGraphCreateNodeFactory) => makeNodeEditorMetadataModifier((metadata) => { + metadata.factory = factory; +}); + +export const poseGraphNodeHide = (hide = true) => makeNodeEditorMetadataModifier((metadata) => { + metadata.hide = hide; +}); + +export const poseGraphNodeAppearance = ( + appearance: Readonly, +) => makeNodeEditorMetadataModifier((metadata) => { + Object.assign(metadata.appearance ??= {}, appearance); +}); + +// eslint-disable-next-line @typescript-eslint/ban-types +function checkDecoratingClass (fn: Function): fn is Constructor { + if (!js.isChildClassOf(fn, PoseGraphNode)) { + error(`This kind of decorator should only be applied to pose graph node classes.`); + return false; + } + return true; +} diff --git a/cocos/animation/marionette/pose-graph/foundation/authoring/enter-node-info.ts b/cocos/animation/marionette/pose-graph/foundation/authoring/enter-node-info.ts new file mode 100644 index 0000000000..9d668dc935 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/authoring/enter-node-info.ts @@ -0,0 +1,10 @@ +export type EnterNodeInfo = { + type: 'animation-blend'; + target: import('../../../motion/animation-blend').AnimationBlend; +} | { + type: 'state-machine'; + target: import('../../../animation-graph').StateMachine; +} | { + type: 'stash'; + stashName: string; +}; diff --git a/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts b/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts new file mode 100644 index 0000000000..a1b69008c4 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/authoring/input-authoring.ts @@ -0,0 +1,460 @@ +import { Quat, Vec3, assertIsTrue, js } from '../../../../../core'; +import { PoseGraphNode } from '../pose-graph-node'; +import { PoseGraphType } from '../type-system'; +import { NodeInputPath } from '../node-shell'; +import { OperationOnFreestandingNodeError } from '../errors'; +import type { PoseGraph } from '../../pose-graph'; + +export type PoseGraphInputKey = NodeInputPath; + +export interface PropertyNodeInputMetadata { + displayName?: string; +} + +interface ArrayPropertySyncGroup { + members: string[]; +} + +export interface PoseGraphNodeInputMetadata { + type: PoseGraphType; + + displayName?: string; + + deletable?: boolean; + + insertPoint?: boolean; +} + +// eslint-disable-next-line @typescript-eslint/ban-types +type Constructor = Function; + +interface PropertyNodeInputRecord { + type: PoseGraphType; + displayName?: string; + getArrayElementDisplayName?(index: number): string; + arraySyncGroup?: ArrayPropertySyncGroup; +} + +export type PoseGraphNodeInputInsertId = string; + +/** + * @zh 描述一个姿势图结点类属性在映射为结点输入时的选项。 + * @en Describes the options used + * when a pose node class property is going to be mapped as node input(s). + */ +export interface PoseGraphNodeInputMappingOptions { + /** + * @zh 此属性或属性的元素映射的输入类型。 + * 输入的类型必须和属性(的元素)的实际值类型匹配。 + * + * @en Type of the input(s) that the property associates. + * The input type should be matched with the actual value type of the property. + */ + type: PoseGraphType; + + /** + * @zh 此属性关联的输入的显示名称。 + * @en Display of the input(s) that the property associates. + */ + displayName?: string; + + /** + * @zh 若有定义,当该属性是数组时,此方法被用来获取数组各个元素所映射的输入的显示名称。 + * @en If specified and if the property is an array, + * this method will be used to retrieve the display name of input mapped by each element. + * @param index 数组元素的索引。 + */ + getArrayElementDisplayName?(index: number): string; + + /** + * @zh 若有定义,当该属性是数组时,声明该数组属性属于指定的同步组。 + * 同步组中的任何成员在进行输入增加、移除或挪动等操作时,其它成员也将进行该操作。 + * + * @en If specified and if the property is an array, + * declares that the array property belongs to specified sync group. + * When any member of the sync group is performing input add/remove/move etc. operation, + * the other members will also perform that operation. + * + * @example + * @zh + * 对于如下结点类来说: + * + * ```ts + * class Blending extends PoseNode { + * \@input({ type: PoseGraphType.POSE, syncGroup: 'blend-item' }) + * poses: PoseNode[] = []; + * + * \@input({ type: PoseGraphType.FLOAT, syncGroup: 'blend-item' }) + * weights: number[] = []; + * } + * ``` + * + * 当 `poses` 插入了一个新的输入后,`weights` 也会被插入一个新输入。 + * + * @en + * For the following node class: + * + * ```ts + * class Blending extends PoseNode { + * \@input({ type: PoseGraphType.POSE, syncGroup: 'blend-item' }) + * poses: PoseNode[] = []; + * + * \@input({ type: PoseGraphType.FLOAT, syncGroup: 'blend-item' }) + * weights: number[] = []; + * } + * ``` + * + * If a new input is inserted into `poses`, there will be also a new input inserted into weights. + */ + arraySyncGroup?: string; +} + +// eslint-disable-next-line @typescript-eslint/ban-types +class PoseGraphNodeInputManager { + public setPropertyNodeInputRecord ( + constructor: Constructor, + propertyKey: string, + options: PoseGraphNodeInputMappingOptions, + ) { + let classInputRecord = this._classInputMap.get(constructor); + if (!classInputRecord) { + classInputRecord = { + properties: {}, + }; + this._classInputMap.set(constructor, classInputRecord); + } + const { + arraySyncGroup, + ...unchanged + } = options; + + const record: PropertyNodeInputRecord = unchanged; + + const arraySyncGroupName = options.arraySyncGroup; + if (arraySyncGroupName) { + if (!classInputRecord.arraySyncGroups) { + classInputRecord.arraySyncGroups = {}; + } + const group = classInputRecord.arraySyncGroups[arraySyncGroupName] ??= { members: [] }; + if (!group.members.includes(propertyKey)) { + group.members.push(propertyKey); + } + record.arraySyncGroup = group; + } + + classInputRecord.properties[propertyKey] = Object.freeze(record); + } + + public getInputKeys (object: PoseGraphNode): readonly PoseGraphInputKey[] { + const result: PoseGraphInputKey[] = []; + const getInputKeysRecurse = (constructor: null | Constructor) => { + if (!constructor) { + return; + } + getInputKeysRecurse(js.getSuper(constructor)); + const record = this._classInputMap.get(constructor); + if (!record) { + return; + } + for (const [propertyKey] of Object.entries(record.properties)) { + // Subclass's input mapping declaration overrides base's. + if (result.findIndex(([subClassPropertyKey]) => propertyKey === subClassPropertyKey) >= 0) { + continue; + } + const field = object[propertyKey]; + if (Array.isArray(field)) { + for (let iElement = 0; iElement < field.length; ++iElement) { + result.push([propertyKey, iElement]); + } + } else { + result.push([propertyKey]); + } + } + }; + getInputKeysRecurse(object.constructor); + return result; + } + + public isPoseInput (object: PoseGraphNode, key: PoseGraphInputKey) { + const [propertyKey] = key; + const propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey); + if (!propertyInputRecord) { + return false; + } + return propertyInputRecord.type === PoseGraphType.POSE; + } + + public getInputMetadata (object: PoseGraphNode, key: PoseGraphInputKey): Readonly | undefined { + const [propertyKey, elementIndex = -1] = key; + const propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey); + if (!propertyInputRecord) { + return undefined; + } + const field = object[propertyKey]; + if (Array.isArray(field)) { + if (elementIndex < 0 || elementIndex >= field.length) { + return undefined; + } else { + const displayName = propertyInputRecord.getArrayElementDisplayName?.call(object, elementIndex) + ?? `${propertyInputRecord.displayName ?? propertyKey} ${elementIndex}`; + return { + type: propertyInputRecord.type, + displayName, + deletable: true, + insertPoint: true, + }; + } + } + return { + type: propertyInputRecord.type, + displayName: propertyInputRecord.displayName ?? propertyKey, + }; + } + + public hasInput (object: PoseGraphNode, key: PoseGraphInputKey) { + const [propertyKey, elementIndex = -1] = key; + const record = this._getPropertyNodeInputRecord(object.constructor, propertyKey); + if (!record) { + return false; + } + const field = object[propertyKey]; + if (Array.isArray(field)) { + if (elementIndex < 0 || elementIndex >= field.length) { + return false; + } + } + return true; + } + + public getInputInsertInfos (object: PoseGraphNode): Readonly> { + const result: Record = {}; + for (let constructor = object.constructor; constructor; constructor = js.getSuper(constructor)) { + const classInputRecord = this._classInputMap.get(constructor); + if (!classInputRecord) { + continue; + } + for (const propertyKey in classInputRecord.properties) { + const propertyInputRecord = classInputRecord.properties[propertyKey]; + const property = object[propertyKey]; + if (Array.isArray(property)) { + result[propertyKey] = { displayName: propertyKey }; + } + } + } + return result; + } + + public deleteInput (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey) { + const [ + propertyKey, + elementIndex = -1, + ] = key; + const propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey); + if (!propertyInputRecord) { + return; + } + const property = node[propertyKey]; + if (!Array.isArray(property)) { + return; + } + if (elementIndex < 0 || elementIndex >= property.length) { + return; + } + + // If it's an array record and belongs to a sync group, + // Perform the deletion on all group members. + // > Note: currently we can only insert input to array. + // eslint-disable-next-line no-constant-condition + if (true) { + const { arraySyncGroup } = propertyInputRecord; + if (arraySyncGroup) { + this._deleteInputInArraySyncGroup( + graph, + node, + arraySyncGroup, + property.length, + elementIndex, + ); + return; + } + } + + deletePoseGraphNodeArrayElement(graph, node, key); + } + + public insertInput (graph: PoseGraph, node: PoseGraphNode, insertId: PoseGraphNodeInputInsertId) { + const propertyKey = insertId; + const propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey); + if (!propertyInputRecord) { + return; + } + const property = node[propertyKey]; + if (!Array.isArray(property)) { + return; + } + + const hint = property.length; // Always insert from back. + + // If it's an array record and belongs to a sync group, + // Perform the insertion on all group members. + // > Note: currently we can only insert input to array. + // eslint-disable-next-line no-constant-condition + if (true) { + const { arraySyncGroup } = propertyInputRecord; + if (arraySyncGroup) { + this._insertInputInArraySyncGroup( + graph, + node, + arraySyncGroup, + property.length, + hint, + ); + return; + } + } + + insertPoseGraphNodeArrayElement( + graph, + node, + [propertyKey, hint], + createDefaultInputValueByType(propertyInputRecord.type), + ); + } + + private _classInputMap = new WeakMap; + arraySyncGroups?: Record; + }>(); + + private _getPropertyNodeInputRecord (constructor: null | Constructor, propertyKey: string): PropertyNodeInputRecord | undefined { + if (!constructor) { + return undefined; + } + const classInputRecord = this._classInputMap.get(constructor); + if (classInputRecord) { + const record = classInputRecord.properties[propertyKey]; + if (record) { + return record; + } + } + return this._getPropertyNodeInputRecord(js.getSuper(constructor), propertyKey); + } + + private _insertInputInArraySyncGroup ( + graph: PoseGraph, + node: PoseGraphNode, + syncGroup: ArrayPropertySyncGroup, + expectedOriginalSyncLength: number, + insertHint: number, + ) { + for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) { + const syncedPropertyKey = syncGroup.members[iGroupMember]; + const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey); + assertIsTrue(syncedPropertyInputRecord); + const syncedProperty = node[syncedPropertyKey]; + if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) { + // The property is declared with a "syncWith", + // but the sync target property is not an array or does not have a matched length. + // To avoid un-expectations, interrupt. + continue; + } + insertPoseGraphNodeArrayElement( + graph, + node, + [syncedPropertyKey, insertHint], + createDefaultInputValueByType(syncedPropertyInputRecord.type), + ); + } + } + + private _deleteInputInArraySyncGroup ( + graph: PoseGraph, + node: PoseGraphNode, + syncGroup: ArrayPropertySyncGroup, + expectedOriginalSyncLength: number, + index: number, + ) { + for (let iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) { + const syncedPropertyKey = syncGroup.members[iGroupMember]; + const syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey); + assertIsTrue(syncedPropertyInputRecord); + const syncedProperty = node[syncedPropertyKey]; + if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) { + // The property is declared with a "syncWith", + // but the sync target property is not an array or does not have a matched length. + // To avoid un-expectations, interrupt. + continue; + } + deletePoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, index]); + } + } +} + +function insertPoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey, value: unknown) { + const shell = graph.getShell(node); + if (!shell) { + throw new OperationOnFreestandingNodeError(node); + } + + const [ + propertyKey, + elementIndex = -1, + ] = inputKey; + const property = node[propertyKey]; + if (!Array.isArray(property)) { + return; + } + + // Insert the element itself. + property.splice(elementIndex, 0, value); + + // Update bindings for following elements. + shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, false); +} + +function deletePoseGraphNodeArrayElement (graph: PoseGraph, node: PoseGraphNode, inputKey: PoseGraphInputKey) { + const shell = graph.getShell(node); + if (!shell) { + throw new OperationOnFreestandingNodeError(node); + } + + const [ + propertyKey, + elementIndex = -1, + ] = inputKey; + const property = node[propertyKey]; + if (!Array.isArray(property)) { + return; + } + if (elementIndex < 0 || elementIndex >= property.length) { + return; + } + + // Delete the binding. + shell.deleteBinding(inputKey); + + // Delete the element itself. + property.splice(elementIndex, 1); + + // Update bindings for following elements. + shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, true); +} + +function createDefaultInputValueByType (type: PoseGraphType) { + switch (type) { + default: + assertIsTrue(false); + // fallthrough + case PoseGraphType.FLOAT: + case PoseGraphType.INTEGER: + return 0; + case PoseGraphType.POSE: + return null; + case PoseGraphType.VEC3: + return new Vec3(); + case PoseGraphType.QUAT: + return new Quat(); + } +} + +export const globalPoseGraphNodeInputManager = new PoseGraphNodeInputManager(); diff --git a/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts b/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts new file mode 100644 index 0000000000..0b5564ed71 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring.ts @@ -0,0 +1,97 @@ +import type { AnimationGraph } from '../../../animation-graph'; +import { PoseGraphNode } from '../pose-graph-node'; + +export {}; + +export interface PoseGraphCreateNodeContext { + animationGraph: AnimationGraph; + + layerIndex: number; +} + +export interface PoseGraphCreateNodeEntry { + arg: TArg; + + menu: string; +} + +export interface PoseGraphCreateNodeFactory { + listEntries(context: PoseGraphCreateNodeContext): Iterable>; + + create: (arg: TArg) => PoseGraphNode; +} + +export interface PoseGraphNodeEditorMetadata { + /** + * @zh + * 为 `true` 时表示此类型的结点对象不应该被编辑器创建和编辑。 + * @en + * If `true`, nodes of this type should not be created and edited by editor. + */ + hide?: boolean; + + /** + * @zh + * 此类型的结点的菜单路径。 + * @en + * The menu path of this type of nodes. + */ + menu?: string; + + /** + * @zh + * 创建此类型结点应使用的选项和方法。 + * @en + * The options and factory should be taken to create this type of nodes. + */ + factory?: PoseGraphCreateNodeFactory; + + /** + * @zh + * 此类型结点的外观配置。 + * @en + * The appearance configs of this type of nodes. + */ + appearance?: PoseGraphNodeAppearanceOptions; +} + +/** + * @zh 描述某类型结点的编辑器外观选项。 + * @en Describes the editor appearance of a type of nodes. + */ +export interface PoseGraphNodeAppearanceOptions { + /** + * @zh + * 主题颜色。目前应为以 “#” 开头的十六进制字符串颜色表示,例如 `"#FF00FF"`。 + * @en + * Theme color. Currently should be a color hex string starting with "#", for example: `"#FF00FF"`. + */ + themeColor?: `#${string}`; + + /** + * @zh + * 为 `true` 时表示展示该类型结点时尽可能地使用“内联”样式。 + * @en + * If `true`, indicates editor should show this type of nodes in "inline" style if possible. + */ + inline?: boolean; +} + +const nodeEditorMetadataMap = new WeakMap, PoseGraphNodeEditorMetadata>(); + +export function getPoseGraphNodeEditorMetadata ( + classConstructor: Constructor, +): Readonly | undefined { + return nodeEditorMetadataMap.get(classConstructor); +} + +export function getOrCreateNodeEditorMetadata (constructor: Constructor) { + const existing = nodeEditorMetadataMap.get(constructor); + if (existing) { + return existing; + } else { + const metadata: PoseGraphNodeEditorMetadata = {}; + nodeEditorMetadataMap.set(constructor, metadata); + return metadata; + } +} diff --git a/cocos/animation/marionette/pose-graph/foundation/errors.ts b/cocos/animation/marionette/pose-graph/foundation/errors.ts new file mode 100644 index 0000000000..05c934e595 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/errors.ts @@ -0,0 +1,13 @@ +import { PoseGraphNode } from './pose-graph-node'; + +export class AddNonFreestandingNodeError extends Error { + constructor (node: PoseGraphNode) { + super(`Can not add the specified ${node.toString()} since it has already been added into another graph.`); + } +} + +export class OperationOnFreestandingNodeError extends Error { + constructor (node: PoseGraphNode) { + super(`Can not perform specified operation on ${node.toString()} since it has not been added in to graph.`); + } +} diff --git a/cocos/animation/marionette/pose-graph/foundation/node-shell.ts b/cocos/animation/marionette/pose-graph/foundation/node-shell.ts new file mode 100644 index 0000000000..e813c90abd --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/node-shell.ts @@ -0,0 +1,230 @@ +import { EditorExtendable } from '../../../../core'; +import { ccclass, serializable } from '../../../../core/data/decorators'; +import { CLASS_NAME_PREFIX_ANIM } from '../../../define'; +import { PoseGraphNode } from './pose-graph-node'; + +/** + * @zh + * 描述姿势图结点上的某项输入的路径。 + * @en + * Describes the path to a input of a pose graph node. + * + * @internal Internally, the path is stored as an tuple. + * The first element of tuple is always the input's property key. + * There can be an optional second tuple element, + * which represents the input's property's element, if it's an array property. + */ +export type NodeInputPath = readonly [string] | readonly [string, number]; + +/** + * @zh 表示姿势图结点的外壳。 + * + * 结点外壳是附着在结点上的、对结点之间的连接(称之为绑定)的描述。 + * 外壳由姿势图以及绑定系统操纵,结点对于其外壳是无感知的。 + * + * @en Represents the shell of a pose graph node. + * + * The node shell is attached to a node, + * and describes the connections(so called binding) between nodes. + * Shells are manipulated by pose graph and binding system. + * Nodes are imperceptible to their shells. + */ +@ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseGraphNodeShell`) +export class PoseGraphNodeShell extends EditorExtendable { + /** + * @zh + * 获取此结点上的所有的绑定。 + * @en + * Gets all bindings on this node. + * @returns @zh 绑定对象数组。 @en The binding objects array. + */ + public getBindings () { + return this._bindings; + } + + /** + * @zh + * 添加一项绑定。 + * @en + * Adds a binding. + * @param inputPath @zh 要绑定的输入的路径。 @en Path of the input to bind. + * @param producer @zh 生产方结点。 @en The producer node. + * @param outputIndex @zh 要绑定的生产方的输出索引。 @en Index of the output to bind. + * @note + * @zh 绑定是由三元组输入路径、生产方结点和生产方索引唯一键定的。重复的添加相同绑定没有效果。 + * @en A binding is keyed by the 3-element tuple: input path, producer node and producer output index. + * Redundantly adding a binding takes no effect. + */ + public addBinding (inputPath: NodeInputPath, producer: PoseGraphNode, outputIndex: number) { + this._emplaceBinding(new PoseGraphNodeInputBinding( + inputPath, + producer, + outputIndex, + )); + } + + /** + * @zh + * 删除指定输入上的绑定。 + * @en + * Deletes the binding on specified input. + * @param inputPath @zh 要解绑的输入的路径。 @en Path of the input to unbind. + */ + public deleteBinding (inputPath: NodeInputPath) { + const index = this._findBindingIndex(inputPath); + if (index >= 0) { + this._bindings.splice(index); + } + } + + /** + * @zh + * 更新绑定, + * 对于具有相同属性键的、索引小于(或大于) `firstIndex` 的输入的绑定, + * 将它们替换为上一个(或下一个)索引上的绑定。 + * @en + * Update bindings so that + * for the input bindings having specified property key but having element index less than the specified index, + * substitute them as previous(or next) index's binding. + * @param propertyKey @zh 输入的属性键。 @en The input's property key. + * @param firstIndex @zh 见描述。 @en See description. + * @param forward @en 替换的方向。`true` 表示向前替换,反之向后。 + * @en Substitution direction. `true` means substitute in forward, backward otherwise. + */ + public moveArrayElementBindingForward (propertyKey: string, firstIndex: number, forward: boolean) { + // TODO: this method has worse performance! + const { _bindings: bindings } = this; + + const oldBindings: PoseGraphNodeInputBinding[] = []; + for (let iBinding = 0; + iBinding < bindings.length; // Note: array length may be varied. + ++iBinding + ) { + const binding = bindings[iBinding]; + const [consumerPropertyKey, consumerElementIndex = -1] = binding.inputPath; + if (consumerPropertyKey === propertyKey && consumerElementIndex >= firstIndex) { + oldBindings.push(binding); + bindings.splice(iBinding, 1); + } + } + + for (const oldBinding of oldBindings) { + const [consumerPropertyKey, consumerElementIndex = -1] = oldBinding.inputPath; + this.addBinding( + [consumerPropertyKey, consumerElementIndex + (forward ? -1 : 1)], + oldBinding.producer, + oldBinding.outputIndex, + ); + } + } + + /** + * @zh + * 删除绑定到指定生产方结点的所有绑定。 + * @en + * Deletes all the bindings bound to specified producer. + * @param producer @zh 生产方结点。 @en The producer node. + */ + public deleteBindingTo (producer: PoseGraphNode) { + const { _bindings: bindings } = this; + for (let iBinding = 0; + iBinding < bindings.length; // Note: array length might vary + ++iBinding + ) { + const binding = bindings[iBinding]; + if (binding.producer === producer) { + bindings.splice(iBinding, 1); + } + } + } + + /** + * @zh + * 查找指定输入上的绑定。 + * @en + * Finds the binding on specified input. + * @param inputPath @zh 要查找的输入的路径。 @en Path of the input to find. + */ + public findBinding (inputPath: NodeInputPath): PoseGraphNodeInputBinding | undefined { + const bindingIndex = this._findBindingIndex(inputPath); + return bindingIndex >= 0 ? this._bindings[bindingIndex] : undefined; + } + + @serializable + private _bindings: PoseGraphNodeInputBinding[] = []; + + private _findBindingIndex (inputPath: NodeInputPath) { + return this._bindings.findIndex( + (searchElement) => isEqualNodeInputPath(searchElement.inputPath, inputPath), + ); + } + + private _emplaceBinding (binding: PoseGraphNodeInputBinding) { + const index = this._bindings.findIndex( + (searchElement) => isEqualNodeInputPath(searchElement.inputPath, binding.inputPath), + ); + if (index >= 0) { + this._bindings[index] = binding; + } else { + this._bindings.push(binding); + } + } +} + +function isEqualNodeInputPath (lhs: NodeInputPath, rhs: NodeInputPath) { + const [lhsPropertyKey, lhsElementIndex] = lhs; + const [rhsPropertyKey, rhsElementIndex] = rhs; + return lhsPropertyKey === rhsPropertyKey && lhsElementIndex === rhsElementIndex; +} + +/** + * @zh 描述既定结点(作为消费方)和另一结点(作为生产方)之间的绑定信息。 + * @en Describes the binding information between a given node(as consumer) and another node(as producer). + */ +@ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseGraphNodeInputBinding`) +class PoseGraphNodeInputBinding { + constructor ( + inputPath: NodeInputPath, + producer: PoseGraphNode, + outputIndex: number, + ) { + this._inputPath = inputPath; + this._producer = producer; + this._outputIndex = outputIndex; + } + + /** + * @zh 消费方结点的输入路径。 + * @en Input path of consumer node. + */ + get inputPath () { + return this._inputPath; + } + + /** + * @zh 生产方结点。 + * @en The producer node. + */ + get producer () { + return this._producer; + } + + /** + * @zh 生产方结点的输出索引。 + * @en The producer node's output index. + */ + get outputIndex () { + return this._outputIndex; + } + + @serializable + private _inputPath: NodeInputPath; + + @serializable + private _producer: PoseGraphNode; + + @serializable + private _outputIndex = 0; +} + +export type { PoseGraphNodeInputBinding }; diff --git a/cocos/animation/marionette/pose-graph/foundation/pose-graph-node.ts b/cocos/animation/marionette/pose-graph/foundation/pose-graph-node.ts new file mode 100644 index 0000000000..de5ff1f292 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/pose-graph-node.ts @@ -0,0 +1,31 @@ +import { EditorExtendable } from '../../../../core'; +import { EnterNodeInfo } from './authoring/enter-node-info'; + +/** + * @zh + * 姿势图中的结点类。 + * @en + * Class of node in pose graph. + */ +export class PoseGraphNode extends EditorExtendable { + /** + * @internal Temporarily hack for deserialization callback. + */ + __callOnAfterDeserializeRecursive?(): void; + + /** + * @zh + * 获取该结点的标题。 + * @en + * Gets title of this node. + */ + public getTitle?(): string; + + /** + * @zh + * 获取该结点的进入信息。 + * @en + * Gets enter info of this node. + */ + public getEnterInfo?(): EnterNodeInfo | undefined; +} diff --git a/cocos/animation/marionette/pose-graph/foundation/type-system.ts b/cocos/animation/marionette/pose-graph/foundation/type-system.ts new file mode 100644 index 0000000000..318cd919da --- /dev/null +++ b/cocos/animation/marionette/pose-graph/foundation/type-system.ts @@ -0,0 +1,15 @@ +export {}; + +export enum PoseGraphType { + FLOAT, + + INTEGER, + + BOOLEAN, + + VEC3, + + QUAT, + + POSE, +} diff --git a/cocos/animation/marionette/pose-graph/graph-output-node.ts b/cocos/animation/marionette/pose-graph/graph-output-node.ts new file mode 100644 index 0000000000..c8362c68c5 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/graph-output-node.ts @@ -0,0 +1,24 @@ +import { EDITOR } from 'internal:constants'; +import { ccclass, serializable } from '../../../core/data/decorators'; +import { CLASS_NAME_PREFIX_ANIM } from '../../define'; +import { PoseNode } from './pose-node'; +import { PoseGraphType } from './foundation/type-system'; +import { PoseGraphNode } from './foundation/pose-graph-node'; +import { globalPoseGraphNodeInputManager } from './foundation/authoring/input-authoring'; + +@ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseGraphOutputNode`) +export class PoseGraphOutputNode extends PoseGraphNode { + // Don't use @input since it requires the owner class being subclass of `PoseNode`. + @serializable + pose: PoseNode | null = null; +} + +globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(PoseGraphOutputNode, 'pose', { + type: PoseGraphType.POSE, +}); + +if (EDITOR) { + PoseGraphOutputNode.prototype.getTitle = function getTitle (this: PoseGraphOutputNode) { + return '输出姿势'; + }; +} diff --git a/cocos/animation/marionette/pose-graph/instantiation.ts b/cocos/animation/marionette/pose-graph/instantiation.ts index 8270b848a8..9b3d49cba9 100644 --- a/cocos/animation/marionette/pose-graph/instantiation.ts +++ b/cocos/animation/marionette/pose-graph/instantiation.ts @@ -1,19 +1,341 @@ -import { instantiate } from '../../../serialization/instantiate'; -import { PoseGraph } from './pose-graph'; -import { PoseNode } from './pose-node'; +// cSpell:words Evaluatable -export function instantiatePoseGraph (poseGraph: PoseGraph): PoseNode | null { - return poseGraph.main - ? instantiatePoseNode(poseGraph.main) - : null; +import { assertIsTrue, warn } from '../../../core'; +import { instantiate } from '../../../serialization'; +import { PoseNode } from './pose-node'; +import { PoseGraph } from './pose-graph'; +import { PureValueNode, PureValueNodeLinkContext } from './pure-value-node'; +import { NodeInputPath } from './foundation/node-shell'; +import { PoseGraphNode } from './foundation/pose-graph-node'; + +type EvaluatableNode = PoseNode | PureValueNode; + +function isEvaluatableNode (node: PoseGraphNode): node is EvaluatableNode { + return (node instanceof PoseNode || node instanceof PureValueNode); } -function instantiatePoseNode (node: PoseNode) { +export function instantiatePoseGraph ( + graph: PoseGraph, + linkContext: PureValueNodeLinkContext, +): PoseNode | undefined { + const { + outputNode, + } = graph; + + const outputNodeShell = graph.getShell(outputNode); + assertIsTrue(outputNodeShell); + const bindings = outputNodeShell.getBindings(); + // Output node can only has 1 or has no binding. + assertIsTrue(bindings.length < 2); + if (bindings.length === 0) { + return undefined; + } + // If the output node has a binding, it must be pose node. + const binding = bindings[0]; + assertIsTrue(binding.outputIndex === 0); + assertIsTrue(binding.producer instanceof PoseNode); + + const instantiationMap = new Map(); + const mainRecord = instantiateNode( + graph, + binding.producer, + instantiationMap, + linkContext, + ); + assertIsTrue(mainRecord instanceof PoseNode); + + return mainRecord; +} + +export interface PoseNodeDependencyEvaluation { + evaluate(): void; +} + +function instantiateNode ( + graph: PoseGraph, + node: TNode, + instantiationMap: Map, + linkContext: PureValueNodeLinkContext, +): RuntimeNodeEvaluation { + const shell = graph.getShell(node); + assertIsTrue(shell, `Want to instantiate an unbound graph?`); + + const existing = instantiationMap.get(node); + if (existing) { + return existing; + } + const instantiated = instantiate(node); + + // Invoke serialization callback. if ('__callOnAfterDeserializeRecursive' in instantiated) { (instantiated as unknown as { __callOnAfterDeserializeRecursive(): void; }).__callOnAfterDeserializeRecursive(); } - return instantiated; + + /** Link. */ + if (instantiated instanceof PureValueNode) { + instantiated.link(linkContext); + } + + /** Alias. */ + const consumerNode = instantiated; + + /** + * Create the pv-node property binding records. + */ + const runtimePVNodePropertyBindings: RuntimePVNodePropertyBinding[] = []; + for (const { + producer: producerNode, + outputIndex: producerOutputIndex, + inputPath: consumerInputPath, + } of shell.getBindings()) { + if (!isEvaluatableNode(producerNode)) { + warn(`There's a input bound to a node with unrecognized type.`); + continue; + } + const producer = instantiateNode(graph, producerNode, instantiationMap, linkContext); + if (producer instanceof PoseNode) { + // Rule: pose nodes can only be used to feed pose nodes. + assertIsTrue(consumerNode instanceof PoseNode); + // Core code: link pose nodes. + linkPoseNode( + consumerNode, + consumerInputPath, + producer, + producerOutputIndex, + ); + } else { + const runtimePVNodePropertyBinding = linkPVNode( + consumerNode, + consumerInputPath, + producer, + producerOutputIndex, + ); + if (runtimePVNodePropertyBinding) { + runtimePVNodePropertyBindings.push(runtimePVNodePropertyBinding); + } + } + } + + // Create the dependency evaluation. + const dependencyEvaluation = new DependencyEvaluation(runtimePVNodePropertyBindings); + + // Create the evaluation record. + let evaluation: PoseNode | RuntimeNodeEvaluation; + if (consumerNode instanceof PoseNode) { + // If this is pose node. Injects the dependency. + consumerNode._setDependencyEvaluation(dependencyEvaluation); + evaluation = consumerNode; + } else { + // Otherwise, create the evaluation record. + const pureValueNodeEvaluation = new RuntimePVNodeEvaluation(consumerNode, dependencyEvaluation); + evaluation = pureValueNodeEvaluation; + } + + instantiationMap.set(node, evaluation); + return evaluation; +} + +class DependencyEvaluation implements PoseNodeDependencyEvaluation { + constructor ( + bindingEvaluations: readonly RuntimePVNodePropertyBinding[], + ) { + this._bindingEvaluations = bindingEvaluations; + } + + public evaluate (): void { + const { + _bindingEvaluations: bindingEvaluations, + } = this; + + for (const binding of bindingEvaluations) { + binding.evaluate(); + } + } + + private _bindingEvaluations: readonly RuntimePVNodePropertyBinding[]; +} + +class RuntimePVNodeEvaluation { + constructor ( + private _node: PureValueNode, + private _dependency: DependencyEvaluation, + ) { + this._outputs = new Array(_node.outputCount); + } + + get node () { + return this._node; + } + + public get outputCount () { + return this._outputs.length; + } + + public getDefaultOutput () { + return this.getOutput(0); + } + + public getOutput (outputIndex: number) { + return this._outputs[outputIndex]; + } + + public evaluate () { + const { + _node: node, + _dependency: dependency, + } = this; + // Evaluate the dependency. + dependency.evaluate(); + // Evaluate the node. + node.selfEvaluate(this._outputs); + } + + protected _outputs: unknown[]; +} + +type RuntimeNodeEvaluation = PoseNode | RuntimePVNodeEvaluation; + +function linkPoseNode ( + consumerNode: PoseNode, + consumerInputPath: NodeInputPath, + producerNode: PoseNode, + producerOutputIndex: number, +) { + const [consumerPropertyKey, consumerElementIndex = -1] = consumerInputPath; + if (!(consumerPropertyKey in consumerNode)) { + // Invalid binding. + warn(`Invalid binding: consumer node has no property ${consumerPropertyKey}`); + return; + } + + if (producerOutputIndex !== 0) { + // Rule: pose nodes have and only have one output. + warn(`Node ${producerNode.toString()} does not have specified output ${producerOutputIndex}.`); + return; + } + + const consumerProperty = consumerNode[consumerPropertyKey]; + + // Plain property binding. + + if (consumerElementIndex < 0) { + if (consumerProperty !== null) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey} should be leaved as evaluation before evaluation.`); + return; + } + + consumerNode[consumerPropertyKey] = producerNode; + return; + } + + // The following is dedicated to array element bindings. + + if (!Array.isArray(consumerProperty)) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey} should be an array.`); + return; + } + + if (consumerElementIndex >= consumerProperty.length) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey} ` + + `have length ${consumerProperty.length} but the binding specified ${consumerElementIndex}`); + return; + } + if (consumerProperty[consumerElementIndex] !== null) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey}[${consumerElementIndex}] should be leaved as null before evaluation`); + return; + } + + consumerProperty[consumerElementIndex] = producerNode; +} + +interface RuntimePVNodePropertyBinding { + evaluate(): void; +} + +class RuntimePVNodePlainPropertyBinding implements RuntimePVNodePropertyBinding { + constructor ( + private _consumerNode: EvaluatableNode, + private _consumerPropertyKey: string, + private _producerRecord: RuntimePVNodeEvaluation, + private _producerOutputIndex: number, + ) { + } + + public evaluate () { + this._producerRecord.evaluate(); + this._consumerNode[this._consumerPropertyKey] = this._producerRecord.getOutput(this._producerOutputIndex); + } +} + +class RuntimePVNodeArrayElementPropertyBinding implements RuntimePVNodePropertyBinding { + constructor ( + private _consumerNode: EvaluatableNode, + private _consumerPropertyKey: string, + private _consumerElementIndex: number, + private _producerRecord: RuntimePVNodeEvaluation, + private _producerOutputIndex: number, + ) { + } + + public evaluate () { + this._producerRecord.evaluate(); + this._consumerNode[this._consumerPropertyKey][this._consumerElementIndex] = this._producerRecord.getOutput(this._producerOutputIndex); + } +} + +function linkPVNode ( + consumerNode: EvaluatableNode, + consumerInputPath: NodeInputPath, + producerRecord: RuntimePVNodeEvaluation, + producerOutputIndex: number, +): RuntimePVNodePropertyBinding | undefined { + const [consumerPropertyKey, consumerElementIndex = -1] = consumerInputPath; + if (!(consumerPropertyKey in consumerNode)) { + // Invalid binding. + warn(`Invalid binding: consumer node has no property ${consumerPropertyKey}`); + return undefined; + } + + const consumerProperty = consumerNode[consumerPropertyKey]; + + // Plain property binding. + + if (consumerElementIndex < 0) { + return new RuntimePVNodePlainPropertyBinding( + consumerNode, + consumerPropertyKey, + producerRecord, + producerOutputIndex, + ); + } + + // The following is dedicated to array element bindings. + + if (!Array.isArray(consumerProperty)) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey} should be an array.`); + return undefined; + } + + if (consumerElementIndex >= consumerProperty.length) { + // Invalid binding. + warn(`Invalid binding: consumer node's input ${consumerPropertyKey} ` + + `have length ${consumerProperty.length} but the binding specified ${consumerElementIndex}`); + return undefined; + } + + return new RuntimePVNodeArrayElementPropertyBinding( + consumerNode, + consumerPropertyKey, + consumerElementIndex, + producerRecord, + producerOutputIndex, + ); } diff --git a/cocos/animation/marionette/pose-graph/op/index.ts b/cocos/animation/marionette/pose-graph/op/index.ts new file mode 100644 index 0000000000..14ed09279d --- /dev/null +++ b/cocos/animation/marionette/pose-graph/op/index.ts @@ -0,0 +1,4 @@ + +import * as poseGraphOp from './internal'; + +export { poseGraphOp }; diff --git a/cocos/animation/marionette/pose-graph/op/internal.ts b/cocos/animation/marionette/pose-graph/op/internal.ts new file mode 100644 index 0000000000..4c3fe074dc --- /dev/null +++ b/cocos/animation/marionette/pose-graph/op/internal.ts @@ -0,0 +1,212 @@ +import { PoseNode } from '../pose-node'; +import { PoseGraphNodeInputInsertId, PoseGraphInputKey, globalPoseGraphNodeInputManager } from '../foundation/authoring/input-authoring'; +import { PureValueNode } from '../pure-value-node'; +import { assertIsTrue, error } from '../../../../core'; +import { PoseGraphType } from '../foundation/type-system'; +import { PoseGraphNode } from '../foundation/pose-graph-node'; +import { PoseGraphOutputNode } from '../graph-output-node'; +import type { PoseGraph } from '../pose-graph'; + +export type { + PoseGraphInputKey as InputKey, + PoseGraphNodeInputMetadata as InputMetadata, + PoseGraphNodeInputInsertId as InputInsertId, +} from '../foundation/authoring/input-authoring'; + +export type OutputKey = number; + +export { PoseGraphNode as Node }; + +export { PoseGraphType }; + +const POSE_NODE_OUTPUT_BINDING_KEY = 0; + +export function getInputKeys (node: PoseGraphNode) { + return globalPoseGraphNodeInputManager.getInputKeys(node); +} + +export function isValidInputKey (node: PoseGraphNode, key: PoseGraphInputKey) { + return globalPoseGraphNodeInputManager.hasInput(node, key); +} + +export function getInputMetadata (node: PoseGraphNode, key: PoseGraphInputKey) { + return globalPoseGraphNodeInputManager.getInputMetadata(node, key); +} + +export function getInputConstantValue (node: PoseGraphNode, key: PoseGraphInputKey): unknown { + if (!globalPoseGraphNodeInputManager.hasInput(node, key)) { + return undefined; + } + if (globalPoseGraphNodeInputManager.isPoseInput(node, key)) { + // Pose input's "constant value" is defined as `null`. + return null; + } + return getPureValueInputConstantValue(node, key); +} + +export function getInputBinding (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey): Readonly<{ + producer: PoseGraphNode; + outputIndex: number; +}> | undefined { + return graph.getShell(node)?.findBinding(key); +} + +export function getInputInsertInfos (node: PoseGraphNode) { + return globalPoseGraphNodeInputManager.getInputInsertInfos(node); +} + +export function insertInput (graph: PoseGraph, node: PoseGraphNode, insertId: PoseGraphNodeInputInsertId) { + return globalPoseGraphNodeInputManager.insertInput(graph, node, insertId); +} + +export function deleteInput (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey) { + globalPoseGraphNodeInputManager.deleteInput(graph, node, key); +} + +export const getOutputKeys = (() => { + const poseNodeOutputKeys = Object.freeze([POSE_NODE_OUTPUT_BINDING_KEY]); + + return (node: PoseGraphNode): readonly OutputKey[] => { + if (node instanceof PoseNode) { + return poseNodeOutputKeys; + } else if (node instanceof PureValueNode) { + // TODO: optimize me + const outputCount = node.outputCount; + return Array.from({ length: outputCount }, (_, i) => i); + } else { + return []; + } + }; +})(); + +export function getOutputType(node: PoseGraphNode, outputId: OutputKey) { + if (node instanceof PoseNode) { + return PoseGraphType.POSE; + } else if (node instanceof PureValueNode) { + const outputIndex = Number(outputId); + if (outputIndex < 0 || outputIndex >= node.outputCount) { + throw new Error(`${node} does not have specified output key ${outputId}`); + } else { + return node.getOutputType(outputIndex); + } + } else { + throw new Error(`${node} does not have specified output key.`); + } +} + +export function connectNode (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey, producer: PoseGraphNode, outputKey?: OutputKey) { + const consumerNode = node; + const consumerShell = graph.getShell(node); + if (!consumerShell) { + error(`Consumer node is not with in graph!`); + return; + } + + const inputMetadata = getInputMetadata(consumerNode, key); + if (!inputMetadata) { + error(`Consumer node does not have such specified input key ${key}`); + return; + } + + let outputIndex = 0; + let outputType: PoseGraphType; + if (producer instanceof PureValueNode) { + if (typeof outputKey !== 'number') { + error(`Output key is not specified.`); + return; + } + const outputIndex = Number(outputKey); + if (outputIndex < 0 || outputIndex >= producer.outputCount) { + error(`Producer node does not have such specified output key ${key}`); + return; + } + outputType = producer.getOutputType(outputIndex); + } else { + if ((outputKey ?? POSE_NODE_OUTPUT_BINDING_KEY) !== POSE_NODE_OUTPUT_BINDING_KEY) { + error(`Pose nodes have and only have single output.`); + return; + } + outputType = PoseGraphType.POSE; + } + + const inputType = inputMetadata.type; + if (inputType !== outputType) { + error(`Type mismatch: input has type ${PoseGraphType[inputType]}, output has type ${PoseGraphType[outputType]}.`); + return; + } + + const [ + propertyKey, + elementIndex = -1, + ] = key; + const property = consumerNode[propertyKey]; + if (elementIndex >= 0) { + if (!Array.isArray(property)) { + return; + } + if (elementIndex >= property.length) { + return; + } + consumerShell.addBinding([propertyKey, elementIndex], producer, outputIndex); + } else { + consumerShell.addBinding([propertyKey], producer, outputIndex); + } +} + +export function disconnectNode (graph: PoseGraph, node: PoseGraphNode, key: PoseGraphInputKey) { + graph.getShell(node)?.deleteBinding(key); +} + +export function connectOutputNode(graph: PoseGraph, outputNode: PoseGraphOutputNode, producer: PoseNode) { + const outputNodeInputKeys = getInputKeys(outputNode); + assertIsTrue(outputNodeInputKeys.length === 1); + connectNode(graph, outputNode, outputNodeInputKeys[0], producer); +} + +export function hasInputBinding ( + graph: PoseGraph, + node: PoseGraphNode, + key: PoseGraphInputKey, + producerNode: PoseGraphNode, + producerOutputKey: OutputKey, +) { + const binding = getInputBinding(graph, node, key); + if (!binding) { + return false; + } + return binding.producer === producerNode && binding.outputIndex === producerOutputKey; +} + +function getPureValueInputConstantValue (node: PoseGraphNode, inputKey: PoseGraphInputKey): unknown { + const [ + propertyKey, + elementIndex = -1, + ] = inputKey; + const property = node[propertyKey]; + if (!Array.isArray(property)) { + return property; + } + if (elementIndex < 0 || elementIndex >= property.length) { + return undefined; + } + return property[elementIndex]; +} + +export function isWellFormedInputKey(test: unknown): test is PoseGraphInputKey { + if (!Array.isArray(test)) { + return false; + } + if (test.length > 2) { + return false; + } + if (typeof test[0] !== 'string') { + return false; + } + if (test.length > 1) { + const e1 = test[1]; + if (typeof e1 !== 'number' || e1 < 0 || !Number.isFinite(e1)) { + return false; + } + } + return true; +} \ No newline at end of file diff --git a/cocos/animation/marionette/pose-graph/pose-graph.ts b/cocos/animation/marionette/pose-graph/pose-graph.ts index 674fa980fb..4d31a3a23f 100644 --- a/cocos/animation/marionette/pose-graph/pose-graph.ts +++ b/cocos/animation/marionette/pose-graph/pose-graph.ts @@ -1,26 +1,30 @@ -import { EditorExtendable, js, warn } from '../../../core'; +import { EditorExtendable, assertIsTrue, error, js, warn } from '../../../core'; import { ccclass, serializable } from '../../../core/data/decorators'; import { CLASS_NAME_PREFIX_ANIM } from '../../define'; -import { PoseNode } from './pose-node'; +import { PoseGraphNodeShell } from './foundation/node-shell'; +import { PoseGraphNode } from './foundation/pose-graph-node'; +import { AddNonFreestandingNodeError } from './foundation/errors'; +import { PoseGraphOutputNode } from './graph-output-node'; +/** + * @zh + * 姿势图。 + * @en + * Pose graph. + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseGraph`) export class PoseGraph extends EditorExtendable { - /** - * @zh - * 连接到该姿势图根输出结点的结点。 - * @en - * The node connected to the root output node of pose graph. - */ - public get main () { - return this._main; + constructor () { + super(); + this.addNode(this._outputNode); } - public set main (value) { - if (value && !this._nodes.includes(value)) { - warn(`Specified pose expr is not within container.`); - return; - } - this._main = value; + /** + * @zh 姿势图的输出结点。 + * @en The pose graph's output node. + */ + public get outputNode () { + return this._outputNode; } /** @@ -28,41 +32,101 @@ export class PoseGraph extends EditorExtendable { * @internal */ public __callOnAfterDeserializeRecursive () { - for (const node of this._nodes) { - if ('__callOnAfterDeserializeRecursive' in node) { - (node as unknown as { - __callOnAfterDeserializeRecursive(): void; - }).__callOnAfterDeserializeRecursive(); - } + assertIsTrue(this._nodes.length === this._shells.length); + for (let iNode = 0; iNode < this._nodes.length; ++iNode) { + const node = this._nodes[iNode]; + const shell = this._shells[iNode]; + this._shellMap.set(node, shell); + node.__callOnAfterDeserializeRecursive?.(); } } - public nodes () { + /** + * @zh 获取所有结点。 + * @en Gets all nodes. + * @returns @zh 用于遍历所有结点的迭代器。 @en The iterator to iterate all nodes. + */ + public nodes (): IterableIterator { return this._nodes.values(); } - public addNode (node: PoseNode) { + /** + * @zh 添加一个结点到图中。 + * @en Adds a node into graph. + * @param node @zh 要添加的结点。 @en Node to add. + * @returns `node` + * + * @note + * @zh 注意,要添加的结点必须是“独立”的,也就是说它不能已经在任何图中。否则会抛出异常。 + * @en Note, the node to add should be "freestanding", + * means it should not been already in any graph. Otherwise, an exception would be thrown. + */ + public addNode (node: TNode) { + if (this._shellMap.has(node)) { + throw new AddNonFreestandingNodeError(node); + } + const shell = new PoseGraphNodeShell(); + this._shells.push(shell); this._nodes.push(node); + this._shellMap.set(node, shell); + return node; } - public removeNode (node: PoseNode) { - // Disconnect from others. - for (const node of this._nodes) { - // TODO before merging: + /** + * @zh 将指定的结点从图中移除。 + * @en Removes specified node from the graph. + * @param removal @zh 要移除的结点。 @en The node to remove. + * + * @note + * @zh 如果要移除的结点不在图中或该结点是图的输出结点,则此方法不会生效。 + * @en If the removal node is not within graph or is the output node of graph, + * this method takes no effect. + */ + public removeNode (removal: PoseGraphNode) { + if (removal === this._outputNode) { + error(`Can not remove the output node.`); + return; } - // Disconnect from output. - if (node === this._main) { - this._main = null; + const nodeIndex = this._nodes.indexOf(removal); + if (nodeIndex < 0) { + return; + } + + // This should be true. + assertIsTrue(this._shellMap.has(removal)); + + // Disconnect from others. + for (const shell of this._shells) { + shell.deleteBindingTo(removal); } // Remove from graph. - js.array.remove(this._nodes, node); + js.array.removeAt(this._shells, nodeIndex); + js.array.removeAt(this._nodes, nodeIndex); + this._shellMap.delete(removal); + } + + /** + * @zh + * 获取指定结点在姿势图中的外壳。 + * @en + * Gets the specified node's shell in pose graph. + * @internal + */ + public getShell (node: PoseGraphNode) { + return this._shellMap.get(node); } @serializable - private _nodes: PoseNode[] = []; + private _outputNode = new PoseGraphOutputNode(); @serializable - private _main: PoseNode | null = null; + private _nodes: PoseGraphNode[] = []; + + @serializable + private _shells: PoseGraphNodeShell[] = []; + + @serializable + private _shellMap = new Map(); } diff --git a/cocos/animation/marionette/pose-graph/pose-node.ts b/cocos/animation/marionette/pose-graph/pose-node.ts index b49dae6702..47b343a502 100644 --- a/cocos/animation/marionette/pose-graph/pose-node.ts +++ b/cocos/animation/marionette/pose-graph/pose-node.ts @@ -1,5 +1,5 @@ import { TEST } from 'internal:constants'; -import { assertIsTrue, EditorExtendable } from '../../../core'; +import { assertIsTrue } from '../../../core'; import { ccclass } from '../../../core/data/decorators'; import { Pose } from '../../core/pose'; import { CLASS_NAME_PREFIX_ANIM } from '../../define'; @@ -9,6 +9,8 @@ import { AnimationGraphSettleContext, AnimationGraphUpdateContext, } from '../animation-graph-context'; +import { PoseGraphNode } from './foundation/pose-graph-node'; +import type { PoseNodeDependencyEvaluation } from './instantiation'; const POSE_NODE_EVALUATION_STACK_ORDER_DEBUG_ENABLED = !!TEST; @@ -18,7 +20,7 @@ const POSE_NODE_EVALUATION_STACK_ORDER_DEBUG_ENABLED = !!TEST; * Pose nodes are nodes in pose graph that yields pose objects. */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}PoseNode`) -export abstract class PoseNode extends EditorExtendable { +export abstract class PoseNode extends PoseGraphNode { /** * Starts the bind stage on this pose node. * @@ -61,7 +63,7 @@ export abstract class PoseNode extends EditorExtendable { * @note Subclasses shall not override this method and should override `doUpdate` instead. */ public update (context: AnimationGraphUpdateContext) { - // TODO: update dependencies. + this._dependencyEvaluation?.evaluate(); this.doUpdate(context); } @@ -98,6 +100,11 @@ export abstract class PoseNode extends EditorExtendable { return context.pushDefaultedPose(); } + /** @internal */ + public _setDependencyEvaluation (dependency: PoseNodeDependencyEvaluation) { + this._dependencyEvaluation = dependency; + } + /** * Implement this method to performs the update stage on this pose node. * @@ -116,4 +123,6 @@ export abstract class PoseNode extends EditorExtendable { * @returns The result pose. */ protected abstract doEvaluate (context: AnimationGraphEvaluationContext): Pose; + + private _dependencyEvaluation: PoseNodeDependencyEvaluation | undefined = undefined; } diff --git a/cocos/animation/marionette/pose-graph/pure-value-node.ts b/cocos/animation/marionette/pose-graph/pure-value-node.ts new file mode 100644 index 0000000000..bc66514007 --- /dev/null +++ b/cocos/animation/marionette/pose-graph/pure-value-node.ts @@ -0,0 +1,50 @@ +import { VarInstance } from '../variable'; +import { PoseGraphNode } from './foundation/pose-graph-node'; +import { PoseGraphType } from './foundation/type-system'; + +type Outputs = unknown[]; + +/** + * Base class of all pure value nodes in pose graph. + * + * Pure value nodes are nodes in pose graph that yields non-pose-object value(s). + * + * Sometimes, pure values nodes are also abbreviated as pv nodes. + */ +export abstract class PureValueNode extends PoseGraphNode { + constructor (outputTypes: readonly PoseGraphType[]) { + super(); + this._outputTypes = outputTypes; + } + + get outputCount () { + return this._outputTypes.length; + } + + public getOutputType (outputIndex: number) { + return this._outputTypes[outputIndex]; + } + + public link (context: PureValueNodeLinkContext) { + } + + private _outputTypes: readonly PoseGraphType[] = []; + + public abstract selfEvaluate(outputs: Outputs): void; +} + +export abstract class SingleOutputPVNode extends PureValueNode { + constructor (outputType: PoseGraphType) { + super([outputType]); + } + + public selfEvaluate (outputs: Outputs): void { + outputs[0] = this.selfEvaluateDefaultOutput(); + } + + protected abstract selfEvaluateDefaultOutput(): TValue; +} + +export interface PureValueNodeLinkContext { + getVar(name: string): VarInstance | undefined; +} diff --git a/cocos/animation/marionette/state-machine/state-machine-eval.ts b/cocos/animation/marionette/state-machine/state-machine-eval.ts index f8eea3305e..043990fa1c 100644 --- a/cocos/animation/marionette/state-machine/state-machine-eval.ts +++ b/cocos/animation/marionette/state-machine/state-machine-eval.ts @@ -1363,7 +1363,7 @@ class PoseStateEval extends StateEval { public constructor (state: PoseState, context: AnimationGraphBindingContext) { super(state); - const poseEval = instantiatePoseGraph(state.graph); + const poseEval = instantiatePoseGraph(state.graph, context); if (poseEval) { poseEval.bind(context); this._rootPoseNodeEval = poseEval; diff --git a/editor/exports/new-gen-anim.ts b/editor/exports/new-gen-anim.ts index 60ebd87ff5..277ea320e9 100644 --- a/editor/exports/new-gen-anim.ts +++ b/editor/exports/new-gen-anim.ts @@ -43,3 +43,5 @@ export { export { getVariableValueAttributes, } from '../src/marionette/get-variable-value-attributes'; + +export * from '../src/marionette/pose-graph-editor-api'; diff --git a/editor/src/marionette/pose-graph-editor-api.ts b/editor/src/marionette/pose-graph-editor-api.ts new file mode 100644 index 0000000000..1c212f25f0 --- /dev/null +++ b/editor/src/marionette/pose-graph-editor-api.ts @@ -0,0 +1,77 @@ +import { PoseGraphNode } from "../../../cocos/animation/marionette/pose-graph/foundation/pose-graph-node"; +import { + getPoseGraphNodeEditorMetadata, PoseGraphCreateNodeContext, PoseGraphNodeAppearanceOptions, +} from "../../../cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring"; +import { js } from "../../../cocos/core/utils"; +import { PoseNode } from "../../../cocos/animation/marionette/pose-graph/pose-node"; +import { PureValueNode } from "../../../cocos/animation/marionette/pose-graph/pure-value-node"; + +type Constructor = new (...args: any[]) => T; + +export interface PoseGraphCreateNodeEntry { + menu: string; + + arg: unknown; +} + +export function* getCreatePoseGraphNodeEntries( + classConstructor: Constructor, + createNodeContext: PoseGraphCreateNodeContext, +): Iterable { + type AbstractedConstructor = abstract new (...args: any[]) => T; + + if ((classConstructor as AbstractedConstructor) === PoseNode || (classConstructor as AbstractedConstructor) === PureValueNode) { + return; + } + const nodeClassMetadata = getPoseGraphNodeEditorMetadata(classConstructor as Constructor); + if (nodeClassMetadata) { + if (nodeClassMetadata.factory) { + yield* nodeClassMetadata.factory.listEntries(createNodeContext); + return; + } else if (nodeClassMetadata.menu) { + yield { arg: undefined, menu: nodeClassMetadata.menu }; + return; + } else if (nodeClassMetadata.hide) { + return; + } + } + const displayName = js.getClassName(classConstructor) || classConstructor.name; + yield { arg: undefined, menu: displayName }; +} + +export function createPoseGraphNode( + classConstructor: Constructor, + arg: unknown, +): PoseGraphNode { + const nodeClassMetadata = getPoseGraphNodeEditorMetadata(classConstructor as Constructor); + if (nodeClassMetadata?.factory) { + return nodeClassMetadata.factory.create(arg) as PoseNode | PureValueNode; + } + return new classConstructor(); +} + +export type { PoseGraphCreateNodeContext }; + +export function getNodeTitle(node: PoseGraphNode) { + if (node.getTitle) { + return node.getTitle(); + } + const classConstructor = node.constructor as Constructor; + const metadata = getPoseGraphNodeEditorMetadata(classConstructor); + if (metadata?.menu) { + return metadata.menu.split('/').pop() ?? ''; + } + const className = js.getClassName(node); + if (className) { + return className; + } + return classConstructor.name; +} + +export type { PoseGraphNodeAppearanceOptions }; + +export function getNodeAppearanceOptions(node: PoseGraphNode) { + const classConstructor = node.constructor as Constructor; + const metadata = getPoseGraphNodeEditorMetadata(classConstructor); + return metadata?.appearance; +} diff --git a/editor/src/marionette/visit.ts b/editor/src/marionette/visit.ts index fa9114057e..e1d4f5b910 100644 --- a/editor/src/marionette/visit.ts +++ b/editor/src/marionette/visit.ts @@ -6,9 +6,11 @@ import { StateMachine, SubStateMachine, AnimationGraph, + PoseState, } from "../../../cocos/animation/marionette/animation-graph"; import { MotionState } from "../../../cocos/animation/marionette/state-machine/motion-state"; import { EditorExtendableObject } from "../../../cocos/core/data/editor-extras-tag"; +import { PoseGraphNode } from "../../../cocos/animation/marionette/pose-graph/foundation/pose-graph-node"; export function* visitAnimationGraphEditorExtras(animationGraph: AnimationGraph): Generator { for (const layer of animationGraph.layers) { @@ -60,6 +62,10 @@ export function* visitAnimationClips(animationGraph: AnimationGraph): Generator< if (motion) { yield* visitMotion(motion); } + } else if (state instanceof PoseState) { + for (const shell of state.graph.nodes()) { + yield* visitPoseNode(shell); + } } else if (state instanceof SubStateMachine) { yield* visitStateMachine(state.stateMachine); } @@ -79,6 +85,15 @@ export function* visitAnimationClips(animationGraph: AnimationGraph): Generator< } } } + + function* visitPoseNode(node: PoseGraphNode): Generator { + // FIXME: HACK HERE + for (const [_, v] of Object.entries(node)) { + if (v instanceof Motion) { + yield* visitMotion(v); + } + } + } } export function* visitAnimationClipsInController(animationController: AnimationController): Generator { diff --git a/scripts/native-pack-tool/package-lock.json b/scripts/native-pack-tool/package-lock.json index cd0b13025a..43a55b0c26 100644 --- a/scripts/native-pack-tool/package-lock.json +++ b/scripts/native-pack-tool/package-lock.json @@ -746,7 +746,7 @@ }, "json5": { "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "resolved": "https://registry.npmmirror.com/json5/-/json5-2.2.3.tgz", "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" }, "jsonfile": { diff --git a/tests/animation/new-gen-anim/event.test.ts b/tests/animation/new-gen-anim/event.test.ts index c4a63c2a82..84d50d8190 100644 --- a/tests/animation/new-gen-anim/event.test.ts +++ b/tests/animation/new-gen-anim/event.test.ts @@ -3,7 +3,7 @@ jest.mock('../../../cocos/animation/marionette/graph-eval'); import { AnimationController } from "../../../cocos/animation/animation"; import { AnimationGraphCustomEventEmitter } from "../../../cocos/animation/marionette/event/custom-event-emitter"; import { AnimationGraphEval } from "../../../cocos/animation/marionette/graph-eval"; -import { AnimationGraph } from "../../../editor/exports/new-gen-anim"; +import { AnimationGraph } from "../../../cocos/animation/marionette/animation-graph"; import { EventTarget, Node } from "../../../exports/base"; import { AnimationGraphEvalMock } from './utils/eval-mock'; import 'jest-extended'; diff --git a/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts new file mode 100644 index 0000000000..de50ad0852 --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/pose-graph-authoring.test.ts @@ -0,0 +1,770 @@ +import { Pose } from "../../../../cocos/animation/core/pose"; +import { AnimationGraph, PoseGraph } from "../../../../cocos/animation/marionette/asset-creation"; +import { assertIsTrue, lerp, quat, v3 } from "../../../../cocos/core"; +import { Node } from "../../../../cocos/scene-graph"; +import { captureErrors, captureWarns } from '../../../utils/log-capture'; +import { input } from "../../../../cocos/animation/marionette/pose-graph/decorator/input"; +import 'jest-extended'; +import { poseGraphOp } from "../../../../cocos/animation/marionette/pose-graph/op"; +import { PoseGraphType } from "../../../../cocos/animation/marionette/pose-graph/foundation/type-system"; +import { PoseGraphNode } from "../../../../cocos/animation/marionette/pose-graph/foundation/pose-graph-node"; +import { AddNonFreestandingNodeError } from "../../../../cocos/animation/marionette/pose-graph/foundation/errors"; +import { poseGraphCreateNodeFactory, poseGraphNodeAppearance, poseGraphNodeHide, poseGraphNodeMenu } from "../../../../cocos/animation/marionette/pose-graph/decorator/node"; +import { PoseGraphNodeEditorMetadata, getPoseGraphNodeEditorMetadata } from "../../../../cocos/animation/marionette/pose-graph/foundation/authoring/node-authoring"; +import { createPoseGraph, findInputKeyHavingDisplayName, getTheOnlyInputKey, getTheOnlyOutputKey, normalizeNodeInputMetadata, UnimplementedPoseNode, UnimplementedPVNode } from "./utils/misc"; +import { PoseNode } from "../../../../cocos/animation/marionette/pose-graph/pose-node"; + +describe(`Class PoseGraph`, () => { + test(`Default`, () => { + const graph = createPoseGraph(); + + // By default, pose graph has no node. + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + ])); + }); + + test(`Add and remove node`, () => { + const graph = createPoseGraph(); + + // Add a node. + const node = new UnimplementedPoseNode(); + graph.addNode(node); + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + node, + ])); + + // Can not add a node twice. + expect(() => graph.addNode(node)).toThrowError(AddNonFreestandingNodeError); + + // Add another node. + const anotherNode = new UnimplementedPVNode([]); + graph.addNode(anotherNode); + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + node, + anotherNode, + ])); + + // Remove a node. + graph.removeNode(anotherNode); + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + node, + ])); + + // The node removed can be later added again to node. + graph.addNode(anotherNode); + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + node, + anotherNode, + ])); + // Still don't add a node twice. + expect(() => graph.addNode(anotherNode)).toThrowError(AddNonFreestandingNodeError); + + // Remove a pose which was marked as main. + poseGraphOp.connectNode(graph, graph.outputNode, getTheOnlyInputKey(graph.outputNode), node); + expect(poseGraphOp.getInputBinding(graph, graph.outputNode, getTheOnlyInputKey(graph.outputNode))).toStrictEqual(expect.objectContaining({ + producer: node, + outputIndex: 0, + })); + graph.removeNode(node); + expect([...graph.nodes()]).toStrictEqual(expect.arrayContaining([ + graph.outputNode, + anotherNode, + ])); + expect(poseGraphOp.getInputBinding(graph, graph.outputNode, getTheOnlyInputKey(graph.outputNode))).toBeUndefined(); + }); +}); + +describe(`Input decorator @input`, () => { + // No need to test for now. + // test.skip(`Should emit error if not string-named field`, () => { + // const tag = Symbol(); + + // const errorWatcher = captureErrors(); + + // class _Node extends PoseNode { + // @input({ type: PoseGraphType.POSE, }) + // 0: PoseNode | null = null; + + // bind() { return unusedBind(); } + // } + + // expect(errorWatcher.captured).toHaveLength(1); + // expect(errorWatcher.captured[0]).toMatchSnapshot(); + + // expect(getPoseInputFieldKeys(new _Node())).toHaveLength(0); + + // errorWatcher.stop(); + // }); + + test(`@input specifying pose input can be only applied to fields of subclasses of PoseNode`, () => { + const errorWatcher = captureErrors(); + + for (const define of [defineSubClassOfPoseGraphNode, defineOtherClass]) { + define(); + + expect(errorWatcher.captured).toHaveLength(1); + expect(errorWatcher.captured[0]).toMatchObject([ + '@input specifying pose input can be only applied to fields of subclasses of PoseNode.', + ]); + + errorWatcher.clear(); + } + + function defineSubClassOfPoseGraphNode() { + class _Node extends PoseGraphNode { + @input({ type: PoseGraphType.POSE }) + pose: PoseNode | null = null; + }; + return _Node; + }; + + function defineOtherClass() { + class _Node { + @input({ type: PoseGraphType.POSE }) + pose: PoseNode | null = null; + }; + return _Node; + }; + }); + + test(`@input can be only applied to fields of subclasses of PoseNode or PureValueNode.`, () => { + const errorWatcher = captureErrors(); + + for (const define of [defineSubClassOfPoseGraphNode, defineOtherClass]) { + define(); + + expect(errorWatcher.captured).toHaveLength(1); + expect(errorWatcher.captured[0]).toMatchObject([ + '@input can be only applied to fields of subclasses of PoseNode or PureValueNode.', + ]); + + errorWatcher.clear(); + } + + function defineSubClassOfPoseGraphNode() { + class _Node extends PoseGraphNode { + @input({ type: PoseGraphType.FLOAT }) + v = 6; + }; + return _Node; + } + + function defineOtherClass() { + class _Node { + @input({ type: PoseGraphType.FLOAT }) + v = 6; + }; + return _Node; + } + }); +}); + +describe(`Node editor decorators`, () => { + test(`@poseGraphNodeMenu`, () => { + checkInjection( + poseGraphNodeMenu('some-menu-item-1/some-menu-item-2'), + { menu: 'some-menu-item-1/some-menu-item-2' }, + ); + }); + + test(`@poseGraphNodeHide`, () => { + checkInjection( + poseGraphNodeHide(true), + { hide: true }, + ); + }); + + test(`@poseGraphNodeAppearance`, () => { + checkInjection( + poseGraphNodeAppearance({ themeColor: '#ff0012', inline: true }), + { appearance: { themeColor: '#ff0012', inline: true } }, + ); + }); + + test(`@poseGraphCreateNodeFactory`, () => { + const factory = { + listEntries: () => [], + create() { throw new Error(`Should never be invoked.`); }, + }; + checkInjection( + poseGraphCreateNodeFactory(factory), + { factory }, + ); + }); + + test(`All node decorators should be node dedicated.`, () => { + const errorWatcher = captureErrors(); + + for (const decorator of [ + poseGraphNodeMenu(''), + poseGraphNodeAppearance({}), + poseGraphCreateNodeFactory({ + listEntries: () => [], + create() { throw new Error(`Should never be invoked.`); }, + }), + ] as const) { + @decorator + class NotPoseGraphNode {} + + expect(errorWatcher.captured).toStrictEqual([ + ['This kind of decorator should only be applied to pose graph node classes.'], + ]); + + errorWatcher.clear(); + } + }); + + function checkInjection(decorator: ClassDecorator, expectedMetadata: PoseGraphNodeEditorMetadata) { + @decorator + class SomePoseGraphNode extends PoseGraphNode {} + + expect(getPoseGraphNodeEditorMetadata(SomePoseGraphNode)).toMatchObject(expectedMetadata); + } +}); + +describe(`Node`, () => { + type PosePropertyName = 'pose_input_with_no_displayName_specified' | 'pose_input_with_displayName_specified'; + + type PVNodePropertyName = 'pv_node_input_with_no_displayName_specified' | 'pv_node_input_with_displayName_specified'; + + interface PoseGraphNodeTestSuite { + makeFundamental: (poseGraph: PoseGraph) => { + node: PoseGraphNode, + }; + makeArrayInput: (poseGraph: PoseGraph) => { + node: PoseGraphNode; + visitArray: () => unknown[]; + }; + } + + const testSuitePoseNode: PoseGraphNodeTestSuite = (() => { + class Fundamental_Node extends UnimplementedPoseNode { + @input({ type: PoseGraphType.POSE, }) + pose_input_with_no_displayName_specified: PoseNode | null = null; + + @input({ type: PoseGraphType.POSE, displayName: 'SomeDisPlayName' }) + pose_input_with_displayName_specified: PoseNode | null = null; + + @input({ type: PoseGraphType.FLOAT }) + pv_node_input_with_no_displayName_specified = 1; + + @input({ type: PoseGraphType.FLOAT, displayName: 'PVNode_SomeDisPlayName' }) + pv_node_input_with_displayName_specified = 2; + + /** + * Does not observed by this test case. + */ + @input({ type: PoseGraphType.POSE, }) + array_inputs: Array = []; + } + + class ArrayInput_Node extends UnimplementedPoseNode { + @input({ type: PoseGraphType.POSE, }) + array_inputs: Array = []; + } + + return { + makeFundamental: (poseGraph) => { + const node = poseGraph.addNode(new Fundamental_Node()); + return { + node, + visitProperty: (propertyKey: string) => node[propertyKey], + }; + }, + makeArrayInput: (poseGraph) => { + const node = poseGraph.addNode(new ArrayInput_Node()); + return { + node, + visitArray: () => node.array_inputs, + }; + }, + }; + })(); + + const testSuitePVNode: PoseGraphNodeTestSuite = (() => { + class Fundamental_Node extends UnimplementedPVNode { + @input({ type: PoseGraphType.FLOAT }) + pv_node_input_with_no_displayName_specified = 1; + + @input({ type: PoseGraphType.FLOAT, displayName: 'PVNode_SomeDisPlayName' }) + pv_node_input_with_displayName_specified = 2; + + /** + * Does not observed by this test case. + */ + @input({ type: PoseGraphType.POSE, }) + array_inputs: Array = []; + } + + class ArrayInput_Node extends UnimplementedPVNode { + @input({ type: PoseGraphType.FLOAT }) + array_inputs: number[] = []; + } + + return { + makeFundamental: (poseGraph: PoseGraph) => { + const node = poseGraph.addNode(new Fundamental_Node([PoseGraphType.FLOAT])); + return { + node, + }; + }, + makeArrayInput: (poseGraph: PoseGraph) => { + const node = poseGraph.addNode(new ArrayInput_Node([PoseGraphType.FLOAT])); + return { + node, + visitArray: () => node.array_inputs, + }; + }, + }; + })(); + + describe.each([ + [`Pose Node`, testSuitePoseNode], + [`X Node`, testSuitePVNode], + ] as [title: string, suite: PoseGraphNodeTestSuite][])(`%s`, (_, { + makeFundamental: makeMainNode, + makeArrayInput: makeArrayNode, + }) => { + test(`Fundamental`, () => { + const animationGraph = new AnimationGraph(); + const { graph: poseGraph } = animationGraph.addLayer().stateMachine.addPoseState(); + + const { + node: mainNode, + } = makeMainNode(poseGraph); + + const shouldContainPoseInputs = mainNode instanceof PoseNode; + + // Pose input keys and metadata query. + const rawKeys = poseGraphOp.getInputKeys(mainNode); + expect(rawKeys).toHaveLength(shouldContainPoseInputs ? 4 : 2); + expect(rawKeys).toSatisfyAll((k) => poseGraphOp.isValidInputKey(mainNode, k)); + const metadataTable = rawKeys.map((k) => normalizeNodeInputMetadata(poseGraphOp.getInputMetadata(mainNode, k))); + expect(metadataTable).toStrictEqual(expect.arrayContaining([ + expect.objectContaining({ + displayName: 'pv_node_input_with_no_displayName_specified', + deletable: false, + insertPoint: false, + type: PoseGraphType.FLOAT, + }), + expect.objectContaining({ + displayName: 'PVNode_SomeDisPlayName', + deletable: false, + insertPoint: false, + type: PoseGraphType.FLOAT, + }), + ])); + if (shouldContainPoseInputs) { + expect(metadataTable).toStrictEqual(expect.arrayContaining([ + expect.objectContaining({ + displayName: 'pose_input_with_no_displayName_specified', + deletable: false, + insertPoint: false, + }), + expect.objectContaining({ + displayName: 'SomeDisPlayName', + deletable: false, + insertPoint: false, + }), + ])); + } + + // Pose inputs binding query. + // Note: only pose node can binding poses. + if (shouldContainPoseInputs) { + for (const [ + expectedDisplayName, + expectedPropertyName, + ] of [ + ['pose_input_with_no_displayName_specified', 'pose_input_with_no_displayName_specified'], + ['SomeDisPlayName', 'pose_input_with_displayName_specified'], + ] as [ + expectedDisplayName: string, + expectedPropertyName: PosePropertyName, + ][]) { + const key = rawKeys.find((k) => poseGraphOp.getInputMetadata(mainNode, k)?.displayName === expectedDisplayName); + expect(key).not.toBeUndefined(); + assertIsTrue(key); + // Initial: no binding. + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toBeUndefined(); + // Connect and reconnect. + for (let i = 0; i < 2; ++i) { + const bindingPose = poseGraph.addNode(new UnimplementedPoseNode()); + // Connect. + poseGraphOp.connectNode(poseGraph,mainNode, key, bindingPose); + // `poseGraphOp.getInputBinding` should returns the connected pose. + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toStrictEqual(expect.objectContaining({ + producer: bindingPose, + outputIndex: 0, + })); + } + // Disconnect. + poseGraphOp.disconnectNode(poseGraph,mainNode, key); + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toBeUndefined(); + } + } + + // PV node input binding query. + for (const [ + expectedDisplayName, + expectedPropertyName, + ] of [ + ['pv_node_input_with_no_displayName_specified', 'pv_node_input_with_no_displayName_specified'], + ['PVNode_SomeDisPlayName', 'pv_node_input_with_displayName_specified'], + ] as [ + expectedDisplayName: string, + expectedPropertyName: PVNodePropertyName, + ][]) { + const key = rawKeys.find((k) => poseGraphOp.getInputMetadata(mainNode, k)?.displayName === expectedDisplayName); + expect(key).not.toBeUndefined(); + assertIsTrue(key); + // Initial: no binding. + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toBeUndefined(); + // Connect and reconnect. + for (let i = 0; i < 2; ++i) { + const bindingNode = poseGraph.addNode(new UnimplementedPVNode([PoseGraphType.FLOAT])); + // Connect. + poseGraphOp.connectNode(poseGraph,mainNode, key, bindingNode, 0); + // Query the binding. + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toStrictEqual(expect.objectContaining({ + producer: bindingNode, + outputIndex: getTheOnlyOutputKey(bindingNode), + })); + } + // Disconnect. + poseGraphOp.disconnectNode(poseGraph,mainNode, key); + expect(poseGraphOp.getInputBinding(poseGraph,mainNode, key)).toBeUndefined(); + } + }); + + test(`Array input`, () => { + const animationGraph = new AnimationGraph(); + const { graph: poseGraph } = animationGraph.addLayer().stateMachine.addPoseState(); + + const { + node, + visitArray, + } = makeArrayNode(poseGraph); + + expect(poseGraphOp.getInputKeys(node)).toStrictEqual([]); + + // Array input. + const inputInsertInfos = Object.entries(poseGraphOp.getInputInsertInfos(node)); + expect(inputInsertInfos).toHaveLength(1); + expect(inputInsertInfos.map(([_, v]) => v)).toStrictEqual(expect.arrayContaining([ + expect.objectContaining({ + displayName: 'array_inputs', + }), + ])); + + // Inserts inputs. + for (let i = 0; i < 5; ++i) { + poseGraphOp.insertInput(poseGraph, node, inputInsertInfos[0][0]); + const expectedElementCount = i + 1; + expect(visitArray()).toHaveLength(expectedElementCount); + const keys = poseGraphOp.getInputKeys(node); + expect(keys).toHaveLength(expectedElementCount); + const metadataTable = keys.map((k) => normalizeNodeInputMetadata(poseGraphOp.getInputMetadata(node, k))); + expect(metadataTable).toStrictEqual(expect.arrayContaining(Array.from({ length: expectedElementCount }, (_, j) => { + return expect.objectContaining({ + displayName: `array_inputs ${j}`, + deletable: true, + insertPoint: true, + }); + }))); + } + + // Delete a middle element. + const middleInputKey = poseGraphOp.getInputKeys(node).find((k) => poseGraphOp.getInputMetadata(node, k)?.displayName === `array_inputs 3`); + expect(middleInputKey).not.toBeUndefined(); + assertIsTrue(middleInputKey); + poseGraphOp.deleteInput(poseGraph, node, middleInputKey); + { + expect(visitArray()).toHaveLength(4); + const keys = poseGraphOp.getInputKeys(node); + expect(keys).toHaveLength(4); + const metadataTable = keys.map((k) => poseGraphOp.getInputMetadata(node, k)); + expect(metadataTable).toStrictEqual(expect.arrayContaining(Array.from({ length: 4 }, (_, j) => { + return expect.objectContaining({ + displayName: `array_inputs ${j}`, + deletable: true, + insertPoint: true, + }); + }))); + } + }); + }); + + describe(`Array input properties sync`, () => { + test(`The group has only one member`, () => { + class SomeNode extends UnimplementedPoseNode { + @input({ type: PoseGraphType.POSE, arraySyncGroup: 'sync-group-1' }) + public prop: PoseNode[] = []; + } + + const poseGraph = createPoseGraph(); + const node = poseGraph.addNode(new SomeNode()); + const insertIds = Object.keys(poseGraphOp.getInputInsertInfos(node)); + expect(insertIds).toHaveLength(1); + poseGraphOp.insertInput(poseGraph, node, insertIds[0]); + // The insertion should succeed with one key inserted! + expect(poseGraphOp.getInputKeys(node)).toHaveLength(1); + }); + + test(`The group has only more than one member`, () => { + class SomeNode extends UnimplementedPoseNode { + @input({ type: PoseGraphType.POSE, arraySyncGroup: 'sync-group-1' }) + public prop1: PoseNode[] = []; + + @input({ type: PoseGraphType.POSE, arraySyncGroup: 'sync-group-1' }) + public prop2: PoseNode[] = []; + + @input({ type: PoseGraphType.FLOAT, arraySyncGroup: 'sync-group-1' }) + public prop3: number[] = []; + } + + const poseGraph = createPoseGraph(); + const node = poseGraph.addNode(new SomeNode()); + + const GROUP_MEMBER_COUNT = 3; + + const insertIds = Object.keys(poseGraphOp.getInputInsertInfos(node)); + expect(insertIds).toHaveLength(GROUP_MEMBER_COUNT); + + const expectedProp1ConstantValue: null[] = []; + const expectedProp2ConstantValue: null[] = []; + const expectedProp3ConstantValue: number[] = []; + const check = () => { + expect(poseGraphOp.getInputKeys(node)).toHaveLength(3 * expectedProp1ConstantValue.length); + expect(node.prop1).toStrictEqual(expectedProp1ConstantValue); + expect(node.prop2).toStrictEqual(expectedProp2ConstantValue); + expect(node.prop3).toStrictEqual(expectedProp3ConstantValue); + }; + + // Fire 4 times insertion on prop1/prop2/prop3... in turn. + for (let i = 0; i < 4; ++i) { + poseGraphOp.insertInput(poseGraph, node, insertIds[i % GROUP_MEMBER_COUNT]); + + // The insertion should causes both all props extending 1 element with its type-specified default value. + expectedProp1ConstantValue.push(null); + expectedProp2ConstantValue.push(null); + expectedProp3ConstantValue.push(0.0); + check(); + + // Fill elements with different constant values to inspect if we're doing something right. + expectedProp3ConstantValue[i] = node.prop3[i] = 1 + lerp(0, 1, i / 4); + } + + // Now perform deletion. + for (let i = 0; i < 3; ++i) { + const deleteIndex = i === 0 + ? 1 // Deletes the middle + : i === 1 + ? 1 // the tail + : 0; // the head + const propName = i === 0 + ? 'prop1' + : i === 1 + ? 'prop2' + : 'prop3'; + poseGraphOp.deleteInput( + poseGraph, + node, + findInputKeyHavingDisplayName(node, `${propName} ${deleteIndex}`), + ); + + // The deletion should causes both all props delete its element at specified index. + expectedProp1ConstantValue.splice(deleteIndex, 1); + expectedProp2ConstantValue.splice(deleteIndex, 1); + expectedProp3ConstantValue.splice(deleteIndex, 1); + check(); + } + }); + }); + + test(`connecting()`, () => { + const poseGraph = createPoseGraph(); + + class PoseNode1 extends UnimplementedPoseNode { + @input({ type: PoseGraphType.FLOAT }) + public pv_node_prop = 2; + + @input({ type: PoseGraphType.POSE, }) + public pose_prop: Pose | null = null; + } + + class PVNode1 extends UnimplementedPVNode { + constructor() { super([PoseGraphType.FLOAT]); } + @input({ type: PoseGraphType.FLOAT }) + public pv_node_prop = 2; + } + + const poseNode1 = poseGraph.addNode(new PoseNode1()); + const poseNode2 = poseGraph.addNode(new PoseNode1()); + const pvNode1 = poseGraph.addNode(new PVNode1()); + const pvNode2 = poseGraph.addNode(new PVNode1()); + + const logCapture = captureErrors(); + + // OK: connect pv-node to pv-node input of pose node. + poseGraphOp.connectNode( + poseGraph, + poseNode1, + findInputKeyHavingDisplayName(poseNode1, 'pv_node_prop'), + pvNode1, + getTheOnlyOutputKey(pvNode1), + ); + expect(logCapture.captured).toHaveLength(0); + + // OK: connect pv-node to pv-node input of pv-node. + poseGraphOp.connectNode( + poseGraph, + pvNode2, + findInputKeyHavingDisplayName(poseNode1, 'pv_node_prop'), + pvNode1, + getTheOnlyOutputKey(pvNode1), + ); + expect(logCapture.captured).toHaveLength(0); + + // Error: connect pv-node to pose input of pose node. + poseGraphOp.connectNode( + poseGraph, + poseNode1, + findInputKeyHavingDisplayName(poseNode1, 'pose_prop'), + pvNode1, + getTheOnlyOutputKey(pvNode1), + ); + expect(logCapture.captured).toHaveLength(1); + expect(logCapture.captured[0]).toStrictEqual([`Type mismatch: input has type POSE, output has type FLOAT.`]); + logCapture.clear(); + + // OK: connect pose node to pose input of pose node. + poseGraphOp.connectNode( + poseGraph, + poseNode1, + findInputKeyHavingDisplayName(poseNode1, 'pose_prop'), + poseNode2, + getTheOnlyOutputKey(poseNode2), + ); + expect(logCapture.captured).toHaveLength(0); + + // Error: connect pose node to pv-node input of pose node. + poseGraphOp.connectNode( + poseGraph, + poseNode1, + findInputKeyHavingDisplayName(poseNode1, 'pv_node_prop'), + poseNode2, + getTheOnlyOutputKey(poseNode2), + ); + expect(logCapture.captured).toHaveLength(1); + expect(logCapture.captured[0]).toStrictEqual([`Type mismatch: input has type FLOAT, output has type POSE.`]); + logCapture.clear(); + + // Error: connect pose node to pv-node input of pv-node node. + poseGraphOp.connectNode( + poseGraph, + pvNode1, + findInputKeyHavingDisplayName(poseNode1, 'pv_node_prop'), + poseNode1, + getTheOnlyOutputKey(poseNode1), + ); + expect(logCapture.captured).toHaveLength(1); + expect(logCapture.captured[0]).toStrictEqual([`Type mismatch: input has type FLOAT, output has type POSE.`]); + logCapture.clear(); + }); +}); + +test(`Inputs from base classes`, () => { + class Base extends UnimplementedPoseNode { + @input({ type: PoseGraphType.FLOAT }) + base_pvNode_input = 1.0; + + @input({ type: PoseGraphType.POSE, }) + base_pose_input: Pose | null = null; + + @input({ type: PoseGraphType.POSE }) + base_input_about_to_be_overrode: Pose | null = null; + } + + class Sub extends Base { + @input({ type: PoseGraphType.FLOAT }) + sub_pvNode_input = 2.0; + + @input({ type: PoseGraphType.POSE, }) + sub_pose_input: Pose | null = null; + + @input({ type: PoseGraphType.POSE }) + base_input_about_to_be_overrode: Pose | null = null; + } + + const poseGraph = createPoseGraph(); + const node = poseGraph.addNode(new Sub()); + + { + const inputKeys = poseGraphOp.getInputKeys(node); + for (const inputKey of inputKeys) { + expect(poseGraphOp.isValidInputKey(node, inputKey)).toBeTrue(); + expect(poseGraphOp.getInputBinding(poseGraph, node, inputKey)).toBeUndefined(); + } + expect(inputKeys.map((key) => ({ + displayName: poseGraphOp.getInputMetadata(node, key)?.displayName, + value: poseGraphOp.getInputConstantValue(node, key), + }))).toStrictEqual([ + // Base inputs first. + { displayName: 'base_pvNode_input', value: 1.0 }, + { displayName: 'base_pose_input', value: null }, + { displayName: 'base_input_about_to_be_overrode', value: null }, + { displayName: 'sub_pvNode_input', value: 2.0 }, + { displayName: 'sub_pose_input', value: null }, + ]); + } +}); + +describe(`Input value assignment`, () => { + test.todo(`Assign number input`); + + // Shall not use simple assignment but Vec3.copy. + test.todo(`Assign vec3 input`); + + // Shall not use simple assignment but Quat.copy. + test.todo(`Assign quat input`); +}); + +test(`Input/output query`, () => { + const poseGraph = createPoseGraph(); + + // Query on the unique output node. + { + // Root output node does not has any output. + expect(poseGraphOp.getOutputKeys(poseGraph.outputNode)).toStrictEqual([]); + + // Root output node has a pose input. + const inputKeys = poseGraphOp.getInputKeys(poseGraph.outputNode); + expect(inputKeys).toHaveLength(1); + expect(poseGraphOp.getInputMetadata(poseGraph.outputNode, inputKeys[0])).toStrictEqual(expect.objectContaining({ + type: PoseGraphType.POSE, + })); + } +}); + +test(`isWellFormedInputKey()`, () => { + expect(poseGraphOp.isWellFormedInputKey(['a'])).toBe(true); + expect(poseGraphOp.isWellFormedInputKey(['a', 0])).toBe(true); + expect(poseGraphOp.isWellFormedInputKey(['a', 1])).toBe(true); + + expect(poseGraphOp.isWellFormedInputKey('a')).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(0)).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(1)).toBe(false); + expect(poseGraphOp.isWellFormedInputKey([1, 'a'])).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(['a', -1])).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(['a', -Infinity])).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(['a', Infinity])).toBe(false); + expect(poseGraphOp.isWellFormedInputKey(['a', Number.NaN])).toBe(false); +}) + +test.todo(`Disallow connect a pose node to multiple inputs`); diff --git a/tests/animation/new-gen-anim/pose-graph/pose-graph-runtime.test.ts b/tests/animation/new-gen-anim/pose-graph/pose-graph-runtime.test.ts new file mode 100644 index 0000000000..340cb71ac8 --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/pose-graph-runtime.test.ts @@ -0,0 +1,301 @@ +import { AuxiliaryCurveHandle } from "../../../../cocos/animation/core/animation-handle"; +import { Pose } from "../../../../cocos/animation/core/pose"; +import { AnimationGraphBindingContext, AnimationGraphEvaluationContext, AnimationGraphSettleContext, AnimationGraphUpdateContext } from "../../../../cocos/animation/marionette/animation-graph-context"; +import { AnimationGraph, PoseGraph } from "../../../../cocos/animation/marionette/asset-creation"; +import { assertIsTrue, lerp, quat, v3 } from "../../../../cocos/core"; +import { Node } from "../../../../cocos/scene-graph"; +import { captureErrors, captureWarns } from '../../../utils/log-capture'; +import { input } from "../../../../cocos/animation/marionette/pose-graph/decorator/input"; +import { createAnimationGraph } from "../utils/factory"; +import { AnimationGraphEvalMock } from "../utils/eval-mock"; +import 'jest-extended'; +import { poseGraphOp } from "../../../../cocos/animation/marionette/pose-graph/op"; +import { PoseGraphType } from "../../../../cocos/animation/marionette/pose-graph/foundation/type-system"; +import { getTheOnlyInputKey, getTheOnlyOutputKey, UnimplementedPoseNode } from "./utils/misc"; +import { PoseNode } from "../../../../cocos/animation/marionette/pose-graph/pose-node"; +import { PureValueNode } from "../../../../cocos/animation/marionette/pose-graph/pure-value-node"; + +describe(`Pose node instantiation`, () => { + test(`Should be instantiated at animation graph initialization stage`, () => { + class PoseNodeMock extends PoseNode { + public settle(context: AnimationGraphSettleContext): void { } + public reenter(): void { } + protected doUpdate(context: AnimationGraphUpdateContext): void { } + + public static counter = 0; + + public static constructorMock: jest.Mock = jest.fn(); + + constructor() { + super(); + this._yieldingValue = PoseNodeMock.#valueGenerator++; + PoseNodeMock.constructorMock(this); + } + + get expectedYieldingValue() { + return this._yieldingValue; + } + + public bind(context: AnimationGraphBindingContext): void { + this._handle = context.bindAuxiliaryCurve('x'); + } + + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + const pose = context.pushDefaultedPose(); + expect(this._handle).not.toBeNull(); + pose.auxiliaryCurves[this._handle!.index] = this._yieldingValue; + return pose; + } + + static #valueGenerator = 0; + private _yieldingValue: number; + private _handle: AuxiliaryCurveHandle | null = null; + } + + const animationGraph = new AnimationGraph(); + const layer = animationGraph.addLayer(); + const poseState = layer.stateMachine.addPoseState(); + const poseNodeMock = poseState.graph.addNode(new PoseNodeMock()); + poseGraphOp.connectNode(poseState.graph, poseState.graph.outputNode, getTheOnlyInputKey(poseState.graph.outputNode), poseNodeMock); + layer.stateMachine.connect(layer.stateMachine.entryState, poseState); + + expect(PoseNodeMock.constructorMock).toBeCalledTimes(1); + PoseNodeMock.constructorMock.mockClear(); + + const instances = Array.from({ length: 2 }, () => { + const node1 = new Node(); + const evalMock = new AnimationGraphEvalMock(node1, animationGraph); + expect(PoseNodeMock.constructorMock).toBeCalledTimes(1); + const node = PoseNodeMock.constructorMock.mock.calls[0][0]; + PoseNodeMock.constructorMock.mockClear(); + return { + node, + evalMock, + }; + }); + + for (const { node: node, evalMock } of instances) { + evalMock.step(0.2); + expect(evalMock.controller.getAuxiliaryCurveValue_experimental('x')).toBe(node.expectedYieldingValue); + } + }); +}); + +describe(`Pose node binding and settlement`, () => { + test(`Should be called at animation graph bind stage`, () => { + const poseNode1BindMethodMock = jest.fn(); + const poseNode1SettleMethodMock = jest.fn(); + const poseNode2BindMethodMock = jest.fn(); + const poseNode2SettleMethodMock = jest.fn(); + + class PoseNode1 extends UnimplementedPoseNode { + public bind(context: AnimationGraphBindingContext) { + poseNode1BindMethodMock(); + } + + public settle(context: AnimationGraphSettleContext) { + poseNode1SettleMethodMock(); + } + } + + class PoseNode2 extends UnimplementedPoseNode { + public bind(context: AnimationGraphBindingContext) { + poseNode2BindMethodMock(); + } + + public settle(context: AnimationGraphSettleContext) { + poseNode2SettleMethodMock(); + } + } + + const animationGraph = createAnimationGraph({ + layers: [{ + stateMachine: { + states: { + 'empty': { type: 'empty' }, + 'pose1': { + type: 'pose', + graph: { rootNode: new PoseNode1() }, + }, + 'pose2': { + type: 'pose', + graph: { rootNode: new PoseNode2() }, + }, + }, + }, + }], + }); + + const evalMock = new AnimationGraphEvalMock(new Node(), animationGraph); + + const bindMocks = [poseNode1BindMethodMock, poseNode2BindMethodMock]; + const settleMocks = [poseNode1SettleMethodMock, poseNode2SettleMethodMock]; + + // Both nodes' bind() should be called. + for (const bindMock of bindMocks) { + expect(bindMock).toBeCalledTimes(1); + } + // Both nodes' settle() should be called. + for (const settleMock of settleMocks) { + expect(settleMock).toBeCalledTimes(1); + } + // All settle() happen after all bind(). + for (const bindMock of bindMocks) { + for (const settleMock of settleMocks) { + expect(bindMock.mock.invocationCallOrder[0]).toBeLessThan(settleMock.mock.invocationCallOrder[0]); + } + } + for (const mock of [...bindMocks, ...settleMocks]) { + mock.mockClear(); + } + + // No further bind/settle calls. + evalMock.step(0.3); + for (const mock of [...bindMocks, ...settleMocks]) { + expect(mock).not.toBeCalled(); + } + }); +}); + +describe(`Pose node reentering`, () => { + test(`Enter a pose node state should trigger the root pose node's reenter() method`, () => { + class PoseNodeMock extends UnimplementedPoseNode { + public reenterRecorder = jest.fn(); + + public reenter(...args: Parameters) { + this.reenterRecorder(...args); + } + + public bind(context: AnimationGraphBindingContext): void { } + + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { return context.pushDefaultedPose(); } + } + + const poseNodeMock = new PoseNodeMock(); + + const animationGraph = createAnimationGraph({ + variableDeclarations: { + 'IncomingTransitionActivated': { type: 'boolean', value: false }, + 'OutgoingTransitionActivated': { type: 'boolean', value: false }, + }, + layers: [{ + stateMachine: { + states: { + 'empty': { type: 'empty' }, + 'pose': { + type: 'pose', + graph: { + rootNode: poseNodeMock, + }, + }, + }, + entryTransitions: [{ to: 'pose' }], + transitions: [{ + from: 'pose', + to: 'empty', + duration: 0.3, + conditions: [{ type: 'unary', operand: { type: 'variable', name: 'OutgoingTransitionActivated' } }], + }, { + from: 'empty', + to: 'pose', + duration: 0.3, + conditions: [{ type: 'unary', operand: { type: 'variable', name: 'IncomingTransitionActivated' } }], + }], + }, + }], + }); + + const evalMock = new AnimationGraphEvalMock(new Node(), animationGraph); + + evalMock.step(0.1); + expect(poseNodeMock.reenterRecorder).toBeCalledTimes(1); + poseNodeMock.reenterRecorder.mockClear(); + + evalMock.step(0.1); + expect(poseNodeMock.reenterRecorder).toBeCalledTimes(0); + + evalMock.controller.setValue('OutgoingTransitionActivated', true); + evalMock.step(0.4); + expect(poseNodeMock.reenterRecorder).toBeCalledTimes(0); + + evalMock.controller.setValue('OutgoingTransitionActivated', false); + evalMock.controller.setValue('IncomingTransitionActivated', true); + evalMock.step(0.1); + expect(poseNodeMock.reenterRecorder).toBeCalledTimes(1); + poseNodeMock.reenterRecorder.mockClear(); + + evalMock.step(0.1); + expect(poseNodeMock.reenterRecorder).toBeCalledTimes(0); + }); +}); + +describe(`Pose node ticking`, () => { + test(`PureValueNode dependencies should be evaluated before pose node updating`, () => { + let pvNodeOutputValue = 0.0; + + const poseNodeUpdateMethodMock = jest.fn(); + const pvNodeEvaluateMethodMock = jest.fn(() => pvNodeOutputValue); + + class ObservedPVNode extends PureValueNode { + constructor() { + super([PoseGraphType.FLOAT]); + } + + public selfEvaluate(outputs: unknown[]): void { + outputs[0] = pvNodeEvaluateMethodMock(); + } + } + + class ObservedPoseNode extends UnimplementedPoseNode { + @input({ type: PoseGraphType.FLOAT }) + public value = 0.0; + + public bind() { } + + protected doUpdate() { + poseNodeUpdateMethodMock(this.value); + } + + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + return context.pushDefaultedPose(); + } + } + + const animationGraph = new AnimationGraph(); + const layer = animationGraph.addLayer(); + const poseState = layer.stateMachine.addPoseState(); + const poseNode = poseState.graph.addNode(new ObservedPoseNode()); + const pvNode = poseState.graph.addNode(new ObservedPVNode()); + const keys = poseGraphOp.getInputKeys(poseNode); + expect(keys).toHaveLength(1); + poseGraphOp.connectNode(poseState.graph, poseNode, keys[0], pvNode, getTheOnlyOutputKey(pvNode)); + poseGraphOp.connectNode(poseState.graph, poseState.graph.outputNode, getTheOnlyInputKey(poseState.graph.outputNode), poseNode); + layer.stateMachine.connect(layer.stateMachine.entryState, poseState); + + const node = new Node(); + for (let i = 0; i < 2; ++i) { + // Change the pv-node's evaluation result. + pvNodeOutputValue = 0.1 + 0.1 * i; + + const evalMock = new AnimationGraphEvalMock(node, animationGraph); + evalMock.step(0.2); + + // Pose node's doUpdate() should have been called. + expect(poseNodeUpdateMethodMock).toHaveBeenCalledTimes(1); + + // PV-node's evaluate() should have been called. + expect(pvNodeEvaluateMethodMock).toHaveBeenCalledTimes(1); + + // PV-node's evaluate() should happen before Pose node's doUpdate(). + expect(pvNodeEvaluateMethodMock.mock.invocationCallOrder[0]).toBeLessThan( + poseNodeUpdateMethodMock.mock.invocationCallOrder[0], + ); + + // Pose nodes's doUpdate() should have received the pv-node's return. + expect(poseNodeUpdateMethodMock.mock.calls[0][0]).toBe(pvNodeEvaluateMethodMock.mock.results[0].value); + + poseNodeUpdateMethodMock.mockClear(); + pvNodeEvaluateMethodMock.mockClear(); + } + }); +}); diff --git a/tests/animation/new-gen-anim/pose-graph/top-level-pose-node.test.ts b/tests/animation/new-gen-anim/pose-graph/top-level-pose-node.test.ts new file mode 100644 index 0000000000..04324b2d88 --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/top-level-pose-node.test.ts @@ -0,0 +1,30 @@ +import { AnimationGraph } from "../../../../cocos/animation/marionette/animation-graph"; +import { connectOutputNode } from "../../../../cocos/animation/marionette/pose-graph/op/internal"; +import { Node } from "../../../../cocos/scene-graph"; +import { AnimationGraphEvalMock } from "../utils/eval-mock"; +import { createAdditivityCheckMock } from "./utils/additive"; + +test(`Additivity inheritance`, () => { + /// - The additivity of top level pose's binding context is inherited from animation graph layer. + + t(true); + t(false); + + function t(additive: boolean) { + const additivityCheckMock = createAdditivityCheckMock(); + + const graph = new AnimationGraph(); + const layer = graph.addLayer(); + layer.additive = additive; + + const poseState = layer.stateMachine.addPoseState(); + const poseNodeMock = poseState.graph.addNode(new additivityCheckMock.PoseNodeMock()); + connectOutputNode(poseState.graph, poseState.graph.outputNode, poseNodeMock); + layer.stateMachine.connect(layer.stateMachine.entryState, poseState); + + void new AnimationGraphEvalMock(new Node(), graph); + + expect(additivityCheckMock.bindMock).toBeCalledTimes(1); + expect(additivityCheckMock.bindMock.mock.calls[0][0]).toBe(additive); + } +}); diff --git a/tests/animation/new-gen-anim/pose-graph/utils/additive.ts b/tests/animation/new-gen-anim/pose-graph/utils/additive.ts new file mode 100644 index 0000000000..e9d2e119f9 --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/utils/additive.ts @@ -0,0 +1,48 @@ +import { AnimationController } from "../../../../../cocos/animation/animation"; +import { AnimationGraphBindingContext, AnimationGraphPoseLayoutMaintainer, AnimationGraphSettleContext, AnimationGraphUpdateContext, AuxiliaryCurveRegistry } from "../../../../../cocos/animation/marionette/animation-graph-context"; +import { PoseNode } from "../../../../../cocos/animation/marionette/pose-graph/pose-node"; +import { Node } from "../../../../../cocos/scene-graph"; + +export function createAdditivityCheckMock() { + const bindMock = jest.fn(); + + const bindMock2 = jest.fn(function(...args: Parameters) { + const [context] = args; + bindMock(context.additive); + }); + + class PoseNodeMock extends PoseNode { + public settle(context: AnimationGraphSettleContext): void { } + public reenter(): void { } + protected doUpdate(context: AnimationGraphUpdateContext): void { } + bind = bindMock2; + doEvaluate = jest.fn(); + } + + return { + bindMock, + PoseNodeMock: PoseNodeMock, + }; +} + +export function createPoseNodeBindContextMock_WithAdditive(additive: boolean): AnimationGraphBindingContext { + const node = new Node(); + const controller = node.addComponent(AnimationController) as AnimationController; + const auxiliaryCurveRegistry = new AuxiliaryCurveRegistry(); + const varRegistry = {}; + const poseLayoutMaintainer = new AnimationGraphPoseLayoutMaintainer(node, auxiliaryCurveRegistry); + const result = new AnimationGraphBindingContext( + node, + poseLayoutMaintainer, + varRegistry, + controller, + // @ts-expect-error HACK here + controller._customEventTarget, + ); + result._pushAdditiveFlag(additive); + return result; +} + +export function invokePoseNodeBindMethod(poseNode: PoseNode, context: AnimationGraphBindingContext) { + poseNode.bind(context); +} \ No newline at end of file diff --git a/tests/animation/new-gen-anim/pose-graph/utils/misc.ts b/tests/animation/new-gen-anim/pose-graph/utils/misc.ts new file mode 100644 index 0000000000..2915d83a0c --- /dev/null +++ b/tests/animation/new-gen-anim/pose-graph/utils/misc.ts @@ -0,0 +1,83 @@ +import { AnimationGraph } from "../../../../../cocos/animation/marionette/asset-creation"; +import { poseGraphOp } from "../../../../../cocos/animation/marionette/pose-graph/op"; +import { PoseGraphNode } from "../../../../../cocos/animation/marionette/pose-graph/foundation/pose-graph-node"; +import { Pose } from "../../../../../cocos/animation/core/pose"; +import { AnimationGraphBindingContext, AnimationGraphEvaluationContext, AnimationGraphSettleContext, AnimationGraphUpdateContext } from "../../../../../cocos/animation/marionette/animation-graph-context"; +import { Quat, Vec3 } from "../../../../../exports/base"; +import { PoseNode } from "../../../../../cocos/animation/marionette/pose-graph/pose-node"; +import { PureValueNode } from "../../../../../cocos/animation/marionette/pose-graph/pure-value-node"; + +export function normalizeNodeInputMetadata(nodeInputMetadata?: poseGraphOp.InputMetadata) { + return nodeInputMetadata ? { + deletable: false, + insertPoint: false, + ...nodeInputMetadata + } : undefined; +} + +export function createPoseGraph() { + return new AnimationGraph().addLayer().stateMachine.addPoseState().graph; +} + +export function getTheOnlyInputKey(node: PoseGraphNode) { + const keys = poseGraphOp.getInputKeys(node); + expect(keys).toHaveLength(1); + return keys[0]; +} + +export function getTheOnlyOutputKey(node: PoseGraphNode) { + const outputs = poseGraphOp.getOutputKeys(node); + expect(outputs).toHaveLength(1); + return outputs[0]; +} + +export function findInputKeyHavingDisplayName(node: PoseGraphNode, displayName: string) { + const key = poseGraphOp.getInputKeys(node) + .find((inputKey) => poseGraphOp.getInputMetadata(node, inputKey)?.displayName === displayName); + expect(key).not.toBeUndefined(); + return key!; +} + +export function checkZeroPose(pose: Pose) { + for (let iTransform = 0; iTransform < pose.transforms.length; ++iTransform) { + expect(pose.transforms.getPosition(iTransform, new Vec3())).toMatchObject({ + x: 0, y: 0, z: 0 + }); + expect(pose.transforms.getRotation(iTransform, new Quat())).toMatchObject({ + x: 0, y: 0, z: 0, w: 1, + }); + expect(pose.transforms.getScale(iTransform, new Vec3())).toMatchObject({ + x: 0, y: 0, z: 0 + }); + } + + for (let iAuxiliaryCurve = 0; iAuxiliaryCurve < pose.auxiliaryCurves.length; ++iAuxiliaryCurve) { + expect(pose.auxiliaryCurves[iAuxiliaryCurve]).toBe(0); + } +} + +export class UnimplementedPoseNode extends PoseNode { + public settle(context: AnimationGraphSettleContext): void { + + } + public reenter(): void { + + } + + public bind(context: AnimationGraphBindingContext): void { + } + + protected doUpdate(context: AnimationGraphUpdateContext): void { + + } + + protected doEvaluate(context: AnimationGraphEvaluationContext): Pose { + throw new Error("Method not implemented."); + } +} + +export class UnimplementedPVNode extends PureValueNode { + public selfEvaluate(outputs: unknown[]): void { + throw new Error("Method not implemented."); + } +} \ No newline at end of file diff --git a/tests/animation/new-gen-anim/utils/factory.ts b/tests/animation/new-gen-anim/utils/factory.ts index cc42625446..2b5cdbfa3d 100644 --- a/tests/animation/new-gen-anim/utils/factory.ts +++ b/tests/animation/new-gen-anim/utils/factory.ts @@ -1,15 +1,16 @@ import { AnimationClip } from "../../../../cocos/animation/animation-clip"; import { AnimationGraph, AnimationTransition, EmptyStateTransition, isAnimationTransition, PoseState, PoseTransition, State, StateMachine, SubStateMachine, Transition } from "../../../../cocos/animation/marionette/animation-graph"; -import { PoseGraph, PoseNode, TCBinding, TCBindingValueType } from "../../../../cocos/animation/marionette/asset-creation"; +import { PoseGraph, poseGraphOp, TCBinding, TCBindingValueType } from "../../../../cocos/animation/marionette/asset-creation"; import { Motion, ClipMotion, AnimationBlend1D, AnimationBlend2D } from "../../../../cocos/animation/marionette/motion"; import { BinaryCondition, TriggerCondition, UnaryCondition } from "../../../../cocos/animation/marionette/state-machine/condition"; import { MotionState } from "../../../../cocos/animation/marionette/state-machine/motion-state"; import { Bindable } from "../../../../cocos/animation/marionette/parametric"; import { TriggerResetMode } from "../../../../cocos/animation/marionette/variable"; -import { Vec2 } from "../../../../exports/base"; +import { assertIsTrue, Vec2 } from "../../../../exports/base"; import { TCVariableBinding } from "../../../../cocos/animation/marionette/state-machine/condition/binding/variable-binding"; import { TCAuxiliaryCurveBinding } from "../../../../cocos/animation/marionette/state-machine/condition/binding/auxiliary-curve-binding"; import { TCStateWeightBinding } from "../../../../cocos/animation/marionette/state-machine/condition/binding/state-weight-binding"; +import { PoseNode } from "../../../../cocos/animation/marionette/pose-graph/pose-node"; export function createAnimationGraph(params: AnimationGraphParams): AnimationGraph { const animationGraph = new AnimationGraph(); @@ -159,7 +160,7 @@ function fillTransition(transition: Transition, params: TransitionAttributes) { function assertsIsDurableTransition(transition: Transition): asserts transition is (AnimationTransition | EmptyStateTransition | PoseTransition) { if (!isAnimationTransition(transition) && !(transition instanceof EmptyStateTransition) && !(transition instanceof PoseTransition)) { - throw new Error(`The transition should be animation/empty transition.`); + throw new Error(`The transition should be animation/empty/pose transition.`); } } @@ -388,21 +389,44 @@ export type MotionParams = { }>; }; -export interface PoseGraphParams { +interface PoseGraphParams { rootNode?: PoseNodeParams; } -export type PoseNodeParams = PoseNode; +export type PoseNodeParams = PoseNode | Node_; function fillPoseGraph(poseGraph: PoseGraph, params: PoseGraphParams) { if (params.rootNode) { const root = createPoseNode(poseGraph, params.rootNode); - poseGraph.main = root; + poseGraphOp.connectOutputNode(poseGraph, poseGraph.outputNode, root); } } -export function createPoseNode(poseGraph: PoseGraph, params: PoseNodeParams): NonNullable { - poseGraph.addNode(params); - return params; +declare global { + interface PoseNodeFactoryRegistry { + } +} + +type Map_ = { + [k in keyof PoseNodeFactoryRegistry]: PoseNodeFactoryRegistry[k] & { type: k }; +} + +const poseNodeFactoryMap: Record PoseNode> = {}; + +export function addPoseNodeFactory ( + type: T, factory: (poseGraph: PoseGraph, params: PoseNodeFactoryRegistry[T]) => PoseNode) { + poseNodeFactoryMap[type] = factory; +} + +export type Node_ = Map_[keyof Map_]; + +export function createPoseNode(poseGraph: PoseGraph, params: PoseNodeParams): PoseNode { + if (params instanceof PoseNode) { + return poseGraph.addNode(params); + } else if (!(params.type in poseNodeFactoryMap)) { + throw new Error(`${params.type} factory does not exist.`); + } else { + return poseNodeFactoryMap[params.type](poseGraph, params); + } }