10 Commits

Author SHA1 Message Date
7c6d070bd5 feat(static_layer): report current only after the map reaches the master
current_ is false before the first map, after every new map, update or
resize, and becomes true only once updateCosts has written the map
(shared markMapWritten helper, also called by CriticalLayer). Readiness
flags are written under the master mutex so the planner can trust
isCurrent() taken under the same lock. Invalid partial updates are
rejected with a throttled error.
2026-11-04 11:14:15 +07:00
52089a0e90 feat(directional_layer): make the allowed deviation configurable
Add max_deviation_deg (default 90, valid 0 < x < 180). The field carries
the value so checkSegment and every planner use the same rule. 90 keeps
the previous masks bit for bit; out-of-range values stop the layer from
initialising.
2026-11-04 08:52:00 +07:00
5e7a22cad8 fix(static_layer): ignore grids addressed to another layer's topic
The sensor gateway sends every OccupancyGrid to every layer of the matching type, so a StaticLayer also sees the direction grid and other StaticLayers' maps. Those used to log two unthrottled errors per push. Right type on another topic is normal traffic and is now ignored; only an unknown data type still logs an error.
2026-11-03 16:57:01 +07:00
3d552b49d0 feat(directional_layer): rewrite as a direction field provider
DirectionalLayer no longer derives from StaticLayer and never writes the
master grid. It receives an OccupancyGrid of direction codes (0 = no
constraint, 1..8 = direction_index + 1) on direction_topic, validates it
against the master geometry and global frame, and publishes an immutable
DirectionField snapshot with a DISABLED / PENDING / READY state and a
generation counter. Every static map on map_topic drops the snapshot and
returns the layer to PENDING until a grid for that map arrives.

direction_field.h holds the core API used by planners: grid validation,
DirectionField with bounds-checked codeAt(), a half-open-cell DDA
(traverseGridSegment), allowedDirectionMask() and checkSegment().
LayeredCostmap::getDirectionFieldSnapshot() exposes the snapshot through
the DirectionFieldProvider interface without adding data members.

Tests: direction_field_test (7) and directional_layer_test (5) pass.
2026-11-03 16:55:10 +07:00
3539afbfb4 build(test): link yaml-cpp into depth_camera_obstacle_layer_test
The test calls yaml-cpp directly; without it the link fails with "DSO missing from command line" when BUILD_COSTMAP_TESTS is ON.
2026-10-28 13:43:56 +07:00
757b381659 feat(depth_layer): add occlusion_guard and attach_distance
occlusion_guard (default false): keep a stored point when a nearer object blocks the ray to it, clear a point the camera sees through. attach_distance (default 0.12 m, as before) is now read per source. Both keys are forwarded from the parent costmap parameters. README, params YAML and tests updated.
2026-10-27 13:09:31 +07:00
9b93a45b45 refactor(depth_layer): read parameters like the other layers
DepthCameraObstacleLayer::loadParameters() wrapped each key in a
readParam() helper. It now reads the same way as
ObstacleLayer::getParams(): one block of loadParam() calls on the default
file, then one block of "if (priv_nh.hasParam(k)) priv_nh.getParam(k, v)"
on "<costmap>/<plugin>". The per-source keys do the same on
"<costmap>/<plugin>/<source>". Values and precedence are unchanged.

getParam() gets the current value as its default, so a value of the
wrong type keeps the file default instead of becoming 0, false or "".
The layer no longer throws on a wrong type itself. A wrong type in the
shared block still stops the costmap, in copyParentParameters(). The two
wrong-type test cases, which set the layer namespace directly, are
removed.
2026-10-22 10:56:10 +07:00
e40e9c0104 fix(costmap): one parameter flow for every layer; fail on a bad layer
Each layer reads its default file under $PNKX_NAV_CORE_CONFIG_DIR/config,
then overrides a key from "<costmap>/<plugin>".
Costmap2DROBOT::copyParentParameters() copies the shared "<plugin>:"
block there first. This was broken in three ways:
- the copy lists covered only part of what the layers read, so a key set
  in the shared block was dropped without a word;
- DepthCameraObstacleLayer had no default file and read the shared block
  itself;
- a layer that failed to initialize left a half-built costmap that
  reported READY.

Failing loudly:
- costmap_2d_robot.cpp: a failing layer, a malformed plugins: list or a
  missing costmap_params.yaml throws std::runtime_error with the costmap
  and layer name, after releasing layered_costmap_.
  NavigationRuntime::buildCostmaps() turns this into an initialization
  error, so the host never reports READY.
- Static/Obstacle/Voxel/Inflation and DepthCameraObstacleLayer throw when
  their default file cannot be opened.
- A key whose value does not convert to the type the layer reads throws.
  getParam() used to write 0, false or "" into the value, and that was
  copied as if configured.

One flow:
- copyParentParameters() copies every key each layer reads, with the
  layer's type, including a new DepthCameraObstacleLayer branch. Copies no
  layer reads are dropped.
- DepthCameraObstacleLayer::loadParameters() reads
  config/depth_camera_obstacle_layer_params.yaml (new, equal to the C++
  defaults), then "<costmap>/<plugin>". ParamReader is gone, and so is the
  node_handle.cpp:265 warning at start-up.
- VoxelLayer: z_resolution can be overridden; unknown_threshold is
  computed after the final z_voxels; the column keys are range-checked;
  the effective column is logged once at start-up.
- config/obstacle_layer_params.yaml: drop the per-source keys the layer
  never read there.
- depth_camera_obstacle_layer_test: set PNKX_NAV_CORE_CONFIG_DIR; add
  tests for a wrong type and a missing default file.

Squash of fix/config-flow (ae7fce9, f8705e1). Checked on the KIT robot on
22/10/2026:
- the depth layer summary at start-up is unchanged;
- a shared-block key now reaches VoxelLayer;
- FOV_W 3.5, z_voxels 17, a wrong-typed key and a missing default file
  each give INITIALIZATION_FAILED.
2026-10-22 10:49:31 +07:00
3b89add5ee refactor(obstacle_layer): drop the DepthCameraData startup guard
ObstacleLayer and VoxelLayer no longer carry any depth code, so the check
that rejected a DepthCameraData source or frustum_clearing_enabled goes too.
A DepthCameraData source still fails at startup through the generic
data_type check; frustum_clearing_enabled is now an unknown key.

The README and the LayerType comment now say the gateway feeds
DepthCameraObstacleLayer PointCloud2 only.
2026-10-21 14:10:55 +07:00
64974d48b7 feat(depth): DepthCameraObstacleLayer replaces depth clearing in ObstacleLayer/VoxelLayer
Depth cameras now go through their own costmap layer instead of the
frustum clearing that lived in ObstacleLayer and VoxelLayer.

- Add DepthCameraObstacleLayer. It stores marked points per costmap
  column, clears stored points inside each camera frustum with a kd-tree
  check against the new cloud, keeps points outside the view, groups
  points with Euclidean clustering, and does not mark a 12 cm band at the
  frustum faces.
- The layer follows the CostmapLayer contract: updateWithMax/Overwrite by
  combination_method, reset(), clearArea() with the usual invert
  semantics, footprint clearing, matchSize() and the layer mutex. So
  ClearCostmapRecovery and costmap resets work on it.
- Add LayerType::DEPTH_CAMERA_LAYER, appended last so the existing values
  keep their numbers. The host's SensorGateway must dispatch PointCloud2
  and DepthCameraData to it (move_base2 feature/depth-camera-layer-type).
- Remove the frustum clearing code from Observation, ObservationBuffer,
  ObstacleLayer, VoxelLayer and costmap_2d_robot.cpp.
- ObstacleLayer and VoxelLayer now reject a DepthCameraData source or
  frustum_clearing_enabled: true at startup, with a message that points
  to DepthCameraObstacleLayer.
- Link PCL into the plugins library only. Add 21 unit tests for the layer
  (depth_camera_obstacle_layer_test).

Squashed from feature/depth-observed-volume (2ca0bcc..40dc70e).
2026-10-21 13:16:07 +07:00
34 changed files with 4071 additions and 2963 deletions

View File

@@ -23,6 +23,9 @@ find_package(Boost REQUIRED COMPONENTS system thread filesystem)
# still configure. The test block below requires it where it is actually used.
find_package(GTest QUIET)
find_package(yaml-cpp REQUIRED)
# DepthCameraObstacleLayer only (voxel grid, kd-tree clearing, Euclidean clustering); the core
# library and the other layers do not use PCL.
find_package(PCL REQUIRED COMPONENTS common filters kdtree search segmentation)
if (NOT BUILDING_WITH_CATKIN)
@@ -109,10 +112,10 @@ add_library(robot_costmap_2d SHARED
src/observation_buffer.cpp
src/layer.cpp
src/layered_costmap.cpp
src/direction_field.cpp
src/costmap_math.cpp
src/footprint.cpp
src/costmap_layer.cpp
src/body_clearance.cpp
)
if(BUILDING_WITH_CATKIN)
@@ -176,7 +179,12 @@ add_library(plugins SHARED
plugins/directional_layer.cpp
plugins/preferred_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)
add_dependencies(plugins ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
@@ -232,6 +240,9 @@ if(BUILDING_WITH_CATKIN)
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
)
install(FILES config/directional_layer_params.yaml
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/config)
## Mark cpp header files for installation
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
@@ -248,6 +259,9 @@ else()
RUNTIME DESTINATION bin
)
install(FILES config/directional_layer_params.yaml
DESTINATION share/${PROJECT_NAME}/config)
# Export targets
install(EXPORT ${PROJECT_NAME}-targets
FILE ${PROJECT_NAME}-targets.cmake
@@ -287,16 +301,11 @@ if(BUILD_COSTMAP_TESTS)
find_package(Boost REQUIRED COMPONENTS system thread filesystem)
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/body_clearance_test.cpp)
add_executable(test_body_clearance test/body_clearance_test.cpp)
target_link_libraries(test_body_clearance PRIVATE
robot_costmap_2d
GTest::GTest
GTest::Main
Boost::system Boost::thread
${TF3_LIBRARY}
)
endif()
add_executable(direction_field_test test/direction_field_test.cpp)
target_link_libraries(direction_field_test PRIVATE robot_costmap_2d GTest::GTest GTest::Main)
add_executable(directional_layer_test test/directional_layer_test.cpp)
target_link_libraries(directional_layer_test PRIVATE plugins robot_costmap_2d GTest::GTest GTest::Main Boost::thread ${TF3_LIBRARY})
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/array_parser_test.cpp)
add_executable(test_array_parser test/array_parser_test.cpp)
@@ -335,4 +344,15 @@ if(BUILD_COSTMAP_TESTS)
${TF3_LIBRARY}
)
endif()
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/depth_camera_obstacle_layer_test.cpp)
add_executable(depth_camera_obstacle_layer_test test/depth_camera_obstacle_layer_test.cpp)
target_link_libraries(depth_camera_obstacle_layer_test PRIVATE
plugins
robot_costmap_2d
yaml-cpp
GTest::GTest
GTest::Main
)
endif()
endif()

227
README.md
View File

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

View File

@@ -0,0 +1,54 @@
# 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] Chống xoá khi bị che, dùng tia nhìn của ảnh depth (cả sàn, trước lọc chiều cao).
# true: điểm đã lưu mà có vật gần hơn nằm trên tia nhìn tới nó thì GIỮ (người đi ngang trước thùng
# không còn xoá thùng); điểm mà camera nhìn xuyên qua thấy nền phía sau thì XOÁ, kể cả khi còn điểm
# khác trong check_radius (vết của vật vừa dịch đi biến nhanh hơn).
# false: chỉ dùng phép kd-tree như gói gốc. Bật thì tốn thêm một ảnh khoảng cách nhỏ mỗi cloud.
# Vết nằm NGOÀI FOV vẫn không xoá được dù bật hay tắt.
occlusion_guard: false
# [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, attach_distance...) KHÔNG
# đặt ở đây mà trong khối <plugin>/<tên nguồn>/ của config costmap. attach_distance [m] mặc định
# 0.12 như gói gốc: điểm cách mặt khối nhìn dưới mức này không được đánh dấu.
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

@@ -0,0 +1,24 @@
# Mặc định đóng gói của directional layer; cây chạy thực tế tùy host là
# pnkx_nav_core/src/Navigations/Packages/move_base2/config/runtime hoặc
# pnkx_nav_core/config.
directional_layer:
# Bật: sau mỗi static map, layer PENDING đến khi nhận grid hợp lệ và planner
# phải từ chối lập đường trong lúc chờ. Host phải gửi grid sau mỗi static map;
# dùng data rỗng nếu map không có zone. Tắt để bỏ ràng buộc hướng.
enabled: false
# Phải trùng map_topic của StaticLayer. Đặt sai khiến layer không thoát
# PENDING hoặc không nhận biết khi map đổi.
map_topic: "map"
# Topic grid hướng: đổi theo tên host gửi; phải khác map_topic.
direction_topic: "direction_map"
# [deg] Góc lệch tối đa giữa hướng di chuyển và hướng zone, tính cả biên.
# Áp chung cho mọi zone. 90 = được đi mọi hướng có thành phần cùng chiều zone
# (đi ngang zone được, đi ngược bị cấm).
# Giảm: robot phải đi sát hướng zone hơn, cấm cắt ngang làn, phải căn hướng
# trước khi vào zone; quay tại chỗ luôn được phép. Dưới 22.5 (bước heading của
# mprim 16 hướng) SBPL có thể không tìm được đường.
# Tăng quá 90: cho phép cả hướng hơi ngược chiều zone, zone một chiều yếu đi.
# Phạm vi hợp lệ: 0 < giá trị < 180; ngoài phạm vi nav core từ chối khởi động.
max_deviation_deg: 90.0
# Bật để ghi log chuyển trạng thái; tắt để giảm log bình thường.
debug_state: true

View File

@@ -1,18 +1,13 @@
# 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:
track_unknown_space: true
transform_tolerance: 0.2
topic: "map"
sensor_frame: laser_frame
observation_persistence: 0.0
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
track_unknown_space: true # [bool] true = ô chưa quan sát giữ NO_INFORMATION; false = coi là free.
transform_tolerance: 0.2 # [s] độ trễ TF tối đa khi đổi điểm sensor sang frame costmap. Nhỏ quá
# thì điểm bị bỏ khi TF trễ; lớn quá thì điểm được đặt sai chỗ khi robot quay.
max_obstacle_height: 2.0 # [m] điểm cao hơn mức này không được đánh dấu.
footprint_clearing_enabled: true # [bool] xoá vật cản nằm trong footprint robot (chính thân robot).
combination_method: 1 # [-] 0 = ghi đè lên master costmap; 1 = lấy max với master.

View File

@@ -1,210 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_costmap_2d — "thân robot ở đâu, còn cách vật cản bao xa": MỘT nguồn hình học duy nhất cho
* mọi thành phần cần trả lời câu hỏi đó (local planner, giám sát tuyến, recovery, global planner).
*
* Vì sao có file này (đo 8-9/2026 trên sim):
* Bốn thành phần cùng trả lời "thân có chạm không", mỗi cái tự dựng hình học riêng —
* PRIEST solver : 3 circle r=0.52 (+0.08 +0.05) -> ellipse 0.65 -> khe lọt 1.30 m
* giám sát tuyến: polygon costmap + 0.05 -> khe lọt 1.06 m
* SBPL : polygon costmap vs LETHAL -> khe lọt ~1.05 m
* head_slowdown : hộp 0.583 x 0.48, ngưỡng 253 -> khác hẳn
* Hệ quả không tránh được: global planner vẽ đường qua khe 1.1 m, local planner không bám nổi,
* residual treo cao, tầng an toàn dừng robot, replan trả về CÙNG một đường, lặp vô hạn (đo được
* 6 vòng ở một góc trụ, 250 vòng ở một ca khác). Chỉnh số ở từng chỗ chỉ kéo hai cột lại gần
* nhau rồi lệch ở chỗ thứ ba; muốn hết thì phải bỏ CHỖ để chúng lệch.
*
* Ba hàm dưới đây là chỗ duy nhất khai hình học thân và ngưỡng ô, và chúng dùng CHUNG một tập ô:
* thứ solver nạp vào (@ref obstaclePoints) đúng bằng thứ phép quét dò (@ref sweep). Nhờ vậy không
* còn tình huống solver báo đường thoáng trong khi tầng an toàn báo sắp chạm.
*
* Không giữ trạng thái, không quyết định gì: chỉ đo và trả số. Ai dừng robot, dừng lúc nào, dừng
* rồi thoát ra sao — việc của tầng trên.
*
* Author: DuongTD
*********************************************************************/
#ifndef ROBOT_COSTMAP_2D_BODY_CLEARANCE_H_
#define ROBOT_COSTMAP_2D_BODY_CLEARANCE_H_
#include <vector>
#include <robot_geometry_msgs/Point.h>
#include <robot_costmap_2d/cost_values.h>
namespace robot_costmap_2d
{
class Costmap2D;
/**
* @struct BodyModel
* @brief Thân robot: hình dạng, biên an toàn, ngưỡng ô. Dựng MỘT lần lúc init.
*
* @ref footprint phải là footprint THẬT của robot, lấy từ `Costmap2DROBOT::getRobotFootprint()` —
* không khai lại bằng tay ở YAML của từng gói, vì đó chính là cách bốn hình học kia sinh ra.
*/
struct BodyModel
{
/// Footprint trong khung base_link, chưa đệm. Rỗng hoặc < 3 đỉnh = chưa dựng được.
std::vector<robot_geometry_msgs::Point> footprint;
/**
* [m] Biên an toàn TƯỜNG MINH nới ra mọi phía trước khi dò.
*
* Đây là chỗ duy nhất khai biên. Trước kia biên đến từ hai nguồn chồng nhau: vành inflation của
* costmap (ngưỡng 253) rồi lại bọc thêm ellipse quanh mỗi ô — đệm hai lần, robot đứng cách tường
* nửa mét vẫn báo "thân trong vật cản". Ở đây ngưỡng là LETHAL nên inflation không tham gia, và
* biên là con số này.
*/
double padding = 0.0;
/**
* Ô có cost >= mức này là vật cản THẬT. Mặc định LETHAL (254).
*
* Đừng hạ xuống INSCRIBED (253): 253 nghĩa là "đặt TÂM robot ở đây thì footprint đã đệm chạm
* vật cản" — nó đã là một phép kiểm thân rồi. Dùng nó làm điểm vật cản rồi lại dò footprint
* quanh nó là đếm thân hai lần.
*/
unsigned char lethal_threshold = LETHAL_OBSTACLE;
/// @brief Đủ dữ kiện để đo chưa (>= 3 đỉnh).
bool valid() const
{
return footprint.size() >= 3;
}
};
/**
* @struct SweepResult
* @brief Kết quả quét cung: lệnh (v, omega) này dẫn thân robot tới đâu.
*
* Ba đại lượng cho một điểm chạm, cố ý — cùng một quãng cung mang ý nghĩa rất khác nhau tuỳ độ
* cong. Đo được 4/9: cung 0.15 m khi đi thẳng 0.36 m/s là "chạm sau 0.4 s"; cũng 0.15 m khi bò
* 0.04 m/s với omega 0.5 (bán kính 0.08 m) là "quay 107 độ nữa, chạm sau 3.7 s" — tức không hề
* sắp chạm. Tầng trên quyết định bằng @ref t_contact và @ref turn, không phải bằng @ref walk.
*/
struct SweepResult
{
bool hit = false; ///< Có chạm trong tầm quét không.
double walk = 0.0; ///< [m] quãng dọc cung tới điểm chạm.
double t_contact = 0.0; ///< [s] còn bao lâu nữa mới chạm, theo tốc độ của chính lệnh này.
double turn = 0.0; ///< [rad] còn phải quay bao nhiêu nữa mới tới chỗ chạm.
int sample = -1; ///< Chỉ số mẫu chạm (1-based); -1 khi không chạm.
int scanned = 0; ///< Số mẫu đã quét; 0 = không quét được (v quá nhỏ, thiếu dữ liệu).
int baseline_cells = 0; ///< Số ô vật cản ĐANG nằm trong thân lúc này (đã được bỏ qua).
};
/**
* @struct SweepParams
* @brief Tầm quét. Ngưỡng dừng KHÔNG nằm ở đây — đây chỉ là phép đo.
*/
struct SweepParams
{
double lookahead = 0.8; ///< [m] quãng cung tối đa cần quét.
double lookahead_angle = 1.0; ///< [rad] góc tối đa; quay quá mức này thì lệnh đã đổi từ lâu.
double min_speed = 0.02; ///< [m/s] |v| dưới mức này cung suy biến, không quét.
double skip_own_body = 0.05; ///< [m] bỏ qua quãng đầu — đất robot đang đứng không phải bằng
///< chứng về tương lai; phán nó là chạm thì robot đứng cạnh vật
///< cản sẽ đứng vĩnh viễn vì chính việc đứng yên giữ nguyên số đo.
};
/**
* @brief [m] Khoảng hở từ thân đã đệm tới ô vật cản gần nhất, tại pose này.
*
* @return >= 0 khi thân sạch; < 0 khi đã có ô vật cản BÊN TRONG thân (giá trị là ước lượng độ lấn).
* Trả @ref no_clearance khi không đo được (model chưa dựng, không có ô nào trong tầm).
*
* @param search_radius [m] chỉ quét quanh robot chừng này (tính từ TÂM); 0 = bán kính ngoại tiếp
* của thân đã đệm cộng @ref default_clearance_reach. Không có ô vật cản nào trong tầm thì
* hàm trả về khoảng hở tối thiểu suy ra được từ chính tầm quét — "ít nhất bằng này" — chứ
* không phải @ref no_clearance: chỉ khi model chưa dựng mới là "không đo được".
*/
double clearance(const BodyModel& body, const Costmap2D& grid, double x, double y, double yaw,
double search_radius = 0.0);
/// Giá trị @ref clearance trả về khi KHÔNG ĐO ĐƯỢC (model chưa dựng). Dương lớn: "không biết"
/// KHÔNG được suy thành "sắp chạm" — làm vậy là robot dừng mỗi lần dữ liệu trễ một nhịp.
extern const double no_clearance;
/// [m] Tầm quét mặc định của @ref clearance, tính thêm ngoài bán kính ngoại tiếp thân. Đủ cho một
/// quyết định giảm tốc ở tốc độ hành trình; quét rộng hơn tốn thời gian trong nhịp điều khiển mà
/// không đổi quyết định nào.
extern const double default_clearance_reach;
/**
* @brief Quét cung cong không đổi mà lệnh (v, omega) vẽ ra từ pose hiện tại.
*
* Mỗi mẫu dò TOÀN BỘ CHU VI footprint đã đệm, lấy mẫu dày hơn một ô lưới; bước dọc cung cũng không
* quá một ô. Nhờ hai điều đó, một ô vật cản muốn lọt vào trong thân bắt buộc phải cắt chu vi ở một
* mẫu nào đó — không còn khe hình học. Dò vài điểm rời (tâm/mũi/hông) thì hở tới nửa bề rộng thân:
* đo 4/9, hai trụ cách nhau 0.45 m nằm lọt giữa hai đường quét, robot ôm cả hai trụ mới dừng.
*
* Ô vật cản ĐANG nằm trong thân lúc này được bỏ qua (@ref SweepResult::baseline_cells). Câu hỏi là
* "lệnh này có đưa THÊM vật cản vào thân không", không phải "thân có đang chạm gì không" — nếu
* không phân biệt, robot đứng lấn vành an toàn sẽ bị cấm MỌI chuyển động, kể cả chuyển động thoát
* ra, và với base chỉ tiến thì đó là kẹt vĩnh viễn (đo được 250 vòng replan liên tiếp).
*
* v < 0 (lùi) quét theo chiều lùi với cùng hình học. NO_INFORMATION và ô ngoài lưới = KHÔNG chạm.
*/
SweepResult sweep(const BodyModel& body, const Costmap2D& grid, double x, double y, double yaw,
double v, double omega, const SweepParams& params);
/**
* @struct CircleApproximation
* @brief Xấp xỉ thân bằng một chuỗi circle dọc trục dọc — dạng mà optimizer cần.
*
* Ràng buộc vật cản của một optimizer khả vi (ADMM, MPPI…) phải là hình trơn, không dùng được đa
* giác. Nhưng bán kính và khoảng cách các circle KHÔNG được khai bằng tay ở YAML riêng của gói đó:
* đúng đó là cách sinh ra hai thân khác nhau cho một robot (đo 8-9/2026: optimizer khai
* r=0.52 + 0.08 + 0.05 -> nửa rộng hiệu dụng 0.65, trong khi tầng an toàn dùng polygon + 0.05 ->
* 0.53; global planner vẽ đường qua khe 1.1 m mà local planner cần 1.30 m, không bám nổi, dừng,
* replan trả về cùng đường, lặp).
*
* @ref circleApproximation suy hai số đó TỪ CHÍNH @ref BodyModel mà tầng an toàn dùng, nên hai bên
* không thể lệch nhau nữa.
*/
struct CircleApproximation
{
double radius = 0.0; ///< [m] bán kính mỗi circle: nửa rộng thân đã đệm (nội tiếp + padding).
double spacing = 0.0; ///< [m] khoảng cách tâm hai circle kề nhau.
int count = 0; ///< Số circle; tâm đặt đối xứng quanh base_link.
};
/**
* @brief Suy chuỗi circle phủ kín thân đã đệm.
*
* Bán kính lấy bằng nửa rộng đã đệm (bán kính NỘI TIẾP + padding) — dùng bán kính ngoại tiếp thì
* thân phình ra hai bên tới góc chéo và robot không lách được khe nào. Khoảng cách tâm chọn sao
* cho hợp các circle phủ trọn chiều dài đã đệm: với nửa dài L và bán kính r, mỗi circle phủ dọc
* ±sqrt(r² − w²) quanh tâm nếu muốn đảm bảo bề rộng w tại mọi lát cắt.
*
* @param count số circle mong muốn (>= 1). 1 = một disc tại base_link, chỉ đúng cho robot gần
* tròn; robot dài dùng 3 trở lên, nếu không mũi và đuôi hụt.
* @return count = 0 khi @p body chưa dựng được.
*/
CircleApproximation circleApproximation(const BodyModel& body, int count);
/**
* @brief Điểm vật cản quanh robot cho solver — CÙNG tập ô mà @ref sweep sẽ dò.
*
* Đây là nửa còn lại của bất biến: solver né đúng những ô mà tầng an toàn sẽ dò. Trước kia solver
* nạp ô >= 253 (gồm cả vành inflation) rồi bọc thêm ellipse, trong khi tầng an toàn dò >= 254 —
* hai bên thấy hai môi trường khác nhau, và cãi nhau ở mọi hàng người.
*
* @param range [m] bán kính quét quanh robot.
* @param cell_step bước nhảy khi quét ô. Với ngưỡng LETHAL, ô vật cản chỉ là đường viền mỏng
* 1-2 ô, nên bước > 1 bỏ sót thật sự (đo 4/9: step 3 làm hàng người 100+ ô còn
* 3-11 điểm, solver tưởng đường thoáng). Chỉ nới khi đã đo.
* @param max_points trần số điểm; điểm GẦN NHẤT được giữ trước.
* @param[out] out ghi đè; cặp (x, y) trong cùng frame với @p grid.
* @return tổng số ô vật cản THẤY trong tầm (có thể lớn hơn out.size() khi chạm trần) — bên gọi
* dùng để biết mình đang bị cắt cụt dữ liệu.
*/
int obstaclePoints(const BodyModel& body, const Costmap2D& grid, double x, double y, double range,
int cell_step, int max_points, std::vector<std::pair<double, double> >& out);
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_BODY_CLEARANCE_H_

View File

@@ -0,0 +1,307 @@
/*********************************************************************
* 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).
* Additions over the source, both off by default so the source behaviour stays the default:
* the attach band width is a per-source parameter (`attach_distance`, the source hard-codes
* 0.12 m), and `occlusion_guard` adds depth-ray evidence to the clearing (keep a stored point a
* nearer return hides, clear one the camera sees past).
*********************************************************************/
#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 ("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]
/// [m] Points this close to a face are not marked: an object cut by the image edge or the
/// noisy image border. 0.12 in the source; a wide band hides low objects near the lower FOV edge.
float attach_distance = 0.12f;
/**
* @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
* @param attach_d width of the attach band [m], see attach_distance
*/
void build(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, double min_d,
double max_d, bool optical, double attach_d = 0.12);
/// Inside all 6 faces (FrustumUtils::isInsideFRUSTUMwoAttach without the band test).
bool inside(const Eigen::Vector3f& p) const;
/// Within attach_distance of a face plane and within max_detect_distance + 0.5 m of the origin in XY.
bool nearFace(const Eigen::Vector3f& p) const;
};
/**
* @brief Nearest depth return per viewing ray of one observation, for the occlusion guard.
*
* Rays are binned by their tangent (x / z and y / z in the optical frame); each bin keeps the
* smallest range it saw. It is built from the whole cloud before the height gate: the floor the
* gate drops is exactly what shows that a stored point is no longer there.
*/
struct DepthCameraRangeImage
{
/// What the returns around the ray to a stored point say about it.
enum class Evidence
{
kNone, ///< no usable return around the ray, or a return at the point itself
kOccluded, ///< something nearer hides the point: clearing must keep it
kSeenThrough, ///< the camera sees past the point: it is gone
};
/// Empty image covering the frustum of a sensor at T_global_sensor.
void reset(const Eigen::Isometry3d& T_global_sensor, double fov_w, double fov_v, bool optical);
/// Adds one return given in the sensor frame.
void addSensorPoint(const Eigen::Vector3f& p);
/// Evidence about a point given in the global frame; kNone while the image is empty.
Evidence test(const Eigen::Vector3f& p_global) const;
bool empty() const
{
return min_range_.empty();
}
private:
Eigen::Vector3f toOptical(const Eigen::Vector3f& p) const;
/// Bin of a point in optical coordinates; false when it is too close or outside the image.
bool bin(const Eigen::Vector3f& q, int& u, int& v) const;
std::size_t index(int u, int v) const
{
return static_cast<std::size_t>(v + half_v_) * (2 * half_u_ + 1) + static_cast<std::size_t>(u + half_u_);
}
Eigen::Isometry3f sensor_from_global_ = Eigen::Isometry3f::Identity();
bool optical_ = true;
int half_u_ = 0;
int half_v_ = 0;
std::vector<float> min_range_; ///< [m] (2 half_u + 1) x (2 half_v + 1), +inf where nothing returned
};
/// 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;
DepthCameraRangeImage range; ///< whole cloud before the gate; empty unless occlusion_guard
};
/// 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]
double attach_distance = 0.12; ///< [m] marking-free band near each frustum face
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;
/// range_images[i] belongs to frustums[i]; null when that observation has no range image.
void clearMarkingByKdtree(const std::vector<Eigen::Vector3f>& cloud,
const std::vector<DepthCameraFrustum>& frustums,
const std::vector<const DepthCameraRangeImage*>& range_images, 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]
bool occlusion_guard_ = false; ///< depth-ray evidence in the clearing, see clearMarkingByKdtree
/// (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;
std::size_t kept_occluded = 0; ///< points the kd-tree test would clear, kept as hidden
std::size_t cleared_seen_through = 0; ///< points the kd-tree test would keep, cleared as seen past
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

@@ -0,0 +1,225 @@
#ifndef ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
#define ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_
#include <cmath>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <vector>
#include <robot_nav_msgs/OccupancyGrid.h>
namespace robot_costmap_2d
{
/** @brief Geometry of an unrotated grid in its global frame. */
struct DirectionGeometry
{
uint32_t width, height; ///< Grid dimensions [cells].
double resolution; ///< Cell size [m/cell].
double origin_x, origin_y; ///< Lower-left grid origin [m] in frame_id.
std::string frame_id; ///< Global coordinate frame.
};
/** @brief Reason a complete direction grid failed validation. */
enum class DirectionValidationError
{
kNone, kOverflow, kGeometry, kFrame, kOrientation, kSize, kCode
};
/** @brief Typed validation result with a human-readable offending value. */
struct DirectionValidationResult
{
DirectionValidationError error;
std::string message;
explicit operator bool() const { return error == DirectionValidationError::kNone; }
};
/** @brief Validate the entire message against the master geometry.
* @param grid Grid in the expected global frame. Codes are 0 for unconstrained
* and 1..8 for direction indices 0..7 in CCW order from +X:
* (+1,0), (+1,+1), (0,+1), (-1,+1), (-1,0), (-1,-1), (0,-1), (+1,-1).
* @param expected Required master dimensions, resolution [m/cell], origin [m], and frame.
* @return Typed error and description; empty data is valid after geometry checks.
* An identity quaternion or the default all-zero quaternion means no rotation.
*/
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
const DirectionGeometry& expected);
/** @brief Traverse a segment in grid coordinates with allocation-free 2D DDA.
* @param x0 Start x [cells] relative to the grid origin.
* @param y0 Start y [cells] relative to the grid origin.
* @param x1 End x [cells] relative to the grid origin.
* @param y1 End y [cells] relative to the grid origin.
* @param visitor Called in order with signed integer cell indices (x, y); return
* false to stop. The visitor must perform its own grid bounds checks.
* @return False for invalid coordinates or a visitor-requested stop.
* Cells own [x,x+1) x [y,y+1). Only positive-length overlaps are visited:
* a boundary-aligned segment belongs to the higher-index cell, a corner touch
* does not visit the adjacent cells, and an endpoint on a boundary does not
* visit the cell beyond it. A zero-length segment visits its point's cell.
* Coordinates must fit within the documented int64_t safety range.
*/
template <typename Visitor>
bool traverseGridSegment(double x0, double y0, double x1, double y1, Visitor&& visitor)
{
const double limit = static_cast<double>(std::numeric_limits<int64_t>::max()) / 2.0;
if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1) ||
std::abs(x0) >= limit || std::abs(y0) >= limit || std::abs(x1) >= limit || std::abs(y1) >= limit)
return false;
const long double dx = static_cast<long double>(x1) - x0;
const long double dy = static_cast<long double>(y1) - y0;
int64_t x = static_cast<int64_t>(std::floor(x0));
int64_t y = static_cast<int64_t>(std::floor(y0));
if (dx < 0 && x0 == std::floor(x0))
--x;
if (dy < 0 && y0 == std::floor(y0))
--y;
if (dx == 0 && dy == 0)
return visitor(x, y);
const int sx = (dx > 0) - (dx < 0);
const int sy = (dy > 0) - (dy < 0);
const long double adx = std::abs(dx);
const long double ady = std::abs(dy);
while (true)
{
if (!visitor(x, y))
return false;
// Recompute crossings from the original point to avoid accumulated error at corners.
const long double distance_x = sx ? std::abs((sx > 0 ? x + 1 : x) - static_cast<long double>(x0)) : 0;
const long double distance_y = sy ? std::abs((sy > 0 ? y + 1 : y) - static_cast<long double>(y0)) : 0;
const bool cross_x = sx && distance_x < adx;
const bool cross_y = sy && distance_y < ady;
if (!cross_x && !cross_y)
break;
if (!cross_y)
{
x += sx;
continue;
}
if (!cross_x)
{
y += sy;
continue;
}
const long double left = distance_x * ady;
const long double right = distance_y * adx;
if (left <= right)
x += sx;
if (right <= left)
y += sy;
}
return true;
}
/** @brief Return allowed direction indices for a displacement.
* @param dx Displacement along +X [m or cells] in the global/grid frame.
* @param dy Displacement along +Y [same units as dx] in the global/grid frame.
* @param max_deviation_rad Maximum inclusive angular deviation [rad], in (0, pi).
* @return Bit k is set when direction k accepts the displacement within relative tolerance.
*/
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad);
/** @brief Outcome of a world-space segment query. */
enum class SegmentResult
{
kAllowed, ///< All visited constrained cells permit the displacement.
kViolation, ///< At least one visited cell forbids the displacement.
kOutOfGrid ///< Any point is outside the grid or coordinates are invalid.
};
/** @brief First prohibited cell and world-frame segment displacement. */
struct SegmentViolation
{
uint32_t x, y; ///< Cell indices [cells] relative to the grid origin.
uint8_t code; ///< Direction code 1..8.
double dx, dy; ///< Segment displacement [m] in the global frame.
};
/** @brief Immutable validated grid, safe to share and hold for a whole search. */
class DirectionField
{
public:
DirectionField(const DirectionField&) = delete;
DirectionField& operator=(const DirectionField&) = delete;
/** @brief Validate and construct a field; invalid input returns null.
* @param grid Complete direction message in the global frame.
* @param expected Master grid geometry in the global frame.
* @param max_deviation_rad Maximum inclusive deviation [rad], in (0, pi).
* @param result Optional output explaining validation success or failure.
*/
static std::shared_ptr<const DirectionField> create(const robot_nav_msgs::OccupancyGrid& grid,
const DirectionGeometry& expected,
double max_deviation_rad,
DirectionValidationResult* result = nullptr);
/** @brief Return cell code: 0 unconstrained, 1..8 direction_index + 1.
* @param x Column [cells] from the grid origin; must be less than width.
* @param y Row [cells] from the grid origin; must be less than height.
* @pre Both indices are in bounds. Use codeAt() for untrusted indices.
*/
uint8_t code(uint32_t x, uint32_t y) const;
/** @brief Read a cell only when both signed indices are in bounds.
* @param x Column [cells] from the grid origin.
* @param y Row [cells] from the grid origin.
* @param code_out Output code; must not be null. Unchanged on failure.
* @return False for an out-of-grid index or null output pointer.
*/
bool codeAt(int64_t x, int64_t y, uint8_t* code_out) const;
/** @brief Return the immutable master geometry and global frame. */
const DirectionGeometry& geometry() const { return geometry_; }
/** @brief Return the immutable maximum angular deviation [rad]. */
double maxDeviationRad() const { return max_deviation_rad_; }
/** @brief True if at least one cell has a nonzero direction code. */
bool hasConstraints() const { return has_constraints_; }
/** @brief Check all owned cells traversed by a world-space segment.
* @param wx0 Start x [m] in the global frame.
* @param wy0 Start y [m] in the global frame.
* @param wx1 End x [m] in the global frame.
* @param wy1 End y [m] in the global frame.
* @param first Optional output populated on kViolation.
* @return kAllowed, kViolation, or kOutOfGrid; see SegmentResult.
*/
SegmentResult checkSegment(double wx0, double wy0, double wx1, double wy1,
SegmentViolation* first = nullptr) const;
private:
DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
double max_deviation_rad);
DirectionGeometry geometry_;
std::vector<uint8_t> codes_;
double max_deviation_rad_;
bool has_constraints_;
};
/** @brief Disabled, waiting for a current grid, or ready for queries. */
enum class DirectionFieldState { kDisabled, kPending, kReady };
/** @brief Consistent state and generation with an immutable, shared field.
* The field is non-null only in kReady. Readers may hold it through a whole
* search while the layer publishes a newer generation on another thread.
*/
struct DirectionFieldSnapshot
{
DirectionFieldState state = DirectionFieldState::kDisabled;
std::shared_ptr<const DirectionField> field;
uint64_t generation = 0;
};
/** @brief Core-side snapshot contract; avoids linking core against libplugins. */
class DirectionFieldProvider
{
public:
virtual ~DirectionFieldProvider() = default;
/** @brief Return a consistent snapshot safe to retain on a planner thread. */
virtual DirectionFieldSnapshot directionSnapshot() const = 0;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DIRECTION_FIELD_H_

View File

@@ -1,40 +1,73 @@
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_V1_H_
#ifndef ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
#define ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
#include <robot_costmap_2d/static_layer.h>
#include <robot_nav_msgs/Path.h>
#include <chrono>
#include <mutex>
#include <string>
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/layer.h>
namespace robot_costmap_2d
{
class DirectionalLayer : public StaticLayer
{
public:
DirectionalLayer();
virtual ~DirectionalLayer();
bool laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan);
void resetMap();
/** @brief Publish immutable direction snapshots without modifying master costs.
* The host thread feeds map and direction messages through dataCallBack(); the
* costmap update thread calls updateBounds()/updateCosts(); planner threads use
* directionSnapshot() and may retain a snapshot for an entire search.
* When both mutexes are required, acquire the master costmap mutex before the
* layer mutex, never the reverse. Snapshot readers hold only the layer mutex
* briefly. Layer::isCurrent() still reads the legacy non-atomic current_ flag.
*/
class DirectionalLayer : public Layer, public DirectionFieldProvider
{
public:
DirectionalLayer();
~DirectionalLayer() override = default;
/** @brief Identify this plugin as a directional layer. */
LayerType getType() const override { return LayerType::DIRECTIONAL_LAYER; }
/** @brief Copy a consistent immutable snapshot for a planner thread. */
DirectionFieldSnapshot directionSnapshot() const override;
/** @brief Update thread: leave bounds unchanged and report a stuck pending state.
* @param robot_x Robot x [m] in the global frame.
* @param robot_y Robot y [m] in the global frame.
* @param robot_yaw Robot yaw [rad] in the global frame.
* @param min_x Lower x bound [m] in the global frame.
* @param min_y Lower y bound [m] in the global frame.
* @param max_x Upper x bound [m] in the global frame.
* @param max_y Upper y bound [m] in the global frame.
*/
void updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x, double* min_y,
double* max_x, double* max_y) override;
/** @brief Update thread: leave master costs unchanged.
* @param master Master costmap in the global frame.
* @param min_i Lower x cell index relative to the grid origin.
* @param min_j Lower y cell index relative to the grid origin.
* @param max_i Upper x cell index relative to the grid origin.
* @param max_j Upper y cell index relative to the grid origin.
*/
void updateCosts(Costmap2D& /*master*/, int /*min_i*/, int /*min_j*/, int /*max_i*/, int /*max_j*/) override {}
/** @brief Resize path: invalidate an enabled layer's snapshot. */
void matchSize() override;
/** @brief Retain a ready snapshot if master geometry [m, cells, frame] is unchanged. */
void reset() override;
LayerType getType() const override
{
return LayerType::DIRECTIONAL_LAYER;
}
private:
void incomingMap(const robot_nav_msgs::OccupancyGrid &new_map);
bool laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path);
unsigned char laneFilter(unsigned int x, unsigned int y, double yaw_robot);
void laneFilter(std::vector<unsigned int> x, std::vector<unsigned int> y, std::vector<double> yaw_robot);
void laneFilter(std::vector<std::pair<unsigned int, double>> x, std::vector<std::pair<unsigned int, double>> y, std::vector<double> yaw_robot);
bool inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance);
void convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th);
bool getRobotPose(double &x, double &y, double &yaw);
protected:
/** @brief Load plugin configuration and establish its initial state. */
void onInitialize() override;
/** @brief Host thread: process static-map and direction-grid callbacks. */
void handleImpl(const void* data, const std::type_info& type, const std::string& topic) override;
std::vector<std::array<uint16_t, 2>> directional_areas_;
double pose_x_, pose_y_, pose_yaw_;
double distance_skip_ = 1.0;
// ros::Publisher lane_mask_pub_;
robot_nav_msgs::OccupancyGrid new_map_;
};
}
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_
private:
DirectionGeometry geometry() const;
void publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field = {});
mutable std::mutex mutex_;
DirectionFieldSnapshot snapshot_;
bool seen_map_;
bool debug_state_;
bool rolling_;
double max_deviation_rad_; ///< Maximum angular deviation [rad].
std::string map_topic_, direction_topic_;
std::chrono::steady_clock::time_point pending_since_, last_pending_log_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_DIRECTIONAL_LAYER_H_

View File

@@ -56,7 +56,10 @@ enum class LayerType
DIRECTIONAL_LAYER,
PREFERRED_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;

View File

@@ -38,6 +38,7 @@
#ifndef ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
#define ROBOT_COSTMAP_2D_LAYERED_COSTMAP_H_
#include <robot_costmap_2d/direction_field.h>
#include <robot_costmap_2d/cost_values.h>
#include <robot_costmap_2d/layer.h>
#include <robot_costmap_2d/costmap_2d.h>
@@ -99,6 +100,9 @@ public:
bool isCurrent();
/** Consistent snapshot; plugin list must be fixed before concurrent reads. */
DirectionFieldSnapshot getDirectionFieldSnapshot() const;
Costmap2D* getCostmap()
{
return &costmap_;

View File

@@ -34,7 +34,6 @@
#include <robot_geometry_msgs/Point.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <utility>
@@ -42,142 +41,6 @@
namespace robot_costmap_2d
{
/**
* @brief A depth frame and its per-source frustum-clearing configuration.
*
* The message is shared so returning buffered observations does not copy the
* full depth image on every costmap update.
*/
/// Per-observation-source configuration of the depth-image frustum clearing,
/// loaded by ObstacleLayer from the source's YAML/ROS params and carried with
/// each DepthCameraObservation.
struct DepthFrustumConfig
{
unsigned int pixel_step = 0;
double min_range = 0.0;
double max_range = 0.0;
/// 3D clearing rays stop this far [m] before the measured surface.
/// Negative: legacy 2 * costmap resolution.
double skip_distance = -1.0;
/// Full-column clearing from the per-pixel-column nearest in-band return.
bool column_clearing = false;
/// Height band [m] used for the in-band test; floor returns below min do
/// not shorten the beam. max < 0: use the layer max_obstacle_height.
double column_min_height = 0.10;
double column_max_height = -1.0;
/// Column beams stop this far [m] before the nearest in-band return.
double column_skip_distance = 0.02;
/// Full columns are only cleared beyond this distance [m]. Negative:
/// derive each frame from the camera intrinsics and mounting pose.
double column_cover_distance = -1.0;
/// Depth-image columns at the LEFT edge excluded from clearing [px]. Covers
/// the stereo no-disparity strip that is permanently invalid there: those
/// pixels carry no free-space evidence, so clearing through them erases
/// obstacles that rotate out of the FOV on that side. Set to the measured
/// width of the black strip in the raw depth image (a few px margin). 0
/// disables. Invalid pixels ELSEWHERE still clear (needed for ghost removal).
unsigned int clear_left_border_px = 0;
/// Same as clear_left_border_px but for the RIGHT edge, for cameras whose
/// stereo no-disparity strip sits on the right instead of the left. Measured
/// from the last image column inward. 0 disables.
unsigned int clear_right_border_px = 0;
};
class DepthCameraObservation
{
public:
DepthCameraObservation()
: data_handle_(),
data_(nullptr),
topic_()
{
}
DepthCameraObservation(
const robot_sensor_msgs::DepthCameraData& data,
std::string topic,
const robot::Time& received_time,
const DepthFrustumConfig& frustum)
: data_handle_(boost::make_shared<robot_sensor_msgs::DepthCameraData>(data)),
data_(data_handle_.get()),
topic_(std::move(topic)),
received_time_(received_time),
frustum_(frustum)
{
}
DepthCameraObservation(
robot_sensor_msgs::DepthCameraData::ConstPtr data,
std::string topic,
const robot::Time& received_time,
const DepthFrustumConfig& frustum)
: data_handle_(std::move(data)),
data_(data_handle_.get()),
topic_(std::move(topic)),
received_time_(received_time),
frustum_(frustum)
{
}
DepthCameraObservation(const DepthCameraObservation& other)
: data_handle_(other.data_handle_),
data_(data_handle_.get()),
topic_(other.topic_),
received_time_(other.received_time_),
frustum_(other.frustum_)
{
}
DepthCameraObservation(DepthCameraObservation&& other) noexcept
: data_handle_(std::move(other.data_handle_)),
data_(data_handle_.get()),
topic_(std::move(other.topic_)),
received_time_(other.received_time_),
frustum_(other.frustum_)
{
other.data_ = nullptr;
other.frustum_ = DepthFrustumConfig();
}
DepthCameraObservation& operator=(const DepthCameraObservation& other)
{
if (this == &other)
return *this;
data_handle_ = other.data_handle_;
data_ = data_handle_.get();
topic_ = other.topic_;
received_time_ = other.received_time_;
frustum_ = other.frustum_;
return *this;
}
DepthCameraObservation& operator=(DepthCameraObservation&& other) noexcept
{
if (this == &other)
return *this;
data_handle_ = std::move(other.data_handle_);
data_ = data_handle_.get();
topic_ = std::move(other.topic_);
received_time_ = other.received_time_;
frustum_ = other.frustum_;
other.data_ = nullptr;
other.frustum_ = DepthFrustumConfig();
return *this;
}
~DepthCameraObservation() = default;
robot_sensor_msgs::DepthCameraData::ConstPtr data_handle_;
const robot_sensor_msgs::DepthCameraData* data_;
std::string topic_;
robot::Time received_time_;
DepthFrustumConfig frustum_;
};
/**
* @brief Stores an observation in terms of a point cloud and the origin of the source
* @note Tried to make members and constructor arguments const but the compiler would not accept the default

View File

@@ -75,12 +75,6 @@ public:
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance);
ObservationBuffer(std::string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, const DepthFrustumConfig& frustum_config,
tf3::BufferCore& tf3_buffer, std::string global_frame,
std::string sensor_frame, double tf_tolerance);
/**
@@ -104,24 +98,12 @@ public:
*/
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
* @param observations The vector to be filled
*/
void getObservations(std::vector<Observation>& observations);
/**
* @brief Append the current depth observation, if it has not expired.
*/
void getDepthObservations(std::vector<DepthCameraObservation>& observations);
/**
* @brief Check if the observation buffer is being update at its expected rate
* @return True if it is being updated at the expected rate, false otherwise
@@ -155,8 +137,6 @@ private:
*/
void purgeStaleObservations();
void purgeStaleDepthObservations();
tf3::BufferCore& tf3_buffer_;
const robot::Duration observation_keep_time_;
const robot::Duration expected_update_rate_;
@@ -164,14 +144,11 @@ private:
std::string global_frame_;
std::string sensor_frame_;
std::list<Observation> observation_list_;
std::list<DepthCameraObservation> depth_observation_list_;
// DepthCameraObservation depth_observation_;
std::string topic_name_;
double min_obstacle_height_, max_obstacle_height_;
boost::recursive_mutex lock_; ///< @brief A lock for accessing data in callbacks safely
double obstacle_range_, raytrace_range_;
double tf_tolerance_;
DepthFrustumConfig frustum_config_;
};
} // namespace robot_costmap_2d
#endif // ROBOT_COSTMAP_2D_OBSERVATION_BUFFER_H_

View File

@@ -48,7 +48,6 @@
#include <mutex>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <robot_sensor_msgs/LaserScan.h>
#include <robot_laser_geometry/laser_geometry.hpp>
#include <robot_sensor_msgs/PointCloud.h>
@@ -131,12 +130,6 @@ protected:
void pointCloud2Callback(const robot_sensor_msgs::PointCloud2& message,
const boost::shared_ptr<robot_costmap_2d::ObservationBuffer>& buffer);
/**
* @brief Buffer a depth image and its camera model for frustum clearing.
*/
void depthImageCallback(robot_sensor_msgs::DepthCameraData::ConstPtr message,
const boost::shared_ptr<robot_costmap_2d::ObservationBuffer>& buffer);
/**
* @brief Get the observations used to mark space
* @param marking_observations A reference to a vector that will be populated with the observations
@@ -151,13 +144,6 @@ protected:
*/
bool getClearingObservations(std::vector<robot_costmap_2d::Observation>& clearing_observations) const;
/**
* @brief Collect fresh depth frames from every configured frustum-clearing source.
* @return True when every configured depth source is current.
*/
bool getFrustumClearingObservations(
std::vector<robot_costmap_2d::DepthCameraObservation>& frustum_clearing_observations) const;
/**
* @brief Clear freespace based on one observation
* @param clearing_observation The observation used to raytrace
@@ -186,9 +172,6 @@ protected:
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > marking_buffers_; ///< @brief Used to store observation buffers used for marking obstacles
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > clearing_buffers_; ///< @brief Used to store observation buffers used for clearing obstacles
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > depth_observation_buffers_;
std::vector<boost::shared_ptr<robot_costmap_2d::ObservationBuffer> > depth_clearing_buffers_;
// Used only for testing purposes
std::vector<robot_costmap_2d::Observation> static_clearing_observations_, static_marking_observations_;
@@ -197,10 +180,6 @@ protected:
int combination_method_;
std::vector<CallBackInfo> callback_infos_;
std::vector<CallBackInfo> callback_depth_infos_;
std::string depth_camera_data_topic_;
mutable std::mutex depth_camera_data_mutex_;
robot_sensor_msgs::DepthCameraData::ConstPtr pending_depth_camera_data_;
private:
bool getParams(const std::string& config_file_name, robot::NodeHandle &nh);

View File

@@ -43,6 +43,7 @@
#include <robot_nav_msgs/OccupancyGrid.h>
#include <robot_map_msgs/OccupancyGridUpdate.h>
#include <chrono>
#include <string>
namespace robot_costmap_2d
@@ -76,14 +77,16 @@ protected:
virtual unsigned char interpretValue(unsigned char value);
virtual void incomingMap(const robot_nav_msgs::OccupancyGrid& new_map);
virtual void incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update);
/// Called under the master costmap mutex after a nonempty region has been written.
void markMapWritten(int min_i, int min_j, int max_i, int max_j);
unsigned char* threshold_;
std::string base_frame_id_;
std::string global_frame_; ///< @brief The global frame for the costmap
std::string map_frame_; /// @brief frame that map is located in
std::string map_topic_; // Hiep thêm vào mục đich phân biết zones
bool subscribe_to_updates_;
bool map_received_;
bool has_updated_data_;
bool map_received_ = false;
bool has_updated_data_ = false;
unsigned int x_, y_, width_, height_;
bool track_unknown_space_;
bool use_maximum_;
@@ -91,6 +94,7 @@ protected:
bool trinary_costmap_;
bool map_shutdown_ = false;
bool map_update_shutdown_ = false;
std::chrono::steady_clock::time_point last_invalid_update_log_;
unsigned char lethal_threshold_, unknown_cost_value_;
private:

View File

@@ -94,65 +94,15 @@ private:
void clearNonLethal(double wx, double wy, double w_size_x, double w_size_y, bool clear_no_info);
virtual void raytraceFreespace(const robot_costmap_2d::Observation& clearing_observation, double* min_x, double* min_y,
double* max_x, double* max_y);
// bool raytraceDepthFrustum(double* min_x, double* min_y, double* max_x, double* max_y);
bool raytraceDepthFrustum(const robot_costmap_2d::DepthCameraObservation& observation,
double* min_x, double* min_y, double* max_x, double* max_y);
bool readDepthMeters(const robot_sensor_msgs::Image& depth, unsigned int u, unsigned int v,
double& depth_m, bool& is_valid) const;
void updateDepthRayCache(unsigned int width, unsigned int height, unsigned int pixel_step,
double fx, double fy, double cx, double cy);
bool clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz);
bool clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
double raytrace_range, unsigned int cell_raytrace_range,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clearDepthColumns(double ox, double oy, double cover_distance, double far_distance,
double min_range, double max_range, double skip_dist,
double* min_x, double* min_y, double* max_x, double* max_y);
bool clipColumnSegment(double& sx, double& sy, double& ex, double& ey) const;
bool publish_voxel_;
robot_voxel_grid::VoxelGrid robot_voxel_grid_;
double z_resolution_, origin_z_;
/// Scratch for the full-column clearing pass (config lives per observation
/// source in DepthFrustumConfig): per depth-image pixel column, the nearest
/// return inside the obstacle height band certifies "no obstacle in this
/// direction closer than d". Cells along that 2D beam get their whole voxel
/// column cleared, removing marked voxels the per-pixel 3D rays cannot
/// reach (above the vertical FOV at close range).
struct DepthColumnStat
{
double min_band_dist = -1.0; ///< horizontal distance of nearest in-band return; < 0 = none
double azimuth = 0.0; ///< beam direction in the global frame
double best_row_delta = std::numeric_limits<double>::infinity();
bool has_ray = false; ///< column had at least one readable pixel
bool in_border = false; ///< column lies in a left/right no-disparity strip
};
std::vector<DepthColumnStat> depth_column_stats_;
unsigned int unknown_threshold_, mark_threshold_, size_z_;
robot_sensor_msgs::PointCloud clearing_endpoints_;
std::vector<unsigned char> rolling_costmap_scratch_;
std::vector<unsigned int> rolling_voxel_scratch_;
struct DepthRay
{
unsigned int u;
unsigned int v;
unsigned int col; ///< pixel-column index in the cache (border column included)
double x;
double y;
double z;
};
std::vector<DepthRay> depth_ray_cache_;
unsigned int cached_column_count_ = 0;
unsigned int cached_depth_width_ = 0;
unsigned int cached_depth_height_ = 0;
unsigned int cached_depth_pixel_step_ = 0;
double cached_fx_ = 0.0;
double cached_fy_ = 0.0;
double cached_cx_ = 0.0;
double cached_cy_ = 0.0;
inline bool worldToMap3DFloat(double wx, double wy, double wz, double& mx, double& my, double& mz)
{
if (wx < origin_x_ || wy < origin_y_ || wz < origin_z_)

View File

@@ -20,6 +20,8 @@
<buildtool_depend version_gte="0.5.68">catkin</buildtool_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>
<build_depend>robot_std_msgs</build_depend>

View File

@@ -30,6 +30,7 @@ void CriticalLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int mi
StaticLayer::CostmapLayer::updateWithOverwrite(master_grid, min_i, min_j, max_i, max_j);
else
updateWithMax(master_grid, min_i, min_j, max_i, max_j);
markMapWritten(min_i, min_j, max_i, max_j);
}
@@ -42,4 +43,4 @@ static boost::shared_ptr<Layer> create_critical_plugin() {
BOOST_DLL_ALIAS(create_critical_plugin, CriticalLayer)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,428 +1,230 @@
#include <robot_costmap_2d/directional_layer.h>
#include <data_convert/data_convert.h>
#include <tf3/convert.h>
#include <tf3/utils.h>
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <filesystem>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <utility>
#include <boost/dll/alias.hpp>
#include <boost/thread/locks.hpp>
#include <yaml-cpp/yaml.h>
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
using robot_costmap_2d::CRITICAL_SPACE;
using robot_costmap_2d::LETHAL_OBSTACLE;
using robot_costmap_2d::NO_INFORMATION;
#include <robot/console.h>
#include <robot/node_handle.h>
#include <robot_costmap_2d/utils.h>
namespace robot_costmap_2d
{
DirectionalLayer::DirectionalLayer()
{}
DirectionalLayer::~DirectionalLayer() {}
namespace
{
constexpr auto kPendingErrorDelay = std::chrono::seconds(5);
constexpr auto kPendingErrorPeriod = std::chrono::seconds(5);
bool DirectionalLayer::laneFilter(const std::vector<robot_geometry_msgs::PoseStamped> plan)
bool topicMatches(const std::string& topic, const std::string& configured)
{
return topic == configured || topic == "/" + configured;
}
const char* stateName(DirectionFieldState state)
{
switch (state)
{
if (directional_areas_.empty())
throw "Has no map data";
robot_nav_msgs::Path path;
path.header.stamp = robot::Time::now();
path.header.frame_id = map_frame_;
path.poses = plan;
return this->laneFilter(directional_areas_, path);
case DirectionFieldState::kDisabled:
return "DISABLED";
case DirectionFieldState::kPending:
return "PENDING";
case DirectionFieldState::kReady:
return "READY";
}
return "unknown";
}
} // namespace
DirectionalLayer::DirectionalLayer()
: Layer(), mutex_(), snapshot_(), seen_map_(false), debug_state_(true), rolling_(false), max_deviation_rad_(M_PI / 2.0),
map_topic_("map"), direction_topic_("direction_map"), pending_since_(), last_pending_log_()
{
}
void DirectionalLayer::onInitialize()
{
robot::NodeHandle nh("~");
robot::NodeHandle priv_nh(nh, name_);
const std::string filename = "directional_layer_params.yaml";
double max_deviation_deg = 90.0;
try
{
const char* env = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
const std::string folder = env && std::filesystem::exists(env) ? env : "";
const YAML::Node layer = YAML::LoadFile(getSourceFile(folder, filename))["directional_layer"];
enabled_ = loadParam(layer, "enabled", false);
map_topic_ = loadParam(layer, "map_topic", std::string("map"));
direction_topic_ = loadParam(layer, "direction_topic", std::string("direction_map"));
max_deviation_deg = loadParam(layer, "max_deviation_deg", 90.0);
debug_state_ = loadParam(layer, "debug_state", true);
if (priv_nh.hasParam("enabled"))
priv_nh.getParam("enabled", enabled_, enabled_);
if (priv_nh.hasParam("map_topic"))
priv_nh.getParam("map_topic", map_topic_);
if (priv_nh.hasParam("direction_topic"))
priv_nh.getParam("direction_topic", direction_topic_);
if (priv_nh.hasParam("max_deviation_deg"))
priv_nh.getParam("max_deviation_deg", max_deviation_deg);
if (priv_nh.hasParam("debug_state"))
priv_nh.getParam("debug_state", debug_state_);
}
catch (const YAML::BadFile&)
{
throw std::runtime_error("DirectionalLayer " + name_ + ": cannot open the default file " + filename);
}
if (!std::isfinite(max_deviation_deg) || max_deviation_deg <= 0.0 || max_deviation_deg >= 180.0)
throw std::runtime_error("DirectionalLayer " + name_ + ": max_deviation_deg must be finite and in (0, 180)");
if (max_deviation_deg < 22.5)
robot::log_warning("DirectionalLayer %s: max_deviation_deg < 22.5 may leave SBPL without a path", name_.c_str());
max_deviation_rad_ = (max_deviation_deg / 180.0) * M_PI;
// Preserve the open interval even when conversion rounds at an extreme value.
if (max_deviation_rad_ <= 0.0)
max_deviation_rad_ = std::nextafter(0.0, M_PI);
else if (max_deviation_rad_ >= M_PI)
max_deviation_rad_ = std::nextafter(M_PI, 0.0);
rolling_ = layered_costmap_->isRolling();
if (enabled_ && rolling_)
robot::log_error("DirectionalLayer %s: rolling costmap is unsupported", name_.c_str());
if (enabled_ && (map_topic_.empty() || direction_topic_.empty() || topicMatches(map_topic_, direction_topic_) ||
topicMatches(direction_topic_, map_topic_)))
throw std::runtime_error("DirectionalLayer " + name_ + ": topics must be nonempty and distinct");
robot::log_info("DirectionalLayer %s: enabled=%d map_topic=%s direction_topic=%s max_deviation_deg=%g debug_state=%d",
name_.c_str(), enabled_, map_topic_.c_str(), direction_topic_.c_str(), max_deviation_deg, debug_state_);
std::lock_guard<std::mutex> lock(mutex_);
publishLocked(enabled_ ? DirectionFieldState::kPending : DirectionFieldState::kDisabled);
}
void DirectionalLayer::publishLocked(DirectionFieldState state, std::shared_ptr<const DirectionField> field)
{
snapshot_.state = state;
snapshot_.field = std::move(field);
++snapshot_.generation;
// Layer::isCurrent() reads this non-atomic bool without this mutex (legacy API limitation).
current_ = state != DirectionFieldState::kPending;
if (state == DirectionFieldState::kPending)
{
pending_since_ = std::chrono::steady_clock::now();
last_pending_log_ = {};
}
if (debug_state_)
robot::log_info("[debug] DirectionalLayer %s: %s generation=%llu", name_.c_str(), stateName(state),
static_cast<unsigned long long>(snapshot_.generation));
}
DirectionFieldSnapshot DirectionalLayer::directionSnapshot() const
{
std::lock_guard<std::mutex> lock(mutex_);
return snapshot_;
}
DirectionGeometry DirectionalLayer::geometry() const
{
const auto* master = layered_costmap_->getCostmap();
return {master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
master->getOriginX(), master->getOriginY(), layered_costmap_->getGlobalFrameID()};
}
void DirectionalLayer::handleImpl(const void* data, const std::type_info& type, const std::string& topic)
{
if (!enabled_ || type != typeid(robot_nav_msgs::OccupancyGrid) ||
(!topicMatches(topic, map_topic_) && !topicMatches(topic, direction_topic_)))
return;
if (topicMatches(topic, map_topic_))
{
std::lock_guard<std::mutex> lock(mutex_);
seen_map_ = true;
publishLocked(DirectionFieldState::kPending);
return;
}
void DirectionalLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
DirectionGeometry expected;
uint64_t generation;
{
if(!map_shutdown_)
{
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
robot::log_info("Received a %d X %d map at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
// resize costmap if size, resolution or origin do not match
Costmap2D *master = layered_costmap_->getCostmap();
if (!layered_costmap_->isRolling() &&
(master->getSizeInCellsX() != size_x / 2 ||
master->getSizeInCellsY() != size_y / 2 ||
master->getResolution() != new_map.info.resolution ||
master->getOriginX() != new_map.info.origin.position.x ||
master->getOriginY() != new_map.info.origin.position.y))
{
// Update the size of the layered costmap (and all layers, including this one)
robot::log_info("Resizing costmap to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
layered_costmap_->resizeMap(size_x / 2, size_y / 2, new_map.info.resolution, new_map.info.origin.position.x,
new_map.info.origin.position.y,
true /* set size_locked to true, prevents reconfigureCb from overriding map size*/);
}
else if (size_x_ != size_x / 2 || size_y_ != size_y / 2 ||
resolution_ != new_map.info.resolution ||
origin_x_ != new_map.info.origin.position.x ||
origin_y_ != new_map.info.origin.position.y)
{
// only update the size of the costmap stored locally in this layer
robot::log_info("Resizing static layer to %d X %d at %f m/pix\n", size_x / 2, size_y / 2, new_map.info.resolution);
resizeMap(size_x / 2, size_y / 2, new_map.info.resolution,
new_map.info.origin.position.x, new_map.info.origin.position.y);
}
unsigned char values[4];
directional_areas_.clear();
directional_areas_.resize(size_x / 2 * size_y / 2);
// initialize the costmap with static data
for (unsigned int iy = 0; iy < size_y; iy += 2)
{
for (unsigned int ix = 0; ix < size_x; ix += 2)
{
values[0] = new_map.data[MAP_IDX(size_x, ix, iy)];
values[1] = new_map.data[MAP_IDX(size_x, ix + 1, iy)];
values[2] = new_map.data[MAP_IDX(size_x, ix, iy + 1)];
values[3] = new_map.data[MAP_IDX(size_x, ix + 1, iy + 1)];
uint32_t color_avg = (uint32_t)(values[0] | values[1] << 8u | values[2] << 16u | values[3] << 24u);
int index = getIndex(ix / 2, iy / 2);
directional_areas_[index][0] = (uint16_t)(color_avg & 0xfff);
directional_areas_[index][1] = (uint16_t)(color_avg >> 12u);
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
}
}
map_frame_ = new_map.header.frame_id;
// we have a new map, update full size of map
x_ = y_ = 0;
width_ = size_x_;
height_ = size_y_;
map_received_ = true;
has_updated_data_ = true;
new_map_.header = new_map.header;
new_map_.header.stamp = robot::Time::now();
new_map_.info = new_map.info;
new_map_.info.width = width_;
new_map_.info.height = height_;
}
else
{
robot::log_info("Stop receive new map!\n");
}
// shutdown the map subscrber if firt_map_only_ flag is on
if (first_map_only_)
{
robot::log_info("Shutting down the map subscriber. first_map_only flag is on\n");
map_shutdown_ = true;
// map_sub_.shutdown();
}
}
bool DirectionalLayer::laneFilter(std::vector<std::array<uint16_t, 2>> new_map, const robot_nav_msgs::Path path)
{
boost::unique_lock<mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
if (new_map.empty())
return false;
std::vector<std::pair<unsigned int, double>> X_List, Y_List;
std::vector<double> Yaw_list;
const robot_geometry_msgs::PoseStamped &e = path.poses.back();
bool get_success = getRobotPose(pose_x_, pose_y_, pose_yaw_);
if(!get_success) return false;
for (auto it = path.poses.begin(); it != path.poses.end(); ++it)
{
const robot_geometry_msgs::PoseStamped &p = *it; // Get the pose from the iterator
unsigned int mx, my;
if (!worldToMap(p.pose.position.x, p.pose.position.y, mx, my))
{
robot::log_error("ERROR: trying to set a start cell %f %f that is outside of map\n", p.pose.position.x, p.pose.position.y);
return false;
}
// Convert to yaw
tf3::Quaternion quaternion = data_convert::convertQuaternion(p.pose.orientation);
double theta = tf3::getYaw(quaternion);
unsigned char value = laneFilter(mx, my, theta);
if (get_success)
{
if (
(!inSkipErea(pose_x_, pose_y_, p.pose.position.x, p.pose.position.y, distance_skip_) &
!inSkipErea(p.pose.position.x, p.pose.position.y, e.pose.position.x, e.pose.position.y, distance_skip_))
|| p == path.poses.back()
)
{
if (value == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || value == robot_costmap_2d::LETHAL_OBSTACLE)
{
std::pair<unsigned int, double> x_val(mx, p.pose.position.x);
std::pair<unsigned int, double> y_val(my, p.pose.position.y);
X_List.push_back(x_val);
Y_List.push_back(y_val);
Yaw_list.push_back(theta);
// costmap_[getIndex(mx, my)] = value;
}
}
}
}
if (!Yaw_list.empty())
{
laneFilter(X_List, Y_List, Yaw_list);
robot_nav_msgs::OccupancyGrid lanes;
convertToMap(costmap_, lanes, 0.65, 0.196);
return false;
}
return true;
}
void DirectionalLayer::convertToMap(unsigned char *costmap, robot_nav_msgs::OccupancyGrid &dir_map, double occ_th, double free_th)
{
dir_map.header = new_map_.header;
dir_map.header.stamp = robot::Time::now();
dir_map.info = new_map_.info;
int size_costmap = new_map_.info.width * new_map_.info.height;
dir_map.data.resize(size_costmap);
for (int i = 0; i < size_costmap; i++)
{
int8_t value;
if (costmap[i] == robot_costmap_2d::NO_INFORMATION)
{
value = -1;
}
else
{
double occ = (costmap[i]) / 255.0;
if (occ > occ_th)
value = +100;
else if (occ < free_th)
value = 0;
else
{
double ratio = (occ - free_th) / (occ_th - free_th);
value = 1 + 98 * ratio;
}
}
dir_map.data[i] = value;
}
}
unsigned char DirectionalLayer::laneFilter(unsigned int x, unsigned int y, double yaw_robot)
{
double yaw_lane;
unsigned char cost = robot_costmap_2d::NO_INFORMATION;
int index = getIndex(x, y);
for (auto &lane : directional_areas_[index])
{
if (lane > 359)
{
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
}
else
{
double yaw_lane = (double)lane / 180 * M_PI;
if (0.4 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= 1.0)
cost = std::min(cost, robot_costmap_2d::FREE_SPACE);
else if (-1.0 <= cos(yaw_robot - yaw_lane) && cos(yaw_robot - yaw_lane) <= -0.4)
cost = std::min(cost, robot_costmap_2d::LETHAL_OBSTACLE);
else
cost = std::min(cost, robot_costmap_2d::NO_INFORMATION);
}
}
return cost;
}
void DirectionalLayer::laneFilter(std::vector<std::pair<unsigned int, double>> x,
std::vector<std::pair<unsigned int, double>> y,
std::vector<double> yaw_robot)
{
if(x.empty() || y.empty() || yaw_robot.empty())
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
std::lock_guard<std::mutex> lock(mutex_);
if (rolling_)
return;
unsigned int x_min, y_min, x_max, y_max;
double x_min_w, y_min_w, x_max_w, y_max_w;
x_min = x.front().first; y_min = y.front().first;
x_max = x.front().first; y_max = y.front().first;
x_min_w = x.front().second; y_min_w = y.front().second;
x_max_w = x.front().second; y_max_w = y.front().second;
for (int i = 1; i < yaw_robot.size(); i++)
if (!seen_map_)
{
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
continue;
x_min = std::min(x_min, x[i].first);
y_min = std::min(y_min, y[i].first);
x_max = std::max(x_max, x[i].first);
y_max = std::max(y_max, y[i].first);
x_min_w = std::min(x_min_w, x[i].second);
y_min_w = std::min(y_min_w, y[i].second);
x_max_w = std::max(x_max_w, x[i].second);
y_max_w = std::max(y_max_w, y[i].second);
}
for (int i = 0; i < yaw_robot.size(); i++)
{
if(inSkipErea(pose_x_, pose_y_, x[i].second, y[i].second, distance_skip_))
continue;
double yaw_rad = (double)yaw_robot[i] / 180 * M_PI;
if (fabs(cos(yaw_rad)) > fabs(sin(yaw_rad)))
{
int x_ = x[i].first;
// Dưới lên trên
for (int j = y[i].first; j <= y_max; j++)
{
int y_ = j;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
// Trên xuống dưới
for (int k = y[i].first; k >= y_min; k--)
{
int y_ = k;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
int y_ = y[i].first;
// Phải qua trái
for (int j = x[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsX(); j++)
{
int x_ = j;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
// Trái qua phải
for (int k = x[i].first; k >= 0; k--)
{
int x_ = k;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
}
else if(fabs(cos(yaw_rad)) < fabs(sin(yaw_rad)))
{
int y_ = y[i].first;
// Phải qua trái
for (int j = x[i].first; j <= x_max; j++)
{
int x_ = j;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
// Trái qua phải
for (int k = x[i].first; k >= x_min; k--)
{
int x_ = k;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
int x_ = x[i].first;
// Dưới lên trên
for (int j = y[i].first; j < layered_costmap_->getCostmap()->getSizeInCellsY(); j++)
{
int y_ = j;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
// Trên xuống dưới
for (int k = y[i].first; k >= 0; k--)
{
int y_ = k;
if (costmap_[getIndex(x_, y_)] == robot_costmap_2d::LETHAL_OBSTACLE)
continue;
unsigned char value = laneFilter(x_, y_, yaw_robot[i]);
if (value >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && value != robot_costmap_2d::NO_INFORMATION)
costmap_[getIndex(x_, y_)] = value;
else
break;
}
}
robot::log_error("DirectionalLayer %s: direction grid arrived before static map", name_.c_str());
return;
}
expected = geometry();
generation = snapshot_.generation;
}
void DirectionalLayer::resetMap()
DirectionValidationResult validation;
auto field = DirectionField::create(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data), expected,
max_deviation_rad_, &validation);
if (!field)
{
unsigned int size_x = layered_costmap_->getCostmap()->getSizeInCellsX();
unsigned int size_y = layered_costmap_->getCostmap()->getSizeInCellsY();
for (unsigned int iy = 0; iy < size_y; iy++)
{
for (unsigned int ix = 0; ix < size_x; ix++)
{
int index = getIndex(ix, iy);
costmap_[index] = robot_costmap_2d::NO_INFORMATION;
}
}
robot::log_error("DirectionalLayer %s: invalid direction grid: %s", name_.c_str(), validation.message.c_str());
return;
}
bool DirectionalLayer::getRobotPose(double &x, double &y, double &yaw)
// resizeMap holds the master mutex through matchSize(), which increments generation.
std::lock_guard<std::mutex> lock(mutex_);
if (snapshot_.generation != generation)
{
tf3::TransformStampedMsg transformMsg;
try
{
transformMsg = tf_->lookupTransform(map_frame_, base_frame_id_, tf3::Time());
// listener_.lookupTransform(map_frame_, base_frame_id_, tf3::Time(), transform);
}
catch (tf3::TransformException &ex)
{
robot::log_error("%s\n", ex.what());
return false;
}
// Copy map data given proper transformations
tf3::Transform tf3_transform;
tf3_transform = data_convert::convertTotf3Transform(transformMsg.transform);
x = tf3_transform.getOrigin().x();
y = tf3_transform.getOrigin().y();
// Extract the rotation as a quaternion from the transform
tf3::Quaternion rotation = tf3_transform.getRotation();
// Convert the quaternion to a yaw angle (in radians)
yaw = tf3::getYaw(rotation);
return true;
robot::log_error("DirectionalLayer %s: grid discarded because map state changed during validation", name_.c_str());
return;
}
publishLocked(DirectionFieldState::kReady, std::move(field));
}
bool DirectionalLayer::inSkipErea(double start_x, double start_y, double end_x, double end_y, double skip_distance)
void DirectionalLayer::matchSize()
{
std::lock_guard<std::mutex> lock(mutex_);
if (enabled_)
publishLocked(DirectionFieldState::kPending);
}
void DirectionalLayer::reset()
{
boost::unique_lock<Costmap2D::mutex_t> master_lock(*layered_costmap_->getCostmap()->getMutex());
std::lock_guard<std::mutex> lock(mutex_);
if (!enabled_ || snapshot_.state != DirectionFieldState::kReady)
return;
const auto now = geometry();
const auto& old = snapshot_.field->geometry();
if (old.width != now.width || old.height != now.height || old.frame_id != now.frame_id ||
!std::isfinite(now.resolution) || !std::isfinite(now.origin_x) || !std::isfinite(now.origin_y) ||
std::abs(old.resolution - now.resolution) > 1e-6 || std::abs(old.origin_x - now.origin_x) > 1e-6 ||
std::abs(old.origin_y - now.origin_y) > 1e-6)
publishLocked(DirectionFieldState::kPending);
}
void DirectionalLayer::updateBounds(double, double, double, double*, double*, double*, double*)
{
std::lock_guard<std::mutex> lock(mutex_);
if (snapshot_.state != DirectionFieldState::kPending)
return;
const auto now = std::chrono::steady_clock::now();
if (now - pending_since_ >= kPendingErrorDelay &&
(last_pending_log_ == std::chrono::steady_clock::time_point() ||
now - last_pending_log_ >= kPendingErrorPeriod))
{
return fabs(hypot(start_x - end_x, start_y - end_y)) <= skip_distance;
robot::log_error("DirectionalLayer %s: PENDING for %.1f seconds", name_.c_str(),
std::chrono::duration<double>(now - pending_since_).count());
last_pending_log_ = now;
}
}
} // namespace robot_costmap_2d
// Export factory function
static boost::shared_ptr<Layer> create_directional_plugin() {
return boost::make_shared<DirectionalLayer>();
}
// Alias cho Boost.DLL (nếu muốn dùng boost::dll::import_alias)
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)
}
boost::shared_ptr<robot_costmap_2d::Layer> create_directional_plugin()
{
return boost::shared_ptr<robot_costmap_2d::Layer>(new robot_costmap_2d::DirectionalLayer());
}
BOOST_DLL_ALIAS(create_directional_plugin, DirectionalLayer)

View File

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

View File

@@ -42,6 +42,7 @@
#include <tf3/exceptions.h>
#include <boost/dll/alias.hpp>
#include <stdexcept>
using robot_costmap_2d::NO_INFORMATION;
@@ -66,7 +67,8 @@ void ObstacleLayer::onInitialize()
stop_receiving_data_ = false;
global_frame_ = layered_costmap_->getGlobalFrameID();
std::string config_file_name = "obstacle_layer_params.yaml";
getParams(config_file_name, priv_nh);
if (!getParams(config_file_name, priv_nh))
throw std::runtime_error("ObstacleLayer " + name_ + ": cannot open the default file " + config_file_name);
}
ObstacleLayer::~ObstacleLayer()
@@ -131,9 +133,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
double observation_keep_time = 0, expected_update_rate = 0, min_obstacle_height = 0, max_obstacle_height = 2;
std::string topic = "map", sensor_frame = "laser_frame", data_type = "PointCloud";
bool inf_is_valid = false, clearing=false, marking=true;
bool frustum_clearing_enabled = false;
int frustum_pixel_step = 8;
DepthFrustumConfig frustum_config;
robot::NodeHandle priv_nh(nh, source);
topic = loadParam(layer[source],"topic", topic);
@@ -146,34 +145,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
inf_is_valid = loadParam(layer[source],"inf_is_valid", false);
clearing = loadParam(layer[source],"clearing", false);
marking = loadParam(layer[source],"marking", true);
// frustum params are per-source; the layer-level key is kept as a
// fallback for older YAMLs
frustum_clearing_enabled = loadParam(layer[source], "frustum_clearing_enabled",
loadParam(layer, "frustum_clearing_enabled", false));
frustum_pixel_step = loadParam(layer[source], "frustum_clearing_pixel_step",
loadParam(layer, "frustum_clearing_pixel_step", 8));
frustum_config.min_range = loadParam(layer[source], "frustum_min_range",
loadParam(layer, "frustum_min_range", 0.2));
frustum_config.max_range = loadParam(layer[source], "frustum_max_range",
loadParam(layer, "frustum_max_range", 3.0));
frustum_config.skip_distance =
loadParam(layer[source], "frustum_skip_distance", frustum_config.skip_distance);
frustum_config.column_clearing =
loadParam(layer[source], "frustum_column_clearing", frustum_config.column_clearing);
frustum_config.column_min_height =
loadParam(layer[source], "column_clear_min_height", frustum_config.column_min_height);
frustum_config.column_max_height =
loadParam(layer[source], "column_clear_max_height", frustum_config.column_max_height);
frustum_config.column_skip_distance =
loadParam(layer[source], "column_skip_distance", frustum_config.column_skip_distance);
frustum_config.column_cover_distance =
loadParam(layer[source], "column_cover_distance", frustum_config.column_cover_distance);
int frustum_clear_left_border =
loadParam(layer[source], "frustum_clear_left_border_px",
loadParam(layer, "frustum_clear_left_border_px", 0));
int frustum_clear_right_border =
loadParam(layer[source], "frustum_clear_right_border_px",
loadParam(layer, "frustum_clear_right_border_px", 0));
if (priv_nh.hasParam("topic"))
priv_nh.getParam("topic", topic);
@@ -195,52 +166,6 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
priv_nh.getParam("clearing", clearing);
if (priv_nh.hasParam("marking"))
priv_nh.getParam("marking", marking);
if (priv_nh.hasParam("frustum_clearing_enabled"))
priv_nh.getParam("frustum_clearing_enabled", frustum_clearing_enabled);
if (priv_nh.hasParam("frustum_clearing_pixel_step"))
{
priv_nh.getParam("frustum_clearing_pixel_step", frustum_pixel_step);
frustum_pixel_step = std::max(1, frustum_pixel_step);
}
if (priv_nh.hasParam("frustum_min_range"))
priv_nh.getParam("frustum_min_range", frustum_config.min_range);
if (priv_nh.hasParam("frustum_max_range"))
priv_nh.getParam("frustum_max_range", frustum_config.max_range);
if (priv_nh.hasParam("frustum_skip_distance"))
priv_nh.getParam("frustum_skip_distance", frustum_config.skip_distance);
if (priv_nh.hasParam("frustum_column_clearing"))
priv_nh.getParam("frustum_column_clearing", frustum_config.column_clearing);
if (priv_nh.hasParam("column_clear_min_height"))
priv_nh.getParam("column_clear_min_height", frustum_config.column_min_height);
if (priv_nh.hasParam("column_clear_max_height"))
priv_nh.getParam("column_clear_max_height", frustum_config.column_max_height);
if (priv_nh.hasParam("column_skip_distance"))
priv_nh.getParam("column_skip_distance", frustum_config.column_skip_distance);
if (priv_nh.hasParam("column_cover_distance"))
priv_nh.getParam("column_cover_distance", frustum_config.column_cover_distance);
if (priv_nh.hasParam("frustum_clear_left_border_px"))
priv_nh.getParam("frustum_clear_left_border_px", frustum_clear_left_border);
if (priv_nh.hasParam("frustum_clear_right_border_px"))
priv_nh.getParam("frustum_clear_right_border_px", frustum_clear_right_border);
if (priv_nh.hasParam("frustum_depth_camera_topic"))
priv_nh.getParam("frustum_depth_camera_topic", depth_camera_data_topic_);
frustum_config.pixel_step = static_cast<unsigned int>(std::max(1, frustum_pixel_step));
frustum_config.clear_left_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_left_border));
frustum_config.clear_right_border_px =
static_cast<unsigned int>(std::max(0, frustum_clear_right_border));
robot::log_info("source %s: frustum_clearing_enabled: %s, pixel_step: %u, range: [%.2f, %.2f] m, "
"skip: %.3f m, column_clearing: %s, column_band: [%.2f, %.2f] m, "
"column_skip: %.3f m, column_cover: %.2f m, clear_left_border_px: %u px, "
"clear_right_border_px: %u px\n",
source.c_str(), frustum_clearing_enabled ? "true" : "false",
frustum_config.pixel_step, frustum_config.min_range, frustum_config.max_range,
frustum_config.skip_distance, frustum_config.column_clearing ? "true" : "false",
frustum_config.column_min_height, frustum_config.column_max_height,
frustum_config.column_skip_distance, frustum_config.column_cover_distance,
frustum_config.clear_left_border_px, frustum_config.clear_right_border_px);
double obstacle_range = 2.5;
obstacle_range = loadParam(layer[source],"obstacle_range", obstacle_range);
@@ -252,57 +177,34 @@ bool ObstacleLayer::getParams(const std::string& config_file_name, robot::NodeHa
if (priv_nh.hasParam("raytrace_range"))
priv_nh.getParam("raytrace_range", raytrace_range);
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan" || data_type == "DepthCameraData"))
if (!(data_type == "PointCloud2" || data_type == "PointCloud" || data_type == "LaserScan"))
{
robot::log_error("Only topics that use point clouds or laser scans are currently supported\n");
throw std::runtime_error("Only topics that use point clouds or laser scans are currently supported");
}
if(!frustum_clearing_enabled)
{
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
CallBackInfo info_tmp;
info_tmp.observation_source = source;
info_tmp.data_type = data_type;
info_tmp.topic = topic;
info_tmp.inf_is_valid = inf_is_valid;
callback_infos_.push_back(info_tmp);
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// enabled_ = enabled;
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
if (marking)
marking_buffers_.push_back(observation_buffers_.back());
robot::log_info("Creating an observation buffer for topic %s, frame %s\n", topic.c_str(),
priv_nh.getNamespace().c_str());
// create an observation buffer
observation_buffers_.push_back(
boost::shared_ptr < ObservationBuffer
> (new ObservationBuffer(topic, observation_keep_time, expected_update_rate, min_obstacle_height,
max_obstacle_height, obstacle_range, raytrace_range, *tf_, global_frame_,
sensor_frame, transform_tolerance)));
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)));
}
// check if we'll also add this buffer to our clearing observation buffers
if (clearing)
clearing_buffers_.push_back(observation_buffers_.back());
robot::log_info(
"Created an observation buffer for topic %s, global frame: %s, "
"expected update rate: %.2f, observation persistence: %.2f\n",
@@ -326,139 +228,60 @@ void ObstacleLayer::handleImpl(const void* data,
if (!enabled_ || stop_receiving_data_)
return;
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr))
// Samples that match no configured source (type and topic) are ignored.
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
{
const robot_sensor_msgs::DepthCameraData::ConstPtr& depth_camera_data_ptr =
*static_cast<const robot_sensor_msgs::DepthCameraData::ConstPtr*>(data);
if (!depth_camera_data_ptr)
return;
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
const robot_sensor_msgs::DepthCameraData& depth_camera_data =
*depth_camera_data_ptr;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
std::size_t bytes_per_pixel = 0;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
bytes_per_pixel = 2;
else if (depth.encoding == "32FC1")
bytes_per_pixel = 4;
else
{
robot::log_error("ObstacleLayer received unsupported depth encoding: %s\n", depth.encoding.c_str());
return;
}
const bool invalid_dimensions = depth.width == 0 || depth.height == 0 ||
depth.step < static_cast<std::size_t>(depth.width) * bytes_per_pixel ||
depth.data.size() < static_cast<std::size_t>(depth.step) * depth.height;
if (invalid_dimensions)
{
robot::log_error("ObstacleLayer received malformed DepthCameraData image\n");
return;
}
if (camera_info.K[0] <= 0.0 || camera_info.K[4] <= 0.0)
{
robot::log_error("ObstacleLayer received invalid camera intrinsics for depth clearing\n");
return;
}
if ((camera_info.width != 0 && camera_info.width != depth.width) ||
(camera_info.height != 0 && camera_info.height != depth.height))
{
robot::log_error("ObstacleLayer received mismatched depth image and camera info dimensions\n");
return;
}
const std::string& depth_frame = depth.header.frame_id;
const std::string& camera_frame = camera_info.header.frame_id;
if (!depth_frame.empty() && !camera_frame.empty() && depth_frame != camera_frame)
{
robot::log_error("ObstacleLayer received mismatched depth and camera-info frames: %s != %s\n",
depth_frame.c_str(), camera_frame.c_str());
return;
}
if (depth_camera_data.header.frame_id.empty() && depth_frame.empty() && camera_frame.empty())
{
robot::log_error("ObstacleLayer received DepthCameraData without an optical frame\n");
return;
}
// std::lock_guard<std::mutex> lock(depth_camera_data_mutex_);
// pending_depth_camera_data_ = depth_camera_data_ptr;
if (depth_observation_buffers_.empty() || callback_depth_infos_.empty())
return;
int size_callback_depth = static_cast<int>(callback_depth_infos_.size());
for(int i = 0; i < size_callback_depth; i++)
{
boost::shared_ptr<ObservationBuffer>& buffer = depth_observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::DepthCameraData::ConstPtr) &&
topic == callback_depth_infos_[i].topic)
{
// robot::log_error_throttle(1.0,"TEST");
depthImageCallback(depth_camera_data_ptr, buffer);
}
}
}
else
{
if (observation_buffers_.empty() || callback_infos_.empty())
return;
int size_callback = static_cast<int>(callback_infos_.size());
for (int i = 0; i < size_callback; i++)
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
boost::shared_ptr<ObservationBuffer>& buffer = observation_buffers_[i];
if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
!callback_infos_[i].inf_is_valid)
{
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
// if(topic == "/f_scan") robot::log_error("DATA front laser! %d",i);
// if(topic == "/b_scan") robot::log_error("DATA back laser! %d",i);
laserScanCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::LaserScan) &&
callback_infos_[i].data_type == "LaserScan" &&
topic == callback_infos_[i].topic &&
callback_infos_[i].inf_is_valid)
{
laserScanValidInfCallback(*static_cast<const robot_sensor_msgs::LaserScan*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud) &&
callback_infos_[i].data_type == "PointCloud" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloudCallback(*static_cast<const robot_sensor_msgs::PointCloud*>(data), buffer);
}
else if (type == typeid(robot_sensor_msgs::PointCloud2) &&
callback_infos_[i].data_type == "PointCloud2" &&
topic == callback_infos_[i].topic)
{
if (callback_infos_[i].inf_is_valid)
{
robot::log_error("obstacle_layer: inf_is_valid option is not applicable to PointCloud observations.\n");
}
pointCloud2Callback(*static_cast<const robot_sensor_msgs::PointCloud2*>(data), buffer);
}
// else
// {
// std::cout << "obstacle_layer: check type: " << (type == typeid(robot_sensor_msgs::LaserScan)) << std::endl
// << "obstacle_layer: inf_is_valid: " << callback_infos_[i].inf_is_valid << std::endl
// << "data type: " << callback_infos_[i].data_type << std::endl
// << "topic: " << topic << std::endl
// << "topic check: " << callback_infos_[i].topic << std::endl << std::endl;
// }
}
}
@@ -560,14 +383,6 @@ void ObstacleLayer::pointCloud2Callback(const robot_sensor_msgs::PointCloud2& me
buffer->unlock();
}
void ObstacleLayer::depthImageCallback(robot_sensor_msgs::DepthCameraData::ConstPtr message,
const boost::shared_ptr<ObservationBuffer>& buffer)
{
buffer->lock();
buffer->bufferDepthCamera(std::move(message));
buffer->unlock();
}
void ObstacleLayer::updateBounds(double robot_x, double robot_y, double robot_yaw, double* min_x,
double* min_y, double* max_x, double* max_y)
{
@@ -737,23 +552,6 @@ bool ObstacleLayer::getClearingObservations(std::vector<Observation>& clearing_o
return current;
}
bool ObstacleLayer::getFrustumClearingObservations(std::vector<DepthCameraObservation>& frustum_clearing_observations) const
{
bool current = true;
// DepthCameraObservation depth_obs;
for (const boost::shared_ptr<ObservationBuffer>& buffer : depth_observation_buffers_)
{
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,
double* max_x, double* max_y)
{

View File

@@ -43,6 +43,7 @@
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
#include <boost/dll/alias.hpp>
#include <stdexcept>
#include <fstream>
#include <cxxabi.h>
@@ -64,14 +65,24 @@ StaticLayer::~StaticLayer()
void StaticLayer::onInitialize()
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
robot::NodeHandle nh("~");
robot::NodeHandle priv_nh(nh, name_);
current_ = true;
current_ = false;
if (map_received_)
{
// Reinitialization must request another master write even if the old map is retained.
has_updated_data_ = true;
x_ = y_ = 0;
width_ = size_x_;
height_ = size_y_;
}
global_frame_ = layered_costmap_->getGlobalFrameID();
std::string config_file_name = "static_layer_params.yaml";
getParams(config_file_name, priv_nh);
if (!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());
}
@@ -157,6 +168,12 @@ void StaticLayer::matchSize()
// unrelated to the size of the layered costmap
if (!layered_costmap_->isRolling())
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
// resizeMap discards this layer's cached cells, even when the geometry is unchanged.
// A new map is required before the layer can write meaningful data again.
current_ = false;
map_received_ = false;
has_updated_data_ = false;
Costmap2D* master = layered_costmap_->getCostmap();
resizeMap(master->getSizeInCellsX(), master->getSizeInCellsY(), master->getResolution(),
master->getOriginX(), master->getOriginY());
@@ -196,9 +213,14 @@ void StaticLayer::handleImpl(const void* data,
if (type == typeid(robot_nav_msgs::OccupancyGrid) &&
(topic == map_topic_ || topic == "/" + map_topic_)) {
incomingMap(*static_cast<const robot_nav_msgs::OccupancyGrid*>(data));
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
} else if (type == typeid(robot_map_msgs::OccupancyGridUpdate) &&
(topic == map_topic_ + "_updates" || topic == "/" + map_topic_ + "_updates")) {
incomingUpdate(*static_cast<const robot_map_msgs::OccupancyGridUpdate*>(data));
} else if (type == typeid(robot_nav_msgs::OccupancyGrid) ||
type == typeid(robot_map_msgs::OccupancyGridUpdate)) {
// Right type, another layer's topic: the gateway sends every grid to every layer of this
// type (other StaticLayers, the direction grid). Normal traffic, not an error.
return;
} else {
std::string readable = boost::core::demangle(type.name());
@@ -207,7 +229,6 @@ void StaticLayer::handleImpl(const void* data,
{
readable = readable.substr(0, pos);
}
robot::log_error("[] con1: %x, con2: %x ", type == typeid(robot_nav_msgs::OccupancyGrid), (topic == map_topic_ || topic == "/" + map_topic_));
robot::log_error("[StaticLayer] Received data of unknown type: %s on topic: %s, map_topic_: %s\n", readable.c_str(), topic.c_str(), map_topic_.c_str());
// std::cout << "[StaticLayer] Unknown type: " << type.name() << " on topic: " << topic << std::endl;
}
@@ -215,8 +236,10 @@ void StaticLayer::handleImpl(const void* data,
void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
if(!map_shutdown_)
{
current_ = false;
std::cout << "[StaticLayer] Received new map!" << std::endl;
unsigned int size_x = new_map.info.width, size_y = new_map.info.height;
@@ -298,8 +321,25 @@ void StaticLayer::incomingMap(const robot_nav_msgs::OccupancyGrid& new_map)
void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& update)
{
if(!map_update_shutdown_)
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
if(!map_update_shutdown_ && map_received_)
{
const bool outside = update.x < 0 || update.y < 0 || update.width == 0 || update.height == 0 ||
static_cast<unsigned int>(update.x) > size_x_ || static_cast<unsigned int>(update.y) > size_y_ ||
update.width > size_x_ - static_cast<unsigned int>(update.x) ||
update.height > size_y_ - static_cast<unsigned int>(update.y);
if (outside || update.data.size() != static_cast<std::size_t>(update.width) * update.height)
{
const auto now = std::chrono::steady_clock::now();
if (last_invalid_update_log_ == std::chrono::steady_clock::time_point{} ||
std::chrono::duration<double>(now - last_invalid_update_log_).count() >= 5.0)
{
robot::log_error("StaticLayer %s: ignoring an invalid map update", name_.c_str());
last_invalid_update_log_ = now;
}
return;
}
current_ = false;
robot::log_info("Update new map!\n");
unsigned int di = 0;
for (unsigned int y = 0; y < update.height ; y++)
@@ -311,16 +351,34 @@ void StaticLayer::incomingUpdate(const robot_map_msgs::OccupancyGridUpdate& upda
costmap_[index] = interpretValue(update.data[di++]);
}
}
x_ = update.x;
y_ = update.y;
width_ = update.width;
height_ = update.height;
if (has_updated_data_)
{
// A full map or another update may still be awaiting updateBounds(). Preserve all dirty
// cells; otherwise a partial update could make the layer current while part of the new map
// has never reached the master.
const unsigned int update_x = static_cast<unsigned int>(update.x);
const unsigned int update_y = static_cast<unsigned int>(update.y);
const unsigned int max_x = std::max(x_ + width_, update_x + update.width);
const unsigned int max_y = std::max(y_ + height_, update_y + update.height);
x_ = std::min(x_, update_x);
y_ = std::min(y_, update_y);
width_ = max_x - x_;
height_ = max_y - y_;
}
else
{
x_ = update.x;
y_ = update.y;
width_ = update.width;
height_ = update.height;
}
has_updated_data_ = true;
}
}
void StaticLayer::activate()
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
map_shutdown_ = false;
map_update_shutdown_ = false;
onInitialize();
@@ -328,6 +386,7 @@ void StaticLayer::activate()
void StaticLayer::deactivate()
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
map_shutdown_ = true;
if (subscribe_to_updates_)
map_update_shutdown_ = true;
@@ -335,11 +394,16 @@ void StaticLayer::deactivate()
void StaticLayer::reset()
{
boost::unique_lock<Costmap2D::mutex_t> lock(*layered_costmap_->getCostmap()->getMutex());
if (first_map_only_)
{
map_shutdown_ = false;
map_update_shutdown_ = false;
current_ = false;
has_updated_data_ = true;
x_ = y_ = 0;
width_ = size_x_;
height_ = size_y_;
}
else
{
@@ -426,6 +490,13 @@ void StaticLayer::updateCosts(robot_costmap_2d::Costmap2D& master_grid, int min_
}
}
}
markMapWritten(min_i, min_j, max_i, max_j);
}
void StaticLayer::markMapWritten(int min_i, int min_j, int max_i, int max_j)
{
if (map_received_ && min_i < max_i && min_j < max_j)
current_ = true;
}
// Export factory function

View File

@@ -45,6 +45,8 @@
#include <cmath>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <string>
#define VOXEL_BITS 16
@@ -65,7 +67,8 @@ void VoxelLayer::onInitialize()
ObstacleLayer::onInitialize();
std::string config_file_name = "voxel_layer_params.yaml";
getParams(config_file_name, priv_nh);
if (!getParams(config_file_name, priv_nh))
throw std::runtime_error("VoxelLayer " + name_ + ": cannot open the default file " + config_file_name);
}
VoxelLayer::~VoxelLayer()
@@ -92,14 +95,14 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
enabled_ = loadParam(layer, "enabled", true);
footprint_clearing_enabled_ = loadParam(layer, "footprint_clearing_enabled", true);
max_obstacle_height_ = loadParam(layer, "max_obstacle_height", 2.0);
size_z_ = loadParam(layer, "z_voxels", 10);
int size_z = loadParam(layer, "z_voxels", 10);
origin_z_ = loadParam(layer, "origin_z", 0.0);
z_resolution_ = loadParam(layer, "z_resolution", 0.2);
unknown_threshold_ = loadParam(layer, "unknown_threshold", 15.0) + (VOXEL_BITS - size_z_);
mark_threshold_ = loadParam(layer, "mark_threshold", 0);
// Read as double: the default file writes 15.0, which yaml-cpp refuses to convert to int.
double unknown_threshold = loadParam(layer, "unknown_threshold", 15.0);
int mark_threshold = loadParam(layer, "mark_threshold", 0);
combination_method_ = loadParam(layer, "combination_method", 0.0);
int size_z, unknown_threshold, mark_threshold, frustum_pixel_step;
if (nh.hasParam("enabled"))
nh.getParam("enabled", enabled_);
if (nh.hasParam("footprint_clearing_enabled"))
@@ -107,25 +110,40 @@ bool VoxelLayer::getParams(const std::string& config_file_name, robot::NodeHandl
if (nh.hasParam("max_obstacle_height"))
nh.getParam("max_obstacle_height", max_obstacle_height_);
if (nh.hasParam("z_voxels"))
{
nh.getParam("z_voxels", size_z);
size_z_ = size_z;
}
if (nh.hasParam("origin_z"))
nh.getParam("origin_z", origin_z_);
if (nh.hasParam("z_resolution"))
nh.getParam("z_resolution", z_resolution_);
if (nh.hasParam("unknown_threshold"))
{
nh.getParam("unknown_threshold", unknown_threshold);
unknown_threshold_ = unknown_threshold + (VOXEL_BITS - size_z_);
}
if (nh.hasParam("mark_threshold"))
{
nh.getParam("mark_threshold", mark_threshold);
mark_threshold_ = mark_threshold;
}
if (nh.hasParam("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();
}
catch (const YAML::BadFile& e) {
@@ -172,7 +190,6 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
bool current = true;
std::vector<Observation> observations, clearing_observations;
std::vector<DepthCameraObservation> depth_observations;
// get the marking observations
current = getMarkingObservations(observations) && current;
@@ -180,16 +197,9 @@ void VoxelLayer::updateBounds(double robot_x, double robot_y, double robot_yaw,
// get the clearing observations
current = getClearingObservations(clearing_observations) && current;
current = getFrustumClearingObservations(depth_observations) && current;
// update the global current status
current_ = current;
for (const DepthCameraObservation& depth_observation : depth_observations)
{
raytraceDepthFrustum(depth_observation, min_x, min_y, max_x, max_y);
}
// raytrace freespace
for (unsigned int i = 0; i < clearing_observations.size(); ++i)
{
@@ -397,539 +407,6 @@ void VoxelLayer::raytraceFreespace(const Observation& clearing_observation, doub
}
}
bool VoxelLayer::readDepthMeters(const robot_sensor_msgs::Image& depth, unsigned int u, unsigned int v,
double& depth_m, bool& is_valid) const
{
depth_m = 0.0;
is_valid = false;
if (u >= depth.width || v >= depth.height)
return false;
if (depth.encoding == "16UC1" || depth.encoding == "mono16")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 2;
if (offset + sizeof(std::uint16_t) > depth.data.size())
return false;
std::uint16_t raw = 0;
if (depth.is_bigendian)
raw = static_cast<std::uint16_t>((depth.data[offset] << 8) | depth.data[offset + 1]);
else
raw = static_cast<std::uint16_t>(depth.data[offset] | (depth.data[offset + 1] << 8));
if (raw == 0)
return true;
depth_m = static_cast<double>(raw) * 0.001;
is_valid = true;
return true;
}
if (depth.encoding == "32FC1")
{
const std::size_t offset = static_cast<std::size_t>(v) * depth.step + static_cast<std::size_t>(u) * 4;
if (offset + sizeof(float) > depth.data.size())
return false;
float raw = 0.0f;
if (depth.is_bigendian)
{
unsigned char bytes[sizeof(float)] = {
depth.data[offset + 3], depth.data[offset + 2], depth.data[offset + 1], depth.data[offset]};
std::memcpy(&raw, bytes, sizeof(float));
}
else
{
std::memcpy(&raw, &depth.data[offset], sizeof(float));
}
if (!std::isfinite(raw) || raw <= 0.0f)
return true;
depth_m = static_cast<double>(raw);
is_valid = true;
return true;
}
robot::log_error("VoxelLayer unsupported depth encoding for frustum clearing: %s\n", depth.encoding.c_str());
return false;
}
void VoxelLayer::updateDepthRayCache(unsigned int width, unsigned int height,
unsigned int pixel_step, double fx, double fy,
double cx, double cy)
{
if (cached_depth_width_ == width && cached_depth_height_ == height &&
cached_depth_pixel_step_ == pixel_step && cached_fx_ == fx && cached_fy_ == fy &&
cached_cx_ == cx && cached_cy_ == cy)
{
return;
}
cached_depth_width_ = width;
cached_depth_height_ = height;
cached_depth_pixel_step_ = pixel_step;
cached_fx_ = fx;
cached_fy_ = fy;
cached_cx_ = cx;
cached_cy_ = cy;
// Sample every pixel_step-th row/column and always include the last image
// row/column, so cells marked from border pixels stay inside the swept
// clearing fan.
std::vector<unsigned int> u_samples, v_samples;
u_samples.reserve(width / pixel_step + 2);
v_samples.reserve(height / pixel_step + 2);
for (unsigned int u = 0; u < width; u += pixel_step)
u_samples.push_back(u);
if (width > 0 && u_samples.back() != width - 1)
u_samples.push_back(width - 1);
for (unsigned int v = 0; v < height; v += pixel_step)
v_samples.push_back(v);
if (height > 0 && v_samples.back() != height - 1)
v_samples.push_back(height - 1);
cached_column_count_ = static_cast<unsigned int>(u_samples.size());
depth_ray_cache_.clear();
depth_ray_cache_.reserve(u_samples.size() * v_samples.size());
for (const unsigned int v : v_samples)
{
for (unsigned int col = 0; col < u_samples.size(); ++col)
{
const unsigned int u = u_samples[col];
const double x = (static_cast<double>(u) - cx) / fx;
const double y = (static_cast<double>(v) - cy) / fy;
const double inverse_norm = 1.0 / std::sqrt(x * x + y * y + 1.0);
depth_ray_cache_.push_back(
DepthRay{u, v, col, x * inverse_norm, y * inverse_norm, inverse_norm});
}
}
}
bool VoxelLayer::clipRaytraceEndpoint(double ox, double oy, double oz, double& wx, double& wy, double& wz)
{
double a = wx - ox;
double b = wy - oy;
double c = wz - oz;
double t = 1.0;
constexpr double kEpsilon = 1e-9;
if (std::fabs(a) < kEpsilon && std::fabs(b) < kEpsilon && std::fabs(c) < kEpsilon)
return false;
if (wz > max_obstacle_height_ && std::fabs(c) > kEpsilon)
t = std::max(0.0, std::min(t, (max_obstacle_height_ - 0.01 - oz) / c));
else if (wz < origin_z_ && std::fabs(c) > kEpsilon)
t = std::min(t, (origin_z_ - oz) / c);
const double map_end_x = origin_x_ + getSizeInMetersX();
const double map_end_y = origin_y_ + getSizeInMetersY();
if (wx < origin_x_ && std::fabs(a) > kEpsilon)
t = std::min(t, (origin_x_ - ox) / a);
if (wy < origin_y_ && std::fabs(b) > kEpsilon)
t = std::min(t, (origin_y_ - oy) / b);
if (wx > map_end_x && std::fabs(a) > kEpsilon)
t = std::min(t, (map_end_x - ox) / a);
if (wy > map_end_y && std::fabs(b) > kEpsilon)
t = std::min(t, (map_end_y - oy) / b);
if (!std::isfinite(t) || t <= 0.0)
return false;
wx = ox + a * t;
wy = oy + b * t;
wz = oz + c * t;
return true;
}
bool VoxelLayer::clearVoxelRay(double ox, double oy, double oz, double wx, double wy, double wz,
double raytrace_range, unsigned int cell_raytrace_range,
double* min_x, double* min_y, double* max_x, double* max_y)
{
double sensor_x, sensor_y, sensor_z;
if (!worldToMap3DFloat(ox, oy, oz, sensor_x, sensor_y, sensor_z))
return false;
if (!clipRaytraceEndpoint(ox, oy, oz, wx, wy, wz))
return false;
double point_x, point_y, point_z;
if (!worldToMap3DFloat(wx, wy, wz, point_x, point_y, point_z))
return false;
robot_voxel_grid_.clearVoxelLineInMap(sensor_x, sensor_y, sensor_z, point_x, point_y, point_z, costmap_,
unknown_threshold_, mark_threshold_, FREE_SPACE, NO_INFORMATION,
cell_raytrace_range);
updateRaytraceBounds(ox, oy, wx, wy, raytrace_range, min_x, min_y, max_x, max_y);
return true;
}
bool VoxelLayer::raytraceDepthFrustum(const DepthCameraObservation& observation,
double* min_x, double* min_y, double* max_x, double* max_y)
{
if (!observation.data_)
return false;
const robot_sensor_msgs::DepthCameraData& depth_camera_data = *observation.data_;
const robot_sensor_msgs::Image& depth = depth_camera_data.depth;
const robot_sensor_msgs::CameraInfo& camera_info = depth_camera_data.camera_info;
if (depth.width == 0 || depth.height == 0 || depth.data.empty())
return false;
const double fx = camera_info.K[0];
const double fy = camera_info.K[4];
const double cx = camera_info.K[2];
const double cy = camera_info.K[5];
if (fx <= 0.0 || fy <= 0.0)
return false;
std::string depth_frame = depth.header.frame_id.empty() ? depth_camera_data.header.frame_id : depth.header.frame_id;
if (depth_frame.empty())
depth_frame = camera_info.header.frame_id;
if (depth_frame.empty() || tf_ == nullptr)
return false;
robot_geometry_msgs::PointStamped local_origin;
local_origin.header = depth.header;
local_origin.header.frame_id = depth_frame;
if (local_origin.header.stamp.isZero())
local_origin.header.stamp = depth_camera_data.header.stamp;
local_origin.point.x = 0.0;
local_origin.point.y = 0.0;
local_origin.point.z = 0.0;
robot_geometry_msgs::PointStamped global_origin;
tf3::TransformStampedMsg tfm;
try
{
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)
{
// project the new origin into the grid

View File

@@ -1,394 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* robot_costmap_2d — hiện thực của @ref robot_costmap_2d/body_clearance.h.
*
* Author: DuongTD
*********************************************************************/
#include <robot_costmap_2d/body_clearance.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_costmap_2d/costmap_math.h>
#include <robot_costmap_2d/footprint.h>
namespace robot_costmap_2d
{
const double no_clearance = std::numeric_limits<double>::max();
const double default_clearance_reach = 1.0; // [m]
namespace
{
/// Một điểm dò: ngoài lưới hay chưa có thông tin đều là KHÔNG chạm — vùng chưa quét mà tính là
/// chạm thì robot dừng ở mọi tuyến đi vào chỗ chưa thấy.
inline bool cellBlocked(const Costmap2D& grid, double wx, double wy, unsigned char threshold)
{
unsigned int mx = 0;
unsigned int my = 0;
if (!grid.worldToMap(wx, wy, mx, my))
{
return false;
}
const unsigned char cost = grid.getCost(mx, my);
return cost != NO_INFORMATION && cost >= threshold;
}
/// Footprint đã đệm, giữ nguyên khung base_link. Đệm bằng `padFootprint` của chính gói này để
/// hình học ở đây không thể lệch khỏi hình học costmap dùng.
std::vector<robot_geometry_msgs::Point> paddedFootprint(const BodyModel& body)
{
std::vector<robot_geometry_msgs::Point> padded = body.footprint;
if (body.padding != 0.0)
{
padFootprint(padded, body.padding);
}
return padded;
}
/// Bán kính ngoại tiếp của thân đã đệm — dùng để giới hạn vùng quét và quy góc sang mét.
double circumscribed(const std::vector<robot_geometry_msgs::Point>& padded)
{
double min_dist = 0.0;
double max_dist = 0.0;
calculateMinAndMaxDistances(padded, min_dist, max_dist);
return max_dist;
}
/**
* @brief Chu vi footprint tại pose (x, y, yaw) có đè ô vật cản nào không.
*
* @param baseline ô thuộc tập này thì BỎ QUA (đã nằm trong thân từ trước).
* @param spacing [m] khoảng cách hai điểm dò trên cạnh; phải nhỏ hơn một ô lưới.
*/
bool perimeterBlocked(const std::vector<robot_geometry_msgs::Point>& padded, const Costmap2D& grid,
double x, double y, double yaw, unsigned char threshold, double spacing,
const std::vector<std::pair<unsigned int, unsigned int> >* baseline)
{
std::vector<robot_geometry_msgs::Point> oriented;
transformFootprint(x, y, yaw, padded, oriented);
const std::size_t n = oriented.size();
for (std::size_t i = 0; i < n; ++i)
{
const robot_geometry_msgs::Point& a = oriented[i];
const robot_geometry_msgs::Point& b = oriented[(i + 1) % n];
const double len = std::hypot(b.x - a.x, b.y - a.y);
const int steps = std::max(1, static_cast<int>(std::ceil(len / spacing)));
for (int s = 0; s <= steps; ++s)
{
const double t = static_cast<double>(s) / steps;
const double px = a.x + (b.x - a.x) * t;
const double py = a.y + (b.y - a.y) * t;
unsigned int mx = 0;
unsigned int my = 0;
if (!grid.worldToMap(px, py, mx, my))
{
continue;
}
const unsigned char cost = grid.getCost(mx, my);
if (cost == NO_INFORMATION || cost < threshold)
{
continue;
}
if (baseline != nullptr &&
std::find(baseline->begin(), baseline->end(), std::make_pair(mx, my)) != baseline->end())
{
continue; // ô này đã trong thân từ trước — không phải ô MỚI do lệnh này mang lại
}
return true;
}
}
return false;
}
/// Ô vật cản đang nằm TRONG thân tại pose hiện tại. Quét hộp bao rồi lọc bằng phép kiểm điểm
/// trong đa giác — số ô cỡ vài trăm, chạy một lần mỗi chu kỳ.
void baselineCells(const std::vector<robot_geometry_msgs::Point>& padded, const Costmap2D& grid,
double x, double y, double yaw, unsigned char threshold,
std::vector<std::pair<unsigned int, unsigned int> >& out)
{
out.clear();
std::vector<robot_geometry_msgs::Point> oriented;
transformFootprint(x, y, yaw, padded, oriented);
double min_x = oriented[0].x;
double max_x = oriented[0].x;
double min_y = oriented[0].y;
double max_y = oriented[0].y;
for (const robot_geometry_msgs::Point& p : oriented)
{
min_x = std::min(min_x, p.x);
max_x = std::max(max_x, p.x);
min_y = std::min(min_y, p.y);
max_y = std::max(max_y, p.y);
}
unsigned int mx0 = 0;
unsigned int my0 = 0;
unsigned int mx1 = 0;
unsigned int my1 = 0;
if (!grid.worldToMap(min_x, min_y, mx0, my0) || !grid.worldToMap(max_x, max_y, mx1, my1))
{
return; // thân ra ngoài lưới: không kết luận được baseline, để rỗng
}
const std::size_t n = oriented.size();
for (unsigned int my = my0; my <= my1; ++my)
{
for (unsigned int mx = mx0; mx <= mx1; ++mx)
{
const unsigned char cost = grid.getCost(mx, my);
if (cost == NO_INFORMATION || cost < threshold)
{
continue;
}
double wx = 0.0;
double wy = 0.0;
grid.mapToWorld(mx, my, wx, wy);
// Ray casting: đếm số cạnh mà tia ngang từ (wx, wy) cắt qua.
bool inside = false;
for (std::size_t i = 0, j = n - 1; i < n; j = i++)
{
const robot_geometry_msgs::Point& a = oriented[i];
const robot_geometry_msgs::Point& b = oriented[j];
if (((a.y > wy) != (b.y > wy)) &&
(wx < (b.x - a.x) * (wy - a.y) / (b.y - a.y) + a.x))
{
inside = !inside;
}
}
if (inside)
{
out.push_back(std::make_pair(mx, my));
}
}
}
}
} // namespace
double clearance(const BodyModel& body, const Costmap2D& grid, double x, double y, double yaw,
double search_radius)
{
if (!body.valid())
{
return no_clearance;
}
const std::vector<robot_geometry_msgs::Point> padded = paddedFootprint(body);
std::vector<robot_geometry_msgs::Point> oriented;
transformFootprint(x, y, yaw, padded, oriented);
const double circum = circumscribed(padded);
const double radius = search_radius > 0.0 ? search_radius : circum + default_clearance_reach;
int mx0 = 0;
int my0 = 0;
int mx1 = 0;
int my1 = 0;
grid.worldToMapEnforceBounds(x - radius, y - radius, mx0, my0);
grid.worldToMapEnforceBounds(x + radius, y + radius, mx1, my1);
const std::size_t n = oriented.size();
double best = no_clearance;
for (int my = my0; my <= my1; ++my)
{
for (int mx = mx0; mx <= mx1; ++mx)
{
const unsigned char cost = grid.getCost(static_cast<unsigned int>(mx),
static_cast<unsigned int>(my));
if (cost == NO_INFORMATION || cost < body.lethal_threshold)
{
continue;
}
double wx = 0.0;
double wy = 0.0;
grid.mapToWorld(static_cast<unsigned int>(mx), static_cast<unsigned int>(my), wx, wy);
// Khoảng cách tới đa giác: min qua các cạnh, mang dấu âm nếu điểm nằm trong.
double dist = no_clearance;
bool inside = false;
for (std::size_t i = 0, j = n - 1; i < n; j = i++)
{
const robot_geometry_msgs::Point& a = oriented[i];
const robot_geometry_msgs::Point& b = oriented[j];
dist = std::min(dist, distanceToLine(wx, wy, a.x, a.y, b.x, b.y));
if (((a.y > wy) != (b.y > wy)) &&
(wx < (b.x - a.x) * (wy - a.y) / (b.y - a.y) + a.x))
{
inside = !inside;
}
}
best = std::min(best, inside ? -dist : dist);
}
}
// Không thấy ô nào trong tầm: khoảng hở ÍT NHẤT bằng phần tầm quét nằm ngoài thân. Trả về số đó
// thay vì "không đo được" — bên gọi cần một con số để so ngưỡng, và "sạch tới hết tầm" là một
// kết luận hợp lệ, khác hẳn với "chưa dựng được model".
if (best == no_clearance)
{
return std::max(0.0, radius - circum);
}
return best;
}
SweepResult sweep(const BodyModel& body, const Costmap2D& grid, double x, double y, double yaw,
double v, double omega, const SweepParams& params)
{
SweepResult result;
if (!body.valid() || std::fabs(v) < params.min_speed || !(params.lookahead > 0.0))
{
return result;
}
const std::vector<robot_geometry_msgs::Point> padded = paddedFootprint(body);
const double resolution = grid.getResolution();
if (!(resolution > 0.0))
{
return result;
}
std::vector<std::pair<unsigned int, unsigned int> > baseline;
baselineCells(padded, grid, x, y, yaw, body.lethal_threshold, baseline);
result.baseline_cells = static_cast<int>(baseline.size());
const double direction = v < 0.0 ? -1.0 : 1.0;
const double kappa = omega / v; // [1/m]; lùi thì cung lật chiều cùng với v
// Cung bị cắt bởi CẢ hai giới hạn: quãng và góc. Quay quá lookahead_angle thì lệnh đã đổi từ
// lâu, các mẫu xa hơn mô tả một chuyển động không bao giờ xảy ra.
double span = params.lookahead;
if (std::fabs(kappa) > 1.0e-6 && params.lookahead_angle > 0.0)
{
span = std::min(span, params.lookahead_angle / std::fabs(kappa));
}
// Bước dọc cung không quá một ô: tường mỏng một ô lọt giữa hai mẫu là đâm xuyên.
const int samples = std::max(1, static_cast<int>(std::ceil(span / resolution)));
const double step = span / samples;
const double spacing = 0.5 * resolution; // hai điểm dò trên chu vi cách nhau nửa ô
const double sin0 = std::sin(yaw);
const double cos0 = std::cos(yaw);
for (int i = 1; i <= samples; ++i)
{
const double walk = std::min(step * i, span); // [m] dọc cung, luôn dương
if (walk < params.skip_own_body)
{
continue;
}
const double s = direction * walk; // quãng có dấu
double px = 0.0;
double py = 0.0;
double pyaw = yaw;
if (std::fabs(kappa) < 1.0e-6)
{
px = x + s * cos0;
py = y + s * sin0;
}
else
{
pyaw = yaw + kappa * s;
px = x + (std::sin(pyaw) - sin0) / kappa;
py = y - (std::cos(pyaw) - cos0) / kappa;
}
++result.scanned;
if (perimeterBlocked(padded, grid, px, py, pyaw, body.lethal_threshold, spacing, &baseline))
{
result.hit = true;
result.sample = i;
result.walk = walk;
result.t_contact = walk / std::fabs(v);
result.turn = std::fabs(kappa) * walk;
return result;
}
}
return result;
}
CircleApproximation circleApproximation(const BodyModel& body, int count)
{
CircleApproximation out;
if (!body.valid() || count < 1)
{
return out;
}
const std::vector<robot_geometry_msgs::Point> padded = paddedFootprint(body);
double half_width = 0.0; // bán kính nội tiếp: lát cắt hẹp nhất của thân
double half_diag = 0.0; // bán kính ngoại tiếp
calculateMinAndMaxDistances(padded, half_width, half_diag);
if (!(half_width > 0.0))
{
return out;
}
// Nửa dài: đỉnh xa nhất theo trục x của thân đã đệm.
double half_length = 0.0;
for (const robot_geometry_msgs::Point& p : padded)
{
half_length = std::max(half_length, std::fabs(p.x));
}
out.count = count;
out.radius = half_width;
if (count == 1)
{
// Một disc phải phủ cả chiều dài, nên nó phình ra hai bên — chỉ hợp lý với robot gần tròn.
out.radius = std::max(half_width, half_length);
out.spacing = 0.0;
return out;
}
// Mỗi circle bán kính r phủ dọc trục ±sqrt(r² − w²) mà vẫn đảm bảo bề rộng w. Tâm ngoài cùng
// phải đặt tại half_length − reach để mũi/đuôi không hụt.
const double reach = std::sqrt(std::max(0.0, out.radius * out.radius - half_width * half_width));
const double outer = std::max(0.0, half_length - reach);
out.spacing = 2.0 * outer / (count - 1);
return out;
}
int obstaclePoints(const BodyModel& body, const Costmap2D& grid, double x, double y, double range,
int cell_step, int max_points, std::vector<std::pair<double, double> >& out)
{
out.clear();
if (!(range > 0.0) || max_points < 1)
{
return 0;
}
const int step = std::max(1, cell_step);
int mx0 = 0;
int my0 = 0;
int mx1 = 0;
int my1 = 0;
grid.worldToMapEnforceBounds(x - range, y - range, mx0, my0);
grid.worldToMapEnforceBounds(x + range, y + range, mx1, my1);
const double range_sq = range * range;
// Giữ điểm GẦN NHẤT khi chạm trần: vật cản sát người mới là thứ quyết định lệnh.
std::vector<std::pair<double, std::pair<double, double> > > scored;
int seen = 0;
for (int my = my0; my <= my1; my += step)
{
for (int mx = mx0; mx <= mx1; mx += step)
{
const unsigned char cost = grid.getCost(static_cast<unsigned int>(mx),
static_cast<unsigned int>(my));
if (cost == NO_INFORMATION || cost < body.lethal_threshold)
{
continue;
}
double wx = 0.0;
double wy = 0.0;
grid.mapToWorld(static_cast<unsigned int>(mx), static_cast<unsigned int>(my), wx, wy);
const double d_sq = (wx - x) * (wx - x) + (wy - y) * (wy - y);
if (d_sq > range_sq)
{
continue;
}
++seen;
scored.push_back(std::make_pair(d_sq, std::make_pair(wx, wy)));
}
}
const std::size_t keep = std::min(scored.size(), static_cast<std::size_t>(max_points));
std::partial_sort(scored.begin(), scored.begin() + keep, scored.end());
out.reserve(keep);
for (std::size_t i = 0; i < keep; ++i)
{
out.push_back(scored[i].second);
}
return seen;
}
} // namespace robot_costmap_2d

View File

@@ -48,6 +48,9 @@
#include <tf3/convert.h>
#include <tf3/utils.h>
#include <exception>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include <boost/dll/import.hpp>
@@ -63,10 +66,26 @@ void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::str
if (!old_h.hasParam(name))
return;
old_h.getParam(name, value);
// A failed getParam() writes its default (0, false, "") into value; copying that would replace
// 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);
}
// 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) :
layered_costmap_(NULL),
name_(name),
@@ -109,6 +128,17 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
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 =
loadParam(layer, "global_frame", std::string("map"));
std::string robot_base_frame =
@@ -224,44 +254,22 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
{
my_list.clear();
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)
{
for (size_t i = 0; i < my_plugins.size(); ++i)
{
YAML::Node plugin_i = my_plugins[i].as<YAML::Node>();
YAML::Node plugin_i = my_plugins[i].as<YAML::Node>();
// Checked before reading the fields: indexing a scalar entry throws a bare YAML error.
if (!plugin_i.IsMap() || !plugin_i["name"] || !plugin_i["type"])
fail("plugins: entry " + std::to_string(i) + " must be a map with a name and a type");
PluginConfig p;
p.type = plugin_i["type"].as<std::string>();
p.name = plugin_i["name"].as<std::string>();
my_list.push_back(p);
if (!plugin_i.IsMap())
{
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;
}
}
}
}
PluginConfig p;
p.type = plugin_i["type"].as<std::string>();
p.name = plugin_i["name"].as<std::string>();
for (const auto& known : my_list)
if (known.name == p.name)
fail("plugins: the name '" + p.name + "' is used twice; each layer needs its own name");
my_list.push_back(p);
}
}
else
@@ -293,10 +301,10 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
plugin->initialize(layered_costmap_,name_ + "/" + info.name, &tf_);
layered_costmap_->addPlugin(plugin);
}
catch (std::exception &ex)
catch (const std::exception& ex)
{
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());
return;
// Covers a missing library or symbol as well as a layer rejecting its parameters.
fail("layer '" + info.name + "' (" + info.type + "): " + ex.what());
}
}
@@ -353,8 +361,11 @@ void Costmap2DROBOT::getParams(const std::string& config_file_name,const std::st
}
catch (const YAML::BadFile& e)
{
std::cerr << "Cannot open YAML file: " << e.what() << std::endl;
return;
// costmap_params.yaml is read before layered_costmap_ exists; delete is a no-op on NULL.
delete layered_costmap_;
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());
}
}
@@ -363,182 +374,81 @@ void Costmap2DROBOT::copyParentParameters(const std::string& costmap_name,
const std::string& plugin_type,
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_plugin_nh(costmap_nh, plugin_name);
robot::NodeHandle plugin_nh(nh, plugin_name);
if(plugin_type == "StaticLayer")
{
std::string map_topic;
int unknown_cost_value;
int lethal_cost_threshold;
bool track_unknown_space;
move_parameter(plugin_nh, costmap_plugin_nh, "map_topic", map_topic);
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"))
// observation_sources, then the keys of each source under "<plugin>/<source>/".
const auto move_sources = [&](const auto& move_source_keys) {
std::string topics_string;
move_parameter(plugin_nh, costmap_plugin_nh, "observation_sources", topics_string);
std::stringstream ss(topics_string);
std::string source;
while (ss >> source)
{
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);
}
robot::NodeHandle plugin_nh_element(plugin_nh, source);
robot::NodeHandle costmap_plugin_nh_element(costmap_plugin_nh, source);
move_source_keys(plugin_nh_element, costmap_plugin_nh_element);
}
}
else if(plugin_type == "ObstacleLayer")
};
if (plugin_type == "StaticLayer")
{
double max_obstacle_height;
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"))
move_parameters<std::string>(plugin_nh, costmap_plugin_nh, {"map_topic", "base_frame_id"});
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"unknown_cost_value", "lethal_cost_threshold"});
move_parameters<bool>(plugin_nh, costmap_plugin_nh,
{"enabled", "track_unknown_space", "first_map_only", "subscribe_to_updates",
"use_maximum", "trinary_costmap"});
}
else if (plugin_type == "ObstacleLayer" || plugin_type == "VoxelLayer")
{
// VoxelLayer runs ObstacleLayer::getParams() first, so it reads these keys too.
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"max_obstacle_height", "transform_tolerance"});
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"combination_method"});
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"track_unknown_space", "footprint_clearing_enabled"});
if (plugin_type == "VoxelLayer")
{
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);
}
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"origin_z", "z_resolution", "unknown_threshold"});
move_parameters<int>(plugin_nh, costmap_plugin_nh, {"z_voxels", "mark_threshold"});
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled"});
}
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 == "InflationLayer")
{
double cost_scaling_factor;
double inflation_radius;
move_parameter(plugin_nh, costmap_plugin_nh, "cost_scaling_factor", cost_scaling_factor);
move_parameter(plugin_nh, costmap_plugin_nh, "inflation_radius", inflation_radius);
move_parameters<double>(plugin_nh, costmap_plugin_nh, {"cost_scaling_factor", "inflation_radius"});
move_parameters<bool>(plugin_nh, costmap_plugin_nh, {"enabled", "inflate_unknown"});
}
else if (plugin_type == "DepthCameraObstacleLayer")
{
move_parameters<bool>(plugin_nh, costmap_plugin_nh,
{"track_unknown_space", "enabled", "footprint_clearing_enabled",
"enable_near_blocked_protection", "use_voxelized_observation", "use_global_frame_to_mark",
"clear_touches_bounds", "debug/stats", "occlusion_guard"});
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", "attach_distance"});
});
}
}
void Costmap2DROBOT::setUnpaddedRobotFootprintPolygon(const robot_geometry_msgs::Polygon& footprint)

177
src/direction_field.cpp Normal file
View File

@@ -0,0 +1,177 @@
#include <robot_costmap_2d/direction_field.h>
#include <algorithm>
#include <cassert>
#include <sstream>
namespace robot_costmap_2d
{
namespace
{
constexpr double kTolerance = 1e-6;
std::string frameName(const std::string& frame)
{
return !frame.empty() && frame[0] == '/' ? frame.substr(1) : frame;
}
DirectionValidationResult fail(DirectionValidationError error, const std::string& message)
{
return {error, message};
}
template<typename T>
std::string value(const char* name, T actual)
{
std::ostringstream out;
out << name << "=" << actual;
return out.str();
}
} // namespace
DirectionValidationResult validateDirectionGrid(const robot_nav_msgs::OccupancyGrid& grid,
const DirectionGeometry& expected)
{
const auto& info = grid.info;
const uint64_t count = uint64_t(info.width) * uint64_t(info.height);
if (count > std::vector<uint8_t>().max_size())
return fail(DirectionValidationError::kOverflow, value("cell count", count));
if (frameName(grid.header.frame_id).empty() || frameName(grid.header.frame_id) != frameName(expected.frame_id))
return fail(DirectionValidationError::kFrame,
"frame_id=" + grid.header.frame_id + " expected=" + expected.frame_id);
if (info.width != expected.width || info.height != expected.height)
return fail(DirectionValidationError::kGeometry,
value("width", info.width) + " " + value("height", info.height));
const auto close = [](double a, double b)
{
return std::isfinite(a) && std::isfinite(b) && std::abs(a - b) <= kTolerance;
};
if (!close(info.resolution, expected.resolution) || info.resolution <= 0.0 || expected.resolution <= 0.0)
return fail(DirectionValidationError::kGeometry, value("resolution", info.resolution));
if (!close(info.origin.position.x, expected.origin_x) || !close(info.origin.position.y, expected.origin_y) ||
!std::isfinite(info.origin.position.z))
return fail(DirectionValidationError::kGeometry,
value("origin.x", info.origin.position.x) + " " + value("origin.y", info.origin.position.y) +
" " + value("origin.z", info.origin.position.z));
const auto& q = info.origin.orientation;
// A default-constructed Pose has a zero quaternion; it denotes no rotation here.
if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w) ||
std::abs(q.x) > kTolerance || std::abs(q.y) > kTolerance || std::abs(q.z) > kTolerance ||
!(std::abs(std::abs(q.w) - 1.0) <= kTolerance || std::abs(q.w) <= kTolerance))
return fail(DirectionValidationError::kOrientation,
value("orientation.x", q.x) + " " + value("y", q.y) + " " + value("z", q.z) +
" " + value("w", q.w));
if (!grid.data.empty() && grid.data.size() != count)
return fail(DirectionValidationError::kSize, value("data.size", grid.data.size()) + " " + value("expected", count));
for (size_t i = 0; i < grid.data.size(); ++i)
{
if (grid.data[i] < 0 || grid.data[i] > 8)
return fail(DirectionValidationError::kCode, value("data index", i) + " " + value("code", int(grid.data[i])));
}
return {DirectionValidationError::kNone, "valid"};
}
uint8_t allowedDirectionMask(double dx, double dy, double max_deviation_rad)
{
if (!std::isfinite(dx) || !std::isfinite(dy))
return 0;
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
const long double x = dx, y = dy;
const bool legacy_right_angle = max_deviation_rad == M_PI / 2.0;
const long double length = std::hypot(x, y);
const long double threshold = (std::cos(max_deviation_rad) - 1e-9L) * length;
const long double legacy_tolerance = 1e-9L * (std::abs(x) + std::abs(y));
constexpr long double kInverseSqrtTwo = 0.707106781186547524400844362104849L;
uint8_t mask = 0;
for (int k = 0; k < 8; ++k)
{
const long double dot = vx[k] * x + vy[k] * y;
// Preserve the exact legacy tolerance at 90 degrees, including near-boundary inputs.
if (legacy_right_angle ? dot >= -legacy_tolerance :
dot * (k % 2 ? kInverseSqrtTwo : 1.0L) >= threshold)
mask |= uint8_t(1u << k);
}
return mask;
}
DirectionField::DirectionField(const robot_nav_msgs::OccupancyGrid& grid, const DirectionGeometry& geometry,
double max_deviation_rad)
: geometry_(geometry), codes_(grid.data.begin(), grid.data.end()),
max_deviation_rad_(max_deviation_rad),
has_constraints_(std::any_of(codes_.begin(), codes_.end(), [](uint8_t c) { return c != 0; }))
{
}
std::shared_ptr<const DirectionField> DirectionField::create(const robot_nav_msgs::OccupancyGrid& grid,
const DirectionGeometry& expected,
double max_deviation_rad,
DirectionValidationResult* result)
{
auto validation = validateDirectionGrid(grid, expected);
if (result)
*result = validation;
if (!validation)
return {};
return std::shared_ptr<const DirectionField>(new DirectionField(grid, expected, max_deviation_rad));
}
uint8_t DirectionField::code(uint32_t x, uint32_t y) const
{
assert(x < geometry_.width && y < geometry_.height);
return codes_.empty() ? 0 : codes_[size_t(y) * geometry_.width + x];
}
bool DirectionField::codeAt(int64_t x, int64_t y, uint8_t* code_out) const
{
if (!code_out || x < 0 || y < 0 || x >= geometry_.width || y >= geometry_.height)
return false;
*code_out = code(static_cast<uint32_t>(x), static_cast<uint32_t>(y));
return true;
}
SegmentResult DirectionField::checkSegment(double wx0, double wy0, double wx1, double wy1,
SegmentViolation* first) const
{
const auto gx = [this](double x) { return (x - geometry_.origin_x) / geometry_.resolution; };
const auto gy = [this](double y) { return (y - geometry_.origin_y) / geometry_.resolution; };
const double x0 = gx(wx0);
const double y0 = gy(wy0);
const double x1 = gx(wx1);
const double y1 = gy(wy1);
const auto inside = [this](double x, double y)
{
return std::isfinite(x) && std::isfinite(y) && x >= 0 && y >= 0 &&
x < geometry_.width && y < geometry_.height;
};
if (!inside(x0, y0) || !inside(x1, y1))
return SegmentResult::kOutOfGrid;
const double dx = wx1 - wx0;
const double dy = wy1 - wy0;
if (!std::isfinite(dx) || !std::isfinite(dy))
return SegmentResult::kOutOfGrid;
const uint8_t mask = allowedDirectionMask(dx, dy, max_deviation_rad_);
SegmentResult result = SegmentResult::kAllowed;
const bool completed = traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
{
uint8_t cell_code;
if (!codeAt(x, y, &cell_code))
{
result = SegmentResult::kOutOfGrid;
return false;
}
if (cell_code && !(mask & (1u << (cell_code - 1))))
{
if (first)
*first = {uint32_t(x), uint32_t(y), cell_code, dx, dy};
result = SegmentResult::kViolation;
return false;
}
return true;
});
return completed || result != SegmentResult::kAllowed ? result : SegmentResult::kOutOfGrid;
}
} // namespace robot_costmap_2d

View File

@@ -366,6 +366,25 @@ namespace robot_costmap_2d
}
}
DirectionFieldSnapshot LayeredCostmap::getDirectionFieldSnapshot() const
{
DirectionFieldSnapshot result;
unsigned int count = 0;
for (const auto& plugin : plugins_)
{
if (!plugin->isEnabled()) continue;
const auto* provider = dynamic_cast<const DirectionFieldProvider*>(plugin.get());
if (!provider) continue;
result = provider->directionSnapshot();
if (++count > 1)
{
robot::log_error("Multiple enabled direction field providers; refusing direction queries");
return {DirectionFieldState::kPending, {}, 0};
}
}
return result;
}
bool LayeredCostmap::isCurrent()
{
current_ = true;

View File

@@ -58,23 +58,6 @@ ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_
{
}
ObservationBuffer::ObservationBuffer(string topic_name, double observation_keep_time, double expected_update_rate,
double min_obstacle_height, double max_obstacle_height, double obstacle_range,
double raytrace_range, const DepthFrustumConfig& frustum_config,
tf3::BufferCore& tf3_buffer, string global_frame,
string sensor_frame, double tf_tolerance) :
tf3_buffer_(tf3_buffer), observation_keep_time_(observation_keep_time), expected_update_rate_(expected_update_rate),
last_updated_(robot::Time::now()), global_frame_(global_frame), sensor_frame_(sensor_frame), topic_name_(topic_name),
min_obstacle_height_(min_obstacle_height), max_obstacle_height_(max_obstacle_height),
obstacle_range_(obstacle_range), raytrace_range_(raytrace_range),
tf_tolerance_(tf_tolerance),
frustum_config_(frustum_config)
{
frustum_config_.pixel_step = std::max(1u, frustum_config_.pixel_step);
frustum_config_.min_range = std::max(0.0, frustum_config_.min_range);
frustum_config_.max_range = std::max(frustum_config_.max_range, frustum_config_.min_range);
}
ObservationBuffer::~ObservationBuffer()
{
}
@@ -229,36 +212,6 @@ void ObservationBuffer::bufferCloud(const robot_sensor_msgs::PointCloud2& cloud)
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
void ObservationBuffer::getObservations(vector<Observation>& observations)
{
@@ -273,26 +226,6 @@ void ObservationBuffer::getObservations(vector<Observation>& observations)
}
}
void ObservationBuffer::getDepthObservations(vector<DepthCameraObservation>& observations)
{
// first... let's make sure that we don't have any stale observations
purgeStaleDepthObservations();
// now we'll just copy the observations for the caller
if (observation_keep_time_ == robot::Duration(0.0))
{
if (!depth_observation_list_.empty())
{
observations.push_back(std::move(depth_observation_list_.front()));
depth_observation_list_.clear();
}
return;
}
observations.insert(
observations.end(), depth_observation_list_.begin(), depth_observation_list_.end());
}
void ObservationBuffer::purgeStaleObservations()
{
if (!observation_list_.empty())
@@ -319,30 +252,6 @@ void ObservationBuffer::purgeStaleObservations()
}
}
void ObservationBuffer::purgeStaleDepthObservations()
{
if (depth_observation_list_.empty())
return;
if (observation_keep_time_ == robot::Duration(0.0))
{
auto observation = depth_observation_list_.begin();
depth_observation_list_.erase(++observation, depth_observation_list_.end());
return;
}
const robot::Time now = robot::Time::now();
for (auto observation = depth_observation_list_.begin(); observation != depth_observation_list_.end(); ++observation)
{
DepthCameraObservation& obs = *observation;
if ((last_updated_ - obs.data_->header.stamp) > observation_keep_time_)
{
depth_observation_list_.erase(observation, depth_observation_list_.end());
return;
}
}
}
bool ObservationBuffer::isCurrent() const
{
if (expected_update_rate_ == robot::Duration(0.0))

View File

@@ -1,397 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm body_clearance: một nguồn hình học thân duy nhất cho toàn stack.
*
* Các ca ở đây là những ca ĐÃ XẢY RA trên sim tháng 8-9/2026, mỗi ca một lần robot đâm hoặc kẹt:
* trụ mảnh lọt giữa hai đường quét, tường mỏng một ô lọt giữa hai mẫu, thân đứng lấn vành an toàn
* bị cấm mọi chuyển động kể cả chuyển động thoát, cùng một quãng cung mang hai ý nghĩa khác nhau
* tuỳ độ cong.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <vector>
#include <robot_costmap_2d/body_clearance.h>
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_costmap_2d/cost_values.h>
namespace
{
using robot_costmap_2d::BodyModel;
using robot_costmap_2d::circleApproximation;
using robot_costmap_2d::Costmap2D;
using robot_costmap_2d::SweepParams;
using robot_costmap_2d::SweepResult;
constexpr double kRes = 0.05; //!< [m] một ô, như costmap local thật
constexpr double kHalfLen = 0.583; //!< [m] nửa dài robot
constexpr double kHalfWid = 0.48; //!< [m] nửa rộng robot
/// Lưới 20x20 m, gốc ở (-10, -10) nên robot đứng ở (0, 0) là giữa lưới.
Costmap2D makeGrid()
{
return Costmap2D(400, 400, kRes, -10.0, -10.0, robot_costmap_2d::FREE_SPACE);
}
void setLethal(Costmap2D& grid, double wx, double wy)
{
unsigned int mx = 0;
unsigned int my = 0;
ASSERT_TRUE(grid.worldToMap(wx, wy, mx, my));
grid.setCost(mx, my, robot_costmap_2d::LETHAL_OBSTACLE);
}
void setCost(Costmap2D& grid, double wx, double wy, unsigned char cost)
{
unsigned int mx = 0;
unsigned int my = 0;
ASSERT_TRUE(grid.worldToMap(wx, wy, mx, my));
grid.setCost(mx, my, cost);
}
BodyModel makeBody(double padding = 0.05)
{
BodyModel body;
body.padding = padding;
const double xs[4] = { kHalfLen, kHalfLen, -kHalfLen, -kHalfLen };
const double ys[4] = { -kHalfWid, kHalfWid, kHalfWid, -kHalfWid };
for (int i = 0; i < 4; ++i)
{
robot_geometry_msgs::Point p;
p.x = xs[i];
p.y = ys[i];
body.footprint.push_back(p);
}
return body;
}
/// Tường ngang (song song trục y) tại x = @p wx, đủ rộng để cắt mọi đường quét.
void wallAt(Costmap2D& grid, double wx)
{
for (double y = -1.0; y <= 1.0; y += kRes)
{
setLethal(grid, wx, y);
}
}
} // namespace
// ================================================================================================
// clearance — khoảng hở tại pose hiện tại
// ================================================================================================
TEST(BodyClearance, EmptyGridReadsAsClearToTheEdgeOfTheScan)
{
// "Sạch tới hết tầm quét" là kết luận hợp lệ và phải ra một CON SỐ để bên gọi so ngưỡng.
// no_clearance chỉ dành cho "chưa dựng được model" — hai chuyện khác hẳn nhau.
Costmap2D grid = makeGrid();
const double c = clearance(makeBody(), grid, 0.0, 0.0, 0.0);
EXPECT_GT(c, 0.5);
EXPECT_LT(c, robot_costmap_2d::no_clearance);
}
TEST(BodyClearance, UnbuiltModelIsNotMeasurable)
{
Costmap2D grid = makeGrid();
BodyModel empty;
EXPECT_EQ(clearance(empty, grid, 0.0, 0.0, 0.0), robot_costmap_2d::no_clearance);
}
TEST(BodyClearance, MeasuresFromThePaddedBodyNotTheCentre)
{
// Tường tại x = 1.0. Mũi đã đệm ở 0.583 + 0.05 = 0.633 -> hở 0.367 m, KHÔNG phải 1.0 m.
Costmap2D grid = makeGrid();
wallAt(grid, 1.0);
EXPECT_NEAR(clearance(makeBody(), grid, 0.0, 0.0, 0.0), 1.0 - (kHalfLen + 0.05), 0.05);
}
TEST(BodyClearance, NegativeWhenAnObstacleIsInsideTheBody)
{
Costmap2D grid = makeGrid();
setLethal(grid, 0.30, 0.0); // nằm trong thân
EXPECT_LT(clearance(makeBody(), grid, 0.0, 0.0, 0.0), 0.0);
}
TEST(BodyClearance, InflationIsNotAnObstacle)
{
// Cả lý do file này tồn tại: 253 nghĩa là "đặt TÂM ở đây thì thân chạm" — nó đã là một phép kiểm
// thân. Lấy nó làm điểm vật cản rồi dò thân quanh nó là đếm thân hai lần; ở ngưỡng LETHAL thì
// vành inflation không tham gia.
Costmap2D grid = makeGrid();
for (double x = 0.0; x <= 2.0; x += kRes)
{
for (double y = -0.7; y <= 0.7; y += kRes)
{
setCost(grid, x, y, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
}
}
EXPECT_GT(clearance(makeBody(), grid, 0.0, 0.0, 0.0), 0.5);
}
TEST(BodyClearance, PaddingIsTheOnlyMargin)
{
Costmap2D grid = makeGrid();
wallAt(grid, 1.0);
const double tight = clearance(makeBody(0.0), grid, 0.0, 0.0, 0.0);
const double padded = clearance(makeBody(0.20), grid, 0.0, 0.0, 0.0);
EXPECT_NEAR(tight - padded, 0.20, 0.02);
}
// ================================================================================================
// sweep — lệnh (v, omega) dẫn thân tới đâu
// ================================================================================================
TEST(BodySweep, ClearArcIsNotBlocked)
{
Costmap2D grid = makeGrid();
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams());
EXPECT_FALSE(r.hit);
EXPECT_GT(r.scanned, 0);
}
TEST(BodySweep, StandingStillScansNothing)
{
// v dưới min_speed: cung suy biến. Xoay tại chỗ có phép kiểm riêng, không phải việc của hàm này.
Costmap2D grid = makeGrid();
wallAt(grid, 0.7);
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.0, 0.5, SweepParams());
EXPECT_FALSE(r.hit);
EXPECT_EQ(r.scanned, 0);
}
TEST(BodySweep, ReportsTimeAndAngleNotJustDistance)
{
// Cùng một quãng cung, hai ý nghĩa. Đo 4/9: cung 0.15 m khi đi thẳng 0.36 m/s là "chạm sau
// 0.4 s"; cũng 0.15 m khi bò 0.04 m/s với omega 0.5 là "quay 107 độ nữa, chạm sau 3.7 s".
Costmap2D grid = makeGrid();
wallAt(grid, 1.0);
const SweepResult fast = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.40, 0.0, SweepParams());
ASSERT_TRUE(fast.hit);
EXPECT_NEAR(fast.t_contact, fast.walk / 0.40, 1e-6);
EXPECT_NEAR(fast.turn, 0.0, 1e-6);
const SweepResult crawl = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.04, 0.0, SweepParams());
ASSERT_TRUE(crawl.hit);
EXPECT_NEAR(crawl.walk, fast.walk, 1e-6); // cùng quãng
EXPECT_GT(crawl.t_contact, 8.0 * fast.t_contact); // nhưng lâu hơn hẳn
}
TEST(BodySweep, ThinPillarAtTheFrontCornerIsCaught)
{
// Trụ mảnh một ô ở góc trước-trái: nằm giữa đường quét mũi (ngang 0) và đường quét hông
// (ngang 0.53) của cách dò vài-điểm-rời — đo 4/9, robot ôm cả trụ mới dừng. Dò kín chu vi thì
// cạnh mũi cắt qua trụ.
Costmap2D grid = makeGrid();
setLethal(grid, 1.0, 0.30);
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams());
ASSERT_TRUE(r.hit);
EXPECT_NEAR(r.walk, 1.0 - (kHalfLen + 0.05), 0.08);
}
TEST(BodySweep, TwoPillarsNarrowerThanTheBodyAreCaught)
{
// Hai trụ cách nhau 0.45 m, thân rộng 0.96 + đệm: không thể lọt.
Costmap2D grid = makeGrid();
setLethal(grid, 1.2, 0.225);
setLethal(grid, 1.2, -0.225);
EXPECT_TRUE(sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
}
TEST(BodySweep, ThinWallBetweenCoarseSamplesIsStillCaught)
{
// Tường dày đúng một ô: bước dọc cung phải <= một ô, nếu không hai mẫu liên tiếp nhảy qua nó và
// robot đâm xuyên.
Costmap2D grid = makeGrid();
wallAt(grid, 1.30);
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams());
ASSERT_TRUE(r.hit);
EXPECT_NEAR(r.walk, 1.30 - (kHalfLen + 0.05), 0.08);
}
TEST(BodySweep, ObstacleAlreadyInsideTheBodyDoesNotBlockTheEscape)
{
// Ca kẹt 250 vòng (đo 4/9 10:35): trụ nằm sát hông, thân đã lấn vành an toàn. Nếu tính cả ô đó
// thì MỌI lệnh tiến đều "chạm" — kể cả lệnh đi RA XA — và base chỉ tiến thì kẹt vĩnh viễn.
Costmap2D grid = makeGrid();
setLethal(grid, -0.30, 0.50); // sau-trái, trong thân đã đệm
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams());
EXPECT_GT(r.baseline_cells, 0);
EXPECT_FALSE(r.hit);
}
TEST(BodySweep, ANewCellStillBlocksEvenWithABaseline)
{
// Nhưng bỏ qua ô cũ KHÔNG có nghĩa là bỏ qua tất cả: ô mới phía trước vẫn phải chặn.
Costmap2D grid = makeGrid();
setLethal(grid, -0.30, 0.50); // baseline
wallAt(grid, 1.0); // ô mới
const SweepResult r = sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams());
EXPECT_GT(r.baseline_cells, 0);
EXPECT_TRUE(r.hit);
}
TEST(BodySweep, ReverseCommandProbesBehind)
{
Costmap2D grid = makeGrid();
wallAt(grid, -1.2);
EXPECT_FALSE(sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
const SweepResult back = sweep(makeBody(), grid, 0.0, 0.0, 0.0, -0.4, 0.0, SweepParams());
ASSERT_TRUE(back.hit);
EXPECT_NEAR(back.walk, 1.2 - (kHalfLen + 0.05), 0.08);
}
TEST(BodySweep, TurningAwayFromAWallIsClear)
{
// Tường ngay trước mặt nhưng lệnh rẽ gắt: cung quay đi trước khi mũi tới. Phép đo đọc LỆNH,
// không đoán.
Costmap2D grid = makeGrid();
for (double y = -0.3; y <= 0.3; y += kRes)
{
setLethal(grid, 1.0, y);
}
SweepParams p;
p.lookahead_angle = 0.5; // cắt cung sớm: quay quá 0.5 rad thì lệnh đã đổi
EXPECT_FALSE(sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.3, 1.5, p).hit);
}
TEST(BodySweep, UnknownCellsAreNotObstacles)
{
Costmap2D grid = makeGrid();
for (double x = 0.0; x <= 2.0; x += kRes)
{
setCost(grid, x, 0.0, robot_costmap_2d::NO_INFORMATION);
}
EXPECT_FALSE(sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
}
// ================================================================================================
// obstaclePoints — solver và phép quét phải thấy CÙNG một môi trường
// ================================================================================================
TEST(BodyObstaclePoints, OnlyLethalCellsCount)
{
Costmap2D grid = makeGrid();
setLethal(grid, 1.0, 0.0);
for (double y = -0.5; y <= 0.5; y += kRes)
{
setCost(grid, 1.5, y, robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
}
std::vector<std::pair<double, double> > pts;
const int seen = obstaclePoints(makeBody(), grid, 0.0, 0.0, 2.8, 1, 200, pts);
EXPECT_EQ(seen, 1);
ASSERT_EQ(pts.size(), 1u);
EXPECT_NEAR(pts[0].first, 1.0, kRes);
}
TEST(BodyObstaclePoints, NearestPointsSurviveTheCap)
{
// Chạm trần thì giữ điểm GẦN NHẤT: vật cản sát người mới là thứ quyết định lệnh.
Costmap2D grid = makeGrid();
setLethal(grid, 0.8, 0.0);
for (double y = -1.0; y <= 1.0; y += kRes)
{
setLethal(grid, 2.5, y);
}
std::vector<std::pair<double, double> > pts;
const int seen = obstaclePoints(makeBody(), grid, 0.0, 0.0, 2.8, 1, 3, pts);
EXPECT_GT(seen, 3);
ASSERT_EQ(pts.size(), 3u);
EXPECT_NEAR(std::hypot(pts[0].first, pts[0].second), 0.8, kRes);
}
TEST(BodyObstaclePoints, RangeIsARadiusNotABox)
{
Costmap2D grid = makeGrid();
setLethal(grid, 1.4, 1.4); // trong hộp bao 1.5 nhưng cách tâm 1.98 m
std::vector<std::pair<double, double> > pts;
EXPECT_EQ(obstaclePoints(makeBody(), grid, 0.0, 0.0, 1.5, 1, 200, pts), 0);
EXPECT_EQ(obstaclePoints(makeBody(), grid, 0.0, 0.0, 2.5, 1, 200, pts), 1);
}
TEST(BodyObstaclePoints, TheSolverSeesWhatTheSweepProbes)
{
// Bất biến trung tâm của file này: thứ solver nạp vào đúng bằng thứ phép quét sẽ dò. Trước kia
// solver nạp >= 253 còn phép quét dò >= 254 — hai bên thấy hai môi trường khác nhau và cãi nhau
// ở mọi hàng người.
Costmap2D grid = makeGrid();
wallAt(grid, 1.0);
std::vector<std::pair<double, double> > pts;
const int seen = obstaclePoints(makeBody(), grid, 0.0, 0.0, 2.8, 1, 500, pts);
EXPECT_GT(seen, 0);
EXPECT_TRUE(sweep(makeBody(), grid, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
}
// ================================================================================================
// circleApproximation — optimizer và tầng an toàn phải cùng một thân
// ================================================================================================
TEST(BodyCircles, RadiusIsTheInscribedHalfWidthPlusPadding)
{
// Đây là con số quyết định khe hẹp nhất robot lọt. Lấy bán kính NGOẠI TIẾP (0.755) thì thân
// phình tới góc chéo và khe cần 1.6 m; lấy nửa rộng đã đệm thì khe cần 1.06 m — bằng đúng số
// của tầng an toàn và của global planner.
const robot_costmap_2d::CircleApproximation c = circleApproximation(makeBody(0.05), 3);
EXPECT_EQ(c.count, 3);
EXPECT_NEAR(c.radius, kHalfWid + 0.05, 1e-9);
}
TEST(BodyCircles, CirclesCoverTheWholeLength)
{
// Circle ngoài cùng phải với tới mũi đã đệm, nếu không mũi robot vô hình với optimizer.
const double padding = 0.05;
const robot_costmap_2d::CircleApproximation c = circleApproximation(makeBody(padding), 3);
const double outer_centre = 0.5 * c.spacing * (c.count - 1);
const double reach = std::sqrt(c.radius * c.radius - (kHalfWid + padding) * (kHalfWid + padding));
EXPECT_NEAR(outer_centre + reach, kHalfLen + padding, 1e-6);
}
TEST(BodyCircles, PaddingFlowsThrough)
{
EXPECT_NEAR(circleApproximation(makeBody(0.0), 3).radius, kHalfWid, 1e-9);
EXPECT_NEAR(circleApproximation(makeBody(0.20), 3).radius, kHalfWid + 0.20, 1e-9);
}
TEST(BodyCircles, SingleCircleMustCoverTheLength)
{
const robot_costmap_2d::CircleApproximation c = circleApproximation(makeBody(0.05), 1);
EXPECT_EQ(c.count, 1);
EXPECT_NEAR(c.radius, kHalfLen + 0.05, 1e-9);
EXPECT_EQ(c.spacing, 0.0);
}
TEST(BodyCircles, UnbuiltModelYieldsNoCircles)
{
BodyModel empty;
EXPECT_EQ(circleApproximation(empty, 3).count, 0);
}
TEST(BodyCircles, TheGapTheCirclesFitMatchesTheGapTheSweepAllows)
{
// Bất biến cuối: khe hẹp nhất mà chuỗi circle lọt = khe hẹp nhất mà phép quét cho qua. Trước kia
// hai số này là 1.30 m và 1.06 m, và mọi hàng người rộng 1.1-1.3 m là một vòng replan vô tận.
const BodyModel body = makeBody(0.05);
const robot_costmap_2d::CircleApproximation c = circleApproximation(body, 3);
const double gap_circles = 2.0 * c.radius;
// Khe rộng hơn 2r một chút: cả hai phải cho qua.
Costmap2D wide = makeGrid();
for (double x = 0.8; x <= 1.4; x += kRes)
{
setLethal(wide, x, 0.5 * gap_circles + 0.06);
setLethal(wide, x, -(0.5 * gap_circles + 0.06));
}
EXPECT_FALSE(sweep(body, wide, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
// Khe hẹp hơn 2r: cả hai phải chặn.
Costmap2D narrow = makeGrid();
for (double x = 0.8; x <= 1.4; x += kRes)
{
setLethal(narrow, x, 0.5 * gap_circles - 0.06);
setLethal(narrow, x, -(0.5 * gap_circles - 0.06));
}
EXPECT_TRUE(sweep(body, narrow, 0.0, 0.0, 0.0, 0.4, 0.0, SweepParams()).hit);
}

View File

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

View File

@@ -0,0 +1,683 @@
#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;
}
// Dense vertical sheet at x (odom): with step / x <= 0.01 every ray bin it covers gets a return,
// unlike object(), whose 6 cm gaps let the rays through.
std::vector<Eigen::Vector3d> sheet(double x, double y0, double y1, double z0, double z1, double step = .01)
{
std::vector<Eigen::Vector3d> pts;
for (double y = y0; y <= y1 + 1e-9; y += step)
for (double z = z0; z <= z1 + 1e-9; z += step)
pts.emplace_back(x, y, z);
return pts;
}
// Far backdrop 2 m ahead, behind everything the guard tests store.
std::vector<Eigen::Vector3d> backdrop()
{
return sheet(2.0, -.10, .60, .05, .60, .015);
}
// 21 x 21 returns 5 mm apart, centred on (x, y0, z0) of a camera_link frame (X forward).
std::vector<Eigen::Vector3f> patch(float x, float y0, float z0)
{
std::vector<Eigen::Vector3f> pts;
for (int i = -10; i <= 10; ++i)
for (int j = -10; j <= 10; ++j)
pts.emplace_back(x, y0 + i * .005f, z0 + j * .005f);
return pts;
}
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, AttachDistanceFollowsTheParameter)
{
DepthCameraFrustum f;
f.build(Eigen::Isometry3d::Identity(), kFovW, kFovV, .15, 2.5, false, .08);
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(.25f, 0, 0))); // 10 cm past the near plane
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(.20f, 0, 0))); // 5 cm past it
const float half_w = std::tan(kFovW / 2);
// 5 cm / 15 cm inside the left face along y: ~4 cm / ~12 cm from its plane.
EXPECT_TRUE(f.nearFace(Eigen::Vector3f(1, half_w - .05f, 0)));
EXPECT_FALSE(f.nearFace(Eigen::Vector3f(1, half_w - .15f, 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)));
}
// ---------------------------------------------------------------------------------------------
// Range image (occlusion guard)
// ---------------------------------------------------------------------------------------------
TEST(DepthCameraRangeImage, NearerReturnsHideAndFartherReturnsShowThrough)
{
using Evidence = DepthCameraRangeImage::Evidence;
DepthCameraRangeImage image;
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // never built
image.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false); // X forward
for (const Eigen::Vector3f& p : patch(1, 0, 0))
image.addSensorPoint(p);
EXPECT_EQ(image.test(Eigen::Vector3f(2, 0, 0)), Evidence::kOccluded); // behind the patch
EXPECT_EQ(image.test(Eigen::Vector3f(.5f, 0, 0)), Evidence::kSeenThrough); // in front of it
EXPECT_EQ(image.test(Eigen::Vector3f(1, 0, 0)), Evidence::kNone); // on it
EXPECT_EQ(image.test(Eigen::Vector3f(1, .5f, 0)), Evidence::kNone); // no return on that ray
EXPECT_EQ(image.test(Eigen::Vector3f(.05f, 0, 0)), Evidence::kNone); // too close to judge
}
TEST(DepthCameraRangeImage, OpticalFrameGivesTheSameEvidence)
{
using Evidence = DepthCameraRangeImage::Evidence;
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
T.linear() << 0, 0, 1, -1, 0, 0, 0, -1, 0; // optical axes expressed in camera_link
DepthCameraRangeImage link, optical;
link.reset(Eigen::Isometry3d::Identity(), kFovW, kFovV, false);
optical.reset(T, kFovW, kFovV, true);
const Eigen::Isometry3f optical_from_link = T.inverse().cast<float>();
// Off-centre patch (left and up), so a mirrored axis would answer for the wrong ray.
for (const Eigen::Vector3f& p : patch(1, .3f, .1f))
{
link.addSensorPoint(p);
optical.addSensorPoint(optical_from_link * p);
}
const Eigen::Vector3f behind(2, .6f, .2f), mirrored(2, -.6f, -.2f), in_front(.5f, .15f, .05f);
EXPECT_EQ(link.test(behind), Evidence::kOccluded);
EXPECT_EQ(link.test(mirrored), Evidence::kNone);
EXPECT_EQ(link.test(in_front), Evidence::kSeenThrough);
EXPECT_EQ(optical.test(behind), Evidence::kOccluded);
EXPECT_EQ(optical.test(mirrored), Evidence::kNone);
EXPECT_EQ(optical.test(in_front), Evidence::kSeenThrough);
}
// ---------------------------------------------------------------------------------------------
// 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);
}
class DepthCameraAttachTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["depth_cam"]["attach_distance"] = .08;
}
};
TEST_F(DepthCameraAttachTest, NarrowerAttachBandMarksCloserToTheFaces)
{
// The scene of AttachBandIsNotMarked: 10 cm past the near plane is outside an 8 cm band.
frame(wall());
const std::size_t wall_points = layer.storedPoints();
ASSERT_GT(wall_points, 0u);
frame(join(object(.25, .10, .19), wall()));
EXPECT_GT(layer.storedPoints(), wall_points);
}
// ---------------------------------------------------------------------------------------------
// Occlusion guard
// ---------------------------------------------------------------------------------------------
class DepthCameraGuardTest : public DepthCameraLayerTest
{
protected:
void configure(YAML::Node& cfg) override
{
cfg["number_clearing_threshold"] = 1; // as on the KIT robot
cfg["occlusion_guard"] = guard();
}
virtual bool guard() const
{
return true;
}
};
class DepthCameraNoGuardTest : public DepthCameraGuardTest
{
protected:
bool guard() const override
{
return false;
}
};
// A box 1.42 m ahead, then a screen 1 m ahead that hides it (a person walking past it).
std::vector<Eigen::Vector3d> hiddenBox()
{
return object(1.42, .13, .30);
}
std::vector<Eigen::Vector3d> screen()
{
return sheet(1.0, -.02, .22, .16, .36);
}
TEST_F(DepthCameraNoGuardTest, HiddenBoxIsClearedWithoutTheGuard)
{
frame(hiddenBox());
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
frame(screen()); // no cloud point near the box: the kd-tree test clears it
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraGuardTest, HiddenBoxIsKeptWithTheGuard)
{
frame(hiddenBox());
ASSERT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame(screen());
EXPECT_EQ(master(1.41, .11), LETHAL_OBSTACLE);
frame(backdrop()); // the screen is gone and the camera sees past the box: now it goes
EXPECT_NE(master(1.41, .11), LETHAL_OBSTACLE);
}
// A box in front of the backdrop moves 18 cm to the left. Its old column y = .22 (corner .20)
// still has a point of the moved box (y = .28) within check_radius, so only the rays show that
// the column is empty. Checked at (1.01, .21): stored corners sit on cell edges, and corner .20
// is the only one that lands in that master cell (corner .15 falls back into the .10 cell).
std::vector<Eigen::Vector3d> boxBefore()
{
return object(1.02, .16, .30);
}
std::vector<Eigen::Vector3d> boxAfter()
{
return object(1.02, .34, .30);
}
TEST_F(DepthCameraNoGuardTest, MovedBoxLeavesAGhostWithoutTheGuard)
{
frame(join(boxBefore(), backdrop()));
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
frame(join(boxAfter(), backdrop()));
EXPECT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
}
TEST_F(DepthCameraGuardTest, MovedBoxLeavesNoGhostWithTheGuard)
{
frame(join(boxBefore(), backdrop()));
ASSERT_EQ(master(1.01, .21), LETHAL_OBSTACLE);
frame(join(boxAfter(), backdrop()));
EXPECT_NE(master(1.01, .21), LETHAL_OBSTACLE);
EXPECT_EQ(master(1.01, .26), LETHAL_OBSTACLE); // the moved box itself (its y = .28 column)
}
TEST_F(DepthCameraGuardTest, SolidBoxSeenAgainIsKept)
{
// A real surface returns on every ray at its own range: no evidence, the kd-tree test keeps it.
const std::vector<Eigen::Vector3d> box = sheet(1.02, .05, .20, .22, .38);
frame(join(box, backdrop()));
ASSERT_EQ(master(), LETHAL_OBSTACLE);
for (int i = 0; i < 5; ++i)
frame(join(box, backdrop()));
EXPECT_EQ(master(), LETHAL_OBSTACLE);
}
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);
cfg = baseConfig();
cfg["depth_cam"]["attach_distance"] = -.01;
expectThrow(cfg);
cfg = baseConfig();
cfg["depth_cam"]["attach_distance"] = 1.2; // near and far bands would meet: (2.5 - .15) / 2
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);
}

View File

@@ -0,0 +1,280 @@
#include <robot_costmap_2d/direction_field.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
using namespace robot_costmap_2d;
namespace
{
DirectionGeometry geometry()
{
return {4, 4, 1.0, 0.0, 0.0, "map"};
}
robot_nav_msgs::OccupancyGrid grid()
{
robot_nav_msgs::OccupancyGrid g;
g.header.frame_id = "/map";
g.info.width = 4;
g.info.height = 4;
g.info.resolution = 1;
g.data.assign(16, 0);
return g;
}
auto field(const robot_nav_msgs::OccupancyGrid& g)
{
return DirectionField::create(g, geometry(), M_PI / 2.0);
}
using Cell = std::pair<int64_t, int64_t>;
std::vector<Cell> cells(double x0, double y0, double x1, double y1)
{
std::vector<Cell> out;
EXPECT_TRUE(traverseGridSegment(x0, y0, x1, y1, [&](int64_t x, int64_t y)
{
out.emplace_back(x, y);
return true;
}));
return out;
}
} // namespace
TEST(DirectionContract, CodesAndSizes)
{
auto g = grid();
ASSERT_TRUE(field(g));
EXPECT_FALSE(field(g)->hasConstraints());
for (int code = 0; code <= 8; ++code)
{
g.data[0] = code;
auto f = field(g);
ASSERT_TRUE(f);
EXPECT_EQ(f->code(0, 0), code);
}
for (int code : {-128, -2, -1, 9, 100, 127})
{
g.data[0] = code;
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kCode);
}
g.data.clear();
auto f = field(g);
ASSERT_TRUE(f);
EXPECT_FALSE(f->hasConstraints());
EXPECT_EQ(f->code(3, 3), 0);
g.data.assign(15, 0);
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kSize);
g.info.width = UINT32_MAX;
g.info.height = UINT32_MAX;
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kOverflow);
}
TEST(DirectionContract, CheckedCellAccess)
{
auto g = grid();
g.data[15] = 8;
const auto f = field(g);
ASSERT_TRUE(f);
uint8_t code = 99;
EXPECT_TRUE(f->codeAt(3, 3, &code));
EXPECT_EQ(code, 8);
EXPECT_TRUE(f->codeAt(0, 0, &code));
EXPECT_EQ(code, 0);
code = 99;
EXPECT_FALSE(f->codeAt(-1, 0, &code));
EXPECT_FALSE(f->codeAt(0, -1, &code));
EXPECT_FALSE(f->codeAt(4, 0, &code));
EXPECT_FALSE(f->codeAt(0, 4, &code));
EXPECT_FALSE(f->codeAt(INT64_MAX, INT64_MAX, &code));
EXPECT_FALSE(f->codeAt(0, 0, nullptr));
EXPECT_EQ(code, 99);
g.data.clear();
const auto empty = field(g);
ASSERT_TRUE(empty);
EXPECT_TRUE(empty->codeAt(3, 3, &code));
EXPECT_EQ(code, 0);
code = 99;
EXPECT_FALSE(empty->codeAt(4, 3, &code));
EXPECT_EQ(code, 99);
}
TEST(DirectionContract, GeometryAndNonFinite)
{
auto g = grid();
EXPECT_TRUE(field(g));
g.header.frame_id = "";
EXPECT_EQ(validateDirectionGrid(g, geometry()).error, DirectionValidationError::kFrame);
g.header.frame_id = "other";
EXPECT_FALSE(field(g));
g = grid();
g.info.width = 3;
EXPECT_FALSE(field(g));
g = grid();
g.info.resolution = 0.5;
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.position.x = 0.01;
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.position.y = 0.01;
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.orientation.z = 0.1;
g.info.origin.orientation.w = 1;
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.orientation.w = 1;
EXPECT_TRUE(field(g));
g.info.origin.orientation.w = -1;
EXPECT_TRUE(field(g));
g = grid();
EXPECT_TRUE(field(g)); // Default zero quaternion.
g.info.origin.position.x = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE(field(g));
g = grid();
g.info.resolution = std::numeric_limits<float>::infinity();
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.position.z = std::numeric_limits<double>::infinity();
EXPECT_FALSE(field(g));
g = grid();
g.info.origin.orientation.w = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE(field(g));
}
TEST(DirectionRule, AllDirectionsAndBoundaries)
{
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
for (int k = 0; k < 8; ++k)
{
auto g = grid();
g.data.assign(16, k + 1);
auto f = field(g);
ASSERT_TRUE(f);
const double x = 1.5;
const double y = 1.5;
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vx[k], y + 0.2 * vy[k]), SegmentResult::kAllowed);
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vx[k], y - 0.2 * vy[k]), SegmentResult::kViolation);
EXPECT_EQ(f->checkSegment(x, y, x - 0.2 * vy[k], y + 0.2 * vx[k]), SegmentResult::kAllowed);
EXPECT_EQ(f->checkSegment(x, y, x + 0.2 * vy[k], y - 0.2 * vx[k]), SegmentResult::kAllowed);
EXPECT_EQ(f->checkSegment(x, y, x, y), SegmentResult::kAllowed);
}
auto g = grid();
g.data.assign(16, 1);
auto f = field(g);
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 - 1e-6, 1.7), SegmentResult::kViolation);
EXPECT_EQ(f->checkSegment(1.5, 1.5, 1.5 + 1e-6, 1.7), SegmentResult::kAllowed);
EXPECT_EQ(allowedDirectionMask(-1e-11, 1.0, M_PI / 2.0) & 1, 1);
EXPECT_EQ(allowedDirectionMask(-1e-6, 1.0, M_PI / 2.0) & 1, 0);
}
TEST(DirectionRule, MaskMatchesDotProducts)
{
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
for (int x = -12; x <= 12; ++x)
{
for (int y = -12; y <= 12; ++y)
{
auto mask = allowedDirectionMask(x, y, M_PI / 2.0);
for (int k = 0; k < 8; ++k)
EXPECT_EQ(bool(mask & (1u << k)), vx[k] * x + vy[k] * y >= 0);
}
}
}
TEST(DirectionRule, RightAngleMatchesLegacySweep)
{
constexpr int vx[] = {1, 1, 0, -1, -1, -1, 0, 1};
constexpr int vy[] = {0, 1, 1, 1, 0, -1, -1, -1};
const auto check = [&](double dx, double dy)
{
uint8_t reference = 0;
const long double x = dx, y = dy;
const long double tolerance = 1e-9L * (std::abs(x) + std::abs(y));
for (int k = 0; k < 8; ++k)
if (vx[k] * x + vy[k] * y >= -tolerance)
reference |= uint8_t(1u << k);
EXPECT_EQ(allowedDirectionMask(dx, dy, M_PI / 2.0), reference) << dx << "," << dy;
};
for (double magnitude : {1e-100, 0.01, 1.0, 1e100})
{
for (int degree = 0; degree < 360; ++degree)
check(magnitude * std::cos(degree * M_PI / 180.0), magnitude * std::sin(degree * M_PI / 180.0));
for (int k = 0; k < 8; ++k)
check(magnitude * vx[k], magnitude * vy[k]);
check(-1.0000000005e-9 * magnitude, magnitude); // Near the legacy tolerance boundary.
}
check(0, 0);
EXPECT_EQ(allowedDirectionMask(std::numeric_limits<double>::infinity(), 0, M_PI / 2.0), 0);
EXPECT_EQ(allowedDirectionMask(0, std::numeric_limits<double>::quiet_NaN(), M_PI / 2.0), 0);
}
TEST(DirectionRule, ConfigurableAngularBoundaries)
{
const auto mask = allowedDirectionMask(1, 0.5, M_PI / 4.0);
EXPECT_NE(mask & (1u << 0), 0);
EXPECT_NE(mask & (1u << 1), 0);
EXPECT_EQ(mask & (1u << 2), 0);
const auto boundary = allowedDirectionMask(1, 1, M_PI / 4.0);
EXPECT_NE(boundary & (1u << 0), 0);
EXPECT_NE(boundary & (1u << 2), 0);
EXPECT_EQ(allowedDirectionMask(1, 1.01, M_PI / 4.0) & 1u, 0);
EXPECT_EQ(allowedDirectionMask(0, 1, M_PI / 6.0) & 1u, 0);
EXPECT_EQ(allowedDirectionMask(0, 0, M_PI / 6.0), 255);
}
TEST(DirectionRule, FieldUsesItsDeviationForCrossing)
{
auto g = grid();
g.data.assign(16, 3); // +Y zone, crossed along +X.
const auto wide = DirectionField::create(g, geometry(), M_PI / 2.0);
const auto narrow = DirectionField::create(g, geometry(), M_PI / 4.0);
ASSERT_TRUE(wide && narrow);
EXPECT_DOUBLE_EQ(narrow->maxDeviationRad(), M_PI / 4.0);
EXPECT_EQ(wide->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kAllowed);
EXPECT_EQ(narrow->checkSegment(0.5, 1.5, 3.5, 1.5), SegmentResult::kViolation);
}
TEST(DirectionDDA, OwnedEdgesCornersEndpointsAndReverse)
{
EXPECT_EQ(cells(1, 0.2, 1, 2.8), (std::vector<Cell>{{1, 0}, {1, 1}, {1, 2}}));
EXPECT_EQ(cells(1, 2.8, 1, 0.2), (std::vector<Cell>{{1, 2}, {1, 1}, {1, 0}}));
EXPECT_EQ(cells(0.5, 0.5, 2.5, 2.5), (std::vector<Cell>{{0, 0}, {1, 1}, {2, 2}}));
EXPECT_EQ(cells(0, 0, 6, 4),
(std::vector<Cell>{{0, 0}, {1, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 2}, {4, 3}, {5, 3}}));
EXPECT_EQ(cells(0.5, 0.5, 2.0, 0.5), (std::vector<Cell>{{0, 0}, {1, 0}}));
EXPECT_EQ(cells(2.0, 0.5, 0.5, 0.5), (std::vector<Cell>{{1, 0}, {0, 0}}));
for (auto p : std::vector<std::vector<double>>{{0.2, 0.3, 3.8, 2.7}, {1, 0.2, 1, 3.5}, {0.5, 0.5, 3.5, 3.5}})
{
auto a = cells(p[0], p[1], p[2], p[3]);
auto b = cells(p[2], p[3], p[0], p[1]);
std::reverse(b.begin(), b.end());
EXPECT_EQ(a, b);
EXPECT_EQ(std::set<Cell>(a.begin(), a.end()).size(), a.size());
}
}
TEST(DirectionDDA, QueriesCrossZonesAndRejectOutside)
{
auto g = grid();
g.data[1] = 5;
g.data[2] = 5;
auto f = field(g);
SegmentViolation v{};
EXPECT_EQ(f->checkSegment(0.2, 0.5, 3.5, 0.5, &v), SegmentResult::kViolation);
EXPECT_EQ(v.x, 1u);
EXPECT_EQ(v.code, 5);
EXPECT_EQ(f->checkSegment(3.5, 0.5, 0.2, 0.5), SegmentResult::kAllowed);
EXPECT_EQ(f->checkSegment(0.2, 0.5, 1.0, 0.5), SegmentResult::kAllowed);
EXPECT_EQ(f->checkSegment(0.2, 0.5, 4.0, 0.5), SegmentResult::kOutOfGrid);
EXPECT_EQ(f->checkSegment(-0.1, 0.5, 0.1, 0.5), SegmentResult::kOutOfGrid);
EXPECT_EQ(f->checkSegment(4, 0.5, 4, 0.5), SegmentResult::kOutOfGrid);
}

View File

@@ -0,0 +1,367 @@
#include <robot_costmap_2d/directional_layer.h>
#include <robot_costmap_2d/critical_layer.h>
#include <robot_costmap_2d/static_layer.h>
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <boost/make_shared.hpp>
#include <boost/thread/locks.hpp>
#include <gtest/gtest.h>
#include <tf3/buffer_core.h>
using namespace robot_costmap_2d;
namespace
{
class LayerTest : public ::testing::Test
{
protected:
std::string directory_;
std::string old_env_;
bool had_env_ = false;
tf3::BufferCore tf_{tf3::Duration(10.0)};
void SetUp() override
{
const char* old = std::getenv("PNKX_NAV_CORE_CONFIG_DIR");
if (old)
{
had_env_ = true;
old_env_ = old;
}
char pattern[] = "/tmp/direction-layer-test-XXXXXX";
char* path = mkdtemp(pattern);
ASSERT_NE(path, nullptr);
directory_ = path;
std::filesystem::create_directory(directory_ + "/config");
ASSERT_EQ(setenv("PNKX_NAV_CORE_CONFIG_DIR", directory_.c_str(), 1), 0);
config(true);
std::ofstream static_config(directory_ + "/config/static_layer_params.yaml");
static_config << "static_layer:\n enabled: true\n map_topic: map\n"
" first_map_only: false\n subscribe_to_updates: true\n";
}
void TearDown() override
{
if (had_env_)
setenv("PNKX_NAV_CORE_CONFIG_DIR", old_env_.c_str(), 1);
else
unsetenv("PNKX_NAV_CORE_CONFIG_DIR");
std::filesystem::remove_all(directory_);
}
void config(bool enabled, double max_deviation_deg = 90.0)
{
std::ofstream out(directory_ + "/config/directional_layer_params.yaml");
out << "directional_layer:\n enabled: " << (enabled ? "true" : "false")
<< "\n map_topic: map\n direction_topic: direction_map\n max_deviation_deg: " << max_deviation_deg
<< "\n debug_state: false\n";
}
robot_nav_msgs::OccupancyGrid grid()
{
robot_nav_msgs::OccupancyGrid g;
g.header.frame_id = "map";
g.info.width = 4;
g.info.height = 4;
g.info.resolution = 1;
g.data.assign(16, 0);
return g;
}
};
TEST_F(LayerTest, StaticAndCriticalReadinessTracksWrites)
{
for (bool critical : {false, true})
{
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
boost::shared_ptr<Layer> layer = critical
? boost::static_pointer_cast<Layer>(boost::make_shared<CriticalLayer>())
: boost::static_pointer_cast<Layer>(boost::make_shared<StaticLayer>());
layer->initialize(&master, critical ? "critical" : "static", &tf_);
master.addPlugin(layer);
EXPECT_FALSE(layer->isCurrent());
EXPECT_FALSE(master.isCurrent());
robot_map_msgs::OccupancyGridUpdate early_update;
early_update.x = early_update.y = 0;
early_update.width = early_update.height = 1;
early_update.data.assign(1, 100);
layer->dataCallBack(early_update, "map_updates");
EXPECT_FALSE(layer->isCurrent());
auto map = grid();
map.data[0] = 100;
layer->dataCallBack(map, "map");
EXPECT_FALSE(layer->isCurrent());
layer->updateCosts(*master.getCostmap(), 0, 0, 0, 0);
EXPECT_FALSE(layer->isCurrent());
master.updateMap(0, 0, 0);
EXPECT_TRUE(layer->isCurrent());
layer->reset();
EXPECT_FALSE(layer->isCurrent());
master.updateMap(0, 0, 0);
EXPECT_TRUE(layer->isCurrent());
EXPECT_TRUE(master.isCurrent());
EXPECT_NE(master.getCostmap()->getCost(0, 0), FREE_SPACE);
map.data[1] = 100;
map.data[15] = 100;
layer->dataCallBack(map, "map");
EXPECT_FALSE(layer->isCurrent());
robot_map_msgs::OccupancyGridUpdate update;
update.x = 0;
update.y = 0;
update.width = 1;
update.height = 1;
update.data.assign(1, 100);
layer->dataCallBack(update, "map_updates");
EXPECT_FALSE(layer->isCurrent());
master.updateMap(0, 0, 0);
EXPECT_TRUE(layer->isCurrent());
EXPECT_EQ(master.getCostmap()->getCost(3, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
update.x = 0;
update.y = 3;
layer->dataCallBack(update, "map_updates");
update.x = 3;
update.y = 0;
layer->dataCallBack(update, "map_updates");
EXPECT_FALSE(layer->isCurrent());
master.updateMap(0, 0, 0);
EXPECT_TRUE(layer->isCurrent());
EXPECT_EQ(master.getCostmap()->getCost(0, 3), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
EXPECT_EQ(master.getCostmap()->getCost(3, 0), critical ? CRITICAL_SPACE : LETHAL_OBSTACLE);
update.x = -1;
layer->dataCallBack(update, "map_updates");
EXPECT_TRUE(layer->isCurrent());
master.resizeMap(4, 4, 1, 0, 0);
EXPECT_FALSE(layer->isCurrent());
layer->dataCallBack(map, "map");
EXPECT_FALSE(layer->isCurrent());
master.updateMap(0, 0, 0);
EXPECT_TRUE(layer->isCurrent());
}
}
TEST_F(LayerTest, InvalidMaxDeviationThrows)
{
for (double degrees : {0.0, 180.0, -5.0, 200.0})
{
config(true, degrees);
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
DirectionalLayer layer;
EXPECT_THROW(layer.initialize(&master, "directional", &tf_), std::runtime_error) << degrees;
}
}
TEST_F(LayerTest, ReadyFieldCarriesConfiguredDeviation)
{
config(true, 45.0);
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
DirectionalLayer layer;
ASSERT_NO_THROW(layer.initialize(&master, "directional", &tf_));
auto g = grid();
layer.dataCallBack(g, "map");
layer.dataCallBack(g, "direction_map");
const auto snapshot = layer.directionSnapshot();
ASSERT_EQ(snapshot.state, DirectionFieldState::kReady);
ASSERT_TRUE(snapshot.field);
EXPECT_DOUBLE_EQ(snapshot.field->maxDeviationRad(), M_PI / 4.0);
}
TEST_F(LayerTest, LifecycleAndProvider)
{
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
auto layer = boost::make_shared<DirectionalLayer>();
layer->initialize(&master, "directional", &tf_);
master.addPlugin(layer);
auto g = grid();
auto s = master.getDirectionFieldSnapshot();
EXPECT_EQ(s.state, DirectionFieldState::kPending);
EXPECT_FALSE(layer->isCurrent());
layer->dataCallBack(g, "direction_map");
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
double min_x = 1;
double min_y = 2;
double max_x = 3;
double max_y = 4;
layer->updateBounds(0, 0, 0, &min_x, &min_y, &max_x, &max_y);
EXPECT_DOUBLE_EQ(min_x, 1);
EXPECT_DOUBLE_EQ(min_y, 2);
EXPECT_DOUBLE_EQ(max_x, 3);
EXPECT_DOUBLE_EQ(max_y, 4);
auto& costs = *master.getCostmap();
costs.setCost(0, 0, 42);
layer->updateCosts(costs, 0, 0, 4, 4);
EXPECT_EQ(costs.getCost(0, 0), 42);
layer->dataCallBack(7, "map");
layer->dataCallBack(g, "other_topic");
EXPECT_EQ(layer->directionSnapshot().generation, s.generation);
layer->dataCallBack(g, "/map");
s = layer->directionSnapshot();
EXPECT_EQ(s.state, DirectionFieldState::kPending);
g.data[0] = 1;
layer->dataCallBack(g, "/direction_map");
auto ready = master.getDirectionFieldSnapshot();
EXPECT_EQ(ready.state, DirectionFieldState::kReady);
ASSERT_TRUE(ready.field);
EXPECT_TRUE(layer->isCurrent());
EXPECT_GT(ready.generation, s.generation);
g.data[0] = 100;
layer->dataCallBack(g, "direction_map");
s = layer->directionSnapshot();
EXPECT_EQ(s.generation, ready.generation);
EXPECT_EQ(s.field, ready.field);
layer->reset();
EXPECT_EQ(layer->directionSnapshot().field, ready.field);
g.data.clear();
layer->dataCallBack(g, "direction_map");
s = layer->directionSnapshot();
ASSERT_TRUE(s.field);
EXPECT_FALSE(s.field->hasConstraints());
EXPECT_GT(s.generation, ready.generation);
layer->dataCallBack(g, "map");
s = layer->directionSnapshot();
EXPECT_EQ(s.state, DirectionFieldState::kPending);
EXPECT_FALSE(s.field);
EXPECT_FALSE(layer->isCurrent());
layer->dataCallBack(g, "direction_map");
layer->matchSize();
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
layer->dataCallBack(g, "direction_map");
master.getCostmap()->resizeMap(3, 3, 1, 0, 0);
layer->reset();
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
master.resizeMap(4, 4, 1, 0, 0);
layer->dataCallBack(g, "direction_map");
master.resizeMap(3, 3, 1, 0, 0);
EXPECT_EQ(layer->directionSnapshot().state, DirectionFieldState::kPending);
}
TEST_F(LayerTest, DisabledAndMultipleProviders)
{
config(false);
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
auto disabled = boost::make_shared<DirectionalLayer>();
disabled->initialize(&master, "directional", &tf_);
master.addPlugin(disabled);
EXPECT_TRUE(disabled->isCurrent());
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kDisabled);
config(true);
auto a = boost::make_shared<DirectionalLayer>();
a->initialize(&master, "first", &tf_);
master.addPlugin(a);
auto b = boost::make_shared<DirectionalLayer>();
b->initialize(&master, "second", &tf_);
master.addPlugin(b);
EXPECT_EQ(master.getDirectionFieldSnapshot().state, DirectionFieldState::kPending);
}
TEST_F(LayerTest, RollingCostmapStaysPending)
{
LayeredCostmap master("map", true, false);
master.resizeMap(4, 4, 1, 0, 0);
DirectionalLayer layer;
layer.initialize(&master, "directional", &tf_);
auto g = grid();
layer.dataCallBack(g, "map");
layer.dataCallBack(g, "direction_map");
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
EXPECT_FALSE(layer.isCurrent());
}
TEST_F(LayerTest, StaticMapCallbackDoesNotWaitForMasterMutex)
{
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
DirectionalLayer layer;
layer.initialize(&master, "directional", &tf_);
auto g = grid();
std::mutex completion_mutex;
std::condition_variable completion;
bool done = false;
bool completed_while_locked = false;
std::thread callback;
{
boost::unique_lock<Costmap2D::mutex_t> master_lock(*master.getCostmap()->getMutex());
callback = std::thread([&]
{
layer.dataCallBack(g, "map");
{
std::lock_guard<std::mutex> lock(completion_mutex);
done = true;
}
completion.notify_one();
});
std::unique_lock<std::mutex> lock(completion_mutex);
completed_while_locked = completion.wait_for(lock, std::chrono::seconds(2), [&] { return done; });
}
callback.join();
EXPECT_TRUE(completed_while_locked);
EXPECT_EQ(layer.directionSnapshot().state, DirectionFieldState::kPending);
}
TEST_F(LayerTest, OldSnapshotSurvivesConcurrentReplacement)
{
LayeredCostmap master("map", false, false);
master.resizeMap(4, 4, 1, 0, 0);
auto layer = boost::make_shared<DirectionalLayer>();
layer->initialize(&master, "directional", &tf_);
master.addPlugin(layer);
auto g = grid();
g.data[0] = 1;
layer->dataCallBack(g, "map");
layer->dataCallBack(g, "direction_map");
auto old = master.getDirectionFieldSnapshot();
ASSERT_TRUE(old.field);
std::atomic<bool> start{false};
std::atomic<bool> ok{true};
std::thread reader([&]
{
while (!start.load())
{
}
for (int i = 0; i < 1000; ++i)
{
auto s = master.getDirectionFieldSnapshot();
if (!s.field || old.field->code(0, 0) != 1)
ok = false;
}
});
std::thread updater([&]
{
while (!start.load())
{
}
for (int i = 0; i < 1000; ++i)
layer->updateBounds(0, 0, 0, nullptr, nullptr, nullptr, nullptr);
});
start = true;
g.data[0] = 3;
layer->dataCallBack(g, "direction_map");
reader.join();
updater.join();
EXPECT_TRUE(ok.load());
EXPECT_EQ(old.field->code(0, 0), 1);
EXPECT_EQ(master.getDirectionFieldSnapshot().field->code(0, 0), 3);
}
} // namespace