实现了yaw轴的转动,mid360参数更加接近实际的参数

This commit is contained in:
mzx committed 2026-11-25 21:22:13 +08:00
1 parent 72f407c110
commit 96445bd5f1
61 files changed
+2458 -233

No files matched your search

+30 -13
View File
@@ -15,6 +15,25 @@
`LOCALIZATION=amcl scripts/sentry_up.sh`(或 Python 启动参数 `localization:=amcl`)选择旧方案。下文与 `docs/定位接入AMCL.md` 中的 AMCL 参数/排障说明仅适用于该分支。每次只启动一种定位器发布 `map→odom`,两种方案均保留 Nav2 的 2D map_server。 `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. 开发环境
### 0.1 操作系统 ### 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。 > 根因与修法:`docs/踩过的坑.md` §G4/§G5、`docs/定位接入AMCL.md` §4.1/§4.2。
> 诊断工具:`python3 tools/check_stack.py`(含真值对照)。 > 诊断工具:`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点云」显示项已经配好,打开就能看到。 RViz 的「MID360点云」显示项已经配好,打开就能看到。
> ⚠️ 量程仍是 **12 m**(真机 40 m),导致 14 m 外的场馆墙打不到、 > 当前 40 m 模型的结果见 [MID-360 接入与验收](docs/MID360-3D雷达接入.md)。
> 10 m 天花板差 4 cm 够不着。想改善见 `docs/仿真场地外壳.md` §10。
### 🆕 2026-11-17 新增 ### 🆕 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 的 1. **LIO 是已知初始位姿下的连续跟踪定位**:不会全局重定位;点云配准连续失效或不确定度超限时会报告定位不可用并触发导航保护。地图对称性、几何退化和传感器断流仍可能导致停车。接口、阈值和验证限制见 [`src/field_localization/README.md`](src/field_localization/README.md)。
轮式里程计积分。打滑/被推之后**永远不会自愈**;真机上完全不可用。 2. **仿真用固定 40 m 量程和规则采样**,真机的探测距离随反射率变化,扫描图案也不同。
真定位需要:点云转 2D → AMCL(当前 `/scan` 因真机视场已基本失效,
得先加 `pointcloud_to_laserscan`)。详见 `docs/仿真场地外壳.md`
2. **雷达量程只有 12 m**(真机 40 m):场馆墙(14 m 外)打不到、10 m 天花板差 4 cm
3. 质量/惯量为估算值(25 kg / 1.5 kg),物理表现可能与真机有偏差 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. 场地外壳是纯视觉设施,没有看台/球架/广告牌等赛场道具 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 项单测覆盖 | | ~~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) | | 2 | **写决策状态机**(PATROL / ENGAGE / RETREAT) | 还没有。骨架是 `patrol`,纯逻辑该写在 `src/core/` 里配单测(5 ms 跑完,不用起 Gazebo) |
| 3 | **把定位做成真的** | 现在是**作弊**的:`map→odom` 写死 (-5.0, 3.0),位置靠轮速积分,打滑/被撞永远不会自愈。真做要 `/scan/points` → `pointcloud_to_laserscan` → AMCL | | 3 | **扩展 LIO 验收与场景覆盖** | 当前默认使用全场 `field_full.flmap` 连续跟踪;继续验证新障碍、长时间往返和传感器断流下的定位保护。不要启用全局重定位来处理场地的 180° 对称歧义 |
| 4 | **雷达量程 12 → 20 m** | 现在 14 m 外的场馆墙打不到、10 m 天花板差 4 cm。改法见 `docs/仿真场地外壳.md` | | ~~4~~ | ~~恢复雷达 40 m 量程~~ | 已恢复,体育馆回波在建图、定位和避障中按用途裁剪 |
| 5 | **补真实参数** | 整车质量 25 kg / 轮 1.5 kg 是估的。找机械要 SolidWorks「评估 → 质量属性」(kg·m²) | | 5 | **补真实参数** | 整车质量 25 kg / 轮 1.5 kg 是估的。找机械要 SolidWorks「评估 → 质量属性」(kg·m²) |
| 6 | **障碍测试补齐** | `models/test_box/` 有模型但世界没 include;加进去后曾出现规划失败(车跑到角落出不来),需要查是代价地图被点云糊住还是控制器问题 | | 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 是调参和补数据。 **1 和 2 是真正该动的代码**;3 是中等工程;4~6 是调参和补数据。
+50 -50
View File
@@ -1,7 +1,7 @@
# MID-360 3D 激光雷达接入说明 # MID-360 3D 激光雷达接入说明
> **状态**:✅ 点云可用,已通过 `self_filter` 接入 Nav2 代价地图 > 已接通 40 m 原始点云、场地建图裁剪与 Nav2 避障。新地图继续作为候选图。
> **最后更新**:2026-11-24 > 最后更新于 2026-11-25。
> **涉及**:`src/sentry_sim/urdf/sentry.urdf.xacro`(传感器定义)、`src/sentry_nav/`(自滤) > **涉及**:`src/sentry_sim/urdf/sentry.urdf.xacro`(传感器定义)、`src/sentry_nav/`(自滤)
## 1. 结论 ## 1. 结论
@@ -9,13 +9,12 @@
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 输出 3D 点云 | ✅ **14400 点/帧(360 水平 × 40 垂直)**,10 Hz | | 输出 3D 点云 | ✅ **14400 点/帧(360 水平 × 40 垂直)**,10 Hz |
| 有效点 / 测距 | ⚠️ 约 4950 个有效点(`inf` 占 65.6%),**0.06 ~ 11.68 m** | | 量程 | 0.10–40 m,Shell 和 Python 采样的最远有效点分别为 29.78 m 和 31.52 m |
| 能看到地面 | ✅ 高度 −0.41 ~ +9.31 m(−7° 打地面,+52° 打到顶棚主梁) | | 可见范围 | 场内地面、外部体育馆墙壁、屋顶 |
| RViz 可视化 | ✅ 「MID360点云」显示项(`/scan/points`) | | RViz 可视化 | ✅ 「MID360点云」显示项(`/scan/points`) |
| 接入 Nav2 避障 | ✅ `/scan/points_filtered`(`self_filter` 剔除车身自回波后) | | 接入 Nav2 避障 | ✅ `/scan/points_filtered`(`self_filter` 剔除车身自回波后) |
> ⚠️ **最大的限制不是视场,是量程 12 m**。真机是 0.1~40 m,我们只给 12 m, 体育馆保持 40 × 28 m、墙高 10 m。原始点云保留体育馆回波,建图和避障分别处理。
> 导致 14 m 外的墙一个点打不到、10 m 天花板差 4 cm 够不着。见 §3。
--- ---
@@ -27,12 +26,15 @@
| 项 | 值 | | 项 | 值 |
|---|---| |---|---|
| 安装位置(ROS) | **(−0.0935, −0.1512, 0.4052)**,外形 84×68×82 mm(装配体实测) | | 安装位置(ROS) | 云台零位时在底盘系 **(−0.0935, −0.1512, 0.4052) m** |
| 外形与质量 | **65 × 65 × 60 mm,265 g**。惯量按均质长方体计算,SDF 转换后并入云台 link |
| 类型 | `type="gpu_lidar"` + OGRE2 `Sensors` | | 类型 | `type="gpu_lidar"` + OGRE2 `Sensors` |
| 水平 | 360 点,−π ~ +π | | 水平 | 360 点,−π ~ +π |
| **垂直** | **40 线,−7° ~ +52°**(真机规格;−0.122173 ~ 0.907571 rad) | | **垂直** | **40 线,−7° ~ +52°**(真机规格;−0.122173 ~ 0.907571 rad) |
| 更新率 | 10 Hz | | 更新率 | 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 话题与桥接 ### 2.2 话题与桥接
@@ -64,30 +66,26 @@
可见网格和物理碰撞体可能采用不同的几何。修改车身视觉网格或场地模型后,重新核对车身自回波和可用点数。 可见网格和物理碰撞体可能采用不同的几何。修改车身视觉网格或场地模型后,重新核对车身自回波和可用点数。
上一版 CPU 雷达的有效点比例是历史测量。 上一版 CPU 雷达的有效点比例是历史测量。
**② `/scan`(2D)现在基本不可用,这是预期的。** **② `/scan` 取中间一层。** 约 +22.5° 的仰角会看到体育馆外壳。AMCL 和碰撞监控用自滤后投影的 `/scan2d`,Nav2 代价地图用 3D 点云。
gz 的 `/scan` 取**中间那层**射线,而中间角 = (−7 + 52) / 2 = **+22.5° 仰角**,射向天空。
只用 3D 点云;Nav2 代价地图吃的也是点云,不受影响。
--- ---
## 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) | 比赛场内车体中心距最近馆墙至少 10 m。避障的 8 m 上限能滤除馆墙,1.20 m 的高度上限能滤除斜上方进入 8 m 水平范围的天花板。LIO 需要场内远端围挡,因此另设 `lio_max_range=40.2` m 为水平预滤上限,其中 0.2 m 覆盖雷达相对底盘的偏心。
|---|---|---|
| +30° | 18.99 m ❌ | 17.89 m ❌ |
| +45.9° | 13.22 m ❌ | 12.46 m ❌ |
| **+52°(最大)** | 12.05 m ❌ | 11.35 m ✅ |
- **天花板下沿需要仰角 ≥ 52.3°**,最高只有 52.0° —— 差 0.3°,够不着 地图在 `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 余量。地图加载和写入不加余量,单独的测站建图使用已知测站位姿。
- **主梁下沿需要 ≥ 48.2°** —— 只有最顶上 1~2 条线打到,就是那 81 个点的来源
- **墙(最近 14.0 m 水平)斜距永远 ≥ 14 m** —— 任何仰角都超量程,**一个点都打不到**
换个说法:**量程 12 m 时射线最高只到 `0.4052 + 12·sin(52°) = 9.86 m`**, 云台转动时,自滤根据点云时间戳查雷达到底盘的 TF。LIO 和录制再把整帧点云统一到 IMU 系。实机若按方位角去畸变,当前实现需要固定安装的雷达。
而天花板下沿在 9.9 m —— 差 4 cm。
### 对照实验:量程改 20 m ### 历史对照(12 m 和 20 m)
| 指标 | 12 m | **20 m** | | 指标 | 12 m | **20 m** |
|---|---|---| |---|---|---|
@@ -97,30 +95,34 @@ gz 的 `/scan` 取**中间那层**射线,而中间角 = (−7 + 52) / 2 = **+2
| 天花板点(z>8) | 81 | **4578** | | 天花板点(z>8) | 81 | **4578** |
| 远处墙点(r>12.5) | **0** | **1440** | | 远处墙点(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%) | Shell | 14,400 点/帧,10.0 Hz | 29.78 m | 7.68 m / 0.37 m |
水平测距 :0.06 ~ 11.68 m | Python | 14,400 点/帧,10.0 Hz | 31.52 m | 7.95 m / 0.42 m |
高度范围 :−0.41 ~ +9.31 m ← 上面是顶棚主梁
垂直角 :−7.0° ~ +52.0° ← 与真机一致
打到天花板的点 :81 个(1.6%)
```
**`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)。
自检命令: 自检命令:
@@ -170,9 +172,7 @@ ros2 topic info /scan/points # PointCloud2
`Collision Ahead - Exiting DriveOnHeading`。抬高 `obstacle_min_range` 到 0.9 m 也不够 `Collision Ahead - Exiting DriveOnHeading`。抬高 `obstacle_min_range` 到 0.9 m 也不够
(车身相对传感器最远约 0.65 m)。 (车身相对传感器最远约 0.65 m)。
**现在的做法**:`src/sentry_nav/` 里的 `self_filter` 节点把点云转到 `base_link`、 两个代价地图都订阅 `/scan/points_filtered`。`self_filter` 按时间戳转换到底盘系,执行车身、距离和高度过滤。避障和定位分别发布点云,见 §3。
剔掉车身包围盒内的点,输出 `/scan/points_filtered`,两个代价地图都改吃它。
实测 3612 → 1546 点,最近距离 0.10 → 0.87 m。
参数与用法见 `src/sentry_nav/README.md`;代码分层见 `src/sentry_nav/src/README.md`。 参数与用法见 `src/sentry_nav/README.md`;代码分层见 `src/sentry_nav/src/README.md`。
@@ -184,7 +184,9 @@ ros2 topic info /scan/points # PointCloud2
|---|---| |---|---|
| 安装位置 | `urdf/sentry.urdf.xacro` 的 `lidar_x/y/z` | | 安装位置 | `urdf/sentry.urdf.xacro` 的 `lidar_x/y/z` |
| 垂直视场 / 线数 | 同文件 `<vertical>` 的 `samples` / `min_angle` / `max_angle`(弧度) | | 垂直视场 / 线数 | 同文件 `<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` | | 碰撞体形状 | 同文件 `chassis_collision` / `gimbal_collision` |
| 桥接话题 | `scripts/sentry_up.sh` **和** `scripts/bridge_after_gz.sh` | | 桥接话题 | `scripts/sentry_up.sh` **和** `scripts/bridge_after_gz.sh` |
| 是否参与避障 | `config/nav2_params.yaml` 的 costmap `plugins` 与 `observation_sources` | | 是否参与避障 | `config/nav2_params.yaml` 的 costmap `plugins` 与 `observation_sources` |
@@ -205,9 +207,7 @@ HEADLESS=0 scripts/sentry_up.sh
| 现象 | 原因 | 处理 | | 现象 | 原因 | 处理 |
|---|---|---| |---|---|---|
| 点云全在 0.2~0.4 m | 雷达被整车碰撞盒包住 | 拆成底盘盒 + 云台盒(§2.4①) | | 点云全在 0.2~0.4 m | 雷达被整车碰撞盒包住 | 拆成底盘盒 + 云台盒(§2.4①) |
| `/scan` 全是 `inf` | 改成真机视场后的**预期行为**(中间层 +22.5° 打向天空) | 正常,只用 3D 点云 | | RViz 的原始点云中看到馆墙和屋顶 | 当前 40 m 传感器回波 | 用 `/scan/points_filtered` 查看实际避障输入 |
| 点云上半区一大片空(`inf` 65%) | 同上 + 大厅空旷、量程 12 m 够不到天花板 | 加大量程(§3) |
| 天花板只打到 81 个点 | 量程 12 m 下最高只到 9.86 m,天花板在 9.9 m | 量程改 20 m(§3) |
| 点云话题收不到 | 只改了 `bridge_after_gz.sh`,实际跑的是 `sentry_up.sh` | 两处都改(§2.2) | | 点云话题收不到 | 只改了 `bridge_after_gz.sh`,实际跑的是 `sentry_up.sh` | 两处都改(§2.2) |
| 接进代价地图后车不动 | 点云含车身自回波 | 已加自滤(§6) | | 接进代价地图后车不动 | 点云含车身自回波 | 已加自滤(§6) |
+1 -1
View File
@@ -10,7 +10,7 @@
| [`操作手册.md`](操作手册.md) | 启动/收尾、体检、遥控、演示、发目标、航点巡逻、看数据、环境变量、场地坐标 | **要动手操作** | | [`操作手册.md`](操作手册.md) | 启动/收尾、体检、遥控、演示、发目标、航点巡逻、看数据、环境变量、场地坐标 | **要动手操作** |
| [`排错速查.md`](排错速查.md) | 7 类 34 条现象 → 原因 → 处理 | **出问题了**(「现在怎么办」) | | [`排错速查.md`](排错速查.md) | 7 类 34 条现象 → 原因 → 处理 | **出问题了**(「现在怎么办」) |
| [`踩过的坑.md`](踩过的坑.md) | 27 条设计经验,按领域分 7 组(§A–§G) | 想知道**为什么**这么设计(「别再犯」) | | [`踩过的坑.md`](踩过的坑.md) | 27 条设计经验,按领域分 7 组(§A–§G) | 想知道**为什么**这么设计(「别再犯」) |
| [`MID360-3D雷达接入.md`](MID360-3D雷达接入.md) | 传感器配置、话题桥接、实测数据、**量程 12 m 这个瓶颈** | 动雷达 | | [`MID360-3D雷达接入.md`](MID360-3D雷达接入.md) | 40 m 雷达配置、场地点云过滤、地图与导航验收 | 动雷达 |
| [`仿真场地外壳.md`](仿真场地外壳.md) | 体育馆大厅 + 屋顶 + 拦截网的尺寸、取舍、怎么改 | 动场地 | | [`仿真场地外壳.md`](仿真场地外壳.md) | 体育馆大厅 + 屋顶 + 拦截网的尺寸、取舍、怎么改 | 动场地 |
| [`定位接入AMCL.md`](定位接入AMCL.md) | **定位怎么做**:为什么之前是假的、AMCL 需要什么、2D 雷达怎么加、`map→odom` 谁发、已知卡点 | 动定位 | | [`定位接入AMCL.md`](定位接入AMCL.md) | **定位怎么做**:为什么之前是假的、AMCL 需要什么、2D 雷达怎么加、`map→odom` 谁发、已知卡点 | 动定位 |
| [`构建体系与代码分层.md`](构建体系与代码分层.md) | C++23 下限证据、为什么全用 xmake、`src/core/` 分层纪律 | 动构建或代码结构 | | [`构建体系与代码分层.md`](构建体系与代码分层.md) | C++23 下限证据、为什么全用 xmake、`src/core/` 分层纪律 | 动构建或代码结构 |
+3 -1
View File
@@ -4,12 +4,14 @@
> **最后更新**:2026-11-17 > **最后更新**:2026-11-17
> **涉及模型**:`arena_walls`(新)、`arena_roof`(新)、`catch_net`(停用但保留) > **涉及模型**:`arena_walls`(新)、`arena_roof`(新)、`catch_net`(停用但保留)
2026-11-25 起原始雷达量程为 40 m,体育馆几何沿用本文的尺寸。下文关于 12 m 和 20 m 的测量是旧版记录。当前观测与场地过滤见 [MID-360 接入与验收](MID360-3D雷达接入.md)。
## 1. 一句话结论 ## 1. 一句话结论
> 比赛场地被包在 **40 × 28 m、墙高 10 m** 的体育馆大厅里,头顶是 10 m 的顶棚 + 梁 + 12 条灯带。 > 比赛场地被包在 **40 × 28 m、墙高 10 m** 的体育馆大厅里,头顶是 10 m 的顶棚 + 梁 + 12 条灯带。
> 墙、地面、顶棚、梁**都有碰撞体**。雷达视场也已改成真机规格 **−7°~+52° / 40 线**。 > 墙、地面、顶棚、梁**都有碰撞体**。雷达视场也已改成真机规格 **−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**。 > 而量程 12 m 下射线最高只到 9.86 m —— **差 4 cm**。
> 实测只打到顶棚主梁 **81 个点**,墙 **0 个**。怎么解决见 §6。 > 实测只打到顶棚主梁 **81 个点**,墙 **0 个**。怎么解决见 §6。
+2 -2
View File
@@ -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` | 传感器高于围挡(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`) | | 点云里全是近距离点 | 传感器被车身碰撞盒包住 | 检查碰撞体是否把雷达罩进去(已拆成 `chassis_collision` + `gimbal_collision`) |
| 代价地图把车自己标成障碍 | 没跑自滤,或包围盒太小 | 确认 `self_filter` 在跑:`ros2 topic hz /scan/points_filtered` | | 代价地图把车自己标成障碍 | 没跑自滤,或包围盒太小 | 确认 `self_filter` 在跑:`ros2 topic hz /scan/points_filtered` |
| 雷达看不到场馆墙 | 量程只有 **12 m**,墙在 14 m 外 | 见 `仿真场地外壳.md` §6.2 | | 避障点云看不到场馆墙 | 底盘系的水平距离上限为 **8 m** | 用原始 `/scan/points` 查看馆墙回波 |
## C. 话题与桥 ## C. 话题与桥
+15 -5
View File
@@ -42,22 +42,32 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl
只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 0.5 m,或旋转严格大于 10°。初始化种子帧是唯一例外。配准失败不写图。 只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 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 地图 ### 单独生成全场 Gazebo 地图
```bash ```bash
python3 tools/capture_lio.py --profile mapping --full-field \ 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 \ 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` 继续沿用原有的地面滤除规则。全场图对应当前仿真模型和雷达外参,改场地或更换外参后应重新采集和验收。 该模式在隔离的 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 接口与坐标约定 ## 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`。 - 默认输入:`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 系完成,不重复施加安装外参。 - 原始云在 `lidar_link`,自滤云在 `base_link`。瞬时点云按消息时间戳转换到 `imu_link`,包含云台角度和偏心位移。两个仿真入口的关节 TF 发布频率设为 100 Hz。
- 默认固定帧:`map/odom/base_link/imu_link/lidar_link`,均可通过同名 frame 参数配置。外参从现有固定 TF 读取;缺失时等待,禁止假设为恒等变换。 - 默认坐标系为 `map/odom/base_link/imu_link/lidar_link`,可通过同名 frame 参数配置。方位角去畸变在原生雷达坐标系计算,要求雷达与 IMU 刚性连接。
- 内部状态原点为 IMU,`q` 将 IMU 坐标旋转到 map,`v/g` 在 map 系。误差顺序为 `p,v,theta,bg,ba,g`,右扰动态度误差。 - 内部状态原点为 IMU,`q` 将 IMU 坐标旋转到 map,`v/g` 在 map 系。误差顺序为 `p,v,theta,bg,ba,g`,右扰动态度误差。
- `get_pose()` 返回 `map → base_link`;`get_snapshot()` 在一把互斥锁内返回配套的位姿、滤波状态、协方差与状态时间。 - `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 同时发布。 - 只发布 TF `map → odom`:`T_map_odom = T_map_base × inverse(T_odom_base)`,两个变换使用同一时间。`publish_map_to_odom=false` 可关闭;不能与 AMCL 同时发布。
@@ -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` 代替真值。 独立真值来自 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 秒。没有真值或足够对应关系时不能声称验证精度。 回放工具不依赖 ROS,不读取轮速作为定位量测。输出 `trajectory.tum/status.csv/metrics.txt`;报告未对齐的平移 ATE、旋转测地角 ATE、1 秒相对位姿 RPE,旋转以度报告。真值线性平移/四元数 slerp 插值,最大真值间隔 0.05 秒。没有真值或足够对应关系时不能声称验证精度。
+67
View File
@@ -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,222 @@
# 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` | 表示「子坐标系 → 父坐标系」的变换 |
**所有时间戳的单位都是秒**(`double`),不是 ROS 的纳秒。
## `imu_integration.hpp`
实现:`src/core/imu_integration.cpp`。
| 符号 | 作用 |
|---|---|
| `skew(v)` / `exp_so3(v)` / `log_so3(q)` | 反对称矩阵、旋转向量 ⇄ 四元数 |
| `compose(a, b)` / `inverse(p)` | 位姿复合与求逆 |
| `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()` 把 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 { namespace field_localization::core {
// Versioned little-endian scalar encoding; never serializes Eigen object memory. // Versioned little-endian scalar encoding; never serializes Eigen object memory.
void write_cloud(const PointCloud &cloud,const std::filesystem::path &path); void write_cloud(const PointCloud &cloud,const std::filesystem::path &path);
PointCloud read_cloud(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); void write_dataset_config(const CoreOptions &options,const std::filesystem::path &path,
CoreOptions read_dataset_config(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; }; struct TrajectorySample { double time; Pose3D pose; };
std::vector<TrajectorySample> read_trajectory(const std::filesystem::path &path); std::vector<TrajectorySample> read_trajectory(const std::filesystem::path &path);
void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample); void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample);
@@ -52,7 +52,9 @@ struct CoreOptions {
Pose3D initial_pose; Pose3D initial_pose;
Pose3D base_from_imu{Eigen::Quaterniond::Identity(), Eigen::Vector3d{0,0,0.15}}; Pose3D base_from_imu{Eigen::Quaterniond::Identity(), Eigen::Vector3d{0,0,0.15}};
DeskewOptions deskew; DeskewOptions deskew;
std::optional<MapBounds> map_bounds;
}; };
inline constexpr double map_association_margin=0.20;
struct LocalizationSnapshot { struct LocalizationSnapshot {
Pose3D pose; Pose3D pose;
FilterSnapshot filter; FilterSnapshot filter;
@@ -88,7 +90,7 @@ public:
private: private:
mutable std::mutex mutex_; mutable std::mutex mutex_;
CoreOptions options_; const CoreOptions options_;
VoxelMap map_; VoxelMap map_;
double last_correction_time_{-1.0}; double last_correction_time_{-1.0};
std::optional<Pose3D> last_keyframe_; std::optional<Pose3D> last_keyframe_;
@@ -1,9 +1,19 @@
#pragma once #pragma once
#include "field_localization/core/registration.hpp" #include "field_localization/core/registration.hpp"
#include <filesystem> #include <filesystem>
#include <optional>
#include <string> #include <string>
namespace field_localization::core { 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); 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 &current); bool new_keyframe(const Pose3D &previous,const Pose3D &current);
} // namespace field_localization::core } // namespace field_localization::core
@@ -0,0 +1,60 @@
# 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);
}
```
三个函数都是纯函数,只依赖消息类型,不碰节点,所以 `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,13 @@
#include "field_localization/core/dataset.hpp" #include "field_localization/core/dataset.hpp"
#include <sensor_msgs/msg/point_cloud2.hpp> #include <sensor_msgs/msg/point_cloud2.hpp>
#include <geometry_msgs/msg/transform.hpp> #include <geometry_msgs/msg/transform.hpp>
#include <tf2_ros/buffer.hpp>
namespace rclcpp { class Node; }
namespace field_localization::ros { namespace field_localization::ros {
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg); 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); core::Pose3D from_transform(const geometry_msgs::msg::Transform &transform);
geometry_msgs::msg::Transform to_transform(const core::Pose3D &pose); geometry_msgs::msg::Transform to_transform(const core::Pose3D &pose);
} // namespace field_localization::ros } // namespace field_localization::ros
+89
View File
@@ -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)
+160
View File
@@ -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)
+25 -5
View File
@@ -43,12 +43,12 @@ void write_cloud(const PointCloud &cloud,const std::filesystem::path &path) {
write<float>(out,p.intensity); 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{}; std::ifstream in(path,std::ios::binary); std::array<char,8> magic{};
in.read(magic.data(),magic.size()); in.read(magic.data(),magic.size());
if (std::string(magic.data(),magic.size())!="FLPC0001" || read<std::uint32_t>(in)!=1) if (std::string(magic.data(),magic.size())!="FLPC0001" || read<std::uint32_t>(in)!=1)
throw std::runtime_error("unsupported cloud format"); 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); 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) 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"); throw std::runtime_error("invalid cloud size");
@@ -61,15 +61,18 @@ PointCloud read_cloud(const std::filesystem::path &path) {
} }
return cloud; 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); 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<<"FIELD_LIO_DATASET 1\ninitial_pose "; pose_fields(out,o.initial_pose);
out<<"\nbase_from_imu "; pose_fields(out,o.base_from_imu); out<<"\nbase_from_imu "; pose_fields(out,o.base_from_imu);
out<<"\nimu_from_lidar "; pose_fields(out,o.deskew.imu_from_sensor); 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<<' ' 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'; <<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; std::ifstream in(path); std::string token; int version=0;
in>>token>>version; in>>token>>version;
if (!in || token!="FIELD_LIO_DATASET" || version!=1) throw std::runtime_error("unsupported dataset"); 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; 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) 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"); 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) { void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample) {
out<<std::setprecision(17)<<sample.time<<' '; pose_fields(out,sample.pose); out<<'\n'; out<<std::setprecision(17)<<sample.time<<' '; pose_fields(out,sample.pose); out<<'\n';
@@ -2,16 +2,18 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <stdexcept>
namespace field_localization::core { namespace field_localization::core {
LocalizationCore::LocalizationCore():LocalizationCore(CoreOptions{}) {} LocalizationCore::LocalizationCore():LocalizationCore(CoreOptions{}) {}
LocalizationCore::LocalizationCore(const CoreOptions &options):options_(options),map_(options.map_resolution),filter_(options.noise) { 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; MotionState initial;
initial.pose=compose(options.initial_pose,options.base_from_imu); initial.pose=compose(options.initial_pose,options.base_from_imu);
filter_.initialize(initial); pose_=options.initial_pose; filter_.initialize(initial); pose_=options.initial_pose;
} }
bool LocalizationCore::load_map(const std::filesystem::path &path,std::string &error) { 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; if (!map) return false;
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
map_=std::move(*map); status_.map_point_count=map_.size(); return true; map_=std::move(*map); status_.map_point_count=map_.size(); return true;
@@ -23,7 +25,8 @@ bool LocalizationCore::export_map(const std::filesystem::path &path,std::string
} }
void LocalizationCore::set_map_points(std::span<const Eigen::Vector3d> points) { void LocalizationCore::set_map_points(std::span<const Eigen::Vector3d> points) {
std::lock_guard<std::mutex> lock(mutex_); 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(); status_.map_point_count=map_.size();
} }
LocalizationSnapshot LocalizationCore::get_snapshot() const { LocalizationSnapshot LocalizationCore::get_snapshot() const {
@@ -150,10 +153,20 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
if (end>a->timestamp_sec && !at_scan.propagate(*a,*finish)) { if (end>a->timestamp_sec && !at_scan.propagate(*a,*finish)) {
status_.reason=FailureReason::IMU_GAP; return true; 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 (map_.size()<5) {
if (options_.map_mode==MapMode::MAPPING && corrected->points.size()>=options_.registration.minimum_inliers) { if (options_.map_mode==MapMode::MAPPING) {
map_.insert(voxel_downsample(*corrected,options_.map_resolution), const auto points=map_scan(predicted_sensor);
compose(at_scan.snapshot().state.pose,options_.deskew.imu_from_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)); last_keyframe_=compose(at_scan.snapshot().state.pose,inverse(options_.base_from_imu));
status_.keyframe_count=1; status_.map_point_count=map_.size(); status_.keyframe_count=1; status_.map_point_count=map_.size();
status_.reason=FailureReason::INITIALIZING; status_.reason=FailureReason::INITIALIZING;
@@ -161,7 +174,10 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
return true; return true;
} }
status_.registration_prediction=at_scan.snapshot(); 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); at_scan.snapshot(),options_.noise,options_.registration);
status_.registration=registration; status_.registration=registration;
status_.registration_residual_available=registration.residual_available; status_.registration_residual_available=registration.residual_available;
@@ -191,9 +207,12 @@ bool LocalizationCore::process_point_cloud(const PointCloud &cloud) {
const Pose3D scan_base=compose(registration.estimate.state.pose,inverse(options_.base_from_imu)); const Pose3D scan_base=compose(registration.estimate.state.pose,inverse(options_.base_from_imu));
if (options_.map_mode==MapMode::MAPPING && registration.degeneracy.dimensions==0 && if (options_.map_mode==MapMode::MAPPING && registration.degeneracy.dimensions==0 &&
(!last_keyframe_ || new_keyframe(*last_keyframe_,scan_base))) { (!last_keyframe_ || new_keyframe(*last_keyframe_,scan_base))) {
map_.insert(voxel_downsample(*corrected,options_.map_resolution), const auto posterior_sensor=map_from_sensor_at(registration.estimate.state.pose);
compose(registration.estimate.state.pose,options_.deskew.imu_from_sensor)); const auto points=map_scan(posterior_sensor);
last_keyframe_=scan_base; ++status_.keyframe_count; status_.map_point_count=map_.size(); 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; status_.last_correction_timestamp=end; ++status_.accepted_corrections;
last_correction_time_=end; status_.mode=TrackingMode::FULL; status_.reason=FailureReason::NONE; last_correction_time_=end; status_.mode=TrackingMode::FULL; status_.reason=FailureReason::NONE;
+21 -3
View File
@@ -20,6 +20,23 @@ template<class T> T read(std::istream &in) {
return std::bit_cast<T>(bytes); 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 &current) { bool new_keyframe(const Pose3D &previous,const Pose3D &current) {
return (current.translation-previous.translation).norm()>0.5 || return (current.translation-previous.translation).norm()>0.5 ||
log_so3(previous.rotation.conjugate()*current.rotation).norm()>10*std::numbers::pi/180; 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; 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(); error.clear();
try { try {
std::ifstream in(path,std::ios::binary); 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); Eigen::Vector3d p; for (int j=0;j<3;++j) p[j]=read<double>(in);
if (!p.allFinite() || p.cwiseAbs().maxCoeff()/resolution>1e12) if (!p.allFinite() || p.cwiseAbs().maxCoeff()/resolution>1e12)
throw std::runtime_error("invalid map coordinate"); 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; return map;
} catch (const std::exception &e) { error=e.what(); return std::nullopt; } } catch (const std::exception &e) { error=e.what(); return std::nullopt; }
} }
+114
View File
@@ -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 协方差。**twist 没填,不能当速度用** |
| 发布 | `~/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 "field_localization/ros/conversion.hpp"
#include <array> #include <array>
#include <bit> #include <bit>
#include <rclcpp/rclcpp.hpp>
#include <stdexcept> #include <stdexcept>
namespace field_localization::ros { namespace field_localization::ros {
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg) { core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg) {
@@ -42,6 +43,26 @@ core::Pose3D from_transform(const geometry_msgs::msg::Transform &t) {
throw std::runtime_error("invalid TF transform"); throw std::runtime_error("invalid TF transform");
p.rotation.normalize(); return p; 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 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(); 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; 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;
@@ -12,11 +12,12 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
const auto mode=declare_parameter<std::string>("mode","localization"); const auto mode=declare_parameter<std::string>("mode","localization");
if (mode!="mapping" && mode!="localization") throw std::invalid_argument("mode must be mapping or 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_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",""); 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" && map_path_.empty()) throw std::invalid_argument("localization requires map_path; run explicit mapping first");
if (mode=="localization") { if (mode=="localization") {
std::string error; 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); publish_map_to_odom_=declare_parameter<bool>("publish_map_to_odom",true);
auto &pose=core_options_.initial_pose; auto &pose=core_options_.initial_pose;
@@ -107,7 +108,14 @@ bool LocalizationNode::ensure_core() {
if (core_) return true; if (core_) return true;
try { try {
core_options_.base_from_imu=from_transform(tf_buffer_->lookupTransform(base_frame_,imu_frame_,tf2::TimePointZero).transform); 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_); core_=std::make_unique<core::LocalizationCore>(core_options_);
if (core_options_.map_mode==core::MapMode::LOCALIZATION) { 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); } 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) { void LocalizationNode::on_point_cloud(sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
if (!check_clock() || !ensure_core()) return; if (!check_clock() || !ensure_core()) return;
try { try {
auto cloud=convert_cloud(*msg); const auto &frame=msg->header.frame_id;
if (cloud.frame_id!=lidar_frame_ && cloud.frame_id!=base_frame_ && cloud.frame_id!=imu_frame_) if (frame!=lidar_frame_ && frame!=base_frame_ && frame!=imu_frame_)
throw std::runtime_error("unexpected cloud frame; configure lidar_frame explicitly"); 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); const auto &target=core_options_.deskew.timing==core::ScanTiming::AZIMUTH ? lidar_frame_ : imu_frame_;
for (auto &p:cloud.points) p.position=(extrinsic.rotation*p.position.cast<double>()+extrinsic.translation).cast<float>(); auto cloud=convert_cloud_in_frame(*msg,target,*tf_buffer_);
cloud.frame_id=lidar_frame_;
if (scans_.size()>=5) { scans_.pop_front(); RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"scan queue overflow"); } 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(); 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()); } } catch (const std::exception &e) { RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"cloud rejected: %s",e.what()); }
+107
View File
@@ -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)
+12 -7
View File
@@ -17,6 +17,8 @@ public:
if (!std::isfinite(duration_) || duration_<=0) throw std::runtime_error("invalid duration"); 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.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_.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"); std::filesystem::create_directories(directory_/"clouds");
imu_.open(directory_/"imu.csv"); scans_.open(directory_/"scans.csv"); truth_.open(directory_/"truth.tum"); 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); 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"), 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) { rclcpp::QoS(20).reliable(),[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
if (!ready_ || done_) return; if (!ready_ || done_) return;
auto cloud=ros::convert_cloud(*msg); const auto stamp=rclcpp::Time(msg->header.stamp).seconds();
if (cloud.timestamp_sec<start_ || cloud.timestamp_sec<=last_scan_ || cloud.timestamp_sec>start_+duration_) return; if (stamp<start_ || stamp<=last_scan_ || stamp>start_+duration_) return;
const auto tf=ros::from_transform(buffer_->lookupTransform("lidar_link",cloud.frame_id,tf2::TimePointZero).transform); core::PointCloud cloud;
for (auto &p:cloud.points) p.position=(tf.rotation*p.position.cast<double>()+tf.translation).cast<float>(); try {
cloud.frame_id="lidar_link"; 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); 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; scans_<<cloud.timestamp_sec<<','<<file<<'\n'; scans_.flush(); last_scan_=cloud.timestamp_sec;
}); });
@@ -41,9 +47,8 @@ public:
if (!ready_) { if (!ready_) {
try { try {
config_.base_from_imu=ros::from_transform(buffer_->lookupTransform("base_link","imu_link",tf2::TimePointZero).transform); 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; } } 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_); RCLCPP_INFO(get_logger(),"recording started at sim %.3f for %.1f sec",start_,duration_);
} }
if (t>start_+duration_+0.1) { imu_complete_=true; return; } if (t>start_+duration_+0.1) { imu_complete_=true; return; }
+7 -4
View File
@@ -26,7 +26,8 @@ int main(int argc,char **argv) {
if (!args.contains("--dataset") || !args.contains("--mode") || !args.contains("--map") || !args.contains("--output")) 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]"); 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"); 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"); 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; 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")); 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"); throw std::runtime_error("--inspect-scan requires localization with instantaneous scans and truth.tum");
inspect_time=std::stod(args.at("--inspect-scan")); inspect_time=std::stod(args.at("--inspect-scan"));
if (!std::isfinite(*inspect_time)) throw std::runtime_error("invalid scan timestamp"); 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); if (!inspect_map) throw std::runtime_error(error);
} }
bool inspected=false; 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 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)); 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"); 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)) { 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"); 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 &prediction=diagnostic.status.registration_prediction.state;
const auto corrected=deskew(cloud,std::array{prediction},options.deskew); const auto corrected=deskew(cloud,std::array{prediction},options.deskew);
if (!corrected) throw std::runtime_error("failed to prepare instantaneous scan"); 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); map_from_imu,options.registration);
const auto error_xyz=prediction.pose.translation-map_from_imu.translation; const auto error_xyz=prediction.pose.translation-map_from_imu.translation;
std::cout<<std::setprecision(12)<<"scan="<<cloud.timestamp_sec std::cout<<std::setprecision(12)<<"scan="<<cloud.timestamp_sec
+153
View File
@@ -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
+13 -1
View File
@@ -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_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()); 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}; 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.initial_pose.translation==options.initial_pose.translation);
CHECK(config.deskew.imu_from_sensor.translation==options.deskew.imu_from_sensor.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; std::vector<TrajectorySample> truth,estimate;
for (int i=0;i<=200;++i) { 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}}; 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}};
@@ -2,6 +2,7 @@
#include "test_util.hpp" #include "test_util.hpp"
#include <fstream> #include <fstream>
#include <iterator> #include <iterator>
#include <limits>
#include <numbers> #include <numbers>
using namespace field_localization::core; using namespace field_localization::core;
namespace { namespace {
@@ -51,6 +52,37 @@ int main() {
CHECK(!localization.load_map(folder/"broken.flmap",error)); CHECK(!error.empty()); CHECK(!localization.load_map(folder/"broken.flmap",error)); CHECK(!error.empty());
CHECK(localization.get_status().map_point_count==count); CHECK(localization.get_status().map_point_count==count);
CHECK(!localization.load_map(folder/"missing.flmap",error)); 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); mapping.reset(); CHECK(mapping.get_status().map_point_count==0);
localization.reset(); CHECK(localization.get_status().map_point_count==count); localization.reset(); CHECK(localization.get_status().map_point_count==count);
std::filesystem::remove_all(folder); std::filesystem::remove_all(folder);
@@ -2,6 +2,7 @@
#include "test_util.hpp" #include "test_util.hpp"
#include <array> #include <array>
#include <bit> #include <bit>
#include <numbers>
using namespace field_localization; using namespace field_localization;
int main() { int main() {
sensor_msgs::msg::PointCloud2 msg; msg.width=2; msg.height=2; msg.point_step=16; msg.row_step=40; sensor_msgs::msg::PointCloud2 msg; msg.width=2; msg.height=2; msg.point_step=16; msg.row_step=40;
@@ -24,5 +25,32 @@ int main() {
const auto recovered=core::compose(ros::from_transform(ros::to_transform(map_from_odom)),odom_from_base); 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((recovered.translation-map_from_base.translation).norm()<1e-12);
CHECK(core::log_so3(recovered.rotation.conjugate()*map_from_base.rotation).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);
}
return sentry_nav_test::Summary("RosConversion"); return sentry_nav_test::Summary("RosConversion");
} }
@@ -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。 // 自滤参数。单位统一为米,坐标系为 base_link。
struct FilterParams { struct FilterParams {
// Keep the lateral limits close to the chassis (y +/-0.2605 m). Gazebo // 云台 yaw 可以 360° 连续转,所以剔除盒必须覆盖**旋转组扫掠圆**,
// 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. // 扫掠半径 0.3021 m = 旋转组最远角 √(0.2656² + 0.1439²),yaw 轴在车体中心。
float box_min_x = -0.294f; // 旋转组的包络来自 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_max_x = 0.365f;
float box_min_y = -0.2655f; float box_min_y = -0.305f;
float box_max_y = 0.2655f; float box_max_y = 0.305f;
float box_min_z = -0.05f; float box_min_z = -0.05f;
float box_max_z = 0.545f; float box_max_z = 0.545f;
float keep_min_z = 0.02f; // 低于此高度视为地面/噪声 float keep_min_z = 0.02f; // 低于此高度视为地面/噪声
float max_range = 12.0f; // 水平距离上限 float keep_max_z = 1.20f; // 与代价地图的观测高度一致,顶棚不参与避障
float max_range = 8.0f; // 导航输入的水平距离上限
}; };
// 丢弃原因。kNone 表示保留。 // 丢弃原因。kNone 表示保留。
@@ -42,6 +48,7 @@ enum class DropReason {
kNonFinite, // NaN 或 inf kNonFinite, // NaN 或 inf
kTooFar, // 水平距离超过 max_range kTooFar, // 水平距离超过 max_range
kTooLow, // 低于 keep_min_z kTooLow, // 低于 keep_min_z
kTooHigh, // 高于 keep_max_z
kInsideEgoBox, // 落在车身包围盒内(自身回波) kInsideEgoBox, // 落在车身包围盒内(自身回波)
}; };
@@ -22,6 +22,9 @@ DropReason SelfFilterCore::Classify(float x, float y, float z) const {
if (z < params_.keep_min_z) { if (z < params_.keep_min_z) {
return DropReason::kTooLow; return DropReason::kTooLow;
} }
if (z > params_.keep_max_z) {
return DropReason::kTooHigh;
}
// 车身包围盒内的点就是自身回波,剔除。 // 车身包围盒内的点就是自身回波,剔除。
// 注意用的是严格不等号:正好落在盒面上的点算保留。 // 注意用的是严格不等号:正好落在盒面上的点算保留。
if (x > params_.box_min_x && x < params_.box_max_x && if (x > params_.box_min_x && x < params_.box_max_x &&
@@ -42,6 +45,8 @@ const char* ToString(DropReason reason) {
return "too_far"; return "too_far";
case DropReason::kTooLow: case DropReason::kTooLow:
return "too_low"; return "too_low";
case DropReason::kTooHigh:
return "too_high";
case DropReason::kInsideEgoBox: case DropReason::kInsideEgoBox:
return "inside_ego_box"; return "inside_ego_box";
} }
+20 -11
View File
@@ -20,20 +20,22 @@
// input_topic /scan/points // input_topic /scan/points
// output_topic /scan/points_filtered // output_topic /scan/points_filtered
// target_frame base_link // target_frame base_link
// box_min_x -0.40 车身包围盒(车身 x±0.288、y±0.26,留 ~10 cm 余量) // box_min_x -0.305 车身/云台扫掠包围盒(云台可 360° 转,
// box_max_x 0.40 // box_max_x 0.365 取旋转组扫掠半径 0.3021 m + 3 mm 余量;
// box_min_y -0.38 // box_min_y -0.305 box_max_x 保留 0.365 以维持原有前向包络过滤;
// box_max_y 0.38 // box_max_y 0.305 实际默认值在 self_filter_core.hpp 的 FilterParams)
// box_min_z -0.05 // box_min_z -0.05
// box_max_z 0.60 // box_max_z 0.545
// keep_min_z 0.02 剔除后仍要保留的最低高度(低于此视为地面/噪声) // 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_topic /scan2d 投影出的 2D 激光话题(给 AMCL;也喂 collision_monitor)
// scan_bins 360 方位角分格数(360 = 每度一格) // scan_bins 360 方位角分格数(360 = 每度一格)
// scan_height_min 0.05 参与投影的最低高度(base_link 系,m) // scan_height_min 0.05 参与投影的最低高度(base_link 系,m)
// scan_height_max 0.50 参与投影的最高高度(base_link 系,m) // scan_height_max 0.50 参与投影的最高高度(base_link 系,m)
// scan_range_min 0.10 激光最小距离(m) // scan_range_min 0.10 激光最小距离(m)
// scan_range_max 12.0 激光最大距离(m) // scan_range_max 8.0 投影激光最大距离(m)
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
@@ -85,6 +87,8 @@ public:
declare_parameter<double>("box_max_z", params.box_max_z)); declare_parameter<double>("box_max_z", params.box_max_z));
params.keep_min_z = static_cast<float>( params.keep_min_z = static_cast<float>(
declare_parameter<double>("keep_min_z", params.keep_min_z)); 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>( params.max_range = static_cast<float>(
declare_parameter<double>("max_range", params.max_range)); declare_parameter<double>("max_range", params.max_range));
@@ -96,11 +100,13 @@ public:
} }
auto lio_params = params; auto lio_params = params;
lio_params.keep_min_z = static_cast<float>(declare_parameter<double>("lio_keep_min_z", -0.25)); 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. // 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_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_core_ = std::make_unique<sentry_nav::SelfFilterCore>(lio_params);
lio_pub_ = create_publisher<sensor_msgs::msg::PointCloud2>(lio_topic, rclcpp::QoS(5).reliable()); 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()); 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_min_ = declare_parameter<double>("scan_height_min", 0.05);
scan_height_max_ = declare_parameter<double>("scan_height_max", 0.50); scan_height_max_ = declare_parameter<double>("scan_height_max", 0.50);
scan_range_min_ = declare_parameter<double>("scan_range_min", 0.10); 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)); scan_pub_ = create_publisher<sensor_msgs::msg::LaserScan>(scan_topic_, rclcpp::QoS(10));
RCLCPP_INFO( RCLCPP_INFO(
@@ -145,7 +151,10 @@ private:
{ {
sensor_msgs::msg::PointCloud2 cloud_in_target; sensor_msgs::msg::PointCloud2 cloud_in_target;
try { 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( geometry_msgs::msg::TransformStamped tf = tf_buffer_->lookupTransform(
target_frame_, msg->header.frame_id, msg->header.stamp, target_frame_, msg->header.frame_id, msg->header.stamp,
rclcpp::Duration::from_seconds(0.2)); rclcpp::Duration::from_seconds(0.2));
@@ -266,7 +275,7 @@ private:
double scan_height_min_{0.05}; double scan_height_min_{0.05};
double scan_height_max_{0.50}; double scan_height_max_{0.50};
double scan_range_min_{0.10}; 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::unique_ptr<tf2_ros::Buffer> tf_buffer_;
std::shared_ptr<tf2_ros::TransformListener> tf_listener_; std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
+31 -8
View File
@@ -36,12 +36,21 @@ int main() {
EXPECT_TRUE(filter.Keep(2.0f, 0.0f, 0.02f)); // 正好等于阈值 -> 保留 EXPECT_TRUE(filter.Keep(2.0f, 0.0f, 0.02f)); // 正好等于阈值 -> 保留
// ---------- 4. 太远的点必须剔除(用的是水平距离)---------- // ---------- 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(12.5f, 0.0f, 0.30f), DropReason::kTooFar);
EXPECT_EQ(filter.Classify(9.0f, 9.0f, 0.30f), DropReason::kTooFar); // 水平 12.73 m 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)); EXPECT_TRUE(filter.Keep(7.9f, 0.0f, 0.30f));
// 水平刚好 12.0 不算「大于」,保留 // 水平刚好 8.0 不算「大于」,保留
EXPECT_TRUE(filter.Keep(12.0f, 0.0f, 0.30f)); 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); EXPECT_EQ(filter.Classify(20.0f, 0.0f, 9.0f), DropReason::kTooFar);
@@ -57,16 +66,30 @@ int main() {
// ---------- 6. 边界:盒面用严格不等号,落在面上算保留 ---------- // ---------- 6. 边界:盒面用严格不等号,落在面上算保留 ----------
EXPECT_TRUE(filter.Keep(0.365f, 0.0f, 0.30f)); // x == box_max_x 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.305f, 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.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_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.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_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_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); 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. 自定义参数的构造函数确实生效 ---------- // ---------- 7. 自定义参数的构造函数确实生效 ----------
FilterParams small; FilterParams small;
small.max_range = 3.0f; small.max_range = 3.0f;
@@ -76,7 +99,7 @@ int main() {
EXPECT_TRUE(strict.Keep(2.9f, 0.0f, 0.30f)); EXPECT_TRUE(strict.Keep(2.9f, 0.0f, 0.30f));
EXPECT_FALSE(strict.Keep(2.0f, 0.0f, 0.05f)); // 低于 0.10 EXPECT_FALSE(strict.Keep(2.0f, 0.0f, 0.05f)); // 低于 0.10
EXPECT_NEAR(strict.squared_max_range(), 9.0f, 1e-6); 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 不返回空 ---------- // ---------- 8. ToString 不返回空 ----------
EXPECT_TRUE(sentry_nav::ToString(DropReason::kInsideEgoBox) != nullptr); EXPECT_TRUE(sentry_nav::ToString(DropReason::kInsideEgoBox) != nullptr);
+1 -1
View File
@@ -80,7 +80,7 @@ cd ~/Gazebo_projects/sentry_nav_dev && scripts/sentry_up.sh
| 传感器 | 位置/参数 | 话题 | | 传感器 | 位置/参数 | 话题 |
|---|---|---| |---|---|---|
| 3D 激光雷达(OGRE2) | 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`) | | 点云自滤 | 剔除车身包围盒内回波 | 输入 `/scan/points` → 输出 `/scan/points_filtered`(frame=`base_link`) |
| 2D 激光(定位用) | 由自滤节点从 3D 点云投影:z∈[0.05, 0.50] m、360 格 | `/scan2d`(frame=`base_link`,AMCL / collision_monitor 用) | | 2D 激光(定位用) | 由自滤节点从 3D 点云投影:z∈[0.05, 0.50] m、360 格 | `/scan2d`(frame=`base_link`,AMCL / collision_monitor 用) |
| IMU | `imu_link`,100 Hz | gz `imu` → `/imu` | | IMU | `imu_link`,100 Hz | gz `imu` → `/imu` |
+6 -4
View File
@@ -3,18 +3,20 @@
| 文件 | 说明 | | 文件 | 说明 |
|---|---| |---|---|
| `nav2_params.yaml` | Nav2 全部参数(代价地图、MPPI 控制器、AMCL、行为树…) | | `nav2_params.yaml` | Nav2 全部参数(代价地图、MPPI 控制器、AMCL、行为树…) |
| `field_cloud.yaml` | 建图、定位与录制共用的比赛场地 XYZ 裁剪范围 |
| `sentry.rviz` | RViz 布局(Map / LaserScan / TF / Costmap 已配好) | | `sentry.rviz` | RViz 布局(Map / LaserScan / TF / Costmap 已配好) |
## nav2_params.yaml 里改过的关键项 ## nav2_params.yaml 里改过的关键项
| 参数 | 值 | 为什么 | | 参数 | 值 | 为什么 |
|---|---|---| |---|---|---|
| `footprint` | `[[0.325,0.270],[0.325,-0.270],[-0.325,-0.270],[-0.325,0.270]]` | 车体 0.578×0.521 实测 | | `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.45`(默认 0.70 会把 12×8 场地填死) | 场地太小 | | `inflation_radius` | `0.60`(默认 0.70 会把 12×8 场地填死;0.45 太贴障碍) | 场地太小 + 矩形底盘要留转向余量 |
| `consider_footprint` | `true` | 与矩形 footprint 对齐,否则 MPPI 判碰撞不一致 | | `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 | | `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 建树失败 | | `default_server_timeout` / `wait_for_service_timeout` | `15000` | 本机启动慢,否则 BT 建树失败 |
| local costmap `plugins` | 只有 `inflation_layer` | 2D 雷达会扫到车身自身,参与代价地图会把自己围死 | | local costmap `plugins` | `static_layer`、`voxel_layer`、`inflation_layer` | 静态栅格和自滤后的实时点云 |
| global costmap `plugins` | `static_layer` + `inflation_layer` | 场地是静态的,用地图就够 | | global costmap `plugins` | `static_layer`、`obstacle_layer`、`inflation_layer` | 使用同一份自滤点云处理动态障碍 |
| 障碍标记 / 清障距离 | 4.5 m / 8 m | 避障距离独立于原始雷达的 40 m 量程 |
> 改之前先看一眼注释,里面写了每处的原因。 > 改之前先看一眼注释,里面写了每处的原因。
+4
View File
@@ -0,0 +1,4 @@
/**:
ros__parameters:
map_crop_min: [-6.4, -4.4, -0.10]
map_crop_max: [6.4, 4.4, 0.65]
+5 -5
View File
@@ -13,7 +13,7 @@ amcl:
global_frame_id: "map" global_frame_id: "map"
lambda_short: 0.1 lambda_short: 0.1
laser_likelihood_max_dist: 2.0 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_min_range: 0.15 # 自击点已被 self_filter 在投影时剔除,不用靠 0.6 遮挡
laser_model_type: "likelihood_field" laser_model_type: "likelihood_field"
max_beams: 60 max_beams: 60
@@ -275,7 +275,7 @@ local_costmap:
width: 6 width: 6
height: 6 height: 6
resolution: 0.05 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 的 3D 点云已接入(/scan/points,PointCloud2)
# MID-360 点云经 sentry_nav/self_filter 自滤(剔除车身包围盒内的点)后接入 # MID-360 点云经 sentry_nav/self_filter 自滤(剔除车身包围盒内的点)后接入
# Retain known thin/occluded geometry when the live cloud sparsely samples it. # Retain known thin/occluded geometry when the live cloud sparsely samples it.
@@ -298,7 +298,7 @@ local_costmap:
obstacle_min_range: 0.20 obstacle_min_range: 0.20
obstacle_max_range: 4.5 obstacle_max_range: 4.5
raytrace_min_range: 0.20 raytrace_min_range: 0.20
raytrace_max_range: 12.0 raytrace_max_range: 8.0
clearing: True clearing: True
marking: True marking: True
filters: ["keepout_filter"] filters: ["keepout_filter"]
@@ -325,7 +325,7 @@ global_costmap:
publish_frequency: 1.0 publish_frequency: 1.0
global_frame: map global_frame: map
robot_base_frame: base_link 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 resolution: 0.05
track_unknown_space: true track_unknown_space: true
plugins: ["static_layer", "obstacle_layer", "inflation_layer"] plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
@@ -341,7 +341,7 @@ global_costmap:
obstacle_min_range: 0.20 obstacle_min_range: 0.20
obstacle_max_range: 4.5 obstacle_max_range: 4.5
raytrace_min_range: 0.20 raytrace_min_range: 0.20
raytrace_max_range: 12.0 raytrace_max_range: 8.0
clearing: True clearing: True
marking: True marking: True
filters: ["keepout_filter", "speed_filter"] filters: ["keepout_filter", "speed_filter"]
@@ -289,6 +289,8 @@ def generate_launch_description():
'robot_description': ParameterValue( 'robot_description': ParameterValue(
robot_description, value_type=str), robot_description, value_type=str),
'use_sim_time': True, 'use_sim_time': True,
# Resolve LiDAR TF at the scan stamp during fast gimbal motion.
'publish_frequency': 100.0,
}], }],
), ),
@@ -321,6 +323,7 @@ def generate_launch_description():
ExecuteProcess( ExecuteProcess(
cmd=[PathJoinSubstitution([BIN_DIR, 'field_localization_node']), '--ros-args', 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', 'use_sim_time:=true', '-p', 'reliable_clouds:=true',
'-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')], '-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')],
'-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map], '-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map],
Binary file not shown.
+22 -5
View File
@@ -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 万 | | `wheel.stl` | 单个麦轮(四个轮子几何相同) | 约 3.1 万 |
| `transform.json` | 旧版(底盘+云台分别导入)的转换参数,仅作参考 | | `transform.json` | 旧版(底盘+云台分别导入)的转换参数,仅作参考 |
| `gimbal_transform.json` | 同上,云台那套的转换参数 | | `gimbal_transform.json` | ⚠️ **过期**:上一次拆分尝试留下的参数,它的原点取的是 GM6020 电机轴(偏 89.9 mm),不是 yaw 轴。以 `full/vehicle_layout.json` 的 `yaw_axis_ros_xy_m` 为准 |
| `full/` | 原始高模 + 装配体实测布局,见其 README | | `full/` | 原始高模 + 装配体实测布局,见其 README |
## 坐标系 ## 坐标系
@@ -15,12 +16,28 @@
已转到 REP-103(X 前、Y 左、Z 上),原点 = 车体几何中心的地面投影。 已转到 REP-103(X 前、Y 左、Z 上),原点 = 车体几何中心的地面投影。
SW 装配体是 Y 向上:`ROS_x = SW_z`、`ROS_y = SW_x`、`ROS_z = SW_y`;车头 = +SW_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 ```bash
python3 tools/build_vehicle.py --src "<SW导出目录>" --out src/sentry_sim/meshes/full 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/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/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 秒甚至起不来。 > ⚠️ 不减面的话,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.
+24 -2
View File
@@ -44,7 +44,29 @@
0.082 0.082
], ],
"yaw_axis_ros_xy_m": [ "yaw_axis_ros_xy_m": [
0.08986, -0.00015,
-0.00017 -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.
+95 -32
View File
@@ -2,15 +2,15 @@
<model name="sentry"> <model name="sentry">
<link name="base_link"> <link name="base_link">
<inertial> <inertial>
<pose>-0.0011065088757396451 -0.001789349112426035 0.18260591715976329 0 0 0</pose> <pose>0 0 0.17994011976047911 0 0 0</pose>
<mass>25.350000000000001</mass> <mass>25.050000000000001</mass>
<inertia> <inertia>
<ixx>1.108330048903353</ixx> <ixx>1.0863903268463071</ixx>
<ixy>-0.00419096875739645</ixy> <ixy>0</ixy>
<ixz>0.0062437640236686397</ixz> <ixz>0</ixz>
<iyy>1.234650669205128</iyy> <iyy>1.2168965768463069</iyy>
<iyz>0.010096867597633129</iyz> <iyz>0</iyz>
<izz>1.2710893212169621</izz> <izz>1.2615204166666669</izz>
</inertia> </inertia>
</inertial> </inertial>
<collision name="base_link_fixed_joint_lump__chassis_collision_collision"> <collision name="base_link_fixed_joint_lump__chassis_collision_collision">
@@ -21,14 +21,6 @@
</box> </box>
</geometry> </geometry>
</collision> </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> <pose>0 0 0 0 0 0</pose>
<geometry> <geometry>
@@ -42,18 +34,6 @@
<ambient>0.187500015 0.187500015 0.212500006 1</ambient> <ambient>0.187500015 0.187500015 0.212500006 1</ambient>
</material> </material>
</visual> </visual>
<visual name="base_link_fixed_joint_lump__lidar_link_visual_1">
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose>
<geometry>
<box>
<size>0.084000000000000005 0.068000000000000005 0.082000000000000003</size>
</box>
</geometry>
<material>
<diffuse>0.125 0.3125 0.75000006 1</diffuse>
<ambient>0.125 0.3125 0.75000006 1</ambient>
</material>
</visual>
<sensor name="imu" type="imu"> <sensor name="imu" type="imu">
<topic>imu</topic> <topic>imu</topic>
<update_rate>100</update_rate> <update_rate>100</update_rate>
@@ -62,6 +42,74 @@
<gz_frame_id>imu_link</gz_frame_id> <gz_frame_id>imu_link</gz_frame_id>
<imu /> <imu />
</sensor> </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.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>
<diffuse>0.125 0.3125 0.75000006 1</diffuse>
<ambient>0.125 0.3125 0.75000006 1</ambient>
</material>
</visual>
<sensor name="lidar" type="gpu_lidar"> <sensor name="lidar" type="gpu_lidar">
<topic>scan</topic> <topic>scan</topic>
<update_rate>10</update_rate> <update_rate>10</update_rate>
@@ -84,7 +132,7 @@
</scan> </scan>
<range> <range>
<min>0.10000000000000001</min> <min>0.10000000000000001</min>
<max>12</max> <max>40</max>
<resolution>0.01</resolution> <resolution>0.01</resolution>
</range> </range>
<noise> <noise>
@@ -93,7 +141,7 @@
<stddev>0.01</stddev> <stddev>0.01</stddev>
</noise> </noise>
</lidar> </lidar>
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose> <pose>-0.0935 -0.1512 0.28649999999999998 0 0 0</pose>
<gz_frame_id>lidar_link</gz_frame_id> <gz_frame_id>lidar_link</gz_frame_id>
</sensor> </sensor>
</link> </link>
@@ -383,14 +431,29 @@
<odom_publish_frequency>50</odom_publish_frequency> <odom_publish_frequency>50</odom_publish_frequency>
<frame_id>odom</frame_id> <frame_id>odom</frame_id>
</plugin> </plugin>
<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"> <frame name="imu_joint" attached_to="base_link">
<pose>0 0 0.14999999999999999 0 0 0</pose> <pose>0 0 0.14999999999999999 0 0 0</pose>
</frame> </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> <pose>0 0 0 0 0 0</pose>
</frame> </frame>
<frame name="lidar_joint" attached_to="base_link"> <frame name="lidar_joint" attached_to="gimbal_yaw_link">
<pose>-0.0935 -0.1512 0.4052 0 0 0</pose> <pose>-0.0935 -0.1512 0.28649999999999998 0 0 0</pose>
</frame> </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> <pose>0 0 0 0 0 0</pose>
@@ -21,4 +21,5 @@ exec ros2 run ros_gz_bridge parameter_bridge \
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \ '/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \ '/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \ '/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 --ros-args -p use_sim_time:=true
+3 -2
View File
@@ -249,6 +249,7 @@ ros2 run ros_gz_bridge parameter_bridge \
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \ '/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \ '/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \ '/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 & --ros-args -p use_sim_time:=true &
PIDS+=($!) PIDS+=($!)
@@ -261,7 +262,7 @@ ROBOT_PARAMS_DIR="$(mktemp -d "$runtime_dir/sentry-robot.XXXXXXXX")"
python3 "$INTERNAL_TOOLS/robot_description.py" runtime-params "$PKG_SHARE" \ python3 "$INTERNAL_TOOLS/robot_description.py" runtime-params "$PKG_SHARE" \
"$ROBOT_PARAMS_DIR/robot_state_publisher.json" "$ROBOT_PARAMS_DIR/robot_state_publisher.json"
ros2 run robot_state_publisher robot_state_publisher --ros-args \ ros2 run robot_state_publisher robot_state_publisher --ros-args \
--params-file "$ROBOT_PARAMS_DIR/robot_state_publisher.json" & --params-file "$ROBOT_PARAMS_DIR/robot_state_publisher.json" -p publish_frequency:=100.0 &
PIDS+=($!) PIDS+=($!)
# ---------- 5. odom -> base_link ---------- # ---------- 5. odom -> base_link ----------
@@ -291,7 +292,7 @@ PIDS+=($!)
# ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ---------- # ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ----------
if [ "$LOCALIZATION" = lio ]; then if [ "$LOCALIZATION" = lio ]; then
echo "[sentry_up] LIO mode=$LIO_MODE map=$LIO_MAP cloud=$LIO_POINT_CLOUD_TOPIC (AMCL disabled)" 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 "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 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:-}'" \ -p publish_map_to_odom:=true -p "diagnostics_path:='${LIO_TRACE_PATH:-}'" \
+208 -7
View File
@@ -5,12 +5,40 @@
## 结构 ## 结构
``` ```
base_link(车体 + 云台 + 悬挂 + MID-360 外形,整体刚体) base_link(底盘 + 悬挂)
├── wheel_fl / wheel_fr / wheel_bl / wheel_br revolute 关节,轴 = Y(横向) ├── wheel_fl / wheel_fr / wheel_bl / wheel_br revolute 关节,轴 = Y(横向)
├── lidar_link fixed,位置 = MID-360 实测位置 ├── imu_link fixed —— 底盘 IMU,不跟云台转
└── imu_link fixed └── 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) | 装配体实测 | | `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_l/w/h` | 0.578 / 0.521 / 0.500 | 装配体 bbox |
| `body_mass` / `wheel_mass` | 25.0 / 1.5 kg | ⚠️ **估算,待机械提供** | | `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 点云 | | 雷达垂直视场 | **−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,原点在车体中心的地面投影 - **车头 = +X**(相机/枪口侧),左 = +Y,上 = +Z,原点在车体中心的地面投影
- 云台做成刚体(导航不需要它转)。要做自瞄时再用 - 云台是**可 360° 连续转的独立 link**。网格用 `tools/build_vehicle.py` 的
`tools/build_vehicle.py --split-gimbal` 拆 yaw/pitch `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,5 +207,36 @@ cd ~/Gazebo_projects/sentry_nav_dev
scripts/sentry_up.sh # 重启仿真(数据包不用编译) scripts/sentry_up.sh # 重启仿真(数据包不用编译)
``` ```
改完 `gen_sdf.sh` 会打印 `Valid.` 并用 `gz sdf -k` 校验。校验不过它不会替换产物。
网格路径通过 xacro 的 `mesh_prefix` 参数设置。生成器分别按 URDF 和 SDF 所在目录填写相对引用。 网格路径通过 xacro 的 `mesh_prefix` 参数设置。生成器分别按 URDF 和 SDF 所在目录填写相对引用。
启动器在发布 ROS 机器人描述时为 RViz 解析网格 URI。 启动器在发布 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` 里的相对路径也是相对它写的 —— 这属于同一批陈旧状态,一并清掉即可。
+118 -14
View File
@@ -44,11 +44,36 @@
<xacro:property name="lidar_x" value="-0.0935"/> <xacro:property name="lidar_x" value="-0.0935"/>
<xacro:property name="lidar_y" value="-0.1512"/> <xacro:property name="lidar_y" value="-0.1512"/>
<xacro:property name="lidar_z" value="0.4052"/> <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="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> <material name="rm_blue"><color rgba="0.10 0.25 0.60 1"/></material>
<!-- ================= 车体(含云台,刚体) ================= --> <!-- ================= 车体(底盘;云台已拆成 gimbal_yaw_link) ================= -->
<link name="base_link"> <link name="base_link">
<visual> <visual>
<origin xyz="0 0 0" rpy="0 0 0"/> <origin xyz="0 0 0" rpy="0 0 0"/>
@@ -57,7 +82,8 @@
</geometry> </geometry>
<material name="dark_gray"/> <material name="dark_gray"/>
</visual> </visual>
<!-- 碰撞体用两个简化盒:底盘(下半)+ 云台(上半靠前)。 <!-- 碰撞体只有底盘一个简化盒。云台的碰撞盒在 gimbal_yaw_link 上,
这样它能跟着 yaw 关节一起转。
不能用一个大盒子包住整车——MID-360 在 z=0.405,会被包在盒子内部, 不能用一个大盒子包住整车——MID-360 在 z=0.405,会被包在盒子内部,
雷达射线全打在盒子内壁上(实测距离只有 0.2~0.4 m)。 --> 雷达射线全打在盒子内壁上(实测距离只有 0.2~0.4 m)。 -->
<collision name="chassis_collision"> <collision name="chassis_collision">
@@ -69,12 +95,6 @@
<box size="${body_l} ${body_w} 0.25"/> <box size="${body_l} ${body_w} 0.25"/>
</geometry> </geometry>
</collision> </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> <inertial>
<origin xyz="0 0 0.18" rpy="0 0 0"/> <origin xyz="0 0 0.18" rpy="0 0 0"/>
<mass value="${body_mass}"/> <mass value="${body_mass}"/>
@@ -87,6 +107,51 @@
</inertial> </inertial>
</link> </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"> <xacro:macro name="wheel_link" params="name xyz">
<link name="${name}"> <link name="${name}">
@@ -133,20 +198,27 @@
<link name="lidar_link"> <link name="lidar_link">
<visual> <visual>
<geometry> <geometry>
<box size="0.084 0.068 0.082"/> <box size="${lidar_width} ${lidar_width} ${lidar_height}"/>
</geometry> </geometry>
<material name="rm_blue"/> <material name="rm_blue"/>
</visual> </visual>
<inertial> <inertial>
<origin xyz="0 0 0" rpy="0 0 0"/> <origin xyz="0 0 0" rpy="0 0 0"/>
<mass value="0.3"/> <mass value="${lidar_mass}"/>
<inertia ixx="0.00012" ixy="0" ixz="0" iyy="0.00012" iyz="0" izz="0.0002"/> <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> </inertial>
</link> </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"> <joint name="lidar_joint" type="fixed">
<parent link="base_link"/> <parent link="gimbal_yaw_link"/>
<child link="lidar_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> </joint>
<link name="imu_link"> <link name="imu_link">
@@ -193,6 +265,37 @@
<odom_publish_frequency>50</odom_publish_frequency> <odom_publish_frequency>50</odom_publish_frequency>
<frame_id>odom</frame_id> <frame_id>odom</frame_id>
</plugin> </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> </gazebo>
<!-- 3D 雷达由世界的 OGRE2 Sensors 系统渲染。 --> <!-- 3D 雷达由世界的 OGRE2 Sensors 系统渲染。 -->
@@ -222,7 +325,8 @@
</scan> </scan>
<range> <range>
<min>0.10</min> <min>0.10</min>
<max>12.0</max> <!-- Livox specifies 40 m at 10% target reflectivity. -->
<max>40.0</max>
<resolution>0.01</resolution> <resolution>0.01</resolution>
</range> </range>
<noise> <noise>
+3 -2
View File
@@ -75,8 +75,9 @@ class ArenaGrid:
return mask return mask
def coverage(self): def coverage(self):
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint. # 外接半径:footprint 现在是 0.61 x 0.61 的正方形(要覆盖云台 yaw 扫掠圆,
travel = self.clear(math.hypot(0.325, 0.270)) # 半径 0.3021 m),外接半径 = 0.305 * sqrt(2)。
travel = self.clear(math.hypot(0.305, 0.305))
start = self.cell(START) start = self.cell(START)
if not travel[start]: if not travel[start]:
raise ValueError('spawn pose fails the footprint clearance check') raise ValueError('spawn pose fails the footprint clearance check')
+12 -4
View File
@@ -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]] 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']: 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') 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 = [] clouds = []
for (x, y), (stamp, filename) in selected: for (x, y), (stamp, filename) in selected:
raw = (directory / filename).read_bytes() raw = (directory / filename).read_bytes()
@@ -72,11 +78,13 @@ def build_map(directory, selected, output):
raise ValueError(f'invalid recorded scan {filename}') raise ValueError(f'invalid recorded scan {filename}')
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24) rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
points = rows['point'][:, :3].astype(np.float64) 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 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) points = np.concatenate(clouds)
# Average measured returns that occupy the same voxel across overlapping views. # Average measured returns that occupy the same voxel across overlapping views.
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64) grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
+82 -11
View File
@@ -37,6 +37,34 @@ GIMBAL_KEYS = (
'24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ', '24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ',
'电机带轮', '拨盘带轮', 'z21胀紧', 'Z21胀紧', '电机带轮', '拨盘带轮', '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' WHEEL_MARK = '轮系-{} 装配体1-1'
@@ -45,6 +73,9 @@ def read_stl(path):
size = os.path.getsize(path) size = os.path.getsize(path)
with open(path, 'rb') as f: with open(path, 'rb') as f:
head = f.read(84) head = f.read(84)
if len(head) < 84:
# 连 84 字节的头都不完整 —— 损坏/截断的文件,当读不出处理
return None
n = struct.unpack('<I', head[80:84])[0] n = struct.unpack('<I', head[80:84])[0]
if 84 + n * 50 != size: if 84 + n * 50 != size:
return None return None
@@ -77,12 +108,53 @@ def classify(name):
for i in (1, 2, 3, 4): for i in (1, 2, 3, 4):
if WHEEL_MARK.format(i) in name: if WHEEL_MARK.format(i) in name:
return f'wheel{i}' return f'wheel{i}'
# 固定件优先:'基座装配' 这个关键字太宽,会把电机和基座板一起划进来
for key in CHASSIS_KEYS:
if key in name:
return 'base'
for key in GIMBAL_KEYS: for key in GIMBAL_KEYS:
if key in name: if key in name:
return 'gimbal' return 'gimbal'
return 'base' 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): def to_ros(tris, center_sw):
"""SW 装配体坐标 -> ROS 坐标(米)。 """SW 装配体坐标 -> ROS 坐标(米)。
@@ -171,17 +243,16 @@ def main():
ground_y, ground_y,
(all_min[2] + all_max[2]) / 2]) (all_min[2] + all_max[2]) / 2])
# yaw 轴:用 GM6020 云台电机的中心(在 gimbal 组内找) # yaw 轴:取与大带轮 / 滑环 / 云台内圈这些**同轴件**的中心,见 find_yaw_axis()。
yaw_xz = None # 不能用 GM6020 电机中心 —— 电机经 35齿小带轮 + 皮带 + 70齿大带轮 减速驱动,
for path in files: # 电机轴与 yaw 轴相差一个皮带中心距(本装配体 89.9 mm),拿电机当转轴会整圈偏移。
if 'GM6020' in os.path.basename(path): try:
tris = read_stl(path) yaw_xz, axis_count, axis_spread = find_yaw_axis(files)
if tris is None: except YawAxisError as error:
continue raise SystemExit(str(error)) from error
v = tris.reshape(-1, 3) if yaw_xz:
c = (v.min(axis=0) + v.max(axis=0)) / 2 print(f' yaw 轴由 {axis_count} 个同轴件求得'
yaw_xz = (c[0], c[2]) f'(离散 {axis_spread[0]:.2f}/{axis_spread[1]:.2f} mm)')
break
wheels_ros = {} wheels_ros = {}
for k, c_sw in wc.items(): for k, c_sw in wc.items():
+4 -1
View File
@@ -156,7 +156,10 @@ def main():
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace)) stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace))
log = open(args.output/'record.log', 'w', encoding='utf8') log = open(args.output/'record.log', 'w', encoding='utf8')
log_handles.append(log) 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'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}',
'-p', f'point_cloud_topic:={cloud_topic}'], '-p', f'point_cloud_topic:={cloud_topic}'],
stdout=log, stderr=subprocess.STDOUT, start_new_session=True) stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+166
View File
@@ -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)
+2 -2
View File
@@ -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])) 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] 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 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)) 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 return min(chassis,gimbal)-radius
+8 -1
View File
@@ -111,6 +111,8 @@ def main():
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests') help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
parser.add_argument('--timeout', type=float, default=420.0, parser.add_argument('--timeout', type=float, default=420.0,
help='whole-stack validation deadline, including up to three startup attempts') 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('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
parser.add_argument('--obstacle-x',type=float,default=-4.0) parser.add_argument('--obstacle-x',type=float,default=-4.0)
parser.add_argument('--obstacle-y',type=float,default=-1.5) parser.add_argument('--obstacle-y',type=float,default=-1.5)
@@ -121,6 +123,8 @@ def main():
parser.error('--round-trip-regression requires clear or cylinder') parser.error('--round-trip-regression requires clear or cylinder')
if args.full_field and args.scenario != 'clear': if args.full_field and args.scenario != 'clear':
parser.error('--full-field starts the clear-field coverage route') parser.error('--full-field starts the clear-field coverage route')
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 multileg = args.round_trip_regression or args.full_field or args.southeast_round_trip
if args.full_field: if args.full_field:
route = ARENA_GOALS route = ARENA_GOALS
@@ -174,6 +178,7 @@ def main():
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0 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') record_log = open(args.output/'record.log', 'w', encoding='utf8')
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', 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', '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}'], '-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) stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
@@ -404,6 +409,7 @@ def main():
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out, 'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
'trajectory_metrics': metrics(estimate_goal, truth_goal), '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_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) '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, if truth_goal and args.scenario == 'cylinder' else None,
'health_failures_during_goal': sum(not value for stamp, value in health_events 'health_failures_during_goal': sum(not value for stamp, value in health_events
@@ -461,7 +467,8 @@ def main():
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True) f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
if multileg and not leg['goal_succeeded']: if multileg and not leg['goal_succeeded']:
spin_for(8) spin_for(8)
break if not args.continue_on_failure:
break
result.update(counts) result.update(counts)
result['map_to_odom_publishers'] = len(publishers) result['map_to_odom_publishers'] = len(publishers)
result['amcl_present'] = 'amcl' in node.get_node_names() result['amcl_present'] = 'amcl' in node.get_node_names()