Compare commits
4
Commits
c710b955b1
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4db635ec78 | ||
|
|
96445bd5f1 | ||
|
|
72f407c110 | ||
|
|
56f4b3adb0 |
No files matched your search
@@ -15,6 +15,25 @@
|
||||
|
||||
`LOCALIZATION=amcl scripts/sentry_up.sh`(或 Python 启动参数 `localization:=amcl`)选择旧方案。下文与 `docs/定位接入AMCL.md` 中的 AMCL 参数/排障说明仅适用于该分支。每次只启动一种定位器发布 `map→odom`,两种方案均保留 Nav2 的 2D map_server。
|
||||
|
||||
## 当前仿真渲染与模型资源
|
||||
|
||||
- **3D 雷达使用 GPU 渲染路径**:模型配置为 `gpu_lidar`,Gazebo Sensors 与场景使用 OGRE2。无界面启动通过 EGL 选择 NVIDIA vendor;具备 NVIDIA 设备和驱动时使用显卡,否则可能回退到 Mesa `llvmpipe` 软件渲染。当前机器的 EGL/NVIDIA 检查和性能数据见 [`docs/Gazebo_GPU评估.md`](docs/Gazebo_GPU评估.md)。GPU 指的是雷达的渲染计算;碰撞与车辆动力学仍由 DART 在 CPU 上计算。
|
||||
- Shell 与 Python 启动入口共享 EGL 和 Gazebo 环境探测。无界面模式使用 Gazebo headless rendering;GUI 和无界面模式均从世界配置使用 OGRE2。
|
||||
- 模型网格引用使用相对路径或 `model://` URI。`tools/gen_sdf.sh` 可从仓库外调用,并依据脚本位置定位工程;它生成 SDF 1.11 与 URDF,按两种产物各自的位置生成相对网格路径,通过校验后才替换产物。启动器按运行位置计算 RViz 所需的 `file://` URI。
|
||||
- `catch_net`、`test_box` 的模型描述与配置统一为 SDF 1.11。模型资源解析和 EGL 启动细节见 [`src/sentry_sim/README.md`](src/sentry_sim/README.md)、[`tools/README.md`](tools/README.md) 与 [`docs/Gazebo_GPU评估.md`](docs/Gazebo_GPU评估.md)。
|
||||
|
||||
## MID-360 与场地点云
|
||||
|
||||
MID-360 使用 **0.10–40 m、360° × 59°(−7° 至 +52°)、40 线、10 Hz**。Gazebo 的规则采样每帧 14,400 点,雷达壳体为 **65 × 65 × 60 mm、265 g**。
|
||||
|
||||
| 话题 | 用途 |
|
||||
|---|---|
|
||||
| `/scan`、`/scan/points` | 原始传感器输出,保留体育馆墙壁和屋顶回波,RViz 使用原始 3D 点云 |
|
||||
| `/scan/points_lio` | 保留场内地面和远端围挡。建图与定位再按 `map` 系场地边界裁剪 |
|
||||
| `/scan/points_filtered`、`/scan2d` | 导航和避障输入,水平距离上限 8 m,障碍标记距离 4.5 m |
|
||||
|
||||
Shell 和 Python 均实测 **10.0 Hz、14,400 点/帧**,原始回波最远分别为 **29.78 m、31.52 m**。34 个测站重建的候选图 `field_full_40m.flmap` 有 **10,583 个体素**,全部落在场地裁剪范围内。Python 全场测试的 70 个代表目标均可规划,13 段导航有 11 段成功、9 段满足全部指标。圆柱复测的终点误差为 **0.082 m**,最小净距为 **0.364 m**。全场验收尚未通过,默认仍加载旧图 `field_full.flmap`,加载时同样裁剪馆外点。详见 [MID-360 接入与验收](docs/MID360-3D雷达接入.md)。
|
||||
|
||||
## 0. 开发环境
|
||||
|
||||
### 0.1 操作系统
|
||||
@@ -236,7 +255,7 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me
|
||||
|
||||
---
|
||||
|
||||
## 7. 当前状态(2026-11-16)
|
||||
## 7. 当前状态(2026-11-25 更新)
|
||||
|
||||
### ✅ 已验证可用
|
||||
|
||||
@@ -266,7 +285,7 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me
|
||||
> 根因与修法:`docs/踩过的坑.md` §G4/§G5、`docs/定位接入AMCL.md` §4.1/§4.2。
|
||||
> 诊断工具:`python3 tools/check_stack.py`(含真值对照)。
|
||||
|
||||
- **MID-360 已做成 3D 激光**(`/scan/points`,PointCloud2),**垂直视场为真机规格**:
|
||||
- **历史记录:12 m 量程版的 MID-360 点云实测**(2026-11-16)。
|
||||
|
||||
| 指标 | 实测 |
|
||||
|---|---|
|
||||
@@ -279,8 +298,7 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me
|
||||
|
||||
RViz 的「MID360点云」显示项已经配好,打开就能看到。
|
||||
|
||||
> ⚠️ 量程仍是 **12 m**(真机 40 m),导致 14 m 外的场馆墙打不到、
|
||||
> 10 m 天花板差 4 cm 够不着。想改善见 `docs/仿真场地外壳.md` §10。
|
||||
> 当前 40 m 模型的结果见 [MID-360 接入与验收](docs/MID360-3D雷达接入.md)。
|
||||
|
||||
### 🆕 2026-11-17 新增
|
||||
|
||||
@@ -298,13 +316,12 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me
|
||||
|
||||
### ⚠️ 仍有局限
|
||||
|
||||
1. **定位是"作弊"的**:`map→odom` 是写死的静态平移 (-5.0, 3.0),位置靠 Gazebo 的
|
||||
轮式里程计积分。打滑/被推之后**永远不会自愈**;真机上完全不可用。
|
||||
真定位需要:点云转 2D → AMCL(当前 `/scan` 因真机视场已基本失效,
|
||||
得先加 `pointcloud_to_laserscan`)。详见 `docs/仿真场地外壳.md`
|
||||
2. **雷达量程只有 12 m**(真机 40 m):场馆墙(14 m 外)打不到、10 m 天花板差 4 cm
|
||||
1. **LIO 是已知初始位姿下的连续跟踪定位**:不会全局重定位;点云配准连续失效或不确定度超限时会报告定位不可用并触发导航保护。地图对称性、几何退化和传感器断流仍可能导致停车。接口、阈值和验证限制见 [`src/field_localization/README.md`](src/field_localization/README.md)。
|
||||
2. **仿真用固定 40 m 量程和规则采样**,真机的探测距离随反射率变化,扫描图案也不同。
|
||||
3. 质量/惯量为估算值(25 kg / 1.5 kg),物理表现可能与真机有偏差
|
||||
4. 云台是刚体(导航不需要转动),自瞄阶段要拆
|
||||
4. 云台 yaw 已拆成独立 link,可 360° 连续转(`gimbal_yaw_link`);pitch 轴还没拆。
|
||||
雷达随云台转动,整帧点云按采样时刻的 TF 转到 IMU 系。
|
||||
细节见 [`src/sentry_sim/urdf/README.md`](src/sentry_sim/urdf/README.md)
|
||||
5. 场地外壳是纯视觉设施,没有看台/球架/广告牌等赛场道具
|
||||
|
||||
---
|
||||
@@ -356,11 +373,11 @@ python3 tools/check_stack.py
|
||||
|---|---|---|
|
||||
| ~~1~~ | ~~修 `patrol` 的朝向~~ | ✅ **已做**(2026-11-17)。原来 `orientation.w` 写死 1.0(永远朝 +X),现在按 `face_mode` 算:默认朝下一个航点,可选顺着来路。角度计算在 `src/core/`,有 190 项单测覆盖 |
|
||||
| 2 | **写决策状态机**(PATROL / ENGAGE / RETREAT) | 还没有。骨架是 `patrol`,纯逻辑该写在 `src/core/` 里配单测(5 ms 跑完,不用起 Gazebo) |
|
||||
| 3 | **把定位做成真的** | 现在是**作弊**的:`map→odom` 写死 (-5.0, 3.0),位置靠轮速积分,打滑/被撞永远不会自愈。真做要 `/scan/points` → `pointcloud_to_laserscan` → AMCL |
|
||||
| 4 | **雷达量程 12 → 20 m** | 现在 14 m 外的场馆墙打不到、10 m 天花板差 4 cm。改法见 `docs/仿真场地外壳.md` |
|
||||
| 3 | **扩展 LIO 验收与场景覆盖** | 当前默认使用全场 `field_full.flmap` 连续跟踪;继续验证新障碍、长时间往返和传感器断流下的定位保护。不要启用全局重定位来处理场地的 180° 对称歧义 |
|
||||
| ~~4~~ | ~~恢复雷达 40 m 量程~~ | 已恢复,体育馆回波在建图、定位和避障中按用途裁剪 |
|
||||
| 5 | **补真实参数** | 整车质量 25 kg / 轮 1.5 kg 是估的。找机械要 SolidWorks「评估 → 质量属性」(kg·m²) |
|
||||
| 6 | **障碍测试补齐** | `models/test_box/` 有模型但世界没 include;加进去后曾出现规划失败(车跑到角落出不来),需要查是代价地图被点云糊住还是控制器问题 |
|
||||
| 7 | **云台拆分**(做自瞄才需要) | 现在云台是刚体。要拆得机械给 yaw / pitch 零件清单,再用 `tools/build_vehicle.py --split-gimbal` |
|
||||
| 7 | ~~**云台拆分**~~ | ✅ **已做**(2026-11-25)。yaw 轴由 5 个同轴件实测在车体中心(**不是** GM6020 电机轴),`gimbal_yaw_link` 用 `continuous` 关节可 360° 转。剩 pitch 轴没拆 |
|
||||
|
||||
**1 和 2 是真正该动的代码**;3 是中等工程;4~6 是调参和补数据。
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# Gazebo GPU 渲染与物理评估
|
||||
|
||||
最后更新:2026-11-24
|
||||
|
||||
## 实测环境
|
||||
|
||||
Gazebo Sim 10.6.0,SDFormat 16.1.0,ROS 2 Lyrical。DART 继续计算接触、刚体和关节。
|
||||
场地和车辆的可视网格与 `gpu_lidar` 使用 OGRE2。无界面入口通过 EGL 初始化渲染。
|
||||
|
||||
**本文有两组测量,条件和结论不同,不要混用:**
|
||||
|
||||
| 场景 | 进程读到的 OpenGL 设备 | 说明了什么 |
|
||||
|---|---|---|
|
||||
| 隔离环境(`/dev` 只有 14 项,看不到 `/dev/nvidiactl`) | Mesa llvmpipe(LLVM 21.1.8) | 只能测软件渲染,**不代表硬件性能** |
|
||||
| 本机(RTX 5060 Max-Q,`/dev/nvidia0` 与 `/dev/dri/card0` 齐全) | **NVIDIA GeForce RTX 5060** | 见「EGL 修复的验证结果」 |
|
||||
|
||||
「雷达对照」那张 CPU 表来自**隔离环境**,衡量的是软件渲染开销。
|
||||
|
||||
## 为什么无界面入口落到 llvmpipe
|
||||
|
||||
改动前,`generated/up.log` 里**每次运行都有 60 组** `libEGL` 警告:
|
||||
|
||||
```text
|
||||
libEGL warning: pci id for fd 113: 10de:2d59, driver (null)
|
||||
libEGL warning: egl: failed to create dri2 screen
|
||||
```
|
||||
|
||||
`10de:2d59` 是本机的独立显卡(RTX 5060 Max-Q)。**设备节点是通的**(有 fd),
|
||||
失败点是 `driver (null)`:glvnd 在用 Mesa 的 DRI2 加载器找驱动,而 **NVIDIA 不提供
|
||||
Mesa DRI 驱动**,它走自己的 `libEGL_nvidia.so`。查找失败后 EGL 回退到 llvmpipe,
|
||||
`gpu_lidar` 于是在 CPU 上做软件光栅化。
|
||||
|
||||
**关键区分:驱动和节点都没问题。** `nvidia-smi` 报告 `595.99.02` / CUDA 13.2,
|
||||
`/dev/nvidia0`、`/dev/nvidiactl`、`/dev/dri/card0`、`/dev/dri/renderD128` 全在,
|
||||
桌面本身也在用这块卡。唯一的问题是 EGL 的 vendor 选择。
|
||||
|
||||
修法是让 EGL 只挑 NVIDIA 的 vendor 库。规则集中在 `tools/project_env.py` 的
|
||||
`gpu_env()`,两个启动入口共用:
|
||||
|
||||
| 入口 | 用法 |
|
||||
|---|---|
|
||||
| Shell | `env_common.sh` 的 `env_gpu_egl()` 在启动 Gazebo 前 `eval` 出 export |
|
||||
| Python | `sentry_arena.launch.py` 把结果作为 `additional_env` 传给 Gazebo 的 `ExecuteProcess` |
|
||||
|
||||
导出内容:
|
||||
|
||||
```bash
|
||||
export __EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/10_nvidia.json
|
||||
export NVIDIA_DRIVER_CAPABILITIES=all
|
||||
```
|
||||
|
||||
`EGL_PLATFORM` 不默认设置(让 OGRE2 自己选 device/surfaceless)。只有某些机器
|
||||
确实需要时才用 `SENTRY_EGL_PLATFORM=surfaceless` 追加。
|
||||
|
||||
| 变量 | 行为 |
|
||||
|---|---|
|
||||
| `SENTRY_GPU_EGL=auto`(默认) | 有 `/dev/nvidiactl` 且存在 vendor json 才启用 |
|
||||
| `SENTRY_GPU_EGL=nvidia` | 强制启用;缺 vendor json 直接报错 |
|
||||
| `SENTRY_GPU_EGL=off` | 不动环境(想自己接管时用) |
|
||||
| `SENTRY_EGL_PLATFORM=surfaceless` | 额外导出 `EGL_PLATFORM`(默认不设) |
|
||||
| `SENTRY_EGL_VENDOR_JSON=<路径>` | 覆盖 vendor json 位置(发行版放别处时用) |
|
||||
|
||||
判定结果随时可查,不用起仿真:
|
||||
|
||||
```bash
|
||||
python3 tools/project_env.py --gpu
|
||||
SENTRY_DRY_RUN=1 scripts/sentry_up.sh # 试运行报告里也有一行 GPU EGL
|
||||
```
|
||||
|
||||
### EGL 修复的验证结果
|
||||
|
||||
在本机(`nvidia-smi` 正常、`/dev/nvidia0` 与 `/dev/dri/card0` 都在)验证,三项证据全部成立:
|
||||
|
||||
```bash
|
||||
$ python3 tools/project_env.py --gpu
|
||||
nvidia → __EGL_VENDOR_LIBRARY_FILENAMES=/usr/share/glvnd/egl_vendor.d/10_nvidia.json NVIDIA_DRIVER_CAPABILITIES=all
|
||||
```
|
||||
|
||||
| 证据 | 修复前 | 修复后 |
|
||||
|---|---|---|
|
||||
| `failed to create dri2 screen`(同一次运行内) | 60 次 | **0 次** |
|
||||
| `[env] GPU EGL → NVIDIA` 日志 | 无 | **有** |
|
||||
| `nvidia-smi` 里的 Gazebo 进程 | 无 | **`gz-sim-main`,Type=`G`,128 MiB** |
|
||||
|
||||
第三项是决定性证据 —— 仿真运行中 `nvidia-smi` 的输出:
|
||||
|
||||
```text
|
||||
| 0 N/A N/A 208686 G .../libexec/gz/sim10/gz-sim-main 128MiB |
|
||||
```
|
||||
|
||||
显存总量也交叉对上了:桌面程序单独占 1,991 MiB,仿真运行中 2,148 MiB,
|
||||
差值 157 MiB 与 Gazebo 的 128 MiB 渲染缓冲一致。
|
||||
|
||||
> **统计 `generated/up.log` 的坑**:这个文件跨多次运行**追加写**,直接
|
||||
> `grep -c` 会把历史记录数进来。要先按最后一次启动切段:
|
||||
>
|
||||
> ```bash
|
||||
> LAST=$(grep -n "sentry_up.*LIO mode=" generated/up.log | tail -1 | cut -d: -f1)
|
||||
> sed -n "${LAST},\$p" generated/up.log | grep -c "failed to create dri2 screen"
|
||||
> ```
|
||||
|
||||
若某台机器上设了 vendor 之后仍出现 `dri2` 警告,先试
|
||||
`SENTRY_EGL_PLATFORM=surfaceless` 再跑一次;仍不行就用 `SENTRY_GPU_EGL=off`
|
||||
保持原来的 llvmpipe 行为。
|
||||
|
||||
### 仍未测量:CPU 收益
|
||||
|
||||
「用上了显卡」已确认,但**省了多少 CPU 还没测**。方法(两组各跑一次):
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev
|
||||
|
||||
# A 组(硬件渲染)
|
||||
HEADLESS=1 scripts/sentry_up.sh &
|
||||
# B 组(强制软件渲染)改成:HEADLESS=1 SENTRY_GPU_EGL=off scripts/sentry_up.sh &
|
||||
|
||||
sleep 20 # 等起稳
|
||||
PID=$(pgrep -f "gz-sim-main" | head -1)
|
||||
A=$(awk '{print $14+$15}' /proc/$PID/stat) # utime+stime(时钟滴答)
|
||||
sleep 30
|
||||
B=$(awk '{print $14+$15}' /proc/$PID/stat)
|
||||
awk -v a="$A" -v b="$B" -v c="$(getconf CLK_TCK)" \
|
||||
'BEGIN{printf "gz 平均单核占用 %.1f%%\n", (b-a)/c/30*100}'
|
||||
```
|
||||
|
||||
对照基线见「雷达对照」:CPU 射线 29.7%,OGRE2 + llvmpipe 83.8%。
|
||||
把 A 组数字补进那张表的第三行后,本文的渲染部分才算完整。
|
||||
|
||||
## 雷达对照
|
||||
|
||||
前两种配置各跑两次,均用同一个场地、机器人、DART 和初始位姿 `(-5, 3)`。
|
||||
起稳后按仿真时间发送 4 秒前进、4 秒后退、2 秒停止。前进和后退速度幅值均为
|
||||
0.16 m/s。独立真值显示最大位移落在 0.643–0.650 m。CPU 射线时不启动渲染,
|
||||
OGRE2 雷达通过 EGL 绘制场景。表中 CPU 占用按单核 100% 计,包括 Gazebo 的子进程。
|
||||
|
||||
| 雷达 | 实时因子 | CPU 秒 / 仿真秒 | 平均单核 CPU 占用 | 点云频率(仿真时间) | 每帧点数 |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| CPU 射线 | 0.973 | 0.305 | 29.7% | 10.0 Hz | 14,400 |
|
||||
| OGRE2 雷达,llvmpipe | 1.000 | 0.838 | 83.8% | 10.0 Hz | 14,400 |
|
||||
| **OGRE2 雷达,RTX 5060** | 待测 | 待测 | 待测 | 10.0 Hz | 14,400 |
|
||||
|
||||
仿真世界的实时因子目标为 1.0。在这组负载下,OGRE2 + llvmpipe 耗用约 2.75 倍于
|
||||
CPU 射线的 CPU 时间,但实时因子反而更好(1.000 vs 0.973)—— 渲染和物理循环解耦,
|
||||
CPU 射线才会直接阻塞物理更新。**前两行都是软件渲染基线与 CPU 射线,不含硬件加速。**
|
||||
第三行的采样方法见「仍未测量:CPU 收益」。
|
||||
|
||||
## GPU 物理迁移
|
||||
|
||||
当前安装中的可选插件为 DART、Bullet、Bullet Featherstone 和 TPE。PhysX
|
||||
可以通过 Gazebo Physics 接口实现独立引擎插件。候选插件需要提供当前模型用到的
|
||||
关节、碰撞和接触接口,并适配 SDF 载入。PhysX 的 CUDA 刚体支持存在按形状和功能
|
||||
回退 CPU 的情况。 [Gazebo Sim 物理引擎](https://gazebosim.org/api/sim/10/physics.html) · [PhysX GPU 刚体](https://nvidia-omniverse.github.io/PhysX/physx/5.7.0/docs/GPURigidBodies.html)
|
||||
|
||||
| 项目 | 迁移核查 |
|
||||
|---|---|
|
||||
| 四轮关节驱动 | 为 `MecanumDrive` 提供四个旋转关节的速度命令、状态读回和限制。对比直行、倒车、原地转向、停止时的轮速和独立真值。PhysX 的部分关节类型仍需要 CPU 参与。 |
|
||||
| 轮地摩擦 | 匹配 DART 下圆柱轮与地板的静摩擦、滑移和停止距离。需要接触修改时,PhysX 可能使用 CPU 窄相。 |
|
||||
| 场地碰撞 | 保留场地静态网格和车身简化碰撞体。对使用 GPU 碰撞的网格启用 GPU 数据预处理,检查围挡、相交边缘和低矮障碍的接触结果。 |
|
||||
| 接触反馈与时序 | 对比接触点、方向和反馈时序,确认 ROS 时钟、IMU、里程计和独立真值时序。PhysX 的场景查询和部分接触功能仍由 CPU 执行。 |
|
||||
|
||||
默认部署继续使用 DART。渲染部分已在本机确认走 NVIDIA(见「EGL 修复的验证结果」),
|
||||
下一步是在同一运动序列上同时记录硬件渲染的 CPU 占用和 Physics 更新耗时,判断
|
||||
动态接触是不是新的主要开销。若确实如此,再做独立 PhysX 插件原型。单车场景的
|
||||
GPU 物理收益目前未实测,轮地下的误差和场地网格碰撞是迁移验收的重点。
|
||||
|
||||
## 模型资源
|
||||
|
||||
运行 `tools/gen_sdf.sh` 可重新生成 SDF 1.11 和 URDF。网格引用以各自产物目录
|
||||
为基准。用 Gazebo CLI 单独检查含 `model://` 的世界时,为 `SDF_PATH` 提供与
|
||||
启动器相同的两处模型目录。运行时的 RViz `file://` URI 由启动器计算。
|
||||
|
||||
## 启动和导航回归
|
||||
|
||||
Shell 和 Python 的 EGL 启动均持续收到 `/scan` 与 `/scan/points`,两者的帧名为
|
||||
`lidar_link`,仿真频率为 10.0 Hz,点云每帧 14,400 点。虚拟显示上运行的 Gazebo GUI
|
||||
加载了场地、车体和四轮。用 RViz 的资源读取库验证了含空格路径下的两种 STL。
|
||||
|
||||
| 验收 | Nav2 成功 | 最大真值终点误差 | 平移 ATE | 最大 3D 误差 |
|
||||
|---|---:|---:|---:|---:|
|
||||
| Shell 首轮 | 2/3 | 1.892 m(返程取消) | 0.028 m | 0.148 m |
|
||||
| Python | 3/3 | 0.459 m | 0.019 m | 0.087 m |
|
||||
| Shell 复测 | 3/3 | 0.235 m | 0.025 m | 0.111 m |
|
||||
|
||||
各次运行均只有一个 `map → odom` 发布者。首轮 Shell 返程在仿真时间 91.57 s
|
||||
因水平位置 3σ 达 0.521 m 触发保护。Shell 复测启动时遇到一次 Nav2 动作发现超时,
|
||||
原有监管流程重试后全部节点 ACTIVE,`/is_path_valid` 正常响应。Python 的真值终点
|
||||
分别为 0.459、0.341 和 0.071 m,前两段超过了原有的 0.30 m 验收值。
|
||||
|
||||
含空格的临时目录中,生成器从仓库外运行两次,产物一致。5 个模型和 1 个世界通过
|
||||
`gz sdf -k`,生成模型保留用于 Gazebo 坐标帧的 `gz_frame_id` 扩展。
|
||||
`xmake test` 通过 15 项,环境探测和模型生成的 Python 回归测试分别通过 11 项和 3 项
|
||||
(新增的 `test_gpu_egl_matches_shell` 校验 `gpu_env()` 在 CLI 与 Shell 两个入口
|
||||
给出的判定一致)。脚本语法检查、Shell 预演和 Python 启动参数检查通过。
|
||||
其他 Gazebo 版本未实测。
|
||||
|
||||
### EGL 修复后的运行检查
|
||||
|
||||
加 EGL vendor 后的一次无界面 Shell 运行:
|
||||
|
||||
```bash
|
||||
$ HEADLESS=1 scripts/sentry_up.sh
|
||||
[env] GPU EGL → NVIDIA(OGRE2 走真显卡;SENTRY_GPU_EGL=off 可关闭)
|
||||
```
|
||||
|
||||
该次运行内 `failed to create dri2 screen` 计数为 **0**(此前每次 60),
|
||||
`field_localization` 的 8 次状态打印全部为 `mode=FULL reason=NONE`,
|
||||
`self_filter` 剔除盒 `x[-0.29,0.37] y[-0.27,0.27] z[-0.05,0.55]` 与车体
|
||||
`0.578 × 0.521` 加上前伸云台的一致,未出现新的启动回归。
|
||||
|
||||
+57
-56
@@ -1,7 +1,7 @@
|
||||
# MID-360 3D 激光雷达接入说明
|
||||
|
||||
> **状态**:✅ 点云可用,已通过 `self_filter` 接入 Nav2 代价地图
|
||||
> **最后更新**:2026-11-17
|
||||
> 已接通 40 m 原始点云、场地建图裁剪与 Nav2 避障。新地图继续作为候选图。
|
||||
> 最后更新于 2026-11-25。
|
||||
> **涉及**:`src/sentry_sim/urdf/sentry.urdf.xacro`(传感器定义)、`src/sentry_nav/`(自滤)
|
||||
|
||||
## 1. 结论
|
||||
@@ -9,13 +9,12 @@
|
||||
| 能力 | 状态 |
|
||||
|---|---|
|
||||
| 输出 3D 点云 | ✅ **14400 点/帧(360 水平 × 40 垂直)**,10 Hz |
|
||||
| 有效点 / 测距 | ⚠️ 约 4950 个有效点(`inf` 占 65.6%),**0.06 ~ 11.68 m** |
|
||||
| 能看到地面 | ✅ 高度 −0.41 ~ +9.31 m(−7° 打地面,+52° 打到顶棚主梁) |
|
||||
| 量程 | 0.10–40 m,Shell 和 Python 采样的最远有效点分别为 29.78 m 和 31.52 m |
|
||||
| 可见范围 | 场内地面、外部体育馆墙壁、屋顶 |
|
||||
| RViz 可视化 | ✅ 「MID360点云」显示项(`/scan/points`) |
|
||||
| 接入 Nav2 避障 | ✅ `/scan/points_filtered`(`self_filter` 剔除车身自回波后) |
|
||||
|
||||
> ⚠️ **最大的限制不是视场,是量程 12 m**。真机是 0.1~40 m,我们只给 12 m,
|
||||
> 导致 14 m 外的墙一个点打不到、10 m 天花板差 4 cm 够不着。见 §3。
|
||||
体育馆保持 40 × 28 m、墙高 10 m。原始点云保留体育馆回波,建图和避障分别处理。
|
||||
|
||||
---
|
||||
|
||||
@@ -27,12 +26,15 @@
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 安装位置(ROS) | **(−0.0935, −0.1512, 0.4052)**,外形 84×68×82 mm(装配体实测) |
|
||||
| 类型 | `type="lidar"` + `gz-sim-cpu-lidar-system`(CPU 射线,不依赖 GPU) |
|
||||
| 安装位置(ROS) | 云台零位时在底盘系 **(−0.0935, −0.1512, 0.4052) m** |
|
||||
| 外形与质量 | **65 × 65 × 60 mm,265 g**。惯量按均质长方体计算,SDF 转换后并入云台 link |
|
||||
| 类型 | `type="gpu_lidar"` + OGRE2 `Sensors` |
|
||||
| 水平 | 360 点,−π ~ +π |
|
||||
| **垂直** | **40 线,−7° ~ +52°**(真机规格;−0.122173 ~ 0.907571 rad) |
|
||||
| 更新率 | 10 Hz |
|
||||
| 量程 | **0.10 ~ 12.0 m**,分辨率 0.01 m,高斯噪声 σ=0.01(真机 0.1~40 m) |
|
||||
| 量程 | **0.10–40 m**,分辨率 0.01 m,高斯噪声 σ=0.01 m |
|
||||
|
||||
40 m 对应官方低反射率规格(10%)。Gazebo 使用固定最大量程和每帧 14,400 点的规则采样。实机的回波距离随反射率变化,扫描图案与仿真不同。[Livox 技术参数](https://www.livoxtech.com/cn/mid-360/specs)
|
||||
|
||||
### 2.2 话题与桥接
|
||||
|
||||
@@ -53,40 +55,37 @@
|
||||
`worlds/sentry_arena.sdf` 里必须有:
|
||||
|
||||
```xml
|
||||
<plugin filename="gz-sim-cpu-lidar-system" name="gz::sim::systems::CpuLidar" />
|
||||
<plugin filename="gz-sim-sensors-system" name="gz::sim::systems::Sensors">
|
||||
<render_engine>ogre2</render_engine>
|
||||
</plugin>
|
||||
```
|
||||
|
||||
### 2.4 两个必须知道的行为
|
||||
|
||||
**① 雷达不能被整车碰撞盒包住。**
|
||||
Gazebo 的激光是给**碰撞体**做射线求交的。原来 `base_link` 一个盒子包住整车,
|
||||
而雷达在 `z = 0.405`(盒内),射线全打在内壁上,测距只有 0.2~0.4 m。
|
||||
现在拆成两个盒子(`chassis_collision` 下半 + `gimbal_collision` 上半靠前),雷达位置就露出来了。
|
||||
**① GPU 雷达测量渲染场景中的表面。**
|
||||
可见网格和物理碰撞体可能采用不同的几何。修改车身视觉网格或场地模型后,重新核对车身自回波和可用点数。
|
||||
上一版 CPU 雷达的有效点比例是历史测量。
|
||||
|
||||
**② `/scan`(2D)现在基本不可用,这是预期的。**
|
||||
gz 的 `/scan` 取**中间那层**射线,而中间角 = (−7 + 52) / 2 = **+22.5° 仰角**,射向天空。
|
||||
只用 3D 点云;Nav2 代价地图吃的也是点云,不受影响。
|
||||
**② `/scan` 取中间一层。** 约 +22.5° 的仰角会看到体育馆外壳。AMCL 和碰撞监控用自滤后投影的 `/scan2d`,Nav2 代价地图用 3D 点云。
|
||||
|
||||
---
|
||||
|
||||
## 3. ⚠️ 真正的瓶颈:量程 12 m
|
||||
## 3. 按用途过滤
|
||||
|
||||
射线是斜的,到目标的**斜距 = 高度 / sin(仰角)**:
|
||||
| 用途 | 坐标系与过滤 |
|
||||
|---|---|
|
||||
| 原始观测 | `/scan` 和 `/scan/points` 在 `lidar_link`,保留硬件模型的 0.10–40 m 射线量程 |
|
||||
| 避障 | `/scan/points_filtered` 在 `base_link`,剔除无效点、车身回波,保留 z 0.02–1.20 m、水平距离 ≤8 m 的点。Nav2 障碍标记仍为 4.5 m,清障为 8 m |
|
||||
| 投影 | `/scan2d` 取底盘系 z 0.05–0.50 m,每个方位取最近回波,AMCL 和碰撞监控使用此话题 |
|
||||
| 建图和定位 | `/scan/points_lio` 保留地面和远端围挡。LIO 配准、地图加载、在线建图和离线测站建图使用场地边界 |
|
||||
|
||||
| 仰角 | 到天花板下沿(上方 9.49 m) | 到主梁下沿(上方 8.94 m) |
|
||||
|---|---|---|
|
||||
| +30° | 18.99 m ❌ | 17.89 m ❌ |
|
||||
| +45.9° | 13.22 m ❌ | 12.46 m ❌ |
|
||||
| **+52°(最大)** | 12.05 m ❌ | 11.35 m ✅ |
|
||||
比赛场内车体中心距最近馆墙至少 10 m。避障的 8 m 上限能滤除馆墙,1.20 m 的高度上限能滤除斜上方进入 8 m 水平范围的天花板。LIO 需要场内远端围挡,因此另设 `lio_max_range=40.2` m 为水平预滤上限,其中 0.2 m 覆盖雷达相对底盘的偏心。
|
||||
|
||||
- **天花板下沿需要仰角 ≥ 52.3°**,最高只有 52.0° —— 差 0.3°,够不着
|
||||
- **主梁下沿需要 ≥ 48.2°** —— 只有最顶上 1~2 条线打到,就是那 81 个点的来源
|
||||
- **墙(最近 14.0 m 水平)斜距永远 ≥ 14 m** —— 任何仰角都超量程,**一个点都打不到**
|
||||
地图在 `map` 系使用 [场地点云配置](../src/sentry_sim/config/field_cloud.yaml) 中的 x ±6.4 m、y ±4.4 m、z −0.10 至 0.65 m。配准先用扫描时刻的 IMU 预测位姿裁剪并留 0.20 m 余量。地图加载和写入不加余量,单独的测站建图使用已知测站位姿。
|
||||
|
||||
换个说法:**量程 12 m 时射线最高只到 `0.4052 + 12·sin(52°) = 9.86 m`**,
|
||||
而天花板下沿在 9.9 m —— 差 4 cm。
|
||||
云台转动时,自滤根据点云时间戳查雷达到底盘的 TF。LIO 和录制再把整帧点云统一到 IMU 系。实机若按方位角去畸变,当前实现需要固定安装的雷达。
|
||||
|
||||
### 对照实验:量程改 20 m
|
||||
### 历史对照(12 m 和 20 m)
|
||||
|
||||
| 指标 | 12 m | **20 m** |
|
||||
|---|---|---|
|
||||
@@ -96,30 +95,34 @@ gz 的 `/scan` 取**中间那层**射线,而中间角 = (−7 + 52) / 2 = **+2
|
||||
| 天花板点(z>8) | 81 | **4578** |
|
||||
| 远处墙点(r>12.5) | **0** | **1440** |
|
||||
|
||||
**改法是两个地方一起改**,否则自滤节点会把新打到的墙点又丢掉:
|
||||
|
||||
1. `urdf/sentry.urdf.xacro` 的 `<ray>` 段 → `max_range` 改成 20.0
|
||||
2. `src/sentry_nav/src/self_filter.cpp` 的 `declare_parameter<double>("max_range", 12.0)` → 20.0
|
||||
|
||||
(实验后已改回 12.0,当前仍是 12 m。)
|
||||
|
||||
---
|
||||
|
||||
## 4. 实测数据
|
||||
## 4. 40 m 实测
|
||||
|
||||
2026-11-16,headless + 临时桥 + rclpy 订阅一帧:
|
||||
2026-11-25,在隔离 ROS Domain 和 Gazebo partition 中使用 Gazebo 10.6、OGRE2 和 Mesa llvmpipe。每个入口采样 50 帧。频率按仿真时间计算,测试覆盖软件渲染。
|
||||
|
||||
```
|
||||
点云规格 :14400 点/帧(360 水平 × 40 垂直)
|
||||
有效点 :4954(inf 占 65.6%)
|
||||
水平测距 :0.06 ~ 11.68 m
|
||||
高度范围 :−0.41 ~ +9.31 m ← 上面是顶棚主梁
|
||||
垂直角 :−7.0° ~ +52.0° ← 与真机一致
|
||||
打到天花板的点 :81 个(1.6%)
|
||||
```
|
||||
| 启动入口 | 原始点云 | 最远有效斜距 | 自滤后最大水平距离 / 高度 |
|
||||
|---|---:|---:|---:|
|
||||
| Shell | 14,400 点/帧,10.0 Hz | 29.78 m | 7.68 m / 0.37 m |
|
||||
| Python | 14,400 点/帧,10.0 Hz | 31.52 m | 7.95 m / 0.42 m |
|
||||
|
||||
**`inf` 高达 65.6%** 是因为大厅空旷:`0° ~ +38°` 那一段射线什么都打不到。
|
||||
不是坏了,是真实的「无回波」。
|
||||
两次原始数据均为 `lidar_link`,`/scan` 报告 `range_max=40.0`,`/scan2d` 报告 `range_max=8.0`。34 个空场测站生成 **10,583 个 0.10 m 体素**,越界数为 0,最高体素点约 0.440 m。轨迹真值来自 Gazebo PosePublisher,仅用于验收。
|
||||
|
||||
| 候选图验收 | Nav2 成功 / 实跑 | 满足全部指标 | 平移 ATE | 1 s 平移 RPE | 最大 3D 定位误差 | 圆柱最小净距 |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| Shell 全场首测 | 2/3 | 2/3 | 0.026 m | 0.029 m | 0.109 m | — |
|
||||
| Shell 全场复测 | 3/4 | 3/4 | 0.027 m | 0.032 m | 0.132 m | — |
|
||||
| Python 全场 | 11/13 | 9/13 | 0.030 m | 0.035 m | 0.167 m | — |
|
||||
| Python 圆柱首测 | 1/1 | 0/1 | 0.024 m | 0.031 m | 0.093 m | 0.346 m |
|
||||
| Python 圆柱复测 | 1/1 | 1/1 | 0.025 m | 0.028 m | 0.095 m | 0.364 m |
|
||||
|
||||
Shell 和 Python 的 70 个代表目标均可规划。Shell 复测成功跑完 `(0,0) ↔ (5,−3)`,真值终点误差分别为 0.105 m 和 0.229 m。两次 Shell 全场测试分别在约 `(1.19,1.51)` 和 `(1.16,1.50)` 停车,水平 3σ 达到 0.529 m 和 0.5002 m。回放首测失败处的扫描仍可满秩配准,IMU 记录到约 89 m/s² 的短时加速度峰值。
|
||||
|
||||
Python 全场测试在 `(1.63,1.73)` 和 `(5.09,−2.04)` 附近触发 3σ 停车,另有两段报告成功但终点误差为 0.487 m 和 0.351 m。圆柱试验首测终点误差 0.502 m,复测 0.082 m。候选图目前通过了裁剪检查和部分导航路段,全场验收仍未通过。两个入口默认继续使用 `field_full.flmap`,加载时保留 10,112 个场内体素。两套默认启动均确认 12 个受管节点 ACTIVE、`/is_path_valid` 正常、`map → odom` 只有一个发布者。
|
||||
|
||||
单独在原地用 13 个约 0.5 rad 的目标角阶跃跨过一圈。关节 TF 发布为 20 Hz 时 194 次定位心跳中有 116 次无效。改为 100 Hz 后,复测 163 次均有效。新旧数据回放分别处理 379 帧和 426 帧,均成功配准。GCC 15.2 / C++23 构建无警告,`xmake test` 15/15 通过。模型与世界通过 `gz sdf -k`,验证器提示 `gz_frame_id` 是 Gazebo 扩展。
|
||||
|
||||
候选图生成、选用和离线回放命令见 [定位包说明](../src/field_localization/README.md)。
|
||||
|
||||
自检命令:
|
||||
|
||||
@@ -169,9 +172,7 @@ ros2 topic info /scan/points # PointCloud2
|
||||
`Collision Ahead - Exiting DriveOnHeading`。抬高 `obstacle_min_range` 到 0.9 m 也不够
|
||||
(车身相对传感器最远约 0.65 m)。
|
||||
|
||||
**现在的做法**:`src/sentry_nav/` 里的 `self_filter` 节点把点云转到 `base_link`、
|
||||
剔掉车身包围盒内的点,输出 `/scan/points_filtered`,两个代价地图都改吃它。
|
||||
实测 3612 → 1546 点,最近距离 0.10 → 0.87 m。
|
||||
两个代价地图都订阅 `/scan/points_filtered`。`self_filter` 按时间戳转换到底盘系,执行车身、距离和高度过滤。避障和定位分别发布点云,见 §3。
|
||||
|
||||
参数与用法见 `src/sentry_nav/README.md`;代码分层见 `src/sentry_nav/src/README.md`。
|
||||
|
||||
@@ -183,7 +184,9 @@ ros2 topic info /scan/points # PointCloud2
|
||||
|---|---|
|
||||
| 安装位置 | `urdf/sentry.urdf.xacro` 的 `lidar_x/y/z` |
|
||||
| 垂直视场 / 线数 | 同文件 `<vertical>` 的 `samples` / `min_angle` / `max_angle`(弧度) |
|
||||
| 量程、噪声、更新率 | 同文件 `<ray>` 段(改量程记得同时改 `self_filter` 的 `max_range`) |
|
||||
| 量程、噪声、更新率 | 同文件 `gpu_lidar` 传感器的 `<lidar>` 段与 `<update_rate>` |
|
||||
| 建图和定位裁剪 | `src/sentry_sim/config/field_cloud.yaml` |
|
||||
| 避障与清障距离 | `self_filter` 的 `max_range` 和 `nav2_params.yaml` 的 `raytrace_max_range` |
|
||||
| 碰撞体形状 | 同文件 `chassis_collision` / `gimbal_collision` |
|
||||
| 桥接话题 | `scripts/sentry_up.sh` **和** `scripts/bridge_after_gz.sh` |
|
||||
| 是否参与避障 | `config/nav2_params.yaml` 的 costmap `plugins` 与 `observation_sources` |
|
||||
@@ -204,9 +207,7 @@ HEADLESS=0 scripts/sentry_up.sh
|
||||
| 现象 | 原因 | 处理 |
|
||||
|---|---|---|
|
||||
| 点云全在 0.2~0.4 m | 雷达被整车碰撞盒包住 | 拆成底盘盒 + 云台盒(§2.4①) |
|
||||
| `/scan` 全是 `inf` | 改成真机视场后的**预期行为**(中间层 +22.5° 打向天空) | 正常,只用 3D 点云 |
|
||||
| 点云上半区一大片空(`inf` 65%) | 同上 + 大厅空旷、量程 12 m 够不到天花板 | 加大量程(§3) |
|
||||
| 天花板只打到 81 个点 | 量程 12 m 下最高只到 9.86 m,天花板在 9.9 m | 量程改 20 m(§3) |
|
||||
| RViz 的原始点云中看到馆墙和屋顶 | 当前 40 m 传感器回波 | 用 `/scan/points_filtered` 查看实际避障输入 |
|
||||
| 点云话题收不到 | 只改了 `bridge_after_gz.sh`,实际跑的是 `sentry_up.sh` | 两处都改(§2.2) |
|
||||
| 接进代价地图后车不动 | 点云含车身自回波 | 已加自滤(§6) |
|
||||
|
||||
|
||||
+7
-2
@@ -3,17 +3,18 @@
|
||||
专项技术文档。**工程总览和目录树在上一层的 [`../README.md`](../README.md)**
|
||||
——这里只放「怎么做」和「为什么」。
|
||||
|
||||
## 七份文档
|
||||
## 八份文档
|
||||
|
||||
| 文档 | 一句话 | 什么时候看 |
|
||||
|---|---|---|
|
||||
| [`操作手册.md`](操作手册.md) | 启动/收尾、体检、遥控、演示、发目标、航点巡逻、看数据、环境变量、场地坐标 | **要动手操作** |
|
||||
| [`排错速查.md`](排错速查.md) | 7 类 34 条现象 → 原因 → 处理 | **出问题了**(「现在怎么办」) |
|
||||
| [`踩过的坑.md`](踩过的坑.md) | 27 条设计经验,按领域分 7 组(§A–§G) | 想知道**为什么**这么设计(「别再犯」) |
|
||||
| [`MID360-3D雷达接入.md`](MID360-3D雷达接入.md) | 传感器配置、话题桥接、实测数据、**量程 12 m 这个瓶颈** | 动雷达 |
|
||||
| [`MID360-3D雷达接入.md`](MID360-3D雷达接入.md) | 40 m 雷达配置、场地点云过滤、地图与导航验收 | 动雷达 |
|
||||
| [`仿真场地外壳.md`](仿真场地外壳.md) | 体育馆大厅 + 屋顶 + 拦截网的尺寸、取舍、怎么改 | 动场地 |
|
||||
| [`定位接入AMCL.md`](定位接入AMCL.md) | **定位怎么做**:为什么之前是假的、AMCL 需要什么、2D 雷达怎么加、`map→odom` 谁发、已知卡点 | 动定位 |
|
||||
| [`构建体系与代码分层.md`](构建体系与代码分层.md) | C++23 下限证据、为什么全用 xmake、`src/core/` 分层纪律 | 动构建或代码结构 |
|
||||
| [`Gazebo_GPU评估.md`](Gazebo_GPU评估.md) | `gpu_lidar` 为什么退到 llvmpipe、**EGL vendor 修法与验证证据**、雷达 CPU 对照、PhysX 迁移核查 | 动渲染 / GPU / 雷达类型 |
|
||||
|
||||
## 几条常见路径
|
||||
|
||||
@@ -28,6 +29,10 @@
|
||||
「车知道自己在哪吗 / 怎么做定位」
|
||||
→ 定位接入AMCL.md(现状、改动清单、验收、卡点)
|
||||
|
||||
「无界面仿真 CPU 吃满了 / 想换 GPU 雷达」
|
||||
→ Gazebo_GPU评估.md(EGL vendor 判定、验证命令、CPU 对照)
|
||||
→ 先跑 python3 tools/project_env.py --gpu
|
||||
|
||||
「我要加决策状态机」
|
||||
→ 构建体系与代码分层 §4(分层)§6(五步流程)
|
||||
→ 代码本身看 src/sentry_nav/ 下的 README
|
||||
|
||||
+3
-1
@@ -4,12 +4,14 @@
|
||||
> **最后更新**:2026-11-17
|
||||
> **涉及模型**:`arena_walls`(新)、`arena_roof`(新)、`catch_net`(停用但保留)
|
||||
|
||||
2026-11-25 起原始雷达量程为 40 m,体育馆几何沿用本文的尺寸。下文关于 12 m 和 20 m 的测量是旧版记录。当前观测与场地过滤见 [MID-360 接入与验收](MID360-3D雷达接入.md)。
|
||||
|
||||
## 1. 一句话结论
|
||||
|
||||
> 比赛场地被包在 **40 × 28 m、墙高 10 m** 的体育馆大厅里,头顶是 10 m 的顶棚 + 梁 + 12 条灯带。
|
||||
> 墙、地面、顶棚、梁**都有碰撞体**。雷达视场也已改成真机规格 **−7°~+52° / 40 线**。
|
||||
>
|
||||
> **但外壳目前基本打不到**:墙最近 14.0 m > 量程 12 m;天花板下沿 9.9 m,
|
||||
> **早期 12 m 模型基本扫不到外壳**:墙最近 14.0 m > 量程 12 m;天花板下沿 9.9 m,
|
||||
> 而量程 12 m 下射线最高只到 9.86 m —— **差 4 cm**。
|
||||
> 实测只打到顶棚主梁 **81 个点**,墙 **0 个**。怎么解决见 §6。
|
||||
|
||||
|
||||
+2
-2
@@ -35,10 +35,10 @@ TF 链(`map→odom` / `odom→base_link` / `map→base_link`),结尾直接
|
||||
| 现象 | 原因 | 处理 |
|
||||
|---|---|---|
|
||||
| 雷达全是 `inf` | 传感器高于围挡(0.42 m),一圈打不到东西 | `ros2 topic echo /scan2d --once` 看 ranges 是不是一堆 `inf`/`nan` |
|
||||
| 点云上半区一大片空(`inf` 65%) | **拦截网默认已停用** + 大厅空旷 + 量程 12 m 够不到天花板 | 当前预期状态;想改善见 `MID360-3D雷达接入.md` §3 |
|
||||
| 点云上半区缺点 | 过滤话题剔除了顶棚,滤除范围随话题而异 | 对照原始 `/scan/points`,见 [MID-360 过滤说明](MID360-3D雷达接入.md) |
|
||||
| 点云里全是近距离点 | 传感器被车身碰撞盒包住 | 检查碰撞体是否把雷达罩进去(已拆成 `chassis_collision` + `gimbal_collision`) |
|
||||
| 代价地图把车自己标成障碍 | 没跑自滤,或包围盒太小 | 确认 `self_filter` 在跑:`ros2 topic hz /scan/points_filtered` |
|
||||
| 雷达看不到场馆墙 | 量程只有 **12 m**,墙在 14 m 外 | 见 `仿真场地外壳.md` §6.2 |
|
||||
| 避障点云看不到场馆墙 | 底盘系的水平距离上限为 **8 m** | 用原始 `/scan/points` 查看馆墙回波 |
|
||||
|
||||
## C. 话题与桥
|
||||
|
||||
|
||||
+4
-4
@@ -24,9 +24,10 @@
|
||||
<axis><xyz>0 1 0</xyz><limit lower="-1e16" upper="1e16" effort="10" velocity="100"/></axis>
|
||||
```
|
||||
|
||||
### A3. `cpu_lidar` 不是合法 SDF sensor 类型
|
||||
### A3. GPU 雷达依赖世界的渲染系统
|
||||
|
||||
CPU 雷达写 `type="lidar"` + `gz-sim-cpu-lidar-system` 插件。写 `type="cpu_lidar"` 会创建失败。
|
||||
模型使用 `type="gpu_lidar"`,世界加载 OGRE2 `Sensors`。服务端无界面运行时使用
|
||||
`--headless-rendering`。若 `/clock` 有数据而 `/scan/points` 无数据,先检查 Sensors 和 EGL 初始化日志。
|
||||
|
||||
### A4. 百万面级网格会让 Gazebo 卡死
|
||||
|
||||
@@ -63,8 +64,7 @@ export GZ_SIM_SYSTEM_PLUGIN_PATH=/usr/lib/x86_64-linux-gnu/gz-sim-10/plugins
|
||||
本机还有个特例:`gz sim --version` 报 **10.5.0**,apt 装的却是 **10.6.0**。
|
||||
原因是 `gz-sim-main` 的 **RUNPATH** 烧进了 vendor 路径,清 `LD_LIBRARY_PATH` 也改不掉 →
|
||||
「10.6 的插件 + 10.5 的核心」混着跑。`scripts/run_gz.sh` 就是为此存在的包装
|
||||
(清掉 `LD_LIBRARY_PATH` 再调 `/usr/bin/gz`,否则连系统版 gz 也会加载 vendor 库,
|
||||
而 vendor 没有 cpu-lidar 插件,雷达会创建失败)。
|
||||
(清掉 `LD_LIBRARY_PATH` 再调 `/usr/bin/gz`,确保系统 gz 使用与自身匹配的库和插件)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -42,26 +42,36 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl
|
||||
|
||||
只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 0.5 m,或旋转严格大于 10°。初始化种子帧是唯一例外。配准失败不写图。
|
||||
|
||||
两个启动入口和录制工具读取 [场地点云配置](../sentry_sim/config/field_cloud.yaml)。`map` 系的保留范围为 `x=[−6.4,6.4]`、`y=[−4.4,4.4]`、`z=[−0.10,0.65]` m。定位用扫描时刻的预测位姿裁剪,并在各边留 0.20 m 余量。读图、写入关键帧和测站建图使用严格边界。默认地图文件有 17,002 个体素,启动时只加载其中 10,112 个场内体素。裁剪依赖已知初始位姿和 IMU 预测,可适应小幅位姿误差。
|
||||
|
||||
### 单独生成全场 Gazebo 地图
|
||||
|
||||
```bash
|
||||
python3 tools/capture_lio.py --profile mapping --full-field \
|
||||
--output generated/full_survey --map generated/field_full.flmap
|
||||
--output generated/full_survey --map generated/field_full_40m.flmap
|
||||
python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \
|
||||
--map generated/field_full.flmap --lio-cloud-topic /scan/points_lio --output generated/full_shell
|
||||
--map generated/field_full_40m.flmap --output generated/full_shell
|
||||
```
|
||||
|
||||
该模式在隔离的 Gazebo 空场沿重叠测站采集实际雷达扫描。测站坐标由命令指定,Gazebo 真值只核对到位误差。全场图包含南走廊的地面回波,为 LIO 提供垂直方向约束。避障用的 `/scan/points_filtered` 和 `/scan2d` 继续沿用原有的地面滤除规则。全场图对应当前仿真模型和雷达外参,改场地或更换外参后应重新采集和验收。
|
||||
|
||||
仓库随附的 `src/sentry_sim/maps/field_full_40m.flmap` 有 10,583 个体素,仍是候选图。Shell 可用 `LIO_MAP` 指定,Python 可传 `lio_map:=`。检查所有路段时可加 `--continue-on-failure`,让脚本在恢复后测试后续目标,失败路段仍计入总结果。见 [40 m 地图实测](../../docs/MID360-3D雷达接入.md)。
|
||||
|
||||
```bash
|
||||
LIO_MAP="$PWD/src/sentry_sim/maps/field_full_40m.flmap" HEADLESS=1 scripts/sentry_up.sh
|
||||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py headless:=true \
|
||||
lio_map:="$PWD/src/sentry_sim/maps/field_full_40m.flmap"
|
||||
```
|
||||
|
||||
## ROS 接口与坐标约定
|
||||
|
||||
- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。Shell、Python 启动和录制工具均使用 `/scan/points_lio`。旧版地图可配合 `LIO_POINT_CLOUD_TOPIC=/scan/points_filtered` 显式录制或启动,Python 也可传 `lio_point_cloud_topic:=/scan/points_filtered`。
|
||||
- 原始云在 `lidar_link`,自滤云在 `base_link`;适配器使用固定 TF 统一到 LiDAR 系。方位角时间估计也在 LiDAR 系完成,不重复施加安装外参。
|
||||
- 默认固定帧:`map/odom/base_link/imu_link/lidar_link`,均可通过同名 frame 参数配置。外参从现有固定 TF 读取;缺失时等待,禁止假设为恒等变换。
|
||||
- 原始云在 `lidar_link`,自滤云在 `base_link`。瞬时点云按消息时间戳转换到 `imu_link`,包含云台角度和偏心位移。两个仿真入口的关节 TF 发布频率设为 100 Hz。
|
||||
- 默认坐标系为 `map/odom/base_link/imu_link/lidar_link`,可通过同名 frame 参数配置。方位角去畸变在原生雷达坐标系计算,要求雷达与 IMU 刚性连接。
|
||||
- 内部状态原点为 IMU,`q` 将 IMU 坐标旋转到 map,`v/g` 在 map 系。误差顺序为 `p,v,theta,bg,ba,g`,右扰动态度误差。
|
||||
- `get_pose()` 返回 `map → base_link`;`get_snapshot()` 在一把互斥锁内返回配套的位姿、滤波状态、协方差与状态时间。
|
||||
- 只发布 TF `map → odom`:`T_map_odom = T_map_base × inverse(T_odom_base)`,两个变换使用同一时间。`publish_map_to_odom=false` 可关闭;不能与 AMCL 同时发布。
|
||||
- `/field_localization/odometry` 为 map 系车体位姿及变换后的位姿协方差;twist 未填充,不能用于速度反馈(速度状态可通过 core 快照读取)。不额外广播 body TF。
|
||||
- `/field_localization/odometry` 为 map 系车体位姿(含 6×6 位姿协方差)以及 `base_link` 系车体线速度/角速度 `twist`(已扣除陀螺零偏与 IMU 偏心安装杆臂速度,含 6×6 速度协方差);也可直接通过 core 快照或 `get_twist()` 读取。不额外广播 body TF。
|
||||
- 每 5 秒打印模式、降级原因、有效点数、残差 RMSE、内点数/比例、退化维数与子空间基、关键帧数和地图点数,同时输出 `/field_localization/status` 摘要。
|
||||
- 支持 `--ros-args -p use_sim_time:=true`。只有消息/ROS 仿真时间参与状态计算。检测到 `/clock` 回跳后停止输出;必须显式调用 `/field_localization/reset` 或重启,以配置的已知初始位姿重新开始。
|
||||
|
||||
@@ -89,7 +99,7 @@ build/bin/field_localization_replay --dataset generated/lio_evaluation --mode lo
|
||||
|
||||
独立真值来自 Gazebo 自带 PosePublisher,100 Hz,桥接至 `/evaluation/ground_truth` 的 PoseStamped。模型原点与 base_link 重合,世界与 map 原点一致。真值不进入定位器,不发布到 TF,也不用 `/odom` 代替真值。
|
||||
|
||||
数据集:`config.txt` 保存版本、已知初始位姿、固定外参及扫描时间模型;`imu.csv` 保存 IMU 系原始测量;`scans.csv` 索引 `clouds/*.flpc`;`truth.tum` 保存世界系真值。FLPC v1 使用固定小端标量:8 字节 magic、uint32 版本、double header 时间、uint32 点数;每点为 double 绝对时间及四个 float32。地图 FLMAP v1 为 8 字节 magic、uint32 版本、double 体素边长、uint64 点数,随后为 map 系 xyz double。均不序列化 Eigen 内存。
|
||||
新录制的 `config.txt` 附带 `cloud_frame imu_link` 和场地裁剪范围,回放重用该范围。旧数据缺少这两项时仍按原来的雷达系、固定外参及扫描时间模型读取。FLPC v1 和 FLMAP v1 的二进制格式保持不变。`imu.csv` 保存 IMU 系原始测量,`scans.csv` 索引 `clouds/*.flpc`,`truth.tum` 保存世界系真值。
|
||||
|
||||
回放工具不依赖 ROS,不读取轮速作为定位量测。输出 `trajectory.tum/status.csv/metrics.txt`;报告未对齐的平移 ATE、旋转测地角 ATE、1 秒相对位姿 RPE,旋转以度报告。真值线性平移/四元数 slerp 插值,最大真值间隔 0.05 秒。没有真值或足够对应关系时不能声称验证精度。
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# field_localization/include/
|
||||
|
||||
C++ 头文件的根目录。和 `sentry_nav/include/` 一样**按包名建子目录**,
|
||||
include 时写成 `#include "field_localization/core/xxx.hpp"`,不会和其他工程的同名头文件撞车。
|
||||
|
||||
```
|
||||
include/
|
||||
├── README.md 本文件
|
||||
└── field_localization/ ← 真正的头文件都在这层
|
||||
├── README.md 公共头文件总表
|
||||
├── core/ 纯算法层接口(8 个头,零 ROS)
|
||||
│ ├── README.md
|
||||
│ ├── types.hpp ImuData / PointXYZI / PointCloud / Pose3D
|
||||
│ ├── imu_integration.hpp 旋转数学、IMU 积分、点云去畸变
|
||||
│ ├── eskf.hpp 18 维误差状态卡尔曼滤波
|
||||
│ ├── registration.hpp 体素地图、点到面配准、退化检测
|
||||
│ ├── map_io.hpp 地图文件读写、关键帧判定
|
||||
│ ├── localization_core.hpp 定位主流程
|
||||
│ ├── dataset.hpp 数据集读写、ATE/RPE 评估、调优轨迹 CSV
|
||||
│ └── tracking_health.hpp 定位有效性(导航联锁的依据)
|
||||
└── ros/ ROS 适配层接口(2 个头,依赖 rclcpp)
|
||||
├── README.md
|
||||
├── conversion.hpp PointCloud2 / Transform 与 core 类型互转
|
||||
└── localization_node.hpp 定位节点
|
||||
```
|
||||
|
||||
## 两个子目录,依赖不一样
|
||||
|
||||
| 目录 | 能 include 什么 | 编进哪个 target |
|
||||
|---|---|---|
|
||||
| `field_localization/core/` | 只有 C++ 标准库和 Eigen | `field_localization_core`(静态库) |
|
||||
| `field_localization/ros/` | 在 core 之上再加 `rclcpp` / `tf2_ros` / 消息类型 | `field_localization_ros`(动态库) |
|
||||
|
||||
`xmake.lua` 里 `field_localization_core` 把 `include/` 设成了 `public` 头目录,
|
||||
所以依赖它的 target(节点、录制工具、回放工具、全部测试)都直接写
|
||||
`#include "field_localization/..."`,不用各自再加 include 路径。
|
||||
|
||||
## 硬规则:`core/` 的头不许 include ROS
|
||||
|
||||
`field_localization_core` 是独立静态库,它的 include 路径里没有 ROS 头文件,编译和链接时也不碰 ROS。
|
||||
本包 12 个测试里有 11 个、离线工具 `field_localization_replay` 也只依赖这个库。
|
||||
|
||||
**往 `core/` 的头里加一行 `#include <rclcpp/...>`,这些测试和工具就全部编不过。**
|
||||
|
||||
判据和 `sentry_nav` 一样:这个头需要 `rclcpp` / `tf2` / 消息类型吗?
|
||||
不需要就放 `core/`,需要就放 `ros/`。
|
||||
|
||||
## 加头文件时要改哪里
|
||||
|
||||
| 加什么 | 要不要改 `xmake.lua` |
|
||||
|---|---|
|
||||
| 头文件(放 `core/` 或 `ros/`) | **不用**,`include/` 已经是 public 头目录 |
|
||||
| `core/` 的实现 | **不用**,`src/core/*.cpp` 是通配 |
|
||||
| `ros/` 的实现 | **要**,`field_localization_ros` 是逐个文件列的 |
|
||||
|
||||
## 这个包的写法
|
||||
|
||||
- 头文件保护统一用 `#pragma once`(没有 include guard 宏)
|
||||
- 符号放在 `field_localization::core` 或 `field_localization::ros`,不往全局命名空间塞东西
|
||||
- 类型名大驼峰(`LocalizationCore`、`ErrorStateFilter`),函数名小写下划线(`scan_to_map`、`process_imu`),枚举一律 `enum class`
|
||||
- 注释中英文都有,跟随所在文件
|
||||
|
||||
## 相关
|
||||
|
||||
- 公共头文件总表:[`field_localization/README.md`](field_localization/README.md)
|
||||
- 实现:[`../src/README.md`](../src/README.md)
|
||||
- 同样的规矩在兄弟包里的版本:[`../../sentry_nav/include/README.md`](../../sentry_nav/include/README.md)
|
||||
@@ -0,0 +1,53 @@
|
||||
# include/field_localization/ (公共头文件)
|
||||
|
||||
包对外的头文件目录,10 个头,分两层。
|
||||
|
||||
| 层 | 头文件 | 实现 | 提供什么 |
|
||||
|---|---|---|---|
|
||||
| core | `core/types.hpp` | 只有头文件 | `ImuData` / `PointXYZI` / `PointCloud` / `Pose3D` |
|
||||
| core | `core/imu_integration.hpp` | `../../src/core/imu_integration.cpp` | 旋转数学、`MotionState`、IMU 积分、`deskew` |
|
||||
| core | `core/eskf.hpp` | `../../src/core/eskf.cpp` | `ErrorStateFilter`:18 维误差状态滤波 |
|
||||
| core | `core/registration.hpp` | `../../src/core/registration.cpp` | `VoxelMap`、`scan_to_map`、`detect_degeneracy` |
|
||||
| core | `core/map_io.hpp` | `../../src/core/map_io.cpp` | `save_map` / `read_map`(FLMAP v1)、`new_keyframe` |
|
||||
| core | `core/localization_core.hpp` | `../../src/core/localization_core.cpp` | `LocalizationCore`:定位主流程 |
|
||||
| core | `core/dataset.hpp` | `../../src/core/dataset.cpp` | FLPC 点云、数据集配置、TUM 轨迹、ATE/RPE、调优 CSV |
|
||||
| core | `core/tracking_health.hpp` | 只有头文件 | `TrackingHealth`:定位能否用于导航 |
|
||||
| ros | `ros/conversion.hpp` | `../../src/ros/conversion.cpp` | ROS 消息 ⇄ core 类型 |
|
||||
| ros | `ros/localization_node.hpp` | `../../src/ros/localization_node.cpp` | `LocalizationNode`:定位节点 |
|
||||
|
||||
## 两层怎么分工
|
||||
|
||||
| | `core/` | `ros/` |
|
||||
|---|---|---|
|
||||
| 能 include 什么 | 只有 C++ 标准库和 Eigen | 在 core 之上再加 `rclcpp` / `tf2_ros` / 消息类型 |
|
||||
| 编进哪个 target | `field_localization_core`(静态库) | `field_localization_ros`(动态库) |
|
||||
| 能不能脱离 ROS 测 | 能(11 个测试) | 只有 `test_ros_conversion` 测到 `conversion.hpp` |
|
||||
|
||||
## 头文件之间的依赖
|
||||
|
||||
`core/` 是一条链,上游在前,**没有环**:
|
||||
|
||||
```
|
||||
types → imu_integration → eskf → registration → map_io → localization_core → dataset
|
||||
└→ tracking_health
|
||||
```
|
||||
|
||||
`ros/` 两个头在这条链的顶端:
|
||||
|
||||
- `ros/conversion.hpp` include `core/dataset.hpp`
|
||||
- `ros/localization_node.hpp` include `ros/conversion.hpp` 和 `core/tracking_health.hpp`
|
||||
|
||||
## 加新头文件
|
||||
|
||||
放对应的层,命名 `xxx.hpp`,在 `.cpp` 里 `#include "field_localization/core/xxx.hpp"`。
|
||||
**不用改 `xmake.lua`**:`include/` 已经是 `field_localization_core` 的 public 头目录。
|
||||
|
||||
先确认它该放哪一层:这个头需要 `rclcpp` / `tf2` / 消息类型吗?
|
||||
不需要就放 `core/`,并配上不依赖 ROS 的测试;需要才放 `ros/`。
|
||||
|
||||
## 相关
|
||||
|
||||
- core 逐个头的说明和默认值:[`core/README.md`](core/README.md)
|
||||
- ros 逐个头的说明:[`ros/README.md`](ros/README.md)
|
||||
- 这层目录的规矩(`#pragma once`、命名空间、命名):[`../README.md`](../README.md)
|
||||
- 实现:[`../../src/README.md`](../../src/README.md)
|
||||
@@ -0,0 +1,224 @@
|
||||
# include/field_localization/core/ (纯算法层接口)
|
||||
|
||||
**这 8 个头只 include C++ 标准库和 Eigen,不 include 任何 ROS / PCL / tf2 头文件。**
|
||||
|
||||
它们属于静态库 `field_localization_core`。11 个测试和离线工具 `field_localization_replay`
|
||||
只链接这个库,所以不开 Gazebo、不 source ROS 也能跑。
|
||||
|
||||
依赖是一条链,上游在前,**没有环**:
|
||||
|
||||
```
|
||||
types → imu_integration → eskf → registration → map_io → localization_core → dataset
|
||||
└→ tracking_health
|
||||
```
|
||||
|
||||
加新头时别把它插成环。
|
||||
|
||||
## `types.hpp`(只有头文件)
|
||||
|
||||
后面所有头都用的四个基础结构:
|
||||
|
||||
| 类型 | 字段 | 注意 |
|
||||
|---|---|---|
|
||||
| `ImuData` | `timestamp_sec`、`frame_id`、`angular_velocity`、`linear_acceleration` | 单位 rad/s、m/s² |
|
||||
| `PointXYZI` | `timestamp_sec`、`position`、`intensity` | `position` 是 **float**(`Eigen::Vector3f`) |
|
||||
| `PointCloud` | `timestamp_sec`、`frame_id`、`points` | |
|
||||
| `Pose3D` | `rotation`(`Eigen::Quaterniond`)、`translation` | 表示「子坐标系 → 父坐标系」的变换 |
|
||||
| `Twist3D` | `linear`、`angular`(均为 `Eigen::Vector3d`) | 车体坐标系下的三维线速度(m/s)与角速度(rad/s) |
|
||||
|
||||
**所有时间戳的单位都是秒**(`double`),不是 ROS 的纳秒。
|
||||
|
||||
## `imu_integration.hpp`
|
||||
|
||||
实现:`src/core/imu_integration.cpp`。
|
||||
|
||||
| 符号 | 作用 |
|
||||
|---|---|
|
||||
| `skew(v)` / `exp_so3(v)` / `log_so3(q)` | 反对称矩阵、旋转向量 ⇄ 四元数 |
|
||||
| `compose(a, b)` / `inverse(p)` | 位姿复合与求逆 |
|
||||
| `base_twist(state, raw_w, base_from_imu)` | 扣除陀螺零偏与 IMU 偏心安装杆臂效应,求 `base_link` 刚体线速度与角速度 |
|
||||
| `valid_imu(imu)` | 时间戳合法、数值全部有限 |
|
||||
| `interpolate_imu(samples, time)` | 在相邻两个 IMU 样本之间线性插值 |
|
||||
| `integrate_midpoint(state, a, b)` | 中值积分,推进一步 |
|
||||
| `integrate_trajectory(samples, initial, end)` | 从 `initial` 积到 `end`,返回整条状态轨迹 |
|
||||
| `preintegrate(samples, start, end, bg, ba)` | 零重力的预积分。**目前只有 `test_imu_integration` 在用**,滤波器走的是 `integrate_midpoint` |
|
||||
| `interpolate_motion(trajectory, time)` | 在状态轨迹上插值:旋转 slerp,平移三次 Hermite(用两端速度) |
|
||||
| `scan_window(cloud, options)` | 这一帧扫描的起止时间 |
|
||||
| `deskew(cloud, trajectory, options)` | 把一帧内的点统一到扫描结束时刻;输出仍在传感器系 |
|
||||
|
||||
`MotionState` 是滤波器的状态:`timestamp_sec`、`pose`、`velocity`、`gyro_bias`、`accel_bias`、`gravity`(默认 `(0, 0, -9.81)`)。
|
||||
**位姿和速度都以 IMU 原点为参考,`pose.rotation` 把 IMU 系转到 map 系**,不是车体系。
|
||||
|
||||
`ScanTiming` 三种扫描时间模型:
|
||||
|
||||
| 取值 | 每个点的采集时刻 | 什么时候用 |
|
||||
|---|---|---|
|
||||
| `INSTANTANEOUS`(默认) | 整帧同一个时刻,不去畸变 | 仿真点云,header 是整帧一个时间戳 |
|
||||
| `AZIMUTH` | 从 `start_angle_rad` 起,按方位角在 `period_sec` 内扫完 | 真机没有逐点时间戳 |
|
||||
| `POINT_TIMESTAMPS` | 每个点自己的 `timestamp_sec` | 真机给了逐点时间戳;ROS 节点目前没开放这个选项 |
|
||||
|
||||
`DeskewOptions` 默认 `period_sec = 0.1`、`start_angle_rad = -π`、`counterclockwise = true`、`stamp_at_end = true`。
|
||||
`imu_from_sensor` 默认是恒等变换,实际必须按真实安装关系填(ROS 节点从 TF 读)。
|
||||
|
||||
## `eskf.hpp`
|
||||
|
||||
实现:`src/core/eskf.cpp`。误差状态卡尔曼滤波,18 维。
|
||||
|
||||
| 类型 | 作用 |
|
||||
|---|---|
|
||||
| `NoiseOptions` | 连续时间噪声密度、零偏随机游走、`integration_error_scale`、`maximum_imu_gap` |
|
||||
| `FilterSnapshot` | `state`(`MotionState`)+ 18×18 `covariance`,可以整体 `restore()` 回去 |
|
||||
| `InnovationCheck` | `FINAL`(过门限)或 `TRIAL`(配准迭代的中间步,不过门限) |
|
||||
| `ErrorStateFilter` | 滤波器本体 |
|
||||
|
||||
误差状态的顺序是**位置、速度、姿态误差(右扰动)、陀螺零偏、加计零偏、重力**,每段 3 维。
|
||||
|
||||
| 方法 | 作用 |
|
||||
|---|---|
|
||||
| `initialize(state)` | 设状态,协方差对角线设成固定初值:位置 0.01、速度 1、姿态 0.01、陀螺零偏 0.01、加计零偏 0.25、重力 0.01 |
|
||||
| `propagate(a, b)` | 用两个 IMU 样本做中值积分,同时传播协方差。间隔超过 `maximum_imu_gap` 或时间戳对不上返回 `false` |
|
||||
| `correct_pose(measurement, noise, projector)` | 直接用一位姿量测更新;`projector` 挑出哪些方向可观 |
|
||||
| `correct_information(prior, linearization, information, gradient, projector, model_covariance, check)` | 固定先验的迭代更新:残差的 Hessian(`information`)和梯度由调用方给。配准用它 |
|
||||
| `last_nis()` / `measurement_rank()` | 上一次更新的归一化新息平方和、量测秩 |
|
||||
| `snapshot()` / `restore(snapshot)` | 取 / 设整体状态 |
|
||||
| `inject(state, error)` / `difference(a, b)` | 把误差注入状态、两个状态求差(静态函数) |
|
||||
|
||||
## `registration.hpp`
|
||||
|
||||
实现:`src/core/registration.cpp`。扫描到地图的点到面配准。
|
||||
|
||||
| 符号 | 作用 |
|
||||
|---|---|
|
||||
| `VoxelMap` | 体素哈希地图,每个体素只留一个点;`plane(point, radius)` 拟合该点邻域的平面并缓存 |
|
||||
| `Plane` | `center`、`normal`、`support_radius`、`valid` |
|
||||
| `voxel_downsample(cloud, resolution)` | 扫描体素降采样,每个体素留第一个点 |
|
||||
| `detect_degeneracy(h, options)` | 对 6×6 信息矩阵做 SVD,分出可观方向(`projector`)和退化方向(`null_basis`) |
|
||||
| `scan_to_map(cloud, imu_from_sensor, map, prediction, noise, options)` | 迭代配准,返回 `RegistrationResult`,成功时 `estimate` 是更新后的滤波状态 |
|
||||
| `inspect_scan_support(...)` | 只统计某个位姿下的关联计数,不更新。回放工具的 `--inspect-scan` 用它 |
|
||||
|
||||
`VoxelMap::plane()` 判定平面的条件:邻域里至少 5 个点,取最近的至多 20 个做主成分分析,
|
||||
最小特征值与第二小特征值之比小于 0.03。
|
||||
**有限大的平面不是无限延伸的墙**:查询点在平面内的投影超出 `support_radius` 一个体素以上,
|
||||
就不算这个平面的对应(计入 `outside_support`)。
|
||||
|
||||
`scan_to_map()` 的阶段和失败原因:
|
||||
|
||||
| 阶段(`RegistrationStage`) | 做什么 | 可能的失败(`RegistrationFailure`) |
|
||||
|---|---|---|
|
||||
| `INITIAL_MATCH` | 在预测位姿处找点到面对应 | `NO_CORRESPONDENCES`(内点少于 `minimum_inliers`);`DEGENERATE`(六个方向全退化) |
|
||||
| `ITERATION` | 最多迭代 `maximum_iterations` 次,每次在私有滤波器里做一步不过门限的试更新 | `INNOVATION`;`QUALITY`(相对先验的修正达到 0.5 m 或 0.35 rad) |
|
||||
| `FINAL_FUSION` | 用收敛后的对应关系,对原始先验做一次**过门限**的正式更新 | `INNOVATION`;`QUALITY`(内点率、RMSE 或修正幅度不达标,阶段停在 `FINAL_FUSION`) |
|
||||
| `COMPLETE` | 成功,`failure == NONE` | 无 |
|
||||
|
||||
`AssociationCounts` 把每一帧的关联过程记成五个数:
|
||||
`sampled` → `candidate_planes` → `outside_support` / `plane_distance_rejected` / `inliers`。
|
||||
`RegistrationResult` 里存了初始和最后一次的计数,`test_registration.cpp` 断言它们满足
|
||||
`candidate_planes == outside_support + plane_distance_rejected + inliers`。
|
||||
|
||||
`map_translation_sigma` / `map_rotation_sigma` 是**地图和关联本身的不确定度**,
|
||||
不随扫描点数增加而缩小,防止把几百个相关的点残差当成几百个独立的绝对位姿观测。
|
||||
要求精确地图的单测(合成地图)会显式把它们设成 0。
|
||||
|
||||
## `map_io.hpp`
|
||||
|
||||
实现:`src/core/map_io.cpp`。
|
||||
|
||||
| 符号 | 作用 |
|
||||
|---|---|
|
||||
| `save_map(map, path, error)` | 写 FLMAP v1。先写 `path.tmp` 再改名,拒绝保存空地图 |
|
||||
| `read_map(path, error)` | 读 FLMAP v1,带完整性检查 |
|
||||
| `new_keyframe(previous, current)` | 位移超过 0.5 m **或** 旋转超过 10° 才算新关键帧(都是严格大于) |
|
||||
|
||||
FLMAP v1 的布局(小端):8 字节魔数 `FLMAP0001`、`uint32` 版本号、`double` 体素边长、
|
||||
`uint64` 点数,然后每个点 3 个 `double`。`read_map` 会核对文件长度恰好等于 `28 + 24 × 点数`,
|
||||
并拒绝超过 500 万点、非有限坐标、坐标绝对值与体素边长之比超过 1e12 的点。
|
||||
|
||||
## `localization_core.hpp`
|
||||
|
||||
实现:`src/core/localization_core.cpp`。定位主流程,把上面几样串起来。
|
||||
|
||||
| 类型 | 作用 |
|
||||
|---|---|
|
||||
| `MapMode` | `MAPPING`(边走边建图)或 `LOCALIZATION`(只读地图,默认) |
|
||||
| `CoreOptions` | 模式、分辨率、`RegistrationOptions`、`NoiseOptions`、已知初始位姿、`base_from_imu`、`DeskewOptions` |
|
||||
| `TrackingMode` | `FULL`(当前有有效的激光约束)或 `IMU_ONLY`(只有预测) |
|
||||
| `FailureReason` | 没进 `FULL` 的原因:`INITIALIZING`、`NO_VALID_POINTS`、`INVALID_INPUT`、`TIME_ORDER`、`IMU_GAP`、`IMU_COVERAGE`、`REGISTRATION_FAILED`、`LIDAR_TIMEOUT`、`MAP_UNAVAILABLE` |
|
||||
| `LocalizationStatus` | 模式、原因、各种计数、最近一次配准的残差 / 内点 / 退化方向、关键帧数、地图点数 |
|
||||
| `LocalizationSnapshot` | `pose` + `filter` + `status`,在**同一把锁**里一起取出来 |
|
||||
| `LocalizationCore` | 本体:`process_imu` / `process_point_cloud` / `get_snapshot` / `load_map` / `export_map` / `set_pose` / `reset` |
|
||||
|
||||
几条约定:
|
||||
|
||||
- **所有公有方法都上锁**,可以从 ROS 回调线程和定时器线程同时调
|
||||
- `get_pose()` 和 `LocalizationSnapshot::pose` 是 **map → base_link**;滤波器内部状态的原点是 IMU
|
||||
- `process_imu` / `process_point_cloud` 的返回值只表示「这份输入收下了没有」,**不等于完成了一次激光更新**。要看 `status.mode` 和 `accepted_corrections`
|
||||
- 必须已知初始位姿:没有全局重定位,`reset()` 也只回到 `CoreOptions::initial_pose`
|
||||
- `reset()` 只在 `MAPPING` 模式下清空地图
|
||||
|
||||
## `dataset.hpp`
|
||||
|
||||
实现:`src/core/dataset.cpp`。离线数据的读写和打分,在线定位不用。
|
||||
|
||||
| 符号 | 作用 |
|
||||
|---|---|
|
||||
| `write_cloud` / `read_cloud` | FLPC v1 点云文件(`.flpc`) |
|
||||
| `write_dataset_config` / `read_dataset_config` | 数据集目录里的 `config.txt`:已知初始位姿、两组固定外参、扫描时间模型 |
|
||||
| `read_trajectory` / `write_trajectory_sample` / `trajectory_pose` | TUM 文本轨迹及其插值(真值间隔超过上限时拒绝插值) |
|
||||
| `evaluate(estimate, truth)` | 未对齐的 ATE(平移 / 旋转)和 1 秒相对位姿误差 RPE |
|
||||
| `write_filter_trace_header` / `write_filter_trace` | 每帧三行的调优 CSV:状态、18×18 协方差、6×6 信息矩阵、梯度、奇异值、配准阶段和关联计数 |
|
||||
| `mode_name` / `reason_name` | 枚举转字符串,日志用 |
|
||||
|
||||
FLPC v1 的布局(小端):8 字节魔数 `FLPC0001`、`uint32` 版本号、`double` 帧时间戳、
|
||||
`uint32` 点数,然后每个点 1 个 `double` 时间戳 + 3 个 `float` 坐标 + 1 个 `float` 强度。
|
||||
文件长度必须是 `24 + 24 × 点数`,单帧最多 100 万点。
|
||||
|
||||
两种二进制格式都逐个字段序列化,不直接写 Eigen 对象的内存。
|
||||
|
||||
## `tracking_health.hpp`(只有头文件)
|
||||
|
||||
定位结果能不能拿去导航。`ros/localization_node.cpp` 用它决定是否继续发布 `map → odom`
|
||||
和 `/field_localization/navigation_valid`,后者是 `sentry_nav` 的 `cmd_vel_relay` 的联锁输入。
|
||||
|
||||
`TrackingHealth::update(snapshot, base_from_imu, now)` 返回当前是否有效。规则(`HealthOptions` 默认值):
|
||||
|
||||
| 条件 | 限值 |
|
||||
|---|---|
|
||||
| 最近一次成功配准距今 | ≤ 0.3 s |
|
||||
| IMU 状态距今 | ≤ 0.1 s(允许 `now` 比状态时间戳早 0.05 s,容忍时钟投递偏差) |
|
||||
| 水平位置 3σ(取 xy 协方差块的最大特征值方向) | ≤ 0.5 m |
|
||||
| 航向 3σ | ≤ 15° |
|
||||
| 恢复有效 | 连续 **5 帧**成功配准。数的是 `accepted_corrections`,不是定时器节拍 |
|
||||
|
||||
任何一条不满足就立刻失效并把连续计数清零;`accepted_corrections` 倒退(被 reset)也判失效。
|
||||
|
||||
`base_pose_covariance()` 与 `base_twist_covariance()` 分别通过 6×18 解析雅可比把 IMU 原点的位姿/速度/零偏协方差换算到 `base_link`(其中速度协方差额外叠加单步陀螺采样白噪声),`update()` 和 ROS 节点都用它们。
|
||||
|
||||
## 默认值速查
|
||||
|
||||
以头文件为准,改了默认值记得同步这里:
|
||||
|
||||
| 项 | 默认值 | 在哪 |
|
||||
|---|---|---|
|
||||
| 地图 / 扫描体素 | 0.1 m | `CoreOptions::map_resolution`、`RegistrationOptions::scan_voxel` |
|
||||
| 邻域半径 | 0.5 m | `RegistrationOptions::neighborhood_radius` |
|
||||
| 点量测 σ | 0.02 m | `RegistrationOptions::measurement_sigma` |
|
||||
| Huber 阈值 | 0.025 m | `RegistrationOptions::huber_threshold` |
|
||||
| 点到面距离上限 | 0.12 m | `RegistrationOptions::max_plane_distance` |
|
||||
| 地图平移 / 旋转不确定度 | 0.03 m / 0.002 rad | `RegistrationOptions::map_translation_sigma` / `map_rotation_sigma` |
|
||||
| 最多迭代 | 10 次 | `RegistrationOptions::maximum_iterations` |
|
||||
| 成功门槛 | 内点 ≥ 50、内点率 ≥ 20%、RMSE ≤ 0.1 m | `RegistrationOptions` |
|
||||
| 退化判定 | 相对 1e-4、绝对 1e-6 | `RegistrationOptions::degeneracy_relative` / `degeneracy_absolute` |
|
||||
| 陀螺 / 加计噪声密度 | 0.003 rad/s/√Hz、0.03 m/s²/√Hz | `NoiseOptions::gyro` / `accel` |
|
||||
| 陀螺 / 加计零偏随机游走 | 1e-5、1e-4 | `NoiseOptions::gyro_bias_walk` / `accel_bias_walk` |
|
||||
| 积分误差尺度 | 1.4 | `NoiseOptions::integration_error_scale` |
|
||||
| IMU 最大间隔 | 0.05 s | `NoiseOptions::maximum_imu_gap` |
|
||||
| IMU 相对 base_link 的位置 | z = 0.15 m | `CoreOptions::base_from_imu`(ROS 节点会用 TF 覆盖) |
|
||||
| 新息门限 | 按量测秩取卡方 99.9% 分位 | `eskf.cpp` 里的 `gates[]` |
|
||||
| 新关键帧 | 位移 > 0.5 m 或旋转 > 10° | `map_io.cpp` 的 `new_keyframe()` |
|
||||
| 导航有效性 | 配准超时 0.3 s、IMU 超时 0.1 s、位置 3σ 0.5 m、航向 3σ 15°、恢复 5 帧 | `HealthOptions` |
|
||||
|
||||
## 相关
|
||||
|
||||
- 实现细节:[`../../../src/core/README.md`](../../../src/core/README.md)
|
||||
- 上层的 ROS 接口:[`../ros/README.md`](../ros/README.md)
|
||||
- 测试:[`../../../tests/README.md`](../../../tests/README.md)
|
||||
@@ -3,9 +3,10 @@
|
||||
namespace field_localization::core {
|
||||
// Versioned little-endian scalar encoding; never serializes Eigen object memory.
|
||||
void write_cloud(const PointCloud &cloud,const std::filesystem::path &path);
|
||||
PointCloud read_cloud(const std::filesystem::path &path);
|
||||
void write_dataset_config(const CoreOptions &options,const std::filesystem::path &path);
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path);
|
||||
PointCloud read_cloud(const std::filesystem::path &path,const std::string &frame="lidar_link");
|
||||
void write_dataset_config(const CoreOptions &options,const std::filesystem::path &path,
|
||||
const std::string &cloud_frame="lidar_link");
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path,std::string *cloud_frame=nullptr);
|
||||
struct TrajectorySample { double time; Pose3D pose; };
|
||||
std::vector<TrajectorySample> read_trajectory(const std::filesystem::path &path);
|
||||
void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample);
|
||||
|
||||
@@ -19,6 +19,9 @@ struct MotionState {
|
||||
Eigen::Vector3d accel_bias{Eigen::Vector3d::Zero()};
|
||||
Eigen::Vector3d gravity{0.0, 0.0, -9.81};
|
||||
};
|
||||
// Body-frame (base_link) linear and angular velocity with gyro-bias and lever-arm compensation.
|
||||
Twist3D base_twist(const MotionState &state, const Eigen::Vector3d &raw_angular_velocity,
|
||||
const Pose3D &base_from_imu);
|
||||
struct Preintegration {
|
||||
Eigen::Quaterniond dR{Eigen::Quaterniond::Identity()};
|
||||
Eigen::Vector3d dv{Eigen::Vector3d::Zero()};
|
||||
|
||||
@@ -52,11 +52,16 @@ struct CoreOptions {
|
||||
Pose3D initial_pose;
|
||||
Pose3D base_from_imu{Eigen::Quaterniond::Identity(), Eigen::Vector3d{0,0,0.15}};
|
||||
DeskewOptions deskew;
|
||||
std::optional<MapBounds> map_bounds;
|
||||
};
|
||||
inline constexpr double map_association_margin=0.20;
|
||||
struct LocalizationSnapshot {
|
||||
Pose3D pose;
|
||||
FilterSnapshot filter;
|
||||
LocalizationStatus status;
|
||||
Twist3D twist{};
|
||||
Eigen::Vector3d raw_angular_velocity{Eigen::Vector3d::Zero()};
|
||||
double imu_dt{0.0};
|
||||
};
|
||||
class LocalizationCore {
|
||||
public:
|
||||
@@ -76,6 +81,9 @@ public:
|
||||
// 获取当前位姿
|
||||
[[nodiscard]] Pose3D get_pose() const;
|
||||
|
||||
// 获取当前车体坐标系(base_link)线速度与角速度
|
||||
[[nodiscard]] Twist3D get_twist() const;
|
||||
|
||||
// 设置位姿(用于初始化和后续算法集成)
|
||||
void set_pose(const Pose3D &pose);
|
||||
|
||||
@@ -88,7 +96,7 @@ public:
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
CoreOptions options_;
|
||||
const CoreOptions options_;
|
||||
VoxelMap map_;
|
||||
double last_correction_time_{-1.0};
|
||||
std::optional<Pose3D> last_keyframe_;
|
||||
@@ -97,6 +105,8 @@ private:
|
||||
std::vector<ImuData> imu_history_;
|
||||
std::vector<FilterSnapshot> state_history_;
|
||||
Pose3D pose_{};
|
||||
Twist3D twist_{};
|
||||
double last_imu_dt_{0.0};
|
||||
LocalizationStatus status_{};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
#pragma once
|
||||
#include "field_localization/core/registration.hpp"
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
namespace field_localization::core {
|
||||
struct MapBounds {
|
||||
Eigen::Vector3d min;
|
||||
Eigen::Vector3d max;
|
||||
bool valid() const;
|
||||
bool contains(const Eigen::Vector3d &point,double margin=0.0) const;
|
||||
};
|
||||
PointCloud crop_to_map(const PointCloud &cloud,const Pose3D &map_from_sensor,
|
||||
const MapBounds &bounds,double margin=0.0);
|
||||
bool save_map(const VoxelMap &map,const std::filesystem::path &path,std::string &error);
|
||||
std::optional<VoxelMap> read_map(const std::filesystem::path &path,std::string &error);
|
||||
std::optional<VoxelMap> read_map(const std::filesystem::path &path,std::string &error,
|
||||
const std::optional<MapBounds> &bounds={});
|
||||
bool new_keyframe(const Pose3D &previous,const Pose3D ¤t);
|
||||
} // namespace field_localization::core
|
||||
@@ -11,6 +11,26 @@ inline Matrix6 base_pose_covariance(const LocalizationSnapshot &s,const Pose3D &
|
||||
j.block<3,3>(3,6)=base_from_imu.rotation.toRotationMatrix();
|
||||
return j*s.filter.covariance*j.transpose();
|
||||
}
|
||||
inline Matrix6 base_twist_covariance(const LocalizationSnapshot &s,const Pose3D &base_from_imu,
|
||||
double gyro_noise_density=0.0) {
|
||||
const Eigen::Matrix3d r_bi=base_from_imu.rotation.normalized().toRotationMatrix();
|
||||
const Eigen::Matrix3d r_mi=s.filter.state.pose.rotation.normalized().toRotationMatrix();
|
||||
const Eigen::Matrix3d lever_r=skew(base_from_imu.translation)*r_bi;
|
||||
Eigen::Matrix<double,6,18> j=Eigen::Matrix<double,6,18>::Zero();
|
||||
j.block<3,3>(0,3)=r_bi*r_mi.transpose();
|
||||
j.block<3,3>(0,6)=r_bi*skew(r_mi.transpose()*s.filter.state.velocity);
|
||||
j.block<3,3>(0,9)=-lever_r;
|
||||
j.block<3,3>(3,9)=-r_bi;
|
||||
Matrix6 cov=j*s.filter.covariance*j.transpose();
|
||||
if(gyro_noise_density>0.0 && s.imu_dt>1e-6) {
|
||||
const double sample_var=(gyro_noise_density*gyro_noise_density)/s.imu_dt;
|
||||
Eigen::Matrix<double,6,3> g;
|
||||
g.topRows<3>()=-lever_r;
|
||||
g.bottomRows<3>()=-r_bi;
|
||||
cov.noalias()+=sample_var*(g*g.transpose());
|
||||
}
|
||||
return 0.5*(cov+cov.transpose());
|
||||
}
|
||||
struct HealthOptions {
|
||||
double correction_timeout{0.3},imu_timeout{0.1},clock_tolerance{0.05};
|
||||
double position_three_sigma{0.5},yaw_three_sigma{15*std::numbers::pi/180};
|
||||
|
||||
@@ -39,4 +39,10 @@ struct Pose3D {
|
||||
Eigen::Vector3d translation{Eigen::Vector3d::Zero()};
|
||||
};
|
||||
|
||||
struct Twist3D {
|
||||
Eigen::Vector3d linear{Eigen::Vector3d::Zero()};
|
||||
|
||||
Eigen::Vector3d angular{Eigen::Vector3d::Zero()};
|
||||
};
|
||||
|
||||
} // namespace field_localization::core
|
||||
@@ -0,0 +1,61 @@
|
||||
# include/field_localization/ros/ (ROS 适配层接口)
|
||||
|
||||
两个头,是 core 和 ROS 之间需要碰 `rclcpp` 的地方。编进 `field_localization_ros`(动态库)。
|
||||
|
||||
| 头文件 | 实现 | 提供什么 |
|
||||
|---|---|---|
|
||||
| `conversion.hpp` | `src/ros/conversion.cpp` | ROS 消息和 core 类型互转 |
|
||||
| `localization_node.hpp` | `src/ros/localization_node.cpp` | `LocalizationNode` 类声明 |
|
||||
|
||||
## `conversion.hpp`
|
||||
|
||||
```cpp
|
||||
namespace field_localization::ros {
|
||||
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg);
|
||||
core::Pose3D from_transform(const geometry_msgs::msg::Transform &transform);
|
||||
geometry_msgs::msg::Transform to_transform(const core::Pose3D &pose);
|
||||
geometry_msgs::msg::Twist to_twist(const core::Twist3D &twist);
|
||||
}
|
||||
```
|
||||
|
||||
三个函数都是纯函数,只依赖消息类型,不碰节点,所以 `tests/test_ros_conversion.cpp`
|
||||
能不起节点直接测。
|
||||
|
||||
`convert_cloud()` 被两个可执行文件用到:定位节点和录制工具 `field_localization_record`。
|
||||
它的要求(不满足就抛 `std::runtime_error`):
|
||||
|
||||
| 检查 | 要求 |
|
||||
|---|---|
|
||||
| 字段 | `x` / `y` / `z` 必须有,`intensity` 可选;类型必须是 `FLOAT32`,偏移不能越过 `point_step` |
|
||||
| 布局 | `point_step` 不为 0,`width × point_step ≤ row_step`,`row_step × height ≤ data 长度`,总点数 ≤ 100 万 |
|
||||
| 字节序 | 按 `is_bigendian` 转到本机字节序,行尾的填充字节会被跳过 |
|
||||
| 单点 | 坐标或强度非有限的点直接丢掉,不抛异常 |
|
||||
|
||||
输出的点在消息自己的 `frame_id` 下,时间戳取 header,单位换成秒。
|
||||
|
||||
## `localization_node.hpp`
|
||||
|
||||
`LocalizationNode` 的成员列表。对外只有构造函数和析构函数,其余全是私有回调。
|
||||
参数、话题、服务这些「怎么用」的内容在 [`../../../src/ros/README.md`](../../../src/ros/README.md)。
|
||||
|
||||
它继承 `rclcpp::Node`,头文件里带着 `tf2_ros` 的 Buffer / Listener / Broadcaster、
|
||||
`TrackingHealth` 和调优 CSV 的 `std::ofstream`。
|
||||
**只有 `src/ros/localization_node.cpp` 和 `src/ros/main.cpp` include 它。**
|
||||
外部代码不要 include,按话题和服务对接就行。
|
||||
|
||||
## 加新东西放哪
|
||||
|
||||
| 要加的 | 放哪 |
|
||||
|---|---|
|
||||
| 新的消息 ⇄ core 转换函数 | `conversion.hpp` + `conversion.cpp`,写成纯函数,在 `test_ros_conversion` 里补用例 |
|
||||
| 新的订阅 / 发布 / 服务 | `localization_node.hpp` + `localization_node.cpp` |
|
||||
| 不依赖 ROS 的逻辑 | 不放这里,放 `core/` |
|
||||
|
||||
`src/ros/` 下的 `.cpp` 在 `xmake.lua` 里是逐个列出来的(不是通配),
|
||||
加新的实现文件必须去 `field_localization_ros` 的文件列表里补一行。
|
||||
|
||||
## 相关
|
||||
|
||||
- 怎么用这个节点:[`../../../src/ros/README.md`](../../../src/ros/README.md)
|
||||
- 被适配的 core:[`../core/README.md`](../core/README.md)
|
||||
- 测试:[`../../../tests/README.md`](../../../tests/README.md)
|
||||
@@ -2,8 +2,15 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
#include <geometry_msgs/msg/transform.hpp>
|
||||
#include <geometry_msgs/msg/twist.hpp>
|
||||
#include <tf2_ros/buffer.hpp>
|
||||
namespace rclcpp { class Node; }
|
||||
namespace field_localization::ros {
|
||||
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg);
|
||||
core::PointCloud convert_cloud_in_frame(const sensor_msgs::msg::PointCloud2 &msg,
|
||||
const std::string &frame,const tf2_ros::Buffer &buffer);
|
||||
std::optional<core::MapBounds> declare_map_bounds(rclcpp::Node &node);
|
||||
core::Pose3D from_transform(const geometry_msgs::msg::Transform &transform);
|
||||
geometry_msgs::msg::Transform to_transform(const core::Pose3D &pose);
|
||||
geometry_msgs::msg::Twist to_twist(const core::Twist3D &twist);
|
||||
} // namespace field_localization::ros
|
||||
@@ -0,0 +1,89 @@
|
||||
# field_localization/src/ (实现文件)
|
||||
|
||||
C++ 实现的根目录,分三块:**纯算法核心**(`core/`)、**ROS 适配**(`ros/`)、**离线工具**(`tools/`)。
|
||||
|
||||
```
|
||||
src/
|
||||
├── README.md 本文件
|
||||
├── core/ ★ 纯算法核心(零 ROS,只用标准库和 Eigen)
|
||||
│ ├── README.md
|
||||
│ ├── imu_integration.cpp 旋转数学、IMU 积分、去畸变
|
||||
│ ├── eskf.cpp 18 维误差状态滤波
|
||||
│ ├── registration.cpp 体素地图、点到面配准、退化检测
|
||||
│ ├── map_io.cpp 地图文件读写、关键帧判定
|
||||
│ ├── localization_core.cpp 定位主流程
|
||||
│ └── dataset.cpp 数据集读写、ATE/RPE、调优轨迹 CSV
|
||||
├── ros/ ROS 适配
|
||||
│ ├── README.md
|
||||
│ ├── main.cpp 定位节点的入口
|
||||
│ ├── localization_node.cpp 定位节点
|
||||
│ └── conversion.cpp ROS 消息 ⇄ core 类型
|
||||
└── tools/ 命令行工具
|
||||
├── README.md
|
||||
├── record.cpp 录数据集(ROS 节点)
|
||||
└── replay.cpp 离线回放打分(不依赖 ROS)
|
||||
```
|
||||
|
||||
## 哪个文件编进哪个 target
|
||||
|
||||
定义都在 [`../xmake.lua`](../xmake.lua),产物统一落在 `build/bin/`。
|
||||
|
||||
| target | 类型 | 用到的文件 | 依赖 ROS |
|
||||
|---|---|---|---|
|
||||
| `field_localization_core` | 静态库 | `core/*.cpp`(**通配**) | 否 |
|
||||
| `field_localization_ros` | 动态库 | `ros/localization_node.cpp`、`ros/conversion.cpp`(逐个列出) | 是 |
|
||||
| `field_localization_node` | 可执行 | `ros/main.cpp` | 是 |
|
||||
| `field_localization_record` | 可执行 | `tools/record.cpp` | 是 |
|
||||
| `field_localization_replay` | 可执行 | `tools/replay.cpp` | 否 |
|
||||
|
||||
此外还有 12 个测试 target,每个对应 `tests/` 里的一个 `test_*.cpp`,
|
||||
除 `test_ros_conversion` 外都只依赖 `field_localization_core`。
|
||||
|
||||
## 构建和运行
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev # 仓库根
|
||||
xmake # 编译,先 source ROS 环境
|
||||
xmake test # 单元测试
|
||||
```
|
||||
|
||||
本工程不用 ament / colcon,没有 `ros2 run`,产物直接按路径执行:
|
||||
|
||||
```bash
|
||||
build/bin/field_localization_node --ros-args -p use_sim_time:=true ...
|
||||
build/bin/field_localization_replay --dataset <目录> --mode localization --map <地图> --output <目录>
|
||||
```
|
||||
|
||||
平时不用手敲:`scripts/sentry_up.sh` 和
|
||||
[`sentry_arena.launch.py`](../../sentry_sim/launch/sentry_arena.launch.py) 会带好参数把节点拉起来。
|
||||
|
||||
## 这三层各管什么
|
||||
|
||||
| 层 | 该写 | 不该写 |
|
||||
|---|---|---|
|
||||
| `core/` | 滤波、积分、配准、地图、文件格式、有效性判定 | 订阅话题、读 ROS 参数、查 TF |
|
||||
| `ros/` | 参数、话题、服务、TF、扫描排队、QoS | 数学和状态逻辑 |
|
||||
| `tools/` | 命令行参数解析、文件输出、打印 | 算法(调用 core 就行) |
|
||||
|
||||
判据和 `sentry_nav` 相同:**这段代码去掉 `rclcpp` 还能写出来吗?** 能就放 `core/`。
|
||||
|
||||
## 加文件时要改哪里
|
||||
|
||||
| 加什么 | 放哪 | 改不改 `xmake.lua` |
|
||||
|---|---|---|
|
||||
| 新算法 | `core/xxx.cpp` | 不用(通配) |
|
||||
| ROS 适配的新实现 | `ros/xxx.cpp` | **要**,加进 `field_localization_ros` 的文件列表 |
|
||||
| 新的可执行文件 | `ros/` 或 `tools/` | **要**,新开一个 target |
|
||||
| 新测试 | `tests/test_xxx.cpp` | **要**,新开一个 target 并 `add_tests` |
|
||||
|
||||
新开 target 时记得抄上 `set_targetdir("$(builddir)/bin")`,
|
||||
否则产物会落到 xmake 默认的 `build/<平台>/<架构>/<模式>/`,和文档、脚本里的路径对不上。
|
||||
|
||||
## 相关
|
||||
|
||||
- 算法细节:[`core/README.md`](core/README.md)
|
||||
- 节点怎么用:[`ros/README.md`](ros/README.md)
|
||||
- 工具怎么用:[`tools/README.md`](tools/README.md)
|
||||
- 接口:[`../include/README.md`](../include/README.md)
|
||||
- 测试:[`../tests/README.md`](../tests/README.md)
|
||||
- 包总览:[`../README.md`](../README.md)
|
||||
@@ -0,0 +1,160 @@
|
||||
# field_localization/src/core/ (纯算法核心)
|
||||
|
||||
**这里的一切都必须能在没有 ROS、没有 Gazebo 的情况下编译和测试。**
|
||||
|
||||
六个实现文件编成静态库 `field_localization_core`,只依赖 C++ 标准库和
|
||||
Eigen 3.4(系统 pkg-config 的 `eigen3`)。
|
||||
接口在 [`../../include/field_localization/core/`](../../include/field_localization/core/README.md),
|
||||
其中 `types.hpp` 和 `tracking_health.hpp` 只有头文件,没有对应的 `.cpp`。
|
||||
|
||||
```
|
||||
core/
|
||||
├── README.md 本文件
|
||||
├── imu_integration.cpp 旋转数学、IMU 中值积分、轨迹插值、点云去畸变
|
||||
├── eskf.cpp 18 维误差状态滤波
|
||||
├── registration.cpp 体素地图、点到面配准、退化检测
|
||||
├── map_io.cpp FLMAP 地图读写、关键帧判定
|
||||
├── localization_core.cpp 定位主流程(IMU 预测 + 激光更新)
|
||||
└── dataset.cpp FLPC 点云、数据集配置、TUM 轨迹、ATE/RPE、调优 CSV
|
||||
```
|
||||
|
||||
## 唯一的硬规则
|
||||
|
||||
> **不许 `#include` 任何 `rclcpp` / `tf2` / ROS 消息类型,也不许用 PCL。**
|
||||
> 只允许 C++ 标准库和 Eigen。
|
||||
|
||||
`field_localization_core` 的 include 路径里没有 ROS 头文件,链接时也不碰 ROS,
|
||||
所以违反了这条直接编不过。
|
||||
|
||||
本包 12 个测试里有 11 个、离线工具 `field_localization_replay` 都只链接这个库,
|
||||
所以能用 `xmake test` 在不开 Gazebo 的情况下验证算法。
|
||||
输入输出只用 `types.hpp` 里的几个结构体(`ImuData` / `PointCloud` / `Pose3D`),
|
||||
ROS 消息的转换全部留在 `../ros/conversion.cpp`。
|
||||
|
||||
## 一帧数据走一遍的流程
|
||||
|
||||
`localization_core.cpp` 是入口,其余五个文件各管一段:
|
||||
|
||||
```
|
||||
IMU 样本 ──▶ process_imu
|
||||
├─ eskf.cpp propagate:中值积分推进一步,传播协方差
|
||||
└─ 记进最近 2 秒的历史(imu_history_ / state_history_)
|
||||
|
||||
点云 ──────▶ process_point_cloud
|
||||
├─ imu_integration.cpp scan_window + deskew:按 IMU 轨迹把点统一到扫描结束时刻
|
||||
├─ eskf.cpp 重建「扫描结束时刻」的滤波状态 at_scan
|
||||
├─ registration.cpp scan_to_map:在体素地图上做点到面迭代配准
|
||||
│ └─ eskf.cpp correct_information:更新 at_scan
|
||||
├─ eskf.cpp 从扫描结束时刻把状态重新传播到最新的 IMU
|
||||
└─ map_io.cpp MAPPING 模式下,够新且无退化才插关键帧
|
||||
```
|
||||
|
||||
## 六个文件各管什么
|
||||
|
||||
### `imu_integration.cpp`
|
||||
|
||||
- **旋转数学**:`skew`、`exp_so3`、`log_so3`,以及位姿的 `compose` / `inverse`
|
||||
- `integrate_midpoint()`:两个样本的角速度和比力取平均、减零偏;姿态先用半步旋转更新,
|
||||
再用更新后的姿态把比力转到 map 系,累加速度和位置
|
||||
- `integrate_trajectory()`:沿一组 IMU 样本从初始状态积到 `end`,首尾用 `interpolate_imu()` 对齐到精确时刻
|
||||
- `interpolate_motion()`:旋转 slerp,平移用三次 Hermite 插值(带上两端速度),匀加速运动插值不出错
|
||||
- `deskew()`:取扫描结束时刻的位姿作参考,把每个点按它自己采集时刻的传感器位姿变换过去。
|
||||
非有限的点直接丢
|
||||
- `preintegrate()`:目前只有 `test_imu_integration` 在用,滤波器走的是 `integrate_midpoint`
|
||||
|
||||
### `eskf.cpp`
|
||||
|
||||
18 维误差状态:位置 3、速度 3、姿态误差 3(右扰动)、陀螺零偏 3、加计零偏 3、重力 3。
|
||||
|
||||
- `propagate()`:状态转移矩阵取到二阶(`I + F·dt + ½F²·dt²`),过程噪声 `½·dt·(Qc + Φ·Qc·Φᵀ)`。
|
||||
**再加一项积分误差**:相邻两个样本的加速度、角速度差得越多,这一步注入的不确定度越大
|
||||
(`integration_error_scale`)。有了这一项,无噪声仿真里的接触冲击不会被误当成加计零偏
|
||||
- `update()`:`S = H·P·Hᵀ + R`,新息门限按**实际量测秩**查卡方 99.9% 分位表;
|
||||
协方差用 Joseph 形式更新,姿态误差注入后用右雅可比重置;
|
||||
更新完检查协方差正定,不正定就整步放弃
|
||||
- `correct_pose()`:先把不可观的方向从量测里投影掉再算增益。只投影增益的位姿行不行,
|
||||
不可观的新息会顺着相关性污染速度和零偏
|
||||
- `correct_information()`:把 6×6 信息矩阵白化成等效量测。迭代过程中线性化点在变,
|
||||
切空间要用右雅可比搬到固定先验的坐标下
|
||||
- 所有入口遇到非有限输入、非法时间间隔都返回 `false`,不抛异常
|
||||
|
||||
### `registration.cpp`
|
||||
|
||||
- `VoxelMap`:体素哈希表,每个体素只留第一个点。`plane()` 的拟合结果按体素缓存,
|
||||
地图一变(`insert()` / `clear()`)缓存作废
|
||||
- `VoxelMap::plane()`:在 `radius` 邻域里找点,至少 5 个,取最近的至多 20 个做主成分分析;
|
||||
最小特征值与第二小特征值之比小于 0.03 才算平面
|
||||
- `linearize()`(文件内私有):对每个点找对应平面、算点到面残差和 Huber 权重,
|
||||
累加 6×6 的 Hessian 和梯度,同时数出 `AssociationCounts`
|
||||
- `detect_degeneracy()`:对信息矩阵做 SVD,奇异值低于阈值的方向是退化方向,其余是可观方向(`projector`)。
|
||||
配准只更新可观方向
|
||||
- `scan_to_map()`:迭代配准。阶段和失败原因见接口说明里的
|
||||
[`registration.hpp`](../../include/field_localization/core/README.md)
|
||||
- Hessian 按内点数归一化之后才做退化检测
|
||||
|
||||
### `map_io.cpp`
|
||||
|
||||
- `save_map()` / `read_map()`:FLMAP v1 二进制地图。保存是先写临时文件再改名;
|
||||
读取时核对魔数、版本号和文件长度
|
||||
- `new_keyframe()`:位移严格大于 0.5 m 或旋转严格大于 10° 才算新关键帧
|
||||
|
||||
### `localization_core.cpp`
|
||||
|
||||
定位主流程,把上面几样串起来。
|
||||
|
||||
- 构造:用已知初始位姿和 `base_from_imu` 初始化滤波器
|
||||
- `process_imu()`:输入检查 → 传播 → 记历史。
|
||||
IMU 断档(间隔超过 `maximum_imu_gap`)时把协方差对角线加 1.0 并清空历史,报 `IMU_GAP`;
|
||||
IMU 时间比最近一帧点云晚 0.3 s 以上,报 `LIDAR_TIMEOUT`
|
||||
- `process_point_cloud()`:输入检查 → 等 IMU 覆盖整个扫描窗口 → 去畸变 → 配准 → 成功后重新传播、
|
||||
更新位姿、必要时插关键帧。配准失败只记原因,不动状态
|
||||
- 地图点数少于 5 个时:`MAPPING` 模式拿这一帧直接播种(第一个关键帧),`LOCALIZATION` 模式报 `MAP_UNAVAILABLE`
|
||||
- `set_pose()` / `reset()`:回到已知初始位姿,清空历史,等新的 IMU。没有全局搜索
|
||||
|
||||
### `dataset.cpp`
|
||||
|
||||
- `write_cloud()` / `read_cloud()`:FLPC v1 点云文件,读取时核对魔数、版本号和文件长度
|
||||
- `write_dataset_config()` / `read_dataset_config()`:数据集目录里的 `config.txt`
|
||||
- `read_trajectory()` / `trajectory_pose()`:TUM 文本轨迹;真值间隔超过上限时拒绝插值
|
||||
- `evaluate()`:未对齐的 ATE(平移、旋转)和 1 秒相对位姿误差 RPE
|
||||
- `write_filter_trace_header()` / `write_filter_trace()`:调优 CSV,每帧把状态、18×18 协方差、
|
||||
6×6 信息矩阵、梯度、奇异值、配准阶段和关联计数都写出来
|
||||
- `mode_name()` / `reason_name()`:枚举转字符串
|
||||
|
||||
## 加新算法的流程
|
||||
|
||||
```bash
|
||||
# ① 头文件(别 include ROS)
|
||||
vim include/field_localization/core/xxx.hpp
|
||||
|
||||
# ② 实现(放这里,xmake.lua 不用改)
|
||||
vim src/core/xxx.cpp
|
||||
|
||||
# ③ 测试
|
||||
vim tests/test_xxx.cpp # 同时到 xmake.lua 加一个 target
|
||||
cd ~/Gazebo_projects/sentry_nav_dev && xmake test
|
||||
```
|
||||
|
||||
**这三步不需要 Gazebo。** 跑通了再接 ROS:在 `../ros/localization_node.cpp` 里读参数、订阅话题、调用它。
|
||||
|
||||
## 判据(写代码时问自己一句)
|
||||
|
||||
> **这段逻辑需要 `#include <rclcpp/...>` 吗?**
|
||||
>
|
||||
> - 不需要 → 放这儿,配不依赖 ROS 的测试
|
||||
> - 需要 → 放 `../ros/`,靠跑仿真验证
|
||||
|
||||
| 逻辑 | 放哪 | 为什么 |
|
||||
|---|---|---|
|
||||
| 点到面残差、Huber 权重 | **这里** | 纯数学 |
|
||||
| 把 `PointCloud2` 转成 `PointCloud` | `../ros/conversion.cpp` | 要消息类型 |
|
||||
| 判断定位能否用于导航 | **这里**(`tracking_health.hpp`) | 只看协方差和时间戳 |
|
||||
| 查 `odom → base_link` 的 TF 再合成 `map → odom` | `../ros/localization_node.cpp` | 要 TF |
|
||||
| 地图文件格式 | **这里** | 只读写文件 |
|
||||
|
||||
## 相关
|
||||
|
||||
- 接口和默认值速查:[`../../include/field_localization/core/README.md`](../../include/field_localization/core/README.md)
|
||||
- 测试:[`../../tests/README.md`](../../tests/README.md)
|
||||
- ROS 适配:[`../ros/README.md`](../ros/README.md)
|
||||
- 包总览:[`../../README.md`](../../README.md)
|
||||
@@ -43,12 +43,12 @@ void write_cloud(const PointCloud &cloud,const std::filesystem::path &path) {
|
||||
write<float>(out,p.intensity);
|
||||
}
|
||||
}
|
||||
PointCloud read_cloud(const std::filesystem::path &path) {
|
||||
PointCloud read_cloud(const std::filesystem::path &path,const std::string &frame) {
|
||||
std::ifstream in(path,std::ios::binary); std::array<char,8> magic{};
|
||||
in.read(magic.data(),magic.size());
|
||||
if (std::string(magic.data(),magic.size())!="FLPC0001" || read<std::uint32_t>(in)!=1)
|
||||
throw std::runtime_error("unsupported cloud format");
|
||||
PointCloud cloud; cloud.frame_id="lidar_link"; cloud.timestamp_sec=read<double>(in);
|
||||
PointCloud cloud; cloud.frame_id=frame; cloud.timestamp_sec=read<double>(in);
|
||||
const auto count=read<std::uint32_t>(in);
|
||||
if (!std::isfinite(cloud.timestamp_sec) || count>1000000 || std::filesystem::file_size(path)!=24+std::uint64_t(count)*24)
|
||||
throw std::runtime_error("invalid cloud size");
|
||||
@@ -61,15 +61,18 @@ PointCloud read_cloud(const std::filesystem::path &path) {
|
||||
}
|
||||
return cloud;
|
||||
}
|
||||
void write_dataset_config(const CoreOptions &o,const std::filesystem::path &path) {
|
||||
void write_dataset_config(const CoreOptions &o,const std::filesystem::path &path,const std::string &cloud_frame) {
|
||||
std::ofstream out(path); out.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
out<<"FIELD_LIO_DATASET 1\ninitial_pose "; pose_fields(out,o.initial_pose);
|
||||
out<<"\nbase_from_imu "; pose_fields(out,o.base_from_imu);
|
||||
out<<"\nimu_from_lidar "; pose_fields(out,o.deskew.imu_from_sensor);
|
||||
out<<"\nscan_timing "<<static_cast<int>(o.deskew.timing)<<' '<<o.deskew.period_sec<<' '
|
||||
<<o.deskew.start_angle_rad<<' '<<o.deskew.counterclockwise<<' '<<o.deskew.stamp_at_end<<'\n';
|
||||
// Version 1 originally assumed lidar_link and the legacy field name denotes the recorded scan extrinsic.
|
||||
if (cloud_frame!="lidar_link") out<<"cloud_frame "<<cloud_frame<<'\n';
|
||||
if (o.map_bounds) out<<"map_bounds "<<o.map_bounds->min.transpose()<<' '<<o.map_bounds->max.transpose()<<'\n';
|
||||
}
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path) {
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path,std::string *cloud_frame) {
|
||||
std::ifstream in(path); std::string token; int version=0;
|
||||
in>>token>>version;
|
||||
if (!in || token!="FIELD_LIO_DATASET" || version!=1) throw std::runtime_error("unsupported dataset");
|
||||
@@ -80,7 +83,24 @@ CoreOptions read_dataset_config(const std::filesystem::path &path) {
|
||||
int timing=0; in>>token>>timing>>o.deskew.period_sec>>o.deskew.start_angle_rad>>o.deskew.counterclockwise>>o.deskew.stamp_at_end;
|
||||
if (!in || token!="scan_timing" || timing<0 || timing>2 || !std::isfinite(o.deskew.period_sec) || o.deskew.period_sec<=0)
|
||||
throw std::runtime_error("invalid dataset timing");
|
||||
o.deskew.timing=static_cast<ScanTiming>(timing); return o;
|
||||
o.deskew.timing=static_cast<ScanTiming>(timing);
|
||||
std::string frame="lidar_link";
|
||||
bool frame_set=false;
|
||||
while (in>>token) {
|
||||
if (token=="cloud_frame" && !frame_set && in>>frame) {
|
||||
frame_set=true;
|
||||
} else if (token=="map_bounds" && !o.map_bounds) {
|
||||
MapBounds bounds;
|
||||
for (int axis=0;axis<3;++axis) in>>bounds.min[axis];
|
||||
for (int axis=0;axis<3;++axis) in>>bounds.max[axis];
|
||||
if (!in || !bounds.valid()) throw std::runtime_error("invalid dataset map bounds");
|
||||
o.map_bounds=bounds;
|
||||
} else {
|
||||
throw std::runtime_error("invalid dataset field: "+token);
|
||||
}
|
||||
}
|
||||
if (cloud_frame) *cloud_frame=frame;
|
||||
return o;
|
||||
}
|
||||
void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample) {
|
||||
out<<std::setprecision(17)<<sample.time<<' '; pose_fields(out,sample.pose); out<<'\n';
|
||||
|
||||
@@ -27,6 +27,14 @@ Pose3D inverse(const Pose3D &p) {
|
||||
const Eigen::Quaterniond q = p.rotation.conjugate();
|
||||
return {q, -(q * p.translation)};
|
||||
}
|
||||
Twist3D base_twist(const MotionState &state, const Eigen::Vector3d &raw_angular_velocity,
|
||||
const Pose3D &base_from_imu) {
|
||||
const Eigen::Matrix3d r_bi = base_from_imu.rotation.normalized().toRotationMatrix();
|
||||
const Eigen::Matrix3d r_mi = state.pose.rotation.normalized().toRotationMatrix();
|
||||
const Eigen::Vector3d omega_b = r_bi * (raw_angular_velocity - state.gyro_bias);
|
||||
const Eigen::Vector3d v_imu_in_b = r_bi * (r_mi.transpose() * state.velocity);
|
||||
return {v_imu_in_b - omega_b.cross(base_from_imu.translation), omega_b};
|
||||
}
|
||||
bool valid_imu(const ImuData &imu) {
|
||||
return std::isfinite(imu.timestamp_sec) && imu.timestamp_sec >= 0 &&
|
||||
imu.angular_velocity.allFinite() && imu.linear_acceleration.allFinite();
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace field_localization::core {
|
||||
LocalizationCore::LocalizationCore():LocalizationCore(CoreOptions{}) {}
|
||||
LocalizationCore::LocalizationCore(const CoreOptions &options):options_(options),map_(options.map_resolution),filter_(options.noise) {
|
||||
if (options_.map_bounds && !options_.map_bounds->valid()) throw std::invalid_argument("invalid map bounds");
|
||||
MotionState initial;
|
||||
initial.pose=compose(options.initial_pose,options.base_from_imu);
|
||||
filter_.initialize(initial); pose_=options.initial_pose;
|
||||
}
|
||||
bool LocalizationCore::load_map(const std::filesystem::path &path,std::string &error) {
|
||||
auto map=read_map(path,error);
|
||||
auto map=read_map(path,error,options_.map_bounds);
|
||||
if (!map) return false;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
map_=std::move(*map); status_.map_point_count=map_.size(); return true;
|
||||
@@ -23,12 +25,14 @@ bool LocalizationCore::export_map(const std::filesystem::path &path,std::string
|
||||
}
|
||||
void LocalizationCore::set_map_points(std::span<const Eigen::Vector3d> points) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
map_.clear(); for (const auto &point:points) map_.insert(point);
|
||||
map_.clear();
|
||||
for (const auto &point:points) if (!options_.map_bounds || options_.map_bounds->contains(point)) map_.insert(point);
|
||||
status_.map_point_count=map_.size();
|
||||
}
|
||||
LocalizationSnapshot LocalizationCore::get_snapshot() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return {pose_,filter_.snapshot(),status_};
|
||||
return {pose_,filter_.snapshot(),status_,twist_,
|
||||
previous_imu_ ? previous_imu_->angular_velocity : Eigen::Vector3d::Zero(),last_imu_dt_};
|
||||
}
|
||||
|
||||
|
||||
@@ -58,15 +62,20 @@ bool LocalizationCore::process_imu(const ImuData &imu) {
|
||||
}
|
||||
|
||||
if (previous_imu_) {
|
||||
const double dt=imu.timestamp_sec-previous_imu_->timestamp_sec;
|
||||
if (!filter_.propagate(*previous_imu_,imu)) {
|
||||
status_.mode=TrackingMode::IMU_ONLY; status_.reason=FailureReason::IMU_GAP;
|
||||
auto snapshot=filter_.snapshot(); snapshot.state.timestamp_sec=imu.timestamp_sec;
|
||||
snapshot.covariance.diagonal().array()+=1.0;
|
||||
filter_.restore(snapshot); imu_history_.clear(); state_history_.clear();
|
||||
last_imu_dt_=0.0;
|
||||
} else {
|
||||
last_imu_dt_=dt;
|
||||
}
|
||||
} else {
|
||||
auto snapshot=filter_.snapshot(); snapshot.state.timestamp_sec=imu.timestamp_sec;
|
||||
filter_.restore(snapshot);
|
||||
last_imu_dt_=0.0;
|
||||
}
|
||||
if (status_.has_point_cloud && imu.timestamp_sec-status_.last_point_cloud_timestamp>0.3) {
|
||||
status_.mode=TrackingMode::IMU_ONLY; status_.reason=FailureReason::LIDAR_TIMEOUT;
|
||||
@@ -76,7 +85,9 @@ bool LocalizationCore::process_imu(const ImuData &imu) {
|
||||
while (imu_history_.size()>1 && imu.timestamp_sec-imu_history_[1].timestamp_sec>2.0) {
|
||||
imu_history_.erase(imu_history_.begin()); state_history_.erase(state_history_.begin());
|
||||
}
|
||||
pose_=compose(filter_.snapshot().state.pose,inverse(options_.base_from_imu));
|
||||
const auto current_state=filter_.snapshot().state;
|
||||
pose_=compose(current_state.pose,inverse(options_.base_from_imu));
|
||||
twist_=base_twist(current_state,imu.angular_velocity,options_.base_from_imu);
|
||||
status_.state_timestamp=imu.timestamp_sec;
|
||||
status_.has_imu = true;
|
||||
status_.last_imu_timestamp = imu.timestamp_sec;
|
||||
@@ -150,10 +161,20 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
|
||||
if (end>a->timestamp_sec && !at_scan.propagate(*a,*finish)) {
|
||||
status_.reason=FailureReason::IMU_GAP; return true;
|
||||
}
|
||||
const auto map_from_sensor_at=[&](const Pose3D &map_from_imu) {
|
||||
return compose(map_from_imu,options_.deskew.imu_from_sensor);
|
||||
};
|
||||
const auto map_scan=[&](const Pose3D &map_from_sensor) {
|
||||
return options_.map_bounds ? crop_to_map(*corrected,map_from_sensor,*options_.map_bounds) : *corrected;
|
||||
};
|
||||
const auto predicted_sensor=map_from_sensor_at(at_scan.snapshot().state.pose);
|
||||
if (map_.size()<5) {
|
||||
if (options_.map_mode==MapMode::MAPPING && corrected->points.size()>=options_.registration.minimum_inliers) {
|
||||
map_.insert(voxel_downsample(*corrected,options_.map_resolution),
|
||||
compose(at_scan.snapshot().state.pose,options_.deskew.imu_from_sensor));
|
||||
if (options_.map_mode==MapMode::MAPPING) {
|
||||
const auto points=map_scan(predicted_sensor);
|
||||
if (points.points.size()<options_.registration.minimum_inliers) {
|
||||
status_.reason=FailureReason::NO_VALID_POINTS; return true;
|
||||
}
|
||||
map_.insert(voxel_downsample(points,options_.map_resolution),predicted_sensor);
|
||||
last_keyframe_=compose(at_scan.snapshot().state.pose,inverse(options_.base_from_imu));
|
||||
status_.keyframe_count=1; status_.map_point_count=map_.size();
|
||||
status_.reason=FailureReason::INITIALIZING;
|
||||
@@ -161,7 +182,10 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
|
||||
return true;
|
||||
}
|
||||
status_.registration_prediction=at_scan.snapshot();
|
||||
const auto registration=scan_to_map(*corrected,options_.deskew.imu_from_sensor,map_,
|
||||
std::optional<PointCloud> cropped;
|
||||
if (options_.map_bounds)
|
||||
cropped=crop_to_map(*corrected,predicted_sensor,*options_.map_bounds,map_association_margin);
|
||||
const auto registration=scan_to_map(cropped ? *cropped : *corrected,options_.deskew.imu_from_sensor,map_,
|
||||
at_scan.snapshot(),options_.noise,options_.registration);
|
||||
status_.registration=registration;
|
||||
status_.registration_residual_available=registration.residual_available;
|
||||
@@ -191,13 +215,18 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
|
||||
const Pose3D scan_base=compose(registration.estimate.state.pose,inverse(options_.base_from_imu));
|
||||
if (options_.map_mode==MapMode::MAPPING && registration.degeneracy.dimensions==0 &&
|
||||
(!last_keyframe_ || new_keyframe(*last_keyframe_,scan_base))) {
|
||||
map_.insert(voxel_downsample(*corrected,options_.map_resolution),
|
||||
compose(registration.estimate.state.pose,options_.deskew.imu_from_sensor));
|
||||
last_keyframe_=scan_base; ++status_.keyframe_count; status_.map_point_count=map_.size();
|
||||
const auto posterior_sensor=map_from_sensor_at(registration.estimate.state.pose);
|
||||
const auto points=map_scan(posterior_sensor);
|
||||
if (!points.points.empty()) {
|
||||
map_.insert(voxel_downsample(points,options_.map_resolution),posterior_sensor);
|
||||
last_keyframe_=scan_base; ++status_.keyframe_count; status_.map_point_count=map_.size();
|
||||
}
|
||||
}
|
||||
status_.last_correction_timestamp=end; ++status_.accepted_corrections;
|
||||
last_correction_time_=end; status_.mode=TrackingMode::FULL; status_.reason=FailureReason::NONE;
|
||||
pose_=compose(filter_.snapshot().state.pose,inverse(options_.base_from_imu));
|
||||
const auto posterior_state=filter_.snapshot().state;
|
||||
pose_=compose(posterior_state.pose,inverse(options_.base_from_imu));
|
||||
if (previous_imu_) twist_=base_twist(posterior_state,previous_imu_->angular_velocity,options_.base_from_imu);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -206,6 +235,11 @@ Pose3D LocalizationCore::get_pose() const {
|
||||
return pose_;
|
||||
}
|
||||
|
||||
Twist3D LocalizationCore::get_twist() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return twist_;
|
||||
}
|
||||
|
||||
void LocalizationCore::set_pose(const Pose3D &pose) {
|
||||
if (!pose.translation.allFinite() || !pose.rotation.coeffs().allFinite() ||
|
||||
pose.rotation.norm() < 1e-12) {
|
||||
@@ -216,6 +250,8 @@ void LocalizationCore::set_pose(const Pose3D &pose) {
|
||||
|
||||
pose_ = pose;
|
||||
pose_.rotation.normalize();
|
||||
twist_ = Twist3D{};
|
||||
last_imu_dt_ = 0.0;
|
||||
MotionState initial; initial.pose=compose(pose_,options_.base_from_imu);
|
||||
filter_.initialize(initial); last_correction_time_=-1; previous_imu_.reset();
|
||||
imu_history_.clear(); state_history_.clear(); status_.has_imu=false;
|
||||
@@ -232,6 +268,8 @@ void LocalizationCore::reset() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
pose_ = options_.initial_pose;
|
||||
twist_ = Twist3D{};
|
||||
last_imu_dt_ = 0.0;
|
||||
MotionState initial; initial.pose=compose(pose_,options_.base_from_imu);
|
||||
filter_.initialize(initial); last_correction_time_=-1; previous_imu_.reset(); imu_history_.clear(); state_history_.clear();
|
||||
if (options_.map_mode==MapMode::MAPPING) map_.clear();
|
||||
|
||||
@@ -20,6 +20,23 @@ template<class T> T read(std::istream &in) {
|
||||
return std::bit_cast<T>(bytes);
|
||||
}
|
||||
}
|
||||
bool MapBounds::valid() const {
|
||||
return min.allFinite() && max.allFinite() && (min.array()<max.array()).all();
|
||||
}
|
||||
bool MapBounds::contains(const Eigen::Vector3d &point,double margin) const {
|
||||
return (point.array()>=min.array()-margin).all() && (point.array()<=max.array()+margin).all();
|
||||
}
|
||||
PointCloud crop_to_map(const PointCloud &cloud,const Pose3D &map_from_sensor,
|
||||
const MapBounds &bounds,double margin) {
|
||||
PointCloud cropped{cloud.timestamp_sec,cloud.frame_id,{}};
|
||||
cropped.points.reserve(cloud.points.size());
|
||||
for (const auto &point:cloud.points) {
|
||||
const Eigen::Vector3d mapped=map_from_sensor.rotation*point.position.cast<double>()+
|
||||
map_from_sensor.translation;
|
||||
if (bounds.contains(mapped,margin)) cropped.points.push_back(point);
|
||||
}
|
||||
return cropped;
|
||||
}
|
||||
bool new_keyframe(const Pose3D &previous,const Pose3D ¤t) {
|
||||
return (current.translation-previous.translation).norm()>0.5 ||
|
||||
log_so3(previous.rotation.conjugate()*current.rotation).norm()>10*std::numbers::pi/180;
|
||||
@@ -38,7 +55,8 @@ bool save_map(const VoxelMap &map,const std::filesystem::path &path,std::string
|
||||
error=e.what(); std::error_code ignored; std::filesystem::remove(temporary,ignored); return false;
|
||||
}
|
||||
}
|
||||
std::optional<VoxelMap> read_map(const std::filesystem::path &path,std::string &error) {
|
||||
std::optional<VoxelMap> read_map(const std::filesystem::path &path,std::string &error,
|
||||
const std::optional<MapBounds> &bounds) {
|
||||
error.clear();
|
||||
try {
|
||||
std::ifstream in(path,std::ios::binary);
|
||||
@@ -53,9 +71,9 @@ std::optional<VoxelMap> read_map(const std::filesystem::path &path,std::string &
|
||||
Eigen::Vector3d p; for (int j=0;j<3;++j) p[j]=read<double>(in);
|
||||
if (!p.allFinite() || p.cwiseAbs().maxCoeff()/resolution>1e12)
|
||||
throw std::runtime_error("invalid map coordinate");
|
||||
map.insert(p);
|
||||
if (!bounds || bounds->contains(p)) map.insert(p);
|
||||
}
|
||||
if (map.size()==0) throw std::runtime_error("empty voxel map");
|
||||
if (map.size()==0) throw std::runtime_error("empty voxel map after applying map bounds");
|
||||
return map;
|
||||
} catch (const std::exception &e) { error=e.what(); return std::nullopt; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# field_localization/src/ros/ (ROS 适配)
|
||||
|
||||
把 `core/` 接到 ROS 上的三个文件。**这里只写胶水**:读参数、订阅、查 TF、排队、发布。
|
||||
|
||||
```
|
||||
ros/
|
||||
├── README.md 本文件
|
||||
├── main.cpp 可执行文件入口
|
||||
├── localization_node.cpp LocalizationNode:定位节点
|
||||
└── conversion.cpp PointCloud2 / Transform ⇄ core 类型
|
||||
```
|
||||
|
||||
| 文件 | 编进 |
|
||||
|---|---|
|
||||
| `main.cpp` | `field_localization_node`(可执行文件) |
|
||||
| `localization_node.cpp`、`conversion.cpp` | `field_localization_ros`(动态库,节点和录制工具共用) |
|
||||
|
||||
## `main.cpp`
|
||||
|
||||
`rclcpp::init` → 创建 `LocalizationNode` → `spin`。
|
||||
构造失败(地图读不了、参数非法)会打印异常并返回 1。
|
||||
|
||||
## `conversion.cpp`
|
||||
|
||||
三个纯函数:`convert_cloud()`、`from_transform()`、`to_transform()`。
|
||||
只依赖消息类型,不起节点。格式要求见
|
||||
[`conversion.hpp` 的说明](../../include/field_localization/ros/README.md)。
|
||||
|
||||
## `localization_node.cpp` —— 定位节点
|
||||
|
||||
节点名 `field_localization`,下面写作 `~/`。
|
||||
|
||||
### 订阅和发布
|
||||
|
||||
| 方向 | 名称 | 类型 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 订阅 | `point_cloud_topic`(默认 `/scan/points`) | `sensor_msgs/PointCloud2` | 点云。帧可以是 `lidar_frame` / `base_frame` / `imu_frame`,节点会转到雷达系 |
|
||||
| 订阅 | `imu_topic`(默认 `/imu`) | `sensor_msgs/Imu` | IMU 消息的坐标系原点必须是配置的 IMU 原点 |
|
||||
| 订阅 | TF | — | 读固定外参:`base_frame ← imu_frame`、`imu_frame ← lidar_frame`、点云的帧到 `lidar_frame` |
|
||||
| 发布 | `~/odometry` | `nav_msgs/Odometry` | map 系的 `base_link` 位姿(6×6 协方差)+ `base_link` 系的刚体速度 `twist`(已扣除零偏与 IMU 杆臂效应,含 6×6 协方差) |
|
||||
| 发布 | `~/navigation_valid` | `std_msgs/Bool` | 定位能否用于导航。状态一变立即发,另有 10 Hz 心跳 |
|
||||
| 发布 | `~/status` | `std_msgs/String` | 每 5 秒一次,内容是 `模式,原因,退化维数` |
|
||||
| 发布 | TF `map_frame → odom_frame` | — | 唯一的 `map → odom` 来源,不能和 AMCL 同时开 |
|
||||
| 服务 | `~/save_map` | `std_srvs/Trigger` | 把当前地图存到 `export_map_path` |
|
||||
| 服务 | `~/reset` | `std_srvs/Trigger` | 回到配置的已知初始位姿,不做全局搜索 |
|
||||
|
||||
启动入口(`sentry_up.sh` 和 launch)把 `point_cloud_topic` 设成 `/scan/points_lio`、
|
||||
`reliable_clouds` 设成 `true`,也就是吃 `sentry_nav/self_filter` 出的、保留地面回波的那份点云。
|
||||
|
||||
### 参数
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `mode` | `localization` | `mapping` 或 `localization`。定位模式必须给 `map_path` |
|
||||
| `map_path` | 空 | 定位模式只读加载的地图(FLMAP) |
|
||||
| `export_map_path` | 空 | 建图模式的保存 / 导出路径。节点正常退出时会做一次最终导出 |
|
||||
| `publish_map_to_odom` | `true` | 是否广播 TF |
|
||||
| `map_frame` / `odom_frame` / `base_frame` | `map` / `odom` / `base_link` | 坐标系名 |
|
||||
| `imu_frame` / `lidar_frame` | `imu_link` / `lidar_link` | 坐标系名 |
|
||||
| `point_cloud_topic` / `imu_topic` | `/scan/points` / `/imu` | 输入话题 |
|
||||
| `reliable_clouds` | `false` | 点云用 RELIABLE 还是 SensorData QoS。要和发布方一致 |
|
||||
| `initial_x` / `initial_y` / `initial_z` | `-5` / `3` / `0` | 已知的初始位姿,**必须和出生点一致** |
|
||||
| `initial_yaw` / `initial_pitch` / `initial_roll` | 0 | 同上,弧度 |
|
||||
| `map_voxel_size` / `scan_voxel_size` | 0.1 / 0.1 | 地图、扫描体素边长(m) |
|
||||
| `scan_timing` | `instantaneous` | `instantaneous` 或 `azimuth` |
|
||||
| `scan_period_sec` / `scan_start_angle_rad` / `scan_counterclockwise` / `scan_stamp_at_end` | 0.1 / −π / true / true | 只在 `azimuth` 下有意义 |
|
||||
| `gyro_noise_density` / `accel_noise_density` | 0.003 / 0.03 | IMU 噪声密度 |
|
||||
| `gyro_bias_walk` / `accel_bias_walk` | 1e-5 / 1e-4 | 零偏随机游走 |
|
||||
| `integration_error_scale` | 1.4 | 积分误差尺度 |
|
||||
| `map_translation_sigma` / `map_rotation_sigma` | 0.03 / 0.002 | 地图和关联的不确定度(m / rad) |
|
||||
| `navigation_correction_timeout` | 0.3 | 多久没配准成功就判导航无效(s) |
|
||||
| `navigation_position_three_sigma` | 0.5 | 水平位置 3σ 上限(m) |
|
||||
| `navigation_yaw_three_sigma_deg` | 15 | 航向 3σ 上限(度) |
|
||||
| `diagnostics_path` | 空 | 非空时每帧写三行调优 CSV(预测 / 候选 / 后验),会增加磁盘写入 |
|
||||
|
||||
节点支持 `use_sim_time`,**只有消息和 ROS 仿真时间参与状态计算**。
|
||||
|
||||
### 节点内部几条要紧的逻辑
|
||||
|
||||
- **外参从 TF 读,读不到就等**。`LocalizationCore` 在两组固定外参齐全后才创建,不假设任何变换是恒等的
|
||||
- **点云排队等 IMU**。点云到了要等 IMU 历史覆盖整帧扫描才处理,队列最多 5 帧(满了丢最旧的)。
|
||||
仿真时间比扫描结束时刻晚 0.2 s 还没等到 IMU,就丢弃这帧
|
||||
- **TF 是补发的**。先缓存最多 30 个位姿快照,等 `odom ← base_link` 在同一时刻的 TF 可查了,
|
||||
再按 `map → odom = (map → base_link) ∘ (odom → base_link)⁻¹` 广播。
|
||||
状态超过 0.1 s 没更新时,里程计和 TF 都不发
|
||||
- **定位无效时不发 TF**。`navigation_valid` 为 false 期间清空待发队列;
|
||||
里程计和心跳照常发,方便排查
|
||||
- **仿真时钟回跳就停**。检测到 `/clock` 倒退后不再输出任何结果,必须调 `~/reset` 或重启。
|
||||
联锁用的是单调墙上时钟,暂停或回拨仿真时间绕不过去
|
||||
|
||||
### 谁在用它的输出
|
||||
|
||||
| 输出 | 使用方 |
|
||||
|---|---|
|
||||
| TF `map → odom` | Nav2(规划、代价地图) |
|
||||
| `~/navigation_valid` | [`sentry_nav/cmd_vel_relay`](../../../sentry_nav/src/cmd_vel_relay.cpp):失效就发零速度并取消目标。`nav_client`:失效就不发目标 |
|
||||
|
||||
## 加新东西
|
||||
|
||||
| 要加的 | 怎么做 |
|
||||
|---|---|
|
||||
| 新的参数 | 构造函数里 `declare_parameter`,写进 `core_options_` 或 `health_options`,并更新上面的表 |
|
||||
| 新的话题 / 服务 | 头文件里声明,`localization_node.cpp` 里创建 |
|
||||
| 新的 ROS 消息类型 ⇄ core 转换 | 写在 `conversion.cpp`,别写进节点 |
|
||||
|
||||
本目录的 `.cpp` 在 `xmake.lua` 里是逐个列出的,**加新的实现文件要去 `field_localization_ros` 补一行**。
|
||||
|
||||
## 相关
|
||||
|
||||
- 类的声明和转换函数的要求:[`../../include/field_localization/ros/README.md`](../../include/field_localization/ros/README.md)
|
||||
- 被调用的算法:[`../core/README.md`](../core/README.md)
|
||||
- 录制工具复用了这里的转换函数:[`../tools/README.md`](../tools/README.md)
|
||||
- 怎么把节点拉起来:[`sentry_up.sh`](../../../../src/sentry_sim/scripts/sentry_up.sh)、
|
||||
[`sentry_arena.launch.py`](../../../../src/sentry_sim/launch/sentry_arena.launch.py)
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "field_localization/ros/conversion.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <stdexcept>
|
||||
namespace field_localization::ros {
|
||||
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg) {
|
||||
@@ -42,8 +43,34 @@ core::Pose3D from_transform(const geometry_msgs::msg::Transform &t) {
|
||||
throw std::runtime_error("invalid TF transform");
|
||||
p.rotation.normalize(); return p;
|
||||
}
|
||||
core::PointCloud convert_cloud_in_frame(const sensor_msgs::msg::PointCloud2 &msg,
|
||||
const std::string &frame,const tf2_ros::Buffer &buffer) {
|
||||
auto cloud=convert_cloud(msg);
|
||||
if (cloud.frame_id==frame) return cloud;
|
||||
const auto transform=from_transform(buffer.lookupTransform(
|
||||
frame,cloud.frame_id,rclcpp::Time(msg.header.stamp),rclcpp::Duration::from_seconds(0.1)).transform);
|
||||
for (auto &point:cloud.points)
|
||||
point.position=(transform.rotation*point.position.cast<double>()+transform.translation).cast<float>();
|
||||
cloud.frame_id=frame;
|
||||
return cloud;
|
||||
}
|
||||
std::optional<core::MapBounds> declare_map_bounds(rclcpp::Node &node) {
|
||||
const auto low=node.declare_parameter("map_crop_min",std::vector<double>{});
|
||||
const auto high=node.declare_parameter("map_crop_max",std::vector<double>{});
|
||||
if (low.empty() && high.empty()) return std::nullopt;
|
||||
if (low.size()!=3 || high.size()!=3) throw std::invalid_argument("map crop requires two XYZ triples");
|
||||
const core::MapBounds bounds{{low[0],low[1],low[2]},{high[0],high[1],high[2]}};
|
||||
if (!bounds.valid()) throw std::invalid_argument("map crop bounds must be finite and ordered");
|
||||
return bounds;
|
||||
}
|
||||
geometry_msgs::msg::Transform to_transform(const core::Pose3D &p) {
|
||||
geometry_msgs::msg::Transform t; t.translation.x=p.translation.x(); t.translation.y=p.translation.y(); t.translation.z=p.translation.z();
|
||||
t.rotation.w=p.rotation.w(); t.rotation.x=p.rotation.x(); t.rotation.y=p.rotation.y(); t.rotation.z=p.rotation.z(); return t;
|
||||
}
|
||||
geometry_msgs::msg::Twist to_twist(const core::Twist3D &v) {
|
||||
geometry_msgs::msg::Twist t;
|
||||
t.linear.x=v.linear.x(); t.linear.y=v.linear.y(); t.linear.z=v.linear.z();
|
||||
t.angular.x=v.angular.x(); t.angular.y=v.angular.y(); t.angular.z=v.angular.z();
|
||||
return t;
|
||||
}
|
||||
} // namespace field_localization::ros
|
||||
@@ -12,11 +12,12 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
|
||||
const auto mode=declare_parameter<std::string>("mode","localization");
|
||||
if (mode!="mapping" && mode!="localization") throw std::invalid_argument("mode must be mapping or localization");
|
||||
core_options_.map_mode=mode=="mapping" ? core::MapMode::MAPPING : core::MapMode::LOCALIZATION;
|
||||
core_options_.map_bounds=declare_map_bounds(*this);
|
||||
map_path_=declare_parameter<std::string>("map_path",""); export_path_=declare_parameter<std::string>("export_map_path","");
|
||||
if (mode=="localization" && map_path_.empty()) throw std::invalid_argument("localization requires map_path; run explicit mapping first");
|
||||
if (mode=="localization") {
|
||||
std::string error;
|
||||
if (!core::read_map(map_path_,error)) throw std::runtime_error(error);
|
||||
if (!core::read_map(map_path_,error,core_options_.map_bounds)) throw std::runtime_error(error);
|
||||
}
|
||||
publish_map_to_odom_=declare_parameter<bool>("publish_map_to_odom",true);
|
||||
auto &pose=core_options_.initial_pose;
|
||||
@@ -107,7 +108,14 @@ bool LocalizationNode::ensure_core() {
|
||||
if (core_) return true;
|
||||
try {
|
||||
core_options_.base_from_imu=from_transform(tf_buffer_->lookupTransform(base_frame_,imu_frame_,tf2::TimePointZero).transform);
|
||||
core_options_.deskew.imu_from_sensor=from_transform(tf_buffer_->lookupTransform(imu_frame_,lidar_frame_,tf2::TimePointZero).transform);
|
||||
if (core_options_.deskew.timing==core::ScanTiming::AZIMUTH) {
|
||||
const auto fixed=tf_buffer_->lookupTransform(imu_frame_,lidar_frame_,tf2::TimePointZero);
|
||||
if (rclcpp::Time(fixed.header.stamp).nanoseconds()!=0)
|
||||
throw std::runtime_error("azimuth deskew requires a fixed IMU-to-LiDAR transform");
|
||||
core_options_.deskew.imu_from_sensor=from_transform(fixed.transform);
|
||||
} else {
|
||||
core_options_.deskew.imu_from_sensor=core::Pose3D{};
|
||||
}
|
||||
core_=std::make_unique<core::LocalizationCore>(core_options_);
|
||||
if (core_options_.map_mode==core::MapMode::LOCALIZATION) {
|
||||
std::string error; if (!core_->load_map(map_path_,error)) { core_.reset(); throw std::runtime_error(error); }
|
||||
@@ -120,12 +128,11 @@ bool LocalizationNode::ensure_core() {
|
||||
void LocalizationNode::on_point_cloud(sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
if (!check_clock() || !ensure_core()) return;
|
||||
try {
|
||||
auto cloud=convert_cloud(*msg);
|
||||
if (cloud.frame_id!=lidar_frame_ && cloud.frame_id!=base_frame_ && cloud.frame_id!=imu_frame_)
|
||||
const auto &frame=msg->header.frame_id;
|
||||
if (frame!=lidar_frame_ && frame!=base_frame_ && frame!=imu_frame_)
|
||||
throw std::runtime_error("unexpected cloud frame; configure lidar_frame explicitly");
|
||||
const auto extrinsic=from_transform(tf_buffer_->lookupTransform(lidar_frame_,cloud.frame_id,tf2::TimePointZero).transform);
|
||||
for (auto &p:cloud.points) p.position=(extrinsic.rotation*p.position.cast<double>()+extrinsic.translation).cast<float>();
|
||||
cloud.frame_id=lidar_frame_;
|
||||
const auto &target=core_options_.deskew.timing==core::ScanTiming::AZIMUTH ? lidar_frame_ : imu_frame_;
|
||||
auto cloud=convert_cloud_in_frame(*msg,target,*tf_buffer_);
|
||||
if (scans_.size()>=5) { scans_.pop_front(); RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"scan queue overflow"); }
|
||||
scans_.push_back(std::move(cloud)); drain_scans(); publish_estimate();
|
||||
} catch (const std::exception &e) { RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"cloud rejected: %s",e.what()); }
|
||||
@@ -171,6 +178,10 @@ void LocalizationNode::publish_estimate() {
|
||||
odom.pose.pose.orientation=transform.rotation;
|
||||
const core::Matrix6 covariance=core::base_pose_covariance(snapshot,core_options_.base_from_imu);
|
||||
for (int i=0;i<6;++i) for (int j=0;j<6;++j) odom.pose.covariance[6*i+j]=covariance(i,j);
|
||||
odom.twist.twist=to_twist(snapshot.twist);
|
||||
const core::Matrix6 twist_covariance=core::base_twist_covariance(
|
||||
snapshot,core_options_.base_from_imu,core_options_.noise.gyro);
|
||||
for (int i=0;i<6;++i) for (int j=0;j<6;++j) odom.twist.covariance[6*i+j]=twist_covariance(i,j);
|
||||
odometry_pub_->publish(odom); last_published_=snapshot.status.state_timestamp;
|
||||
pending_tf_.push_back(snapshot); if (pending_tf_.size()>30) pending_tf_.pop_front();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# field_localization/src/tools/ (离线工具)
|
||||
|
||||
两个独立的可执行文件,都是录制 / 命令行工具,不在导航链路上跑。
|
||||
|
||||
```
|
||||
tools/
|
||||
├── README.md 本文件
|
||||
├── record.cpp field_localization_record 录数据集(ROS 节点)
|
||||
└── replay.cpp field_localization_replay 离线回放打分(不依赖 ROS)
|
||||
```
|
||||
|
||||
| target | 依赖 ROS | 作用 |
|
||||
|---|---|---|
|
||||
| `field_localization_record` | 是 | 把仿真里的点云、IMU、真值按时间录成一个数据集目录 |
|
||||
| `field_localization_replay` | 否 | 不开 Gazebo,把录好的数据集喂给同一套 `core/`,输出轨迹和精度指标 |
|
||||
|
||||
两个工具和在线节点链接的是同一个静态库 `field_localization_core`,
|
||||
回放走的就是在线那套滤波和配准代码,结果才和在线行为可比。
|
||||
|
||||
## `record.cpp` —— 录数据集
|
||||
|
||||
节点名 `field_localization_record`。通常不用手敲,由
|
||||
[`tools/capture_lio.py`](../../../../tools/capture_lio.py) 在隔离的 Gazebo 里拉起来。
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `output_directory` | 空(必填) | 输出目录,**必须是新的**(里面已有 `imu.csv` 就拒绝启动) |
|
||||
| `duration_sec` | 120 | 录多长(仿真时间) |
|
||||
| `point_cloud_topic` | `/scan/points_lio` | 点云输入,RELIABLE QoS |
|
||||
| `initial_x` / `initial_y` / `initial_z` / `initial_yaw` | `-5` / `3` / `0` / `0` | 写进 `config.txt` 的已知初始位姿 |
|
||||
|
||||
订阅点云、`/imu`(坐标系必须是 `imu_link`)和 `/evaluation/ground_truth`
|
||||
(Gazebo 的 PosePublisher 发的独立真值)。
|
||||
收到第一条 IMU 且固定外参可查时开始录,IMU 和真值都越过结束时刻后写 `complete.txt` 并退出。
|
||||
|
||||
输出的布局(每种文件的格式见 [`../../tests/data/README.md`](../../tests/data/README.md)):
|
||||
|
||||
```
|
||||
<output_directory>/
|
||||
├── config.txt 已知初始位姿、固定外参、扫描时间模型
|
||||
├── imu.csv IMU 系原始测量
|
||||
├── scans.csv 每帧点云的时间戳和文件名
|
||||
├── clouds/N.flpc 点云,已转到 lidar_link 系
|
||||
├── truth.tum 世界系真值
|
||||
└── complete.txt 录完的标志,里面有样本计数
|
||||
```
|
||||
|
||||
- 真值只写进 `truth.tum`,不进定位器,也不发到 TF
|
||||
- 点云只收时间戳落在录制窗口内的,而且必须严格递增
|
||||
- IMU 和真值缺一样都不会结束,节点会一直等
|
||||
|
||||
## `replay.cpp` —— 离线回放
|
||||
|
||||
不依赖 ROS,直接跑:
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev
|
||||
build/bin/field_localization_replay \
|
||||
--dataset generated/lio_evaluation \
|
||||
--mode localization \
|
||||
--map src/sentry_sim/maps/field_full.flmap \
|
||||
--output generated/lio_metrics
|
||||
```
|
||||
|
||||
| 参数 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `--dataset DIR` | 是 | 数据集目录 |
|
||||
| `--mode mapping` 或 `--mode localization` | 是 | 回放模式。`mapping` 结束时把地图写到 `--map` |
|
||||
| `--map FILE` | 是 | 定位模式要加载的地图,或建图模式要输出的地图 |
|
||||
| `--output DIR` | 是 | 结果目录,不存在会创建 |
|
||||
| `--inspect-scan 秒` | 否 | 打印某一帧在预测位姿和真值位姿下各有多少关联。要求定位模式、`instantaneous` 扫描和 `truth.tum` |
|
||||
| `--map-translation-sigma 值` | 否 | 覆盖地图平移不确定度 |
|
||||
| `--integration-error-scale 值` | 否 | 覆盖积分误差尺度 |
|
||||
|
||||
参数一律写成 `--键 值` 成对出现,**每个选项后面都必须跟一个值**。
|
||||
要查的时间戳从数据集的 `scans.csv` 里挑。
|
||||
|
||||
`--output` 里生成四个文件:
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `trajectory.tum` | 估计轨迹(未对齐真值) |
|
||||
| `status.csv` | 每帧的模式、原因、RMSE、内点、退化维数、零偏、新息、单帧耗时 |
|
||||
| `filter_trace.csv` | 每帧三行(预测 / 候选 / 后验)的完整滤波状态、协方差、信息矩阵 |
|
||||
| `metrics.txt` | 帧数、`FULL` 比例、单帧耗时 p95;有真值时还有 ATE 和 1 秒 RPE,没有就写 `ground_truth=UNVERIFIED` |
|
||||
|
||||
回放不读轮速里程计,位姿全部来自 IMU + 点云。出错时向 stderr 打印原因并返回 1。
|
||||
|
||||
> `tests/data/` 里的三个回归片段不能直接用这个工具回放:回放从 `config.txt` 的初始位姿起步,
|
||||
> 不读 `checkpoint.txt`,而那三个片段的起点状态只存在 `checkpoint.txt` 里。
|
||||
|
||||
## 加新工具
|
||||
|
||||
1. 在本目录加 `xxx.cpp`(自带 `int main()`)
|
||||
2. 到 [`../../xmake.lua`](../../xmake.lua) 照抄一个 target:
|
||||
不依赖 ROS 就只 `add_deps("field_localization_core")`;
|
||||
需要 ROS 消息再 `add_deps("field_localization_ros")` 并加上 `ros_common()`
|
||||
3. 记得 `set_targetdir("$(builddir)/bin")`
|
||||
4. 仓库根 `xmake`
|
||||
|
||||
工具里只写参数解析和文件输出,算法调用 `core/`。
|
||||
|
||||
## 相关
|
||||
|
||||
- 录制脚本和验收脚本的用法:[`tools/README.md`](../../../../tools/README.md)
|
||||
- 数据集格式:[`../../tests/data/README.md`](../../tests/data/README.md)
|
||||
- 被调用的算法:[`../core/README.md`](../core/README.md)
|
||||
@@ -17,6 +17,8 @@ public:
|
||||
if (!std::isfinite(duration_) || duration_<=0) throw std::runtime_error("invalid duration");
|
||||
config_.initial_pose.translation={declare_parameter<double>("initial_x",-5),declare_parameter<double>("initial_y",3),declare_parameter<double>("initial_z",0)};
|
||||
config_.initial_pose.rotation=core::exp_so3({0,0,declare_parameter<double>("initial_yaw",0)});
|
||||
config_.map_bounds=ros::declare_map_bounds(*this);
|
||||
config_.deskew.imu_from_sensor=core::Pose3D{};
|
||||
std::filesystem::create_directories(directory_/"clouds");
|
||||
imu_.open(directory_/"imu.csv"); scans_.open(directory_/"scans.csv"); truth_.open(directory_/"truth.tum");
|
||||
imu_.exceptions(std::ios::badbit|std::ios::failbit); scans_.exceptions(std::ios::badbit|std::ios::failbit); truth_.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
@@ -25,11 +27,15 @@ public:
|
||||
cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(declare_parameter<std::string>("point_cloud_topic","/scan/points_lio"),
|
||||
rclcpp::QoS(20).reliable(),[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
if (!ready_ || done_) return;
|
||||
auto cloud=ros::convert_cloud(*msg);
|
||||
if (cloud.timestamp_sec<start_ || cloud.timestamp_sec<=last_scan_ || cloud.timestamp_sec>start_+duration_) return;
|
||||
const auto tf=ros::from_transform(buffer_->lookupTransform("lidar_link",cloud.frame_id,tf2::TimePointZero).transform);
|
||||
for (auto &p:cloud.points) p.position=(tf.rotation*p.position.cast<double>()+tf.translation).cast<float>();
|
||||
cloud.frame_id="lidar_link";
|
||||
const auto stamp=rclcpp::Time(msg->header.stamp).seconds();
|
||||
if (stamp<start_ || stamp<=last_scan_ || stamp>start_+duration_) return;
|
||||
core::PointCloud cloud;
|
||||
try {
|
||||
cloud=ros::convert_cloud_in_frame(*msg,"imu_link",*buffer_);
|
||||
} catch (const tf2::TransformException &e) {
|
||||
RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),2000,"scan not recorded: %s",e.what());
|
||||
return;
|
||||
}
|
||||
const auto file="clouds/"+std::to_string(scan_count_++)+".flpc"; core::write_cloud(cloud,directory_/file);
|
||||
scans_<<cloud.timestamp_sec<<','<<file<<'\n'; scans_.flush(); last_scan_=cloud.timestamp_sec;
|
||||
});
|
||||
@@ -41,9 +47,8 @@ public:
|
||||
if (!ready_) {
|
||||
try {
|
||||
config_.base_from_imu=ros::from_transform(buffer_->lookupTransform("base_link","imu_link",tf2::TimePointZero).transform);
|
||||
config_.deskew.imu_from_sensor=ros::from_transform(buffer_->lookupTransform("imu_link","lidar_link",tf2::TimePointZero).transform);
|
||||
} catch (const tf2::TransformException &) { return; }
|
||||
core::write_dataset_config(config_,directory_/"config.txt"); start_=t; ready_=true;
|
||||
core::write_dataset_config(config_,directory_/"config.txt","imu_link"); start_=t; ready_=true;
|
||||
RCLCPP_INFO(get_logger(),"recording started at sim %.3f for %.1f sec",start_,duration_);
|
||||
}
|
||||
if (t>start_+duration_+0.1) { imu_complete_=true; return; }
|
||||
|
||||
@@ -26,7 +26,8 @@ int main(int argc,char **argv) {
|
||||
if (!args.contains("--dataset") || !args.contains("--mode") || !args.contains("--map") || !args.contains("--output"))
|
||||
throw std::runtime_error("usage: field_localization_replay --dataset DIR --mode mapping|localization --map FILE --output DIR [--inspect-scan SIM_SECONDS]");
|
||||
const std::filesystem::path dataset=args.at("--dataset"),output=args.at("--output");
|
||||
auto options=read_dataset_config(dataset/"config.txt");
|
||||
std::string cloud_frame;
|
||||
auto options=read_dataset_config(dataset/"config.txt",&cloud_frame);
|
||||
if (args.at("--mode")!="mapping" && args.at("--mode")!="localization") throw std::runtime_error("invalid mode");
|
||||
options.map_mode=args.at("--mode")=="mapping" ? MapMode::MAPPING : MapMode::LOCALIZATION;
|
||||
if(args.contains("--map-translation-sigma")) options.registration.map_translation_sigma=std::stod(args.at("--map-translation-sigma"));
|
||||
@@ -43,7 +44,7 @@ int main(int argc,char **argv) {
|
||||
throw std::runtime_error("--inspect-scan requires localization with instantaneous scans and truth.tum");
|
||||
inspect_time=std::stod(args.at("--inspect-scan"));
|
||||
if (!std::isfinite(*inspect_time)) throw std::runtime_error("invalid scan timestamp");
|
||||
inspect_map=read_map(args.at("--map"),error);
|
||||
inspect_map=read_map(args.at("--map"),error,options.map_bounds);
|
||||
if (!inspect_map) throw std::runtime_error(error);
|
||||
}
|
||||
bool inspected=false;
|
||||
@@ -67,7 +68,7 @@ int main(int argc,char **argv) {
|
||||
const auto comma=line.find(','); if (comma==std::string::npos) throw std::runtime_error("invalid scan index");
|
||||
const auto relative=std::filesystem::path(line.substr(comma+1));
|
||||
if (relative.is_absolute() || relative.string().find("..")!=std::string::npos) throw std::runtime_error("unsafe scan path");
|
||||
auto cloud=read_cloud(dataset/relative); const double end=scan_window(cloud,options.deskew).second;
|
||||
auto cloud=read_cloud(dataset/relative,cloud_frame); const double end=scan_window(cloud,options.deskew).second;
|
||||
while (index<imu.size() && (!core.get_status().has_imu || core.get_status().last_imu_timestamp<end)) {
|
||||
if (!core.process_imu(imu[index++])) throw std::runtime_error("IMU rejected during replay");
|
||||
}
|
||||
@@ -83,7 +84,9 @@ int main(int argc,char **argv) {
|
||||
const auto &prediction=diagnostic.status.registration_prediction.state;
|
||||
const auto corrected=deskew(cloud,std::array{prediction},options.deskew);
|
||||
if (!corrected) throw std::runtime_error("failed to prepare instantaneous scan");
|
||||
const auto truth_support=inspect_scan_support(*corrected,options.deskew.imu_from_sensor,*inspect_map,
|
||||
const auto inspected_scan=options.map_bounds ? crop_to_map(*corrected,
|
||||
compose(map_from_imu,options.deskew.imu_from_sensor),*options.map_bounds,map_association_margin) : *corrected;
|
||||
const auto truth_support=inspect_scan_support(inspected_scan,options.deskew.imu_from_sensor,*inspect_map,
|
||||
map_from_imu,options.registration);
|
||||
const auto error_xyz=prediction.pose.translation-map_from_imu.translation;
|
||||
std::cout<<std::setprecision(12)<<"scan="<<cloud.timestamp_sec
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
# field_localization/tests/ (单元测试与回归数据)
|
||||
|
||||
**12 个测试程序,`xmake test` 统一跑。其中 11 个不需要 ROS,全部不需要 Gazebo。**
|
||||
|
||||
```
|
||||
tests/
|
||||
├── README.md 本文件
|
||||
├── test_util.hpp 断言宏(转调 sentry_nav 的计数框架)
|
||||
├── test_localization_core.cpp 定位主流程
|
||||
├── test_imu_integration.cpp IMU 积分、去畸变
|
||||
├── test_eskf.cpp 滤波器零偏收敛
|
||||
├── test_registration.cpp 配准、退化、新息门限
|
||||
├── test_lio_synthetic.cpp 合成数据的端到端
|
||||
├── test_map_management.cpp 建图 / 只读定位 / 地图文件
|
||||
├── test_dataset.cpp 点云文件、数据集配置、ATE/RPE
|
||||
├── test_ros_conversion.cpp ROS 消息转换(唯一需要 ROS 的)
|
||||
├── test_tracking_safety.cpp 定位有效性、运动联锁
|
||||
├── test_field_tracking.cpp 2.5D 合成场地的跟踪
|
||||
├── test_filter_consistency.cpp 滤波器一致性
|
||||
├── test_recorded_update.cpp 录制数据的回归(读 data/)
|
||||
├── data/ ★ 回归用的录制片段(3 个数据集)
|
||||
│ └── README.md
|
||||
└── validation/ 历次验收的文字记录(没有任何代码读)
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 怎么跑
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev # 仓库根;先 source ROS 环境
|
||||
xmake # 编译
|
||||
xmake test # 全部 15 个:sentry_nav 3 个 + 本包 12 个
|
||||
xmake test test_eskf/default # 只跑一个(必须带 /default)
|
||||
xmake test -v # 带输出,能看到每个套件打印的数字
|
||||
```
|
||||
|
||||
`xmake test` 在 release 下也执行,没有「只在 debug 跑」的开关。
|
||||
|
||||
11 个不依赖 ROS 的测试也可以直接执行二进制,不用 source ROS:
|
||||
|
||||
```bash
|
||||
build/bin/test_registration
|
||||
```
|
||||
|
||||
只有两个会往磁盘写东西,且都是临时位置:
|
||||
|
||||
| 测试 | 写什么 |
|
||||
|---|---|
|
||||
| `test_eskf` | `/tmp/field_lio_bias_filter.csv`(5 个种子的零偏收敛曲线) |
|
||||
| `test_lio_synthetic` | `/tmp/field_lio_bias_end_to_end.csv`(同上,端到端版) |
|
||||
|
||||
这两个的第一个位置参数可以改 CSV 路径:`build/bin/test_eskf /tmp/mine.csv`。
|
||||
|
||||
## 断言框架
|
||||
|
||||
本目录的 `test_util.hpp` 只有 4 行:include 兄弟包的 `../../sentry_nav/tests/test_util.hpp`,
|
||||
再把 `EXPECT_TRUE` / `EXPECT_NEAR` 包成 `CHECK` / `CHECK_NEAR`。
|
||||
|
||||
```cpp
|
||||
CHECK(condition); // 断言为真
|
||||
CHECK_NEAR(actual, expected, tolerance); // 浮点近似相等,浮点只准用这个
|
||||
return sentry_nav_test::Summary("套件名"); // 返回失败数:0 = 通过
|
||||
```
|
||||
|
||||
## 每个测试测什么
|
||||
|
||||
| 测试(套件名) | 测什么 | 通过条件(摘要) |
|
||||
|---|---|---|
|
||||
| `test_localization_core`(`LocalizationCore`) | 主流程的输入输出:默认位姿、`set_pose`、乱序输入被拒、静止不漂移、匀加速 1 s 走 0.5 m、空点云报 `NO_VALID_POINTS`、`reset` 清零 | 逐项断言 |
|
||||
| `test_imu_integration`(`ImuIntegration`) | 恒定角速度下预积分的旋转和闭式解一致;时间区间非法、时间戳重复时返回空;逐点时间戳去畸变后一面墙的点落回同一个平面,非有限的点被丢掉;`instantaneous` 模式不改点的坐标;`azimuth` 模式对一帧旋转扫描去畸变 | 旋转误差 < 1e-6 rad;平面残差 < 1 mm |
|
||||
| `test_eskf`(`ESKF`) | 合成一条带真实零偏的轨迹(陀螺 (0.02, −0.015, 0.01) rad/s、加计 (0.15, −0.10, 0.08) m/s²)。IMU 加高斯噪声,100 Hz 传播,每 10 个样本给一次带噪位姿,5 个随机种子。另测 IMU 间隔过大被拒,以及只观测 z、横滚、俯仰时 x、y 位置和它们的协方差**一个数都不变** | 最后 100 次修正的零偏 RMSE:陀螺 < 0.003 rad/s、加计 < 0.03 m/s²;协方差保持半正定 |
|
||||
| `test_registration`(`Registration`) | 三面正交墙的地图,带初始误差配准能收敛;关联计数自洽;初始位姿偏 20 m 时报 `NO_CORRESPONDENCES`;只有一个平面时退化 3 维,x、y 不被更新;整体偏 0.09 m 的平面配上过度自信的先验,内点很多但被最终新息门限拒绝(`INNOVATION`,阶段 `FINAL_FUSION`);信息矩阵整体旋转后零空间跟着转;`set_pose` 后要等新的 IMU 时刻才更新;全是 `inf` 的点云被拒 | 收敛时位置、旋转误差均 < 1e-3 |
|
||||
| `test_lio_synthetic`(`LioSynthetic`) | 端到端:合成地图 + 带零偏和噪声的 IMU + 带噪声的扫描,60 秒、600 帧,5 个种子 | 每个种子 `FULL` ≥ 570/600 帧;零偏 RMSE 陀螺 < 0.003 rad/s、加计 < 0.03 m/s² |
|
||||
| `test_map_management`(`MapManagement`) | 关键帧门槛(0.5 m 和 10° 都是严格大于);建图模式首帧播种 1 个关键帧、不动不加,平移 0.6 m 后才有第 2 个;地图导出再读回;定位模式不往地图写,导出的文件和原地图逐字节相同;坏地图、缺失地图被拒且不清空已加载的地图;`reset` 只在建图模式清地图 | 逐项断言 |
|
||||
| `test_dataset`(`DatasetAndMetrics`) | 点云写读往返(含一个 `inf` 点);数据集配置往返;整体偏 0.1 m 的轨迹算出 ATE = 0.1 m、RPE ≈ 0;真值间隔过大时拒绝插值;截断的点云文件被拒 | 逐项断言 |
|
||||
| `test_ros_conversion`(`RosConversion`) | 大端、带行填充的 `PointCloud2` 正确转成 core 点云;数据被截断时抛异常;`from_transform` / `to_transform` 往返后和 `odom → base_link` 复合,能还原 `map → base_link` | 逐项断言 |
|
||||
| `test_tracking_safety`(`TrackingSafety`) | 恢复有效要数满 5 **帧**成功配准,同一帧重复更新 20 次不计数;`IMU_ONLY` 0.2 s 内仍有效、0.31 s 失效;协方差变大立即失效,恢复要重新数 5 帧。另测 `sentry_nav` 的 `MotionInterlock`:指令和心跳各自超时 0.3 s 就不放行、时间往回走不放行、手动模式不要求心跳 | 逐项断言 |
|
||||
| `test_field_tracking`(`FieldTracking`) | 2.5D 合成场地(地面、四面墙、一块 0.42 m 高的平台),按 MID-360 的视场和量程生成扫描;第 4–14 秒出现一个地图里没有的圆柱,第 8.0–8.8 秒点云全空。分无噪声和带零偏噪声两版 | 每版 `FULL` ≥ 180/200 帧;最大位置误差 < 0.15 m;断流期间 `navigation_valid` 变 false,之后恢复 |
|
||||
| `test_filter_consistency`(`FilterConsistency`) | 不可观的 x 量测不改变任何状态(含相关的速度、零偏);秩一量测的 4σ 新息被一自由度门限拒绝,状态和协方差原样不动;有限大的平面不匹配支撑范围之外的点;零噪声 IMU 里单个 50 m/s² 的加速度尖峰不被当成加计零偏 | 逐项断言 |
|
||||
| `test_recorded_update`(`RecordedUpdate`) | 用 `data/` 里三段真实录制做回归,见下 | 见下 |
|
||||
|
||||
## `test_recorded_update` 和 `data/`
|
||||
|
||||
`xmake.lua` 在 `on_load` 里给这个测试塞了三个固定参数,按顺序是
|
||||
`data/turn_contact`、`data/return_contact`、`data/return_cylinder`。
|
||||
每个片段从自己的 `checkpoint.txt`(出事前一瞬间的滤波器状态)出发,重放里面的点云和 IMU。
|
||||
|
||||
| 片段 | 用哪份地图 | 断言 |
|
||||
|---|---|---|
|
||||
| `turn_contact` | 自带的 `map.flmap`,当前默认参数 | 5 帧全部成功;最大位置误差 < 0.10 m;最大旋转误差 < 0.02 rad |
|
||||
| `return_contact` | 自带的 `map.flmap` | 当前参数和旧参数(积分误差尺度 2.0、地图平移 σ 0.02 m)都 5/5 成功;当前参数的最大位置误差 < 0.10 m;先验水平位置 3σ 的最大值:当前参数 < 0.5 m,旧参数 > 0.5 m |
|
||||
| `return_cylinder` | `return_contact/map.flmap` | 7 帧;当前参数成功的帧数多于旧参数(地图平移 σ 0.02 m);最大配准间隔当前参数 < 0.3 s、旧参数 ≥ 0.3 s;最大位置误差 < 0.10 m;旧参数至少 1 次新息拒绝 |
|
||||
|
||||
手动跑必须**正好带这三个目录**,顺序也要对,少一个多一个都直接返回 1:
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev
|
||||
build/bin/test_recorded_update \
|
||||
src/field_localization/tests/data/turn_contact \
|
||||
src/field_localization/tests/data/return_contact \
|
||||
src/field_localization/tests/data/return_cylinder
|
||||
```
|
||||
|
||||
每个片段的来源和它复现的问题见 [`data/README.md`](data/README.md)。
|
||||
|
||||
## 跨包依赖
|
||||
|
||||
本包的测试有两处依赖兄弟包 `sentry_nav` 的文件,删改那边时要留意:
|
||||
|
||||
| 依赖的文件 | 谁用 |
|
||||
|---|---|
|
||||
| `../../sentry_nav/tests/test_util.hpp` | 本目录的 `test_util.hpp`,也就是全部 12 个测试 |
|
||||
| `../../sentry_nav/include/sentry_nav/core/motion_interlock.hpp` | `test_tracking_safety.cpp`(`xmake.lua` 里给它加了 `add_includedirs("../sentry_nav/include")`) |
|
||||
|
||||
## 加新测试
|
||||
|
||||
1. 在本目录建 `test_xxx.cpp`
|
||||
2. `#include "test_util.hpp"` + `#include "field_localization/core/xxx.hpp"`
|
||||
3. `main()` 里跑断言,最后 `return sentry_nav_test::Summary("xxx");`
|
||||
4. 到 [`../xmake.lua`](../xmake.lua) 照抄一段:
|
||||
|
||||
```lua
|
||||
target("test_xxx")
|
||||
set_targetdir("$(builddir)/bin")
|
||||
set_kind("binary")
|
||||
set_languages("c++23")
|
||||
add_files("tests/test_xxx.cpp")
|
||||
add_deps("field_localization_core")
|
||||
add_tests("default", {group = "unit"})
|
||||
```
|
||||
|
||||
5. `xmake test`
|
||||
|
||||
> 加**测试**要改 `xmake.lua`(每个测试是独立 target);
|
||||
> 加**被测实现**(`src/core/*.cpp`)不用改,那是通配。
|
||||
|
||||
## 规矩
|
||||
|
||||
- **浮点比较永远用 `CHECK_NEAR`**,别用 `CHECK(a == b)`(`0.1 + 0.2 != 0.3`)
|
||||
- 每个测试文件 `main()` 只干一件事:把所有断言跑一遍、返回 `Summary()`
|
||||
- 断言旁边写一句**为什么**这个值是期望值,否则半年后看不懂
|
||||
- 除了 `test_ros_conversion`,测试里不许出现 ROS 头文件
|
||||
- 合成的精确地图要显式把 `map_translation_sigma` / `map_rotation_sigma` 设成 0,
|
||||
参考 `test_registration.cpp` 里的 `exact_map`
|
||||
- 修复过的线上(或录制里)失败要留一段数据做回归,放进 `data/`,并在 `provenance.txt` 里写清来源和现象
|
||||
|
||||
## 相关
|
||||
|
||||
- 回归数据:[`data/README.md`](data/README.md)
|
||||
- 历次验收记录:[`validation/README.md`](validation/README.md)
|
||||
- 被测实现:[`../src/core/README.md`](../src/core/README.md)
|
||||
- 接口:[`../include/field_localization/core/README.md`](../include/field_localization/core/README.md)
|
||||
- 断言框架的本体:[`../../sentry_nav/tests/README.md`](../../sentry_nav/tests/README.md)
|
||||
@@ -0,0 +1,81 @@
|
||||
# field_localization/tests/data/ (回归用的录制数据)
|
||||
|
||||
三段从 Gazebo 仿真里录下来的真实数据,**只有 `test_recorded_update.cpp` 用**,
|
||||
用来复现三个修复过的配准失败。总共约 1.2 MB,都在 git 里。
|
||||
|
||||
```
|
||||
data/
|
||||
├── README.md 本文件
|
||||
├── turn_contact/ 转弯时接触冲击:地图模型过度自信 → 新息拒绝级联
|
||||
├── return_contact/ 回程接触冲击:积分误差尺度太大 → 位置 3σ 越界、联锁停车
|
||||
└── return_cylinder/ 绕圆柱回程:配准在 FINAL_FUSION 被拒 → 停车
|
||||
```
|
||||
|
||||
它们不是完整的数据集,是从长录制里剪出来的几帧(5–7 帧点云、半秒多的 IMU),
|
||||
再加上一个**起始时刻的滤波器状态**,所以能从出事前一瞬间开始重放。
|
||||
|
||||
## 每个目录里有什么
|
||||
|
||||
| 文件 | 内容 | 读写方 |
|
||||
|---|---|---|
|
||||
| `config.txt` | 数据集头:已知初始位姿、两组固定外参、扫描时间模型 | `read_dataset_config()` / `write_dataset_config()` |
|
||||
| `imu.csv` | 表头 `timestamp,gx,gy,gz,ax,ay,az`。IMU 系的原始角速度(rad/s)和比力(m/s²),单位秒 | 录制工具写;回放工具和 `test_recorded_update` 读 |
|
||||
| `scans.csv` | 表头 `timestamp,file`。每帧点云的时间戳和相对本目录的路径 | 同上 |
|
||||
| `N.flpc` | FLPC v1 二进制点云,`lidar_link` 系 | `write_cloud()` / `read_cloud()` |
|
||||
| `truth.tum` | TUM 文本轨迹 `tx ty tz qx qy qz qw`,世界系(= map 系)真值 | `write_trajectory_sample()` / `read_trajectory()` |
|
||||
| `checkpoint.txt` | 起始时刻的滤波器状态,344 个空白分隔的数 | **只有 `test_recorded_update` 读** |
|
||||
| `provenance.txt` | 给人看的来源说明 | 没有代码读 |
|
||||
| `map.flmap` | FLMAP v1 地图,只有前两个目录有 | `read_map()` |
|
||||
|
||||
格式的定义在 [`dataset.hpp`](../../include/field_localization/core/dataset.hpp)
|
||||
和 [`map_io.hpp`](../../include/field_localization/core/map_io.hpp)。
|
||||
|
||||
`checkpoint.txt` 的排列顺序和 `FilterSnapshot` 一致:
|
||||
|
||||
```
|
||||
时间戳(1) 平移 xyz(3) 速度 xyz(3) 四元数 x y z w(4)
|
||||
陀螺零偏(3) 加计零偏(3) 重力(3) 协方差 18×18(324,按行)
|
||||
```
|
||||
|
||||
三份片段的 `config.txt` 内容相同:初始位姿 (−5, 3, 0) 朝向 0、IMU 在 base_link 上方 0.15 m、
|
||||
雷达相对 IMU 在 (−0.0935, −0.1512, 0.2552)、`instantaneous` 扫描。
|
||||
|
||||
`.flpc` 的编号不是从 0 开始的,因为是从长录制里剪出来的,保留的是原录制里的序号。
|
||||
|
||||
## 怎么用
|
||||
|
||||
平时不用管,`xmake test` 会连同 `test_recorded_update` 一起跑。手动跑的方式见
|
||||
[`../README.md`](../README.md)。
|
||||
|
||||
**这几个片段不能用 `field_localization_replay` 回放**:回放工具从 `config.txt` 的初始位姿起步、
|
||||
不读 `checkpoint.txt`,而片段的起点状态只存在 `checkpoint.txt` 里。
|
||||
|
||||
## 几条注意
|
||||
|
||||
- **IMU 传感器本身没有噪声**(Gazebo 的 IMU 配置如此),但有限采样率下的动力学不为零,
|
||||
接触冲击时单个样本的加速度变化能到 70 m/s² 以上
|
||||
- **真值只用来打分**,从不喂给滤波器
|
||||
- **三份片段用的是同一张地图**:`turn_contact/map.flmap` 和 `return_contact/map.flmap`
|
||||
是同一个文件,`return_cylinder` 直接用后者
|
||||
|
||||
## 加新的回归片段
|
||||
|
||||
1. 用 [`tools/capture_lio.py`](../../../../tools/capture_lio.py) 录一段完整的数据
|
||||
2. 新建目录,把出事前后的几帧剪出来:
|
||||
- `imu.csv` 要从起始时刻**或之前**开始,一直覆盖到最后一帧点云
|
||||
- `truth.tum` 覆盖同样的区间
|
||||
- `scans.csv` 里的路径是相对本目录的,`.flpc` 的文件名随意
|
||||
- `config.txt` 照抄录制出来的那份
|
||||
3. 写 `checkpoint.txt`。仓库里**没有**生成它的代码,现有三份是修复过程中手工导出的
|
||||
4. 写 `provenance.txt`:怎么录的、当时看到了什么现象
|
||||
5. 注册进测试:
|
||||
- [`../../xmake.lua`](../../xmake.lua) 里 `test_recorded_update` 的 `runargs` 加一项
|
||||
- [`../test_recorded_update.cpp`](../test_recorded_update.cpp) 里 `CHECK(argc==4)`
|
||||
和参数解析要一起改,并补上断言
|
||||
|
||||
## 相关
|
||||
|
||||
- 各片段的说明:[`turn_contact/`](turn_contact/README.md)、
|
||||
[`return_contact/`](return_contact/README.md)、[`return_cylinder/`](return_cylinder/README.md)
|
||||
- 用它们的测试:[`../README.md`](../README.md)
|
||||
- 完整数据集是怎么录出来的:[`../../src/tools/README.md`](../../src/tools/README.md)
|
||||
@@ -0,0 +1,47 @@
|
||||
# tests/data/return_contact/ (回归片段:回程接触冲击 → 位置 3σ 越界、联锁停车)
|
||||
|
||||
5 帧点云 + 对应 IMU,仿真时间 108.5–108.9 s,外加 108.5 s 时刻的滤波器预测。
|
||||
`test_recorded_update` 的第 2 个参数就是本目录。
|
||||
|
||||
## 来源
|
||||
|
||||
- 隔离的 Gazebo 仿真,**Shell 启动入口**(`sentry_up.sh`)拉起,空场景
|
||||
- 第二段路程:从 (0, 0) 回 (−5, 3)
|
||||
- 加速度在 108.59 s 变化了 72.23 m/s²,108.60 s 又变化了 71.77 m/s²(接触冲击)
|
||||
- IMU 传感器无噪声
|
||||
|
||||
来源说明的原文在 [`provenance.txt`](provenance.txt)。
|
||||
|
||||
## 它复现的问题
|
||||
|
||||
旧的积分误差尺度(2.0)下,冲击之后水平位置的 3σ 在 108.7 s 越过 0.5 m 的阈值,
|
||||
运动联锁据此停掉了导航目标。**地图匹配其实一直在正常进行**,停车是因为不确定度被估得太大。
|
||||
|
||||
现在的默认积分误差尺度是 1.4,同样的数据 3σ 保持在阈值以内。
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `1070.flpc` – `1074.flpc` | 5 帧点云,108.5 – 108.9 s |
|
||||
| `imu.csv` | 45 个 IMU 样本,108.48 – 108.92 s,100 Hz |
|
||||
| `truth.tum` | 44 行真值,108.48 – 108.92 s |
|
||||
| `map.flmap` | 本片段和 [`return_cylinder`](../return_cylinder/README.md) 用的地图。和 `turn_contact/map.flmap` 内容相同 |
|
||||
| `checkpoint.txt` | 108.5 s 的原始滤波器预测 |
|
||||
| `config.txt` | 初始位姿、外参、扫描时间模型 |
|
||||
| `provenance.txt` | 来源说明 |
|
||||
|
||||
通用的文件格式见 [`../README.md`](../README.md)。
|
||||
|
||||
## 测试里断言了什么
|
||||
|
||||
同一份数据跑两遍,比较**每帧扫描之前**的先验(见
|
||||
[`test_recorded_update.cpp`](../../test_recorded_update.cpp)):
|
||||
|
||||
| | 当前默认参数 | 旧参数 |
|
||||
|---|---|---|
|
||||
| 积分误差尺度 | 1.4 | 2.0 |
|
||||
| 地图平移 σ | 0.03 m | 0.02 m |
|
||||
| 配准成功 | 5/5 | 5/5 |
|
||||
| 最大位置误差 | < 0.10 m | 不断言 |
|
||||
| 先验水平位置 3σ 的最大值 | < 0.5 m | > 0.5 m |
|
||||
@@ -0,0 +1,50 @@
|
||||
# tests/data/return_cylinder/ (回归片段:绕圆柱回程 → 配准被拒后停车)
|
||||
|
||||
7 帧点云 + 对应 IMU,仿真时间 73.0–73.6 s,外加 73.0 s 时刻的实时预测。
|
||||
`test_recorded_update` 的第 3 个参数就是本目录。
|
||||
|
||||
## 来源
|
||||
|
||||
- 隔离的 Gazebo 仿真,**Python 启动入口**(`ros2 launch`)拉起
|
||||
- 场地里放了一个圆柱:中心 (−4, −1.5) m,半径 0.22 m
|
||||
- 路线:从 (0, 0) 回 (−5, 3)
|
||||
- IMU 传感器无噪声
|
||||
|
||||
来源说明的原文在 [`provenance.txt`](provenance.txt)。
|
||||
|
||||
## 它复现的问题
|
||||
|
||||
这段路在 73.3 s 和 73.4 s 连续两帧被拒后停下。被拒的帧配准阶段停在 `FINAL_FUSION`,
|
||||
新息超过六自由度门限。73.3 s 时估计比真值低了 0.075 m;
|
||||
在预测位姿和真实位姿下分别能找到 513 和 545 个内点。
|
||||
|
||||
> `provenance.txt` 写明:最初那次「找不到任何对应」的失败是另一个症状,
|
||||
> 没有同步录制,不在本片段里。
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `716.flpc` – `722.flpc` | 7 帧点云,73.0 – 73.6 s |
|
||||
| `imu.csv` | 65 个 IMU 样本,72.98 – 73.62 s,100 Hz |
|
||||
| `truth.tum` | 63 行真值,72.986 – 73.616 s |
|
||||
| `checkpoint.txt` | 73.0 s 的实时预测 |
|
||||
| `config.txt` | 初始位姿、外参、扫描时间模型 |
|
||||
| `provenance.txt` | 来源说明 |
|
||||
|
||||
**本目录没有 `map.flmap`**,测试用的是 [`../return_contact/map.flmap`](../return_contact/map.flmap)。
|
||||
|
||||
通用的文件格式见 [`../README.md`](../README.md)。
|
||||
|
||||
## 测试里断言了什么
|
||||
|
||||
用 `return_contact/map.flmap`,同样跑两遍比较(见
|
||||
[`test_recorded_update.cpp`](../../test_recorded_update.cpp)):
|
||||
|
||||
| | 当前默认参数 | 旧参数 |
|
||||
|---|---|---|
|
||||
| 地图平移 σ | 0.03 m | 0.02 m |
|
||||
| 配准成功的帧数 | **多于**旧参数(不写死具体数) | 较少 |
|
||||
| 最大配准间隔 | < 0.3 s | ≥ 0.3 s |
|
||||
| 最大位置误差 | < 0.10 m | 不断言 |
|
||||
| 新息拒绝次数 | 不断言 | ≥ 1 |
|
||||
@@ -0,0 +1,44 @@
|
||||
# tests/data/turn_contact/ (回归片段:转弯接触 → 新息拒绝级联)
|
||||
|
||||
5 帧点云 + 对应 IMU,仿真时间 21.6–22.0 s,外加 21.5 s 时刻的滤波器状态。
|
||||
`test_recorded_update` 的第 1 个参数就是本目录。
|
||||
|
||||
## 来源
|
||||
|
||||
- 隔离的 Gazebo 仿真,**Python 启动入口**(`ros2 launch`)拉起
|
||||
- 场地里放了一个圆柱:中心 (−4, −1.5) m,半径 0.22 m,高 0.8 m
|
||||
- IMU 传感器无噪声,但有限采样率下的动力学不为零
|
||||
|
||||
来源说明的原文在 [`provenance.txt`](provenance.txt)。
|
||||
|
||||
## 它复现的问题
|
||||
|
||||
[`checkpoint.txt`](checkpoint.txt) 是 21.5 s 时刻、**修复前的模型**已经接受的估计。
|
||||
从它出发处理这 5 帧,在「地图模型过度自信」的旧参数下会触发新息拒绝级联
|
||||
(NIS 先是 31.6,随后 35.1……):对应找得到,却因为新息过大被整帧拒绝。
|
||||
|
||||
> `provenance.txt` 里写明:这是**修复过程中发现的**失败的录制回归,
|
||||
> 不声称精确复现了最初那次没有录下来的发散。
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 内容 |
|
||||
|---|---|
|
||||
| `152.flpc` – `156.flpc` | 5 帧点云(`lidar_link` 系),时间 21.6 / 21.7 / 21.8 / 21.9 / 22.0 s |
|
||||
| `imu.csv` | 61 个 IMU 样本,21.5 – 22.1 s,100 Hz |
|
||||
| `truth.tum` | 5 行真值,21.6 – 22.0 s |
|
||||
| `map.flmap` | 本片段用的地图。和 [`return_contact/map.flmap`](../return_contact/map.flmap) 内容相同 |
|
||||
| `checkpoint.txt` | 21.5 s 的滤波器状态 |
|
||||
| `config.txt` | 初始位姿 (−5, 3, 0)、外参、`instantaneous` 扫描 |
|
||||
| `provenance.txt` | 来源说明 |
|
||||
|
||||
通用的文件格式见 [`../README.md`](../README.md)。
|
||||
|
||||
## 测试里断言了什么
|
||||
|
||||
用本目录的 `map.flmap` 和**当前默认参数**(见
|
||||
[`test_recorded_update.cpp`](../../test_recorded_update.cpp)):
|
||||
|
||||
- 5 帧全部配准成功(`FULL = 5/5`)
|
||||
- 最大位置误差 < 0.10 m
|
||||
- 最大旋转误差 < 0.02 rad
|
||||
@@ -14,9 +14,21 @@ int main() {
|
||||
CHECK_NEAR(read.points[0].timestamp_sec,0.99,1e-12); CHECK(read.points[0].position==cloud.points[0].position);
|
||||
CHECK(!read.points[1].position.allFinite());
|
||||
CoreOptions options; options.initial_pose.translation={-5,3,0}; options.deskew.imu_from_sensor.translation={-0.0935,-0.1512,0.2552};
|
||||
write_dataset_config(options,dir/"config.txt"); const auto config=read_dataset_config(dir/"config.txt");
|
||||
std::string frame;
|
||||
write_dataset_config(options,dir/"config.txt"); const auto config=read_dataset_config(dir/"config.txt",&frame);
|
||||
CHECK(frame=="lidar_link"); CHECK(!config.map_bounds);
|
||||
CHECK(config.initial_pose.translation==options.initial_pose.translation);
|
||||
CHECK(config.deskew.imu_from_sensor.translation==options.deskew.imu_from_sensor.translation);
|
||||
options.map_bounds=MapBounds{{-6.4,-4.4,-0.10},{6.4,4.4,0.65}};
|
||||
options.deskew.imu_from_sensor=Pose3D{};
|
||||
write_dataset_config(options,dir/"config.txt","imu_link");
|
||||
const auto cropped_config=read_dataset_config(dir/"config.txt",&frame);
|
||||
CHECK(frame=="imu_link"); CHECK(cropped_config.map_bounds.has_value());
|
||||
if (cropped_config.map_bounds) {
|
||||
CHECK(cropped_config.map_bounds->min==options.map_bounds->min);
|
||||
CHECK(cropped_config.map_bounds->max==options.map_bounds->max);
|
||||
}
|
||||
CHECK(read_cloud(dir/"scan.flpc",frame).frame_id=="imu_link");
|
||||
std::vector<TrajectorySample> truth,estimate;
|
||||
for (int i=0;i<=200;++i) {
|
||||
const double t=0.01*i; Pose3D pose{exp_so3({0.01*t,-0.03*t,0.1*t}),Eigen::Vector3d{t,0.2*t,0.1*t*t}};
|
||||
|
||||
@@ -88,7 +88,26 @@ int main() {
|
||||
}
|
||||
CHECK_NEAR(moving.get_pose().translation.x(),0.5,1e-9);
|
||||
CHECK_NEAR(moving.get_snapshot().filter.state.velocity.x(),1,1e-9);
|
||||
CHECK_NEAR(moving.get_twist().linear.x(),1.0,1e-9);
|
||||
CHECK_NEAR(moving.get_twist().linear.y(),0.0,1e-9);
|
||||
CHECK_NEAR(moving.get_snapshot().imu_dt,0.01,1e-12);
|
||||
CHECK(moving.get_status().mode==TrackingMode::IMU_ONLY);
|
||||
|
||||
// 偏心安装 IMU 原地小陀螺时,base_twist 必须消除杆臂切向速度 (v_base = 0)
|
||||
const Pose3D base_from_imu_offset{exp_so3({0,0,0.5*3.14159265358979323846}),Eigen::Vector3d{0.20,-0.10,0.15}};
|
||||
MotionState spin_state;
|
||||
spin_state.pose=compose(Pose3D{exp_so3({0,0,0.7}),Eigen::Vector3d{1.0,-2.0,0.0}},base_from_imu_offset);
|
||||
const Eigen::Vector3d omega_base{0.0,0.0,4.0};
|
||||
const Eigen::Vector3d gyro_bias_imu{0.02,-0.03,0.01};
|
||||
const Eigen::Vector3d raw_omega_imu=base_from_imu_offset.rotation.conjugate()*omega_base+gyro_bias_imu;
|
||||
// 刚体原地绕 base_link Z 轴旋转时,偏心 IMU 在 map 系的真实线速度为 R_MB * (omega_base x p_BI^B)
|
||||
const Eigen::Quaterniond r_mb=exp_so3({0,0,0.7});
|
||||
spin_state.velocity=r_mb*(omega_base.cross(base_from_imu_offset.translation));
|
||||
spin_state.gyro_bias=gyro_bias_imu;
|
||||
const Twist3D recovered_twist=base_twist(spin_state,raw_omega_imu,base_from_imu_offset);
|
||||
CHECK(recovered_twist.linear.norm()<1e-12);
|
||||
CHECK((recovered_twist.angular-omega_base).norm()<1e-12);
|
||||
|
||||
accelerated.timestamp_sec=0.5;
|
||||
CHECK(!moving.process_imu(accelerated));
|
||||
CHECK(moving.get_status().reason==FailureReason::TIME_ORDER);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "test_util.hpp"
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <numbers>
|
||||
using namespace field_localization::core;
|
||||
namespace {
|
||||
@@ -51,6 +52,37 @@ int main() {
|
||||
CHECK(!localization.load_map(folder/"broken.flmap",error)); CHECK(!error.empty());
|
||||
CHECK(localization.get_status().map_point_count==count);
|
||||
CHECK(!localization.load_map(folder/"missing.flmap",error));
|
||||
const MapBounds bounds{{-6.4,-4.4,-0.1},{6.4,4.4,0.65}};
|
||||
const Pose3D map_from_sensor{Eigen::Quaterniond::Identity(),{-6.0,0,0.4}};
|
||||
PointCloud extra;
|
||||
for (const Eigen::Vector3f &p : {Eigen::Vector3f{12,0,0.02F}, // far wall of playing field
|
||||
Eigen::Vector3f{2,0,-0.4F}, Eigen::Vector3f{0.5F,0,-0.2F}, // floor and near obstacle
|
||||
Eigen::Vector3f{26,0,0}, Eigen::Vector3f{6,0,9}, // gym wall and roof
|
||||
Eigen::Vector3f{12.5F,0,0}, // association margin only
|
||||
Eigen::Vector3f{std::numeric_limits<float>::quiet_NaN(),0,0},
|
||||
Eigen::Vector3f{std::numeric_limits<float>::infinity(),0,0}}) {
|
||||
PointXYZI point; point.position=p; extra.points.push_back(point);
|
||||
}
|
||||
CHECK(crop_to_map(extra,map_from_sensor,bounds).points.size()==3);
|
||||
CHECK(crop_to_map(extra,map_from_sensor,bounds,map_association_margin).points.size()==4);
|
||||
VoxelMap with_gym;
|
||||
with_gym.insert(extra,map_from_sensor);
|
||||
CHECK(save_map(with_gym,folder/"gym.flmap",error));
|
||||
const auto field=read_map(folder/"gym.flmap",error,bounds);
|
||||
CHECK(field && field->size()==3);
|
||||
|
||||
auto bounded_options=options;
|
||||
bounded_options.map_bounds=bounds;
|
||||
bounded_options.initial_pose=map_from_sensor;
|
||||
bounded_options.registration.minimum_inliers=3;
|
||||
LocalizationCore bounded(bounded_options);
|
||||
for (int i=0;i<=30;++i) { imu.timestamp_sec=0.01*i; CHECK(bounded.process_imu(imu)); }
|
||||
extra.timestamp_sec=0.2;
|
||||
CHECK(bounded.process_point_cloud(extra));
|
||||
CHECK(bounded.get_status().map_point_count==3);
|
||||
CHECK(bounded.export_map(folder/"bounded.flmap",error));
|
||||
const auto bounded_map=read_map(folder/"bounded.flmap",error);
|
||||
CHECK(bounded_map && bounded_map->size()==3);
|
||||
mapping.reset(); CHECK(mapping.get_status().map_point_count==0);
|
||||
localization.reset(); CHECK(localization.get_status().map_point_count==count);
|
||||
std::filesystem::remove_all(folder);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "test_util.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <numbers>
|
||||
using namespace field_localization;
|
||||
int main() {
|
||||
sensor_msgs::msg::PointCloud2 msg; msg.width=2; msg.height=2; msg.point_step=16; msg.row_step=40;
|
||||
@@ -24,5 +25,40 @@ int main() {
|
||||
const auto recovered=core::compose(ros::from_transform(ros::to_transform(map_from_odom)),odom_from_base);
|
||||
CHECK((recovered.translation-map_from_base.translation).norm()<1e-12);
|
||||
CHECK(core::log_so3(recovered.rotation.conjugate()*map_from_base.rotation).norm()<1e-12);
|
||||
tf2_ros::Buffer buffer(std::make_shared<rclcpp::Clock>(RCL_ROS_TIME));
|
||||
buffer.setUsingDedicatedThread(true);
|
||||
const Eigen::Vector3d feature{5.2,-0.3,0.4};
|
||||
const Eigen::Vector3d offset{-0.0935,-0.1512,0.2552};
|
||||
for (int sample=1;sample<=2;++sample) {
|
||||
const auto angle=core::exp_so3({0,0,(sample-1)*std::numbers::pi/2});
|
||||
const core::Pose3D imu_from_lidar{angle,angle*offset};
|
||||
geometry_msgs::msg::TransformStamped tf;
|
||||
tf.header.frame_id="imu_link"; tf.child_frame_id="lidar_link"; tf.header.stamp.sec=sample;
|
||||
tf.transform=ros::to_transform(imu_from_lidar);
|
||||
CHECK(buffer.setTransform(tf,"test"));
|
||||
}
|
||||
msg.header.frame_id="lidar_link"; msg.width=1; msg.height=1; msg.row_step=16;
|
||||
msg.data.resize(16);
|
||||
for (int sample=1;sample<=2;++sample) {
|
||||
msg.header.stamp.sec=sample;
|
||||
const auto angle=core::exp_so3({0,0,(sample-1)*std::numbers::pi/2});
|
||||
const Eigen::Vector3d local=angle.conjugate()*feature-offset;
|
||||
for (int axis=0;axis<3;++axis) {
|
||||
auto data=std::bit_cast<std::array<std::uint8_t,4>>(static_cast<float>(local[axis]));
|
||||
if constexpr(std::endian::native==std::endian::little) std::reverse(data.begin(),data.end());
|
||||
std::copy(data.begin(),data.end(),msg.data.begin()+axis*4);
|
||||
}
|
||||
const auto in_imu=ros::convert_cloud_in_frame(msg,"imu_link",buffer);
|
||||
CHECK(in_imu.frame_id=="imu_link"); CHECK(in_imu.points.size()==1);
|
||||
if (in_imu.points.size()==1) CHECK((in_imu.points.front().position.cast<double>()-feature).norm()<1e-6);
|
||||
}
|
||||
const core::Twist3D body_twist{{1.8,-0.25,0.03},{-0.01,0.02,3.4}};
|
||||
const auto ros_twist=ros::to_twist(body_twist);
|
||||
CHECK_NEAR(ros_twist.linear.x,1.8,1e-12);
|
||||
CHECK_NEAR(ros_twist.linear.y,-0.25,1e-12);
|
||||
CHECK_NEAR(ros_twist.linear.z,0.03,1e-12);
|
||||
CHECK_NEAR(ros_twist.angular.x,-0.01,1e-12);
|
||||
CHECK_NEAR(ros_twist.angular.y,0.02,1e-12);
|
||||
CHECK_NEAR(ros_twist.angular.z,3.4,1e-12);
|
||||
return sentry_nav_test::Summary("RosConversion");
|
||||
}
|
||||
@@ -30,5 +30,36 @@ int main() {
|
||||
gate.health(true,1.31);CHECK(gate.allowed(1.31));gate.health(false,1.32);CHECK(!gate.allowed(1.32));
|
||||
CHECK(!gate.allowed(0.9));
|
||||
sentry_nav::core::MotionInterlock manual(false);manual.command(2);CHECK(manual.allowed(2.1));CHECK(!manual.allowed(2.31));
|
||||
|
||||
// Verify base_twist_covariance analytical Jacobian against 18-DOF numerical central differences.
|
||||
LocalizationSnapshot ts;
|
||||
const Pose3D b_from_i{exp_so3({0.1,-0.2,0.6}),Eigen::Vector3d{0.18,-0.12,0.15}};
|
||||
ts.filter.state.pose={exp_so3({-0.05,0.08,1.1}),Eigen::Vector3d{-2.0,1.5,0.0}};
|
||||
ts.filter.state.velocity={2.3,-0.7,0.1};
|
||||
ts.filter.state.gyro_bias={0.01,-0.02,0.015};
|
||||
ts.raw_angular_velocity={0.1,0.2,3.5};
|
||||
ts.imu_dt=0.01;
|
||||
Matrix18 p18=0.02*Matrix18::Identity();
|
||||
Vector18 corr;
|
||||
for(int k=0;k<18;++k) corr[k]=0.01*(k+1);
|
||||
p18+=corr*corr.transpose();
|
||||
ts.filter.covariance=p18;
|
||||
Eigen::Matrix<double,6,18> j_num=Eigen::Matrix<double,6,18>::Zero();
|
||||
constexpr double eps=1e-6;
|
||||
for(int k=0;k<18;++k) {
|
||||
Vector18 delta=Vector18::Zero(); delta[k]=eps;
|
||||
const auto plus=base_twist(ErrorStateFilter::inject(ts.filter.state,delta),ts.raw_angular_velocity,b_from_i);
|
||||
const auto minus=base_twist(ErrorStateFilter::inject(ts.filter.state,-delta),ts.raw_angular_velocity,b_from_i);
|
||||
j_num.block<3,1>(0,k)=(plus.linear-minus.linear)/(2*eps);
|
||||
j_num.block<3,1>(3,k)=(plus.angular-minus.angular)/(2*eps);
|
||||
}
|
||||
const Matrix6 expected_cov=j_num*p18*j_num.transpose();
|
||||
const Matrix6 analytic_cov=base_twist_covariance(ts,b_from_i,0.0);
|
||||
CHECK((analytic_cov-expected_cov).norm()<1e-8);
|
||||
const Matrix6 noisy_cov=base_twist_covariance(ts,b_from_i,0.003);
|
||||
const Eigen::SelfAdjointEigenSolver<Matrix6> eig(noisy_cov);
|
||||
CHECK(eig.info()==Eigen::Success && eig.eigenvalues().minCoeff()>0.0);
|
||||
CHECK(noisy_cov(5,5)>analytic_cov(5,5));
|
||||
|
||||
return sentry_nav_test::Summary("TrackingSafety");
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# field_localization/tests/validation/ (历次验收的文字记录)
|
||||
|
||||
三个纯文本文件,是 2026-11-22 那一轮开发里三个阶段验收结果的留档。
|
||||
|
||||
- **没有任何脚本、测试或构建规则读它们。** 放在 `tests/` 下只是因为它们记录的是测试和验收的结论
|
||||
- 它们是**当时的快照**。之后代码和默认参数还改过,里面的数字不一定等于现在跑出来的结果,
|
||||
以代码和重新跑的结果为准
|
||||
- 三个文件都是英文,按阶段命名
|
||||
|
||||
| 文件 | 阶段 | 记了什么 |
|
||||
|---|---|---|
|
||||
| `filter_stage.txt` | 滤波器一致性 | 当时确认的 4 个滤波缺陷;单测通过情况;1078 帧和 159 帧两段 Gazebo 回放的 ATE / RPE;地图和关联不确定度的处理方式 |
|
||||
| `arena_stage.txt` | 场地导航 | 验收标准;圆柱场景两个启动入口的通过数;断流时 310 ms 出零速度并取消目标 |
|
||||
| `protection_stage.txt` | 失效保护与传输 | 单测 15/15、Nav2 就绪检查 15 项、监管 5 项、在线联锁 9 项;雷达断流后 233 ms 出零速度;点云和桥协商为 RELIABLE |
|
||||
|
||||
## 读的时候注意
|
||||
|
||||
**结果不是全过的。** `arena_stage.txt` 里圆柱场景的通过数是 Shell 入口 2/3、
|
||||
Python 入口 0/3(其中 2/3 到达了目标),文件末尾写明完整的导航验收当时仍然未通过。
|
||||
一次运行里垂直方向误差到了 0.652 m:水平位置和航向的联锁不保证垂直精度。
|
||||
|
||||
数字和现在的代码有出入的地方:
|
||||
|
||||
| 记录里写的 | 现在 |
|
||||
|---|---|
|
||||
| `filter_stage.txt`:单测 14/14 套件 | 15 个(本包 12 个 + `sentry_nav` 3 个),和另外两份记录一致 |
|
||||
| `filter_stage.txt`:地图不确定度默认 0.02 m、0.002 rad | 地图平移 σ 默认 0.03 m(`RegistrationOptions::map_translation_sigma`),旋转仍是 0.002 rad |
|
||||
|
||||
## 要现在的结果
|
||||
|
||||
重新跑,不要抄这里的数:
|
||||
|
||||
```bash
|
||||
cd ~/Gazebo_projects/sentry_nav_dev
|
||||
xmake test
|
||||
python3 tools/validation/verify_lio_stack.py --map src/sentry_sim/maps/field_full.flmap --output generated/lio_stack_check
|
||||
python3 tools/validation/validate_lio_navigation.py --launcher shell --scenario clear --goal 0 0 \
|
||||
--map src/sentry_sim/maps/field_full.flmap --output generated/lio_nav_check
|
||||
```
|
||||
|
||||
用法和各脚本对输出目录的要求见 [`tools/README.md`](../../../../tools/README.md)。
|
||||
|
||||
新的验收记录建议和这三个文件并排放在本目录,一个阶段一个文件,写明日期。
|
||||
|
||||
## 相关
|
||||
|
||||
- 单元测试:[`../README.md`](../README.md)
|
||||
- 录制数据回归:[`../data/README.md`](../data/README.md)
|
||||
@@ -21,19 +21,25 @@ namespace sentry_nav {
|
||||
|
||||
// 自滤参数。单位统一为米,坐标系为 base_link。
|
||||
struct FilterParams {
|
||||
// Keep the lateral limits close to the chassis (y +/-0.2605 m). Gazebo
|
||||
// lidar range noise puts gimbal returns beyond its physical x=0.32 m and
|
||||
// z=0.50 m limits. The recorded stationary envelope reaches x=0.357 m
|
||||
// and z=0.530 m, so retain margin at the front and above the gimbal.
|
||||
float box_min_x = -0.294f;
|
||||
// 云台 yaw 可以 360° 连续转,所以剔除盒必须覆盖**旋转组扫掠圆**,
|
||||
// 不能只贴着云台朝前时的位置。
|
||||
//
|
||||
// 扫掠半径 0.3021 m = 旋转组最远角 √(0.2656² + 0.1439²),yaw 轴在车体中心。
|
||||
// 旋转组的包络来自 tools/build_vehicle.py --split-gimbal(60 个零件)。
|
||||
//
|
||||
// Gazebo 雷达的距离噪声会把回波推到物理边界外一点,所以 x/y 都留 3 mm 余量,
|
||||
// 到 ±0.305 m。z 上限 0.545 m 沿用记录到的静止包络(实测到 0.530 m)。
|
||||
// box_max_x 保留 0.365:原来记录的静止包络到 x=0.357,那是既有行为,不顺手改。
|
||||
float box_min_x = -0.305f;
|
||||
float box_max_x = 0.365f;
|
||||
float box_min_y = -0.2655f;
|
||||
float box_max_y = 0.2655f;
|
||||
float box_min_y = -0.305f;
|
||||
float box_max_y = 0.305f;
|
||||
float box_min_z = -0.05f;
|
||||
float box_max_z = 0.545f;
|
||||
|
||||
float keep_min_z = 0.02f; // 低于此高度视为地面/噪声
|
||||
float max_range = 12.0f; // 水平距离上限
|
||||
float keep_max_z = 1.20f; // 与代价地图的观测高度一致,顶棚不参与避障
|
||||
float max_range = 8.0f; // 导航输入的水平距离上限
|
||||
};
|
||||
|
||||
// 丢弃原因。kNone 表示保留。
|
||||
@@ -42,6 +48,7 @@ enum class DropReason {
|
||||
kNonFinite, // NaN 或 inf
|
||||
kTooFar, // 水平距离超过 max_range
|
||||
kTooLow, // 低于 keep_min_z
|
||||
kTooHigh, // 高于 keep_max_z
|
||||
kInsideEgoBox, // 落在车身包围盒内(自身回波)
|
||||
};
|
||||
|
||||
|
||||
@@ -22,6 +22,9 @@ DropReason SelfFilterCore::Classify(float x, float y, float z) const {
|
||||
if (z < params_.keep_min_z) {
|
||||
return DropReason::kTooLow;
|
||||
}
|
||||
if (z > params_.keep_max_z) {
|
||||
return DropReason::kTooHigh;
|
||||
}
|
||||
// 车身包围盒内的点就是自身回波,剔除。
|
||||
// 注意用的是严格不等号:正好落在盒面上的点算保留。
|
||||
if (x > params_.box_min_x && x < params_.box_max_x &&
|
||||
@@ -42,6 +45,8 @@ const char* ToString(DropReason reason) {
|
||||
return "too_far";
|
||||
case DropReason::kTooLow:
|
||||
return "too_low";
|
||||
case DropReason::kTooHigh:
|
||||
return "too_high";
|
||||
case DropReason::kInsideEgoBox:
|
||||
return "inside_ego_box";
|
||||
}
|
||||
|
||||
@@ -20,20 +20,22 @@
|
||||
// input_topic /scan/points
|
||||
// output_topic /scan/points_filtered
|
||||
// target_frame base_link
|
||||
// box_min_x -0.40 车身包围盒(车身 x±0.288、y±0.26,留 ~10 cm 余量)
|
||||
// box_max_x 0.40
|
||||
// box_min_y -0.38
|
||||
// box_max_y 0.38
|
||||
// box_min_x -0.305 车身/云台扫掠包围盒(云台可 360° 转,
|
||||
// box_max_x 0.365 取旋转组扫掠半径 0.3021 m + 3 mm 余量;
|
||||
// box_min_y -0.305 box_max_x 保留 0.365 以维持原有前向包络过滤;
|
||||
// box_max_y 0.305 实际默认值在 self_filter_core.hpp 的 FilterParams)
|
||||
// box_min_z -0.05
|
||||
// box_max_z 0.60
|
||||
// box_max_z 0.545
|
||||
// keep_min_z 0.02 剔除后仍要保留的最低高度(低于此视为地面/噪声)
|
||||
// max_range 12.0 超过此**水平**距离的点丢弃
|
||||
// keep_max_z 1.20 排除超出代价地图观测高度的回波
|
||||
// max_range 8.0 避障点云水平距离上限
|
||||
// lio_max_range 40.2 雷达 40 m 量程加 0.2 m 安装偏心余量
|
||||
// scan_topic /scan2d 投影出的 2D 激光话题(给 AMCL;也喂 collision_monitor)
|
||||
// scan_bins 360 方位角分格数(360 = 每度一格)
|
||||
// scan_height_min 0.05 参与投影的最低高度(base_link 系,m)
|
||||
// scan_height_max 0.50 参与投影的最高高度(base_link 系,m)
|
||||
// scan_range_min 0.10 激光最小距离(m)
|
||||
// scan_range_max 12.0 激光最大距离(m)
|
||||
// scan_range_max 8.0 投影激光最大距离(m)
|
||||
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
@@ -85,6 +87,8 @@ public:
|
||||
declare_parameter<double>("box_max_z", params.box_max_z));
|
||||
params.keep_min_z = static_cast<float>(
|
||||
declare_parameter<double>("keep_min_z", params.keep_min_z));
|
||||
params.keep_max_z = static_cast<float>(
|
||||
declare_parameter<double>("keep_max_z", params.keep_max_z));
|
||||
params.max_range = static_cast<float>(
|
||||
declare_parameter<double>("max_range", params.max_range));
|
||||
|
||||
@@ -96,11 +100,13 @@ public:
|
||||
}
|
||||
auto lio_params = params;
|
||||
lio_params.keep_min_z = static_cast<float>(declare_parameter<double>("lio_keep_min_z", -0.25));
|
||||
lio_params.max_range = static_cast<float>(declare_parameter<double>("lio_max_range", 40.2));
|
||||
// Keep the floor outside the body footprint without admitting underbody returns.
|
||||
lio_params.box_min_z = std::min(lio_params.box_min_z, lio_params.keep_min_z);
|
||||
lio_core_ = std::make_unique<sentry_nav::SelfFilterCore>(lio_params);
|
||||
lio_pub_ = create_publisher<sensor_msgs::msg::PointCloud2>(lio_topic, rclcpp::QoS(5).reliable());
|
||||
RCLCPP_INFO(get_logger(), "LIO cloud: %s (keep_min_z=%.2f)", lio_topic.c_str(), lio_params.keep_min_z);
|
||||
RCLCPP_INFO(get_logger(), "LIO cloud: %s (z=[%.2f,%.2f] horizontal range=%.1f)",
|
||||
lio_topic.c_str(), lio_params.keep_min_z, lio_params.keep_max_z, lio_params.max_range);
|
||||
}
|
||||
|
||||
tf_buffer_ = std::make_unique<tf2_ros::Buffer>(get_clock());
|
||||
@@ -123,7 +129,7 @@ public:
|
||||
scan_height_min_ = declare_parameter<double>("scan_height_min", 0.05);
|
||||
scan_height_max_ = declare_parameter<double>("scan_height_max", 0.50);
|
||||
scan_range_min_ = declare_parameter<double>("scan_range_min", 0.10);
|
||||
scan_range_max_ = declare_parameter<double>("scan_range_max", 12.0);
|
||||
scan_range_max_ = declare_parameter<double>("scan_range_max", params.max_range);
|
||||
scan_pub_ = create_publisher<sensor_msgs::msg::LaserScan>(scan_topic_, rclcpp::QoS(10));
|
||||
|
||||
RCLCPP_INFO(
|
||||
@@ -145,7 +151,10 @@ private:
|
||||
{
|
||||
sensor_msgs::msg::PointCloud2 cloud_in_target;
|
||||
try {
|
||||
// 点云转到 base_link(雷达在 lidar_link 上,两者只差一个固定变换)
|
||||
// 点云转到 base_link。雷达装在弹仓上、弹仓随云台 yaw 转,
|
||||
// 所以 base_link->lidar_link 是一条**会变**的变换链
|
||||
// (base_link->gimbal_yaw_link 由 /joint_states 驱动),
|
||||
// 必须按时间戳查 TF,不能当固定外参处理。
|
||||
geometry_msgs::msg::TransformStamped tf = tf_buffer_->lookupTransform(
|
||||
target_frame_, msg->header.frame_id, msg->header.stamp,
|
||||
rclcpp::Duration::from_seconds(0.2));
|
||||
@@ -266,7 +275,7 @@ private:
|
||||
double scan_height_min_{0.05};
|
||||
double scan_height_max_{0.50};
|
||||
double scan_range_min_{0.10};
|
||||
double scan_range_max_{12.0};
|
||||
double scan_range_max_{8.0};
|
||||
|
||||
std::unique_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
|
||||
@@ -36,12 +36,21 @@ int main() {
|
||||
EXPECT_TRUE(filter.Keep(2.0f, 0.0f, 0.02f)); // 正好等于阈值 -> 保留
|
||||
|
||||
// ---------- 4. 太远的点必须剔除(用的是水平距离)----------
|
||||
// max_range = 12.0
|
||||
// Nav2 range is separate from the range used by the LiDAR and LIO.
|
||||
EXPECT_EQ(filter.Classify(12.5f, 0.0f, 0.30f), DropReason::kTooFar);
|
||||
EXPECT_EQ(filter.Classify(9.0f, 9.0f, 0.30f), DropReason::kTooFar); // 水平 12.73 m
|
||||
EXPECT_TRUE(filter.Keep(11.9f, 0.0f, 0.30f));
|
||||
// 水平刚好 12.0 不算「大于」,保留
|
||||
EXPECT_TRUE(filter.Keep(12.0f, 0.0f, 0.30f));
|
||||
EXPECT_TRUE(filter.Keep(7.9f, 0.0f, 0.30f));
|
||||
// 水平刚好 8.0 不算「大于」,保留
|
||||
EXPECT_TRUE(filter.Keep(8.0f, 0.0f, 0.30f));
|
||||
EXPECT_FALSE(filter.Keep(8.01f, 0.0f, 0.30f));
|
||||
EXPECT_FALSE(filter.Keep(0.0f, 7.5f, 9.9f)); // gym roof within the horizontal limit
|
||||
EXPECT_TRUE(filter.Keep(2.0f, 0.0f, 1.2f));
|
||||
FilterParams lio_params;
|
||||
lio_params.max_range=40.2f;
|
||||
lio_params.keep_min_z=-0.25f;
|
||||
const SelfFilterCore lio(lio_params);
|
||||
EXPECT_TRUE(lio.Keep(13.0f, 0.0f, 0.42f)); // opposite field boundary
|
||||
EXPECT_TRUE(lio.Keep(2.0f, 0.0f, 0.0f)); // floor
|
||||
|
||||
// 高度不影响距离判定:很高的远点仍然按水平距离算
|
||||
EXPECT_EQ(filter.Classify(20.0f, 0.0f, 9.0f), DropReason::kTooFar);
|
||||
@@ -57,16 +66,30 @@ int main() {
|
||||
|
||||
// ---------- 6. 边界:盒面用严格不等号,落在面上算保留 ----------
|
||||
EXPECT_TRUE(filter.Keep(0.365f, 0.0f, 0.30f)); // x == box_max_x
|
||||
EXPECT_TRUE(filter.Keep(-0.294f, 0.0f, 0.30f)); // x == box_min_x
|
||||
EXPECT_TRUE(filter.Keep(0.0f, 0.2655f, 0.30f)); // y == box_max_y
|
||||
EXPECT_TRUE(filter.Keep(-0.305f, 0.0f, 0.30f)); // x == box_min_x
|
||||
EXPECT_TRUE(filter.Keep(0.0f, 0.305f, 0.30f)); // y == box_max_y
|
||||
EXPECT_TRUE(filter.Keep(0.0f, -0.305f, 0.30f)); // y == box_min_y
|
||||
EXPECT_TRUE(filter.Keep(0.0f, 0.0f, 0.545f)); // z == box_max_z
|
||||
// 稍微往里一点就该被剔
|
||||
EXPECT_EQ(filter.Classify(0.364f, 0.0f, 0.30f), DropReason::kInsideEgoBox);
|
||||
EXPECT_EQ(filter.Classify(0.0f, 0.304f, 0.30f), DropReason::kInsideEgoBox);
|
||||
|
||||
EXPECT_TRUE(filter.Keep(0.37f, 0.0f, 0.30f)); // external obstacle before contact
|
||||
EXPECT_FALSE(filter.Keep(0.357f, 0.14f, 0.530f)); // measured gimbal return envelope
|
||||
EXPECT_TRUE(filter.Keep(0.0f, 0.30f, 0.30f));
|
||||
EXPECT_TRUE(filter.Keep(0.0f, 0.31f, 0.30f)); // just outside the widened box
|
||||
EXPECT_EQ(filter.Classify(0.319f, 0.14f, 0.49f), DropReason::kInsideEgoBox);
|
||||
|
||||
// ---------- 6b. 云台 360° 旋转:剔除盒必须覆盖整个扫掠圆 ----------
|
||||
// 旋转组绕 yaw 轴(车体中心)转,最远角半径 0.3021 m。盒是正方形,
|
||||
// 所以只要四个边都 >= 0.3021,圆上任意一点都在盒内。
|
||||
constexpr float kSweptRadius = 0.3021f;
|
||||
constexpr int kSteps = 72; // 每 5° 取一个方向
|
||||
for (int i = 0; i < kSteps; ++i) {
|
||||
const float angle = 6.2831853f * static_cast<float>(i) / kSteps;
|
||||
const float x = kSweptRadius * std::cos(angle);
|
||||
const float y = kSweptRadius * std::sin(angle);
|
||||
EXPECT_EQ(filter.Classify(x, y, 0.40f), DropReason::kInsideEgoBox);
|
||||
}
|
||||
// ---------- 7. 自定义参数的构造函数确实生效 ----------
|
||||
FilterParams small;
|
||||
small.max_range = 3.0f;
|
||||
@@ -76,7 +99,7 @@ int main() {
|
||||
EXPECT_TRUE(strict.Keep(2.9f, 0.0f, 0.30f));
|
||||
EXPECT_FALSE(strict.Keep(2.0f, 0.0f, 0.05f)); // 低于 0.10
|
||||
EXPECT_NEAR(strict.squared_max_range(), 9.0f, 1e-6);
|
||||
EXPECT_NEAR(filter.squared_max_range(), 144.0f, 1e-6);
|
||||
EXPECT_NEAR(filter.squared_max_range(), 64.0f, 1e-6);
|
||||
|
||||
// ---------- 8. ToString 不返回空 ----------
|
||||
EXPECT_TRUE(sentry_nav::ToString(DropReason::kInsideEgoBox) != nullptr);
|
||||
|
||||
@@ -24,14 +24,8 @@ PKG_SHARE="${SENTRY_SIM_SHARE:-${WS}/src/sentry_sim}"
|
||||
`PKG_SHARE` 直接指向**这个目录本身**。没有 `install/`、没有符号链接、
|
||||
没有 `ros2 pkg prefix` —— 以前那套 ament 安装已经去掉了。
|
||||
|
||||
唯一的例外是 URDF 里引用网格的路径:
|
||||
|
||||
```xml
|
||||
<mesh filename="$(env SENTRY_SIM_SHARE)/meshes/base.stl"/>
|
||||
```
|
||||
|
||||
`scripts/sentry_up.sh` 和 `tools/gen_sdf.sh` 都会自动 `export SENTRY_SIM_SHARE`,
|
||||
你手动跑 `xacro` 时要自己设一下(不设会报 `environment variable 'SENTRY_SIM_SHARE' is not set`)。
|
||||
模型网格以模型文件所在目录为基准。生成的 URDF 也使用以自身目录为基准的相对路径。
|
||||
启动器在将机器人描述交给 ROS 时,才把网格路径解析成 RViz 能读取的 `file://` URI。
|
||||
|
||||
## 改完东西的标准流程
|
||||
|
||||
@@ -86,7 +80,7 @@ cd ~/Gazebo_projects/sentry_nav_dev && scripts/sentry_up.sh
|
||||
|
||||
| 传感器 | 位置/参数 | 话题 |
|
||||
|---|---|---|
|
||||
| 3D 激光雷达(CPU 射线) | 360 线 × 40 层,垂直 -7°~+52°,量程 0.10–12 m,10 Hz,噪声 σ=0.01;装在 `lidar_link`(z≈0.405) | gz `scan` → `/scan`(LaserScan)+ `/scan/points`(PointCloud2,frame=`lidar_link`) |
|
||||
| 3D 激光雷达(OGRE2) | 360 方位 × 40 层,垂直 −7° 至 +52°,量程 0.10–40 m,10 Hz,噪声 σ=0.01 m,随云台转动 | gz `scan` → `/scan`(LaserScan)+ `/scan/points`(PointCloud2,frame=`lidar_link`) |
|
||||
| 点云自滤 | 剔除车身包围盒内回波 | 输入 `/scan/points` → 输出 `/scan/points_filtered`(frame=`base_link`) |
|
||||
| 2D 激光(定位用) | 由自滤节点从 3D 点云投影:z∈[0.05, 0.50] m、360 格 | `/scan2d`(frame=`base_link`,AMCL / collision_monitor 用) |
|
||||
| IMU | `imu_link`,100 Hz | gz `imu` → `/imu` |
|
||||
@@ -182,15 +176,11 @@ ax_min: -3.5
|
||||
两个都是**只读诊断**,不需要高性能,没有迁移成 C++ 的理由。
|
||||
`launch/sentry_arena.launch.py` 是 ROS launch 系统要求,**没法用 C++**。
|
||||
|
||||
## CPU 忙不过来怎么办(雷达是 CPU 射线)
|
||||
## Gazebo 渲染与物理
|
||||
|
||||
3D 雷达是 `type="lidar"`(CPU 射线),360×40 = **14,400 束/帧 × 10 Hz**,
|
||||
再加 Gazebo 渲染 + RViz,是整台机器最大的 CPU 消耗。可选手段:
|
||||
|
||||
1. **关 RViz**:`RVIZ=0 scripts/sentry_up.sh`(导航不受影响,需要看图时另开 RViz);
|
||||
2. **降低雷达竖直采样**:`urdf/sentry.urdf.xacro` 里 `<vertical><samples>40` 改小(如 24),
|
||||
再 `./tools/gen_sdf.sh`——代价是点云变稀;
|
||||
3. **GPU 辅助**:把传感器换成 `gpu_lidar`(OGRE2 渲染,射线在 GPU 上算)。
|
||||
前提是显卡驱动可用:本机有 RTX 5060 Max-Q,但当前 `nvidia-smi` 连不上驱动(prime on-demand
|
||||
模式下驱动未加载),**先修驱动再谈 GPU 雷达**;修好后把 URDF 换成 gpu_lidar 即可显著降 CPU。
|
||||
场地和车辆网格由 OGRE2 绘制,3D 雷达使用 `gpu_lidar`。无界面启动时,`HEADLESS=1`
|
||||
和 `headless:=true` 都启用 EGL。Gazebo 的渲染器日志可用来确认实际设备,
|
||||
其中 `llvmpipe` 表示 Mesa 软件渲染。
|
||||
|
||||
刚体碰撞、车轮关节和摩擦由 Gazebo 的默认 DART 物理引擎计算。性能对照时同时记录实时因子、
|
||||
CPU 开销和点云频率,并标注渲染设备。
|
||||
@@ -3,18 +3,20 @@
|
||||
| 文件 | 说明 |
|
||||
|---|---|
|
||||
| `nav2_params.yaml` | Nav2 全部参数(代价地图、MPPI 控制器、AMCL、行为树…) |
|
||||
| `field_cloud.yaml` | 建图、定位与录制共用的比赛场地 XYZ 裁剪范围 |
|
||||
| `sentry.rviz` | RViz 布局(Map / LaserScan / TF / Costmap 已配好) |
|
||||
|
||||
## nav2_params.yaml 里改过的关键项
|
||||
|
||||
| 参数 | 值 | 为什么 |
|
||||
|---|---|---|
|
||||
| `footprint` | `[[0.325,0.270],[0.325,-0.270],[-0.325,-0.270],[-0.325,0.270]]` | 车体 0.578×0.521 实测 |
|
||||
| `inflation_radius` | `0.45`(默认 0.70 会把 12×8 场地填死) | 场地太小 |
|
||||
| `footprint` | `[[0.305,0.305],[0.305,-0.305],[-0.305,-0.305],[-0.305,0.305]]` | 0.61×0.61 正方形:必须覆盖云台 yaw 的扫掠圆(半径 0.3021 m,见 `src/sentry_sim/urdf/README.md`) |
|
||||
| `inflation_radius` | `0.60`(默认 0.70 会把 12×8 场地填死;0.45 太贴障碍) | 场地太小 + 矩形底盘要留转向余量 |
|
||||
| `consider_footprint` | `true` | 与矩形 footprint 对齐,否则 MPPI 判碰撞不一致 |
|
||||
| `enable_stamped_cmd_vel` | `false`(**8 处**:bt_navigator / controller_server / behavior_server / route_server / velocity_smoother / collision_monitor / docking_server / following_server) | 本版本默认发 TwistStamped,而 ros_gz 桥只认 Twist |
|
||||
| `default_server_timeout` / `wait_for_service_timeout` | `15000` | 本机启动慢,否则 BT 建树失败 |
|
||||
| local costmap `plugins` | 只有 `inflation_layer` | 2D 雷达会扫到车身自身,参与代价地图会把自己围死 |
|
||||
| global costmap `plugins` | `static_layer` + `inflation_layer` | 场地是静态的,用地图就够 |
|
||||
| local costmap `plugins` | `static_layer`、`voxel_layer`、`inflation_layer` | 静态栅格和自滤后的实时点云 |
|
||||
| global costmap `plugins` | `static_layer`、`obstacle_layer`、`inflation_layer` | 使用同一份自滤点云处理动态障碍 |
|
||||
| 障碍标记 / 清障距离 | 4.5 m / 8 m | 避障距离独立于原始雷达的 40 m 量程 |
|
||||
|
||||
> 改之前先看一眼注释,里面写了每处的原因。
|
||||
@@ -0,0 +1,4 @@
|
||||
/**:
|
||||
ros__parameters:
|
||||
map_crop_min: [-6.4, -4.4, -0.10]
|
||||
map_crop_max: [6.4, 4.4, 0.65]
|
||||
@@ -13,7 +13,7 @@ amcl:
|
||||
global_frame_id: "map"
|
||||
lambda_short: 0.1
|
||||
laser_likelihood_max_dist: 2.0
|
||||
laser_max_range: 12.0 # 雷达量程 12 m(真机 40 m),写 100 会把虚警算成有效
|
||||
laser_max_range: 8.0 # /scan2d 的导航观测距离
|
||||
laser_min_range: 0.15 # 自击点已被 self_filter 在投影时剔除,不用靠 0.6 遮挡
|
||||
laser_model_type: "likelihood_field"
|
||||
max_beams: 60
|
||||
@@ -275,7 +275,7 @@ local_costmap:
|
||||
width: 6
|
||||
height: 6
|
||||
resolution: 0.05
|
||||
footprint: "[[0.325, 0.270], [0.325, -0.270], [-0.325, -0.270], [-0.325, 0.270]]"
|
||||
footprint: "[[0.305, 0.305], [0.305, -0.305], [-0.305, -0.305], [-0.305, 0.305]]"
|
||||
# MID-360 的 3D 点云已接入(/scan/points,PointCloud2)
|
||||
# MID-360 点云经 sentry_nav/self_filter 自滤(剔除车身包围盒内的点)后接入
|
||||
# Retain known thin/occluded geometry when the live cloud sparsely samples it.
|
||||
@@ -298,7 +298,7 @@ local_costmap:
|
||||
obstacle_min_range: 0.20
|
||||
obstacle_max_range: 4.5
|
||||
raytrace_min_range: 0.20
|
||||
raytrace_max_range: 12.0
|
||||
raytrace_max_range: 8.0
|
||||
clearing: True
|
||||
marking: True
|
||||
filters: ["keepout_filter"]
|
||||
@@ -325,7 +325,7 @@ global_costmap:
|
||||
publish_frequency: 1.0
|
||||
global_frame: map
|
||||
robot_base_frame: base_link
|
||||
footprint: "[[0.325, 0.270], [0.325, -0.270], [-0.325, -0.270], [-0.325, 0.270]]"
|
||||
footprint: "[[0.305, 0.305], [0.305, -0.305], [-0.305, -0.305], [-0.305, 0.305]]"
|
||||
resolution: 0.05
|
||||
track_unknown_space: true
|
||||
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
|
||||
@@ -341,7 +341,7 @@ global_costmap:
|
||||
obstacle_min_range: 0.20
|
||||
obstacle_max_range: 4.5
|
||||
raytrace_min_range: 0.20
|
||||
raytrace_max_range: 12.0
|
||||
raytrace_max_range: 8.0
|
||||
clearing: True
|
||||
marking: True
|
||||
filters: ["keepout_filter", "speed_filter"]
|
||||
|
||||
@@ -26,7 +26,7 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py --show-args # 看
|
||||
|
||||
| 参数 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `headless` | `false` | `true` = 不显示 Gazebo 界面(`gz sim -s`) |
|
||||
| `headless` | `false` | `true` = 无界面 EGL 渲染(`gz sim -s --headless-rendering`) |
|
||||
| `nav2` | `true` | `false` = 不起 Nav2 |
|
||||
| `rviz` | `true` | `false` = 不起 RViz(`headless:=true` 时自动关) |
|
||||
| `world` | `sentry_arena.sdf` | `worlds/` 下的世界文件名 |
|
||||
|
||||
@@ -67,8 +67,8 @@ from launch_ros.parameter_descriptions import ParameterValue
|
||||
# ---------------------------------------------------------------------------
|
||||
# 路径推算:launch/ 的上一级是 src/sentry_sim,再上三级是仓库根
|
||||
# ---------------------------------------------------------------------------
|
||||
PKG_SHARE = Path(__file__).resolve().parents[1] # src/sentry_sim
|
||||
WS = Path(__file__).resolve().parents[3] # 仓库根
|
||||
WS = Path(__file__).resolve().parents[3]
|
||||
PKG_SHARE = Path(os.environ.get('SENTRY_SIM_SHARE') or WS / 'src' / 'sentry_sim').resolve()
|
||||
SCRIPTS = PKG_SHARE / 'scripts'
|
||||
TOOLS_DIR = WS / 'tools'
|
||||
INTERNAL_TOOLS = TOOLS_DIR / '_internal'
|
||||
@@ -81,6 +81,7 @@ if str(TOOLS_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(TOOLS_DIR))
|
||||
import project_env # noqa: E402 (必须在 sys.path 调整之后导入)
|
||||
from _internal.dds_environment import defaults as dds_defaults # noqa: E402
|
||||
from _internal.robot_description import runtime_description # noqa: E402
|
||||
|
||||
BIN_DIR = LaunchConfiguration('_sentry_bin_dir')
|
||||
GZ_MAJOR_VERSION = LaunchConfiguration('_sentry_gz_major_version')
|
||||
@@ -111,13 +112,17 @@ def _resolve_environment(context):
|
||||
def _start_gazebo(context):
|
||||
headless = LaunchConfiguration('headless').perform(context).lower() in ('true', '1')
|
||||
# Keep -r in both modes so that the world starts unpaused.
|
||||
args = ['-s', '-r'] if headless else ['-r']
|
||||
args = ['-s', '--headless-rendering', '-r'] if headless else ['-r']
|
||||
if major := GZ_MAJOR_VERSION.perform(context):
|
||||
args.extend(['--force-version', major])
|
||||
world_path = PathJoinSubstitution([str(PKG_SHARE / 'worlds'), LaunchConfiguration('world')])
|
||||
# 无界面模式下 OGRE2 走 EGL:不把 vendor 指向 NVIDIA,gpu_lidar 会退到
|
||||
# Mesa llvmpipe 软件光栅。判定在 project_env.gpu_env() 里,
|
||||
# SENTRY_GPU_EGL=off 可关闭。
|
||||
return [ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', *args, world_path],
|
||||
name='gazebo', output='screen',
|
||||
additional_env=project_env.gpu_env(),
|
||||
)]
|
||||
|
||||
|
||||
@@ -127,20 +132,6 @@ def _on_bridge_exit(event, context):
|
||||
return []
|
||||
|
||||
|
||||
def _robot_description():
|
||||
"""在**构建 launch 描述时**就把 URDF 展开成字符串。
|
||||
|
||||
为什么不放到运行时用 `Command(['xacro ', ...])`:URDF 里的网格路径是
|
||||
`$(env SENTRY_SIM_SHARE)/meshes/*.stl`,而本工程不用 ament。
|
||||
这里显式给 xacro 传入这个环境变量,时序上最稳。
|
||||
"""
|
||||
env = dict(os.environ)
|
||||
env['SENTRY_SIM_SHARE'] = str(PKG_SHARE)
|
||||
return subprocess.run(
|
||||
['xacro', str(PKG_SHARE / 'urdf' / 'sentry.urdf.xacro')],
|
||||
env=env, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def _gz_resource_path():
|
||||
"""GZ_SIM_RESOURCE_PATH:本包的 models + 迁移包的 models(可带用户追加的)。"""
|
||||
# 注意冒号分隔符不能漏 —— 漏了会拼成一条不存在的路径,
|
||||
@@ -208,7 +199,7 @@ def generate_launch_description():
|
||||
"'", rviz, "'.lower() in ('true', '1') and '",
|
||||
headless, "'.lower() not in ('true', '1')"])
|
||||
|
||||
robot_description = _robot_description()
|
||||
robot_description = runtime_description(PKG_SHARE)
|
||||
bridge = ExecuteProcess(
|
||||
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
|
||||
name='ros_gz_bridge', output='screen',
|
||||
@@ -250,7 +241,7 @@ def generate_launch_description():
|
||||
# ---------------- 参数 ----------------
|
||||
DeclareLaunchArgument(
|
||||
'headless', default_value='false',
|
||||
description='true = 不显示 Gazebo 界面(gz sim -s)'),
|
||||
description='true = Gazebo 服务端使用 EGL 渲染,无界面'),
|
||||
DeclareLaunchArgument(
|
||||
'nav2', default_value='true', description='false = 不起 Nav2'),
|
||||
DeclareLaunchArgument(
|
||||
@@ -274,7 +265,7 @@ def generate_launch_description():
|
||||
'GZ_PARTITION', os.environ.get('GZ_PARTITION') or 'sentry'),
|
||||
SetEnvironmentVariable(
|
||||
'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']),
|
||||
# URDF 的网格路径靠它解析;tools/check_stack.py 也读它
|
||||
# 给子进程保留数据包目录
|
||||
SetEnvironmentVariable('SENTRY_SIM_SHARE', str(PKG_SHARE)),
|
||||
OpaqueFunction(function=_preflight_nav2),
|
||||
|
||||
@@ -298,6 +289,8 @@ def generate_launch_description():
|
||||
'robot_description': ParameterValue(
|
||||
robot_description, value_type=str),
|
||||
'use_sim_time': True,
|
||||
# Resolve LiDAR TF at the scan stamp during fast gimbal motion.
|
||||
'publish_frequency': 100.0,
|
||||
}],
|
||||
),
|
||||
|
||||
@@ -330,6 +323,7 @@ def generate_launch_description():
|
||||
|
||||
ExecuteProcess(
|
||||
cmd=[PathJoinSubstitution([BIN_DIR, 'field_localization_node']), '--ros-args',
|
||||
'--params-file', str(PKG_SHARE / 'config' / 'field_cloud.yaml'),
|
||||
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true',
|
||||
'-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')],
|
||||
'-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map],
|
||||
|
||||
Binary file not shown.
@@ -4,10 +4,11 @@
|
||||
|
||||
| 文件 | 内容 | 面数 |
|
||||
|---|---|---|
|
||||
| `base.stl` | 车体(含云台、MID-360、悬挂等,除 4 个轮子外全部) | 约 25.7 万 |
|
||||
| `base.stl` | 车体(底盘 + MID-360 + 悬挂 + 传动件,除 4 个轮子和**云台**外全部) | 约 19.5 万 |
|
||||
| `gimbal.stl` | 云台旋转组(60 个零件),原点 = **yaw 轴 + 安装面** | 约 6.1 万 |
|
||||
| `wheel.stl` | 单个麦轮(四个轮子几何相同) | 约 3.1 万 |
|
||||
| `transform.json` | 旧版(底盘+云台分别导入)的转换参数,仅作参考 |
|
||||
| `gimbal_transform.json` | 同上,云台那套的转换参数 |
|
||||
| `gimbal_transform.json` | ⚠️ **过期**:上一次拆分尝试留下的参数,它的原点取的是 GM6020 电机轴(偏 89.9 mm),不是 yaw 轴。以 `full/vehicle_layout.json` 的 `yaw_axis_ros_xy_m` 为准 |
|
||||
| `full/` | 原始高模 + 装配体实测布局,见其 README |
|
||||
|
||||
## 坐标系
|
||||
@@ -15,12 +16,28 @@
|
||||
已转到 REP-103(X 前、Y 左、Z 上),原点 = 车体几何中心的地面投影。
|
||||
SW 装配体是 Y 向上:`ROS_x = SW_z`、`ROS_y = SW_x`、`ROS_z = SW_y`;车头 = +SW_z。
|
||||
|
||||
`gimbal.stl` 例外:原点在 **yaw 轴 + 安装面**,因为 URDF 的 `gimbal_yaw_joint`
|
||||
就绕这一点转。yaw 轴由 5 个本该同轴的零件(70齿大带轮 / 云台内圈 / 15.5滑环 /
|
||||
内70外86 轴承 ×2)求得,实测落在车体中心,共轴离散 0.03 mm。
|
||||
|
||||
## 重新生成
|
||||
|
||||
云台已经拆成独立 link(可 360° 连续转),所以 `--split-gimbal` 是**必须**的:
|
||||
|
||||
```bash
|
||||
python3 tools/build_vehicle.py --src "<SW导出目录>" --out src/sentry_sim/meshes/full
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/meshes/wheel.stl --grid 0.0025
|
||||
python3 tools/build_vehicle.py --src "<SW导出目录>" --out src/sentry_sim/meshes/full --split-gimbal
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/gimbal.stl src/sentry_sim/meshes/gimbal.stl --grid 0.0025
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/meshes/wheel.stl --grid 0.0025
|
||||
./tools/gen_sdf.sh
|
||||
```
|
||||
|
||||
> ⚠️ 不减面的话,250 万面的车体会让 Gazebo 加载超过 150 秒甚至起不来。
|
||||
>
|
||||
> ⚠️ 不带 `--split-gimbal` 时云台零件会并回 `base.stl`,而 URDF 引用的
|
||||
> `gimbal.stl` 就不存在了 —— 仿真会报找不到网格。
|
||||
|
||||
`--split-gimbal` 有两项自检,任一不过就停下(不会静默产出错的图):
|
||||
|
||||
1. `classify()` 先判 `CHASSIS_KEYS`(电机 / 皮带 / 基座板留在底盘),再判云台关键字
|
||||
2. yaw 轴候选的共轴离散必须 ≤ `YAW_AXIS_SPREAD_MM`(5 mm)
|
||||
Binary file not shown.
Binary file not shown.
@@ -44,7 +44,29 @@
|
||||
0.082
|
||||
],
|
||||
"yaw_axis_ros_xy_m": [
|
||||
0.08986,
|
||||
-0.00017
|
||||
-0.00015,
|
||||
-1e-05
|
||||
],
|
||||
"gimbal_origin_sw_mm": [
|
||||
31386.38,
|
||||
176.6,
|
||||
10455.21
|
||||
],
|
||||
"gimbal_bbox_ros_m": [
|
||||
[
|
||||
-0.1951,
|
||||
-0.1399,
|
||||
0.0
|
||||
],
|
||||
[
|
||||
0.2658,
|
||||
0.1439,
|
||||
0.3818
|
||||
]
|
||||
],
|
||||
"gimbal_joint_origin_ros_m": [
|
||||
-0.00015,
|
||||
-1e-05,
|
||||
0.11872
|
||||
]
|
||||
}
|
||||
Binary file not shown.
@@ -2,7 +2,7 @@
|
||||
<model>
|
||||
<name>catch_net</name>
|
||||
<version>1.0</version>
|
||||
<sdf version="1.12">model.sdf</sdf>
|
||||
<sdf version="1.11">model.sdf</sdf>
|
||||
<author><name>sentry_nav_dev</name><email>sentry.sim@example.com</email></author>
|
||||
<description>
|
||||
场地周边拦截网(半透明四面围网 + 四角立柱)。高 3.5 m,位于外框外侧 0.25 m。
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
如果哪天不想让激光看见,删掉 collision 段即可(只留 visual)。
|
||||
============================================================================
|
||||
-->
|
||||
<sdf version="1.12">
|
||||
<sdf version="1.11">
|
||||
<model name="catch_net">
|
||||
<static>true</static>
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
<sdf version='1.11'>
|
||||
<model name='sentry'>
|
||||
<link name='base_link'>
|
||||
<sdf version="1.11">
|
||||
<model name="sentry">
|
||||
<link name="base_link">
|
||||
<inertial>
|
||||
<pose>-0.0011065088757396451 -0.001789349112426035 0.18260591715976329 0 0 0</pose>
|
||||
<mass>25.350000000000001</mass>
|
||||
<pose>0 0 0.17994011976047911 0 0 0</pose>
|
||||
<mass>25.050000000000001</mass>
|
||||
<inertia>
|
||||
<ixx>1.108330048903353</ixx>
|
||||
<ixy>-0.00419096875739645</ixy>
|
||||
<ixz>0.0062437640236686397</ixz>
|
||||
<iyy>1.234650669205128</iyy>
|
||||
<iyz>0.010096867597633129</iyz>
|
||||
<izz>1.2710893212169621</izz>
|
||||
<ixx>1.0863903268463071</ixx>
|
||||
<ixy>0</ixy>
|
||||
<ixz>0</ixz>
|
||||
<iyy>1.2168965768463069</iyy>
|
||||
<iyz>0</iyz>
|
||||
<izz>1.2615204166666669</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name='base_link_fixed_joint_lump__chassis_collision_collision'>
|
||||
<collision name="base_link_fixed_joint_lump__chassis_collision_collision">
|
||||
<pose>0 0 0.14499999999999999 0 0 0</pose>
|
||||
<geometry>
|
||||
<box>
|
||||
@@ -21,20 +21,12 @@
|
||||
</box>
|
||||
</geometry>
|
||||
</collision>
|
||||
<collision name='base_link_fixed_joint_lump__gimbal_collision_collision_1'>
|
||||
<pose>0.12 0 0.375 0 0 0</pose>
|
||||
<geometry>
|
||||
<box>
|
||||
<size>0.40000000000000002 0.29999999999999999 0.25</size>
|
||||
</box>
|
||||
</geometry>
|
||||
</collision>
|
||||
<visual name='base_link_visual'>
|
||||
<visual name="base_link_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>/home/jelly_candy/VSAG_SENTRY_SIM_27RMUL/src/sentry_sim/meshes/base.stl</uri>
|
||||
<uri>../../meshes/base.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -42,11 +34,75 @@
|
||||
<ambient>0.187500015 0.187500015 0.212500006 1</ambient>
|
||||
</material>
|
||||
</visual>
|
||||
<visual name='base_link_fixed_joint_lump__lidar_link_visual_1'>
|
||||
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose>
|
||||
<sensor name="imu" type="imu">
|
||||
<topic>imu</topic>
|
||||
<update_rate>100</update_rate>
|
||||
<always_on>true</always_on>
|
||||
<pose>0 0 0.14999999999999999 0 0 0</pose>
|
||||
<gz_frame_id>imu_link</gz_frame_id>
|
||||
<imu />
|
||||
</sensor>
|
||||
</link>
|
||||
<joint name="gimbal_yaw_joint" type="revolute">
|
||||
<pose relative_to="base_link">0 0 0.1187 0 0 0</pose>
|
||||
<parent>base_link</parent>
|
||||
<child>gimbal_yaw_link</child>
|
||||
<axis>
|
||||
<xyz>0 0 1</xyz>
|
||||
<limit>
|
||||
<effort>20</effort>
|
||||
<velocity>30</velocity>
|
||||
<lower>-inf</lower>
|
||||
<upper>inf</upper>
|
||||
</limit>
|
||||
<dynamics>
|
||||
<damping>0.10000000000000001</damping>
|
||||
<friction>0.050000000000000003</friction>
|
||||
<spring_reference>0</spring_reference>
|
||||
<spring_stiffness>0</spring_stiffness>
|
||||
</dynamics>
|
||||
</axis>
|
||||
</joint>
|
||||
<link name="gimbal_yaw_link">
|
||||
<pose relative_to="gimbal_yaw_joint">0 0 0 0 0 0</pose>
|
||||
<inertial>
|
||||
<pose>0.02009823399558499 -0.01592406181015452 0.2020849889624724 0 0 0</pose>
|
||||
<mass>2.2650000000000001</mass>
|
||||
<inertia>
|
||||
<ixx>0.045522251178256048</ixx>
|
||||
<ixy>-0.0046118611037527599</ixy>
|
||||
<ixz>0.0028778976600441512</ixz>
|
||||
<iyy>0.065884199699227347</iyy>
|
||||
<iyz>0.003427080618101546</iyz>
|
||||
<izz>0.05837989776490065</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name="gimbal_yaw_link_fixed_joint_lump__gimbal_collision_collision">
|
||||
<pose>0.035150000000000001 0.0020000000000000022 0.19089999999999999 0 0 0</pose>
|
||||
<geometry>
|
||||
<box>
|
||||
<size>0.084000000000000005 0.068000000000000005 0.082000000000000003</size>
|
||||
<size>0.46089999999999998 0.2838 0.38179999999999992</size>
|
||||
</box>
|
||||
</geometry>
|
||||
</collision>
|
||||
<visual name="gimbal_yaw_link_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>../../meshes/gimbal.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
<diffuse>0.187500015 0.187500015 0.212500006 1</diffuse>
|
||||
<ambient>0.187500015 0.187500015 0.212500006 1</ambient>
|
||||
</material>
|
||||
</visual>
|
||||
<visual name="gimbal_yaw_link_fixed_joint_lump__lidar_link_visual_1">
|
||||
<pose>-0.0935 -0.1512 0.28649999999999998 0 0 0</pose>
|
||||
<geometry>
|
||||
<box>
|
||||
<size>0.065000000000000002 0.065000000000000002 0.059999999999999998</size>
|
||||
</box>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -54,20 +110,12 @@
|
||||
<ambient>0.125 0.3125 0.75000006 1</ambient>
|
||||
</material>
|
||||
</visual>
|
||||
<sensor name='imu' type='imu'>
|
||||
<topic>imu</topic>
|
||||
<update_rate>100</update_rate>
|
||||
<always_on>true</always_on>
|
||||
<pose>0 0 0.14999999999999999 0 0 0</pose>
|
||||
<gz_frame_id>imu_link</gz_frame_id>
|
||||
<imu/>
|
||||
</sensor>
|
||||
<sensor name='lidar' type='lidar'>
|
||||
<sensor name="lidar" type="gpu_lidar">
|
||||
<topic>scan</topic>
|
||||
<update_rate>10</update_rate>
|
||||
<always_on>true</always_on>
|
||||
<visualize>true</visualize>
|
||||
<ray>
|
||||
<lidar>
|
||||
<scan>
|
||||
<horizontal>
|
||||
<samples>360</samples>
|
||||
@@ -84,7 +132,7 @@
|
||||
</scan>
|
||||
<range>
|
||||
<min>0.10000000000000001</min>
|
||||
<max>12</max>
|
||||
<max>40</max>
|
||||
<resolution>0.01</resolution>
|
||||
</range>
|
||||
<noise>
|
||||
@@ -92,13 +140,13 @@
|
||||
<mean>0</mean>
|
||||
<stddev>0.01</stddev>
|
||||
</noise>
|
||||
</ray>
|
||||
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose>
|
||||
</lidar>
|
||||
<pose>-0.0935 -0.1512 0.28649999999999998 0 0 0</pose>
|
||||
<gz_frame_id>lidar_link</gz_frame_id>
|
||||
</sensor>
|
||||
</link>
|
||||
<joint name='wheel_bl_joint' type='revolute'>
|
||||
<pose relative_to='base_link'>-0.16582 0.21351999999999999 0.076200000000000004 0 0 0</pose>
|
||||
<joint name="wheel_bl_joint" type="revolute">
|
||||
<pose relative_to="base_link">-0.16582 0.21351999999999999 0.076200000000000004 0 0 0</pose>
|
||||
<parent>base_link</parent>
|
||||
<child>wheel_bl</child>
|
||||
<axis>
|
||||
@@ -115,8 +163,8 @@
|
||||
</dynamics>
|
||||
</axis>
|
||||
</joint>
|
||||
<link name='wheel_bl'>
|
||||
<pose relative_to='wheel_bl_joint'>0 0 0 0 0 0</pose>
|
||||
<link name="wheel_bl">
|
||||
<pose relative_to="wheel_bl_joint">0 0 0 0 0 0</pose>
|
||||
<inertial>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<mass>1.5</mass>
|
||||
@@ -129,7 +177,7 @@
|
||||
<izz>0.0028453662500000001</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name='wheel_bl_collision'>
|
||||
<collision name="wheel_bl_collision">
|
||||
<pose>0 0 0 1.5708 0 0</pose>
|
||||
<geometry>
|
||||
<cylinder>
|
||||
@@ -139,7 +187,7 @@
|
||||
</geometry>
|
||||
<surface>
|
||||
<contact>
|
||||
<ode/>
|
||||
<ode />
|
||||
</contact>
|
||||
<friction>
|
||||
<ode>
|
||||
@@ -149,12 +197,12 @@
|
||||
</friction>
|
||||
</surface>
|
||||
</collision>
|
||||
<visual name='wheel_bl_visual'>
|
||||
<visual name="wheel_bl_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>/home/jelly_candy/VSAG_SENTRY_SIM_27RMUL/src/sentry_sim/meshes/wheel.stl</uri>
|
||||
<uri>../../meshes/wheel.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -163,8 +211,8 @@
|
||||
</material>
|
||||
</visual>
|
||||
</link>
|
||||
<joint name='wheel_br_joint' type='revolute'>
|
||||
<pose relative_to='base_link'>-0.16663 -0.21288000000000001 0.076200000000000004 0 0 0</pose>
|
||||
<joint name="wheel_br_joint" type="revolute">
|
||||
<pose relative_to="base_link">-0.16663 -0.21288000000000001 0.076200000000000004 0 0 0</pose>
|
||||
<parent>base_link</parent>
|
||||
<child>wheel_br</child>
|
||||
<axis>
|
||||
@@ -181,8 +229,8 @@
|
||||
</dynamics>
|
||||
</axis>
|
||||
</joint>
|
||||
<link name='wheel_br'>
|
||||
<pose relative_to='wheel_br_joint'>0 0 0 0 0 0</pose>
|
||||
<link name="wheel_br">
|
||||
<pose relative_to="wheel_br_joint">0 0 0 0 0 0</pose>
|
||||
<inertial>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<mass>1.5</mass>
|
||||
@@ -195,7 +243,7 @@
|
||||
<izz>0.0028453662500000001</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name='wheel_br_collision'>
|
||||
<collision name="wheel_br_collision">
|
||||
<pose>0 0 0 1.5708 0 0</pose>
|
||||
<geometry>
|
||||
<cylinder>
|
||||
@@ -205,7 +253,7 @@
|
||||
</geometry>
|
||||
<surface>
|
||||
<contact>
|
||||
<ode/>
|
||||
<ode />
|
||||
</contact>
|
||||
<friction>
|
||||
<ode>
|
||||
@@ -215,12 +263,12 @@
|
||||
</friction>
|
||||
</surface>
|
||||
</collision>
|
||||
<visual name='wheel_br_visual'>
|
||||
<visual name="wheel_br_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>/home/jelly_candy/VSAG_SENTRY_SIM_27RMUL/src/sentry_sim/meshes/wheel.stl</uri>
|
||||
<uri>../../meshes/wheel.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -229,8 +277,8 @@
|
||||
</material>
|
||||
</visual>
|
||||
</link>
|
||||
<joint name='wheel_fl_joint' type='revolute'>
|
||||
<pose relative_to='base_link'>0.16633999999999999 0.21288000000000001 0.076200000000000004 0 0 0</pose>
|
||||
<joint name="wheel_fl_joint" type="revolute">
|
||||
<pose relative_to="base_link">0.16633999999999999 0.21288000000000001 0.076200000000000004 0 0 0</pose>
|
||||
<parent>base_link</parent>
|
||||
<child>wheel_fl</child>
|
||||
<axis>
|
||||
@@ -247,8 +295,8 @@
|
||||
</dynamics>
|
||||
</axis>
|
||||
</joint>
|
||||
<link name='wheel_fl'>
|
||||
<pose relative_to='wheel_fl_joint'>0 0 0 0 0 0</pose>
|
||||
<link name="wheel_fl">
|
||||
<pose relative_to="wheel_fl_joint">0 0 0 0 0 0</pose>
|
||||
<inertial>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<mass>1.5</mass>
|
||||
@@ -261,7 +309,7 @@
|
||||
<izz>0.0028453662500000001</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name='wheel_fl_collision'>
|
||||
<collision name="wheel_fl_collision">
|
||||
<pose>0 0 0 1.5708 0 0</pose>
|
||||
<geometry>
|
||||
<cylinder>
|
||||
@@ -271,7 +319,7 @@
|
||||
</geometry>
|
||||
<surface>
|
||||
<contact>
|
||||
<ode/>
|
||||
<ode />
|
||||
</contact>
|
||||
<friction>
|
||||
<ode>
|
||||
@@ -281,12 +329,12 @@
|
||||
</friction>
|
||||
</surface>
|
||||
</collision>
|
||||
<visual name='wheel_fl_visual'>
|
||||
<visual name="wheel_fl_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>/home/jelly_candy/VSAG_SENTRY_SIM_27RMUL/src/sentry_sim/meshes/wheel.stl</uri>
|
||||
<uri>../../meshes/wheel.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -295,8 +343,8 @@
|
||||
</material>
|
||||
</visual>
|
||||
</link>
|
||||
<joint name='wheel_fr_joint' type='revolute'>
|
||||
<pose relative_to='base_link'>0.16553000000000001 -0.21351999999999999 0.076200000000000004 0 0 0</pose>
|
||||
<joint name="wheel_fr_joint" type="revolute">
|
||||
<pose relative_to="base_link">0.16553000000000001 -0.21351999999999999 0.076200000000000004 0 0 0</pose>
|
||||
<parent>base_link</parent>
|
||||
<child>wheel_fr</child>
|
||||
<axis>
|
||||
@@ -313,8 +361,8 @@
|
||||
</dynamics>
|
||||
</axis>
|
||||
</joint>
|
||||
<link name='wheel_fr'>
|
||||
<pose relative_to='wheel_fr_joint'>0 0 0 0 0 0</pose>
|
||||
<link name="wheel_fr">
|
||||
<pose relative_to="wheel_fr_joint">0 0 0 0 0 0</pose>
|
||||
<inertial>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<mass>1.5</mass>
|
||||
@@ -327,7 +375,7 @@
|
||||
<izz>0.0028453662500000001</izz>
|
||||
</inertia>
|
||||
</inertial>
|
||||
<collision name='wheel_fr_collision'>
|
||||
<collision name="wheel_fr_collision">
|
||||
<pose>0 0 0 1.5708 0 0</pose>
|
||||
<geometry>
|
||||
<cylinder>
|
||||
@@ -337,7 +385,7 @@
|
||||
</geometry>
|
||||
<surface>
|
||||
<contact>
|
||||
<ode/>
|
||||
<ode />
|
||||
</contact>
|
||||
<friction>
|
||||
<ode>
|
||||
@@ -347,12 +395,12 @@
|
||||
</friction>
|
||||
</surface>
|
||||
</collision>
|
||||
<visual name='wheel_fr_visual'>
|
||||
<visual name="wheel_fr_visual">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<geometry>
|
||||
<mesh>
|
||||
<scale>1 1 1</scale>
|
||||
<uri>/home/jelly_candy/VSAG_SENTRY_SIM_27RMUL/src/sentry_sim/meshes/wheel.stl</uri>
|
||||
<uri>../../meshes/wheel.stl</uri>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<material>
|
||||
@@ -361,7 +409,7 @@
|
||||
</material>
|
||||
</visual>
|
||||
</link>
|
||||
<plugin name='gz::sim::systems::PosePublisher' filename='gz-sim-pose-publisher-system'>
|
||||
<plugin name="gz::sim::systems::PosePublisher" filename="gz-sim-pose-publisher-system">
|
||||
<publish_model_pose>true</publish_model_pose>
|
||||
<publish_link_pose>false</publish_link_pose>
|
||||
<publish_nested_model_pose>false</publish_nested_model_pose>
|
||||
@@ -369,7 +417,7 @@
|
||||
<update_frequency>100</update_frequency>
|
||||
<topic>/evaluation/ground_truth</topic>
|
||||
</plugin>
|
||||
<plugin name='gz::sim::systems::MecanumDrive' filename='gz-sim-mecanum-drive-system'>
|
||||
<plugin name="gz::sim::systems::MecanumDrive" filename="gz-sim-mecanum-drive-system">
|
||||
<front_left_joint>wheel_fl_joint</front_left_joint>
|
||||
<front_right_joint>wheel_fr_joint</front_right_joint>
|
||||
<back_left_joint>wheel_bl_joint</back_left_joint>
|
||||
@@ -383,16 +431,31 @@
|
||||
<odom_publish_frequency>50</odom_publish_frequency>
|
||||
<frame_id>odom</frame_id>
|
||||
</plugin>
|
||||
<frame name='imu_joint' attached_to='base_link'>
|
||||
<plugin name="gz::sim::systems::JointPositionController" filename="gz-sim-joint-position-controller-system">
|
||||
<joint_name>gimbal_yaw_joint</joint_name>
|
||||
<sub_topic>gimbal_yaw_cmd</sub_topic>
|
||||
<use_velocity_commands>true</use_velocity_commands>
|
||||
<p_gain>20</p_gain>
|
||||
<i_gain>0</i_gain>
|
||||
<d_gain>2</d_gain>
|
||||
<i_max>1</i_max>
|
||||
<i_min>-1</i_min>
|
||||
<cmd_max>30</cmd_max>
|
||||
<cmd_min>-30</cmd_min>
|
||||
</plugin>
|
||||
<plugin name="gz::sim::systems::JointStatePublisher" filename="gz-sim-joint-state-publisher-system">
|
||||
<topic>joint_states</topic>
|
||||
</plugin>
|
||||
<frame name="imu_joint" attached_to="base_link">
|
||||
<pose>0 0 0.14999999999999999 0 0 0</pose>
|
||||
</frame>
|
||||
<frame name='imu_link' attached_to='imu_joint'>
|
||||
<frame name="imu_link" attached_to="imu_joint">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
</frame>
|
||||
<frame name='lidar_joint' attached_to='base_link'>
|
||||
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose>
|
||||
<frame name="lidar_joint" attached_to="gimbal_yaw_link">
|
||||
<pose>-0.0935 -0.1512 0.28649999999999998 0 0 0</pose>
|
||||
</frame>
|
||||
<frame name='lidar_link' attached_to='lidar_joint'>
|
||||
<frame name="lidar_link" attached_to="lidar_joint">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
</frame>
|
||||
</model>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<model>
|
||||
<name>test_box</name>
|
||||
<version>1.0</version>
|
||||
<sdf version="1.12">model.sdf</sdf>
|
||||
<sdf version="1.11">model.sdf</sdf>
|
||||
<author><name>sentry_nav_dev</name><email>sentry.sim@example.com</email></author>
|
||||
<description>避障测试用的障碍箱(0.5×0.5×0.6 m)</description>
|
||||
</model>
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0"?>
|
||||
<sdf version="1.12">
|
||||
<sdf version="1.11">
|
||||
<model name="test_box">
|
||||
<static>true</static>
|
||||
<link name="box_link">
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| `cmd_vel_relay.py` ~~已迁移~~ | 原 Python 版已删除;现用 `build/bin/cmd_vel_relay`(C++,源码 `src/sentry_nav/src/cmd_vel_relay.cpp`)。把 `/cmd_vel` 改名转发到 `/model/sentry/cmd_vel` |
|
||||
| (内联于 `sentry_up.sh`) | `build/bin/self_filter`:点云自滤 + 从点云投影出 `/scan2d`,Nav2 避障和 AMCL 都依赖它(xmake 产物,不是 `ros2 run`) |
|
||||
| (内联于 `sentry_up.sh`) | `map`→`field` **恒等变换**:世界和地图都已整体平移过,`map` 本身就以场地中心为原点,`field` 只是给决策代码用的别名 |
|
||||
| `spawn_robot.sh` | 用 URDF 动态生成实体(当前方案用世界 include,本脚本备用) |
|
||||
| `spawn_robot.sh` | 用生成的 SDF 动态加载实体(当前方案用世界 include,本脚本备用) |
|
||||
|
||||
## 为什么这么绕
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `HEADLESS` | `0` | `1` = 无界面(`gz sim -s`),服务器/只想看数据时用 |
|
||||
| `HEADLESS` | `0` | `1` = 无界面 EGL 渲染(`gz sim -s --headless-rendering`),服务器/只想看数据时用 |
|
||||
| `NAV2` | `1` | `0` = 不起 Nav2 |
|
||||
| `RVIZ` | `1` | `0` = 不起 RViz |
|
||||
| `ROS_DOMAIN_ID` | `0` | 两个终端必须一致才能互相看到话题 |
|
||||
|
||||
@@ -21,4 +21,5 @@ exec ros2 run ros_gz_bridge parameter_bridge \
|
||||
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
|
||||
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
|
||||
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \
|
||||
'/joint_states@sensor_msgs/msg/JointState[gz.msgs.Model' \
|
||||
--ros-args -p use_sim_time:=true
|
||||
@@ -49,6 +49,22 @@ env_map_yaml() {
|
||||
_env_query --map --field-root "${1:?需要场地根路径}"
|
||||
}
|
||||
|
||||
env_gpu_egl() {
|
||||
# 让 OGRE2 / gpu_lidar 走真显卡而不是 Mesa 软件光栅。
|
||||
# 判定规则只有一份(tools/project_env.py 的 gpu_env),这里只负责 eval 出来。
|
||||
# 混合显卡笔记本上不设这几行,无界面 Gazebo 会退到 llvmpipe。
|
||||
local lines
|
||||
lines=$(_env_query --gpu-shell) || return
|
||||
[ -n "$lines" ] || return 0
|
||||
eval "$lines"
|
||||
echo "[env] GPU EGL → NVIDIA(OGRE2 走真显卡;SENTRY_GPU_EGL=off 可关闭)" >&2
|
||||
}
|
||||
|
||||
env_gpu_egl_report() {
|
||||
# 只查询、不 export:给试运行和体检用。
|
||||
_env_query --gpu
|
||||
}
|
||||
|
||||
env_report() {
|
||||
local ws="${1:?需要仓库根路径}"
|
||||
printf ' SENTRY_SIM_SHARE = %s\n' "${SENTRY_SIM_SHARE:-<未设>}"
|
||||
@@ -64,4 +80,7 @@ env_report() {
|
||||
printf ' GZ_BIN = %s\n' "$gz"
|
||||
printf ' GZ 版本参数 = %s\n' "${versions//$'\n'/ }"
|
||||
printf ' FIELD_ROOT = %s\n' "$field"
|
||||
local gpu
|
||||
gpu=$(_env_query --gpu 2>/dev/null) || gpu='<查询失败>'
|
||||
printf ' GPU EGL = %s\n' "$gpu"
|
||||
}
|
||||
@@ -2,10 +2,8 @@
|
||||
# 用「系统安装的 Gazebo」启动仿真,绕开 ROS vendor 版 gz 的库路径污染。
|
||||
#
|
||||
# 为什么需要这个包装脚本:
|
||||
# source 过 ROS 2 之后,LD_LIBRARY_PATH 会指向 <ros 前缀>/opt/gz_*_vendor/lib,
|
||||
# 此时连系统版 gz 也会去加载 vendor 的 gz-sim 库,而 vendor 那份**没有
|
||||
# cpu-lidar 系统插件**,导致雷达传感器创建失败(世界加载了,但 /scan 一条都没有)。
|
||||
# 所以这里清掉 LD_LIBRARY_PATH 再调 gz。
|
||||
# source ROS 2 后,LD_LIBRARY_PATH 可能优先加载 vendor 版 Gazebo
|
||||
# 库。清掉它,让系统 gz 使用与自身匹配的仿真和渲染插件。
|
||||
#
|
||||
# gz 可执行文件的路径**不写死**:由 env_common.sh 探测(优先 /usr/bin/gz,
|
||||
# 其次 /usr/local/bin/gz、$PATH 上的 gz),也可以用 GZ_BIN=<路径> 强制指定。
|
||||
|
||||
@@ -63,6 +63,10 @@ fi
|
||||
HEADLESS="${HEADLESS:-0}"
|
||||
NAV2="${NAV2:-1}"
|
||||
RVIZ="${RVIZ:-1}"
|
||||
GZ_ARGS=("${GZ_VER_ARGS[@]}" -r)
|
||||
if [ "$HEADLESS" = "1" ]; then
|
||||
GZ_ARGS=(-s --headless-rendering "${GZ_ARGS[@]}")
|
||||
fi
|
||||
|
||||
# Use exactly the same defaults as the Python launch entry point.
|
||||
eval "$(python3 "$INTERNAL_TOOLS/dds_environment.py" --shell)"
|
||||
@@ -87,6 +91,7 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
|
||||
echo " NAV_BIN_DIR = $NAV_BIN_DIR"
|
||||
echo " GZ_EXE = $GZ_EXE"
|
||||
echo " GZ 版本参数 = ${GZ_VER_ARGS[*]:-<无>}"
|
||||
echo " GZ 启动参数 = ${GZ_ARGS[*]}"
|
||||
echo " FIELD_ROOT = $FIELD_ROOT"
|
||||
echo " MAP_YAML = $MAP_YAML"
|
||||
echo " LIO_MAP = $LIO_MAP"
|
||||
@@ -96,6 +101,8 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
|
||||
echo " ROS_DISTRO = ${ROS_DISTRO:-<未设>}"
|
||||
echo " ROS 前缀 = ${AMENT_PREFIX_PATH%%:*}"
|
||||
echo " HEADLESS/NAV2/RVIZ = $HEADLESS/$NAV2/$RVIZ"
|
||||
# 无界面模式下 OGRE2 走 EGL;这里只报告判定结果,真正 export 在 Gazebo 之前。
|
||||
echo " GPU EGL = $(env_gpu_egl_report 2>/dev/null || echo '<查询失败>')"
|
||||
echo " 可执行文件检查:"
|
||||
for _n in self_filter odom_tf cmd_vel_relay patrol; do
|
||||
if [ -f "${NAV_BIN_DIR}/${_n}" ] && [ -x "${NAV_BIN_DIR}/${_n}" ]; then
|
||||
@@ -148,6 +155,7 @@ fi
|
||||
WORLD="${PKG_SHARE}/worlds/sentry_arena.sdf"
|
||||
PIDS=()
|
||||
CLEANED=0
|
||||
ROBOT_PARAMS_DIR=""
|
||||
|
||||
# 递归列出某进程的全部后代,**子在前、父在后**(正好是 kill 的顺序)。
|
||||
# 用 pgrep -P 按「真实父 PID」匹配,不是按命令行字符串匹配 —— 绝不会误匹配到自己。
|
||||
@@ -170,6 +178,9 @@ cleanup() {
|
||||
[ "$CLEANED" = "1" ] && return 0
|
||||
CLEANED=1
|
||||
echo "[sentry_up] 收尾..."
|
||||
if [ -n "$ROBOT_PARAMS_DIR" ]; then
|
||||
rm -rf -- "$ROBOT_PARAMS_DIR"
|
||||
fi
|
||||
|
||||
local all=() p d
|
||||
for p in "${PIDS[@]}"; do
|
||||
@@ -214,10 +225,10 @@ fi
|
||||
# ---------- 1. Gazebo(系统版,清掉 ROS vendor 的库路径)----------
|
||||
# --force-version 的大版本号是**探测出来的**(env_gz_version_args):
|
||||
# 换了 Gazebo 大版本不用改脚本;想强制指定就 GZ_FORCE_VERSION=11。
|
||||
GZ_ARGS=("${GZ_VER_ARGS[@]}" -r)
|
||||
if [ "$HEADLESS" = "1" ]; then
|
||||
GZ_ARGS=(-s "${GZ_VER_ARGS[@]}" -r)
|
||||
fi
|
||||
# 无界面模式下 OGRE2 走 EGL:不把 vendor 指向 NVIDIA,gpu_lidar 会退到
|
||||
# Mesa llvmpipe 软件光栅(实测单核 84%,而 CPU 射线只要 30%)。
|
||||
# 判定在 project_env.gpu_env() 里,SENTRY_GPU_EGL=off 可关闭。
|
||||
env_gpu_egl || true
|
||||
echo "[sentry_up] 启动 Gazebo: ${GZ_EXE} sim ${GZ_ARGS[*]} ${WORLD}"
|
||||
env -u LD_LIBRARY_PATH "$GZ_EXE" sim "${GZ_ARGS[@]}" "${WORLD}" &
|
||||
GZ_PID=$!
|
||||
@@ -238,24 +249,20 @@ ros2 run ros_gz_bridge parameter_bridge \
|
||||
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
|
||||
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
|
||||
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \
|
||||
'/joint_states@sensor_msgs/msg/JointState[gz.msgs.Model' \
|
||||
--ros-args -p use_sim_time:=true &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 4. robot_state_publisher(TF 树)----------
|
||||
echo "[sentry_up] 启动 robot_state_publisher"
|
||||
# XML must be passed as a typed string; CLI YAML parsing breaks on XML comments.
|
||||
runtime_dir="${SENTRY_RUNTIME_DIR:-${WS}/generated}"
|
||||
mkdir -p "$runtime_dir"
|
||||
xacro "${PKG_SHARE}/urdf/sentry.urdf.xacro" > "$runtime_dir/robot_description.urdf"
|
||||
python3 - "$runtime_dir/robot_description.urdf" "$runtime_dir/robot_state_publisher.json" <<'PY_PARAMS'
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
text = Path(sys.argv[1]).read_text()
|
||||
Path(sys.argv[2]).write_text(json.dumps({'robot_state_publisher': {'ros__parameters': {'robot_description': text, 'use_sim_time': True}}}))
|
||||
PY_PARAMS
|
||||
# RViz resolves meshes from the runtime description's file URIs.
|
||||
runtime_dir="${SENTRY_RUNTIME_DIR:-${TMPDIR:-/tmp}}"
|
||||
mkdir -p -- "$runtime_dir"
|
||||
ROBOT_PARAMS_DIR="$(mktemp -d "$runtime_dir/sentry-robot.XXXXXXXX")"
|
||||
python3 "$INTERNAL_TOOLS/robot_description.py" runtime-params "$PKG_SHARE" \
|
||||
"$ROBOT_PARAMS_DIR/robot_state_publisher.json"
|
||||
ros2 run robot_state_publisher robot_state_publisher --ros-args \
|
||||
--params-file "$runtime_dir/robot_state_publisher.json" &
|
||||
--params-file "$ROBOT_PARAMS_DIR/robot_state_publisher.json" -p publish_frequency:=100.0 &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5. odom -> base_link ----------
|
||||
@@ -285,7 +292,7 @@ PIDS+=($!)
|
||||
# ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ----------
|
||||
if [ "$LOCALIZATION" = lio ]; then
|
||||
echo "[sentry_up] LIO mode=$LIO_MODE map=$LIO_MAP cloud=$LIO_POINT_CLOUD_TOPIC (AMCL disabled)"
|
||||
"$LIO_EXE" --ros-args -p use_sim_time:=true \
|
||||
"$LIO_EXE" --ros-args --params-file "$PKG_SHARE/config/field_cloud.yaml" -p use_sim_time:=true \
|
||||
-p "point_cloud_topic:=$LIO_POINT_CLOUD_TOPIC" -p imu_topic:=/imu -p reliable_clouds:=true \
|
||||
-p mode:="$LIO_MODE" -p map_path:="$LIO_MAP" -p export_map_path:="$LIO_EXPORT_MAP" \
|
||||
-p publish_map_to_odom:=true -p "diagnostics_path:='${LIO_TRACE_PATH:-}'" \
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# 等 Gazebo 就绪后,用 URDF 在场地里生成哨兵。
|
||||
#
|
||||
# 为什么单独一个脚本:xacro 要先展开成 .urdf 文件,Gazebo 的 create 服务只认文件路径;
|
||||
# 而且必须等 gz server 起来(launch 里用 TimerAction 延迟调用本脚本)。
|
||||
# 在已启动的 Gazebo 世界中加载仓库生成的 SDF 模型。
|
||||
set -e
|
||||
|
||||
# 数据包直接用源码目录(本工程不使用 ament/colcon,没有 ros2 pkg prefix)
|
||||
WS="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")/../../.." && pwd)"
|
||||
pkg_share="${SENTRY_SIM_SHARE:-${WS}/src/sentry_sim}"
|
||||
export SENTRY_SIM_SHARE="$pkg_share"
|
||||
cache_dir="${HOME}/.cache/sentry_sim"
|
||||
mkdir -p "$cache_dir"
|
||||
urdf_file="${cache_dir}/sentry_robot.urdf"
|
||||
model_file="$pkg_share/models/sentry/model.sdf"
|
||||
|
||||
# shellcheck source=./env_common.sh
|
||||
. "${pkg_share}/scripts/env_common.sh"
|
||||
env_source_ros 2>/dev/null || true
|
||||
|
||||
echo "[spawn_robot] 展开 xacro -> ${urdf_file}"
|
||||
xacro "${pkg_share}/urdf/sentry.urdf.xacro" > "$urdf_file"
|
||||
env_source_ros
|
||||
if [ ! -f "$model_file" ]; then
|
||||
echo "[spawn_robot] 找不到模型:$model_file" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ⚠️ 默认出生点必须和这两处保持一致(三处不同步,车一启动就"在别处"):
|
||||
# worlds/sentry_arena.sdf 里 sentry 的 <pose>
|
||||
@@ -29,7 +23,7 @@ SPAWN_Y="${SPAWN_Y:-3.0}"
|
||||
echo "[spawn_robot] 生成实体(world=rmul_arena, x=${SPAWN_X}, y=${SPAWN_Y})"
|
||||
ros2 run ros_gz_sim create \
|
||||
-name sentry \
|
||||
-file "$urdf_file" \
|
||||
-file "$model_file" \
|
||||
-x "${SPAWN_X}" \
|
||||
-y "${SPAWN_Y}" \
|
||||
-z "${SPAWN_Z:-0.02}"
|
||||
+210
-10
@@ -5,12 +5,40 @@
|
||||
## 结构
|
||||
|
||||
```
|
||||
base_link(车体 + 云台 + 悬挂 + MID-360 外形,整体刚体)
|
||||
base_link(底盘 + 悬挂)
|
||||
├── wheel_fl / wheel_fr / wheel_bl / wheel_br revolute 关节,轴 = Y(横向)
|
||||
├── lidar_link fixed,位置 = MID-360 实测位置
|
||||
└── imu_link fixed
|
||||
├── imu_link fixed —— 底盘 IMU,不跟云台转
|
||||
└── gimbal_yaw_link continuous 关节,轴 = Z,360° 无界
|
||||
├── (网格 gimbal.stl;pitch 轴还没拆)
|
||||
└── lidar_link fixed —— 雷达装在弹仓上,随 yaw 一起转
|
||||
```
|
||||
|
||||
`gimbal_yaw_joint` 在 URDF 里写 `type="continuous"`。`gz sdf -p` 会把它转成 SDF 的
|
||||
`revolute` + `<lower>-inf</lower><upper>inf</upper>` —— 那才是无界旋转,**不要**手工
|
||||
给 SDF 补上下限。
|
||||
|
||||
> ⚠️ `imu_link` **必须留在 base_link 上**。它的外参被 `field_localization` 的
|
||||
> 去畸变和 LIO 使用,挪到会转的 link 上会连带改掉 `imu_from_sensor` 外参链和
|
||||
> `map→odom` 的语义 —— 云台一转,姿态就被云台转角污染了。
|
||||
>
|
||||
> `lidar_link` 则相反:**实车雷达装在弹仓上,弹仓随 yaw 转,所以它必须挂在
|
||||
> `gimbal_yaw_link` 下**。这一点 2026-11-25 之前写错过(挂在 base_link 上),
|
||||
> 表现是云台转了、雷达不动。
|
||||
|
||||
## 固定关节会被合并(`fixed_joint_lump`)
|
||||
|
||||
URDF→SDF 转换会把 `type="fixed"` 的关节**合并掉**,子 link 的视觉和传感器直接焊进父 link。
|
||||
所以 SDF 里根本不存在 `lidar_link` 这个 link,别以为改丢了。证据是名字前缀:
|
||||
|
||||
```
|
||||
gimbal_yaw_link_fixed_joint_lump__lidar_link_visual_1 ← 现在(正确)
|
||||
base_link_fixed_joint_lump__lidar_link_visual_1 ← 改之前(雷达不动)
|
||||
```
|
||||
|
||||
**这意味着"雷达跟谁转"完全由 `lidar_joint` 的 `<parent>` 决定**,不需要、也不应该
|
||||
去手改 `model.sdf`。改完 parent 重新 `gen_sdf.sh`,`fixed_joint_lump` 的前缀会跟着变,
|
||||
那个前缀本身就是改动是否生效的验证标志。
|
||||
|
||||
## 参数区(文件顶部)
|
||||
|
||||
| 属性 | 当前值 | 来源 |
|
||||
@@ -19,15 +47,157 @@ base_link(车体 + 云台 + 悬挂 + MID-360 外形,整体刚体)
|
||||
| `wheel_front_left` 等四个 | FL(0.166,0.213) FR(0.166,−0.214) BL(−0.166,0.214) BR(−0.167,−0.213) | 装配体实测 |
|
||||
| `body_l/w/h` | 0.578 / 0.521 / 0.500 | 装配体 bbox |
|
||||
| `body_mass` / `wheel_mass` | 25.0 / 1.5 kg | ⚠️ **估算,待机械提供** |
|
||||
| `lidar_x/y/z` | −0.0935 / −0.1512 / 0.4052 | MID-360 实测位置 |
|
||||
| `lidar_x/y/z` | −0.0935 / −0.1512 / 0.4052 | MID-360 实测位置,**底盘系** |
|
||||
| 雷达垂直视场 | **−7° ~ +52° / 40 线** | ✅ 2026-11-16 改成真机规格(原来是 ±15° / 16 线);`/scan` 因此基本失效,只用 3D 点云 |
|
||||
| 碰撞体 | 底盘盒(z 0~0.25)+ 云台盒(z 0.25~0.5) | 不能用一个大盒包住整车,否则雷达射线全打在盒内壁 |
|
||||
| `yaw_axis_x/y` | **0.0 / 0.0** | yaw 轴在车体中心:5 个同轴件(70齿大带轮 / 云台内圈 / 滑环 / 内70外86 轴承)实测共轴离散 0.03 mm。**不是 GM6020 电机轴(在 x=+0.0899)** |
|
||||
| `yaw_mount_z` | 0.1187 | 云台组最低点 = `split-gimbal` 的 `gimbal_joint_origin_ros_m.z` |
|
||||
| `gimbal_min/max_x` | −0.1953 / +0.2656 | 旋转组包络(60 个零件) |
|
||||
| `gimbal_min/max_y` | −0.1399 / +0.1439 | 同上 |
|
||||
| `gimbal_top_z` | 0.5005 | 同上 |
|
||||
| `gimbal_mass` | 2.0 kg | ⚠️ **估算,待机械提供** |
|
||||
| 碰撞体 | 底盘盒(z 0.02~0.27)+ **云台上的包络盒**(跟关节转) | 不能用一个大盒包住整车,否则雷达射线全打在盒内壁 |
|
||||
|
||||
`lidar_x/y/z` 是**底盘系**坐标。因为雷达现在挂在云台下,`lidar_joint` 的
|
||||
`<origin>` 要换算到云台系:
|
||||
|
||||
```xml
|
||||
<origin xyz="${lidar_x} ${lidar_y} ${lidar_z - yaw_mount_z}" rpy="0 0 0"/>
|
||||
<!-- = -0.0935 -0.1512 0.2865 -->
|
||||
```
|
||||
|
||||
**扫掠半径 0.3021 m** = √(0.2656² + 0.1439²),即 yaw 轴到旋转组最远角的距离。
|
||||
云台能 360° 转,所以 `nav2_params.yaml` 的 `footprint` 和 `self_filter` 的剔除盒
|
||||
都必须覆盖这个圆(现在两边都是 ±0.305)。
|
||||
|
||||
## 约定
|
||||
|
||||
- **车头 = +X**(相机/枪口侧),左 = +Y,上 = +Z,原点在车体中心的地面投影
|
||||
- 云台做成刚体(导航不需要它转)。要做自瞄时再用
|
||||
`tools/build_vehicle.py --split-gimbal` 拆 yaw/pitch
|
||||
- 云台是**可 360° 连续转的独立 link**。网格用 `tools/build_vehicle.py` 的
|
||||
`split-gimbal` 生成,原点在 yaw 轴 + 安装面
|
||||
|
||||
## 云台 yaw 的命令接口
|
||||
|
||||
仿真里由 Gazebo 插件驱动(`gz-sim-joint-position-controller-system`,
|
||||
`use_velocity_commands=true`):
|
||||
|
||||
```bash
|
||||
# 话题:/model/sentry/gimbal_yaw_cmd 类型:gz.msgs.Double(目标角速度 rad/s)
|
||||
gz topic -t /model/sentry/gimbal_yaw_cmd -m gz.msgs.Double -p data:1.0 # 正转 1 rad/s
|
||||
gz topic -t /model/sentry/gimbal_yaw_cmd -m gz.msgs.Double -p data:0.0 # 停
|
||||
```
|
||||
|
||||
发一次就**一直保持**这个角速度,不会自己停;`0` 才停。
|
||||
|
||||
### ⚠️ 手敲 gz 命令必须先 `export GZ_PARTITION=sentry`
|
||||
|
||||
`sentry_up.sh` 第 137 行做了这件事:
|
||||
|
||||
```bash
|
||||
export GZ_PARTITION="${GZ_PARTITION:-sentry}"
|
||||
```
|
||||
|
||||
`GZ_PARTITION` 是 gz transport 的**通信分区**,不同分区 = 两套完全独立的 DDS 域,
|
||||
互相看不见对方任何话题。而你在新终端里敲 `gz topic` 时**没有继承这个变量**,于是:
|
||||
|
||||
| 症状 | 真相 |
|
||||
|---|---|
|
||||
| `gz topic -l \| wc -l` 返回 **0** | 不是仿真没起,是分区看不见 |
|
||||
| `gz topic -p data:1.0` **不报错但没反应** | 发进了自己那个空分区,没人收 |
|
||||
|
||||
`gz topic -p` 往不存在的话题发布会**静默退出码 0**,所以"没报错"完全不能当作"发成功了"。
|
||||
|
||||
```bash
|
||||
export GZ_PARTITION=sentry # 一次,之后所有 gz 命令都正常
|
||||
# 或者每条前面加 GZ_PARTITION=sentry
|
||||
```
|
||||
|
||||
ROS 2 侧不受影响 —— `ros_gz_bridge` 是在脚本里启动的,继承了正确的分区,
|
||||
所以 `/cmd_vel`、`/scan`、`/joint_states` 都照常工作。
|
||||
|
||||
## 雷达挂在云台上 —— 连带影响
|
||||
|
||||
### 必须桥接 `/joint_states`
|
||||
|
||||
雷达跟着云台转之后,`base_link → gimbal_yaw_link` 是**会变的**变换,TF 必须知道云台
|
||||
转到了多少度,否则 `robot_state_publisher` 里云台永远停在 0°,点云姿态和实际对不上,
|
||||
`self_filter` 会把点云投影到错误的姿态上,Nav2 代价地图跟着错。
|
||||
|
||||
xacro 里的插件(注意:**必须写在 `<model>` 里**):
|
||||
|
||||
```xml
|
||||
<plugin filename="gz-sim-joint-state-publisher-system"
|
||||
name="gz::sim::systems::JointStatePublisher">
|
||||
<topic>joint_states</topic>
|
||||
</plugin>
|
||||
```
|
||||
|
||||
两个坑:
|
||||
|
||||
1. **挂到 world 上会直接初始化失败**:
|
||||
`[error] [JointStatePublisher.cc:62] The JointStatePublisher system should be attached to a model entity.`
|
||||
2. **不写 `<topic>` 的话话题名是 `/world/<world>/model/<model>/joint_state`**,
|
||||
换了世界名就失效。显式指定成 `joint_states` 后话题就是干净的 `/joint_states`,
|
||||
桥那边也不用 remap、不用硬编码世界名。
|
||||
|
||||
桥的清单在**两个地方重复**,改一个漏一个就会静默失效:
|
||||
|
||||
- `src/sentry_sim/scripts/sentry_up.sh`
|
||||
- `src/sentry_sim/scripts/bridge_after_gz.sh`
|
||||
|
||||
```bash
|
||||
'/joint_states@sensor_msgs/msg/JointState[gz.msgs.Model' \
|
||||
```
|
||||
|
||||
(`[` 表示 gz→ROS 单向。符号表里确认过 `ros_gz_bridge` 支持
|
||||
`convert_gz_to_ros<sensor_msgs::msg::JointState, gz::msgs::Model>`。)
|
||||
|
||||
**验证**(`./scripts/sentry_up.sh` 起来之后):
|
||||
|
||||
```bash
|
||||
ros2 topic echo /joint_states --once # name: [gimbal_yaw_joint] position 在变
|
||||
ros2 run tf2_ros tf2_echo base_link lidar_link # z ≈ 0.2865,随云台角变化
|
||||
```
|
||||
|
||||
### 周期性遮挡的担心不成立,但有个固定盲区
|
||||
|
||||
`self_filter` 读的是标准 TF(`lookupTransform`),不是写死的固定外参,所以雷达转动
|
||||
它也能正确变换 —— 这块不用改。它的剔除盒工作在 `base_link` 系,±0.305 覆盖
|
||||
"机身 + 云台扫掠盘",雷达挂哪儿都不影响。
|
||||
|
||||
之前这里写过"雷达会被云台周期性遮挡",**那个判断现在不成立**:雷达和云台是刚性
|
||||
相连的,两者相对位置固定,不存在"云台转到雷达和墙之间"这回事。取而代之的是一个
|
||||
**固定的盲区** —— 朝向云台本体那一侧看不到东西,且这个盲区会跟着云台一起转。
|
||||
|
||||
## 残留风险(还没解决)
|
||||
|
||||
### 1. 弹仓本体的网格还在静态组里
|
||||
|
||||
雷达挂在弹仓上,但**弹仓的几何目前躺在静态的 `base.stl` 里**:当前 `gimbal.stl`
|
||||
的 y 范围只到 −0.1399,而雷达在 −0.1512 —— 在旋转组外面。
|
||||
|
||||
表现:蓝色雷达盒子会跟着云台转,**但它底下的弹仓不转**,视觉穿帮。
|
||||
|
||||
要修得把弹仓零件真正划进旋转组:
|
||||
|
||||
```bash
|
||||
# 需要插上 CAD 盘
|
||||
ls /run/media/mzxiang/CPBA_X64FRE/装配车
|
||||
cd ~/Gazebo_projects/sentry_nav_dev && ./tools/build_vehicle.py --split-gimbal
|
||||
```
|
||||
|
||||
`GIMBAL_KEYS` 里已经有 `'弹仓'`,但历史产物 `meshes/gimbal_transform.json` 记录的是
|
||||
**跳过**了 `装配体 - 弹仓前1-3.STL` 和 `新哨兵-云台-弹仓底B-1.STL` —— 说明分类规则
|
||||
在某个阶段是把弹仓排除掉的,需要重新核实。
|
||||
|
||||
⚠️ **一旦弹仓进入旋转组,扫掠包络可能变大**:如果弹仓伸到 y < −0.1512,
|
||||
扫掠半径会超过现在的 0.3021,那么 `footprint 0.61×0.61`、`inflation_radius 0.60`、
|
||||
`self_filter` 剔除盒全都得跟着重算。
|
||||
|
||||
### 2. 真机必须做 deskew(仿真看不出来)
|
||||
|
||||
gz 的 `gpu_lidar` 是**同一时刻采样全部光线**,所以仿真里点云没有扫描内畸变。
|
||||
真机不是:云台 1 rad/s 转、10 Hz 扫描 → 每帧内雷达姿态差 5.7°,不逐点补偿点云会糊。
|
||||
另外雷达离轴 0.178 m,云台转动时它还在**绕轴公转**,位移也要一起补偿。
|
||||
|
||||
## 改完必须做
|
||||
|
||||
@@ -37,6 +207,36 @@ cd ~/Gazebo_projects/sentry_nav_dev
|
||||
scripts/sentry_up.sh # 重启仿真(数据包不用编译)
|
||||
```
|
||||
|
||||
> 要点:本工程不使用 ament/colcon,URDF 里的网格路径写成
|
||||
> `$(env SENTRY_SIM_SHARE)/meshes/*.stl`,`gen_sdf.sh` 会自动设置该变量。
|
||||
> 手动跑 `xacro` 时记得自己 `export SENTRY_SIM_SHARE=<仓库>/src/sentry_sim`。
|
||||
改完 `gen_sdf.sh` 会打印 `Valid.` 并用 `gz sdf -k` 校验。校验不过它不会替换产物。
|
||||
|
||||
网格路径通过 xacro 的 `mesh_prefix` 参数设置。生成器分别按 URDF 和 SDF 所在目录填写相对引用。
|
||||
启动器在发布 ROS 机器人描述时为 RViz 解析网格 URI。
|
||||
|
||||
## ⚠️ 编译:`xmake` 的增量构建在这个仓库里是坏的
|
||||
|
||||
改了 C++(不是 URDF/配置)时:
|
||||
|
||||
```bash
|
||||
xmake build -r -a # 全量强制重建,约 20 秒
|
||||
xmake test # 15 个 target
|
||||
```
|
||||
|
||||
**不要只敲 `xmake`** —— 它会打印 `build ok, spent 0.1s` 然后什么都没编。
|
||||
|
||||
两个原因,都已验证:
|
||||
|
||||
1. **`build/.built_by` 的内容是 `colcon`**(2026-11-12 留下的)。xmake 靠这个文件判断
|
||||
"这个 build 目录是谁建的",看到不是自己就直接空跑退出,拒绝增量构建。
|
||||
2. **头文件依赖完全不跟踪**:`build/.objs` 下面 **0 个 `.d` 文件**,`build/.deps/*.d`
|
||||
里只有 obj 和链接参数、没有任何 `.hpp`。所以**只改头文件永远不会触发重编**。
|
||||
这个项目里 `self_filter` 的盒子常量就住在 `self_filter_core.hpp` 里,踩中过一次。
|
||||
|
||||
想彻底修好(`build/` 和 `.xmake` 都是可完全重建的产物,20 秒就能恢复):
|
||||
|
||||
```bash
|
||||
rm -rf build .xmake && xmake build -r -a
|
||||
```
|
||||
|
||||
另外 `.xmake/linux/x86_64/xmake.conf` 里没有 `projectdir`,但 `xmake show` 会报出
|
||||
一个 2026-11-22 遗留的 `.../outputs/lio_full_field/build-check` 工程路径,
|
||||
`build/.deps/*.d` 里的相对路径也是相对它写的 —— 这属于同一批陈旧状态,一并清掉即可。
|
||||
@@ -15,14 +15,12 @@
|
||||
- 轮子质量 1.5 kg
|
||||
- 雷达安装位置(本装配体里没有雷达模型,位置未知)
|
||||
|
||||
⚠️ 网格路径用 `$(env SENTRY_SIM_SHARE)`,**不是** `$(find sentry_sim)`:
|
||||
本工程不使用 ament/colcon,没有资源索引,xacro 的 `$(find pkg)` 查不到包。
|
||||
展开前必须设好环境变量,例如
|
||||
export SENTRY_SIM_SHARE=~/Gazebo_projects/sentry_nav_dev/src/sentry_sim
|
||||
(`tools/gen_sdf.sh` 和 `scripts/sentry_up.sh` 都会自动设置。)
|
||||
mesh_prefix 默认以本 xacro 文件所在目录为基准,各调用方可指定自己的资源基准。
|
||||
-->
|
||||
<robot name="sentry" xmlns:xacro="http://www.ros.org/wiki/xacro">
|
||||
|
||||
<xacro:arg name="mesh_prefix" default="../meshes"/>
|
||||
|
||||
<!-- ================= 参数区 ================= -->
|
||||
<xacro:property name="wheel_radius" value="0.0762"/>
|
||||
<xacro:property name="wheel_width" value="0.0731"/>
|
||||
@@ -42,27 +40,50 @@
|
||||
<xacro:property name="body_mass" value="25.0"/>
|
||||
<xacro:property name="wheel_mass" value="1.5"/>
|
||||
|
||||
<!-- 雷达 = MID-360 的实际安装位置(装配体实测:ROS xyz=(-0.0935, -0.1512, 0.4052))。
|
||||
⚠️ 仿真里目前用 2D 单层扫描代替 MID-360(真机是 3D 激光,含竖直方向 7 线);
|
||||
该高度 0.405 m 略低于场地围挡 0.42 m,射线擦着围挡上沿走,因此避障数据质量一般,
|
||||
导航阶段用静态地图兜底。等需要 3D 点云时再换 gpu_lidar + vertical 通道。 -->
|
||||
<!-- MID-360 安装位置,装配体实测 ROS xyz=(-0.0935, -0.1512, 0.4052)。 -->
|
||||
<xacro:property name="lidar_x" value="-0.0935"/>
|
||||
<xacro:property name="lidar_y" value="-0.1512"/>
|
||||
<xacro:property name="lidar_z" value="0.4052"/>
|
||||
<xacro:property name="lidar_width" value="0.065"/>
|
||||
<xacro:property name="lidar_height" value="0.060"/>
|
||||
<xacro:property name="lidar_mass" value="0.265"/>
|
||||
|
||||
<!-- ============ 云台 yaw(连续旋转关节)============
|
||||
yaw 轴在车体中心 (0, 0):由 tools/build_vehicle.py 的 split-gimbal 从 5 个
|
||||
本该同轴的零件(70齿大带轮 / 云台内圈 / 15.5滑环 / 内70外86 轴承 ×2)求得,
|
||||
实测共轴离散 0.03 mm。
|
||||
⚠️ 不要用 GM6020 电机中心 —— 电机经 35齿小带轮 + 皮带 + 70齿大带轮 减速,
|
||||
电机轴在 x=+0.0899,与 yaw 轴差一个皮带中心距(89.9 mm)。 -->
|
||||
<xacro:property name="yaw_axis_x" value="0.0"/>
|
||||
<xacro:property name="yaw_axis_y" value="0.0"/>
|
||||
<!-- 云台安装面高度:等于云台组最低点(split-gimbal 输出的 gimbal_joint_origin_ros_m.z) -->
|
||||
<xacro:property name="yaw_mount_z" value="0.1187"/>
|
||||
|
||||
<!-- 旋转组包络(相对 yaw 轴,装配体实测)。
|
||||
绕 z 轴自由旋转后的扫掠半径 = 0.3021 m(= 最远角 √(0.2656² + 0.1439²)),
|
||||
nav2 footprint 与 self_filter 剔除盒都按这个圆来。 -->
|
||||
<xacro:property name="gimbal_min_x" value="-0.1953"/>
|
||||
<xacro:property name="gimbal_max_x" value="0.2656"/>
|
||||
<xacro:property name="gimbal_min_y" value="-0.1399"/>
|
||||
<xacro:property name="gimbal_max_y" value="0.1439"/>
|
||||
<xacro:property name="gimbal_top_z" value="0.5005"/>
|
||||
<!-- TODO(机械):质量是估值,拿到 SolidWorks「质量属性」后替换 -->
|
||||
<xacro:property name="gimbal_mass" value="2.0"/>
|
||||
|
||||
<material name="dark_gray"><color rgba="0.15 0.15 0.17 1"/></material>
|
||||
<material name="rm_blue"><color rgba="0.10 0.25 0.60 1"/></material>
|
||||
|
||||
<!-- ================= 车体(含云台,刚体) ================= -->
|
||||
<!-- ================= 车体(底盘;云台已拆成 gimbal_yaw_link) ================= -->
|
||||
<link name="base_link">
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="$(env SENTRY_SIM_SHARE)/meshes/base.stl"/>
|
||||
<mesh filename="$(arg mesh_prefix)/base.stl"/>
|
||||
</geometry>
|
||||
<material name="dark_gray"/>
|
||||
</visual>
|
||||
<!-- 碰撞体用两个简化盒:底盘(下半)+ 云台(上半靠前)。
|
||||
<!-- 碰撞体只有底盘一个简化盒。云台的碰撞盒在 gimbal_yaw_link 上,
|
||||
这样它能跟着 yaw 关节一起转。
|
||||
不能用一个大盒子包住整车——MID-360 在 z=0.405,会被包在盒子内部,
|
||||
雷达射线全打在盒子内壁上(实测距离只有 0.2~0.4 m)。 -->
|
||||
<collision name="chassis_collision">
|
||||
@@ -74,12 +95,6 @@
|
||||
<box size="${body_l} ${body_w} 0.25"/>
|
||||
</geometry>
|
||||
</collision>
|
||||
<collision name="gimbal_collision">
|
||||
<origin xyz="0.12 0 0.375" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<box size="0.40 0.30 0.25"/>
|
||||
</geometry>
|
||||
</collision>
|
||||
<inertial>
|
||||
<origin xyz="0 0 0.18" rpy="0 0 0"/>
|
||||
<mass value="${body_mass}"/>
|
||||
@@ -92,13 +107,58 @@
|
||||
</inertial>
|
||||
</link>
|
||||
|
||||
<!-- ================= 云台 yaw(可 360° 连续旋转) =================
|
||||
visual 用 gimbal.stl —— 由 tools/build_vehicle.py 的 split-gimbal 生成,
|
||||
原点就在 yaw 轴 + 安装面上,所以这里 origin 是 (0,0,0)。 -->
|
||||
<link name="gimbal_yaw_link">
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="$(arg mesh_prefix)/gimbal.stl"/>
|
||||
</geometry>
|
||||
<material name="dark_gray"/>
|
||||
</visual>
|
||||
<!-- 碰撞体=旋转组包络盒(相对 yaw 轴)。旋转时它跟着 link 转。 -->
|
||||
<collision name="gimbal_collision">
|
||||
<origin
|
||||
xyz="${(gimbal_min_x + gimbal_max_x) / 2} ${(gimbal_min_y + gimbal_max_y) / 2} ${(gimbal_top_z - yaw_mount_z) / 2}"
|
||||
rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<box size="${gimbal_max_x - gimbal_min_x} ${gimbal_max_y - gimbal_min_y} ${gimbal_top_z - yaw_mount_z}"/>
|
||||
</geometry>
|
||||
</collision>
|
||||
<inertial>
|
||||
<origin
|
||||
xyz="${(gimbal_min_x + gimbal_max_x) / 2} ${(gimbal_min_y + gimbal_max_y) / 2} ${(gimbal_top_z - yaw_mount_z) / 2}"
|
||||
rpy="0 0 0"/>
|
||||
<mass value="${gimbal_mass}"/>
|
||||
<inertia
|
||||
ixx="${gimbal_mass/12*((gimbal_max_y - gimbal_min_y)*(gimbal_max_y - gimbal_min_y) + (gimbal_top_z - yaw_mount_z)*(gimbal_top_z - yaw_mount_z))}"
|
||||
ixy="0" ixz="0"
|
||||
iyy="${gimbal_mass/12*((gimbal_max_x - gimbal_min_x)*(gimbal_max_x - gimbal_min_x) + (gimbal_top_z - yaw_mount_z)*(gimbal_top_z - yaw_mount_z))}"
|
||||
iyz="0"
|
||||
izz="${gimbal_mass/12*((gimbal_max_x - gimbal_min_x)*(gimbal_max_x - gimbal_min_x) + (gimbal_max_y - gimbal_min_y)*(gimbal_max_y - gimbal_min_y))}"/>
|
||||
</inertial>
|
||||
</link>
|
||||
|
||||
<!-- type="continuous" 才能 360° 连续转;revolute 必须有上下限。
|
||||
continuous 关节在 URDF 里仍要写 effort/velocity 上限(没有 lower/upper)。 -->
|
||||
<joint name="gimbal_yaw_joint" type="continuous">
|
||||
<parent link="base_link"/>
|
||||
<child link="gimbal_yaw_link"/>
|
||||
<origin xyz="${yaw_axis_x} ${yaw_axis_y} ${yaw_mount_z}" rpy="0 0 0"/>
|
||||
<axis xyz="0 0 1"/>
|
||||
<limit effort="20.0" velocity="30.0"/>
|
||||
<dynamics damping="0.1" friction="0.05"/>
|
||||
</joint>
|
||||
|
||||
<!-- ================= 四个麦轮 ================= -->
|
||||
<xacro:macro name="wheel_link" params="name xyz">
|
||||
<link name="${name}">
|
||||
<visual>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<geometry>
|
||||
<mesh filename="$(env SENTRY_SIM_SHARE)/meshes/wheel.stl"/>
|
||||
<mesh filename="$(arg mesh_prefix)/wheel.stl"/>
|
||||
</geometry>
|
||||
<material name="dark_gray"/>
|
||||
</visual>
|
||||
@@ -138,20 +198,27 @@
|
||||
<link name="lidar_link">
|
||||
<visual>
|
||||
<geometry>
|
||||
<box size="0.084 0.068 0.082"/>
|
||||
<box size="${lidar_width} ${lidar_width} ${lidar_height}"/>
|
||||
</geometry>
|
||||
<material name="rm_blue"/>
|
||||
</visual>
|
||||
<inertial>
|
||||
<origin xyz="0 0 0" rpy="0 0 0"/>
|
||||
<mass value="0.3"/>
|
||||
<inertia ixx="0.00012" ixy="0" ixz="0" iyy="0.00012" iyz="0" izz="0.0002"/>
|
||||
<mass value="${lidar_mass}"/>
|
||||
<inertia ixx="${lidar_mass / 12 * (lidar_width**2 + lidar_height**2)}"
|
||||
ixy="0" ixz="0"
|
||||
iyy="${lidar_mass / 12 * (lidar_width**2 + lidar_height**2)}"
|
||||
iyz="0" izz="${lidar_mass / 6 * lidar_width**2}"/>
|
||||
</inertial>
|
||||
</link>
|
||||
<!-- 雷达装在弹仓上,弹仓随 yaw 轴一起转,所以父级是 gimbal_yaw_link 而不是 base_link。
|
||||
原点必须换算到云台系:底盘系里的 lidar_z 减掉云台安装面高度 yaw_mount_z。
|
||||
注意:type="fixed" 的关节在 URDF→SDF 转换时会被合并(fixed_joint_lump),
|
||||
合并到哪个 link 取决于这里的 parent,所以 parent 一改,雷达就跟着云台转。 -->
|
||||
<joint name="lidar_joint" type="fixed">
|
||||
<parent link="base_link"/>
|
||||
<parent link="gimbal_yaw_link"/>
|
||||
<child link="lidar_link"/>
|
||||
<origin xyz="${lidar_x} ${lidar_y} ${lidar_z}" rpy="0 0 0"/>
|
||||
<origin xyz="${lidar_x} ${lidar_y} ${lidar_z - yaw_mount_z}" rpy="0 0 0"/>
|
||||
</joint>
|
||||
|
||||
<link name="imu_link">
|
||||
@@ -198,18 +265,49 @@
|
||||
<odom_publish_frequency>50</odom_publish_frequency>
|
||||
<frame_id>odom</frame_id>
|
||||
</plugin>
|
||||
<!-- 云台 yaw:连续旋转由外部命令驱动。
|
||||
use_velocity_commands=true → 话题上的 Double 是**目标角速度**(rad/s),
|
||||
关节可以一直往同一个方向转,不受 ±π 限制。
|
||||
话题:/model/sentry/gimbal_yaw_cmd
|
||||
发 1.0 就是 1 rad/s 正转,发 -1.0 反转,发 0 停。
|
||||
⚠️ 这个是纯仿真驱动;真机上由云台电机的 CAN 控制接管。 -->
|
||||
<plugin filename="gz-sim-joint-position-controller-system"
|
||||
name="gz::sim::systems::JointPositionController">
|
||||
<joint_name>gimbal_yaw_joint</joint_name>
|
||||
<sub_topic>gimbal_yaw_cmd</sub_topic>
|
||||
<use_velocity_commands>true</use_velocity_commands>
|
||||
<p_gain>20</p_gain>
|
||||
<i_gain>0</i_gain>
|
||||
<d_gain>2</d_gain>
|
||||
<i_max>1</i_max>
|
||||
<i_min>-1</i_min>
|
||||
<cmd_max>30</cmd_max>
|
||||
<cmd_min>-30</cmd_min>
|
||||
</plugin>
|
||||
|
||||
<!-- 关节状态发布:雷达挂在云台上,云台转角必须能被 ROS 侧看到,
|
||||
否则 TF 里 base_link→gimbal_yaw_link 永远是 0,点云姿态和实际对不上。
|
||||
<topic> 显式指定成 /joint_states,省掉 "world 名 + model 名" 的长话题
|
||||
(默认是 /world/<world>/model/<model>/joint_state,换世界就失效)。
|
||||
不写 <joint_name> 就是发布全部关节,轮子也能在 RViz 里正常转。
|
||||
必须挂在 model 上——挂到 world 会报
|
||||
"The JointStatePublisher system should be attached to a model entity"。 -->
|
||||
<plugin filename="gz-sim-joint-state-publisher-system"
|
||||
name="gz::sim::systems::JointStatePublisher">
|
||||
<topic>joint_states</topic>
|
||||
</plugin>
|
||||
</gazebo>
|
||||
|
||||
<!-- 2D 激光雷达(PLACEHOLDER:type="lidar" 走 CPU 射线,不依赖 GPU) -->
|
||||
<!-- 3D 雷达由世界的 OGRE2 Sensors 系统渲染。 -->
|
||||
<gazebo reference="lidar_link">
|
||||
<sensor name="lidar" type="lidar">
|
||||
<sensor name="lidar" type="gpu_lidar">
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
<topic>scan</topic>
|
||||
<gz_frame_id>lidar_link</gz_frame_id>
|
||||
<update_rate>10</update_rate>
|
||||
<always_on>true</always_on>
|
||||
<visualize>true</visualize>
|
||||
<ray>
|
||||
<lidar>
|
||||
<scan>
|
||||
<horizontal>
|
||||
<samples>360</samples>
|
||||
@@ -217,13 +315,7 @@
|
||||
<min_angle>-3.14159265</min_angle>
|
||||
<max_angle>3.14159265</max_angle>
|
||||
</horizontal>
|
||||
<!-- 垂直 FOV:2026-11-16 改成真机 MID-360 规格 -7° ~ +52°(59°),40 线。
|
||||
原来用的是对称 ±15° / 16 线,理由是"抬头看天没用"。
|
||||
改成真机规格的原因:体育馆有 10 m 高的天花板,
|
||||
+52° 时 12 m 处能到 15.8 m,10 m 天花板在 7.5 m 处就能打到 ——
|
||||
这样场地外壳才能真正干扰点云,环境不再是"露天理想场"。
|
||||
代价:点数 360x16=5760 → 360x40=14400(×2.5),CPU 负载上升;
|
||||
最近的地面环从 1.51 m 外移到 3.30 m(-7° 比 -15° 平)。 -->
|
||||
<!-- 垂直 FOV 对应 MID-360 的 -7° 至 +52°,共 40 线。 -->
|
||||
<vertical>
|
||||
<samples>40</samples>
|
||||
<resolution>1</resolution>
|
||||
@@ -233,7 +325,8 @@
|
||||
</scan>
|
||||
<range>
|
||||
<min>0.10</min>
|
||||
<max>12.0</max>
|
||||
<!-- Livox specifies 40 m at 10% target reflectivity. -->
|
||||
<max>40.0</max>
|
||||
<resolution>0.01</resolution>
|
||||
</range>
|
||||
<noise>
|
||||
@@ -241,7 +334,7 @@
|
||||
<mean>0.0</mean>
|
||||
<stddev>0.01</stddev>
|
||||
</noise>
|
||||
</ray>
|
||||
</lidar>
|
||||
</sensor>
|
||||
</gazebo>
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
## 其它内容
|
||||
|
||||
- 插件:Physics / UserCommands / SceneBroadcaster / **CpuLidar** / Imu
|
||||
- 插件:Physics / UserCommands / SceneBroadcaster / Sensors(OGRE2)/ Imu
|
||||
- 世界坐标已整体平移 (−6,−4):**场地中心 = 世界原点 (0,0)**,内场范围
|
||||
x[−6,6] y[−4,4];地图 `rmul_2027.yaml` 的 origin 同步改为 (−6.4,−4.4),
|
||||
保证 2D 栅格图与 AMCL/世界坐标系一致
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" ?>
|
||||
<sdf version="1.11">
|
||||
<!-- 开发用世界:RMUL 2027 场地 + 哨兵(URDF 由 create 服务生成)
|
||||
场地模型来自 ~/Gazebo_projects/RMUL2027_map_transfer_20261016_STEP_R1
|
||||
<!-- 开发用世界:RMUL 2027 场地 + 哨兵。
|
||||
场地模型由启动入口从仓库或 SENTRY_FIELD_ROOT 发现。
|
||||
运行需 GZ_SIM_RESOURCE_PATH 包含:
|
||||
<迁移包>/src/guodong_sentry_sim/models
|
||||
|
||||
@@ -20,8 +20,9 @@
|
||||
<plugin filename="gz-sim-physics-system" name="gz::sim::systems::Physics" />
|
||||
<plugin filename="gz-sim-user-commands-system" name="gz::sim::systems::UserCommands" />
|
||||
<plugin filename="gz-sim-scene-broadcaster-system" name="gz::sim::systems::SceneBroadcaster" />
|
||||
<!-- CPU 雷达不依赖渲染,无 GPU 的 headless 环境也能出数据 -->
|
||||
<plugin filename="gz-sim-cpu-lidar-system" name="gz::sim::systems::CpuLidar" />
|
||||
<plugin filename="gz-sim-sensors-system" name="gz::sim::systems::Sensors">
|
||||
<render_engine>ogre2</render_engine>
|
||||
</plugin>
|
||||
<plugin filename="gz-sim-imu-system" name="gz::sim::systems::Imu" />
|
||||
|
||||
<scene>
|
||||
|
||||
+3
-2
@@ -18,7 +18,7 @@ tools/
|
||||
├── capture_lio.py 录制 LIO 建图 / 评估数据
|
||||
├── build_vehicle.py 整车 STL → 仿真网格 + 布局 JSON
|
||||
├── decimate.py 网格降面
|
||||
├── gen_sdf.sh xacro → SDF / URDF
|
||||
├── gen_sdf.sh xacro → SDF 1.11 / URDF,使用相对网格路径
|
||||
├── _internal/ 启动链内部件;被 sentry_up.sh / launch / 测试 import
|
||||
├── validation/ 验收脚本(会真的拉起 Gazebo,跑完整流程)
|
||||
└── tests/ 回归测试(不碰 Gazebo 运动,最快的检查)
|
||||
@@ -47,7 +47,7 @@ tools/
|
||||
| `python3 tools/capture_lio.py --help` | 录制建图(`--profile mapping`)或评估(`--profile evaluation`)数据 |
|
||||
| `python3 tools/build_vehicle.py --help` | 整车装配体 STL → 仿真网格 + 布局 JSON。`--dry-run` 只打印分类结果 |
|
||||
| `python3 tools/decimate.py --help` | 顶点聚类降面:`decimate.py --grid 0.01 src.stl dst.stl` |
|
||||
| `tools/gen_sdf.sh` | xacro → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
| `tools/gen_sdf.sh` | 从脚本位置定位仓库,生成使用相对网格路径的 SDF 1.11 和 URDF |
|
||||
|
||||
**发导航目标不用工具脚本**,用 xmake 产物 `build/bin/nav_client`。
|
||||
`xmake` 构建会自动刷新 `compile_commands.json`(clangd 靠它跳转)。
|
||||
@@ -100,6 +100,7 @@ python3 tools/validation/compare_lio_maps.py --dataset generated/full_shell/data
|
||||
|
||||
| 命令 | 需要什么 | 实测 |
|
||||
|---|---|---|
|
||||
| `python3 tools/tests/test_robot_description.py` | Python 3 | 相对网格路径、含空格的运行时 URI 和失败保留旧产物 |
|
||||
| `python3 tools/tests/test_project_env.py` | Python 3 和 Bash | 临时文件和假 Gazebo 覆盖路径、退出码、版本超时与桥等待 |
|
||||
| `python3 tools/tests/test_nav2_supervisor.py` | **什么都不需要**(不碰 ROS、不碰 Gazebo) | ✅ 5 项检查,约 1 秒 |
|
||||
| `python3 tools/tests/test_nav2_startup.py` | ROS 环境(起隔离 domain 的服务) | ✅ 15 项检查 |
|
||||
|
||||
@@ -75,8 +75,9 @@ class ArenaGrid:
|
||||
return mask
|
||||
|
||||
def coverage(self):
|
||||
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint.
|
||||
travel = self.clear(math.hypot(0.325, 0.270))
|
||||
# 外接半径:footprint 现在是 0.61 x 0.61 的正方形(要覆盖云台 yaw 扫掠圆,
|
||||
# 半径 0.3021 m),外接半径 = 0.305 * sqrt(2)。
|
||||
travel = self.clear(math.hypot(0.305, 0.305))
|
||||
start = self.cell(START)
|
||||
if not travel[start]:
|
||||
raise ValueError('spawn pose fails the footprint clearance check')
|
||||
|
||||
@@ -64,6 +64,12 @@ def build_map(directory, selected, output):
|
||||
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
|
||||
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
|
||||
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
|
||||
bounds_rows = [row.split()[1:] for row in config if row.startswith('map_bounds ')]
|
||||
if len(bounds_rows) != 1 or len(bounds_rows[0]) != 6:
|
||||
raise ValueError('survey recorder configuration is missing map bounds')
|
||||
low, high = np.array(bounds_rows[0], dtype=float).reshape(2, 3)
|
||||
if not np.isfinite([low, high]).all() or not (low < high).all():
|
||||
raise ValueError('survey recorder configuration has invalid map bounds')
|
||||
clouds = []
|
||||
for (x, y), (stamp, filename) in selected:
|
||||
raw = (directory / filename).read_bytes()
|
||||
@@ -72,11 +78,13 @@ def build_map(directory, selected, output):
|
||||
raise ValueError(f'invalid recorded scan {filename}')
|
||||
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
|
||||
points = rows['point'][:, :3].astype(np.float64)
|
||||
points = points[np.isfinite(points).all(axis=1)]
|
||||
if not len(points):
|
||||
raise RuntimeError(f'no finite returns at station {(x, y)}')
|
||||
base_from_imu, imu_from_lidar = extrinsics
|
||||
clouds.append(transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0])
|
||||
points = points[np.isfinite(points).all(axis=1)]
|
||||
world = transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0]
|
||||
selected_points = world[((world >= low) & (world <= high)).all(axis=1)]
|
||||
if not len(selected_points):
|
||||
raise RuntimeError(f'no in-field returns at station {(x, y)}')
|
||||
clouds.append(selected_points)
|
||||
points = np.concatenate(clouds)
|
||||
# Average measured returns that occupy the same voxel across overlapping views.
|
||||
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Build relocatable model files and the runtime ROS robot description."""
|
||||
|
||||
import argparse
|
||||
from contextlib import ExitStack
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import subprocess
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
|
||||
def expand_urdf(share, mesh_prefix):
|
||||
source = share / 'urdf' / 'sentry.urdf.xacro'
|
||||
# Passing the source name keeps the xacro provenance comment relocatable too.
|
||||
return subprocess.run(
|
||||
['xacro', source.name, f'mesh_prefix:={mesh_prefix}'],
|
||||
cwd=source.parent, check=True, stdout=subprocess.PIPE, text=True,
|
||||
).stdout
|
||||
|
||||
|
||||
def runtime_description(share):
|
||||
# resource_retriever's local-file plugin opens the URI path directly.
|
||||
# Retain spaces instead of applying URL percent encoding.
|
||||
meshes = (share / 'meshes').resolve()
|
||||
return expand_urdf(share, f'file://{meshes.as_posix()}')
|
||||
|
||||
|
||||
def mesh_target(reference, parent):
|
||||
path = Path(reference)
|
||||
if path.is_absolute() or PureWindowsPath(reference).anchor or ':' in reference:
|
||||
raise ValueError(f'expected a relative mesh reference, got {reference!r}')
|
||||
target = Path(os.path.normpath(parent / path))
|
||||
if not target.is_file():
|
||||
raise ValueError(f'mesh reference {reference!r} does not exist relative to {parent}')
|
||||
return target
|
||||
|
||||
|
||||
def relative_path(target, parent):
|
||||
return Path(os.path.relpath(target, parent)).as_posix()
|
||||
|
||||
|
||||
def generate(workspace, gz):
|
||||
share = workspace / 'src' / 'sentry_sim'
|
||||
urdf = workspace / 'generated' / 'sentry.urdf'
|
||||
sdf = share / 'models' / 'sentry' / 'model.sdf'
|
||||
urdf.parent.mkdir(parents=True, exist_ok=True)
|
||||
source = expand_urdf(share, relative_path(share / 'meshes', urdf.parent))
|
||||
robot = ET.fromstring(source)
|
||||
if robot.tag != 'robot':
|
||||
raise ValueError('xacro did not produce a URDF robot')
|
||||
urdf_meshes = [mesh_target(node.attrib['filename'], urdf.parent) for node in robot.iter('mesh')]
|
||||
if not urdf_meshes:
|
||||
raise ValueError('URDF contains no meshes')
|
||||
env = os.environ.copy()
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
|
||||
with ExitStack() as cleanup:
|
||||
staged = []
|
||||
for output in (urdf, sdf):
|
||||
with tempfile.NamedTemporaryFile(dir=output.parent, suffix=output.suffix, delete=False) as stream:
|
||||
stage = Path(stream.name)
|
||||
cleanup.callback(stage.unlink, missing_ok=True)
|
||||
staged.append(stage)
|
||||
urdf_stage, sdf_stage = staged
|
||||
urdf_stage.write_text(source, encoding='utf-8')
|
||||
converted = subprocess.run([str(gz), 'sdf', '-p', str(urdf_stage)], env=env, check=True,
|
||||
stdout=subprocess.PIPE, text=True, timeout=30).stdout
|
||||
model = ET.fromstring(converted)
|
||||
if model.tag != 'sdf' or model.get('version') not in ('1.11', '1.12'):
|
||||
raise ValueError(f'unsupported SDFormat conversion output: {model.tag} {model.get("version")}')
|
||||
model.set('version', '1.11')
|
||||
sdf_meshes = []
|
||||
for uri in model.findall('.//mesh/uri'):
|
||||
target = mesh_target(uri.text or '', urdf.parent)
|
||||
sdf_meshes.append(target)
|
||||
uri.text = relative_path(target, sdf.parent)
|
||||
if sorted(urdf_meshes) != sorted(sdf_meshes):
|
||||
raise ValueError('SDF conversion changed the mesh inventory')
|
||||
ET.indent(model)
|
||||
sdf_stage.write_text(ET.tostring(model, encoding='unicode') + '\n', encoding='utf-8')
|
||||
subprocess.run([str(gz), 'sdf', '-k', str(sdf_stage)], env=env, check=True, timeout=30)
|
||||
for stage, output in zip(staged, (urdf, sdf)):
|
||||
stage.chmod(0o644)
|
||||
stage.replace(output)
|
||||
print(output.relative_to(workspace))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
generator = commands.add_parser('generate')
|
||||
generator.add_argument('workspace', type=Path)
|
||||
generator.add_argument('gz', type=Path)
|
||||
runtime = commands.add_parser('runtime-params')
|
||||
runtime.add_argument('share', type=Path)
|
||||
runtime.add_argument('output', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'generate':
|
||||
generate(args.workspace.resolve(), args.gz)
|
||||
else:
|
||||
description = runtime_description(args.share)
|
||||
parameters = {'robot_description': description, 'use_sim_time': True}
|
||||
args.output.write_text(json.dumps({'robot_state_publisher': {'ros__parameters': parameters}}),
|
||||
encoding='utf-8')
|
||||
except (ValueError, OSError, subprocess.SubprocessError, ET.ParseError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+82
-11
@@ -37,6 +37,34 @@ GIMBAL_KEYS = (
|
||||
'24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ',
|
||||
'电机带轮', '拨盘带轮', 'z21胀紧', 'Z21胀紧',
|
||||
)
|
||||
|
||||
# 底盘固定件:名字里虽然带 '基座装配',但**不跟着 yaw 转**。
|
||||
# 先判这张表、再判 GIMBAL_KEYS —— 否则电机会跟着云台绕圈。
|
||||
# GM6020 / 35齿小带轮 电机与电机轴
|
||||
# 涨紧轮 / 上供皮带 皮带传动件
|
||||
# 基座铝件 / 支座碳板 / 打印件补强板 / 轴承压板 基座结构件
|
||||
# thrust ball bearings / 内70外86 内60外76 轴承(外圈固定)
|
||||
# 15.5直径滑环 滑环定子侧
|
||||
# 大yaw6020底板 电机安装底板
|
||||
# F6703ZZ 法兰轴承 实测在 ROS (-0.071, 0),不在 yaw 轴上
|
||||
CHASSIS_KEYS = (
|
||||
'GM6020', '35齿小带轮', '涨紧轮', '上供皮带', '基座铝件', '支座碳板',
|
||||
'打印件补强板', '轴承压板', 'thrust ball bearings', '内70外86',
|
||||
'滑环', '大yaw6020底板', 'F6703ZZ',
|
||||
# '轮系-N 装配体1-1' 之外的轮系零件(如轮上的 Z21 胀紧套):
|
||||
# 它们跟着轮子转,不属于云台。WHEEL_MARK 已先匹配掉轮子本体。
|
||||
'轮系-',
|
||||
)
|
||||
|
||||
# 与 yaw 轴同轴的零件:用它们的中心算 yaw 轴位置(不是电机中心)。
|
||||
# 电机经 35齿小带轮 → 皮带 → 70齿大带轮 减速,电机轴与 yaw 轴相距一个
|
||||
# 皮带中心距(本装配体实测 89.9 mm),拿电机中心当转轴会整圈偏移。
|
||||
# ⚠️ 只放**确认在转轴上**的零件。'胀紧联结套' 不行:全车有 5 个
|
||||
# (电机轴 1 个 + 四个轮子各 1 个),会污染平均值。
|
||||
YAW_AXIS_KEYS = ('70齿大带轮', '云台内圈', '滑环', '内70外86')
|
||||
# 这些同轴件的中心必须一致;离散超过该值就说明关键字选错了,直接报警
|
||||
YAW_AXIS_SPREAD_MM = 5.0
|
||||
|
||||
# 轮子本体(会绕自身轴转)
|
||||
WHEEL_MARK = '轮系-{} 装配体1-1'
|
||||
|
||||
@@ -45,6 +73,9 @@ def read_stl(path):
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
if len(head) < 84:
|
||||
# 连 84 字节的头都不完整 —— 损坏/截断的文件,当读不出处理
|
||||
return None
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 != size:
|
||||
return None
|
||||
@@ -77,12 +108,53 @@ def classify(name):
|
||||
for i in (1, 2, 3, 4):
|
||||
if WHEEL_MARK.format(i) in name:
|
||||
return f'wheel{i}'
|
||||
# 固定件优先:'基座装配' 这个关键字太宽,会把电机和基座板一起划进来
|
||||
for key in CHASSIS_KEYS:
|
||||
if key in name:
|
||||
return 'base'
|
||||
for key in GIMBAL_KEYS:
|
||||
if key in name:
|
||||
return 'gimbal'
|
||||
return 'base'
|
||||
|
||||
|
||||
class YawAxisError(RuntimeError):
|
||||
"""yaw 轴候选零件不共轴 —— 说明 YAW_AXIS_KEYS 选错了。"""
|
||||
|
||||
|
||||
def find_yaw_axis(files):
|
||||
"""按 YAW_AXIS_KEYS 定位 yaw 轴,返回 ``(yaw_xz, 候选数, (离散x, 离散z))``。
|
||||
|
||||
``yaw_xz`` 是 SW 装配体坐标下的 ``(x, z)``;没有候选时返回 ``None``。
|
||||
候选零件的包围盒中心必须共轴(离散 <= ``YAW_AXIS_SPREAD_MM``),否则抛
|
||||
``YawAxisError`` —— 宁可停下,也不要带着偏移的转轴去生成 URDF。
|
||||
"""
|
||||
centers = []
|
||||
for path in files:
|
||||
if not any(k in os.path.basename(path) for k in YAW_AXIS_KEYS):
|
||||
continue
|
||||
tris = read_stl(path)
|
||||
if tris is None:
|
||||
continue
|
||||
v = tris.reshape(-1, 3)
|
||||
centers.append((v.min(axis=0) + v.max(axis=0)) / 2)
|
||||
if not centers:
|
||||
return None, 0, (0.0, 0.0)
|
||||
arr = np.array(centers)
|
||||
mean = arr.mean(axis=0)
|
||||
spread = np.ptp(arr, axis=0) * SCALE * 1000.0 # mm
|
||||
if max(spread[0], spread[2]) > YAW_AXIS_SPREAD_MM:
|
||||
lines = '\n'.join(
|
||||
f' dx={c[0] - mean[0]:+9.1f} dz={c[2] - mean[2]:+9.1f} mm'
|
||||
for c in centers)
|
||||
raise YawAxisError(
|
||||
f'yaw 轴候选不共轴:{len(centers)} 个同轴件的中心离散 '
|
||||
f'{spread[0]:.1f}/{spread[2]:.1f} mm(阈值 {YAW_AXIS_SPREAD_MM} mm)。\n'
|
||||
f' 各候选相对均值:\n{lines}\n'
|
||||
f' 检查 YAW_AXIS_KEYS = {YAW_AXIS_KEYS}')
|
||||
return (mean[0], mean[2]), len(centers), (spread[0], spread[2])
|
||||
|
||||
|
||||
def to_ros(tris, center_sw):
|
||||
"""SW 装配体坐标 -> ROS 坐标(米)。
|
||||
|
||||
@@ -171,17 +243,16 @@ def main():
|
||||
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
|
||||
# yaw 轴:取与大带轮 / 滑环 / 云台内圈这些**同轴件**的中心,见 find_yaw_axis()。
|
||||
# 不能用 GM6020 电机中心 —— 电机经 35齿小带轮 + 皮带 + 70齿大带轮 减速驱动,
|
||||
# 电机轴与 yaw 轴相差一个皮带中心距(本装配体 89.9 mm),拿电机当转轴会整圈偏移。
|
||||
try:
|
||||
yaw_xz, axis_count, axis_spread = find_yaw_axis(files)
|
||||
except YawAxisError as error:
|
||||
raise SystemExit(str(error)) from error
|
||||
if yaw_xz:
|
||||
print(f' yaw 轴由 {axis_count} 个同轴件求得'
|
||||
f'(离散 {axis_spread[0]:.2f}/{axis_spread[1]:.2f} mm)')
|
||||
|
||||
wheels_ros = {}
|
||||
for k, c_sw in wc.items():
|
||||
|
||||
@@ -156,7 +156,10 @@ def main():
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace))
|
||||
log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
log_handles.append(log)
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true',
|
||||
sim_share = Path(os.environ.get('SENTRY_SIM_SHARE') or workspace/'src/sentry_sim')
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
|
||||
'--params-file', str(sim_share/'config/field_cloud.yaml'),
|
||||
'-p', 'use_sim_time:=true',
|
||||
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}',
|
||||
'-p', f'point_cloud_topic:={cloud_topic}'],
|
||||
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
|
||||
+9
-32
@@ -1,38 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# 由 URDF(xacro) 生成 Gazebo 用的静态模型 SDF。
|
||||
# 改了 URDF(或换了网格/雷达参数)之后重跑一次本脚本。
|
||||
#
|
||||
# 产物:
|
||||
# src/sentry_sim/models/sentry/model.sdf Gazebo 世界里 include 的 model://sentry
|
||||
# generated/sentry.urdf 本次 xacro 展开的中间结果(留给人看)
|
||||
# 由 xacro 生成带相对网格引用的 URDF 和 Gazebo SDF 1.11。
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
WS="$PWD"
|
||||
SELF="$(readlink -f -- "${BASH_SOURCE[0]}")"
|
||||
WS="$(cd -- "$(dirname -- "$SELF")/.." && pwd)"
|
||||
|
||||
# 本工程不使用 ament / colcon,xacro 的 `$(find sentry_sim)` 查不到包,
|
||||
# 所以 URDF 里写的是 `$(env SENTRY_SIM_SHARE)`,这里必须先把变量设好。
|
||||
export SENTRY_SIM_SHARE="${SENTRY_SIM_SHARE:-$WS/src/sentry_sim}"
|
||||
|
||||
# 可移植探测:ROS 发行版和 gz 可执行文件都不写死。
|
||||
# shellcheck source=../src/sentry_sim/scripts/env_common.sh
|
||||
. "$WS/src/sentry_sim/scripts/env_common.sh"
|
||||
|
||||
# xacro 只需要 ROS 的基础环境,不需要工作空间的 install/setup.bash(也没有了)。
|
||||
# 探测不到就继续 —— 后面 xacro 找不到时它自己会报错,报错信息更准确。
|
||||
env_source_ros 2>/dev/null || true
|
||||
|
||||
# `gz sdf -p` 只是 URDF → SDF 转换,用系统 gz(避免 vendor 库路径干扰)。
|
||||
GZ=$(env_gz_bin)
|
||||
|
||||
mkdir -p generated
|
||||
TMP="$(mktemp -d)"
|
||||
trap 'rm -rf "$TMP"' EXIT
|
||||
|
||||
xacro src/sentry_sim/urdf/sentry.urdf.xacro > "$TMP/sentry.urdf"
|
||||
cp "$TMP/sentry.urdf" generated/sentry.urdf
|
||||
env -u LD_LIBRARY_PATH "$GZ" sdf -p "$TMP/sentry.urdf" > src/sentry_sim/models/sentry/model.sdf
|
||||
|
||||
echo "已生成:"
|
||||
echo " src/sentry_sim/models/sentry/model.sdf ($(wc -l < src/sentry_sim/models/sentry/model.sdf) 行)"
|
||||
echo " generated/sentry.urdf ($(wc -l < generated/sentry.urdf) 行)"
|
||||
echo "网格路径前缀:$SENTRY_SIM_SHARE"
|
||||
# xacro 可以来自已加载的 ROS 环境,也可以直接安装在 PATH 上。
|
||||
if [ -n "${ROS_SETUP:-}" ] || ! command -v xacro >/dev/null; then
|
||||
env_source_ros
|
||||
fi
|
||||
GZ="$(env_gz_bin)"
|
||||
exec python3 "$WS/tools/_internal/robot_description.py" generate "$WS" "$GZ"
|
||||
+75
-1
@@ -6,6 +6,7 @@ import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
@@ -20,6 +21,12 @@ _KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_re
|
||||
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
|
||||
_GZ_VERSION_TIMEOUT = 5
|
||||
_FIELD_PACKAGE = Path('src/guodong_sentry_sim')
|
||||
# 无界面 Gazebo 的 OGRE2 走 EGL。混合显卡笔记本上 glvnd 默认挑 Mesa,
|
||||
# gpu_lidar 于是退化成 llvmpipe 软件光栅(实测单核 84%,CPU 射线只要 30%)。
|
||||
# 把 EGL vendor 指向 NVIDIA 的 json,OGRE2 才能真正用上显卡。
|
||||
_EGL_NVIDIA_JSON = Path('/usr/share/glvnd/egl_vendor.d/10_nvidia.json')
|
||||
_NVIDIA_DEVICE_NODE = Path('/dev/nvidiactl')
|
||||
_GPU_EGL_MODES = ('auto', 'nvidia', 'off')
|
||||
|
||||
|
||||
class ProbeError(RuntimeError):
|
||||
@@ -197,6 +204,66 @@ def wait_gz_clock(gz, gazebo_pid=None):
|
||||
f'{os.environ.get("GZ_PARTITION") or "sentry"}')
|
||||
|
||||
|
||||
def egl_vendor_json():
|
||||
"""NVIDIA 的 EGL vendor 描述文件。
|
||||
|
||||
`SENTRY_EGL_VENDOR_JSON` 可覆盖 —— 发行版把 glvnd 配置放别处时用。
|
||||
"""
|
||||
override = os.environ.get('SENTRY_EGL_VENDOR_JSON')
|
||||
return Path(override) if override else _EGL_NVIDIA_JSON
|
||||
|
||||
|
||||
def gpu_env():
|
||||
"""Return the EGL environment that makes OGRE2 (and gpu_lidar) use the dGPU.
|
||||
|
||||
`SENTRY_GPU_EGL` selects the behaviour:
|
||||
auto enable only when an NVIDIA device node and the vendor json exist
|
||||
nvidia always enable; missing vendor json is an error
|
||||
off never touch the environment
|
||||
`SENTRY_EGL_PLATFORM` additionally exports `EGL_PLATFORM` when set (some
|
||||
hosts only reach the surfaceless platform that way).
|
||||
|
||||
An empty dict means "leave the environment alone" so callers can splat it
|
||||
unconditionally.
|
||||
"""
|
||||
mode = (os.environ.get('SENTRY_GPU_EGL') or 'auto').strip().lower()
|
||||
if mode not in _GPU_EGL_MODES:
|
||||
raise ProbeError(
|
||||
f'SENTRY_GPU_EGL 只能是 {"|".join(_GPU_EGL_MODES)},当前为 {mode!r}')
|
||||
if mode == 'off':
|
||||
return {}
|
||||
vendor = egl_vendor_json()
|
||||
if mode == 'nvidia' and not vendor.is_file():
|
||||
raise ProbeError(f'SENTRY_GPU_EGL=nvidia 但找不到 {vendor}')
|
||||
if mode == 'auto' and not (_NVIDIA_DEVICE_NODE.exists() and vendor.is_file()):
|
||||
return {}
|
||||
env = {
|
||||
'__EGL_VENDOR_LIBRARY_FILENAMES': str(vendor),
|
||||
'NVIDIA_DRIVER_CAPABILITIES':
|
||||
os.environ.get('NVIDIA_DRIVER_CAPABILITIES') or 'all',
|
||||
}
|
||||
if platform := os.environ.get('SENTRY_EGL_PLATFORM'):
|
||||
env['EGL_PLATFORM'] = platform
|
||||
return env
|
||||
|
||||
|
||||
def describe_gpu_env():
|
||||
"""One-line human summary of what `gpu_env()` decided and why."""
|
||||
mode = (os.environ.get('SENTRY_GPU_EGL') or 'auto').strip().lower()
|
||||
env = gpu_env()
|
||||
if env:
|
||||
return 'nvidia → ' + ' '.join(f'{k}={v}' for k, v in env.items())
|
||||
if mode == 'off':
|
||||
return 'off(SENTRY_GPU_EGL=off,不改环境)'
|
||||
reasons = []
|
||||
if not _NVIDIA_DEVICE_NODE.exists():
|
||||
reasons.append(f'{_NVIDIA_DEVICE_NODE} 不存在')
|
||||
vendor = egl_vendor_json()
|
||||
if not vendor.is_file():
|
||||
reasons.append(f'{vendor} 不存在')
|
||||
return 'off(' + ';'.join(reasons or ['未找到可用显卡']) + ')'
|
||||
|
||||
|
||||
def find_field_root(ws=WORKSPACE, *, explicit=None):
|
||||
if explicit:
|
||||
return require_directory(explicit, 'field_root')
|
||||
@@ -244,13 +311,15 @@ def report(ws):
|
||||
print(f' gz 版本参数 : {versions or "<无>"}')
|
||||
print(f' FIELD_ROOT : {field_root}')
|
||||
print(f' MAP_YAML : {map_yaml}')
|
||||
print(f' GPU EGL : {describe_gpu_env()}')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE)
|
||||
queries = parser.add_mutually_exclusive_group()
|
||||
for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup'):
|
||||
for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup',
|
||||
'gpu', 'gpu-shell'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query)
|
||||
for query in ('gz-version-args-lines', 'wait-gz-clock'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query,
|
||||
@@ -283,6 +352,11 @@ def main(argv=None):
|
||||
print()
|
||||
case 'ros-setup':
|
||||
print(find_ros_setup() or '')
|
||||
case 'gpu':
|
||||
print(describe_gpu_env())
|
||||
case 'gpu-shell':
|
||||
for name, value in gpu_env().items():
|
||||
print(f'export {name}={shlex.quote(value)}')
|
||||
case 'wait-gz-clock':
|
||||
wait_gz_clock(find_gz_bin(), args.gazebo_pid)
|
||||
case None:
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lock the two decisions that are easy to get silently wrong in build_vehicle:
|
||||
|
||||
1. which parts rotate with the gimbal yaw (`classify`)
|
||||
2. where the yaw axis actually is (`find_yaw_axis`)
|
||||
|
||||
Both used to be wrong: the motor centre was taken as the yaw axis even though a
|
||||
belt drives it (89.9 mm offset), and the broad `基座装配` keyword pulled the
|
||||
motor and base plates into the rotating mesh.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import build_vehicle
|
||||
|
||||
|
||||
PREFIX = '完全车2 - 装配体-3 '
|
||||
|
||||
|
||||
def write_box_stl(path, lo, hi):
|
||||
"""Write a one-triangle binary STL whose bounding box is exactly [lo, hi]."""
|
||||
vertices = [(lo[0], lo[1], lo[2]),
|
||||
(hi[0], lo[1], lo[2]),
|
||||
(lo[0], hi[1], hi[2])]
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, 'wb') as handle:
|
||||
handle.write(b'\0' * 80)
|
||||
handle.write(struct.pack('<I', 1))
|
||||
handle.write(struct.pack('<3f', 0.0, 0.0, 1.0))
|
||||
for vertex in vertices:
|
||||
handle.write(struct.pack('<3f', *vertex))
|
||||
handle.write(struct.pack('<H', 0))
|
||||
return path
|
||||
|
||||
|
||||
class ClassifyTest(unittest.TestCase):
|
||||
"""`classify` decides what spins with the yaw; getting it wrong is visible."""
|
||||
|
||||
def test_chassis_parts_stay_with_the_base(self):
|
||||
# '基座装配' alone would match all of these; the explicit chassis list wins.
|
||||
for name in (
|
||||
PREFIX + '基座装配-1 RoboMaster GM6020 直流无刷电机-1.STL',
|
||||
PREFIX + '基座装配-1 35齿小带轮-1.STL',
|
||||
PREFIX + '基座装配-1 涨紧轮-1.STL',
|
||||
PREFIX + '基座装配-1 涨紧轮-2.STL',
|
||||
PREFIX + '基座装配-1 上供皮带2-1.STL',
|
||||
PREFIX + '基座装配-1 基座铝件-1.STL',
|
||||
PREFIX + '基座装配-1 支座碳板-1.STL',
|
||||
PREFIX + '基座装配-1 打印件补强板-1.STL',
|
||||
PREFIX + '基座装配-1 轴承压板-1.STL',
|
||||
PREFIX + '基座装配-1 15.5直径滑环-1.STL',
|
||||
PREFIX + '基座装配-1 thrust ball bearings gb-1.STL',
|
||||
PREFIX + '基座装配-1 内70外86外圈-1 内60外76内圈-1.STL',
|
||||
PREFIX + 'F6703ZZ法兰轴承-1.STL',
|
||||
PREFIX + '大yaw6020底板-1.STL',
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(build_vehicle.classify(name), 'base')
|
||||
|
||||
def test_rotating_parts_follow_the_gimbal(self):
|
||||
for name in (
|
||||
PREFIX + '基座装配-1 70齿大带轮-1.STL',
|
||||
PREFIX + '基座装配-1 云台内圈-1.STL',
|
||||
PREFIX + '八爪拨盘平面盘体-1.STL',
|
||||
PREFIX + '八爪拨盘柱体-1.STL',
|
||||
PREFIX + 'yaw板^装配体-1.STL',
|
||||
PREFIX + '小云台装配体-1 鹅颈云台-相机架-顶部保护板-v1.0-1.STL',
|
||||
PREFIX + '小云台装配体-1 相机支架-v1.0-2.STL',
|
||||
PREFIX + '24哨兵-拨盘-电机带轮垫片-1.STL',
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(build_vehicle.classify(name), 'gimbal')
|
||||
|
||||
def test_wheels_win_over_every_other_keyword(self):
|
||||
self.assertEqual(
|
||||
build_vehicle.classify(PREFIX + '轮系-1 装配体1-1.STL'), 'wheel1')
|
||||
self.assertEqual(
|
||||
build_vehicle.classify(PREFIX + '轮系-4 装配体1-1.STL'), 'wheel4')
|
||||
|
||||
def test_wheel_side_parts_do_not_join_the_gimbal(self):
|
||||
# The four wheel hubs carry their own Z21 sleeves; 'Z21胀紧' must not
|
||||
# drag them into the gimbal because they spin with the wheels.
|
||||
for index in (1, 2, 3, 4):
|
||||
name = PREFIX + f'轮系-{index} Z21胀紧联结套[Z21-10].step-2.STL'
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(build_vehicle.classify(name), 'base')
|
||||
|
||||
|
||||
class YawAxisTest(unittest.TestCase):
|
||||
"""`find_yaw_axis` must refuse an off-axis candidate set instead of drifting."""
|
||||
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory(prefix='sentry yaw ')
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
|
||||
def place(self, name, centre_x, centre_z):
|
||||
"""A part centred at (centre_x, centre_z) mm in SW x/z, 10 mm across."""
|
||||
return write_box_stl(
|
||||
self.root / name,
|
||||
(centre_x - 5.0, 0.0, centre_z - 5.0),
|
||||
(centre_x + 5.0, 100.0, centre_z + 5.0))
|
||||
|
||||
def test_coaxial_parts_give_their_shared_centre(self):
|
||||
files = [self.place('a 70齿大带轮-1.STL', 31386.4, 10455.2),
|
||||
self.place('b 云台内圈-1.STL', 31386.4, 10455.2),
|
||||
self.place('c 15.5直径滑环-1.STL', 31386.5, 10455.3)]
|
||||
axis, count, spread = build_vehicle.find_yaw_axis(files)
|
||||
self.assertEqual(count, 3)
|
||||
self.assertAlmostEqual(axis[0], 31386.43, places=1)
|
||||
self.assertAlmostEqual(axis[1], 10455.23, places=1)
|
||||
self.assertLess(max(spread), build_vehicle.YAW_AXIS_SPREAD_MM)
|
||||
|
||||
def test_motor_style_offset_is_rejected(self):
|
||||
# e.g. accidentally including a belt-driven motor beside the pulley.
|
||||
files = [self.place('a 70齿大带轮-1.STL', 31386.4, 10455.2),
|
||||
self.place('b 云台内圈-1.STL', 31386.4, 10455.2),
|
||||
self.place('c 35齿小带轮-1.STL', 31476.3, 10455.0)]
|
||||
# 35齿小带轮 is not a YAW_AXIS_KEY, so it is ignored entirely.
|
||||
axis, count, _ = build_vehicle.find_yaw_axis(files)
|
||||
self.assertEqual(count, 2)
|
||||
self.assertAlmostEqual(axis[0], 31386.4, places=1)
|
||||
|
||||
# But a *keyword* part that sits off-axis must raise, not average.
|
||||
files.append(self.place('d 70齿大带轮-2.STL', 31476.3, 10455.0))
|
||||
with self.assertRaisesRegex(build_vehicle.YawAxisError, '不共轴'):
|
||||
build_vehicle.find_yaw_axis(files)
|
||||
|
||||
def test_no_candidates_returns_none(self):
|
||||
files = [self.place('wheel 轮系-1 装配体1-1.STL', 31599.0, 10621.0)]
|
||||
self.assertEqual(build_vehicle.find_yaw_axis(files), (None, 0, (0.0, 0.0)))
|
||||
|
||||
def test_unreadable_candidate_is_skipped(self):
|
||||
good = self.place('a 70齿大带轮-1.STL', 1000.0, 2000.0)
|
||||
bad = self.root / 'b 云台内圈-1.STL'
|
||||
bad.write_bytes(b'not an stl')
|
||||
axis, count, _ = build_vehicle.find_yaw_axis([good, bad])
|
||||
self.assertEqual(count, 1)
|
||||
self.assertAlmostEqual(axis[0], 1000.0, places=1)
|
||||
self.assertAlmostEqual(axis[1], 2000.0, places=1)
|
||||
|
||||
|
||||
class KeywordTest(unittest.TestCase):
|
||||
"""The keyword lists themselves are part of the contract."""
|
||||
|
||||
def test_axis_keys_exclude_generic_fasteners(self):
|
||||
# '胀紧联结套' appears on the motor shaft and all four wheel hubs.
|
||||
self.assertNotIn('胀紧联结套', build_vehicle.YAW_AXIS_KEYS)
|
||||
for key in ('70齿大带轮', '云台内圈', '滑环'):
|
||||
self.assertIn(key, build_vehicle.YAW_AXIS_KEYS)
|
||||
|
||||
def test_motor_is_not_an_axis_key(self):
|
||||
self.assertNotIn('GM6020', build_vehicle.YAW_AXIS_KEYS)
|
||||
self.assertIn('GM6020', build_vehicle.CHASSIS_KEYS)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -27,7 +28,9 @@ class EnvironmentTest(unittest.TestCase):
|
||||
self.env['PYTHONDONTWRITEBYTECODE'] = '1'
|
||||
for name in ('ROS_SETUP', 'ROS_INSTALL_ROOT', 'ROS_DISTRO', 'AMENT_PREFIX_PATH',
|
||||
'SENTRY_BIN_DIR', 'NAV_BIN_DIR', 'SENTRY_FIELD_ROOT', 'SENTRY_MAP_YAML',
|
||||
'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION'):
|
||||
'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION',
|
||||
'SENTRY_GPU_EGL', 'SENTRY_EGL_VENDOR_JSON', 'SENTRY_EGL_PLATFORM',
|
||||
'NVIDIA_DRIVER_CAPABILITIES', 'EGL_PLATFORM'):
|
||||
self.env.pop(name, None)
|
||||
|
||||
def run_command(self, command, **overrides):
|
||||
@@ -139,6 +142,61 @@ class EnvironmentTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(project_env.ProbeError, '找不到 Gazebo'):
|
||||
project_env.find_gz_bin()
|
||||
|
||||
def test_gpu_egl_matches_shell(self):
|
||||
"""`gpu_env()` 的判定必须在 CLI 和 Shell 两个入口给出同样结果。"""
|
||||
vendor = self.root/'glvnd/nvidia egl.json'
|
||||
vendor.parent.mkdir(parents=True)
|
||||
vendor.write_text('{"ICD":{"library_path":"libEGL_nvidia.so.0"}}\n')
|
||||
missing = self.root/'nope.json'
|
||||
|
||||
# nvidia:只校验 vendor json,不依赖设备节点 —— 两边都该导出两条。
|
||||
env = dict(SENTRY_GPU_EGL='nvidia', SENTRY_EGL_VENDOR_JSON=str(vendor))
|
||||
exports = (f'export __EGL_VENDOR_LIBRARY_FILENAMES={shlex.quote(str(vendor))}\n'
|
||||
'export NVIDIA_DRIVER_CAPABILITIES=all\n')
|
||||
self.assertEqual(self.cli('--gpu-shell', **env).stdout, exports)
|
||||
result = self.run_command(
|
||||
['bash', '-c', 'source "$1"; env_gpu_egl 2>/dev/null; '
|
||||
'printf "%s|%s\\n" "$__EGL_VENDOR_LIBRARY_FILENAMES" '
|
||||
'"$NVIDIA_DRIVER_CAPABILITIES"',
|
||||
'env-test', str(SCRIPTS/'env_common.sh')], **env)
|
||||
self.expect_value(result, f'{vendor}|all')
|
||||
|
||||
# off:两边都静默(空输出,连换行都没有)。
|
||||
off_cli = self.cli('--gpu-shell', SENTRY_GPU_EGL='off')
|
||||
self.assertEqual(off_cli.returncode, 0, off_cli.stderr)
|
||||
self.assertEqual(off_cli.stdout, '')
|
||||
off = self.shell('env_gpu_egl')
|
||||
self.assertEqual(off.returncode, 0, off.stderr)
|
||||
self.assertEqual(off.stdout, '')
|
||||
|
||||
# EGL_PLATFORM 只在显式设置时才追加。
|
||||
with patch.dict(os.environ, {**env, 'SENTRY_EGL_PLATFORM': 'surfaceless'}):
|
||||
self.assertEqual(project_env.gpu_env()['EGL_PLATFORM'], 'surfaceless')
|
||||
|
||||
# auto:设备节点和 vendor json 缺一不可。
|
||||
auto = {**env, 'SENTRY_GPU_EGL': 'auto'}
|
||||
with patch.dict(os.environ, auto):
|
||||
with patch.object(project_env, '_NVIDIA_DEVICE_NODE', self.root/'missing-device'):
|
||||
self.assertEqual(project_env.gpu_env(), {})
|
||||
self.assertIn('不存在', project_env.describe_gpu_env())
|
||||
with patch.object(project_env, '_NVIDIA_DEVICE_NODE', vendor):
|
||||
self.assertEqual(project_env.gpu_env()['__EGL_VENDOR_LIBRARY_FILENAMES'],
|
||||
str(vendor))
|
||||
|
||||
# 缺 vendor json:nvidia 报错,auto 静默。
|
||||
self.expect_error(self.cli('--gpu-shell', SENTRY_GPU_EGL='nvidia',
|
||||
SENTRY_EGL_VENDOR_JSON=str(missing)), '找不到')
|
||||
with patch.dict(os.environ, {'SENTRY_GPU_EGL': 'auto',
|
||||
'SENTRY_EGL_VENDOR_JSON': str(missing)}):
|
||||
with patch.object(project_env, '_NVIDIA_DEVICE_NODE', vendor):
|
||||
self.assertEqual(project_env.gpu_env(), {})
|
||||
|
||||
# 非法取值必须被拒绝,而不是静默当成 auto。
|
||||
self.expect_error(self.cli('--gpu', SENTRY_GPU_EGL='bogus'), 'SENTRY_GPU_EGL')
|
||||
with patch.dict(os.environ, {'SENTRY_GPU_EGL': 'bogus'}):
|
||||
with self.assertRaisesRegex(project_env.ProbeError, 'SENTRY_GPU_EGL'):
|
||||
project_env.gpu_env()
|
||||
|
||||
def test_build_directory_priority_matches_shell(self):
|
||||
build = self.root/'build'
|
||||
unified = build/'bin'
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression tests for relocatable generated and runtime mesh paths."""
|
||||
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from _internal import robot_description as description
|
||||
|
||||
|
||||
class RobotDescriptionTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temporary = tempfile.TemporaryDirectory(prefix='sentry workspace ')
|
||||
self.addCleanup(temporary.cleanup)
|
||||
self.workspace = Path(temporary.name)
|
||||
self.share = self.workspace / 'src/sentry_sim'
|
||||
meshes = self.share / 'meshes'
|
||||
meshes.mkdir(parents=True)
|
||||
(meshes / 'base.stl').write_text('mesh')
|
||||
self.sdf = self.share / 'models/sentry/model.sdf'
|
||||
self.sdf.parent.mkdir(parents=True)
|
||||
self.urdf = self.workspace / 'generated/sentry.urdf'
|
||||
|
||||
def test_runtime_local_file_uri_keeps_spaces(self):
|
||||
with patch.object(description, 'expand_urdf') as expand:
|
||||
description.runtime_description(self.share)
|
||||
expand.assert_called_once_with(self.share, f'file://{self.share.resolve()}/meshes')
|
||||
|
||||
def test_generated_meshes_resolve_from_each_output(self):
|
||||
def fake_gz(command, **kwargs):
|
||||
if command[2] == '-p':
|
||||
result = ('<sdf version="1.12"><model><mesh>'
|
||||
'<uri>../src/sentry_sim/meshes/base.stl</uri>'
|
||||
'</mesh></model></sdf>')
|
||||
return subprocess.CompletedProcess(command, 0, stdout=result)
|
||||
self.assertEqual(command[2], '-k')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
|
||||
expanded = '<robot><mesh filename="../src/sentry_sim/meshes/base.stl"/></robot>'
|
||||
with patch.object(description, 'expand_urdf', return_value=expanded), \
|
||||
patch.object(description.subprocess, 'run', side_effect=fake_gz):
|
||||
description.generate(self.workspace, Path('gz'))
|
||||
robot = ET.parse(self.urdf).getroot()
|
||||
model = ET.parse(self.sdf).getroot()
|
||||
self.assertEqual(model.get('version'), '1.11')
|
||||
self.assertEqual(robot.find('mesh').get('filename'), '../src/sentry_sim/meshes/base.stl')
|
||||
self.assertEqual(model.findtext('.//mesh/uri'), '../../meshes/base.stl')
|
||||
|
||||
def test_bad_conversion_keeps_previous_outputs(self):
|
||||
self.urdf.parent.mkdir()
|
||||
self.urdf.write_text('previous URDF')
|
||||
self.sdf.write_text('previous SDF')
|
||||
expanded = '<robot><mesh filename="../src/sentry_sim/meshes/base.stl"/></robot>'
|
||||
bad_output = '<sdf version="1.11"><mesh><uri>/someone/base.stl</uri></mesh></sdf>'
|
||||
with patch.object(description, 'expand_urdf', return_value=expanded), \
|
||||
patch.object(description.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0, stdout=bad_output)):
|
||||
with self.assertRaises(ValueError):
|
||||
description.generate(self.workspace, Path('gz'))
|
||||
self.assertEqual(self.urdf.read_text(), 'previous URDF')
|
||||
self.assertEqual(self.sdf.read_text(), 'previous SDF')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -59,7 +59,7 @@ def cylinder_clearance(row,x,y,radius):
|
||||
q=row[4:];yaw=math.atan2(2*(q[3]*q[2]+q[0]*q[1]),1-2*(q[1]*q[1]+q[2]*q[2]))
|
||||
dx,dy=x-row[1],y-row[2]
|
||||
bx=math.cos(yaw)*dx+math.sin(yaw)*dy;by=-math.sin(yaw)*dx+math.cos(yaw)*dy
|
||||
# Union of the actual SDF chassis and gimbal collision boxes.
|
||||
# Chassis box and the yaw sweep of the SDF gimbal collision box.
|
||||
chassis=math.hypot(max(0,abs(bx)-0.289),max(0,abs(by)-0.2605))
|
||||
gimbal=math.hypot(max(0,abs(bx-0.12)-0.20),max(0,abs(by)-0.15))
|
||||
gimbal=math.hypot(bx,by)-math.hypot(0.2656,0.1439)
|
||||
return min(chassis,gimbal)-radius
|
||||
@@ -42,6 +42,7 @@ from verify_lio_stack import NODES, process_environment
|
||||
|
||||
ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0))
|
||||
ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16)
|
||||
SOUTHEAST_ROUND_TRIP = ((0.0, 0.0), (5.0, -3.0), (0.0, 0.0))
|
||||
|
||||
|
||||
def check_field_coverage(node, grid):
|
||||
@@ -100,6 +101,8 @@ def main():
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
goals = parser.add_mutually_exclusive_group()
|
||||
goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
goals.add_argument('--southeast-round-trip', action='store_true',
|
||||
help='navigate center, southeast corner, and back to center')
|
||||
goals.add_argument('--full-field', action='store_true',
|
||||
help='check reachability in 1 m tiles and navigate the whole-field route')
|
||||
goals.add_argument('--round-trip-regression', action='store_true',
|
||||
@@ -108,6 +111,8 @@ def main():
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--continue-on-failure', action='store_true',
|
||||
help='try later full-field goals after recording a failed leg and waiting for recovery')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
@@ -118,8 +123,17 @@ def main():
|
||||
parser.error('--round-trip-regression requires clear or cylinder')
|
||||
if args.full_field and args.scenario != 'clear':
|
||||
parser.error('--full-field starts the clear-field coverage route')
|
||||
multileg = args.round_trip_regression or args.full_field
|
||||
route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ())
|
||||
if args.continue_on_failure and not args.full_field:
|
||||
parser.error('--continue-on-failure requires --full-field')
|
||||
multileg = args.round_trip_regression or args.full_field or args.southeast_round_trip
|
||||
if args.full_field:
|
||||
route = ARENA_GOALS
|
||||
elif args.round_trip_regression:
|
||||
route = ROUND_TRIP
|
||||
elif args.southeast_round_trip:
|
||||
route = SOUTHEAST_ROUND_TRIP
|
||||
else:
|
||||
route = (args.goal,) if args.goal else ()
|
||||
pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route)
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
@@ -164,6 +178,7 @@ def main():
|
||||
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
|
||||
'--params-file', str(params_file.with_name('field_cloud.yaml')),
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'],
|
||||
stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
@@ -394,6 +409,7 @@ def main():
|
||||
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
|
||||
'trajectory_metrics': metrics(estimate_goal, truth_goal),
|
||||
'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None,
|
||||
'truth_end_xy_m': truth_goal[-1][1:3] if truth_goal else None,
|
||||
'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal)
|
||||
if truth_goal and args.scenario == 'cylinder' else None,
|
||||
'health_failures_during_goal': sum(not value for stamp, value in health_events
|
||||
@@ -451,7 +467,8 @@ def main():
|
||||
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
|
||||
if multileg and not leg['goal_succeeded']:
|
||||
spin_for(8)
|
||||
break
|
||||
if not args.continue_on_failure:
|
||||
break
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
|
||||
Reference in new issue
Block a user