A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(anim): a layer writes the part of the rig it was given
esengine067054db38ae
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ae77fe06e..44f77fd05 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -540,6 +540,7 @@ send: (event: AnimatorEventPayload) => voidanyStateTransitions: AnimatorTransition[] | undefinedblend: AnimatorLayerBlend | undefinedinitialState: string+mask: AnimatorMask | undefinedname: stringstates: AnimatorState[]weight: number | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 84cca8061..f48c02178 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -540,6 +540,7 @@ send: (event: AnimatorEventPayload) => voidanyStateTransitions: AnimatorTransition[] | undefinedblend: AnimatorLayerBlend | undefinedinitialState: string+mask: AnimatorMask | undefinedname: stringstates: AnimatorState[]weight: number | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 752a267ce..b93758922 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -535,6 +535,7 @@ send: (event: AnimatorEventPayload) => voidanyStateTransitions: AnimatorTransition[] | undefinedblend: AnimatorLayerBlend | undefinedinitialState: string+mask: AnimatorMask | undefinedname: stringstates: AnimatorState[]weight: number | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 45ce4a877..3e170e615 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -535,6 +535,7 @@ send: (event: AnimatorEventPayload) => voidanyStateTransitions: AnimatorTransition[] | undefinedblend: AnimatorLayerBlend | undefinedinitialState: string+mask: AnimatorMask | undefinedname: stringstates: AnimatorState[]weight: number | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5331fcf65..092a6c6bd 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -535,6 +535,7 @@ send: (event: AnimatorEventPayload) => voidanyStateTransitions: AnimatorTransition[] | undefinedblend: AnimatorLayerBlend | undefinedinitialState: string+mask: AnimatorMask | undefinedname: stringstates: AnimatorState[]weight: number | undefineddiff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsindex 330dd72fe..d8a5a8609 100644--- a/sdk/src/animation/Animator.ts+++ b/sdk/src/animation/Animator.ts@@ -31,6 +31,7 @@ import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';import { Pose } from './pose';import { mixPoses } from './poseMix';import { overlayPose, addPoseOver } from './layerStack';+import { MaskReach, type AnimatorMask } from './animatorMask';import { AnimatorRootMotion, type AnimatorRootMotionData } from './animatorRootMotion';import type { AnimatorEventSink } from './animatorEvent';import { Transform, type TransformData } from '../ecs/component';@@ -168,6 +169,8 @@ export interface AnimatorLayer extends AnimatorScope {/** 0 leaves the layers below untouched, 1 states this layer whole. */weight?: number;blend?: AnimatorLayerBlend;+ /** Which part of the rig this layer may write; absent is all of it. */+ mask?: AnimatorMask;}/** What a `.esanimator` this build writes claims. */@@ -817,8 +820,9 @@ export class AnimatorControllerAPI {}const layer = def.layers![index - 1]!;const weight = layer.weight ?? 1;+ const reach = this.reachFor(world, ctx.entity, rt.layers[index]!, layer.mask);if (layer.blend !== 'additive') {- overlayPose(rt.composed, pose, weight, world, null);+ overlayPose(rt.composed, pose, weight, world, reach);return;}rt.rest.reset();@@ -826,7 +830,7 @@ export class AnimatorControllerAPI {// The clip's own first frame is its rest: an additive clip says "from// where this motion starts", so nothing else has to be authored for it.if (ctx.sample(motion, 0, rt.rest)) {- addPoseOver(rt.composed, pose, rt.rest, weight, world, null);+ addPoseOver(rt.composed, pose, rt.rest, weight, world, reach);}}@@ -922,6 +926,16 @@ export class AnimatorControllerAPI {if (rt.fadeElapsed >= rt.fadeDuration) rt.fadeFrom = null;}+ /** This layer's mask against this rig, or null where it writes all of it. */+ private reachFor(+ world: World, entity: Entity, rt: LayerRuntime, mask: AnimatorMask | undefined,+ ): MaskReach | null {+ if (!mask) return null;+ const reach = rt.reach ?? (rt.reach = new MaskReach());+ reach.resolve(world, entity, mask);+ return reach;+ }+/*** What this layer's motion says, as a pose for the stack to compose — two* composed here already when a fade is running, mixing being the operation@@ -1039,6 +1053,8 @@ interface LayerRuntime {poseFrom: Pose;poseTo: Pose;mixed: Pose;+ /** This layer's mask, resolved against the rig it is running on. */+ reach?: MaskReach;}const EMPTY_PARAMS: ReadonlyMap<string, number | boolean> = new Map();diff --git a/sdk/src/animation/animatorMask.ts b/sdk/src/animation/animatorMask.tsnew file mode 100644index 000000000..ea7855fef--- /dev/null+++ b/sdk/src/animation/animatorMask.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file animatorMask.ts+ * @brief The part of a rig a layer is allowed to write.+ *+ * @details A mask needs no vocabulary of its own: a rig's joints ARE its entity+ * hierarchy, and a clip already names what it animates by `childPath`.+ * So a mask is a set of those same paths, each standing for the subtree+ * under it — and it is resolved against the entity being animated,+ * because the same controller drives rigs that are not the same objects.+ */++import type { Entity } from '../types';+import type { World } from '../ecs/world';+import { resolveChildEntity, collectSubtree } from '../ecs/childPath';+import type { PoseTrack } from './pose';+import type { LayerReach } from './layerStack';++/** Which subtrees of the animated entity a layer may write. */+export interface AnimatorMask {+ /**+ * Each names a subtree by `childPath`, the subtree's own root included; the+ * empty path is the whole rig. A mask with no paths admits nothing, which is+ * a layer switched off rather than a layer with no restriction — that is+ * spelled by having no mask at all.+ */+ paths: string[];+}++/**+ * One layer's resolved mask, reused across frames. Re-resolved each time rather+ * than cached against the hierarchy: a rig gains and loses entities while it+ * plays, and a mask that went stale would silently start writing a joint the+ * author excluded.+ */+export class MaskReach implements LayerReach {+ private readonly admitted_ = new Set<Entity>();++ resolve(world: Pick<World, 'tryGet'>, root: Entity, mask: AnimatorMask): void {+ this.admitted_.clear();+ for (const path of mask.paths) {+ const at = resolveChildEntity(world, root, path);+ if (at !== null) collectSubtree(world, at, this.admitted_);+ }+ }++ admits(track: PoseTrack): boolean {+ return this.admitted_.has(track.entity);+ }+}diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex 18ad99f6b..969c82cbf 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -141,6 +141,11 @@ export {type AnimClipSizing,} from './AnimClipLoader';+export {+ MaskReach,+ type AnimatorMask,+} from './animatorMask';+export {migrateAnimatorController,type AnimatorMigration,diff --git a/sdk/src/ecs/childPath.ts b/sdk/src/ecs/childPath.tsnew file mode 100644index 000000000..85f591427--- /dev/null+++ b/sdk/src/ecs/childPath.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file childPath.ts+ * @brief Address a descendant by its `"a/b/c"` path of names, and walk a subtree.+ *+ * A rig's joints ARE its entity hierarchy here, so this is how an animation clip+ * reaches the bone it animates and how a layer mask names the part of the body it+ * is allowed to write. It grew up under `timeline/` because clips asked first,+ * but nothing in it is a timeline — it speaks Children and Name — so it lives+ * where anything addressing a rig can reach it without importing that module.+ */+import type { World } from './world';+import type { Entity } from '../types';+import { getComponent } from './component';++/**+ * The descendant `childPath` names, relative to `rootEntity`; the root itself for+ * an empty path. Null when a segment names no child, which is what an authored+ * path pointing at a renamed bone comes to.+ */+export function resolveChildEntity(+ world: Pick<World, 'tryGet'>, rootEntity: Entity, childPath: string,+): Entity | null {+ if (!childPath) return rootEntity;++ const Children = getComponent('Children');+ const Name = getComponent('Name');+ if (!Children || !Name) return null;++ let current: Entity = rootEntity;+ for (const segment of childPath.split('/')) {+ const childrenData = world.tryGet(current, Children);+ if (!childrenData) return null;++ const childEntities: Entity[] = childrenData['entities'] || [];+ let found: Entity | null = null;+ for (const childId of childEntities) {+ const nameData = world.tryGet(childId, Name);+ if (nameData && nameData['value'] === segment) {+ found = childId;+ break;+ }+ }+ if (found === null) return null;+ current = found;+ }+ return current;+}++/** Add `root` and everything under it to `out`. */+export function collectSubtree(+ world: Pick<World, 'tryGet'>, root: Entity, out: Set<Entity>,+): void {+ if (out.has(root)) return;+ out.add(root);+ const Children = getComponent('Children');+ if (!Children) return;+ const children = world.tryGet(root, Children);+ if (!children) return;+ for (const child of (children['entities'] || []) as Entity[]) {+ collectSubtree(world, child, out);+ }+}diff --git a/sdk/src/timeline/TimelineRuntime.ts b/sdk/src/timeline/TimelineRuntime.tsindex a6336deb7..479847c11 100644--- a/sdk/src/timeline/TimelineRuntime.ts+++ b/sdk/src/timeline/TimelineRuntime.ts@@ -24,6 +24,8 @@ export const TimelineEventType = {ActivationSet: 4,} as const;+export { resolveChildEntity } from '../ecs/childPath';+export function setNestedProperty(obj: Record<string, any>, path: string, value: number): boolean {const parts = path.split('.');let target = obj;@@ -37,40 +39,7 @@ export function setNestedProperty(obj: Record<string, any>, path: string, value:return true;}-export function resolveChildEntity(world: Pick<World, 'tryGet'>, rootEntity: Entity, childPath: string): Entity | null {- if (!childPath) return rootEntity;-- const Children = getComponent('Children');- const Name = getComponent('Name');- if (!Children || !Name) return null;-- let current: Entity = rootEntity;- const segments = childPath.split('/');-- for (const segment of segments) {- const childrenData = world.tryGet(current, Children);- if (!childrenData) return null;-- const childEntities: Entity[] = childrenData.entities || [];- let found: Entity | null = null;- for (const childId of childEntities) {- const nameData = world.tryGet(childId, Name);- if (nameData && nameData.value === segment) {- found = childId;- break;- }- }- if (found === null) return null;- current = found;- }-- return current;-}-/**- * Apply ONE timeline event to the world (component mutations / audio). Called by- * the pure-TS runtime (TimelineDrive) with edge-detected events.- */export function applyTimelineEvent(world: any, audio: AudioAPI | null,type: number, entity: Entity,diff --git a/sdk/tests/animatorLayers.test.ts b/sdk/tests/animatorLayers.test.tsindex 7723edc04..b253d68e5 100644--- a/sdk/tests/animatorLayers.test.ts+++ b/sdk/tests/animatorLayers.test.ts@@ -13,7 +13,7 @@ import {} from '../src/animation';import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';import { TimelineAPI } from '../src/timeline/TimelineControl';-import { defineComponent } from '../src/ecs/component';+import { defineComponent, Name, Children, Parent } from '../src/ecs/component';import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';const E = 1;@@ -386,3 +386,105 @@ describe('the controller format guard', () => {expect(() => migrateAnimatorController({ ...v1(), layers: {} })).toThrow(/layers/);});});++// ---------------------------------------------------------------------------+// What a layer is allowed to touch+// ---------------------------------------------------------------------------++/**+ * A rig: root → `hips` → `legs`, root → `chest` → `arms`. Names are what a+ * childPath resolves through, so the mask and the clips address it the same way.+ */+function rig(world: any): Record<string, number> {+ const ids = { root: E, hips: 2, legs: 3, chest: 4, arms: 5 };+ const link = (parent: number, child: number, name: string) => {+ world.insert(child, Name, { value: name });+ world.insert(child, Parent, { entity: parent });+ const held = world.tryGet(parent, Children) as { entities: number[] } | null;+ world.insert(parent, Children, { entities: [...(held?.entities ?? []), child] });+ world.insert(child, probe(), { lift: 0, turn: 0, rot: { w: 1, x: 0, y: 0, z: 0 } });+ };+ world.insert(ids.root, Name, { value: 'root' });+ link(ids.root, ids.hips, 'hips');+ link(ids.hips, ids.legs, 'legs');+ link(ids.root, ids.chest, 'chest');+ link(ids.chest, ids.arms, 'arms');+ return ids;+}++/** A clip writing `lift` on every joint of the rig. */+function wholeBody(lift: number): TimelineAsset {+ const channel = (childPath: string) => ({+ type: TrackType.Property, component: 'LayerProbe', childPath, name: childPath || 'root',+ channels: [{+ property: 'lift',+ keyframes: [{+ time: 0, value: lift, inTangent: 0, outTangent: 0,+ interpolation: InterpType.Linear,+ }],+ }],+ });+ return {+ version: '1.2', type: 'timeline', duration: 10, wrapMode: WrapMode.Loop,+ tracks: ['', 'hips', 'hips/legs', 'chest', 'chest/arms'].map(channel),+ } as TimelineAsset;+}++describe('a masked layer', () => {+ const assets = {+ 'base.estimeline': wholeBody(10),+ 'upper.estimeline': wholeBody(90),+ };+ const liftAt = (world: any, e: number) => (world.get(e, probe()) as { lift: number }).lift;++ function run(mask: { paths: string[] } | undefined, weight = 1) {+ const world = seedWorld();+ const ids = rig(world);+ const ctrl = build(assets, 'base.estimeline',+ [over('upper.estimeline', { mask, weight })]);+ attach(world);+ ctrl.update(world, 0.016);+ return { world, ids };+ }++ it('writes the subtree it names, root included', () => {+ const { world, ids } = run({ paths: ['chest'] });+ expect(liftAt(world, ids.chest)).toBeCloseTo(90, 4);+ expect(liftAt(world, ids.arms)).toBeCloseTo(90, 4);+ });++ it('leaves everything outside it exactly as the layer below left it', () => {+ // Not "close to" the base value — the same number. A mask that merely+ // reduced the weight outside itself would still read as nearly right.+ const { world, ids } = run({ paths: ['chest'] });+ expect(liftAt(world, ids.hips)).toBe(10);+ expect(liftAt(world, ids.legs)).toBe(10);+ expect(liftAt(world, ids.root)).toBe(10);+ });++ it('carries the layer weight inside the mask and nothing outside it', () => {+ const { world, ids } = run({ paths: ['chest'] }, 0.5);+ expect(liftAt(world, ids.arms)).toBeCloseTo(50, 4);+ expect(liftAt(world, ids.legs)).toBe(10);+ });++ it('writes the whole rig when there is no mask', () => {+ const { world, ids } = run(undefined);+ expect(liftAt(world, ids.legs)).toBeCloseTo(90, 4);+ expect(liftAt(world, ids.arms)).toBeCloseTo(90, 4);+ });++ it('writes nothing for a mask that names nothing', () => {+ // An empty path list is a layer switched off, which is different from+ // having no mask — and the two must not read the same.+ const { world, ids } = run({ paths: [] });+ expect(liftAt(world, ids.legs)).toBe(10);+ expect(liftAt(world, ids.arms)).toBe(10);+ });++ it('ignores a path that names no joint on this rig', () => {+ const { world, ids } = run({ paths: ['chest', 'tail'] });+ expect(liftAt(world, ids.arms)).toBeCloseTo(90, 4);+ expect(liftAt(world, ids.legs)).toBe(10);+ });+});