feat(model): add xiaozhao single-arm collision models and update joint limits

This commit is contained in:
lgv 2026-11-18 15:05:55 +08:00
parent 2c4dff5d7f
commit f2d8910bea
23 changed files with 3352 additions and 46 deletions

View File

@ -1,3 +1,4 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
@ -5,6 +6,7 @@
#include <fstream>
#include <initializer_list>
#include <limits>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>
@ -14,6 +16,8 @@
#include "algorithms/collision_detection/include/distance_sampling_policy.h"
#include "algorithms/collision_detection/include/collision_checker.h"
#include "cmvr/config/self_collision_task_config/self_collision_task_config.pb.h"
#include "common/io/proto_file_io.h"
#include "common/types/arm/arm_types.h"
#include "environment/include/robot_model.h"
@ -459,6 +463,165 @@ TEST(CollisionCheckerTest, LoadsRightArmFromDualArmUrdf)
EXPECT_TRUE(result.second.rfind("L_", 0) != 0);
}
TEST(CollisionCheckerTest, XiaozhaoSourceKinematicsAndGeneratedGeometrySelectOnlyRequestedArm)
{
const std::string model_root = std::string(CMVR_ES_SOURCE_DIR) + "/model/xiaozhao/";
for (const std::string side : {"left", "right"}) {
SCOPED_TRACE(side);
RobotModel model;
std::set<std::string> expected_links{"base_link"};
for (int joint = 1; joint <= 7; ++joint) {
model.joint_names.push_back("joint" + std::to_string(joint) + "-" + side);
expected_links.insert("link" + std::to_string(joint) + "-" + side);
}
const auto selected_joints = model.joint_names;
ASSERT_TRUE(model.loadUrdf(model_root + "urdf/xiaozhao.urdf"));
ASSERT_TRUE(model.loadCollisionGeometry(
model_root + "collision/xiaozhao_collision.urdf"));
EXPECT_EQ(model.joint_names, selected_joints);
EXPECT_EQ(model.dof, 7U);
CollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(model, selected_joints, {}, &error)) << error;
EXPECT_EQ(checker.jointNames(), selected_joints);
EXPECT_EQ(checker.dof(), 7U);
EXPECT_GT(checker.activePairCount(), 0U);
const auto bodies = checker.collisionBodies(std::vector<double>(7, 0.0));
std::set<std::string> selected_links;
std::size_t wrist_piece_count = 0;
for (const auto& body : bodies) {
ASSERT_NE(body.geometry, nullptr);
EXPECT_TRUE(body.position.allFinite());
EXPECT_TRUE(body.orientation.coeffs().allFinite());
selected_links.insert(body.link_name);
if (body.link_name == "link5-" + side) {
EXPECT_EQ(body.geometry->getNodeType(), coal::GEOM_BOX);
++wrist_piece_count;
}
}
EXPECT_EQ(wrist_piece_count, 3U);
// Root geometry participates, but the opposite arm, moving neck and
// geometry-free TCP frames must not enter this single-arm query.
EXPECT_EQ(selected_links, expected_links);
for (const auto& link : std::vector<std::string>{
"base_link", "link2-" + side, "link5-" + side, "link7-" + side}) {
EXPECT_GT(std::count_if(bodies.begin(), bodies.end(), [&](const auto& body) {
return body.link_name == link;
}), 1) << "Expected multiple collision pieces for " << link;
}
const auto result = checker.check(bodies);
ASSERT_TRUE(result.valid) << result.error;
EXPECT_TRUE(std::isfinite(result.minimum_distance_m));
EXPECT_EQ(expected_links.count(result.first), 1U);
EXPECT_EQ(expected_links.count(result.second), 1U);
}
}
TEST(CollisionCheckerTest, XiaozhaoWristBoxesAndConfiguredPairExclusions)
{
const std::string path = std::string(CMVR_ES_SOURCE_DIR) +
"/model/xiaozhao/collision/xiaozhao_collision.urdf";
for (const std::string side : {"left", "right"}) {
SCOPED_TRACE(side);
std::vector<std::string> joints;
for (int joint = 1; joint <= 7; ++joint) {
joints.push_back("joint" + std::to_string(joint) + "-" + side);
}
CollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(path, joints, {}, &error)) << error;
const std::string wrist = "link5-" + side;
const std::string hand = "link7-" + side;
const auto isolated_wrist_bodies = [&](const std::vector<double>& q) {
auto bodies = checker.collisionBodies(q);
// Preserve the actual FK and all pieces of both wrist links. Move
// every other geometry far apart so shoulder padding cannot mask
// wrist regressions.
for (std::size_t index = 0; index < bodies.size(); ++index) {
auto& body = bodies[index];
if (body.link_name != wrist && body.link_name != hand) {
body.position = Eigen::Vector3d(
10.0 * static_cast<double>(index + 1), 10.0, 10.0);
}
}
return bodies;
};
const auto is_wrist_pair = [&](const CollisionResult& result) {
return (result.first == wrist && result.second == hand) ||
(result.first == hand && result.second == wrist);
};
// Preserve the physical all-zero pose from before the J3/J5 origins
// gained pi. This is a geometry reference, not a motion target or a
// claim that the new all-zero pose (or the whole robot) is collision-free.
const double pi = std::acos(-1.0);
const std::vector<double> historical_zero{0.0, 0.0, pi, 0.0, pi, 0.0, 0.0};
const auto historical = checker.check(isolated_wrist_bodies(historical_zero));
ASSERT_TRUE(historical.valid) << historical.error;
EXPECT_TRUE(is_wrist_pair(historical));
EXPECT_TRUE(std::isfinite(historical.minimum_distance_m));
if (side == "right") {
// Merging the inner supports and outer cheeks closes the historical
// gap. Keep the overlap within the 1 mm fitting margin.
EXPECT_GE(historical.minimum_distance_m, -0.001);
// Frozen reference: original STL triangle queries independently
// confirmed wrist interference here. Do not read task config;
// choosing a new touch initialization must not invalidate this test.
// J3/J5 use new coordinates: q_new = wrap(q_old - pi).
const std::vector<double> known_interference{
1.8648861126, 0.8084619160, 2.727417567789793, 1.6622227972,
1.810335360989793, -0.2423592867, -1.0088169947,
};
const auto full = checker.check(known_interference);
ASSERT_TRUE(full.valid) << full.error;
EXPECT_TRUE(full.in_collision);
const auto isolated = checker.check(isolated_wrist_bodies(known_interference));
ASSERT_TRUE(isolated.valid) << isolated.error;
EXPECT_TRUE(is_wrist_pair(isolated));
EXPECT_TRUE(isolated.in_collision);
EXPECT_TRUE(std::isfinite(isolated.minimum_distance_m));
EXPECT_LE(isolated.minimum_distance_m, 0.0);
}
const auto root = std::filesystem::path(CMVR_ES_SOURCE_DIR);
const auto task_path = root / "cmvr-es/config/tasks/self_collision_task" /
("self_collision_task_xiaozhao_" + side + ".pb.txt");
config::SelfCollisionTaskRootConfig task;
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(task_path.string(), &task));
auto config = task.self_collision_task().checker();
config.set_urdf_path((root / config.urdf_path()).string());
CollisionChecker filtered;
ASSERT_TRUE(filtered.init(config, joints, &error)) << error;
const auto filtered_zero = filtered.check(isolated_wrist_bodies(historical_zero));
ASSERT_TRUE(filtered_zero.valid) << filtered_zero.error;
EXPECT_FALSE(filtered_zero.in_collision);
EXPECT_FALSE(is_wrist_pair(filtered_zero));
std::vector<double> bent_wrist(7, 0.0);
bent_wrist[5] = side == "left" ? 0.45 : -0.45;
const auto bodies = isolated_wrist_bodies(bent_wrist);
const auto raw = checker.check(bodies);
ASSERT_TRUE(raw.valid) << raw.error;
ASSERT_TRUE(is_wrist_pair(raw));
ASSERT_TRUE(raw.in_collision);
const auto monitored = filtered.check(bodies);
ASSERT_TRUE(monitored.valid) << monitored.error;
EXPECT_FALSE(monitored.in_collision);
EXPECT_FALSE(is_wrist_pair(monitored));
const auto piece_count = [&](const std::string& link) {
return std::count_if(bodies.begin(), bodies.end(),
[&](const auto& body) { return body.link_name == link; });
};
EXPECT_EQ(checker.activePairCount() - filtered.activePairCount(),
piece_count(wrist) * piece_count(hand));
}
}
TEST(CollisionCheckerTest, RejectsWrongJointVectorSize)
{
CollisionChecker checker;

View File

@ -38,7 +38,7 @@ arm {
joints { joint_name: "joint1-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-left" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: -2.355 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
@ -188,7 +188,7 @@ arm {
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: 0 q_ub: 2.355 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }

View File

@ -17,7 +17,7 @@ motor {
joints { joint_name: "joint1-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-left" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: -2.355 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
@ -47,7 +47,7 @@ motor {
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: 0 q_ub: 2.355 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }

View File

@ -23,6 +23,23 @@ task_manager {
config_file: "tasks/self_collision_task/self_collision_task.pb.txt"
enable: false
}
# 小赵左右臂分别检测;碰撞代理完成验收前不启用在线保护停止。
tasks {
id: "xiaozhao_left_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt"
enable: false
}
tasks {
id: "xiaozhao_right_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt"
enable: false
}
tasks {
id: "quic_edge"
type: TASK_TYPE_QUIC_EDGE

View File

@ -0,0 +1,35 @@
# 小赵左臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
# 这是碰撞模型验收配置;manager 默认关闭,确认初姿/代理几何后再启用。
self_collision_task {
id: "xiaozhao_left_arm_self_collision"
arm_id: "xiaozhao_left_arm"
checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs {
first: "link5-left"
second: "link7-left"
}
}
sampling {
max_geometry_displacement_m: 0.002
max_check_period_s: 0.01
}
# 暂沿用既有阈值。原网格肩部间隙约 2.3 mm,低于此处 5 mm 停止距离;
# 细化碰撞体后仍需校核装配间隙处理,不能直接启用。
safety {
warning_distance_m: 0.02
stop_distance_m: 0.005
}
recovery {
clear_distance_m: 0.025
stable_period_s: 0.1
max_joint_velocity_rad_s: 0.15
max_joint_acceleration_rad_s2: 0.3
history_duration_s: 10.0
max_distance_regression_m: 0.001
}
}

View File

@ -0,0 +1,35 @@
# 小赵右臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
# 这是碰撞模型验收配置;manager 默认关闭,确认初姿/代理几何后再启用。
self_collision_task {
id: "xiaozhao_right_arm_self_collision"
arm_id: "xiaozhao_right_arm"
checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs {
first: "link5-right"
second: "link7-right"
}
}
sampling {
max_geometry_displacement_m: 0.002
max_check_period_s: 0.01
}
# 暂沿用既有阈值。原网格肩部间隙约 2.3 mm,低于此处 5 mm 停止距离;
# 细化碰撞体后仍需校核装配间隙处理,不能直接启用。
safety {
warning_distance_m: 0.02
stop_distance_m: 0.005
}
recovery {
clear_distance_m: 0.025
stable_period_s: 0.1
max_joint_velocity_rad_s: 0.15
max_joint_acceleration_rad_s2: 0.3
history_duration_s: 10.0
max_distance_regression_m: 0.001
}
}

View File

@ -39,9 +39,10 @@ touch_screen_task {
# 手相机 1280x720 原图中 (953, 592) 附近为可见屏幕区域;点击运动尚未动态验证。
joint_positions { joint_name: "joint1-right" rad: 1.8648861126 }
joint_positions { joint_name: "joint2-right" rad: 0.8084619160 }
joint_positions { joint_name: "joint3-right" rad: -0.4141750858 }
# J3/J5 零位已各沿局部轴 +pi;以下角度按 wrap(q_old-pi) 换算,保持原物理起姿。
joint_positions { joint_name: "joint3-right" rad: 2.727417567789793 }
joint_positions { joint_name: "joint4-right" rad: 1.6622227972 }
joint_positions { joint_name: "joint5-right" rad: -1.3312572926 }
joint_positions { joint_name: "joint5-right" rad: 1.810335360989793 }
joint_positions { joint_name: "joint6-right" rad: -0.2423592867 }
joint_positions { joint_name: "joint7-right" rad: -1.0088169947 }
velocity: 0.5

View File

@ -13,8 +13,14 @@ xiaozhao 的双臂关节名为 `joint1-left`…`joint7-left` 和
模型最初基于 urdf6 导入的 18 个 STL,颈部现已同步 `model/00 0930Body-urdf7.SLDASM`;其中
`link7-right.STL` 已替换为完整 `link7-left.STL` 关于局部 XY 平面的镜像(Z 坐标取反),左右手各使用一份完整 STL。
两侧手部 STL 已从各 268,502 面减至 21,479 面,减少约 92%;URDF 保持原路径即可读取轻量手部。
`neck_Link1`~`neck_Link3`、`neck-joint1`~`neck-joint3` 已按 urdf7 更新。双臂的关节定义、
限位、TCP 和惯量保持原配置;J3/J4 仅调整 visual/collision origin,适配新网格的局部坐标。
`neck_Link1`~`neck_Link3`、`neck-joint1`~`neck-joint3` 已按 urdf7 更新。
双臂 J3/J5 的机械零位已于 2026-11-18 各沿原关节局部 Z 轴旋转 +180°;
新的 `q=0` 对应旧模型的 `q=pi`,URDF 安装旋转为 `R_new = R_old * Rz(pi)`。
左右臂同步调整,关节轴向、位置限位数值、TCP 局部偏移和惯量保持原配置;
J3/J4 之前的 visual/collision origin 调整继续保留,用于适配网格局部坐标。
URDF、生成的 MuJoCo XML 和分块碰撞 URDF 使用同一零位。
保持旧物理姿态时,仅 J3/J5 需换算为 `q_new = wrap(q_old - pi)`,其余关节不变;
旧角度不能直接作为当前模型的运动目标。修改后需重启 CMVR,使运动学和仿真同时加载新模型。
颈部沿用源 URDF 的 `0 0 1` 轴向及限位:J1 `[-1.57, 1.57]`、
J2 `[-1.57, 0.44]`、J3 `[-0.44, 0.44]` rad;首关节已补偿现有基座绕 Z 轴的 +90° 变换。
颈部 J3 相对 `neck_Link2` 的 origin 更新为 `(0, 0.0035, -0.035) m`,安装旋转保持原值。
@ -29,7 +35,8 @@ J2 `[-1.57, 0.44]`、J3 `[-0.44, 0.44]` rad;首关节已补偿现有基座绕
颈部真正的零位(`qpos=0`)是直立的;Control 面板中的数值是执行器目标角度。
头部与下段颈部的凸包在内部机构处重叠,曾把零目标下的 J3 推到约 19.62°。
颈部仅排除 `neck_Link1`/`neck_Link3` 这一对内部碰撞,保留其他碰撞、关节原点、轴向及限位。
此规则及原有两条肩部排除统一放在 `xml/contact_exclusions.xml`,由 `scene.xml` 加载一次;
每只手腕也排除本臂 `link5` 与 `link7` 之间的接触。腕部、颈部及原有两条肩部排除
统一放在 `xml/contact_exclusions.xml`,由 `scene.xml` 加载。
从 URDF 重新生成机器人 XML 不会覆盖碰撞配置。修改排除规则后重新加载 `scene.xml` 即可。
原生 MuJoCo 3.3.7 验证:零目标运行 10 秒后 J3 约 −0.001°、J2 约 +0.087°;
三组非零目标及回零的最大稳态误差约 0.168°,未产生仿真警告。
@ -104,8 +111,9 @@ G/H 相对位置误差约 1.3 mm,不作为当前 S05 参考布局的精度结
`mujoco_hand_cam` 的 RGB 图像并点击屏幕上的目标。`u/v` 使用原始图像的 1280 × 720 像素坐标;
上位机 RGB Image 页面会按原图尺寸换算点击坐标。不要使用外部相机或编码视频的像素直接调用 touch。
每次 touch 请求还会用 MoveJ 确认初始位,点击后不要手动改变机械臂姿态。
右臂初始角按 J1~J7 顺序为 `[1.8648861126, 0.8084619160, -0.4141750858, 1.6622227972,
-1.3312572926, -0.2423592867, -1.0088169947]` rad;MoveJ 使用速度 `0.5 rad/s`、加速度 `1.0 rad/s²`。
右臂初始角按 J1~J7 顺序为 `[1.8648861126, 0.8084619160, 2.727417567789793, 1.6622227972,
1.810335360989793, -0.2423592867, -1.0088169947]` rad;MoveJ 使用速度 `0.5 rad/s`、加速度 `1.0 rad/s²`。
J3/J5 已换算到新零位,实际物理起姿保持不变。
TCP 约 `(0.52237, -0.23207, 0.42622) m`,距屏幕正面约 86.95 mm。
以下头相机静态识别及像素数据在颈部零位时测得;当前头部采用上述非零初始角,以实际画面为准。
新起姿经项目实际 AprilTag 检测器确认:手相机识别 ID 1,头相机同时识别 ID 0 和 ID 1。
@ -115,8 +123,7 @@ TCP 约 `(0.52237, -0.23207, 0.42622) m`,距屏幕正面约 86.95 mm。
`(x=-0.08, y=0.015, z=0.045) m`;不要直接把右上角 Tag 中心作为第一个触碰目标。
此参考点仅做静态投影检查;左右偏转改为 0° 后,点击运动的 IK、整条路径避碰及
完整视觉伺服流程尚未重新验证。
当前模型仍有肩、颈及腕部内部接触,新初姿右腕碰撞几何穿透约 20.3 mm,
因此该初姿不作为无碰撞路径验证结果。
加入腕部接触排除前,上述初姿测得右腕碰撞几何穿透约 20.3 mm。
小赵尚未配置 MoveP 避障规划,因此此配置关闭 MoveP 预接近及完成/失败后的自动回初始位,
直接从初始位进行 PBVS 视觉对齐。更换测试点前需手动回初始位并重新取图。
@ -144,6 +151,7 @@ cp cmvr-es/config/devices/arm/xiaozhao_arm.pb.txt output/bin/config/devices/arm/
cp cmvr-es/config/devices/arm/xiaozhao_head.pb.txt output/bin/config/devices/arm/
cp cmvr-es/config/devices/camera/xiaozhao_camera.pb.txt output/bin/config/devices/camera/
cp cmvr-es/config/tasks/touch_screen_task/touch_screen_task_xiaozhao_mujoco.pb.txt output/bin/config/tasks/touch_screen_task/
cp cmvr-es/config/tasks/self_collision_task/self_collision_task_xiaozhao_{left,right}.pb.txt output/bin/config/tasks/self_collision_task/
cp -a model/xiaozhao output/bin/model/
./output/bin/cmvr_es
```
@ -185,13 +193,15 @@ MuJoCo 下 `torqueOn` 保持当前关节位置;`torqueOff` 解除直接位置/
新模型的专用碰撞配置尚未验证,不能直接复用 xiaoyan 的碰撞模型。
修改 `joint_limits.csv` 后,除运行下方同步工具,还需同步修改两份控制配置中的
`joint_limits` / `joint_limit_policy.limits`,保持电机、IK 与模型的位置限位一致。
小赵 J4 的限位为右臂 `[-2.35, 0]`、左臂 `[0, 2.35]` rad。
当前右臂触控初姿的 J4 为 `+1.6622227972 rad`,超出新范围,重新设定初姿后才能执行触控回位。
### moveL / speedL 测试起始姿态
### 历史 moveL / speedL 测试姿态
预设和两臂的 gRPC 请求示例保存在
`model/xiaozhao/config/cartesian_test_pose.json`。这是手动测试预设,不会自动改变启动位置。
先对目标臂调用 `torqueOn`,再用 `moveJ` 到下列姿态;七个关节全部选择,顺序为 J1~J7。
MoveJ 参数:速度 `0.5 rad/s`、加速度 `1.0 rad/s²`,等待到位后再测试笛卡尔运动。
下表和本节 TCP 数值记录 J3/J5 零位修正之前的测试,不能直接发送到当前模型。
此前文档引用的 `cartesian_test_pose.json` 当前仓库中不存在。
下表旧 J3/J5 均为 0,保持其物理姿态需要新角度 ±pi,略超现有 ±3.14 rad 限位;
因此不将其自动截断为当前可执行预设,新的笛卡尔测试起姿需重新选择。
| 机械臂 | J1~J7,单位 ° |
| --- | --- |
@ -201,29 +211,23 @@ MoveJ 参数:速度 `0.5 rad/s`、加速度 `1.0 rad/s²`,等待到位后再
使用 `ARM_FRAME_BASE`,基准为 `base_link`,TCP 分别为 `tcp-left` / `tcp-right`。
调用 `getPose` 时,`base_link` 填 `base_link`,`ee_link` 按左右臂填 `tcp-left` 或 `tcp-right`。
客户端如果仍加载 xiaoyan 的 URDF,需要修改关节名称,且不能沿用旧模型的 GetPose 坐标系。
预设中的 `expected_tcp_pose` 是按当前 URDF 计算的六个值;姿态单位为 rad,
约定为 `R = Rx(rx) * Ry(ry) * Rz(rz)`,不是旋转向量。
`base_link` 坐标轴和上述 TCP 偏移更新后,预设内的绝对 TCP 示例已按当前 URDF 重新计算;
调整前保存的绝对坐标不能继续直接使用。修改模型后应重新 `getPose`,
预设中的 `expected_tcp_pose_urdf_sha256` 标记了生成示例时的 URDF 版本。
当前 `base_link` 已直接作为根,关节轴向和限位保持不变,因此上表的关节角仍适用。
位姿姿态单位为 rad,约定为 `R = Rx(rx) * Ry(ry) * Rz(rz)`,不是旋转向量。
修改模型后应重新 `getPose`,不要沿用历史绝对 TCP 示例。
机器人正前方为 Base 的 +X;上表保留的是旧 −X 侧测试姿态(机器人后方),
不能作为当前正前方触屏场景的起始姿态。这组姿态的左右 TCP 分别约为
`(-0.482792, 0.101209, 0.374712) m` 和 `(-0.482788, -0.101205, 0.374712) m`。
- `moveL`:读取当前 `getPose`,保持 `rx/ry/rz`,单独修改 X、Y 或 Z 的绝对目标 ±`0.01 m`;速度 `0.01 m/s`,加速度 `0.05 m/s²`,blend 为 0。
- `speedL`:单轴线速度 ±`0.01 m/s`,其余速度包括角速度全部为 0;加速度 `0.05 m/s²`,duration 为 `0.5 s`。返回后调用 `stopMotion`,确认成功且关节速度归零。duration 为 0 会持续运行。
- 每项测试前用 `moveJ` 回到上述姿态,避免连续点击产生累计位移。SpeedL 有加减速过程,位移不能直接按速度乘时长计算。
- 选定并验证新的测试起姿后,每项测试前用 `moveJ` 回到该姿态,避免连续点击产生累计位移。SpeedL 有加减速过程,位移不能直接按速度乘时长计算。
以下控制接口执行记录均来自添加初版 170 mm TCP 之前,使用 `link7-left/right` 作为 TCP;
本次偏移更新已重新计算位姿示例,URDF/MuJoCo 一致性检查结果记录在 JSON 的
`tcp_frame_validation` 中;尚未重新执行 MoveL/SpeedL 接口测试。
尚未在当前 J3/J5 零位下重新执行 MoveL/SpeedL 接口测试。
坐标轴调整前的隔离仿真通过两臂 × 六个平移方向 × 两种接口,共 24 项 C++ 控制接口测试;
基座系调整后、添加 TCP 之前的模型通过左臂六方向 MoveL(jerk 为 gRPC 默认值 `5 m/s³`),
最大末端位置误差约 `3.32 μm`,运动中最小关节限位余量约 `0.226 rad`。
该次测试随后在首项 SpeedL 前的回预设/切换阶段阻塞,未完成 SpeedL 和右臂执行验证。
该结果只覆盖上述小幅平移。当前碰撞网格仍有 link5/link7 腕部接触,
不代表避碰验证或原生力矩控制验证。
该结果只覆盖上述小幅平移。测试时 MuJoCo 仍计算同臂 link5/link7 的腕部接触。
## 从 CSV 同步关节限位
@ -290,7 +294,7 @@ python3 model/update_joint_limits.py --xiaozhao \
也支持 SolidWorks 导出 CSV 的 `Joint Name`、`Limit Lower`、`Limit Upper` 列,
按弧度读取,跳过无关节名的根链接行。SolidWorks 格式 CSV 和另一份原始 URDF 不会由限位脚本自动修改。
当前 SolidWorks 格式 CSV 的关节坐标、轴向、限位及链接原点已按 `xiaozhao.urdf` 同步。
SolidWorks 格式 CSV 保留 J3/J5 零位修正之前的导出快照,当前关节坐标以 `xiaozhao.urdf` 为准。
该格式每个链接仅记录一组 visual/collision;当前左右手各用一份完整 STL,URDF/XML 不再叠加额外的镜像手掌几何。
另一份原始 URDF 保留为历史导出。
目标 MJCF 必须是包含关节定义的机器人文件,不是仅含 `include` 的 `scene.xml`。

View File

@ -0,0 +1,153 @@
# 小赵单臂分块碰撞模型
`xiaozhao_collision.urdf` 使用同一 link 下的多个 box/cylinder 表示躯干、肩部和腕部。
它保留源 URDF 的 19 个 joint(17 个活动关节)、惯性、visual 和 TCP 定义;
TCP 红球仍为 visual-only。碰撞生成脚本不修改源 URDF、原 STL 或 MuJoCo 模型。
2026-11-18 双臂 J3/J5 零位沿局部 Z 轴各修正 +180° 后,本文件已从新 URDF 重新生成;
该次零位修正只换算关节坐标。
左右臂分别使用各自七个关节进行检测,范围为本臂加固定 base。另一臂、活动头颈和
屏幕等外部物体不在本次范围。除自动跳过同关节及直接父子关节对外,每侧任务通过
`ignored_pairs` 跳过本臂 `link5` 与 `link7` 之间的所有分块组合。MuJoCo 场景在
`../xml/contact_exclusions.xml` 中排除同样的两对接触。
## 分块方式
配置位于 `xiaozhao_collision.toml`:
- `base_link` 由底脚、下躯干、上躯干、肩部中央和颈部安装座五个方盒组成。
左右肩环分区设置 `enabled = false`,每侧 232 个源三角面从拟合和覆盖检查中排除。
- 左右 `link2` 各使用过渡段 `elbow_transition` 和远端外壳 `distal_housing` 两个方盒。
长圆柱 `proximal_back`、下端盖 `proximal_lower_cap` 和上端盖 `proximal_upper_cap` 的分区均已停用。
- `link5-left` 和 `link5-right` 各使用三个方盒,分别包住腕叉主体和两侧叉臂。
- 左右 `link7` 各保留腕部圆端的圆柱和掌根、手掌、手指三个方盒。靠近 `link6` 的薄方盒 `plate_body` 和转接段方盒 `adapter` 已停用。
参与拟合的原始三角面保留 **1 mm** 的外扩余量。
左右腕在各自 link 坐标下的方向不同,使用各自的参数。块名描述的是几何分区,
不表示已经识别出真实物料或可拆卸外壳。
`pieces` 使用 link-local 坐标下的半开区域,按三角面重心分组。例如:
```toml
[[links.base_link.pieces]]
name = "lower"
bounds_max = [inf, inf, 0.30]
[[links.base_link.pieces]]
name = "upper"
bounds_min = [-inf, -inf, 0.30]
```
`bounds_min` 默认全为 `-inf`,`bounds_max` 默认全为 `inf`;每个源三角面必须恰好
归入一块,包括显式停用的分区。遗漏、重叠、空分区、非法名称或数值都会终止生成。即使三角面跨越分区
边界,也保留其三个原顶点,不能只截取重心所在区域的顶点。
每块默认使用 link 轴对齐 box;可选 `alignment = "oriented"`,或使用
`primitive = "cylinder"` 配合 `axis = "x" / "y" / "z" / "auto"`。
固定轴圆柱可设置 `axial_layers = 3`,沿轴向把选中的几何等分为三层。
跨层三角面按与分层平面的交线切分,再用层内全部顶点和边交点拟合圆柱。
细长组件可使用 `primitive = "auto"`、`allowed_primitives = ["box", "cylinder"]`
及 `axis = "auto"`,按拟合体积选择形状。任意轴圆柱拟合先归一化零件尺度,
避免米制小体积导致优化器停在粗采样方向,结果和外扩量再还原为米;公共拟合脚本
保持原样。所有尺寸由原三角面拟合。
另有两个局部细化选项:
- `split_normals = true`:按主法线轴及正负方向分六组,派生名称带 `x_pos` 等后缀。
- `split_components = true`:按共享三角边的连通性进一步分组,派生名称带 `part000`
等后缀。只焊接重复顶点以恢复邻接,不删除原三角面;孤立面、退化面也保留。
这两个选项都可以局部开启;同时开启时先按法线、再按连通性分组。全部派生名称必须
唯一。URDF 中的片段名称用于审查,现有检测器的 `ignored_pairs` 仍按整 link 匹配,
不会因为增加了 collision 名称就自动支持片段级忽略。
## 生成和检查
需要 Python 3.11+、numpy、trimesh、scipy、networkx。`networkx` 用于 trimesh 的
部分有向包围盒拟合路径。普通 Python 环境可安装这些依赖后,在仓库根目录执行:
```bash
python model/xiaozhao/collision/generate_collision.py
python model/xiaozhao/collision/verify_collision.py
python model/xiaozhao/collision/test_collision_pieces.py -v
```
本机 Isaac Python 已包含其余依赖,networkx 则位于 Isaac 扩展包中。以下方式只临时
引入纯 Python 的 networkx,不将整个扩展依赖目录加入搜索路径(整目录会覆盖 numpy):
```bash
mkdir -p /tmp/xiaozhao_networkx_deps
ln -sfn /home/lgv/app/isaacsim/extscache/omni.cip.pip-2.0.5+lx64.cp312/pip_prebundle/networkx /tmp/xiaozhao_networkx_deps/networkx
PYTHONPATH=/tmp/xiaozhao_networkx_deps PYTHONDONTWRITEBYTECODE=1 /home/lgv/app/isaacsim/python.sh model/xiaozhao/collision/generate_collision.py
PYTHONPATH=/tmp/xiaozhao_networkx_deps PYTHONDONTWRITEBYTECODE=1 /home/lgv/app/isaacsim/python.sh model/xiaozhao/collision/verify_collision.py
```
生成器明确读取当前 `model/xiaozhao/meshes`,避免源 URDF 的历史 package 名解析到旧
模型;未分块的 link 继续复用公共 `scripts/isaac_sim/generate_collision_primitives.py`
中的拟合函数。公共脚本保持原样。`--output /tmp/candidate.urdf` 可生成候选,成功完成
独立覆盖审查后才发布输出文件。禁止将输出指向源 URDF 或非 `.urdf` 文件。
审查器逐 link 检查参与拟合的完整三角面是否位于某个内缩 1 mm 的凸体内。跨圆柱层界的三角面
还可以按生成圆柱的轴向区间裁开,逐片验证整个子面。这个检查覆盖三角面内部和层间接缝。
源 STL 本身包含非水密组件,手部又已减面,覆盖范围不等同于原始 CAD、MuJoCo 原手部
OBJ 或未建模附件。
Python 分块测试与 C++ collision checker 测试覆盖倒角分层、层间接缝、倾斜细圆柱的尺度一致性、
多块实际加载、单臂筛选及固定腕部冲突的正反例。
生成与审查同时验证所有关节、全部非 collision 模型字段、visual 资产及 TCP 定义。
生成器会输出源/目标 SHA256。固定姿态、抽样距离、查询耗时和模型指纹保存在
`validation_report.json`;修改网格或参数后,旧报告不再代表新模型。
## 查看
```bash
/home/lgv/miniconda3/envs/cmvr-es/bin/python scripts/meshcat/view_urdf_collisions.py --input model/xiaozhao/collision/xiaozhao_collision.urdf --visual-opacity 0.35
```
默认显示零位、半透明原网格和绿色碰撞线框。visual 的 `../meshes/*.STL` 相对 URDF
目录解析,仓库查看器支持该方式。Pinocchio 加载 VISUAL 时需显式将 URDF 父目录作为
`package_dirs`;primitive 碰撞加载不需要这些视觉资源搜索设置。
## 在线任务状态
两套配置分别绑定 `xiaozhao_left_arm`、`xiaozhao_right_arm`:
- `cmvr-es/config/tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt`
- `cmvr-es/config/tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt`
`cmvr-es/config/manager/task_manager.pb.txt` 中两项继续保持 `enable: false`。
分块拟合不调整全局距离阈值,也不接入 MoveP。触控初姿的 J3/J5 已换算到新零位,
对应同一物理姿态。在线保护和触控运动仍待验收。
原网格肩部正常间隙约 2.3 mm,低于当前 5 mm 停止阈值。下方离线几何记录保留了
右触控初姿的腕部原网格相交结果。任务启用后也会跳过这个腕部对。
当前模型共有 34 个碰撞体,基座占 5 个,每侧 `link2` 各占 2 个。
## 分块拟合离线结果(2026-11-18,修正零位之前)
最终模型包含 118 个碰撞体:base 7 块;左右 link2 各 5 块;左右 link7 各 6 块;
右 link5 为 5 块,左 link5 为 73 块,其较多的独立 CAD 薄片和细长结构全部保留;
其余物理 link 各 1 块。覆盖校验包含全部 1,410,356 个源三角面,每个完整面在某个
凸碰撞体内保留至少 1 mm 余量。左右单臂分别选入 95/27 个几何体。
| 检查项 | 原单体包络 | 最终分块包络 |
| --- | ---: | ---: |
| 左腕旧零位 link5/link7 | -40.4 mm | +0.0452 mm |
| 右腕旧零位 link5/link7 | -40.4 mm | +0.0441 mm |
| 肩部旧零位 base/link2 | -43.2 mm | 约 -0.2502 mm |
表中的旧零位在当前模型下对应两臂 J3/J5=pi,其余关节为 0,仅作离线几何对照。
它不是当前全零姿态,也略超现有 ±3.14 rad 限位,不能作为 MoveJ 目标。
这张表是代理几何间距,不是原始 CAD 的间距或实机测量结果。小的正间距只表示该
检查姿态下代理未相交,不等于满足 5 mm 停止阈值。仅在临时诊断副本中撤销肩部外扩后,
零位、旧预设和触控初姿的肩部间隙约为 2.30 mm,与原 STL 约 2.324 mm 接近;
正式模型仍保留全部 1 mm 外扩。
未过滤腕部对时,旧笛卡尔预设在分块代理中有约 7.27 mm 腕部重叠,右触控初姿的原网格腕部
相交也仍被检出。两臂各 20 个随机限位内样本均未成为全臂无相交状态。
上述残余及近距离配合规则仍需继续处理,不能只根据零位腕部改善启用在线保护。
零位修正后,源模型和碰撞模型分别通过 19 个姿态、全部 20 个 link/TCP 的新旧 FK
对照(每个模型 380 项),按 J3/J5 的 pi 偏移换算后位置误差小于 5e-16 m。
碰撞回归使用换算后的历史物理姿态;报告的 `historical_reference` 保留修正前的
距离、随机样本和耗时记录,不能把其中的 `zero` 当成新零位。

View File

@ -0,0 +1,213 @@
"""Fit named convex pieces to complete source triangles in link coordinates."""
import importlib.util
from pathlib import Path
import re
import sys
import numpy as np
import trimesh
FITTER_PATH = (Path(__file__).resolve().parents[3] /
"scripts/isaac_sim/generate_collision_primitives.py")
def shared_fitter():
name = "xiaozhao_shared_primitive_fitter"
if name not in sys.modules:
spec = importlib.util.spec_from_file_location(name, FITTER_PATH)
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return sys.modules[name]
def link_triangles(link):
"""Input mesh URIs must already identify the current local model assets."""
fitter = shared_fitter()
triangles = []
for visual in link.findall("visual"):
mesh_element = visual.find("geometry/mesh")
if mesh_element is None:
continue
path = Path(mesh_element.get("filename", ""))
if not path.is_absolute() or not path.is_file():
raise ValueError(f"expected an absolute current-model mesh path: {path}")
mesh = trimesh.load(path, force="mesh", process=False)
scale = fitter._parse_vector(mesh_element.get("scale"), 3, (1, 1, 1))
transform = fitter._urdf_origin_transform(visual.find("origin"))
vertices = trimesh.transform_points(np.asarray(mesh.vertices) * scale, transform)
triangles.append(vertices[np.asarray(mesh.faces)])
if not triangles:
raise ValueError(f"no visual triangles on {link.get('name')}")
result = np.concatenate(triangles)
if result.ndim != 3 or result.shape[1:] != (3, 3) or not np.isfinite(result).all():
raise ValueError(f"invalid source triangles on {link.get('name')}")
return result
def partition_triangles(triangles, pieces):
"""Assign each complete face to exactly one half-open centroid region."""
triangles = np.asarray(triangles, dtype=float)
if (triangles.ndim != 3 or triangles.shape[1:] != (3, 3) or
not len(triangles) or not np.isfinite(triangles).all()):
raise ValueError("expected finite, nonempty triangles with shape (N, 3, 3)")
if not pieces:
raise ValueError("pieces must not be empty")
centroids = triangles.mean(axis=1)
owner = np.full(len(triangles), -1, dtype=np.int32)
names = set()
for index, piece in enumerate(pieces):
name = piece.get("name", "")
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_\-]+", name) or name in names:
raise ValueError(f"piece names must be unique simple identifiers: {name!r}")
names.add(name)
if not isinstance(piece.get("enabled", True), bool):
raise ValueError(f"enabled must be a boolean on {name}")
lower = np.asarray(piece.get("bounds_min", [-np.inf] * 3), dtype=float)
upper = np.asarray(piece.get("bounds_max", [np.inf] * 3), dtype=float)
if (lower.shape != (3,) or upper.shape != (3,) or
np.isnan(lower).any() or np.isnan(upper).any() or not (lower < upper).all()):
raise ValueError(f"invalid region bounds for {name}")
selected = np.all((centroids >= lower) & (centroids < upper), axis=1)
if not selected.any():
raise ValueError(f"empty piece: {name}")
if np.any(owner[selected] >= 0):
raise ValueError(f"overlapping triangle assignments at piece: {name}")
owner[selected] = index
missing = int(np.count_nonzero(owner < 0))
if missing:
raise ValueError(f"{missing} source triangles are not assigned to a piece")
return owner
def connected_face_groups(faces):
"""Split only at disconnected triangle edges; retain even isolated faces."""
mesh = trimesh.Trimesh(vertices=faces.reshape(-1, 3),
faces=np.arange(len(faces) * 3).reshape(-1, 3), process=False)
# STL repeats the vertices of each face. Weld identical positions to recover
# adjacency without processing/removing any original faces.
mesh.merge_vertices(digits_vertex=12)
components = trimesh.graph.connected_components(mesh.face_adjacency,
nodes=np.arange(len(faces)),
min_len=1, engine="scipy")
return [faces[indices] for indices in sorted(components, key=lambda item: int(np.min(item)))]
def axial_layer_points(name, faces, axis, layers):
"""Get all vertices of each triangle portion clipped to an axial slab."""
coordinates = faces[:, :, axis]
axial_min = coordinates.min(axis=1)
axial_max = coordinates.max(axis=1)
if axial_max.max() <= axial_min.min():
raise ValueError(f"cannot split a flat piece along its cylinder axis: {name}")
cuts = np.linspace(axial_min.min(), axial_max.max(), layers + 1)
for index, (lower, upper) in enumerate(zip(cuts[:-1], cuts[1:])):
selected = faces[(axial_max >= lower) & (axial_min <= upper)]
if not len(selected):
raise ValueError(f"empty axial layer {index} on {name}")
starts = selected.reshape(-1, 3)
ends = np.roll(selected, -1, axis=1).reshape(-1, 3)
a, b = starts[:, axis], ends[:, axis]
vertices = [starts[(a >= lower) & (a <= upper)]]
# The clipped polygon's vertices are the source vertices in the slab
# and the intersections of its edges with either boundary plane.
for plane in (lower, upper):
crosses = (np.minimum(a, b) < plane) & (plane < np.maximum(a, b))
fraction = (plane - a[crosses]) / (b[crosses] - a[crosses])
vertices.append(starts[crosses] + fraction[:, None] *
(ends[crosses] - starts[crosses]))
yield f"{name}_slice{index:02d}", np.concatenate(vertices), len(selected)
def fit_pieces(triangles, settings):
fitter = shared_fitter()
pieces = settings["pieces"]
owner = partition_triangles(triangles, pieces)
result = []
for index, piece in enumerate(pieces):
if not piece.get("enabled", True):
continue
config = {**settings, **piece}
kind = piece.get("primitive", "box")
if kind not in ("box", "cylinder", "auto"):
raise ValueError(f"piece must be box, cylinder or auto: {piece['name']}")
allowed = config.get("allowed_primitives", ["box", "cylinder"])
if not isinstance(allowed, list) or not allowed or set(allowed) - {"box", "cylinder"}:
raise ValueError("piece allowed_primitives must select box and/or cylinder")
alignment = config.get("alignment", "link")
if alignment not in ("link", "oriented"):
raise ValueError(f"invalid alignment on {piece['name']}")
axis = config.get("axis")
if (kind == "cylinder" or (kind == "auto" and "cylinder" in allowed)) and axis not in ("x", "y", "z", "auto"):
raise ValueError(f"piece cylinder requires x/y/z/auto axis: {piece['name']}")
if axis == "auto":
axis = None
layers = config.get("axial_layers", 1)
if type(layers) is not int or layers < 1:
raise ValueError("axial_layers must be a positive integer")
if layers > 1 and (kind != "cylinder" or axis not in ("x", "y", "z")):
raise ValueError("axial_layers requires a cylinder with a fixed axis")
padding, scale = float(config.get("padding", 0.001)), float(config.get("scale", 1.0))
if not np.isfinite([padding, scale]).all() or padding < 0 or scale < 1:
raise ValueError("piece padding must be nonnegative; scale must be at least 1")
selected = triangles[owner == index]
split_normals = config.get("split_normals", False)
if not isinstance(split_normals, bool):
raise ValueError("split_normals must be a boolean")
groups = [(piece["name"], selected)]
if split_normals:
normals = np.cross(selected[:, 1] - selected[:, 0], selected[:, 2] - selected[:, 0])
dominant = np.argmax(np.abs(normals), axis=1)
negative = normals[np.arange(len(normals)), dominant] < 0
direction = 2 * dominant + negative.astype(int)
# Six deterministic normal groups; zero-area triangles go to x_pos
# and are retained. Empty derived groups emit no geometry.
labels = ("x_pos", "x_neg", "y_pos", "y_neg", "z_pos", "z_neg")
groups = [(piece["name"] + "_" + label, selected[direction == group])
for group, label in enumerate(labels) if np.any(direction == group)]
split_components = config.get("split_components", False)
if not isinstance(split_components, bool):
raise ValueError("split_components must be a boolean")
if split_components:
groups = [(name + f"_part{index:03d}", component)
for name, faces in groups
for index, component in enumerate(connected_face_groups(faces))]
if layers > 1:
samples = (sample for name, faces in groups for sample in
axial_layer_points(name, faces, "xyz".index(axis), layers))
else:
samples = ((name, faces.reshape(-1, 3), len(faces)) for name, faces in groups)
for name, points, face_count in samples:
if len(points) == 3:
points = np.concatenate([points, points[:1]])
fit_alignment = alignment
if kind in ("box", "auto") and alignment == "oriented" and np.linalg.matrix_rank(points - points[0]) < 2:
fit_alignment = "link" # AABB also encloses degenerate line/point faces.
center = np.zeros(3)
unit = 1.0
fit_points = points
if kind == "auto" or (kind == "cylinder" and axis is None):
# The shared minimum-cylinder solver optimizes volume with an
# absolute tolerance. SI-sized thin parts otherwise stop at a
# coarse sampled axis. Normalize before fitting, keeping the
# physical padding unchanged when restoring metric dimensions.
center = (points.min(axis=0) + points.max(axis=0)) / 2
unit = float(np.ptp(points, axis=0).max()) or 1.0
fit_points = (points - center) / unit
fit = fitter.fit_primitive(fit_points, kind, allowed=allowed, padding=padding / unit,
scale=scale, cylinder_sample_count=6,
cylinder_angle_tol=1e-7, alignment=fit_alignment, axis=axis)
transform = fit.transform.copy()
transform[:3, 3] = transform[:3, 3] * unit + center
fit = fitter.PrimitiveFit(fit.kind, transform,
tuple(value * unit for value in fit.dimensions),
fit.volume * unit ** 3)
if not np.isfinite(fit.dimensions).all() or min(fit.dimensions) <= 0:
raise ValueError(f"invalid fitted dimensions on {name}")
result.append((name, fit, face_count))
names = [name for name, _, _ in result]
if len(set(names)) != len(names):
raise ValueError("derived normal-group names collide with explicit piece names")
return result

View File

@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Generate xiaozhao collision envelopes using the shared primitive fitter.
Only temporary input mesh URIs are normalized. The original URDF, meshes,
MuJoCo model and shared generator are left untouched.
"""
import argparse
import hashlib
import os
from pathlib import Path
import tempfile
import xml.etree.ElementTree as ET
from collision_pieces import fit_pieces, link_triangles, shared_fitter
from verify_collision import verify
HERE = Path(__file__).resolve().parent
MODEL = HERE.parent
SOURCE = MODEL / "urdf/xiaozhao.urdf"
def parse(path):
return ET.parse(path, parser=ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
def signature(element):
"""Compare XML contents independently of indentation."""
return (element.tag, sorted(element.attrib.items()), (element.text or "").strip(),
[signature(child) for child in element])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=HERE / "xiaozhao_collision.urdf")
parser.add_argument("--config", type=Path, default=HERE / "xiaozhao_collision.toml")
args = parser.parse_args()
output = args.output.resolve()
if output.suffix.lower() != ".urdf":
raise ValueError("output must be a .urdf file, not a mesh, configuration or MuJoCo XML")
if output == SOURCE.resolve():
raise ValueError("output must not overwrite the source URDF")
original = SOURCE.read_bytes()
tree = parse(SOURCE)
root = tree.getroot()
joints = [signature(joint) for joint in root.findall("joint")]
links = [link.get("name") for link in root.findall("link")]
mesh_paths = set()
for mesh in root.iter("mesh"):
# The package name in the CAD export is historical. Resolve each asset
# under this model explicitly, never through the generic package search.
asset = (MODEL / "meshes" / Path(mesh.get("filename", "")).name).resolve()
if not asset.is_file() or asset.parent != (MODEL / "meshes").resolve():
raise FileNotFoundError(f"xiaozhao mesh missing: {asset}")
mesh.set("filename", str(asset))
mesh_paths.add(asset)
fitter = shared_fitter()
config = fitter.load_config(args.config.resolve())
defaults = config.get("defaults", {})
unknown = set(config.get("links", {})) - set(links)
if unknown:
raise ValueError(f"configuration names unknown links: {sorted(unknown)}")
for link in root.findall("link"):
name = link.get("name")
settings = fitter.link_settings(config, name)
if not settings.get("enabled", True):
continue
if not link.findall("collision"):
raise ValueError(f"visual-only link must be explicitly disabled: {name}")
if "pieces" in settings:
fits = fit_pieces(link_triangles(link), settings)
else:
fit, count = fitter._fit_urdf_link(link, SOURCE, config, defaults,
list(fitter.PRIMITIVE_TYPES))
fits = [("envelope", fit, None)]
for collision in list(link.findall("collision")):
link.remove(collision)
for piece_name, fit, face_count in fits:
collision = fitter.create_urdf_collision(fit)
collision.set("name", "collision_" + piece_name)
link.append(collision)
print(f"FIT {name}/{piece_name}: {fit.kind}, "
f"triangles={face_count if face_count is not None else 'whole-link'}")
with tempfile.TemporaryDirectory(prefix="xiaozhao-collision-") as temporary:
work = Path(temporary)
result = work / "collision.urdf"
tree.write(result, encoding="utf-8", xml_declaration=True)
# Audit the retained STL faces and all non-collision fields before publishing.
report = verify(result, 0.001, config)
print(f"Coverage verified: {report['triangles_covered']} complete triangles, "
f"{report['triangles_excluded']} triangles in disabled pieces, "
f"{report['primitive_count']} pieces, margin >= 1 mm")
generated = parse(result)
generated_root = generated.getroot()
if joints != [signature(joint) for joint in generated_root.findall("joint")]:
raise RuntimeError("generated joint definitions differ from source")
if links != [link.get("name") for link in generated_root.findall("link")]:
raise RuntimeError("generated link structure differs from source")
for name in ("tcp-left", "tcp-right"):
link = generated_root.find(f"link[@name='{name}']")
if link is None or link.find("collision") is not None:
raise RuntimeError(f"TCP marker must remain collision-free: {name}")
for mesh in generated_root.iter("mesh"):
asset = Path(mesh.get("filename")).resolve()
if asset not in mesh_paths:
raise RuntimeError(f"unexpected generated mesh path: {asset}")
mesh.set("filename", Path(os.path.relpath(asset, output.parent)).as_posix())
if SOURCE.read_bytes() != original:
raise RuntimeError("source URDF changed during generation")
output.parent.mkdir(parents=True, exist_ok=True)
ET.indent(generated, space=" ")
pending = output.with_name(f".{output.name}.tmp")
generated.write(pending, encoding="utf-8", xml_declaration=True)
os.replace(pending, output)
print(f"Verified {len(mesh_paths)} current xiaozhao mesh assets")
print(f"Preserved {len(joints)} joints, including "
f"{sum(j.get('type') != 'fixed' for j in root.findall('joint'))} movable joints")
print(f"Source SHA256: {hashlib.sha256(original).hexdigest()}")
print(f"Output SHA256: {hashlib.sha256(output.read_bytes()).hexdigest()}")
print(f"Output: {output}")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,477 @@
"""Small geometry counterexamples for complete-face fitting and auditing."""
import copy
import math
from pathlib import Path
import tempfile
import unittest
import xml.etree.ElementTree as ET
import numpy as np
import trimesh
from collision_pieces import (connected_face_groups, fit_pieces, link_triangles,
partition_triangles, shared_fitter)
from verify_collision import best_face_margins, coverage_selection, face_coverage_margins
def box(size, position=(0, 0, 0), rpy=(0, 0, 0)):
collision = ET.Element("collision")
ET.SubElement(collision, "origin", xyz=" ".join(map(str, position)),
rpy=" ".join(map(str, rpy)))
geometry = ET.SubElement(collision, "geometry")
ET.SubElement(geometry, "box", size=" ".join(map(str, size)))
return collision
def cylinder(radius, length, position=(0, 0, 0), rpy=(0, 0, 0)):
collision = ET.Element("collision")
ET.SubElement(collision, "origin", xyz=" ".join(map(str, position)),
rpy=" ".join(map(str, rpy)))
geometry = ET.SubElement(collision, "geometry")
ET.SubElement(geometry, "cylinder", radius=str(radius), length=str(length))
return collision
class CollisionPiecesTest(unittest.TestCase):
def setUp(self):
# The first face's centroid is below x=0.2, although two vertices cross
# that boundary. The second face belongs to the other region.
self.faces = np.array([
[[-0.2, 0.0, 0.0], [0.3, 0.2, 0.0], [0.4, 0.0, 0.1]],
[[0.6, 0.0, 0.0], [0.8, 0.2, 0.0], [0.9, 0.0, 0.1]],
])
self.pieces = [
{"name": "near", "bounds_max": [0.2, math.inf, math.inf]},
{"name": "far", "bounds_min": [0.2, -math.inf, -math.inf]},
]
def test_separately_enclosed_vertices_do_not_cover_a_face(self):
face = np.array([[[-2.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]])
boxes = [box((0.4, 0.4, 0.4), vertex) for vertex in face[0]]
# Every vertex is well inside some box, while the connecting triangle
# passes through empty space. A vertex-wise union test would pass.
point_faces = np.repeat(face[0, :, None, :], 3, axis=1)
np.testing.assert_allclose(best_face_margins(point_faces, boxes), 0.2)
self.assertLess(best_face_margins(face, boxes)[0], 0.0)
def test_fit_keeps_whole_faces_crossing_centroid_region_boundaries(self):
np.testing.assert_array_equal(partition_triangles(self.faces, self.pieces), [0, 1])
fits = fit_pieces(self.faces, {"pieces": self.pieces, "padding": 0.001})
self.assertEqual([count for _, _, count in fits], [1, 1])
# Audit each assigned face against its own fitted body, independently
# of the partitioner. Both out-of-region vertices must remain covered.
for face, (_, fit, _) in zip(self.faces, fits):
collider = shared_fitter().create_urdf_collision(fit)
self.assertGreaterEqual(best_face_margins(face[None], [collider])[0],
0.001 - 1e-10)
def test_half_open_boundary_has_one_owner(self):
faces = np.array([
[[-1, 0, 0], [0, 1, 0], [1, 0, 1]], # centroid x=0
[[-2, 0, 0], [-1, 1, 0], [0, 0, 1]],
], dtype=float)
pieces = [
{"name": "negative", "bounds_max": [0, math.inf, math.inf]},
{"name": "nonnegative", "bounds_min": [0, -math.inf, -math.inf]},
]
np.testing.assert_array_equal(partition_triangles(faces, pieces), [1, 0])
def test_disabled_piece_preserves_its_region_and_other_fits(self):
original = fit_pieces(self.faces, {"pieces": self.pieces})
pieces = [self.pieces[0], {**self.pieces[1], "enabled": False}]
filtered = fit_pieces(self.faces, {"pieces": pieces})
self.assertEqual([(name, count) for name, _, count in filtered], [("near", 1)])
np.testing.assert_array_equal(filtered[0][1].dimensions, original[0][1].dimensions)
np.testing.assert_array_equal(filtered[0][1].transform, original[0][1].transform)
# Disabling "far" must not silently excuse any face outside both regions.
pieces[0] = {**pieces[0], "bounds_min": [-1, -math.inf, -math.inf]}
unassigned = self.faces[0] - [2, 0, 0]
with self.assertRaisesRegex(ValueError, "not assigned"):
fit_pieces(np.array([*self.faces, unassigned]), {"pieces": pieces})
def test_audit_excludes_only_faces_assigned_to_disabled_piece(self):
pieces = [self.pieces[0], {**self.pieces[1], "enabled": False}]
retained, excluded = coverage_selection(self.faces, pieces, ["collision_near"])
np.testing.assert_array_equal(retained, [True, False])
self.assertEqual(excluded, {"far": 1})
# The retained face crosses the region boundary. Its farthest vertex
# is still required when auditing coverage of the remaining collider.
margins, _ = face_coverage_margins(self.faces[retained], [box((0.5, 1, 1))], 0.001)
self.assertLess(margins[0], 0.0)
with self.assertRaises((ValueError, RuntimeError)):
coverage_selection(self.faces, pieces, ["collision_near", "collision_far_slice00"])
def test_axial_layers_follow_a_taper_across_original_triangles(self):
# Every side face spans all three layers. The middle radius therefore
# has to come from intersections on the edges, not original vertices.
ring = np.array([[1, 0, 0], [0, 0, 1], [-1, 0, 0], [0, 0, -1]])
wide = 2 * ring
narrow = ring + [0, 1, 0]
faces = []
for i in range(len(ring)):
j = (i + 1) % len(ring)
faces.extend([[wide[i], wide[j], narrow[i]], [wide[j], narrow[j], narrow[i]]])
settings = {"padding": 0.001, "pieces": [
{"name": "rim", "primitive": "cylinder", "axis": "y", "axial_layers": 3}]}
fits = fit_pieces(np.array(faces), settings)
self.assertEqual([name for name, _, _ in fits],
["rim_slice00", "rim_slice01", "rim_slice02"])
radii, lengths = np.array([fit.dimensions for _, fit, _ in fits]).T
np.testing.assert_allclose(radii, np.array([2, 5 / 3, 4 / 3]) + 0.001)
np.testing.assert_allclose(lengths, 1 / 3 + 0.002)
def test_invalid_partitions_fail_instead_of_discarding_faces(self):
invalid = {
"overlap": [{"name": "all"}, {"name": "again"}],
"disabled_overlap": [{"name": "all"}, {**self.pieces[1], "enabled": False}],
"invalid_enabled": [self.pieces[0], {**self.pieces[1], "enabled": "false"}],
"omission": [self.pieces[0]],
"empty_piece": self.pieces + [{"name": "empty", "bounds_min": [10, 10, 10]}],
"nan_bound": [{"name": "nan", "bounds_min": [math.nan, 0, 0]}],
"duplicate_name": [{"name": "same"}, {"name": "same"}],
"inverted_bounds": [{"name": "inverted", "bounds_min": [1, 0, 0],
"bounds_max": [0, 1, 1]}],
}
for name, pieces in invalid.items():
with self.subTest(name=name), self.assertRaises(ValueError):
partition_triangles(self.faces, pieces)
def test_nonfinite_source_geometry_is_rejected_by_fit_and_audit(self):
faces = self.faces.copy()
faces[0, 1, 2] = math.nan
with self.assertRaises(ValueError):
fit_pieces(faces, {"pieces": self.pieces})
with self.assertRaises(RuntimeError):
best_face_margins(faces, [box((10, 10, 10))])
def test_repeat_fit_preserves_explicit_names_order_and_geometry(self):
settings = {"pieces": list(reversed(self.pieces)), "padding": 0.001}
first = fit_pieces(self.faces, settings)
second = fit_pieces(self.faces.copy(), copy.deepcopy(settings))
self.assertEqual([name for name, _, _ in first], ["far", "near"])
self.assertEqual([name for name, _, _ in second], ["far", "near"])
for (_, a, count_a), (_, b, count_b) in zip(first, second):
self.assertEqual(count_a, count_b)
self.assertEqual(a.kind, b.kind)
np.testing.assert_array_equal(a.dimensions, b.dimensions)
np.testing.assert_array_equal(a.transform, b.transform)
def test_normal_groups_cover_complete_faces_with_stable_names_and_geometry(self):
# Six explicitly oriented faces, supplied in an unrelated order. No
# normal-classification helper is reused to determine the expectations.
faces_by_name = {
"skin_x_pos": [[0, 0, 0], [0, 1, 0], [0, 0, 1]],
"skin_x_neg": [[2, 0, 0], [2, 0, 1], [2, 1, 0]],
"skin_y_pos": [[0, 2, 0], [0, 2, 1], [1, 2, 0]],
"skin_y_neg": [[0, 4, 0], [1, 4, 0], [0, 4, 1]],
"skin_z_pos": [[0, 0, 3], [1, 0, 3], [0, 1, 3]],
"skin_z_neg": [[0, 0, 5], [0, 1, 5], [1, 0, 5]],
}
expected_names = list(faces_by_name)
faces = np.array([faces_by_name[expected_names[index]]
for index in [5, 2, 0, 3, 4, 1]], dtype=float)
settings = {"pieces": [{"name": "skin", "split_normals": True}],
"padding": 0.001}
first = fit_pieces(faces, settings)
second = fit_pieces(faces[::-1].copy(), copy.deepcopy(settings))
self.assertEqual([name for name, _, _ in first], expected_names)
self.assertEqual([name for name, _, _ in second], expected_names)
self.assertEqual(sum(count for _, _, count in first), len(faces))
for (name, a, count_a), (_, b, count_b) in zip(first, second):
self.assertEqual(count_a, 1)
self.assertEqual(count_b, 1)
np.testing.assert_array_equal(a.dimensions, b.dimensions)
np.testing.assert_array_equal(a.transform, b.transform)
collider = shared_fitter().create_urdf_collision(a)
source_face = np.array([faces_by_name[name]], dtype=float)
self.assertGreaterEqual(best_face_margins(source_face, [collider])[0],
0.001 - 1e-10)
def test_normal_split_keeps_degenerate_faces_and_rejects_name_collisions(self):
degenerates = {
"line": [[-1, 0, 0], [0, 0, 0], [1, 0, 0]],
"point": [[2, 3, 4], [2, 3, 4], [2, 3, 4]],
}
for kind, face in degenerates.items():
with self.subTest(degenerate=kind):
faces = np.array([face], dtype=float)
fits = fit_pieces(faces, {"alignment": "oriented", "padding": 0.001,
"pieces": [{"name": "degenerate",
"split_normals": True}]})
self.assertEqual([(name, count) for name, _, count in fits],
[("degenerate_x_pos", 1)])
collider = shared_fitter().create_urdf_collision(fits[0][1])
self.assertGreaterEqual(best_face_margins(faces, [collider])[0],
0.001 - 1e-10)
faces = np.array([
[[-1, 0, 0], [-1, 1, 0], [-1, 0, 1]],
[[1, 0, 0], [1, 1, 0], [1, 0, 1]],
], dtype=float)
pieces = [
{"name": "panel", "split_normals": True,
"bounds_max": [0, math.inf, math.inf]},
{"name": "panel_x_pos", "bounds_min": [0, -math.inf, -math.inf]},
]
with self.subTest(derived_name_conflict=True), self.assertRaisesRegex(ValueError, "names collide"):
fit_pieces(faces, {"pieces": pieces})
for invalid_flag in ("false", 1):
with self.subTest(split_normals=invalid_flag), self.assertRaisesRegex(ValueError, "boolean"):
fit_pieces(faces, {"pieces": [{"name": "panel", "split_normals": invalid_flag}]})
def test_components_preserve_original_faces_and_isolated_degenerates(self):
# Interleave a connected pair with unrelated STL faces. Welding their
# duplicated positions must not reorder or remove the source faces.
faces = np.array([
[[10, 0, 0], [11, 0, 0], [10, 1, 0]],
[[0, 0, 0], [1, 0, 0], [0, 1, 0]],
[[30, 0, 0], [30, 0, 0], [30, 0, 0]],
[[1, 0, 0], [1, 1, 0], [0, 1, 0]],
[[20, 0, 0], [21, 0, 0], [22, 0, 0]],
], dtype=float)
expected_indices = [[0], [1, 3], [2], [4]]
original = faces.copy()
groups = connected_face_groups(faces)
self.assertEqual(len(groups), len(expected_indices))
for group, indices in zip(groups, expected_indices):
np.testing.assert_array_equal(group, faces[indices])
np.testing.assert_array_equal(faces, original)
settings = {"pieces": [{"name": "shell", "split_components": True}],
"padding": 0.001, "alignment": "oriented"}
first = fit_pieces(faces, settings)
second = fit_pieces(faces.copy(), copy.deepcopy(settings))
self.assertEqual([(name, count) for name, _, count in first],
[("shell_part000", 1), ("shell_part001", 2),
("shell_part002", 1), ("shell_part003", 1)])
self.assertEqual(sum(count for _, _, count in first), len(faces))
for (name, a, count_a), (other_name, b, count_b), indices in zip(
first, second, expected_indices):
self.assertEqual((name, count_a), (other_name, count_b))
np.testing.assert_array_equal(a.dimensions, b.dimensions)
np.testing.assert_array_equal(a.transform, b.transform)
collider = shared_fitter().create_urdf_collision(a)
self.assertTrue(np.all(best_face_margins(faces[indices], [collider]) >=
0.001 - 1e-10))
def test_component_split_rejects_invalid_flags_and_derived_name_collision(self):
for invalid_flag in ("false", 1):
with self.subTest(split_components=invalid_flag), self.assertRaisesRegex(ValueError, "boolean"):
fit_pieces(self.faces, {"pieces": [{"name": "panel",
"split_components": invalid_flag}]})
pieces = copy.deepcopy(self.pieces)
pieces[0].update(name="panel", split_components=True)
pieces[1]["name"] = "panel_part000"
with self.assertRaisesRegex(ValueError, "names collide"):
fit_pieces(self.faces, {"pieces": pieces})
def test_auto_fits_a_tilted_cylinder_and_keeps_complete_face_padding(self):
# Build a closed, triangulated tube without using the fitting helpers.
# Its known axis is oblique to every link axis, so a fixed-axis fit
# cannot accidentally satisfy the orientation and coverage assertions.
segments = 32
angles = np.arange(segments) * (2 * math.pi / segments)
ring = np.column_stack([0.01 * np.cos(angles), 0.01 * np.sin(angles)])
vertices = np.concatenate([
np.column_stack([ring, np.full(segments, -0.05)]),
np.column_stack([ring, np.full(segments, 0.05)]),
[[0, 0, -0.05], [0, 0, 0.05]],
])
indices = []
for index in range(segments):
following = (index + 1) % segments
indices.extend([
[index, following, following + segments],
[index, following + segments, index + segments],
[2 * segments, following, index],
[2 * segments + 1, index + segments, following + segments],
])
expected_axis = np.array([1.0, 2.0, 3.0]) / math.sqrt(14)
radial_axis = np.array([2.0, -1.0, 0.0]) / math.sqrt(5)
rotation = np.column_stack([radial_axis,
np.cross(expected_axis, radial_axis),
expected_axis])
transformed = vertices @ rotation.T + np.array([0.12, -0.07, 0.03])
faces = transformed[np.asarray(indices)]
piece = {"name": "wire", "primitive": "auto", "axis": "auto",
"allowed_primitives": ["box", "cylinder"]}
settings = {"pieces": [piece], "alignment": "oriented", "padding": 0.001}
[(name, fit, count)] = fit_pieces(faces, settings)
self.assertEqual((name, fit.kind, count), ("wire", "cylinder", 4 * segments))
fitted_axis = fit.transform[:3, 2]
self.assertGreater(abs(float(fitted_axis @ expected_axis)), 0.999)
self.assertLess(float(np.max(np.abs(fitted_axis))), 0.95)
collider = shared_fitter().create_urdf_collision(fit)
self.assertTrue(np.all(best_face_margins(faces, [collider]) >= 0.001 - 1e-9))
# Changing the length unit must preserve the chosen shape, including
# its physical padding. Compare axes up to their equivalent sign.
[(scaled_name, scaled_fit, scaled_count)] = fit_pieces(
faces * 10, {**settings, "padding": 0.01})
self.assertEqual((scaled_name, scaled_fit.kind, scaled_count),
(name, fit.kind, count))
np.testing.assert_allclose(np.array(scaled_fit.dimensions) / 10,
fit.dimensions, rtol=1e-4, atol=1e-8)
np.testing.assert_allclose(scaled_fit.transform[:3, 3] / 10,
fit.transform[:3, 3], rtol=1e-4, atol=1e-8)
scaled_axis = scaled_fit.transform[:3, 2]
aligned_axis = scaled_axis * np.sign(scaled_axis @ fitted_axis)
np.testing.assert_allclose(aligned_axis, fitted_axis, rtol=1e-4, atol=1e-4)
for invalid in ({"allowed_primitives": []}, {"axis": "diagonal"}):
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
fit_pieces(faces, {**settings, "pieces": [{**piece, **invalid}]})
def test_rotated_translated_box_margin_matches_local_geometry(self):
local = np.array([[[0.8, 0, 0], [0, 0.1, 0.2], [-0.6, -0.2, 0]]])
# Rz(pi/2) Rx(pi/2), calculated explicitly rather than using the
# verifier's origin parser to manufacture its own expected result.
rotation = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
position = np.array([3, -2, 1])
world = local @ rotation.T + position
collider = box((2, 0.8, 0.6), position, (math.pi / 2, 0, math.pi / 2))
np.testing.assert_allclose(best_face_margins(world, [collider]), [0.1], atol=1e-12)
def test_rotated_cylinder_checks_radial_and_end_cap_margins(self):
local = np.array([
[[0.4, 0, 0], [0, 0.2, 0.8], [-0.2, 0, 0]],
[[0.1, 0, 0.95], [0, 0.2, 0.8], [-0.2, 0, 0.5]],
])
rotation = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])
position = np.array([-2, 3, 4])
world = local @ rotation.T + position
collider = cylinder(0.5, 2, position, (0, math.pi / 2, 0))
expected = [0.1, 0.05]
np.testing.assert_allclose(best_face_margins(world, [collider]), expected, atol=1e-12)
np.testing.assert_allclose(best_face_margins(world, [collider], batch_size=1),
expected, atol=1e-12)
def test_source_visual_scale_and_origin_are_applied_before_partitioning(self):
vertices = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=float)
with tempfile.TemporaryDirectory(prefix="xiaozhao-piece-test-") as directory:
mesh_path = Path(directory) / "triangle.stl"
trimesh.Trimesh(vertices=vertices, faces=[[0, 1, 2]], process=False).export(mesh_path)
link = ET.Element("link", name="fixture")
visual = ET.SubElement(link, "visual")
ET.SubElement(visual, "origin", xyz="1 2 3", rpy=f"0 0 {math.pi / 2}")
geometry = ET.SubElement(visual, "geometry")
ET.SubElement(geometry, "mesh", filename=str(mesh_path), scale="2 3 4")
expected = np.array([[[1, 4, 3], [-2, 2, 3], [1, 2, 7]]])
np.testing.assert_allclose(link_triangles(link), expected, atol=1e-12)
def test_invalid_primitive_dimensions_and_origins_fail_audit(self):
invalid = [box((1, 0, 1)), box((math.nan, 1, 1)), cylinder(-1, 2),
cylinder(1, math.inf), box((1, 1, 1), rpy=(math.nan, 0, 0))]
for collider in invalid:
with self.subTest(collider=ET.tostring(collider)), self.assertRaises(RuntimeError):
best_face_margins(self.faces, [collider])
class AxialSliceCoverageTest(unittest.TestCase):
"""Independent fixtures: no generation/partition/clipping helper is used."""
def slices(self, gap=0.0, padding=0.1):
pieces = [cylinder(1.1, 1 + 2 * padding - gap, (0, 0, center))
for center in (-0.5, 0.5)]
for index, piece in enumerate(pieces):
piece.set("name", f"collision_test_ring_slice{index:02d}")
return pieces
def crossing_triangle(self):
return np.array([[[-0.6, 0.0, -0.8], [0.6, 0.0, 0.8],
[0.1, 0.4, 0.6]]])
def test_complete_crossing_triangle_is_proved_and_counted_once(self):
faces, pieces = self.crossing_triangle(), self.slices()
self.assertLess(best_face_margins(faces, pieces)[0], 0.1)
margins, rescued = face_coverage_margins(faces, pieces, 0.1)
self.assertEqual(rescued, 1)
self.assertGreaterEqual(margins[0], 0.1 - 1e-12)
# Choosing a CLI margin below fitting padding must keep the proof valid.
for margin in (0.0, 0.05):
with self.subTest(required_margin=margin):
margins, rescued = face_coverage_margins(faces, pieces, margin)
self.assertEqual(rescued, 1)
self.assertGreaterEqual(margins[0], margin - 1e-12)
def test_vertex_coverage_cannot_hide_a_real_seam_gap(self):
faces = self.crossing_triangle()
# The two physical cylinders have an actual 0.1 m gap. Every original
# vertex nevertheless has 0.1 m clearance in some cylinder.
pieces = self.slices(gap=0.3)
vertex_faces = np.repeat(faces[0, :, None, :], 3, axis=1)
self.assertTrue(np.all(best_face_margins(vertex_faces, pieces) >= 0.1))
margins, rescued = face_coverage_margins(faces, pieces, 0.1)
self.assertEqual(rescued, 0)
self.assertLess(margins[0], 0.1 - 1e-9)
def test_padding_seam_and_sub_nanometer_tolerance_are_not_silent_gaps(self):
faces = self.crossing_triangle()
# A 6 nm missing band at the required inset must be rejected; only the
# documented 1 nm point-to-surface comparison tolerance is allowed.
for gap in (0.01, 6e-9):
with self.subTest(gap=gap):
margins, rescued = face_coverage_margins(faces, self.slices(gap=gap), 0.1)
self.assertEqual(rescued, 0)
self.assertLess(margins[0], 0.1 - 1e-9)
def test_radial_hole_between_covered_original_vertices_is_rejected(self):
pieces = self.slices()
pieces[0].find("geometry/cylinder").set("radius", "0.35")
faces = np.array([[[0.1, 0, -0.8], [0.9, 0, 0.8], [0.8, 0.1, 0.7]]])
vertex_faces = np.repeat(faces[0, :, None, :], 3, axis=1)
self.assertTrue(np.all(best_face_margins(vertex_faces, pieces) >= 0.1 - 1e-12))
margins, rescued = face_coverage_margins(faces, pieces, 0.1)
self.assertEqual(rescued, 0)
self.assertLess(margins[0], 0.1 - 1e-9)
def test_only_explicit_contiguous_same_group_cylinder_names_enable_union(self):
invalid_names = [
["ordinary_lower", "ordinary_upper"],
["collision_ring_slice0", "collision_ring_slice1"],
["collision_ring_slice00", "collision_ring_slice02"],
["collision_first_slice00", "collision_second_slice01"],
]
for names in invalid_names:
pieces = self.slices()
for piece, name in zip(pieces, names):
piece.set("name", name)
with self.subTest(names=names):
margins, rescued = face_coverage_margins(self.crossing_triangle(), pieces, 0.1)
self.assertEqual(rescued, 0)
np.testing.assert_array_equal(margins, best_face_margins(self.crossing_triangle(), pieces))
def test_rotated_translated_group_uses_each_actual_radial_center(self):
faces, pieces = self.crossing_triangle(), self.slices()
# Explicit Ry(pi/2): common cylinder axis is now world X. Give the
# second slice a distinct radial center, larger than numerical noise.
rotation = np.array([[0, 0, 1], [0, 1, 0], [-1, 0, 0]])
translation = np.array([3., -2., 4.])
world_faces = faces @ rotation.T + translation
for index, (piece, axial_center) in enumerate(zip(pieces, (-0.5, 0.5))):
center = rotation @ np.array([0.02 * index, 0., axial_center]) + translation
piece.find("origin").set("xyz", " ".join(map(str, center)))
piece.find("origin").set("rpy", f"0 {math.pi / 2} 0")
margins, rescued = face_coverage_margins(world_faces, pieces, 0.1)
self.assertEqual(rescued, 1)
self.assertGreaterEqual(margins[0], 0.1 - 1e-12)
def test_plain_whole_face_and_degenerate_line_keep_their_proofs(self):
pieces = self.slices()
whole_face = np.array([[[0, 0, -0.8], [0.2, 0, -0.6], [0, 0.1, -0.3]]])
margins, rescued = face_coverage_margins(whole_face, pieces, 0.1)
self.assertEqual(rescued, 0)
np.testing.assert_array_equal(margins, best_face_margins(whole_face, pieces))
line = np.array([[[0, 0, -0.8], [0, 0, 0.8], [0, 0, 0.8]]])
margins, rescued = face_coverage_margins(line, pieces, 0.1)
self.assertEqual(rescued, 1)
self.assertGreaterEqual(margins[0], 0.1 - 1e-12)
margins, rescued = face_coverage_margins(line, self.slices(gap=0.3), 0.1)
self.assertEqual(rescued, 0)
self.assertLess(margins[0], 0.1 - 1e-9)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,789 @@
{
"validation_date": "2026-11-18",
"status": "Each link7 retains four collision pieces after excluding its plate_body and adapter boxes. The retained STL surfaces passed the 1 mm coverage check.",
"source_urdf": "model/xiaozhao/urdf/xiaozhao.urdf",
"source_urdf_sha256": "d9d371b29aaea3477c5895f63f72debbb64613c4ffeac7918f6cca3e77765b65",
"published_urdf": "model/xiaozhao/collision/xiaozhao_collision.urdf",
"published_urdf_sha256": "8dd44595bbe8fe2f6e9c31a463a00d1152bc05dcaeb9bd640e0e4d8999460d0f",
"total_collision_pieces": 34,
"per_arm_geometry_count": {
"left": 18,
"right": 18
},
"scope": "Independent static single-arm Coal/CollisionChecker evaluation; no GUI/live service/robot commands; default same-joint/direct-parent exclusions only; no ignored_pairs.",
"zero_reference": {
"changed_joints": [
"joint3-left",
"joint5-left",
"joint3-right",
"joint5-right"
],
"local_axis_offset_rad": 3.141592653589793,
"origin_rotation": "R_new=R_old*Rz(pi)",
"same_physical_pose_mapping": "q_new=wrap(q_old-pi) for J3/J5, unchanged others",
"all_link_local_geometry_and_inertia_unchanged": true,
"joint_axes_and_numeric_limits_unchanged": true,
"touch_initialization_same_physical_pose": true,
"touch_right_joint3_rad": 2.727417567789793,
"touch_right_joint5_rad": 1.810335360989793,
"historical_zero_note": "Old J3/J5=0 maps to +/-pi, just outside current +/-3.14 limits; use only for offline equivalence checks.",
"scope": "Records the preceding zero-reference change before the shoulder-ring refinement below."
},
"kinematics_validation": {
"source": {
"comparisons": 380,
"mapping": "q_old=wrap(q_new+pi) for bilateral J3/J5; unchanged others",
"max_rotation_error_rad": 8.800093355403147e-16,
"max_translation_error_m": 4.032327312544114e-16,
"new_urdf": "/home/lgv/cmvr/0-workspace/cmvr-es/model/xiaozhao/urdf/xiaozhao.urdf",
"old_urdf": "/tmp/xiaozhao_zero_before/source.urdf",
"passed": true,
"case_count": 19,
"scope": "19 static poses including new zero, historical zero/touch and 16 general configurations; every link/TCP; FK only, not limit/path acceptance."
},
"collision": {
"comparisons": 380,
"mapping": "q_old=wrap(q_new+pi) for bilateral J3/J5; unchanged others",
"max_rotation_error_rad": 8.800093355403147e-16,
"max_translation_error_m": 4.032327312544114e-16,
"new_urdf": "/home/lgv/cmvr/0-workspace/cmvr-es/model/xiaozhao/collision/xiaozhao_collision.urdf",
"old_urdf": "/tmp/xiaozhao_zero_before/collision.urdf",
"passed": true,
"case_count": 19,
"scope": "19 static poses including new zero, historical zero/touch and 16 general configurations; every link/TCP; FK only, not limit/path acceptance."
},
"mujoco": {
"native_version": "3.3.7",
"nq": 17,
"njnt": 17,
"nu": 17,
"ncam": 2,
"methods": "mj_loadXML, mj_makeData, mj_resetData, mj_forward; no mj_step",
"source_hashes": {
"urdf/xiaozhao.urdf": "61193a5a9e926165f75b87ca4d69a1e4bae891f1cf132dc9d8a0a4e2338f063b",
"xml/xiaozhao.xml": "b1d76ccbbee0c05b393b2db64353f2b5f92ede47e813a3931e83d4299171fa8f",
"xml/scene.xml": "a3e021da1416bdf5000b40491833985dfe8bb43808f975e952eb4d3d30d115bc",
"xml/hand_camera.xml": "baa637ab4d22fb443e9aa501009fbec13c512a2418e4d5f359d388d62820d40d",
"xml/head_camera.xml": "1bc0f33a2ce56c9493e88fcff69e90b534e98dc5d6763a9bbabe9292f27c301f",
"xml/actuators.xml": "dc798a87f444a306642dba1257e4b44840d7e3bccb21f9d4c5de0071b8ae40ee"
},
"position_tolerance_m": 1e-05,
"rotation_tolerance_rad": 2e-05,
"limits_note": "Historical-equivalent coordinates may be outside numeric limits; FK only, no stepping or commands.",
"fixed_head_between_arm_poses": {
"translation_error_m": 0.0,
"rotation_error_rad": 0.0
},
"max_translation_error_m": 5.326670709696408e-07,
"max_rotation_error_rad": 1.2007192857770254e-06,
"passed": true,
"report": "/tmp/xiaozhao_zero_native_validation.json",
"case_count": 2
}
},
"mesh_sha256": {
"base_link.STL": "2fdd0b0d3fdaed9ab17eac5870b1026513d544b5c4963808abe3f9e90c3c33c7",
"link1-left.STL": "4a171f7985e324f3dc536d1f5909efc65dc0c9326f46f98131bd8f85260b551d",
"link1-right.STL": "28550e0f2cd66b06175aaca3b1c7bdda62e10b947aaed015121041bd43e46deb",
"link2-left.STL": "19f89071892e642b9a67745e09f6bad7ce4297d3652c4dd63a70adc20946d088",
"link2-right.STL": "0e6888b4089046cbdd8959829294829bb5792f699413f1485c7ee83b990b4f6f",
"link3-left.STL": "321d53bbcd65d8fb5e3e678c93bc2b832e29f067e4965956d752248ce0589fba",
"link3-right.STL": "bfaa104792529e280f373621e4281684faa5a1b2012e7f7aead909d3bcd72e2e",
"link4-left.STL": "7321111ef3c363004278c6ab88c67e43291b7052413319afa59f4e1b9f65bc78",
"link4-right.STL": "77a4eaf24f438fa7af172522420452c46b5c3371e894de0829b8d9f322417499",
"link5-left.STL": "dcfa389745a9893771e2473f6437cf38c49d2e3cb85ba5a9ed6333c04059b734",
"link5-right.STL": "75fdd5b7a69cf9bb5541ac827f7df4633fe9bfc440cf97407e3f57b06558fcf7",
"link6-left.STL": "5751e5b18aded2fd1f4d25c3bfc46e338c24545df28dddf21b4303d9efc3c10b",
"link6-right.STL": "ace2f885bd95bd42370a6039dbf60f100d051aff9455f49535074196e7d5e0ef",
"link7-left.STL": "26d7edb3fb8e52e31ae0e134656ac3e019f11f54d0742ff2c74a46a312beb8d2",
"link7-right.STL": "662ac6ba5002ac897f3ceafeab9a7c1d11d7321fdcae6ff572222ccba3c69bd9",
"neck_Link1.STL": "f6ae5e8b5ed87be05891e3eecc8f244472a5b191eaa84b4719db04c8b22be1b1",
"neck_Link2.STL": "d5c04d90019d4ce0e11cc55d85e0db6926a7e6f22a787399fcb0941de99c05c9",
"neck_Link3.STL": "05245467e1f49487d2b0d4fa8d2d280d60587859456278ea970267c0ce4da074"
},
"coverage_verification": {
"status": "passed",
"source": "model/xiaozhao/urdf/xiaozhao.urdf",
"collision": "model/xiaozhao/collision/xiaozhao_collision.urdf",
"source_sha256": "d9d371b29aaea3477c5895f63f72debbb64613c4ffeac7918f6cca3e77765b65",
"collision_sha256": "8dd44595bbe8fe2f6e9c31a463a00d1152bc05dcaeb9bd640e0e4d8999460d0f",
"joints_preserved": 19,
"movable_joints_preserved": 17,
"all_non_collision_fields_preserved": true,
"visual_asset_resolution": "absolute or URDF-relative paths; verified current model assets",
"primitive_count": 34,
"vertices_checked": 4155552,
"triangles_covered": 1385184,
"triangles_excluded": 24496,
"triangles_covered_by_slice_union": 0,
"required_margin_m": 0.001,
"minimum_margin_m": 0.000999999999724041,
"coverage_scope": "each retained current source STL triangle fits inside one convex primitive, or is fully partitioned into closed subfaces covered by an explicitly named parallel-axis cylinder-slice group, with the required margin. Explicitly disabled piece regions are counted separately.",
"solid_volume_coverage_validated": false,
"pose_or_path_safety_validated": false,
"links": [
{
"link": "base_link",
"primitive_count": 5,
"pieces": [
"collision_foot",
"collision_lower_torso",
"collision_upper_torso",
"collision_shoulder_middle",
"collision_neck_mount"
],
"vertices_checked": 2243172,
"triangles_covered": 747724,
"triangles_excluded": 464,
"excluded_pieces": {
"negative_shoulder_ring": 232,
"positive_shoulder_ring": 232
},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.000999999999808595
},
{
"link": "link1-left",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 173280,
"triangles_covered": 57760,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0010000000000075504
},
{
"link": "link2-left",
"primitive_count": 2,
"pieces": [
"collision_elbow_transition",
"collision_distal_housing"
],
"vertices_checked": 195825,
"triangles_covered": 65275,
"triangles_excluded": 10493,
"excluded_pieces": {
"proximal_back": 5316,
"proximal_lower_cap": 2816,
"proximal_upper_cap": 2361
},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999998671627
},
{
"link": "link3-left",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 112104,
"triangles_covered": 37368,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999997630932
},
{
"link": "link4-left",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 135270,
"triangles_covered": 45090,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.000999999999791057
},
{
"link": "link5-left",
"primitive_count": 3,
"pieces": [
"collision_negative_cheek",
"collision_core",
"collision_positive_cheek"
],
"vertices_checked": 160836,
"triangles_covered": 53612,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999998587111
},
{
"link": "link6-left",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 64398,
"triangles_covered": 21466,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999999557516
},
{
"link": "link7-left",
"primitive_count": 4,
"pieces": [
"collision_plate_round_end",
"collision_palm_root",
"collision_palm",
"collision_fingers"
],
"vertices_checked": 59871,
"triangles_covered": 19957,
"triangles_excluded": 1522,
"excluded_pieces": {
"plate_body": 238,
"adapter": 1284
},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.000999999999998709
},
{
"link": "link1-right",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 170694,
"triangles_covered": 56898,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0010000000000060447
},
{
"link": "link2-right",
"primitive_count": 2,
"pieces": [
"collision_distal_housing",
"collision_elbow_transition"
],
"vertices_checked": 197121,
"triangles_covered": 65707,
"triangles_excluded": 10495,
"excluded_pieces": {
"proximal_back": 5314,
"proximal_lower_cap": 2817,
"proximal_upper_cap": 2364
},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999998041437
},
{
"link": "link3-right",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 112104,
"triangles_covered": 37368,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999999437265
},
{
"link": "link4-right",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 135084,
"triangles_covered": 45028,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999998204223
},
{
"link": "link5-right",
"primitive_count": 3,
"pieces": [
"collision_negative_cheek",
"collision_core",
"collision_positive_cheek"
],
"vertices_checked": 160848,
"triangles_covered": 53616,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999997495415
},
{
"link": "link6-right",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 64398,
"triangles_covered": 21466,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999999557585
},
{
"link": "link7-right",
"primitive_count": 4,
"pieces": [
"collision_fingers",
"collision_palm",
"collision_palm_root",
"collision_plate_round_end"
],
"vertices_checked": 59871,
"triangles_covered": 19957,
"triangles_excluded": 1522,
"excluded_pieces": {
"adapter": 1284,
"plate_body": 238
},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999999987064
},
{
"link": "neck_Link1",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 18150,
"triangles_covered": 6050,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.000999999999724041
},
{
"link": "neck_Link2",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 12834,
"triangles_covered": 4278,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999999872992
},
{
"link": "neck_Link3",
"primitive_count": 1,
"pieces": [
"collision_envelope"
],
"vertices_checked": 79692,
"triangles_covered": 26564,
"triangles_excluded": 0,
"excluded_pieces": {},
"triangles_covered_by_slice_union": 0,
"minimum_margin_m": 0.0009999999998456521
}
]
},
"regression_tests": {
"collision_checker_cpp_tests_passed": 24,
"failed": 0,
"touch_config_protobuf_parse": "passed",
"python_piece_tests_passed": 25
},
"viewer": {
"visual_geometries_loaded": 20,
"collision_geometries_loaded": 34,
"joint_pose": "current zero",
"verification": "Loaded all visual and collision shapes using the MeshCat viewer geometry loader and calculated zero-pose link transforms offline."
},
"historical_reference": {
"candidate_urdf": "/tmp/xiaozhao_multipart_candidate_v8_3b13dfd7f164.urdf",
"candidate_sha256": "3b13dfd7f1645ec44c2cdc36f64d44d7c49f4fb018a011da32d90a4c081da29e",
"total_collision_pieces": 118,
"scope": "Independent static single-arm Coal/CollisionChecker evaluation; no GUI/live service/robot commands; default same-joint/direct-parent exclusions only; no ignored_pairs.",
"status": "Multipart geometry implemented and validated; online monitoring not accepted/enabled because shoulder padding still overlaps and old Cartesian presets retain wrist envelope false positives.",
"sampling_seed": 20261118,
"random_samples_per_arm": 20,
"note_on_penetration": "Primitive signed distances describe overlap of conservative padded envelopes, not penetration depth of physical robot/CAD solids. The frozen right-touch pose separately has confirmed original-STL triangle intersection.",
"test_file": "cmvr-es/algorithms/collision_detection/test/collision_checker_test.cpp",
"regression_scope": "Original kinematics with generated multi-piece geometry; per-arm body filtering; multi-piece base/link2/link5/link7; isolated original-FK wrists free at zero; fixed known right-wrist interference remains detected without ignored_pairs.",
"left": {
"geometry_count": 95,
"piece_counts_by_link": {
"base_link": 7,
"link1-left": 1,
"link2-left": 5,
"link3-left": 1,
"link4-left": 1,
"link5-left": 73,
"link6-left": 1,
"link7-left": 6
},
"active_geometry_pairs": 1621,
"query_performance": {
"description": "Warm-cache CollisionChecker::check(q), including FK and all active geometry pairs, 200 calls cycling fixed-seed random poses; observational timing, no real-time guarantee.",
"max_us": 871.455,
"mean_us": 635.9070649999999,
"p50_us": 628.939,
"p95_us": 760.0,
"query_count": 200
},
"v1_query_performance": {
"description": "Warm-cache CollisionChecker::check(q), including FK and all active geometry pairs, 200 calls cycling fixed-seed random poses; observational timing, no real-time guarantee.",
"max_us": 240.835,
"mean_us": 96.93720499999998,
"p50_us": 93.943,
"p95_us": 112.909,
"query_count": 200
},
"sampled_collision_count": 20,
"sampled_free_count": 0,
"fixed_pose_comparison_mm": {
"old_cartesian_preset": {
"shoulder": -0.2502056410389741,
"wrist": -7.271149478559156,
"global": -7.271149478559156,
"v1_shoulder": -62.43173855967542,
"v1_wrist": -68.14863275342276,
"original_mesh_near_pairs": [
{
"first": "base_link",
"second": "link2-left",
"distance_mm": 2.404919458077736
},
{
"first": "link5-left",
"second": "link7-left",
"distance_mm": 10.93613352603968
}
]
},
"zero": {
"shoulder": -0.25020404759313963,
"wrist": 0.04515181500262932,
"global": -0.25020404759313963,
"v1_shoulder": -43.21676718821117,
"v1_wrist": -40.40821273239367,
"original_mesh_near_pairs": [
{
"first": "base_link",
"second": "link2-left",
"distance_mm": 2.324303727315741
},
{
"first": "link5-left",
"second": "link7-left",
"distance_mm": 3.066347385789243
}
]
}
}
},
"right": {
"geometry_count": 27,
"piece_counts_by_link": {
"base_link": 7,
"link1-right": 1,
"link2-right": 5,
"link3-right": 1,
"link4-right": 1,
"link5-right": 5,
"link6-right": 1,
"link7-right": 6
},
"active_geometry_pairs": 261,
"query_performance": {
"description": "Warm-cache CollisionChecker::check(q), including FK and all active geometry pairs, 200 calls cycling fixed-seed random poses; observational timing, no real-time guarantee.",
"max_us": 260.37,
"mean_us": 198.32299500000005,
"p50_us": 188.898,
"p95_us": 249.219,
"query_count": 200
},
"v1_query_performance": {
"description": "Warm-cache CollisionChecker::check(q), including FK and all active geometry pairs, 200 calls cycling fixed-seed random poses; observational timing, no real-time guarantee.",
"max_us": 174.102,
"mean_us": 96.20344999999999,
"p50_us": 93.412,
"p95_us": 106.687,
"query_count": 200
},
"sampled_collision_count": 20,
"sampled_free_count": 0,
"fixed_pose_comparison_mm": {
"current_touch_initialization": {
"shoulder": -0.25018482622374627,
"wrist": -32.74487186644071,
"global": -32.74487186644071,
"v1_shoulder": -64.94093050226273,
"v1_wrist": -82.21221592348202,
"original_mesh_near_pairs": [
{
"first": "base_link",
"second": "link2-right",
"distance_mm": 2.334969492719822
},
{
"first": "link5-right",
"second": "link7-right",
"distance_mm": 0.0
}
]
},
"old_cartesian_preset": {
"shoulder": -0.25018897581179694,
"wrist": -7.2712323776026295,
"global": -7.2712323776026295,
"v1_shoulder": -62.43195906964794,
"v1_wrist": -68.14972818863303,
"original_mesh_near_pairs": [
{
"first": "base_link",
"second": "link2-right",
"distance_mm": 2.4049707172922976
}
]
},
"zero": {
"shoulder": -0.2501910013153098,
"wrist": 0.04410592127675109,
"global": -0.2501910013153098,
"v1_shoulder": -43.21640062415096,
"v1_wrist": -40.408143919355155,
"original_mesh_near_pairs": [
{
"first": "base_link",
"second": "link2-right",
"distance_mm": 2.3245148211764874
},
{
"first": "link5-right",
"second": "link7-right",
"distance_mm": 7.185779012675438
}
]
}
}
},
"artifacts": [
{
"path": "/tmp/cmvr_xiaozhao_multipart_v8_report.json",
"bytes": 1399281
},
{
"path": "/tmp/xiaozhao_multipart_candidate_v8_3b13dfd7f164.urdf",
"bytes": 51859
},
{
"path": "/tmp/cmvr_xiaozhao_shoulder_no_padding_DIAGNOSTIC_ONLY_report.json",
"bytes": 2790111
}
],
"validation_date": "2026-11-18",
"source_urdf": "model/xiaozhao/urdf/xiaozhao.urdf",
"source_urdf_sha256": "7f11ff9c72e79043262bcb2b2d1da41ecc1c111e9237f3589c1637e2a1208d1e",
"published_urdf": "model/xiaozhao/collision/xiaozhao_collision.urdf",
"published_urdf_sha256": "7696c636ea4ebac3cf533989b36b35523f9f2e610460813958b6c99bb132155f",
"candidate_matches_published_except_visual_uri_spelling": true,
"repeated_generation_identical": true,
"regression_tests": {
"python_piece_tests_passed": 15,
"collision_checker_cpp_tests_passed": 24,
"failed": 0
},
"shoulder_padding_diagnostic": {
"formal_padding_m": 0.001,
"diagnostic_only_formal_model_unchanged": true,
"unpadded_shoulder_distance_range_m": [
0.002299698,
0.002300177
],
"padded_shoulder_distance_approx_m": -0.0002502,
"report": "/tmp/cmvr_xiaozhao_shoulder_no_padding_DIAGNOSTIC_ONLY_report.json",
"note": "Temporary shoulder-only comparison; formal 1 mm padding, task thresholds and touch initialization remain unchanged."
},
"coordinate_convention": "Before bilateral J3/J5 +pi zero correction; zero and old_cartesian_preset are OLD coordinates, not current all-zero or executable presets.",
"applicability": "Same physical poses retain the same geometry under q_new=wrap(q_old-pi). Old sample coordinates must also be remapped; no current-zero collision-free claim."
},
"shoulder_ring_refinement": {
"baseline_urdf_sha256": "42d625eb83d7ea833bd362e579a96fedfa317d9ea2b6669d1c7a4e0bad23417f",
"links": [
"base_link"
],
"rings": [
"negative_shoulder_ring",
"positive_shoulder_ring"
],
"axial_layers_per_ring": 3,
"full_radius_axial_retreat_m": 0.000666668,
"padding_m": 0.001,
"measurements": {
"left": {
"fixed_shoulder_gaps_m": {
"zero": 8.313462936289017e-05
},
"j1_j2_grid": {
"shape": [
9,
9
],
"shoulder_overlaps_before": 81,
"shoulder_overlaps_after": 18,
"within_5mm_after": 81,
"at_joint2_limits_rad": [
-1.57,
1.57
],
"worst_shoulder_gap_m": -0.005342587685940273
}
},
"right": {
"fixed_shoulder_gaps_m": {
"zero": 8.373268210925313e-05,
"current_touch_initialization": 8.314585300650226e-05
},
"j1_j2_grid": {
"shape": [
9,
9
],
"shoulder_overlaps_before": 81,
"shoulder_overlaps_after": 18,
"within_5mm_after": 81,
"at_joint2_limits_rad": [
-1.57,
1.57
],
"worst_shoulder_gap_m": -0.005342243938482569
}
}
},
"scope": "Historical results for the model with shoulder rings. Per-arm base/link2 only. At both joint2 limits the link2 proximal_back proxy also intersects the original base STL. All grid samples are within the configured 5 mm stop distance.",
"evaluated_urdf_sha256": "1ddef92810d232aabc733d5550e1e4fb627a6551e1a82281d95573b3abbc5c48"
},
"joint4_limit_update": {
"left_rad": [
0,
2.35
],
"right_rad": [
-2.35,
0
],
"note": "Only the two J4 limits changed. Records of positive right J4 touch poses below or in earlier reports are offline geometric references outside the current motion limits."
},
"shoulder_ring_removal": {
"previous_urdf_sha256": "1ddef92810d232aabc733d5550e1e4fb627a6551e1a82281d95573b3abbc5c48",
"removed_cylinders": 6,
"all_other_urdf_bytes_identical": true,
"base_link2_distances": {
"left": {
"zero_gap_m": 0.000299717291248955,
"j1_j2_grid_samples": 81,
"grid_overlaps": 18,
"minimum_grid_gap_m": -0.004543009623718781
},
"right": {
"zero_gap_m": 0.0003003166253852666,
"j1_j2_grid_samples": 81,
"grid_overlaps": 18,
"minimum_grid_gap_m": -0.004542775243240373
}
},
"evaluated_urdf_sha256": "c1e1e907cd10eb2e829b1a3c2650ecdf46b9236dbfe58cdc0c53b1b3766616d6",
"scope": "Historical measurements after removing the base shoulder rings, before removing link2 cylinders."
},
"link2_cylinder_removal": {
"previous_urdf_sha256": "c1e1e907cd10eb2e829b1a3c2650ecdf46b9236dbfe58cdc0c53b1b3766616d6",
"removed_pieces_per_link": [
"proximal_back",
"proximal_lower_cap"
],
"links": [
"link2-left",
"link2-right"
],
"removed_cylinders": 4,
"all_other_urdf_bytes_identical": true,
"base_link2_distances": {
"left": {
"zero_gap_m": 0.00030033278632804965,
"j1_j2_grid_samples": 81,
"grid_overlaps": 0,
"within_5mm": 81,
"minimum_grid_gap_m": 0.0002998138035813176
},
"right": {
"zero_gap_m": 0.0003004355680381605,
"j1_j2_grid_samples": 81,
"grid_overlaps": 0,
"within_5mm": 81,
"minimum_grid_gap_m": 0.0002997083300199327
}
},
"evaluated_urdf_sha256": "92336310fe1c01f6eea14c37a868d36720b67fd3f4f428080a74ab811d24721f",
"scope": "Historical measurements with the proximal upper caps retained on both link2 assemblies."
},
"link2_upper_cap_removal": {
"previous_urdf_sha256": "92336310fe1c01f6eea14c37a868d36720b67fd3f4f428080a74ab811d24721f",
"removed_pieces_per_link": [
"proximal_upper_cap"
],
"links": [
"link2-left",
"link2-right"
],
"removed_cylinders": 2,
"all_other_urdf_bytes_identical": true,
"base_link2_distances": {
"left": {
"zero_gap_m": 0.08051480410203748,
"j1_j2_grid_samples": 81,
"grid_overlaps": 0,
"within_5mm": 18,
"minimum_grid_gap_m": 0.0024552578960203453
},
"right": {
"zero_gap_m": 0.08051293467189549,
"j1_j2_grid_samples": 81,
"grid_overlaps": 0,
"within_5mm": 18,
"minimum_grid_gap_m": 0.0024556033435989633
}
},
"evaluated_urdf_sha256": "a81788def90bae7241ad1808a67b28a8dd318405e41af214b884325255e5cdce",
"scope": "Shoulder measurements on the preceding model, after removing the link2 upper caps."
},
"link5_left_three_boxes": {
"previous_urdf_sha256": "a81788def90bae7241ad1808a67b28a8dd318405e41af214b884325255e5cdce",
"previous_primitive_count": 73,
"pieces": [
"collision_negative_cheek",
"collision_core",
"collision_positive_cheek"
],
"source_triangles_covered": 53612,
"minimum_margin_m": 0.0009999999998587111,
"urdf_bytes_outside_left_wrist_collisions_unchanged": true,
"evaluated_urdf_sha256": "7d999315b7780e26940cd81fc6436d6c9c9481f7b1a7f0c1d6d373b8d03bf6dd"
},
"link5_right_three_boxes": {
"previous_urdf_sha256": "7d999315b7780e26940cd81fc6436d6c9c9481f7b1a7f0c1d6d373b8d03bf6dd",
"previous_primitive_count": 5,
"pieces": [
"collision_negative_cheek",
"collision_core",
"collision_positive_cheek"
],
"source_triangles_covered": 53616,
"minimum_margin_m": 0.0009999999997495415,
"urdf_bytes_outside_right_wrist_collisions_unchanged": true
}
}

View File

@ -0,0 +1,372 @@
#!/usr/bin/env python3
"""Audit single- and multi-primitive xiaozhao collision URDFs.
Each retained source triangle normally fits inside one convex primitive.
Faces assigned to disabled configuration pieces are reported separately.
Explicitly named parallel-axis cylinder slices may instead cover a triangle by
independently verified, closed subfaces cut from the complete original face.
This proves surface coverage, not solid-volume or pose/path collision safety.
"""
import argparse
import copy
import hashlib
import json
from pathlib import Path
import re
import sys
import xml.etree.ElementTree as ET
import numpy as np
import trimesh
from collision_pieces import partition_triangles, shared_fitter
HERE = Path(__file__).resolve().parent
MODEL = HERE.parent
SOURCE = MODEL / "urdf/xiaozhao.urdf"
COVERAGE_TOLERANCE = 1e-9
def signature(element):
return (element.tag, sorted(element.attrib.items()), (element.text or "").strip(),
[signature(child) for child in element])
def origin(element):
if element is None:
return np.eye(4)
transform = trimesh.transformations.euler_matrix(
*np.fromstring(element.get("rpy", "0 0 0"), sep=" "))
transform[:3, 3] = np.fromstring(element.get("xyz", "0 0 0"), sep=" ")
return transform
def current_asset(mesh):
path = (MODEL / "meshes" / Path(mesh.get("filename", "")).name).resolve()
if not path.is_file() or path.parent != (MODEL / "meshes").resolve():
raise RuntimeError(f"source mesh missing from current xiaozhao assets: {path}")
return path
def generated_asset(mesh, collision_path):
filename = mesh.get("filename", "")
if filename.startswith("package://"):
raise RuntimeError(f"generated visual retains ambiguous package URI: {filename}")
path = Path(filename.removeprefix("file://"))
if not path.is_absolute():
path = collision_path.parent / path
path = path.resolve()
if not path.is_file():
raise RuntimeError(f"generated visual asset is not readable: {path}")
return path
def strip_collisions(root):
for link in root.findall("link"):
for collision in list(link.findall("collision")):
link.remove(collision)
def best_face_margins(triangles, colliders, batch_size=32768):
"""Independently test whole faces; vertices may not use different pieces."""
triangles = np.asarray(triangles, dtype=float)
if (triangles.ndim != 3 or triangles.shape[1:] != (3, 3) or not len(triangles)
or not np.isfinite(triangles).all() or not colliders):
raise RuntimeError("expected finite source triangles and nonempty collision pieces")
best = np.full(len(triangles), -np.inf)
for collision in colliders:
geometry = collision.find("geometry")
if geometry is None or len(geometry) != 1 or geometry[0].tag not in ("box", "cylinder"):
raise RuntimeError("expected one box or cylinder per collision piece")
primitive = geometry[0]
transform = np.linalg.inv(origin(collision.find("origin")))
if not np.isfinite(transform).all():
raise RuntimeError("nonfinite collision origin")
if primitive.tag == "box":
half_size = np.fromstring(primitive.get("size", ""), sep=" ") / 2
if len(half_size) != 3 or not np.isfinite(half_size).all() or (half_size <= 0).any():
raise RuntimeError("invalid box dimensions")
else:
radius = float(primitive.get("radius", "nan"))
length = float(primitive.get("length", "nan"))
if not np.isfinite([radius, length]).all() or min(radius, length) <= 0:
raise RuntimeError("invalid cylinder dimensions")
for start in range(0, len(triangles), batch_size):
stop = min(start + batch_size, len(triangles))
local = trimesh.transform_points(triangles[start:stop].reshape(-1, 3), transform)
local = local.reshape(-1, 3, 3)
if primitive.tag == "box":
margin = np.min(half_size - np.abs(local), axis=(1, 2))
else:
radial = radius - np.linalg.norm(local[:, :, :2], axis=2)
axial = length / 2 - np.abs(local[:, :, 2])
margin = np.minimum(radial.min(axis=1), axial.min(axis=1))
best[start:stop] = np.maximum(best[start:stop], margin)
return best
def _axial_cylinder_groups(colliders, required_margin):
"""Recognize explicit slice groups without trusting generation settings.
Slice numbering must be contiguous from 00, and all pieces must be
cylinders with parallel axes. Their fitted radial centers may differ: the
proof below tests against each actual transform and radius independently;
this grouping tolerance cannot relax the geometric coverage check.
"""
named = {}
for collider in colliders:
match = re.fullmatch(r"(collision_.+)_slice([0-9]{2,})", collider.get("name", ""))
if match:
named.setdefault(match[1], []).append((int(match[2]), collider))
groups = []
for name, entries in sorted(named.items()):
entries.sort(key=lambda item: item[0])
if len(entries) < 2 or [index for index, _ in entries] != list(range(len(entries))):
continue
cylinders = [collider for _, collider in entries]
if any(c.find("geometry/cylinder") is None for c in cylinders):
continue
frames = [origin(c.find("origin")) for c in cylinders]
axis = frames[0][:3, 2]
if any(np.linalg.norm(np.cross(axis, frame[:3, 2])) > COVERAGE_TOLERANCE
for frame in frames[1:]):
continue
intervals = []
for collider, frame in zip(cylinders, frames):
primitive = collider.find("geometry/cylinder")
half_length = float(primitive.get("length")) / 2 - required_margin
if half_length < 0 or float(primitive.get("radius")) < required_margin:
break
center = float(frame[:3, 3] @ axis)
intervals.append((center, center - half_length, center + half_length))
if len(intervals) != len(cylinders):
continue
intervals.sort()
# The actual inset end caps locate the seam even when CLI margin is
# smaller than fitting padding. A real gap is NOT removed: its middle
# becomes a cut and must itself pass the subsequent primitive test.
cuts = sorted(set((left[2] + right[1]) / 2
for left, right in zip(intervals, intervals[1:])))
groups.append((name, axis, cuts, cylinders))
return groups
def _clip_polygon(polygon, axis, cut, keep_lower):
"""Closed half-space clipping, including seam vertices and degenerates.
No epsilon or small-area filter is used here: neither a narrow uncovered
strip nor a line/point on the seam may disappear from the proof.
"""
if not len(polygon):
return np.empty((0, 3))
sign = 1 if keep_lower else -1
distances = sign * (polygon @ axis - cut)
result = []
previous, previous_distance = polygon[-1], distances[-1]
for current, distance in zip(polygon, distances):
if (previous_distance <= 0) != (distance <= 0):
fraction = previous_distance / (previous_distance - distance)
result.append(previous + fraction * (current - previous))
if distance <= 0:
result.append(current)
previous, previous_distance = current, distance
return np.asarray(result, dtype=float).reshape(-1, 3)
def _polygon_margin(polygon, colliders):
# A fan exactly covers a convex clipped polygon. Each complete fan triangle
# must fit one primitive; its vertices cannot choose different cylinders.
# Lines and points remain explicit, rather than being discarded as zero area.
if len(polygon) < 3:
triangles = np.array([[polygon[0], polygon[-1], polygon[-1]]])
else:
triangles = np.array([[polygon[0], polygon[index], polygon[index + 1]]
for index in range(1, len(polygon) - 1)])
return float(best_face_margins(triangles, colliders).min())
def face_coverage_margins(triangles, colliders, required_margin):
"""Return proven face-margin lower bounds and the slice-rescued face count.
The ordinary whole-face result is unchanged. Only failed faces may use an
explicit slice group; each group's cuts partition the WHOLE triangle into
closed polygons, including the portions outside the group's axial extent.
A successful proof covers every subface at the requested margin.
"""
if not np.isfinite(required_margin) or required_margin < 0:
raise ValueError("minimum margin must be finite and nonnegative")
triangles = np.asarray(triangles, dtype=float)
margins = best_face_margins(triangles, colliders)
failed = np.flatnonzero(margins < required_margin - COVERAGE_TOLERANCE)
if not len(failed):
return margins, 0
groups = _axial_cylinder_groups(colliders, required_margin)
rescued = 0
for index in failed:
for _, axis, cuts, cylinders in groups:
remaining = triangles[index]
lower_bound = float("inf")
for cut in cuts:
lower = _clip_polygon(remaining, axis, cut, True)
remaining = _clip_polygon(remaining, axis, cut, False)
if len(lower):
lower_bound = min(lower_bound, _polygon_margin(lower, cylinders))
if lower_bound < required_margin - COVERAGE_TOLERANCE or not len(remaining):
break
if len(remaining):
lower_bound = min(lower_bound, _polygon_margin(remaining, cylinders))
if np.isfinite(lower_bound) and lower_bound >= required_margin - COVERAGE_TOLERANCE:
margins[index] = max(margins[index], lower_bound)
rescued += 1
break
return margins, rescued
def coverage_selection(triangles, pieces, collider_names):
"""Remove only complete faces assigned to explicitly disabled pieces."""
retained = np.ones(len(triangles), dtype=bool)
disabled = [(i, piece["name"]) for i, piece in enumerate(pieces)
if not piece.get("enabled", True)]
counts = {}
if disabled:
owner = partition_triangles(triangles, pieces)
for index, name in disabled:
pattern = (rf"collision_{re.escape(name)}(?:_[xyz]_(?:pos|neg))?"
r"(?:_part[0-9]+)?(?:_slice[0-9]+)?")
if any(re.fullmatch(pattern, collider) for collider in collider_names):
raise RuntimeError(f"disabled piece still has collision geometry: {name}")
selected = owner == index
counts[name] = int(np.count_nonzero(selected))
retained[selected] = False
return retained, counts
def verify(collision_path, required_margin, config=None):
source_bytes = SOURCE.read_bytes()
collision_bytes = collision_path.read_bytes()
source = ET.fromstring(source_bytes)
generated = ET.fromstring(collision_bytes)
source_joints = source.findall("joint")
if [signature(j) for j in source_joints] != [signature(j) for j in generated.findall("joint")]:
raise RuntimeError("joint definitions differ from source (including origins/limits/axes)")
# Check every other source field as well, except replaced collisions and
# mesh URI spelling. Resolve both documents to the same verified assets.
source_structure, generated_structure = copy.deepcopy(source), copy.deepcopy(generated)
strip_collisions(source_structure)
strip_collisions(generated_structure)
for mesh in source_structure.iter("mesh"):
mesh.set("filename", str(current_asset(mesh)))
for mesh in generated_structure.iter("mesh"):
actual = generated_asset(mesh, collision_path)
if actual != current_asset(mesh):
raise RuntimeError(f"visual uses an asset outside the current model: {actual}")
mesh.set("filename", str(actual))
if signature(source_structure) != signature(generated_structure):
raise RuntimeError("non-collision model fields differ from source")
result = []
for source_link in source.findall("link"):
name = source_link.get("name")
link = generated.find(f"link[@name='{name}']")
colliders = link.findall("collision")
if not source_link.findall("collision"):
if colliders:
raise RuntimeError(f"visual-only link gained a collider: {name}")
continue
if not colliders:
raise RuntimeError(f"source collision link has no generated pieces: {name}")
piece_names = [collision.get("name", "") for collision in colliders]
if any(not value for value in piece_names) or len(set(piece_names)) != len(piece_names):
raise RuntimeError(f"collision pieces must have unique nonempty names on {name}")
vertex_count = 0
triangles_by_mesh = []
indices_by_mesh = []
for visual in source_link.findall("visual"):
mesh_element = visual.find("geometry/mesh")
if mesh_element is None:
continue
mesh = trimesh.load(current_asset(mesh_element), force="mesh", process=False)
scale = np.fromstring(mesh_element.get("scale", "1 1 1"), sep=" ")
vertices = trimesh.transform_points(np.asarray(mesh.vertices) * scale,
origin(visual.find("origin")))
faces = np.asarray(mesh.faces)
triangles_by_mesh.append(vertices[faces])
indices_by_mesh.append(faces + vertex_count)
vertex_count += len(vertices)
if not vertex_count:
raise RuntimeError(f"no source mesh vertices checked on {name}")
triangles = (triangles_by_mesh[0] if len(triangles_by_mesh) == 1
else np.concatenate(triangles_by_mesh))
pieces = shared_fitter().link_settings(config or {}, name).get("pieces", [])
retained, excluded = coverage_selection(triangles, pieces, piece_names)
if excluded:
if not np.any(retained):
raise RuntimeError(f"no retained source triangles on {name}")
vertex_count = len(np.unique(np.concatenate(indices_by_mesh)[retained]))
triangles = triangles[retained]
margins, rescued = face_coverage_margins(triangles, colliders, required_margin)
minimum = float(margins.min())
if not np.isfinite(minimum) or minimum < required_margin - COVERAGE_TOLERANCE:
missed = int(np.count_nonzero(margins < required_margin - COVERAGE_TOLERANCE))
raise RuntimeError(f"whole-triangle coverage failed on {name}: {missed} faces "
f"(including optional axial-slice union proof), "
f"margin {minimum:.9g} m, required {required_margin:.9g} m")
result.append({"link": name, "primitive_count": len(colliders), "pieces": piece_names,
"vertices_checked": vertex_count,
"triangles_covered": len(triangles),
"triangles_excluded": sum(excluded.values()),
"excluded_pieces": excluded,
"triangles_covered_by_slice_union": rescued,
"minimum_margin_m": minimum})
return {
"status": "passed",
"source": str(SOURCE),
"collision": str(collision_path),
"source_sha256": hashlib.sha256(source_bytes).hexdigest(),
"collision_sha256": hashlib.sha256(collision_bytes).hexdigest(),
"joints_preserved": len(source_joints),
"movable_joints_preserved": sum(j.get("type") != "fixed" for j in source_joints),
"all_non_collision_fields_preserved": True,
"visual_asset_resolution": "absolute or URDF-relative paths; verified current model assets",
"primitive_count": sum(item["primitive_count"] for item in result),
"vertices_checked": sum(item["vertices_checked"] for item in result),
"triangles_covered": sum(item["triangles_covered"] for item in result),
"triangles_excluded": sum(item["triangles_excluded"] for item in result),
"triangles_covered_by_slice_union": sum(item["triangles_covered_by_slice_union"] for item in result),
"required_margin_m": required_margin,
"minimum_margin_m": min(item["minimum_margin_m"] for item in result),
"coverage_scope": ("each retained current source STL triangle fits inside one convex primitive, "
"or is fully partitioned into closed subfaces covered by an explicitly named "
"parallel-axis cylinder-slice group, with the required margin. "
"Explicitly disabled piece regions are counted separately."),
"solid_volume_coverage_validated": False,
"pose_or_path_safety_validated": False,
"links": result,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--collision", type=Path, default=HERE / "xiaozhao_collision.urdf")
parser.add_argument("--config", type=Path, default=HERE / "xiaozhao_collision.toml",
help="piece configuration used to generate this collision URDF")
parser.add_argument("--minimum-margin", type=float, default=0.001)
args = parser.parse_args()
if not np.isfinite(args.minimum_margin) or args.minimum_margin < 0:
parser.error("minimum margin must be finite and nonnegative")
try:
config = shared_fitter().load_config(args.config.resolve())
report = verify(args.collision.resolve(), args.minimum_margin, config)
except (RuntimeError, ValueError, OSError, ET.ParseError) as error:
print(f"FAIL: {error}", file=sys.stderr)
return 1
print(json.dumps(report, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,265 @@
# Conservative triangle-partition envelopes of the current xiaozhao meshes.
# Generate with generate_collision.py in this directory: the source URDF's
# legacy package name must not select meshes from an older model directory.
# These envelopes are for offline review, not a declaration of collision-free
# zero/start poses. No link-pair exclusions or geometry shrinkage are applied.
[defaults]
primitive = "box"
alignment = "link"
padding = 0.001
scale = 1.0
# The chest and bent motor housings retain link-aligned boxes. Rotational
# housings below use cylinders along their actual link-local Z axes.
[links.base_link]
primitive = "box"
[links."link1-left"]
primitive = "cylinder"
axis = "z"
[links."link1-right"]
primitive = "cylinder"
axis = "z"
[links."link3-left"]
primitive = "cylinder"
axis = "z"
[links."link3-right"]
primitive = "cylinder"
axis = "z"
[links."link5-left"]
primitive = "cylinder"
axis = "z"
[links."link5-right"]
primitive = "cylinder"
axis = "z"
[links.neck_Link1]
primitive = "cylinder"
axis = "z"
# TCP spheres are display markers, not solid robot parts. The original source
# has no collision on these links; enabled=false preserves that fact.
[links."tcp-left"]
enabled = false
[links."tcp-right"]
enabled = false
# Partition in link-local coordinates by each complete triangle's centroid.
# The fitter still encloses all three vertices, including faces crossing a cut.
# The wide lower base must not determine the width of the shoulder envelope.
[[links.base_link.pieces]]
name = "foot"
bounds_max = [inf, inf, 0.0]
[[links.base_link.pieces]]
name = "lower_torso"
bounds_min = [-inf, -inf, 0.0]
bounds_max = [inf, inf, 0.30]
[[links.base_link.pieces]]
name = "upper_torso"
bounds_min = [-inf, -inf, 0.30]
bounds_max = [inf, inf, 0.38]
[[links.base_link.pieces]]
name = "negative_shoulder_ring"
enabled = false
primitive = "cylinder"
axis = "y"
axial_layers = 3
bounds_min = [-inf, -inf, 0.38]
bounds_max = [inf, -0.1471, 0.50]
[[links.base_link.pieces]]
name = "shoulder_middle"
bounds_min = [-inf, -0.1471, 0.38]
bounds_max = [inf, 0.1471, 0.50]
[[links.base_link.pieces]]
name = "positive_shoulder_ring"
enabled = false
primitive = "cylinder"
axis = "y"
axial_layers = 3
bounds_min = [-inf, 0.1471, 0.38]
bounds_max = [inf, inf, 0.50]
[[links.base_link.pieces]]
name = "neck_mount"
bounds_min = [-inf, -inf, 0.50]
# The second links bend away from their proximal motors in opposite Y directions.
# The side facing the shoulder ring has two end caps with an actual axial gap
# around local Z=-49.75 mm. A single full-length motor envelope fills this gap.
[[links."link2-left".pieces]]
name = "proximal_back"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, 0.0, -inf]
bounds_max = [inf, 0.04, inf]
[[links."link2-left".pieces]]
name = "proximal_lower_cap"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_max = [inf, 0.0, -0.05]
[[links."link2-left".pieces]]
name = "proximal_upper_cap"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, -inf, -0.05]
bounds_max = [inf, 0.0, inf]
[[links."link2-left".pieces]]
name = "elbow_transition"
bounds_min = [-inf, 0.04, -inf]
bounds_max = [inf, 0.09, inf]
[[links."link2-left".pieces]]
name = "distal_housing"
bounds_min = [-inf, 0.09, -inf]
[[links."link2-right".pieces]]
name = "distal_housing"
bounds_max = [inf, -0.09, inf]
[[links."link2-right".pieces]]
name = "elbow_transition"
bounds_min = [-inf, -0.09, -inf]
bounds_max = [inf, -0.04, inf]
[[links."link2-right".pieces]]
name = "proximal_back"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, -0.04, -inf]
bounds_max = [inf, 0.0, inf]
[[links."link2-right".pieces]]
name = "proximal_lower_cap"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, 0.0, -inf]
bounds_max = [inf, inf, -0.05]
[[links."link2-right".pieces]]
name = "proximal_upper_cap"
enabled = false
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, 0.0, -0.05]
# Each side of the right fork includes its outer cheek and inner brace.
[[links."link5-right".pieces]]
name = "negative_cheek"
primitive = "box"
bounds_max = [-0.03, inf, inf]
[[links."link5-right".pieces]]
name = "core"
primitive = "box"
bounds_min = [-0.03, -inf, -inf]
bounds_max = [0.03, inf, inf]
[[links."link5-right".pieces]]
name = "positive_cheek"
primitive = "box"
bounds_min = [0.03, -inf, -inf]
# Represent the left wrist with the two outer fork cheeks and the body between them.
[[links."link5-left".pieces]]
name = "negative_cheek"
primitive = "box"
bounds_max = [inf, -0.035, inf]
[[links."link5-left".pieces]]
name = "core"
primitive = "box"
bounds_min = [-inf, -0.035, -inf]
bounds_max = [inf, 0.035, inf]
[[links."link5-left".pieces]]
name = "positive_cheek"
primitive = "box"
bounds_min = [-inf, 0.035, -inf]
# Separate the round wrist plate, adapter, palm and fingers. The two hands are
# mirrored along Y in their current link frames. A distal thumb must not widen
# the proximal wrist envelope. The plate's circular part includes its diameter
# near Y=0; the rectangular tongue and adapter are excluded on both sides.
[[links."link7-left".pieces]]
name = "plate_round_end"
primitive = "cylinder"
axis = "z"
bounds_max = [inf, 0.005, inf]
[[links."link7-left".pieces]]
name = "plate_body"
enabled = false
bounds_min = [-inf, 0.005, -inf]
bounds_max = [inf, 0.025, inf]
[[links."link7-left".pieces]]
name = "adapter"
enabled = false
bounds_min = [-inf, 0.025, -inf]
bounds_max = [inf, 0.05, inf]
[[links."link7-left".pieces]]
name = "palm_root"
bounds_min = [-inf, 0.05, -inf]
bounds_max = [inf, 0.10, inf]
[[links."link7-left".pieces]]
name = "palm"
bounds_min = [-inf, 0.10, -inf]
bounds_max = [inf, 0.15, inf]
[[links."link7-left".pieces]]
name = "fingers"
bounds_min = [-inf, 0.15, -inf]
[[links."link7-right".pieces]]
name = "fingers"
bounds_max = [inf, -0.15, inf]
[[links."link7-right".pieces]]
name = "palm"
bounds_min = [-inf, -0.15, -inf]
bounds_max = [inf, -0.10, inf]
[[links."link7-right".pieces]]
name = "palm_root"
bounds_min = [-inf, -0.10, -inf]
bounds_max = [inf, -0.05, inf]
[[links."link7-right".pieces]]
name = "adapter"
enabled = false
bounds_min = [-inf, -0.05, -inf]
bounds_max = [inf, -0.025, inf]
[[links."link7-right".pieces]]
name = "plate_body"
enabled = false
primitive = "box"
bounds_min = [-inf, -0.025, -inf]
bounds_max = [inf, -0.005, inf]
[[links."link7-right".pieces]]
name = "plate_round_end"
primitive = "cylinder"
axis = "z"
bounds_min = [-inf, -0.005, -inf]

View File

@ -0,0 +1,650 @@
<?xml version='1.0' encoding='utf-8'?>
<robot name="xiaozhao">
<!-- Base axes: X_new = -Y_old, Y_new = X_old, Z_new = Z_old. -->
<link name="base_link">
<inertial>
<origin xyz="-0.0158820586330755 -1.19384910205036e-06 0.0601572634202883" rpy="0 0 1.5707963267949" />
<mass value="12.0939193087609" />
<inertia ixx="0.0771992576048866" ixy="-4.71603477080102E-07" ixz="-1.48909012424014E-07" iyy="0.110011609259562" iyz="-0.00671136747575047" izz="0.130299609920884" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 1.5707963267949" />
<geometry>
<mesh filename="../meshes/base_link.STL" />
</geometry>
<material name="">
<color rgba="0.752941176470588 0.752941176470588 0.752941176470588 1" />
</material>
</visual>
<collision name="collision_foot">
<origin xyz="0.0452465042472 0 -0.0810000011697" rpy="0 0 0" />
<geometry>
<box size="0.294493000627 0.383032913923 0.205999994323" />
</geometry>
</collision>
<collision name="collision_lower_torso">
<origin xyz="-0.0316252112389 0 0.165000005625" rpy="0 0 0" />
<geometry>
<box size="0.241598065615 0.264049347162 0.39200001736" />
</geometry>
</collision>
<collision name="collision_upper_torso">
<origin xyz="-0.0296741873026 8.94069670243e-08 0.337000012398" rpy="0 0 0" />
<geometry>
<box size="0.249691601515 0.277749415159 0.224000002861" />
</geometry>
</collision>
<collision name="collision_shoulder_middle">
<origin xyz="-0.0301204994321 0 0.410750001669" rpy="0 0 0" />
<geometry>
<box size="0.25077281487 0.295999999762 0.195499982357" />
</geometry>
</collision>
<collision name="collision_neck_mount">
<origin xyz="-0.0391487628222 -1.25467777254e-05 0.510239779949" rpy="0 0 0" />
<geometry>
<box size="0.205257292509 0.26913937521 0.0389484424591" />
</geometry>
</collision>
</link>
<link name="link1-left">
<inertial>
<origin xyz="6.75324341598005E-05 -0.00414124893712335 0.0357014132791962" rpy="0 0 0" />
<mass value="0.304090721433475" />
<inertia ixx="0.000245055173827115" ixy="-2.11027978489438E-07" ixz="9.11870207358669E-08" iyy="0.00042828640186093" iyz="-3.16718145546335E-06" izz="0.000350389449270938" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link1-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0 0.0028669228816 0.0450000008568" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0608516019311" length="0.105000001982" />
</geometry>
</collision>
</link>
<joint name="joint1-left" type="revolute">
<origin xyz="-0.0405 0.1478 0.441" rpy="0 1.5708 1.5707963267949" />
<parent link="base_link" />
<child link="link1-left" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link2-left">
<inertial>
<origin xyz="7.25060001084687e-05 0.0807829812620638 -0.0422541168775343" rpy="-3.14159265358979 0 0" />
<mass value="0.238735801407796" />
<inertia ixx="0.000233070980658983" ixy="1.78430707346592E-07" ixz="-1.10102013961508E-07" iyy="0.000172880087203634" iyz="1.98817891913915E-05" izz="0.000249700712948652" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="-3.14159265358979 0 0" />
<geometry>
<mesh filename="../meshes/link2-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_elbow_transition">
<origin xyz="-0.000978602096438 0.0913880290464 -0.0497500002384" rpy="0 0 0" />
<geometry>
<box size="0.0987755205929 0.127346040353 0.12629715693" />
</geometry>
</collision>
<collision name="collision_distal_housing">
<origin xyz="-0.0008509978652 0.0992805268615 -0.0497499963967" rpy="0 0 0" />
<geometry>
<box size="0.0985203121305 0.131438955337 0.0968098527733" />
</geometry>
</collision>
</link>
<joint name="joint2-left" type="revolute">
<origin xyz="0 -0.04975 0.053" rpy="1.57079265358979 0 0" />
<parent link="link1-left" />
<child link="link2-left" />
<axis xyz="0 0 1" />
<limit lower="-1.57" upper="1.57" effort="0" velocity="0" />
</joint>
<link name="link3-left">
<inertial>
<origin xyz="0.000612207603460563 0.00229659018905651 0.0517902912984107" rpy="0 0 0" />
<mass value="0.206576313767245" />
<inertia ixx="0.000106807122863566" ixy="1.3686406496755E-08" ixz="-9.39521625510296E-07" iyy="0.000211842956357412" iyz="-5.34315488439938E-06" izz="0.000188701328569606" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 -1.5707963267949" />
<geometry>
<mesh filename="../meshes/link3-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="-0.000405770460272 0 0.0820475821346" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0742732827272" length="0.166095162421" />
</geometry>
</collision>
</link>
<joint name="joint3-left" type="revolute">
<origin xyz="0 0.1575 -0.04975" rpy="1.57079265358979 0 3.141592653589793" />
<parent link="link2-left" />
<child link="link3-left" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link4-left">
<inertial>
<origin xyz="0.000268740390489769 0.0373908800531662 -0.0359490477915483" rpy="0 0 0" />
<mass value="0.0803293338116679" />
<inertia ixx="0.000106626468821837" ixy="-2.31152323845664E-10" ixz="6.45631718028383E-08" iyy="1.58918187475175E-05" iyz="-9.54676249280788E-07" izz="0.000120588702228947" />
</inertial>
<visual>
<origin xyz="-0.0038192 0 -0.0416" rpy="0 -1.5707963267949 0" />
<geometry>
<mesh filename="../meshes/link4-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0.00960380884426 0.0395001098514 -0.0434047075719" rpy="0 0 0" />
<geometry>
<box size="0.126203134328 0.186000000358 0.116697616547" />
</geometry>
</collision>
</link>
<joint name="joint4-left" type="revolute">
<origin xyz="0 -0.04125 0.0945" rpy="1.5708 0 0" />
<parent link="link3-left" />
<child link="link4-left" />
<axis xyz="0 0 1" />
<limit lower="0" upper="2.35" effort="0" velocity="0" />
</joint>
<link name="link5-left">
<inertial>
<origin xyz="-0.00064770787776916 0.00811977664913954 0.0418779781048378" rpy="0 0 0" />
<mass value="0.171115687396794" />
<inertia ixx="0.000110604944142724" ixy="-4.13537904185603E-07" ixz="3.02142205581103E-06" iyy="0.000175689959913363" iyz="-1.13002104132245E-06" izz="8.46587908656625E-05" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link5-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_negative_cheek">
<origin xyz="0 -0.0398671794683 0.0591981799807" rpy="0 0 0" />
<geometry>
<box size="0.0842411850095 0.0162656378448 0.130396358807" />
</geometry>
</collision>
<collision name="collision_core">
<origin xyz="-0.00723346509039 0.00111977010965 0.0541026792489" rpy="0 0 0" />
<geometry>
<box size="0.106540098459 0.0797547731996 0.120205358274" />
</geometry>
</collision>
<collision name="collision_positive_cheek">
<origin xyz="-0.000189702957869 0.0397057179362 0.0611822658684" rpy="0 0 0" />
<geometry>
<box size="0.0846205909252 0.016588560909 0.134364530582" />
</geometry>
</collision>
</link>
<joint name="joint5-left" type="revolute">
<origin xyz="0 0.1315 -0.04125" rpy="1.5708 0 3.141592653589793" />
<parent link="link4-left" />
<child link="link5-left" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link6-left">
<inertial>
<origin xyz="0.0160147732367327 0.000660038957990938 -0.0380434793705672" rpy="-3.14159265358979 0 0" />
<mass value="0.0326968497975282" />
<inertia ixx="2.67125153002924E-05" ixy="-1.34580437208919E-11" ixz="5.06790755246012E-07" iyy="3.04838493405727E-05" iyz="6.45171446902217E-08" izz="6.26296697174092E-06" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="-3.14159265358979 0 0" />
<geometry>
<mesh filename="../meshes/link6-left.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="-0.00350000057369 0 -0.0373999985168" rpy="0 0 0" />
<geometry>
<box size="0.0689999998063 0.0669999976158 0.0809999987464" />
</geometry>
</collision>
</link>
<joint name="joint6-left" type="revolute">
<origin xyz="0 -0.0369 0.1145" rpy="1.57079265358979 0 0" />
<parent link="link5-left" />
<child link="link6-left" />
<axis xyz="0 0 1" />
<limit lower="-0.785" upper="0.45" effort="0" velocity="0" />
</joint>
<link name="link7-left">
<inertial>
<origin xyz="0.00178604570829378 0.0813605007818323 -0.0221116181447386" rpy="0 0 0" />
<mass value="0.0935116969865748" />
<inertia ixx="5.06673735014526E-05" ixy="-2.71420525306304E-07" ixz="1.46838383946241E-08" iyy="3.0989237776473E-05" iyz="1.23593328732233E-05" izz="5.31215311149928E-05" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link7-left.STL" />
</geometry>
<material name="">
<color rgba="1 1 1 1" />
</material>
</visual>
<collision name="collision_plate_round_end">
<origin xyz="5.27310885945e-06 -0.000170275400988 -0.00249031097064" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0264754271309" length="0.0070193778352" />
</geometry>
</collision>
<collision name="collision_palm_root">
<origin xyz="0.00517101213336 0.0815633572638 -0.0175419766456" rpy="0 0 0" />
<geometry>
<box size="0.0834593732357 0.0723258290887 0.140681393117" />
</geometry>
</collision>
<collision name="collision_palm">
<origin xyz="0.00219525769353 0.119412533939 -0.0219602454454" rpy="0 0 0" />
<geometry>
<box size="0.0960851196647 0.0810630728006 0.149508721799" />
</geometry>
</collision>
<collision name="collision_fingers">
<origin xyz="0.00384377129376 0.186507329345 -0.0526449256577" rpy="0 0 0" />
<geometry>
<box size="0.0864790749252 0.0899066586494 0.0848151656315" />
</geometry>
</collision>
</link>
<joint name="joint7-left" type="revolute">
<origin xyz="-0.037 0 -0.0369" rpy="7.34641020683213e-06 -1.5708 0" />
<parent link="link6-left" />
<child link="link7-left" />
<axis xyz="0 0 1" />
<limit lower="-1.05" upper="1.05" effort="0" velocity="0" />
</joint>
<link name="link1-right">
<inertial>
<origin xyz="0.00186094851680057 -6.57027673802435E-05 0.0370126157045176" rpy="0 0 0" />
<mass value="0.286348053119183" />
<inertia ixx="0.000422547329511247" ixy="-2.35462474504554E-07" ixz="2.72544434270392E-06" iyy="0.000244327585311168" iyz="9.11871120787603E-08" izz="0.000344505354022551" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link1-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="-0.00445471951247 0 0.0450000008568" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0596973641195" length="0.105000001982" />
</geometry>
</collision>
</link>
<joint name="joint1-right" type="revolute">
<origin xyz="-0.0405 -0.1478 0.441" rpy="1.5708 0 -3.67320510341607e-06" />
<parent link="base_link" />
<child link="link1-right" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link2-right">
<inertial>
<origin xyz="7.27312859680473E-05 -0.0807829812704791 -0.0425927065933143" rpy="0 0 0" />
<mass value="0.238735801407796" />
<inertia ixx="0.000233070980658933" ixy="1.78543084939719E-07" ixz="-1.10102016012101E-07" iyy="0.000172880087203568" iyz="-2.00130653105994E-05" izz="0.000249700712948636" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link2-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_distal_housing">
<origin xyz="-0.0008509978652 -0.0992805268615 -0.0497500000056" rpy="0 0 0" />
<geometry>
<box size="0.0985203121305 0.131438955337 0.0968098455556" />
</geometry>
</collision>
<collision name="collision_elbow_transition">
<origin xyz="-0.000978602096438 -0.0916216559708 -0.0497499997728" rpy="0 0 0" />
<geometry>
<box size="0.0987755205929 0.127817738473 0.126297157861" />
</geometry>
</collision>
</link>
<joint name="joint2-right" type="revolute">
<origin xyz="0.04975 0 0.053" rpy="-1.5708 0 -1.5708" />
<parent link="link1-right" />
<child link="link2-right" />
<axis xyz="0 0 1" />
<limit lower="-1.57" upper="1.57" effort="0" velocity="0" />
</joint>
<link name="link3-right">
<inertial>
<origin xyz="-0.00460138616057136 0.000426610219036727 0.0434471351805352" rpy="0 0 0" />
<mass value="0.194030047437472" />
<inertia ixx="0.000208755273065386" ixy="9.19066905598572E-11" ixz="5.3068688461369E-06" iyy="0.00010579532895932" iyz="2.40971986387619E-07" izz="0.000186285169356577" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 1.5707963267949" />
<geometry>
<mesh filename="../meshes/link3-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0 0.000405770460272 0.0599999981932" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0742732827272" length="0.134999994792" />
</geometry>
</collision>
</link>
<joint name="joint3-right" type="revolute">
<origin xyz="0 -0.164 -0.04975" rpy="-1.5708 1.5708 3.141592653589793" />
<parent link="link2-right" />
<child link="link3-right" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link4-right">
<inertial>
<origin xyz="0.000268622682690761 -0.0373908249854035 -0.0354483066519652" rpy="0 0 0" />
<mass value="0.0803291784530421" />
<inertia ixx="0.000106626439664163" ixy="-2.08649766890664E-10" ixz="-6.4569389547017E-08" iyy="1.5891801109711E-05" iyz="9.54668799732348E-07" izz="0.000120588654971646" />
</inertial>
<visual>
<origin xyz="0.0038192 0 -0.0416" rpy="0 -1.5707963267949 0" />
<geometry>
<mesh filename="../meshes/link4-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0.00960376930816 -0.0395001098514 -0.0390952954799" rpy="0 0 0" />
<geometry>
<box size="0.126203134328 0.186000000358 0.116697616547" />
</geometry>
</collision>
</link>
<joint name="joint4-right" type="revolute">
<origin xyz="0.04125 0 0.088" rpy="-1.5708 0 -1.5708" />
<parent link="link3-right" />
<child link="link4-right" />
<axis xyz="0 0 1" />
<limit lower="-2.35" upper="0" effort="0" velocity="0" />
</joint>
<link name="link5-right">
<inertial>
<origin xyz="-0.00811980437592285 0.000647652694718309 0.0416257106322934" rpy="0 0 0" />
<mass value="0.17111560162694" />
<inertia ixx="0.000175689930428249" ixy="-4.13222163023912E-07" ixz="1.1300608500523E-06" iyy="0.000110604895479297" iyz="-2.66474916177748E-06" izz="8.46587925468465E-05" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link5-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_negative_cheek">
<origin xyz="-0.0371628636494 0 0.0611822658684" rpy="0 0 0" />
<geometry>
<box size="0.0216742694825 0.0892511044145 0.134364530582" />
</geometry>
</collision>
<collision name="collision_core">
<origin xyz="-0.00111977010965 0.00722802616656 0.0283024860546" rpy="0 0 0" />
<geometry>
<box size="0.0797547731996 0.106550976306 0.119015684023" />
</geometry>
</collision>
<collision name="collision_positive_cheek">
<origin xyz="0.0368999987841 0 0.0591981799807" rpy="0 0 0" />
<geometry>
<box size="0.0221999992132 0.0892511044145 0.130396358807" />
</geometry>
</collision>
</link>
<joint name="joint5-right" type="revolute">
<origin xyz="0 -0.1315 -0.04125" rpy="-1.5708 1.5708 3.141592653589793" />
<parent link="link4-right" />
<child link="link5-right" />
<axis xyz="0 0 1" />
<limit lower="-3.14" upper="3.14" effort="0" velocity="0" />
</joint>
<link name="link6-right">
<inertial>
<origin xyz="0.0160147732366216 -0.000660099421881388 -0.0368134594403946" rpy="0 0 0" />
<mass value="0.0326968497975282" />
<inertia ixx="2.67125153002924E-05" ixy="1.34952551021368E-11" ixz="-5.0679067297724E-07" iyy="3.04838493405727E-05" iyz="6.4517144690801E-08" izz="6.26296697174077E-06" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/link6-right.STL" />
</geometry>
<material name="">
<color rgba="0.898039215686275 0.917647058823529 0.929411764705882 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="-0.00350000057369 0 -0.0373999985168" rpy="0 0 0" />
<geometry>
<box size="0.0689999998063 0.0669999976158 0.0809999987464" />
</geometry>
</collision>
</link>
<joint name="joint6-right" type="revolute">
<origin xyz="0.0369 0 0.1145" rpy="-1.5708 0 -1.5708" />
<parent link="link5-right" />
<child link="link6-right" />
<axis xyz="0 0 1" />
<limit lower="-0.45" upper="0.785" effort="0" velocity="0" />
</joint>
<link name="link7-right">
<!-- Complete left-hand STL mirrored in mesh Z, then mounted with Rx(pi): fingers along right J7 -Y. -->
<inertial>
<origin xyz="-7.26286393318538E-06 0.025058851607589 0.0149290377499663" rpy="0 0 0" />
<mass value="0.0419946886424074" />
<inertia ixx="3.12202177376165E-05" ixy="4.70222651242745E-09" ixz="1.00026929410169E-08" iyy="2.02239467874676E-05" iyz="-9.50264156124728E-06" izz="2.91363049162484E-05" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="3.141592653589793 0 0" />
<geometry>
<mesh filename="../meshes/link7-right.STL" />
</geometry>
<material name="">
<color rgba="1 1 1 1" />
</material>
</visual>
<collision name="collision_fingers">
<origin xyz="0.00384377129376 -0.186507329345 -0.0526449256577" rpy="0 0 0" />
<geometry>
<box size="0.0864790749252 0.0899066586494 0.0848151656315" />
</geometry>
</collision>
<collision name="collision_palm">
<origin xyz="0.00219525769353 -0.119412533939 -0.0219602454454" rpy="0 0 0" />
<geometry>
<box size="0.0960851196647 0.0810630728006 0.149508721799" />
</geometry>
</collision>
<collision name="collision_palm_root">
<origin xyz="0.00517101213336 -0.0815633572638 -0.0175419766456" rpy="0 0 0" />
<geometry>
<box size="0.0834593732357 0.0723258290887 0.140681393117" />
</geometry>
</collision>
<collision name="collision_plate_round_end">
<origin xyz="5.27310885945e-06 0.000170275400988 -0.00249031097064" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0264754271309" length="0.0070193778352" />
</geometry>
</collision>
</link>
<joint name="joint7-right" type="revolute">
<origin xyz="-0.037 0 -0.0369" rpy="0 -1.5708 0" />
<parent link="link6-right" />
<child link="link7-right" />
<axis xyz="0 0 1" />
<limit lower="-1.05" upper="1.05" effort="0" velocity="0" />
</joint>
<!-- Fixed TCP frames at mirrored hand-tip offsets; red markers are 5 mm in diameter. -->
<link name="tcp-left">
<visual name="tcp-left-marker">
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<sphere radius="0.0025" />
</geometry>
<material name="tcp-left-red">
<color rgba="1 0 0 1" />
</material>
</visual>
</link>
<joint name="tcp-left-fixed" type="fixed">
<origin xyz="0.007 0.23 -0.045" rpy="0 0 0" />
<parent link="link7-left" />
<child link="tcp-left" />
</joint>
<link name="tcp-right">
<visual name="tcp-right-marker">
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<sphere radius="0.0025" />
</geometry>
<material name="tcp-right-red">
<color rgba="1 0 0 1" />
</material>
</visual>
</link>
<joint name="tcp-right-fixed" type="fixed">
<origin xyz="0.007 -0.23 -0.045" rpy="0 0 0" />
<parent link="link7-right" />
<child link="tcp-right" />
</joint>
<!-- Neck branch from urdf6; mounted in the existing corrected base frame. -->
<link name="neck_Link1">
<inertial>
<origin xyz="0.0151599456281617 -6.12012555002722E-08 0.0402004715446036" rpy="0 0 0" />
<mass value="0.189845491279983" />
<inertia ixx="0.000265543601471852" ixy="-3.38808879149074E-11" ixz="-4.95566815108624E-05" iyy="0.000265166507716" iyz="-5.392904011033E-10" izz="0.000104301534284507" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/neck_Link1.STL" />
</geometry>
<material name="">
<color rgba="1 1 1 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0.00264907115085 0 0.0685000037192" rpy="0 0 0" />
<geometry>
<cylinder radius="0.0416364450853" length="0.137000007343" />
</geometry>
</collision>
</link>
<joint name="neck-joint1" type="revolute">
<origin xyz="-0.0405 0 0.5195" rpy="0 0 1.5707963267949" />
<parent link="base_link" />
<child link="neck_Link1" />
<axis xyz="0 0 1" />
<limit lower="-1.57" upper="1.57" effort="0" velocity="0" />
</joint>
<link name="neck_Link2">
<inertial>
<origin xyz="-2.81713499803993E-05 -0.00170019104546993 -0.0313058952737208" rpy="0 0 0" />
<mass value="0.121849801440166" />
<inertia ixx="4.54157737539868E-05" ixy="-3.57669452070411E-08" ixz="-8.73828761656588E-08" iyy="5.73142513703822E-05" iyz="-4.8205277266393E-06" izz="3.74767660970369E-05" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/neck_Link2.STL" />
</geometry>
<material name="">
<color rgba="1 1 1 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0 -0.000750000588596 -0.0304999575019" rpy="0 0 0" />
<geometry>
<box size="0.0618120242357 0.0464999989122 0.0709999163151" />
</geometry>
</collision>
</link>
<joint name="neck-joint2" type="revolute">
<origin xyz="0.031 0 0.1085" rpy="0 1.5708 0" />
<parent link="neck_Link1" />
<child link="neck_Link2" />
<axis xyz="0 0 1" />
<limit lower="-1.57" upper="0.44" effort="0" velocity="0" />
</joint>
<link name="neck_Link3">
<inertial>
<origin xyz="0.000267765101194494 0.0821520757940103 0.0266245622880571" rpy="0 0 0" />
<mass value="0.521691388878172" />
<inertia ixx="0.0014052179047482" ixy="-2.38666183274677E-06" ixz="-5.69631570744507E-07" iyy="0.00123536484042354" iyz="0.000139207275153035" izz="0.00205087372298224" />
</inertial>
<visual>
<origin xyz="0 0 0" rpy="0 0 0" />
<geometry>
<mesh filename="../meshes/neck_Link3.STL" />
</geometry>
<material name="">
<color rgba="0.631372549019608 0.658823529411765 0.67843137254902 1" />
</material>
</visual>
<collision name="collision_envelope">
<origin xyz="0 0.0663604028523 0.0146355591714" rpy="0 0 0" />
<geometry>
<box size="0.156981389642 0.216843325317 0.170625436723" />
</geometry>
</collision>
</link>
<joint name="neck-joint3" type="revolute">
<origin xyz="0 0.0035 -0.035" rpy="1.5708 -1.5708 0" />
<parent link="neck_Link2" />
<child link="neck_Link3" />
<axis xyz="0 0 1" />
<limit lower="-0.44" upper="0.44" effort="0" velocity="0" />
</joint>
</robot>

View File

@ -2,14 +2,14 @@ joint_name,lower,upper,unit
joint1-left,-3.14,3.14,rad
joint2-left,-1.57,1.57,rad
joint3-left,-3.14,3.14,rad
joint4-left,-2.355,0,rad
joint4-left,0,2.35,rad
joint5-left,-3.14,3.14,rad
joint6-left,-0.785,0.45,rad
joint7-left,-1.05,1.05,rad
joint1-right,-3.14,3.14,rad
joint2-right,-1.57,1.57,rad
joint3-right,-3.14,3.14,rad
joint4-right,0,2.355,rad
joint4-right,-2.35,0,rad
joint5-right,-3.14,3.14,rad
joint6-right,-0.45,0.785,rad
joint7-right,-1.05,1.05,rad

1 joint_name lower upper unit
2 joint1-left -3.14 3.14 rad
3 joint2-left -1.57 1.57 rad
4 joint3-left -3.14 3.14 rad
5 joint4-left -2.355 0 0 2.35 rad
6 joint5-left -3.14 3.14 rad
7 joint6-left -0.785 0.45 rad
8 joint7-left -1.05 1.05 rad
9 joint1-right -3.14 3.14 rad
10 joint2-right -1.57 1.57 rad
11 joint3-right -3.14 3.14 rad
12 joint4-right 0 -2.35 2.355 0 rad
13 joint5-right -3.14 3.14 rad
14 joint6-right -0.45 0.785 rad
15 joint7-right -1.05 1.05 rad

Binary file not shown.

View File

@ -104,7 +104,7 @@
</collision>
</link>
<joint name="joint3-left" type="revolute">
<origin xyz="0 0.1575 -0.04975" rpy="-1.57079265358979 0 0" />
<origin xyz="0 0.1575 -0.04975" rpy="1.57079265358979 0 3.141592653589793" />
<parent link="link2-left" />
<child link="link3-left" />
<axis xyz="0 0 1" />
@ -137,7 +137,7 @@
<parent link="link3-left" />
<child link="link4-left" />
<axis xyz="0 0 1" />
<limit lower="-2.355" upper="0" effort="0" velocity="0" />
<limit lower="0" upper="2.35" effort="0" velocity="0" />
</joint>
<link name="link5-left">
<inertial>
@ -162,7 +162,7 @@
</collision>
</link>
<joint name="joint5-left" type="revolute">
<origin xyz="0 0.1315 -0.04125" rpy="-1.5708 0 0" />
<origin xyz="0 0.1315 -0.04125" rpy="1.5708 0 3.141592653589793" />
<parent link="link4-left" />
<child link="link5-left" />
<axis xyz="0 0 1" />
@ -307,7 +307,7 @@
</collision>
</link>
<joint name="joint3-right" type="revolute">
<origin xyz="0 -0.164 -0.04975" rpy="1.5708 -1.5708 0" />
<origin xyz="0 -0.164 -0.04975" rpy="-1.5708 1.5708 3.141592653589793" />
<parent link="link2-right" />
<child link="link3-right" />
<axis xyz="0 0 1" />
@ -340,7 +340,7 @@
<parent link="link3-right" />
<child link="link4-right" />
<axis xyz="0 0 1" />
<limit lower="0" upper="2.355" effort="0" velocity="0" />
<limit lower="-2.35" upper="0" effort="0" velocity="0" />
</joint>
<link name="link5-right">
<inertial>
@ -365,7 +365,7 @@
</collision>
</link>
<joint name="joint5-right" type="revolute">
<origin xyz="0 -0.1315 -0.04125" rpy="1.5708 -1.5708 0" />
<origin xyz="0 -0.1315 -0.04125" rpy="-1.5708 1.5708 3.141592653589793" />
<parent link="link4-right" />
<child link="link5-right" />
<axis xyz="0 0 1" />

View File

@ -17,7 +17,7 @@
<position name="joint3-left_pos" class="xiaozhao_position"
joint="joint3-left" ctrlrange="-3.14 3.14"/>
<position name="joint4-left_pos" class="xiaozhao_position"
joint="joint4-left" kp="150" ctrlrange="-2.355 0"/>
joint="joint4-left" kp="150" ctrlrange="0 2.35"/>
<position name="joint5-left_pos" class="xiaozhao_position"
joint="joint5-left" kp="80" ctrlrange="-3.14 3.14"/>
<position name="joint6-left_pos" class="xiaozhao_position"
@ -33,7 +33,7 @@
<position name="joint3-right_pos" class="xiaozhao_position"
joint="joint3-right" ctrlrange="-3.14 3.14"/>
<position name="joint4-right_pos" class="xiaozhao_position"
joint="joint4-right" kp="150" ctrlrange="0 2.355"/>
joint="joint4-right" kp="150" ctrlrange="-2.35 0"/>
<position name="joint5-right_pos" class="xiaozhao_position"
joint="joint5-right" kp="80" ctrlrange="-3.14 3.14"/>
<position name="joint6-right_pos" class="xiaozhao_position"

View File

@ -7,6 +7,10 @@
<exclude body1="base_link" body2="link1-left"/>
<exclude body1="base_link" body2="link1-right"/>
<!-- The wrist fork and hand mounting plate have overlapping convex hulls. -->
<exclude body1="link5-left" body2="link7-left"/>
<exclude body1="link5-right" body2="link7-right"/>
<!-- The head and lower-neck convex hulls overlap around the internal gimbal.
Exclude this internal pair so it does not push neck J3 away from zero. -->
<exclude body1="neck_Link1" body2="neck_Link3"/>

View File

@ -62,17 +62,17 @@
<joint name="joint2-left" pos="0 0 0" axis="0 0 1" range="-1.57 1.57" />
<geom quat="0 -1 0 0" type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link2-left_visual" />
<geom quat="0 -1 0 0" type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link2-left" group="3" />
<body name="link3-left" pos="0 0.1575 -0.04975" quat="0.707108 -0.707105 0 0">
<body name="link3-left" pos="0 0.1575 -0.04975" quat="0 0 0.707105 0.707108">
<inertial pos="0.000612208 0.00229659 0.0517903" quat="0.554126 0.440405 0.547991 0.445751" mass="0.206576" diaginertia="0.000213017 0.000187538 0.000106796" />
<joint name="joint3-left" pos="0 0 0" axis="0 0 1" range="-3.14 3.14" />
<geom quat="0.707107 0 0 -0.707107" type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link3-left_visual" />
<geom quat="0.707107 0 0 -0.707107" type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link3-left" group="3" />
<body name="link4-left" pos="0 -0.04125 0.0945" quat="0.707105 0.707108 0 0">
<inertial pos="0.00026874 0.0373909 -0.035949" quat="0.498863 0.503434 -0.501111 0.496565" mass="0.0803293" diaginertia="0.000120598 0.000106626 1.58831e-05" />
<joint name="joint4-left" pos="0 0 0" axis="0 0 1" range="-2.355 0" />
<joint name="joint4-left" pos="0 0 0" axis="0 0 1" range="0 2.35" />
<geom pos="-0.0038192 0 -0.0416" quat="0.707107 0 -0.707107 0" type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link4-left_visual" />
<geom pos="-0.0038192 0 -0.0416" quat="0.707107 0 -0.707107 0" type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link4-left" group="3" />
<body name="link5-left" pos="0 0.1315 -0.04125" quat="0.707105 -0.707108 0 0">
<body name="link5-left" pos="0 0.1315 -0.04125" quat="0 0 0.707108 0.707105">
<inertial pos="-0.000647708 0.00811978 0.041878" quat="0.703234 -0.0446477 -0.0360034 0.708642" mass="0.171116" diaginertia="0.000175707 0.000110948 8.42989e-05" />
<joint name="joint5-left" pos="0 0 0" axis="0 0 1" range="-3.14 3.14" />
<geom type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link5-left_visual" />
@ -107,17 +107,17 @@
<joint name="joint2-right" pos="0 0 0" axis="0 0 1" range="-1.57 1.57" />
<geom type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link2-right_visual" />
<geom type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link2-right" group="3" />
<body name="link3-right" pos="0 -0.164 -0.04975" quat="0.499998 0.5 -0.5 0.500002">
<body name="link3-right" pos="0 -0.164 -0.04975" quat="-0.500002 -0.5 -0.5 0.499998">
<inertial pos="-0.00460139 0.00042661 0.0434471" quat="0.703869 0.701746 -0.0777895 0.0779152" mass="0.19403" diaginertia="0.000209946 0.000185096 0.000105795" />
<joint name="joint3-right" pos="0 0 0" axis="0 0 1" range="-3.14 3.14" />
<geom quat="0.707107 0 0 0.707107" type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link3-right_visual" />
<geom quat="0.707107 0 0 0.707107" type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link3-right" group="3" />
<body name="link4-right" pos="0.04125 0 0.088" quat="0.499998 -0.5 0.500002 -0.5">
<inertial pos="0.000268623 -0.0373908 -0.0354483" quat="0.501111 0.496565 -0.498863 0.503434" mass="0.0803292" diaginertia="0.000120598 0.000106626 1.58831e-05" />
<joint name="joint4-right" pos="0 0 0" axis="0 0 1" range="0 2.355" />
<joint name="joint4-right" pos="0 0 0" axis="0 0 1" range="-2.35 0" />
<geom pos="0.0038192 0 -0.0416" quat="0.707107 0 -0.707107 0" type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link4-right_visual" />
<geom pos="0.0038192 0 -0.0416" quat="0.707107 0 -0.707107 0" type="mesh" rgba="0.898039 0.917647 0.929412 1" mesh="link4-right" group="3" />
<body name="link5-right" pos="0 -0.1315 -0.04125" quat="0.499998 0.5 -0.5 0.500002">
<body name="link5-right" pos="0 -0.1315 -0.04125" quat="-0.500002 -0.5 -0.5 0.499998">
<inertial pos="-0.0081198 0.000647653 0.0416257" quat="0.998699 -0.0504829 -0.00612479 -0.00374546" mass="0.171116" diaginertia="0.000175707 0.000110871 8.43751e-05" />
<joint name="joint5-right" pos="0 0 0" axis="0 0 1" range="-3.14 3.14" />
<geom type="mesh" contype="0" conaffinity="0" group="1" density="0" rgba="0.898039 0.917647 0.929412 1" mesh="link5-right_visual" />