refactor(depth): keep DepthCameraObstacleLayer, drop the legacy depth clearing

Two depth-image clearing designs lived in this package: the frustum ray
clearing inherited from dev_cam_intel (DepthCameraData sources of
ObstacleLayer/VoxelLayer, frustum_* and column_* keys) and the observed_volume
evidence clearing (ROC) on top of it. Both are replaced on the robot by
DepthCameraObstacleLayer, a port of costmap_depth_camera that takes the
filtered PointCloud2 directly, so both are removed and the tree is rebuilt
from main (a63c084) plus the plugin.

- observation.h / observation_buffer: DepthFrustumConfig, DepthCameraObservation
  and the depth buffering API are gone; buffers hold point clouds only.
- ObstacleLayer/VoxelLayer: no frustum ray casting, column clearing or depth
  ray cache. A DepthCameraData source or frustum_clearing_enabled: true now
  fails at startup with a message pointing to DepthCameraObstacleLayer
  instead of silently dropping the camera; DepthCameraData reaching the layer
  through the gateway is ignored.
- copyParentParameters no longer forwards the frustum_* / column_* keys.
- ROC files (depth_evidence_store, depth_visibility, depth_frame_pairer) and
  their tests are not carried over; CloudProcessingConfig goes with them.
- PCL is needed by the plugin library only. The plugin test moves under
  BUILD_COSTMAP_TESTS; BUILD_DEPTH_MARKING_TESTS is gone.
- README documents DepthCameraObstacleLayer and its known limits.

The plugin code is unchanged from the version running on the KIT robot.
This commit is contained in:
2026-10-20 09:47:25 +07:00
parent 9a67eee148
commit b23ff27a3c
20 changed files with 222 additions and 3768 deletions

View File

@@ -23,7 +23,8 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem)
# still configure. The test block below requires it where it is actually used.
find_package(GTest QUIET)
find_package(yaml-cpp REQUIRED)
# kdtree/search/segmentation: DepthCameraObstacleLayer (kd-tree clearing, Euclidean clustering).
# DepthCameraObstacleLayer only (voxel grid, kd-tree clearing, Euclidean clustering); the core
# library and the other layers do not use PCL.
find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation)
if (NOT BUILDING_WITH_CATKIN)
@@ -109,17 +110,12 @@ add_library(robot_costmap_2d SHARED
src/array_parser.cpp
src/costmap_2d.cpp
src/observation_buffer.cpp
src/depth_visibility.cpp
src/depth_evidence_store.cpp
src/layer.cpp
src/layered_costmap.cpp
src/costmap_math.cpp
src/footprint.cpp
src/costmap_layer.cpp
)
target_include_directories(robot_costmap_2d SYSTEM PRIVATE ${PCL_INCLUDE_DIRS})
target_compile_options(robot_costmap_2d PRIVATE ${PCL_DEFINITIONS})
target_link_libraries(robot_costmap_2d PRIVATE ${PCL_LIBRARIES})
if(BUILDING_WITH_CATKIN)
add_dependencies(robot_costmap_2d ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
@@ -184,7 +180,7 @@ add_library(plugins SHARED
plugins/unpreferred_layer.cpp
plugins/depth_camera_obstacle_layer.cpp
)
# PCL stays private to the plugin library, like robot_costmap_2d: no PCL type in public headers.
# PCL stays private to the plugin library: no PCL type in public headers.
target_include_directories(plugins SYSTEM PRIVATE ${PCL_INCLUDE_DIRS})
target_compile_options(plugins PRIVATE ${PCL_DEFINITIONS})
target_link_libraries(plugins PRIVATE ${PCL_LIBRARIES})
@@ -293,25 +289,6 @@ endif()
option(BUILD_COSTMAP_TESTS "Build robot_costmap_2d test executables"
${BUILDING_WITH_CATKIN})
option(BUILD_DEPTH_MARKING_TESTS "Build depth observation buffer regression tests" OFF)
if(BUILD_DEPTH_MARKING_TESTS)
find_package(GTest REQUIRED)
add_executable(depth_observation_buffer_test test/depth_observation_buffer_test.cpp)
target_compile_definitions(depth_observation_buffer_test PRIVATE
DEPTH_MARKING_TEST_PLUGIN_PATH="$<TARGET_FILE:plugins>")
target_link_libraries(depth_observation_buffer_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
add_executable(depth_visibility_test test/depth_visibility_test.cpp)
target_link_libraries(depth_visibility_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
add_executable(depth_evidence_store_test test/depth_evidence_store_test.cpp)
target_link_libraries(depth_evidence_store_test PRIVATE
robot_costmap_2d GTest::GTest GTest::Main)
add_executable(depth_camera_obstacle_layer_test test/depth_camera_obstacle_layer_test.cpp)
target_link_libraries(depth_camera_obstacle_layer_test PRIVATE
plugins robot_costmap_2d GTest::GTest GTest::Main)
endif()
if(BUILD_COSTMAP_TESTS)
find_package(GTest REQUIRED)
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
@@ -354,4 +331,14 @@ if(BUILD_COSTMAP_TESTS)
${TF3_LIBRARY}
)
endif()
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/depth_camera_obstacle_layer_test.cpp)
add_executable(depth_camera_obstacle_layer_test test/depth_camera_obstacle_layer_test.cpp)
target_link_libraries(depth_camera_obstacle_layer_test PRIVATE
plugins
robot_costmap_2d
GTest::GTest
GTest::Main
)
endif()
endif()

217
README.md
View File

@@ -15,7 +15,8 @@ Luồng cập nhật chính:
```text
OccupancyGrid -------------------------> StaticLayer ---------+
LaserScan / PointCloud / PointCloud2 --> ObstacleLayer -------+--> master costmap
PointCloud2 + DepthCameraData ---------> VoxelLayer ----------+
LaserScan / PointCloud2 ---------------> VoxelLayer ----------+
PointCloud2 từ depth camera -----------> DepthCameraObstacleLayer
master costmap ------------------------> InflationLayer -------+
```
@@ -35,7 +36,8 @@ Các plugin được build trong package:
| --- | --- |
| `StaticLayer` | Đưa `OccupancyGrid` tĩnh vào costmap. |
| `ObstacleLayer` | Marking/clearing 2D từ `LaserScan`, `PointCloud`, `PointCloud2`. |
| `VoxelLayer` | Lưu vật cản theo voxel 3D, chiếu kết quả xuống costmap 2D và hỗ trợ clearing theo frustum depth camera. |
| `VoxelLayer` | Lưu vật cản theo voxel 3D, chiếu kết quả xuống costmap 2D, xóa bằng raytrace (laser/point cloud). |
| `DepthCameraObstacleLayer` | Vật cản từ depth camera: lưu điểm 3D, xóa trong khối nhìn của camera bằng kd-tree, đánh dấu theo cụm Euclidean. Xem mục 5.6. |
| `InflationLayer` | Tạo vùng chi phí giảm dần quanh ô vật cản. |
| `CriticalLayer` | Gộp vùng critical do hệ thống T800 cung cấp. |
| `DirectionalLayer` | Gộp thông tin vùng có hướng di chuyển. |
@@ -191,21 +193,11 @@ voxel_layer:
unknown_threshold: 15.0
mark_threshold: 0
combination_method: 1
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8
frustum_min_range: 0.20
frustum_max_range: 3.0
frustum_depth_camera_topic: /camera/depth/data
```
Trong implementation hiện tại, các tham số `frustum_*` được đọc theo từng
observation source bởi `ObstacleLayer`, là lớp cha của `VoxelLayer`. Vì vậy,
đừng chỉ chỉnh các key `frustum_*` trong `voxel_layer_params.yaml`; hãy đặt
chúng dưới source depth camera trong `costmap_common_params.yaml`.
Topic dùng để dispatch dữ liệu depth là `topic` của source. Key
`frustum_depth_camera_topic` vẫn có trong cấu hình fallback nhưng không thay thế
cho `pc_clearing.topic` trong contract hiện tại.
Depth camera không còn đi qua `VoxelLayer`: khai báo source `DepthCameraData` hoặc
`frustum_clearing_enabled: true` cho `ObstacleLayer`/`VoxelLayer` sẽ báo lỗi lúc khởi
động. Dùng plugin `DepthCameraObstacleLayer` (mục 5.6).
### 3.5. Inflation layer
@@ -221,8 +213,8 @@ inflation_layer:
## 4. Cấu hình tham khảo cho T800
Ví dụ sau dùng laser để marking/clearing 2D, point cloud đã xử lý để marking
vật cản 3D và message gộp `DepthCameraData` để clearing theo frustum.
Ví dụ sau dùng laser cho `VoxelLayer` (marking + raytrace clearing) và point cloud đã
xử lý của depth camera cho `DepthCameraObstacleLayer`.
### 4.1. Tham số dùng chung cho global và local costmap
@@ -238,11 +230,11 @@ footprint:
- [-0.583, 0.48]
- [-0.583, -0.48]
obstacles:
observation_sources: b_scan pc_marking pc_clearing
lidar_obstacles:
observation_sources: f_scan
b_scan:
topic: /b_scan
f_scan:
topic: /f_scan
data_type: LaserScan
sensor_frame: ""
marking: true
@@ -254,52 +246,30 @@ obstacles:
raytrace_range: 3.0
min_obstacle_height: 0.0
max_obstacle_height: 0.25
frustum_clearing_enabled: false
# Giữ PointCloud2 cho marking và persistence nếu cần.
pc_marking:
depth_obstacles:
observation_sources: depth_cam
# tham số chung cho mọi camera của layer: xem mục 5.6
check_radius: 0.1
number_clearing_threshold: 2
ec_seg_distance: 0.2
ec_cluster_min_size: 1
size_of_cluster_rejection: 0
depth_cam:
topic: /camera/depth/points_proc
data_type: PointCloud2
sensor_frame: ""
marking: true
clearing: false
inf_is_valid: false
sensor_frame_is_optical: true
observation_persistence: 0.0
expected_update_rate: 0.5
obstacle_range: 2.5
raytrace_range: 3.0
min_obstacle_height: 0.10
max_obstacle_height: 1.00
frustum_clearing_enabled: false
# Clearing dùng raw depth + CameraInfo trong cùng một message.
pc_clearing:
topic: /camera/depth/data
data_type: DepthCameraData
sensor_frame: ""
marking: false
clearing: false
observation_persistence: 0.0
expected_update_rate: 0.5
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8
frustum_min_range: 0.20
frustum_max_range: 3.5
expected_update_rate: 0.8
FOV_W: 1.23
FOV_V: 0.76
min_detect_distance: 0.15
max_detect_distance: 2.5
min_obstacle_height: 0.04
max_obstacle_height: 1.0
```
Với `DepthCameraData`, cờ `frustum_clearing_enabled: true` chọn buffer depth
riêng. Clearing được thực hiện trực tiếp theo tia camera trong `VoxelLayer`, vì
vậy không cần đặt `clearing: true` cho source này.
Message `DepthCameraData` phải thỏa các điều kiện:
- Depth encoding là `16UC1`, `mono16` hoặc `32FC1`.
- `width`, `height`, `step` và kích thước `data` hợp lệ.
- `CameraInfo.K[0]` (`fx`) và `K[4]` (`fy`) lớn hơn `0`.
- Kích thước depth và camera info khớp nhau nếu camera info khai báo kích thước.
- Frame của depth và camera info không mâu thuẫn.
- Có TF từ optical frame của camera tới `global_frame` costmap.
### 4.2. Global costmap
```yaml
@@ -362,10 +332,11 @@ local_costmap:
origin_y: 0.0
plugins:
- {name: obstacles, type: VoxelLayer}
- {name: lidar_obstacles, type: VoxelLayer}
- {name: depth_obstacles, type: DepthCameraObstacleLayer}
- {name: inflation, type: InflationLayer}
obstacles:
lidar_obstacles:
enabled: true
footprint_clearing_enabled: true
origin_z: 0.0
@@ -444,15 +415,15 @@ Quy trình chỉnh:
### 5.4. Observation source của ObstacleLayer/VoxelLayer
`observation_sources` là chuỗi các tên source cách nhau bằng khoảng trắng, ví
dụ `b_scan pc_marking pc_clearing`. Mỗi tên phải có một map tham số cùng tên.
dụ `f_scan b_scan`. Mỗi tên phải có một map tham số cùng tên.
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `topic` | `map` | Topic input. Đây cũng là key dispatch callback, phải khớp tuyệt đối. |
| `data_type` | `PointCloud` | Một trong `LaserScan`, `PointCloud`, `PointCloud2`, `DepthCameraData`. |
| `data_type` | `PointCloud` | Một trong `LaserScan`, `PointCloud`, `PointCloud2`. `DepthCameraData` báo lỗi lúc khởi động. |
| `sensor_frame` | rỗng | Để rỗng để dùng `header.frame_id`; chỉ đặt khi cần ép origin của sensor. |
| `marking` | `true` | Đánh dấu điểm quan sát thành vật cản. |
| `clearing` | `false` | Raytrace PointCloud/LaserScan để xóa vùng trống. Không điều khiển depth-frustum clearing. |
| `clearing` | `false` | Raytrace PointCloud/LaserScan để xóa vùng trống. |
| `inf_is_valid` | `false` | Với `LaserScan`, coi `+Inf` là tia không gặp vật cản để clearing. Không áp dụng cho point cloud. |
| `observation_persistence` | `0.0 s` | `0`: chỉ giữ mẫu mới nhất; tăng khi sensor thưa nhưng có thể tạo ghost obstacle. |
| `expected_update_rate` | `0.0 s` | Khoảng thời gian cập nhật mong đợi; `0`: không kiểm tra stale. Trong code đây là duration, không phải Hz. |
@@ -488,28 +459,74 @@ Dải này phải bao phủ vùng `min_obstacle_height..max_obstacle_height` mà
cần quan sát. Không tăng `max_obstacle_height` vượt khỏi voxel grid mà không
đồng thời kiểm tra `origin_z`, `z_resolution` và `z_voxels`.
### 5.6. Depth frustum clearing
### 5.6. DepthCameraObstacleLayer
Port của `costmap_depth_camera` (noetic). Layer nhận `PointCloud2` đã lọc của từng depth
camera, giữ các điểm vật cản 3D trong frame global của costmap và ghi `LETHAL` trực tiếp
lên master costmap. Mỗi chu kỳ:
1. Cloud mới nhất của từng source được biến đổi sang frame global bằng TF **tại đúng
stamp của cloud** (chờ tối đa `transform_tolerance`, quá hạn thì bỏ cloud và log lỗi),
lọc theo `min/max_obstacle_height`, rồi gộp voxel 5 cm.
2. **Xóa:** điểm đã lưu nằm trong khối nhìn (frustum) của bất kỳ camera nào bị xóa nếu cloud
hiện tại có ít hơn `number_clearing_threshold` điểm trong bán kính `check_radius`,
hoặc nếu điểm cách tâm robot dưới `forced_clearing_distance`. Cloud có
`<= number_points_considered_as_blocked` điểm thì xóa hết trong khối nhìn, trừ khi
bật `enable_near_blocked_protection`.
3. **Đánh dấu:** gom cụm Euclidean (`ec_seg_distance`); cụm có `<= size_of_cluster_rejection`
điểm bị bỏ; điểm của cụm còn lại nằm trong khối nhìn và cách mọi mặt khối nhìn hơn
12 cm thì được lưu.
4. Điểm ra ngoài cửa sổ costmap (rolling window) bị bỏ.
Tham số chung của layer:
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
| --- | ---: | --- |
| `frustum_clearing_enabled` | `false` | Chọn đường clearing trực tiếp từ `DepthCameraData`. |
| `frustum_clearing_pixel_step` | `8 px` | Lấy một tia mỗi N pixel theo cả hai chiều. Tăng để giảm CPU, giảm để clear dày hơn. Code clamp tối thiểu là `1`. |
| `frustum_min_range` | `0.20 m` | Không clear vùng quá gần camera, nơi depth thường không đáng tin. |
| `frustum_max_range` | `3.0 m` | Chiều dài ray tối đa khi pixel không có depth hợp lệ hoặc depth ở xa. |
| `enabled` | `true` | Bật/tắt layer. |
| `observation_sources` | rỗng | Danh sách tên source, mỗi camera một source. |
| `check_radius` | `0.1 m` | Bán kính tìm điểm cloud quanh điểm đã lưu khi xét xóa. |
| `number_clearing_threshold` | `2` | Ít hơn số điểm này trong `check_radius` thì xóa. Giảm xuống `1`: giữ vật nhỏ tốt hơn, ma xóa chậm hơn một chút. |
| `ec_seg_distance` | `0.2 m` | Khoảng cách gom cụm. |
| `ec_cluster_min_size` | `5` | Cụm nhỏ nhất PCL trả về. Vật nhỏ (vài voxel) cần `1`. |
| `size_of_cluster_rejection` | `5` | Bỏ cụm có số điểm không vượt quá giá trị này. Vật nhỏ cần `0`. |
| `forced_clearing_distance` | `0.1 m` | Điểm trong khối nhìn gần tâm robot hơn mức này luôn bị xóa. |
| `enable_near_blocked_protection` | `true` | `false`: cloud gần như trống thì xóa hết trong khối nhìn. |
| `number_points_considered_as_blocked` | `5` | Ngưỡng "cloud gần như trống". |
| `voxel_resolution` | `0.01 m` | Bước lượng tử độ cao của điểm lưu. |
| `use_voxelized_observation` | `true` | Gộp voxel 5 cm trước khi xử lý. |
| `transform_tolerance` | `0.2 s` | Thời gian chờ TF tại stamp của cloud. |
| `footprint_clearing_enabled` | `true` | Như các layer khác (xem ghi chú bên dưới). |
| `combination_method` | `1` | Như các layer khác. |
| `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. |
| `clear_touches_bounds` | `false` | `true`: điểm bị xóa cũng mở rộng vùng cập nhật để master được reset ngay. |
| `debug/stats` | `true` | Log `[debug/stats]` định kỳ: số điểm, số điểm đánh dấu/xóa, TF chờ/bỏ, thời gian. |
| `debug/stats_period` | `5.0 s` | Chu kỳ log trên. |
Mỗi pixel được sample tạo một tia từ camera. Với depth hợp lệ, ray dừng trước
điểm đo khoảng `2 * resolution` để không xóa chính vật cản. Với pixel không hợp
lệ, ray có thể clear tới `frustum_max_range`; vì vậy không đặt range vượt vùng
camera thực sự đáng tin.
Tham số của từng source (camera):
Gợi ý tuning:
| Tham số | Mặc định code | Ý nghĩa |
| --- | ---: | --- |
| `topic` | tên source | Topic `PointCloud2`, phải khớp tên topic mà gateway đẩy vào. |
| `sensor_frame` | rỗng | Rỗng: dùng frame của cloud để dựng khối nhìn. |
| `sensor_frame_is_optical` | `false` | `true` khi frame là frame quang học (Z hướng nhìn). |
| `FOV_W`, `FOV_V` | `1.5`, `1.0 rad` | Góc nhìn ngang/dọc của khối nhìn. Tính từ `camera_info`. |
| `min_detect_distance`, `max_detect_distance` | `0.15`, `2.5 m` | Mặt gần/xa của khối nhìn. Ngoài khoảng này không đánh dấu, không xóa. |
| `min_obstacle_height`, `max_obstacle_height` | `0.0`, `2.0 m` | Lọc độ cao trong frame global. |
| `marking` | `true` | `false`: bỏ qua source. |
| `observation_persistence` | `0.0 s` | `0`: chỉ dùng cloud mới nhất. |
| `expected_update_rate` | `0.0 s` | Quá lâu không có cloud thì costmap báo không current. `0`: tắt. |
- Bắt đầu với `pixel_step: 8`.
- Nếu còn các dải ghost obstacle mỏng giữa các tia, thử `6`, rồi `4`.
- Nếu CPU cao, thử `10`, `12` hoặc giảm `frustum_max_range`.
- `frustum_min_range` nên lớn hơn hoặc bằng khoảng mù gần của camera.
- `frustum_max_range` nên nhỉnh hơn `pc_marking.obstacle_range`, nhưng không
vượt quá range depth ổn định trong môi trường thực tế.
Giới hạn đã biết:
- Điểm chỉ được xét xóa khi nằm **trong khối nhìn**. Điểm ra ngoài khối nhìn (robot quay đi,
vật đi ra ngoài FOV, hoặc điểm cao vượt mép trên ảnh khi robot tới gần) được giữ cho tới
khi ra khỏi cửa sổ costmap. Đặt `max_obstacle_height` sát chiều cao robot để giảm loại thứ
hai.
- Khối nhìn đối xứng và trùng mép ảnh; dải mép ảnh không có depth (lọc mép, dải stereo
bên trái) vẫn được coi là "nhìn thấy trống".
- `reset()`, `clearArea()` và footprint clearing không xóa các điểm đã lưu; layer ghi lại
chúng ở chu kỳ sau.
- `DepthCameraData` (ảnh depth) đi tới layer này bị bỏ qua.
### 5.7. InflationLayer
@@ -544,8 +561,8 @@ Chỉ thay một nhóm tham số mỗi lần và lưu lại bag/log trước khi
`6..10 m` tùy vận tốc và khoảng phanh.
4. **Chỉ bật marking**: xác nhận vật cản xuất hiện đúng vị trí, đúng height và
range.
5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng source
`DepthCameraData` với frustum clearing.
5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng
`DepthCameraObstacleLayer`.
6. **Chỉnh voxel**: đặt dải z, sau đó tăng `mark_threshold` nếu nhiễu đơn điểm.
7. **Chỉnh inflation**: chỉnh `inflation_radius` trước, sau đó mới chỉnh
`cost_scaling_factor` theo khoảng cách đường đi mong muốn.
@@ -558,7 +575,7 @@ Các ràng buộc nên giữ:
resolution > 0
width > 0 và height > 0 nếu không lấy size từ static map
raytrace_range >= obstacle_range
frustum_max_range >= frustum_min_range >= 0
max_detect_distance > min_detect_distance >= 0 (DepthCameraObstacleLayer)
1 <= z_voxels <= 16
origin_z + z_resolution * z_voxels đủ bao phủ dải vật cản cần quan sát
InflationLayer nằm sau các layer tạo vật cản
@@ -568,32 +585,27 @@ InflationLayer nằm sau các layer tạo vật cản
| Triệu chứng | Kiểm tra trước | Hướng chỉnh |
| --- | --- | --- |
| Vật cản đã đi nhưng vẫn còn trên costmap | TF, topic clearing, dữ liệu có còn cập nhật | Bật đúng `clearing`; với depth dùng `DepthCameraData` + `frustum_clearing_enabled`; giảm `observation_persistence`; giảm `pixel_step` nếu còn khe giữa tia. |
| Vật cản đã đi nhưng vẫn còn trên costmap | TF, topic clearing, dữ liệu có còn cập nhật; với depth: điểm có nằm trong khối nhìn không | Bật đúng `clearing`; giảm `observation_persistence`; với depth xem giới hạn ở mục 5.6. |
| Vật cản thật không được đánh dấu | Topic/type/frame, range và height | Kiểm tra `marking`, `min/max_obstacle_height`, `obstacle_range`; với voxel thử `mark_threshold: 0` trước. |
| Vật cản chớp tắt | Tần số sensor, packet drop, TF | Đặt `expected_update_rate` đúng chu kỳ; tăng nhẹ `observation_persistence` nhưng phải kiểm tra ghost obstacle. |
| Robot đi quá sát vật cản | Footprint trước, inflation sau | Tăng `inflation_radius` hoặc giảm `cost_scaling_factor`. |
| Robot tránh quá xa/không tìm được đường | Footprint, unknown space, inflation | Giảm `inflation_radius` hoặc tăng `cost_scaling_factor`; kiểm tra `inflate_unknown`. |
| Costmap local trễ hoặc CPU cao | Metrics theo layer | Tăng `resolution`, giảm `width/height`, giảm `update_frequency`, tăng depth `pixel_step`, giảm range hoặc giảm mật độ `/camera/depth/points_proc`. |
| Costmap local trễ hoặc CPU cao | Metrics theo layer | Tăng `resolution`, giảm `width/height`, giảm `update_frequency`, giảm `max_detect_distance` hoặc giảm mật độ `/camera/depth/points_proc`. |
| Costmap báo stale/not current | Sensor thực tế có đúng chu kỳ không | Tăng giá trị `expected_update_rate` theo đơn vị giây hoặc đặt `0` để tắt kiểm tra trong lúc chẩn đoán. |
| Clearing xóa xuyên vật cản depth | Depth invalid, range quá lớn, TF camera | Giảm `frustum_max_range`, tăng `frustum_min_range`, kiểm tra encoding/calibration và đảm bảo point-cloud marking hoạt động. |
| Vật nhỏ/thấp từ depth bị mất | Số điểm trên vật sau lọc độ cao | `ec_cluster_min_size: 1`, `size_of_cluster_rejection: 0`, cân nhắc `number_clearing_threshold: 1` và `min_obstacle_height` (đổi lại: dễ có sàn ma nếu TF camera lệch). |
| Sensor origin nằm ngoài voxel map | `global_frame`, rolling window, TF z | Sửa TF/origin, tăng cửa sổ phù hợp; không chỉ tăng tolerance. |
| Vật cản sàn/nhiễu thấp xuất hiện | Height filter và calibration | Tăng `min_obstacle_height` từng bước nhỏ; không tăng quá đáy vật cản robot cần tránh. |
## 8. Lưu ý riêng cho depth camera T800
## 8. Lưu ý cho depth camera
- Marking và clearing có contract khác nhau: `/camera/depth/points_proc`
(`PointCloud2`) dùng cho marking/persistence; `/camera/depth/data`
(`DepthCameraData`) dùng cho frustum clearing.
- Không cấu hình cùng một full point cloud để vừa marking vừa clearing nếu mục
tiêu là giảm tải. Đường frustum dùng raw depth semantics và sampling theo
pixel, tránh xử lý toàn bộ cloud thêm lần nữa.
- Mỗi camera nên có cặp source riêng, ví dụ `pc0_marking pc0_clearing
pc1_marking pc1_clearing`, với topic, frame, range và pixel step riêng.
- `observation_persistence: 0.0` giữ mẫu mới nhất. Chỉ tăng khi đã đo được tần
suất sensor và hiểu rõ thời gian ghost obstacle chấp nhận được.
- Khi mất marking, kiểm tra lần lượt output sau bước chuyển depth thành
`/camera/depth/points_proc`, TF sang costmap frame và buffer của
`ObstacleLayer` trước khi chỉnh `mark_threshold`.
- Layer chỉ dùng `PointCloud2` đã lọc (ví dụ `/camera/depth/points_proc`). Ảnh
`DepthCameraData` mà bridge vẫn gửi bị các layer bỏ qua.
- Mỗi camera là một source trong `observation_sources` của cùng một
`DepthCameraObstacleLayer`, với topic, frame, FOV và dải độ cao riêng.
- Ngưỡng độ cao làm việc trong frame global: sai số lắp camera (roll, pitch, chiều cao)
quyết định ngưỡng thấp nhất dùng được trước khi sàn bị đánh dấu.
- Khi mất marking, kiểm tra lần lượt cloud sau bridge, TF tại stamp của cloud (dòng
`[debug/stats]`: `tf_wait`, `tf_drop`) và ngưỡng cụm trước khi đổi ngưỡng độ cao.
## 9. Build và kiểm tra
@@ -610,6 +622,7 @@ Các executable test được tạo khi `BUILD_COSTMAP_TESTS=ON`:
./devel/lib/robot_costmap_2d/test_array_parser
./devel/lib/robot_costmap_2d/test_costmap
./devel/lib/robot_costmap_2d/test_plugin
./devel/lib/robot_costmap_2d/depth_camera_obstacle_layer_test
```
Kiểm tra tối thiểu trước khi chạy robot:

View File

@@ -1,92 +0,0 @@
#ifndef ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_
#define ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_
#include <Eigen/Core>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <unordered_map>
#include <vector>
namespace robot_costmap_2d
{
/**
* @brief Measured points that marked each voxel of a depth-only VoxelLayer.
*
* The observed_volume clearing certifies these points instead of the whole voxel box:
* the occupancy of a depth-only layer is exactly what the camera saw, so the part of a
* voxel the camera never saw carries no occupancy of its own. Keys use a
* window-independent cell index, so a rolling origin shift needs no copy; callers drop
* keys that left the window with eraseIf().
*
* Per voxel it keeps the 6 per-axis extreme points (min/max x, y, z) and fills the
* remaining slots with the most recent points.
*/
class DepthEvidenceStore
{
public:
static constexpr unsigned int kExtremeSlots = 6;
static constexpr unsigned int kMaxPoints = 16;
struct VoxelKey
{
int x;
int y;
unsigned int z;
bool operator==(const VoxelKey& other) const
{
return x == other.x && y == other.y && z == other.z;
}
};
explicit DepthEvidenceStore(unsigned int points_per_voxel = 8);
/// Clamped to [kExtremeSlots, kMaxPoints]; drops all stored evidence.
void setPointsPerVoxel(unsigned int points_per_voxel);
unsigned int pointsPerVoxel() const { return points_per_voxel_; }
/// Records a marking point [global frame, m]. fresh = true drops points left over from
/// an earlier occupancy of the voxel (it was not MARKED before this point). A marking
/// point also restarts the voxel's re-observe miss count.
void add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh);
/// Re-observe-or-clear: adds weight to the voxel's miss count and returns the new count;
/// 0 when the voxel has no evidence.
float addMiss(const VoxelKey& key, float weight);
void resetMiss(const VoxelKey& key);
/// Distinct evidence points of one voxel. Returns false when the voxel has none.
bool points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const;
void erase(const VoxelKey& key);
void eraseIf(const std::function<bool(const VoxelKey&)>& predicate);
void clear();
std::size_t size() const { return entries_.size(); }
private:
struct KeyHash
{
std::size_t operator()(const VoxelKey& key) const noexcept
{
return (static_cast<std::size_t>(static_cast<uint32_t>(key.x)) * 73856093u) ^
(static_cast<std::size_t>(static_cast<uint32_t>(key.y)) * 19349663u) ^
(static_cast<std::size_t>(key.z) * 83492791u);
}
};
struct Entry
{
std::array<Eigen::Vector3f, kMaxPoints> points;
unsigned char count = 0; ///< valid slots, extremes included
unsigned char next_recent = 0; ///< ring position among the recent slots
float miss = 0.f; ///< re-observe misses since last marked or confirmed
};
unsigned int points_per_voxel_;
std::unordered_map<VoxelKey, Entry, KeyHash> entries_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DEPTH_EVIDENCE_STORE_H_

View File

@@ -1,166 +0,0 @@
#pragma once
#include <robot_costmap_2d/observation.h>
#include <boost/make_shared.hpp>
#include <chrono>
#include <map>
#include <mutex>
#include <cmath>
#include <stdexcept>
#include <algorithm>
namespace robot_costmap_2d
{
// A source pair owns immutable measurement messages; the update thread alone
// acknowledges applied frames. Queue timeout/freshness never expires occupancy.
class DepthFramePairer
{
public:
using Clock = std::chrono::steady_clock;
struct Candidate
{
uint64_t stamp{0};
robot_sensor_msgs::PointCloud2::ConstPtr cloud;
robot_sensor_msgs::DepthCameraData::ConstPtr depth;
};
struct Counts
{
uint64_t applied{0}, expired{0}, overflow{0}, stale{0}, duplicate{0}, invalid{0}, tf_wait{0};
};
explicit DepthFramePairer(const DepthFrustumConfig& config, double expected_period)
: config_(config), expected_period_(expected_period), started_(robot::Time::now()), last_clock_(started_)
{
if (!std::isfinite(expected_period_) || expected_period_ < 0 ||
!config_.pair_queue_size || !std::isfinite(config_.pair_max_wait_s) || config_.pair_max_wait_s <= 0 ||
!std::isfinite(config_.observation_max_age_s) || config_.observation_max_age_s <= 0)
throw std::invalid_argument("invalid depth pair queue/age configuration");
}
void addCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
if (cloud.header.stamp.isZero()) { ++counts_.invalid; return; }
const auto key = cloud.header.stamp.toNSec();
if (key <= applied_stamp_) { ++counts_.duplicate; return; }
auto& p = pending_[key];
if (p.cloud) { ++counts_.duplicate; return; }
if (!p.depth) p.arrival = Clock::now();
p.cloud = boost::make_shared<robot_sensor_msgs::PointCloud2>(cloud);
expire();
}
void addDepth(robot_sensor_msgs::DepthCameraData::ConstPtr depth)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
if (!depth || depth->depth.header.stamp.isZero()) { ++counts_.invalid; return; }
const auto key = depth->depth.header.stamp.toNSec();
if (key <= applied_stamp_) { ++counts_.duplicate; return; }
auto& p = pending_[key];
if (p.depth) { ++counts_.duplicate; return; }
if (!p.cloud) p.arrival = Clock::now();
p.depth = std::move(depth);
expire();
}
bool next(Candidate& out)
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock(); expire();
for (auto it = pending_.begin(); it != pending_.end();)
{
auto& p = it->second;
if (!p.cloud || !p.depth) { ++it; continue; }
if (p.cloud->header.frame_id != p.depth->depth.header.frame_id ||
p.depth->depth.header.stamp != p.depth->camera_info.header.stamp ||
p.depth->depth.header.stamp != p.depth->header.stamp)
{
++counts_.invalid;
it = pending_.erase(it);
continue;
}
out = {it->first, p.cloud, p.depth};
return true;
}
return false;
}
void applied(uint64_t stamp)
{
std::lock_guard<std::mutex> lock(mutex_);
applied_stamp_ = std::max(applied_stamp_, stamp);
last_applied_ = robot::Time::now();
++counts_.applied;
for (auto it = pending_.begin(); it != pending_.end() && it->first <= applied_stamp_;)
it = pending_.erase(it);
}
void discard(uint64_t stamp)
{
std::lock_guard<std::mutex> lock(mutex_);
pending_.erase(stamp); ++counts_.invalid;
}
void noteTfWait()
{
std::lock_guard<std::mutex> lock(mutex_); ++counts_.tf_wait;
}
bool isCurrent()
{
std::lock_guard<std::mutex> lock(mutex_);
observeClock();
const auto last = last_applied_.isZero() ? started_ : last_applied_;
return expected_period_ <= 0 || (robot::Time::now() - last).toSec() <= expected_period_;
}
void reset()
{
std::lock_guard<std::mutex> lock(mutex_);
const auto watermark = applied_stamp_;
resetUnlocked(robot::Time::now());
applied_stamp_ = watermark; // map resets must not replay a cached old frame
}
Counts counts() const
{
std::lock_guard<std::mutex> lock(mutex_); return counts_;
}
private:
struct Pending
{
robot_sensor_msgs::PointCloud2::ConstPtr cloud;
robot_sensor_msgs::DepthCameraData::ConstPtr depth;
Clock::time_point arrival;
};
void resetUnlocked(const robot::Time& now)
{
pending_.clear(); applied_stamp_ = 0; last_applied_ = robot::Time();
started_ = now; last_clock_ = now;
}
void observeClock()
{
const auto now = robot::Time::now();
if (now < last_clock_) resetUnlocked(now);
last_clock_ = now;
}
void expire()
{
const auto now = Clock::now();
const double measurement_now = robot::Time::now().toSec();
for (auto it = pending_.begin(); it != pending_.end();)
{
const double age = measurement_now - static_cast<double>(it->first) * 1e-9;
if (age > config_.observation_max_age_s || age < -.05)
{ ++counts_.stale; it = pending_.erase(it); }
else if (std::chrono::duration<double>(now - it->second.arrival).count() > config_.pair_max_wait_s)
{ ++counts_.expired; it = pending_.erase(it); }
else ++it;
}
while (pending_.size() > config_.pair_queue_size)
{ pending_.erase(pending_.begin()); ++counts_.overflow; }
}
DepthFrustumConfig config_;
double expected_period_;
robot::Time started_, last_clock_, last_applied_;
uint64_t applied_stamp_{0};
std::map<uint64_t, Pending> pending_;
Counts counts_;
mutable std::mutex mutex_;
};
} // namespace robot_costmap_2d

View File

@@ -1,68 +0,0 @@
#pragma once
#include <robot_costmap_2d/observation.h>
#include <tf3/compat.h>
#include <Eigen/Geometry>
#include <vector>
namespace robot_costmap_2d
{
enum class DepthVisibility { Free, Unknown, Surface };
enum class DepthVisibilityReason { Free, OutsideView, InvalidDepth, Surface, EmptyRegion };
/// What one frame says about a marked voxel under the re-observe-or-clear rule, weakest first.
enum class DepthObservation { OutOfView, NoReturn, SeenThrough, Occluded, Confirmed };
struct DepthVisibilityResult
{
DepthVisibility state{DepthVisibility::Unknown};
DepthVisibilityReason reason{DepthVisibilityReason::OutsideView};
};
// Pure geometry/measurement helper. It never mutates occupancy or queries TF.
class DepthVisibilityChecker
{
public:
bool prepare(robot_sensor_msgs::DepthCameraData::ConstPtr data,
const tf3::TransformStampedMsg& global_from_camera,
double min_height, double max_height, const DepthFrustumConfig& config);
DepthVisibilityResult classify(const Eigen::Vector3d& lower,
const Eigen::Vector3d& upper) const;
/**
* @brief Certifies the measured evidence points of one voxel [global frame, m].
*
* Free only when every point projects with its projection_margin_px patch fully inside
* the usable image, every patch pixel holds valid depth, and that depth lies behind the
* point by more than free_margin_m. Any pixel in front keeps the voxel (Surface); an
* invalid pixel or a point out of view keeps it as Unknown. An empty list is Unknown.
*/
DepthVisibilityResult classifyPoints(const std::vector<Eigen::Vector3d>& points) const;
/**
* @brief Re-observes the measured evidence points of one voxel [global frame, m].
*
* Per point, its projection_margin_px patch decides: a valid pixel within confirm_tolerance_m
* of the point is Confirmed; otherwise a valid pixel in front is Occluded; otherwise one
* behind is SeenThrough; otherwise NoReturn. A point outside the trusted depth range, the
* usable image or the stereo band is OutOfView. The voxel takes its strongest point result.
*/
DepthObservation observePoints(const std::vector<Eigen::Vector3d>& points) const;
/// True when a global-frame point projects at least border_px inside the usable image
/// (the clear_left/right border strips and the stereo band are not usable). Used to gate
/// evidence marking, so every marked point can be re-checked later.
bool projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const;
private:
/// Raw depth at a pixel [m]; NaN for an unsupported encoding. Caller checks bounds.
double depthAt(int u, int v) const;
/// First usable image column for a point at depth z [m] > 0: the left border strip or the
/// stereo no-disparity band, whichever is wider.
int usableLeft(double z) const;
robot_sensor_msgs::DepthCameraData::ConstPtr data_;
Eigen::Isometry3d camera_from_global_{Eigen::Isometry3d::Identity()};
double min_height_{0}, max_height_{0};
DepthFrustumConfig config_;
unsigned int bytes_per_pixel_{0};
};
} // namespace robot_costmap_2d

View File

@@ -34,7 +34,6 @@
#include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <utility>
@@ -42,184 +41,6 @@
namespace robot_costmap_2d
{
/**
* @brief A depth frame and its per-source frustum-clearing configuration.
*
* The message is shared so returning buffered observations does not copy the
* full depth image on every costmap update.
*/
/// Per-observation-source configuration of the depth-image frustum clearing,
/// loaded by ObstacleLayer from the source's YAML/ROS params and carried with
/// each DepthCameraObservation.
struct DepthFrustumConfig
{
unsigned int pixel_step = 0;
double min_range = 0.0;
double max_range = 0.0;
/// 3D clearing rays stop this far [m] before the measured surface.
/// Negative: legacy 2 * costmap resolution.
double skip_distance = -1.0;
/// Full-column clearing from the per-pixel-column nearest in-band return.
bool column_clearing = false;
/// Height band [m] used for the in-band test; floor returns below min do
/// not shorten the beam. max < 0: use the layer max_obstacle_height.
double column_min_height = 0.10;
double column_max_height = -1.0;
/// Column beams stop this far [m] before the nearest in-band return.
double column_skip_distance = 0.02;
/// Full columns are only cleared beyond this distance [m]. Negative:
/// derive each frame from the camera intrinsics and mounting pose.
double column_cover_distance = -1.0;
/// Depth-image columns at the LEFT edge excluded from clearing [px]. Covers
/// the stereo no-disparity strip that is permanently invalid there: those
/// pixels carry no free-space evidence, so clearing through them erases
/// obstacles that rotate out of the FOV on that side. Set to the measured
/// width of the black strip in the raw depth image (a few px margin). 0
/// disables. Invalid pixels ELSEWHERE still clear (needed for ghost removal).
unsigned int clear_left_border_px = 0;
/// Same as clear_left_border_px but for the RIGHT edge, for cameras whose
/// stereo no-disparity strip sits on the right instead of the left. Measured
/// from the last image column inward. 0 disables.
unsigned int clear_right_border_px = 0;
// Opt-in observed-volume mode. Legacy range/column keys are not used by it.
bool observed_volume_clearing = false;
double voxel_z_resolution_m = 0.0625; // depth-only grid: low objects must not occupy an entire 20 cm slab
std::string paired_marking_source;
unsigned int pair_queue_size = 4;
double pair_max_wait_s = 0.25;
double observation_max_age_s = 0.5;
double valid_min_z_m = 0.1;
double valid_max_z_m = 3.0;
double free_margin_m = 0.02;
unsigned int projection_margin_px = 1;
/// Certify the measured evidence points of each marked voxel instead of the whole
/// voxel box. A box cut by the image edge can never be certified, while the points
/// that marked it were inside the image when they were seen.
bool evidence_points_enabled = false;
/// [points] evidence kept per voxel: 6 per-axis extremes plus the most recent ones.
unsigned int evidence_points_per_voxel = 8;
/// [px] with evidence points, marking drops points that project closer than this to
/// the usable image edge, so each kept point has a full projection patch in view.
unsigned int marking_border_px = 0;
/// With evidence points, a valid return deeper than valid_max_z_m counts as behind a point
/// that lies at least free_margin_m inside the trusted range: the ray passed the point.
bool far_return_is_behind = false;
/// Re-observe-or-clear rule (needs evidence points). A marked voxel in view must be measured
/// again at one of its points each frame; seen through for miss_frames frames in a row frees
/// it. Occluded, out-of-view and no-return frames keep it, so nothing expires out of the FOV.
/// false: a voxel is freed only when every pixel of every point proves free space.
bool reobserve_clearing = false;
/// [m] Re-observe: |measured - point depth| within this means the surface is still there.
/// Nearer than that is an occluder, deeper is free space seen through. Replaces free_margin_m.
double confirm_tolerance_m = 0.05;
/// [frames] Re-observe: seen-through frames in a row that free a voxel.
unsigned int miss_frames = 3;
/// [0..1] Re-observe: miss added by a frame whose patch pixels are all invalid. 0 keeps invalid
/// depth as unknown; > 0 lets voxels in view expire where the camera returns nothing.
double no_return_weight = 0.0;
/// [m] Stereo baseline of the left no-disparity band, fx * baseline / z + stereo_band_margin_px
/// wide at depth z. Points inside it cannot be re-checked: they are out of view and are not
/// marked. 0 disables (only clear_left_border_px applies).
double stereo_baseline_m = 0.0;
/// [px] Added to the stereo band width.
unsigned int stereo_band_margin_px = 10;
};
class DepthCameraObservation
{
public:
DepthCameraObservation()
: data_handle_(),
data_(nullptr),
topic_()
{
}
DepthCameraObservation(
const robot_sensor_msgs::DepthCameraData& data,
std::string topic,
const robot::Time& received_time,
const DepthFrustumConfig& frustum)
: data_handle_(boost::make_shared<robot_sensor_msgs::DepthCameraData>(data)),
data_(data_handle_.get()),
topic_(std::move(topic)),
received_time_(received_time),
frustum_(frustum)
{
}
DepthCameraObservation(
robot_sensor_msgs::DepthCameraData::ConstPtr data,
std::string topic,
const robot::Time& received_time,
const DepthFrustumConfig& frustum)
: data_handle_(std::move(data)),
data_(data_handle_.get()),
topic_(std::move(topic)),
received_time_(received_time),
frustum_(frustum)
{
}
DepthCameraObservation(const DepthCameraObservation& other)
: data_handle_(other.data_handle_),
data_(data_handle_.get()),
topic_(other.topic_),
received_time_(other.received_time_),
frustum_(other.frustum_)
{
}
DepthCameraObservation(DepthCameraObservation&& other) noexcept
: data_handle_(std::move(other.data_handle_)),
data_(data_handle_.get()),
topic_(std::move(other.topic_)),
received_time_(other.received_time_),
frustum_(other.frustum_)
{
other.data_ = nullptr;
other.frustum_ = DepthFrustumConfig();
}
DepthCameraObservation& operator=(const DepthCameraObservation& other)
{
if (this == &other)
return *this;
data_handle_ = other.data_handle_;
data_ = data_handle_.get();
topic_ = other.topic_;
received_time_ = other.received_time_;
frustum_ = other.frustum_;
return *this;
}
DepthCameraObservation& operator=(DepthCameraObservation&& other) noexcept
{
if (this == &other)
return *this;
data_handle_ = std::move(other.data_handle_);
data_ = data_handle_.get();
topic_ = std::move(other.topic_);
received_time_ = other.received_time_;
frustum_ = other.frustum_;
other.data_ = nullptr;
other.frustum_ = DepthFrustumConfig();
return *this;
}
~DepthCameraObservation() = default;
robot_sensor_msgs::DepthCameraData::ConstPtr data_handle_;
const robot_sensor_msgs::DepthCameraData* data_;
std::string topic_;
robot::Time received_time_;
DepthFrustumConfig frustum_;
};
/**
* @brief Stores an observation in terms of a point cloud and the origin of the source
* @note Tried to make members and constructor arguments const but the compiler would not accept the default

View File

@@ -50,14 +50,6 @@
namespace robot_costmap_2d
{
// Opt-in per source: legacy callers keep their TF and cloud policy.
struct CloudProcessingConfig
{
bool transform_at_stamp{false};
bool voxel_filter_enabled{false};
double voxel_leaf_size{0.05}; // [m], applied after height/range gates
};
/**
* @class ObservationBuffer
* @brief Takes in point clouds from sensors, transforms them to the desired frame, and stores them
@@ -84,12 +76,6 @@ public:
double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance);
ObservationBuffer(std::string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, const DepthFrustumConfig& frustum_config,
tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance);
/**
* @brief Destructor... cleans up
@@ -112,32 +98,12 @@ public:
*/
void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
// Configure before receiving samples. Empty valid clouds return true;
// missing TF/malformed observations return false and do not refresh the buffer.
void setCloudProcessingConfig(const CloudProcessingConfig& config);
bool tryBufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
bool tryBufferCloudWithTransform(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg& transform);
const std::string& sensorFrame() const { return sensor_frame_; }
/**
* @brief Store the newest depth frame without converting it to PointCloud2.
*/
void bufferDepthCamera(const robot_sensor_msgs::DepthCameraData& depth);
void bufferDepthCamera(robot_sensor_msgs::DepthCameraData::ConstPtr depth);
/**
* @brief Pushes copies of all current observations onto the end of the vector passed in
* @param observations The vector to be filled
*/
void getObservations(std::vector<Observation>& observations);
/**
* @brief Append the current depth observation, if it has not expired.
*/
void getDepthObservations(std::vector<DepthCameraObservation>& observations);
/**
* @brief Check if the observation buffer is being update at its expected rate
* @return True if it is being updated at the expected rate, false otherwise
@@ -171,10 +137,6 @@ private:
*/
void purgeStaleObservations();
void purgeStaleDepthObservations();
bool tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg* prepared_transform);
tf3::BufferCore& tf3_buffer_;
const robot::Duration observation_keep_time_;
const robot::Duration expected_update_rate_;
@@ -182,15 +144,11 @@ private:
std::string global_frame_;
std::string sensor_frame_;
std::list<Observation> observation_list_;
std::list<DepthCameraObservation> depth_observation_list_;
// DepthCameraObservation depth_observation_;
std::string topic_name_;
double min_obstacle_height_, max_obstacle_height_;
boost::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely
double obstacle_range_, raytrace_range_;
double tf_tolerance_;
DepthFrustumConfig frustum_config_;
CloudProcessingConfig cloud_processing_config_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_

View File

@@ -42,14 +42,12 @@
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_costmap_2d/observation_buffer.h>
#include <robot_costmap_2d/depth_frame_pairer.h>
#include <robot_costmap_2d/footprint.h>
#include <robot_nav_msgs/OccupancyGrid.h>
#include <mutex>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <robot_sensor_msgs/LaserScan.h>
#include <robot_laser_geometry/laser_geometry.hpp>
#include <robot_sensor_msgs/PointCloud.h>
@@ -132,12 +130,6 @@ protected:
void pointCloud2Callback(const robot_sensor_msgs::PointCloud2& message,
const boost::shared_ptr<robot_costmap_2d::ObservationBuffer>& buffer);
/**
* @brief Buffer a depth image and its camera model for frustum clearing.
*/
void depthImageCallback(robot_sensor_msgs::DepthCameraData::ConstPtr message,
const boost::shared_ptr<robot_costmap_2d::ObservationBuffer>& buffer);
/**
* @brief Get the observations used to mark space
* @param marking_observations A reference to a vector that will be populated with the observations
@@ -152,13 +144,6 @@ protected:
*/
bool getClearingObservations(std::vector<robot_costmap_2d::Observation>& clearing_observations) const;
/**
* @brief Collect fresh depth frames from every configured frustum-clearing source.
* @return True when every configured depth source is current.
*/
bool getFrustumClearingObservations(
std::vector<robot_costmap_2d::DepthCameraObservation>& frustum_clearing_observations) const;
/**
* @brief Clear freespace based on one observation
* @param clearing_observation The observation used to raytrace
@@ -187,9 +172,6 @@ protected:
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > marking_buffers_; ///< @brief Used to store observation buffers used for marking obstacles
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > clearing_buffers_; ///< @brief Used to store observation buffers used for clearing obstacles
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > depth_observation_buffers_;
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > depth_clearing_buffers_;
// Used only for testing purposes
std::vector<robot_costmap_2d::Observation> static_clearing_observations_, static_marking_observations_;
@@ -198,24 +180,6 @@ protected:
int combination_method_;
std::vector<CallBackInfo> callback_infos_;
std::vector<CallBackInfo> callback_depth_infos_;
std::string depth_camera_data_topic_;
mutable std::mutex depth_camera_data_mutex_;
robot_sensor_msgs::DepthCameraData::ConstPtr pending_depth_camera_data_;
struct PairedDepthSource
{
PairedDepthSource(const DepthFrustumConfig& config, double expected_period)
: config(config), pairer(config, expected_period) {}
std::string cloud_topic, depth_topic;
boost::shared_ptr<ObservationBuffer> marking_buffer, depth_buffer;
double min_height{0}, max_height{0};
DepthFrustumConfig config;
DepthFramePairer pairer;
};
std::vector<boost::shared_ptr<PairedDepthSource>> paired_depth_sources_;
bool pairedDepthCurrent() const;
void resetPairedDepth();
private:
bool getParams(const std::string& config_file_name, robot::NodeHandle &nh);

View File

@@ -49,7 +49,6 @@
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_sensor_msgs/point_cloud_conversion.h>
#include <robot_costmap_2d/obstacle_layer.h>
#include <robot_costmap_2d/depth_evidence_store.h>
#include <robot_voxel_grid/voxel_grid.h>
#include <limits>
@@ -58,9 +57,6 @@
namespace robot_costmap_2d
{
class DepthVisibilityChecker;
enum class DepthObservation;
class VoxelLayer : public ObstacleLayer
{
public:
@@ -77,17 +73,12 @@ public:
double* max_x, double* max_y);
void updateOrigin(double new_origin_x, double new_origin_y);
// Diagnostic snapshot; caller must hold the layer/update lock, as with getCharMap().
VoxelGrid voxelSnapshot();
bool isDiscretized()
{
return true;
}
virtual void matchSize();
virtual void reset();
/// Recovery clear. Also drops the voxels and evidence points of the cleared cells: the
/// base class only writes the 2D cells, and the next column update re-derived the obstacle.
void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override;
LayerType getType() const override
{
@@ -103,103 +94,15 @@ private:
void clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info);
virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_y);
// bool raytraceDepthFrustum(double* min_x, double* min_y, double* max_x, double* max_y);
bool raytraceDepthFrustum(const robot_costmap_2d::DepthCameraObservation& observation,
double* min_x, double* min_y, double* max_x, double* max_y);
bool readDepthMeters(const robot_sensor_msgs::Image& depth, unsigned int u, unsigned int v,
double& depth_m, bool& is_valid) const;
void updateDepthRayCache(unsigned int width, unsigned int height, unsigned int pixel_step,
double fx, double fy, double cx, double cy);
bool clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz);
bool clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
double raytrace_range, unsigned int cell_raytrace_range,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clearDepthColumns(double ox, double oy, double cover_distance, double far_distance,
double min_range, double max_range, double skip_dist,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const;
/// Paired depth marking: the checker of the same frame gates marking at the image
/// border and the store records evidence points. Null for every other source.
struct PairedMarking
{
const DepthVisibilityChecker* checker;
const DepthFrustumConfig* config;
};
void markObservation(const Observation& observation, double* min_x, double* min_y,
double* max_x, double* max_y, const PairedMarking* paired = nullptr);
void processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y);
struct VisibilityCounts
{
uint64_t free{0}, unknown{0}, surface{0}, frames{0};
uint64_t by_evidence{0}; ///< decisions made from evidence points
uint64_t border_dropped{0}; ///< marking points dropped at the image border
/// re-observe-or-clear outcomes per voxel and frame
uint64_t confirmed{0}, occluded{0}, seen_through{0}, no_return{0}, out_of_view{0};
} visibility_counts_;
/// Re-observe-or-clear: applies one frame's observation to the voxel's miss count.
/// Returns true when the voxel is to be freed.
bool reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key,
const DepthFrustumConfig& config);
/// Window-independent key: local cell index plus the cells the rolling origin moved.
DepthEvidenceStore::VoxelKey evidenceKey(unsigned int x, unsigned int y, unsigned int z) const
{
return {static_cast<int>(x) + evidence_offset_x_, static_cast<int>(y) + evidence_offset_y_, z};
}
/// Drops evidence of voxels that left the window or are no longer MARKED.
void pruneDepthEvidence();
/// Frees every voxel of the column and its evidence points; the 2D cell is left to the caller.
void clearDepthColumn(unsigned int x, unsigned int y);
/// Paired depth only: the voxels under the footprint, which ObstacleLayer frees in 2D only.
void clearFootprintVoxels();
DepthEvidenceStore depth_evidence_;
int evidence_offset_x_ = 0;
int evidence_offset_y_ = 0;
uint64_t frames_since_evidence_prune_ = 0;
bool publish_voxel_;
robot_voxel_grid::VoxelGrid robot_voxel_grid_;
double z_resolution_, origin_z_;
/// Scratch for the full-column clearing pass (config lives per observation
/// source in DepthFrustumConfig): per depth-image pixel column, the nearest
/// return inside the obstacle height band certifies "no obstacle in this
/// direction closer than d". Cells along that 2D beam get their whole voxel
/// column cleared, removing marked voxels the per-pixel 3D rays cannot
/// reach (above the vertical FOV at close range).
struct DepthColumnStat
{
double min_band_dist = -1.0; ///< horizontal distance of nearest in-band return; < 0 = none
double azimuth = 0.0; ///< beam direction in the global frame
double best_row_delta = std::numeric_limits<double>::infinity();
bool has_ray = false; ///< column had at least one readable pixel
bool in_border = false; ///< column lies in a left/right no-disparity strip
};
std::vector<DepthColumnStat> depth_column_stats_;
unsigned int unknown_threshold_, mark_threshold_, size_z_;
robot_sensor_msgs::PointCloud clearing_endpoints_;
std::vector<unsigned char> rolling_costmap_scratch_;
std::vector<unsigned int> rolling_voxel_scratch_;
struct DepthRay
{
unsigned int u;
unsigned int v;
unsigned int col; ///< pixel-column index in the cache (border column included)
double x;
double y;
double z;
};
std::vector<DepthRay> depth_ray_cache_;
unsigned int cached_column_count_ = 0;
unsigned int cached_depth_width_ = 0;
unsigned int cached_depth_height_ = 0;
unsigned int cached_depth_pixel_step_ = 0;
double cached_fx_ = 0.0;
double cached_fy_ = 0.0;
double cached_cx_ = 0.0;
double cached_cy_ = 0.0;
inline bool worldToMap3DFloat(double wx, double wy, double wz, double& mx, double& my, double& mz)
{
if (wx < origin_x_ || wy < origin_y_ || wz < origin_z_)

View File

@@ -37,7 +37,6 @@
*********************************************************************/
#include <robot_costmap_2d/obstacle_layer.h>
#include <robot_costmap_2d/costmap_math.h>
#include <robot_costmap_2d/depth_evidence_store.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
@@ -124,25 +123,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
// now we need to split the topics based on whitespace which we can use a stringstream for
std::stringstream ss(topics_string);
struct CloudSourceDefinition
{
boost::shared_ptr<ObservationBuffer> buffer;
CloudProcessingConfig processing;
std::string topic, data_type;
double min_height, max_height, keep_time, expected_period;
bool marking, clearing;
};
struct DepthSourceDefinition
{
boost::shared_ptr<ObservationBuffer> buffer;
DepthFrustumConfig config;
std::string topic, data_type;
double expected_period;
};
std::map<std::string, CloudSourceDefinition> cloud_sources;
std::vector<DepthSourceDefinition> depth_sources;
paired_depth_sources_.clear();
std::string source;
callback_infos_.clear();
while (ss >> source)
@@ -151,9 +131,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
double observation_keep_time = 0, expected_update_rate = 0, min_obstacle_height = 0, max_obstacle_height = 2;
std::string topic = "map", sensor_frame = "laser_frame", data_type = "PointCloud";
bool inf_is_valid = false, clearing=false, marking=true;
bool frustum_clearing_enabled = false;
int frustum_pixel_step = 8;
DepthFrustumConfig frustum_config;
robot::NodeHandle priv_nh(nh, source);
topic = loadParam(layer[source],"topic", topic);
@@ -166,34 +143,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
inf_is_valid = loadParam(layer[source],"inf_is_valid", false);
clearing = loadParam(layer[source],"clearing", false);
marking = loadParam(layer[source],"marking", true);
// frustum params are per-source; the layer-level key is kept as a
// fallback for older YAMLs
frustum_clearing_enabled = loadParam(layer[source], "frustum_clearing_enabled",
loadParam(layer, "frustum_clearing_enabled", false));
frustum_pixel_step = loadParam(layer[source], "frustum_clearing_pixel_step",
loadParam(layer, "frustum_clearing_pixel_step", 8));
frustum_config.min_range = loadParam(layer[source], "frustum_min_range",
loadParam(layer, "frustum_min_range", 0.2));
frustum_config.max_range = loadParam(layer[source], "frustum_max_range",
loadParam(layer, "frustum_max_range", 3.0));
frustum_config.skip_distance =
loadParam(layer[source], "frustum_skip_distance", frustum_config.skip_distance);
frustum_config.column_clearing =
loadParam(layer[source], "frustum_column_clearing", frustum_config.column_clearing);
frustum_config.column_min_height =
loadParam(layer[source], "column_clear_min_height", frustum_config.column_min_height);
frustum_config.column_max_height =
loadParam(layer[source], "column_clear_max_height", frustum_config.column_max_height);
frustum_config.column_skip_distance =
loadParam(layer[source], "column_skip_distance", frustum_config.column_skip_distance);
frustum_config.column_cover_distance =
loadParam(layer[source], "column_cover_distance", frustum_config.column_cover_distance);
int frustum_clear_left_border =
loadParam(layer[source], "frustum_clear_left_border_px",
loadParam(layer, "frustum_clear_left_border_px", 0));
int frustum_clear_right_border =
loadParam(layer[source], "frustum_clear_right_border_px",
loadParam(layer, "frustum_clear_right_border_px", 0));
if (priv_nh.hasParam("topic"))
priv_nh.getParam("topic", topic);
@@ -215,133 +164,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
priv_nh.getParam("clearing", clearing);
if (priv_nh.hasParam("marking"))
priv_nh.getParam("marking", marking);
if (priv_nh.hasParam("frustum_clearing_enabled"))
priv_nh.getParam("frustum_clearing_enabled", frustum_clearing_enabled);
if (priv_nh.hasParam("frustum_clearing_pixel_step"))
{
priv_nh.getParam("frustum_clearing_pixel_step", frustum_pixel_step);
frustum_pixel_step = std::max(1, frustum_pixel_step);
}
if (priv_nh.hasParam("frustum_min_range"))
priv_nh.getParam("frustum_min_range", frustum_config.min_range);
if (priv_nh.hasParam("frustum_max_range"))
priv_nh.getParam("frustum_max_range", frustum_config.max_range);
if (priv_nh.hasParam("frustum_skip_distance"))
priv_nh.getParam("frustum_skip_distance", frustum_config.skip_distance);
if (priv_nh.hasParam("frustum_column_clearing"))
priv_nh.getParam("frustum_column_clearing", frustum_config.column_clearing);
if (priv_nh.hasParam("column_clear_min_height"))
priv_nh.getParam("column_clear_min_height", frustum_config.column_min_height);
if (priv_nh.hasParam("column_clear_max_height"))
priv_nh.getParam("column_clear_max_height", frustum_config.column_max_height);
if (priv_nh.hasParam("column_skip_distance"))
priv_nh.getParam("column_skip_distance", frustum_config.column_skip_distance);
if (priv_nh.hasParam("column_cover_distance"))
priv_nh.getParam("column_cover_distance", frustum_config.column_cover_distance);
if (priv_nh.hasParam("frustum_clear_left_border_px"))
priv_nh.getParam("frustum_clear_left_border_px", frustum_clear_left_border);
if (priv_nh.hasParam("frustum_clear_right_border_px"))
priv_nh.getParam("frustum_clear_right_border_px", frustum_clear_right_border);
if (priv_nh.hasParam("frustum_depth_camera_topic"))
priv_nh.getParam("frustum_depth_camera_topic", depth_camera_data_topic_);
const auto read_depth_option = [&](const char* key, auto& value) {
value = loadParam(layer[source], key, value);
if (priv_nh.hasParam(key)) priv_nh.getParam(key, value);
};
std::string depth_mode = "legacy";
read_depth_option("depth_clearing_mode", depth_mode);
if (depth_mode != "legacy" && depth_mode != "observed_volume")
throw std::invalid_argument("unknown depth_clearing_mode: " + depth_mode);
frustum_config.observed_volume_clearing = depth_mode == "observed_volume";
read_depth_option("paired_marking_source", frustum_config.paired_marking_source);
int pair_queue = 4, projection_margin = 1;
read_depth_option("depth_pair_queue_size", pair_queue);
read_depth_option("depth_pair_max_wait_s", frustum_config.pair_max_wait_s);
read_depth_option("depth_observation_max_age_s", frustum_config.observation_max_age_s);
read_depth_option("depth_valid_min_z_m", frustum_config.valid_min_z_m);
read_depth_option("depth_valid_max_z_m", frustum_config.valid_max_z_m);
read_depth_option("depth_free_margin_m", frustum_config.free_margin_m);
read_depth_option("depth_projection_margin_px", projection_margin);
read_depth_option("depth_voxel_z_resolution_m", frustum_config.voxel_z_resolution_m);
if (pair_queue < 1 || pair_queue > 64 || projection_margin < 0 || projection_margin > 16)
throw std::invalid_argument("depth pair queue/projection margin out of bounds");
frustum_config.pair_queue_size = static_cast<unsigned int>(pair_queue);
frustum_config.projection_margin_px = static_cast<unsigned int>(projection_margin);
if (frustum_config.observed_volume_clearing &&
(!frustum_clearing_enabled || data_type != "DepthCameraData"))
throw std::invalid_argument("observed_volume requires a DepthCameraData frustum source");
if (frustum_config.observed_volume_clearing &&
(!std::isfinite(frustum_config.valid_min_z_m) || frustum_config.valid_min_z_m <= 0 ||
!std::isfinite(frustum_config.valid_max_z_m) || frustum_config.valid_max_z_m <= frustum_config.valid_min_z_m ||
!std::isfinite(frustum_config.free_margin_m) || frustum_config.free_margin_m < 0))
throw std::invalid_argument("observed_volume requires finite optical depth limits and free margin");
if (frustum_config.observed_volume_clearing &&
(!std::isfinite(frustum_config.voxel_z_resolution_m) || frustum_config.voxel_z_resolution_m <= 0))
throw std::invalid_argument("observed_volume requires finite positive voxel z resolution");
int evidence_points = static_cast<int>(frustum_config.evidence_points_per_voxel);
int marking_border = static_cast<int>(frustum_config.marking_border_px);
read_depth_option("depth_evidence_points_enabled", frustum_config.evidence_points_enabled);
read_depth_option("depth_evidence_points_per_voxel", evidence_points);
read_depth_option("depth_marking_border_px", marking_border);
if (evidence_points < static_cast<int>(DepthEvidenceStore::kExtremeSlots) ||
evidence_points > static_cast<int>(DepthEvidenceStore::kMaxPoints) ||
marking_border < 0 || marking_border > 64)
throw std::invalid_argument("depth_evidence_points_per_voxel must be 6..16 and "
"depth_marking_border_px 0..64");
frustum_config.evidence_points_per_voxel = static_cast<unsigned int>(evidence_points);
frustum_config.marking_border_px = static_cast<unsigned int>(marking_border);
if (frustum_config.evidence_points_enabled && !frustum_config.observed_volume_clearing)
throw std::invalid_argument("depth_evidence_points_enabled requires depth_clearing_mode: observed_volume");
read_depth_option("depth_far_return_is_behind", frustum_config.far_return_is_behind);
if (frustum_config.far_return_is_behind && !frustum_config.evidence_points_enabled)
throw std::invalid_argument("depth_far_return_is_behind requires depth_evidence_points_enabled");
int miss_frames = static_cast<int>(frustum_config.miss_frames);
int band_margin = static_cast<int>(frustum_config.stereo_band_margin_px);
read_depth_option("depth_reobserve_clearing", frustum_config.reobserve_clearing);
read_depth_option("depth_confirm_tolerance_m", frustum_config.confirm_tolerance_m);
read_depth_option("depth_miss_frames", miss_frames);
read_depth_option("depth_no_return_weight", frustum_config.no_return_weight);
read_depth_option("depth_stereo_baseline_m", frustum_config.stereo_baseline_m);
read_depth_option("depth_stereo_band_margin_px", band_margin);
if ((frustum_config.reobserve_clearing || frustum_config.stereo_baseline_m > 0) &&
!frustum_config.evidence_points_enabled)
throw std::invalid_argument("depth_reobserve_clearing and depth_stereo_baseline_m require "
"depth_evidence_points_enabled");
if (!std::isfinite(frustum_config.confirm_tolerance_m) || frustum_config.confirm_tolerance_m <= 0 ||
frustum_config.confirm_tolerance_m > 0.5 || miss_frames < 1 || miss_frames > 100 ||
!std::isfinite(frustum_config.no_return_weight) || frustum_config.no_return_weight < 0 ||
frustum_config.no_return_weight > 1 || !std::isfinite(frustum_config.stereo_baseline_m) ||
frustum_config.stereo_baseline_m < 0 || frustum_config.stereo_baseline_m > 1 ||
band_margin < 0 || band_margin > 200)
throw std::invalid_argument("depth_confirm_tolerance_m must be in (0, 0.5] m, depth_miss_frames 1..100, "
"depth_no_return_weight 0..1, depth_stereo_baseline_m 0..1 m and "
"depth_stereo_band_margin_px 0..200");
frustum_config.miss_frames = static_cast<unsigned int>(miss_frames);
frustum_config.stereo_band_margin_px = static_cast<unsigned int>(band_margin);
// One pixel more than the patch radius absorbs rounding of the stored float points,
// so every kept evidence point is re-checked with a full patch from its own pose.
if (frustum_config.evidence_points_enabled &&
frustum_config.marking_border_px <= frustum_config.projection_margin_px)
throw std::invalid_argument("depth_marking_border_px must be > depth_projection_margin_px "
"when depth_evidence_points_enabled is true");
frustum_config.pixel_step = static_cast<unsigned int>(std::max(1, frustum_pixel_step));
frustum_config.clear_left_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_left_border));
frustum_config.clear_right_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_right_border));
robot::log_info("source %s: frustum_clearing_enabled: %s, pixel_step: %u, range: [%.2f, %.2f] m, "
"skip: %.3f m, column_clearing: %s, column_band: [%.2f, %.2f] m, "
"column_skip: %.3f m, column_cover: %.2f m, clear_left_border_px: %u px, "
"clear_right_border_px: %u px\n",
source.c_str(), frustum_clearing_enabled ? "true" : "false",
frustum_config.pixel_step, frustum_config.min_range, frustum_config.max_range,
frustum_config.skip_distance, frustum_config.column_clearing ? "true" : "false",
frustum_config.column_min_height, frustum_config.column_max_height,
frustum_config.column_skip_distance, frustum_config.column_cover_distance,
frustum_config.clear_left_border_px, frustum_config.clear_right_border_px);
double obstacle_range = 2.5;
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
@@ -353,133 +175,50 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (priv_nh.hasParam("raytrace_range"))
priv_nh.getParam("raytrace_range", raytrace_range);
CloudProcessingConfig cloud_processing;
cloud_processing.transform_at_stamp =
loadParam(layer[source], "cloud_transform_at_stamp", false);
const YAML::Node voxel_filter = layer[source]["marking_voxel_filter"];
if (voxel_filter && voxel_filter.IsMap())
// Depth images are handled by DepthCameraObstacleLayer; the frustum clearing that used to
// live here was removed. Fail at startup instead of silently dropping a camera.
if (data_type == "DepthCameraData" ||
loadParam(layer[source], "frustum_clearing_enabled", false))
{
cloud_processing.voxel_filter_enabled = loadParam(voxel_filter, "enabled", false);
cloud_processing.voxel_leaf_size = loadParam(voxel_filter, "leaf_size_m", 0.05);
robot::log_error("source %s: DepthCameraData / frustum_clearing_enabled are no longer supported by "
"ObstacleLayer/VoxelLayer, use a DepthCameraObstacleLayer plugin\n", source.c_str());
throw std::invalid_argument("source " + source + ": depth frustum clearing was removed from "
"ObstacleLayer/VoxelLayer, use DepthCameraObstacleLayer");
}
if (priv_nh.hasParam("cloud_transform_at_stamp"))
priv_nh.getParam("cloud_transform_at_stamp", cloud_processing.transform_at_stamp);
if (priv_nh.hasParam("marking_voxel_filter/enabled"))
priv_nh.getParam("marking_voxel_filter/enabled", cloud_processing.voxel_filter_enabled);
if (priv_nh.hasParam("marking_voxel_filter/leaf_size_m"))
priv_nh.getParam("marking_voxel_filter/leaf_size_m", cloud_processing.voxel_leaf_size);
if (cloud_processing.voxel_filter_enabled &&
(data_type != "PointCloud2" || !marking || clearing || frustum_clearing_enabled))
throw std::invalid_argument("marking_voxel_filter requires a marking-only PointCloud2 source");
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan" || data_type == "DepthCameraData"))
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan"))
{
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
throw std::runtime_error("Only topics that use point clouds or laser scans are currently supported");
}
if(!frustum_clearing_enabled)
{
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// enabled_ = enabled;
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
if (marking)
marking_buffers_.push_back(observation_buffers_.back());
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
observation_buffers_.back()->setCloudProcessingConfig(cloud_processing);
cloud_sources.emplace(source, CloudSourceDefinition{observation_buffers_.back(), cloud_processing,
topic, data_type, min_obstacle_height, max_obstacle_height, observation_keep_time,
expected_update_rate, marking, clearing});
robot::log_info("source %s: cloud_tf=%s height=[%.3f, %.3f] m range=%.3f m; "
"PCL_after_height_range=%s leaf=%.3f m\n", source.c_str(),
cloud_processing.transform_at_stamp ? "measurement_stamp" : "latest",
min_obstacle_height, max_obstacle_height, obstacle_range,
cloud_processing.voxel_filter_enabled ? "true" : "false",
cloud_processing.voxel_leaf_size);
if (marking)
marking_buffers_.push_back(observation_buffers_.back());
// check if we'll also add this buffer to our clearing observation buffers
if (clearing)
clearing_buffers_.push_back(observation_buffers_.back());
}
else
{
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_depth_infos_.push_back(info_tmp);
depth_observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, frustum_config,
*tf_, global_frame_,
sensor_frame, transform_tolerance)));
depth_sources.push_back({depth_observation_buffers_.back(), frustum_config,
topic, data_type, expected_update_rate});
}
// check if we'll also add this buffer to our clearing observation buffers
if (clearing)
clearing_buffers_.push_back(observation_buffers_.back());
robot::log_info(
"Created an observation buffer for topic %s, global frame: %s, "
"expected update rate: %.2f, observation persistence: %.2f\n",
topic.c_str(), global_frame_.c_str(), expected_update_rate, observation_keep_time);
}
for (const auto& depth_source : depth_sources)
{
if (!depth_source.config.observed_volume_clearing) continue;
const auto marker = cloud_sources.find(depth_source.config.paired_marking_source);
if (marker == cloud_sources.end() || marker->second.data_type != "PointCloud2" ||
!marker->second.marking || marker->second.clearing || marker->second.keep_time != 0 ||
!marker->second.processing.transform_at_stamp || getType() != LayerType::VOXEL_LAYER)
throw std::invalid_argument("observed_volume needs a timestamped marking-only PointCloud2 pair with persistence=0");
for (const auto& other : cloud_sources)
if (other.first != marker->first && (other.second.marking || other.second.clearing))
throw std::invalid_argument("observed_volume depth must use its own VoxelLayer; mixed sensor ownership is unsupported");
if (!paired_depth_sources_.empty() || depth_sources.size() != 1)
throw std::invalid_argument("observed_volume supports one depth camera per VoxelLayer");
const auto& m = marker->second;
double period = m.expected_period;
if (period <= 0 || (depth_source.expected_period > 0 && depth_source.expected_period < period))
period = depth_source.expected_period;
auto paired = boost::make_shared<PairedDepthSource>(depth_source.config, period);
paired->cloud_topic = m.topic; paired->depth_topic = depth_source.topic;
paired->marking_buffer = m.buffer; paired->depth_buffer = depth_source.buffer;
paired->min_height = m.min_height; paired->max_height = m.max_height;
paired_depth_sources_.push_back(paired);
marking_buffers_.erase(std::remove(marking_buffers_.begin(), marking_buffers_.end(), m.buffer), marking_buffers_.end());
robot::log_info("depth clearing observed_volume: paired %s + %s, height=[%.3f, %.3f] m; "
"unknown/occluded/outside FOV retained; queue=%u age=%.3f s; rule=%s; "
"evidence_points=%s per_voxel=%u marking_border=%u px projection_margin=%u px "
"far_return_behind=%s; reobserve tolerance=%.3f m miss_frames=%u no_return_weight=%.2f; "
"stereo_baseline=%.3f m band_margin=%u px\n",
paired->cloud_topic.c_str(), paired->depth_topic.c_str(), m.min_height, m.max_height,
paired->config.pair_queue_size, paired->config.observation_max_age_s,
paired->config.reobserve_clearing ? "re-observe or clear" : "one valid free frame",
paired->config.evidence_points_enabled ? "true" : "false",
paired->config.evidence_points_per_voxel, paired->config.marking_border_px,
paired->config.projection_margin_px,
paired->config.far_return_is_behind ? "true" : "false",
paired->config.confirm_tolerance_m, paired->config.miss_frames,
paired->config.no_return_weight, paired->config.stereo_baseline_m,
paired->config.stereo_band_margin_px);
}
}
catch (const YAML::BadFile& e) {
robot::log_error("Cannot open YAML file: %s\n", e.what());
@@ -497,147 +236,60 @@ void ObstacleLayer::handleImpl(const void* data,
if (!enabled_ || stop_receiving_data_)
return;
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr))
// DepthCameraData and other types are for other layers sharing this gateway; ignored here.
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
{
const robot_sensor_msgs::DepthCameraData::ConstPtr& depth_camera_data_ptr =
*static_cast<const robot_sensor_msgs::DepthCameraData::ConstPtr*>(data);
if (!depth_camera_data_ptr)
return;
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
const robot_sensor_msgs::DepthCameraData& depth_camera_data =
*depth_camera_data_ptr;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
std::size_t bytes_per_pixel = 0;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
bytes_per_pixel = 2;
else if (depth.encoding == "32FC1")
bytes_per_pixel = 4;
else
{
robot::log_error("ObstacleLayer received unsupported depth encoding: %s\n", depth.encoding.c_str());
return;
}
const bool invalid_dimensions = depth.width == 0 || depth.height == 0 ||
depth.step < static_cast<std::size_t>(depth.width) * bytes_per_pixel ||
depth.data.size() < static_cast<std::size_t>(depth.step) * depth.height;
if (invalid_dimensions)
{
robot::log_error("ObstacleLayer received malformed DepthCameraData image\n");
return;
}
if (camera_info.K[0] <= 0.0 || camera_info.K[4] <= 0.0)
{
robot::log_error("ObstacleLayer received invalid camera intrinsics for depth clearing\n");
return;
}
if ((camera_info.width != 0 && camera_info.width != depth.width) ||
(camera_info.height != 0 && camera_info.height != depth.height))
{
robot::log_error("ObstacleLayer received mismatched depth image and camera info dimensions\n");
return;
}
const std::string& depth_frame = depth.header.frame_id;
const std::string& camera_frame = camera_info.header.frame_id;
if (!depth_frame.empty() && !camera_frame.empty() && depth_frame != camera_frame)
{
robot::log_error("ObstacleLayer received mismatched depth and camera-info frames: %s != %s\n",
depth_frame.c_str(), camera_frame.c_str());
return;
}
if (depth_camera_data.header.frame_id.empty() && depth_frame.empty() && camera_frame.empty())
{
robot::log_error("ObstacleLayer received DepthCameraData without an optical frame\n");
return;
}
// std::lock_guard<std::mutex> lock(depth_camera_data_mutex_);
// pending_depth_camera_data_ = depth_camera_data_ptr;
if (depth_observation_buffers_.empty() || callback_depth_infos_.empty())
return;
int size_callback_depth = static_cast<int>(callback_depth_infos_.size());
for(int i = 0; i < size_callback_depth; i++)
{
boost::shared_ptr<ObservationBuffer>& buffer = depth_observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr) &&
topic == callback_depth_infos_[i].topic)
{
// robot::log_error_throttle(1.0,"TEST");
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->depth_topic == topic)
{ source->pairer.addDepth(depth_camera_data_ptr); paired = true; break; }
if (!paired) depthImageCallback(depth_camera_data_ptr, buffer);
}
}
}
else
{
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->cloud_topic == topic)
{ source->pairer.addCloud(*static_cast<const robot_sensor_msgs::PointCloud2*>(data)); paired = true; break; }
if (!paired) pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
}
}
@@ -739,14 +391,6 @@ void ObstacleLayer::pointCloud2Callback(const robot_sensor_msgs::PointCloud2& me
buffer->unlock();
}
void ObstacleLayer::depthImageCallback(robot_sensor_msgs::DepthCameraData::ConstPtr message,
const boost::shared_ptr<ObservationBuffer>& buffer)
{
buffer->lock();
buffer->bufferDepthCamera(std::move(message));
buffer->unlock();
}
void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
@@ -916,39 +560,6 @@ bool ObstacleLayer::getClearingObservations(std::vector<Observation>& clearing_o
return current;
}
bool ObstacleLayer::getFrustumClearingObservations(std::vector<DepthCameraObservation>& frustum_clearing_observations) const
{
bool current = true;
// DepthCameraObservation depth_obs;
for (const boost::shared_ptr<ObservationBuffer>& buffer : depth_observation_buffers_)
{
bool paired = false;
for (const auto& source : paired_depth_sources_)
if (source->depth_buffer == buffer) { paired = true; break; }
if (paired) continue;
buffer->lock();
buffer->getDepthObservations(frustum_clearing_observations);
current = buffer->isCurrent() && current;
buffer->unlock();
// frustum_clearing_observations.push_back(depth_obs);
}
return current;
}
bool ObstacleLayer::pairedDepthCurrent() const
{
bool current = true;
for (const auto& source : paired_depth_sources_) current = source->pairer.isCurrent() && current;
return current;
}
void ObstacleLayer::resetPairedDepth()
{
for (const auto& source : paired_depth_sources_) source->pairer.reset();
}
void ObstacleLayer::raytraceFreespace(const Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_y)
{

View File

@@ -36,7 +36,6 @@
* David V. Lu!!
*********************************************************************/
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/depth_visibility.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <robot_geometry_msgs/Vector3.h>
@@ -46,7 +45,6 @@
#include <cmath>
#include <cstdint>
#include <cstring>
#include <array>
#define VOXEL_BITS 16
@@ -73,18 +71,6 @@ void VoxelLayer::onInitialize()
VoxelLayer::~VoxelLayer()
{}
VoxelGrid VoxelLayer::voxelSnapshot()
{
VoxelGrid out;
out.header.frame_id = global_frame_;
out.header.stamp = robot::Time::now();
out.size_x = size_x_; out.size_y = size_y_; out.size_z = size_z_;
out.origin.x = origin_x_; out.origin.y = origin_y_; out.origin.z = origin_z_;
out.resolutions.x = out.resolutions.y = resolution_; out.resolutions.z = z_resolution_;
out.data.assign(robot_voxel_grid_.getData(), robot_voxel_grid_.getData() + size_x_ * size_y_);
return out;
}
bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandle &nh)
{
try
@@ -113,7 +99,7 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
mark_threshold_ = loadParam(layer, "mark_threshold", 0);
combination_method_ = loadParam(layer, "combination_method", 0.0);
int size_z, unknown_threshold, mark_threshold, frustum_pixel_step;
int size_z, unknown_threshold, mark_threshold;
if (nh.hasParam("enabled"))
nh.getParam("enabled", enabled_);
if (nh.hasParam("footprint_clearing_enabled"))
@@ -140,20 +126,6 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
if (nh.hasParam("combination_method"))
nh.getParam("combination_method", combination_method_);
if (!paired_depth_sources_.empty())
{
z_resolution_ = paired_depth_sources_.front()->config.voxel_z_resolution_m;
const auto& source = paired_depth_sources_.front();
if (!size_z_ || size_z_ > VOXEL_BITS || source->min_height < origin_z_ ||
source->max_height > origin_z_ + size_z_ * z_resolution_)
throw std::invalid_argument("observed_volume marking height band must fit its voxel grid");
robot::log_info("observed_volume grid: z_resolution=%.4f m bins=%u span=[%.3f, %.3f) m\n",
z_resolution_, size_z_, origin_z_, origin_z_ + size_z_ * z_resolution_);
depth_evidence_.setPointsPerVoxel(source->config.evidence_points_per_voxel);
robot::log_info("observed_volume evidence points: %s, points_per_voxel=%u, marking_border_px=%u px\n",
source->config.evidence_points_enabled ? "enabled" : "disabled (whole-voxel check)",
depth_evidence_.pointsPerVoxel(), source->config.marking_border_px);
}
this->matchSize();
}
catch (const YAML::BadFile& e) {
@@ -168,7 +140,6 @@ void VoxelLayer::matchSize()
{
ObstacleLayer::matchSize();
robot_voxel_grid_.resize(size_x_, size_y_, size_z_);
depth_evidence_.clear();
if (!(robot_voxel_grid_.sizeX() == size_x_ && robot_voxel_grid_.sizeY() == size_y_))
{
std::cerr << "[FATAL] Voxel grid size mismatch: "
@@ -188,10 +159,8 @@ void VoxelLayer::reset()
void VoxelLayer::resetMaps()
{
resetPairedDepth();
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
depth_evidence_.clear();
}
void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
@@ -201,16 +170,8 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
useExtraBounds(min_x, min_y, max_x, max_y);
if (!paired_depth_sources_.empty() &&
(!static_marking_observations_.empty() || !static_clearing_observations_.empty()))
{
current_ = false;
robot::log_error_throttle(5.0, "observed_volume cannot share its voxel grid with static observations\n");
return;
}
bool current = true;
std::vector<Observation> observations, clearing_observations;
std::vector<DepthCameraObservation> depth_observations;
// get the marking observations
current = getMarkingObservations(observations) && current;
@@ -218,82 +179,19 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
// get the clearing observations
current = getClearingObservations(clearing_observations) && current;
current = getFrustumClearingObservations(depth_observations) && current;
// update the global current status
current_ = current;
for (const DepthCameraObservation& depth_observation : depth_observations)
{
raytraceDepthFrustum(depth_observation, min_x, min_y, max_x, max_y);
}
// raytrace freespace
for (unsigned int i = 0; i < clearing_observations.size(); ++i)
{
raytraceFreespace(clearing_observations[i], min_x, min_y, max_x, max_y);
}
for (const auto& observation : observations)
markObservation(observation, min_x, min_y, max_x, max_y);
processPairedDepth(min_x, min_y, max_x, max_y);
current_ = current_ && pairedDepthCurrent();
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
if (footprint_clearing_enabled_ && !paired_depth_sources_.empty())
clearFootprintVoxels();
}
void VoxelLayer::clearDepthColumn(unsigned int x, unsigned int y)
{
if (x >= size_x_ || y >= size_y_)
return;
const unsigned int index = getIndex(x, y);
if (robot_voxel_grid_.getData()[index] >> 16)
for (unsigned int z = 0; z < size_z_; ++z)
depth_evidence_.erase(evidenceKey(x, y, z));
robot_voxel_grid_.clearVoxelColumn(index);
}
void VoxelLayer::clearFootprintVoxels()
{
if (transformed_footprint_.size() < 3)
return;
std::vector<MapLocation> map_polygon;
for (const auto& point : transformed_footprint_)
// place the new obstacles into a priority queue... each with a priority of zero to begin with
for (std::vector<Observation>::const_iterator it = observations.begin(); it != observations.end(); ++it)
{
MapLocation location;
// Same rule as setConvexPolygonCost: a footprint partly outside the window clears nothing.
if (!worldToMap(point.x, point.y, location.x, location.y))
return;
map_polygon.push_back(location);
}
std::vector<MapLocation> cells;
convexFillCells(map_polygon, cells);
for (const auto& cell : cells)
{
clearDepthColumn(cell.x, cell.y);
costmap_[getIndex(cell.x, cell.y)] = FREE_SPACE;
}
}
void VoxelLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area)
{
// Same cell selection as CostmapLayer::clearArea, which then writes the 2D cells.
for (int x = 0; x < static_cast<int>(size_x_); ++x)
{
const bool xrange = x > start_x && x < end_x;
for (int y = 0; y < static_cast<int>(size_y_); ++y)
if ((xrange && y > start_y && y < end_y) == invert_area)
clearDepthColumn(static_cast<unsigned int>(x), static_cast<unsigned int>(y));
}
CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area);
}
void VoxelLayer::markObservation(const Observation& obs, double* min_x, double* min_y,
double* max_x, double* max_y, const PairedMarking* paired)
{
const bool record_evidence = paired != nullptr && paired->config->evidence_points_enabled;
const Observation& obs = *it;
const robot_sensor_msgs::PointCloud2& cloud = *(obs.cloud_);
@@ -330,21 +228,6 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
continue;
}
bool fresh_voxel = false;
if (record_evidence)
{
// A point at the image edge could never be re-checked with a full patch from the
// pose that saw it, and would leave a voxel that only the whole-box rule judges.
const Eigen::Vector3d point(*iter_x, *iter_y, *iter_z);
if ((paired->config->marking_border_px > 0 || paired->config->stereo_baseline_m > 0) &&
!paired->checker->projectsInside(point, paired->config->marking_border_px))
{
++visibility_counts_.border_dropped;
continue;
}
fresh_voxel = robot_voxel_grid_.getVoxel(mx, my, mz) != robot_voxel_grid::MARKED;
}
// mark the cell in the voxel grid and check if we should also mark it in the costmap
if (robot_voxel_grid_.markVoxelInMap(mx, my, mz, mark_threshold_))
{
@@ -353,184 +236,9 @@ void VoxelLayer::markObservation(const Observation& obs, double* min_x, double*
costmap_[index] = LETHAL_OBSTACLE;
touch(double(*iter_x), double(*iter_y), min_x, min_y, max_x, max_y);
}
if (record_evidence)
depth_evidence_.add(evidenceKey(mx, my, mz), Eigen::Vector3f(*iter_x, *iter_y, *iter_z), fresh_voxel);
}
}
void VoxelLayer::pruneDepthEvidence()
{
if (depth_evidence_.size() == 0)
return;
depth_evidence_.eraseIf([this](const DepthEvidenceStore::VoxelKey& key) {
const int x = key.x - evidence_offset_x_;
const int y = key.y - evidence_offset_y_;
return x < 0 || y < 0 || x >= static_cast<int>(size_x_) || y >= static_cast<int>(size_y_) ||
key.z >= size_z_ ||
robot_voxel_grid_.getVoxel(static_cast<unsigned int>(x), static_cast<unsigned int>(y), key.z) !=
robot_voxel_grid::MARKED;
});
}
bool VoxelLayer::reobserveFrees(DepthObservation observation, const DepthEvidenceStore::VoxelKey& key,
const DepthFrustumConfig& config)
{
float miss = 0.f;
switch (observation)
{
case DepthObservation::Confirmed:
++visibility_counts_.confirmed;
depth_evidence_.resetMiss(key);
return false;
case DepthObservation::Occluded:
++visibility_counts_.occluded;
return false;
case DepthObservation::OutOfView:
++visibility_counts_.out_of_view;
return false;
case DepthObservation::SeenThrough:
++visibility_counts_.seen_through;
miss = depth_evidence_.addMiss(key, 1.f);
break;
case DepthObservation::NoReturn:
++visibility_counts_.no_return;
if (config.no_return_weight <= 0)
return false;
miss = depth_evidence_.addMiss(key, static_cast<float>(config.no_return_weight));
break;
}
// The small slack absorbs float rounding when fractional no-return weights add up.
return miss >= static_cast<float>(config.miss_frames) - 1e-3f;
}
void VoxelLayer::processPairedDepth(double* min_x, double* min_y, double* max_x, double* max_y)
{
for (const auto& source : paired_depth_sources_)
{
DepthFramePairer::Candidate pair;
while (source->pairer.next(pair))
{
tf3::TransformStampedMsg pose;
try
{
pose = tf_->lookupTransform(global_frame_, pair.cloud->header.frame_id,
data_convert::convertTime(pair.cloud->header.stamp));
}
catch (const tf3::TransformException& ex)
{
source->pairer.noteTfWait();
robot::log_error_throttle(5.0, "paired depth waiting for measurement TF: %s\n", ex.what());
break; // retain occupancy and bounded pending pair, never use latest TF
}
DepthVisibilityChecker checker;
if (!checker.prepare(pair.depth, pose, source->min_height,
std::min(source->max_height, max_obstacle_height_), source->config))
{
source->pairer.discard(pair.stamp);
robot::log_error_throttle(5.0, "paired depth rejected invalid image/model/pose\n");
continue;
}
std::vector<Observation> observations;
bool buffered;
{
std::lock_guard<ObservationBuffer> guard(*source->marking_buffer);
buffered = source->marking_buffer->tryBufferCloudWithTransform(*pair.cloud, pose);
if (buffered) source->marking_buffer->getObservations(observations);
}
if (!buffered || observations.size() != 1 ||
observations.front().cloud_->header.stamp.toNSec() != pair.stamp)
{
source->pairer.discard(pair.stamp);
continue; // no partial clear when marking branch cannot be prepared
}
// No occupied cache: the live voxel grid already contains rolling-window overlap.
// Plan all clears before applying this frame; both branches share exactly one pose.
// With evidence points a voxel is judged by the points that marked it; a voxel
// without evidence (marked before the mode was enabled) keeps the whole-box rule.
const bool use_evidence = source->config.evidence_points_enabled;
const bool reobserve = use_evidence && source->config.reobserve_clearing;
std::vector<Eigen::Vector3d> evidence;
std::vector<std::array<unsigned int, 3>> free_voxels;
for (unsigned int y = 0; y < size_y_; ++y)
for (unsigned int x = 0; x < size_x_; ++x)
{
if (!(robot_voxel_grid_.getData()[getIndex(x, y)] >> 16)) continue;
for (unsigned int z = 0; z < size_z_; ++z)
{
if (robot_voxel_grid_.getVoxel(x, y, z) != robot_voxel_grid::MARKED) continue;
DepthVisibilityResult visibility;
const auto key = evidenceKey(x, y, z);
if (use_evidence && depth_evidence_.points(key, evidence))
{
++visibility_counts_.by_evidence;
if (reobserve)
{
if (reobserveFrees(checker.observePoints(evidence), key, source->config))
{ free_voxels.push_back({x, y, z}); ++visibility_counts_.free; }
continue;
}
visibility = checker.classifyPoints(evidence);
}
else
{
const Eigen::Vector3d lower(origin_x_ + x * resolution_,
origin_y_ + y * resolution_, origin_z_ + z * z_resolution_);
const Eigen::Vector3d upper = lower + Eigen::Vector3d(resolution_, resolution_, z_resolution_);
visibility = checker.classify(lower, upper);
}
if (visibility.state == DepthVisibility::Free)
{ free_voxels.push_back({x, y, z}); ++visibility_counts_.free; }
else if (visibility.state == DepthVisibility::Surface) ++visibility_counts_.surface;
else ++visibility_counts_.unknown;
}
}
for (const auto& voxel : free_voxels)
{
const auto x = voxel[0], y = voxel[1], z = voxel[2];
robot_voxel_grid_.clearVoxel(x, y, z);
depth_evidence_.erase(evidenceKey(x, y, z));
const auto status = robot_voxel_grid_.getVoxelColumn(x, y, unknown_threshold_, mark_threshold_);
costmap_[getIndex(x, y)] = status == robot_voxel_grid::MARKED ? LETHAL_OBSTACLE :
status == robot_voxel_grid::FREE ? FREE_SPACE : NO_INFORMATION;
// Include whole cell so master/inflation can remove the former obstacle.
touch(origin_x_ + x * resolution_, origin_y_ + y * resolution_, min_x, min_y, max_x, max_y);
touch(origin_x_ + (x + 1) * resolution_, origin_y_ + (y + 1) * resolution_, min_x, min_y, max_x, max_y);
}
const PairedMarking paired_marking{&checker, &source->config};
markObservation(observations.front(), min_x, min_y, max_x, max_y, &paired_marking);
source->pairer.applied(pair.stamp);
++visibility_counts_.frames;
// Voxels cleared by other paths (footprint, recovery, legacy rays) leave stale
// evidence; a bounded sweep keeps the store at the size of the live occupancy.
constexpr uint64_t kEvidencePrunePeriodFrames = 50;
if (use_evidence && ++frames_since_evidence_prune_ >= kEvidencePrunePeriodFrames)
{
pruneDepthEvidence();
frames_since_evidence_prune_ = 0;
}
}
const auto counts = source->pairer.counts();
robot::log_info_throttle(5.0, "paired depth [%s]: applied=%llu tf_wait=%llu "
"invalid=%llu stale=%llu expired=%llu overflow=%llu duplicate=%llu; "
"voxel decisions free=%llu surface=%llu unknown=%llu by_evidence=%llu; "
"reobserve confirmed=%llu occluded=%llu seen_through=%llu no_return=%llu out_of_view=%llu; "
"border_dropped_points=%llu evidence_voxels=%zu (cumulative)\n",
name_.c_str(), static_cast<unsigned long long>(counts.applied),
static_cast<unsigned long long>(counts.tf_wait), static_cast<unsigned long long>(counts.invalid),
static_cast<unsigned long long>(counts.stale), static_cast<unsigned long long>(counts.expired),
static_cast<unsigned long long>(counts.overflow), static_cast<unsigned long long>(counts.duplicate),
static_cast<unsigned long long>(visibility_counts_.free),
static_cast<unsigned long long>(visibility_counts_.surface),
static_cast<unsigned long long>(visibility_counts_.unknown),
static_cast<unsigned long long>(visibility_counts_.by_evidence),
static_cast<unsigned long long>(visibility_counts_.confirmed),
static_cast<unsigned long long>(visibility_counts_.occluded),
static_cast<unsigned long long>(visibility_counts_.seen_through),
static_cast<unsigned long long>(visibility_counts_.no_return),
static_cast<unsigned long long>(visibility_counts_.out_of_view),
static_cast<unsigned long long>(visibility_counts_.border_dropped), depth_evidence_.size());
}
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
}
void VoxelLayer::clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info)
@@ -681,545 +389,6 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
}
}
bool VoxelLayer::readDepthMeters(const robot_sensor_msgs::Image& depth, unsigned int u, unsigned int v,
double& depth_m, bool& is_valid) const
{
depth_m = 0.0;
is_valid = false;
if (u >= depth.width || v >= depth.height)
return false;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 2;
if (offset + sizeof(std::uint16_t) > depth.data.size())
return false;
std::uint16_t raw = 0;
if (depth.is_bigendian)
raw = static_cast<std::uint16_t>((depth.data[offset] << 8) | depth.data[offset + 1]);
else
raw = static_cast<std::uint16_t>(depth.data[offset] | (depth.data[offset + 1] << 8));
if (raw == 0)
return true;
depth_m = static_cast<double>(raw) * 0.001;
is_valid = true;
return true;
}
if (depth.encoding == "32FC1")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 4;
if (offset + sizeof(float) > depth.data.size())
return false;
float raw = 0.0f;
if (depth.is_bigendian)
{
unsigned char bytes[sizeof(float)] = {
depth.data[offset + 3], depth.data[offset + 2], depth.data[offset + 1], depth.data[offset]};
std::memcpy(&raw, bytes, sizeof(float));
}
else
{
std::memcpy(&raw, &depth.data[offset], sizeof(float));
}
if (!std::isfinite(raw) || raw <= 0.0f)
return true;
depth_m = static_cast<double>(raw);
is_valid = true;
return true;
}
robot::log_error("VoxelLayer unsupported depth encoding for frustum clearing: %s\n", depth.encoding.c_str());
return false;
}
void VoxelLayer::updateDepthRayCache(unsigned int width, unsigned int height,
unsigned int pixel_step, double fx, double fy,
double cx, double cy)
{
if (cached_depth_width_ == width && cached_depth_height_ == height &&
cached_depth_pixel_step_ == pixel_step && cached_fx_ == fx && cached_fy_ == fy &&
cached_cx_ == cx && cached_cy_ == cy)
{
return;
}
cached_depth_width_ = width;
cached_depth_height_ = height;
cached_depth_pixel_step_ = pixel_step;
cached_fx_ = fx;
cached_fy_ = fy;
cached_cx_ = cx;
cached_cy_ = cy;
// Sample every pixel_step-th row/column and always include the last image
// row/column, so cells marked from border pixels stay inside the swept
// clearing fan.
std::vector<unsigned int> u_samples, v_samples;
u_samples.reserve(width / pixel_step + 2);
v_samples.reserve(height / pixel_step + 2);
for (unsigned int u = 0; u < width; u += pixel_step)
u_samples.push_back(u);
if (width > 0 && u_samples.back() != width - 1)
u_samples.push_back(width - 1);
for (unsigned int v = 0; v < height; v += pixel_step)
v_samples.push_back(v);
if (height > 0 && v_samples.back() != height - 1)
v_samples.push_back(height - 1);
cached_column_count_ = static_cast<unsigned int>(u_samples.size());
depth_ray_cache_.clear();
depth_ray_cache_.reserve(u_samples.size() * v_samples.size());
for (const unsigned int v : v_samples)
{
for (unsigned int col = 0; col < u_samples.size(); ++col)
{
const unsigned int u = u_samples[col];
const double x = (static_cast<double>(u) - cx) / fx;
const double y = (static_cast<double>(v) - cy) / fy;
const double inverse_norm = 1.0 / std::sqrt(x * x + y * y + 1.0);
depth_ray_cache_.push_back(
DepthRay{u, v, col, x * inverse_norm, y * inverse_norm, inverse_norm});
}
}
}
bool VoxelLayer::clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz)
{
double a = wx - ox;
double b = wy - oy;
double c = wz - oz;
double t = 1.0;
constexpr double kEpsilon = 1e-9;
if (std::fabs(a) < kEpsilon && std::fabs(b) < kEpsilon && std::fabs(c) < kEpsilon)
return false;
if (wz > max_obstacle_height_ && std::fabs(c) > kEpsilon)
t = std::max(0.0, std::min(t, (max_obstacle_height_ - 0.01 - oz) / c));
else if (wz < origin_z_ && std::fabs(c) > kEpsilon)
t = std::min(t, (origin_z_ - oz) / c);
const double map_end_x = origin_x_ + getSizeInMetersX();
const double map_end_y = origin_y_ + getSizeInMetersY();
if (wx < origin_x_ && std::fabs(a) > kEpsilon)
t = std::min(t, (origin_x_ - ox) / a);
if (wy < origin_y_ && std::fabs(b) > kEpsilon)
t = std::min(t, (origin_y_ - oy) / b);
if (wx > map_end_x && std::fabs(a) > kEpsilon)
t = std::min(t, (map_end_x - ox) / a);
if (wy > map_end_y && std::fabs(b) > kEpsilon)
t = std::min(t, (map_end_y - oy) / b);
if (!std::isfinite(t) || t <= 0.0)
return false;
wx = ox + a * t;
wy = oy + b * t;
wz = oz + c * t;
return true;
}
bool VoxelLayer::clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
double raytrace_range, unsigned int cell_raytrace_range,
double* min_x, double* min_y, double* max_x, double* max_y)
{
double sensor_x, sensor_y, sensor_z;
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
return false;
if (!clipRaytraceEndpoint(ox, oy, oz, wx, wy, wz))
return false;
double point_x, point_y, point_z;
if (!worldToMap3DFloat(wx, wy, wz, point_x, point_y, point_z))
return false;
robot_voxel_grid_.clearVoxelLineInMap(sensor_x, sensor_y, sensor_z, point_x, point_y, point_z, costmap_,
unknown_threshold_, mark_threshold_, FREE_SPACE, NO_INFORMATION,
cell_raytrace_range);
updateRaytraceBounds(ox, oy, wx, wy, raytrace_range, min_x, min_y, max_x, max_y);
return true;
}
bool VoxelLayer::raytraceDepthFrustum(const DepthCameraObservation& observation,
double* min_x, double* min_y, double* max_x, double* max_y)
{
if (!observation.data_)
return false;
const robot_sensor_msgs::DepthCameraData& depth_camera_data = *observation.data_;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
if (depth.width == 0 || depth.height == 0 || depth.data.empty())
return false;
const double fx = camera_info.K[0];
const double fy = camera_info.K[4];
const double cx = camera_info.K[2];
const double cy = camera_info.K[5];
if (fx <= 0.0 || fy <= 0.0)
return false;
std::string depth_frame = depth.header.frame_id.empty() ? depth_camera_data.header.frame_id : depth.header.frame_id;
if (depth_frame.empty())
depth_frame = camera_info.header.frame_id;
if (depth_frame.empty() || tf_ == nullptr)
return false;
robot_geometry_msgs::PointStamped local_origin;
local_origin.header = depth.header;
local_origin.header.frame_id = depth_frame;
if (local_origin.header.stamp.isZero())
local_origin.header.stamp = depth_camera_data.header.stamp;
local_origin.point.x = 0.0;
local_origin.point.y = 0.0;
local_origin.point.z = 0.0;
robot_geometry_msgs::PointStamped global_origin;
tf3::TransformStampedMsg tfm;
try
{
const robot::Time& depth_stamp = local_origin.header.stamp;
const tf3::Time query_time =
depth_stamp.isZero()
? tf3::Time()
: tf3::Time(depth_stamp.sec, depth_stamp.nsec);
tfm = tf_->lookupTransform(global_frame_, depth_frame, query_time);
tf3::doTransform(local_origin, global_origin, tfm);
}
catch (tf3::TransformException& ex)
{
robot::log_error_throttle(
5.0, "VoxelLayer depth topic [%s] TF exception from %s to %s: %s\n",
observation.topic_.c_str(), depth_frame.c_str(), global_frame_.c_str(), ex.what());
return false;
}
const double ox = global_origin.point.x;
const double oy = global_origin.point.y;
const double oz = global_origin.point.z;
double sensor_x, sensor_y, sensor_z;
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
{
robot::log_error_throttle(
5.0, "VoxelLayer depth topic [%s] origin at (%.2f, %.2f, %.2f) is outside the voxel map\n",
observation.topic_.c_str(), ox, oy, oz);
return false;
}
const DepthFrustumConfig& frustum = observation.frustum_;
const unsigned int step = std::max(1u, frustum.pixel_step);
const double min_range = frustum.min_range;
const double max_range = frustum.max_range;
const double skip_dist =
frustum.skip_distance >= 0.0 ? frustum.skip_distance : 2.0 * resolution_;
const unsigned int width = std::min(depth.width, camera_info.width == 0 ? depth.width : camera_info.width);
const unsigned int height = std::min(depth.height, camera_info.height == 0 ? depth.height : camera_info.height);
updateDepthRayCache(width, height, step, fx, fy, cx, cy);
double qx = tfm.transform.rotation.x;
double qy = tfm.transform.rotation.y;
double qz = tfm.transform.rotation.z;
double qw = tfm.transform.rotation.w;
const double quaternion_norm = std::sqrt(qx * qx + qy * qy + qz * qz + qw * qw);
if (quaternion_norm <= 0.0)
return false;
qx /= quaternion_norm;
qy /= quaternion_norm;
qz /= quaternion_norm;
qw /= quaternion_norm;
const double r00 = 1.0 - 2.0 * (qy * qy + qz * qz);
const double r01 = 2.0 * (qx * qy - qz * qw);
const double r02 = 2.0 * (qx * qz + qy * qw);
const double r10 = 2.0 * (qx * qy + qz * qw);
const double r11 = 1.0 - 2.0 * (qx * qx + qz * qz);
const double r12 = 2.0 * (qy * qz - qx * qw);
const double r20 = 2.0 * (qx * qz - qy * qw);
const double r21 = 2.0 * (qy * qz + qx * qw);
const double r22 = 1.0 - 2.0 * (qx * qx + qy * qy);
const unsigned int cell_raytrace_range = cellDistance(max_range);
bool cleared_any = false;
// Column clearing: certify the beam length per pixel column and the distance
// window [cover, far] where the vertical FOV spans the whole height band.
// Outside that window a real obstacle could sit above/below the FOV, so only
// the per-pixel 3D rays may clear there.
const double band_min_h = frustum.column_min_height;
const double band_max_h =
frustum.column_max_height >= 0.0 ? frustum.column_max_height : max_obstacle_height_;
double cover_dist = frustum.column_cover_distance;
double far_dist = std::numeric_limits<double>::infinity();
bool column_pass = frustum.column_clearing && band_max_h > band_min_h;
if (column_pass && cover_dist < 0.0)
{
const double up_half = std::atan2(cy, fy);
const double down_half = std::atan2(static_cast<double>(height) - 1.0 - cy, fy);
const double axis_elev = std::atan2(r22, std::hypot(r02, r12));
const double alpha_top = axis_elev + up_half;
const double alpha_bot = axis_elev - down_half;
const double band_top = band_max_h - oz;
const double band_bot = band_min_h - oz;
constexpr double kMinSlope = 1e-3;
cover_dist = 0.0;
if (band_top > 0.0)
{
if (alpha_top <= kMinSlope)
column_pass = false; // camera can never look up to the band top
else
cover_dist = std::max(cover_dist, band_top / std::tan(alpha_top));
}
else if (alpha_top < -kMinSlope)
{
far_dist = std::min(far_dist, band_top / std::tan(alpha_top));
}
if (band_bot < 0.0)
{
if (alpha_bot >= -kMinSlope)
column_pass = false; // camera can never look down to the band bottom
else
cover_dist = std::max(cover_dist, band_bot / std::tan(alpha_bot));
}
else if (alpha_bot > kMinSlope)
{
far_dist = std::min(far_dist, band_bot / std::tan(alpha_bot));
}
if (!column_pass)
{
robot::log_warning_throttle(
10.0, "VoxelLayer column clearing disabled: vertical FOV [%.1f, %.1f] deg at camera "
"height %.2f m never covers band [%.2f, %.2f] m\n",
alpha_bot * 180.0 / M_PI, alpha_top * 180.0 / M_PI, oz, band_min_h, band_max_h);
}
}
if (column_pass)
depth_column_stats_.assign(cached_column_count_, DepthColumnStat());
for (const DepthRay& local_ray : depth_ray_cache_)
{
double depth_m = 0.0;
bool valid = false;
if (!readDepthMeters(depth, local_ray.u, local_ray.v, depth_m, valid))
continue;
// Edge stereo no-disparity strips (left and/or right, depending on the
// camera). An INVALID pixel in such a strip is structurally invalid (carries
// no free-space evidence), so clearing it out to max_range erases obstacles
// rotating out of the FOV on that side (the turn bug) — skip only those. A
// VALID return there is a real measured surface, so it must still clear
// normally; otherwise the border becomes a clearing dead zone and obstacles
// there never get cleared. Invalid pixels OUTSIDE the strips still clear to
// max_range (ghost removal). Right edge measured inward from the last column;
// the unsigned test avoids underflow when the border exceeds the width.
const bool in_left_border = local_ray.u < frustum.clear_left_border_px;
const bool in_right_border =
frustum.clear_right_border_px > 0 &&
local_ray.u + frustum.clear_right_border_px >= width;
const bool in_border = in_left_border || in_right_border;
if (in_border && !valid)
continue;
// depth images store z-depth; local_ray.z is the unit ray's optical axis
// component, so depth / z is the Euclidean range
const double euclid_range = valid ? depth_m / local_ray.z : 0.0;
robot_geometry_msgs::Vector3 global_ray;
global_ray.x = r00 * local_ray.x + r01 * local_ray.y + r02 * local_ray.z;
global_ray.y = r10 * local_ray.x + r11 * local_ray.y + r12 * local_ray.z;
global_ray.z = r20 * local_ray.x + r21 * local_ray.y + r22 * local_ray.z;
if (column_pass && local_ray.col < depth_column_stats_.size())
{
const double horiz_norm = std::hypot(global_ray.x, global_ray.y);
if (horiz_norm > 1e-6)
{
DepthColumnStat& stat = depth_column_stats_[local_ray.col];
const double row_delta = std::fabs(static_cast<double>(local_ray.v) - cy);
if (stat.min_band_dist < 0.0 && row_delta < stat.best_row_delta)
{
// no in-band return yet: aim the beam along the ray nearest the
// principal row
stat.azimuth = std::atan2(global_ray.y, global_ray.x);
stat.best_row_delta = row_delta;
}
stat.has_ray = true;
if (in_border)
stat.in_border = true;
if (valid)
{
const double pz = oz + global_ray.z * euclid_range;
if (pz >= band_min_h && pz <= band_max_h)
{
const double dist_h = horiz_norm * euclid_range;
if (stat.min_band_dist < 0.0 || dist_h < stat.min_band_dist)
{
stat.min_band_dist = dist_h;
stat.azimuth = std::atan2(global_ray.y, global_ray.x);
}
}
}
}
}
double ray_len = max_range;
if (valid && euclid_range < max_range)
ray_len = std::max(0.0, euclid_range - skip_dist);
if (ray_len <= min_range)
continue;
const double sx = ox + global_ray.x * min_range;
const double sy = oy + global_ray.y * min_range;
const double sz = oz + global_ray.z * min_range;
const double wx = ox + global_ray.x * ray_len;
const double wy = oy + global_ray.y * ray_len;
const double wz = oz + global_ray.z * ray_len;
cleared_any = clearVoxelRay(sx, sy, sz, wx, wy, wz, ray_len, cell_raytrace_range,
min_x, min_y, max_x, max_y) || cleared_any;
}
if (column_pass)
{
cleared_any = clearDepthColumns(ox, oy, cover_dist, far_dist, min_range, max_range,
std::max(0.0, frustum.column_skip_distance),
min_x, min_y, max_x, max_y) ||
cleared_any;
}
return cleared_any;
}
namespace
{
/// raytraceLine action: frees the 2D cell and wipes its whole voxel column.
class ClearFullColumn
{
public:
ClearFullColumn(unsigned char* costmap, robot_voxel_grid::VoxelGrid& voxel_grid)
: costmap_(costmap), voxel_grid_(voxel_grid)
{
}
inline void operator()(unsigned int offset)
{
costmap_[offset] = FREE_SPACE;
voxel_grid_.clearVoxelColumn(offset);
}
private:
unsigned char* costmap_;
robot_voxel_grid::VoxelGrid& voxel_grid_;
};
} // namespace
bool VoxelLayer::clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const
{
// Liang-Barsky clip against the map interior; the half-resolution margin
// keeps clipped endpoints valid for worldToMap.
const double min_wx = origin_x_;
const double min_wy = origin_y_;
const double max_wx = origin_x_ + getSizeInMetersX() - 0.5 * resolution_;
const double max_wy = origin_y_ + getSizeInMetersY() - 0.5 * resolution_;
const double dx = ex - sx;
const double dy = ey - sy;
const double p[4] = {-dx, dx, -dy, dy};
const double q[4] = {sx - min_wx, max_wx - sx, sy - min_wy, max_wy - sy};
double t0 = 0.0;
double t1 = 1.0;
for (int i = 0; i < 4; ++i)
{
if (std::fabs(p[i]) < 1e-12)
{
if (q[i] < 0.0)
return false;
continue;
}
const double r = q[i] / p[i];
if (p[i] < 0.0)
t0 = std::max(t0, r);
else
t1 = std::min(t1, r);
}
if (t0 > t1)
return false;
const double bx = sx;
const double by = sy;
sx = bx + t0 * dx;
sy = by + t0 * dy;
ex = bx + t1 * dx;
ey = by + t1 * dy;
return true;
}
bool VoxelLayer::clearDepthColumns(double ox, double oy, double cover_distance,
double far_distance, double min_range, double max_range,
double skip_dist, double* min_x, double* min_y,
double* max_x, double* max_y)
{
const double start_dist = std::max(cover_distance, min_range);
bool cleared_any = false;
for (const DepthColumnStat& stat : depth_column_stats_)
{
if (!stat.has_ray)
continue;
// In an edge stereo strip, never clear a whole column out to max_range on a
// missing in-band return: that is exactly the no-free-space-evidence case that
// erases obstacles turning out of view. Only an in-band measured surface may
// shorten (and thus clear) a border column.
if (stat.in_border && stat.min_band_dist < 0.0)
continue;
double end_dist = stat.min_band_dist >= 0.0 ? stat.min_band_dist - skip_dist : max_range;
end_dist = std::min(std::min(end_dist, max_range), far_distance);
if (end_dist <= start_dist)
continue;
const double cos_az = std::cos(stat.azimuth);
const double sin_az = std::sin(stat.azimuth);
double sx = ox + cos_az * start_dist;
double sy = oy + sin_az * start_dist;
double ex = ox + cos_az * end_dist;
double ey = oy + sin_az * end_dist;
if (!clipColumnSegment(sx, sy, ex, ey))
continue;
unsigned int sx_m, sy_m, ex_m, ey_m;
if (!worldToMap(sx, sy, sx_m, sy_m) || !worldToMap(ex, ey, ex_m, ey_m))
continue;
ClearFullColumn clearer(costmap_, robot_voxel_grid_);
raytraceLine(clearer, sx_m, sy_m, ex_m, ey_m);
touch(sx, sy, min_x, min_y, max_x, max_y);
touch(ex, ey, min_x, min_y, max_x, max_y);
cleared_any = true;
}
return cleared_any;
}
void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
{
// project the new origin into the grid
@@ -1267,10 +436,8 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
cell_size_x, cell_size_x, cell_size_y);
}
// Shift storage without resetting the paired input queue. A newly received
// measurement must still apply after the rolling origin moves this cycle.
Costmap2D::resetMaps();
robot_voxel_grid_.reset();
// we'll reset our maps to unknown space if appropriate
resetMaps();
// update the origin with the appropriate world coordinates
origin_x_ = new_grid_ox;
@@ -1289,10 +456,6 @@ void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
size_x_, cell_size_x, cell_size_y);
}
// Evidence keys are window-independent: track the shift, then drop what left the window.
evidence_offset_x_ += cell_ox;
evidence_offset_y_ += cell_oy;
pruneDepthEvidence();
}
// Export factory function

View File

@@ -414,21 +414,6 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height;
double obstacle_range;
double raytrace_range;
bool cloud_transform_at_stamp = false;
bool marking_voxel_enabled = false;
double marking_voxel_leaf_size = 0.05;
bool frustum_clearing_enabled = false;
int frustum_clearing_pixel_step = 8;
double frustum_min_range = 0.2;
double frustum_max_range = 3.0;
double frustum_skip_distance = -1.0;
bool frustum_column_clearing = false;
double column_clear_min_height = 0.10;
double column_clear_max_height = -1.0;
double column_skip_distance = 0.02;
double column_cover_distance = -1.0;
int frustum_clear_left_border_px = 0;
int frustum_clear_right_border_px = 0;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
@@ -442,38 +427,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
// These source options must reach local/global plugin namespaces too;
// loading the common YAML alone does not scope them to the layer.
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"cloud_transform_at_stamp", cloud_transform_at_stamp);
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"marking_voxel_filter/enabled", marking_voxel_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element,
"marking_voxel_filter/leaf_size_m", marking_voxel_leaf_size);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_enabled", frustum_clearing_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_pixel_step", frustum_clearing_pixel_step);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_min_range", frustum_min_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_max_range", frustum_max_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_skip_distance", frustum_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_column_clearing", frustum_column_clearing);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_min_height", column_clear_min_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_max_height", column_clear_max_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_skip_distance", column_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_cover_distance", column_cover_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_left_border_px", frustum_clear_left_border_px);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_right_border_px", frustum_clear_right_border_px);
for (const char* key : {"depth_clearing_mode", "paired_marking_source", "depth_pair_queue_size",
"depth_pair_max_wait_s", "depth_observation_max_age_s", "depth_valid_min_z_m",
"depth_valid_max_z_m", "depth_free_margin_m", "depth_projection_margin_px",
"depth_voxel_z_resolution_m", "depth_evidence_points_enabled",
"depth_evidence_points_per_voxel", "depth_marking_border_px",
"depth_far_return_is_behind", "depth_reobserve_clearing",
"depth_confirm_tolerance_m", "depth_miss_frames", "depth_no_return_weight",
"depth_stereo_baseline_m", "depth_stereo_band_margin_px"})
if (plugin_nh_element.hasParam(key))
costmap_plugin_nh_element.setParam(key, YAML::Clone(plugin_nh_element.getParamValue(key)));
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
robot::log_info("frustum_clearing_enabled: %s, frustum_clearing_pixel_step: %d, frustum_min_range: %f, frustum_max_range: %f, frustum_clear_left_border_px: %d, frustum_clear_right_border_px: %d", frustum_clearing_enabled ? "true" : "false", frustum_clearing_pixel_step, frustum_min_range, frustum_max_range, frustum_clear_left_border_px, frustum_clear_right_border_px);
}
}
}
@@ -510,18 +464,6 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
double max_obstacle_height;
double obstacle_range;
double raytrace_range;
bool frustum_clearing_enabled = false;
int frustum_clearing_pixel_step = 8;
double frustum_min_range = 0.2;
double frustum_max_range = 3.0;
double frustum_skip_distance = -1.0;
bool frustum_column_clearing = false;
double column_clear_min_height = 0.10;
double column_clear_max_height = -1.0;
double column_skip_distance = 0.02;
double column_cover_distance = -1.0;
int frustum_clear_left_border_px = 0;
int frustum_clear_right_border_px = 0;
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
@@ -535,20 +477,7 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_enabled", frustum_clearing_enabled);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_pixel_step", frustum_clearing_pixel_step);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_min_range", frustum_min_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_max_range", frustum_max_range);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_skip_distance", frustum_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_column_clearing", frustum_column_clearing);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_min_height", column_clear_min_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_clear_max_height", column_clear_max_height);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_skip_distance", column_skip_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "column_cover_distance", column_cover_distance);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_left_border_px", frustum_clear_left_border_px);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clear_right_border_px", frustum_clear_right_border_px);
robot::log_info("topic: %s data_type: %s clearing: %d marking: %d inf_is_valid: %d min_obstacle_height: %f max_obstacle_height: %f", topic.c_str(), data_type.c_str(), clearing, marking, inf_is_valid, min_obstacle_height, max_obstacle_height);
robot::log_info("frustum_clearing_enabled: %s, frustum_clearing_pixel_step: %d, frustum_min_range: %f, frustum_max_range: %f, frustum_clear_left_border_px: %d, frustum_clear_right_border_px: %d", frustum_clearing_enabled ? "true" : "false", frustum_clearing_pixel_step, frustum_min_range, frustum_max_range, frustum_clear_left_border_px, frustum_clear_right_border_px);
}
}
}

View File

@@ -1,106 +0,0 @@
#include <robot_costmap_2d/depth_evidence_store.h>
#include <algorithm>
namespace robot_costmap_2d
{
DepthEvidenceStore::DepthEvidenceStore(unsigned int points_per_voxel)
: points_per_voxel_(std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints)), entries_()
{
}
void DepthEvidenceStore::setPointsPerVoxel(unsigned int points_per_voxel)
{
points_per_voxel_ = std::clamp(points_per_voxel, kExtremeSlots, kMaxPoints);
entries_.clear();
}
void DepthEvidenceStore::add(const VoxelKey& key, const Eigen::Vector3f& point, bool fresh)
{
if (!point.allFinite())
return;
Entry& entry = entries_[key];
entry.miss = 0.f;
if (fresh || entry.count == 0)
{
// Slots 0..5 hold min/max of x, y, z; the first point is every extreme.
entry.points.fill(point);
entry.count = kExtremeSlots;
entry.next_recent = 0;
return;
}
for (int axis = 0; axis < 3; ++axis)
{
if (point[axis] < entry.points[2 * axis][axis])
entry.points[2 * axis] = point;
if (point[axis] > entry.points[2 * axis + 1][axis])
entry.points[2 * axis + 1] = point;
}
const unsigned int recent_slots = points_per_voxel_ - kExtremeSlots;
if (recent_slots == 0)
return;
if (entry.count < points_per_voxel_)
{
entry.points[entry.count++] = point;
return;
}
entry.points[kExtremeSlots + entry.next_recent] = point;
entry.next_recent = static_cast<unsigned char>((entry.next_recent + 1) % recent_slots);
}
bool DepthEvidenceStore::points(const VoxelKey& key, std::vector<Eigen::Vector3d>& out) const
{
out.clear();
const auto it = entries_.find(key);
if (it == entries_.end() || it->second.count == 0)
return false;
const Entry& entry = it->second;
for (unsigned int i = 0; i < entry.count; ++i)
{
const Eigen::Vector3d point = entry.points[i].cast<double>();
// Extreme slots often repeat the same point; checking it twice adds nothing.
if (std::find(out.begin(), out.end(), point) == out.end())
out.push_back(point);
}
return true;
}
float DepthEvidenceStore::addMiss(const VoxelKey& key, float weight)
{
const auto it = entries_.find(key);
if (it == entries_.end())
return 0.f;
it->second.miss += weight;
return it->second.miss;
}
void DepthEvidenceStore::resetMiss(const VoxelKey& key)
{
const auto it = entries_.find(key);
if (it != entries_.end())
it->second.miss = 0.f;
}
void DepthEvidenceStore::erase(const VoxelKey& key)
{
entries_.erase(key);
}
void DepthEvidenceStore::eraseIf(const std::function<bool(const VoxelKey&)>& predicate)
{
for (auto it = entries_.begin(); it != entries_.end();)
{
if (predicate(it->first))
it = entries_.erase(it);
else
++it;
}
}
void DepthEvidenceStore::clear()
{
entries_.clear();
}
} // namespace robot_costmap_2d

View File

@@ -1,308 +0,0 @@
#include <robot_costmap_2d/depth_visibility.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
namespace robot_costmap_2d
{
namespace
{
double cross(const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c)
{
const auto x = b - a, y = c - a;
return x.x() * y.y() - x.y() * y.x();
}
std::vector<Eigen::Vector2d> convexHull(std::vector<Eigen::Vector2d> points)
{
std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) {
return a.x() < b.x() || (a.x() == b.x() && a.y() < b.y());
});
points.erase(std::unique(points.begin(), points.end(), [](const auto& a, const auto& b) {
return a.x() == b.x() && a.y() == b.y();
}), points.end());
std::vector<Eigen::Vector2d> hull;
for (const auto& p : points)
{
while (hull.size() >= 2 && cross(hull[hull.size()-2], hull.back(), p) <= 0) hull.pop_back();
hull.push_back(p);
}
const size_t lower_size = hull.size();
for (auto it = points.rbegin() + (points.empty() ? 0 : 1); it != points.rend(); ++it)
{
while (hull.size() > lower_size && cross(hull[hull.size()-2], hull.back(), *it) <= 0) hull.pop_back();
hull.push_back(*it);
}
if (!hull.empty()) hull.pop_back();
return hull;
}
// SAT tests the full pixel cell expanded by calibration margin, not only its center.
bool intersectsPixel(const std::vector<Eigen::Vector2d>& polygon, int u, int v, double half)
{
const Eigen::Vector2d center(u, v);
for (int dimension = 0; dimension < 2; ++dimension)
{
double lo = std::numeric_limits<double>::infinity(), hi = -lo;
for (const auto& p : polygon) { lo = std::min(lo, p[dimension]); hi = std::max(hi, p[dimension]); }
if (center[dimension] + half < lo - 1e-9 || center[dimension] - half > hi + 1e-9) return false;
}
for (size_t i = 0; i < polygon.size(); ++i)
{
const auto edge = polygon[(i+1) % polygon.size()] - polygon[i];
const Eigen::Vector2d axis(-edge.y(), edge.x());
double lo = std::numeric_limits<double>::infinity(), hi = -lo;
for (const auto& p : polygon) { const double d = axis.dot(p); lo = std::min(lo, d); hi = std::max(hi, d); }
const double c = axis.dot(center), r = half * (std::abs(axis.x()) + std::abs(axis.y()));
if (c + r < lo - 1e-9 || c - r > hi + 1e-9) return false;
}
return true;
}
} // namespace
bool DepthVisibilityChecker::prepare(robot_sensor_msgs::DepthCameraData::ConstPtr data,
const tf3::TransformStampedMsg& pose, double min_height, double max_height,
const DepthFrustumConfig& config)
{
data_.reset();
if (!data || !std::isfinite(min_height) || !std::isfinite(max_height) || min_height > max_height ||
!std::isfinite(config.valid_min_z_m) || !std::isfinite(config.valid_max_z_m) ||
config.valid_min_z_m <= 0 || config.valid_max_z_m <= config.valid_min_z_m ||
!std::isfinite(config.free_margin_m) || config.free_margin_m < 0)
return false;
const auto& image = data->depth;
const auto& ci = data->camera_info;
bytes_per_pixel_ = image.encoding == "16UC1" || image.encoding == "mono16" ? 2u : image.encoding == "32FC1" ? 4u : 0u;
if (!bytes_per_pixel_ || image.is_bigendian || !image.width || !image.height ||
image.width > static_cast<unsigned>(std::numeric_limits<int>::max()) ||
image.height > static_cast<unsigned>(std::numeric_limits<int>::max()) ||
image.step < static_cast<size_t>(image.width) * bytes_per_pixel_ ||
image.data.size() < static_cast<size_t>(image.step) * image.height ||
ci.width != image.width || ci.height != image.height || image.header.stamp.isZero() ||
image.header.stamp != ci.header.stamp || image.header.stamp != data->header.stamp ||
pose.header.stamp != tf3::Time(image.header.stamp.sec, image.header.stamp.nsec) ||
image.header.frame_id.empty() || image.header.frame_id != ci.header.frame_id ||
image.header.frame_id != data->header.frame_id || image.header.frame_id != pose.child_frame_id ||
pose.header.frame_id.empty() || ci.binning_x > 1 || ci.binning_y > 1 ||
ci.roi.x_offset || ci.roi.y_offset || ci.roi.width || ci.roi.height)
return false;
for (double value : ci.K) if (!std::isfinite(value)) return false;
for (double value : ci.P) if (!std::isfinite(value)) return false;
if (ci.K[0] <= 0 || ci.K[4] <= 0 || std::abs(ci.K[1]) > 1e-6 ||
std::abs(ci.K[3]) > 1e-6 || std::abs(ci.K[6]) > 1e-6 ||
std::abs(ci.K[7]) > 1e-6 || std::abs(ci.K[8] - 1) > 1e-6 ||
std::abs(ci.P[0] - ci.K[0]) > 1e-6 || std::abs(ci.P[5] - ci.K[4]) > 1e-6 ||
std::abs(ci.P[2] - ci.K[2]) > 1e-6 || std::abs(ci.P[6] - ci.K[5]) > 1e-6 ||
std::abs(ci.P[3]) > 1e-6 || std::abs(ci.P[7]) > 1e-6) return false;
const auto& q = pose.transform.rotation;
const auto& t = pose.transform.translation;
Eigen::Quaterniond rotation(q.w, q.x, q.y, q.z);
if (!rotation.coeffs().allFinite() || std::abs(rotation.norm() - 1.0) > .01 ||
!std::isfinite(t.x) || !std::isfinite(t.y) || !std::isfinite(t.z)) return false;
Eigen::Isometry3d global_from_camera = Eigen::Isometry3d::Identity();
global_from_camera.linear() = rotation.normalized().toRotationMatrix();
global_from_camera.translation() = Eigen::Vector3d(t.x, t.y, t.z);
camera_from_global_ = global_from_camera.inverse();
min_height_ = min_height; max_height_ = max_height; config_ = config;
data_ = std::move(data);
return true;
}
DepthVisibilityResult DepthVisibilityChecker::classify(const Eigen::Vector3d& box_lower,
const Eigen::Vector3d& box_upper) const
{
if (!data_ || !box_lower.allFinite() || !box_upper.allFinite()) return {};
Eigen::Vector3d lower = box_lower, upper = box_upper;
lower.z() = std::max(lower.z(), min_height_); upper.z() = std::min(upper.z(), max_height_);
if (upper.z() < lower.z() || upper.x() <= lower.x() || upper.y() <= lower.y())
return {DepthVisibility::Unknown, DepthVisibilityReason::EmptyRegion};
const auto& image = data_->depth;
const auto& ci = data_->camera_info;
std::vector<Eigen::Vector2d> corners;
double far_z = 0;
for (int i = 0; i < 8; ++i)
{
const Eigen::Vector3d world(i & 1 ? upper.x() : lower.x(), i & 2 ? upper.y() : lower.y(), i & 4 ? upper.z() : lower.z());
const auto p = camera_from_global_ * world;
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m) return {};
far_z = std::max(far_z, p.z());
corners.emplace_back(ci.K[0] * p.x() / p.z() + ci.K[2], ci.K[4] * p.y() / p.z() + ci.K[5]);
}
const auto hull = convexHull(corners);
if (hull.size() < 3) return {};
double min_u = image.width, max_u = -1, min_v = image.height, max_v = -1;
for (const auto& p : hull)
{
min_u = std::min(min_u, p.x()); max_u = std::max(max_u, p.x());
min_v = std::min(min_v, p.y()); max_v = std::max(max_v, p.y());
}
const double margin = config_.projection_margin_px;
// Reject unbounded projections before converting to signed pixel indices.
if (!std::isfinite(min_u) || !std::isfinite(max_u) || !std::isfinite(min_v) || !std::isfinite(max_v) ||
min_u - margin - .5 < 0 || max_u + margin + .5 >= image.width ||
min_v - margin - .5 < 0 || max_v + margin + .5 >= image.height) return {};
const int left = static_cast<int>(std::floor(min_u - margin - .5));
const int right = static_cast<int>(std::ceil(max_u + margin + .5));
const int top = static_cast<int>(std::floor(min_v - margin - .5));
const int bottom = static_cast<int>(std::ceil(max_v + margin + .5));
if (left < static_cast<int>(config_.clear_left_border_px) ||
right >= static_cast<int>(image.width) - static_cast<int>(config_.clear_right_border_px) ||
top < 0 || bottom >= static_cast<int>(image.height)) return {};
bool any_pixel = false;
for (int v = top; v <= bottom; ++v)
for (int u = left; u <= right; ++u)
{
if (!intersectsPixel(hull, u, v, margin + .5)) continue;
any_pixel = true;
const double measured_z = depthAt(u, v);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m || measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= far_z + config_.free_margin_m)
return {DepthVisibility::Surface, DepthVisibilityReason::Surface};
}
return any_pixel ? DepthVisibilityResult{DepthVisibility::Free, DepthVisibilityReason::Free} : DepthVisibilityResult{};
}
double DepthVisibilityChecker::depthAt(int u, int v) const
{
const auto& image = data_->depth;
const auto* pixel = image.data.data() + static_cast<size_t>(v) * image.step +
static_cast<size_t>(u) * bytes_per_pixel_;
if (bytes_per_pixel_ == 2)
{
uint16_t millimeters;
std::memcpy(&millimeters, pixel, 2);
return millimeters * .001;
}
if (bytes_per_pixel_ == 4)
{
float meters;
std::memcpy(&meters, pixel, 4);
return meters;
}
return std::numeric_limits<double>::quiet_NaN();
}
namespace
{
// Pixel index of a projection; the bounds test keeps lround() away from huge values.
bool projectToPixel(const Eigen::Vector3d& camera_point, const robot_sensor_msgs::CameraInfo& ci,
int left, int right, int top, int bottom, int& u, int& v)
{
const double pu = ci.K[0] * camera_point.x() / camera_point.z() + ci.K[2];
const double pv = ci.K[4] * camera_point.y() / camera_point.z() + ci.K[5];
// round(p) in [lo, hi] <=> p in [lo - 0.5, hi + 0.5)
if (!std::isfinite(pu) || !std::isfinite(pv) || pu < left - .5 || pu >= right + .5 ||
pv < top - .5 || pv >= bottom + .5)
return false;
u = static_cast<int>(std::lround(pu));
v = static_cast<int>(std::lround(pv));
return true;
}
} // namespace
int DepthVisibilityChecker::usableLeft(double z) const
{
int left = static_cast<int>(config_.clear_left_border_px);
// The right imager cannot see the leftmost fx * B / z columns at depth z: no disparity there.
if (config_.stereo_baseline_m > 0)
left = std::max(left, static_cast<int>(std::ceil(data_->camera_info.K[0] * config_.stereo_baseline_m / z)) +
static_cast<int>(config_.stereo_band_margin_px));
return left;
}
bool DepthVisibilityChecker::projectsInside(const Eigen::Vector3d& point, unsigned int border_px) const
{
if (!data_ || !point.allFinite())
return false;
const auto& image = data_->depth;
const Eigen::Vector3d p = camera_from_global_ * point;
if (!p.allFinite() || p.z() < config_.valid_min_z_m)
return false;
const int border = static_cast<int>(border_px);
int u, v;
return projectToPixel(p, data_->camera_info, usableLeft(p.z()) + border,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - border,
border, static_cast<int>(image.height) - 1 - border, u, v);
}
DepthObservation DepthVisibilityChecker::observePoints(const std::vector<Eigen::Vector3d>& points) const
{
DepthObservation best = DepthObservation::OutOfView;
if (!data_)
return best;
const auto& image = data_->depth;
const int r = static_cast<int>(config_.projection_margin_px);
const double tolerance = config_.confirm_tolerance_m;
for (const auto& point : points)
{
if (!point.allFinite())
continue;
const Eigen::Vector3d p = camera_from_global_ * point;
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m)
continue;
int u, v;
if (!projectToPixel(p, data_->camera_info, usableLeft(p.z()) + r,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - r,
r, static_cast<int>(image.height) - 1 - r, u, v))
continue;
// A return beyond the trusted range only proves free space for a point well inside it.
const bool far_is_behind = config_.far_return_is_behind && p.z() + tolerance < config_.valid_max_z_m;
bool in_front = false, behind = false;
for (int dv = -r; dv <= r; ++dv)
for (int du = -r; du <= r; ++du)
{
const double measured_z = depthAt(u + du, v + dv);
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m ||
(measured_z > config_.valid_max_z_m && !far_is_behind))
continue; // no return: says nothing about this point
if (std::abs(measured_z - p.z()) <= tolerance)
return DepthObservation::Confirmed;
if (measured_z < p.z())
in_front = true;
else
behind = true;
}
const DepthObservation seen = in_front ? DepthObservation::Occluded :
behind ? DepthObservation::SeenThrough : DepthObservation::NoReturn;
best = std::max(best, seen);
}
return best;
}
DepthVisibilityResult DepthVisibilityChecker::classifyPoints(const std::vector<Eigen::Vector3d>& points) const
{
if (!data_ || points.empty())
return {};
const auto& image = data_->depth;
const int r = static_cast<int>(config_.projection_margin_px);
for (const auto& point : points)
{
if (!point.allFinite())
return {};
const Eigen::Vector3d p = camera_from_global_ * point;
// Same view limits as classify(): out of the trusted optical range is not seen.
if (!p.allFinite() || p.z() < config_.valid_min_z_m || p.z() > config_.valid_max_z_m)
return {};
int u, v;
if (!projectToPixel(p, data_->camera_info,
static_cast<int>(config_.clear_left_border_px) + r,
static_cast<int>(image.width) - 1 - static_cast<int>(config_.clear_right_border_px) - r,
r, static_cast<int>(image.height) - 1 - r, u, v))
return {};
for (int dv = -r; dv <= r; ++dv)
for (int du = -r; du <= r; ++du)
{
const double measured_z = depthAt(u + du, v + dv);
if (config_.far_return_is_behind && std::isfinite(measured_z) &&
measured_z > config_.valid_max_z_m && p.z() + config_.free_margin_m < config_.valid_max_z_m)
continue;
if (!std::isfinite(measured_z) || measured_z < config_.valid_min_z_m ||
measured_z > config_.valid_max_z_m)
return {DepthVisibility::Unknown, DepthVisibilityReason::InvalidDepth};
if (measured_z <= p.z() + config_.free_margin_m)
return {DepthVisibility::Surface, DepthVisibilityReason::Surface};
}
}
return {DepthVisibility::Free, DepthVisibilityReason::Free};
}
} // namespace robot_costmap_2d

View File

@@ -41,41 +41,12 @@
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <cstring>
#include <cmath>
#include <stdexcept>
#include <pcl/filters/voxel_grid.h>
#include <pcl/point_types.h>
#include <data_convert/pcl_convert.h>
using namespace std;
using namespace tf3;
namespace robot_costmap_2d
{
namespace
{
bool validTimestampCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
if (cloud.header.stamp.isZero() || cloud.header.frame_id.empty() ||
cloud.is_bigendian || cloud.point_step == 0 || cloud.height != 1 ||
cloud.row_step != static_cast<size_t>(cloud.width) * cloud.point_step ||
cloud.data.size() != cloud.row_step)
return false;
unsigned int fields = 0;
for (const auto& field : cloud.fields)
{
const unsigned int bit = field.name == "x" ? 1u : field.name == "y" ? 2u : field.name == "z" ? 4u : 0u;
if (!bit) continue;
if ((fields & bit) || field.count != 1 ||
field.datatype != robot_sensor_msgs::PointField::FLOAT32 ||
static_cast<size_t>(field.offset) + sizeof(float) > cloud.point_step)
return false;
fields |= bit;
}
return fields == 7u;
}
} // namespace
ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, tf3::BufferCore& tf3_buffer, string global_frame,
@@ -87,23 +58,6 @@ ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_
{
}
ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, const DepthFrustumConfig& frustum_config,
tf3::BufferCore& tf3_buffer, string global_frame,
string sensor_frame, double tf_tolerance) :
tf3_buffer_(tf3_buffer), observation_keep_time_(observation_keep_time), expected_update_rate_(expected_update_rate),
last_updated_(robot::Time::now()), global_frame_(global_frame), sensor_frame_(sensor_frame), topic_name_(topic_name),
min_obstacle_height_(min_obstacle_height), max_obstacle_height_(max_obstacle_height),
obstacle_range_(obstacle_range), raytrace_range_(raytrace_range),
tf_tolerance_(tf_tolerance),
frustum_config_(frustum_config)
{
frustum_config_.pixel_step = std::max(1u, frustum_config_.pixel_step);
frustum_config_.min_range = std::max(0.0, frustum_config_.min_range);
frustum_config_.max_range = std::max(frustum_config_.max_range, frustum_config_.min_range);
}
ObservationBuffer::~ObservationBuffer()
{
}
@@ -172,43 +126,6 @@ bool ObservationBuffer::setGlobalFrame(const std::string new_global_frame)
}
void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
(void)tryBufferCloud(cloud);
}
void ObservationBuffer::setCloudProcessingConfig(const CloudProcessingConfig& config)
{
const float leaf = static_cast<float>(config.voxel_leaf_size);
if (config.voxel_filter_enabled &&
(!config.transform_at_stamp || !std::isfinite(leaf) || leaf <= 0.0f ||
!std::isfinite(config.voxel_leaf_size)))
throw std::invalid_argument("cloud voxel filter requires timestamp TF and a finite positive leaf [m]");
if (config.transform_at_stamp &&
(!std::isfinite(min_obstacle_height_) || !std::isfinite(max_obstacle_height_) ||
min_obstacle_height_ > max_obstacle_height_ ||
!std::isfinite(obstacle_range_) || obstacle_range_ <= 0.0))
throw std::invalid_argument("timestamp cloud processing requires finite height/range limits");
cloud_processing_config_ = config;
}
bool ObservationBuffer::tryBufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
{
return tryBufferCloudImpl(cloud, nullptr);
}
bool ObservationBuffer::tryBufferCloudWithTransform(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg& transform)
{
if (!cloud_processing_config_.transform_at_stamp || transform.header.frame_id != global_frame_ ||
transform.header.stamp != data_convert::convertTime(cloud.header.stamp) ||
transform.child_frame_id != cloud.header.frame_id ||
(!sensor_frame_.empty() && sensor_frame_ != cloud.header.frame_id))
return false;
return tryBufferCloudImpl(cloud, &transform);
}
bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2& cloud,
const tf3::TransformStampedMsg* prepared_transform)
{
robot_geometry_msgs::PointStamped global_origin;
Observation observation;
@@ -216,13 +133,6 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
// check whether the origin frame has been set explicitly or whether we should get it from the cloud
string origin_frame = sensor_frame_ == "" ? cloud.header.frame_id : sensor_frame_;
if (cloud_processing_config_.transform_at_stamp && !validTimestampCloud(cloud))
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s]: invalid timestamp cloud layout/header\n",
topic_name_.c_str());
return false;
}
try
{
// given these observations come from sensors... we'll need to store the origin pt of the sensor
@@ -233,16 +143,14 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
local_origin.point.y = 0;
local_origin.point.z = 0;
// tf3_buffer_.transform(local_origin, global_origin, global_frame_);
const tf3::Time query_time = cloud_processing_config_.transform_at_stamp
? tf3::Time(cloud.header.stamp.sec, cloud.header.stamp.nsec) : tf3::Time();
const tf3::TransformStampedMsg cloud_transform = prepared_transform ? *prepared_transform
: tf3_buffer_.lookupTransform(global_frame_, cloud.header.frame_id, query_time);
const tf3::TransformStampedMsg cloud_transform = tf3_buffer_.lookupTransform(
global_frame_, cloud.header.frame_id, tf3::Time());
if (origin_frame == cloud.header.frame_id)
tf3::doTransform(local_origin, global_origin, cloud_transform);
else
tf3::doTransform(
local_origin, global_origin,
tf3_buffer_.lookupTransform(global_frame_, origin_frame, query_time));
tf3_buffer_.lookupTransform(global_frame_, origin_frame, tf3::Time()));
tf3::convert(global_origin.point, observation.origin_);
observation.raytrace_range_ = raytrace_range_;
@@ -257,24 +165,11 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
const std::size_t point_step = observation_cloud.point_step;
std::size_t point_count = 0;
robot_sensor_msgs::PointCloud2Iterator<float> iter_z(observation_cloud, "z");
robot_sensor_msgs::PointCloud2Iterator<float> iter_x(observation_cloud, "x");
robot_sensor_msgs::PointCloud2Iterator<float> iter_y(observation_cloud, "y");
const double sq_range = obstacle_range_ * obstacle_range_;
// Compact accepted points in-place. This avoids allocating and copying a
// second full-size filtered cloud after the TF transform.
for (std::size_t read_index = 0; read_index < cloud_size;
++read_index, ++iter_x, ++iter_y, ++iter_z)
for (std::size_t read_index = 0; read_index < cloud_size; ++read_index, ++iter_z)
{
if (cloud_processing_config_.transform_at_stamp)
{
const double dx = *iter_x - observation.origin_.x;
const double dy = *iter_y - observation.origin_.y;
const double dz = *iter_z - observation.origin_.z;
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z) ||
dx * dx + dy * dy + dz * dz >= sq_range)
continue;
}
if ((*iter_z) > max_obstacle_height_ || (*iter_z) < min_obstacle_height_)
continue;
@@ -292,36 +187,12 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
robot_sensor_msgs::PointCloud2Modifier modifier(observation_cloud);
modifier.resize(point_count);
}
// Floor/out-of-band points cannot pull a small obstacle's centroid below
// its marking threshold. Only this source's opted-in cloud is downsampled.
if (cloud_processing_config_.voxel_filter_enabled && point_count != 0)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr input(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROBOTMsg(observation_cloud, *input);
pcl::VoxelGrid<pcl::PointXYZ> voxel;
const float leaf = static_cast<float>(cloud_processing_config_.voxel_leaf_size);
voxel.setLeafSize(leaf, leaf, leaf);
voxel.setInputCloud(input);
pcl::PointCloud<pcl::PointXYZ> output;
voxel.filter(output);
const robot_std_msgs::Header header = observation_cloud.header;
pcl::toROBOTMsg(output, observation_cloud);
observation_cloud.header = header; // PCL timestamps only have microseconds.
}
}
catch (TransformException& ex)
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s] missing TF for frame %s at %u.%09u: %s\n",
topic_name_.c_str(), cloud.header.frame_id.c_str(),
cloud.header.stamp.sec, cloud.header.stamp.nsec, ex.what());
return false;
}
catch (const std::exception& ex)
{
robot::log_error_throttle(5.0, "ObservationBuffer [%s] rejected cloud: %s\n",
topic_name_.c_str(), ex.what());
return false;
robot::log_error("TF Exception that should never happen for sensor frame: %s, cloud frame: %s, %s\n", sensor_frame_.c_str(),
cloud.header.frame_id.c_str(), ex.what());
return;
}
if (observation_keep_time_ == robot::Duration(0.0) && !observation_list_.empty())
@@ -339,37 +210,6 @@ bool ObservationBuffer::tryBufferCloudImpl(const robot_sensor_msgs::PointCloud2&
// we'll also remove any stale observations from the list
purgeStaleObservations();
return true;
}
void ObservationBuffer::bufferDepthCamera(const robot_sensor_msgs::DepthCameraData& depth_camera_data)
{
bufferDepthCamera(boost::make_shared<robot_sensor_msgs::DepthCameraData>(depth_camera_data));
}
void ObservationBuffer::bufferDepthCamera(robot_sensor_msgs::DepthCameraData::ConstPtr depth_camera_data)
{
if (!depth_camera_data)
return;
DepthCameraObservation observation(
std::move(depth_camera_data), topic_name_, robot::Time::now(), frustum_config_);
if (observation_keep_time_ == robot::Duration(0.0) && !depth_observation_list_.empty())
{
depth_observation_list_.front() = std::move(observation);
depth_observation_list_.erase(++depth_observation_list_.begin(), depth_observation_list_.end());
}
else
{
depth_observation_list_.push_front(std::move(observation));
}
// if the update was successful, we want to update the last updated time
last_updated_ = robot::Time::now();
// first... let's make sure that we don't have any stale observations
purgeStaleDepthObservations();
}
// returns a copy of the observations
@@ -386,26 +226,6 @@ void ObservationBuffer::getObservations(vector<Observation>& observations)
}
}
void ObservationBuffer::getDepthObservations(vector<DepthCameraObservation>& observations)
{
// first... let's make sure that we don't have any stale observations
purgeStaleDepthObservations();
// now we'll just copy the observations for the caller
if (observation_keep_time_ == robot::Duration(0.0))
{
if (!depth_observation_list_.empty())
{
observations.push_back(std::move(depth_observation_list_.front()));
depth_observation_list_.clear();
}
return;
}
observations.insert(
observations.end(), depth_observation_list_.begin(), depth_observation_list_.end());
}
void ObservationBuffer::purgeStaleObservations()
{
if (!observation_list_.empty())
@@ -432,30 +252,6 @@ void ObservationBuffer::purgeStaleObservations()
}
}
void ObservationBuffer::purgeStaleDepthObservations()
{
if (depth_observation_list_.empty())
return;
if (observation_keep_time_ == robot::Duration(0.0))
{
auto observation = depth_observation_list_.begin();
depth_observation_list_.erase(++observation, depth_observation_list_.end());
return;
}
const robot::Time now = robot::Time::now();
for (auto observation = depth_observation_list_.begin(); observation != depth_observation_list_.end(); ++observation)
{
DepthCameraObservation& obs = *observation;
if ((last_updated_ - obs.data_->header.stamp) > observation_keep_time_)
{
depth_observation_list_.erase(observation, depth_observation_list_.end());
return;
}
}
}
bool ObservationBuffer::isCurrent() const
{
if (expected_update_rate_ == robot::Duration(0.0))

View File

@@ -180,28 +180,6 @@ TEST(CostmapPerformanceRegression, observation_copy_shares_cloud_payload)
EXPECT_EQ(copied.cloud_->data, cloud.data);
}
TEST(CostmapPerformanceRegression, latest_depth_frame_is_consumed_once)
{
// tf3::BufferCore tf_buffer(tf3::Duration(10.0));
// ObservationBuffer buffer(
// "/camera/depth/data", 0.0, 0.5, 0.0, 2.0, 2.5, 3.0,
// 8, 0.2, 3.0, tf_buffer, "odom", "", 0.2);
// robot_sensor_msgs::DepthCameraData::ConstPtr depth =
// boost::make_shared<robot_sensor_msgs::DepthCameraData>();
// buffer.bufferDepthCamera(depth);
// std::vector<DepthCameraObservation> first_snapshot;
// buffer.getDepthObservations(first_snapshot);
// ASSERT_EQ(first_snapshot.size(), 1u);
// EXPECT_EQ(first_snapshot.front().data_, depth.get());
// EXPECT_EQ(first_snapshot.front().topic_, "/camera/depth/data");
// std::vector<DepthCameraObservation> second_snapshot;
// buffer.getDepthObservations(second_snapshot);
// EXPECT_TRUE(second_snapshot.empty());
}
TEST(CostmapPerformanceRegression, inflation_buckets_preserve_radial_costs)
{
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);

View File

@@ -1,110 +0,0 @@
#include <robot_costmap_2d/depth_evidence_store.h>
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
using robot_costmap_2d::DepthEvidenceStore;
namespace
{
bool contains(const std::vector<Eigen::Vector3d>& points, const Eigen::Vector3d& point)
{
return std::any_of(points.begin(), points.end(),
[&](const Eigen::Vector3d& p) { return (p - point).norm() < 1e-6; });
}
} // namespace
TEST(DepthEvidenceStore, FirstPointIsTheOnlyEvidence)
{
DepthEvidenceStore store(8);
std::vector<Eigen::Vector3d> points;
EXPECT_FALSE(store.points({1, 2, 3}, points));
store.add({1, 2, 3}, Eigen::Vector3f(1.f, 2.f, .3f), false);
ASSERT_TRUE(store.points({1, 2, 3}, points));
ASSERT_EQ(points.size(), 1u);
EXPECT_TRUE(contains(points, Eigen::Vector3d(1.0, 2.0, 0.3)));
EXPECT_FALSE(store.points({1, 2, 4}, points));
}
TEST(DepthEvidenceStore, KeepsAxisExtremesWhenFull)
{
DepthEvidenceStore store(6); // extremes only, no recent slots
const DepthEvidenceStore::VoxelKey key{0, 0, 0};
store.add(key, Eigen::Vector3f(.02f, .02f, .02f), false);
store.add(key, Eigen::Vector3f(.00f, .03f, .03f), false); // new min x
store.add(key, Eigen::Vector3f(.04f, .01f, .01f), false); // new max x, min y, min z
store.add(key, Eigen::Vector3f(.02f, .02f, .02f), false); // inside: changes nothing
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.00, .03, .03)));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.04, .01, .01)));
EXPECT_LE(points.size(), 6u);
}
TEST(DepthEvidenceStore, RecentSlotsRotate)
{
DepthEvidenceStore store(7); // one recent slot
const DepthEvidenceStore::VoxelKey key{0, 0, 0};
store.add(key, Eigen::Vector3f(.0f, .0f, .0f), false);
store.add(key, Eigen::Vector3f(.04f, .04f, .04f), false);
store.add(key, Eigen::Vector3f(.01f, .02f, .03f), false);
store.add(key, Eigen::Vector3f(.03f, .02f, .01f), false);
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
EXPECT_TRUE(contains(points, Eigen::Vector3d(.03, .02, .01)));
EXPECT_FALSE(contains(points, Eigen::Vector3d(.01, .02, .03)));
}
TEST(DepthEvidenceStore, FreshVoxelDropsOldEvidence)
{
DepthEvidenceStore store(8);
const DepthEvidenceStore::VoxelKey key{5, -3, 2};
store.add(key, Eigen::Vector3f(1.f, 1.f, .2f), false);
store.add(key, Eigen::Vector3f(1.04f, 1.04f, .24f), true);
std::vector<Eigen::Vector3d> points;
ASSERT_TRUE(store.points(key, points));
ASSERT_EQ(points.size(), 1u);
EXPECT_TRUE(contains(points, Eigen::Vector3d(1.04, 1.04, .24)));
}
TEST(DepthEvidenceStore, EraseEraseIfClearAndNonFinite)
{
DepthEvidenceStore store(8);
store.add({0, 0, 0}, Eigen::Vector3f(0.f, 0.f, 0.f), false);
store.add({1, 0, 0}, Eigen::Vector3f(.05f, 0.f, 0.f), false);
store.add({2, 0, 0}, Eigen::Vector3f(.1f, 0.f, 0.f), false);
store.add({3, 0, 0}, Eigen::Vector3f(std::nanf(""), 0.f, 0.f), false);
EXPECT_EQ(store.size(), 3u);
store.erase({0, 0, 0});
EXPECT_EQ(store.size(), 2u);
store.eraseIf([](const DepthEvidenceStore::VoxelKey& key) { return key.x == 2; });
std::vector<Eigen::Vector3d> points;
EXPECT_TRUE(store.points({1, 0, 0}, points));
EXPECT_FALSE(store.points({2, 0, 0}, points));
store.clear();
EXPECT_EQ(store.size(), 0u);
}
TEST(DepthEvidenceStore, MissCountRestartsOnMarkingAndLeavesWithTheVoxel)
{
DepthEvidenceStore store(8);
const DepthEvidenceStore::VoxelKey key{1, 2, 3};
EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 0.f); // no evidence, nothing to count
store.add(key, Eigen::Vector3f(1.f, 2.f, .3f), false);
EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f);
EXPECT_FLOAT_EQ(store.addMiss(key, .5f), 1.5f);
store.add(key, Eigen::Vector3f(1.01f, 2.f, .3f), false); // marked again
EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f);
store.resetMiss(key);
EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 1.f);
store.erase(key);
EXPECT_FLOAT_EQ(store.addMiss(key, 1.f), 0.f);
}
TEST(DepthEvidenceStore, CapacityIsClamped)
{
EXPECT_EQ(DepthEvidenceStore(2).pointsPerVoxel(), DepthEvidenceStore::kExtremeSlots);
EXPECT_EQ(DepthEvidenceStore(100).pointsPerVoxel(), DepthEvidenceStore::kMaxPoints);
}

View File

@@ -1,277 +0,0 @@
#include <robot_costmap_2d/observation_buffer.h>
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <gtest/gtest.h>
#include <array>
#include <limits>
#include <filesystem>
#include <cstdlib>
namespace
{
using robot_costmap_2d::CloudProcessingConfig;
using robot_costmap_2d::Observation;
using robot_costmap_2d::ObservationBuffer;
using Points = std::vector<std::array<float, 3>>;
robot_sensor_msgs::PointCloud2 cloud(const Points &points)
{
robot_sensor_msgs::PointCloud2 out;
out.height = 1;
out.header.frame_id = "camera";
out.header.stamp = robot::Time(10, 123456789);
out.header.seq = 9;
robot_sensor_msgs::PointCloud2Modifier m(out);
m.setPointCloud2FieldsByString(1, "xyz");
m.resize(points.size());
robot_sensor_msgs::PointCloud2Iterator<float> x(out, "x"), y(out, "y"), z(out, "z");
for (const auto &p : points)
{
*x = p[0]; *y = p[1]; *z = p[2];
++x; ++y; ++z;
}
return out;
}
void transform(tf3::BufferCore &tf, const std::string &child, double x, double z,
uint32_t sec = 10, bool fixed = true)
{
tf3::TransformStampedMsg t;
t.header.frame_id = "odom";
t.header.stamp = tf3::Time(sec, 123456789);
t.child_frame_id = child;
t.transform.translation.x = x;
t.transform.translation.z = z;
ASSERT_TRUE(tf.setTransform(t, "test", fixed));
}
CloudProcessingConfig config(bool voxel = true)
{
CloudProcessingConfig c;
c.transform_at_stamp = true;
c.voxel_filter_enabled = voxel;
return c;
}
Points output(ObservationBuffer &buffer, Observation *observation = nullptr)
{
std::vector<Observation> observations;
buffer.getObservations(observations);
if (observations.empty()) return {};
if (observation) *observation = observations.front();
const auto &c = *observations.front().cloud_;
Points points;
robot_sensor_msgs::PointCloud2ConstIterator<float> x(c, "x"), y(c, "y"), z(c, "z");
for (size_t i = 0; i < c.width * c.height; ++i, ++x, ++y, ++z)
points.push_back({*x, *y, *z});
return points;
}
TEST(DepthBuffer, HeightGatePrecedesCentroidAndKeepsExactHeader)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0.04);
ObservationBuffer b("depth", 0, 0, 0.05, 1, 2.5, 3, tf, "odom", "", 0.2);
b.setCloudProcessingConfig(config());
// Two floor points + a 6 cm obstacle share a camera-frame leaf before TF.
// Their premature centroid would be below the 5 cm height threshold.
ASSERT_TRUE(b.tryBufferCloud(cloud({{0.011f, 0.011f, 0.001f},
{0.013f, 0.011f, 0.001f},
{0.019f, 0.011f, 0.020f}})));
Observation obs;
const auto pts = output(b, &obs);
ASSERT_EQ(pts.size(), 1u);
EXPECT_NEAR(pts[0][2], 0.06, 1e-6);
EXPECT_EQ(obs.cloud_->header.frame_id, "odom");
EXPECT_EQ(obs.cloud_->header.stamp.nsec, 123456789u);
EXPECT_EQ(obs.cloud_->header.seq, 9u);
EXPECT_DOUBLE_EQ(obs.origin_.z, 0.04);
}
TEST(DepthBuffer, VoxelCentroidsArePerSourceOptIn)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
const auto c = cloud({{.011f, .011f, .11f}, {.019f, .011f, .11f}});
ObservationBuffer filtered("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
filtered.setCloudProcessingConfig(config());
ASSERT_TRUE(filtered.tryBufferCloud(c));
ASSERT_EQ(output(filtered).size(), 1u);
EXPECT_NEAR(output(filtered)[0][0], .015, 1e-6);
ObservationBuffer legacy("other", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
ASSERT_TRUE(legacy.tryBufferCloud(c));
EXPECT_EQ(output(legacy).size(), 2u);
}
TEST(DepthBuffer, UsesMeasurementTransformForCloudAndDifferentOriginFrame)
{
tf3::BufferCore tf;
transform(tf, "camera", 1, 0, 10, false);
transform(tf, "camera", 4, 0, 11, false);
transform(tf, "sensor_origin", .5, 0, 10, false);
transform(tf, "sensor_origin", 3.5, 0, 11, false);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "sensor_origin", .2);
b.setCloudProcessingConfig(config(false));
ASSERT_TRUE(b.tryBufferCloud(cloud({{0, 0, .1f}})));
Observation obs;
ASSERT_EQ(output(b, &obs).size(), 1u);
EXPECT_NEAR(output(b)[0][0], 1, 1e-6);
EXPECT_DOUBLE_EQ(obs.origin_.x, .5);
}
TEST(DepthBuffer, EmptyCloudIsValidAndMissingTfDoesNotReplaceIt)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0, 10, false);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
ASSERT_TRUE(b.tryBufferCloud(cloud({})));
auto late = cloud({{0, 0, .1f}});
late.header.stamp.sec = 20;
EXPECT_FALSE(b.tryBufferCloud(late));
std::vector<Observation> obs;
b.getObservations(obs);
ASSERT_EQ(obs.size(), 1u);
EXPECT_EQ(obs[0].cloud_->header.stamp.sec, 10u);
EXPECT_EQ(obs[0].cloud_->width, 0u);
EXPECT_FALSE(obs[0].cloud_->fields.empty());
}
TEST(DepthBuffer, FiniteHeightAndRangeGatesPrecedePcl)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config(false));
const float nan = std::numeric_limits<float>::quiet_NaN();
ASSERT_TRUE(b.tryBufferCloud(cloud({{nan, 0, .1f}, {0, 0, nan},
{3, 0, .1f}, {0, 0, .049f},
{.1f, 0, .05f}, {.2f, 0, 1.f}, {.3f, 0, 1.01f}})));
EXPECT_EQ(output(b).size(), 2u);
}
TEST(DepthBuffer, RejectsZeroStampAndInvalidFilterConfig)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
auto c = cloud({}); c.header.stamp = robot::Time();
EXPECT_FALSE(b.tryBufferCloud(c));
auto bad = config();
for (double leaf : {0., -1., std::numeric_limits<double>::infinity()})
{
bad.voxel_leaf_size = leaf;
EXPECT_THROW(b.setCloudProcessingConfig(bad), std::invalid_argument);
}
bad = config(); bad.transform_at_stamp = false;
EXPECT_THROW(b.setCloudProcessingConfig(bad), std::invalid_argument);
}
TEST(DepthBuffer, RejectsMalformedXyzFieldsBeforeReadingOrTransforming)
{
tf3::BufferCore tf;
transform(tf, "camera", 0, 0);
ObservationBuffer b("depth", 0, 0, .05, 1, 2.5, 3, tf, "odom", "", .2);
b.setCloudProcessingConfig(config());
auto c = cloud({{0, 0, .1f}});
c.fields[0].offset = c.point_step;
EXPECT_FALSE(b.tryBufferCloud(c));
c = cloud({}); c.fields.pop_back();
EXPECT_FALSE(b.tryBufferCloud(c));
c = cloud({}); c.is_bigendian = true;
EXPECT_FALSE(b.tryBufferCloud(c));
}
class InspectVoxelLayer : public robot_costmap_2d::VoxelLayer
{
public:
using robot_costmap_2d::ObstacleLayer::getMarkingObservations;
size_t pairedSources() const { return paired_depth_sources_.size(); }
};
TEST(DepthBuffer, RuntimeYamlActuallyEnablesTimestampAndPclOnDepthSource)
{
const auto runtime = std::filesystem::path(ROBOT_COSTMAP_2D_DIR)
.parent_path().parent_path().parent_path() / "config/runtime";
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", runtime.c_str(), 1), 0);
tf3::BufferCore tf;
transform(tf, "camera", 1, 0, 10, false);
transform(tf, "camera", 4, 0, 11, false);
transform(tf, "base_link", 0, 0);
tf3::TransformStampedMsg map_odom;
map_odom.header.frame_id = "map";
map_odom.child_frame_id = "odom";
ASSERT_TRUE(tf.setTransform(map_odom, "test", true));
// Run the real costmap factory so copyParentParameters(), not test-only
// manual parameter injection, forwards common source options to this layer.
// Select the camera observation profile in memory; the default runtime may
// intentionally use f_scan. No config file or ROS parameter server is written.
robot::NodeHandle root("~");
root.setParam("obstacles/observation_sources", std::string("pc_marking"));
root.setParam("local_costmap/library_path", std::string(DEPTH_MARKING_TEST_PLUGIN_PATH));
robot_costmap_2d::Costmap2DROBOT configured("local_costmap", tf);
configured.pause();
robot::NodeHandle settings("local_costmap/obstacles/pc_marking");
bool stamp_tf = false, pcl_enabled = false;
ASSERT_TRUE(settings.getParam("cloud_transform_at_stamp", stamp_tf));
ASSERT_TRUE(settings.getParam("marking_voxel_filter/enabled", pcl_enabled));
EXPECT_TRUE(stamp_tf);
EXPECT_TRUE(pcl_enabled);
robot_costmap_2d::LayeredCostmap parent("odom", true, false);
parent.getCostmap()->resizeMap(40, 40, .05, -1, -1);
InspectVoxelLayer layer;
ASSERT_NO_THROW(layer.initialize(&parent, "local_costmap/obstacles", &tf));
ASSERT_TRUE(layer.isEnabled());
layer.dataCallBack(cloud({{.011f, .011f, .11f}, {.019f, .011f, .11f}}),
"/camera/depth/points_proc");
std::vector<Observation> observations;
EXPECT_TRUE(layer.getMarkingObservations(observations));
ASSERT_EQ(observations.size(), 1u);
const auto &c = *observations.front().cloud_;
ASSERT_EQ(c.width, 1u);
robot_sensor_msgs::PointCloud2ConstIterator<float> x(c, "x");
EXPECT_NEAR(*x, 1.015, 1e-6);
EXPECT_EQ(c.header.stamp.nsec, 123456789u);
}
TEST(DepthBuffer, RuntimeFactoryForwardsObservedVolumeModeAndPairsSources)
{
const auto runtime = std::filesystem::path(ROBOT_COSTMAP_2D_DIR)
.parent_path().parent_path().parent_path() / "config/runtime";
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", runtime.c_str(), 1), 0);
tf3::BufferCore tf;
transform(tf, "base_link", 0, 0);
tf3::TransformStampedMsg map_odom;
map_odom.header.frame_id = "map"; map_odom.child_frame_id = "odom";
ASSERT_TRUE(tf.setTransform(map_odom, "test", true));
robot::NodeHandle root("~");
root.setParam("obstacles/observation_sources", std::string("pc_marking pc_clearing"));
root.setParam("local_costmap/library_path", std::string(DEPTH_MARKING_TEST_PLUGIN_PATH));
robot_costmap_2d::Costmap2DROBOT configured("local_costmap", tf);
configured.pause();
robot::NodeHandle settings("local_costmap/obstacles/pc_clearing");
std::string mode;
ASSERT_TRUE(settings.getParam("depth_clearing_mode", mode));
EXPECT_EQ(mode,"observed_volume");
// Every observed_volume key of the runtime YAML must reach the layer namespace; a key
// missing from the factory forward list silently falls back to its C++ default.
const YAML::Node runtime_clearing =
YAML::LoadFile((runtime / "costmap_common_params.yaml").string())["obstacles"]["pc_clearing"];
for (const char* key : {"depth_evidence_points_enabled", "depth_evidence_points_per_voxel",
"depth_marking_border_px", "depth_projection_margin_px", "depth_valid_max_z_m",
"depth_far_return_is_behind", "depth_reobserve_clearing", "depth_confirm_tolerance_m",
"depth_miss_frames", "depth_no_return_weight", "depth_stereo_baseline_m",
"depth_stereo_band_margin_px"})
{
ASSERT_TRUE(runtime_clearing[key].IsDefined()) << key;
ASSERT_TRUE(settings.hasParam(key)) << key;
EXPECT_EQ(YAML::Dump(settings.getParamValue(key)), YAML::Dump(runtime_clearing[key])) << key;
}
// Instantiate with the factory's scoped parameters, then verify the paired
// owner exists and a marking-only half does not enter legacy observations.
robot_costmap_2d::LayeredCostmap parent("odom", true, false);
parent.getCostmap()->resizeMap(40,40,.05,-1,-1);
InspectVoxelLayer layer;
ASSERT_NO_THROW(layer.initialize(&parent,"local_costmap/obstacles",&tf));
ASSERT_EQ(layer.pairedSources(),1u);
layer.dataCallBack(cloud({{.1f,0,.1f}}),"/camera/depth/points_proc");
std::vector<Observation> observations;
EXPECT_TRUE(layer.getMarkingObservations(observations));
EXPECT_TRUE(observations.empty());
}
} // namespace
int main(int argc, char **argv)
{
robot::Time::init();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -1,542 +0,0 @@
#include <robot_costmap_2d/depth_visibility.h>
#include <robot_costmap_2d/depth_frame_pairer.h>
#include <robot_costmap_2d/voxel_layer.h>
#include <robot_costmap_2d/inflation_layer.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <filesystem>
#include <cstring>
#include <thread>
using namespace robot_costmap_2d;
namespace {
robot_sensor_msgs::DepthCameraData::Ptr depth(double meters, robot::Time stamp = robot::Time(100,0)) {
auto d = boost::make_shared<robot_sensor_msgs::DepthCameraData>();
d->header.stamp=stamp; d->header.frame_id="camera";
d->depth.header=d->header; d->camera_info.header=d->header;
d->depth.width=d->camera_info.width=200; d->depth.height=d->camera_info.height=160;
d->depth.step=400; d->depth.encoding="16UC1"; d->depth.data.resize(64000);
uint16_t value=static_cast<uint16_t>(meters*1000);
for(size_t i=0;i<d->depth.data.size();i+=2) std::memcpy(&d->depth.data[i], &value, 2);
d->camera_info.K={100,0,100,0,100,80,0,0,1};
d->camera_info.P={100,0,100,0,0,100,80,0,0,0,1,0};
return d;
}
robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, bool point=true) {
robot_sensor_msgs::PointCloud2 c; c.header.stamp=stamp; c.header.frame_id="camera"; c.height=1;
robot_sensor_msgs::PointCloud2Modifier m(c); m.setPointCloud2FieldsByString(1,"xyz"); m.resize(point?1:0);
if(point) { robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"), y(c,"y"), z(c,"z");
*x=-.01;*y=.11;*z=.62; }
return c;
}
// One marking point given in the optical frame of the camera.
robot_sensor_msgs::PointCloud2 cloudAt(robot::Time stamp, float ox, float oy, float oz) {
robot_sensor_msgs::PointCloud2 c=cloud(stamp,true);
robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"), y(c,"y"), z(c,"z");
*x=ox;*y=oy;*z=oz;
return c;
}
tf3::TransformStampedMsg pose(robot::Time stamp, double yaw=0) {
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(stamp.sec,stamp.nsec);
Eigen::Matrix3d optical; optical << 0,0,1, -1,0,0, 0,-1,0;
Eigen::Quaterniond q(Eigen::AngleAxisd(yaw,Eigen::Vector3d::UnitZ())*optical);
p.transform.rotation.x=q.x();p.transform.rotation.y=q.y();
p.transform.rotation.z=q.z();p.transform.rotation.w=q.w();p.transform.translation.z=.19;
return p;
}
TEST(DepthVisibility, FullRegionFreeInvalidOccludedAndOutsideView) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;
auto d=depth(2);
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
Eigen::Vector3d lo(-.02,-.02,1),hi(.02,.02,1.05);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Free);
uint16_t zero=0;std::memcpy(&d->depth.data[80*400+100*2],&zero,2);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Unknown);
d=depth(.8);ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Surface);
d=depth(2);ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(Eigen::Vector3d(1,-.02,1),Eigen::Vector3d(1.05,.02,1.05)).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classify(Eigen::Vector3d(-.02,-.02,.05),hi).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classify(Eigen::Vector3d(1e30,-.02,1),Eigen::Vector3d(2e30,.02,1.05)).state,DepthVisibility::Unknown);
}
TEST(DepthVisibility, InvalidPixelAtProjectedEdgeAlsoBlocksClear) {
auto d=depth(2); DepthVisibilityChecker c;DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
uint16_t zero=0;std::memcpy(&d->depth.data[80*400+97*2],&zero,2);
ASSERT_TRUE(c.prepare(d,p,0,3,cfg));
EXPECT_EQ(c.classify(Eigen::Vector3d(-.02,-.02,1),Eigen::Vector3d(.02,.02,1.05)).state,DepthVisibility::Unknown);
}
TEST(DepthVisibility, RejectsWrongStampModelAndMalformedImage) {
auto d=depth(2);DepthVisibilityChecker c;DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(101,0);p.transform.rotation.w=1;
EXPECT_FALSE(c.prepare(d,p,0,3,cfg));p.header.stamp=tf3::Time(100,0);
d->camera_info.P[0]=90;EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
d=depth(2);d->depth.data.pop_back();EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
d=depth(2);d->depth.is_bigendian=true;EXPECT_FALSE(c.prepare(d,p,0,3,cfg));
}
// Camera frame == global frame here. A box whose top crosses the image top can never be
// certified, while a measured point inside the image can.
TEST(DepthVisibility, EvidencePointsCertifyAVoxelCutByTheImageTop) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
const Eigen::Vector3d lo(-.02,-.80,1),hi(.02,-.75,1.05); // v from about 0 to 5 px
const std::vector<Eigen::Vector3d> evidence{Eigen::Vector3d(0,-.77,1)}; // v = 3
auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classify(lo,hi).state,DepthVisibility::Unknown);
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Free);
d=depth(.9);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Surface);
d=depth(2);uint16_t zero=0;std::memcpy(&d->depth.data[4*400+101*2],&zero,2); // inside the 3x3 patch
ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(evidence).state,DepthVisibility::Unknown);
d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,-.80,1)}).state,DepthVisibility::Unknown); // v = 0
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,-1)}).state,DepthVisibility::Unknown); // behind
EXPECT_EQ(c.classifyPoints({}).state,DepthVisibility::Unknown);
// Every point must be free: one point in front of a surface keeps the voxel.
d=depth(1.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.6)}).state,DepthVisibility::Surface);
}
// A return beyond valid_max_z_m (3 m) proves the ray passed a point well inside the range.
TEST(DepthVisibility, FarReturnCountsAsBehindOnlyWhenEnabled) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
const std::vector<Eigen::Vector3d> point{Eigen::Vector3d(0,0,1)}; // u = 100, v = 80
auto d=depth(4);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Unknown); // default: not proof
cfg.far_return_is_behind=true;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Free);
// point + margin reaches the range limit: a far return proves nothing about it
EXPECT_EQ(c.classifyPoints({Eigen::Vector3d(0,0,2.99)}).state,DepthVisibility::Unknown);
d=depth(4);uint16_t zero=0;std::memcpy(&d->depth.data[80*400+101*2],&zero,2); // no-data in the patch
ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Unknown);
d=depth(.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.classifyPoints(point).state,DepthVisibility::Surface); // a nearer surface still keeps it
}
TEST(DepthVisibility, ProjectsInsideHonoursBorderAndUsableStrips) {
DepthVisibilityChecker c; DepthFrustumConfig cfg;cfg.clear_left_border_px=10;
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;
auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_TRUE(c.projectsInside(Eigen::Vector3d(0,-.77,1),2)); // v = 3
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(0,-.79,1),2)); // v = 1
EXPECT_TRUE(c.projectsInside(Eigen::Vector3d(-.88,0,1),2)); // u = 12
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(-.89,0,1),2)); // u = 11, inside the left strip + 2
EXPECT_FALSE(c.projectsInside(Eigen::Vector3d(0,0,.05),2)); // nearer than valid_min_z
}
// Re-observe-or-clear checker. Camera frame == global frame; (0,0,1) projects to u = 100, v = 80.
void setPixel(robot_sensor_msgs::DepthCameraData::Ptr& d,unsigned u,unsigned v,double meters) {
uint16_t value=static_cast<uint16_t>(meters*1000);std::memcpy(&d->depth.data[v*400+u*2],&value,2);
}
tf3::TransformStampedMsg identity() {
tf3::TransformStampedMsg p; p.header.frame_id="odom";p.child_frame_id="camera";
p.header.stamp=tf3::Time(100,0);p.transform.rotation.w=1;return p;
}
TEST(DepthReobserve, FourOutcomesOfOnePoint) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
const std::vector<Eigen::Vector3d> point{Eigen::Vector3d(0,0,1)};
auto d=depth(1.03);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::Confirmed); // within 5 cm
d=depth(.9);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::Occluded);
d=depth(1.2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::SeenThrough);
d=depth(0);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::NoReturn);
}
TEST(DepthReobserve, OutOfViewWhenNotProjectableOrOutsideTheTrustedRange) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
auto d=depth(2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({}),DepthObservation::OutOfView);
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,-1)}),DepthObservation::OutOfView); // behind the camera
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,3.5)}),DepthObservation::OutOfView); // beyond valid_max_z_m
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,-.80,1)}),DepthObservation::OutOfView); // v = 0: no full patch
EXPECT_EQ(c.observePoints({Eigen::Vector3d(5,0,1)}),DepthObservation::OutOfView); // right of the image
}
TEST(DepthReobserve, InvalidPixelsDoNotBlockSeeingThrough) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
const std::vector<Eigen::Vector3d> point{Eigen::Vector3d(0,0,1)};
auto d=depth(0);setPixel(d,101,81,2); // one valid pixel behind, eight with no return
ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::SeenThrough);
}
TEST(DepthReobserve, OccluderInThePatchBeatsSeenThroughAndConfirmBeatsBoth) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
const std::vector<Eigen::Vector3d> point{Eigen::Vector3d(0,0,1)};
auto d=depth(2);setPixel(d,99,79,.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::Occluded);
setPixel(d,101,81,1.02);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints(point),DepthObservation::Confirmed);
// The voxel takes its strongest point: one point still on a surface keeps it.
d=depth(1.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.5)}),DepthObservation::Confirmed);
d=depth(1.2);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1),Eigen::Vector3d(0,0,1.5)}),DepthObservation::Occluded);
}
TEST(DepthReobserve, FarReturnIsBehindOnlyWhenEnabledAndInsideTheRange) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
auto d=depth(4);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1)}),DepthObservation::NoReturn);
cfg.far_return_is_behind=true;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,1)}),DepthObservation::SeenThrough);
EXPECT_EQ(c.observePoints({Eigen::Vector3d(0,0,2.99)}),DepthObservation::NoReturn); // 2.99 + 0.05 >= 3
}
// fx = 100: the band at depth z is ceil(100 * 0.1 / z) + 10 px. Column u = 30 is in it at 0.5 m
// (30 + 1 px patch > 30) and clear of it at 2.5 m (14 + 1 px).
TEST(DepthReobserve, StereoBandIsOutOfViewNearAndUsableFar) {
DepthVisibilityChecker c; DepthFrustumConfig cfg; const auto p=identity();
const Eigen::Vector3d near(-.35,0,.5), far(-1.75,0,2.5); // both u = 30
auto d=depth(.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({near}),DepthObservation::Confirmed); // band disabled
cfg.stereo_baseline_m=.1;cfg.stereo_band_margin_px=10;ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({near}),DepthObservation::OutOfView);
EXPECT_FALSE(c.projectsInside(near,2));
d=depth(2.5);ASSERT_TRUE(c.prepare(d,p,-10,10,cfg));
EXPECT_EQ(c.observePoints({far}),DepthObservation::Confirmed);
EXPECT_TRUE(c.projectsInside(far,2));
}
TEST(DepthPairer, MissingHalfExactPairAndDeduplication) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5);
auto c=cloud(robot::Time(100,0));p.addCloud(c);DepthFramePairer::Candidate next;
EXPECT_FALSE(p.next(next));p.addDepth(depth(2));ASSERT_TRUE(p.next(next));
EXPECT_EQ(next.stamp,c.header.stamp.toNSec());p.applied(next.stamp);
p.addCloud(c);p.addDepth(depth(2));EXPECT_FALSE(p.next(next));
EXPECT_EQ(p.counts().applied,1u);EXPECT_EQ(p.counts().duplicate,2u);
}
TEST(DepthPairer, NewerAppliedFrameCannotBeResurrectedByDelayedOlderCloud) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;DepthFramePairer p(cfg,.5);
p.addCloud(cloud(robot::Time(100,0)));robot::Time::setNow(robot::Time(100,100000000));
p.addCloud(cloud(robot::Time(100,100000000)));p.addDepth(depth(2,robot::Time(100,100000000)));
DepthFramePairer::Candidate n;ASSERT_TRUE(p.next(n));p.applied(n.stamp);
p.addDepth(depth(2));EXPECT_FALSE(p.next(n));p.reset();
p.addCloud(cloud(robot::Time(100,0)));p.addDepth(depth(2));EXPECT_FALSE(p.next(n));
}
TEST(DepthPairer, BoundTimeoutAgeAndClockReset) {
robot::Time::setNow(robot::Time(100,0));DepthFrustumConfig cfg;cfg.pair_queue_size=2;cfg.pair_max_wait_s=.005;
DepthFramePairer p(cfg,.5);
for(int i=0;i<3;++i) {robot::Time::setNow(robot::Time(100,i*10000000));p.addCloud(cloud(robot::Time(100,i*10000000)));}
EXPECT_EQ(p.counts().overflow,1u);std::this_thread::sleep_for(std::chrono::milliseconds(10));
DepthFramePairer::Candidate n;EXPECT_FALSE(p.next(n));EXPECT_EQ(p.counts().expired,2u);
p.addCloud(cloud(robot::Time(99,0)));EXPECT_EQ(p.counts().stale,1u);
p.applied(robot::Time(100,20000000).toNSec());
robot::Time::setNow(robot::Time(10,0));p.addCloud(cloud(robot::Time(10,0)));p.addDepth(depth(2,robot::Time(10,0)));
EXPECT_TRUE(p.next(n));
}
class DepthLayerTest:public ::testing::Test {
protected:
tf3::BufferCore tf;
LayeredCostmap parent{"odom",false,false};
VoxelLayer layer;
uint32_t tick=0;
void SetUp() override {
robot::Time::setNow(robot::Time(100,0));
auto runtime=std::filesystem::path(ROBOT_COSTMAP_2D_DIR).parent_path().parent_path().parent_path()/"config/runtime";
setenv("PNKX_NAV_CORE_CONFIG_DIR",runtime.c_str(),1);
YAML::Node cfg=YAML::Clone(YAML::LoadFile((runtime/"costmap_common_params.yaml").string())["obstacles"]);
cfg["observation_sources"]="pc_marking pc_clearing";cfg["footprint_clearing_enabled"]=false;cfg["enabled"]=true;
// Explicit, so the result does not depend on what the runtime YAML currently enables.
cfg["pc_clearing"]["depth_evidence_points_enabled"]=false;
cfg["pc_clearing"]["depth_far_return_is_behind"]=false;
cfg["pc_clearing"]["depth_reobserve_clearing"]=false;
cfg["pc_clearing"]["depth_stereo_baseline_m"]=0.0;
configure(cfg);
robot::NodeHandle nh("~");nh.setParam("depth_test",cfg);
parent.getCostmap()->resizeMap(80,80,.05,-2,-2);layer.initialize(&parent,"depth_test",&tf);
ASSERT_TRUE(layer.isEnabled());
}
virtual void configure(YAML::Node&) {}
robot::Time now() {return robot::Time(100,++tick*10000000);}
// Marking point given in the camera optical frame; the image shows `measurement` everywhere.
void frameCloud(double measurement,float ox,float oy,float oz) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloudAt(stamp,ox,oy,oz),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(measurement,stamp);
layer.dataCallBack(d,"/camera/depth/data");update();
}
void update() {double a=1e9,b=1e9,c=-1e9,d=-1e9;layer.updateBounds(0,0,0,&a,&b,&c,&d);}
void frame(double measurement,bool point=false,double yaw=0,bool hasTf=true,bool hasCloud=true,bool hasDepth=true) {
auto stamp=now();robot::Time::setNow(stamp);
if(hasTf) ASSERT_TRUE(tf.setTransform(pose(stamp,yaw),"test"));
if(hasCloud) layer.dataCallBack(cloud(stamp,point),"/camera/depth/points_proc");
if(hasDepth) {robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(measurement,stamp);
layer.dataCallBack(d,"/camera/depth/data");}
update();
}
unsigned char at(double x=.62,double y=.01) {unsigned a,b;EXPECT_TRUE(layer.worldToMap(x,y,a,b));return layer.getCost(a,b);}
};
TEST_F(DepthLayerTest, RetainsOutsideInvalidOccludedAndClearsOnFirstValidFrame) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,1.57);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(.4);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE); // one valid frame; no free-frame delay
}
TEST_F(DepthLayerTest, MissingCloudDepthOrTfCannotClearAndNoTtl) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,true,false,true);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,true,true,false);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,false,true,true);EXPECT_EQ(at(),LETHAL_OBSTACLE);
robot::Time::setNow(robot::Time(110,0));update();EXPECT_EQ(at(),LETHAL_OBSTACLE);
EXPECT_FALSE(layer.isCurrent());
}
TEST_F(DepthLayerTest, ClearingFrameDoesNotRepeatOldMarkingCloud) {
frame(.62,true);frame(2);ASSERT_EQ(at(),FREE_SPACE);
layer.dataCallBack(cloud(robot::Time(100,10000000)),"/camera/depth/points_proc");
update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, RollingOriginPreservesOverlapAndDropsExitedCells) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(-1.5,-2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(1,-2);layer.updateOrigin(-2,-2);EXPECT_NE(at(),LETHAL_OBSTACLE);
}
TEST_F(DepthLayerTest, WaitingPairAppliesWhenItsExactTfArrives) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,0,false);EXPECT_EQ(at(),LETHAL_OBSTACLE);
auto stamp=robot::Time(100,tick*10000000);
ASSERT_TRUE(tf.setTransform(pose(stamp),"late_tf"));
update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, PendingFrameSurvivesRollingStorageShift) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(2,stamp);layer.dataCallBack(d,"/camera/depth/data");
layer.updateOrigin(-1.5,-2);update();EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthLayerTest, MasterAndInflationRemoveTheClearedObstacle) {
parent.addPlugin(boost::shared_ptr<Layer>(&layer,[](Layer*){}));
auto inflation=boost::make_shared<InflationLayer>();
robot::NodeHandle nh("~");nh.setParam("depth_inflation/inflation_radius",.3);
nh.setParam("depth_inflation/cost_scaling_factor",10.);
parent.addPlugin(inflation);inflation->initialize(&parent,"depth_inflation",&tf);
std::vector<robot_geometry_msgs::Point> footprint(4);
footprint[0].x=footprint[1].x=-.1;footprint[2].x=footprint[3].x=.1;
footprint[0].y=footprint[3].y=-.1;footprint[1].y=footprint[2].y=.1;
parent.setFootprint(footprint);
for(bool occupied : {true,false}) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
layer.dataCallBack(cloud(stamp,occupied),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(occupied?.62:2,stamp);
layer.dataCallBack(d,"/camera/depth/data");parent.updateMap(0,0,0);
unsigned x,y;ASSERT_TRUE(parent.getCostmap()->worldToMap(.62,.01,x,y));
EXPECT_EQ(parent.getCostmap()->getCost(x,y),occupied?LETHAL_OBSTACLE:FREE_SPACE);
ASSERT_TRUE(parent.getCostmap()->worldToMap(.72,.01,x,y));
if(occupied) EXPECT_GT(parent.getCostmap()->getCost(x,y),FREE_SPACE);
else EXPECT_EQ(parent.getCostmap()->getCost(x,y),FREE_SPACE);
}
}
TEST_F(DepthLayerTest, AStillOccludedVoxelKeepsItsColumnLethal) {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto c=cloud(stamp);robot_sensor_msgs::PointCloud2Modifier m(c);m.resize(2);
robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"),y(c,"y"),z(c,"z");
*x=-.01;*y=.11;*z=.62;++x;++y;++z;*x=-.01;*y=-.29;*z=.62;
layer.dataCallBack(c,"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(.62,stamp);layer.dataCallBack(d,"/camera/depth/data");update();
ASSERT_EQ(at(),LETHAL_OBSTACLE);
stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto partial=depth(2,stamp);uint16_t blocked=400;
for(unsigned v=0;v<65;++v) for(unsigned u=0;u<200;++u)
std::memcpy(&partial->depth.data[v*400+u*2],&blocked,2);
layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc");
d=partial;layer.dataCallBack(d,"/camera/depth/data");update();EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
// A point seen 7 px below the image top marks voxel z [0.625, 0.6875] m, whose top
// corner projects above the image. Whole-voxel rule: never certified (the person/hand
// phantom of the 2026-10-15 lift bag).
TEST_F(DepthLayerTest, WholeVoxelRuleKeepsAVoxelCutByTheImageTop) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
}
class DepthEvidenceLayerTest:public DepthLayerTest {
protected:
void configure(YAML::Node& cfg) override {
cfg["pc_clearing"]["depth_evidence_points_enabled"]=true;
cfg["pc_clearing"]["depth_marking_border_px"]=2;
}
};
TEST_F(DepthEvidenceLayerTest, EvidencePointsClearAVoxelCutByTheImageTop) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, RetainsOutsideInvalidOccludedAndClearsOnFirstValidFrame) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2,false,1.57);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(.4);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, MarkingDropsPointsInTheImageBorder) {
frameCloud(.62,-.01f,-.49f,.62f);EXPECT_NE(at(),LETHAL_OBSTACLE); // v = 0.97 px
frameCloud(.62,-.01f,-.45f,.62f);EXPECT_EQ(at(),LETHAL_OBSTACLE); // v = 7.4 px
}
TEST_F(DepthEvidenceLayerTest, EvidenceSurvivesRollingShift) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
layer.updateOrigin(-1.5,-2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthEvidenceLayerTest, AStillVisibleObjectIsNeverCertifiedFree) {
frameCloud(.62,-.01f,-.45f,.62f);ASSERT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<3;++i) {frameCloud(.62,-.01f,-.45f,.62f);EXPECT_EQ(at(),LETHAL_OBSTACLE);}
frame(.62);EXPECT_EQ(at(),LETHAL_OBSTACLE); // no marking this frame, surface still seen
}
// Two voxels in the column of (0.62, 0.01): z 0.08 m (seen by image rows below 65) and
// z 0.48 m (rows above 65). The partial frame frees the low one and keeps the high one
// occluded, so a column update would re-derive the cell from any voxel left behind.
class DepthColumnClearTest:public DepthEvidenceLayerTest {
protected:
void configure(YAML::Node& cfg) override {
DepthEvidenceLayerTest::configure(cfg);
cfg["footprint_clearing_enabled"]=true;
}
void markTwoVoxels() {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto c=cloud(stamp);robot_sensor_msgs::PointCloud2Modifier m(c);m.resize(2);
robot_sensor_msgs::PointCloud2Iterator<float> x(c,"x"),y(c,"y"),z(c,"z");
*x=-.01;*y=.11;*z=.62;++x;++y;++z;*x=-.01;*y=-.29;*z=.62;
layer.dataCallBack(c,"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=depth(.62,stamp);layer.dataCallBack(d,"/camera/depth/data");update();
}
void partialFrame() {
auto stamp=now();robot::Time::setNow(stamp);ASSERT_TRUE(tf.setTransform(pose(stamp),"test"));
auto partial=depth(2,stamp);uint16_t blocked=400;
for(unsigned v=0;v<65;++v) for(unsigned u=0;u<200;++u)
std::memcpy(&partial->depth.data[v*400+u*2],&blocked,2);
layer.dataCallBack(cloud(stamp,false),"/camera/depth/points_proc");
robot_sensor_msgs::DepthCameraData::ConstPtr d=partial;layer.dataCallBack(d,"/camera/depth/data");update();
}
void setFootprint(double x0,double x1,double y0,double y1) {
std::vector<robot_geometry_msgs::Point> footprint(4);
footprint[0].x=footprint[1].x=x0;footprint[2].x=footprint[3].x=x1;
footprint[0].y=footprint[3].y=y0;footprint[1].y=footprint[2].y=y1;
parent.setFootprint(footprint);
}
uint32_t markedBits(double x=.62,double y=.01) {
unsigned a,b;EXPECT_TRUE(layer.worldToMap(x,y,a,b));
return layer.voxelSnapshot().data[b*layer.getSizeInCellsX()+a]>>16;
}
};
TEST_F(DepthColumnClearTest, FootprintClearingAlsoFreesTheVoxelColumn) {
setFootprint(-1.9,-1.8,-1.9,-1.8); // far corner of the window
markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE);ASSERT_NE(markedBits(),0u);
setFootprint(.50,.75,-.10,.10);update(); // robot body now covers the cell
EXPECT_EQ(at(),FREE_SPACE);EXPECT_EQ(markedBits(),0u);
setFootprint(-1.9,-1.8,-1.9,-1.8);partialFrame();
EXPECT_EQ(at(),FREE_SPACE); // nothing left in the column to re-derive the cell
}
TEST_F(DepthColumnClearTest, ClearAreaAlsoFreesTheVoxelColumn) {
setFootprint(-1.9,-1.8,-1.9,-1.8);
markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE);
layer.clearArea(0,0,0,0,false); // empty kept window: clear the whole layer
EXPECT_EQ(at(),NO_INFORMATION);EXPECT_EQ(markedBits(),0u);
partialFrame();EXPECT_NE(at(),LETHAL_OBSTACLE);
}
TEST_F(DepthColumnClearTest, ClearAreaFollowsTheBaseWindowSelection) {
setFootprint(-1.9,-1.8,-1.9,-1.8);
markTwoVoxels();ASSERT_EQ(at(),LETHAL_OBSTACLE);
unsigned ux,uy;ASSERT_TRUE(layer.worldToMap(.62,.01,ux,uy));
const int x=static_cast<int>(ux),y=static_cast<int>(uy);
layer.clearArea(x-3,y-3,x+3,y+3,false); // default recovery: keep the window, clear outside it
EXPECT_EQ(at(),LETHAL_OBSTACLE);EXPECT_NE(markedBits(),0u);
layer.clearArea(x-3,y-3,x+3,y+3,true); // inverted: clear inside the window
EXPECT_EQ(at(),NO_INFORMATION);EXPECT_EQ(markedBits(),0u);
}
class DepthFarReturnLayerTest:public DepthEvidenceLayerTest {
protected:
void configure(YAML::Node& cfg) override {
DepthEvidenceLayerTest::configure(cfg);
cfg["pc_clearing"]["depth_far_return_is_behind"]=true;
}
};
TEST_F(DepthEvidenceLayerTest, FarReturnKeepsTheVoxelByDefault) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(4);EXPECT_EQ(at(),LETHAL_OBSTACLE);
}
TEST_F(DepthFarReturnLayerTest, FarReturnClearsWhenEnabledButNoDataStillKeeps) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(4);EXPECT_EQ(at(),FREE_SPACE);
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(0);EXPECT_EQ(at(),LETHAL_OBSTACLE);
}
// Re-observe-or-clear on the layer. The marked point (0.62, 0.01, 0.08) projects to (98, 98);
// frame(m) shows depth m everywhere: .62 re-observes it, 2 sees through, .4 occludes, 0 is no return.
class DepthReobserveLayerTest:public DepthEvidenceLayerTest {
protected:
void configure(YAML::Node& cfg) override {
DepthEvidenceLayerTest::configure(cfg);
cfg["pc_clearing"]["depth_reobserve_clearing"]=true;
cfg["pc_clearing"]["depth_confirm_tolerance_m"]=.05;
cfg["pc_clearing"]["depth_miss_frames"]=3;
cfg["pc_clearing"]["depth_no_return_weight"]=noReturnWeight();
cfg["pc_clearing"]["depth_stereo_baseline_m"]=stereoBaseline();
cfg["pc_clearing"]["depth_stereo_band_margin_px"]=10;
}
virtual double noReturnWeight() const {return 0.;}
virtual double stereoBaseline() const {return 0.;}
};
TEST_F(DepthReobserveLayerTest, SeenThroughFreesOnlyAfterMissFrames) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthReobserveLayerTest, ConfirmRestartsTheMissCount) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);frame(2);frame(.62); // surface measured again, no marking point
frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthReobserveLayerTest, RemarkedVoxelStartsANewMissCount) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
frame(2);
frameCloud(2,-.01f,.11f,.62f); // seen through (2nd miss), then marked again in the same frame
frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthReobserveLayerTest, OccludedOutOfViewAndNoReturnNeverExpire) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<20;++i) frame(.4);
EXPECT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<20;++i) frame(2,false,1.57); // camera turned away
EXPECT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<20;++i) frame(0);
EXPECT_EQ(at(),LETHAL_OBSTACLE);
frame(2);frame(2);EXPECT_EQ(at(),LETHAL_OBSTACLE); // none of the above counted as a miss
frame(2);EXPECT_EQ(at(),FREE_SPACE);
}
TEST_F(DepthReobserveLayerTest, StillVisibleObjectIsKept) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<20;++i) frame(i%2?.64:.60); // depth noise inside the 5 cm tolerance
EXPECT_EQ(at(),LETHAL_OBSTACLE);
}
class DepthReobserveNoReturnTest:public DepthReobserveLayerTest {
protected:
double noReturnWeight() const override {return .5;}
};
TEST_F(DepthReobserveNoReturnTest, NoReturnFreesWhenWeighted) {
frame(.62,true);ASSERT_EQ(at(),LETHAL_OBSTACLE);
for(int i=0;i<5;++i) frame(0);
EXPECT_EQ(at(),LETHAL_OBSTACLE); // 2.5 misses
frame(0);EXPECT_EQ(at(),FREE_SPACE);
}
// Band at 0.62 m: ceil(100 * 0.1 / 0.62) + 10 = 27 px, plus the 2 px marking border.
class DepthReobserveStereoBandTest:public DepthReobserveLayerTest {
protected:
double stereoBaseline() const override {return .1;}
};
TEST_F(DepthReobserveStereoBandTest, MarkingSkipsTheStereoBand) {
frameCloud(.62,-.496f,.11f,.62f);EXPECT_NE(at(.62,.496),LETHAL_OBSTACLE); // u = 20
frameCloud(.62,-.248f,.11f,.62f);EXPECT_EQ(at(.62,.248),LETHAL_OBSTACLE); // u = 60
}
}
int main(int argc,char**argv) {robot::Time::init();testing::InitGoogleTest(&argc,argv);return RUN_ALL_TESTS();}