19 Commits

Author SHA1 Message Date
af66991a3e build: bỏ dependency PCL không dùng
Gói không include một header pcl/ nào — đây là di sản từ thời còn dùng pcl_ros.

Trên robot aarch64 có VTK 9.1 build kèm MPI, chuỗi PCL -> VTK -> VTK::mpi ->
MPI::MPI_C làm CMake gãy ở generate step: root project khai LANGUAGES CXX nên
find_package(MPI COMPONENTS C) không bao giờ thành công và target MPI::MPI_C
không được tạo. Component io là chỗ kéo VTK vào. Máy dev không dính vì không
cài VTK cmake package, find_VTK() tìm không thấy rồi bỏ qua trong im lặng.

Bỏ find_package, DEPENDS PCL, PCL_INCLUDE_DIRS, PCL_LIBRARIES,
link_directories(PCL_LIBRARY_DIRS) và PCL_DEFINITIONS.
2026-08-25 12:38:48 +07:00
d60e1e8db7 feat: đặt tên thread map-update (cm_<tên costmap>) cho top -H / pidstat -t
Đo CPU thật của costmap ở mức OS không cần bật metrics nội bộ: thread hiện ra
là cm_local_costma / cm_global_costm thay vì lẫn vào amr_control_node.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 10:24:04 +07:00
84c83786ba feat: snapshot API cho reader — planner solve trên bản copy, hết chặn map-update
Costmap2D::copyFrom: copy metadata + grid, chỉ realloc khi size đổi (operator=
delete/new mỗi lần — không hợp copy định kỳ 30 Hz). Caller giữ mutex nguồn.

Costmap2DROBOT: key config snapshot_for_readers (mặc định false = nguyên trạng);
refreshSnapshot() khoá master mutex đúng bằng thời gian memcpy;
getCostmapForRead() trả snapshot khi bật / lưới live khi tắt. Object snapshot
ổn định địa chỉ, refresh tại chỗ — không tái tạo con trỏ (bài học
DOUBLE_FREE_BUG_FIX_REPORT). Hợp đồng single-consumer: refresh + đọc cùng
thread control loop.

Kèm: load debug_level (commit trước) + fix priv_nh(priv_nh, name) tự khởi tạo
từ chính nó — đổi thành (nh, name), cùng kết quả namespace, hết UB-adjacent.

Verify: test_costmap 10/10 (3 test copyFrom mới), sim mission — lock_wait local
53 ms max -> 13 us, p99 cycle 21.4 -> 3.4 ms, local costmap chạy được 10 Hz
với 1.2% một core.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:19:33 +07:00
37eece7a11 feat: debug metrics updateMap — lock_wait/lock_hold, window cells, empty cycles
debug_level (0/1/2) trên báo cáo performance định kỳ: 0 giữ nguyên output cũ;
1 thêm lock_wait (tranh chấp mutex với planner) tách khỏi lock_hold (việc của
chính costmap), kích thước window update và số cycle rỗng — cycle rỗng giờ vẫn
được đếm + report nên costmap idle (global) không còn biến mất khỏi log;
2 thêm per-layer bounds_grow [m^2] chỉ mặt layer nào nở vùng update.

Số đo sim: lock_wait chiếm 75-90% cycle local costmap khi PRIEST solve
(median 7.5 ms, max 53 ms) trong khi lock_hold chỉ ~1.8 ms — căn cứ trực tiếp
cho snapshot API ở commit sau.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:19:18 +07:00
3196a19040 build: look up GTest quietly instead of requiring it
GTest is only used by the test executables, which the robot deployment build
does not produce. Requiring it at the top of the file made cmake fail to
configure on a machine without GTest installed even with the tests off.
2026-08-15 12:43:50 +07:00
678874e1c9 build: default the test executables to the build mode instead of always on
The standalone CMake build is the robot deployment path and must not pull in
GTest or produce test executables. A catkin workspace is a development machine
and keeps the tests. -DBUILD_COSTMAP_TESTS=ON still forces them on standalone.
2026-08-15 12:37:12 +07:00
bb74601f09 update 2026-08-14 14:25:00 +07:00
9f7e2f82f1 :optimal test NUC 27/7 15:14 2026-07-27 15:14:39 +07:00
c17ac9fc06 :optimal test NUC 27/7 14:52 2026-07-27 14:52:19 +07:00
c2944f7a98 :optimal 27/7 14:45 2026-07-27 14:45:26 +07:00
ffe2f77c1b :optimal 27/7 13:48 2026-07-27 13:48:17 +07:00
5da5421ec7 :optimal 27/7 12:11 2026-07-27 12:11:14 +07:00
e3b52765c1 :optimal 2026-07-27 11:22:49 +07:00
e2ee28bd63 :optimal 2026-07-27 10:09:38 +07:00
c888af3b7c otimal 2026-07-23 16:12:55 +07:00
0e84ac53cb otimal 2026-07-23 14:47:27 +07:00
03b13f6936 add file readme 2026-07-14 11:37:35 +07:00
bdbb03aa51 otimal deep coppy obj 2026-07-14 11:08:23 +07:00
6a9834d3a8 add multi camera depth 2026-07-14 09:42:35 +07:00
20 changed files with 1500 additions and 2134 deletions

View File

@@ -23,9 +23,6 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem)
# still configure. The test block below requires it where it is actually used. # still configure. The test block below requires it where it is actually used.
find_package(GTest QUIET) find_package(GTest QUIET)
find_package(yaml-cpp REQUIRED) find_package(yaml-cpp REQUIRED)
# 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) if (NOT BUILDING_WITH_CATKIN)
@@ -178,12 +175,7 @@ add_library(plugins SHARED
plugins/directional_layer.cpp plugins/directional_layer.cpp
plugins/preferred_layer.cpp plugins/preferred_layer.cpp
plugins/unpreferred_layer.cpp plugins/unpreferred_layer.cpp
plugins/depth_camera_obstacle_layer.cpp
) )
# 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})
if(BUILDING_WITH_CATKIN) if(BUILDING_WITH_CATKIN)
add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
@@ -331,14 +323,4 @@ if(BUILD_COSTMAP_TESTS)
${TF3_LIBRARY} ${TF3_LIBRARY}
) )
endif() 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() endif()

221
README.md
View File

@@ -15,8 +15,7 @@ Luồng cập nhật chính:
```text ```text
OccupancyGrid -------------------------> StaticLayer ---------+ OccupancyGrid -------------------------> StaticLayer ---------+
LaserScan / PointCloud / PointCloud2 --> ObstacleLayer -------+--> master costmap LaserScan / PointCloud / PointCloud2 --> ObstacleLayer -------+--> master costmap
LaserScan / PointCloud2 ---------------> VoxelLayer ----------+ PointCloud2 + DepthCameraData ---------> VoxelLayer ----------+
PointCloud2 từ depth camera -----------> DepthCameraObstacleLayer
master costmap ------------------------> InflationLayer -------+ master costmap ------------------------> InflationLayer -------+
``` ```
@@ -36,8 +35,7 @@ Các plugin được build trong package:
| --- | --- | | --- | --- |
| `StaticLayer` | Đưa `OccupancyGrid` tĩnh vào costmap. | | `StaticLayer` | Đưa `OccupancyGrid` tĩnh vào costmap. |
| `ObstacleLayer` | Marking/clearing 2D từ `LaserScan`, `PointCloud`, `PointCloud2`. | | `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, xóa bằng raytrace (laser/point cloud). | | `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. |
| `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. | | `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. | | `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. | | `DirectionalLayer` | Gộp thông tin vùng có hướng di chuyển. |
@@ -193,9 +191,21 @@ voxel_layer:
unknown_threshold: 15.0 unknown_threshold: 15.0
mark_threshold: 0 mark_threshold: 0
combination_method: 1 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
``` ```
Depth camera dùng plugin `DepthCameraObstacleLayer` (mục 5.6), không đi qua `VoxelLayer`. 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.
### 3.5. Inflation layer ### 3.5. Inflation layer
@@ -211,8 +221,8 @@ inflation_layer:
## 4. Cấu hình tham khảo cho T800 ## 4. Cấu hình tham khảo cho T800
Ví dụ sau dùng laser cho `VoxelLayer` (marking + raytrace clearing) và point cloud đã Ví dụ sau dùng laser để marking/clearing 2D, point cloud đã xử lý để marking
xử lý của depth camera cho `DepthCameraObstacleLayer`. vật cản 3D và message gộp `DepthCameraData` để clearing theo frustum.
### 4.1. Tham số dùng chung cho global và local costmap ### 4.1. Tham số dùng chung cho global và local costmap
@@ -228,11 +238,11 @@ footprint:
- [-0.583, 0.48] - [-0.583, 0.48]
- [-0.583, -0.48] - [-0.583, -0.48]
lidar_obstacles: obstacles:
observation_sources: f_scan observation_sources: b_scan pc_marking pc_clearing
f_scan: b_scan:
topic: /f_scan topic: /b_scan
data_type: LaserScan data_type: LaserScan
sensor_frame: "" sensor_frame: ""
marking: true marking: true
@@ -244,30 +254,52 @@ lidar_obstacles:
raytrace_range: 3.0 raytrace_range: 3.0
min_obstacle_height: 0.0 min_obstacle_height: 0.0
max_obstacle_height: 0.25 max_obstacle_height: 0.25
frustum_clearing_enabled: false
depth_obstacles: # Giữ PointCloud2 cho marking và persistence nếu cần.
observation_sources: depth_cam pc_marking:
# 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 topic: /camera/depth/points_proc
data_type: PointCloud2
sensor_frame: "" sensor_frame: ""
sensor_frame_is_optical: true marking: true
clearing: false
inf_is_valid: false
observation_persistence: 0.0 observation_persistence: 0.0
expected_update_rate: 0.8 expected_update_rate: 0.5
FOV_W: 1.23 obstacle_range: 2.5
FOV_V: 0.76 raytrace_range: 3.0
min_detect_distance: 0.15 min_obstacle_height: 0.10
max_detect_distance: 2.5 max_obstacle_height: 1.00
min_obstacle_height: 0.04 frustum_clearing_enabled: false
max_obstacle_height: 1.0
# 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
``` ```
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 ### 4.2. Global costmap
```yaml ```yaml
@@ -330,11 +362,10 @@ local_costmap:
origin_y: 0.0 origin_y: 0.0
plugins: plugins:
- {name: lidar_obstacles, type: VoxelLayer} - {name: obstacles, type: VoxelLayer}
- {name: depth_obstacles, type: DepthCameraObstacleLayer}
- {name: inflation, type: InflationLayer} - {name: inflation, type: InflationLayer}
lidar_obstacles: obstacles:
enabled: true enabled: true
footprint_clearing_enabled: true footprint_clearing_enabled: true
origin_z: 0.0 origin_z: 0.0
@@ -413,15 +444,15 @@ Quy trình chỉnh:
### 5.4. Observation source của ObstacleLayer/VoxelLayer ### 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í `observation_sources` là chuỗi các tên source cách nhau bằng khoảng trắng, ví
dụ `f_scan b_scan`. Mỗi tên phải có một map tham số cùng tên. dụ `b_scan pc_marking pc_clearing`. 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 | | 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. | | `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`; giá trị khác báo lỗi lúc khởi động. | | `data_type` | `PointCloud` | Một trong `LaserScan`, `PointCloud`, `PointCloud2`, `DepthCameraData`. |
| `sensor_frame` | rỗng | Để rỗng để dùng `header.frame_id`; chỉ đặt khi cần ép origin của sensor. | | `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. | | `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. | | `clearing` | `false` | Raytrace PointCloud/LaserScan để xóa vùng trống. Không điều khiển depth-frustum clearing. |
| `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. | | `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. | | `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. | | `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. |
@@ -457,80 +488,28 @@ 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 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`. đồng thời kiểm tra `origin_z`, `z_resolution` và `z_voxels`.
### 5.6. DepthCameraObstacleLayer ### 5.6. Depth frustum clearing
Port thuật toán của `costmap_depth_camera` (noetic). Layer có loại riêng `LayerType::DEPTH_CAMERA_LAYER`:
`SensorGateway` của `move_base2` chỉ đẩy `PointCloud2` vào nó (không đẩy `LaserScan`, `PointCloud`, `DepthCameraData`).
Layer nhận `PointCloud2` đã lọc của từng depth camera và giữ các điểm vật cản 3D trong frame global của costmap. Lưới riêng của layer
phản chiếu các điểm đó theo từng ô (cột có điểm là `LETHAL`, cột mất điểm cuối cùng thành
`FREE_SPACE`), rồi được gộp lên master như `ObstacleLayer` (`combination_method`). 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ỏ; điểm dưới footprint robot bị xóa khi
bật `footprint_clearing_enabled`.
Mọi ô đổi trạng thái (đánh dấu hoặc xóa) đều được đưa vào vùng cập nhật, nên ô vừa xóa biến
khỏi master ngay trong chu kỳ đó. `reset()` (dùng bởi `Costmap2DROBOT::resetLayers()`) xóa toàn
bộ điểm đã lưu; `clearArea()` (dùng bởi `ClearCostmapRecovery`) xóa điểm theo đúng ngữ nghĩa
của `CostmapLayer::clearArea()`: `invert_area: false` xóa các ô **ngoài** hình chữ nhật và giữ
các ô bên trong, `true` xóa các ô **bên trong**.
Tham số chung của layer:
| Tham số | Mặc định code | Ý nghĩa và cách chỉnh | | Tham số | Mặc định code | Ý nghĩa và cách chỉnh |
| --- | ---: | --- | | --- | ---: | --- |
| `enabled` | `true` | Bật/tắt layer. | | `frustum_clearing_enabled` | `false` | Chọn đường clearing trực tiếp từ `DepthCameraData`. |
| `observation_sources` | rỗng | Danh sách tên source, mỗi camera một source. | | `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`. |
| `check_radius` | `0.1 m` | Bán kính tìm điểm cloud quanh điểm đã lưu khi xét xóa. | | `frustum_min_range` | `0.20 m` | Không clear vùng quá gần camera, nơi depth thường không đáng tin. |
| `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. | | `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. |
| `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` | Xóa ô và điểm đã lưu nằm dưới footprint robot. |
| `combination_method` | `1` | Như các layer khác. |
| `use_global_frame_to_mark` | `true` | Chỉ hỗ trợ `true`; `false` báo lỗi. |
| `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. |
Tham số của từng source (camera): 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ố | Mặc định code | Ý nghĩa | Gợi ý tuning:
| --- | ---: | --- |
| `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. |
Giới hạn đã biế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`.
- Đ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, - Nếu CPU cao, thử `10`, `12` hoặc giảm `frustum_max_range`.
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 - `frustum_min_range` nên lớn hơn hoặc bằng khoảng mù gần của camera.
khi ra khỏi cửa sổ costmap. Đặt `max_obstacle_height` sát chiều cao robot để giảm loại thứ - `frustum_max_range` nên nhỉnh hơn `pc_marking.obstacle_range`, nhưng không
hai. vượt quá range depth ổn định trong môi trường thực tế.
- 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".
- Layer không dùng ảnh depth (`DepthCameraData`): host phải đổi ảnh sang `PointCloud2` trước khi đẩy vào.
### 5.7. InflationLayer ### 5.7. InflationLayer
@@ -565,8 +544,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. `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à 4. **Chỉ bật marking**: xác nhận vật cản xuất hiện đúng vị trí, đúng height và
range. range.
5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng 5. **Bật clearing**: laser/point cloud dùng raytrace; depth camera dùng source
`DepthCameraObstacleLayer`. `DepthCameraData` với frustum clearing.
6. **Chỉnh voxel**: đặt dải z, sau đó tăng `mark_threshold` nếu nhiễu đơn điểm. 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 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. `cost_scaling_factor` theo khoảng cách đường đi mong muốn.
@@ -579,7 +558,7 @@ Các ràng buộc nên giữ:
resolution > 0 resolution > 0
width > 0 và height > 0 nếu không lấy size từ static map width > 0 và height > 0 nếu không lấy size từ static map
raytrace_range >= obstacle_range raytrace_range >= obstacle_range
max_detect_distance > min_detect_distance >= 0 (DepthCameraObstacleLayer) frustum_max_range >= frustum_min_range >= 0
1 <= z_voxels <= 16 1 <= z_voxels <= 16
origin_z + z_resolution * z_voxels đủ bao phủ dải vật cản cần quan sát 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 InflationLayer nằm sau các layer tạo vật cản
@@ -589,27 +568,32 @@ 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 | | 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; 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 đã đ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 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 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. | | 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 đ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`. | | 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`, giảm `max_detect_distance` 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`, tăng depth `pixel_step`, giảm range 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. | | 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. |
| 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). | | 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. |
| 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. | | 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. | | 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 ý cho depth camera ## 8. Lưu ý riêng cho depth camera T800
- Layer chỉ dùng `PointCloud2` đã lọc (ví dụ `/camera/depth/points_proc`); bridge đổi ảnh - Marking và clearing có contract khác nhau: `/camera/depth/points_proc`
depth sang cloud trước khi đẩy vào nav core. (`PointCloud2`) dùng cho marking/persistence; `/camera/depth/data`
- Mỗi camera là một source trong `observation_sources` của cùng một (`DepthCameraData`) dùng cho frustum clearing.
`DepthCameraObstacleLayer`, với topic, frame, FOV và dải độ cao riêng. - Không cấu hình cùng một full point cloud để vừa marking vừa clearing nếu mục
- Ngưỡng độ cao làm việc trong frame global: sai số lắp camera (roll, pitch, chiều cao) tiêu là giảm tải. Đường frustum dùng raw depth semantics và sampling theo
quyết định ngưỡng thấp nhất dùng được trước khi sàn bị đánh dấu. pixel, tránh xử lý toàn bộ cloud thêm lần nữa.
- Khi mất marking, kiểm tra lần lượt cloud sau bridge, TF tại stamp của cloud (dòng - Mỗi camera nên có cặp source riêng, ví dụ `pc0_marking pc0_clearing
`[debug/stats]`: `tf_wait`, `tf_drop`) và ngưỡng cụm trước khi đổi ngưỡng độ cao. 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`.
## 9. Build và kiểm tra ## 9. Build và kiểm tra
@@ -626,7 +610,6 @@ 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_array_parser
./devel/lib/robot_costmap_2d/test_costmap ./devel/lib/robot_costmap_2d/test_costmap
./devel/lib/robot_costmap_2d/test_plugin ./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: Kiểm tra tối thiểu trước khi chạy robot:

View File

@@ -1,46 +0,0 @@
# Giá trị mặc định của DepthCameraObstacleLayer, bằng mặc định trong code.
# Plugin đọc file này TRƯỚC, rồi khoá cùng tên trong khối <costmap>/<plugin> của config costmap đè lên
# (Costmap2DROBOT chép khối chung <plugin>: vào đó trước khi tạo layer).
# Đây là bản đóng gói kèm gói robot_costmap_2d; robot chạy bản trong
# pnkx_nav_core/config/runtime/config/depth_camera_obstacle_layer_params.yaml.
depth_camera_obstacle_layer:
enabled: true # [bool] false = layer không đánh dấu, không xoá gì.
# [m] Độ phân giải chiều cao của điểm lưu. > 0. Tăng (vd 0.05): ít điểm, nhẹ CPU hơn nhiều;
# giảm: nhiều điểm hơn, kd-tree mỗi chu kỳ nặng hơn.
voxel_resolution: 0.01
# [m] Bán kính tìm điểm cloud quanh điểm đã lưu. > 0. Tăng: khó xoá (vết ma bám lâu hơn);
# giảm: vật mỏng/thưa dễ bị xoá nhầm.
check_radius: 0.1
# [điểm] Ít hơn số điểm cloud này trong check_radius thì điểm đã lưu bị xoá. >= 1. Tăng: xoá mạnh hơn.
number_clearing_threshold: 2
# [m] Khoảng cách gom cụm Euclidean khi đánh dấu. > 0.
ec_seg_distance: 0.2
# [điểm] Cỡ cụm nhỏ nhất khi gom cụm. >= 1.
ec_cluster_min_size: 5
# [điểm] Cụm có <= số điểm này không được đánh dấu (lọc nhiễu). >= 0. Tăng: bỏ vật nhỏ.
size_of_cluster_rejection: 5
# [m] Điểm trong FOV cách tâm robot dưới mức này luôn bị xoá. >= 0.
forced_clearing_distance: 0.1
# [bool] true: cloud dưới number_points_considered_as_blocked điểm thì bỏ qua xoá (coi camera bị che).
# false: cloud ít điểm như vậy thì xoá hết điểm trong FOV ("không thấy gì").
enable_near_blocked_protection: true
number_points_considered_as_blocked: 5 # [điểm] >= 0.
# [bool] VoxelGrid 5 cm trên cloud gộp trước khi xoá/đánh dấu (nhẹ CPU).
use_voxelized_observation: true
# [bool] Chỉ hỗ trợ true (lưu điểm theo toạ độ global). false thì nav từ chối khởi động.
use_global_frame_to_mark: true
# [s] Cloud chờ TF đúng stamp tối đa bao lâu rồi bỏ. >= 0. Không bao giờ dùng TF mới nhất.
transform_tolerance: 0.2
# [bool] true: xoá ô và điểm đã lưu nằm dưới footprint robot mỗi chu kỳ. false: chỉ dùng khi chẩn đoán.
footprint_clearing_enabled: true
# [-] Cách gộp lên costmap chung: 1 = lấy max (không hạ cost của layer khác), 0 = ghi đè trong vùng
# cập nhật. Giá trị khác: layer không tác động gì lên costmap.
combination_method: 1
# Danh sách nguồn, cách nhau bằng dấu cách. Rỗng = layer không đánh dấu gì. Khoá của từng nguồn
# (topic, FOV_W, FOV_V, min/max_detect_distance, min/max_obstacle_height...) KHÔNG đặt ở đây mà
# trong khối <plugin>/<tên nguồn>/ của config costmap.
observation_sources: ""
# track_unknown_space cố ý KHÔNG có ở đây: không đặt thì layer theo track_unknown_space của costmap.
debug:
stats: true # [bool] log đếm định kỳ (điểm cloud, điểm lưu, đánh dấu/xoá, thời gian).
stats_period: 5.0 # [s] chu kỳ in log đếm. > 0.

View File

@@ -1,13 +1,18 @@
# Giá trị mặc định của ObstacleLayer (cũng là phần ObstacleLayer bên trong VoxelLayer).
# Plugin đọc file này TRƯỚC, rồi khoá cùng tên trong khối <costmap>/<plugin> của config costmap đè lên.
# Đây là bản đóng gói kèm gói robot_costmap_2d; robot chạy bản trong
# pnkx_nav_core/config/runtime/config/obstacle_layer_params.yaml.
# Khoá theo từng nguồn (topic, sensor_frame, data_type, clearing, marking, obstacle_range,
# raytrace_range...) KHÔNG đặt ở đây: plugin chỉ đọc chúng trong khối <plugin>/<tên source>/.
obstacle_layer: obstacle_layer:
track_unknown_space: true # [bool] true = ô chưa quan sát giữ NO_INFORMATION; false = coi là free. track_unknown_space: true
transform_tolerance: 0.2 # [s] độ trễ TF tối đa khi đổi điểm sensor sang frame costmap. Nhỏ quá transform_tolerance: 0.2
# thì điểm bị bỏ khi TF trễ; lớn quá thì điểm được đặt sai chỗ khi robot quay. topic: "map"
max_obstacle_height: 2.0 # [m] điểm cao hơn mức này không được đánh dấu. sensor_frame: laser_frame
footprint_clearing_enabled: true # [bool] xoá vật cản nằm trong footprint robot (chính thân robot). observation_persistence: 0.0
combination_method: 1 # [-] 0 = ghi đè lên master costmap; 1 = lấy max với master. expected_update_rate: 0.0
data_type: PointCloud
min_obstacle_height: 0.0
max_obstacle_height: 2.0
inf_is_valid: false
clearing: false
marking: true
obstacle_range: 2.5
raytrace_range: 3.0
footprint_clearing_enabled: true
combination_method: 1

View File

@@ -1,248 +0,0 @@
/*********************************************************************
* Port of costmap_depth_camera::DepthCameraObstacleLayer (BSD, Apola),
* https://github.com/tsengapola/costmap_depth_camera, noetic branch 59b7737,
* onto robot_costmap_2d (boost::dll, robot::NodeHandle, tf3).
*
* The clearing and marking algorithm is the source's (kd-tree "seen again" test inside the
* frustums, Euclidean clusters away from the frustum faces). How the result reaches the costmap
* follows the CostmapLayer contract of ObstacleLayer/VoxelLayer instead of the source, which
* wrote LETHAL straight into the master and left its own grid empty:
* - the stored 3D points (pc_3d_map_global_) stay the source of truth, and this layer's own
* grid mirrors them cell by cell: a column with points is LETHAL, a column that loses its
* last point becomes FREE_SPACE, and every such change touches the update bounds, so a
* cleared cell leaves the master in the same cycle (the source's B7);
* - updateCosts() only merges the own grid (combination_method), like ObstacleLayer;
* - reset(), clearArea() and footprint clearing also erase the stored points, so
* Costmap2DROBOT::resetLayers() and ClearCostmapRecovery work on this layer (the source's
* reset() kept its global-mode points, B9).
* Host adaptations: data arrives through handleImpl() and a cloud is processed in
* updateBounds() once TF at its stamp exists (the role of the tf2_ros::MessageFilter);
* getType() is its own DEPTH_CAMERA_LAYER, which SensorGateway feeds PointCloud2 and
* DepthCameraData; no ROS publishers or dynamic_reconfigure; `sensor_frame_is_optical` builds the frustum in a Z-forward
* optical frame; markings that leave the rolling window are dropped (B6).
*********************************************************************/
#ifndef ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#define ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_
#include <robot/robot.h>
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_costmap_2d/footprint.h>
#include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <tf3/buffer_core.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <array>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
namespace robot_costmap_2d
{
/**
* @brief Truncated pyramid of one depth camera observation, in the global frame.
*
* Same construction as costmap_depth_camera::Observation: 8 vertices from the configured
* FOV and detect range in the sensor frame, transformed to the global frame, then 6 inward
* normals (inside test) and 6 plane equations (12 cm "attach" band test).
*/
struct DepthCameraFrustum
{
Eigen::Vector3f origin = Eigen::Vector3f::Zero(); ///< sensor origin, global frame [m]
std::array<Eigen::Vector3f, 8> vertices; ///< TLNear TRNear BLNear BRNear TLFar TRFar BLFar BRFar
std::array<Eigen::Vector3f, 6> normals; ///< near right bottom left far top
std::array<Eigen::Vector4f, 6> planes; ///< a, b, c, d of each face
double max_detect_distance = 2.5; ///< [m]
/**
* @brief Build the frustum.
* @param T_global_sensor pose of the sensor frame in the global frame
* @param fov_w, fov_v full horizontal / vertical field of view [rad]
* @param min_d, max_d near / far plane distance along the viewing axis [m]
* @param optical true: sensor frame is Z forward, X right, Y down (REP 103 optical);
* false: X forward, Y left, Z up (camera_link), as the source assumes
*/
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
double max_d, bool optical);
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
bool inside(const Eigen::Vector3f& p) const;
/// Within 0.12 m of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
bool nearFace(const Eigen::Vector3f& p) const;
};
/// FrustumUtils::isInsideFRUSTUMs: inside at least one frustum.
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
/// FrustumUtils::isAttachFRUSTUMs: near a face of one frustum and not well inside another.
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p);
class DepthCameraObstacleLayer : public CostmapLayer
{
public:
DepthCameraObstacleLayer();
~DepthCameraObstacleLayer() override;
void onInitialize() override;
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
double* max_x, double* max_y) override;
void updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j) override;
void activate() override;
void deactivate() override;
/// Drops the stored points and the buffered observations as well as the own grid.
void reset() override;
/**
* @brief Same contract as CostmapLayer::clearArea(), applied to the stored points too.
*
* Cells strictly inside (start, end) are kept and the rest is cleared when invert_area is
* false; invert_area true clears the inside instead. Called by ClearCostmapRecovery with the
* layer mutex held (recursive).
*/
void clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area = false) override;
/// Own type: SensorGateway delivers PointCloud2 and DepthCameraData to it, not LaserScan.
LayerType getType() const override
{
return LayerType::DEPTH_CAMERA_LAYER;
}
/// Resizes the own grid to the master and re-marks the stored columns right away.
void matchSize() override;
/// Number of stored (column, height) points, for tests and the stats log.
std::size_t storedPoints() const;
protected:
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
private:
/// One observation: cloud after TF and the height gate, plus its frustum (both global frame).
struct Observation
{
robot::Time stamp;
std::vector<Eigen::Vector3f> points;
DepthCameraFrustum frustum;
};
/// ObservationBuffer of the source, one per entry of observation_sources.
struct Source
{
std::string name;
std::string topic;
std::string sensor_frame;
bool sensor_frame_is_optical = false;
double observation_keep_time = 0.0; ///< [s] 0 keeps only the newest observation
double expected_update_rate = 0.0; ///< [s] 0 disables the staleness check
double min_obstacle_height = 0.0; ///< [m] global-frame z gate
double max_obstacle_height = 2.0; ///< [m]
double fov_w = 1.5; ///< [rad]
double fov_v = 1.0; ///< [rad]
double min_detect_distance = 0.15; ///< [m]
double max_detect_distance = 2.5; ///< [m]
bool marking = true;
std::list<Observation> observations; ///< newest first
robot::Time last_updated;
std::mutex pending_mutex; ///< guards pending: handleImpl runs on the producer thread
std::shared_ptr<const robot_sensor_msgs::PointCloud2> pending;
};
void loadParameters();
bool processPending(Source& source);
bool bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud);
void purgeStale(Source& source) const;
bool sourceIsCurrent(const Source& source) const;
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums, double robot_x,
double robot_y, double* min_x, double* min_y, double* max_x,
double* max_y);
void processCluster(const std::vector<DepthCameraFrustum>& frustums,
const std::vector<Eigen::Vector3f>& cluster, double* min_x, double* min_y,
double* max_x, double* max_y);
void updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y);
bool isValid(int mx, int my) const;
/// Own-grid cell of a stored column; false when it is outside the window or on its edge.
bool columnCell(const std::pair<int, int>& column, unsigned int& mx, unsigned int& my) const;
/// Drops columns that left the window (B6), frees edge cells, re-marks cells a column lost.
void dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x, double* max_y);
/// The column became empty: erase it, free its own-grid cell and touch the bounds.
std::map<std::pair<int, int>, std::map<int, float>>::iterator eraseColumn(
std::map<std::pair<int, int>, std::map<int, float>>::iterator it, double* min_x, double* min_y,
double* max_x, double* max_y);
void logStats();
// (int)(x / res) toward zero and back to the cell corner, exactly as the source stores points.
void worldToIntIndex(double wx, double wy, int& mx, int& my, double resolution) const
{
mx = static_cast<int>(wx / resolution);
my = static_cast<int>(wy / resolution);
}
void intIndexToWorld(double& wx, double& wy, int mx, int my, double resolution) const
{
wx = mx * resolution;
wy = my * resolution;
}
std::string global_frame_;
bool rolling_window_ = false;
std::vector<std::unique_ptr<Source>> sources_;
// Parameters, names and defaults as in the source.
bool footprint_clearing_enabled_ = true;
int combination_method_ = 1; ///< 0 overwrite, 1 maximum, other: nothing
bool enable_near_blocked_protection_ = true;
int number_points_considered_as_blocked_ = 5;
double forced_clearing_distance_ = 0.1; ///< [m] from robot_base_frame
double ec_seg_distance_ = 0.2; ///< [m] Euclidean cluster tolerance
int ec_cluster_min_size_ = 5;
int size_of_cluster_rejection_ = 5; ///< clusters with <= this many points are not marked
double voxel_resolution_ = 0.01; ///< [m] height quantization of stored points
double check_radius_ = 0.1; ///< [m] kd-tree radius of the "seen again" test
int number_clearing_threshold_ = 2; ///< fewer neighbours than this clears the point
bool use_voxelized_observation_ = true; ///< VoxelGrid 5 cm on the combined cloud
double transform_tolerance_ = 0.2; ///< [s] how long a cloud may wait for its TF
double marking_height_under_ground_ = 100.0;
double marking_height_above_ground_ = -100.0;
// Additions of this port.
bool debug_stats_ = true; ///< debug/stats: periodic counters log
double debug_stats_period_ = 5.0; ///< [s]
/// (ix, iy) of the cell corner -> {height index -> label}, global frame (use_global_frame_to_mark).
std::map<std::pair<int, int>, std::map<int, float>> pc_3d_map_global_;
std::vector<robot_geometry_msgs::Point> transformed_footprint_;
struct Stats
{
std::size_t cycles = 0;
std::size_t cloud_points = 0;
std::size_t marked = 0;
std::size_t cleared = 0;
std::size_t footprint_cleared = 0; ///< columns erased under the robot footprint
std::size_t cleared_all_frames = 0;
std::size_t bypassed_frames = 0;
std::size_t tf_waits = 0;
std::size_t tf_drops = 0;
std::size_t dropped_out_of_window = 0;
double bounds_ms_sum = 0.0;
double bounds_ms_max = 0.0;
} stats_;
robot::Time last_stats_log_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DEPTH_CAMERA_OBSTACLE_LAYER_H_

View File

@@ -56,10 +56,7 @@ enum class LayerType
DIRECTIONAL_LAYER, DIRECTIONAL_LAYER,
PREFERRED_LAYER, PREFERRED_LAYER,
UNPREFERRED_LAYER, UNPREFERRED_LAYER,
VOXEL_LAYER, VOXEL_LAYER
/// DepthCameraObstacleLayer. Appended last so the values above keep their numbers; the host's
/// SensorGateway feeds it PointCloud2.
DEPTH_CAMERA_LAYER
}; };
class LayeredCostmap; class LayeredCostmap;

View File

@@ -34,6 +34,7 @@
#include <robot_geometry_msgs/Point.h> #include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h> #include <robot_sensor_msgs/PointCloud2.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <boost/make_shared.hpp> #include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp> #include <boost/shared_ptr.hpp>
#include <utility> #include <utility>
@@ -41,6 +42,142 @@
namespace robot_costmap_2d 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;
};
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 * @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 * @note Tried to make members and constructor arguments const but the compiler would not accept the default

View File

@@ -76,6 +76,12 @@ public:
double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame, double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance); 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 * @brief Destructor... cleans up
@@ -98,12 +104,24 @@ public:
*/ */
void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud); void bufferCloud(const robot_sensor_msgs::PointCloud2& cloud);
/**
* @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 * @brief Pushes copies of all current observations onto the end of the vector passed in
* @param observations The vector to be filled * @param observations The vector to be filled
*/ */
void getObservations(std::vector<Observation>& observations); 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 * @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 * @return True if it is being updated at the expected rate, false otherwise
@@ -137,6 +155,8 @@ private:
*/ */
void purgeStaleObservations(); void purgeStaleObservations();
void purgeStaleDepthObservations();
tf3::BufferCore& tf3_buffer_; tf3::BufferCore& tf3_buffer_;
const robot::Duration observation_keep_time_; const robot::Duration observation_keep_time_;
const robot::Duration expected_update_rate_; const robot::Duration expected_update_rate_;
@@ -144,11 +164,14 @@ private:
std::string global_frame_; std::string global_frame_;
std::string sensor_frame_; std::string sensor_frame_;
std::list<Observation> observation_list_; std::list<Observation> observation_list_;
std::list<DepthCameraObservation> depth_observation_list_;
// DepthCameraObservation depth_observation_;
std::string topic_name_; std::string topic_name_;
double min_obstacle_height_, max_obstacle_height_; double min_obstacle_height_, max_obstacle_height_;
boost::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely boost::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely
double obstacle_range_, raytrace_range_; double obstacle_range_, raytrace_range_;
double tf_tolerance_; double tf_tolerance_;
DepthFrustumConfig frustum_config_;
}; };
} // namespace robot_costmap_2d } // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_ #endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_

View File

@@ -48,6 +48,7 @@
#include <mutex> #include <mutex>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <robot_sensor_msgs/LaserScan.h> #include <robot_sensor_msgs/LaserScan.h>
#include <robot_laser_geometry/laser_geometry.hpp> #include <robot_laser_geometry/laser_geometry.hpp>
#include <robot_sensor_msgs/PointCloud.h> #include <robot_sensor_msgs/PointCloud.h>
@@ -130,6 +131,12 @@ protected:
void pointCloud2Callback(const robot_sensor_msgs::PointCloud2& message, void pointCloud2Callback(const robot_sensor_msgs::PointCloud2& message,
const boost::shared_ptr<robot_costmap_2d::ObservationBuffer>& buffer); 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 * @brief Get the observations used to mark space
* @param marking_observations A reference to a vector that will be populated with the observations * @param marking_observations A reference to a vector that will be populated with the observations
@@ -144,6 +151,13 @@ protected:
*/ */
bool getClearingObservations(std::vector<robot_costmap_2d::Observation>& clearing_observations) const; 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 * @brief Clear freespace based on one observation
* @param clearing_observation The observation used to raytrace * @param clearing_observation The observation used to raytrace
@@ -172,6 +186,9 @@ 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> > 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> > 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 // Used only for testing purposes
std::vector<robot_costmap_2d::Observation> static_clearing_observations_, static_marking_observations_; std::vector<robot_costmap_2d::Observation> static_clearing_observations_, static_marking_observations_;
@@ -180,6 +197,10 @@ protected:
int combination_method_; int combination_method_;
std::vector<CallBackInfo> callback_infos_; 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_;
private: private:
bool getParams(const std::string& config_file_name, robot::NodeHandle &nh); bool getParams(const std::string& config_file_name, robot::NodeHandle &nh);

View File

@@ -94,15 +94,65 @@ private:
void clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info); 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, virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_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;
bool publish_voxel_; bool publish_voxel_;
robot_voxel_grid::VoxelGrid robot_voxel_grid_; robot_voxel_grid::VoxelGrid robot_voxel_grid_;
double z_resolution_, origin_z_; 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_; unsigned int unknown_threshold_, mark_threshold_, size_z_;
robot_sensor_msgs::PointCloud clearing_endpoints_; robot_sensor_msgs::PointCloud clearing_endpoints_;
std::vector<unsigned char> rolling_costmap_scratch_; std::vector<unsigned char> rolling_costmap_scratch_;
std::vector<unsigned int> rolling_voxel_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) 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_) if (wx < origin_x_ || wy < origin_y_ || wz < origin_z_)

View File

@@ -20,8 +20,6 @@
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend> <buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>libconsole-bridge-dev</build_depend> <build_depend>libconsole-bridge-dev</build_depend>
<build_depend>libpcl-all-dev</build_depend>
<run_depend>libpcl-all</run_depend>
<run_depend>libconsole-bridge-dev</run_depend> <run_depend>libconsole-bridge-dev</run_depend>
<build_depend>robot_std_msgs</build_depend> <build_depend>robot_std_msgs</build_depend>

View File

@@ -1,974 +0,0 @@
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Apola (costmap_depth_camera); port to robot_costmap_2d.
*********************************************************************/
#include <robot_costmap_2d/depth_camera_obstacle_layer.h>
#include <robot_costmap_2d/cost_values.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <tf3/exceptions.h>
#include <data_convert/data_convert.h>
#include <boost/dll/alias.hpp>
#include <boost/make_shared.hpp>
#include <boost/thread/locks.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/search/kdtree.h>
#include <pcl/segmentation/extract_clusters.h>
#include <robot_costmap_2d/utils.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <unordered_set>
namespace robot_costmap_2d
{
namespace
{
// Distance of the "attach" band around each frustum face, hard-coded in the source [m].
constexpr float kAttachDistance = 0.12f;
// Stored columns farther than this from the robot are not tested for clearing [m].
constexpr double kClearingSkipDistance = 10.0;
// VoxelGrid leaf of the combined observation, hard-coded in the source [m].
constexpr float kObservationLeaf = 0.05f;
Eigen::Isometry3d toIsometry(const tf3::TransformStampedMsg& t)
{
const auto& q = t.transform.rotation;
const auto& p = t.transform.translation;
Eigen::Isometry3d iso = Eigen::Isometry3d::Identity();
iso.linear() = Eigen::Quaterniond(q.w, q.x, q.y, q.z).normalized().toRotationMatrix();
iso.translation() << p.x, p.y, p.z;
return iso;
}
// Steps 1 and 3 of the costmap layer config flow for one key: the value in the layer's default
// file, overridden by "<costmap>/<plugin>/<key>", which Costmap2DROBOT::copyParentParameters() has
// filled from the shared "<plugin>:" block. A value that does not convert to T is a configuration
// error: getParam() would otherwise replace it with 0, false or "" without a word.
template <typename T>
T readParam(const YAML::Node& file_node, const std::string& file_key, const robot::NodeHandle& nh,
const std::string& key, const T& fallback)
{
T value = loadParam(file_node, file_key, fallback);
if (nh.hasParam(key) && !nh.getParam(key, value, value))
throw std::invalid_argument("DepthCameraObstacleLayer: '" + nh.getNamespace() + "/" + key +
"' does not convert to the type the layer reads");
return value;
}
template <typename T>
T readParam(const YAML::Node& file_node, const robot::NodeHandle& nh, const std::string& key, const T& fallback)
{
return readParam(file_node, key, nh, key, fallback);
}
void requireRange(bool ok, const std::string& what)
{
if (!ok)
throw std::invalid_argument("DepthCameraObstacleLayer: " + what);
}
} // namespace
// ---------------------------------------------------------------------------------------------
// Frustum (costmap_depth_camera::Observation::findFrustum* and FrustumUtils)
// ---------------------------------------------------------------------------------------------
void DepthCameraFrustum::build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v,
double min_d, double max_d, bool optical)
{
max_detect_distance = max_d;
const double tw = std::tan(fov_w / 2.0);
const double tv = std::tan(fov_v / 2.0);
// findFrustumVertex(): X forward, +Y left, +Z up. TL = +Y +Z, BR = -Y -Z.
const std::array<Eigen::Vector3d, 8> local = {
Eigen::Vector3d(min_d, min_d * tw, min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, min_d * tv),
Eigen::Vector3d(min_d, min_d * tw, -min_d * tv), Eigen::Vector3d(min_d, -min_d * tw, -min_d * tv),
Eigen::Vector3d(max_d, max_d * tw, max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, max_d * tv),
Eigen::Vector3d(max_d, max_d * tw, -max_d * tv), Eigen::Vector3d(max_d, -max_d * tw, -max_d * tv)};
for (std::size_t i = 0; i < local.size(); ++i)
{
Eigen::Vector3d v = local[i];
// Same pyramid expressed in an optical frame: forward = +Z, left = -X, up = -Y.
if (optical)
v = Eigen::Vector3d(-local[i].y(), -local[i].z(), local[i].x());
vertices[i] = (T_global_sensor * v).cast<float>();
}
origin = T_global_sensor.translation().cast<float>();
const Eigen::Vector3f& TLNear = vertices[0];
const Eigen::Vector3f& TRNear = vertices[1];
const Eigen::Vector3f& BLNear = vertices[2];
const Eigen::Vector3f& BRNear = vertices[3];
const Eigen::Vector3f& TLFar = vertices[4];
const Eigen::Vector3f& TRFar = vertices[5];
const Eigen::Vector3f& BLFar = vertices[6];
const Eigen::Vector3f& BRFar = vertices[7];
// findFrustumNormal(): getVec(a, b) = b - a, inward normals in this order.
normals[0] = (TRNear - TLNear).cross(BRNear - TRNear); // near
normals[1] = (TRFar - TRNear).cross(BRFar - TRFar); // right
normals[2] = (BRFar - BRNear).cross(BLFar - BRFar); // bottom
normals[3] = (BLFar - BLNear).cross(TLFar - BLFar); // left
normals[4] = (TRFar - BRFar).cross(TLFar - TRFar); // far
normals[5] = (TRFar - TLFar).cross(TRNear - TRFar); // top
// findFrustumPlane(): getPlaneN(p1, p2, p3) = cross(p2 - p1, p3 - p1), d = -n . p1.
const auto plane = [](const Eigen::Vector3f& p1, const Eigen::Vector3f& p2, const Eigen::Vector3f& p3) {
const Eigen::Vector3f n = (p2 - p1).cross(p3 - p1);
return Eigen::Vector4f(n.x(), n.y(), n.z(), -n.dot(p1));
};
planes[0] = plane(TLNear, TLFar, BLNear);
planes[1] = plane(BLNear, BRNear, BLFar);
planes[2] = plane(TRNear, BRNear, BRFar);
planes[3] = plane(TLNear, TRNear, TLFar);
planes[4] = plane(TLNear, BLNear, BRNear);
planes[5] = plane(TLFar, TRFar, BRFar);
}
bool DepthCameraFrustum::inside(const Eigen::Vector3f& p) const
{
// Faces 0..2 pass through BRNear, faces 3..5 through TLFar.
for (int i = 0; i < 6; ++i)
{
const Eigen::Vector3f& corner = i < 3 ? vertices[3] : vertices[4];
if ((p - corner).dot(normals[i]) < 0.f)
return false;
}
return true;
}
bool DepthCameraFrustum::nearFace(const Eigen::Vector3f& p) const
{
for (const Eigen::Vector4f& pl : planes)
{
const float dis = std::fabs(pl[0] * p.x() + pl[1] * p.y() + pl[2] * p.z() + pl[3]) /
std::sqrt(pl[0] * pl[0] + pl[1] * pl[1] + pl[2] * pl[2]);
if (dis <= kAttachDistance &&
std::hypot(p.x() - origin.x(), p.y() - origin.y()) < max_detect_distance + 0.5)
return true;
}
return false;
}
bool insideAnyFrustum(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
{
for (const DepthCameraFrustum& f : frustums)
if (f.inside(p))
return true;
return false;
}
bool attachedToFrustums(const std::vector<DepthCameraFrustum>& frustums, const Eigen::Vector3f& p)
{
for (std::size_t i = 0; i < frustums.size(); ++i)
{
if (!frustums[i].nearFace(p))
continue;
// Attached to this one; not attached overall if it lies well inside another camera's frustum.
for (std::size_t j = 0; j < frustums.size(); ++j)
if (j != i && !frustums[j].nearFace(p) && frustums[j].inside(p))
return false;
return true;
}
return false;
}
// ---------------------------------------------------------------------------------------------
// Layer
// ---------------------------------------------------------------------------------------------
DepthCameraObstacleLayer::DepthCameraObstacleLayer()
{
costmap_ = NULL; // the unsigned char* of the parent Costmap2D
}
DepthCameraObstacleLayer::~DepthCameraObstacleLayer() = default;
void DepthCameraObstacleLayer::onInitialize()
{
rolling_window_ = layered_costmap_->isRolling();
global_frame_ = layered_costmap_->getGlobalFrameID();
loadParameters();
matchSize();
current_ = true;
last_stats_log_ = robot::Time::now();
}
void DepthCameraObstacleLayer::loadParameters()
{
// Step 1 of the config flow: the default file, like the other layers. A missing file or block
// stops the costmap from being built instead of running on C++ defaults.
const std::string config_file_name = "depth_camera_obstacle_layer_params.yaml";
const char* env_config = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
const std::string folder = (env_config && std::filesystem::exists(env_config)) ? env_config : "";
YAML::Node config;
try
{
config = YAML::LoadFile(getSourceFile(folder, config_file_name));
}
catch (const YAML::BadFile&)
{
throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": cannot open the default file " +
config_file_name);
}
YAML::Node layer = config["depth_camera_obstacle_layer"];
if (!layer.IsMap())
throw std::runtime_error("DepthCameraObstacleLayer " + name_ + ": " + config_file_name +
" has no depth_camera_obstacle_layer: block");
// Step 3: "<costmap>/<plugin>", filled by copyParentParameters() from the shared block.
robot::NodeHandle nh("~");
const robot::NodeHandle priv_nh(nh, name_);
// Not in the default file on purpose: unset, the layer follows the costmap's track_unknown_space.
const bool track_unknown_space =
readParam(layer, priv_nh, "track_unknown_space", layered_costmap_->isTrackingUnknown());
default_value_ = track_unknown_space ? NO_INFORMATION : FREE_SPACE;
enabled_ = readParam(layer, priv_nh, "enabled", true);
footprint_clearing_enabled_ = readParam(layer, priv_nh, "footprint_clearing_enabled", true);
combination_method_ = readParam(layer, priv_nh, "combination_method", 1);
enable_near_blocked_protection_ = readParam(layer, priv_nh, "enable_near_blocked_protection", true);
number_points_considered_as_blocked_ = readParam(layer, priv_nh, "number_points_considered_as_blocked", 5);
forced_clearing_distance_ = readParam(layer, priv_nh, "forced_clearing_distance", 0.1);
ec_seg_distance_ = readParam(layer, priv_nh, "ec_seg_distance", 0.2);
ec_cluster_min_size_ = readParam(layer, priv_nh, "ec_cluster_min_size", 5);
size_of_cluster_rejection_ = readParam(layer, priv_nh, "size_of_cluster_rejection", 5);
voxel_resolution_ = readParam(layer, priv_nh, "voxel_resolution", 0.01);
check_radius_ = readParam(layer, priv_nh, "check_radius", 0.1);
number_clearing_threshold_ = readParam(layer, priv_nh, "number_clearing_threshold", 2);
use_voxelized_observation_ = readParam(layer, priv_nh, "use_voxelized_observation", true);
transform_tolerance_ = readParam(layer, priv_nh, "transform_tolerance", 0.2);
const bool use_global_frame_to_mark = readParam(layer, priv_nh, "use_global_frame_to_mark", true);
if (layer["clear_touches_bounds"] || priv_nh.hasParam("clear_touches_bounds"))
robot::log_warning("DepthCameraObstacleLayer %s: clear_touches_bounds is obsolete and ignored: a cleared "
"cell now always resets its master cell\n", name_.c_str());
YAML::Node debug = layer["debug"];
debug_stats_ = readParam(debug, "stats", priv_nh, "debug/stats", true);
debug_stats_period_ = readParam(debug, "stats_period", priv_nh, "debug/stats_period", 5.0);
// The source's local mode keys points by costmap index, so markings move with a rolling
// window (its README shows it). Only the global mode is ported.
requireRange(use_global_frame_to_mark, "use_global_frame_to_mark: false is not ported");
requireRange(voxel_resolution_ > 0.0 && std::isfinite(voxel_resolution_), "voxel_resolution must be > 0");
requireRange(check_radius_ > 0.0 && std::isfinite(check_radius_), "check_radius must be > 0");
requireRange(ec_seg_distance_ > 0.0 && std::isfinite(ec_seg_distance_), "ec_seg_distance must be > 0");
requireRange(ec_cluster_min_size_ >= 1, "ec_cluster_min_size must be >= 1");
requireRange(size_of_cluster_rejection_ >= 0, "size_of_cluster_rejection must be >= 0");
requireRange(number_clearing_threshold_ >= 1, "number_clearing_threshold must be >= 1");
requireRange(number_points_considered_as_blocked_ >= 0, "number_points_considered_as_blocked must be >= 0");
requireRange(forced_clearing_distance_ >= 0.0, "forced_clearing_distance must be >= 0");
requireRange(transform_tolerance_ >= 0.0 && std::isfinite(transform_tolerance_), "transform_tolerance must be >= 0");
requireRange(debug_stats_period_ > 0.0, "debug/stats_period must be > 0");
marking_height_under_ground_ = 100.0;
marking_height_above_ground_ = -100.0;
std::stringstream ss(readParam(layer, priv_nh, "observation_sources", std::string("")));
std::string name;
while (ss >> name)
{
// Like obstacle_layer_params.yaml, the default file has no block per source, so a source key
// comes from "<costmap>/<plugin>/<source>/" or falls back to the C++ default below.
YAML::Node source_defaults = layer[name];
const robot::NodeHandle s(priv_nh, name);
std::unique_ptr<Source> src(new Source());
src->name = name;
src->topic = readParam(source_defaults, s, "topic", name);
src->sensor_frame = readParam(source_defaults, s, "sensor_frame", std::string(""));
src->sensor_frame_is_optical = readParam(source_defaults, s, "sensor_frame_is_optical", false);
src->observation_keep_time = readParam(source_defaults, s, "observation_persistence", 0.0);
src->expected_update_rate = readParam(source_defaults, s, "expected_update_rate", 0.0);
src->min_obstacle_height = readParam(source_defaults, s, "min_obstacle_height", 0.0);
src->max_obstacle_height = readParam(source_defaults, s, "max_obstacle_height", 2.0);
src->marking = readParam(source_defaults, s, "marking", true);
src->fov_v = readParam(source_defaults, s, "FOV_V", 1.0);
src->fov_w = readParam(source_defaults, s, "FOV_W", 1.5);
src->min_detect_distance = readParam(source_defaults, s, "min_detect_distance", 0.15);
src->max_detect_distance = readParam(source_defaults, s, "max_detect_distance", 2.5);
if (readParam(source_defaults, s, "inf_is_valid", false))
robot::log_warning("DepthCameraObstacleLayer: inf_is_valid is not applicable to PointCloud observations\n");
const std::string what = "source " + name + ": ";
requireRange(src->fov_w > 0.0 && src->fov_w < M_PI, what + "FOV_W must be in (0, pi) [rad]");
requireRange(src->fov_v > 0.0 && src->fov_v < M_PI, what + "FOV_V must be in (0, pi) [rad]");
requireRange(src->min_detect_distance >= 0.0 && src->max_detect_distance > src->min_detect_distance,
what + "need 0 <= min_detect_distance < max_detect_distance [m]");
requireRange(src->min_obstacle_height <= src->max_obstacle_height,
what + "min_obstacle_height must be <= max_obstacle_height [m]");
requireRange(src->observation_keep_time >= 0.0 && src->expected_update_rate >= 0.0,
what + "observation_persistence and expected_update_rate must be >= 0 [s]");
// Update minimum height and maximum height for overall marking.
marking_height_above_ground_ = std::max(marking_height_above_ground_, src->max_obstacle_height);
marking_height_under_ground_ = std::min(marking_height_under_ground_, src->min_obstacle_height);
src->last_updated = robot::Time::now();
robot::log_info("DepthCameraObstacleLayer %s: source %s topic=%s sensor_frame=%s optical=%s "
"FOV_W=%.3f FOV_V=%.3f rad detect=[%.2f, %.2f] m height=[%.2f, %.2f] m "
"persistence=%.2f s expected_update_rate=%.2f s marking=%s\n",
name_.c_str(), name.c_str(), src->topic.c_str(),
src->sensor_frame.empty() ? "(cloud frame)" : src->sensor_frame.c_str(),
src->sensor_frame_is_optical ? "true" : "false", src->fov_w, src->fov_v,
src->min_detect_distance, src->max_detect_distance, src->min_obstacle_height,
src->max_obstacle_height, src->observation_keep_time, src->expected_update_rate,
src->marking ? "true" : "false");
sources_.push_back(std::move(src));
}
if (sources_.empty())
robot::log_warning("DepthCameraObstacleLayer %s: observation_sources is empty, the layer marks nothing\n",
name_.c_str());
robot::log_info("DepthCameraObstacleLayer %s: global_frame=%s rolling=%s track_unknown=%s "
"voxel_resolution=%.3f m check_radius=%.3f m number_clearing_threshold=%d "
"ec_seg_distance=%.2f m ec_cluster_min_size=%d size_of_cluster_rejection=%d "
"forced_clearing_distance=%.2f m near_blocked_protection=%s (%d pts) "
"voxelized_observation=%s transform_tolerance=%.2f s combination_method=%d "
"footprint_clearing=%s marking_height=[%.2f, %.2f] m debug/stats=%s\n",
name_.c_str(), global_frame_.c_str(), rolling_window_ ? "true" : "false",
track_unknown_space ? "true" : "false", voxel_resolution_, check_radius_,
number_clearing_threshold_, ec_seg_distance_, ec_cluster_min_size_,
size_of_cluster_rejection_, forced_clearing_distance_,
enable_near_blocked_protection_ ? "true" : "false", number_points_considered_as_blocked_,
use_voxelized_observation_ ? "true" : "false", transform_tolerance_, combination_method_,
footprint_clearing_enabled_ ? "true" : "false",
marking_height_under_ground_, marking_height_above_ground_, debug_stats_ ? "on" : "off");
}
void DepthCameraObstacleLayer::handleImpl(const void* data, const std::type_info& type,
const std::string& topic)
{
// DepthCameraData, LaserScan, ... are meant for other layers of the same type.
if (type != typeid(robot_sensor_msgs::PointCloud2))
return;
const auto& cloud = *static_cast<const robot_sensor_msgs::PointCloud2*>(data);
std::shared_ptr<const robot_sensor_msgs::PointCloud2> copy;
for (const auto& source : sources_)
{
if (source->topic != topic)
continue;
if (!copy)
copy = std::make_shared<const robot_sensor_msgs::PointCloud2>(cloud);
// Newest only: the source buffer keeps one observation, and a cloud still waiting for its
// TF is superseded by a newer one, like a full tf2_ros::MessageFilter queue.
std::lock_guard<std::mutex> lock(source->pending_mutex);
source->pending = copy;
}
}
bool DepthCameraObstacleLayer::processPending(Source& source)
{
std::shared_ptr<const robot_sensor_msgs::PointCloud2> cloud;
{
std::lock_guard<std::mutex> lock(source.pending_mutex);
cloud = source.pending;
}
if (!cloud)
return false;
bool done = true;
try
{
bufferCloud(source, *cloud);
}
catch (const tf3::TransformException& ex)
{
// Measurement TF only, never the latest TF. Wait while the cloud is younger than the
// tolerance, then drop it.
const double age = (robot::Time::now() - cloud->header.stamp).toSec();
if (age <= transform_tolerance_)
{
++stats_.tf_waits;
done = false;
}
else
{
++stats_.tf_drops;
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: no TF %s <- %s at the cloud stamp "
"(%.3f s old), cloud dropped: %s\n", name_.c_str(), global_frame_.c_str(),
cloud->header.frame_id.c_str(), age, ex.what());
}
}
catch (const std::exception& ex)
{
robot::log_error_throttle(5.0, "DepthCameraObstacleLayer %s: malformed cloud on %s dropped: %s\n",
name_.c_str(), source.topic.c_str(), ex.what());
}
if (done)
{
std::lock_guard<std::mutex> lock(source.pending_mutex);
if (source.pending == cloud)
source.pending.reset();
}
return done;
}
bool DepthCameraObstacleLayer::bufferCloud(Source& source, const robot_sensor_msgs::PointCloud2& cloud)
{
if (cloud.header.frame_id.empty())
throw std::invalid_argument("cloud has no frame_id");
const std::string origin_frame = source.sensor_frame.empty() ? cloud.header.frame_id : source.sensor_frame;
const tf3::Time stamp = data_convert::convertTime(cloud.header.stamp);
const Eigen::Isometry3d T_cloud = toIsometry(tf_->lookupTransform(global_frame_, cloud.header.frame_id, stamp));
const Eigen::Isometry3d T_origin = origin_frame == cloud.header.frame_id
? T_cloud : toIsometry(tf_->lookupTransform(global_frame_, origin_frame, stamp));
Observation obs;
obs.stamp = cloud.header.stamp;
// Frustum vertices are given in the sensor frame, then everything is in the global frame.
obs.frustum.build(T_origin, source.fov_w, source.fov_v, source.min_detect_distance,
source.max_detect_distance, source.sensor_frame_is_optical);
const std::size_t size = static_cast<std::size_t>(cloud.width) * cloud.height;
obs.points.reserve(size);
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_x(cloud, "x");
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_y(cloud, "y");
robot_sensor_msgs::PointCloud2ConstIterator<float> iter_z(cloud, "z");
for (std::size_t i = 0; i < size; ++i, ++iter_x, ++iter_y, ++iter_z)
{
// The source relies on dense clouds; NaN would only disappear later in PCL. Drop it here.
if (!std::isfinite(*iter_x) || !std::isfinite(*iter_y) || !std::isfinite(*iter_z))
continue;
const Eigen::Vector3d g = T_cloud * Eigen::Vector3d(*iter_x, *iter_y, *iter_z);
if (g.z() <= source.max_obstacle_height && g.z() >= source.min_obstacle_height)
obs.points.push_back(g.cast<float>());
}
source.observations.push_front(std::move(obs));
source.last_updated = robot::Time::now();
purgeStale(source);
return true;
}
void DepthCameraObstacleLayer::purgeStale(Source& source) const
{
if (source.observations.empty())
return;
// Keeping observations for no time keeps exactly one.
if (source.observation_keep_time == 0.0)
{
source.observations.erase(std::next(source.observations.begin()), source.observations.end());
return;
}
for (auto it = source.observations.begin(); it != source.observations.end(); ++it)
{
if ((source.last_updated - it->stamp).toSec() > source.observation_keep_time)
{
source.observations.erase(it, source.observations.end());
return;
}
}
}
bool DepthCameraObstacleLayer::sourceIsCurrent(const Source& source) const
{
if (source.expected_update_rate == 0.0)
return true;
const double since = (robot::Time::now() - source.last_updated).toSec();
const bool current = since <= source.expected_update_rate;
if (!current)
robot::log_warning_throttle(5.0, "DepthCameraObstacleLayer %s: source %s not updated for %.2f s, expected "
"every %.2f s\n", name_.c_str(), source.name.c_str(), since,
source.expected_update_rate);
return current;
}
void DepthCameraObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
// ClearCostmapRecovery and resetLayers() reach the stored points from other threads.
boost::unique_lock<mutex_t> lock(*getMutex());
if (rolling_window_)
updateOrigin(robot_x - getSizeInMetersX() / 2, robot_y - getSizeInMetersY() / 2);
if (!enabled_)
return;
const auto start = std::chrono::steady_clock::now();
useExtraBounds(min_x, min_y, max_x, max_y);
dropColumnsOutsideWindow(min_x, min_y, max_x, max_y);
bool current = true;
std::vector<DepthCameraFrustum> frustums;
std::vector<Eigen::Vector3f> combined;
for (const auto& source : sources_)
{
if (!source->marking)
continue; // the source marks and clears with marking observations only
processPending(*source);
purgeStale(*source);
for (const Observation& obs : source->observations)
{
frustums.push_back(obs.frustum);
combined.insert(combined.end(), obs.points.begin(), obs.points.end());
}
current = sourceIsCurrent(*source) && current;
}
current_ = current;
pcl::PointCloud<pcl::PointXYZI>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZI>);
cloud->points.reserve(combined.size());
for (const Eigen::Vector3f& q : combined)
{
pcl::PointXYZI pt;
pt.x = q.x();
pt.y = q.y();
pt.z = q.z();
pt.intensity = 0.f;
cloud->points.push_back(pt);
}
cloud->width = static_cast<std::uint32_t>(cloud->points.size());
cloud->height = 1;
cloud->is_dense = true;
// Voxelized combined observation to save computation.
if (use_voxelized_observation_ && !cloud->points.empty())
{
pcl::VoxelGrid<pcl::PointXYZI> voxel;
voxel.setLeafSize(kObservationLeaf, kObservationLeaf, kObservationLeaf);
voxel.setInputCloud(cloud);
pcl::PointCloud<pcl::PointXYZI>::Ptr filtered(new pcl::PointCloud<pcl::PointXYZI>);
voxel.filter(*filtered);
cloud = filtered;
}
std::vector<Eigen::Vector3f> points;
points.reserve(cloud->points.size());
for (const auto& pt : cloud->points)
points.emplace_back(pt.x, pt.y, pt.z);
stats_.cloud_points += points.size();
clearMarkingByKdtree(points, frustums, robot_x, robot_y, min_x, min_y, max_x, max_y);
if (cloud->points.size() > 5)
{
pcl::search::KdTree<pcl::PointXYZI>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZI>);
tree->setInputCloud(cloud);
std::vector<pcl::PointIndices> clusters;
pcl::EuclideanClusterExtraction<pcl::PointXYZI> ec;
ec.setClusterTolerance(ec_seg_distance_);
ec.setMinClusterSize(ec_cluster_min_size_);
ec.setMaxClusterSize(static_cast<int>(cloud->points.size()));
ec.setSearchMethod(tree);
ec.setInputCloud(cloud);
ec.extract(clusters);
std::vector<Eigen::Vector3f> cluster;
for (const pcl::PointIndices& indices : clusters)
{
// PCL can still output clusters below ec_cluster_min_size; the source rejects them here.
if (static_cast<int>(indices.indices.size()) <= size_of_cluster_rejection_)
continue;
cluster.clear();
for (int idx : indices.indices)
cluster.push_back(points[idx]);
processCluster(frustums, cluster, min_x, min_y, max_x, max_y);
}
}
updateFootprint(robot_x, robot_y, robot_yaw, min_x, min_y, max_x, max_y);
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
++stats_.cycles;
stats_.bounds_ms_sum += ms;
stats_.bounds_ms_max = std::max(stats_.bounds_ms_max, ms);
logStats();
}
void DepthCameraObstacleLayer::clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums,
double robot_x, double robot_y, double* min_x,
double* min_y, double* max_x, double* max_y)
{
bool bypass_clearing = false;
if (enable_near_blocked_protection_ &&
static_cast<int>(cloud.size()) < number_points_considered_as_blocked_)
{
robot::log_warning_throttle(30.0, "DepthCameraObstacleLayer %s: blocked by something, clearing is skipped\n",
name_.c_str());
bypass_clearing = true;
}
bool clear_all_marking_in_this_frame = false;
pcl::KdTreeFLANN<pcl::PointXYZI> kdtree;
if (cloud.size() > 5)
{
pcl::PointCloud<pcl::PointXYZI>::Ptr input(new pcl::PointCloud<pcl::PointXYZI>);
input->points.reserve(cloud.size());
for (const Eigen::Vector3f& q : cloud)
{
pcl::PointXYZI pt;
pt.x = q.x();
pt.y = q.y();
pt.z = q.z();
pt.intensity = 0.f;
input->points.push_back(pt);
}
input->width = static_cast<std::uint32_t>(input->points.size());
input->height = 1;
kdtree.setInputCloud(input);
}
else if (!enable_near_blocked_protection_)
clear_all_marking_in_this_frame = true; // we really see nothing in the space
else
bypass_clearing = true;
if (clear_all_marking_in_this_frame)
++stats_.cleared_all_frames;
else if (bypass_clearing)
++stats_.bypassed_frames;
const double resolution = layered_costmap_->getCostmap()->getResolution();
std::vector<int> indices;
std::vector<float> sq_distances;
for (auto column = pc_3d_map_global_.begin(); column != pc_3d_map_global_.end();)
{
double wx, wy;
intIndexToWorld(wx, wy, column->first.first, column->first.second, resolution);
// Marked points this far from the robot are out of every frustum.
const double pc_dis = std::hypot(wx - robot_x, wy - robot_y);
if (pc_dis > kClearingSkipDistance)
{
++column;
continue;
}
auto& heights = column->second;
for (auto it = heights.begin(), next_it = it; it != heights.end(); it = next_it)
{
++next_it;
// Clearing tests the stored cell-corner position; the attach band is cleared too.
const Eigen::Vector3f search(static_cast<float>(wx), static_cast<float>(wy),
static_cast<float>(it->first * voxel_resolution_));
if (!insideAnyFrustum(frustums, search))
continue;
bool erase = false;
if (clear_all_marking_in_this_frame)
erase = true;
else if (!bypass_clearing && pc_dis <= forced_clearing_distance_)
erase = true;
else if (!bypass_clearing)
{
pcl::PointXYZI q;
q.x = search.x();
q.y = search.y();
q.z = search.z();
erase = kdtree.radiusSearch(q, check_radius_, indices, sq_distances) < number_clearing_threshold_;
}
if (!erase)
continue;
heights.erase(it);
++stats_.cleared;
}
// The last point of the column is gone: the cell is free again, in the own grid and,
// through the bounds, in the master this cycle.
column = heights.empty() ? eraseColumn(column, min_x, min_y, max_x, max_y) : std::next(column);
}
}
void DepthCameraObstacleLayer::processCluster(const std::vector<DepthCameraFrustum>& frustums,
const std::vector<Eigen::Vector3f>& cluster, double* min_x,
double* min_y, double* max_x, double* max_y)
{
const double resolution = layered_costmap_->getCostmap()->getResolution();
const int h_max = static_cast<int>(marking_height_above_ground_ / voxel_resolution_);
const int h_min = static_cast<int>(marking_height_under_ground_ / voxel_resolution_);
for (const Eigen::Vector3f& p : cluster)
{
// Robust marking condition: the raw point, inside a frustum and away from its faces.
if (!insideAnyFrustum(frustums, p) || attachedToFrustums(frustums, p))
continue;
int mmx, mmy;
worldToIntIndex(p.x(), p.y(), mmx, mmy, resolution);
const int h_ind = static_cast<int>(std::round(p.z() * (1 / voxel_resolution_)));
if (h_ind > h_max || h_ind < h_min)
continue;
const std::pair<int, int> key(mmx, mmy);
unsigned int cx, cy;
if (!columnCell(key, cx, cy))
continue; // would be dropped as out of the window anyway
auto& slot = pc_3d_map_global_[key];
auto inserted = slot.insert(std::make_pair(h_ind, 0.f));
if (inserted.second)
++stats_.marked;
setCost(cx, cy, LETHAL_OBSTACLE);
double wx, wy;
intIndexToWorld(wx, wy, mmx, mmy, resolution);
touch(wx, wy, min_x, min_y, max_x, max_y);
}
}
void DepthCameraObstacleLayer::updateFootprint(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
if (!footprint_clearing_enabled_)
return;
transformFootprint(robot_x, robot_y, robot_yaw, getFootprint(), transformed_footprint_);
for (const auto& pt : transformed_footprint_)
touch(pt.x, pt.y, min_x, min_y, max_x, max_y);
// updateCosts() frees the footprint in the own grid like ObstacleLayer; the stored points under
// it must go too, or the next marking pass would not bring them back but nothing would ever
// remove them either.
std::vector<MapLocation> polygon, cells;
for (const auto& pt : transformed_footprint_)
{
MapLocation loc;
if (!worldToMap(pt.x, pt.y, loc.x, loc.y))
return; // footprint leaves the window: same give-up as setConvexPolygonCost
polygon.push_back(loc);
}
if (polygon.size() < 3)
return;
convexFillCells(polygon, cells);
std::unordered_set<unsigned int> under;
for (const MapLocation& c : cells)
under.insert(getIndex(c.x, c.y));
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my) && under.count(getIndex(mx, my)))
{
++stats_.footprint_cleared;
it = eraseColumn(it, min_x, min_y, max_x, max_y);
}
else
++it;
}
}
bool DepthCameraObstacleLayer::isValid(int mx, int my) const
{
// Same result as the source's unsigned test: mx - 1 of cell 0 is out of range.
return mx >= 0 && my >= 0 && mx <= static_cast<int>(getSizeInCellsX()) &&
my <= static_cast<int>(getSizeInCellsY());
}
bool DepthCameraObstacleLayer::columnCell(const std::pair<int, int>& column, unsigned int& mx,
unsigned int& my) const
{
double wx, wy;
intIndexToWorld(wx, wy, column.first, column.second, getResolution());
if (!worldToMap(wx, wy, mx, my))
return false;
// The +-1 cells guard the rounding of the stored corner, as in the source.
const int x = static_cast<int>(mx), y = static_cast<int>(my);
return isValid(x - 1, y - 1) && isValid(x - 1, y + 1) && isValid(x + 1, y - 1) && isValid(x + 1, y + 1);
}
std::map<std::pair<int, int>, std::map<int, float>>::iterator DepthCameraObstacleLayer::eraseColumn(
std::map<std::pair<int, int>, std::map<int, float>>::iterator it, double* min_x, double* min_y,
double* max_x, double* max_y)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
setCost(mx, my, FREE_SPACE);
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
touch(wx, wy, min_x, min_y, max_x, max_y);
}
return pc_3d_map_global_.erase(it);
}
void DepthCameraObstacleLayer::dropColumnsOutsideWindow(double* min_x, double* min_y, double* max_x,
double* max_y)
{
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
// Keep the own grid in step with the points even after matchSize() or a cleared area
// wiped the cell: one O(columns) pass that writes only when something is missing.
if (getCost(mx, my) != LETHAL_OBSTACLE)
{
setCost(mx, my, LETHAL_OBSTACLE);
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
touch(wx, wy, min_x, min_y, max_x, max_y);
}
++it;
continue;
}
// B6: the source keeps such points forever, so the map and every loop over it grow.
++stats_.dropped_out_of_window;
double wx, wy;
intIndexToWorld(wx, wy, it->first.first, it->first.second, getResolution());
if (worldToMap(wx, wy, mx, my))
{
// Still inside the window, on its edge row/column: free that cell as well.
setCost(mx, my, FREE_SPACE);
touch(wx, wy, min_x, min_y, max_x, max_y);
}
it = pc_3d_map_global_.erase(it);
}
}
void DepthCameraObstacleLayer::updateCosts(Costmap2D& master_grid, int min_i, int min_j, int max_i, int max_j)
{
boost::unique_lock<mutex_t> lock(*getMutex());
if (!enabled_)
return;
// The own grid mirrors the stored points (see updateBounds), so the layer merges like
// ObstacleLayer and the master is only changed inside the update bounds.
if (footprint_clearing_enabled_)
setConvexPolygonCost(transformed_footprint_, FREE_SPACE);
switch (combination_method_)
{
case 0: // Overwrite
updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
break;
case 1: // Maximum
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
break;
default: // Nothing
break;
}
}
std::size_t DepthCameraObstacleLayer::storedPoints() const
{
std::size_t n = 0;
for (const auto& column : pc_3d_map_global_)
n += column.second.size();
return n;
}
void DepthCameraObstacleLayer::logStats()
{
const robot::Time now = robot::Time::now();
const double since = (now - last_stats_log_).toSec();
if (since < debug_stats_period_ && since >= 0.0)
return;
last_stats_log_ = now;
if (debug_stats_ && stats_.cycles > 0)
robot::log_info("[debug/stats] DepthCameraObstacleLayer %s: cycles=%zu cloud_pts/cycle=%.0f stored=%zu "
"columns=%zu marked=%zu cleared=%zu footprint_cleared=%zu clear_all_cycles=%zu bypass_cycles=%zu "
"tf_wait=%zu tf_drop=%zu out_of_window=%zu bounds_ms avg=%.1f max=%.1f\n",
name_.c_str(), stats_.cycles, static_cast<double>(stats_.cloud_points) / stats_.cycles,
storedPoints(), pc_3d_map_global_.size(), stats_.marked, stats_.cleared, stats_.footprint_cleared,
stats_.cleared_all_frames, stats_.bypassed_frames, stats_.tf_waits, stats_.tf_drops,
stats_.dropped_out_of_window, stats_.bounds_ms_sum / stats_.cycles, stats_.bounds_ms_max);
stats_ = Stats();
}
void DepthCameraObstacleLayer::activate()
{
for (const auto& source : sources_)
source->last_updated = robot::Time::now();
}
void DepthCameraObstacleLayer::deactivate()
{
// The source unsubscribes and clears its local-mode map only; the global-mode map stays.
for (const auto& source : sources_)
{
std::lock_guard<std::mutex> lock(source->pending_mutex);
source->pending.reset();
}
}
void DepthCameraObstacleLayer::reset()
{
boost::unique_lock<mutex_t> lock(*getMutex());
deactivate();
resetMaps();
// The source keeps its global-mode points here (B9), so a reset changed nothing on the master.
pc_3d_map_global_.clear();
for (const auto& source : sources_)
source->observations.clear();
current_ = true;
activate();
}
void DepthCameraObstacleLayer::matchSize()
{
// The master was resized (or this is onInitialize): CostmapLayer::matchSize() rebuilds the own
// grid with default_value_, so put the stored columns back now instead of waiting a cycle, and
// ask the next update to merge the whole layer.
boost::unique_lock<mutex_t> lock(*getMutex());
CostmapLayer::matchSize();
for (const auto& column : pc_3d_map_global_)
{
unsigned int mx, my;
if (columnCell(column.first, mx, my))
setCost(mx, my, LETHAL_OBSTACLE);
}
if (!pc_3d_map_global_.empty())
addExtraBounds(getOriginX(), getOriginY(), getOriginX() + getSizeInMetersX(),
getOriginY() + getSizeInMetersY());
}
void DepthCameraObstacleLayer::clearArea(int start_x, int start_y, int end_x, int end_y, bool invert_area)
{
boost::unique_lock<mutex_t> lock(*getMutex());
CostmapLayer::clearArea(start_x, start_y, end_x, end_y, invert_area);
for (auto it = pc_3d_map_global_.begin(); it != pc_3d_map_global_.end();)
{
unsigned int mx, my;
if (columnCell(it->first, mx, my))
{
// Same test as CostmapLayer::clearArea: keep what it keeps.
const int x = static_cast<int>(mx), y = static_cast<int>(my);
const bool inside = x > start_x && x < end_x && y > start_y && y < end_y;
if (inside != invert_area)
{
++it;
continue;
}
}
// The own grid cell is already NO_INFORMATION from CostmapLayer::clearArea.
it = pc_3d_map_global_.erase(it);
}
}
// Export factory function
static boost::shared_ptr<Layer> create_depth_camera_obstacle_plugin()
{
return boost::make_shared<DepthCameraObstacleLayer>();
}
BOOST_DLL_ALIAS(create_depth_camera_obstacle_plugin, DepthCameraObstacleLayer)
} // namespace robot_costmap_2d

View File

@@ -41,7 +41,6 @@
#include <robot_costmap_2d/footprint.h> #include <robot_costmap_2d/footprint.h>
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include <boost/dll/alias.hpp> #include <boost/dll/alias.hpp>
#include <stdexcept>
using robot_costmap_2d::LETHAL_OBSTACLE; using robot_costmap_2d::LETHAL_OBSTACLE;
@@ -81,8 +80,7 @@ void InflationLayer::onInitialize()
need_reinflation_ = false; need_reinflation_ = false;
std::string config_file_name = "inflation_layer_params.yaml"; std::string config_file_name = "inflation_layer_params.yaml";
// std::cout << "InflationLayer: " << config_file_name << std::endl; // std::cout << "InflationLayer: " << config_file_name << std::endl;
if (!getParams(config_file_name, priv_nh)) getParams(config_file_name, priv_nh);
throw std::runtime_error("InflationLayer " + name_ + ": cannot open the default file " + config_file_name);
matchSize(); matchSize();
} }

View File

@@ -42,7 +42,6 @@
#include <tf3/exceptions.h> #include <tf3/exceptions.h>
#include <boost/dll/alias.hpp> #include <boost/dll/alias.hpp>
#include <stdexcept>
using robot_costmap_2d::NO_INFORMATION; using robot_costmap_2d::NO_INFORMATION;
@@ -67,8 +66,7 @@ void ObstacleLayer::onInitialize()
stop_receiving_data_ = false; stop_receiving_data_ = false;
global_frame_ = layered_costmap_->getGlobalFrameID(); global_frame_ = layered_costmap_->getGlobalFrameID();
std::string config_file_name = "obstacle_layer_params.yaml"; std::string config_file_name = "obstacle_layer_params.yaml";
if (!getParams(config_file_name, priv_nh)) getParams(config_file_name, priv_nh);
throw std::runtime_error("ObstacleLayer " + name_ + ": cannot open the default file " + config_file_name);
} }
ObstacleLayer::~ObstacleLayer() ObstacleLayer::~ObstacleLayer()
@@ -133,6 +131,9 @@ 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; 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"; std::string topic = "map", sensor_frame = "laser_frame", data_type = "PointCloud";
bool inf_is_valid = false, clearing=false, marking=true; 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); robot::NodeHandle priv_nh(nh, source);
topic = loadParam(layer[source],"topic", topic); topic = loadParam(layer[source],"topic", topic);
@@ -145,6 +146,34 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
inf_is_valid = loadParam(layer[source],"inf_is_valid", false); inf_is_valid = loadParam(layer[source],"inf_is_valid", false);
clearing = loadParam(layer[source],"clearing", false); clearing = loadParam(layer[source],"clearing", false);
marking = loadParam(layer[source],"marking", true); 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")) if (priv_nh.hasParam("topic"))
priv_nh.getParam("topic", topic); priv_nh.getParam("topic", topic);
@@ -166,6 +195,52 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
priv_nh.getParam("clearing", clearing); priv_nh.getParam("clearing", clearing);
if (priv_nh.hasParam("marking")) if (priv_nh.hasParam("marking"))
priv_nh.getParam("marking", 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_);
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; double obstacle_range = 2.5;
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range); obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
@@ -177,34 +252,57 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (priv_nh.hasParam("raytrace_range")) if (priv_nh.hasParam("raytrace_range"))
priv_nh.getParam("raytrace_range", raytrace_range); priv_nh.getParam("raytrace_range", raytrace_range);
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan")) if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan" || data_type == "DepthCameraData"))
{ {
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n"); 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"); throw std::runtime_error("Only topics that use point clouds or laser scans are currently supported");
} }
CallBackInfo info_tmp; if(!frustum_clearing_enabled)
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(), CallBackInfo info_tmp;
priv_nh.getNamespace().c_str()); 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);
// create an observation buffer // enabled_ = enabled;
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());
// check if we'll also add this buffer to our clearing observation buffers robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
if (clearing) priv_nh.getNamespace().c_str());
clearing_buffers_.push_back(observation_buffers_.back());
// 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());
// 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)));
}
robot::log_info( robot::log_info(
"Created an observation buffer for topic %s, global frame: %s, " "Created an observation buffer for topic %s, global frame: %s, "
"expected update rate: %.2f, observation persistence: %.2f\n", "expected update rate: %.2f, observation persistence: %.2f\n",
@@ -228,60 +326,139 @@ void ObstacleLayer::handleImpl(const void* data,
if (!enabled_ || stop_receiving_data_) if (!enabled_ || stop_receiving_data_)
return; return;
// Samples that match no configured source (type and topic) are ignored. if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr))
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++)
{ {
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[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;
if (type == typeid(robot_sensor_msgs::LaserScan) && const robot_sensor_msgs::DepthCameraData& depth_camera_data =
callback_infos_[i].data_type == "LaserScan" && *depth_camera_data_ptr;
topic == callback_infos_[i].topic && const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
!callback_infos_[i].inf_is_valid) const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
{
// 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); std::size_t bytes_per_pixel = 0;
} if (depth.encoding == "16UC1" || depth.encoding == "mono16")
else if (type == typeid(robot_sensor_msgs::PointCloud) && bytes_per_pixel = 2;
callback_infos_[i].data_type == "PointCloud" && else if (depth.encoding == "32FC1")
topic == callback_infos_[i].topic) bytes_per_pixel = 4;
{ else
if (callback_infos_[i].inf_is_valid)
{ {
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n"); robot::log_error("ObstacleLayer received unsupported depth encoding: %s\n", depth.encoding.c_str());
return;
} }
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
} const bool invalid_dimensions = depth.width == 0 || depth.height == 0 ||
else if (type == typeid(robot_sensor_msgs::PointCloud2) && depth.step < static_cast<std::size_t>(depth.width) * bytes_per_pixel ||
callback_infos_[i].data_type == "PointCloud2" && depth.data.size() < static_cast<std::size_t>(depth.step) * depth.height;
topic == callback_infos_[i].topic) if (invalid_dimensions)
{
if (callback_infos_[i].inf_is_valid)
{ {
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n"); robot::log_error("ObstacleLayer received malformed DepthCameraData image\n");
return;
} }
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
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");
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++)
{
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");
}
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;
// }
} }
// 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;
// }
} }
} }
@@ -383,6 +560,14 @@ void ObstacleLayer::pointCloud2Callback(const robot_sensor_msgs::PointCloud2& me
buffer->unlock(); 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, void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y) double* min_y, double* max_x, double* max_y)
{ {
@@ -552,6 +737,23 @@ bool ObstacleLayer::getClearingObservations(std::vector<Observation>& clearing_o
return current; 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_)
{
buffer->lock();
buffer->getDepthObservations(frustum_clearing_observations);
current = buffer->isCurrent() && current;
buffer->unlock();
// frustum_clearing_observations.push_back(depth_obs);
}
return current;
}
void ObstacleLayer::raytraceFreespace(const Observation& clearing_observation, double* min_x, double* min_y, void ObstacleLayer::raytraceFreespace(const Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_y) double* max_x, double* max_y)
{ {

View File

@@ -43,7 +43,6 @@
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h> #include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <boost/dll/alias.hpp> #include <boost/dll/alias.hpp>
#include <stdexcept>
#include <fstream> #include <fstream>
#include <cxxabi.h> #include <cxxabi.h>
@@ -72,8 +71,7 @@ void StaticLayer::onInitialize()
global_frame_ = layered_costmap_->getGlobalFrameID(); global_frame_ = layered_costmap_->getGlobalFrameID();
std::string config_file_name = "static_layer_params.yaml"; std::string config_file_name = "static_layer_params.yaml";
if (!getParams(config_file_name, priv_nh)) getParams(config_file_name, priv_nh);
throw std::runtime_error("StaticLayer " + name_ + ": cannot open the default file " + config_file_name);
robot::log_warning("Initializing static layer with map topic \"%s\" in frame \"%s\"", map_topic_.c_str(), global_frame_.c_str()); robot::log_warning("Initializing static layer with map topic \"%s\" in frame \"%s\"", map_topic_.c_str(), global_frame_.c_str());
} }

View File

@@ -45,8 +45,6 @@
#include <cmath> #include <cmath>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <stdexcept>
#include <string>
#define VOXEL_BITS 16 #define VOXEL_BITS 16
@@ -67,8 +65,7 @@ void VoxelLayer::onInitialize()
ObstacleLayer::onInitialize(); ObstacleLayer::onInitialize();
std::string config_file_name = "voxel_layer_params.yaml"; std::string config_file_name = "voxel_layer_params.yaml";
if (!getParams(config_file_name, priv_nh)) getParams(config_file_name, priv_nh);
throw std::runtime_error("VoxelLayer " + name_ + ": cannot open the default file " + config_file_name);
} }
VoxelLayer::~VoxelLayer() VoxelLayer::~VoxelLayer()
@@ -95,14 +92,14 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
enabled_ = loadParam(layer, "enabled", true); enabled_ = loadParam(layer, "enabled", true);
footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true); footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true);
max_obstacle_height_ = loadParam(layer, "max_obstacle_height", 2.0); max_obstacle_height_ = loadParam(layer, "max_obstacle_height", 2.0);
int size_z = loadParam(layer, "z_voxels", 10); size_z_ = loadParam(layer, "z_voxels", 10);
origin_z_ = loadParam(layer, "origin_z", 0.0); origin_z_ = loadParam(layer, "origin_z", 0.0);
z_resolution_ = loadParam(layer, "z_resolution", 0.2); z_resolution_ = loadParam(layer, "z_resolution", 0.2);
// Read as double: the default file writes 15.0, which yaml-cpp refuses to convert to int. unknown_threshold_ = loadParam(layer, "unknown_threshold", 15.0) + (VOXEL_BITS - size_z_);
double unknown_threshold = loadParam(layer, "unknown_threshold", 15.0); mark_threshold_ = loadParam(layer, "mark_threshold", 0);
int mark_threshold = loadParam(layer, "mark_threshold", 0);
combination_method_ = loadParam(layer, "combination_method", 0.0); combination_method_ = loadParam(layer, "combination_method", 0.0);
int size_z, unknown_threshold, mark_threshold, frustum_pixel_step;
if (nh.hasParam("enabled")) if (nh.hasParam("enabled"))
nh.getParam("enabled", enabled_); nh.getParam("enabled", enabled_);
if (nh.hasParam("footprint_clearing_enabled")) if (nh.hasParam("footprint_clearing_enabled"))
@@ -110,40 +107,25 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
if (nh.hasParam("max_obstacle_height")) if (nh.hasParam("max_obstacle_height"))
nh.getParam("max_obstacle_height", max_obstacle_height_); nh.getParam("max_obstacle_height", max_obstacle_height_);
if (nh.hasParam("z_voxels")) if (nh.hasParam("z_voxels"))
{
nh.getParam("z_voxels", size_z); nh.getParam("z_voxels", size_z);
size_z_ = size_z;
}
if (nh.hasParam("origin_z")) if (nh.hasParam("origin_z"))
nh.getParam("origin_z", origin_z_); nh.getParam("origin_z", origin_z_);
if (nh.hasParam("z_resolution"))
nh.getParam("z_resolution", z_resolution_);
if (nh.hasParam("unknown_threshold")) if (nh.hasParam("unknown_threshold"))
{
nh.getParam("unknown_threshold", unknown_threshold); nh.getParam("unknown_threshold", unknown_threshold);
unknown_threshold_ = unknown_threshold + (VOXEL_BITS - size_z_);
}
if (nh.hasParam("mark_threshold")) if (nh.hasParam("mark_threshold"))
{
nh.getParam("mark_threshold", mark_threshold); nh.getParam("mark_threshold", mark_threshold);
mark_threshold_ = mark_threshold;
}
if (nh.hasParam("combination_method")) if (nh.hasParam("combination_method"))
nh.getParam("combination_method", combination_method_); nh.getParam("combination_method", combination_method_);
// A column stores VOXEL_BITS levels at most, and worldToMap3D divides by z_resolution.
if (size_z < 1 || size_z > VOXEL_BITS)
throw std::invalid_argument("VoxelLayer " + name_ + ": z_voxels must be in [1, 16]");
if (!(z_resolution_ > 0.0) || !std::isfinite(z_resolution_))
throw std::invalid_argument("VoxelLayer " + name_ + ": z_resolution must be > 0 [m]");
if (!std::isfinite(origin_z_))
throw std::invalid_argument("VoxelLayer " + name_ + ": origin_z must be finite [m]");
if (!(unknown_threshold >= 0.0) || mark_threshold < 0)
throw std::invalid_argument("VoxelLayer " + name_ + ": unknown_threshold and mark_threshold must be >= 0");
size_z_ = size_z;
// Levels above z_voxels are never observed and stay unknown; adding them keeps the threshold
// counting only the levels in use. Computed after size_z_ is final, so overriding z_voxels
// alone no longer leaves the threshold sized for the default file's column.
unknown_threshold_ = static_cast<unsigned int>(unknown_threshold) + (VOXEL_BITS - size_z_);
mark_threshold_ = static_cast<unsigned int>(mark_threshold);
robot::log_info("VoxelLayer %s: column origin_z=%.2f m z_resolution=%.3f m z_voxels=%u (top %.2f m) "
"unknown_threshold=%u mark_threshold=%u max_obstacle_height=%.2f m\n",
name_.c_str(), origin_z_, z_resolution_, size_z_, origin_z_ + size_z_ * z_resolution_,
unknown_threshold_, mark_threshold_, max_obstacle_height_);
this->matchSize(); this->matchSize();
} }
catch (const YAML::BadFile& e) { catch (const YAML::BadFile& e) {
@@ -190,6 +172,7 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
bool current = true; bool current = true;
std::vector<Observation> observations, clearing_observations; std::vector<Observation> observations, clearing_observations;
std::vector<DepthCameraObservation> depth_observations;
// get the marking observations // get the marking observations
current = getMarkingObservations(observations) && current; current = getMarkingObservations(observations) && current;
@@ -197,9 +180,16 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
// get the clearing observations // get the clearing observations
current = getClearingObservations(clearing_observations) && current; current = getClearingObservations(clearing_observations) && current;
current = getFrustumClearingObservations(depth_observations) && current;
// update the global current status // update the global current status
current_ = current; current_ = current;
for (const DepthCameraObservation& depth_observation : depth_observations)
{
raytraceDepthFrustum(depth_observation, min_x, min_y, max_x, max_y);
}
// raytrace freespace // raytrace freespace
for (unsigned int i = 0; i < clearing_observations.size(); ++i) for (unsigned int i = 0; i < clearing_observations.size(); ++i)
{ {
@@ -407,6 +397,539 @@ 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
{
tfm = tf_->lookupTransform(global_frame_, depth_frame, tf3::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) void VoxelLayer::updateOrigin(double new_origin_x, double new_origin_y)
{ {
// project the new origin into the grid // project the new origin into the grid

View File

@@ -48,9 +48,6 @@
#include <tf3/convert.h> #include <tf3/convert.h>
#include <tf3/utils.h> #include <tf3/utils.h>
#include <exception> #include <exception>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include <boost/dll/import.hpp> #include <boost/dll/import.hpp>
@@ -66,26 +63,10 @@ void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::str
if (!old_h.hasParam(name)) if (!old_h.hasParam(name))
return; return;
// A failed getParam() writes its default (0, false, "") into value; copying that would replace old_h.getParam(name, value);
// the layer's own default with a silent zero. A key of the wrong type is a configuration error.
if (!old_h.getParam(name, value, value))
throw std::invalid_argument("'" + old_h.getNamespace() + "/" + name +
"' does not convert to the type the layer reads");
new_h.setParam(name, value); new_h.setParam(name, value);
} }
// Moves each key of names that exists under old_h, read as T.
template <class T>
void move_parameters(robot::NodeHandle& old_h, robot::NodeHandle& new_h,
std::initializer_list<const char*> names)
{
for (const char* name : names)
{
T value{};
move_parameter(old_h, new_h, name, value);
}
}
Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) : Costmap2DROBOT::Costmap2DROBOT(const std::string& name, tf3::BufferCore& tf) :
layered_costmap_(NULL), layered_costmap_(NULL),
name_(name), name_(name),
@@ -128,17 +109,6 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
robot::NodeHandle priv_nh(nh, name); robot::NodeHandle priv_nh(nh, name);
// A costmap missing a layer, the layers after it or its update thread still looks alive to the
// planner, which then drives on a map that never marks obstacles. Refuse to build it instead:
// NavigationRuntime::buildCostmaps() turns the exception into an initialization error and the
// host never reports READY. The destructor does not run when the constructor throws, so the
// layered costmap (and the layers already added to it) is released here.
const auto fail = [this](const std::string& what) {
delete layered_costmap_;
layered_costmap_ = NULL;
throw std::runtime_error("costmap '" + name_ + "': " + what);
};
std::string global_frame = std::string global_frame =
loadParam(layer, "global_frame", std::string("map")); loadParam(layer, "global_frame", std::string("map"));
std::string robot_base_frame = std::string robot_base_frame =
@@ -254,22 +224,44 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
{ {
my_list.clear(); my_list.clear();
YAML::Node my_plugins = priv_nh.getParamValue("plugins"); YAML::Node my_plugins = priv_nh.getParamValue("plugins");
if (!my_plugins || !my_plugins.IsSequence()) if (my_plugins && my_plugins.IsSequence())
fail("plugins: must be a list of {name, type} maps");
for (size_t i = 0; i < my_plugins.size(); ++i)
{ {
YAML::Node plugin_i = my_plugins[i].as<YAML::Node>(); for (size_t i = 0; i < my_plugins.size(); ++i)
// Checked before reading the fields: indexing a scalar entry throws a bare YAML error. {
if (!plugin_i.IsMap() || !plugin_i["name"] || !plugin_i["type"]) YAML::Node plugin_i = my_plugins[i].as<YAML::Node>();
fail("plugins: entry " + std::to_string(i) + " must be a map with a name and a type");
PluginConfig p; PluginConfig p;
p.type = plugin_i["type"].as<std::string>(); p.type = plugin_i["type"].as<std::string>();
p.name = plugin_i["name"].as<std::string>(); p.name = plugin_i["name"].as<std::string>();
for (const auto& known : my_list) my_list.push_back(p);
if (known.name == p.name) if (!plugin_i.IsMap())
fail("plugins: the name '" + p.name + "' is used twice; each layer needs its own name"); {
my_list.push_back(p); std::cerr << "Plugins must be specified as maps. We'll use the default recovery behaviors instead." << std::endl;
return;
}
if (!plugin_i["name"] || !plugin_i["type"])
{
std::cerr << "Plugins must have a name and a type. Using the default recovery behaviors instead." << std::endl;
return;
}
// check for recovery behaviors with the same name
std::string name_i = plugin_i["name"].as<std::string>();
for (size_t j = i + 1; j < my_plugins.size(); ++j)
{
YAML::Node plugin_j = my_plugins[j].as<YAML::Node>();
if (plugin_j.IsMap() && plugin_j["name"])
{
std::string name_j = plugin_j["name"].as<std::string>();
if (name_i == name_j)
{
std::cerr << "A plugin with the name " << name_i << " already exists, this is not allowed. Using the default recovery behaviors instead." << std::endl;
return;
}
}
}
}
} }
} }
else else
@@ -301,10 +293,10 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
plugin->initialize(layered_costmap_,name_ + "/" + info.name, &tf_); plugin->initialize(layered_costmap_,name_ + "/" + info.name, &tf_);
layered_costmap_->addPlugin(plugin); layered_costmap_->addPlugin(plugin);
} }
catch (const std::exception& ex) catch (std::exception &ex)
{ {
// Covers a missing library or symbol as well as a layer rejecting its parameters. robot::log_error("Failed to create the %s, are you sure it is properly registered and that the containing library is built? Exception: %s\n", info.name.c_str(), ex.what());
fail("layer '" + info.name + "' (" + info.type + "): " + ex.what()); return;
} }
} }
@@ -361,11 +353,8 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
} }
catch (const YAML::BadFile& e) catch (const YAML::BadFile& e)
{ {
// costmap_params.yaml is read before layered_costmap_ exists; delete is a no-op on NULL. std::cerr << "Cannot open YAML file: " << e.what() << std::endl;
delete layered_costmap_; return;
layered_costmap_ = NULL;
throw std::runtime_error("costmap '" + name_ + "': cannot open the default file " + config_file_name +
" under $PNKX_NAV_CORE_CONFIG_DIR/config: " + e.what());
} }
} }
@@ -374,81 +363,182 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
const std::string& plugin_type, const std::string& plugin_type,
robot::NodeHandle& nh) robot::NodeHandle& nh)
{ {
// Step 2 of the layer config flow. A layer reads its default file, then overrides each key found
// in "<costmap>/<plugin>". This copies the keys of the shared "<plugin>:" block there first, so the
// lists below must hold every key the layer reads with hasParam(): a key missing here is ignored
// without a word when it is set in the shared block. A copied key overwrites the same key in
// "<costmap>/<plugin>". Types follow what the layer reads.
robot::NodeHandle costmap_nh(nh, costmap_name); robot::NodeHandle costmap_nh(nh, costmap_name);
robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name); robot::NodeHandle costmap_plugin_nh(costmap_nh, plugin_name);
robot::NodeHandle plugin_nh(nh, plugin_name); robot::NodeHandle plugin_nh(nh, plugin_name);
if(plugin_type == "StaticLayer")
// observation_sources, then the keys of each source under "<plugin>/<source>/". {
const auto move_sources = [&](const auto& move_source_keys) { std::string map_topic;
std::string topics_string; int unknown_cost_value;
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string); int lethal_cost_threshold;
std::stringstream ss(topics_string); bool track_unknown_space;
std::string source; move_parameter(plugin_nh, costmap_plugin_nh, "map_topic", map_topic);
while (ss >> source) move_parameter(plugin_nh, costmap_plugin_nh, "unknown_cost_value", unknown_cost_value);
move_parameter(plugin_nh, costmap_plugin_nh, "lethal_cost_threshold", lethal_cost_threshold);
move_parameter(plugin_nh, costmap_plugin_nh, "track_unknown_space", track_unknown_space);
}
else if(plugin_type == "VoxelLayer")
{
double origin_z;
double z_resolution;
int z_voxels;
int mark_threshold;
int unknown_threshold;
bool publish_voxel_map;
move_parameter(plugin_nh, costmap_plugin_nh, "origin_z", origin_z);
move_parameter(plugin_nh, costmap_plugin_nh, "z_resolution", z_resolution);
move_parameter(plugin_nh, costmap_plugin_nh, "z_voxels", z_voxels);
move_parameter(plugin_nh, costmap_plugin_nh, "mark_threshold", mark_threshold);
move_parameter(plugin_nh, costmap_plugin_nh, "unknown_threshold", unknown_threshold);
move_parameter(plugin_nh, costmap_plugin_nh, "publish_voxel_map", publish_voxel_map);
if(plugin_nh.hasParam("observation_sources"))
{ {
robot::NodeHandle plugin_nh_element(plugin_nh, source); std::string topics_string;
robot::NodeHandle costmap_plugin_nh_element(costmap_plugin_nh, source); move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
move_source_keys(plugin_nh_element, costmap_plugin_nh_element); robot::log_error("topics_string: %s", topics_string.c_str());
} std::stringstream ss(topics_string);
}; std::string source;
while (ss >> source)
{
robot::NodeHandle plugin_nh_element(plugin_nh, source);
robot::NodeHandle costmap_plugin_nh_element(costmap_plugin_nh, source);
std::string topic;
std::string data_type;
bool clearing;
bool marking;
bool inf_is_valid;
std::string sensor_frame;
double observation_persistence;
double expected_update_rate;
double min_obstacle_height;
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;
if (plugin_type == "StaticLayer") move_parameter(plugin_nh_element, costmap_plugin_nh_element, "topic", topic);
{ move_parameter(plugin_nh_element, costmap_plugin_nh_element, "sensor_frame", sensor_frame);
move_parameters<std::string>(plugin_nh, costmap_plugin_nh, {"map_topic", "base_frame_id"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "observation_persistence", observation_persistence);
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"unknown_cost_value", "lethal_cost_threshold"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "expected_update_rate", expected_update_rate);
move_parameters<bool>(plugin_nh, costmap_plugin_nh, move_parameter(plugin_nh_element, costmap_plugin_nh_element, "data_type", data_type);
{"enabled", "track_unknown_space", "first_map_only", "subscribe_to_updates", move_parameter(plugin_nh_element, costmap_plugin_nh_element, "clearing", clearing);
"use_maximum", "trinary_costmap"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "marking", marking);
} move_parameter(plugin_nh_element, costmap_plugin_nh_element, "inf_is_valid", inf_is_valid);
else if (plugin_type == "ObstacleLayer" || plugin_type == "VoxelLayer") move_parameter(plugin_nh_element, costmap_plugin_nh_element, "min_obstacle_height", min_obstacle_height);
{ move_parameter(plugin_nh_element, costmap_plugin_nh_element, "max_obstacle_height", max_obstacle_height);
// VoxelLayer runs ObstacleLayer::getParams() first, so it reads these keys too. move_parameter(plugin_nh_element, costmap_plugin_nh_element, "obstacle_range", obstacle_range);
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"max_obstacle_height", "transform_tolerance"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "raytrace_range", raytrace_range);
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"combination_method"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_enabled", frustum_clearing_enabled);
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"track_unknown_space", "footprint_clearing_enabled"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_clearing_pixel_step", frustum_clearing_pixel_step);
if (plugin_type == "VoxelLayer") 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_parameters<double>(plugin_nh, costmap_plugin_nh, {"origin_z", "z_resolution", "unknown_threshold"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_skip_distance", frustum_skip_distance);
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"z_voxels", "mark_threshold"}); move_parameter(plugin_nh_element, costmap_plugin_nh_element, "frustum_column_clearing", frustum_column_clearing);
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled"}); 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);
}
} }
move_sources([](robot::NodeHandle& from, robot::NodeHandle& to) {
move_parameters<std::string>(from, to, {"topic", "sensor_frame", "data_type"});
move_parameters<double>(from, to, {"observation_persistence", "expected_update_rate", "min_obstacle_height",
"max_obstacle_height", "obstacle_range", "raytrace_range"});
move_parameters<bool>(from, to, {"clearing", "marking", "inf_is_valid"});
});
} }
else if (plugin_type == "InflationLayer") else if(plugin_type == "ObstacleLayer")
{ {
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"cost_scaling_factor", "inflation_radius"}); double max_obstacle_height;
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled", "inflate_unknown"}); double raytrace_range;
double obstacle_range;
bool track_unknown_space;
move_parameter(plugin_nh, costmap_plugin_nh, "max_obstacle_height", max_obstacle_height);
move_parameter(plugin_nh, costmap_plugin_nh, "raytrace_range", raytrace_range);
move_parameter(plugin_nh, costmap_plugin_nh, "obstacle_range", obstacle_range);
move_parameter(plugin_nh, costmap_plugin_nh, "track_unknown_space", track_unknown_space);
if(plugin_nh.hasParam("observation_sources"))
{
std::string topics_string;
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
robot::log_error("topics_string: %s", topics_string.c_str());
std::stringstream ss(topics_string);
std::string source;
while (ss >> source)
{
robot::NodeHandle plugin_nh_element(plugin_nh, source);
robot::NodeHandle costmap_plugin_nh_element(costmap_plugin_nh, source);
std::string topic;
std::string data_type;
bool clearing;
bool marking;
bool inf_is_valid;
std::string sensor_frame;
double observation_persistence;
double expected_update_rate;
double min_obstacle_height;
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);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "observation_persistence", observation_persistence);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "expected_update_rate", expected_update_rate);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "data_type", data_type);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "clearing", clearing);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "marking", marking);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "inf_is_valid", inf_is_valid);
move_parameter(plugin_nh_element, costmap_plugin_nh_element, "min_obstacle_height", min_obstacle_height);
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);
}
}
} }
else if (plugin_type == "DepthCameraObstacleLayer") else if(plugin_type == "InflationLayer")
{ {
move_parameters<bool>(plugin_nh, costmap_plugin_nh, double cost_scaling_factor;
{"track_unknown_space", "enabled", "footprint_clearing_enabled", double inflation_radius;
"enable_near_blocked_protection", "use_voxelized_observation", "use_global_frame_to_mark", move_parameter(plugin_nh, costmap_plugin_nh, "cost_scaling_factor", cost_scaling_factor);
"clear_touches_bounds", "debug/stats"}); move_parameter(plugin_nh, costmap_plugin_nh, "inflation_radius", inflation_radius);
move_parameters<int>(plugin_nh, costmap_plugin_nh,
{"combination_method", "number_points_considered_as_blocked", "ec_cluster_min_size",
"size_of_cluster_rejection", "number_clearing_threshold"});
move_parameters<double>(plugin_nh, costmap_plugin_nh,
{"forced_clearing_distance", "ec_seg_distance", "voxel_resolution", "check_radius",
"transform_tolerance", "debug/stats_period"});
move_sources([](robot::NodeHandle& from, robot::NodeHandle& to) {
move_parameters<std::string>(from, to, {"topic", "sensor_frame"});
move_parameters<bool>(from, to, {"sensor_frame_is_optical", "marking", "inf_is_valid"});
move_parameters<double>(from, to, {"observation_persistence", "expected_update_rate", "min_obstacle_height",
"max_obstacle_height", "FOV_V", "FOV_W", "min_detect_distance",
"max_detect_distance"});
});
} }
} }
void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint) void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint)

View File

@@ -58,6 +58,23 @@ 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() ObservationBuffer::~ObservationBuffer()
{ {
} }
@@ -212,6 +229,36 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
purgeStaleObservations(); purgeStaleObservations();
} }
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 // returns a copy of the observations
void ObservationBuffer::getObservations(vector<Observation>& observations) void ObservationBuffer::getObservations(vector<Observation>& observations)
{ {
@@ -226,6 +273,26 @@ 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() void ObservationBuffer::purgeStaleObservations()
{ {
if (!observation_list_.empty()) if (!observation_list_.empty())
@@ -252,6 +319,30 @@ 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 bool ObservationBuffer::isCurrent() const
{ {
if (expected_update_rate_ == robot::Duration(0.0)) if (expected_update_rate_ == robot::Duration(0.0))

View File

@@ -180,6 +180,28 @@ TEST(CostmapPerformanceRegression, observation_copy_shares_cloud_payload)
EXPECT_EQ(copied.cloud_->data, cloud.data); 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) TEST(CostmapPerformanceRegression, inflation_buckets_preserve_radial_costs)
{ {
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0); ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);

View File

@@ -1,486 +0,0 @@
#include <robot_costmap_2d/depth_camera_obstacle_layer.h>
#include <robot_costmap_2d/cost_values.h>
#include <robot_sensor_msgs/point_cloud2_iterator.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <boost/make_shared.hpp>
#include <gtest/gtest.h>
#include <unistd.h>
#include <cmath>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
using namespace robot_costmap_2d;
namespace
{
constexpr double kFovW = 1.23; // D410 at 424x240, fx = 300 [rad]
constexpr double kFovV = 0.76;
constexpr char kTopic[] = "/camera/depth/points_proc";
// The layer reads config/depth_camera_obstacle_layer_params.yaml under PNKX_NAV_CORE_CONFIG_DIR
// before its own namespace; point it at this package for every test.
class ConfigDirEnvironment : public ::testing::Environment
{
public:
void SetUp() override
{
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);
}
};
::testing::Environment* const kConfigDirEnvironment = ::testing::AddGlobalTestEnvironment(new ConfigDirEnvironment);
// Optical frame "camera" 0.19 m above odom, looking along +x of odom (rotated by yaw).
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;
}
// Points given in odom for a camera at yaw 0; stored in the optical frame of the cloud.
robot_sensor_msgs::PointCloud2 cloud(robot::Time stamp, const std::vector<Eigen::Vector3d>& odom_points)
{
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(odom_points.size());
robot_sensor_msgs::PointCloud2Iterator<float> x(c, "x"), y(c, "y"), z(c, "z");
for (const auto& p : odom_points)
{
*x = -p.y();
*y = .19 - p.z();
*z = p.x();
++x;
++y;
++z;
}
return c;
}
// 3 x 3 points, 6 cm apart (one per 5 cm voxel), one Euclidean cluster. Kept away from cell
// boundaries: the source stores (int)(x / 0.05), so y = .07 .13 .19 are columns 1 2 3.
std::vector<Eigen::Vector3d> object(double x = 1.02, double y = .13, double z = .30)
{
std::vector<Eigen::Vector3d> pts;
for (double dy : {-.06, 0., .06})
for (double dz : {-.06, 0., .06})
pts.emplace_back(x, y + dy, z + dz);
return pts;
}
// 11 points in a row 0.6 m behind the object: keeps the cloud above 5 points, own cluster.
std::vector<Eigen::Vector3d> wall()
{
std::vector<Eigen::Vector3d> pts;
for (int i = -5; i <= 5; ++i)
pts.emplace_back(1.62, i * .06 + .13, .30);
return pts;
}
std::vector<Eigen::Vector3d> join(std::vector<Eigen::Vector3d> a, const std::vector<Eigen::Vector3d>& b)
{
a.insert(a.end(), b.begin(), b.end());
return a;
}
YAML::Node baseConfig()
{
YAML::Node cfg;
cfg["enabled"] = true;
cfg["footprint_clearing_enabled"] = false;
cfg["use_global_frame_to_mark"] = true;
cfg["enable_near_blocked_protection"] = false;
cfg["observation_sources"] = "depth_cam";
cfg["debug"]["stats"] = false;
cfg["depth_cam"]["topic"] = kTopic;
cfg["depth_cam"]["sensor_frame_is_optical"] = true;
cfg["depth_cam"]["FOV_W"] = kFovW;
cfg["depth_cam"]["FOV_V"] = kFovV;
cfg["depth_cam"]["min_detect_distance"] = .15;
cfg["depth_cam"]["max_detect_distance"] = 2.5;
cfg["depth_cam"]["min_obstacle_height"] = .05;
cfg["depth_cam"]["max_obstacle_height"] = 1.0;
return cfg;
}
} // namespace
// ---------------------------------------------------------------------------------------------
// Frustum geometry
// ---------------------------------------------------------------------------------------------
TEST(DepthCameraFrustum, InsideFollowsTheConfiguredPyramid)
{
DepthCameraFrustum f;
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false); // X forward
const float half_w = std::tan(kFovW / 2), half_v = std::tan(kFovV / 2);
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(.1f, 0, 0))); // before the near plane
EXPECT_FALSE(f.inside(Eigen::Vector3f(2.6f, 0, 0))); // beyond the far plane
EXPECT_FALSE(f.inside(Eigen::Vector3f(-1, 0, 0)));
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, .98f * half_w, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 1.02f * half_w, 0)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, -1.02f * half_w, 0)));
EXPECT_TRUE(f.inside(Eigen::Vector3f(1, 0, -.98f * half_v)));
EXPECT_FALSE(f.inside(Eigen::Vector3f(1, 0, 1.02f * half_v)));
}
TEST(DepthCameraFrustum, AttachBandIsTwelveCentimetresFromEveryFace)
{
DepthCameraFrustum f;
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, 0, 0)));
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(2.4f, 0, 0))); // 10 cm before the far plane
const float half_w = std::tan(kFovW / 2);
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .3f, 0)));
}
TEST(DepthCameraFrustum, OpticalFrameGivesTheSamePyramid)
{
DepthCameraFrustum link, optical;
link.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
optical.build(T, kFovW, kFovV, .15, 2.5, true);
for (int i = 0; i < 8; ++i)
EXPECT_LT((link.vertices[i] - optical.vertices[i]).norm(), 1e-5f) << "vertex " << i;
EXPECT_TRUE(optical.inside(Eigen::Vector3f(1, 0, 0)));
}
TEST(DepthCameraFrustum, AttachedUnlessWellInsideAnotherFrustum)
{
DepthCameraFrustum a, b;
a.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.translation() << 0, .3, 0; // second camera 30 cm to the left
b.build(T, kFovW, kFovV, .15, 2.5, false);
const Eigen::Vector3f near_left_face_of_a(1, std::tan(kFovW / 2) - .05f, 0);
EXPECT_TRUE(attachedToFrustums({a}, near_left_face_of_a));
EXPECT_FALSE(attachedToFrustums({a, b}, near_left_face_of_a));
EXPECT_FALSE(attachedToFrustums({a}, Eigen::Vector3f(1, 0, 0)));
}
// ---------------------------------------------------------------------------------------------
// Layer
// ---------------------------------------------------------------------------------------------
class DepthCameraLayerTest : public ::testing::Test
{
protected:
tf3::BufferCore tf;
LayeredCostmap parent{"odom", false, false};
DepthCameraObstacleLayer layer;
uint32_t tick = 0;
double min_x = 0, min_y = 0, max_x = 0, max_y = 0;
void SetUp() override
{
robot::Time::setNow(robot::Time(100, 0));
YAML::Node cfg = baseConfig();
configure(cfg);
robot::NodeHandle nh("~");
nh.setParam("dcam_test", cfg);
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
layer.initialize(&parent, "dcam_test", &tf);
ASSERT_TRUE(layer.isEnabled());
}
virtual void configure(YAML::Node&) {}
robot::Time next()
{
return robot::Time(100, ++tick * 10000000);
}
void update()
{
min_x = min_y = 1e9;
max_x = max_y = -1e9;
layer.updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
}
void frame(const std::vector<Eigen::Vector3d>& pts, double yaw = 0, bool has_tf = true)
{
const robot::Time stamp = next();
robot::Time::setNow(stamp);
if (has_tf)
ASSERT_TRUE(tf.setTransform(pose(stamp, yaw), "test"));
layer.dataCallBack(cloud(stamp, pts), kTopic);
update();
}
unsigned char master(double x = 1.01, double y = .11)
{
Costmap2D& m = *parent.getCostmap();
m.resetMap(0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
layer.updateCosts(m, 0, 0, m.getSizeInCellsX(), m.getSizeInCellsY());
unsigned int a, b;
EXPECT_TRUE(m.worldToMap(x, y, a, b));
return m.getCost(a, b);
}
};
TEST_F(DepthCameraLayerTest, MarksAClusterInsideTheFrustum)
{
frame(object());
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE);
EXPECT_TRUE(layer.isCurrent());
}
TEST_F(DepthCameraLayerTest, SmallClusterAndOutOfHeightPointsAreNotMarked)
{
std::vector<Eigen::Vector3d> five = object();
five.resize(5); // <= size_of_cluster_rejection
frame(join(five, wall()));
EXPECT_NE(master(), LETHAL_OBSTACLE);
frame(join(object(1.02, .13, 1.5), wall())); // above max_obstacle_height
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, KeptWhileSeenAgainAndClearedWhenGone)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame(join(object(), wall()));
EXPECT_EQ(master(), LETHAL_OBSTACLE);
frame(wall()); // no cloud point within check_radius of the stored points
EXPECT_NE(master(), LETHAL_OBSTACLE);
EXPECT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, OutsideTheFrustumIsKept)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame({}, 1.57); // camera turned away, sees nothing
EXPECT_EQ(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, NearlyEmptyCloudClearsEverythingInViewWithoutProtection)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
frame({});
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
class DepthCameraBlockedTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["enable_near_blocked_protection"] = true;
}
};
TEST_F(DepthCameraBlockedTest, NearlyEmptyCloudSkipsClearingWithProtection)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame({});
EXPECT_EQ(master(), LETHAL_OBSTACLE);
frame(wall());
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, AttachBandIsNotMarked)
{
// 10 cm past the near plane (0.15 m) of a camera at x = 0: inside, but attached.
frame(wall());
const std::size_t wall_points = layer.storedPoints();
ASSERT_GT(wall_points, 0u);
frame(join(object(.25, .10, .19), wall()));
EXPECT_EQ(layer.storedPoints(), wall_points);
}
TEST_F(DepthCameraLayerTest, WaitsForTheMeasurementTfThenDropsAfterTheTolerance)
{
frame(object(), 0, false); // no TF at this stamp yet
EXPECT_EQ(layer.storedPoints(), 0u);
const robot::Time stamp(100, tick * 10000000);
ASSERT_TRUE(tf.setTransform(pose(stamp), "late_tf"));
update();
EXPECT_EQ(layer.storedPoints(), 9u);
frame(object(1.32, -.47, .3), 0, false);
const robot::Time late(100, tick * 10000000);
robot::Time::setNow(robot::Time(101, 0)); // older than transform_tolerance (0.2 s)
update();
ASSERT_TRUE(tf.setTransform(pose(late), "too_late_tf"));
update();
EXPECT_NE(master(1.31, -.44), LETHAL_OBSTACLE); // the waiting cloud was dropped
EXPECT_EQ(layer.storedPoints(), 9u);
}
TEST_F(DepthCameraLayerTest, OtherTopicsAndDepthImagesAreIgnored)
{
const robot::Time stamp = next();
robot::Time::setNow(stamp);
ASSERT_TRUE(tf.setTransform(pose(stamp), "test"));
layer.dataCallBack(cloud(stamp, object()), "/other/points");
robot_sensor_msgs::DepthCameraData::ConstPtr depth = boost::make_shared<robot_sensor_msgs::DepthCameraData>();
layer.dataCallBack(depth, kTopic);
update();
EXPECT_EQ(layer.storedPoints(), 0u);
}
TEST_F(DepthCameraLayerTest, MarkingsThatLeaveTheWindowAreDropped)
{
frame(object());
ASSERT_EQ(layer.storedPoints(), 9u);
layer.updateOrigin(10, 10); // the stored cells are outside the layer now
update();
EXPECT_EQ(layer.storedPoints(), 0u);
}
TEST_F(DepthCameraLayerTest, ClearedCellLeavesTheMasterInsideTheBounds)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE); // master now holds the object cell
frame(wall());
EXPECT_LT(min_x, 1.05); // the cleared object cell is part of this cycle's bounds
// What LayeredCostmap does: reset the master inside the bounds only, then merge the layer there.
Costmap2D& m = *parent.getCostmap();
int i0, j0, i1, j1;
m.worldToMapEnforceBounds(min_x, min_y, i0, j0);
m.worldToMapEnforceBounds(max_x, max_y, i1, j1);
m.resetMap(i0, j0, i1 + 1, j1 + 1);
layer.updateCosts(m, i0, j0, i1 + 1, j1 + 1);
unsigned int a, b;
ASSERT_TRUE(m.worldToMap(1.01, .11, a, b));
EXPECT_NE(m.getCost(a, b), LETHAL_OBSTACLE);
ASSERT_TRUE(m.worldToMap(1.61, .11, a, b));
EXPECT_EQ(m.getCost(a, b), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, ClearAreaKeepsTheInsideByDefaultAndClearsItWhenInverted)
{
frame(join(object(), wall()));
ASSERT_EQ(master(), LETHAL_OBSTACLE);
ASSERT_EQ(master(1.61, .11), LETHAL_OBSTACLE);
// Cells strictly inside (55, 35)-(65, 50) hold the object (cell x 60); the wall is at cell x 72.
layer.clearArea(55, 35, 65, 50, false); // CostmapLayer contract: clears OUTSIDE the box
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE);
EXPECT_NE(master(1.61, .11), LETHAL_OBSTACLE);
layer.clearArea(55, 35, 65, 50, true); // inverted: clears the inside
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, ResetDropsTheStoredPointsAndObservations)
{
frame(join(object(), wall()));
ASSERT_GT(layer.storedPoints(), 0u);
layer.reset();
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
update(); // no new cloud: the buffered observation is gone too, nothing comes back
EXPECT_EQ(layer.storedPoints(), 0u);
}
class DepthCameraFootprintTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["footprint_clearing_enabled"] = true;
cfg["enable_near_blocked_protection"] = true; // an empty cycle must not clear by itself
}
};
TEST_F(DepthCameraFootprintTest, FootprintClearingErasesThePointsUnderTheRobot)
{
std::vector<robot_geometry_msgs::Point> square(4);
square[0].x = -.3; square[0].y = -.3;
square[1].x = .3; square[1].y = -.3;
square[2].x = .3; square[2].y = .3;
square[3].x = -.3; square[3].y = .3;
parent.setFootprint(square);
frame(object());
ASSERT_EQ(layer.storedPoints(), 9u);
layer.updateBounds(1.02, .13, 0, &min_x, &min_y, &max_x, &max_y); // robot drives onto it
EXPECT_EQ(layer.storedPoints(), 0u);
EXPECT_NE(master(), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraLayerTest, HasItsOwnLayerType)
{
EXPECT_EQ(layer.getType(), LayerType::DEPTH_CAMERA_LAYER);
EXPECT_NE(layer.getType(), LayerType::VOXEL_LAYER);
}
TEST_F(DepthCameraLayerTest, MatchSizeKeepsAndReMarksTheStoredPoints)
{
frame(object());
ASSERT_EQ(master(), LETHAL_OBSTACLE);
layer.matchSize(); // rebuilds the own grid from scratch
EXPECT_EQ(layer.storedPoints(), 9u);
EXPECT_EQ(master(), LETHAL_OBSTACLE); // re-marked without waiting for an update
}
TEST(DepthCameraLayerConfig, RejectsUnportedModeAndOutOfRangeValues)
{
tf3::BufferCore tf;
LayeredCostmap parent{"odom", false, false};
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
robot::NodeHandle nh("~");
const auto expectThrow = [&](const YAML::Node& cfg) {
nh.setParam("dcam_bad", cfg);
DepthCameraObstacleLayer layer;
EXPECT_THROW(layer.initialize(&parent, "dcam_bad", &tf), std::invalid_argument);
};
YAML::Node cfg = baseConfig();
cfg["use_global_frame_to_mark"] = false;
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["FOV_W"] = 3.5;
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["min_detect_distance"] = 3.0;
expectThrow(cfg);
cfg = baseConfig();
cfg["voxel_resolution"] = 0.0;
expectThrow(cfg);
// A value of the wrong type stops the layer instead of becoming 0.
cfg = baseConfig();
cfg["number_clearing_threshold"] = "many";
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["FOV_W"] = "wide";
expectThrow(cfg);
}
TEST(DepthCameraLayerConfig, RefusesToStartWithoutItsDefaultFile)
{
tf3::BufferCore tf;
LayeredCostmap parent{"odom", false, false};
parent.getCostmap()->resizeMap(80, 80, .05, -2, -2);
robot::NodeHandle nh("~");
nh.setParam("dcam_no_default", baseConfig());
// An empty directory: it has no config/depth_camera_obstacle_layer_params.yaml.
char empty_dir[] = "/tmp/dcam_no_default_XXXXXX";
ASSERT_NE(mkdtemp(empty_dir), nullptr);
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", empty_dir, 1), 0);
DepthCameraObstacleLayer layer;
EXPECT_THROW(layer.initialize(&parent, "dcam_no_default", &tf), std::runtime_error);
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_COSTMAP_2D_DIR, 1), 0);
rmdir(empty_dir);
}