diff --git a/include/custom_planner/custom_planner.h b/include/custom_planner/custom_planner.h index 408a1e1..70946cf 100755 --- a/include/custom_planner/custom_planner.h +++ b/include/custom_planner/custom_planner.h @@ -90,7 +90,7 @@ public: return false; } - virtual ~CustomPlanner(){}; + ~CustomPlanner() override; private: void publishStats(int solution_cost, int solution_size, @@ -101,10 +101,10 @@ private: const std::vector& footprint, std::vector& out_footprint); - Pose pointOnAngleBisector(Pose& A, Pose& B, Pose& C, double length = 1.0); - bool countRobotDirectionChangeAngle(vector& savePosesOnEdge, int& total_edge); + Pose pointOnAngleBisector(Pose& A, Pose& B, Pose& C, double length); + inline bool isOppositeSign(double angleA, double angleB) { return (angleA > 0 && angleB < 0) || (angleA < 0 && angleB > 0); @@ -172,4 +172,3 @@ private: } #endif - diff --git a/src/custom_planner.cpp b/src/custom_planner.cpp index 3db0155..dd633cd 100755 --- a/src/custom_planner.cpp +++ b/src/custom_planner.cpp @@ -10,37 +10,62 @@ using namespace std; namespace custom_planner { CustomPlanner::CustomPlanner() - : initialized_(false), costmap_robot_(NULL) + : input_spline_inf_(nullptr), + CurveDesign_(nullptr), + initialized_(false), + costmap_robot_(nullptr), + current_env_width_(0), + current_env_height_(0) { } CustomPlanner::CustomPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) - : initialized_(false), costmap_robot_(NULL) + : input_spline_inf_(nullptr), + CurveDesign_(nullptr), + initialized_(false), + costmap_robot_(nullptr), + current_env_width_(0), + current_env_height_(0) { initialize(name, costmap_robot); } + CustomPlanner::~CustomPlanner() + { + delete input_spline_inf_; + delete CurveDesign_; + } + bool CustomPlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) { - if (!initialized_) + if (initialized_) { - robot::NodeHandle private_nh("~/" + name); - robot::NodeHandle p_nh("~"); - printf("Name is %s", name.c_str()); - - input_spline_inf_ = new Spline_Inf(); - CurveDesign_ = new Curve_common(); - - name_ = name; - costmap_robot_ = costmap_robot; - - footprint_ = costmap_robot_->getRobotFootprint(); - - initialized_ = true; - printf("[custom_planner] Initialized successfully"); - return true; + return false; } - return false; + + if (costmap_robot == nullptr || costmap_robot->getCostmap() == nullptr) + { + robot::log_error("[custom_planner] initialize() requires a valid costmap.\n"); + return false; + } + + robot::NodeHandle private_nh("~/" + name); + robot::NodeHandle p_nh("~"); + robot::log_info("Name is %s", name.c_str()); + + input_spline_inf_ = new Spline_Inf(); + CurveDesign_ = new Curve_common(); + + name_ = name; + costmap_robot_ = costmap_robot; + + footprint_ = costmap_robot_->getRobotFootprint(); + current_env_width_ = costmap_robot_->getCostmap()->getSizeInCellsX(); + current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY(); + + initialized_ = true; + robot::log_info("[custom_planner] Initialized successfully"); + return true; } bool CustomPlanner::makePlan(const robot_protocol_msgs::Order& msg, @@ -50,28 +75,35 @@ namespace custom_planner { plan.clear(); - // Check for reinitialization needs - bool do_init = false; - if(!makePlanWithOrder(msg, start, goal)) return false; - if (current_env_width_ != costmap_robot_->getCostmap()->getSizeInCellsX() || - current_env_height_ != costmap_robot_->getCostmap()->getSizeInCellsY()) { - printf("Costmap dimensions have changed from (%d x %d) to (%d x %d), reinitializing custom_planner.", - current_env_width_, current_env_height_, - costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY()); - do_init = true; - } else if (footprint_ != costmap_robot_->getRobotFootprint()) { - printf("Robot footprint has changed, reinitializing custom_planner."); - do_init = true; + if (!initialized_ || costmap_robot_ == nullptr || costmap_robot_->getCostmap() == nullptr) + { + robot::log_error("[custom_planner] makePlan() called before a valid initialize().\n"); + return false; } - if (do_init) { - initialized_ = false; - initialize(name_, costmap_robot_); + // Size and footprint are snapshots used only to detect a runtime costmap update. They do + // not configure Spline_Inf or Curve_common, so recreating those objects here was both + // unnecessary and leaked their previous allocations. Refresh the snapshot before planning + // so this request observes the current costmap state. + const unsigned int width = costmap_robot_->getCostmap()->getSizeInCellsX(); + const unsigned int height = costmap_robot_->getCostmap()->getSizeInCellsY(); + const std::vector footprint = + costmap_robot_->getRobotFootprint(); + if (current_env_width_ != width || current_env_height_ != height || footprint_ != footprint) + { + robot::log_info("[custom_planner] costmap snapshot changed: %u x %u -> %u x %u; " + "refreshing snapshot without reinitializing planner.\n", + current_env_width_, current_env_height_, width, height); + current_env_width_ = width; + current_env_height_ = height; + footprint_ = footprint; } + if (!makePlanWithOrder(msg, start, goal)) return false; + // ===== STEP 2: VALIDATE PATHWAY ===== if (posesOnPathWay_.empty()) { - printf("[custom_planner] posesOnPathWay_ is empty"); + robot::log_info("[custom_planner] posesOnPathWay_ is empty"); return false; } @@ -79,7 +111,7 @@ namespace custom_planner unsigned int mx_start, my_start, mx_end, my_end; if (!costmap_robot_->getCostmap()->worldToMap(start.pose.position.x, start.pose.position.y, mx_start, my_start) || !costmap_robot_->getCostmap()->worldToMap(goal.pose.position.x, goal.pose.position.y, mx_end, my_end)) { - printf("[custom_planner] Cannot convert world coordinates to map coordinates"); + robot::log_info("[custom_planner] Cannot convert world coordinates to map coordinates"); } // ===== STEP 4: FIND NEAREST POINT ON PATHWAY ===== @@ -114,7 +146,7 @@ namespace custom_planner if (d_start_to_path <= DISTANCE_THRESHOLD && d_path_to_goal <= DISTANCE_THRESHOLD) { // CASE 1: Both start and goal are close to pathway - Direct path - printf("[custom_planner] Using direct pathway"); + robot::log_info("[custom_planner] Using direct pathway"); for (size_t i = nearest_idx; i < posesOnPathWay_.size(); i++) { robot_geometry_msgs::PoseStamped pose; @@ -129,7 +161,7 @@ namespace custom_planner } else if (d_start_to_path > DISTANCE_THRESHOLD && d_path_to_goal <= DISTANCE_THRESHOLD) { // CASE 2: Start is far, goal is close - NURBS from start to pathway - printf("[custom_planner] Using start NURBS path reverse_(%x)", reverse_); + robot::log_info("[custom_planner] Using start NURBS path reverse_(%x)", reverse_); std::vector start_control_points; bool valid_start_nurbs = merge_path_calc_.findNURBSControlPoints( @@ -175,7 +207,7 @@ namespace custom_planner } else if (d_start_to_path <= DISTANCE_THRESHOLD && d_path_to_goal > DISTANCE_THRESHOLD) { // CASE 3: Start is close, goal is far - NURBS from pathway to goal - printf("[custom_planner] Using goal NURBS path"); + robot::log_info("[custom_planner] Using goal NURBS path"); std::vector goal_control_points; bool valid_goal_nurbs = merge_path_calc_.findNURBSControlPoints( @@ -221,7 +253,7 @@ namespace custom_planner } else { // CASE 4: Both start and goal are far - Dual NURBS or special handling - printf("[custom_planner] Using dual NURBS path"); + robot::log_info("[custom_planner] Using dual NURBS path"); std::vector start_control_points, goal_control_points; bool valid_start_nurbs = merge_path_calc_.findNURBSControlPoints( @@ -287,7 +319,7 @@ namespace custom_planner } else { // Fallback: Direct pathway from nearest point - printf("[custom_planner] NURBS control points not found, using fallback path"); + robot::log_info("[custom_planner] NURBS control points not found, using fallback path"); for (size_t i = nearest_idx; i < posesOnPathWay_.size(); i++) { robot_geometry_msgs::PoseStamped pose; pose.header.stamp = plan_time; @@ -321,7 +353,7 @@ namespace custom_planner gui_path.poses = plan; // plan_pub_.publish(gui_path); - printf("[custom_planner] Generated plan with %zu waypoints", plan.size()); + robot::log_info("[custom_planner] Generated plan with %zu waypoints", plan.size()); return true; } @@ -427,6 +459,39 @@ namespace custom_planner } degree = (int)msg.edges[i].trajectory.degree; + // `trajectory` là TUỲ CHỌN theo VDA5050: master controller chỉ gửi khi muốn áp đặt một + // đường cong cụ thể. Không gửi thì edge chỉ nói "đi từ node này sang node kia" và robot tự + // lo đường — bắt buộc phải có NURBS làm mọi order không kèm trajectory fail ngay ở đây. + // + // Dựng B-spline bậc 1 với đúng hai control point là vị trí hai node: knot {0,0,1,1} cho ra + // chính xác đoạn thẳng nối chúng. Làm theo cách này thay vì sinh thẳng danh sách pose để + // toàn bộ xử lý phía dưới — tính độ dài, bước lấy mẫu thích nghi theo resolution costmap, + // né vật cản, tính góc, ghép path — dùng lại nguyên vẹn, không phải nhân đôi logic. + const bool trajectory_supplied = degree >= 1 && + !msg.edges[i].trajectory.controlPoints.empty() && + !msg.edges[i].trajectory.knotVector.empty(); + if(!trajectory_supplied) + { + degree = 1; + control_points.clear(); + knot_vector.clear(); + weight_vector.clear(); + + control_points.push_back(Eigen::Vector3d(start_nodeId_it->second.position_x, + start_nodeId_it->second.position_y, 0)); + control_points.push_back(Eigen::Vector3d(end_nodeId_it->second.position_x, + end_nodeId_it->second.position_y, 0)); + weight_vector.push_back(1.0); + weight_vector.push_back(1.0); + knot_vector = {0.0, 0.0, 1.0, 1.0}; + + robot::log_info("[custom_planner] Edge %s khong kem trajectory - noi thang hai node " + "(%.3f, %.3f) -> (%.3f, %.3f)\n", + msg.edges[i].edgeId.c_str(), + start_nodeId_it->second.position_x, start_nodeId_it->second.position_y, + end_nodeId_it->second.position_x, end_nodeId_it->second.position_y); + } + if(curveIsValid(degree, knot_vector, control_points)) { double t_intervel = 0.01; @@ -457,7 +522,7 @@ namespace custom_planner } if ((int)posesOnEdge.size() < 3) { - printf("Edge has too few poses for angle calculation"); + robot::log_info("Edge has too few poses for angle calculation"); continue; } @@ -560,27 +625,27 @@ namespace custom_planner } } else{ - printf("Trajectory of Edge: %s, startNodeId: %s, endNodeId: %s is invalid", msg.edges[i].edgeId.c_str(), + robot::log_info("Trajectory of Edge: %s, startNodeId: %s, endNodeId: %s is invalid", msg.edges[i].edgeId.c_str(), msg.edges[i].startNodeId.c_str(), msg.edges[i].endNodeId.c_str()); return false; } } else{ - printf("Edge: %s not found startNodeId: %s or endNodeId: %s", msg.edges[i].edgeId.c_str(), + robot::log_info("Edge: %s not found startNodeId: %s or endNodeId: %s", msg.edges[i].edgeId.c_str(), msg.edges[i].startNodeId.c_str(), msg.edges[i].endNodeId.c_str()); return false; } } - printf("[custom_planner][makePlanWithOrder] All nodes: %s", all_nodes.c_str()); - printf("[custom_planner][makePlanWithOrder] All edges: %s", all_edges.c_str()); - // printf("[custom_planner][makePlanWithOrder] savePosesOnEdge: %d", (int)savePosesOnEdge.size()); + robot::log_info("[custom_planner][makePlanWithOrder] All nodes: %s", all_nodes.c_str()); + robot::log_info("[custom_planner][makePlanWithOrder] All edges: %s", all_edges.c_str()); + // robot::log_info("[custom_planner][makePlanWithOrder] savePosesOnEdge: %d", (int)savePosesOnEdge.size()); total_edge = (int)edges_info_.size(); bool status_countRobotDirectionChangeAngle = countRobotDirectionChangeAngle(savePosesOnEdge, total_edge); bool status_calcAllYaw = false; - // printf("[custom_planner][makePlanWithOrder] DEBUG 1000 total_edge: %d", total_edge); + // robot::log_info("[custom_planner][makePlanWithOrder] DEBUG 1000 total_edge: %d", total_edge); if(status_countRobotDirectionChangeAngle) status_calcAllYaw = calcAllYaw(start, goal, savePosesOnEdge, total_edge); - // printf("[custom_planner][makePlanWithOrder] DEBUG 2000"); + // robot::log_info("[custom_planner][makePlanWithOrder] DEBUG 2000"); return status_calcAllYaw; } @@ -766,7 +831,7 @@ namespace custom_planner if (cost_start >= 30 || cost_end >= 30) i++; // else return false; } - // printf("[custom_planner][countRobotDirectionChangeAngle] DEBUG: 400 count_two_curve_idx(%d)", count_two_curve_idx); + // robot::log_info("[custom_planner][countRobotDirectionChangeAngle] DEBUG: 400 count_two_curve_idx(%d)", count_two_curve_idx); return true; } @@ -776,13 +841,13 @@ namespace custom_planner int& total_edge) { int total_two_curve = (int)RobotDirectionChangeAngle_info_.size(); - // printf("[custom_planner][calcAllYaw] total_two_curve: %d", total_two_curve); + // robot::log_info("[custom_planner][calcAllYaw] total_two_curve: %d", total_two_curve); vector savePoseTMP; if(!savePoseTMP.empty()) savePoseTMP.clear(); if(savePosesOnEdge.empty()) { - printf("[custom_planner][calcAllYaw] savePosesOnEdge is empty!\n"); + robot::log_info("[custom_planner][calcAllYaw] savePosesOnEdge is empty!\n"); return false; } @@ -794,7 +859,7 @@ namespace custom_planner { if(total_two_curve > 0) { - robot::log_warning("DEBUG 1"); + // robot::log_warning("DEBUG 1"); if(total_two_curve == 1) { vector Pose_start_tmp; @@ -884,21 +949,21 @@ namespace custom_planner } else { - robot::log_warning("DEBUG 2"); + // robot::log_warning("DEBUG 2"); if(merge_path_calc_.status_yaw_edge_end_) { - robot::log_warning("DEBUG 2.1"); + // robot::log_warning("DEBUG 2.1"); reverse_ = true; - // printf("custom_planner][calcAllYaw] DEBUG 300"); + // robot::log_info("custom_planner][calcAllYaw] DEBUG 300"); setYawAllPosesOnEdge(savePosesOnEdge,true); } else { - robot::log_warning("DEBUG 2.2"); + // robot::log_warning("DEBUG 2.2"); reverse_ = false; - // printf("custom_planner][calcAllYaw] DEBUG 310"); + // robot::log_info("custom_planner][calcAllYaw] DEBUG 310"); setYawAllPosesOnEdge(savePosesOnEdge,false); } savePoseTMP.insert(savePoseTMP.end(), savePosesOnEdge.begin(),savePosesOnEdge.end()); @@ -917,7 +982,7 @@ namespace custom_planner idx_2 < 0 || idx_2 >= static_cast(savePoseTMP.size()) || idx_3 < 0 || idx_3 >= static_cast(savePoseTMP.size())) { - printf("Invalid indices: %d, %d, %d", idx_1, idx_2, idx_3); + robot::log_info("Invalid indices: %d, %d, %d", idx_1, idx_2, idx_3); continue; } @@ -1036,7 +1101,7 @@ namespace custom_planner merge_path_calc_.edge_back_end_idx_ = (int)posesOnPathWay_.size() - 1; merge_path_calc_.edge_back_start_idx_ = merge_path_calc_.edge_back_end_idx_ - total; // posesOnPathWay_.shrink_to_fit(); - // printf("[custom_planner][makePlanWithOrder] DEBUG: 2 posesOnPathWay_ size(%d)", (int)posesOnPathWay_.size()); + // robot::log_info("[custom_planner][makePlanWithOrder] DEBUG: 2 posesOnPathWay_ size(%d)", (int)posesOnPathWay_.size()); } } return true; @@ -1083,17 +1148,17 @@ namespace custom_planner { if(degree < 1 || degree > 9) { - printf("degree is invalid value\n"); + robot::log_info("degree is invalid value\n"); return false; } if(!((knot_vector.size() - degree - 1) == control_points.size())) { - printf("relation between degree, number of knots, and number of control points is invalid\n"); + robot::log_info("relation between degree, number of knots, and number of control points is invalid\n"); return false; } // if(std::is_sorted(knot_vector.begin(), knot_vector.end())) // { - // printf("knot vector is not monotonic"); + // robot::log_info("knot vector is not monotonic"); // return false; // } return true; @@ -1156,7 +1221,7 @@ namespace custom_planner double angle = merge_path_calc_.calculateAngle(start_edge_pose.getX(), start_edge_pose.getY(), end_edge_pose.getX(), end_edge_pose.getY()); double yaw_goal = data_convert::getYaw(goal.pose.orientation); - // printf("[custom_planner] DEBUG: angle: %f; yaw_goal: %f",angle, yaw_goal); + // robot::log_info("[custom_planner] DEBUG: angle: %f; yaw_goal: %f",angle, yaw_goal); // nomalize angle to [-pi, pi] auto normalizeAngle = [](double a) { while (a > M_PI) a -= 2 * M_PI; @@ -1165,7 +1230,7 @@ namespace custom_planner }; double delta_angle = std::fabs(std::fabs(normalizeAngle(yaw_goal)) - std::fabs(normalizeAngle(angle))); - robot::log_warning("DEBUG 3: yaw_goal: %f, angle: %f, delta_angle: %f", yaw_goal, angle, delta_angle); + // robot::log_warning("DEBUG 3: yaw_goal: %f, angle: %f, delta_angle: %f", yaw_goal, angle, delta_angle); return (delta_angle > (0.5 * M_PI)); }