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(rig2d): bones keep an id, take a new parent, and rebind onto another skeleton by name
yhh8badae081b3f
diff --git a/desktop b/desktopindex 67d4139e9..a1b45b00e 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 67d4139e9ad01b945e1d955ca1745c074b79cfeb+Subproject commit a1b45b00e2e2e51e025382e9c03c90fecf5f0e76diff --git a/docs/astro/src/content/docs/animation/rig-2d.mdx b/docs/astro/src/content/docs/animation/rig-2d.mdxindex f4892505e..28c40c56d 100644--- a/docs/astro/src/content/docs/animation/rig-2d.mdx+++ b/docs/astro/src/content/docs/animation/rig-2d.mdx@@ -26,12 +26,29 @@ Right-click an image in the Content Browser and choose **Create 2D Rig**. Then w| **Weights** | **By Distance** binds what is nearest, then paint what that got wrong: pick a bone on the right and drag. `Shift` inverts, `Ctrl` smooths, `[` and `]` change the radius. **Whole Part to Selected Bone** is for a piece that does not bend. || **Deforms** | **New Shape**, then drag to push vertices: a breath, a smile, a bulge. |-**Try Pose** turns bones to see how the weights hold up. It changes nothing in the rig, and **Bind Pose** puts it back. **Place in Scene** saves and instantiates the prefab. Saving again updates every instance, keeping what a scene added to one.+**Try Pose** turns bones to see how the weights hold up. It changes nothing in the rig, and **Bind Pose** puts it back. **Place in Scene** saves and instantiates the prefab. Saving again updates every instance in the open scene, keeping what a scene added to one; when the scene has unsaved changes, its instances update the next time it opens.<Aside type="note">This version has no adding or deleting single vertices, and a character draws from one image. Generating a part's mesh again clears that part's weights and deforms, and asks first.</Aside>+## Rebind after binding++A character is never locked to the skeleton it was weighted on.++- **Move a bone.** In **Bind Pose**, dragging a bone or typing its length or rotation changes the bind pose itself. The picture stays where it is, so a bone placed wrong can just be moved.+- **New parent.** In **Bones**, pick **Parent** for the selected bone, or **None (root)**. It keeps its place in the picture, and so does everything below it.+- **Rename or remove.** Removing a bone hands its children and vertices to its parent.+- **Recompute weights.** **By Distance** again, or **Whole Part to Selected Bone**, then paint.+- **Another rig's skeleton.** Under **Skeleton**, pick another `.esrig` and **Rebind to This Skeleton**. Bones are matched by name. A vertex on a bone with no namesake goes to its nearest matched parent. Rigs that share a skeleton have the same bone names and paths, so they play the same clips.++Saving keeps up what depended on the old names:++- Clips (`.estimeline`) and Animator layer masks (`.esanimator`) that named a renamed or reparented bone by its path are rewritten. A clip counts as this rig's when most of its paths are this rig's bones. A track on a removed bone keeps its path, and the save says how many there are.+- Each bone keeps an id, which is what its prefab entity is named by. What the scene added to a bone, such as an `IK2D` or a sword parented to the hand, stays on that bone through reordering, reparenting and removal elsewhere.++**In the scene**, select an entity with a `MeshSkin` and use **Rebind To** in Details: pick another skeleton in the scene and **Rebind Joints by Name**. Each joint finds the entity of its name below that skeleton. When a name appears twice, as `hand` does under both arms, the parents' names decide. A joint with no match keeps its entity and is named. This works for 3D skins too, for example a jacket bound to a body.+## Animate itSelect the character and key its bones in the [Sequencer](/docs/animation/timeline/) like any other entity. A bone is named by its path under the root, such as `hips/spine/arm`. A deform is a weight on the `MeshMorph` component, which keys the same way.diff --git a/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdx b/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdxindex cedf95668..08674f9ec 100644--- a/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdx+++ b/docs/astro/src/content/docs/zh-cn/animation/rig-2d.mdx@@ -26,12 +26,29 @@ import { Aside } from '@astrojs/starlight/components';| **权重** | **按距离** 先绑定最近的骨骼,再刷它弄错的地方:在右侧选一根骨骼后拖动。`Shift` 反向,`Ctrl` 平滑,`[` 和 `]` 调半径。**整个部件跟选中骨骼** 用于不弯的部件。 || **变形** | **新建形状**,然后拖动把顶点推过去:呼吸、微笑、鼓起。 |-**试摆** 可以转动骨骼,看权重是否合适。它不改骨骼文件,回到 **绑定姿势** 就复原。**放入场景** 会保存并实例化 prefab。再次保存时所有实例都会更新,实例上后加的内容会保留。+**试摆** 可以转动骨骼,看权重是否合适。它不改骨骼文件,回到 **绑定姿势** 就复原。**放入场景** 会保存并实例化 prefab。再次保存时,打开的场景里所有实例都会更新,实例上后加的内容会保留;如果场景有未保存的修改,实例会在下次打开场景时更新。<Aside type="note">这一版不支持单独增删顶点,一个角色只能用一张图。重新生成部件网格会清掉这个部件的权重和变形,操作前会提醒。</Aside>+## 绑定之后重新绑定++角色不会锁死在最初刷权重的那套骨骼上。++- **挪骨骼。** 在 **绑定姿势** 下拖动骨骼或改长度、旋转,改的就是绑定姿势本身。图不会动,所以放错的骨骼直接挪就行。+- **换父骨骼。** 在 **骨骼** 模式里给选中的骨骼选 **父骨骼**,或者选 **无(根骨骼)**。它在图上的位置不变,下面的骨骼也不变。+- **改名、删除。** 删除骨骼时,它的子骨骼和顶点交给父骨骼。+- **重算权重。** 再点一次 **按距离**,或 **整个部件跟选中骨骼**,然后再刷。+- **换成另一个骨骼文件的骨架。** 在 **骨架** 下选另一个 `.esrig`,点 **换绑到这套骨架**。骨骼按名字对应;没有同名骨骼的顶点交给最近的同名父骨骼。用同一套骨架的角色骨骼名和路径都一样,可以共用动画。++保存时,依赖旧名字的东西会跟着更新:++- 用路径引用了改名或换父骨骼的动画(`.estimeline`)和 Animator 层遮罩(`.esanimator`)会被改写。一个文件里大部分路径都是这个角色的骨骼,才算这个角色的。指向已删除骨骼的轨道保留原路径,保存时会提示有几条。+- 每根骨骼有一个固定 id,prefab 里的实体就按它命名。所以场景里加在某根骨骼上的东西(`IK2D`、挂在手上的剑),在别处重排、换父或删除骨骼之后仍然留在这根骨骼上。++**在场景里**,选中带 `MeshSkin` 的实体,在 Details 里用 **换绑到**:选场景里的另一套骨架,点 **按名字换绑关节**。每个关节在那套骨架下找同名实体;同一个名字出现两次时(比如两只胳膊下都有 `hand`),按父级的名字区分。找不到的关节保持原样,并列出名字。3D 蒙皮同样适用,比如把一件外套绑到身体上。+## 做动画选中角色,在[时间线](/docs/zh-cn/animation/timeline/)里像其他实体一样给骨骼打关键帧。骨骼按它在根下面的路径命名,比如 `hips/spine/arm`。变形是 `MeshMorph` 组件上的权重,打关键帧的方式相同。diff --git a/sdk/etc/rig2d.api.md b/sdk/etc/rig2d.api.mdindex e472a41a1..520f907a6 100644--- a/sdk/etc/rig2d.api.md+++ b/sdk/etc/rig2d.api.md@@ -1,7 +1,7 @@# API surface — esengine/rig2d<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 43 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 53 experimental · 0 deprecated## Bone2D — const @experimental```@@ -92,6 +92,7 @@ static prototype: Rig2DPlugin## RigBone — interface @experimental```+id: string | undefinedlength: numbername: stringparent: number@@ -131,6 +132,19 @@ x: numbery: number```+## RigPathChanges — interface @experimental+```+before: Set<string>+removed: string[]+renamed: Map<string, string>+```++## RigRebindReport — interface @experimental+```+matched: string[]+moved: { from: string; to: string; }[]+```+## RigSource — interface @experimental```bones: RigBone[]@@ -199,6 +213,11 @@ root: number(texture: string, textureWidth: number, textureHeight: number, unitsPerPixel?: number): RigSource```+## ensureRigBoneIds — function @experimental+```+(rig: RigSource): void+```+## findRigParts — function @experimental```(image: RigImage, opts?: { threshold?: number; minArea?: number; }): { x: number; y: number; w: number; h: number; }[]@@ -224,11 +243,31 @@ root: number(rig: RigSource, deformIndex: number, x: number, y: number, radius: number, dx: number, dy: number): number```+## rebindRigToSkeleton — function @experimental+```+(rig: RigSource, skeleton: readonly RigBone[]): RigRebindReport+```++## remapRigPath — function @experimental+```+(path: string, changes: RigPathChanges): string | null+```+## removeRigBone — function @experimental```(rig: RigSource, index: number): void```+## rigBoneId — function @experimental+```+(bones: readonly RigBone[], index: number): string+```++## rigBonePaths — function @experimental+```+(bones: readonly RigBone[]): string[]+```+## rigBoneWorlds — function @experimental```(bones: readonly RigBone[], rotations?: ArrayLike<number>): RigBoneWorld[]@@ -239,6 +278,16 @@ root: number(width: number, height: number, rgba: ArrayLike<number>): RigImage```+## rigParentProblem — function @experimental+```+(rig: RigSource, index: number, parent: number): string | null+```++## rigPathChanges — function @experimental+```+(before: readonly RigBone[], after: readonly RigBone[]): RigPathChanges+```+## rigPrefab — function @experimental```(rig: RigSource, name: string, mesh: string, texture: string): { version: string; name: string; rootEntityId: string; entities: Record<string, unknown>[]; }@@ -254,6 +303,11 @@ root: number(rig: RigSource): string```+## setRigBoneParent — function @experimental+```+(rig: RigSource, index: number, parent: number): number+```+## skinRigPart — function @experimental```(rig: RigSource, partIndex: number, posed: readonly RigBoneWorld[], deformWeights?: ArrayLike<number>): Float32Arraydiff --git a/sdk/src/rig2d/index.ts b/sdk/src/rig2d/index.tsindex 9cf7e9743..aee51a86e 100644--- a/sdk/src/rig2d/index.ts+++ b/sdk/src/rig2d/index.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport {- RIG_SOURCE_VERSION, RIG_SOURCE_EXT, RIG_MAX_INFLUENCES, createRig, checkRig, parseRig, serializeRig, rigBoneWorlds, removeRigBone,+ RIG_SOURCE_VERSION, RIG_SOURCE_EXT, RIG_MAX_INFLUENCES, createRig, checkRig, parseRig, serializeRig, rigBoneWorlds, removeRigBone, rigBoneId, ensureRigBoneIds,type RigSource, type RigBone, type RigPart, type RigDeform, type RigBoneWorld,} from './rigSource';export {@@ -9,6 +9,10 @@ export {type RigImage, type RigWeightDab,} from './rigMesh';export { bakeRig, skinRigPart } from './rigBake';+export {+ rigBonePaths, rigParentProblem, setRigBoneParent, rebindRigToSkeleton, rigPathChanges, remapRigPath,+ type RigRebindReport, type RigPathChanges,+} from './rigRebind';export { solveChain2D, chainTip, clampAngle, type ChainBone, type ChainSolveOptions } from './solve2d';export {Bone2D, IK2D, BoneConstraint2D, BoneConstraintKind, Rig2DPlugin,diff --git a/sdk/src/rig2d/rigRebind.ts b/sdk/src/rig2d/rigRebind.tsnew file mode 100644index 000000000..06401a812--- /dev/null+++ b/sdk/src/rig2d/rigRebind.ts@@ -0,0 +1,181 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file rigRebind.ts+ * @brief Changing which bone is which after a rig is bound: a new parent, a whole skeleton from another rig, and what the paths a clip names become.+ *+ * @details A bone has three names. Its index is what a vertex follows and what joint of the mesh it is, and it moves whenever the list is+ * reordered. Its path (`upper/lower`) is what a clip names it by, and it moves when it or a bone above it is renamed or reparented.+ * Its `id` never moves: it is what the prefab names the bone's entity by, so what a scene added to one bone (an IK2D, a sword) stays+ * on that bone through every edit here. Every function in this file keeps vertices where they are in rig space: rebinding+ * changes what follows what, never what the character looks like at rest.+ */+import { ensureRigBoneIds, rigBoneId, rigBoneWorlds, type RigBone, type RigSource } from './rigSource';++/** Each bone's path, as a clip names it below the rig's root. @experimental */+export function rigBonePaths(bones: readonly RigBone[]): string[] {+ const out: string[] = [];+ bones.forEach((b, i) => { out[i] = b.parent >= 0 && b.parent < i ? `${out[b.parent]}/${b.name}` : b.name; });+ return out;+}++/** Whether `bone` is `ancestor` or below it. */+function isUnder(bones: readonly RigBone[], bone: number, ancestor: number): boolean {+ for (let at = bone; at >= 0; at = bones[at]!.parent) if (at === ancestor) return true;+ return false;+}++/** Reorders bones so every parent comes first, keeping the order otherwise; `order[newIndex] = oldIndex`. */+function parentsFirst(bones: readonly RigBone[]): number[] {+ const order: number[] = [], placed = new Set<number>();+ const place = (i: number): void => {+ if (placed.has(i)) return;+ const parent = bones[i]!.parent;+ if (parent >= 0) place(parent);+ placed.add(i);+ order.push(i);+ };+ bones.forEach((_, i) => place(i));+ return order;+}++/** Puts the bones in `order` (`order[newIndex] = oldIndex`), carrying parents and every vertex's weights along. */+function reorderBones(rig: RigSource, order: readonly number[]): void {+ const newIndexOf = new Map(order.map((old, i) => [old, i]));+ const at = (old: number): number => newIndexOf.get(old)!;+ rig.bones = order.map((old) => {+ const b = rig.bones[old]!;+ return { ...b, parent: b.parent >= 0 ? at(b.parent) : -1 };+ });+ for (const part of rig.parts) {+ part.weights = part.weights.map((w) => w.map((v, i) => (i % 2 === 0 ? at(v) : v)));+ }+}++/** Why a bone cannot take this parent, or null when it can. @experimental */+export function rigParentProblem(rig: RigSource, index: number, parent: number): string | null {+ if (!rig.bones[index]) return 'there is no such bone';+ if (parent < -1 || parent >= rig.bones.length) return 'there is no such parent';+ if (parent >= 0 && isUnder(rig.bones, parent, index)) return parent === index ? 'a bone cannot be its own parent' : 'that bone hangs below this one';+ return null;+}++/**+ * Hangs a bone (and everything below it) off another, or makes it a root with -1, where it stands now: its place and rotation are+ * re-expressed in the new parent's space, so nothing moves at rest. The list is reordered when the new parent came after it, and the+ * weights with it; ids stay, so the scene keeps what it added to each bone. Returns the bone's index afterwards.+ * Throws on a parent {@link rigParentProblem} refuses.+ * @experimental+ */+export function setRigBoneParent(rig: RigSource, index: number, parent: number): number {+ const problem = rigParentProblem(rig, index, parent);+ if (problem) throw new Error(`cannot reparent: ${problem}`);+ ensureRigBoneIds(rig);+ const bone = rig.bones[index]!;+ if (bone.parent === parent) return index;+ const worlds = rigBoneWorlds(rig.bones), w = worlds[index]!;+ const up = parent >= 0 ? worlds[parent]! : { x: 0, y: 0, rotation: 0 };+ const c = Math.cos(up.rotation), s = Math.sin(up.rotation), dx = w.x - up.x, dy = w.y - up.y;+ bone.x = c * dx + s * dy;+ bone.y = -s * dx + c * dy;+ bone.rotation = w.rotation - up.rotation;+ bone.parent = parent;+ const id = bone.id!;+ reorderBones(rig, parentsFirst(rig.bones));+ return rig.bones.findIndex(b => b.id === id);+}++/** What {@link rebindRigToSkeleton} did, bone by bone of the rig as it was. @experimental */+export interface RigRebindReport {+ /** Old bone names that found a bone of the same name. */+ matched: string[];+ /** Old bone names that did not, and the new bone their vertices went to. */+ moved: { from: string; to: string }[];+}++/**+ * Binds the rig to another skeleton, a list of bones as a `.esrig` holds them, matched by name. The rig's bones become a copy of+ * `skeleton`, ids included, so two rigs bound to one skeleton have entities of the same ids and names and play the same clips.+ * A vertex keeps its weights on every bone that found its namesake. A bone that did not hands them to its nearest ancestor that did,+ * or, with none, to the new bone whose head is closest to its own. Vertices stay where they are in rig space; what moves is the bind+ * pose, so the skin rests where it did against whatever pose the new skeleton rests in.+ * @experimental+ */+export function rebindRigToSkeleton(rig: RigSource, skeleton: readonly RigBone[]): RigRebindReport {+ if (skeleton.length === 0) throw new Error('cannot rebind: the skeleton has no bones');+ const next = skeleton.map(b => ({ ...b }));+ const nextRig: RigSource = { ...rig, bones: next, parts: [] };+ ensureRigBoneIds(nextRig);+ const byName = new Map(next.map((b, i) => [b.name, i]));+ const oldWorlds = rigBoneWorlds(rig.bones), newWorlds = rigBoneWorlds(next);+ const report: RigRebindReport = { matched: [], moved: [] };+ const target = rig.bones.map((b, i) => {+ const same = byName.get(b.name);+ if (same !== undefined) { report.matched.push(b.name); return same; }+ let to = -1;+ for (let up = b.parent; up >= 0 && to < 0; up = rig.bones[up]!.parent) to = byName.get(rig.bones[up]!.name) ?? -1;+ if (to < 0) {+ const at = oldWorlds[i]!;+ let best = Infinity;+ newWorlds.forEach((w, j) => {+ const d = Math.hypot(w.x - at.x, w.y - at.y);+ if (d < best) { best = d; to = j; }+ });+ }+ report.moved.push({ from: b.name, to: next[to]!.name });+ return to;+ });+ for (const part of rig.parts) {+ part.weights = part.weights.map((w) => {+ const merged = new Map<number, number>();+ for (let i = 0; i < w.length; i += 2) {+ const bone = target[w[i]!]!;+ merged.set(bone, (merged.get(bone) ?? 0) + w[i + 1]!);+ }+ return [...merged].flat();+ });+ }+ rig.bones = next;+ return report;+}++/** How the paths a clip names changed between two saves of one rig, by bone id. @experimental */+export interface RigPathChanges {+ /** Old path to new, for every bone still there whose path is not what it was. */+ renamed: Map<string, string>;+ /** Paths of bones that are gone. */+ removed: string[];+ /** Every path the rig had before: what a clip must name to be one of this rig's. */+ before: Set<string>;+}++/** Compares two saves of a rig. Bones without ids are matched by index, which is what they were saved as. @experimental */+export function rigPathChanges(before: readonly RigBone[], after: readonly RigBone[]): RigPathChanges {+ const oldPaths = rigBonePaths(before), newPaths = rigBonePaths(after);+ const newById = new Map(after.map((_, i) => [rigBoneId(after, i), newPaths[i]!]));+ const renamed = new Map<string, string>(), removed: string[] = [];+ before.forEach((_, i) => {+ const now = newById.get(rigBoneId(before, i));+ if (now === undefined) removed.push(oldPaths[i]!);+ else if (now !== oldPaths[i]) renamed.set(oldPaths[i]!, now);+ });+ return { renamed, removed, before: new Set(oldPaths) };+}++/**+ * Where a path named before the change points now. A path below a bone (a sword parented to `arm` in the scene, `arm/sword`) follows the+ * deepest bone it starts with. Null when that bone is gone; the path itself when nothing it starts with changed.+ * @experimental+ */+export function remapRigPath(path: string, changes: RigPathChanges): string | null {+ if (!path) return path;+ const parts = path.split('/');+ for (let n = parts.length; n > 0; n--) {+ const head = parts.slice(0, n).join('/');+ if (!changes.before.has(head)) continue;+ if (changes.removed.includes(head)) return null;+ const now = changes.renamed.get(head);+ return now === undefined ? path : [now, ...parts.slice(n)].join('/');+ }+ return path;+}diff --git a/sdk/src/rig2d/rigSource.ts b/sdk/src/rig2d/rigSource.tsindex bdd897799..9e8889755 100644--- a/sdk/src/rig2d/rigSource.ts+++ b/sdk/src/rig2d/rigSource.ts@@ -27,6 +27,11 @@ export interface RigBone {rotation: number;/** How far it reaches along its own +x. Draws the bone, aims an IK chain, and shapes automatic weights. */length: number;+ /**+ * What the prefab names this bone's entity by, so what a scene adds to it stays on it when bones are reordered, removed or reparented.+ * Missing on a rig saved before there were ids, which is read as `b<index>`, the name those prefabs used. See {@link ensureRigBoneIds}.+ */+ id?: string;}/** @experimental */@@ -82,11 +87,14 @@ export function checkRig(rig: RigSource): string[] {if (!(rig.textureWidth > 0) || !(rig.textureHeight > 0)) out.push('the image size is missing');if (!(rig.unitsPerPixel > 0)) out.push('unitsPerPixel must be above 0');if (!Array.isArray(rig.bones) || !Array.isArray(rig.parts) || !Array.isArray(rig.deforms)) return [...out, 'bones, parts and deforms must be lists'];- const boneNames = new Set<string>();+ const boneNames = new Set<string>(), boneIds = new Set<string>();rig.bones.forEach((b, i) => {if (typeof b?.name !== 'string' || b.name === '') out.push(`bone ${i} has no name`);else if (boneNames.has(b.name)) out.push(`two bones are called "${b.name}": a clip names a bone by its path, so the second could not be reached`);else boneNames.add(b.name);+ if (b?.id !== undefined && (typeof b.id !== 'string' || b.id === '')) out.push(`bone "${b?.name}" has a bad id`);+ else if (b?.id !== undefined && boneIds.has(b.id)) out.push(`two bones have the id "${b.id}": a scene could not tell their entities apart`);+ else if (b?.id !== undefined) boneIds.add(b.id);if (!Number.isInteger(b?.parent) || b.parent < -1 || b.parent >= i) out.push(`bone "${b?.name}" must name a parent earlier in the list`);if (![b?.x, b?.y, b?.rotation, b?.length].every(finite) || b.length < 0) out.push(`bone "${b?.name}" has a bad position, rotation or length`);});@@ -134,6 +142,32 @@ export function serializeRig(rig: RigSource): string {return `${JSON.stringify(rig, (_key, value) => (typeof value === 'number' && !Number.isInteger(value) ? Number(value.toFixed(5)) : value), 2)}\n`;}+const ID_PATTERN = /^b(\d+)$/;++/** The id the prefab names bone `index`'s entity by. A bone with none is named by its index, which is what every rig saved before ids had. @experimental */+export function rigBoneId(bones: readonly RigBone[], index: number): string {+ return bones[index]?.id ?? `b${index}`;+}++/**+ * Gives every bone without an id one, without reusing one already given: a scene may still hold what it added to a removed bone's entity,+ * and a new bone must not inherit it. Call before anything reorders the list.+ * @experimental+ */+export function ensureRigBoneIds(rig: RigSource): void {+ // A rig with no ids yet is one saved before them: its bones keep the names its prefab already gave their entities.+ if (rig.bones.every(b => !b.id)) { rig.bones.forEach((b, i) => { b.id = `b${i}`; }); return; }+ let next = rig.bones.length;+ for (const b of rig.bones) next = Math.max(next, Number(ID_PATTERN.exec(b.id ?? '')?.[1] ?? -1) + 1);+ const used = new Set(rig.bones.flatMap(b => (b.id ? [b.id] : [])));+ for (const b of rig.bones) {+ if (b.id) continue;+ while (used.has(`b${next}`)) next++;+ b.id = `b${next++}`;+ used.add(b.id);+ }+}+/** A bone's place in rig space. @experimental */export interface RigBoneWorld { x: number; y: number; rotation: number }@@ -152,6 +186,8 @@ export function rigBoneWorlds(bones: readonly RigBone[], rotations?: ArrayLike<n/** Takes a bone out, giving its children to its parent where they stand, and its vertices to its parent or nearest survivor. @experimental */export function removeRigBone(rig: RigSource, index: number): void {+ // The survivors move up the list, so they need names that do not.+ ensureRigBoneIds(rig);const worlds = rigBoneWorlds(rig.bones), gone = rig.bones[index];if (!gone) return;const heir = gone.parent >= 0 ? gone.parent : -1;diff --git a/sdk/src/rig2d/spawnRig.ts b/sdk/src/rig2d/spawnRig.tsindex d00a119b9..4288b0fa7 100644--- a/sdk/src/rig2d/spawnRig.ts+++ b/sdk/src/rig2d/spawnRig.ts@@ -9,7 +9,7 @@ import { PREFAB_FORMAT_VERSION } from '../prefab/migrate';import type { World } from '../ecs/world';import type { Entity } from '../types';import { Bone2D } from './rig2dPlugin';-import type { RigSource } from './rigSource';+import { rigBoneId, type RigSource } from './rigSource';/** @experimental */export interface SpawnedRig {@@ -46,7 +46,8 @@ export function spawnRig(world: World, rig: RigSource, opts: { mesh: number; tex* @experimental*/export function rigPrefab(rig: RigSource, name: string, mesh: string, texture: string): { version: string; name: string; rootEntityId: string; entities: Record<string, unknown>[] } {- const idOf = (i: number): string => `b${i}`;+ // By id, not index: what a scene added to a bone's entity has to stay on that bone when the rig's list is reordered.+ const idOf = (i: number): string => rigBoneId(rig.bones, i);const children = (parent: number): string[] => rig.bones.flatMap((b, i) => (b.parent === parent ? [idOf(i)] : []));const entities: Record<string, unknown>[] = [{prefabEntityId: 'root', name, parent: null, children: children(-1), visible: true,diff --git a/sdk/tests/rig2d.test.ts b/sdk/tests/rig2d.test.tsindex bc66c278b..5ae33348d 100644--- a/sdk/tests/rig2d.test.ts+++ b/sdk/tests/rig2d.test.ts@@ -5,7 +5,8 @@ import { decodeMesh, encodeMesh, MeshChannel } from '../src/asset/meshFormat';import {autoWeightPart, bakeRig, bindPartToBone, chainTip, checkRig, clampAngle, coverRigPart, createRig, findRigParts, paintPartWeights, parseRig,partWeightsOf, pushRigDeform, removeRigBone, rigBoneWorlds, rigImageFromRGBA, rigVertex, serializeRig, skinRigPart, solveChain2D,- type ChainBone, type RigPart, type RigSource,+ ensureRigBoneIds, rebindRigToSkeleton, remapRigPath, rigBoneId, rigBonePaths, rigParentProblem, rigPathChanges, rigPrefab, setRigBoneParent,+ type ChainBone, type RigBone, type RigPart, type RigSource,} from '../src/rig2d/index';const solidImage = (w: number, h: number, drawn: (x: number, y: number) => boolean) => ({ width: w, height: h, alpha: (x: number, y: number) => (drawn(x, y) ? 255 : 0) });@@ -317,3 +318,118 @@ describe('chain solving', () => {expect(clampAngle(5, undefined, undefined)).toBe(5);});});++describe('rebinding', () => {+ /** a -> b -> c along +x, and d a second root, each vertex on one bone. */+ function chain(): RigSource {+ const rig = createRig('x.png', 10, 10);+ rig.bones.push(+ { name: 'a', parent: -1, x: 0, y: 0, rotation: 0.3, length: 10 },+ { name: 'b', parent: 0, x: 10, y: 0, rotation: 0.4, length: 10 },+ { name: 'c', parent: 1, x: 10, y: 0, rotation: -0.2, length: 10 },+ { name: 'd', parent: -1, x: 5, y: 20, rotation: 1, length: 10 },+ );+ rig.parts.push({ name: 'p', rect: { x: 0, y: 0, w: 1, h: 1 }, x: 0, y: 0, vertices: [0, 0, 1, 0, 2, 0, 3, 0], triangles: [], weights: [[0, 1], [1, 1], [2, 1], [3, 1]] });+ return rig;+ }+ const worldsByName = (rig: RigSource) => new Map(rigBoneWorlds(rig.bones).map((w, i) => [rig.bones[i]!.name, w]));++ it("gives an old rig's bones the ids its prefab already used, and a new bone one nobody had", () => {+ const rig = chain();+ ensureRigBoneIds(rig);+ expect(rig.bones.map(b => b.id)).toEqual(['b0', 'b1', 'b2', 'b3']);+ removeRigBone(rig, 3);+ rig.bones.push({ name: 'e', parent: -1, x: 0, y: 0, rotation: 0, length: 1 });+ ensureRigBoneIds(rig);+ expect(rig.bones[3]!.id).not.toBe('b3');+ removeRigBone(rig, 1);+ rig.bones.push({ name: 'f', parent: -1, x: 0, y: 0, rotation: 0, length: 1 });+ ensureRigBoneIds(rig);+ expect(new Set(rig.bones.map(b => b.id)).size).toBe(rig.bones.length);+ expect(checkRig(rig)).toEqual([]);+ });++ it("names a bone's prefab entity by its id, so a reorder leaves a scene's additions on the same bone", () => {+ const rig = chain();+ ensureRigBoneIds(rig);+ const before = rigPrefab(rig, 'R', 'm', 't').entities.find(e => e.name === 'd')!.prefabEntityId;+ setRigBoneParent(rig, 0, 3);+ const prefab = rigPrefab(rig, 'R', 'm', 't');+ expect(prefab.entities.find(e => e.name === 'd')!.prefabEntityId).toBe(before);+ expect(prefab.entities.find(e => e.name === 'a')!.parent).toBe(before);+ });++ it("refuses two bones of one id, and a parent below the bone", () => {+ const rig = chain();+ ensureRigBoneIds(rig);+ rig.bones[1]!.id = 'b0';+ expect(checkRig(rig).join(' ')).toMatch(/id "b0"/);+ expect(rigParentProblem(chain(), 0, 2)).toMatch(/below/);+ expect(rigParentProblem(chain(), 1, 1)).toMatch(/own parent/);+ expect(() => setRigBoneParent(chain(), 0, 2)).toThrow(/below/);+ });++ it("reparents where the bone stands, reordering the list and the weights with it", () => {+ const rig = chain();+ const before = worldsByName(rig);+ const index = setRigBoneParent(rig, 0, 3);+ expect(rig.bones.map(b => b.name)).toEqual(['d', 'a', 'b', 'c']);+ expect(index).toBe(1);+ expect(rig.bones[1]!.parent).toBe(0);+ for (const [name, w] of worldsByName(rig)) {+ expect(w.x).toBeCloseTo(before.get(name)!.x); expect(w.y).toBeCloseTo(before.get(name)!.y); expect(w.rotation).toBeCloseTo(before.get(name)!.rotation);+ }+ // Each vertex still follows the bone of the same name.+ expect(rig.parts[0]!.weights.map(w => rig.bones[w[0]!]!.name)).toEqual(['a', 'b', 'c', 'd']);+ expect(checkRig(rig)).toEqual([]);+ expect(() => bakeRig(rig)).not.toThrow();+ });++ it("makes a bone a root where it stands", () => {+ const rig = chain();+ const before = worldsByName(rig).get('c')!;+ setRigBoneParent(rig, 2, -1);+ const after = worldsByName(rig).get('c')!;+ expect(after.x).toBeCloseTo(before.x); expect(after.y).toBeCloseTo(before.y); expect(after.rotation).toBeCloseTo(before.rotation);+ expect(rigBonePaths(rig.bones)).toContain('c');+ });++ it("binds to another skeleton by name, giving an unmatched bone's vertices to its nearest matched ancestor", () => {+ const rig = chain();+ const skeleton: RigBone[] = [+ { name: 'root', parent: -1, x: 0, y: 0, rotation: 0, length: 1, id: 'r' },+ { name: 'a', parent: 0, x: 0, y: 0, rotation: 0, length: 12, id: 'ka' },+ { name: 'b', parent: 1, x: 12, y: 0, rotation: 0, length: 12, id: 'kb' },+ ];+ const vertsBefore = JSON.stringify(rig.parts[0]!.vertices);+ const report = rebindRigToSkeleton(rig, skeleton);+ expect(rig.bones.map(b => b.id)).toEqual(['r', 'ka', 'kb']);+ expect(report.matched).toEqual(['a', 'b']);+ expect(report.moved).toEqual([{ from: 'c', to: 'b' }, { from: 'd', to: expect.any(String) }]);+ expect(rig.parts[0]!.weights.slice(0, 3).map(w => rig.bones[w[0]!]!.name)).toEqual(['a', 'b', 'b']);+ expect(JSON.stringify(rig.parts[0]!.vertices)).toBe(vertsBefore);+ expect(checkRig(rig)).toEqual([]);+ // The skeleton handed in is not changed by the rig that took it.+ expect(skeleton[1]!.length).toBe(12);+ });++ it("tells a clip's paths what they became: renamed, reparented, below a bone, and gone", () => {+ const before = chain().bones;+ ensureRigBoneIds({ bones: before } as RigSource);+ const rig = chain();+ rig.bones.forEach((b, i) => { b.id = before[i]!.id; });+ rig.bones[1]!.name = 'mid';+ setRigBoneParent(rig, 3, 0);+ removeRigBone(rig, rig.bones.findIndex(b => b.name === 'c'));+ const changes = rigPathChanges(before, rig.bones);+ expect(remapRigPath('a', changes)).toBe('a');+ expect(remapRigPath('a/b', changes)).toBe('a/mid');+ expect(remapRigPath('d', changes)).toBe('a/d');+ expect(remapRigPath('a/b/sword', changes)).toBe('a/mid/sword');+ expect(remapRigPath('a/b/c', changes)).toBeNull();+ expect(remapRigPath('a/b/c/tip', changes)).toBeNull();+ expect(remapRigPath('elsewhere', changes)).toBe('elsewhere');+ expect(remapRigPath('', changes)).toBe('');+ expect(rigBoneId(rig.bones, 0)).toBe('b0');+ });+});