Files
VSAG_SENTRY_SIM_27RMUL/tools/build_vehicle.py
T
mzx f7412ec369 初始化:RMUL 2027 哨兵导航仿真工程
- Gazebo Sim (Jetty 10.6) + ROS 2 Lyrical + Nav2 全栈
- 整车模型:URDF/SDF + 减面网格(SolidWorks 装配体实测尺寸)
- 场地:RMUL 2027 官方包(2D 栅格地图 + 3D 场地模型),放在 field/
- sentry_nav C++ 包:self_filter 点云自滤 / patrol 航点巡逻
- 文档:README(含本机开发环境实测)、MID-360 接入说明

已排除:build/ install/ log/ 缓存目录,以及 115 MB 的原始高模
(仿真实际用的是 meshes/base.stl 减面版,约 25.7 万面)
2026-11-14 21:18:04 +08:00

296 lines
12 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""从「整车装配体」STL 导出构建仿真网格(底盘 / 4 轮 / 云台),并输出布局参数。
相比之前分别用「底盘」「云台」两套导出,整车装配体的优势:所有零件在同一坐标系里,
云台的位置和朝向可以直接量出来,不需要推测。
坐标约定(本装配体):Y 轴向上(地面 = 轮心Y - 轮半径)、X 横向、Z 前后。
输出到 ROS/REP-103:ROS_x=SW_z、ROS_y=SW_x、ROS_z=SW_y(与之前一致)。
用法:
python3 tools/build_vehicle.py --src "/run/media/.../装配车" --out src/sentry_sim/meshes
"""
import argparse
import glob
import json
import os
import struct
import sys
import numpy as np
SCALE = 0.001
# 车头方向:装配体里「相机支架/发射核心板」在 SW +Z 侧、「弹仓后」在 -Z 侧,
# 因此车头 = +SW_z,映射到 ROS 后即 +X。无需翻转(曾经试过 180°,方向反而反了)。
FLIP_180 = False
# SW(装配体) -> ROS:ROS_x=SW_z、ROS_y=SW_x、ROS_z=SW_y(Y 向上转成 Z 向上)
ROT = np.array([[0.0, 0.0, 1.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0]])
# 云台(会绕 yaw 轴转)的零件名关键字
GIMBAL_KEYS = (
'yaw板', 'pitch', '小云台装配体', '基座装配', '八爪拨盘', '拨盘',
'云台', '鹅颈', '枪管', '相机', '发射核心', '弹链', '弹仓',
'24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ',
'电机带轮', '拨盘带轮', 'z21胀紧', 'Z21胀紧',
)
# 轮子本体(会绕自身轴转)
WHEEL_MARK = '轮系-{} 装配体1-1'
def read_stl(path):
size = os.path.getsize(path)
with open(path, 'rb') as f:
head = f.read(84)
n = struct.unpack('<I', head[80:84])[0]
if 84 + n * 50 != size:
return None
f.seek(84)
buf = f.read(n * 50)
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
('v', '<9f4'),
('a', '<u2')]))
return rec['v'].reshape(-1, 3, 3).astype(np.float64)
def write_stl(path, tris):
n = len(tris)
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
normals = np.cross(v1 - v0, v2 - v0)
leng = np.linalg.norm(normals, axis=1)
leng[leng == 0] = 1.0
normals = normals / leng[:, None]
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
rec['n'] = normals
rec['v'] = tris.reshape(n, 9)
with open(path, 'wb') as f:
f.write(b'sentry_sim vehicle'.ljust(80, b' '))
f.write(struct.pack('<I', n))
f.write(rec.tobytes())
def classify(name):
"""返回 'wheelN' / 'gimbal' / 'base'。"""
for i in (1, 2, 3, 4):
if WHEEL_MARK.format(i) in name:
return f'wheel{i}'
for key in GIMBAL_KEYS:
if key in name:
return 'gimbal'
return 'base'
def to_ros(tris, center_sw):
"""SW 装配体坐标 -> ROS 坐标(米)。
p_ros = ROT @ (p_sw - center) * 0.001
FLIP_180 为 True 时再绕 ROS 的 Z 轴转 180°(x、y 同时取反,仍是右手系)。
当前为 False:实测车头(相机/枪口侧)本来就朝 +SW_z,即映射后朝 +X。
"""
out = ((np.asarray(tris, dtype=np.float64).reshape(-1, 3) - center_sw) @ ROT.T) * SCALE
if FLIP_180:
out[:, 0] *= -1.0
out[:, 1] *= -1.0
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--src', required=True)
ap.add_argument('--out', required=True)
ap.add_argument('--dry-run', action='store_true', help='只打印分类结果,不写文件')
ap.add_argument('--split-gimbal', action='store_true',
help='把云台拆成独立 link(需要准确零件清单;默认整车刚体)')
args = ap.parse_args()
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
glob.glob(os.path.join(args.src, '*.stl')))
if not files:
sys.exit(f'没找到 STL:{args.src}')
groups = {'base': [], 'gimbal': [], 'wheel1': [], 'wheel2': [],
'wheel3': [], 'wheel4': []}
skipped = []
# ---- 第一遍:读所有零件,找出主簇(装配体可能被放在离原点很远的位置)----
loaded = []
for path in files:
name = os.path.basename(path)
tris = read_stl(path)
if tris is None:
skipped.append((name, '无法解析'))
continue
v = tris.reshape(-1, 3)
lo, hi = v.min(axis=0), v.max(axis=0)
loaded.append((name, tris, lo, hi))
ok = [x for x in loaded if max(x[3] - x[2]) <= 2000] # 尺寸异常(30 米量级)的直接剔除
for name, _t, _lo, _hi in loaded:
if max(_hi - _lo) > 2000:
skipped.append((name, f'异常几何 尺寸{np.round(_hi-_lo,0)}'))
if not ok:
sys.exit('没有可用零件')
cen = np.array([(x[2] + x[3]) / 2 for x in ok])
med = np.median(cen, axis=0)
all_min = np.full(3, np.inf)
all_max = np.full(3, -np.inf)
for name, tris, lo, hi in ok:
c = (lo + hi) / 2
# 离主簇太远(>3m)的当作放错了的零件
if max(abs(c[0] - med[0]), abs(c[1] - med[1]), abs(c[2] - med[2])) > 3000:
skipped.append((name, f'离主簇太远 中心{np.round(c,0)}'))
continue
all_min = np.minimum(all_min, lo)
all_max = np.maximum(all_max, hi)
groups[classify(name)].append(tris)
wc = {}
for i in (1, 2, 3, 4):
if groups[f'wheel{i}']:
v = np.concatenate(groups[f'wheel{i}']).reshape(-1, 3)
wc[f'wheel{i}'] = (v.min(axis=0) + v.max(axis=0)) / 2
print(f'总零件 {len(files)},跳过 {len(skipped)}')
for n, why in skipped:
print(f' 跳过 {n[:60]} ({why})')
for g, arrs in groups.items():
if not arrs:
continue
v = np.concatenate(arrs).reshape(-1, 3)
lo, hi = v.min(axis=0), v.max(axis=0)
print(f' {g:8} 零件 {len(arrs):3} 件 SW bbox min={np.round(lo,1)} max={np.round(hi,1)} 尺寸={np.round(hi-lo,1)}')
ground_y = all_min[1]
print(f'\n地面 Y={ground_y:.1f} mm;整车 bbox {np.round(all_max-all_min,1)} mm')
# 原点:横向/前后取整车中心,高度取地面
origin_sw = np.array([(all_min[0] + all_max[0]) / 2,
ground_y,
(all_min[2] + all_max[2]) / 2])
# yaw 轴:用 GM6020 云台电机的中心(在 gimbal 组内找)
yaw_xz = None
for path in files:
if 'GM6020' in os.path.basename(path):
tris = read_stl(path)
if tris is None:
continue
v = tris.reshape(-1, 3)
c = (v.min(axis=0) + v.max(axis=0)) / 2
yaw_xz = (c[0], c[2])
break
wheels_ros = {}
for k, c_sw in wc.items():
pts = to_ros(np.array([c_sw]), origin_sw).reshape(-1, 3)[0]
rel = pts
wheels_ros[k] = [round(float(x), 5) for x in rel]
print(f' {k} SW中心={np.round(c_sw,1)} -> ROS {wheels_ros[k]}')
meta = {
'source_dir': os.path.abspath(args.src),
'origin_sw_mm': [round(float(x), 2) for x in origin_sw],
'ground_sw_y_mm': round(float(ground_y), 2),
'size_ros_m': [round(float(x) * SCALE, 4) for x in (all_max - all_min)],
'wheels_ros_m': wheels_ros,
}
# MID-360 雷达位置(如果装配体里放了)
mid_pts = []
for path in files:
if 'MID' in os.path.basename(path).upper() or 'mid-360' in os.path.basename(path):
tris = read_stl(path)
if tris is not None:
mid_pts.append(tris.reshape(-1, 3))
if mid_pts:
mv = np.concatenate(mid_pts)
mid_c = (mv.min(axis=0) + mv.max(axis=0)) / 2
mid_ros = to_ros(np.array([mid_c]), origin_sw).reshape(-1, 3)[0]
meta['mid360_ros_m'] = [round(float(x), 4) for x in mid_ros]
W = mv.max(axis=0) - mv.min(axis=0)
meta['mid360_size_m'] = [round(float(x) * SCALE, 4) for x in W]
print(f' MID-360 SW中心={np.round(mid_c,1)} -> ROS {meta["mid360_ros_m"]} 尺寸(m)={meta["mid360_size_m"]}')
if yaw_xz:
yaw_rel = np.array([yaw_xz[1], yaw_xz[0], 0.0]) # ROS_x=SW_z, ROS_y=SW_x
yaw_rel = yaw_rel - np.array([origin_sw[2], origin_sw[0], 0.0])
meta['yaw_axis_ros_xy_m'] = [round(float(yaw_rel[0]) * SCALE, 5),
round(float(yaw_rel[1]) * SCALE, 5)]
print(f' yaw 轴 ROS(x,y) = {meta["yaw_axis_ros_xy_m"]}')
if args.dry_run:
print('\n[dry-run] 未写文件')
return
os.makedirs(args.out, exist_ok=True)
# 底盘:原点在整车原点;默认把云台并进来(导航阶段刚体即可,避免拆分错误)
base_parts = list(groups['base'])
if not args.split_gimbal:
base_parts += list(groups['gimbal'])
print(' [rigid] 云台零件并入底盘(不再单独出 gimbal.stl)')
base = np.concatenate(base_parts)
write_stl(os.path.join(args.out, 'base.stl'), to_ros(base, origin_sw).reshape(-1, 3, 3))
print(f'\nbase.stl {len(base):,} 面')
# 轮子:以第一个轮子的中心为原点(四个轮子几何相同,尺寸一致已核对)
w1 = np.concatenate(groups['wheel1'])
write_stl(os.path.join(args.out, 'wheel.stl'), to_ros(w1, wc['wheel1']).reshape(-1, 3, 3))
print(f'wheel.stl {len(w1):,} 面')
if not args.split_gimbal:
with open(os.path.join(args.out, 'vehicle_layout.json'), 'w') as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
print(f'\n布局写入 {os.path.join(args.out, "vehicle_layout.json")}')
return
# 云台:原点在 yaw 轴 + 安装面(取云台组最低 Y)
gim = np.concatenate(groups['gimbal'])
gv = gim.reshape(-1, 3)
g_min, g_max = gv.min(axis=0), gv.max(axis=0)
mount_y = g_min[1]
# MID-360 雷达位置(如果装配体里放了)
mid_pts = []
for path in files:
if 'MID' in os.path.basename(path).upper() or 'mid-360' in os.path.basename(path):
tris = read_stl(path)
if tris is not None:
mid_pts.append(tris.reshape(-1, 3))
if mid_pts:
mv = np.concatenate(mid_pts)
mid_c = (mv.min(axis=0) + mv.max(axis=0)) / 2
mid_ros = to_ros(np.array([mid_c]), origin_sw).reshape(-1, 3)[0]
meta['mid360_ros_m'] = [round(float(x), 4) for x in mid_ros]
W = mv.max(axis=0) - mv.min(axis=0)
meta['mid360_size_m'] = [round(float(x) * SCALE, 4) for x in W]
print(f' MID-360 SW中心={np.round(mid_c,1)} -> ROS {meta["mid360_ros_m"]} 尺寸(m)={meta["mid360_size_m"]}')
if yaw_xz:
g_center_sw = np.array([yaw_xz[0], mount_y, yaw_xz[1]])
else:
g_center_sw = np.array([(g_min[0] + g_max[0]) / 2, mount_y,
(g_min[2] + g_max[2]) / 2])
gim_ros = to_ros(gim, g_center_sw).reshape(-1, 3, 3)
write_stl(os.path.join(args.out, 'gimbal.stl'), gim_ros)
gv_ros = gim_ros.reshape(-1, 3)
print(f'gimbal.stl {len(gim):,} 面 ROS bbox min={np.round(gv_ros.min(axis=0),3)} max={np.round(gv_ros.max(axis=0),3)}')
meta['gimbal_origin_sw_mm'] = [round(float(x), 2) for x in g_center_sw]
meta['gimbal_bbox_ros_m'] = [
[round(float(x), 4) for x in gv_ros.min(axis=0)],
[round(float(x), 4) for x in gv_ros.max(axis=0)]]
meta['gimbal_joint_origin_ros_m'] = [
round(float((g_center_sw[2] - origin_sw[2]) * SCALE), 5),
round(float((g_center_sw[0] - origin_sw[0]) * SCALE), 5),
round(float((g_center_sw[1] - origin_sw[1]) * SCALE), 5)]
with open(os.path.join(args.out, 'vehicle_layout.json'), 'w') as f:
json.dump(meta, f, ensure_ascii=False, indent=2)
print(f'\n云台关节安装点(ROS 米): {meta["gimbal_joint_origin_ros_m"]}')
print(f'布局写入 {os.path.join(args.out, "vehicle_layout.json")}')
if __name__ == '__main__':
main()