#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace lane_route_planner; using namespace lane_route_core; using namespace robot_costmap_2d; namespace { robot_geometry_msgs::PoseStamped pose(double x, double y, double yaw = 0) { robot_geometry_msgs::PoseStamped p; p.header.frame_id = "map"; p.pose.position.x = x; p.pose.position.y = y; p.pose.orientation.z = std::sin(yaw / 2); p.pose.orientation.w = std::cos(yaw / 2); return p; } SessionRequest validRequest(std::vector& cost) { SessionRequest r; r.initialized = true; r.frame = "map"; r.live.width = 40; r.live.height = 40; r.live.resolution = 0.05; r.live.cost = cost.data(); auto graph = std::make_shared(); graph->geometry = { 40, 40, 0.05, 0, 0, "map" }; graph->static_cost = cost; graph->clearance_mm.assign(cost.size(), 1000); r.graph = { ReferenceGraphState::kReady, graph, 1 }; r.footprint = rectangleFootprint(0.30, 0.30); r.inscribed_radius_m = 0.30; r.start = pose(0.6, 0.6); r.goal = pose(1.2, 1.2); return r; } TEST(AdapterGuard, NotInitialized) { std::vector c(1600, 60); auto r = validRequest(c); r.initialized = false; EXPECT_EQ(validateRequest(r), "not_initialized"); } TEST(AdapterGuard, InvalidStart) { std::vector c(1600, 60); auto r = validRequest(c); r.start.pose.orientation.w = std::numeric_limits::quiet_NaN(); EXPECT_EQ(validateRequest(r), "invalid_start_pose"); } TEST(AdapterGuard, InvalidGoal) { std::vector c(1600, 60); auto r = validRequest(c); r.goal.pose.position.x = std::numeric_limits::infinity(); EXPECT_EQ(validateRequest(r), "invalid_goal_pose"); } TEST(AdapterGuard, Frame) { std::vector c(1600, 60); auto r = validRequest(c); r.goal.header.frame_id = "odom"; EXPECT_EQ(validateRequest(r), "frame_mismatch"); } TEST(AdapterGuard, DisabledGraph) { std::vector c(1600, 60); auto r = validRequest(c); r.graph.state = ReferenceGraphState::kDisabled; EXPECT_EQ(validateRequest(r), "graph_disabled"); } TEST(AdapterGuard, PendingGraph) { std::vector c(1600, 60); auto r = validRequest(c); r.graph.state = ReferenceGraphState::kPending; EXPECT_EQ(validateRequest(r), "graph_pending"); } TEST(AdapterGuard, PendingDirection) { std::vector c(1600, 60); auto r = validRequest(c); r.direction.state = DirectionFieldState::kPending; EXPECT_EQ(validateRequest(r), "direction_pending"); } TEST(AdapterGuard, MissingReadyGraph) { std::vector c(1600, 60); auto r = validRequest(c); r.graph.graph.reset(); EXPECT_EQ(validateRequest(r), "graph_pending"); } TEST(AdapterGuard, MissingReadyDirection) { std::vector c(1600, 60); auto r = validRequest(c); r.direction.state = DirectionFieldState::kReady; EXPECT_EQ(validateRequest(r), "direction_pending"); } TEST(AdapterGuard, DirectionGeneration) { std::vector c(1600, 60); auto r = validRequest(c); r.direction.generation = 2; EXPECT_EQ(validateRequest(r), "direction_generation_mismatch"); } TEST(AdapterGuard, Geometry) { std::vector c(1600, 60); auto r = validRequest(c); r.live.origin_x = 1; EXPECT_EQ(validateRequest(r), "graph_geometry_mismatch"); } TEST(AdapterGuard, Footprint) { std::vector c(1600, 60); auto r = validRequest(c); r.footprint.resize(2); EXPECT_EQ(validateRequest(r), "invalid_footprint"); } TEST(AdapterGuard, InvalidSnapshotData) { std::vector c(1600, 60); auto r = validRequest(c); auto g = std::make_shared(*r.graph.graph); g->clearance_mm.clear(); r.graph.graph = g; EXPECT_EQ(validateRequest(r), "graph_data_invalid"); } TEST(AdapterGuard, InvalidRadius) { std::vector c(1600, 60); auto r = validRequest(c); r.inscribed_radius_m = -1; EXPECT_EQ(validateRequest(r), "invalid_inscribed_radius"); } TEST(AdapterGuard, StateDoesNotRequireGrid) { std::vector c(1600, 60); auto r = validRequest(c); r.live = {}; EXPECT_TRUE(validateState(r).empty()); EXPECT_EQ(validateGrid(r), "graph_geometry_mismatch"); EXPECT_EQ(validateRequest(r), "graph_geometry_mismatch"); r.initialized = false; EXPECT_EQ(validateRequest(r), "not_initialized"); } TEST(AdapterConfig, RejectsInvalidParameters) { SessionConfig c; c.clearance_min_margin_m = -1; const std::string invalid_margin = c.validate(); EXPECT_NE(invalid_margin.find("clearance_min_margin_m"), std::string::npos); EXPECT_NE(invalid_margin.find("-1"), std::string::npos); c = SessionConfig(); c.clearance_min_margin_m = 0.2; c.clearance_preferred_margin_m = 0.1; const std::string inverted_margins = c.validate(); EXPECT_NE(inverted_margins.find("clearance_preferred_margin_m"), std::string::npos); EXPECT_NE(inverted_margins.find("0.1"), std::string::npos); EXPECT_NE(inverted_margins.find("clearance_min_margin_m"), std::string::npos); EXPECT_NE(inverted_margins.find("0.2"), std::string::npos); c = SessionConfig(); c.clearance_preferred_margin_m = -0.5; const std::string invalid_preferred = c.validate(); EXPECT_NE(invalid_preferred.find("clearance_preferred_margin_m"), std::string::npos); EXPECT_NE(invalid_preferred.find("-0.5"), std::string::npos); c = SessionConfig(); c.collision_check_margin_m = -0.25; const std::string invalid_collision = c.validate(); EXPECT_NE(invalid_collision.find("collision_check_margin_m"), std::string::npos); EXPECT_NE(invalid_collision.find("-0.25"), std::string::npos); c = SessionConfig(); c.planner.min_turn_radius_m = 0; EXPECT_FALSE(c.validate().empty()); c = SessionConfig(); c.planner.zone_transition_m = -0.01; EXPECT_FALSE(c.validate().empty()); c = SessionConfig(); c.planner.max_route_attempts = 0; EXPECT_FALSE(c.validate().empty()); c = SessionConfig(); c.planner.time_limit_s = std::numeric_limits::infinity(); EXPECT_FALSE(c.validate().empty()); } TEST(AdapterConfig, LatticeYamlReachesPlannerConfig) { robot::NodeHandle root; root.setParam("LaneRouteLatticeConfigTest", YAML::Load(R"( lattice_enabled: true zone_transition_m: 0.7 lattice_preferred_gap_m: 0.18 lattice_preferred_time_fraction: 0.35 lattice_smooth_enabled: false lattice_smooth_max_checks: 123456 lattice_heading_bins: 64 lattice_closed_resolution_m: 0.2 lattice_heuristic_weight: 2.0 lattice_bucket_width_m: 0.3 lattice_field_clearance_weight_m: 0.4 lattice_wall_weight_m: 0.5 lattice_switch_cost_m: 0.6 lattice_steer_cost_m: 0.02 lattice_primitive_multiple_1: 1 lattice_primitive_multiple_2: 2 lattice_primitive_multiple_3: 4 lattice_analytic_radius_m: 1.2 lattice_analytic_interval: 123 lattice_analytic_near_goal_m: 1.5 lattice_analytic_goal_headings: 8 lattice_field_standability_relax_m: 0.035 lattice_field_time_fraction: 0.3 lattice_field_cell_factor: 2 lattice_field_max_cells: 123456 fallback_time_limit_s: 2.0 lattice_end_relax_radius_m: 0.8 lattice_max_memory_mb: 256 debug: {fallback: false} )")); robot::NodeHandle nh(root, "LaneRouteLatticeConfigTest"); const SessionConfig config = loadSessionConfig(nh); const auto& p = config.planner; EXPECT_TRUE(config.validate().empty()); EXPECT_TRUE(p.lattice_enabled); EXPECT_DOUBLE_EQ(p.zone_transition_m, 0.7); EXPECT_DOUBLE_EQ(p.lattice_preferred_gap_m, 0.18); EXPECT_DOUBLE_EQ(p.lattice_preferred_time_fraction, 0.35); EXPECT_FALSE(p.lattice_smooth_enabled); EXPECT_EQ(p.lattice_smooth_max_checks, 123456); EXPECT_EQ(p.lattice_heading_bins, 64); EXPECT_DOUBLE_EQ(p.lattice_closed_resolution_m, 0.2); EXPECT_DOUBLE_EQ(p.lattice_heuristic_weight, 2.0); EXPECT_DOUBLE_EQ(p.lattice_bucket_width_m, 0.3); EXPECT_DOUBLE_EQ(p.lattice_field_clearance_weight_m, 0.4); EXPECT_DOUBLE_EQ(p.lattice_wall_weight_m, 0.5); EXPECT_DOUBLE_EQ(p.lattice_switch_cost_m, 0.6); EXPECT_DOUBLE_EQ(p.lattice_steer_cost_m, 0.02); EXPECT_EQ(p.lattice_primitive_multiple_1, 1); EXPECT_EQ(p.lattice_primitive_multiple_2, 2); EXPECT_EQ(p.lattice_primitive_multiple_3, 4); EXPECT_DOUBLE_EQ(p.lattice_analytic_radius_m, 1.2); EXPECT_EQ(p.lattice_analytic_interval, 123); EXPECT_DOUBLE_EQ(p.lattice_analytic_near_goal_m, 1.5); EXPECT_EQ(p.lattice_analytic_goal_headings, 8); EXPECT_DOUBLE_EQ(p.lattice_field_standability_relax_m, 0.035); EXPECT_DOUBLE_EQ(p.lattice_field_time_fraction, 0.3); EXPECT_EQ(p.lattice_field_cell_factor, 2); EXPECT_EQ(p.lattice_field_max_cells, 123456); EXPECT_DOUBLE_EQ(p.fallback_time_limit_s, 2.0); EXPECT_DOUBLE_EQ(p.lattice_end_relax_radius_m, 0.8); EXPECT_EQ(p.lattice_max_memory_mb, 256); EXPECT_FALSE(config.debug_fallback); root.setParam("LaneRouteLatticeDefaultsTest", YAML::Load("{other: 1}")); const auto defaults = loadSessionConfig(robot::NodeHandle(root, "LaneRouteLatticeDefaultsTest")); const PlannerConfig expected; EXPECT_FALSE(defaults.planner.lattice_enabled); EXPECT_DOUBLE_EQ(defaults.planner.zone_transition_m, 1.0); EXPECT_FALSE(defaults.output_endpoint_spins); EXPECT_EQ(defaults.planner.lattice_heading_bins, expected.lattice_heading_bins); EXPECT_DOUBLE_EQ(defaults.planner.lattice_preferred_gap_m, expected.lattice_preferred_gap_m); EXPECT_DOUBLE_EQ(defaults.planner.lattice_preferred_time_fraction, expected.lattice_preferred_time_fraction); EXPECT_EQ(defaults.planner.lattice_smooth_enabled, expected.lattice_smooth_enabled); EXPECT_EQ(defaults.planner.lattice_smooth_max_checks, expected.lattice_smooth_max_checks); EXPECT_DOUBLE_EQ(defaults.planner.fallback_time_limit_s, expected.fallback_time_limit_s); EXPECT_DOUBLE_EQ(defaults.planner.lattice_field_standability_relax_m, 0.0); EXPECT_EQ(defaults.planner.lattice_field_max_cells, expected.lattice_field_max_cells); EXPECT_EQ(defaults.planner.lattice_max_memory_mb, expected.lattice_max_memory_mb); EXPECT_TRUE(defaults.debug_fallback); // A non-default first primitive is invalid, but must still reach core validation. root.setParam("LaneRouteBadPrimitiveTest", YAML::Load("{lattice_enabled: true, lattice_primitive_multiple_1: 2}")); const auto invalid = loadSessionConfig(robot::NodeHandle(root, "LaneRouteBadPrimitiveTest")); EXPECT_EQ(invalid.planner.lattice_primitive_multiple_1, 2); EXPECT_NE(invalid.validate().find("lattice primitive multiples"), std::string::npos); } TEST(AdapterConfig, InvalidLatticeRejectsPluginInitialization) { robot::NodeHandle root; root.setParam("LaneRouteInvalidLatticeTest", YAML::Load("{lattice_enabled: true, lattice_heading_bins: 7}")); LaneRoutePlanner planner; testing::internal::CaptureStdout(); const bool initialized = planner.initialize("LaneRouteInvalidLatticeTest", nullptr); const std::string log = testing::internal::GetCapturedStdout(); EXPECT_FALSE(initialized); EXPECT_NE(log.find("invalid configuration: lattice_heading_bins must be even and in [8, 1024]"), std::string::npos); root.setParam("LaneRouteDisabledInvalidLatticeTest", YAML::Load("{lattice_enabled: false, lattice_heading_bins: 7}")); LaneRoutePlanner disabled; testing::internal::CaptureStdout(); const bool disabled_initialized = disabled.initialize("LaneRouteDisabledInvalidLatticeTest", nullptr); const std::string disabled_log = testing::internal::GetCapturedStdout(); EXPECT_FALSE(disabled_initialized); EXPECT_NE(disabled_log.find("invalid configuration: lattice_heading_bins must be even and in [8, 1024]"), std::string::npos); // A minimum gap above the preferred gap only switches the preferred pass off; it must not stop initialisation. root.setParam("LaneRouteWideMinimumGapTest", YAML::Load("{lattice_enabled: true, footprint_min_gap_m: 0.20}")); LaneRoutePlanner wide_gap; testing::internal::CaptureStdout(); EXPECT_FALSE(wide_gap.initialize("LaneRouteWideMinimumGapTest", nullptr)); const std::string wide_gap_log = testing::internal::GetCapturedStdout(); EXPECT_EQ(wide_gap_log.find("invalid configuration"), std::string::npos); EXPECT_NE(wide_gap_log.find("missing costmap"), std::string::npos); // A broken smoother budget is rejected even while the lattice is off. root.setParam("LaneRouteDisabledSmoothTest", YAML::Load("{lattice_enabled: false, lattice_smooth_max_checks: -1}")); LaneRoutePlanner disabled_smooth; testing::internal::CaptureStdout(); EXPECT_FALSE(disabled_smooth.initialize("LaneRouteDisabledSmoothTest", nullptr)); const std::string disabled_smooth_log = testing::internal::GetCapturedStdout(); EXPECT_NE(disabled_smooth_log.find("invalid configuration"), std::string::npos); root.setParam("LaneRouteBadFieldRelaxTest", YAML::Load("{lattice_enabled: false, lattice_field_standability_relax_m: -0.001}")); LaneRoutePlanner bad_field_relax; testing::internal::CaptureStdout(); EXPECT_FALSE(bad_field_relax.initialize("LaneRouteBadFieldRelaxTest", nullptr)); const std::string bad_field_relax_log = testing::internal::GetCapturedStdout(); EXPECT_NE(bad_field_relax_log.find("lattice_field_standability_relax_m"), std::string::npos); } TEST(AdapterLog, FallbackSwitchDoesNotSuppressFailure) { robot::NodeHandle root; root.setParam("LaneRouteFallbackLogTest", YAML::Load("{debug: {fallback: false}}")); const auto config = loadSessionConfig(robot::NodeHandle(root, "LaneRouteFallbackLogTest")); PlanResult result; result.info.reason = "lattice_exhausted"; result.info.graph_reason = "no_route"; result.info.lattice_reason = "lattice_exhausted"; result.info.lattice_ms = 1.0; result.info.lattice_gap_pass = "minimum"; result.info.min_gap_m = 0.08; result.info.lattice_upgrade_ms = 12.3; result.info.lattice_rung_reasons.push_back(result.info.lattice_reason); testing::internal::CaptureStdout(); logPlanResult(result, config.debug_fallback); const std::string quiet = testing::internal::GetCapturedStdout(); EXPECT_EQ(quiet.find("[debug] fallback tier="), std::string::npos); EXPECT_NE(quiet.find("plan failed: lattice_exhausted"), std::string::npos); testing::internal::CaptureStdout(); logPlanResult(result, true); const std::string verbose = testing::internal::GetCapturedStdout(); EXPECT_NE(verbose.find("[debug] fallback tier=none"), std::string::npos); EXPECT_NE(verbose.find("gap_pass=minimum min_gap_m=0.080"), std::string::npos); EXPECT_NE(verbose.find("upgrade=12.3ms"), std::string::npos); EXPECT_NE(verbose.find("plan failed: lattice_exhausted"), std::string::npos); result.info.lattice_ms = 0.0; testing::internal::CaptureStdout(); logPlanResult(result, true); const std::string no_lattice = testing::internal::GetCapturedStdout(); EXPECT_EQ(no_lattice.find("[debug] fallback tier="), std::string::npos); EXPECT_NE(no_lattice.find("plan failed: lattice_exhausted"), std::string::npos); } TEST(AdapterConfig, FootprintBoundsAndCollisionDistances) { double x, y; bool rectangle; auto points = rectangleFootprint(0.30, 0.30); ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); EXPECT_TRUE(rectangle); EXPECT_NEAR(std::hypot(x, y) + 0.056, 0.48, 0.001); points = rectangleFootprint(0.325, 0.345); ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); EXPECT_NEAR(std::hypot(x, y) + 0.056, 0.53, 0.001); points[0].x = 0.1; ASSERT_TRUE(footprintRectangle(points, &x, &y, &rectangle)); EXPECT_FALSE(rectangle); } TEST(AdapterSession, ZeroDeviationUsesOneRung) { std::vector c(1600, 60); auto r = validRequest(c); robot_nav_msgs::OccupancyGrid msg; msg.header.frame_id = "map"; msg.info.width = 40; msg.info.height = 40; msg.info.resolution = 0.05; msg.data.assign(1600, 1); r.direction = { DirectionFieldState::kReady, DirectionField::create(msg, r.graph.graph->geometry, 0.0), 1 }; ASSERT_TRUE(r.direction.field); auto graph = std::make_shared(*r.graph.graph); graph->direction_generation = 1; r.graph.graph = graph; r.goal = pose(1.2, 0.6); LaneRouteSession session; const auto result = session.plan(r); EXPECT_LE(result.info.rung_reasons.size(), 1u); if (result.ok) EXPECT_DOUBLE_EQ(result.info.rung_used_deg, 0.0); } TEST(AdapterSession, CacheDroppedOnGenerationChange) { std::vector c(1600, 60); auto r = validRequest(c); LaneRouteSession session; session.plan(r); ASSERT_GT(session.cachedGraphCount(), 0u); const auto compiled = session.compileCount(); EXPECT_EQ(session.cachedGeneration(), 1u); r.graph.generation++; std::atomic cancel{ true }; r.cancel = &cancel; // A cancelled request is refused before mutating the cache; the next real request drops it. EXPECT_EQ(session.plan(r).info.reason, "cancelled"); cancel = false; r.live.cost = c.data(); session.plan(r); EXPECT_GT(session.cachedGraphCount(), 0u); EXPECT_EQ(session.cachedGeneration(), 2u); EXPECT_GT(session.compileCount(), compiled); } TEST(AdapterSession, PreferredChangesInvalidateCache) { std::vector c(1600, 60); auto r = validRequest(c); LaneRouteSession session; session.plan(r); const auto n = session.compileCount(); ASSERT_GT(n, 0u); session.plan(r); EXPECT_EQ(session.compileCount(), n); c[0] = 100; session.plan(r); EXPECT_EQ(session.compileCount(), n); c[0] = 20; session.plan(r); const auto preferred_count = session.compileCount(); EXPECT_GT(preferred_count, n); session.plan(r); EXPECT_EQ(session.compileCount(), preferred_count); c[0] = 60; c[1] = 20; session.plan(r); const auto moved_count = session.compileCount(); EXPECT_GT(moved_count, preferred_count); c[1] = 60; session.plan(r); const auto cleared_count = session.compileCount(); EXPECT_GT(cleared_count, moved_count); session.plan(r); EXPECT_EQ(session.compileCount(), cleared_count); } TEST(AdapterSession, PreemptAndNextCall) { std::vector c(1600, 60); auto r = validRequest(c); auto graph = std::make_shared(*r.graph.graph); graph->nodes.resize(1000000, ReferencePoint{ 0.5, 0.5 }); r.graph.graph = graph; LaneRouteSession session; std::atomic cancel{ false }; r.cancel = &cancel; PlanResult result; std::atomic started{ false }; const auto begin = std::chrono::steady_clock::now(); std::thread worker([&] { started = true; result = session.plan(r); }); while (!started.load()) std::this_thread::yield(); std::this_thread::sleep_for(std::chrono::milliseconds(2)); cancel = true; worker.join(); EXPECT_EQ(result.info.reason, "cancelled"); EXPECT_LT(std::chrono::duration(std::chrono::steady_clock::now() - begin).count(), 5.0); cancel = false; r.graph = validRequest(c).graph; r.graph.generation = 2; EXPECT_NE(session.plan(r).info.reason, "cancelled"); } std::vector readRuns(std::istream& in, const std::string& expected) { std::string key; std::size_t n; in >> key >> n; if (key != expected) throw std::runtime_error("expected " + expected + ", got " + key); std::vector values; for (std::size_t i = 0; i < n; ++i) { int value; std::size_t count; in >> value >> count; values.insert(values.end(), count, static_cast(value)); } return values; } struct Fixture { DirectionGeometry geometry{}; ReferenceGraphParams params; std::vector cost; std::vector direction; std::shared_ptr graph; }; Fixture loadFixture(const std::string& path) { std::ifstream in(path); if (!in) throw std::runtime_error("cannot open fixture " + path); Fixture f; std::string key; int version; double hx, hy; in >> key >> version; if (key != "reference_graph_fixture" || version != 1) throw std::runtime_error("bad fixture"); in >> key >> f.geometry.width >> f.geometry.height >> key >> f.geometry.resolution >> key >> f.geometry.origin_x >> f.geometry.origin_y; in >> key >> f.params.min_clearance_m >> f.params.ridge_min_separation_m >> f.params.spur_min_length_m >> f.params.lane_offset_step_m >> hx >> hy; f.geometry.frame_id = "map"; f.params.debug_log = false; f.cost = readRuns(in, "cost"); f.direction = readRuns(in, "direction"); ReferenceGridView view; view.geometry = f.geometry; view.cost = f.cost.data(); view.direction_codes = f.direction.data(); const auto skeleton = computeVoronoiSkeleton(view, f.params); f.graph = std::make_shared(buildReferenceGraph(view, skeleton, rectangleFootprint(hx, hy), f.params)); return f; } struct Scene { std::string id; Pose2 start; Pose2 goal; }; std::vector loadScenes(const std::string& path) { std::ifstream in(path); if (!in) throw std::runtime_error("cannot open scenes " + path); std::vector scenes; std::string line; while (std::getline(in, line)) { if (line.empty()) continue; std::istringstream row(line); Scene s; std::string grid, live; int variant, sy, gy, boxes; row >> s.id >> grid >> variant >> live >> sy >> s.start.x >> s.start.y >> s.start.yaw >> gy >> s.goal.x >> s.goal.y >> s.goal.yaw >> boxes; if (!row || variant != 0 || live != "-" || boxes != 0) throw std::runtime_error("unsupported real scene"); s.start.has_yaw = sy != 0; s.goal.has_yaw = gy != 0; scenes.push_back(s); } return scenes; } std::vector loadEvalMaster(const std::string& path) { std::ifstream in(path); if (!in) throw std::runtime_error("cannot open eval grid"); std::string key; int version, w, h; double res, ox, oy; in >> key >> version >> key >> w >> h >> key >> res >> key >> ox >> oy; return readRuns(in, "cost"); } std::vector inflated(const Fixture& f) { auto cost = f.cost; for (std::size_t i = 0; i < cost.size(); ++i) { if (cost[i] >= kInscribedCost) continue; const double rounded_cells = f.graph->clearance_mm[i] / (1000.0 * f.geometry.resolution); const double d = f.geometry.resolution * std::sqrt(std::round(rounded_cells * rounded_cells)); if (d > 0.6) continue; unsigned value = d <= 0.30 ? kInscribedCost : static_cast(252.0 * std::exp(-15.0 * (d - 0.30))); cost[i] = std::max(cost[i], static_cast(value)); } return cost; } DirectionFieldSnapshot direction(const Fixture& f, double degrees, uint64_t generation) { robot_nav_msgs::OccupancyGrid msg; msg.header.frame_id = "map"; msg.info.width = f.geometry.width; msg.info.height = f.geometry.height; msg.info.resolution = f.geometry.resolution; msg.info.origin.position.x = f.geometry.origin_x; msg.info.origin.position.y = f.geometry.origin_y; msg.data.assign(f.direction.begin(), f.direction.end()); return { DirectionFieldState::kReady, DirectionField::create(msg, f.geometry, degrees * kPi / 180.0), generation }; } using Json = nlohmann::json; std::map, Json> loadReference(const std::string& path) { std::ifstream in(path); if (!in) throw std::runtime_error("cannot open reference " + path); std::map, Json> refs; std::string line; while (std::getline(in, line)) { std::size_t pos = 0; while ((pos = line.find(":inf", pos)) != std::string::npos) line.replace(pos, 4, ":null"); Json j = Json::parse(line); // In C++17 the right side of an assignment runs first, so the key must be read before j is moved. const std::pair key(j.at("scene").get(), j.at("dev").get()); refs[key] = std::move(j); } return refs; } void runParity(bool real_inflation) { const char* env = std::getenv("LANE_ROUTE_FIXTURE_DIR"); if (!env) { // The installed gtest predates GTEST_SKIP. std::cout << "[ SKIPPED ] Set LANE_ROUTE_FIXTURE_DIR to oneway_eval/results" << std::endl; return; } const std::string base(env); const auto fixture = loadFixture(base + "/r12_cpp_fixtures/text/sehc.fixture"); auto master = real_inflation ? inflated(fixture) : loadEvalMaster(base + "/r12_cpp_eval/sehc.grid"); const auto scenes = loadScenes(base + "/r12_cpp_eval/sehc_real.txt"); const auto refs = loadReference(base + "/r15_cpp_eval/out_real.jsonl"); ASSERT_EQ(scenes.size(), 12u); ASSERT_EQ(refs.size(), 60u); SessionConfig config; config.collision_check_margin_m = 0.48 - std::hypot(0.30, 0.30); LaneRouteSession session(config); const double levels[] = { 90, 45, 22.5, 135, 179 }; uint64_t generation = 0; for (double level : levels) { ++generation; auto g = std::make_shared(*fixture.graph); g->direction_generation = generation; const auto field = direction(fixture, level, generation); ASSERT_TRUE(field.field); for (const auto& s : scenes) { SCOPED_TRACE(s.id + " level=" + std::to_string(level)); SessionRequest r; r.initialized = true; r.frame = "map"; r.graph = { ReferenceGraphState::kReady, g, generation }; r.direction = field; r.live.width = fixture.geometry.width; r.live.height = fixture.geometry.height; r.live.resolution = fixture.geometry.resolution; r.live.origin_x = fixture.geometry.origin_x; r.live.origin_y = fixture.geometry.origin_y; r.live.cost = master.data(); r.footprint = rectangleFootprint(0.3, 0.3); r.inscribed_radius_m = 0.3; r.start = pose(s.start.x, s.start.y, s.start.yaw); r.goal = pose(s.goal.x, s.goal.y, s.goal.yaw); r.start_has_yaw = s.start.has_yaw; r.goal_has_yaw = s.goal.has_yaw; const auto found = refs.find({ s.id, level }); ASSERT_NE(found, refs.end()); const PlanResult result = session.plan(r); const Json& ref = found->second; ASSERT_EQ(result.ok, ref.at("ok").get() != 0) << result.info.reason; EXPECT_EQ(result.info.reason, ref.at("reason").get()); if (!result.ok) continue; EXPECT_TRUE(result.check.valid); const auto& path = ref.at("path"); ASSERT_EQ(result.path.size(), path.size()); for (std::size_t i = 0; i < result.path.size(); ++i) { EXPECT_NEAR(result.path[i].x, path[i][0].get(), 1e-8); EXPECT_NEAR(result.path[i].y, path[i][1].get(), 1e-8); EXPECT_NEAR(result.path[i].yaw, path[i][2].get(), 1e-8); } } } } TEST(AdapterParity, RealCalls) { runParity(false); } TEST(AdapterParity, Inflation) { runParity(true); } TEST(AdapterDump, FailureDumpIsReadableRunLengthText) { // 4 x 3 grid: one lethal cell, one zone cell. The replay tool reads " " and then value/count pairs. std::vector master{ 60, 60, 254, 60, 60, 60, 60, 60, 253, 60, 60, 60 }; const std::vector static_cost{ 0, 0, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; std::vector directions(12, 0); directions[5] = 3; GridRef live; live.width = 4; live.height = 3; live.resolution = 0.05; live.origin_x = -1.5; live.origin_y = 2.25; live.cost = master.data(); RouteRequest route; route.start = { 0.1, 0.2, 0.3, true }; route.goal = { 0.4, 0.5, 0.0, false }; PlannerConfig config; config.max_deviation_deg = 22.5; PlanResult result; result.info.reason = "lattice_timeout"; const std::string dir = (std::filesystem::temp_directory_path() / "lane_route_dump_test").string(); const std::string stem = writeFailureDump(dir, "case", live, static_cost, directions, route, config, result); ASSERT_EQ(stem, dir + "/case"); std::ifstream grid(stem + ".grid"); std::string key; int version = 0, width = 0, height = 0, runs = 0, variants = 0; double resolution = 0.0, ox = 0.0, oy = 0.0; grid >> key >> version >> key >> width >> height >> key >> resolution >> key >> ox >> oy >> key >> runs; EXPECT_EQ(width, 4); EXPECT_EQ(height, 3); EXPECT_DOUBLE_EQ(resolution, 0.05); EXPECT_DOUBLE_EQ(ox, -1.5); EXPECT_DOUBLE_EQ(oy, 2.25); EXPECT_EQ(key, "cost"); EXPECT_EQ(runs, 3); // 0 x2, 254 x1, 0 x9 int value = 0, count = 0, total = 0; for (int i = 0; i < runs; ++i) { grid >> value >> count; total += count; } EXPECT_EQ(total, 12); grid >> key >> variants >> key >> runs; EXPECT_EQ(variants, 1); EXPECT_EQ(key, "direction"); EXPECT_EQ(runs, 3); std::ifstream scene(stem + ".scene"); std::string id, grid_file, live_file; int variant = -1, has_start = -1, has_goal = -1, boxes = -1; double sx, sy, syaw, gx, gy, gyaw; scene >> id >> grid_file >> variant >> live_file >> has_start >> sx >> sy >> syaw >> has_goal >> gx >> gy >> gyaw >> boxes; EXPECT_EQ(id, "case"); EXPECT_EQ(grid_file, stem + ".grid"); EXPECT_EQ(live_file, stem + ".live"); EXPECT_EQ(has_start, 1); EXPECT_DOUBLE_EQ(syaw, 0.3); EXPECT_EQ(has_goal, 0); EXPECT_EQ(boxes, 0); std::ifstream master_file(stem + ".live"); master_file >> key >> runs; EXPECT_EQ(key, "cost"); EXPECT_EQ(runs, 5); // 60 x2, 254, 60 x5, 253, 60 x3 std::ifstream meta(stem + ".txt"); std::stringstream text; text << meta.rdbuf(); EXPECT_NE(text.str().find("reason lattice_timeout"), std::string::npos); EXPECT_NE(text.str().find("max_deviation_deg 22.5"), std::string::npos); // A grid whose static layer does not match the master size is refused instead of writing a misleading replay. EXPECT_TRUE(writeFailureDump(dir, "bad", live, std::vector(5, 0), directions, route, config, result).empty()); } TEST(EndpointSpins, TrimKeepsFirstDrivingPoseAndArrivalPose) { // Start spin 0 -> 0.2 rad, drive 1 m along x, goal spin 0.2 -> 1.0 rad. const Path path{ {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.1, 0.0}, {0.0, 0.0, 0.2, 0.0}, {0.5, 0.0, 0.2, 0.0}, {1.0, 0.0, 0.2, 0.0}, {1.0, 0.0, 0.6, 0.0}, {1.0, 0.0, 1.0, 0.0} }; const Path trimmed = trimEndpointSpins(path); ASSERT_EQ(trimmed.size(), 3u); EXPECT_DOUBLE_EQ(trimmed.front().x, 0.0); EXPECT_DOUBLE_EQ(trimmed.front().yaw, 0.2); EXPECT_DOUBLE_EQ(trimmed[1].x, 0.5); EXPECT_DOUBLE_EQ(trimmed.back().x, 1.0); EXPECT_DOUBLE_EQ(trimmed.back().yaw, 0.2); for (std::size_t i = 1; i < trimmed.size(); ++i) EXPECT_GT(std::hypot(trimmed[i].x - trimmed[i - 1].x, trimmed[i].y - trimmed[i - 1].y), 0.1); } TEST(EndpointSpins, PathsWithoutSpinsOrWithoutDrivingAreUnchanged) { const Path straight{ {0.0, 0.0, 0.0, 0.0}, {0.5, 0.0, 0.0, 0.0}, {1.0, 0.0, 0.0, 0.0} }; EXPECT_EQ(trimEndpointSpins(straight).size(), straight.size()); // A rotation-only plan has no driving pose to keep, so the controller still gets the full turn. const Path rotate{ {2.0, 1.0, 0.0, 0.0}, {2.0, 1.0, 0.5, 0.0}, {2.0, 1.0, 1.0, 0.0} }; EXPECT_EQ(trimEndpointSpins(rotate).size(), rotate.size()); const Path two{ {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0} }; EXPECT_EQ(trimEndpointSpins(two).size(), two.size()); } } // namespace