fix(web): robot rig places bones on the URDF chain and keeps bound worlds
Some checks failed
M6 deployable RC / quick (push) Has been cancelled
M6 deployable RC / chromium (push) Has been cancelled
M6 deployable RC / release (push) Has been cancelled

The rig step placed every bone at its parent-link-relative URDF offset and
the engine's keep_transform world recursion treated already-bound ancestors
as plain PAROBJECT, so binding in chain order dropped the ancestor bone
matrix and every link jumped on the rig click (deltas up to 1.26).

- set_parent: refresh the pose before computing the world and compose
  PARBONE ancestors like BKE_object_calc_parent/ob_parbone.
- robot-workflow rig: accumulate URDF joint frames from rootLink (fixed
  joints included) and place head/axis on the real joint position.
- robot-rig-web now asserts zero world drift, bone pivots on the URDF
  joints, bone Y on the joint axes, joint_3 rotation moving only its
  subtree about the true axis, and 恢复零位 restoring every link.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
mes123456
2026-11-29 19:20:27 +08:00
parent 8f08c1bda9
commit 013ea78a45
7 changed files with 133 additions and 40 deletions

View File

@@ -17746,21 +17746,6 @@ bool web_engine_blend_main_set_parent(WebBlendMainState *state, const char *obje
Object *object = find_object(state, object_id);
Object *parent = parent_id == nullptr || parent_id[0] == '\0' ? nullptr : find_object(state, parent_id);
const bool bone_parent = parent != nullptr && parent_bone != nullptr && parent_bone[0] != '\0';
float world[4][4];
const auto calculate_world = [&](const Object *value, auto &&self, float result[4][4]) -> void {
float local[4][4];
BKE_object_to_mat4(value, local);
if (value->parent == nullptr) {
copy_m4_m4(result, local);
return;
}
float parent_world[4][4];
float parent_with_inverse[4][4];
self(value->parent, self, parent_world);
mul_m4_m4m4(parent_with_inverse, parent_world, value->parentinv);
mul_m4_m4m4(result, parent_with_inverse, local);
};
calculate_world(object, calculate_world, world);
bPoseChannel *bone_channel = nullptr;
if (bone_parent) {
/* pose_mat only tracks writes after an evaluation, so refresh before bind. */
@@ -17772,6 +17757,34 @@ bool web_engine_blend_main_set_parent(WebBlendMainState *state, const char *obje
return false;
}
}
float world[4][4];
const auto calculate_world = [&](const Object *value, auto &&self, float result[4][4]) -> void {
float local[4][4];
BKE_object_to_mat4(value, local);
if (value->parent == nullptr) {
copy_m4_m4(result, local);
return;
}
float parent_world[4][4];
float parent_with_inverse[4][4];
self(value->parent, self, parent_world);
/* Ancestors may already be bone-parented (robot links bind in chain order);
* mirror BKE_object_get_parent_matrix/ob_parbone instead of plain PAROBJECT. */
if (value->partype == PARBONE && value->parent->pose != nullptr) {
if (const bPoseChannel *ancestor_channel = BKE_pose_channel_find_name(value->parent->pose, value->parsubstr)) {
float bone[4][4];
copy_m4_m4(bone, ancestor_channel->pose_mat);
float tail[3];
sub_v3_v3v3(tail, ancestor_channel->pose_tail, ancestor_channel->pose_head);
mul_v3_fl(tail, value->parent_bone_head_tail_factor);
add_v3_v3(bone[3], tail);
mul_m4_m4m4(parent_world, parent_world, bone);
}
}
mul_m4_m4m4(parent_with_inverse, parent_world, value->parentinv);
mul_m4_m4m4(result, parent_with_inverse, local);
};
calculate_world(object, calculate_world, world);
const auto parent_world_matrix = [&](float result[4][4]) -> void {
float armature_world[4][4];
calculate_world(parent, calculate_world, armature_world);

View File

@@ -27,6 +27,7 @@ node tools/web/check-armature-robot-headed.mjs --dir /abs/tests/golden/ARMATURE-
| `robot-sample-web` | 六轴机器人工具 → 加载 ABB IRB120 样例 | provenance/URDF 哈希一致,零件导入后各 link 挂在根对象下 |
| `robot-assemble-check-web` | 建立 URDF 层级 → 六轴检查 | 真实父子链与六轴检查通过 |
| `robot-pose-web` | joint_1 30° → 应用关节角度 → 恢复零位 | link_1 world 变化、复位还原 |
| `robot-rig-web` | 建立骨架 → joint_3 30° → 恢复零位 | 6 骨骼与 6 转动关节一一对应;绑定前后 link 世界矩阵零漂移(<1e-5);骨骼 pivot = URDF 链累积关节位置、骨 Y = 关节轴;joint_3 旋转只带动 link_3 子树、关节 pivot 不平移、joint_5 绕关节轴等半径圆周运动;恢复零位还原 |
| `armature-bones-web` | 引擎命令 `setArmatureBones` | Root/Child 骨链、rest/pose 通道读回 |
| `armature-bind-web` | `setParent` + `parentType:"BONE"` | 刚性绑定后 world 不变;未知骨名返回 `PARENT_BONE_INVALID` |
| `armature-pose-web` | `setPoseBoneTransform` | poseMatrix/子物体 world 变化、重复写入幂等、归零复原 |
@@ -58,6 +59,13 @@ node tools/web/check-armature-robot-headed.mjs --dir /abs/tests/golden/ARMATURE-
绑定语义镜像桌面 `ob_parbone`:`pose_mat` 的 Y 列 × 骨长 × `parent_bone_head_tail_factor`(DNA 默认 1.0),
`partype = PARBONE`,`parsubstr = <骨名>`;world = 骨架对象 world × 骨骼矩阵 × `parentinv` × basis。
骨骼放置按 URDF 链累积(`robot-workflow.py`):从 `rootLink` 单位阵起,逐关节
`frames[child] = frames[parent] @ origin(joint)`(含 fixed 关节),转动关节骨骼的 head = 该关节累积原点,
tail = head + (帧旋转 @ 关节轴) × 0.12(骨 Y 即关节轴)。IRB120 实测 pivot:
J1 (0,0,0)、J2 (0,0,0.29)、J3 (0,0,0.56)、J4 (0,0,0.63)、J5 (0.302,0,0.63)、J6 (0.374,0,0.63),
与各子 link 绑定前的世界平移一致。引擎 `setParent(BONE, keepTransform)` 递归时对已绑定的祖先按
PARBONE 组合骨骼矩阵(镜像 `BKE_object_calc_parent`),因此按链序绑定不会丢祖先骨骼矩阵。
## 约束
- 全部落盘走 OPFS;禁用 IDBFS/IndexedDB;测试产物不写入 OPFS。
@@ -66,11 +74,15 @@ node tools/web/check-armature-robot-headed.mjs --dir /abs/tests/golden/ARMATURE-
## 残余
- rig 阶段骨骼父级的世界保持偏差:绑定后各 link 的世界矩阵与绑定前不一致(`robot-rig-web` 证据
`residuals.worldPreservation.deltas`,最大约 1.26)。按用户指示归入机器人逆解一并处理;该用例当前
只判定 URDF 层级与装配绑定关系(6 骨骼对应 6 个转动关节、每个 link 绑定到自己的关节骨骼、无产品控制台错误)。
- 机器人工具动作「建立骨架(6 骨骼 + 刚性绑定)」已落地:Python 只建骨架与 6 根骨骼,刚性绑定经引擎
`setParent(BONE, keepTransform)` 完成,与 `armature-bind-web` 共用同一实现。
- rig 阶段骨骼父级的世界保持偏差已修复(原最大值约 1.26):根因是引擎 `set_parent` 的 `keep_transform`
世界递归把已绑定的祖先当作 PAROBJECT,丢掉祖先骨骼矩阵;现按 PARBONE 组合(对齐 `BKE_object_calc_parent`),
绑定前后各 link 世界矩阵零漂移(`robot-rig-web` 证据 `worldDelta`,全部 <1e-5)。
- 关节角度调整只围绕该关节:姿态经骨骼通道(`Quaternion((0,1,0), angle)` 绕骨 Y = 关节轴)写入,
`BKE_pose_where_is` 驱动子骨骼,子 link 经 PARBONE 组合自动跟随;three.js 消费快照世界矩阵。`robot-rig-web`
实测 joint_3 30°:link_1/link_2 不变,link_3..link_6 跟随,joint_3 pivot 不平移,joint_5 沿关节轴等半径
圆周运动,恢复零位全部还原。
- 机器人工具动作「建立骨架(6 骨骼 + 刚性绑定)」已落地:Python 只建骨架与 6 根骨骼(按 URDF 链放置 pivot 与轴向),
刚性绑定经引擎 `setParent(BONE, keepTransform)` 完成,与 `armature-bind-web` 共用同一实现。
- `armature-reopen-web` 已落地:保存走「文件 → 保存到浏览器 OPFS」,重开走「文件 → 最近打开」。
断言前必须等到 worker 的 `openBlend` 成功回复计数增长(证据 `openBlendReplies` 1→2),否则活着的
Main 会直接回答快照、比较恒真;实测重开前 r4 → 重开后 r1,骨骼 / 父级 / 姿态 / 世界矩阵零偏差。

Binary file not shown.

View File

@@ -10,7 +10,7 @@
"single": {
"fileName": "web_engine.wasm",
"url": "/vendor/blender/web_engine.wasm",
"sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56"
"sha256": "f07de0a823848a932ada2c69d9f605f32ad3a1de817c69f65cbb588a870a4e81"
},
"pthread": {
"fileName": "web_engine.wasm",
@@ -27,7 +27,7 @@
"single": {
"fileName": "web_engine.wasm",
"url": "/vendor/blender/web_engine.wasm",
"sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56"
"sha256": "f07de0a823848a932ada2c69d9f605f32ad3a1de817c69f65cbb588a870a4e81"
},
"pthread": {
"fileName": "web_engine.wasm",
@@ -44,7 +44,7 @@
"single": {
"fileName": "web_engine.wasm",
"url": "/vendor/blender/web_engine.wasm",
"sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56"
"sha256": "f07de0a823848a932ada2c69d9f605f32ad3a1de817c69f65cbb588a870a4e81"
},
"pthread": {
"fileName": "web_engine.wasm",
@@ -61,7 +61,7 @@
"single": {
"fileName": "web_engine.wasm",
"url": "/vendor/blender/web_engine.wasm",
"sha256": "f3678ad48723668b2282bdea3227900c918bf0ad9e36abe5f11754cda2ff5c56"
"sha256": "f07de0a823848a932ada2c69d9f605f32ad3a1de817c69f65cbb588a870a4e81"
},
"pthread": {
"fileName": "web_engine.wasm",

View File

@@ -94,12 +94,19 @@ elif action=='rig':
arm.parent=root;arm.matrix_parent_inverse=Matrix.Identity(4);arm.matrix_basis=Matrix.Identity(4)
bpy.context.view_layer.objects.active=arm
bpy.ops.object.mode_set(mode='EDIT')
frames={model['rootLink']:Matrix.Identity(4)};pending=list(model['joints'])
while pending:
progressed=False
for joint in list(pending):
if joint['parent'] in frames:
frames[joint['child']]=frames[joint['parent']]@origin(joint);pending.remove(joint);progressed=True
if not progressed:raise RuntimeError('URDF 关节链不完整')
previous=None;bindings={}
for joint in model['joints']:
if joint['type']=='fixed':continue
head=origin(joint).translation.copy()
frame=frames[joint['child']];head=frame.translation.copy()
bone=armature.edit_bones.new(joint['name'])
bone.head=head;bone.tail=head+Vector(joint['axis']).normalized()*.12
bone.head=head;bone.tail=head+(frame.to_3x3()@Vector(joint['axis']).normalized())*.12
if previous:bone.parent=armature.edit_bones[previous]
previous=joint['name'];bindings[joint['child']]=joint['name']
bpy.ops.object.mode_set(mode='OBJECT')

Binary file not shown.

View File

@@ -227,6 +227,11 @@ test('joint_1 pose moves the link chain and 恢复零位 restores it [robot-pose
* link to it (desktop ob_parbone semantics). The check runs on the engine
* snapshot, never on the tool's own report. */
const EXPECTED_BONES: Record<string, string> = { link_1: 'joint_1', link_2: 'joint_2', link_3: 'joint_3', link_4: 'joint_4', link_5: 'joint_5', link_6: 'joint_6' };
/* URDF joint axes in the sample are expressed in the joint (parent link) frame;
* every joint rpy is zero, so the axis equals the armature-space bone Y. */
const URDF_AXIS: Record<string, number[]> = { joint_1: [0, 0, 1], joint_2: [0, 1, 0], joint_3: [0, 1, 0], joint_4: [1, 0, 0], joint_5: [0, 1, 0], joint_6: [1, 0, 0] };
const translation = (matrix: number[] | null | undefined) => (matrix && matrix.length === 16 ? [matrix[12], matrix[13], matrix[14]] : null);
const matrixMaxDelta = (a: number[] | null | undefined, b: number[] | null | undefined) => (a && b && a.length === b.length ? Math.max(...a.map((value, index) => Math.abs(value - b[index]))) : Number.POSITIVE_INFINITY);
test('establishing the armature binds every link to its joint bone [robot-rig-web]', async ({ page }, testInfo) => {
const errors = consoleCollector(page);
@@ -241,39 +246,95 @@ test('establishing the armature binds every link to its joint bone [robot-rig-we
await expect(dialog).toContainText('骨架已建立(6 骨骼 + 刚性绑定)', { timeout: 180_000 });
const rigged = await readAfterRevision(page, before.revision ?? 0, [ROOT_OBJECT, ...LINKS]);
const bones = (rigged.armatures ?? []).flatMap((armature) => armature.bones).map((bone) => bone.name).sort();
const riggedBones = (rigged.armatures ?? []).flatMap((armature) => armature.bones);
const bones = riggedBones.map((bone) => bone.name).sort();
const boneByName = (list: typeof riggedBones, name: string) => list.find((bone) => bone.name === name) ?? null;
const bound = Object.fromEntries(Object.entries(rigged.nodes ?? {})
.filter(([, node]) => node.parentType === 'BONE')
.map(([name, node]) => [name, node.parentBoneName]));
const worldDelta = Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link,
matrixDistance(before.nodes?.[link]?.worldMatrix ?? null, rigged.nodes?.[link]?.worldMatrix ?? null)]));
/* A bone pivot must sit on the true URDF joint position: the chain-accumulated
* origin of the joint that drives it, which for this sample equals the child
* link's pre-rig world translation. */
const boneHeadDelta = Object.fromEntries(Object.entries(EXPECTED_BONES).map(([link, bone]) => [bone,
matrixMaxDelta(translation(boneByName(riggedBones, bone)?.restMatrix), translation(before.nodes?.[link]?.worldMatrix))]));
const boneAxis = Object.fromEntries(riggedBones.map((bone) => [bone.name,
bone.restMatrix ? [bone.restMatrix[4], bone.restMatrix[5], bone.restMatrix[6]].map((value) => Math.round(value * 1e6) / 1e6) : null]));
const boneAxisDelta = Object.fromEntries(Object.entries(URDF_AXIS).map(([bone, axis]) => [bone,
boneAxis[bone] ? Math.max(...axis.map((value, index) => Math.abs(value - boneAxis[bone]![index]))) : Number.POSITIVE_INFINITY]));
/* 调整关节角度只围绕该关节:pose joint_3 and read the subtree back. */
const rigRevision = rigged.revision ?? 0;
await dialog.getByLabel('joint_3 角度', { exact: true }).fill('30');
await dialog.getByRole('button', { name: '应用关节角度', exact: true }).click();
const posed = await readAfterRevision(page, rigRevision, [ROOT_OBJECT, ...LINKS]);
const posedBones = (posed.armatures ?? []).flatMap((armature) => armature.bones);
const posedDelta = Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link,
matrixDistance(rigged.nodes?.[link]?.worldMatrix ?? null, posed.nodes?.[link]?.worldMatrix ?? null)]));
const joint3Rest = translation(boneByName(riggedBones, 'joint_3')?.restMatrix);
const joint3Posed = translation(boneByName(posedBones, 'joint_3')?.poseMatrix);
const joint5Posed = translation(boneByName(posedBones, 'joint_5')?.poseMatrix);
const joint5Rest = translation(boneByName(riggedBones, 'joint_5')?.restMatrix);
/* joint_5 is a child of joint_3, so it must ride the circle of constant radius
* about joint_3's Y axis while joint_3's own pivot stays put. */
const radius = (point: number[] | null, center: number[] | null) => (point && center ? Math.hypot(point[0] - center[0], point[2] - center[2]) : Number.POSITIVE_INFINITY);
const joint5Radius = { rest: radius(joint5Rest, joint3Rest), posed: radius(joint5Posed, joint3Posed) };
const joint3X = boneByName(posedBones, 'joint_3')?.poseMatrix;
const posedXAxis = joint3X ? [joint3X[0], joint3X[1], joint3X[2]] : null;
const thirty = Math.PI / 6;
await dialog.getByRole('button', { name: '恢复零位', exact: true }).click();
const restored = await readAfterRevision(page, posed.revision ?? rigRevision, [ROOT_OBJECT, ...LINKS]);
const restoreDelta = Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link,
matrixDistance(rigged.nodes?.[link]?.worldMatrix ?? null, restored.nodes?.[link]?.worldMatrix ?? null)]));
const evidence = {
schemaVersion: 1,
case: 'robot-rig-web',
candidate: CANDIDATE,
revisions: { before: before.revision ?? null, rigged: rigged.revision ?? null },
revisions: { before: before.revision ?? null, rigged: rigged.revision ?? null, posed: posed.revision ?? null, restored: restored.revision ?? null },
bones,
bound,
worldDelta,
boneHeadDelta,
boneAxis,
boneAxisDelta,
matrices: Object.fromEntries(Object.keys(EXPECTED_BONES).map((link) => [link, { before: before.nodes?.[link]?.worldMatrix ?? null, rigged: rigged.nodes?.[link]?.worldMatrix ?? null, boundMatrix: rigged.nodes?.[link]?.parentBoneMatrix ?? null }])),
bonePose: Object.fromEntries((rigged.armatures ?? []).flatMap((armature) => armature.bones).map((bone) => [bone.name, { rest: bone.restMatrix, pose: bone.poseMatrix }])),
bonePose: Object.fromEntries(riggedBones.map((bone) => [bone.name, { rest: bone.restMatrix, pose: bone.poseMatrix }])),
jointPose: {
joint: 'joint_3', degrees: 30,
worldDelta: posedDelta,
joint3Pivot: { rest: joint3Rest, posed: joint3Posed },
joint5Head: { rest: joint5Rest, posed: joint5Posed },
joint5Radius,
posedXAxis,
restoreDelta,
},
rawNodes: Object.fromEntries(Object.entries(rigged.nodes ?? {}).filter(([, node]) => node.parentType === 'BONE' || node.type === 'ARMATURE')),
console: { productErrors: productConsole(errors), rawErrorCount: errors.length },
residuals: {
worldPreservation: {
status: 'deferred',
note: 'rig 阶段骨骼父级的世界保持偏差归入机器人逆解一并处理;本用例只判定 URDF 层级与装配绑定关系',
deltas: worldDelta,
},
},
acceptance: 'NOT_CLAIMED',
};
await attachEvidence(testInfo, 'robot-rig-web', evidence);
expect(bones).toEqual([...REVOLUTE].sort());
for (const [link, bone] of Object.entries(EXPECTED_BONES)) expect(bound[link]).toBe(bone);
/* World preservation across the rig step is recorded in evidence (residuals)
* and handled together with robot inverse kinematics; this case asserts the
* URDF hierarchy and assembly binding only. */
for (const [link, bone] of Object.entries(EXPECTED_BONES)) {
expect(bound[link]).toBe(bone);
/* Rigid binding keeps the rendered world: three.js only sees the world
* matrix, so any drift here is a visible jump on the rig click. */
expect(worldDelta[link], `${link} world preserved`).toBeLessThan(1e-5);
expect(boneHeadDelta[bone], `${bone} pivot on the URDF joint`).toBeLessThan(1e-5);
expect(boneAxisDelta[bone], `${bone} Y along the URDF axis`).toBeLessThan(1e-5);
}
/* Only the joint_3 subtree moves; upstream links stay bit-identical. */
expect(posedDelta.link_1).toBeLessThan(1e-9);
expect(posedDelta.link_2).toBeLessThan(1e-9);
for (const link of ['link_3', 'link_4', 'link_5', 'link_6']) expect(posedDelta[link], `${link} follows joint_3`).toBeGreaterThan(0.01);
expect(matrixMaxDelta(joint3Posed, joint3Rest), 'joint_3 pivot does not translate').toBeLessThan(1e-6);
expect(Math.abs(joint5Radius.posed - joint5Radius.rest), 'joint_5 rides the joint_3 circle').toBeLessThan(1e-3);
expect(Math.abs(Math.abs(posedXAxis![2]) - Math.sin(thirty)), 'rotation magnitude about the joint axis').toBeLessThan(1e-3);
expect(Math.abs(posedXAxis![0] - Math.cos(thirty)), 'rotation magnitude about the joint axis').toBeLessThan(1e-3);
expect(Math.abs(posedXAxis![1])).toBeLessThan(1e-6);
for (const link of Object.keys(EXPECTED_BONES)) expect(restoreDelta[link], `${link} restored`).toBeLessThan(1e-6);
expect(productConsole(errors)).toEqual([]);
});