first commit
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# Bỏ qua thư mục build/ (cmake -S . -B build)
|
||||
build/
|
||||
109
CMakeLists.txt
Normal file
109
CMakeLists.txt
Normal file
@@ -0,0 +1,109 @@
|
||||
cmake_minimum_required(VERSION 3.10)
|
||||
project(voronoi_route VERSION 0.1.0 LANGUAGES CXX)
|
||||
|
||||
# Standalone CMake, no catkin: the library runs inside RBApp (a plain CMake project), called once
|
||||
# per map right after the scanned map is copied into data/maps/<id>/. RBApp pulls it in either by
|
||||
# `find_package(voronoi_route)` after `cmake --install`, or by compiling src/*.cpp into robot_app
|
||||
# the way it does robot_time; the exported target is voronoi_route::voronoi_route.
|
||||
#
|
||||
# cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build -j
|
||||
# ./build/voronoi_route_compile --map <map.yaml>
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE Release)
|
||||
endif()
|
||||
|
||||
option(VORONOI_ROUTE_BUILD_TOOLS "Build voronoi_route_compile (needs OpenCV, yaml-cpp, nlohmann_json)" ON)
|
||||
option(VORONOI_ROUTE_BUILD_TESTS "Build GTest unit tests" ON)
|
||||
|
||||
# ---- library ------------------------------------------------------------------------------------
|
||||
add_library(voronoi_route
|
||||
src/dynamic_voronoi.cpp
|
||||
src/voronoi_field.cpp
|
||||
src/voronoi_graph.cpp
|
||||
src/attachment.cpp
|
||||
src/corridor_mask.cpp
|
||||
src/voronoi_route.cpp
|
||||
src/map_convert.cpp
|
||||
src/params.cpp)
|
||||
add_library(voronoi_route::voronoi_route ALIAS voronoi_route)
|
||||
target_include_directories(voronoi_route PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>)
|
||||
target_compile_features(voronoi_route PUBLIC cxx_std_17)
|
||||
target_compile_options(voronoi_route PRIVATE -Wall -Wextra)
|
||||
set_target_properties(voronoi_route PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# ---- bundle I/O (json + pgm), separate so the core stays free of nlohmann ---------------------
|
||||
find_path(NLOHMANN_JSON_INCLUDE_DIR nlohmann/json.hpp HINTS /usr/local/include /usr/include)
|
||||
find_package(yaml-cpp QUIET)
|
||||
if(NLOHMANN_JSON_INCLUDE_DIR AND yaml-cpp_FOUND)
|
||||
add_library(voronoi_route_io src/bundle_io.cpp src/params_io.cpp)
|
||||
add_library(voronoi_route::voronoi_route_io ALIAS voronoi_route_io)
|
||||
target_include_directories(voronoi_route_io PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
PRIVATE ${NLOHMANN_JSON_INCLUDE_DIR})
|
||||
target_link_libraries(voronoi_route_io PUBLIC voronoi_route yaml-cpp)
|
||||
target_compile_options(voronoi_route_io PRIVATE -Wall -Wextra)
|
||||
set_target_properties(voronoi_route_io PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
else()
|
||||
message(WARNING "nlohmann/json.hpp or yaml-cpp not found — voronoi_route_io and the compile tool are skipped")
|
||||
endif()
|
||||
|
||||
# ---- tool ---------------------------------------------------------------------------------------
|
||||
if(VORONOI_ROUTE_BUILD_TOOLS AND TARGET voronoi_route_io)
|
||||
find_package(OpenCV REQUIRED COMPONENTS core imgcodecs imgproc)
|
||||
add_executable(voronoi_route_compile tools/voronoi_route_compile.cpp)
|
||||
target_link_libraries(voronoi_route_compile PRIVATE voronoi_route_io ${OpenCV_LIBS})
|
||||
target_compile_options(voronoi_route_compile PRIVATE -Wall -Wextra)
|
||||
endif()
|
||||
|
||||
# ---- tests --------------------------------------------------------------------------------------
|
||||
if(VORONOI_ROUTE_BUILD_TESTS)
|
||||
find_package(GTest QUIET)
|
||||
if(GTest_FOUND)
|
||||
enable_testing()
|
||||
set(VORONOI_ROUTE_TEST_SOURCES test/voronoi_route_test.cpp)
|
||||
if(TARGET voronoi_route_io)
|
||||
list(APPEND VORONOI_ROUTE_TEST_SOURCES test/params_io_test.cpp)
|
||||
endif()
|
||||
add_executable(voronoi_route_test ${VORONOI_ROUTE_TEST_SOURCES})
|
||||
target_link_libraries(voronoi_route_test PRIVATE voronoi_route GTest::GTest GTest::Main pthread)
|
||||
if(TARGET voronoi_route_io)
|
||||
target_link_libraries(voronoi_route_test PRIVATE voronoi_route_io)
|
||||
target_compile_definitions(voronoi_route_test PRIVATE
|
||||
VORONOI_ROUTE_PACKAGED_PARAMS="${CMAKE_CURRENT_SOURCE_DIR}/config/voronoi_route_params.yaml")
|
||||
endif()
|
||||
add_test(NAME voronoi_route_test COMMAND voronoi_route_test)
|
||||
else()
|
||||
message(STATUS "GTest not found — voronoi_route_test skipped")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# ---- install ------------------------------------------------------------------------------------
|
||||
include(GNUInstallDirs)
|
||||
install(TARGETS voronoi_route EXPORT voronoi_route-targets
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
if(TARGET voronoi_route_io)
|
||||
install(TARGETS voronoi_route_io EXPORT voronoi_route-targets
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
endif()
|
||||
install(DIRECTORY include/voronoi_route DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
|
||||
install(DIRECTORY config/ DESTINATION share/voronoi_route/config)
|
||||
install(EXPORT voronoi_route-targets NAMESPACE voronoi_route:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/voronoi_route)
|
||||
# Minimal package config so a host (RBApp) can `find_package(voronoi_route)`; voronoi_route_io
|
||||
# links yaml-cpp publicly, so the dependency has to be resolved on the consumer side too.
|
||||
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/voronoi_route-config.cmake"
|
||||
"include(CMakeFindDependencyMacro)\n"
|
||||
"find_dependency(yaml-cpp QUIET)\n"
|
||||
"include(\"\${CMAKE_CURRENT_LIST_DIR}/voronoi_route-targets.cmake\")\n")
|
||||
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/voronoi_route-config.cmake"
|
||||
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/voronoi_route)
|
||||
if(TARGET voronoi_route_compile)
|
||||
install(TARGETS voronoi_route_compile RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
endif()
|
||||
191
README.md
Normal file
191
README.md
Normal file
@@ -0,0 +1,191 @@
|
||||
# voronoi_route
|
||||
|
||||
Route graph từ generalized Voronoi diagram (GVD) của một lưới occupancy, và dải hành lang
|
||||
(corridor mask) quanh tuyến giữa hai điểm. Không phụ thuộc ROS, costmap hay planner: vào là
|
||||
`std::vector<uint8_t>` phẳng (1 = vật cản), ra là chuỗi ô và bitmap.
|
||||
|
||||
Nơi chạy: **RBApp**, ngay sau khi khung chương trình copy map quét xong vào
|
||||
`data/maps/<id>/` — map đó chạy qua Voronoi một lần, graph lưu phẳng vào chính thư mục map đó
|
||||
(`voronoi.json` + ảnh phụ). Gói không link vào planner nào; ai cần graph thì đọc bundle. Cách
|
||||
build/chạy/ghép xem `USAGE.md`; thiết kế đầy đủ ở `Test/docs/voronoi_route/VORONOI_ROUTE_LIB_PLAN.md`;
|
||||
đường đưa graph từ host vào nav core (việc của consumer, tách khỏi gói này) ở
|
||||
`Test/docs/ROUTE_GRAPH_INJECTION_PLAN.md`.
|
||||
|
||||
## Thành phần
|
||||
|
||||
| Lớp / hàm | Làm gì |
|
||||
|---|---|
|
||||
| `DynamicVoronoi` | Port nguyên vẹn của Lau, Sprunk, Burgard (ICRA 2010), BSD, từ `Test/simulators/third_party/map_plugins/voronoi_layer`. Chỉ thêm namespace. |
|
||||
| `VoronoiField` | Bọc `DynamicVoronoi` sau lưới phẳng row-major; `rebuild`, `setOccupied/setFree` + `refresh` (incremental), `distanceCells`, `isVoronoi`. |
|
||||
| `VoronoiGraph` | Trích node (ngã rẽ / đầu cụt / node tổng hợp của vòng kín) và edge (chuỗi ô GVD) từ GVD đã prune; lọc spur ngắn; gộp node bậc 2; Dijkstra `route()` giữa hai điểm gắn trên edge. |
|
||||
| `attachPoint` | BFS 8-hướng từ một ô tới ô GVD gần nhất, trả cả đường đi. |
|
||||
| `corridorMask` | Bitmap quanh polyline, nửa bề rộng thích nghi `max(W_min, k × clearance)`, trần `W_max`. |
|
||||
| `VoronoiRoute` | Facade: `rebuild`, `syncOccupancy` (tự chọn incremental / rebuild), `attach`, `query`, `corridorMask`, `stats`, `occupancyHash`. |
|
||||
| `occupancyFromGray` / `occupancyFromGrid` / `occupancyFromCostmap` | Ảnh map_server, OccupancyGrid int8, hay char map costmap → mask vật cản theo `ObstacleRule` (port `StaticLayer::interpretValue` + `allow_unknown`). Lib không decode PNG; host tự decode. |
|
||||
| `saveBundle` / `loadBundleMeta` | Ghi/đọc bundle (`voronoi.json` + 2 PGM) — target riêng `voronoi_route_io` vì cần nlohmann/json. |
|
||||
| `RouteParams` / `loadRouteParams` / `RouteParams::toObstacleRule` / `findConfigFile` | Tham số vận hành theo mét từ `voronoi_route_params.yaml`, kể cả luật "vật cản" (block `obstacle:`, tự chứa — không đọc chéo config costmap/SBPL) (`params.h` core, `params_io.h` trong `voronoi_route_io`, cần yaml-cpp). |
|
||||
| `hashObstacleMask` | FNV-1a 64 trên bitmap vật cản — producer và consumer dùng chung để biết graph có đúng map không. |
|
||||
|
||||
Toạ độ: `x` = cột, `y` = hàng của lưới đưa vào. Với ảnh map_server, hàng 0 là **trên cùng**; đổi
|
||||
sang mét ở biên (tool có `--start-m/--goal-m`).
|
||||
|
||||
## Config
|
||||
|
||||
`config/voronoi_route_params.yaml` — bản mặc định đóng gói, comment tiếng Việt, đơn vị mét. Ba cây
|
||||
đang có bản sao: `Test/move_base2/config/runtime/` (dev/sim), `pnkx_nav_core/config/`; `rb_ws` và
|
||||
RBApp `data/config/runtime/` thêm khi ghép (hỏi trước với `rb_ws`). Tool tìm file này trong
|
||||
`--config-dir` (mặc định `$PNKX_NAV_CORE_CONFIG_DIR`) như costmap tìm `*_layer_params.yaml` — file
|
||||
khớp tên đầu tiên thắng; `--params <file>` chỉ đích danh; không có thì dùng mặc định trong code và
|
||||
nói rõ ở dòng `params :`. Mọi `--flag` chỉ ghi đè cho một lần chạy.
|
||||
|
||||
| Khối | Khoá | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| `graph` | `min_edge_length_m`, `spur_clearance_ratio`, `min_component_length_m`, `min_clearance_m`, `attach_max_radius_m`, `graph_rebuild_min_changed_cells`, `full_rebuild_fraction` | lọc/trích graph, gắn điểm, chính sách cập nhật |
|
||||
| `corridor` | `half_width_min_m`, `clearance_scale`, `half_width_max_m` | bề rộng dải thích nghi |
|
||||
| `bundle` | `write_gvd`, `write_dist`, `write_preview`, `write_graph_image`, `write_graph_overlay` | ghi file nào |
|
||||
| `obstacle` | `track_unknown_space`, `lethal_cost_threshold`, `unknown_cost_value`, `trinary_costmap`, `unknown: traversable\|obstacle`, `roi_margin_m` | luật "vật cản" của riêng gói này, không suy từ config costmap/SBPL nào; `unknown` quyết định thẳng ô chưa quét có chặn Voronoi không; ROI = hộp bao tường + lề, ngoài hộp là vật cản (chặn tia Voronoi bắn từ khe tường ra mép ảnh, bỏ tính vùng unknown ngoài nhà) |
|
||||
|
||||
Khoá thiếu → mặc định + một dòng `params: <khoá>: missing, using default`; giá trị ngoài khoảng →
|
||||
clamp + báo (`validateRouteParams`). Host nạp bằng `loadRouteParams()` rồi
|
||||
`RouteParams::toConfig(resolution)` / `toCorridor(resolution)`.
|
||||
|
||||
## API cho host (RBApp, hay bất kỳ ai có map trong RAM)
|
||||
|
||||
Không cần file YAML/PNG trên đĩa — tool chỉ là một caller của cùng bộ hàm này.
|
||||
|
||||
```cpp
|
||||
#include <voronoi_route/map_convert.h> // ảnh/grid -> mask vật cản (lib core, không dependency)
|
||||
#include <voronoi_route/voronoi_route.h> // rebuild / attach / query / mask (lib core)
|
||||
#include <voronoi_route/bundle_io.h> // saveBundle / loadBundleMeta (voronoi_route_io, cần nlohmann/json)
|
||||
|
||||
// Luật "vật cản" của riêng gói này, khai trong `voronoi_route_params.yaml` (block `obstacle:`) —
|
||||
// không đọc file config nào khác lúc chạy. Có RouteParams rồi thì gọi thẳng:
|
||||
voronoi_route::ObstacleRule rule = params.toObstacleRule(resolution_m);
|
||||
// Không có RouteParams (host tự set tay): layer mặc định lethal>=100, unknown=-1, track_unknown,
|
||||
// trinary; đổi unknown policy trực tiếp:
|
||||
rule.unknown = voronoi_route::UnknownPolicy::kTraversable; // ô chưa quét không chặn Voronoi
|
||||
|
||||
// Đầu vào A — có PNG bytes + YAML text (RBApp lúc copy map, map_import.cpp):
|
||||
// PNG bytes -> gray (stb_image, libpng… tuỳ host) -> mask
|
||||
voronoi_route::MapServerThresholds thr; // negate / occupied_thresh / free_thresh từ YAML
|
||||
auto occupied = voronoi_route::occupancyFromGray(gray, w, h, thr, rule);
|
||||
|
||||
// Đầu vào B — có OccupancyGrid int8 (RBApp lúc localize: copyOccupancyGrid()):
|
||||
auto occupied = voronoi_route::occupancyFromGrid(g.data.data(), g.info.width, g.info.height, rule);
|
||||
|
||||
// Phía consumer (nav core) — hash static layer sống theo ĐÚNG luật ghi trong bundle:
|
||||
voronoi_route::ObstacleRule r; voronoi_route::parseObstacleRuleString(bundle_source_without_prefix, &r);
|
||||
auto live = voronoi_route::occupancyFromCostmap(static_layer.getCharMap(), w, h, r.unknown, /*rows_bottom_up=*/true);
|
||||
bool same_map = voronoi_route::hashObstacleMask(live) == bundle_map_hash;
|
||||
|
||||
// Tính
|
||||
voronoi_route::RouteParams prm; // hoặc loadRouteParams(findConfigFile(cfg_dir, "voronoi_route_params.yaml"), ...)
|
||||
voronoi_route::VoronoiRoute vr(prm.toConfig(resolution));
|
||||
vr.rebuild(occupied, w, h); // ~0.1–0.4 s map RBApp, ~0.7 s map 9.4M ô
|
||||
vr.stats(); vr.occupancyHash(); vr.graph(); // node/edge, hash, thời gian
|
||||
|
||||
// Đầu ra — bundle trong thư mục map
|
||||
voronoi_route::BundleMeta bm; // width/height/resolution/origin/source/map_hash
|
||||
bm.map_hash = vr.occupancyHash();
|
||||
std::string err;
|
||||
voronoi_route::saveBundle(vr, bm, map_dir, /*gvd=*/true, /*dist=*/true, &err); // phẳng, cạnh map.png
|
||||
// -> voronoi.json (meta + node/edge kèm chuỗi ô), voronoi_gvd.pgm, voronoi_dist.pgm
|
||||
// Preview PNG chỉ có trong tool (cần OpenCV); host tự vẽ nếu muốn.
|
||||
|
||||
// Kiểm bundle có đúng map không (trước khi gửi xuống nav core):
|
||||
voronoi_route::BundleMeta have;
|
||||
if (voronoi_route::loadBundleMeta(map_dir, &have, &err) && have.map_hash == hash_hien_tai) …
|
||||
```
|
||||
|
||||
Link: `voronoi_route::voronoi_route` (core) và `voronoi_route::voronoi_route_io` (bundle). Cài
|
||||
`cmake --install build --prefix /opt/pnkx_nav_core` là RBApp `find_package(voronoi_route)` được.
|
||||
|
||||
Toạ độ trong lib = ảnh (x = cột, y = hàng, hàng 0 trên cùng). `occupancyFromGrid` tự lật từ
|
||||
quy ước ROS (hàng 0 dưới cùng) sang quy ước đó.
|
||||
|
||||
## Build (standalone)
|
||||
|
||||
```bash
|
||||
cd Test/voronoi_route
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
./build/voronoi_route_test
|
||||
```
|
||||
|
||||
Cần: g++ ≥ 9, CMake ≥ 3.10, GTest (test), nlohmann/json + yaml-cpp (`voronoi_route_io`), OpenCV (chỉ tool).
|
||||
|
||||
## Chạy thử trên map thật
|
||||
|
||||
```bash
|
||||
./build/voronoi_route_compile \
|
||||
--map /home/duongtd/T800_ws/src/AMR_T800/Managerments/maps/sehc_factory/sehc_factory.yaml \
|
||||
--out /tmp/sehc_voronoi \ # bỏ --out = ghi thẳng vào thư mục map, cạnh <tên>.pgm
|
||||
--start-m -20.0 5.0 --goal-m 30.0 -10.0
|
||||
```
|
||||
|
||||
In ra: số ô vật cản/unknown, thời gian build field và trích graph, số node/edge/thành phần liên
|
||||
thông, hash; nếu có start/goal thì chiều dài tuyến, số ô mask. Ghi vào `--out`:
|
||||
|
||||
| File | Nội dung |
|
||||
|---|---|
|
||||
| `voronoi.json` | meta map, tham số, stats, node, edge (kèm chuỗi ô), route nếu có |
|
||||
| `voronoi_gvd.pgm` | 255 = ô GVD |
|
||||
| `voronoi_dist.pgm` | PGM 16-bit, khoảng cách tới vật cản ×10 theo ô |
|
||||
| `voronoi_preview.png` | map tô lại (trắng free, xám unknown, đen vật cản) + GVD thô hồng + graph đỏ + node xanh lá + tuyến xanh dương + dải vàng |
|
||||
| `voronoi_graph.png` | **ảnh map gốc** (đúng pixel `map.png`) + graph đã lọc: edge đỏ, ngã rẽ xanh lá, đầu cụt xanh dương. Không GVD thô, không tuyến |
|
||||
| `voronoi_graph_overlay.png` | cùng nét vẽ, nền trong suốt RGBA — lớp web đặt đè lên `map.png` (`bundle.write_graph_overlay`, mặc định tắt) |
|
||||
|
||||
Mở `voronoi_preview.png` để soát: GVD đứt ở cửa hẹp, spur nhiễu ở tường răng cưa, phòng không nối
|
||||
hành lang. Ba khoá lọc:
|
||||
|
||||
| Khoá | Mặc định | Cắt gì |
|
||||
|---|---|---|
|
||||
| `--min-edge-m` | 0.3 | nhánh cụt ngắn hơn ngưỡng tuyệt đối |
|
||||
| `--spur-ratio` | 1.2 | nhánh cụt ngắn hơn `ratio × clearance` tại ngã rẽ gốc — "râu" từ ridge đâm vào vết lõm trên tường, dài bằng đúng khoảng trống nên ngưỡng tuyệt đối không cắt được. 0 = tắt |
|
||||
| `--min-component-m` | 2.0 | thành phần liên thông có tổng chiều dài nhỏ hơn — túi cô lập trong lòng kệ/vùng unknown |
|
||||
| `--min-clearance-m` | 0 (tắt) | cạnh có điểm hẹp nhất < ngưỡng — lối robot không lọt. **Đặt = bán kính nội tiếp robot (0.3)** với map xloc: biên free/unknown răng cưa sinh hàng nghìn vòng nhỏ mà spur filter không đụng (không phải nhánh cụt) |
|
||||
|
||||
Số đo `Managerments/maps` (i5-13400F, luật costmap `unknown=traversable`, `roi_margin_m: 0.5`):
|
||||
|
||||
| map | kích thước | field + trích | node / edge / thành phần | wall (đủ 5 file) |
|
||||
|---|---|---|---|---|
|
||||
| `505_room` | 203×159 | 3 + 1 ms | 33 / 75 / 2 | 0.03 s |
|
||||
| `maze` | 400×400 | 10 + 3 ms | 15 / 29 / 1 | 0.06 s |
|
||||
| `A9A10` | 2540×2480 (phòng 9×6 m giữa canvas 127 m) | 111 + 159 ms | 2 / 2 / 1 | 0.74 s |
|
||||
| `warehouse` | 2048×2048 | 189 + 258 ms | 498 / 1102 / 42 | 0.82 s |
|
||||
| `sehc_factory` | 3060×3060 | 419 + 439 ms | 431 / 1117 / 24 | 1.68 s |
|
||||
|
||||
Không ROI, `sehc_factory` mất 1.14 s field + 0.39 s trích (sóng lan qua 7.4M ô unknown ngoài nhà),
|
||||
`warehouse` 110 thành phần vì tia từ khe tường bắn ra mép. RSS ~480 MB ở 9.4M ô. `--min-edge-m 0.5`: nodes 1444 / edges 2260 khi `--spur-ratio 0`, còn 460 / 1276 khi 1.2.
|
||||
Tuyến 106 m qua hai sảnh + lối giữa kệ: attach + Dijkstra + mask 3.9 ms, mask 279k ô = 3 % map.
|
||||
|
||||
Map xloc của RBApp (`data/maps/<id>/`, ví dụ `d3a62ea26494e164` 1242×1018): biên free/unknown răng
|
||||
cưa, không có tường sạch → GVD thô đầy vòng nhỏ dọc biên. `--min-edge-m 1.0 --min-clearance-m 0.3`:
|
||||
758 → **107 node**, 1 thành phần, field 77 ms + trích 290 ms. Lưu ý `map.yaml` ở đó ghi
|
||||
`image: t4.png` (chép nguyên từ xloc) trong khi file là `map.png` — dùng `--image map.png`.
|
||||
|
||||
Ngưỡng "vật cản" (21/9/2026, tự chứa hoàn toàn 21/9/2026): `voronoi_route_params.yaml` block
|
||||
`obstacle:` (`lethal_cost_threshold`, `track_unknown_space`, `trinary_costmap`, `unknown_cost_value`,
|
||||
`unknown: traversable|obstacle`) là quyết định của riêng gói này — không đọc, không suy theo config
|
||||
costmap/SBPL lúc chạy (`RouteParams::toObstacleRule`, không còn hàm quét `--config-dir` tìm
|
||||
`static_layer_params.yaml`/`sbpl_global_params.yaml`). Mặc định đóng gói trùng số với costmap mặc
|
||||
định và `unknown: traversable`, để GVD tràn qua khe tường ra vùng chưa quét giống hành vi SBPL
|
||||
`allow_unknown: true` hiện tại — nhưng đây là trùng hợp cố ý lúc đặt số, không phải liên kết runtime;
|
||||
đổi costmap/SBPL thật thì sửa tay các khoá này cho khớp, không tự đổi theo. Luật ghi vào
|
||||
`voronoi.json/source` (`costmap:lethal>=100;...;unknown=traversable`), consumer hash static layer
|
||||
sống theo đúng luật đó (`occupancyFromCostmap`). Ép tay nhanh: `--unknown-as-obstacle` / `--unknown-free`.
|
||||
|
||||
Luật đọc pixel = luật **map_server của ROS** (`image_loader.cpp`, mode trinary): trung bình
|
||||
**mọi kênh kể cả alpha** rồi mới so ngưỡng (`occupancyFromImage`, 21/9/2026). Map RGBA như
|
||||
`sehc_factory.png`: (79,79,79,255) → 123 → unknown chứ không occupied; (205,205,205,255) → 217 →
|
||||
**free** chứ không unknown. Decode luminance (`IMREAD_GRAYSCALE`) cho tập lethal khác đúng 1 ô →
|
||||
hash khác → consumer từ chối graph (đã xảy ra: `b058c9487f46e17e` vs `c38fabd537e567fe`). Tool
|
||||
đọc `IMREAD_UNCHANGED`; host cũng phải đưa đủ kênh vào `occupancyFromImage`.
|
||||
|
||||
## Chưa có
|
||||
|
||||
- Ghép vào build RBApp (`target_sources(robot_app ...)` từ cây nguồn hoặc `find_package(voronoi_route)` sau `cmake --install`) và hook gọi lúc copy map — xem `USAGE.md` mục 5.
|
||||
- `toMsg/fromMsg` sang `robot_nav_msgs::RouteGraph` (plan tiêm graph, mục 6). `saveBundle` đã có; msg là dạng RAM của cùng dữ liệu.
|
||||
- Cụm node ở ngã rẽ đã được xử lý (thinning skeleton 1 ô + contract cạnh ngắn giữa hai node không
|
||||
phải lá, nối chuỗi ô để giữ 8-liên thông). Còn lại: GVD trong lối giữa kệ lượn sóng theo chân kệ —
|
||||
không sai, mask vẫn phủ; planner làm mượt bên trong dải.
|
||||
196
USAGE.md
Normal file
196
USAGE.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# Cách dùng & ghép nối RBApp
|
||||
|
||||
Tài liệu này trả lời hai câu: build/chạy gói `voronoi_route` thế nào, và nó nằm ở đâu trong luồng
|
||||
quét map của RBApp. Kiến trúc lib (class, API, bảng config đầy đủ) xem `README.md` cùng thư mục;
|
||||
thiết kế và lý do chọn phương án xem `Test/docs/voronoi_route/VORONOI_ROUTE_LIB_PLAN.md`.
|
||||
|
||||
## 1. Gói này là gì, chạy ở đâu
|
||||
|
||||
Thư viện dựng route graph (generalized Voronoi diagram) từ một lưới occupancy. Vào là bitmap vật
|
||||
cản phẳng, ra là graph (node/edge/chuỗi ô) + ảnh phụ. Không phụ thuộc ROS, costmap hay planner.
|
||||
|
||||
Nơi chạy: **RBApp**. Khi khung chương trình copy map quét xong vào
|
||||
`/home/duongtd/dev_ws/RBApp/data/maps/<id>/`, map đó được cho chạy qua Voronoi **một lần**, graph
|
||||
lưu **phẳng vào chính thư mục map đó** (`voronoi.json`, `voronoi_graph.png`...). Gói không link vào
|
||||
planner nào; ai cần graph thì đọc bundle từ thư mục map (việc đó nằm ngoài gói này, xem mục 6).
|
||||
|
||||
Hiện tại gói build/test **độc lập** bằng CMake thường, chưa nối vào build của RBApp.
|
||||
|
||||
## 2. Build
|
||||
|
||||
```bash
|
||||
cd /home/duongtd/T800_ws/src/AMR_T800/Test/voronoi_route
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build -j
|
||||
```
|
||||
|
||||
Cần `yaml-cpp`, `nlohmann/json`, OpenCV (chỉ cho tool CLI), GTest (chỉ cho test). Tắt phần không cần:
|
||||
`-DVORONOI_ROUTE_BUILD_TOOLS=OFF`, `-DVORONOI_ROUTE_BUILD_TESTS=OFF`.
|
||||
|
||||
| Target | Là gì |
|
||||
|---|---|
|
||||
| `voronoi_route` (`libvoronoi_route.a`) | Lõi: GVD, trích graph, attach, corridor, `map_convert`, `RouteParams`. Không dependency ngoài. |
|
||||
| `voronoi_route_io` (`libvoronoi_route_io.a`) | `saveBundle`/`loadBundleMeta` (nlohmann/json) + `loadRouteParams` (yaml-cpp). RBApp link cái này. |
|
||||
| `voronoi_route_compile` | Binary CLI: `map.yaml` + ảnh -> bundle. Cần OpenCV để decode PNG. Là caller mẫu của đúng bộ API RBApp sẽ gọi. |
|
||||
|
||||
`cmake --install build --prefix <dir>` cài header + lib + `share/voronoi_route/config/` + cmake config
|
||||
(`find_package(voronoi_route)` -> target `voronoi_route::voronoi_route`, `voronoi_route::voronoi_route_io`).
|
||||
|
||||
## 3. Test
|
||||
|
||||
```bash
|
||||
./build/voronoi_route_test
|
||||
```
|
||||
|
||||
20 test: hình học tổng hợp (hành lang, ngã ba, vòng, phòng kín), lọc spur/thành phần, corridor mask,
|
||||
sync incremental, hash, ROI, `classifyGridValue` khớp `StaticLayer::interpretValue`, loader YAML.
|
||||
|
||||
## 4. Chạy tool CLI trên một map
|
||||
|
||||
```bash
|
||||
./build/voronoi_route_compile --map <map.yaml> --params config/voronoi_route_params.yaml \
|
||||
[--image map.png] [--start-m X Y --goal-m X Y]
|
||||
```
|
||||
|
||||
Cờ hay dùng:
|
||||
|
||||
| Cờ | Tác dụng |
|
||||
|---|---|
|
||||
| `--image <file>` | Ép đường dẫn ảnh thay vì `image:` trong YAML. **Bắt buộc với map RBApp**: `map.yaml` chép nguyên của xloc ghi `image: t4.png` trong khi file thật là `map.png`. |
|
||||
| `--out <dir>` | Thư mục ghi bundle; mặc định là thư mục chứa `map.yaml`. |
|
||||
| `--params <yaml>` | File tham số; không có thì tìm `voronoi_route_params.yaml` trong `--config-dir`, không có nữa thì default trong code (tool in rõ ở dòng `params :`). |
|
||||
| `--unknown-as-obstacle` / `--unknown-free` | Ép chính sách ô chưa quét cho một lần chạy. |
|
||||
| `--min-edge-m`, `--spur-ratio`, `--min-component-m`, `--min-clearance-m` | Ghi đè lọc graph một lần, để dò số khi soát preview. |
|
||||
| `--start-m/--goal-m` | In thử tuyến + corridor mask, vẽ lên preview. Không ảnh hưởng bundle. |
|
||||
| `--no-preview`, `--no-graph-image`, `--graph-overlay`, `--no-gvd`, `--no-dist` | Bật/tắt từng file phụ. |
|
||||
|
||||
Danh sách cờ đầy đủ ở comment đầu `tools/voronoi_route_compile.cpp`.
|
||||
|
||||
Output, ghi phẳng cùng thư mục map (tên có tiền tố `voronoi_`, không đụng file map):
|
||||
|
||||
| File | Là gì | Ai đọc |
|
||||
|---|---|---|
|
||||
| `voronoi.json` | Graph đã lọc (node, edge, chuỗi ô) + `resolution`, `origin`, `map_hash`, `source` (luật vật cản) | consumer đọc graph |
|
||||
| `voronoi_gvd.pgm`, `voronoi_dist.pgm` | GVD thô + clearance ×10 (16-bit) | tuỳ chọn, tắt bằng `write_gvd`/`write_dist` |
|
||||
| `voronoi_preview.png` | Map tô lại màu + GVD thô (hồng) + graph đã lọc (đỏ) + node | người soát khi graph rối/đứt |
|
||||
| `voronoi_graph.png` | Ảnh map gốc + graph đã lọc vẽ đè (edge đỏ, ngã rẽ xanh lá, đầu cụt xanh dương) | người vận hành, web |
|
||||
| `voronoi_graph_overlay.png` | Cùng nét vẽ, nền trong suốt | lớp web đặt đè lên `map.png` |
|
||||
|
||||
## 5. Ghép nối với RBApp
|
||||
|
||||
### 5a. Map RBApp nằm ở đâu, ghi xong lúc nào
|
||||
|
||||
`MapStore::mapDir(id)` (`backend/storage/map_store.cpp`) = `data/maps/<uuid>/`, luôn có `map.png` +
|
||||
`map.yaml` (tên cố định). Hai chỗ ghi map trong `backend/robot/map_import/map_import.cpp`:
|
||||
|
||||
- `importXlocMap()` — quét map mới.
|
||||
- `overwriteXlocMap()` — quét lại đè map cũ.
|
||||
|
||||
Cả hai kết thúc bằng `store.saveImageFile(id, "map.png", png_bytes, err)` rồi
|
||||
`store.saveYamlFile(id, yaml_text, err)`. **Ngay sau khi hàm trả `true` là điểm gọi Voronoi**: thư mục
|
||||
map đã đủ ảnh + YAML, `png_bytes` còn trong RAM.
|
||||
|
||||
### 5b. Gọi thế nào trong RBApp (chưa code)
|
||||
|
||||
Hai cách, chọn một:
|
||||
|
||||
**(1) Gọi lib trong tiến trình** — khuyến nghị. Không cần OpenCV: RBApp đã có `backend/third_party/stb_image_write.h`,
|
||||
thêm `stb_image.h` cùng chỗ để decode `png_bytes` -> gray. Chạy trên thread nền (Voronoi map lớn
|
||||
~1–2 s trên PC, ước 3–5× trên robot) để request quét map trả về ngay:
|
||||
|
||||
```cpp
|
||||
#include <voronoi_route/map_convert.h>
|
||||
#include <voronoi_route/voronoi_route.h>
|
||||
#include <voronoi_route/bundle_io.h>
|
||||
#include <voronoi_route/params_io.h>
|
||||
|
||||
void compileVoronoi(const std::filesystem::path& map_dir, const std::string& png_bytes,
|
||||
double resolution, double ox, double oy, double oyaw,
|
||||
const std::string& config_dir)
|
||||
{
|
||||
int w = 0, h = 0, ch = 0;
|
||||
unsigned char* gray = stbi_load_from_memory(
|
||||
reinterpret_cast<const stbi_uc*>(png_bytes.data()), static_cast<int>(png_bytes.size()),
|
||||
&w, &h, &ch, /*desired_channels=*/1);
|
||||
if (!gray) return;
|
||||
|
||||
voronoi_route::RouteParams prm;
|
||||
std::string err; std::vector<std::string> notes;
|
||||
const std::string yaml = voronoi_route::findConfigFile(config_dir, "voronoi_route_params.yaml");
|
||||
if (!yaml.empty()) voronoi_route::loadRouteParams(yaml, &prm, &err, ¬es);
|
||||
|
||||
const voronoi_route::ObstacleRule rule = prm.toObstacleRule(resolution);
|
||||
voronoi_route::MapServerThresholds thr; // negate/occupied_thresh/free_thresh từ map.yaml
|
||||
auto occupied = voronoi_route::occupancyFromGray(gray, w, h, thr, rule);
|
||||
voronoi_route::applyObstacleRoi(occupied, w, h, rule.roi_margin_cells);
|
||||
stbi_image_free(gray);
|
||||
|
||||
voronoi_route::VoronoiRoute vr(prm.toConfig(resolution));
|
||||
vr.rebuild(occupied, w, h);
|
||||
|
||||
voronoi_route::BundleMeta bm;
|
||||
bm.width = w; bm.height = h; bm.resolution = resolution;
|
||||
bm.origin_x = ox; bm.origin_y = oy; bm.origin_yaw = oyaw;
|
||||
bm.source = "costmap:" + voronoi_route::obstacleRuleString(rule);
|
||||
bm.map_hash = vr.occupancyHash();
|
||||
voronoi_route::saveBundle(vr, bm, map_dir.string(), prm.write_gvd, prm.write_dist, &err);
|
||||
}
|
||||
```
|
||||
|
||||
`voronoi_preview.png` / `voronoi_graph.png` là phần vẽ bằng OpenCV trong tool; trong RBApp muốn có
|
||||
ảnh thì vẽ bằng `stb_image_write` từ `vr.graph().edges()`/`nodes()` (chuỗi ô đã có sẵn), hoặc bỏ.
|
||||
|
||||
**(2) Gọi binary CLI** — nhanh nhất để có kết quả, không sửa build RBApp: `std::system`/`posix_spawn`
|
||||
`voronoi_route_compile --map <map_dir>/map.yaml --image map.png --config-dir <config_dir>` sau
|
||||
`saveYamlFile`. Đổi lại phải cài binary + OpenCV lên robot và mất kiểm soát lỗi (chỉ có exit code).
|
||||
|
||||
### 5c. Nối vào build RBApp (cách 1)
|
||||
|
||||
RBApp là CMake thường, lấy thư viện ngoài theo hai kiểu (xem `robot_time`/`tf3` trong
|
||||
`RBApp/CMakeLists.txt`): ưu tiên bản đã cài, không có thì biên dịch từ cây nguồn. Làm giống vậy:
|
||||
|
||||
```cmake
|
||||
find_package(voronoi_route QUIET) # sau `cmake --install` của gói này
|
||||
if(voronoi_route_FOUND)
|
||||
target_link_libraries(robot_app PRIVATE voronoi_route::voronoi_route_io)
|
||||
else()
|
||||
file(GLOB LM_VORONOI_SOURCES "${VORONOI_ROUTE_DIR}/src/*.cpp")
|
||||
target_sources(robot_app PRIVATE ${LM_VORONOI_SOURCES})
|
||||
target_include_directories(robot_app PRIVATE "${VORONOI_ROUTE_DIR}/include")
|
||||
endif()
|
||||
```
|
||||
|
||||
`voronoi_route_io` cần nlohmann/json (RBApp đã FetchContent) và yaml-cpp (RBApp chưa có — thêm
|
||||
`find_package(yaml-cpp)`, hoặc bỏ `loadRouteParams` và set `RouteParams` bằng số trong code).
|
||||
|
||||
### 5d. Config trên robot
|
||||
|
||||
Chép `config/voronoi_route_params.yaml` vào `RBApp/data/config/runtime/` (cùng cây với
|
||||
`static_layer_params.yaml` mà RBApp đang dùng). Khối `obstacle:` trong đó phải cùng số với costmap/SBPL
|
||||
đang chạy thật — không tự đọc, soát tay theo comment trong YAML.
|
||||
|
||||
### 5e. Chạy tay ngay bây giờ cho một map RBApp
|
||||
|
||||
```bash
|
||||
./build/voronoi_route_compile \
|
||||
--map /home/duongtd/dev_ws/RBApp/data/maps/<id>/map.yaml --image map.png \
|
||||
--config-dir /home/duongtd/dev_ws/RBApp/data/config/runtime \
|
||||
--params config/voronoi_route_params.yaml
|
||||
```
|
||||
|
||||
Đã chạy trên `91765560f0dc9eeb`, `d3a62ea26494e164`, `f445564b1d04280a` — bundle đang nằm trong từng
|
||||
thư mục map (sinh trước khi có ROI, chạy lại nếu cần `roi=` trong `source`).
|
||||
|
||||
## 6. Ai đọc graph sau đó
|
||||
|
||||
Ngoài phạm vi gói này. Phương án đã chốt (chưa code): lúc RBApp đẩy map vào nav core
|
||||
(`NavService::setStaticMap` -> `pushNavStaticMap`), đọc `voronoi.json` trong thư mục map và gửi kèm
|
||||
qua API mới `BaseNavigation::addRouteGraph` (msg `robot_nav_msgs::RouteGraph`) vào
|
||||
`robot_sensor_ports`, ai cần thì lấy. Chi tiết ở `Test/docs/ROUTE_GRAPH_INJECTION_PLAN.md`.
|
||||
|
||||
## 7. Trạng thái
|
||||
|
||||
- Đã: lib + tool CLI, test 20/20, chạy trên 5 map `Managerments/maps/*` và 3 map RBApp, ngưỡng vật
|
||||
cản tự chứa trong config gói.
|
||||
- Chưa: hook trong `map_import.cpp`, nối build RBApp, `stb_image.h`, config vào `data/config/runtime/`,
|
||||
mọi thứ ở mục 6.
|
||||
104
config/voronoi_route_params.yaml
Normal file
104
config/voronoi_route_params.yaml
Normal file
@@ -0,0 +1,104 @@
|
||||
# =================================================================================================
|
||||
# voronoi_route — tham số dựng route graph (GVD) và dải hành lang cho goal xa.
|
||||
#
|
||||
# Ai đọc: người vận hành / dev khi soát `voronoi_preview.png` thấy graph rối, đứt, hay tuyến đi vòng.
|
||||
# Ai nạp: RBApp lúc copy map quét xong vào `data/maps/<id>/` (chạy Voronoi một lần, lưu graph vào
|
||||
# chính thư mục map đó), và tool `voronoi_route_compile` khi chạy tay. Cả hai tìm file này trong
|
||||
# thư mục config truyền vào (--config-dir / PNKX_NAV_CORE_CONFIG_DIR) giống cách costmap tìm
|
||||
# *_layer_params.yaml — file khớp tên ĐẦU TIÊN thắng, đừng để hai bản trong cùng cây.
|
||||
#
|
||||
# Đây là BẢN MẶC ĐỊNH đóng gói kèm gói. Cây đang chạy thật là RBApp `data/config/runtime/` (thêm
|
||||
# khi ghép); các bản sao khác chỉ để tham chiếu schema.
|
||||
#
|
||||
# Đơn vị: mét ở đây, lib làm việc theo ô — quy đổi bằng `resolution` của map lúc nạp.
|
||||
# Luật "ô nào là vật cản" (block `obstacle:` dưới) TỰ CHỨA trong file này — gói chạy độc lập, KHÔNG
|
||||
# đọc, không suy theo config của gói khác (costmap, sbpl...). Mỗi khoá dưới `obstacle:` là quyết định
|
||||
# của riêng gói này; đổi tay khi muốn map/graph coi vật cản khác đi, không có nguồn nào khác chi phối.
|
||||
# =================================================================================================
|
||||
|
||||
voronoi_route:
|
||||
graph:
|
||||
# [m] Nhánh cụt ngắn hơn ngưỡng này bị cắt (nhiễu răng cưa ở góc tường lồi). Tăng = graph gọn
|
||||
# hơn nhưng có thể mất ngõ cụt ngắn thật (robot vẫn tới được nhờ attach, chỉ không có tuyến sẵn).
|
||||
min_edge_length_m: 0.3
|
||||
# Nhánh cụt ngắn hơn `ratio × clearance(ngã rẽ gốc)` bị cắt: nhánh không thoát khỏi đĩa trống
|
||||
# quanh ngã rẽ thì không dẫn đi đâu — đây là "râu" từ ridge đâm vào vết lõm tường, dài đúng bằng
|
||||
# khoảng trống nên ngưỡng mét ở trên không cắt được. 1.0–1.5 hợp lý; 0 = tắt.
|
||||
spur_clearance_ratio: 1.2
|
||||
# [m] Thành phần liên thông có tổng chiều dài edge nhỏ hơn bị bỏ (túi cô lập trong lòng kệ,
|
||||
# mảng unknown lẫn free). Tăng nếu preview còn cụm đỏ nhỏ không nối với đâu.
|
||||
min_component_length_m: 2.0
|
||||
# [m] Edge có điểm hẹp nhất < ngưỡng này bị bỏ: lối robot không lọt thì không phải tuyến. Đặt =
|
||||
# bán kính NỘI TIẾP footprint. Map SLAM (xloc) biên free/unknown răng cưa sinh hàng nghìn vòng nhỏ
|
||||
# đúng loại này — không có khoá này graph gấp 3–5 lần. 0 = tắt. Nguy hiểm nếu đặt lớn hơn nửa cửa
|
||||
# hẹp nhất trong nhà: cửa đó biến mất khỏi graph, tuyến đi vòng.
|
||||
min_clearance_m: 0.3
|
||||
# [m] Bán kính BFS tối đa khi gắn start/goal vào graph. Điểm nằm trong phòng kín xa GVD hơn
|
||||
# ngần này = gắn thất bại -> planner chạy full, không dùng dải.
|
||||
attach_max_radius_m: 10.0
|
||||
# Số ô lethal đổi tích luỹ trước khi trích lại graph (update khoảng cách vẫn chạy ngay). Nhỏ =
|
||||
# graph luôn tươi nhưng tốn CPU mỗi lượt plan khi map hay đổi.
|
||||
graph_rebuild_min_changed_cells: 200
|
||||
# Tỉ lệ ô đổi so với toàn map mà từ đó build lại từ đầu thay vì cập nhật dần (đổi tầng cùng kích
|
||||
# thước rơi vào đây). Incremental trên thay đổi diện rộng chậm hơn build mới.
|
||||
full_rebuild_fraction: 0.02
|
||||
|
||||
corridor:
|
||||
# [m] Nửa bề rộng dải tối thiểu quanh tuyến. Phải >= bán kính NGOẠI TIẾP footprint + 1 ô, nếu không
|
||||
# footprint tại start/goal đè lên ô ngoài dải và planner từ chối. Hẹp = tìm nhanh, dễ cạn ở chỗ rẽ.
|
||||
half_width_min_m: 1.5
|
||||
# Nửa bề rộng tại mỗi ô tuyến = max(half_width_min, hệ số × clearance tại ô đó). Sảnh rộng -> dải
|
||||
# phủ cả sảnh, tránh ép robot đi giữa sảnh vòng hơn đường chéo. 0 = bề rộng cố định.
|
||||
clearance_scale: 0.8
|
||||
# [m] Trần của nửa bề rộng thích nghi. Lớn = ít thu hẹp không gian tìm ở sảnh; nhỏ = nhanh hơn
|
||||
# nhưng đường chéo qua sảnh có thể ra ngoài dải.
|
||||
half_width_max_m: 6.0
|
||||
|
||||
bundle:
|
||||
# Ghi `voronoi_gvd.pgm` (ô GVD, 8-bit). Consumer dựng lại được từ edge, tắt để tiết kiệm đĩa.
|
||||
write_gvd: true
|
||||
# Ghi `voronoi_dist.pgm` (clearance ×10, 16-bit). Cần cho bề rộng thích nghi khi nạp bundle;
|
||||
# tắt thì corridor dùng half_width_min cố định.
|
||||
write_dist: true
|
||||
# Ghi `voronoi_preview.png` — chỉ cho người soát, runtime không đọc. Tool mới ghi được (cần OpenCV).
|
||||
write_preview: true
|
||||
# Ghi `voronoi_graph.png` — ẢNH MAP GỐC (đúng pixel map.png) + graph đã lọc vẽ đè: edge đỏ, ngã rẽ
|
||||
# xanh lá, đầu cụt xanh dương. Không tô lại màu, không GVD thô, không tuyến/dải — để đối chiếu
|
||||
# graph với tường thật, hoặc hiện lên web thay preview. Tool mới ghi được (cần OpenCV).
|
||||
write_graph_image: true
|
||||
# Ghi `voronoi_graph_overlay.png` — cùng nét vẽ nhưng nền TRONG SUỐT (RGBA), để lớp web (Konva)
|
||||
# đặt đè lên map.png sẵn có mà không nhân đôi ảnh nền.
|
||||
write_graph_overlay: false
|
||||
|
||||
obstacle:
|
||||
# 4 khoá + `unknown` dưới đây KHÔNG đọc config nào khác lúc chạy, nhưng cùng Ý NGHĨA với costmap
|
||||
# thật đang chạy — đổi robot/costmap thì soát tay, sửa theo cho khớp, không tự đồng bộ:
|
||||
# unknown_cost_value / track_unknown_space / lethal_cost_threshold / trinary_costmap
|
||||
# <-> `static_layer:` trong `static_layer_params.yaml` (cùng cây config với costmap đang dùng,
|
||||
# unknown (traversable/obstacle) <-> `SBPLLatticePlanner/allow_unknown` trong `sbpl_global_params.yaml`
|
||||
# cùng cây trên: allow_unknown=true -> đặt `traversable`; allow_unknown=false -> đặt `obstacle`.
|
||||
|
||||
# Ô = giá trị này -> coi là "chưa quét".
|
||||
unknown_cost_value: -1
|
||||
# true: ô unknown giữ nguyên trạng thái "chưa biết" (đi tiếp theo `unknown` bên dưới).
|
||||
# false: ô unknown coi luôn là free — tắt thì khoá `unknown` dưới vô nghĩa.
|
||||
track_unknown_space: true
|
||||
# Giá trị ô >= ngưỡng này -> vật cản chắc chắn (lethal).
|
||||
lethal_cost_threshold: 100
|
||||
# true: mọi ô dưới ngưỡng lethal đều FREE (bản đồ 3 trạng thái). false: dùng giá trị đã scale —
|
||||
# gói này không nội suy cost trung gian, để false thì mọi ô dưới lethal cũng vẫn coi là free.
|
||||
trinary_costmap: true
|
||||
|
||||
# traversable | obstacle. Ô unknown (NO_INFORMATION, chỉ có tác dụng khi track_unknown_space=true)
|
||||
# có chặn Voronoi không.
|
||||
# traversable = không chặn (GVD tràn ra vùng chưa quét qua khe tường).
|
||||
# obstacle = chặn (graph gọn hơn, nhưng có thể LỆCH với planner nếu planner vẫn đi qua được
|
||||
# ô unknown — hash bundle vẫn đúng vì luật được ghi vào `source`, chỉ là tuyến có
|
||||
# thể tránh chỗ planner đi được).
|
||||
unknown: traversable
|
||||
# [m] Vùng quan tâm: hộp bao mọi ô vật cản (tường) nở thêm lề này; NGOÀI hộp coi là vật cản.
|
||||
# Chặn các tia Voronoi bắn từ khe tường ra mép ảnh khi bên ngoài là free/unknown-đi-được (map sim
|
||||
# `warehouse`: 110 thành phần -> vài chục; map SLAM 9.4M ô: bỏ tính 7M ô unknown ngoài nhà, ~2x nhanh).
|
||||
# Lề nhỏ (0.5) cố ý: dải free giữa tường ngoài và mép hộp < 2×min_clearance nên không sinh vòng GVD
|
||||
# bao quanh nhà. Không đổi gì bên trong hộp. Consumer hash theo cùng lề (ghi trong `source`). < 0 = tắt.
|
||||
roi_margin_m: 0.5
|
||||
24
include/voronoi_route/attachment.h
Normal file
24
include/voronoi_route/attachment.h
Normal file
@@ -0,0 +1,24 @@
|
||||
#ifndef VORONOI_ROUTE_ATTACHMENT_H_
|
||||
#define VORONOI_ROUTE_ATTACHMENT_H_
|
||||
|
||||
#include "voronoi_route/types.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
class VoronoiField;
|
||||
class VoronoiGraph;
|
||||
|
||||
/**
|
||||
* @brief Walk from `from` through non-occupied cells to the nearest cell that lies on the route
|
||||
* graph (BFS, 8-connected, Chebyshev radius bound).
|
||||
*
|
||||
* The start cell itself is accepted even if occupied: a robot reported inside a lethal cell
|
||||
* (localisation jitter next to a wall) still needs a way out. Every other cell on the path is
|
||||
* free. Inflation is deliberately not avoided — the start of a plan is usually inside it.
|
||||
*/
|
||||
Attachment attachPoint(const VoronoiField& field, const VoronoiGraph& graph, Cell from,
|
||||
int max_radius_cells);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_ATTACHMENT_H_
|
||||
64
include/voronoi_route/bucketed_queue.h
Normal file
64
include/voronoi_route/bucketed_queue.h
Normal file
@@ -0,0 +1,64 @@
|
||||
#ifndef VORONOI_ROUTE_BUCKETED_QUEUE_H_
|
||||
#define VORONOI_ROUTE_BUCKETED_QUEUE_H_
|
||||
|
||||
#include <vector>
|
||||
#include <set>
|
||||
#include <queue>
|
||||
#include <assert.h>
|
||||
#include <map>
|
||||
#include "voronoi_route/point.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
//! Priority queue for integer coordinates with squared distances as priority.
|
||||
/** A priority queue that uses buckets to group elements with the same priority.
|
||||
* The individual buckets are unsorted, which increases efficiency if these groups are large.
|
||||
* The elements are assumed to be integer coordinates, and the priorities are assumed
|
||||
* to be squared Euclidean distances (integers).
|
||||
*/
|
||||
|
||||
template <typename T>
|
||||
class BucketPrioQueue {
|
||||
|
||||
public:
|
||||
//! Standard constructor
|
||||
/** Standard constructor. When called for the first time it creates a look up table
|
||||
* that maps square distances to bucket numbers, which might take some time...
|
||||
*/
|
||||
BucketPrioQueue();
|
||||
|
||||
|
||||
void clear() {
|
||||
buckets.clear();
|
||||
count = 0;
|
||||
nextPop = buckets.end();
|
||||
}
|
||||
|
||||
//! Checks whether the Queue is empty
|
||||
bool empty();
|
||||
//! push an element
|
||||
void push(int prio, T t);
|
||||
//! return and pop the element with the lowest squared distance */
|
||||
T pop();
|
||||
|
||||
int size() { return count; }
|
||||
int getNumBuckets() { return buckets.size(); }
|
||||
|
||||
int getTopPriority(){
|
||||
return nextPop->first;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
int count;
|
||||
|
||||
typedef std::map< int, std::queue<T> > BucketType;
|
||||
BucketType buckets;
|
||||
typename BucketType::iterator nextPop;
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#include "voronoi_route/bucketed_queue.hxx"
|
||||
|
||||
#endif // VORONOI_ROUTE_BUCKETED_QUEUE_H_
|
||||
41
include/voronoi_route/bucketed_queue.hxx
Normal file
41
include/voronoi_route/bucketed_queue.hxx
Normal file
@@ -0,0 +1,41 @@
|
||||
// Template bodies of BucketPrioQueue; included only from bucketed_queue.h.
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
template <class T>
|
||||
BucketPrioQueue<T>::BucketPrioQueue() {
|
||||
clear();
|
||||
}
|
||||
|
||||
template <class T>
|
||||
bool BucketPrioQueue<T>::empty() {
|
||||
return (count==0);
|
||||
}
|
||||
|
||||
|
||||
template <class T>
|
||||
void BucketPrioQueue<T>::push(int prio, T t) {
|
||||
buckets[prio].push(t);
|
||||
if (nextPop == buckets.end() || prio < nextPop->first) nextPop = buckets.find(prio);
|
||||
count++;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
T BucketPrioQueue<T>::pop() {
|
||||
while (nextPop!=buckets.end() && nextPop->second.empty()) ++nextPop;
|
||||
|
||||
T p = nextPop->second.front();
|
||||
nextPop->second.pop();
|
||||
if (nextPop->second.empty()) {
|
||||
typename BucketType::iterator it = nextPop;
|
||||
nextPop++;
|
||||
buckets.erase(it);
|
||||
}
|
||||
count--;
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
44
include/voronoi_route/bundle_io.h
Normal file
44
include/voronoi_route/bundle_io.h
Normal file
@@ -0,0 +1,44 @@
|
||||
#ifndef VORONOI_ROUTE_BUNDLE_IO_H_
|
||||
#define VORONOI_ROUTE_BUNDLE_IO_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/types.h"
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/** What a bundle says about the map it was built from. Consumers compare this before trusting it. */
|
||||
struct BundleMeta {
|
||||
uint32_t version = 1; ///< Bundle schema; bump when extraction semantics change.
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
double resolution = 0.0; ///< [m/cell]
|
||||
double origin_x = 0.0; ///< [m] map_server origin (lower-left corner of the image)
|
||||
double origin_y = 0.0;
|
||||
double origin_yaw = 0.0;
|
||||
std::string source; ///< e.g. "map_server:occupied+unknown"
|
||||
uint64_t map_hash = 0; ///< hashObstacleMask() of the occupancy the graph came from
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Write `<dir>/voronoi.json` (meta, params, stats, nodes, edges with cell chains) and
|
||||
* optionally `<dir>/voronoi_gvd.pgm` (8-bit, 255 = GVD cell) and `<dir>/voronoi_dist.pgm`
|
||||
* (16-bit, clearance x10 in cells). Creates `dir`. No preview image — that needs an image
|
||||
* library and lives in the tool.
|
||||
*/
|
||||
bool saveBundle(const VoronoiRoute& vr, const BundleMeta& meta, const std::string& dir,
|
||||
bool with_gvd, bool with_dist, std::string* err);
|
||||
|
||||
/** Read only the meta block of `<dir>/voronoi.json` (cheap; for "is this bundle for my map?"). */
|
||||
bool loadBundleMeta(const std::string& dir, BundleMeta* meta, std::string* err);
|
||||
|
||||
/** Route polyline + mask count the tool may add under "route"; optional. */
|
||||
bool appendRouteToBundle(const std::string& dir, const Polyline& route, size_t mask_cells,
|
||||
std::string* err);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_BUNDLE_IO_H_
|
||||
29
include/voronoi_route/corridor_mask.h
Normal file
29
include/voronoi_route/corridor_mask.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef VORONOI_ROUTE_CORRIDOR_MASK_H_
|
||||
#define VORONOI_ROUTE_CORRIDOR_MASK_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/types.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
class VoronoiField;
|
||||
|
||||
/**
|
||||
* @brief Bitmap of cells within an adaptive half-width of a polyline.
|
||||
*
|
||||
* Width at a route cell is max(W_min, scale * clearance) capped at W_max: narrow where the map
|
||||
* is narrow, the whole hall where it is open, so the corridor never forces a detour through the
|
||||
* middle of a big room. Drawn by stamping discs on cells sampled every ~W/2 along the line; the
|
||||
* discs overlap, so the band has no gaps. Every polyline cell is guaranteed inside the mask.
|
||||
*
|
||||
* @return row-major size_x*size_y bitmap, 1 = inside corridor. `cells_in_mask` gets the count.
|
||||
*/
|
||||
std::vector<uint8_t> corridorMask(const VoronoiField& field, const Polyline& polyline,
|
||||
const CorridorParams& params, size_t* cells_in_mask);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_CORRIDOR_MASK_H_
|
||||
124
include/voronoi_route/dynamic_voronoi.h
Normal file
124
include/voronoi_route/dynamic_voronoi.h
Normal file
@@ -0,0 +1,124 @@
|
||||
// Port of DynamicVoronoi (Lau, Sprunk, Burgard, ICRA 2010) from
|
||||
// Test/simulators/third_party/map_plugins/voronoi_layer (BSD). Namespaced, otherwise unchanged.
|
||||
#ifndef VORONOI_ROUTE_DYNAMIC_VORONOI_H_
|
||||
#define VORONOI_ROUTE_DYNAMIC_VORONOI_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
#include "voronoi_route/bucketed_queue.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
//! A DynamicVoronoi object computes and updates a distance map and Voronoi diagram.
|
||||
class DynamicVoronoi {
|
||||
|
||||
public:
|
||||
|
||||
DynamicVoronoi();
|
||||
~DynamicVoronoi();
|
||||
|
||||
//! Initialization with an empty map
|
||||
void initializeEmpty(int _sizeX, int _sizeY, bool initGridMap=true);
|
||||
//! Initialization with a given binary map (false==free, true==occupied)
|
||||
void initializeMap(int _sizeX, int _sizeY, bool** _gridMap);
|
||||
|
||||
//! add an obstacle at the specified cell coordinate
|
||||
void occupyCell(int x, int y);
|
||||
//! remove an obstacle at the specified cell coordinate
|
||||
void clearCell(int x, int y);
|
||||
//! remove old dynamic obstacles and add the new ones
|
||||
void exchangeObstacles(std::vector<INTPOINT>& newObstacles);
|
||||
|
||||
//! update distance map and Voronoi diagram to reflect the changes
|
||||
void update(bool updateRealDist=true);
|
||||
//! prune the Voronoi diagram
|
||||
void prune();
|
||||
//! prune the Voronoi diagram by globally revisiting all Voronoi nodes. Takes more time but gives a more sparsely pruned Voronoi graph. You need to call this after every call to udpate()
|
||||
void updateAlternativePrunedDiagram();
|
||||
//! retrieve the alternatively pruned diagram. see updateAlternativePrunedDiagram()
|
||||
int** alternativePrunedDiagram() const {
|
||||
return alternativeDiagram;
|
||||
};
|
||||
//! retrieve the number of neighbors that are Voronoi nodes (4-connected)
|
||||
int getNumVoronoiNeighborsAlternative(int x, int y) const;
|
||||
//! returns whether the specified cell is part of the alternatively pruned diagram. See updateAlternativePrunedDiagram.
|
||||
bool isVoronoiAlternative( int x, int y ) const;
|
||||
|
||||
//! returns the obstacle distance at the specified location
|
||||
float getDistance( int x, int y ) const;
|
||||
//! returns whether the specified cell is part of the (pruned) Voronoi graph
|
||||
bool isVoronoi( int x, int y ) const;
|
||||
//! checks whether the specficied location is occupied
|
||||
bool isOccupied(int x, int y) const;
|
||||
//! write the current distance map and voronoi diagram as ppm file
|
||||
void visualize(const char* filename="result.ppm");
|
||||
|
||||
//! returns the horizontal size of the workspace/map
|
||||
unsigned int getSizeX() const {return sizeX;}
|
||||
//! returns the vertical size of the workspace/map
|
||||
unsigned int getSizeY() const {return sizeY;}
|
||||
|
||||
private:
|
||||
struct dataCell {
|
||||
float dist;
|
||||
char voronoi;
|
||||
char queueing;
|
||||
int obstX;
|
||||
int obstY;
|
||||
bool needsRaise;
|
||||
int sqdist;
|
||||
};
|
||||
|
||||
typedef enum {voronoiKeep=-4, freeQueued = -3, voronoiRetry=-2, voronoiPrune=-1, free=0, occupied=1} State;
|
||||
typedef enum {fwNotQueued=1, fwQueued=2, fwProcessed=3, bwQueued=4, bwProcessed=1} QueueingState;
|
||||
typedef enum {invalidObstData = SHRT_MAX/2} ObstDataState;
|
||||
typedef enum {pruned, keep, retry} markerMatchResult;
|
||||
|
||||
|
||||
|
||||
// methods
|
||||
void setObstacle(int x, int y);
|
||||
void removeObstacle(int x, int y);
|
||||
inline void checkVoro(int x, int y, int nx, int ny, dataCell& c, dataCell& nc);
|
||||
void recheckVoro();
|
||||
void commitAndColorize(bool updateRealDist=true);
|
||||
inline void reviveVoroNeighbors(int &x, int &y);
|
||||
|
||||
inline bool isOccupied(int &x, int &y, dataCell &c);
|
||||
inline markerMatchResult markerMatch(int x, int y);
|
||||
inline bool markerMatchAlternative(int x, int y);
|
||||
inline int getVoronoiPruneValence(int x, int y);
|
||||
|
||||
// queues
|
||||
|
||||
BucketPrioQueue<INTPOINT> open;
|
||||
std::queue<INTPOINT> pruneQueue;
|
||||
BucketPrioQueue<INTPOINT> sortedPruneQueue;
|
||||
|
||||
std::vector<INTPOINT> removeList;
|
||||
std::vector<INTPOINT> addList;
|
||||
std::vector<INTPOINT> lastObstacles;
|
||||
|
||||
// maps
|
||||
int sizeY;
|
||||
int sizeX;
|
||||
dataCell** data;
|
||||
bool** gridMap;
|
||||
bool allocatedGridMap;
|
||||
|
||||
// parameters
|
||||
int padding;
|
||||
double doubleThreshold;
|
||||
|
||||
double sqrt2;
|
||||
|
||||
// dataCell** getData(){ return data; }
|
||||
int** alternativeDiagram;
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_DYNAMIC_VORONOI_H_
|
||||
127
include/voronoi_route/map_convert.h
Normal file
127
include/voronoi_route/map_convert.h
Normal file
@@ -0,0 +1,127 @@
|
||||
#ifndef VORONOI_ROUTE_MAP_CONVERT_H_
|
||||
#define VORONOI_ROUTE_MAP_CONVERT_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/**
|
||||
* The costmap's own reading of an OccupancyGrid value — a port of
|
||||
* `robot_costmap_2d::StaticLayer::interpretValue()` with the same parameter names, so a Voronoi
|
||||
* built here calls the same cells "obstacle" as the static layer the planner runs on. Values are
|
||||
* the ones `static_layer_params.yaml` (block `static_layer:`) carries; overrides per layer come
|
||||
* from the costmap YAML (`global_costmap/<layer>/...`).
|
||||
*/
|
||||
struct StaticLayerRule {
|
||||
bool track_unknown_space = true; ///< unknown -> NO_INFORMATION (true) or FREE_SPACE (false)
|
||||
int lethal_cost_threshold = 100; ///< value >= this -> LETHAL_OBSTACLE
|
||||
int unknown_cost_value = -1; ///< the grid value that means "unknown"
|
||||
bool trinary_costmap = true; ///< true: everything below lethal is FREE; false: scaled cost
|
||||
};
|
||||
|
||||
/** What the planner does with NO_INFORMATION cells: SBPL `allow_unknown`. */
|
||||
enum class UnknownPolicy : uint8_t {
|
||||
kTraversable, ///< allow_unknown = true (SBPL default): unknown is not an obstacle
|
||||
kObstacle ///< allow_unknown = false: unknown blocks the robot
|
||||
};
|
||||
|
||||
/** Full obstacle rule: how a grid value becomes a cost class, and which classes block. */
|
||||
struct ObstacleRule {
|
||||
StaticLayerRule layer;
|
||||
UnknownPolicy unknown = UnknownPolicy::kTraversable;
|
||||
/**
|
||||
* Region of interest: the bounding box of obstacle cells grown by this margin; everything
|
||||
* outside counts as obstacle. Kills the Voronoi rays that shoot from every wall gap to the image
|
||||
* edge when the outside is free/unknown-traversable, and skips the distance transform over
|
||||
* millions of empty cells. < 0 = off. The consumer must apply the same margin (it is part of the
|
||||
* rule string) — the box is derived from the map itself, so both sides get the same box.
|
||||
*/
|
||||
int roi_margin_cells = -1;
|
||||
};
|
||||
|
||||
/** Cost classes the static layer can produce. `kScaled` only when !trinary_costmap. */
|
||||
enum class CostClass : uint8_t { kFree, kLethal, kNoInformation, kScaled };
|
||||
|
||||
/** Costmap cost values as `robot_costmap_2d/cost_values.h` defines them (copied, no dependency). */
|
||||
constexpr unsigned char kCostmapLethalObstacle = 254;
|
||||
constexpr unsigned char kCostmapNoInformation = 255;
|
||||
|
||||
/** map_server YAML fields that decide what an image pixel means. */
|
||||
struct MapServerThresholds {
|
||||
bool negate = false;
|
||||
double occupied_thresh = 0.65;
|
||||
double free_thresh = 0.196;
|
||||
};
|
||||
|
||||
struct MapConvertStats {
|
||||
size_t occupied = 0; ///< cells classified kLethal
|
||||
size_t unknown = 0; ///< cells classified kNoInformation
|
||||
size_t free = 0; ///< everything else
|
||||
};
|
||||
|
||||
/** StaticLayer::interpretValue(), classification only. */
|
||||
CostClass classifyGridValue(int value, const StaticLayerRule& rule);
|
||||
|
||||
/** True when a cell of this class is an obstacle for the Voronoi diagram under `rule`. */
|
||||
bool isObstacleClass(CostClass c, const ObstacleRule& rule);
|
||||
|
||||
/**
|
||||
* @brief Map image (any channel count) -> obstacle mask, by the ROS map_server rule in TRINARY
|
||||
* mode, which is what the robot's static layer actually receives.
|
||||
*
|
||||
* map_server (`image_loader.cpp`) averages ALL channels of a pixel — alpha included in trinary
|
||||
* mode — then occ = (255 - avg) / 255 (avg / 255 when negate); occ > occupied_thresh -> 100,
|
||||
* occ < free_thresh -> 0, otherwise -1. On an RGBA map a gray pixel (79,79,79,255) therefore
|
||||
* averages to 123 and is UNKNOWN, not occupied, and (205,205,205,255) averages to 217 and is
|
||||
* FREE. Reading the same file as luminance gives a different lethal set and a different hash, so
|
||||
* the producer must apply this rule, not a decoder's grayscale conversion.
|
||||
*
|
||||
* Then value -> class by `rule.layer`, class -> obstacle by `rule.unknown`. `pixels` is row-major,
|
||||
* row 0 = top, `channels` bytes per pixel; the mask keeps that layout.
|
||||
*/
|
||||
std::vector<uint8_t> occupancyFromImage(const uint8_t* pixels, int width, int height, int channels,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
|
||||
|
||||
/** Single-channel convenience: occupancyFromImage(gray, w, h, 1, ...). */
|
||||
std::vector<uint8_t> occupancyFromGray(const uint8_t* gray, int width, int height,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
|
||||
|
||||
/**
|
||||
* @brief OccupancyGrid int8 array -> obstacle mask, by `rule`. Input is ROS layout (row 0 =
|
||||
* bottom); output is flipped to row 0 = top to match the image layout used everywhere else.
|
||||
*/
|
||||
std::vector<uint8_t> occupancyFromGrid(const int8_t* data, int width, int height,
|
||||
const ObstacleRule& rule, MapConvertStats* stats = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Live costmap char map (values 0..255 as the static layer wrote them) -> obstacle mask.
|
||||
* This is what a runtime consumer hashes to decide whether a bundle matches:
|
||||
* 254 -> obstacle; 255 -> obstacle only under UnknownPolicy::kObstacle; else free.
|
||||
* @param rows_bottom_up true for a costmap (row 0 = bottom): the mask is flipped to row 0 = top.
|
||||
*/
|
||||
std::vector<uint8_t> occupancyFromCostmap(const unsigned char* charmap, int width, int height,
|
||||
UnknownPolicy unknown, bool rows_bottom_up);
|
||||
|
||||
/**
|
||||
* @brief Apply ObstacleRule::roi_margin_cells to a mask in place: cells outside the grown bounding
|
||||
* box of the mask's obstacle cells become obstacles. No-op when margin < 0 or when the mask
|
||||
* has fewer than `min_obstacle_cells` obstacles (a near-empty map has no meaningful box).
|
||||
* @return number of cells turned into obstacles.
|
||||
*/
|
||||
size_t applyObstacleRoi(std::vector<uint8_t>& mask, int width, int height, int margin_cells,
|
||||
size_t min_obstacle_cells = 16);
|
||||
|
||||
/** Compact, stable description for the bundle's `source` field, e.g. "lethal>=100;...;unknown=traversable;roi=40". */
|
||||
std::string obstacleRuleString(const ObstacleRule& rule);
|
||||
|
||||
/** Inverse of obstacleRuleString(); false if the string is not one it produced. */
|
||||
bool parseObstacleRuleString(const std::string& s, ObstacleRule* rule);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_MAP_CONVERT_H_
|
||||
62
include/voronoi_route/params.h
Normal file
62
include/voronoi_route/params.h
Normal file
@@ -0,0 +1,62 @@
|
||||
#ifndef VORONOI_ROUTE_PARAMS_H_
|
||||
#define VORONOI_ROUTE_PARAMS_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/map_convert.h"
|
||||
#include "voronoi_route/types.h"
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/**
|
||||
* @brief Operator-facing parameters, in metres — the contents of `voronoi_route_params.yaml`.
|
||||
*
|
||||
* The library computes in cells; convert with the map's resolution at load time. Defaults here
|
||||
* are the ones in the packaged YAML; a missing key keeps the default and the loader says so.
|
||||
*/
|
||||
struct RouteParams {
|
||||
// graph
|
||||
double min_edge_length_m = 0.3;
|
||||
double spur_clearance_ratio = 1.2;
|
||||
double min_component_length_m = 2.0;
|
||||
double min_clearance_m = 0.3;
|
||||
double attach_max_radius_m = 10.0;
|
||||
int graph_rebuild_min_changed_cells = 200;
|
||||
double full_rebuild_fraction = 0.02;
|
||||
// corridor
|
||||
double half_width_min_m = 1.5;
|
||||
double clearance_scale = 0.8;
|
||||
double half_width_max_m = 6.0;
|
||||
// bundle
|
||||
bool write_gvd = true;
|
||||
bool write_dist = true;
|
||||
bool write_preview = true;
|
||||
bool write_graph_image = true;
|
||||
bool write_graph_overlay = false;
|
||||
// obstacle: luật "ô nào là vật cản" của riêng gói này, không đọc chéo sang config gói khác.
|
||||
bool track_unknown_space = true;
|
||||
int lethal_cost_threshold = 100;
|
||||
int unknown_cost_value = -1;
|
||||
bool trinary_costmap = true;
|
||||
// obstacle.unknown: false traversable, true obstacle — quyết định thẳng, không suy từ khoá nào khác.
|
||||
bool unknown_is_obstacle = false;
|
||||
// obstacle.roi_margin_m: < 0 = off
|
||||
double roi_margin_m = 0.5;
|
||||
|
||||
VoronoiRoute::Config toConfig(double resolution_m) const;
|
||||
CorridorParams toCorridor(double resolution_m) const;
|
||||
/** Obstacle rule for this map's resolution, resolved from the fields above only. */
|
||||
ObstacleRule toObstacleRule(double resolution_m) const;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Clamp out-of-range values to something safe and describe each fix. Empty vector = all
|
||||
* good. Never throws: a bad number in a YAML must not stop a map from being compiled.
|
||||
*/
|
||||
std::vector<std::string> validateRouteParams(RouteParams* p);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_PARAMS_H_
|
||||
29
include/voronoi_route/params_io.h
Normal file
29
include/voronoi_route/params_io.h
Normal file
@@ -0,0 +1,29 @@
|
||||
#ifndef VORONOI_ROUTE_PARAMS_IO_H_
|
||||
#define VORONOI_ROUTE_PARAMS_IO_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/params.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/**
|
||||
* @brief First file named `name` under `dir`, searched recursively — the lookup
|
||||
* robot_costmap_2d uses for its layer YAMLs, so "the robot's config dir" means the same
|
||||
* thing here. Empty string if not found or `dir` is not a directory.
|
||||
*/
|
||||
std::string findConfigFile(const std::string& dir, const std::string& name);
|
||||
|
||||
/**
|
||||
* @brief Load `voronoi_route_params.yaml` (root key `voronoi_route`). Missing keys keep defaults;
|
||||
* every missing key is listed in `notes` so a typo does not silently become a default.
|
||||
* Out-of-range values are clamped by validateRouteParams(), also reported in `notes`.
|
||||
* @return false only when the file cannot be read or parsed at all.
|
||||
*/
|
||||
bool loadRouteParams(const std::string& yaml_path, RouteParams* params, std::string* err,
|
||||
std::vector<std::string>* notes);
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_PARAMS_IO_H_
|
||||
18
include/voronoi_route/point.h
Normal file
18
include/voronoi_route/point.h
Normal file
@@ -0,0 +1,18 @@
|
||||
#ifndef VORONOI_ROUTE_POINT_H_
|
||||
#define VORONOI_ROUTE_POINT_H_
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
#define INTPOINT IntPoint
|
||||
|
||||
/*! A light-weight integer point with fields x,y */
|
||||
class IntPoint {
|
||||
public:
|
||||
IntPoint() : x(0), y(0) {}
|
||||
IntPoint(int _x, int _y) : x(_x), y(_y) {}
|
||||
int x,y;
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_POINT_H_
|
||||
39
include/voronoi_route/types.h
Normal file
39
include/voronoi_route/types.h
Normal file
@@ -0,0 +1,39 @@
|
||||
#ifndef VORONOI_ROUTE_TYPES_H_
|
||||
#define VORONOI_ROUTE_TYPES_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/** Integer grid cell. x = column, y = row of the occupancy grid as handed to the library. */
|
||||
struct Cell {
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
Cell() = default;
|
||||
Cell(int x_, int y_) : x(x_), y(y_) {}
|
||||
bool operator==(const Cell& o) const { return x == o.x && y == o.y; }
|
||||
bool operator!=(const Cell& o) const { return !(*this == o); }
|
||||
};
|
||||
|
||||
/** Ordered, 8-connected chain of cells. */
|
||||
using Polyline = std::vector<Cell>;
|
||||
|
||||
/** Where a free cell attaches to the route graph, plus the free-space path that gets there. */
|
||||
struct Attachment {
|
||||
bool ok = false;
|
||||
int edge = -1; ///< Graph edge holding the attach cell.
|
||||
int index = -1; ///< Position of the attach cell inside that edge's cell chain.
|
||||
Polyline path; ///< From the queried cell (front) to the attach cell (back), 8-connected, free.
|
||||
};
|
||||
|
||||
/** Corridor width policy, all in cells. */
|
||||
struct CorridorParams {
|
||||
double half_width_min_cells = 30.0; ///< W_min: never narrower than this.
|
||||
double clearance_scale = 0.8; ///< W(c) = max(W_min, scale * clearance(c)).
|
||||
double half_width_max_cells = 120.0; ///< Cap for the adaptive width.
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_TYPES_H_
|
||||
65
include/voronoi_route/voronoi_field.h
Normal file
65
include/voronoi_route/voronoi_field.h
Normal file
@@ -0,0 +1,65 @@
|
||||
#ifndef VORONOI_ROUTE_VORONOI_FIELD_H_
|
||||
#define VORONOI_ROUTE_VORONOI_FIELD_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/types.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
class DynamicVoronoi;
|
||||
|
||||
/**
|
||||
* @brief Distance map + generalized Voronoi diagram over a flat occupancy grid.
|
||||
*
|
||||
* Thin owner of the ported DynamicVoronoi (Lau et al.). Callers hand in a flat row-major grid;
|
||||
* this class keeps the column-major `bool**` view DynamicVoronoi insists on, so the caller never
|
||||
* sees that layout. Only cells flagged occupied by the caller's predicate are obstacles — the
|
||||
* library has no opinion on what "occupied" means (lethal, unknown, ...). That decision is the
|
||||
* caller's, and it must be the same decision the runtime consumer makes, or hashes will not match.
|
||||
*/
|
||||
class VoronoiField {
|
||||
public:
|
||||
VoronoiField();
|
||||
~VoronoiField();
|
||||
VoronoiField(const VoronoiField&) = delete;
|
||||
VoronoiField& operator=(const VoronoiField&) = delete;
|
||||
|
||||
/** Rebuild from scratch. `occupied` is row-major, size_x*size_y, nonzero = obstacle. */
|
||||
void rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y);
|
||||
|
||||
/** Queue occupancy changes; nothing is recomputed until refresh(). */
|
||||
void setOccupied(const std::vector<Cell>& cells);
|
||||
void setFree(const std::vector<Cell>& cells);
|
||||
|
||||
/** Propagate queued changes (incremental) and re-thin the diagram. */
|
||||
void refresh();
|
||||
|
||||
bool ready() const { return ready_; }
|
||||
int sizeX() const { return size_x_; }
|
||||
int sizeY() const { return size_y_; }
|
||||
|
||||
bool inBounds(int x, int y) const { return x >= 0 && y >= 0 && x < size_x_ && y < size_y_; }
|
||||
bool isVoronoi(int x, int y) const;
|
||||
bool isOccupied(int x, int y) const;
|
||||
/** Euclidean distance to the nearest obstacle, in cells. Occupied cells return 0. */
|
||||
float distanceCells(int x, int y) const;
|
||||
|
||||
/** Row-major copy of the occupancy the field currently holds (what the diagram was built from). */
|
||||
const std::vector<uint8_t>& occupancy() const { return occupancy_; }
|
||||
|
||||
private:
|
||||
std::unique_ptr<DynamicVoronoi> dv_;
|
||||
int size_x_ = 0;
|
||||
int size_y_ = 0;
|
||||
bool ready_ = false;
|
||||
std::vector<uint8_t> occupancy_; // row-major mirror, kept in sync with dv_
|
||||
std::vector<std::unique_ptr<bool[]>> columns_; // column-major storage DynamicVoronoi points into
|
||||
std::vector<bool*> column_ptrs_;
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_VORONOI_FIELD_H_
|
||||
114
include/voronoi_route/voronoi_graph.h
Normal file
114
include/voronoi_route/voronoi_graph.h
Normal file
@@ -0,0 +1,114 @@
|
||||
#ifndef VORONOI_ROUTE_VORONOI_GRAPH_H_
|
||||
#define VORONOI_ROUTE_VORONOI_GRAPH_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/types.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
class VoronoiField;
|
||||
|
||||
struct GraphNode {
|
||||
Cell cell;
|
||||
std::vector<int> edges; ///< Incident edge indices. A loop edge (u == v) appears once.
|
||||
};
|
||||
|
||||
struct GraphEdge {
|
||||
int u = -1;
|
||||
int v = -1;
|
||||
Polyline cells; ///< cells.front() is node u's cell, cells.back() node v's.
|
||||
std::vector<float> cum_cells; ///< cum_cells[i] = walked length from cells[0] to cells[i].
|
||||
float length_cells = 0.0f; ///< == cum_cells.back().
|
||||
float min_clearance_cells = 0.0f; ///< Narrowest point along the chain.
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Route graph extracted from a thinned GVD: junctions/dead-ends are nodes, the chains
|
||||
* between them are edges. Also answers "which edge does this GVD cell belong to" and
|
||||
* routes between two attached points with Dijkstra.
|
||||
*/
|
||||
class VoronoiGraph {
|
||||
public:
|
||||
/**
|
||||
* @param min_edge_length_cells Dead-end branches shorter than this are pruned (SLAM wall
|
||||
* noise grows stubs a few cells long at every convex corner). Pruning repeats until
|
||||
* nothing short is left, and nodes left with exactly two edges are merged away.
|
||||
*/
|
||||
struct ExtractParams {
|
||||
double min_edge_length_cells = 6.0;
|
||||
/**
|
||||
* A dead-end branch shorter than `ratio * clearance(root junction)` never leaves the empty
|
||||
* disc around its junction: it is the diagram reacting to a notch in a far wall, not a way
|
||||
* anywhere. Real dead-end corridors are longer than the hall they leave. 0 disables.
|
||||
*/
|
||||
double spur_clearance_ratio = 1.0;
|
||||
/** Connected components whose total edge length is below this are dropped (pockets). */
|
||||
double min_component_length_cells = 0.0;
|
||||
/**
|
||||
* Edges whose narrowest point has less clearance than this are dropped before anything
|
||||
* else: a passage the robot cannot fit through is not a route, and on SLAM maps the ragged
|
||||
* free/unknown frontier grows dense little loops of exactly that kind. Set it to the robot's
|
||||
* inscribed radius in cells. 0 disables.
|
||||
*/
|
||||
double min_clearance_cells = 0.0;
|
||||
};
|
||||
|
||||
void extract(const VoronoiField& field, const ExtractParams& params);
|
||||
void extract(const VoronoiField& field, double min_edge_length_cells)
|
||||
{
|
||||
ExtractParams p;
|
||||
p.min_edge_length_cells = min_edge_length_cells;
|
||||
extract(field, p);
|
||||
}
|
||||
|
||||
void clear();
|
||||
bool empty() const { return edges_.empty(); }
|
||||
int sizeX() const { return size_x_; }
|
||||
int sizeY() const { return size_y_; }
|
||||
|
||||
const std::vector<GraphNode>& nodes() const { return nodes_; }
|
||||
const std::vector<GraphEdge>& edges() const { return edges_; }
|
||||
|
||||
/** Edge index of a GVD cell, -1 if the cell is not on the graph. */
|
||||
int edgeAt(int x, int y) const;
|
||||
/** Position of the cell inside edges()[edgeAt(x,y)].cells, -1 if not on the graph. */
|
||||
int indexOnEdge(int x, int y) const;
|
||||
|
||||
/** Number of connected components (nodes reachable from each other). */
|
||||
int componentCount() const;
|
||||
|
||||
/**
|
||||
* Shortest route along the graph between two attached points. Result runs from a's attach
|
||||
* cell to b's attach cell inclusive, 8-connected. Empty if they are on different components.
|
||||
*/
|
||||
Polyline route(const Attachment& a, const Attachment& b) const;
|
||||
|
||||
private:
|
||||
struct RawEdge {
|
||||
int u, v;
|
||||
Polyline cells;
|
||||
};
|
||||
|
||||
void traceFromNodes(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
const std::vector<int>& degree, std::vector<int>& node_of_cell,
|
||||
std::vector<uint8_t>& visited, std::vector<RawEdge>& raw);
|
||||
void traceCycles(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
|
||||
std::vector<RawEdge>& raw);
|
||||
void pruneSpursAndMerge(const VoronoiField& field, const ExtractParams& params);
|
||||
void dropSmallComponents(double min_total_length_cells);
|
||||
void finalize(const VoronoiField& field);
|
||||
|
||||
int size_x_ = 0;
|
||||
int size_y_ = 0;
|
||||
std::vector<GraphNode> nodes_;
|
||||
std::vector<GraphEdge> edges_;
|
||||
std::vector<int32_t> cell_edge_; // size_x*size_y, -1 = not on graph
|
||||
std::vector<int32_t> cell_index_; // position within that edge's chain
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_VORONOI_GRAPH_H_
|
||||
98
include/voronoi_route/voronoi_route.h
Normal file
98
include/voronoi_route/voronoi_route.h
Normal file
@@ -0,0 +1,98 @@
|
||||
#ifndef VORONOI_ROUTE_VORONOI_ROUTE_H_
|
||||
#define VORONOI_ROUTE_VORONOI_ROUTE_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/attachment.h"
|
||||
#include "voronoi_route/corridor_mask.h"
|
||||
#include "voronoi_route/types.h"
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
#include "voronoi_route/voronoi_graph.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
/**
|
||||
* @brief FNV-1a 64 over the bit-packed obstacle mask, row-major. The one hash both the producer
|
||||
* (offline compile) and the consumer (planner on the live static layer) use; if they ever
|
||||
* computed it differently, a stale graph could be accepted in silence.
|
||||
*/
|
||||
uint64_t hashObstacleMask(const std::vector<uint8_t>& occupied);
|
||||
|
||||
/**
|
||||
* @brief Facade: occupancy in, route polylines and corridor masks out.
|
||||
*
|
||||
* Holds the distance field, the extracted graph and the config. Nothing here knows about
|
||||
* costmaps, messages or threads; the caller decides what "occupied" means and serialises access.
|
||||
*/
|
||||
class VoronoiRoute {
|
||||
public:
|
||||
struct Config {
|
||||
double min_edge_length_cells = 6.0; ///< Spur filter, absolute (0.3 m at 5 cm).
|
||||
double spur_clearance_ratio = 1.2; ///< Spur filter, relative to clearance at root.
|
||||
double min_component_length_cells = 40.0; ///< Drop pocket components (2 m at 5 cm).
|
||||
double min_clearance_cells = 0.0; ///< Drop edges narrower than the robot (0 = off).
|
||||
int attach_max_radius_cells = 200; ///< BFS bound for attach() (10 m at 5 cm).
|
||||
size_t graph_rebuild_min_changed_cells = 200; ///< Below: distance update only, graph kept.
|
||||
double full_rebuild_fraction = 0.02; ///< Above this share of cells: rebuild, not incremental.
|
||||
};
|
||||
|
||||
struct Stats {
|
||||
int nodes = 0;
|
||||
int edges = 0;
|
||||
int components = 0;
|
||||
size_t gvd_cells = 0;
|
||||
size_t obstacle_cells = 0;
|
||||
double field_ms = 0.0; ///< DynamicVoronoi build/update + prune.
|
||||
double extract_ms = 0.0; ///< Graph extraction.
|
||||
size_t last_sync_changed = 0;
|
||||
bool last_sync_full_rebuild = false;
|
||||
};
|
||||
|
||||
VoronoiRoute();
|
||||
explicit VoronoiRoute(const Config& cfg);
|
||||
|
||||
/** Build everything from scratch. `occupied` row-major, size_x*size_y, nonzero = obstacle. */
|
||||
void rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y);
|
||||
|
||||
/**
|
||||
* Compare `occupied` (same size as the current field) with what the field holds and bring it up
|
||||
* to date: nothing, incremental occupy/clear + refresh, or a full rebuild when the change is
|
||||
* wide (a whole-floor swap is faster from scratch than by propagation). The graph is
|
||||
* re-extracted when the number of changed cells exceeds `graph_rebuild_min_changed_cells`.
|
||||
* @return number of cells whose obstacle state differed. Size mismatch -> full rebuild.
|
||||
*/
|
||||
size_t syncOccupancy(const std::vector<uint8_t>& occupied, int size_x, int size_y);
|
||||
|
||||
bool ready() const { return field_.ready() && !graph_.empty(); }
|
||||
|
||||
Attachment attach(Cell c) const;
|
||||
|
||||
/** start -> ... -> goal, including both attach paths. Empty if no route on the graph. */
|
||||
Polyline query(const Attachment& start, const Attachment& goal) const;
|
||||
|
||||
std::vector<uint8_t> corridorMask(const Polyline& route, const CorridorParams& p,
|
||||
size_t* cells_in_mask) const;
|
||||
|
||||
const VoronoiField& field() const { return field_; }
|
||||
const VoronoiGraph& graph() const { return graph_; }
|
||||
const Stats& stats() const { return stats_; }
|
||||
const Config& config() const { return cfg_; }
|
||||
|
||||
/** Hash of the occupancy the field was built from. */
|
||||
uint64_t occupancyHash() const { return occupancy_hash_; }
|
||||
|
||||
private:
|
||||
void extractGraph();
|
||||
|
||||
Config cfg_;
|
||||
VoronoiField field_;
|
||||
VoronoiGraph graph_;
|
||||
Stats stats_;
|
||||
uint64_t occupancy_hash_ = 0;
|
||||
};
|
||||
|
||||
} // namespace voronoi_route
|
||||
|
||||
#endif // VORONOI_ROUTE_VORONOI_ROUTE_H_
|
||||
82
src/attachment.cpp
Normal file
82
src/attachment.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
#include "voronoi_route/attachment.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <queue>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
#include "voronoi_route/voronoi_graph.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
constexpr int kDx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
|
||||
constexpr int kDy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
|
||||
} // namespace
|
||||
|
||||
Attachment attachPoint(const VoronoiField& field, const VoronoiGraph& graph, Cell from,
|
||||
int max_radius_cells)
|
||||
{
|
||||
Attachment out;
|
||||
if (!field.ready() || graph.empty() || !field.inBounds(from.x, from.y)) return out;
|
||||
|
||||
// Already on the graph.
|
||||
if (graph.edgeAt(from.x, from.y) >= 0)
|
||||
{
|
||||
out.ok = true;
|
||||
out.edge = graph.edgeAt(from.x, from.y);
|
||||
out.index = graph.indexOnEdge(from.x, from.y);
|
||||
out.path = {from};
|
||||
return out;
|
||||
}
|
||||
|
||||
// Parent map keyed by linear index; a full-grid array would cost 4M entries per query.
|
||||
const int w = field.sizeX();
|
||||
auto key = [w](const Cell& c) { return static_cast<long long>(c.y) * w + c.x; };
|
||||
std::unordered_map<long long, long long> parent;
|
||||
std::queue<Cell> q;
|
||||
parent[key(from)] = -1;
|
||||
q.push(from);
|
||||
|
||||
Cell hit;
|
||||
bool found = false;
|
||||
while (!q.empty())
|
||||
{
|
||||
const Cell c = q.front();
|
||||
q.pop();
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const Cell n(c.x + kDx[k], c.y + kDy[k]);
|
||||
if (!field.inBounds(n.x, n.y)) continue;
|
||||
if (std::abs(n.x - from.x) > max_radius_cells || std::abs(n.y - from.y) > max_radius_cells)
|
||||
continue;
|
||||
if (field.isOccupied(n.x, n.y)) continue;
|
||||
const long long nk = key(n);
|
||||
if (parent.count(nk)) continue;
|
||||
parent[nk] = key(c);
|
||||
if (graph.edgeAt(n.x, n.y) >= 0)
|
||||
{
|
||||
hit = n;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
q.push(n);
|
||||
}
|
||||
if (found) break;
|
||||
}
|
||||
if (!found) return out;
|
||||
|
||||
Polyline rev;
|
||||
for (long long k = key(hit); k != -1; k = parent[k])
|
||||
rev.push_back(Cell(static_cast<int>(k % w), static_cast<int>(k / w)));
|
||||
std::reverse(rev.begin(), rev.end());
|
||||
|
||||
out.ok = true;
|
||||
out.edge = graph.edgeAt(hit.x, hit.y);
|
||||
out.index = graph.indexOnEdge(hit.x, hit.y);
|
||||
out.path = std::move(rev);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
235
src/bundle_io.cpp
Normal file
235
src/bundle_io.cpp
Normal file
@@ -0,0 +1,235 @@
|
||||
#include "voronoi_route/bundle_io.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
bool ensureDir(const std::string& dir)
|
||||
{
|
||||
// mkdir -p: the bundle dir normally sits inside a map folder that already exists, but a tool
|
||||
// pointed at a fresh --out must not fail on the parent.
|
||||
std::string cur;
|
||||
for (size_t i = 0; i <= dir.size(); ++i)
|
||||
{
|
||||
if (i < dir.size() && dir[i] != '/') continue;
|
||||
cur = dir.substr(0, i);
|
||||
if (cur.empty()) continue;
|
||||
struct stat st;
|
||||
if (::stat(cur.c_str(), &st) == 0)
|
||||
{
|
||||
if (!S_ISDIR(st.st_mode)) return false;
|
||||
continue;
|
||||
}
|
||||
if (::mkdir(cur.c_str(), 0775) != 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string hexOf(uint64_t v)
|
||||
{
|
||||
std::ostringstream o;
|
||||
o << std::hex << std::setw(16) << std::setfill('0') << v;
|
||||
return o.str();
|
||||
}
|
||||
|
||||
bool parseHex(const std::string& s, uint64_t* out)
|
||||
{
|
||||
if (s.empty() || !out) return false;
|
||||
char* end = nullptr;
|
||||
const unsigned long long v = std::strtoull(s.c_str(), &end, 16);
|
||||
if (end == nullptr || *end != '\0') return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool writePgm8(const std::string& path, const std::vector<uint8_t>& data, int w, int h)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
f << "P5\n" << w << " " << h << "\n255\n";
|
||||
f.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
|
||||
return static_cast<bool>(f);
|
||||
}
|
||||
|
||||
bool writePgm16(const std::string& path, const std::vector<uint16_t>& data, int w, int h)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f) return false;
|
||||
f << "P5\n" << w << " " << h << "\n65535\n";
|
||||
std::vector<uint8_t> be(data.size() * 2);
|
||||
for (size_t i = 0; i < data.size(); ++i)
|
||||
{
|
||||
be[2 * i] = static_cast<uint8_t>(data[i] >> 8);
|
||||
be[2 * i + 1] = static_cast<uint8_t>(data[i] & 0xFF);
|
||||
}
|
||||
f.write(reinterpret_cast<const char*>(be.data()), static_cast<std::streamsize>(be.size()));
|
||||
return static_cast<bool>(f);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool saveBundle(const VoronoiRoute& vr, const BundleMeta& meta, const std::string& dir,
|
||||
bool with_gvd, bool with_dist, std::string* err)
|
||||
{
|
||||
if (!vr.ready())
|
||||
{
|
||||
if (err) *err = "graph not built";
|
||||
return false;
|
||||
}
|
||||
if (!ensureDir(dir))
|
||||
{
|
||||
if (err) *err = "cannot create " + dir;
|
||||
return false;
|
||||
}
|
||||
const int w = vr.field().sizeX(), h = vr.field().sizeY();
|
||||
const auto& st = vr.stats();
|
||||
const auto& cfg = vr.config();
|
||||
|
||||
nlohmann::json j;
|
||||
j["version"] = meta.version;
|
||||
j["source"] = meta.source;
|
||||
j["map_hash"] = hexOf(meta.map_hash ? meta.map_hash : vr.occupancyHash());
|
||||
j["info"] = {{"width", w}, {"height", h}, {"resolution", meta.resolution},
|
||||
{"origin", {meta.origin_x, meta.origin_y, meta.origin_yaw}}};
|
||||
j["params"] = {{"min_edge_length_cells", cfg.min_edge_length_cells},
|
||||
{"spur_clearance_ratio", cfg.spur_clearance_ratio},
|
||||
{"min_component_length_cells", cfg.min_component_length_cells}};
|
||||
j["stats"] = {{"nodes", st.nodes}, {"edges", st.edges}, {"components", st.components},
|
||||
{"gvd_cells", st.gvd_cells}, {"obstacle_cells", st.obstacle_cells},
|
||||
{"field_ms", st.field_ms}, {"extract_ms", st.extract_ms}};
|
||||
j["files"] = {{"gvd", with_gvd ? "voronoi_gvd.pgm" : ""},
|
||||
{"dist", with_dist ? "voronoi_dist.pgm" : ""}};
|
||||
|
||||
nlohmann::json nodes = nlohmann::json::array();
|
||||
for (const auto& nd : vr.graph().nodes()) nodes.push_back({nd.cell.x, nd.cell.y});
|
||||
j["nodes"] = std::move(nodes);
|
||||
nlohmann::json edges = nlohmann::json::array();
|
||||
for (const auto& e : vr.graph().edges())
|
||||
{
|
||||
nlohmann::json cells = nlohmann::json::array();
|
||||
for (const auto& c : e.cells) cells.push_back({c.x, c.y});
|
||||
edges.push_back({{"u", e.u}, {"v", e.v}, {"length_cells", e.length_cells},
|
||||
{"min_clearance_cells", e.min_clearance_cells}, {"cells", std::move(cells)}});
|
||||
}
|
||||
j["edges"] = std::move(edges);
|
||||
|
||||
{
|
||||
std::ofstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "cannot write " + dir + "/voronoi.json";
|
||||
return false;
|
||||
}
|
||||
f << j.dump();
|
||||
}
|
||||
|
||||
if (with_gvd)
|
||||
{
|
||||
std::vector<uint8_t> gvd(static_cast<size_t>(w) * h, 0);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
if (vr.field().isVoronoi(x, y)) gvd[static_cast<size_t>(y) * w + x] = 255;
|
||||
if (!writePgm8(dir + "/voronoi_gvd.pgm", gvd, w, h))
|
||||
{
|
||||
if (err) *err = "cannot write voronoi_gvd.pgm";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (with_dist)
|
||||
{
|
||||
std::vector<uint16_t> dist(static_cast<size_t>(w) * h, 0);
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const double d = vr.field().distanceCells(x, y) * 10.0;
|
||||
dist[static_cast<size_t>(y) * w + x] =
|
||||
static_cast<uint16_t>(std::min(65535.0, std::max(0.0, d)));
|
||||
}
|
||||
if (!writePgm16(dir + "/voronoi_dist.pgm", dist, w, h))
|
||||
{
|
||||
if (err) *err = "cannot write voronoi_dist.pgm";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadBundleMeta(const std::string& dir, BundleMeta* meta, std::string* err)
|
||||
{
|
||||
std::ifstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "no voronoi.json in " + dir;
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
nlohmann::json j;
|
||||
f >> j;
|
||||
BundleMeta m;
|
||||
m.version = j.value("version", 0u);
|
||||
m.source = j.value("source", "");
|
||||
if (!parseHex(j.value("map_hash", ""), &m.map_hash))
|
||||
{
|
||||
if (err) *err = "bad map_hash";
|
||||
return false;
|
||||
}
|
||||
const auto& info = j.at("info");
|
||||
m.width = info.value("width", 0);
|
||||
m.height = info.value("height", 0);
|
||||
m.resolution = info.value("resolution", 0.0);
|
||||
const auto& o = info.at("origin");
|
||||
m.origin_x = o.at(0).get<double>();
|
||||
m.origin_y = o.at(1).get<double>();
|
||||
m.origin_yaw = o.size() > 2 ? o.at(2).get<double>() : 0.0;
|
||||
if (meta) *meta = m;
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = std::string("voronoi.json: ") + e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool appendRouteToBundle(const std::string& dir, const Polyline& route, size_t mask_cells,
|
||||
std::string* err)
|
||||
{
|
||||
nlohmann::json j;
|
||||
{
|
||||
std::ifstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "no voronoi.json in " + dir;
|
||||
return false;
|
||||
}
|
||||
try { f >> j; }
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
nlohmann::json rc = nlohmann::json::array();
|
||||
for (const auto& c : route) rc.push_back({c.x, c.y});
|
||||
j["route"] = {{"cells", std::move(rc)}, {"mask_cells", mask_cells}};
|
||||
std::ofstream f(dir + "/voronoi.json");
|
||||
if (!f)
|
||||
{
|
||||
if (err) *err = "cannot write voronoi.json";
|
||||
return false;
|
||||
}
|
||||
f << j.dump();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
87
src/corridor_mask.cpp
Normal file
87
src/corridor_mask.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
#include "voronoi_route/corridor_mask.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
void stampDisc(std::vector<uint8_t>& mask, int w, int h, const Cell& c, double r, size_t& count)
|
||||
{
|
||||
const int ri = static_cast<int>(std::ceil(r));
|
||||
const double r2 = r * r;
|
||||
const int y0 = std::max(0, c.y - ri), y1 = std::min(h - 1, c.y + ri);
|
||||
const int x0 = std::max(0, c.x - ri), x1 = std::min(w - 1, c.x + ri);
|
||||
for (int y = y0; y <= y1; ++y)
|
||||
{
|
||||
const double dy = static_cast<double>(y - c.y);
|
||||
uint8_t* row = mask.data() + static_cast<size_t>(y) * w;
|
||||
for (int x = x0; x <= x1; ++x)
|
||||
{
|
||||
const double dx = static_cast<double>(x - c.x);
|
||||
if (dx * dx + dy * dy > r2) continue;
|
||||
if (!row[x])
|
||||
{
|
||||
row[x] = 1;
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> corridorMask(const VoronoiField& field, const Polyline& polyline,
|
||||
const CorridorParams& params, size_t* cells_in_mask)
|
||||
{
|
||||
const int w = field.sizeX(), h = field.sizeY();
|
||||
std::vector<uint8_t> mask(static_cast<size_t>(w) * h, 0);
|
||||
size_t count = 0;
|
||||
if (!field.ready() || polyline.empty())
|
||||
{
|
||||
if (cells_in_mask) *cells_in_mask = 0;
|
||||
return mask;
|
||||
}
|
||||
|
||||
const double w_min = std::max(1.0, params.half_width_min_cells);
|
||||
const double w_max = std::max(w_min, params.half_width_max_cells);
|
||||
|
||||
double last_stamp_pos = -1e9;
|
||||
double pos = 0.0;
|
||||
for (size_t i = 0; i < polyline.size(); ++i)
|
||||
{
|
||||
const Cell& c = polyline[i];
|
||||
if (i > 0)
|
||||
{
|
||||
const Cell& p = polyline[i - 1];
|
||||
pos += (p.x != c.x && p.y != c.y) ? 1.41421356 : 1.0;
|
||||
}
|
||||
const double clearance = field.distanceCells(c.x, c.y);
|
||||
double r = std::max(w_min, params.clearance_scale * clearance);
|
||||
r = std::min(r, w_max);
|
||||
|
||||
const bool last = i + 1 == polyline.size();
|
||||
if (i == 0 || last || pos - last_stamp_pos >= r * 0.5)
|
||||
{
|
||||
stampDisc(mask, w, h, c, r, count);
|
||||
last_stamp_pos = pos;
|
||||
}
|
||||
// The line itself is always inside, whatever the sampling did.
|
||||
if (field.inBounds(c.x, c.y))
|
||||
{
|
||||
uint8_t& m = mask[static_cast<size_t>(c.y) * w + c.x];
|
||||
if (!m)
|
||||
{
|
||||
m = 1;
|
||||
++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cells_in_mask) *cells_in_mask = count;
|
||||
return mask;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
724
src/dynamic_voronoi.cpp
Normal file
724
src/dynamic_voronoi.cpp
Normal file
@@ -0,0 +1,724 @@
|
||||
#include "voronoi_route/dynamic_voronoi.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <iostream>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
DynamicVoronoi::DynamicVoronoi() {
|
||||
sqrt2 = sqrt(2.0);
|
||||
data = NULL;
|
||||
gridMap = NULL;
|
||||
alternativeDiagram = NULL;
|
||||
allocatedGridMap = false;
|
||||
}
|
||||
|
||||
DynamicVoronoi::~DynamicVoronoi() {
|
||||
if (data) {
|
||||
for (int x=0; x<sizeX; x++) delete[] data[x];
|
||||
delete[] data;
|
||||
}
|
||||
if (allocatedGridMap && gridMap) {
|
||||
for (int x=0; x<sizeX; x++) delete[] gridMap[x];
|
||||
delete[] gridMap;
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::initializeEmpty(int _sizeX, int _sizeY, bool initGridMap) {
|
||||
if (data) {
|
||||
for (int x=0; x<sizeX; x++) delete[] data[x];
|
||||
delete[] data;
|
||||
data = NULL;
|
||||
}
|
||||
if(alternativeDiagram){
|
||||
for (int x=0; x<sizeX; x++) delete[] alternativeDiagram[x];
|
||||
delete[] alternativeDiagram;
|
||||
alternativeDiagram = NULL;
|
||||
}
|
||||
if (initGridMap) {
|
||||
if (allocatedGridMap && gridMap) {
|
||||
for (int x=0; x<sizeX; x++) delete[] gridMap[x];
|
||||
delete[] gridMap;
|
||||
gridMap = NULL;
|
||||
allocatedGridMap = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
sizeX = _sizeX;
|
||||
sizeY = _sizeY;
|
||||
data = new dataCell*[sizeX];
|
||||
for (int x=0; x<sizeX; x++) data[x] = new dataCell[sizeY];
|
||||
|
||||
if (initGridMap) {
|
||||
gridMap = new bool*[sizeX];
|
||||
for (int x=0; x<sizeX; x++) gridMap[x] = new bool[sizeY];
|
||||
allocatedGridMap = true;
|
||||
}
|
||||
|
||||
dataCell c;
|
||||
c.dist = INFINITY;
|
||||
c.sqdist = INT_MAX;
|
||||
c.obstX = invalidObstData;
|
||||
c.obstY = invalidObstData;
|
||||
c.voronoi = free;
|
||||
c.queueing = fwNotQueued;
|
||||
c.needsRaise = false;
|
||||
|
||||
for (int x=0; x<sizeX; x++)
|
||||
for (int y=0; y<sizeY; y++) data[x][y] = c;
|
||||
|
||||
if (initGridMap) {
|
||||
for (int x=0; x<sizeX; x++)
|
||||
for (int y=0; y<sizeY; y++) gridMap[x][y] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::initializeMap(int _sizeX, int _sizeY, bool** _gridMap) {
|
||||
gridMap = _gridMap;
|
||||
initializeEmpty(_sizeX, _sizeY, false);
|
||||
|
||||
for (int x=0; x<sizeX; x++) {
|
||||
for (int y=0; y<sizeY; y++) {
|
||||
if (gridMap[x][y]) {
|
||||
dataCell c = data[x][y];
|
||||
if (!isOccupied(x,y,c)) {
|
||||
|
||||
bool isSurrounded = true;
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
|
||||
if (!gridMap[nx][ny]) {
|
||||
isSurrounded = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isSurrounded) {
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
c.sqdist = 0;
|
||||
c.dist=0;
|
||||
c.voronoi=occupied;
|
||||
c.queueing = fwProcessed;
|
||||
data[x][y] = c;
|
||||
} else setObstacle(x,y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::occupyCell(int x, int y) {
|
||||
gridMap[x][y] = 1;
|
||||
setObstacle(x,y);
|
||||
}
|
||||
void DynamicVoronoi::clearCell(int x, int y) {
|
||||
gridMap[x][y] = 0;
|
||||
removeObstacle(x,y);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::setObstacle(int x, int y) {
|
||||
dataCell c = data[x][y];
|
||||
if(isOccupied(x,y,c)) return;
|
||||
|
||||
addList.push_back(INTPOINT(x,y));
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
data[x][y] = c;
|
||||
}
|
||||
|
||||
void DynamicVoronoi::removeObstacle(int x, int y) {
|
||||
dataCell c = data[x][y];
|
||||
if(isOccupied(x,y,c) == false) return;
|
||||
|
||||
removeList.push_back(INTPOINT(x,y));
|
||||
c.obstX = invalidObstData;
|
||||
c.obstY = invalidObstData;
|
||||
c.queueing = bwQueued;
|
||||
data[x][y] = c;
|
||||
}
|
||||
|
||||
void DynamicVoronoi::exchangeObstacles(std::vector<INTPOINT>& points) {
|
||||
|
||||
for (unsigned int i=0; i<lastObstacles.size(); i++) {
|
||||
int x = lastObstacles[i].x;
|
||||
int y = lastObstacles[i].y;
|
||||
|
||||
bool v = gridMap[x][y];
|
||||
if (v) continue;
|
||||
removeObstacle(x,y);
|
||||
}
|
||||
|
||||
lastObstacles.clear();
|
||||
|
||||
for (unsigned int i=0; i<points.size(); i++) {
|
||||
int x = points[i].x;
|
||||
int y = points[i].y;
|
||||
bool v = gridMap[x][y];
|
||||
if (v) continue;
|
||||
setObstacle(x,y);
|
||||
lastObstacles.push_back(points[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void DynamicVoronoi::update(bool updateRealDist) {
|
||||
|
||||
commitAndColorize(updateRealDist);
|
||||
|
||||
while (!open.empty()) {
|
||||
INTPOINT p = open.pop();
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if(c.queueing==fwProcessed) continue;
|
||||
|
||||
if (c.needsRaise) {
|
||||
// RAISE
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if (nc.obstX!=invalidObstData && !nc.needsRaise) {
|
||||
if(!isOccupied(nc.obstX,nc.obstY,data[nc.obstX][nc.obstY])) {
|
||||
open.push(nc.sqdist, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
nc.needsRaise = true;
|
||||
nc.obstX = invalidObstData;
|
||||
nc.obstY = invalidObstData;
|
||||
if (updateRealDist) nc.dist = INFINITY;
|
||||
nc.sqdist = INT_MAX;
|
||||
data[nx][ny] = nc;
|
||||
} else {
|
||||
if(nc.queueing != fwQueued){
|
||||
open.push(nc.sqdist, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
data[nx][ny] = nc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
c.needsRaise = false;
|
||||
c.queueing = bwProcessed;
|
||||
data[x][y] = c;
|
||||
}
|
||||
else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,data[c.obstX][c.obstY])) {
|
||||
|
||||
// LOWER
|
||||
c.queueing = fwProcessed;
|
||||
c.voronoi = occupied;
|
||||
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if(!nc.needsRaise) {
|
||||
int distx = nx-c.obstX;
|
||||
int disty = ny-c.obstY;
|
||||
int newSqDistance = distx*distx + disty*disty;
|
||||
bool overwrite = (newSqDistance < nc.sqdist);
|
||||
if(!overwrite && newSqDistance==nc.sqdist) {
|
||||
if (nc.obstX == invalidObstData || isOccupied(nc.obstX,nc.obstY,data[nc.obstX][nc.obstY])==false) overwrite = true;
|
||||
}
|
||||
if (overwrite) {
|
||||
open.push(newSqDistance, INTPOINT(nx,ny));
|
||||
nc.queueing = fwQueued;
|
||||
if (updateRealDist) {
|
||||
nc.dist = sqrt((double) newSqDistance);
|
||||
}
|
||||
nc.sqdist = newSqDistance;
|
||||
nc.obstX = c.obstX;
|
||||
nc.obstY = c.obstY;
|
||||
} else {
|
||||
checkVoro(x,y,nx,ny,c,nc);
|
||||
}
|
||||
data[nx][ny] = nc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
data[x][y] = c;
|
||||
}
|
||||
}
|
||||
|
||||
float DynamicVoronoi::getDistance( int x, int y ) const {
|
||||
if( (x>0) && (x<sizeX) && (y>0) && (y<sizeY)) return data[x][y].dist;
|
||||
else return -INFINITY;
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isVoronoi( int x, int y ) const {
|
||||
dataCell c = data[x][y];
|
||||
return (c.voronoi==free || c.voronoi==voronoiKeep);
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isVoronoiAlternative(int x, int y) const {
|
||||
int v = alternativeDiagram[x][y];
|
||||
return (v == free || v == voronoiKeep);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::commitAndColorize(bool updateRealDist) {
|
||||
// ADD NEW OBSTACLES
|
||||
for (unsigned int i=0; i<addList.size(); i++) {
|
||||
INTPOINT p = addList[i];
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if(c.queueing != fwQueued){
|
||||
if (updateRealDist) c.dist = 0;
|
||||
c.sqdist = 0;
|
||||
c.obstX = x;
|
||||
c.obstY = y;
|
||||
c.queueing = fwQueued;
|
||||
c.voronoi = occupied;
|
||||
data[x][y] = c;
|
||||
open.push(0, INTPOINT(x,y));
|
||||
}
|
||||
}
|
||||
|
||||
// REMOVE OLD OBSTACLES
|
||||
for (unsigned int i=0; i<removeList.size(); i++) {
|
||||
INTPOINT p = removeList[i];
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
dataCell c = data[x][y];
|
||||
|
||||
if (isOccupied(x,y,c)==true) continue; // obstacle was removed and reinserted
|
||||
open.push(0, INTPOINT(x,y));
|
||||
if (updateRealDist) c.dist = INFINITY;
|
||||
c.sqdist = INT_MAX;
|
||||
c.needsRaise = true;
|
||||
data[x][y] = c;
|
||||
}
|
||||
removeList.clear();
|
||||
addList.clear();
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::checkVoro(int x, int y, int nx, int ny, dataCell& c, dataCell& nc) {
|
||||
|
||||
if ((c.sqdist>1 || nc.sqdist>1) && nc.obstX!=invalidObstData) {
|
||||
if (abs(c.obstX-nc.obstX) > 1 || abs(c.obstY-nc.obstY) > 1) {
|
||||
//compute dist from x,y to obstacle of nx,ny
|
||||
int dxy_x = x-nc.obstX;
|
||||
int dxy_y = y-nc.obstY;
|
||||
int sqdxy = dxy_x*dxy_x + dxy_y*dxy_y;
|
||||
int stability_xy = sqdxy - c.sqdist;
|
||||
if (sqdxy - c.sqdist<0) return;
|
||||
|
||||
//compute dist from nx,ny to obstacle of x,y
|
||||
int dnxy_x = nx - c.obstX;
|
||||
int dnxy_y = ny - c.obstY;
|
||||
int sqdnxy = dnxy_x*dnxy_x + dnxy_y*dnxy_y;
|
||||
int stability_nxy = sqdnxy - nc.sqdist;
|
||||
if (sqdnxy - nc.sqdist <0) return;
|
||||
|
||||
//which cell is added to the Voronoi diagram?
|
||||
if(stability_xy <= stability_nxy && c.sqdist>2) {
|
||||
if (c.voronoi != free) {
|
||||
c.voronoi = free;
|
||||
reviveVoroNeighbors(x,y);
|
||||
pruneQueue.push(INTPOINT(x,y));
|
||||
}
|
||||
}
|
||||
if(stability_nxy <= stability_xy && nc.sqdist>2) {
|
||||
if (nc.voronoi != free) {
|
||||
nc.voronoi = free;
|
||||
reviveVoroNeighbors(nx,ny);
|
||||
pruneQueue.push(INTPOINT(nx,ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::reviveVoroNeighbors(int &x, int &y) {
|
||||
for (int dx=-1; dx<=1; dx++) {
|
||||
int nx = x+dx;
|
||||
if (nx<=0 || nx>=sizeX-1) continue;
|
||||
for (int dy=-1; dy<=1; dy++) {
|
||||
if (dx==0 && dy==0) continue;
|
||||
int ny = y+dy;
|
||||
if (ny<=0 || ny>=sizeY-1) continue;
|
||||
dataCell nc = data[nx][ny];
|
||||
if (nc.sqdist != INT_MAX && !nc.needsRaise && (nc.voronoi == voronoiKeep || nc.voronoi == voronoiPrune)) {
|
||||
nc.voronoi = free;
|
||||
data[nx][ny] = nc;
|
||||
pruneQueue.push(INTPOINT(nx,ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool DynamicVoronoi::isOccupied(int x, int y) const {
|
||||
dataCell c = data[x][y];
|
||||
return (c.obstX==x && c.obstY==y);
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::isOccupied(int &x, int &y, dataCell &c) {
|
||||
return (c.obstX==x && c.obstY==y);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::visualize(const char *filename) {
|
||||
// write ppm files
|
||||
|
||||
FILE* F = fopen(filename, "w");
|
||||
if (!F) {
|
||||
std::cerr << "could not open 'result.pgm' for writing!\n";
|
||||
return;
|
||||
}
|
||||
fprintf(F, "P6\n#\n");
|
||||
fprintf(F, "%d %d\n255\n", sizeX, sizeY);
|
||||
|
||||
for(int y = sizeY-1; y >=0; y--){
|
||||
for(int x = 0; x<sizeX; x++){
|
||||
unsigned char c = 0;
|
||||
if (alternativeDiagram!=NULL && (alternativeDiagram[x][y] == free || alternativeDiagram[x][y]==voronoiKeep)) {
|
||||
fputc( 255, F );
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
} else if(isVoronoi(x,y)){
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
fputc( 255, F );
|
||||
} else if (data[x][y].sqdist==0) {
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
fputc( 0, F );
|
||||
} else {
|
||||
float f = 80+(sqrt(data[x][y].sqdist)*10);
|
||||
if (f>255) f=255;
|
||||
if (f<0) f=0;
|
||||
c = (unsigned char)f;
|
||||
fputc( c, F );
|
||||
fputc( c, F );
|
||||
fputc( c, F );
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(F);
|
||||
}
|
||||
|
||||
|
||||
void DynamicVoronoi::prune() {
|
||||
// filler
|
||||
while(!pruneQueue.empty()) {
|
||||
INTPOINT p = pruneQueue.front();
|
||||
pruneQueue.pop();
|
||||
int x = p.x;
|
||||
int y = p.y;
|
||||
|
||||
if (data[x][y].voronoi==occupied) continue;
|
||||
if (data[x][y].voronoi==freeQueued) continue;
|
||||
|
||||
data[x][y].voronoi = freeQueued;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, p);
|
||||
|
||||
/* tl t tr
|
||||
l c r
|
||||
bl b br */
|
||||
|
||||
dataCell tr,tl,br,bl;
|
||||
tr = data[x+1][y+1];
|
||||
tl = data[x-1][y+1];
|
||||
br = data[x+1][y-1];
|
||||
bl = data[x-1][y-1];
|
||||
|
||||
dataCell r,b,t,l;
|
||||
r = data[x+1][y];
|
||||
l = data[x-1][y];
|
||||
t = data[x][y+1];
|
||||
b = data[x][y-1];
|
||||
|
||||
if (x+2<sizeX && r.voronoi==occupied) {
|
||||
// fill to the right
|
||||
if (tr.voronoi!=occupied && br.voronoi!=occupied && data[x+2][y].voronoi!=occupied) {
|
||||
r.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(r.sqdist, INTPOINT(x+1,y));
|
||||
data[x+1][y] = r;
|
||||
}
|
||||
}
|
||||
if (x-2>=0 && l.voronoi==occupied) {
|
||||
// fill to the left
|
||||
if (tl.voronoi!=occupied && bl.voronoi!=occupied && data[x-2][y].voronoi!=occupied) {
|
||||
l.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(l.sqdist, INTPOINT(x-1,y));
|
||||
data[x-1][y] = l;
|
||||
}
|
||||
}
|
||||
if (y+2<sizeY && t.voronoi==occupied) {
|
||||
// fill to the top
|
||||
if (tr.voronoi!=occupied && tl.voronoi!=occupied && data[x][y+2].voronoi!=occupied) {
|
||||
t.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(t.sqdist, INTPOINT(x,y+1));
|
||||
data[x][y+1] = t;
|
||||
}
|
||||
}
|
||||
if (y-2>=0 && b.voronoi==occupied) {
|
||||
// fill to the bottom
|
||||
if (br.voronoi!=occupied && bl.voronoi!=occupied && data[x][y-2].voronoi!=occupied) {
|
||||
b.voronoi = freeQueued;
|
||||
sortedPruneQueue.push(b.sqdist, INTPOINT(x,y-1));
|
||||
data[x][y-1] = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while(!sortedPruneQueue.empty()) {
|
||||
INTPOINT p = sortedPruneQueue.pop();
|
||||
dataCell c = data[p.x][p.y];
|
||||
int v = c.voronoi;
|
||||
if (v!=freeQueued && v!=voronoiRetry) { // || v>free || v==voronoiPrune || v==voronoiKeep) {
|
||||
// assert(v!=retry);
|
||||
continue;
|
||||
}
|
||||
|
||||
markerMatchResult r = markerMatch(p.x,p.y);
|
||||
if (r==pruned) c.voronoi = voronoiPrune;
|
||||
else if (r==keep) c.voronoi = voronoiKeep;
|
||||
else { // r==retry
|
||||
c.voronoi = voronoiRetry;
|
||||
// printf("RETRY %d %d\n", x, sizeY-1-y);
|
||||
pruneQueue.push(p);
|
||||
}
|
||||
data[p.x][p.y] = c;
|
||||
|
||||
if (sortedPruneQueue.empty()) {
|
||||
while (!pruneQueue.empty()) {
|
||||
INTPOINT p = pruneQueue.front();
|
||||
pruneQueue.pop();
|
||||
sortedPruneQueue.push(data[p.x][p.y].sqdist, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
// printf("match: %d\nnomat: %d\n", matchCount, noMatchCount);
|
||||
}
|
||||
|
||||
void DynamicVoronoi::updateAlternativePrunedDiagram() {
|
||||
|
||||
if(alternativeDiagram==NULL){
|
||||
alternativeDiagram = new int*[sizeX];
|
||||
for(int x=0; x<sizeX; x++){
|
||||
alternativeDiagram[x] = new int[sizeY];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
std::queue<INTPOINT> end_cells;
|
||||
BucketPrioQueue<INTPOINT> sortedPruneQueue;
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
dataCell& c = data[x][y];
|
||||
alternativeDiagram[x][y] = c.voronoi;
|
||||
if(c.voronoi <=free){
|
||||
sortedPruneQueue.push(c.sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
if( getNumVoronoiNeighborsAlternative(x, y) >= 3){
|
||||
alternativeDiagram[x][y] = voronoiKeep;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(int x=1; x<sizeX-1; x++){
|
||||
for(int y=1; y<sizeY-1; y++){
|
||||
if( getNumVoronoiNeighborsAlternative(x, y) >= 3){
|
||||
alternativeDiagram[x][y] = voronoiKeep;
|
||||
sortedPruneQueue.push(data[x][y].sqdist, INTPOINT(x,y));
|
||||
end_cells.push(INTPOINT(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while (!sortedPruneQueue.empty()) {
|
||||
INTPOINT p = sortedPruneQueue.pop();
|
||||
|
||||
if (markerMatchAlternative(p.x, p.y)) {
|
||||
alternativeDiagram[p.x][p.y]=voronoiPrune;
|
||||
} else {
|
||||
alternativeDiagram[p.x][p.y]=voronoiKeep;
|
||||
}
|
||||
}
|
||||
|
||||
// //delete worms
|
||||
while (!end_cells.empty()) {
|
||||
INTPOINT p = end_cells.front();
|
||||
end_cells.pop();
|
||||
|
||||
if (isVoronoiAlternative(p.x,p.y) && getNumVoronoiNeighborsAlternative(p.x, p.y) == 1) {
|
||||
alternativeDiagram[p.x][p.y] = voronoiPrune;
|
||||
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
if (!(dx || dy) || (dx && dy)) {
|
||||
continue;
|
||||
}
|
||||
int nx = p.x + dx;
|
||||
int ny = p.y + dy;
|
||||
if (nx < 0 || nx >= sizeX || ny < 0 || ny >= sizeY) {
|
||||
continue;
|
||||
}
|
||||
if (isVoronoiAlternative(nx,ny)) {
|
||||
if (getNumVoronoiNeighborsAlternative(nx, ny) == 1) {
|
||||
end_cells.push(INTPOINT(nx, ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool DynamicVoronoi::markerMatchAlternative(int x, int y) {
|
||||
// prune if this returns true
|
||||
|
||||
bool f[8];
|
||||
|
||||
int nx, ny;
|
||||
int dx, dy;
|
||||
|
||||
int i = 0;
|
||||
// int obstacleCount=0;
|
||||
int voroCount = 0;
|
||||
for (dy = 1; dy >= -1; dy--) {
|
||||
ny = y + dy;
|
||||
for (dx = -1; dx <= 1; dx++) {
|
||||
if (dx || dy) {
|
||||
nx = x + dx;
|
||||
int v = alternativeDiagram[nx][ny];
|
||||
bool b = (v <= free && v != voronoiPrune);
|
||||
// if (v==occupied) obstacleCount++;
|
||||
f[i] = b;
|
||||
if (v <= free && !(dx && dy))
|
||||
voroCount++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 5 6 7
|
||||
* 3 4
|
||||
* 0 1 2
|
||||
*/
|
||||
|
||||
{
|
||||
//connected horizontal or vertically to only one cell
|
||||
if (voroCount == 1 && (f[1] || f[3] || f[4] || f[6])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 4-connected
|
||||
if ((!f[0] && f[1] && f[3]) || (!f[2] && f[1] && f[4]) || (!f[5] && f[3] && f[6]) || (!f[7] && f[6] && f[4]))
|
||||
return false;
|
||||
|
||||
if ((f[3] && f[4] && !f[1] && !f[6]) || (f[1] && f[6] && !f[3] && !f[4]))
|
||||
return false;
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int DynamicVoronoi::getNumVoronoiNeighborsAlternative(int x, int y) const {
|
||||
int count = 0;
|
||||
for (int dx = -1; dx <= 1; dx++) {
|
||||
for (int dy = -1; dy <= 1; dy++) {
|
||||
if ((dx == 0 && dy == 0) || (dx != 0 && dy != 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int nx = x + dx;
|
||||
int ny = y + dy;
|
||||
if (nx < 0 || nx >= sizeX || ny < 0 || ny >= sizeY) {
|
||||
continue;
|
||||
}
|
||||
if (alternativeDiagram[nx][ny]==free || alternativeDiagram[nx][ny]==voronoiKeep) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
DynamicVoronoi::markerMatchResult DynamicVoronoi::markerMatch(int x, int y) {
|
||||
// implementation of connectivity patterns
|
||||
bool f[8];
|
||||
|
||||
int nx, ny;
|
||||
int dx, dy;
|
||||
|
||||
int i=0;
|
||||
int count=0;
|
||||
// int obstacleCount=0;
|
||||
int voroCount=0;
|
||||
int voroCountFour=0;
|
||||
|
||||
for (dy=1; dy>=-1; dy--) {
|
||||
ny = y+dy;
|
||||
for (dx=-1; dx<=1; dx++) {
|
||||
if (dx || dy) {
|
||||
nx = x+dx;
|
||||
dataCell nc = data[nx][ny];
|
||||
int v = nc.voronoi;
|
||||
bool b = (v<=free && v!=voronoiPrune);
|
||||
// if (v==occupied) obstacleCount++;
|
||||
f[i] = b;
|
||||
if (b) {
|
||||
voroCount++;
|
||||
if (!(dx && dy)) voroCountFour++;
|
||||
}
|
||||
if (b && !(dx && dy) ) count++;
|
||||
// if (v<=free && !(dx && dy)) voroCount++;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (voroCount<3 && voroCountFour==1 && (f[1] || f[3] || f[4] || f[6])) {
|
||||
// assert(voroCount<2);
|
||||
// if (voroCount>=2) printf("voro>2 %d %d\n", x, y);
|
||||
return keep;
|
||||
}
|
||||
|
||||
// 4-connected
|
||||
if ((!f[0] && f[1] && f[3]) || (!f[2] && f[1] && f[4]) || (!f[5] && f[3] && f[6]) || (!f[7] && f[6] && f[4])) return keep;
|
||||
if ((f[3] && f[4] && !f[1] && !f[6]) || (f[1] && f[6] && !f[3] && !f[4])) return keep;
|
||||
|
||||
|
||||
|
||||
// keep voro cells inside of blocks and retry later
|
||||
if (voroCount>=5 && voroCountFour>=3 && data[x][y].voronoi!=voronoiRetry) {
|
||||
return retry;
|
||||
}
|
||||
|
||||
return pruned;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
211
src/map_convert.cpp
Normal file
211
src/map_convert.cpp
Normal file
@@ -0,0 +1,211 @@
|
||||
#include "voronoi_route/map_convert.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
CostClass classifyGridValue(int value, const StaticLayerRule& rule)
|
||||
{
|
||||
// Mirror of StaticLayer::interpretValue(), branch for branch.
|
||||
if (value == rule.unknown_cost_value)
|
||||
return rule.track_unknown_space ? CostClass::kNoInformation : CostClass::kFree;
|
||||
if (value >= rule.lethal_cost_threshold) return CostClass::kLethal;
|
||||
if (rule.trinary_costmap) return CostClass::kFree;
|
||||
return CostClass::kScaled;
|
||||
}
|
||||
|
||||
bool isObstacleClass(CostClass c, const ObstacleRule& rule)
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case CostClass::kLethal:
|
||||
return true;
|
||||
case CostClass::kNoInformation:
|
||||
return rule.unknown == UnknownPolicy::kObstacle;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
inline void count(CostClass c, MapConvertStats& st)
|
||||
{
|
||||
if (c == CostClass::kLethal) ++st.occupied;
|
||||
else if (c == CostClass::kNoInformation) ++st.unknown;
|
||||
else ++st.free;
|
||||
}
|
||||
|
||||
// map_server image_loader.cpp, trinary mode: average of every channel (alpha included), in double.
|
||||
inline int mapServerValue(const uint8_t* px, int channels, const MapServerThresholds& t)
|
||||
{
|
||||
int sum = 0;
|
||||
for (int k = 0; k < channels; ++k) sum += px[k];
|
||||
double avg = sum / static_cast<double>(channels);
|
||||
if (t.negate) avg = 255.0 - avg;
|
||||
const double occ = (255.0 - avg) / 255.0;
|
||||
if (occ > t.occupied_thresh) return 100;
|
||||
if (occ < t.free_thresh) return 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<uint8_t> occupancyFromImage(const uint8_t* pixels, int width, int height, int channels,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (pixels == nullptr || width <= 0 || height <= 0 || channels <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
MapConvertStats st;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const uint8_t* row = pixels + static_cast<size_t>(y) * width * channels;
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const CostClass c =
|
||||
classifyGridValue(mapServerValue(row + static_cast<size_t>(x) * channels, channels, thresholds),
|
||||
rule.layer);
|
||||
count(c, st);
|
||||
orow[x] = isObstacleClass(c, rule) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (stats) *stats = st;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromGray(const uint8_t* gray, int width, int height,
|
||||
const MapServerThresholds& thresholds,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
return occupancyFromImage(gray, width, height, 1, thresholds, rule, stats);
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromGrid(const int8_t* data, int width, int height,
|
||||
const ObstacleRule& rule, MapConvertStats* stats)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (data == nullptr || width <= 0 || height <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
MapConvertStats st;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const int8_t* row = data + static_cast<size_t>(height - 1 - y) * width; // ROS: row 0 = bottom
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const CostClass c = classifyGridValue(row[x], rule.layer);
|
||||
count(c, st);
|
||||
orow[x] = isObstacleClass(c, rule) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (stats) *stats = st;
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> occupancyFromCostmap(const unsigned char* charmap, int width, int height,
|
||||
UnknownPolicy unknown, bool rows_bottom_up)
|
||||
{
|
||||
std::vector<uint8_t> out;
|
||||
if (charmap == nullptr || width <= 0 || height <= 0) return out;
|
||||
out.assign(static_cast<size_t>(width) * height, 0);
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const int src_row = rows_bottom_up ? height - 1 - y : y;
|
||||
const unsigned char* row = charmap + static_cast<size_t>(src_row) * width;
|
||||
uint8_t* orow = out.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
const unsigned char v = row[x];
|
||||
orow[x] = (v == kCostmapLethalObstacle ||
|
||||
(v == kCostmapNoInformation && unknown == UnknownPolicy::kObstacle))
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
size_t applyObstacleRoi(std::vector<uint8_t>& mask, int width, int height, int margin_cells,
|
||||
size_t min_obstacle_cells)
|
||||
{
|
||||
if (margin_cells < 0 || width <= 0 || height <= 0 ||
|
||||
mask.size() != static_cast<size_t>(width) * height)
|
||||
return 0;
|
||||
int x0 = width, y0 = height, x1 = -1, y1 = -1;
|
||||
size_t n_obs = 0;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
const uint8_t* row = mask.data() + static_cast<size_t>(y) * width;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
if (!row[x]) continue;
|
||||
++n_obs;
|
||||
if (x < x0) x0 = x;
|
||||
if (x > x1) x1 = x;
|
||||
if (y < y0) y0 = y;
|
||||
if (y > y1) y1 = y;
|
||||
}
|
||||
}
|
||||
if (n_obs < min_obstacle_cells) return 0;
|
||||
x0 = x0 - margin_cells < 0 ? 0 : x0 - margin_cells;
|
||||
y0 = y0 - margin_cells < 0 ? 0 : y0 - margin_cells;
|
||||
x1 = x1 + margin_cells >= width ? width - 1 : x1 + margin_cells;
|
||||
y1 = y1 + margin_cells >= height ? height - 1 : y1 + margin_cells;
|
||||
size_t turned = 0;
|
||||
for (int y = 0; y < height; ++y)
|
||||
{
|
||||
uint8_t* row = mask.data() + static_cast<size_t>(y) * width;
|
||||
const bool row_out = y < y0 || y > y1;
|
||||
for (int x = 0; x < width; ++x)
|
||||
{
|
||||
if (row[x]) continue;
|
||||
if (row_out || x < x0 || x > x1)
|
||||
{
|
||||
row[x] = 1;
|
||||
++turned;
|
||||
}
|
||||
}
|
||||
}
|
||||
return turned;
|
||||
}
|
||||
|
||||
std::string obstacleRuleString(const ObstacleRule& rule)
|
||||
{
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof(buf),
|
||||
"lethal>=%d;unknown_value=%d;track_unknown=%d;trinary=%d;unknown=%s;roi=%d",
|
||||
rule.layer.lethal_cost_threshold, rule.layer.unknown_cost_value,
|
||||
rule.layer.track_unknown_space ? 1 : 0, rule.layer.trinary_costmap ? 1 : 0,
|
||||
rule.unknown == UnknownPolicy::kObstacle ? "obstacle" : "traversable",
|
||||
rule.roi_margin_cells);
|
||||
return buf;
|
||||
}
|
||||
|
||||
bool parseObstacleRuleString(const std::string& s, ObstacleRule* rule)
|
||||
{
|
||||
int lethal = 0, unk = 0, track = 0, trin = 0, roi = -1;
|
||||
char pol[16] = {0};
|
||||
if (std::sscanf(s.c_str(),
|
||||
"lethal>=%d;unknown_value=%d;track_unknown=%d;trinary=%d;unknown=%15[a-z];roi=%d",
|
||||
&lethal, &unk, &track, &trin, pol, &roi) != 6)
|
||||
return false;
|
||||
if (std::strcmp(pol, "obstacle") != 0 && std::strcmp(pol, "traversable") != 0) return false;
|
||||
if (rule)
|
||||
{
|
||||
rule->layer.lethal_cost_threshold = lethal;
|
||||
rule->layer.unknown_cost_value = unk;
|
||||
rule->layer.track_unknown_space = track != 0;
|
||||
rule->layer.trinary_costmap = trin != 0;
|
||||
rule->unknown = std::strcmp(pol, "obstacle") == 0 ? UnknownPolicy::kObstacle
|
||||
: UnknownPolicy::kTraversable;
|
||||
rule->roi_margin_cells = roi;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
93
src/params.cpp
Normal file
93
src/params.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
#include "voronoi_route/params.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
double cellsOf(double metres, double resolution_m)
|
||||
{
|
||||
return resolution_m > 0.0 ? metres / resolution_m : 0.0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
VoronoiRoute::Config RouteParams::toConfig(double resolution_m) const
|
||||
{
|
||||
VoronoiRoute::Config c;
|
||||
c.min_edge_length_cells = cellsOf(min_edge_length_m, resolution_m);
|
||||
c.spur_clearance_ratio = spur_clearance_ratio;
|
||||
c.min_component_length_cells = cellsOf(min_component_length_m, resolution_m);
|
||||
c.min_clearance_cells = cellsOf(min_clearance_m, resolution_m);
|
||||
c.attach_max_radius_cells = static_cast<int>(std::lround(cellsOf(attach_max_radius_m, resolution_m)));
|
||||
c.graph_rebuild_min_changed_cells = static_cast<size_t>(std::max(0, graph_rebuild_min_changed_cells));
|
||||
c.full_rebuild_fraction = full_rebuild_fraction;
|
||||
return c;
|
||||
}
|
||||
|
||||
CorridorParams RouteParams::toCorridor(double resolution_m) const
|
||||
{
|
||||
CorridorParams p;
|
||||
p.half_width_min_cells = cellsOf(half_width_min_m, resolution_m);
|
||||
p.clearance_scale = clearance_scale;
|
||||
p.half_width_max_cells = cellsOf(half_width_max_m, resolution_m);
|
||||
return p;
|
||||
}
|
||||
|
||||
ObstacleRule RouteParams::toObstacleRule(double resolution_m) const
|
||||
{
|
||||
ObstacleRule rule;
|
||||
rule.layer.track_unknown_space = track_unknown_space;
|
||||
rule.layer.lethal_cost_threshold = lethal_cost_threshold;
|
||||
rule.layer.unknown_cost_value = unknown_cost_value;
|
||||
rule.layer.trinary_costmap = trinary_costmap;
|
||||
rule.unknown = unknown_is_obstacle ? UnknownPolicy::kObstacle : UnknownPolicy::kTraversable;
|
||||
rule.roi_margin_cells =
|
||||
roi_margin_m < 0.0 ? -1 : static_cast<int>(std::lround(roi_margin_m / resolution_m));
|
||||
return rule;
|
||||
}
|
||||
|
||||
std::vector<std::string> validateRouteParams(RouteParams* p)
|
||||
{
|
||||
std::vector<std::string> out;
|
||||
if (!p) return out;
|
||||
auto fix = [&out](const char* key, double& v, double lo, double hi, double dflt) {
|
||||
if (std::isfinite(v) && v >= lo && v <= hi) return;
|
||||
out.push_back(std::string(key) + " out of range, using " + std::to_string(dflt));
|
||||
v = dflt;
|
||||
};
|
||||
fix("graph.min_edge_length_m", p->min_edge_length_m, 0.0, 100.0, 0.3);
|
||||
fix("graph.spur_clearance_ratio", p->spur_clearance_ratio, 0.0, 10.0, 1.2);
|
||||
fix("graph.min_component_length_m", p->min_component_length_m, 0.0, 1000.0, 2.0);
|
||||
fix("graph.min_clearance_m", p->min_clearance_m, 0.0, 10.0, 0.3);
|
||||
fix("graph.attach_max_radius_m", p->attach_max_radius_m, 0.1, 1000.0, 10.0);
|
||||
fix("graph.full_rebuild_fraction", p->full_rebuild_fraction, 0.0, 1.0, 0.02);
|
||||
if (p->graph_rebuild_min_changed_cells < 0)
|
||||
{
|
||||
out.push_back("graph.graph_rebuild_min_changed_cells negative, using 200");
|
||||
p->graph_rebuild_min_changed_cells = 200;
|
||||
}
|
||||
fix("corridor.half_width_min_m", p->half_width_min_m, 0.05, 100.0, 1.5);
|
||||
fix("corridor.clearance_scale", p->clearance_scale, 0.0, 10.0, 0.8);
|
||||
fix("corridor.half_width_max_m", p->half_width_max_m, 0.05, 1000.0, 6.0);
|
||||
if (p->half_width_max_m < p->half_width_min_m)
|
||||
{
|
||||
out.push_back("corridor.half_width_max_m < half_width_min_m, raising max to min");
|
||||
p->half_width_max_m = p->half_width_min_m;
|
||||
}
|
||||
if (!std::isfinite(p->roi_margin_m) || p->roi_margin_m > 1000.0)
|
||||
{
|
||||
out.push_back("obstacle.roi_margin_m out of range, using 0.5");
|
||||
p->roi_margin_m = 0.5;
|
||||
}
|
||||
if (p->lethal_cost_threshold < 0 || p->lethal_cost_threshold > 255)
|
||||
{
|
||||
out.push_back("obstacle.lethal_cost_threshold out of range, using 100");
|
||||
p->lethal_cost_threshold = 100;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
101
src/params_io.cpp
Normal file
101
src/params_io.cpp
Normal file
@@ -0,0 +1,101 @@
|
||||
#include "voronoi_route/params_io.h"
|
||||
|
||||
#include <filesystem>
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
std::string findConfigFile(const std::string& dir, const std::string& name)
|
||||
{
|
||||
std::error_code ec;
|
||||
if (dir.empty() || !std::filesystem::is_directory(dir, ec)) return "";
|
||||
for (const auto& e : std::filesystem::recursive_directory_iterator(dir, ec))
|
||||
if (e.is_regular_file(ec) && e.path().filename() == name) return e.path().string();
|
||||
return "";
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
template <class T>
|
||||
void take(const YAML::Node& n, const char* section, const char* key, T& out,
|
||||
std::vector<std::string>* notes)
|
||||
{
|
||||
const YAML::Node s = n[section];
|
||||
if (s && s[key])
|
||||
{
|
||||
try
|
||||
{
|
||||
out = s[key].as<T>();
|
||||
return;
|
||||
}
|
||||
catch (const std::exception&)
|
||||
{
|
||||
if (notes) notes->push_back(std::string(section) + "." + key + ": bad value, using default");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (notes) notes->push_back(std::string(section) + "." + key + ": missing, using default");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool loadRouteParams(const std::string& yaml_path, RouteParams* params, std::string* err,
|
||||
std::vector<std::string>* notes)
|
||||
{
|
||||
if (!params) return false;
|
||||
YAML::Node root;
|
||||
try
|
||||
{
|
||||
root = YAML::LoadFile(yaml_path);
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
if (err) *err = std::string(yaml_path) + ": " + e.what();
|
||||
return false;
|
||||
}
|
||||
const YAML::Node n = root["voronoi_route"];
|
||||
if (!n)
|
||||
{
|
||||
if (err) *err = yaml_path + ": no `voronoi_route` root key";
|
||||
return false;
|
||||
}
|
||||
RouteParams& p = *params;
|
||||
take(n, "graph", "min_edge_length_m", p.min_edge_length_m, notes);
|
||||
take(n, "graph", "spur_clearance_ratio", p.spur_clearance_ratio, notes);
|
||||
take(n, "graph", "min_component_length_m", p.min_component_length_m, notes);
|
||||
take(n, "graph", "min_clearance_m", p.min_clearance_m, notes);
|
||||
take(n, "graph", "attach_max_radius_m", p.attach_max_radius_m, notes);
|
||||
take(n, "graph", "graph_rebuild_min_changed_cells", p.graph_rebuild_min_changed_cells, notes);
|
||||
take(n, "graph", "full_rebuild_fraction", p.full_rebuild_fraction, notes);
|
||||
take(n, "corridor", "half_width_min_m", p.half_width_min_m, notes);
|
||||
take(n, "corridor", "clearance_scale", p.clearance_scale, notes);
|
||||
take(n, "corridor", "half_width_max_m", p.half_width_max_m, notes);
|
||||
take(n, "bundle", "write_gvd", p.write_gvd, notes);
|
||||
take(n, "bundle", "write_dist", p.write_dist, notes);
|
||||
take(n, "bundle", "write_preview", p.write_preview, notes);
|
||||
take(n, "bundle", "write_graph_image", p.write_graph_image, notes);
|
||||
take(n, "bundle", "write_graph_overlay", p.write_graph_overlay, notes);
|
||||
|
||||
take(n, "obstacle", "track_unknown_space", p.track_unknown_space, notes);
|
||||
take(n, "obstacle", "lethal_cost_threshold", p.lethal_cost_threshold, notes);
|
||||
take(n, "obstacle", "unknown_cost_value", p.unknown_cost_value, notes);
|
||||
take(n, "obstacle", "trinary_costmap", p.trinary_costmap, notes);
|
||||
take(n, "obstacle", "roi_margin_m", p.roi_margin_m, notes);
|
||||
|
||||
std::string unknown = "traversable";
|
||||
take(n, "obstacle", "unknown", unknown, notes);
|
||||
if (unknown == "traversable") p.unknown_is_obstacle = false;
|
||||
else if (unknown == "obstacle") p.unknown_is_obstacle = true;
|
||||
else
|
||||
{
|
||||
if (notes) notes->push_back("obstacle.unknown: '" + unknown + "' unknown, using traversable");
|
||||
p.unknown_is_obstacle = false;
|
||||
}
|
||||
|
||||
for (const std::string& w : validateRouteParams(&p))
|
||||
if (notes) notes->push_back(w);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
107
src/voronoi_field.cpp
Normal file
107
src/voronoi_field.cpp
Normal file
@@ -0,0 +1,107 @@
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "voronoi_route/dynamic_voronoi.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
VoronoiField::VoronoiField() = default;
|
||||
VoronoiField::~VoronoiField() = default;
|
||||
|
||||
void VoronoiField::rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
ready_ = false;
|
||||
if (size_x <= 0 || size_y <= 0 || occupied.size() != static_cast<size_t>(size_x) * size_y)
|
||||
{
|
||||
size_x_ = size_y_ = 0;
|
||||
return;
|
||||
}
|
||||
size_x_ = size_x;
|
||||
size_y_ = size_y;
|
||||
occupancy_ = occupied;
|
||||
|
||||
// DynamicVoronoi keeps the bool** it is given and writes into it on occupy/clear, so the
|
||||
// storage has to outlive it and stay put. Column-major because it indexes data[x][y].
|
||||
columns_.clear();
|
||||
columns_.reserve(size_x_);
|
||||
column_ptrs_.assign(size_x_, nullptr);
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
columns_.emplace_back(new bool[size_y_]);
|
||||
bool* col = columns_.back().get();
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
col[y] = occupancy_[static_cast<size_t>(y) * size_x_ + x] != 0;
|
||||
column_ptrs_[x] = col;
|
||||
}
|
||||
|
||||
dv_.reset(new DynamicVoronoi());
|
||||
dv_->initializeMap(size_x_, size_y_, column_ptrs_.data());
|
||||
dv_->update(true);
|
||||
dv_->prune();
|
||||
ready_ = true;
|
||||
}
|
||||
|
||||
void VoronoiField::setOccupied(const std::vector<Cell>& cells)
|
||||
{
|
||||
if (!ready_) return;
|
||||
for (const Cell& c : cells)
|
||||
{
|
||||
if (!inBounds(c.x, c.y)) continue;
|
||||
uint8_t& o = occupancy_[static_cast<size_t>(c.y) * size_x_ + c.x];
|
||||
if (o) continue;
|
||||
o = 1;
|
||||
dv_->occupyCell(c.x, c.y);
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiField::setFree(const std::vector<Cell>& cells)
|
||||
{
|
||||
if (!ready_) return;
|
||||
for (const Cell& c : cells)
|
||||
{
|
||||
if (!inBounds(c.x, c.y)) continue;
|
||||
uint8_t& o = occupancy_[static_cast<size_t>(c.y) * size_x_ + c.x];
|
||||
if (!o) continue;
|
||||
o = 0;
|
||||
dv_->clearCell(c.x, c.y);
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiField::refresh()
|
||||
{
|
||||
if (!ready_) return;
|
||||
dv_->update(true);
|
||||
dv_->prune();
|
||||
}
|
||||
|
||||
bool VoronoiField::isVoronoi(int x, int y) const
|
||||
{
|
||||
// DynamicVoronoi initialises every cell in state `free` (= "on the diagram") and its update
|
||||
// loops only touch neighbours inside [1, size-2], so the outer row/column is never processed
|
||||
// and stays flagged. It is not a ridge, it is untouched memory: the map frame is not GVD.
|
||||
if (!ready_ || x <= 0 || y <= 0 || x >= size_x_ - 1 || y >= size_y_ - 1) return false;
|
||||
return dv_->isVoronoi(x, y);
|
||||
}
|
||||
|
||||
bool VoronoiField::isOccupied(int x, int y) const
|
||||
{
|
||||
return ready_ && inBounds(x, y) && occupancy_[static_cast<size_t>(y) * size_x_ + x] != 0;
|
||||
}
|
||||
|
||||
float VoronoiField::distanceCells(int x, int y) const
|
||||
{
|
||||
if (!ready_ || !inBounds(x, y)) return 0.0f;
|
||||
if (isOccupied(x, y)) return 0.0f;
|
||||
// Port quirk: getDistance() treats x==0 / y==0 as out of range and returns -inf. Border cells
|
||||
// are next to the frame anyway; report them as touching an obstacle rather than leaking -inf
|
||||
// into a corridor width.
|
||||
const float d = dv_->getDistance(x, y);
|
||||
if (d < 0.0f) return 0.0f;
|
||||
// Cells no obstacle wave ever reached (a map with no obstacle at all) keep +inf; clamp to
|
||||
// "farther than the grid" so callers can still do arithmetic on it.
|
||||
if (!std::isfinite(d)) return static_cast<float>(size_x_ + size_y_);
|
||||
return d;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
681
src/voronoi_graph.cpp
Normal file
681
src/voronoi_graph.cpp
Normal file
@@ -0,0 +1,681 @@
|
||||
#include "voronoi_route/voronoi_graph.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <queue>
|
||||
#include <utility>
|
||||
|
||||
#include "voronoi_route/voronoi_field.h"
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kDx[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
|
||||
constexpr int kDy[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
|
||||
|
||||
inline float stepLength(const Cell& a, const Cell& b)
|
||||
{
|
||||
return (a.x != b.x && a.y != b.y) ? 1.41421356f : 1.0f;
|
||||
}
|
||||
|
||||
float chainLength(const Polyline& cells)
|
||||
{
|
||||
float len = 0.0f;
|
||||
for (size_t i = 1; i < cells.size(); ++i) len += stepLength(cells[i - 1], cells[i]);
|
||||
return len;
|
||||
}
|
||||
|
||||
// Number of 8-connected components among the GVD cells in the 3x3 ring around (x, y), ignoring
|
||||
// the centre. Two ring cells are joined when they touch (Chebyshev distance 1).
|
||||
int ringComponents(const std::vector<uint8_t>& is_gvd, int w, int h, int x, int y, int* count)
|
||||
{
|
||||
int rx[8], ry[8], n = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int nx = x + kDx[k], ny = y + kDy[k];
|
||||
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
|
||||
if (!is_gvd[static_cast<size_t>(ny) * w + nx]) continue;
|
||||
rx[n] = nx;
|
||||
ry[n] = ny;
|
||||
++n;
|
||||
}
|
||||
if (count) *count = n;
|
||||
int parent[8];
|
||||
for (int i = 0; i < n; ++i) parent[i] = i;
|
||||
auto find = [&](int a) { while (parent[a] != a) a = parent[a] = parent[parent[a]]; return a; };
|
||||
for (int i = 0; i < n; ++i)
|
||||
for (int j = i + 1; j < n; ++j)
|
||||
if (std::abs(rx[i] - rx[j]) <= 1 && std::abs(ry[i] - ry[j]) <= 1) parent[find(i)] = find(j);
|
||||
int comps = 0;
|
||||
for (int i = 0; i < n; ++i) comps += find(i) == i ? 1 : 0;
|
||||
return comps;
|
||||
}
|
||||
|
||||
// Lau's prune leaves 8-connected lines that are two cells thick on diagonals ("**" stairs); with
|
||||
// 8-neighbour degrees every such cell looks like a junction. Delete cells whose GVD neighbours
|
||||
// stay one 8-connected piece without them, but only when they have >= 3 neighbours: a cell with
|
||||
// two neighbours is line interior or a line tip, and deleting tips would eat a two-thick branch
|
||||
// from its end inward one cell at a time. Stair cells have 3-4 neighbours, so the stairs collapse
|
||||
// to a single diagonal while branch length and topology stay. Sequential in scan order, so it is
|
||||
// deterministic.
|
||||
void thinToSkeleton(std::vector<uint8_t>& is_gvd, int w, int h)
|
||||
{
|
||||
for (int pass = 0; pass < 32; ++pass)
|
||||
{
|
||||
bool changed = false;
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * w + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
int n = 0;
|
||||
const int comps = ringComponents(is_gvd, w, h, x, y, &n);
|
||||
if (n >= 3 && comps == 1)
|
||||
{
|
||||
is_gvd[i] = 0;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void VoronoiGraph::clear()
|
||||
{
|
||||
size_x_ = size_y_ = 0;
|
||||
nodes_.clear();
|
||||
edges_.clear();
|
||||
cell_edge_.clear();
|
||||
cell_index_.clear();
|
||||
}
|
||||
|
||||
void VoronoiGraph::extract(const VoronoiField& field, const ExtractParams& params)
|
||||
{
|
||||
clear();
|
||||
if (!field.ready()) return;
|
||||
size_x_ = field.sizeX();
|
||||
size_y_ = field.sizeY();
|
||||
const size_t n = static_cast<size_t>(size_x_) * size_y_;
|
||||
|
||||
std::vector<uint8_t> is_gvd(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
is_gvd[static_cast<size_t>(y) * size_x_ + x] = field.isVoronoi(x, y) ? 1 : 0;
|
||||
thinToSkeleton(is_gvd, size_x_, size_y_);
|
||||
|
||||
std::vector<int> degree(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * size_x_ + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
int d = 0;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int nx = x + kDx[k], ny = y + kDy[k];
|
||||
if (field.inBounds(nx, ny) && is_gvd[static_cast<size_t>(ny) * size_x_ + nx]) ++d;
|
||||
}
|
||||
degree[i] = d;
|
||||
}
|
||||
|
||||
// Nodes: junctions (>= 3) and dead ends (1). Isolated GVD pixels (0) are noise, dropped.
|
||||
std::vector<int> node_of_cell(n, -1);
|
||||
std::vector<uint8_t> visited(n, 0);
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = static_cast<size_t>(y) * size_x_ + x;
|
||||
if (!is_gvd[i]) continue;
|
||||
if (degree[i] == 0)
|
||||
{
|
||||
visited[i] = 1;
|
||||
continue;
|
||||
}
|
||||
if (degree[i] != 2)
|
||||
{
|
||||
node_of_cell[i] = static_cast<int>(nodes_.size());
|
||||
nodes_.push_back(GraphNode{Cell(x, y), {}});
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<RawEdge> raw;
|
||||
traceFromNodes(field, is_gvd, degree, node_of_cell, visited, raw);
|
||||
traceCycles(field, is_gvd, node_of_cell, visited, raw);
|
||||
|
||||
edges_.clear();
|
||||
edges_.reserve(raw.size());
|
||||
for (RawEdge& r : raw)
|
||||
{
|
||||
GraphEdge e;
|
||||
e.u = r.u;
|
||||
e.v = r.v;
|
||||
e.cells = std::move(r.cells);
|
||||
e.length_cells = chainLength(e.cells);
|
||||
float mn = std::numeric_limits<float>::max();
|
||||
for (const Cell& c : e.cells) mn = std::min(mn, field.distanceCells(c.x, c.y));
|
||||
e.min_clearance_cells = e.cells.empty() ? 0.0f : mn;
|
||||
edges_.push_back(std::move(e));
|
||||
}
|
||||
|
||||
pruneSpursAndMerge(field, params);
|
||||
if (params.min_component_length_cells > 0.0) dropSmallComponents(params.min_component_length_cells);
|
||||
finalize(field);
|
||||
}
|
||||
|
||||
void VoronoiGraph::traceFromNodes(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
const std::vector<int>& degree,
|
||||
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
|
||||
std::vector<RawEdge>& raw)
|
||||
{
|
||||
(void)degree;
|
||||
auto idx = [this](int x, int y) { return static_cast<size_t>(y) * size_x_ + x; };
|
||||
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
const Cell nc = nodes_[ni].cell;
|
||||
visited[idx(nc.x, nc.y)] = 1;
|
||||
for (int k = 0; k < 8; ++k)
|
||||
{
|
||||
const int sx = nc.x + kDx[k], sy = nc.y + kDy[k];
|
||||
if (!field.inBounds(sx, sy) || !is_gvd[idx(sx, sy)]) continue;
|
||||
const int other = node_of_cell[idx(sx, sy)];
|
||||
if (other >= 0)
|
||||
{
|
||||
// Two nodes touching: a zero-interior edge. Record once, from the lower index.
|
||||
if (static_cast<int>(ni) < other)
|
||||
raw.push_back(RawEdge{static_cast<int>(ni), other, {nc, Cell(sx, sy)}});
|
||||
continue;
|
||||
}
|
||||
if (visited[idx(sx, sy)]) continue; // chain already traced from its other end
|
||||
|
||||
Polyline chain{nc, Cell(sx, sy)};
|
||||
Cell prev = nc;
|
||||
Cell cur(sx, sy);
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
int end_node = -1;
|
||||
for (;;)
|
||||
{
|
||||
int next_node = -1;
|
||||
Cell next_free;
|
||||
bool have_free = false;
|
||||
for (int j = 0; j < 8; ++j)
|
||||
{
|
||||
const int nx = cur.x + kDx[j], ny = cur.y + kDy[j];
|
||||
if (!field.inBounds(nx, ny) || !is_gvd[idx(nx, ny)]) continue;
|
||||
if (nx == prev.x && ny == prev.y) continue;
|
||||
const int nn = node_of_cell[idx(nx, ny)];
|
||||
if (nn >= 0)
|
||||
{
|
||||
next_node = nn;
|
||||
break;
|
||||
}
|
||||
if (!visited[idx(nx, ny)] && !have_free)
|
||||
{
|
||||
next_free = Cell(nx, ny);
|
||||
have_free = true;
|
||||
}
|
||||
}
|
||||
if (next_node >= 0)
|
||||
{
|
||||
chain.push_back(nodes_[next_node].cell);
|
||||
end_node = next_node;
|
||||
break;
|
||||
}
|
||||
if (!have_free) break; // ran into already-visited territory: dangling, drop below
|
||||
prev = cur;
|
||||
cur = next_free;
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
chain.push_back(cur);
|
||||
}
|
||||
if (end_node >= 0) raw.push_back(RawEdge{static_cast<int>(ni), end_node, std::move(chain)});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiGraph::traceCycles(const VoronoiField& field, const std::vector<uint8_t>& is_gvd,
|
||||
std::vector<int>& node_of_cell, std::vector<uint8_t>& visited,
|
||||
std::vector<RawEdge>& raw)
|
||||
{
|
||||
auto idx = [this](int x, int y) { return static_cast<size_t>(y) * size_x_ + x; };
|
||||
for (int y = 0; y < size_y_; ++y)
|
||||
for (int x = 0; x < size_x_; ++x)
|
||||
{
|
||||
const size_t i = idx(x, y);
|
||||
if (!is_gvd[i] || visited[i]) continue;
|
||||
// Every unvisited GVD cell here has degree 2 and no node anywhere on its chain: a closed
|
||||
// ring. Make this cell a synthetic node and walk the ring back to it.
|
||||
const int ni = static_cast<int>(nodes_.size());
|
||||
nodes_.push_back(GraphNode{Cell(x, y), {}});
|
||||
node_of_cell[i] = ni;
|
||||
visited[i] = 1;
|
||||
|
||||
Polyline chain{Cell(x, y)};
|
||||
Cell prev(x, y);
|
||||
Cell cur(x, y);
|
||||
bool started = false;
|
||||
for (;;)
|
||||
{
|
||||
Cell next;
|
||||
bool found = false;
|
||||
for (int j = 0; j < 8; ++j)
|
||||
{
|
||||
const int nx = cur.x + kDx[j], ny = cur.y + kDy[j];
|
||||
if (!field.inBounds(nx, ny) || !is_gvd[idx(nx, ny)]) continue;
|
||||
if (started && nx == prev.x && ny == prev.y) continue;
|
||||
if (node_of_cell[idx(nx, ny)] == ni && started)
|
||||
{
|
||||
next = Cell(nx, ny);
|
||||
found = true;
|
||||
break; // closed the ring
|
||||
}
|
||||
if (!visited[idx(nx, ny)])
|
||||
{
|
||||
next = Cell(nx, ny);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) break;
|
||||
started = true;
|
||||
prev = cur;
|
||||
cur = next;
|
||||
chain.push_back(cur);
|
||||
if (node_of_cell[idx(cur.x, cur.y)] == ni) break;
|
||||
visited[idx(cur.x, cur.y)] = 1;
|
||||
}
|
||||
if (chain.size() >= 3 && chain.back() == chain.front())
|
||||
raw.push_back(RawEdge{ni, ni, std::move(chain)});
|
||||
}
|
||||
}
|
||||
|
||||
void VoronoiGraph::pruneSpursAndMerge(const VoronoiField& field, const ExtractParams& params)
|
||||
{
|
||||
const double min_edge_length_cells = params.min_edge_length_cells;
|
||||
auto clearanceAt = [&field](const Cell& c) { return static_cast<double>(field.distanceCells(c.x, c.y)); };
|
||||
std::vector<uint8_t> edge_alive(edges_.size(), 1);
|
||||
std::vector<uint8_t> node_alive(nodes_.size(), 1);
|
||||
|
||||
auto nodeDegree = [&](std::vector<int>& deg) {
|
||||
deg.assign(nodes_.size(), 0);
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
++deg[edges_[e].u];
|
||||
if (edges_[e].v != edges_[e].u) ++deg[edges_[e].v];
|
||||
}
|
||||
};
|
||||
|
||||
// 0a) Impassable edges go first; the rest of the loop then cleans up what they leave behind.
|
||||
if (params.min_clearance_cells > 0.0)
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
if (edges_[e].min_clearance_cells < params.min_clearance_cells) edge_alive[e] = 0;
|
||||
|
||||
for (int pass = 0; pass < 64; ++pass)
|
||||
{
|
||||
bool changed = false;
|
||||
std::vector<int> deg;
|
||||
nodeDegree(deg);
|
||||
|
||||
// 0) Junction clusters. Where the thinned GVD is still a small tangle (a triangle of three
|
||||
// cells at a fork, a tiny ring at a tip), the tangle shows up as short edges between
|
||||
// non-leaf nodes and short loops. Contract those edges into one node, splicing their cells
|
||||
// into the neighbouring edges so every chain stays 8-connected through the junction.
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
GraphEdge& ge = edges_[e];
|
||||
if (ge.length_cells >= min_edge_length_cells) continue;
|
||||
if (ge.u == ge.v)
|
||||
{
|
||||
edge_alive[e] = 0; // tiny loop: noise
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if (deg[ge.u] < 2 || deg[ge.v] < 2) continue; // leaf spurs handled below
|
||||
const int keep = std::min(ge.u, ge.v), drop = std::max(ge.u, ge.v);
|
||||
Polyline keep_to_drop = ge.cells; // oriented keep -> drop
|
||||
if (ge.u != keep) std::reverse(keep_to_drop.begin(), keep_to_drop.end());
|
||||
for (size_t f = 0; f < edges_.size(); ++f)
|
||||
{
|
||||
if (f == e || !edge_alive[f]) continue;
|
||||
GraphEdge& gf = edges_[f];
|
||||
if (gf.u == drop)
|
||||
{
|
||||
Polyline spliced = keep_to_drop;
|
||||
spliced.insert(spliced.end(), gf.cells.begin() + 1, gf.cells.end());
|
||||
gf.cells = std::move(spliced);
|
||||
gf.u = keep;
|
||||
}
|
||||
if (gf.v == drop)
|
||||
{
|
||||
gf.cells.insert(gf.cells.end(), keep_to_drop.rbegin() + 1, keep_to_drop.rend());
|
||||
gf.v = keep;
|
||||
}
|
||||
if (gf.u == drop || gf.v == drop) gf.length_cells = chainLength(gf.cells);
|
||||
else if (gf.u == keep && gf.v == keep) gf.length_cells = chainLength(gf.cells);
|
||||
}
|
||||
edge_alive[e] = 0;
|
||||
node_alive[drop] = 0;
|
||||
changed = true;
|
||||
nodeDegree(deg);
|
||||
}
|
||||
|
||||
// 1) Drop short dead-end branches.
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
const bool leaf_u = deg[ge.u] == 1, leaf_v = deg[ge.v] == 1;
|
||||
if (!leaf_u && !leaf_v) continue;
|
||||
bool drop = ge.length_cells < min_edge_length_cells;
|
||||
if (!drop && params.spur_clearance_ratio > 0.0 && leaf_u != leaf_v)
|
||||
{
|
||||
const Cell& root = leaf_u ? nodes_[ge.v].cell : nodes_[ge.u].cell;
|
||||
drop = ge.length_cells < params.spur_clearance_ratio * clearanceAt(root);
|
||||
}
|
||||
if (!drop) continue;
|
||||
edge_alive[e] = 0;
|
||||
changed = true;
|
||||
if (leaf_u) node_alive[ge.u] = 0;
|
||||
if (leaf_v) node_alive[ge.v] = 0;
|
||||
}
|
||||
if (changed) nodeDegree(deg);
|
||||
|
||||
// 2) A node left with exactly two distinct, non-loop edges is just a bend: merge them.
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
if (!node_alive[ni] || deg[ni] != 2) continue;
|
||||
int e1 = -1, e2 = -1;
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
if (ge.u == static_cast<int>(ni) || ge.v == static_cast<int>(ni))
|
||||
{
|
||||
if (e1 < 0) e1 = static_cast<int>(e);
|
||||
else if (e2 < 0) e2 = static_cast<int>(e);
|
||||
}
|
||||
}
|
||||
if (e1 < 0 || e2 < 0) continue; // one of them is a loop; leave the node
|
||||
GraphEdge& a = edges_[e1];
|
||||
GraphEdge& b = edges_[e2];
|
||||
// Orient a to end at ni, b to start at ni.
|
||||
if (a.u == static_cast<int>(ni))
|
||||
{
|
||||
std::reverse(a.cells.begin(), a.cells.end());
|
||||
std::swap(a.u, a.v);
|
||||
}
|
||||
if (b.v == static_cast<int>(ni))
|
||||
{
|
||||
std::reverse(b.cells.begin(), b.cells.end());
|
||||
std::swap(b.u, b.v);
|
||||
}
|
||||
GraphEdge merged;
|
||||
merged.u = a.u;
|
||||
merged.v = b.v;
|
||||
merged.cells = a.cells;
|
||||
merged.cells.insert(merged.cells.end(), b.cells.begin() + 1, b.cells.end());
|
||||
merged.length_cells = a.length_cells + b.length_cells;
|
||||
merged.min_clearance_cells = std::min(a.min_clearance_cells, b.min_clearance_cells);
|
||||
edge_alive[e1] = edge_alive[e2] = 0;
|
||||
node_alive[ni] = 0;
|
||||
edges_.push_back(std::move(merged));
|
||||
edge_alive.push_back(1);
|
||||
changed = true;
|
||||
nodeDegree(deg);
|
||||
}
|
||||
if (!changed) break;
|
||||
}
|
||||
|
||||
// Compact, remapping node indices.
|
||||
std::vector<int> remap(nodes_.size(), -1);
|
||||
std::vector<GraphNode> new_nodes;
|
||||
for (size_t ni = 0; ni < nodes_.size(); ++ni)
|
||||
{
|
||||
if (!node_alive[ni]) continue;
|
||||
remap[ni] = static_cast<int>(new_nodes.size());
|
||||
new_nodes.push_back(GraphNode{nodes_[ni].cell, {}});
|
||||
}
|
||||
std::vector<GraphEdge> new_edges;
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
if (!edge_alive[e]) continue;
|
||||
GraphEdge ge = std::move(edges_[e]);
|
||||
ge.u = remap[ge.u];
|
||||
ge.v = remap[ge.v];
|
||||
if (ge.u < 0 || ge.v < 0) continue;
|
||||
new_edges.push_back(std::move(ge));
|
||||
}
|
||||
nodes_ = std::move(new_nodes);
|
||||
edges_ = std::move(new_edges);
|
||||
}
|
||||
|
||||
void VoronoiGraph::dropSmallComponents(double min_total_length_cells)
|
||||
{
|
||||
std::vector<int> parent(nodes_.size());
|
||||
for (size_t i = 0; i < parent.size(); ++i) parent[i] = static_cast<int>(i);
|
||||
std::function<int(int)> find = [&](int a) { return parent[a] == a ? a : parent[a] = find(parent[a]); };
|
||||
for (const GraphEdge& e : edges_) parent[find(e.u)] = find(e.v);
|
||||
std::vector<double> total(nodes_.size(), 0.0);
|
||||
for (const GraphEdge& e : edges_) total[find(e.u)] += e.length_cells;
|
||||
|
||||
std::vector<int> remap(nodes_.size(), -1);
|
||||
std::vector<GraphNode> new_nodes;
|
||||
for (size_t i = 0; i < nodes_.size(); ++i)
|
||||
{
|
||||
if (total[find(static_cast<int>(i))] < min_total_length_cells) continue;
|
||||
remap[i] = static_cast<int>(new_nodes.size());
|
||||
new_nodes.push_back(GraphNode{nodes_[i].cell, {}});
|
||||
}
|
||||
std::vector<GraphEdge> new_edges;
|
||||
for (GraphEdge& e : edges_)
|
||||
{
|
||||
if (remap[e.u] < 0 || remap[e.v] < 0) continue;
|
||||
e.u = remap[e.u];
|
||||
e.v = remap[e.v];
|
||||
new_edges.push_back(std::move(e));
|
||||
}
|
||||
nodes_ = std::move(new_nodes);
|
||||
edges_ = std::move(new_edges);
|
||||
}
|
||||
|
||||
void VoronoiGraph::finalize(const VoronoiField& field)
|
||||
{
|
||||
// Deterministic order: sort edges by their first cell, then rebuild incidence lists.
|
||||
std::sort(edges_.begin(), edges_.end(), [](const GraphEdge& a, const GraphEdge& b) {
|
||||
const Cell& ca = a.cells.front();
|
||||
const Cell& cb = b.cells.front();
|
||||
return ca.y != cb.y ? ca.y < cb.y : ca.x < cb.x;
|
||||
});
|
||||
for (GraphNode& nd : nodes_) nd.edges.clear();
|
||||
|
||||
const size_t n = static_cast<size_t>(size_x_) * size_y_;
|
||||
cell_edge_.assign(n, -1);
|
||||
cell_index_.assign(n, -1);
|
||||
|
||||
for (size_t e = 0; e < edges_.size(); ++e)
|
||||
{
|
||||
GraphEdge& ge = edges_[e];
|
||||
ge.cum_cells.assign(ge.cells.size(), 0.0f);
|
||||
float mn = std::numeric_limits<float>::max();
|
||||
for (size_t i = 0; i < ge.cells.size(); ++i)
|
||||
{
|
||||
if (i > 0) ge.cum_cells[i] = ge.cum_cells[i - 1] + stepLength(ge.cells[i - 1], ge.cells[i]);
|
||||
mn = std::min(mn, field.distanceCells(ge.cells[i].x, ge.cells[i].y));
|
||||
const size_t ci = static_cast<size_t>(ge.cells[i].y) * size_x_ + ge.cells[i].x;
|
||||
if (cell_edge_[ci] < 0)
|
||||
{
|
||||
cell_edge_[ci] = static_cast<int32_t>(e);
|
||||
cell_index_[ci] = static_cast<int32_t>(i);
|
||||
}
|
||||
}
|
||||
ge.length_cells = ge.cells.empty() ? 0.0f : ge.cum_cells.back();
|
||||
ge.min_clearance_cells = ge.cells.empty() ? 0.0f : mn;
|
||||
nodes_[ge.u].edges.push_back(static_cast<int>(e));
|
||||
if (ge.v != ge.u) nodes_[ge.v].edges.push_back(static_cast<int>(e));
|
||||
}
|
||||
}
|
||||
|
||||
int VoronoiGraph::edgeAt(int x, int y) const
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= size_x_ || y >= size_y_ || cell_edge_.empty()) return -1;
|
||||
return cell_edge_[static_cast<size_t>(y) * size_x_ + x];
|
||||
}
|
||||
|
||||
int VoronoiGraph::indexOnEdge(int x, int y) const
|
||||
{
|
||||
if (x < 0 || y < 0 || x >= size_x_ || y >= size_y_ || cell_index_.empty()) return -1;
|
||||
return cell_index_[static_cast<size_t>(y) * size_x_ + x];
|
||||
}
|
||||
|
||||
int VoronoiGraph::componentCount() const
|
||||
{
|
||||
std::vector<int> parent(nodes_.size());
|
||||
for (size_t i = 0; i < parent.size(); ++i) parent[i] = static_cast<int>(i);
|
||||
std::function<int(int)> find = [&](int a) { return parent[a] == a ? a : parent[a] = find(parent[a]); };
|
||||
for (const GraphEdge& e : edges_) parent[find(e.u)] = find(e.v);
|
||||
int count = 0;
|
||||
for (size_t i = 0; i < parent.size(); ++i)
|
||||
if (find(static_cast<int>(i)) == static_cast<int>(i)) ++count;
|
||||
return count;
|
||||
}
|
||||
|
||||
Polyline VoronoiGraph::route(const Attachment& a, const Attachment& b) const
|
||||
{
|
||||
Polyline out;
|
||||
if (!a.ok || !b.ok || a.edge < 0 || b.edge < 0) return out;
|
||||
if (a.edge >= static_cast<int>(edges_.size()) || b.edge >= static_cast<int>(edges_.size())) return out;
|
||||
const GraphEdge& ea = edges_[a.edge];
|
||||
const GraphEdge& eb = edges_[b.edge];
|
||||
if (a.index < 0 || b.index < 0 || a.index >= static_cast<int>(ea.cells.size()) ||
|
||||
b.index >= static_cast<int>(eb.cells.size()))
|
||||
return out;
|
||||
|
||||
const float kInf = std::numeric_limits<float>::infinity();
|
||||
|
||||
// Candidate 0: stay on the same edge.
|
||||
float best = kInf;
|
||||
bool direct = false;
|
||||
if (a.edge == b.edge)
|
||||
{
|
||||
best = std::fabs(ea.cum_cells[a.index] - ea.cum_cells[b.index]);
|
||||
direct = true;
|
||||
}
|
||||
|
||||
// Dijkstra over nodes, seeded from both ends of a's edge.
|
||||
std::vector<float> dist(nodes_.size(), kInf);
|
||||
std::vector<int> parent_edge(nodes_.size(), -1);
|
||||
std::vector<int> parent_node(nodes_.size(), -1);
|
||||
std::vector<int> seed_side(nodes_.size(), -1); // 0 = reached via ea.u, 1 = via ea.v
|
||||
using QItem = std::pair<float, int>;
|
||||
std::priority_queue<QItem, std::vector<QItem>, std::greater<QItem>> pq;
|
||||
const float off_u = ea.cum_cells[a.index];
|
||||
const float off_v = ea.length_cells - off_u;
|
||||
auto seed = [&](int node, float d, int side) {
|
||||
if (d < dist[node])
|
||||
{
|
||||
dist[node] = d;
|
||||
seed_side[node] = side;
|
||||
parent_node[node] = -1;
|
||||
parent_edge[node] = -1;
|
||||
pq.push({d, node});
|
||||
}
|
||||
};
|
||||
seed(ea.u, off_u, 0);
|
||||
seed(ea.v, off_v, 1);
|
||||
|
||||
while (!pq.empty())
|
||||
{
|
||||
const QItem top = pq.top();
|
||||
pq.pop();
|
||||
const int u = top.second;
|
||||
if (top.first > dist[u]) continue;
|
||||
for (int e : nodes_[u].edges)
|
||||
{
|
||||
const GraphEdge& ge = edges_[e];
|
||||
if (ge.u == ge.v) continue;
|
||||
const int w = ge.u == u ? ge.v : ge.u;
|
||||
const float nd = dist[u] + ge.length_cells;
|
||||
if (nd < dist[w])
|
||||
{
|
||||
dist[w] = nd;
|
||||
parent_node[w] = u;
|
||||
parent_edge[w] = e;
|
||||
seed_side[w] = seed_side[u];
|
||||
pq.push({nd, w});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Candidate 1/2: arrive at b's edge through eb.u or eb.v.
|
||||
const float b_off_u = eb.cum_cells[b.index];
|
||||
const float b_off_v = eb.length_cells - b_off_u;
|
||||
int target = -1;
|
||||
int target_side = -1; // 0 = entered at eb.u, 1 = at eb.v
|
||||
if (dist[eb.u] + b_off_u < best)
|
||||
{
|
||||
best = dist[eb.u] + b_off_u;
|
||||
target = eb.u;
|
||||
target_side = 0;
|
||||
direct = false;
|
||||
}
|
||||
if (dist[eb.v] + b_off_v < best)
|
||||
{
|
||||
best = dist[eb.v] + b_off_v;
|
||||
target = eb.v;
|
||||
target_side = 1;
|
||||
direct = false;
|
||||
}
|
||||
if (!std::isfinite(best)) return out;
|
||||
|
||||
auto appendUnique = [&out](const Cell& c) {
|
||||
if (out.empty() || out.back() != c) out.push_back(c);
|
||||
};
|
||||
|
||||
if (direct)
|
||||
{
|
||||
if (a.index <= b.index)
|
||||
for (int i = a.index; i <= b.index; ++i) appendUnique(ea.cells[i]);
|
||||
else
|
||||
for (int i = a.index; i >= b.index; --i) appendUnique(ea.cells[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
// a's cell -> seed endpoint of ea.
|
||||
const int side = seed_side[target];
|
||||
if (side == 0)
|
||||
for (int i = a.index; i >= 0; --i) appendUnique(ea.cells[i]);
|
||||
else
|
||||
for (int i = a.index; i < static_cast<int>(ea.cells.size()); ++i) appendUnique(ea.cells[i]);
|
||||
|
||||
// Node chain from seed to target.
|
||||
std::vector<int> chain_nodes;
|
||||
for (int n = target; n != -1; n = parent_node[n]) chain_nodes.push_back(n);
|
||||
std::reverse(chain_nodes.begin(), chain_nodes.end());
|
||||
for (size_t i = 1; i < chain_nodes.size(); ++i)
|
||||
{
|
||||
const int to = chain_nodes[i];
|
||||
const GraphEdge& ge = edges_[parent_edge[to]];
|
||||
if (ge.u == chain_nodes[i - 1])
|
||||
for (size_t k = 0; k < ge.cells.size(); ++k) appendUnique(ge.cells[k]);
|
||||
else
|
||||
for (size_t k = ge.cells.size(); k-- > 0;) appendUnique(ge.cells[k]);
|
||||
}
|
||||
|
||||
// target endpoint of eb -> b's cell.
|
||||
if (target_side == 0)
|
||||
for (int i = 0; i <= b.index; ++i) appendUnique(eb.cells[i]);
|
||||
else
|
||||
for (int i = static_cast<int>(eb.cells.size()) - 1; i >= b.index; --i) appendUnique(eb.cells[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
148
src/voronoi_route.cpp
Normal file
148
src/voronoi_route.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace voronoi_route {
|
||||
|
||||
namespace {
|
||||
|
||||
double msSince(const std::chrono::steady_clock::time_point& t0)
|
||||
{
|
||||
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
uint64_t hashObstacleMask(const std::vector<uint8_t>& occupied)
|
||||
{
|
||||
uint64_t h = 1469598103934665603ULL; // FNV offset basis
|
||||
uint8_t packed = 0;
|
||||
int bit = 0;
|
||||
for (uint8_t o : occupied)
|
||||
{
|
||||
if (o) packed |= static_cast<uint8_t>(1u << bit);
|
||||
if (++bit == 8)
|
||||
{
|
||||
h ^= packed;
|
||||
h *= 1099511628211ULL; // FNV prime
|
||||
packed = 0;
|
||||
bit = 0;
|
||||
}
|
||||
}
|
||||
if (bit != 0)
|
||||
{
|
||||
h ^= packed;
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
h ^= static_cast<uint64_t>(occupied.size());
|
||||
h *= 1099511628211ULL;
|
||||
return h;
|
||||
}
|
||||
|
||||
VoronoiRoute::VoronoiRoute() = default;
|
||||
VoronoiRoute::VoronoiRoute(const Config& cfg) : cfg_(cfg) {}
|
||||
|
||||
void VoronoiRoute::rebuild(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
stats_ = Stats();
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
field_.rebuild(occupied, size_x, size_y);
|
||||
stats_.field_ms = msSince(t0);
|
||||
occupancy_hash_ = hashObstacleMask(field_.occupancy());
|
||||
for (uint8_t o : field_.occupancy()) stats_.obstacle_cells += o ? 1 : 0;
|
||||
extractGraph();
|
||||
}
|
||||
|
||||
size_t VoronoiRoute::syncOccupancy(const std::vector<uint8_t>& occupied, int size_x, int size_y)
|
||||
{
|
||||
if (!field_.ready() || size_x != field_.sizeX() || size_y != field_.sizeY() ||
|
||||
occupied.size() != field_.occupancy().size())
|
||||
{
|
||||
rebuild(occupied, size_x, size_y);
|
||||
stats_.last_sync_changed = occupied.size();
|
||||
stats_.last_sync_full_rebuild = true;
|
||||
return occupied.size();
|
||||
}
|
||||
|
||||
const std::vector<uint8_t>& have = field_.occupancy();
|
||||
std::vector<Cell> now_occupied, now_free;
|
||||
const int w = size_x;
|
||||
for (size_t i = 0; i < occupied.size(); ++i)
|
||||
{
|
||||
const bool a = have[i] != 0, b = occupied[i] != 0;
|
||||
if (a == b) continue;
|
||||
const Cell c(static_cast<int>(i % w), static_cast<int>(i / w));
|
||||
(b ? now_occupied : now_free).push_back(c);
|
||||
}
|
||||
const size_t changed = now_occupied.size() + now_free.size();
|
||||
stats_.last_sync_changed = changed;
|
||||
stats_.last_sync_full_rebuild = false;
|
||||
if (changed == 0) return 0;
|
||||
|
||||
if (static_cast<double>(changed) > cfg_.full_rebuild_fraction * static_cast<double>(occupied.size()))
|
||||
{
|
||||
rebuild(occupied, size_x, size_y);
|
||||
stats_.last_sync_changed = changed;
|
||||
stats_.last_sync_full_rebuild = true;
|
||||
return changed;
|
||||
}
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
field_.setOccupied(now_occupied);
|
||||
field_.setFree(now_free);
|
||||
field_.refresh();
|
||||
stats_.field_ms = msSince(t0);
|
||||
occupancy_hash_ = hashObstacleMask(field_.occupancy());
|
||||
stats_.obstacle_cells = 0;
|
||||
for (uint8_t o : field_.occupancy()) stats_.obstacle_cells += o ? 1 : 0;
|
||||
if (changed > cfg_.graph_rebuild_min_changed_cells || graph_.empty()) extractGraph();
|
||||
return changed;
|
||||
}
|
||||
|
||||
void VoronoiRoute::extractGraph()
|
||||
{
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
VoronoiGraph::ExtractParams ep;
|
||||
ep.min_edge_length_cells = cfg_.min_edge_length_cells;
|
||||
ep.spur_clearance_ratio = cfg_.spur_clearance_ratio;
|
||||
ep.min_component_length_cells = cfg_.min_component_length_cells;
|
||||
ep.min_clearance_cells = cfg_.min_clearance_cells;
|
||||
graph_.extract(field_, ep);
|
||||
stats_.extract_ms = msSince(t0);
|
||||
stats_.nodes = static_cast<int>(graph_.nodes().size());
|
||||
stats_.edges = static_cast<int>(graph_.edges().size());
|
||||
stats_.components = graph_.componentCount();
|
||||
stats_.gvd_cells = 0;
|
||||
for (int y = 0; y < field_.sizeY(); ++y)
|
||||
for (int x = 0; x < field_.sizeX(); ++x)
|
||||
if (field_.isVoronoi(x, y)) ++stats_.gvd_cells;
|
||||
}
|
||||
|
||||
Attachment VoronoiRoute::attach(Cell c) const
|
||||
{
|
||||
return attachPoint(field_, graph_, c, cfg_.attach_max_radius_cells);
|
||||
}
|
||||
|
||||
Polyline VoronoiRoute::query(const Attachment& start, const Attachment& goal) const
|
||||
{
|
||||
Polyline out;
|
||||
if (!start.ok || !goal.ok) return out;
|
||||
Polyline mid = graph_.route(start, goal);
|
||||
if (mid.empty()) return out;
|
||||
|
||||
auto appendUnique = [&out](const Cell& c) {
|
||||
if (out.empty() || out.back() != c) out.push_back(c);
|
||||
};
|
||||
for (const Cell& c : start.path) appendUnique(c); // start cell -> attach cell
|
||||
for (const Cell& c : mid) appendUnique(c); // along the graph
|
||||
for (size_t i = goal.path.size(); i-- > 0;) appendUnique(goal.path[i]); // attach -> goal cell
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> VoronoiRoute::corridorMask(const Polyline& route, const CorridorParams& p,
|
||||
size_t* cells_in_mask) const
|
||||
{
|
||||
return voronoi_route::corridorMask(field_, route, p, cells_in_mask);
|
||||
}
|
||||
|
||||
} // namespace voronoi_route
|
||||
93
test/params_io_test.cpp
Normal file
93
test/params_io_test.cpp
Normal file
@@ -0,0 +1,93 @@
|
||||
// Loader tests: missing keys keep defaults and are reported; bad ranges are clamped and reported.
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#include "voronoi_route/params_io.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::string writeTemp(const std::string& body)
|
||||
{
|
||||
const std::string path = "/tmp/voronoi_route_params_test_" + std::to_string(::getpid()) + ".yaml";
|
||||
std::ofstream f(path);
|
||||
f << body;
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(ParamsIo, PackagedDefaultsLoadCleanly)
|
||||
{
|
||||
voronoi_route::RouteParams p;
|
||||
std::string err;
|
||||
std::vector<std::string> notes;
|
||||
ASSERT_TRUE(voronoi_route::loadRouteParams(VORONOI_ROUTE_PACKAGED_PARAMS, &p, &err, ¬es)) << err;
|
||||
EXPECT_TRUE(notes.empty()) << notes.front();
|
||||
EXPECT_DOUBLE_EQ(p.min_clearance_m, 0.3);
|
||||
EXPECT_FALSE(p.unknown_is_obstacle);
|
||||
const auto c = p.toConfig(0.05);
|
||||
EXPECT_DOUBLE_EQ(c.min_edge_length_cells, 6.0);
|
||||
EXPECT_DOUBLE_EQ(c.min_clearance_cells, 6.0);
|
||||
EXPECT_EQ(c.attach_max_radius_cells, 200);
|
||||
const auto cp = p.toCorridor(0.05);
|
||||
EXPECT_DOUBLE_EQ(cp.half_width_min_cells, 30.0);
|
||||
}
|
||||
|
||||
TEST(ParamsIo, MissingAndBadKeysAreReportedNotFatal)
|
||||
{
|
||||
const std::string path = writeTemp(
|
||||
"voronoi_route:\n"
|
||||
" graph:\n"
|
||||
" min_edge_length_m: -5\n" // out of range -> clamped to default
|
||||
" spur_clearance_ratio: 1.0\n"
|
||||
" corridor:\n"
|
||||
" half_width_min_m: 3.0\n"
|
||||
" half_width_max_m: 1.0\n" // max < min -> raised
|
||||
" obstacle:\n"
|
||||
" unknown: obstacle\n");
|
||||
voronoi_route::RouteParams p;
|
||||
std::string err;
|
||||
std::vector<std::string> notes;
|
||||
ASSERT_TRUE(voronoi_route::loadRouteParams(path, &p, &err, ¬es)) << err;
|
||||
std::remove(path.c_str());
|
||||
EXPECT_DOUBLE_EQ(p.spur_clearance_ratio, 1.0);
|
||||
EXPECT_DOUBLE_EQ(p.min_edge_length_m, 0.3); // clamped
|
||||
EXPECT_DOUBLE_EQ(p.half_width_max_m, 3.0); // raised to min
|
||||
EXPECT_TRUE(p.unknown_is_obstacle);
|
||||
EXPECT_DOUBLE_EQ(p.min_clearance_m, 0.3); // missing -> default
|
||||
bool saw_missing = false, saw_clamp = false;
|
||||
for (const auto& n : notes)
|
||||
{
|
||||
if (n.find("min_clearance_m: missing") != std::string::npos) saw_missing = true;
|
||||
if (n.find("min_edge_length_m out of range") != std::string::npos) saw_clamp = true;
|
||||
}
|
||||
EXPECT_TRUE(saw_missing);
|
||||
EXPECT_TRUE(saw_clamp);
|
||||
}
|
||||
|
||||
TEST(ParamsIo, NoRootKeyFails)
|
||||
{
|
||||
const std::string path = writeTemp("something_else: 1\n");
|
||||
voronoi_route::RouteParams p;
|
||||
std::string err;
|
||||
EXPECT_FALSE(voronoi_route::loadRouteParams(path, &p, &err, nullptr));
|
||||
std::remove(path.c_str());
|
||||
EXPECT_NE(err.find("voronoi_route"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(ParamsIo, ObstacleRuleIsSelfContainedInOwnParams)
|
||||
{
|
||||
// No config-dir scan, no formula from another package's flags: `unknown_is_obstacle` decides
|
||||
// the policy directly, everything else in the rule is this package's own default.
|
||||
voronoi_route::RouteParams p;
|
||||
const auto r = p.toObstacleRule(0.05);
|
||||
EXPECT_EQ(r.layer.lethal_cost_threshold, 100);
|
||||
EXPECT_TRUE(r.layer.track_unknown_space);
|
||||
EXPECT_EQ(r.unknown, voronoi_route::UnknownPolicy::kTraversable);
|
||||
|
||||
p.unknown_is_obstacle = true;
|
||||
EXPECT_EQ(p.toObstacleRule(0.05).unknown, voronoi_route::UnknownPolicy::kObstacle);
|
||||
}
|
||||
387
test/voronoi_route_test.cpp
Normal file
387
test/voronoi_route_test.cpp
Normal file
@@ -0,0 +1,387 @@
|
||||
// Unit tests on synthetic grids. Coordinates are image-style: x = column, y = row.
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using voronoi_route::Cell;
|
||||
using voronoi_route::VoronoiRoute;
|
||||
|
||||
struct Grid {
|
||||
int w, h;
|
||||
std::vector<uint8_t> occ;
|
||||
Grid(int w_, int h_) : w(w_), h(h_), occ(static_cast<size_t>(w_) * h_, 0) {}
|
||||
void set(int x, int y, uint8_t v = 1) { occ[static_cast<size_t>(y) * w + x] = v; }
|
||||
void rect(int x0, int y0, int x1, int y1, uint8_t v = 1)
|
||||
{
|
||||
for (int y = y0; y <= y1; ++y)
|
||||
for (int x = x0; x <= x1; ++x) set(x, y, v);
|
||||
}
|
||||
void frame() { rect(0, 0, w - 1, 0); rect(0, h - 1, w - 1, h - 1); rect(0, 0, 0, h - 1); rect(w - 1, 0, w - 1, h - 1); }
|
||||
};
|
||||
|
||||
// Straight corridor: walls at rows [0..4] and [h-5..h-1], free in between, closed ends.
|
||||
Grid corridor(int w = 200, int h = 40)
|
||||
{
|
||||
Grid g(w, h);
|
||||
g.rect(0, 0, w - 1, 4);
|
||||
g.rect(0, h - 5, w - 1, h - 1);
|
||||
g.rect(0, 0, 4, h - 1);
|
||||
g.rect(w - 5, 0, w - 1, h - 1);
|
||||
return g;
|
||||
}
|
||||
|
||||
// T: horizontal corridor plus a vertical stem going down from the middle.
|
||||
Grid tee()
|
||||
{
|
||||
Grid g(200, 120);
|
||||
g.rect(0, 0, 199, 119); // all wall
|
||||
g.rect(5, 40, 194, 79, 0); // horizontal free band
|
||||
g.rect(85, 79, 114, 114, 0); // vertical stem
|
||||
return g;
|
||||
}
|
||||
|
||||
// Ring: free band around a solid block.
|
||||
Grid ring()
|
||||
{
|
||||
Grid g(160, 160);
|
||||
g.rect(0, 0, 159, 159);
|
||||
g.rect(5, 5, 154, 154, 0);
|
||||
g.rect(45, 45, 114, 114); // block
|
||||
return g;
|
||||
}
|
||||
|
||||
int degreeOf(const VoronoiRoute& vr, int node)
|
||||
{
|
||||
return static_cast<int>(vr.graph().nodes()[node].edges.size());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(VoronoiRoute, CorridorIsOneEdgeBetweenTwoDeadEnds)
|
||||
{
|
||||
Grid g = corridor();
|
||||
VoronoiRoute vr;
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
ASSERT_TRUE(vr.ready());
|
||||
const auto& st = vr.stats();
|
||||
EXPECT_EQ(st.components, 1);
|
||||
EXPECT_GE(st.edges, 1);
|
||||
// Longest edge runs most of the corridor.
|
||||
float longest = 0;
|
||||
for (const auto& e : vr.graph().edges()) longest = std::max(longest, e.length_cells);
|
||||
EXPECT_GT(longest, 150.0f);
|
||||
// Diagram sits on the centre row.
|
||||
int on_centre = 0, total = 0;
|
||||
for (int x = 20; x < g.w - 20; ++x)
|
||||
for (int y = 5; y < g.h - 5; ++y)
|
||||
if (vr.field().isVoronoi(x, y))
|
||||
{
|
||||
++total;
|
||||
if (std::abs(y - (g.h - 1) / 2) <= 1) ++on_centre;
|
||||
}
|
||||
EXPECT_GT(total, 0);
|
||||
EXPECT_GT(on_centre, total * 0.8);
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, TeeHasAJunction)
|
||||
{
|
||||
Grid g = tee();
|
||||
VoronoiRoute::Config cfg;
|
||||
cfg.min_edge_length_cells = 8;
|
||||
VoronoiRoute vr(cfg);
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
ASSERT_TRUE(vr.ready());
|
||||
int junctions = 0, leaves = 0;
|
||||
for (size_t i = 0; i < vr.graph().nodes().size(); ++i)
|
||||
{
|
||||
const int d = degreeOf(vr, static_cast<int>(i));
|
||||
if (d >= 3) ++junctions;
|
||||
if (d == 1) ++leaves;
|
||||
}
|
||||
EXPECT_GE(junctions, 1);
|
||||
EXPECT_GE(leaves, 3);
|
||||
EXPECT_EQ(vr.stats().components, 1);
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, RingIsConnectedAndRoutesTheShortWay)
|
||||
{
|
||||
Grid g = ring();
|
||||
VoronoiRoute vr;
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
ASSERT_TRUE(vr.ready());
|
||||
EXPECT_EQ(vr.stats().components, 1);
|
||||
// Two points on the top band, close to each other: route must not go around the block.
|
||||
const auto a = vr.attach(Cell(60, 25));
|
||||
const auto b = vr.attach(Cell(100, 25));
|
||||
ASSERT_TRUE(a.ok);
|
||||
ASSERT_TRUE(b.ok);
|
||||
const auto route = vr.query(a, b);
|
||||
ASSERT_FALSE(route.empty());
|
||||
EXPECT_EQ(route.front(), Cell(60, 25));
|
||||
EXPECT_EQ(route.back(), Cell(100, 25));
|
||||
EXPECT_LT(route.size(), 120u);
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, ShortSpurIsPrunedLongOneKept)
|
||||
{
|
||||
Grid g = corridor(200, 60);
|
||||
// Long dead-end pocket off the corridor (kept), and a tiny notch (pruned).
|
||||
g.rect(60, 55, 80, 59, 0); // notch 5 deep — spur way below 8 cells? it barely forms one
|
||||
g.rect(140, 40, 150, 59, 0); // pocket 20 deep
|
||||
VoronoiRoute::Config cfg;
|
||||
cfg.min_edge_length_cells = 8;
|
||||
VoronoiRoute vr(cfg);
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
ASSERT_TRUE(vr.ready());
|
||||
for (const auto& e : vr.graph().edges())
|
||||
{
|
||||
const bool leaf = degreeOf(vr, e.u) == 1 || degreeOf(vr, e.v) == 1;
|
||||
if (leaf && e.u != e.v)
|
||||
{
|
||||
EXPECT_GE(e.length_cells, 8.0f) << "spur survived pruning";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, AttachFailsInsideSealedRoom)
|
||||
{
|
||||
Grid g = corridor();
|
||||
g.rect(100, 10, 120, 30); // solid block
|
||||
g.rect(105, 15, 115, 25, 0); // hollow inside, sealed
|
||||
VoronoiRoute::Config cfg;
|
||||
cfg.attach_max_radius_cells = 50;
|
||||
VoronoiRoute vr(cfg);
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
const auto a = vr.attach(Cell(110, 20));
|
||||
// Either no GVD inside the sealed pocket (attach fails) or a tiny isolated diagram there;
|
||||
// what must never happen is a path that crosses the wall.
|
||||
if (a.ok)
|
||||
{
|
||||
for (const auto& c : a.path) EXPECT_FALSE(vr.field().isOccupied(c.x, c.y));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, CorridorMaskCoversRouteAndRespectsWidth)
|
||||
{
|
||||
Grid g = corridor(300, 60);
|
||||
VoronoiRoute vr;
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
const auto a = vr.attach(Cell(20, 30));
|
||||
const auto b = vr.attach(Cell(280, 30));
|
||||
ASSERT_TRUE(a.ok && b.ok);
|
||||
const auto route = vr.query(a, b);
|
||||
ASSERT_FALSE(route.empty());
|
||||
voronoi_route::CorridorParams p;
|
||||
p.half_width_min_cells = 6;
|
||||
p.clearance_scale = 0.0;
|
||||
p.half_width_max_cells = 6;
|
||||
size_t n = 0;
|
||||
const auto mask = vr.corridorMask(route, p, &n);
|
||||
EXPECT_GT(n, 0u);
|
||||
for (const auto& c : route) EXPECT_EQ(mask[static_cast<size_t>(c.y) * g.w + c.x], 1);
|
||||
EXPECT_EQ(mask[static_cast<size_t>(8) * g.w + 150], 0); // 22 rows from centre: outside
|
||||
EXPECT_EQ(mask[static_cast<size_t>(30) * g.w + 150], 1); // on the line
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, SyncOccupancySplitsAndRejoins)
|
||||
{
|
||||
Grid g = corridor(200, 40);
|
||||
VoronoiRoute::Config cfg;
|
||||
cfg.graph_rebuild_min_changed_cells = 1;
|
||||
VoronoiRoute vr(cfg);
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
const uint64_t h0 = vr.occupancyHash();
|
||||
EXPECT_EQ(vr.stats().components, 1);
|
||||
|
||||
Grid blocked = g;
|
||||
blocked.rect(100, 5, 101, 34); // wall across the corridor
|
||||
const size_t changed = vr.syncOccupancy(blocked.occ, g.w, g.h);
|
||||
EXPECT_EQ(changed, 60u);
|
||||
EXPECT_NE(vr.occupancyHash(), h0);
|
||||
EXPECT_GE(vr.stats().components, 2);
|
||||
const auto a = vr.attach(Cell(30, 20));
|
||||
const auto b = vr.attach(Cell(170, 20));
|
||||
ASSERT_TRUE(a.ok && b.ok);
|
||||
EXPECT_TRUE(vr.query(a, b).empty());
|
||||
|
||||
vr.syncOccupancy(g.occ, g.w, g.h);
|
||||
EXPECT_EQ(vr.occupancyHash(), h0);
|
||||
EXPECT_EQ(vr.stats().components, 1);
|
||||
const auto a2 = vr.attach(Cell(30, 20));
|
||||
const auto b2 = vr.attach(Cell(170, 20));
|
||||
EXPECT_FALSE(vr.query(a2, b2).empty());
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, SyncWithWholeDifferentMapMatchesFreshRebuild)
|
||||
{
|
||||
Grid a = tee();
|
||||
Grid b = ring();
|
||||
ASSERT_EQ(a.w, 200);
|
||||
// Same size grids: pad ring into 200x120 by cropping rows.
|
||||
Grid b2(200, 120);
|
||||
b2.rect(0, 0, 199, 119);
|
||||
b2.rect(5, 5, 194, 114, 0);
|
||||
b2.rect(60, 40, 139, 79);
|
||||
VoronoiRoute vr;
|
||||
vr.rebuild(a.occ, a.w, a.h);
|
||||
vr.syncOccupancy(b2.occ, b2.w, b2.h);
|
||||
EXPECT_TRUE(vr.stats().last_sync_full_rebuild);
|
||||
VoronoiRoute fresh;
|
||||
fresh.rebuild(b2.occ, b2.w, b2.h);
|
||||
EXPECT_EQ(vr.occupancyHash(), fresh.occupancyHash());
|
||||
EXPECT_EQ(vr.graph().nodes().size(), fresh.graph().nodes().size());
|
||||
EXPECT_EQ(vr.graph().edges().size(), fresh.graph().edges().size());
|
||||
for (size_t i = 0; i < vr.graph().edges().size(); ++i)
|
||||
EXPECT_EQ(vr.graph().edges()[i].cells, fresh.graph().edges()[i].cells);
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, ExtractionIsDeterministic)
|
||||
{
|
||||
Grid g = tee();
|
||||
VoronoiRoute a, b;
|
||||
a.rebuild(g.occ, g.w, g.h);
|
||||
b.rebuild(g.occ, g.w, g.h);
|
||||
ASSERT_EQ(a.graph().edges().size(), b.graph().edges().size());
|
||||
for (size_t i = 0; i < a.graph().edges().size(); ++i)
|
||||
{
|
||||
EXPECT_EQ(a.graph().edges()[i].u, b.graph().edges()[i].u);
|
||||
EXPECT_EQ(a.graph().edges()[i].v, b.graph().edges()[i].v);
|
||||
EXPECT_EQ(a.graph().edges()[i].cells, b.graph().edges()[i].cells);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, HashChangesWhenOneCellFlips)
|
||||
{
|
||||
Grid g = corridor();
|
||||
const uint64_t h0 = voronoi_route::hashObstacleMask(g.occ);
|
||||
g.set(100, 20, 1);
|
||||
EXPECT_NE(h0, voronoi_route::hashObstacleMask(g.occ));
|
||||
}
|
||||
|
||||
// ---- obstacle rule = StaticLayer::interpretValue + allow_unknown -------------------------------
|
||||
#include "voronoi_route/map_convert.h"
|
||||
|
||||
TEST(MapConvert, ClassifyMirrorsStaticLayer)
|
||||
{
|
||||
using voronoi_route::CostClass;
|
||||
voronoi_route::StaticLayerRule r; // track_unknown true, lethal 100, unknown -1, trinary
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(-1, r), CostClass::kNoInformation);
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(100, r), CostClass::kLethal);
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(99, r), CostClass::kFree);
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(0, r), CostClass::kFree);
|
||||
r.track_unknown_space = false;
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(-1, r), CostClass::kFree);
|
||||
r.trinary_costmap = false;
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(50, r), CostClass::kScaled);
|
||||
r.lethal_cost_threshold = 50;
|
||||
EXPECT_EQ(voronoi_route::classifyGridValue(50, r), CostClass::kLethal);
|
||||
}
|
||||
|
||||
TEST(MapConvert, UnknownPolicyDecidesNoInformation)
|
||||
{
|
||||
const int8_t grid[4] = {100, -1, 0, 50}; // one row, ROS layout == image layout for h = 1
|
||||
voronoi_route::ObstacleRule rule; // traversable
|
||||
auto m = voronoi_route::occupancyFromGrid(grid, 4, 1, rule);
|
||||
EXPECT_EQ((std::vector<uint8_t>{1, 0, 0, 0}), m);
|
||||
rule.unknown = voronoi_route::UnknownPolicy::kObstacle;
|
||||
m = voronoi_route::occupancyFromGrid(grid, 4, 1, rule);
|
||||
EXPECT_EQ((std::vector<uint8_t>{1, 1, 0, 0}), m);
|
||||
}
|
||||
|
||||
TEST(MapConvert, GrayAndGridAndCostmapAgree)
|
||||
{
|
||||
// Pixel -> map_server value -> class must equal feeding the value directly, and equal the
|
||||
// costmap chars the static layer would write (254 / 255 / other).
|
||||
const uint8_t gray[3] = {0, 128, 255}; // black, mid, white
|
||||
const int8_t grid[3] = {100, -1, 0}; // what map_server makes of them
|
||||
const unsigned char cost[3] = {254, 255, 0}; // what StaticLayer makes of the grid
|
||||
voronoi_route::MapServerThresholds thr;
|
||||
for (auto pol : {voronoi_route::UnknownPolicy::kTraversable, voronoi_route::UnknownPolicy::kObstacle})
|
||||
{
|
||||
voronoi_route::ObstacleRule rule;
|
||||
rule.unknown = pol;
|
||||
const auto a = voronoi_route::occupancyFromGray(gray, 3, 1, thr, rule);
|
||||
const auto b = voronoi_route::occupancyFromGrid(grid, 3, 1, rule);
|
||||
const auto c = voronoi_route::occupancyFromCostmap(cost, 3, 1, pol, false);
|
||||
EXPECT_EQ(a, b);
|
||||
EXPECT_EQ(b, c);
|
||||
EXPECT_EQ(voronoi_route::hashObstacleMask(a), voronoi_route::hashObstacleMask(c));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(MapConvert, ImageRuleAveragesAlphaLikeMapServer)
|
||||
{
|
||||
// ROS map_server (trinary) averages every channel, alpha included: (79,79,79,255) -> 123 ->
|
||||
// occ 0.52 -> UNKNOWN, not occupied; (0,0,0,255) -> 63.75 -> occ 0.75 -> occupied;
|
||||
// (205,205,205,255) -> 217.5 -> occ 0.15 -> FREE (what the robot really sees on an RGBA map).
|
||||
const uint8_t rgba[4 * 4] = {79, 79, 79, 255, 0, 0, 0, 255, 205, 205, 205, 255, 254, 254, 254, 255};
|
||||
voronoi_route::MapServerThresholds thr;
|
||||
voronoi_route::ObstacleRule rule;
|
||||
voronoi_route::MapConvertStats st;
|
||||
const auto m = voronoi_route::occupancyFromImage(rgba, 4, 1, 4, thr, rule, &st);
|
||||
EXPECT_EQ((std::vector<uint8_t>{0, 1, 0, 0}), m);
|
||||
EXPECT_EQ(st.occupied, 1u);
|
||||
EXPECT_EQ(st.unknown, 1u);
|
||||
EXPECT_EQ(st.free, 2u);
|
||||
// Same pixels as 1-channel luminance would call the first one occupied — the two must differ.
|
||||
const uint8_t gray[4] = {79, 0, 205, 254};
|
||||
const auto g = voronoi_route::occupancyFromGray(gray, 4, 1, thr, rule);
|
||||
EXPECT_EQ((std::vector<uint8_t>{1, 1, 0, 0}), g);
|
||||
}
|
||||
|
||||
TEST(MapConvert, RuleStringRoundTrip)
|
||||
{
|
||||
voronoi_route::ObstacleRule r;
|
||||
r.layer.lethal_cost_threshold = 90;
|
||||
r.layer.track_unknown_space = false;
|
||||
r.unknown = voronoi_route::UnknownPolicy::kObstacle;
|
||||
voronoi_route::ObstacleRule back;
|
||||
ASSERT_TRUE(voronoi_route::parseObstacleRuleString(voronoi_route::obstacleRuleString(r), &back));
|
||||
EXPECT_EQ(back.layer.lethal_cost_threshold, 90);
|
||||
EXPECT_FALSE(back.layer.track_unknown_space);
|
||||
EXPECT_EQ(back.unknown, voronoi_route::UnknownPolicy::kObstacle);
|
||||
EXPECT_FALSE(voronoi_route::parseObstacleRuleString("map_server:occupied", nullptr));
|
||||
r.roi_margin_cells = 40;
|
||||
ASSERT_TRUE(voronoi_route::parseObstacleRuleString(voronoi_route::obstacleRuleString(r), &back));
|
||||
EXPECT_EQ(back.roi_margin_cells, 40);
|
||||
}
|
||||
|
||||
TEST(MapConvert, RoiTurnsOutsideOfObstacleBoxIntoObstacle)
|
||||
{
|
||||
const int w = 50, h = 40;
|
||||
std::vector<uint8_t> m(static_cast<size_t>(w) * h, 0);
|
||||
for (int x = 20; x < 30; ++x) m[static_cast<size_t>(15) * w + x] = 1; // one wall segment
|
||||
for (int x = 20; x < 30; ++x) m[static_cast<size_t>(25) * w + x] = 1;
|
||||
const size_t turned = voronoi_route::applyObstacleRoi(m, w, h, 2);
|
||||
EXPECT_GT(turned, 0u);
|
||||
EXPECT_EQ(m[static_cast<size_t>(20) * w + 25], 0); // inside the box: untouched
|
||||
EXPECT_EQ(m[static_cast<size_t>(0) * w + 0], 1); // far corner: outside
|
||||
EXPECT_EQ(m[static_cast<size_t>(13) * w + 18], 0); // (18,13) = box corner grown by 2: inside, untouched
|
||||
EXPECT_EQ(m[static_cast<size_t>(12) * w + 25], 1); // one row past the margin: outside
|
||||
// fewer than min_obstacle_cells -> no-op
|
||||
std::vector<uint8_t> tiny(static_cast<size_t>(w) * h, 0);
|
||||
tiny[5] = 1;
|
||||
EXPECT_EQ(voronoi_route::applyObstacleRoi(tiny, w, h, 2), 0u);
|
||||
}
|
||||
|
||||
TEST(VoronoiRoute, GridBorderIsNeverVoronoi)
|
||||
{
|
||||
// Lone block in open space: DynamicVoronoi leaves the untouched outer ring flagged; the wrapper
|
||||
// must hide it, and the graph must not pick it up as a frame around the map.
|
||||
Grid g(120, 80);
|
||||
g.rect(50, 30, 69, 49);
|
||||
VoronoiRoute vr;
|
||||
vr.rebuild(g.occ, g.w, g.h);
|
||||
int border = 0;
|
||||
for (int x = 0; x < g.w; ++x) border += vr.field().isVoronoi(x, 0) + vr.field().isVoronoi(x, g.h - 1);
|
||||
for (int y = 0; y < g.h; ++y) border += vr.field().isVoronoi(0, y) + vr.field().isVoronoi(g.w - 1, y);
|
||||
EXPECT_EQ(border, 0);
|
||||
for (const auto& e : vr.graph().edges())
|
||||
for (const auto& c : e.cells)
|
||||
EXPECT_TRUE(c.x > 0 && c.y > 0 && c.x < g.w - 1 && c.y < g.h - 1);
|
||||
}
|
||||
412
tools/voronoi_route_compile.cpp
Normal file
412
tools/voronoi_route_compile.cpp
Normal file
@@ -0,0 +1,412 @@
|
||||
// voronoi_route_compile — build the Voronoi route graph of a map_server-style map (YAML + image)
|
||||
// and write the bundle next to it, plus a preview PNG a human can look at.
|
||||
//
|
||||
// The tool is the only place with image/YAML dependencies (OpenCV, yaml-cpp). Everything it does
|
||||
// after decoding is library API a host can call the same way: occupancyFromGray() ->
|
||||
// VoronoiRoute::rebuild() -> saveBundle().
|
||||
//
|
||||
// "Obstacle" = pixel -> occupancy by the map's own `negate` / `occupied_thresh` / `free_thresh`
|
||||
// (the map_server rule xloc also uses), then occupancy -> cost class by `lethal_cost_threshold` /
|
||||
// `track_unknown_space` / `trinary_costmap` / `unknown_cost_value`, then NO_INFORMATION blocks or
|
||||
// not by `unknown: traversable|obstacle`. All of it lives in `voronoi_route_params.yaml`'s own
|
||||
// `obstacle:` block, decided by this package alone — it never reads another package's costmap or
|
||||
// planner config. The rule is written to the bundle's `source` so a consumer hashes the live map
|
||||
// the same way.
|
||||
//
|
||||
// Parameters come from `voronoi_route_params.yaml` (--params, else the first one found under
|
||||
// --config-dir, else built-in defaults); every --flag below overrides one key for this run only.
|
||||
//
|
||||
// Usage:
|
||||
// voronoi_route_compile --map <map.yaml> [--image <file>] [--out <dir, default: the map's folder>]
|
||||
// [--config-dir <PNKX_NAV_CORE_CONFIG_DIR>] [--params <voronoi_route_params.yaml>]
|
||||
// [--unknown-as-obstacle | --unknown-free]
|
||||
// [--min-edge-m X] [--spur-ratio X] [--min-component-m X] [--min-clearance-m X]
|
||||
// [--start-cell X Y --goal-cell X Y | --start-m X Y --goal-m X Y]
|
||||
// [--half-width-m X] [--clearance-scale X] [--max-half-width-m X]
|
||||
// [--no-preview] [--no-dist] [--no-gvd] [--no-graph-image] [--graph-overlay]
|
||||
//
|
||||
// --image overrides the YAML's `image:` — RBApp copies xloc's YAML verbatim (`image: t4.png`)
|
||||
// next to a file it renamed to map.png.
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <opencv2/imgcodecs.hpp>
|
||||
#include <opencv2/imgproc.hpp>
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include "voronoi_route/bundle_io.h"
|
||||
#include "voronoi_route/map_convert.h"
|
||||
#include "voronoi_route/params.h"
|
||||
#include "voronoi_route/params_io.h"
|
||||
#include "voronoi_route/voronoi_route.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kUnset = -1e300;
|
||||
|
||||
struct Args {
|
||||
std::string map_yaml, image_override, out_dir, config_dir, params_yaml;
|
||||
// Per-run overrides of voronoi_route_params.yaml; kUnset = keep the file's value.
|
||||
double min_edge_m = kUnset, spur_ratio = kUnset, min_component_m = kUnset, min_clearance_m = kUnset;
|
||||
double half_width_m = kUnset, clearance_scale = kUnset, max_half_width_m = kUnset;
|
||||
int unknown_override = -1; // -1 = keep file's, 0 traversable, 1 obstacle
|
||||
int preview = -1, write_dist = -1, write_gvd = -1, graph_image = -1, graph_overlay = -1; // -1 keep file's
|
||||
bool have_start = false, have_goal = false, start_in_meters = false, goal_in_meters = false;
|
||||
double sx = 0, sy = 0, gx = 0, gy = 0;
|
||||
};
|
||||
|
||||
bool parseArgs(int argc, char** argv, Args& a)
|
||||
{
|
||||
for (int i = 1; i < argc; ++i)
|
||||
{
|
||||
const std::string k = argv[i];
|
||||
auto need = [&](int n) {
|
||||
if (i + n >= argc)
|
||||
{
|
||||
std::fprintf(stderr, "%s needs %d value(s)\n", k.c_str(), n);
|
||||
std::exit(2);
|
||||
}
|
||||
};
|
||||
if (k == "--map") { need(1); a.map_yaml = argv[++i]; }
|
||||
else if (k == "--image") { need(1); a.image_override = argv[++i]; }
|
||||
else if (k == "--out") { need(1); a.out_dir = argv[++i]; }
|
||||
else if (k == "--min-edge-m") { need(1); a.min_edge_m = std::atof(argv[++i]); }
|
||||
else if (k == "--spur-ratio") { need(1); a.spur_ratio = std::atof(argv[++i]); }
|
||||
else if (k == "--min-component-m") { need(1); a.min_component_m = std::atof(argv[++i]); }
|
||||
else if (k == "--min-clearance-m") { need(1); a.min_clearance_m = std::atof(argv[++i]); }
|
||||
else if (k == "--config-dir") { need(1); a.config_dir = argv[++i]; }
|
||||
else if (k == "--params") { need(1); a.params_yaml = argv[++i]; }
|
||||
else if (k == "--unknown-free") { a.unknown_override = 0; }
|
||||
else if (k == "--unknown-as-obstacle") { a.unknown_override = 1; }
|
||||
else if (k == "--start-cell") { need(2); a.have_start = true; a.start_in_meters = false; a.sx = std::atof(argv[++i]); a.sy = std::atof(argv[++i]); }
|
||||
else if (k == "--goal-cell") { need(2); a.have_goal = true; a.goal_in_meters = false; a.gx = std::atof(argv[++i]); a.gy = std::atof(argv[++i]); }
|
||||
else if (k == "--start-m") { need(2); a.have_start = true; a.start_in_meters = true; a.sx = std::atof(argv[++i]); a.sy = std::atof(argv[++i]); }
|
||||
else if (k == "--goal-m") { need(2); a.have_goal = true; a.goal_in_meters = true; a.gx = std::atof(argv[++i]); a.gy = std::atof(argv[++i]); }
|
||||
else if (k == "--half-width-m") { need(1); a.half_width_m = std::atof(argv[++i]); }
|
||||
else if (k == "--clearance-scale") { need(1); a.clearance_scale = std::atof(argv[++i]); }
|
||||
else if (k == "--max-half-width-m") { need(1); a.max_half_width_m = std::atof(argv[++i]); }
|
||||
else if (k == "--no-preview") { a.preview = 0; }
|
||||
else if (k == "--no-dist") { a.write_dist = 0; }
|
||||
else if (k == "--no-gvd") { a.write_gvd = 0; }
|
||||
else if (k == "--no-graph-image") { a.graph_image = 0; }
|
||||
else if (k == "--graph-overlay") { a.graph_overlay = 1; }
|
||||
else
|
||||
{
|
||||
std::fprintf(stderr, "unknown argument: %s\n", k.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (a.map_yaml.empty())
|
||||
{
|
||||
std::fprintf(stderr, "--map <map.yaml> is required\n");
|
||||
return false;
|
||||
}
|
||||
if (a.config_dir.empty())
|
||||
if (const char* e = std::getenv("PNKX_NAV_CORE_CONFIG_DIR")) a.config_dir = e;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct MapMeta {
|
||||
std::string image;
|
||||
double resolution = 0.05, origin_x = 0, origin_y = 0, origin_yaw = 0;
|
||||
voronoi_route::MapServerThresholds thr;
|
||||
};
|
||||
|
||||
bool loadMeta(const std::string& yaml_path, MapMeta& m, std::string& err)
|
||||
{
|
||||
try
|
||||
{
|
||||
YAML::Node n = YAML::LoadFile(yaml_path);
|
||||
m.image = n["image"].as<std::string>();
|
||||
m.resolution = n["resolution"].as<double>();
|
||||
const YAML::Node o = n["origin"];
|
||||
m.origin_x = o[0].as<double>();
|
||||
m.origin_y = o[1].as<double>();
|
||||
m.origin_yaw = o.size() > 2 ? o[2].as<double>() : 0.0;
|
||||
m.thr.negate = n["negate"] ? n["negate"].as<int>() != 0 : false;
|
||||
if (n["occupied_thresh"]) m.thr.occupied_thresh = n["occupied_thresh"].as<double>();
|
||||
if (n["free_thresh"]) m.thr.free_thresh = n["free_thresh"].as<double>();
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
err = e.what();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string dirOf(const std::string& path)
|
||||
{
|
||||
const size_t p = path.find_last_of('/');
|
||||
return p == std::string::npos ? std::string(".") : path.substr(0, p);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
Args a;
|
||||
if (!parseArgs(argc, argv, a)) return 2;
|
||||
|
||||
MapMeta meta;
|
||||
std::string err;
|
||||
if (!loadMeta(a.map_yaml, meta, err))
|
||||
{
|
||||
std::fprintf(stderr, "cannot read %s: %s\n", a.map_yaml.c_str(), err.c_str());
|
||||
return 1;
|
||||
}
|
||||
const std::string map_dir = dirOf(a.map_yaml);
|
||||
std::string image_path = a.image_override;
|
||||
if (image_path.empty())
|
||||
image_path = meta.image.front() == '/' ? meta.image : map_dir + "/" + meta.image;
|
||||
else if (image_path.front() != '/' && image_path.find('/') == std::string::npos)
|
||||
image_path = map_dir + "/" + image_path;
|
||||
if (a.out_dir.empty()) a.out_dir = map_dir; // flat, next to the map files; names are voronoi_* so nothing collides
|
||||
|
||||
// UNCHANGED, not GRAYSCALE: the robot's map_server averages ALL channels of a pixel (alpha
|
||||
// included in trinary mode) — a luminance decode of an RGBA map yields a different lethal set,
|
||||
// a different hash, and the consumer rejects the graph. See occupancyFromImage().
|
||||
cv::Mat raw = cv::imread(image_path, cv::IMREAD_UNCHANGED);
|
||||
if (raw.empty())
|
||||
{
|
||||
std::fprintf(stderr, "cannot decode image %s (use --image to point at the real file)\n",
|
||||
image_path.c_str());
|
||||
return 1;
|
||||
}
|
||||
if (raw.depth() != CV_8U)
|
||||
{
|
||||
std::fprintf(stderr, "image %s is not 8-bit per channel (depth %d) — not supported\n",
|
||||
image_path.c_str(), raw.depth());
|
||||
return 1;
|
||||
}
|
||||
if (!raw.isContinuous()) raw = raw.clone();
|
||||
const int w = raw.cols, h = raw.rows, channels = raw.channels();
|
||||
// 8-bit channel average for the human-facing images only; classification uses `raw` in double.
|
||||
cv::Mat img(h, w, CV_8UC1);
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
const uint8_t* src = raw.ptr<uint8_t>(y);
|
||||
uint8_t* dst = img.ptr<uint8_t>(y);
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
int sum = 0;
|
||||
for (int k = 0; k < channels; ++k) sum += src[x * channels + k];
|
||||
dst[x] = static_cast<uint8_t>(sum / channels);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- parameters: YAML first, flags override ---------------------------------------------------
|
||||
voronoi_route::RouteParams prm;
|
||||
std::string params_path = a.params_yaml;
|
||||
if (params_path.empty()) params_path = voronoi_route::findConfigFile(a.config_dir, "voronoi_route_params.yaml");
|
||||
if (!params_path.empty())
|
||||
{
|
||||
std::vector<std::string> notes;
|
||||
if (!voronoi_route::loadRouteParams(params_path, &prm, &err, ¬es))
|
||||
{
|
||||
std::fprintf(stderr, "params: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
for (const auto& n : notes) std::fprintf(stderr, "params: %s\n", n.c_str());
|
||||
}
|
||||
auto ov = [](double& dst, double v) { if (v != kUnset) dst = v; };
|
||||
ov(prm.min_edge_length_m, a.min_edge_m);
|
||||
ov(prm.spur_clearance_ratio, a.spur_ratio);
|
||||
ov(prm.min_component_length_m, a.min_component_m);
|
||||
ov(prm.min_clearance_m, a.min_clearance_m);
|
||||
ov(prm.half_width_min_m, a.half_width_m);
|
||||
ov(prm.clearance_scale, a.clearance_scale);
|
||||
ov(prm.half_width_max_m, a.max_half_width_m);
|
||||
if (a.unknown_override != -1) prm.unknown_is_obstacle = a.unknown_override != 0;
|
||||
if (a.preview >= 0) prm.write_preview = a.preview != 0;
|
||||
if (a.write_dist >= 0) prm.write_dist = a.write_dist != 0;
|
||||
if (a.write_gvd >= 0) prm.write_gvd = a.write_gvd != 0;
|
||||
if (a.graph_image >= 0) prm.write_graph_image = a.graph_image != 0;
|
||||
if (a.graph_overlay >= 0) prm.write_graph_overlay = a.graph_overlay != 0;
|
||||
for (const auto& w : voronoi_route::validateRouteParams(&prm)) std::fprintf(stderr, "params: %s\n", w.c_str());
|
||||
|
||||
const voronoi_route::ObstacleRule rule = prm.toObstacleRule(meta.resolution);
|
||||
const std::string rule_str = voronoi_route::obstacleRuleString(rule);
|
||||
|
||||
voronoi_route::MapConvertStats cs;
|
||||
std::vector<uint8_t> occupied =
|
||||
voronoi_route::occupancyFromImage(raw.ptr<uint8_t>(0), w, h, channels, meta.thr, rule, &cs);
|
||||
const size_t roi_turned = voronoi_route::applyObstacleRoi(occupied, w, h, rule.roi_margin_cells);
|
||||
|
||||
const voronoi_route::VoronoiRoute::Config cfg = prm.toConfig(meta.resolution);
|
||||
voronoi_route::VoronoiRoute vr(cfg);
|
||||
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
vr.rebuild(occupied, w, h);
|
||||
const double total_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
const auto& st = vr.stats();
|
||||
|
||||
std::printf("map : %s (%d x %d @ %.3f m, %d channel(s), origin %.3f %.3f)\n", image_path.c_str(),
|
||||
w, h, meta.resolution, channels, meta.origin_x, meta.origin_y);
|
||||
std::printf("params : %s\n", params_path.empty() ? "built-in defaults (no voronoi_route_params.yaml)" : params_path.c_str());
|
||||
std::printf("rule : %s%s\n", rule_str.c_str(),
|
||||
a.unknown_override != -1 ? " (unknown forced by --unknown-free/--unknown-as-obstacle)" : "");
|
||||
std::printf("cells : lethal=%zu unknown=%zu (%s) free=%zu | roi: %zu cells outside box -> obstacle\n",
|
||||
cs.occupied, cs.unknown,
|
||||
rule.unknown == voronoi_route::UnknownPolicy::kObstacle ? "as obstacle" : "traversable",
|
||||
cs.free, roi_turned);
|
||||
std::printf("voronoi : field %.0f ms, extract %.0f ms, total %.0f ms\n", st.field_ms,
|
||||
st.extract_ms, total_ms);
|
||||
std::printf("graph : gvd_cells=%zu nodes=%d edges=%d components=%d (min_edge=%.1f cells, "
|
||||
"spur_ratio=%.2f, min_component=%.0f cells, min_clearance=%.1f cells)\n",
|
||||
st.gvd_cells, st.nodes, st.edges, st.components, cfg.min_edge_length_cells,
|
||||
cfg.spur_clearance_ratio, cfg.min_component_length_cells, cfg.min_clearance_cells);
|
||||
std::printf("hash : %016llx\n", static_cast<unsigned long long>(vr.occupancyHash()));
|
||||
|
||||
// ---- optional route ------------------------------------------------------------------------
|
||||
auto toCell = [&](double x, double y, bool meters) {
|
||||
if (!meters) return voronoi_route::Cell(static_cast<int>(std::lround(x)), static_cast<int>(std::lround(y)));
|
||||
const double cx = (x - meta.origin_x) / meta.resolution;
|
||||
const double cy_up = (y - meta.origin_y) / meta.resolution;
|
||||
return voronoi_route::Cell(static_cast<int>(std::lround(cx)),
|
||||
static_cast<int>(std::lround(h - 1 - cy_up)));
|
||||
};
|
||||
voronoi_route::Polyline route;
|
||||
std::vector<uint8_t> mask;
|
||||
size_t mask_cells = 0;
|
||||
if (a.have_start && a.have_goal)
|
||||
{
|
||||
const voronoi_route::Cell s = toCell(a.sx, a.sy, a.start_in_meters);
|
||||
const voronoi_route::Cell g = toCell(a.gx, a.gy, a.goal_in_meters);
|
||||
const auto t1 = std::chrono::steady_clock::now();
|
||||
const auto as = vr.attach(s);
|
||||
const auto ag = vr.attach(g);
|
||||
std::printf("attach : start (%d,%d) %s path=%zu | goal (%d,%d) %s path=%zu\n", s.x, s.y,
|
||||
as.ok ? "ok" : "FAIL", as.path.size(), g.x, g.y, ag.ok ? "ok" : "FAIL",
|
||||
ag.path.size());
|
||||
route = vr.query(as, ag);
|
||||
double route_m = 0.0;
|
||||
for (size_t i = 1; i < route.size(); ++i)
|
||||
route_m += ((route[i].x != route[i - 1].x && route[i].y != route[i - 1].y) ? 1.41421356 : 1.0) *
|
||||
meta.resolution;
|
||||
const voronoi_route::CorridorParams cp = prm.toCorridor(meta.resolution);
|
||||
if (!route.empty()) mask = vr.corridorMask(route, cp, &mask_cells);
|
||||
const double q_ms =
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t1).count();
|
||||
const double euclid_m = std::hypot(g.x - s.x, g.y - s.y) * meta.resolution;
|
||||
std::printf("route : %s cells=%zu length=%.1f m (euclid %.1f m) | mask=%zu cells (%.2f%% of map) "
|
||||
"| query+mask %.1f ms\n",
|
||||
route.empty() ? "NONE" : "ok", route.size(), route_m, euclid_m, mask_cells,
|
||||
100.0 * mask_cells / (static_cast<double>(w) * h), q_ms);
|
||||
}
|
||||
|
||||
// ---- bundle ----------------------------------------------------------------------------------
|
||||
voronoi_route::BundleMeta bm;
|
||||
bm.width = w;
|
||||
bm.height = h;
|
||||
bm.resolution = meta.resolution;
|
||||
bm.origin_x = meta.origin_x;
|
||||
bm.origin_y = meta.origin_y;
|
||||
bm.origin_yaw = meta.origin_yaw;
|
||||
bm.source = "costmap:" + rule_str;
|
||||
bm.map_hash = vr.occupancyHash();
|
||||
if (!voronoi_route::saveBundle(vr, bm, a.out_dir, prm.write_gvd, prm.write_dist, &err))
|
||||
{
|
||||
std::fprintf(stderr, "bundle: %s\n", err.c_str());
|
||||
return 1;
|
||||
}
|
||||
if (!route.empty()) voronoi_route::appendRouteToBundle(a.out_dir, route, mask_cells, nullptr);
|
||||
|
||||
// ---- preview ---------------------------------------------------------------------------------
|
||||
if (prm.write_preview)
|
||||
{
|
||||
cv::Mat pv(h, w, CV_8UC3);
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
const uint8_t* row = img.ptr<uint8_t>(y);
|
||||
cv::Vec3b* prow = pv.ptr<cv::Vec3b>(y);
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const double p = row[x];
|
||||
const double occ = meta.thr.negate ? p / 255.0 : (255.0 - p) / 255.0;
|
||||
if (occ > meta.thr.occupied_thresh) prow[x] = cv::Vec3b(0, 0, 0);
|
||||
else if (occ >= meta.thr.free_thresh) prow[x] = cv::Vec3b(200, 200, 200);
|
||||
else prow[x] = cv::Vec3b(255, 255, 255);
|
||||
}
|
||||
}
|
||||
if (!mask.empty())
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
if (mask[static_cast<size_t>(y) * w + x])
|
||||
{
|
||||
cv::Vec3b& px = pv.at<cv::Vec3b>(y, x);
|
||||
px = cv::Vec3b(static_cast<uint8_t>(px[0] * 0.55), static_cast<uint8_t>(px[1] * 0.75 + 60),
|
||||
static_cast<uint8_t>(px[2] * 0.75 + 60));
|
||||
}
|
||||
// Raw GVD in pale pink (what the diagram is), graph edges in red (what survives pruning and
|
||||
// is actually routed on). The difference is the pruning at work.
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x)
|
||||
if (vr.field().isVoronoi(x, y)) pv.at<cv::Vec3b>(y, x) = cv::Vec3b(210, 190, 255);
|
||||
for (const auto& e : vr.graph().edges())
|
||||
for (const auto& c : e.cells) pv.at<cv::Vec3b>(c.y, c.x) = cv::Vec3b(0, 0, 255);
|
||||
const int r = std::max(2, std::min(w, h) / 600);
|
||||
for (const auto& nd : vr.graph().nodes())
|
||||
cv::circle(pv, cv::Point(nd.cell.x, nd.cell.y), r, cv::Scalar(0, 180, 0), -1);
|
||||
for (size_t i = 1; i < route.size(); ++i)
|
||||
cv::line(pv, cv::Point(route[i - 1].x, route[i - 1].y), cv::Point(route[i].x, route[i].y),
|
||||
cv::Scalar(255, 0, 0), std::max(1, r - 1));
|
||||
if (a.have_start && a.have_goal)
|
||||
{
|
||||
const auto s = toCell(a.sx, a.sy, a.start_in_meters);
|
||||
const auto g = toCell(a.gx, a.gy, a.goal_in_meters);
|
||||
cv::circle(pv, cv::Point(s.x, s.y), r * 3, cv::Scalar(255, 0, 255), 2);
|
||||
cv::circle(pv, cv::Point(g.x, g.y), r * 3, cv::Scalar(255, 128, 0), 2);
|
||||
}
|
||||
if (!cv::imwrite(a.out_dir + "/voronoi_preview.png", pv))
|
||||
std::fprintf(stderr, "warning: cannot write voronoi_preview.png\n");
|
||||
}
|
||||
|
||||
// ---- graph on the real map image ---------------------------------------------------------------
|
||||
// Unlike the preview this keeps map.png's own pixels: what the operator sees is the scan, with the
|
||||
// pruned graph on top. Junctions green, dead ends blue, edges red. The overlay variant is the same
|
||||
// drawing on a transparent background for a web layer stacked over map.png.
|
||||
if (prm.write_graph_image || prm.write_graph_overlay)
|
||||
{
|
||||
const int t = std::max(1, std::min(w, h) / 1200);
|
||||
const int r = std::max(2, std::min(w, h) / 600);
|
||||
auto draw = [&](cv::Mat& canvas, const cv::Scalar& edge, const cv::Scalar& junction,
|
||||
const cv::Scalar& leaf) {
|
||||
for (const auto& e : vr.graph().edges())
|
||||
for (size_t i = 1; i < e.cells.size(); ++i)
|
||||
cv::line(canvas, cv::Point(e.cells[i - 1].x, e.cells[i - 1].y),
|
||||
cv::Point(e.cells[i].x, e.cells[i].y), edge, t, cv::LINE_8);
|
||||
for (const auto& nd : vr.graph().nodes())
|
||||
cv::circle(canvas, cv::Point(nd.cell.x, nd.cell.y), r,
|
||||
nd.edges.size() == 1 ? leaf : junction, -1);
|
||||
};
|
||||
if (prm.write_graph_image)
|
||||
{
|
||||
cv::Mat base;
|
||||
cv::cvtColor(img, base, cv::COLOR_GRAY2BGR);
|
||||
draw(base, cv::Scalar(0, 0, 255), cv::Scalar(0, 180, 0), cv::Scalar(255, 120, 0));
|
||||
if (!cv::imwrite(a.out_dir + "/voronoi_graph.png", base))
|
||||
std::fprintf(stderr, "warning: cannot write voronoi_graph.png\n");
|
||||
}
|
||||
if (prm.write_graph_overlay)
|
||||
{
|
||||
cv::Mat ov(h, w, CV_8UC4, cv::Scalar(0, 0, 0, 0));
|
||||
draw(ov, cv::Scalar(0, 0, 255, 255), cv::Scalar(0, 180, 0, 255), cv::Scalar(255, 120, 0, 255));
|
||||
if (!cv::imwrite(a.out_dir + "/voronoi_graph_overlay.png", ov))
|
||||
std::fprintf(stderr, "warning: cannot write voronoi_graph_overlay.png\n");
|
||||
}
|
||||
}
|
||||
|
||||
std::printf("bundle : %s/{voronoi.json%s%s%s%s%s}\n", a.out_dir.c_str(),
|
||||
prm.write_gvd ? ", voronoi_gvd.pgm" : "", prm.write_dist ? ", voronoi_dist.pgm" : "",
|
||||
prm.write_preview ? ", voronoi_preview.png" : "",
|
||||
prm.write_graph_image ? ", voronoi_graph.png" : "",
|
||||
prm.write_graph_overlay ? ", voronoi_graph_overlay.png" : "");
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user