diff --git a/CMakeLists.txt b/CMakeLists.txt index cfb8a22..1ea1a3b 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,9 +30,6 @@ if (NOT BUILDING_WITH_CATKIN) set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") set(PACKAGES_DIR - robot_visualization_msgs - robot_nav_msgs - robot_std_msgs robot_geometry_msgs tf3 robot_tf3_geometry_msgs @@ -50,9 +47,6 @@ else() # Catkin specific configuration # ======================================================== find_package(catkin REQUIRED COMPONENTS - robot_visualization_msgs - robot_nav_msgs - robot_std_msgs robot_geometry_msgs robot_tf3_geometry_msgs robot_time @@ -68,7 +62,7 @@ else() catkin_package( INCLUDE_DIRS include LIBRARIES ${PROJECT_NAME} - CATKIN_DEPENDS robot_visualization_msgs robot_nav_msgs robot_std_msgs robot_geometry_msgs robot_tf3_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_protocol_msgs robot_cpp + CATKIN_DEPENDS robot_geometry_msgs robot_tf3_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_protocol_msgs robot_cpp DEPENDS Eigen3 Boost ) @@ -85,8 +79,7 @@ endif() # ======================================================== add_library(${PROJECT_NAME} SHARED src/custom_planner.cpp - src/pathway.cc - src/pose.cc + src/custom_planner_config.cpp src/Curve_common.cpp src/merge_path_calc.cpp ) @@ -175,6 +168,6 @@ else() message(STATUS "Project: ${PROJECT_NAME}") message(STATUS "Version: ${PROJECT_VERSION}") message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}") - message(STATUS "Dependencies: robot_visualization_msgs, robot_nav_msgs, robot_std_msgs, robot_geometry_msgs, tf3, robot_tf3_geometry_msgs, robot_time, data_convert, robot_costmap_2d, robot_nav_core, robot_protocol_msgs, robot_cpp, Eigen3, Boost") + message(STATUS "Dependencies: robot_geometry_msgs, tf3, robot_tf3_geometry_msgs, robot_time, data_convert, robot_costmap_2d, robot_nav_core, robot_protocol_msgs, robot_cpp, Eigen3, Boost") message(STATUS "=================================") endif() diff --git a/config/custom_global_params.yaml b/config/custom_global_params.yaml index 6536a6e..7d49cc5 100755 --- a/config/custom_global_params.yaml +++ b/config/custom_global_params.yaml @@ -1,17 +1,33 @@ -base_global_planner: CustomPlanner +# custom_planner — tham số runtime, đọc qua robot::NodeHandle("CustomPlanner"). +# Thiếu key nào thì dùng default trong CustomPlannerConfig (cùng giá trị ghi ở đây). CustomPlanner: - environment_type: XYThetaLattice - planner_type: ARAPlanner - allocated_time: 10.0 - initial_epsilon: 1.0 - force_scratch_limit: 10000 - forward_search: false - nominalvel_mpersecs: 0.8 - timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s - allow_unknown: true - directory_to_save_paths: "/init/paths" - pathway_filename: "pathway.txt" - current_pose_topic_name: "/amcl_pose" - map_frame_id: "map" - base_frame_id: "base_link" - + # [m] start/goal cách pathway dưới ngưỡng này thì coi là đã bám vào pathway + # (quyết định cách nối NURBS start/goal vào tuyến). + pathway_attach_distance: 0.1 + + # [m] order không có node/edge (goal trần): chỉ nhận khi start-goal gần hơn + # ngưỡng này, ngược lại trả false để move_base2 dùng backup planner. + bare_goal_max_distance: 0.2 + + # Bước tham số u trong [0,1] khi đo chiều dài NURBS một cạnh (không phải mét). + nurbs_length_t_interval: 0.01 + + # [m] khoảng cách mong muốn giữa hai pose khi lấy mẫu NURBS nối start/goal. + nurbs_point_spacing: 0.05 + + # [rad] hai cạnh thẳng đầu gãy dưới góc này thì bỏ cạnh đầu khi tính yaw. + skip_edge_angle: 0.4712 # = 0.15*pi + + # [rad] góc nối giữa hai cạnh <= tight: gãy gắt (cost 20); < wide: gãy vừa (cost 10). + cost_angle_tight: 0.3142 # = 0.1*pi + cost_angle_wide: 1.4137 # = 0.45*pi + + # [rad] cửa sổ góc đổi hướng cần chèn chuỗi pose xoay tại chỗ giữa hai cạnh. + rotation_insert_min: 1.4137 # = 0.45*pi + rotation_insert_max: 2.6704 # = 0.85*pi + + # [rad] bước yaw giữa hai pose xoay tại chỗ được chèn. + rotation_step: 0.1571 # = 0.05*pi + + # [rad] |yaw goal - hướng cạnh cuối| vượt ngưỡng này thì đoạn cuối đi lùi. + backward_decision_angle: 1.5708 # = 0.5*pi diff --git a/include/custom_planner/Curve_common.h b/include/custom_planner/Curve_common.h index 014ad0d..a79c030 100755 --- a/include/custom_planner/Curve_common.h +++ b/include/custom_planner/Curve_common.h @@ -1,84 +1,41 @@ #ifndef CUSTOM_PLANNER_CURVE_COMMON_H_ #define CUSTOM_PLANNER_CURVE_COMMON_H_ -//#include "agv_path_smoothing/conversion.h" +#include + #include -//#include -// #include -// #include -#include #include -#include -#include "custom_planner/color.h" +// Thông tin NURBS/B-spline: knot vector, control point, weight và buffer basis +// function dùng lại giữa các lần CalculateCurvePoint trên cùng một cạnh. struct Spline_Inf { int order; std::vector knot_vector; std::vector weight; - //std::vector N; EIGEN_MAKE_ALIGNED_OPERATOR_NEW std::vector > control_point; - std::vector > N; - std::vector > dN; - std::vector > ddN; std::vector N_double_vec; - std::vector R_double_vec; - std::vector dR_double_vec; - std::vector ddR_double_vec; - // std::vector ddN_double_vec; - //Eigen::Matrix N; //bsaic function - Eigen::MatrixXd curvefit_N; - -}; - -struct EigenTrajectoryPoint -{ - typedef std::vector > Vector; - double u_data; - EIGEN_MAKE_ALIGNED_OPERATOR_NEW - Eigen::Vector3d position; - //Eigen::VectorXd u_data; }; class Curve_common { public: Curve_common(); - robot_nav_msgs::Path Generate_Line(robot_geometry_msgs::Point start_point, robot_geometry_msgs::Point end_point, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_BezierCurve(EigenTrajectoryPoint::Vector control_point, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_BsplineCurve(Spline_Inf bspline_inf, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_NURBSCurve(Spline_Inf spline_inf, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_DerivativeBsplineCurve(Spline_Inf bspline_inf, int differential_times, double t_intervel, std::string frame_id); - robot_nav_msgs::Path Generate_DerivativeBasisFuncCurve(Spline_Inf bspline_inf, int differential_times, int index, double t_intervel, std::string frame_id); - void CalculateDerivativeBasisFunc(Spline_Inf *spline_inf, double u_data, int differential_times); - robot_geometry_msgs::Point CalculateDerivativeCurvePoint(Spline_Inf *spline_inf, double u_data, int differential_times, bool UsingNURBS); + /// Nạp order + control point + knot vector vào spline_inf. + void ReadSplineInf(Spline_Inf *bspline_inf, int order, + std::vector > control_point, + std::vector knot_vector); + + /// Nạp weight vector (bắt buộc trước khi tính NURBS với UsingNURBS=true). + void ReadSplineInf(Spline_Inf *bspline_inf, std::vector weight_vector, + bool use_limit_derivative_fitting); + + /// Tính điểm trên đường cong tại tham số u_data trong [0, 1]. robot_geometry_msgs::Point CalculateCurvePoint(Spline_Inf *spline_inf, double u_data, bool UsingNURBS); - double CalculateCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateSignedCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - Eigen::Vector3d CalculateCurvatureDirectionVector(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateCurvatureRadius(Spline_Inf spline_inf, double u_data, bool UsingNURBS); - double CalculateCurveLength(Spline_Inf spline_inf, double start_u, double end_u, int sub_intervals, bool UsingNURBS); - - void ReadSplineInf(Spline_Inf *bspline_inf, int order, std::vector > control_point, std::vector knot_vector); - void ReadSplineInf(Spline_Inf *bspline_inf, std::vector weight_vector, bool use_limit_derivative_fitting); - void ReadDiscreate2DPointFromLaunch(EigenTrajectoryPoint::Vector *input_point, std::vector file_discreate_point); - void ReadDiscreate2DPointFromLaunch(std::vector > *input_point, std::vector file_discreate_point); - void ShowDiscreatePoint(robot_visualization_msgs::Marker *points, EigenTrajectoryPoint::Vector discreate_point); - void ShowDiscreatePoint(robot_visualization_msgs::Marker *points, std::vector > discreate_point); - - //TODO: move relate visualize function to new vislization.h - int print(); - robot_visualization_msgs::Marker ShowDiscreatePoint(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint2(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint(std::vector > discreate_point, const std::string& frame_id, const std::string& name, double scale); - robot_visualization_msgs::Marker ShowDiscreatePoint2(std::vector > discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale); - private: - - }; -#endif //CUSTOM_PLANNER_CURVE_COMMON_H_ \ No newline at end of file +#endif //CUSTOM_PLANNER_CURVE_COMMON_H_ diff --git a/include/custom_planner/color.h b/include/custom_planner/color.h deleted file mode 100755 index ce80d18..0000000 --- a/include/custom_planner/color.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef CUSTOM_PLANNER_COLOR_H_ -#define CUSTOM_PLANNER_COLOR_H_ - -#include - -namespace agv_visualization -{ - class Color : public robot_std_msgs::ColorRGBA - { - public: - Color() : robot_std_msgs::ColorRGBA() {} - Color(double red, double green, double blue) : Color(red, green, blue, 1.0) {} - Color(double red, double green, double blue, double alpha) : Color() { - r = red; - g = green; - b = blue; - a = alpha; - } - - static const Color White() { return Color(1.0, 1.0, 1.0); } - static const Color Black() { return Color(0.0, 0.0, 0.0); } - static const Color Gray() { return Color(0.5, 0.5, 0.5); } - static const Color Red() { return Color(1.0, 0.0, 0.0); } - static const Color Green() { return Color(0.0, 1.0, 0.0); } - static const Color Blue() { return Color(0.0, 0.0, 1.0); } - static const Color Yellow() { return Color(1.0, 1.0, 0.0); } - static const Color Orange() { return Color(1.0, 0.5, 0.0); } - static const Color Purple() { return Color(0.5, 0.0, 1.0); } - static const Color Chartreuse() { return Color(0.5, 1.0, 0.0); } - static const Color Teal() { return Color(0.0, 1.0, 1.0); } - static const Color Pink() { return Color(1.0, 0.0, 0.5); } - }; -} -#endif //CUSTOM_PLANNER_COLOR_H_ \ No newline at end of file diff --git a/include/custom_planner/conversion.h b/include/custom_planner/conversion.h deleted file mode 100755 index ce758f3..0000000 --- a/include/custom_planner/conversion.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef CUSTOM_PLANNER_CONVERSION_H_ -#define CUSTOM_PLANNER_CONVERSION_H_ -#include "custom_planner/Curve_common.h" - -#include -#include -#include - -inline Eigen::Vector3d EigenVecter3dFromPointMsg(const robot_geometry_msgs::Point& msg) { - return Eigen::Vector3d(msg.x, msg.y, msg.z); -} - -inline EigenTrajectoryPoint::Vector EigenTrajectoryVectorFromVector(const std::vector &plan) -{ - EigenTrajectoryPoint::Vector eigen_trajectory_point_vec; - EigenTrajectoryPoint eigen_trajectory_point; - - for(int i = 0; i < static_cast(plan.size()); i++) - { - eigen_trajectory_point.position(0) = plan.at(i).pose.position.x; - eigen_trajectory_point.position(1) = plan.at(i).pose.position.y; - eigen_trajectory_point_vec.push_back(eigen_trajectory_point); - } - - return eigen_trajectory_point_vec; -} - -inline EigenTrajectoryPoint::Vector EigenTrajectoryVectorFromVector(const std::vector &discreate_point_vec) -{ - EigenTrajectoryPoint::Vector eigen_trajectory_point_vec; - EigenTrajectoryPoint eigen_trajectory_point; - - for(int i = 0; i < static_cast(discreate_point_vec.size()); i++) - { - eigen_trajectory_point.position(0) = discreate_point_vec.at(i).x; - eigen_trajectory_point.position(1) = discreate_point_vec.at(i).y; - eigen_trajectory_point_vec.push_back(eigen_trajectory_point); - } - - return eigen_trajectory_point_vec; -} - -#endif //CUSTOM_PLANNER_CONVERSION_H_ \ No newline at end of file diff --git a/include/custom_planner/custom_planner.h b/include/custom_planner/custom_planner.h index 70946cf..2f778ef 100755 --- a/include/custom_planner/custom_planner.h +++ b/include/custom_planner/custom_planner.h @@ -1,45 +1,32 @@ #ifndef CUSTOM_PLANNER_H #define CUSTOM_PLANNER_H -#include -#include -#include #include - -using namespace std; - -// ROS -#include -#include +#include +#include +#include // Costmap used for the map representation #include -// global representation +// global planner interface #include -// tf -#include -#include - -// internal lib -#include -#include -#include "custom_planner/Curve_common.h" -#include "custom_planner/conversion.h" -#include "custom_planner/merge_path_calc.h" - -#include +#include #include -const double EPSILON = 1e-6; - -using namespace std; +// internal lib +#include +#include +#include +#include namespace custom_planner{ +constexpr double kEpsilon = 1e-6; + struct OrderNode{ - string nodeId; + std::string nodeId; uint32_t sequenceId; double position_x; double position_y; @@ -48,126 +35,103 @@ struct OrderNode{ class CustomPlanner : public robot_nav_core::BaseGlobalPlanner{ public: - - /** - * @brief Default constructor for the NavFnROS object - */ + CustomPlanner(); - /** * @brief Constructor for the CustomPlanner object * @param name The name of this planner - * @param costmap_ros A pointer to the ROS wrapper of the costmap to use + * @param costmap_robot A pointer to the wrapper of the costmap to use */ CustomPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot); - /** * @brief Initialization function for the CustomPlanner object * @param name The name of this planner - * @param costmap_ros A pointer to the ROS wrapper of the costmap to use + * @param costmap_robot A pointer to the wrapper of the costmap to use */ - virtual bool initialize(std::string name, - robot_costmap_2d::Costmap2DROBOT* costmap_robot); + bool initialize(std::string name, + robot_costmap_2d::Costmap2DROBOT* costmap_robot) override; - virtual bool makePlan(const robot_protocol_msgs::Order& msg, - const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - std::vector& plan); /** - * @brief Given a goal pose in the world, compute a plan - * @param start The start pose - * @param goal The goal pose - * @param plan The plan... filled by the planner - * @return True if a valid plan was found, false otherwise + * @brief Materialize một VDA5050 Order (node/edge + NURBS) thành plan. */ - virtual bool makePlan(const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal, - std::vector& plan) + bool makePlan(const robot_protocol_msgs::Order& msg, + const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) override; + + /** + * @brief Contract 3 tham số không được hỗ trợ: CustomPlanner là route + * materializer theo Order, không phải search planner. move_base2 sẽ rơi + * xuống backup planner khi hàm này trả false. + */ + bool makePlan(const robot_geometry_msgs::PoseStamped& start, + const robot_geometry_msgs::PoseStamped& goal, + std::vector& plan) override { - printf("[%s:%d] This function is not available!",__FILE__,__LINE__); + (void)start; (void)goal; (void)plan; + robot::log_warning("[custom_planner] makePlan(start, goal) is not supported — use the Order overload."); return false; } - ~CustomPlanner() override; + ~CustomPlanner() override = default; private: - void publishStats(int solution_cost, int solution_size, - const robot_geometry_msgs::PoseStamped& start, - const robot_geometry_msgs::PoseStamped& goal); - - static void transformFootprintToEdges(const robot_geometry_msgs::Pose& robot_pose, - const std::vector& footprint, - std::vector& out_footprint); - - bool countRobotDirectionChangeAngle(vector& savePosesOnEdge, int& total_edge); + bool countRobotDirectionChangeAngle(std::vector& savePosesOnEdge, int& total_edge); Pose pointOnAngleBisector(Pose& A, Pose& B, Pose& C, double length); - inline bool isOppositeSign(double angleA, double angleB) + inline bool isOppositeSign(double angleA, double angleB) { return (angleA > 0 && angleB < 0) || (angleA < 0 && angleB > 0); } - bool checkYawEdgeEnd(Pose& start_edge_pose, Pose& end_edge_pose, + bool checkYawEdgeEnd(Pose& start_edge_pose, Pose& end_edge_pose, const robot_geometry_msgs::PoseStamped &goal); - bool loadPathwayData(const string& filename); - - bool findNearestPoseOfPath(vector& posesOnPathWay, Pose& PoseToCheck, Pose& PoseResult); - - // void order_msg_handle(const vda5050_msgs::Order::ConstPtr& msg); - - bool makePlanWithOrder(robot_protocol_msgs::Order msg, - const robot_geometry_msgs::PoseStamped& start, + bool makePlanWithOrder(robot_protocol_msgs::Order msg, + const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal); bool doIntersect(const robot_geometry_msgs::Point& p1, const robot_geometry_msgs::Point& q1, const robot_geometry_msgs::Point& p2, const robot_geometry_msgs::Point& q2); - + std::optional computeIntersectionPoint(const robot_geometry_msgs::Point& p1, const robot_geometry_msgs::Point& q1, const robot_geometry_msgs::Point& p2, const robot_geometry_msgs::Point& q2); - - bool calcAllYaw(const robot_geometry_msgs::PoseStamped& start, + + bool calcAllYaw(const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal, - vector& saveposesOnEdge, + std::vector& saveposesOnEdge, int& total_edge); - bool isThetaValid(double theta); - bool curveIsValid(int degree, const std::vector &knot_vector, - vector>& control_points); + std::vector>& control_points); - void setYawAllPosesOnEdge(vector& posesOnEdge, bool reverse); - - double computeDeltaAngle(Pose& Pose1, Pose& Pose2); - - vector divideSegment(Pose& A, Pose& B, double d); - vector divideSegment(robot_geometry_msgs::PoseStamped& A, robot_geometry_msgs::PoseStamped& B, double d); + void setYawAllPosesOnEdge(std::vector& posesOnEdge, bool reverse); // Vector lưu thông tin các cạnh - std::vector edges_info_; + std::vector edges_info_; std::vector RobotDirectionChangeAngle_info_; MergePathCalc merge_path_calc_; bool skipEdge_flag_ = false; bool reverse_ = false; - Spline_Inf* input_spline_inf_; - Curve_common* CurveDesign_; - vector posesOnPathWay_; + Spline_Inf input_spline_inf_; + Curve_common CurveDesign_; + std::vector posesOnPathWay_; + + CustomPlannerConfig config_; bool initialized_; bool rotating_robot_plag_ = false; /**< whether the robot is rotating or not, used to determine the direction of the path */ std::string name_; - robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< manages the cost map for us */ + robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< non-owning, do not cache the inner costmap pointer */ std::vector footprint_; unsigned int current_env_width_; unsigned int current_env_height_; - - boost::mutex mutex_; }; } diff --git a/include/custom_planner/custom_planner_config.h b/include/custom_planner/custom_planner_config.h index 10feb93..71035e4 100644 --- a/include/custom_planner/custom_planner_config.h +++ b/include/custom_planner/custom_planner_config.h @@ -1,12 +1,65 @@ #ifndef CUSTOM_PLANNER_CONFIG_H_ #define CUSTOM_PLANNER_CONFIG_H_ +#include + #include namespace custom_planner { - // struct -} +/** + * @brief Tham số runtime của CustomPlanner, nạp từ YAML qua robot::NodeHandle. + * + * Mọi default giữ nguyên giá trị đã hard-code trước refactor để không đổi + * hành vi khi YAML thiếu key. Đơn vị ghi ngay tại từng field. + */ +struct CustomPlannerConfig +{ + // [m] start/goal cách pathway dưới ngưỡng này thì coi là đã bám vào pathway + // (quyết định 1 trong 4 cách nối NURBS start/goal vào tuyến). + double pathway_attach_distance = 0.1; -#endif // CUSTOM_PLANNER_CONFIG_H_ \ No newline at end of file + // [m] order không có node/edge (goal trần): chỉ chấp nhận khi start-goal + // gần hơn ngưỡng này, ngược lại trả false để move_base2 rơi xuống backup planner. + double bare_goal_max_distance = 0.2; + + // Bước tham số u trong [0,1] khi đo chiều dài NURBS của một cạnh + // (không phải mét; nhỏ hơn = đo chính xác hơn, chậm hơn). + double nurbs_length_t_interval = 0.01; + + // [m] khoảng cách mong muốn giữa hai pose liên tiếp khi lấy mẫu NURBS + // trong calculateNURBSPath (nhánh nối start/goal vào pathway). + double nurbs_point_spacing = 0.05; + + // [rad] hai cạnh thẳng đầu tiên gãy dưới góc này thì bỏ cạnh đầu khi tính yaw + // (robot xuất phát giữa khúc gãy ngắn, đi thẳng luôn sang cạnh sau). + double skip_edge_angle = 0.15 * M_PI; + + // [rad] góc nối giữa hai cạnh <= ngưỡng này: gãy gắt (cost 20). + double cost_angle_tight = 0.1 * M_PI; + + // [rad] góc nối < ngưỡng này (và > tight): gãy vừa (cost 10). + double cost_angle_wide = 0.45 * M_PI; + + // [rad] cửa sổ góc đổi hướng (min, max) mà planner chèn chuỗi pose xoay + // tại chỗ giữa hai cạnh thay vì đi cong liền mạch. + double rotation_insert_min = 0.45 * M_PI; + double rotation_insert_max = 0.85 * M_PI; + + // [rad] bước yaw giữa hai pose xoay tại chỗ được chèn. + double rotation_step = 0.05 * M_PI; + + // [rad] |yaw goal - hướng cạnh cuối| vượt ngưỡng này thì đoạn cuối đi lùi. + double backward_decision_angle = 0.5 * M_PI; + + /// Nạp param từ nh (thiếu key giữ default), validate range rồi log giá trị chốt. + void load(robot::NodeHandle& nh); + + /// Kẹp giá trị về range hợp lệ; log warning mỗi lần phải sửa. + void validate(); +}; + +} // namespace custom_planner + +#endif // CUSTOM_PLANNER_CONFIG_H_ diff --git a/include/custom_planner/merge_path_calc.h b/include/custom_planner/merge_path_calc.h index 46bcbea..0d1f76f 100755 --- a/include/custom_planner/merge_path_calc.h +++ b/include/custom_planner/merge_path_calc.h @@ -96,7 +96,7 @@ namespace custom_planner * Hàm này tìm các điểm điều khiển NURBS dựa trên vị trí bắt đầu, kết thúc và các điểm trên đường đi. * Nó sử dụng bậc của đường cong NURBS để xác định số lượng điểm điều khiển cần thiết. */ - bool findNURBSControlPoints(vector& control_points, + bool findNURBSControlPoints(std::vector& control_points, const robot_geometry_msgs::PoseStamped& start, std::vector& posesOnPathWay, point_type type); @@ -109,11 +109,11 @@ namespace custom_planner * Hàm này sẽ tính toán đường đi NURBS dựa trên các điểm điều khiển đã tìm được. * Nó sẽ sử dụng các hàm từ CurveCommon và Spline_Inf để tính toán các điểm trên đường cong. */ - std::vector calculateNURBSPath(vector& control_points, + std::vector calculateNURBSPath(std::vector& control_points, bool reverse); - bool handleEdgeIntersection(vector& savePosesOnEdge, - vector& posesOnEdge, + bool handleEdgeIntersection(std::vector& savePosesOnEdge, + std::vector& posesOnEdge, size_t current_edge_idx); /** @@ -173,16 +173,16 @@ namespace custom_planner bool status_yaw_edge_end_ = true; + // [m] khoảng cách mong muốn giữa hai pose khi lấy mẫu NURBS trong + // calculateNURBSPath; CustomPlanner nạp từ config khi initialize. + double desired_point_spacing_ = 0.05; + private: - // vector control_points; - bool normal_plag = false; - // CurveCommon* curve_design = nullptr; - // Spline_Inf* spline_inf = nullptr; - Spline_Inf* spline_inf = nullptr; - Curve_common* curve_design = nullptr; - + Spline_Inf spline_inf; + Curve_common curve_design; + /** * \brief Cập nhật hướng của các Pose trong đường đi NURBS. * \param saved_poses Vector chứa các Pose đã lưu. diff --git a/include/custom_planner/pathway.h b/include/custom_planner/pathway.h deleted file mode 100755 index 3e70456..0000000 --- a/include/custom_planner/pathway.h +++ /dev/null @@ -1,150 +0,0 @@ -#ifndef CUSTOM_PLANNER_CUSTOM_PLANNER_PATHWAY_H -#define CUSTOM_PLANNER_CUSTOM_PLANNER_PATHWAY_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace std; - -namespace custom_planner -{ - - class Point { - private: - double x_, y_; - - public: - Point(): - x_(0.0), y_(0.0) {}; - - Point(double x, double y): - x_(x), y_(y) {}; - - ~Point() {}; - - inline void setX(double x) { x_ = x; } - inline void setY(double y) { y_ = y; } - inline void setPoint(double x, double y) { x_ = x, y_ = y; } - inline void setPoint(Point p) { x_ = p.x_, y_ = p.y_; } - - inline double getX(void) { return x_; } - inline double getY(void) { return y_; } - inline Point getPoint(void) { return Point(x_, y_); } - - }; // class Point - - class Edge { - private: - Pose p1_; - Pose p2_; - public: - Edge(void): - p1_(Pose(0.0, 0.0, 0.0)), - p2_(Pose(0.0, 0.0, 0.0)) {} - Edge(Pose p1, Pose p2): - p1_(p1), - p2_(p2) {} - inline void setEdge(Pose p1, Pose p2){ - p1_ = p1; p2_ = p2; - } - ~Edge() {} - inline void setP1(Pose p1){p1_ = p1;} - inline void setP2(Pose p2){p2_ = p2;} - inline Pose getP1(void){return p1_;} - inline Pose getP2(void){return p2_;} - }; - - class Pathway { - private: - std::vector path_; - vector posesOnPath_; - Pose startPoseOfPath; - // Given three collinear poses p, q, r, the function checks if - // pose q lies on edge 'pr' - bool onSegment(Pose p, Pose q, Pose r); - - //To find orientation of ordered triplet (p, q, r) - // The function returns following values - // 0 --> p, q and r are collinear - // 1 --> Clockwise - // 2 --> Counterclockwise - int orientation(Pose p, Pose q, Pose r); - - bool doIntersect(Pose p1, Pose q1, Pose p2, Pose q2); - - bool isIntersect(Edge L); - - bool isPoseExisted(Pose p); - - double calculateAngle(Pose p1, Pose p2, Pose p3); - - bool findIntersection(Edge L1, Edge L2, Point* resultPoint); - - public: - bool isPathInitilized_; - bool isPathClear_; - Pathway():isPathInitilized_(false),isPathClear_(false) - { - - // startPointOfPath = Pose() - - } - ~Pathway(){ - path_.clear(); - posesOnPath_.clear(); - } - void RecordPath(Pose startPose, Pose currentPose, double delta_angle_th, double InitialSegmentLengthMin, double SegmentLengthMin); - void ResetAndRecordPath(Pose startPose, Pose currentPose, double delta_angle_th, double InitialSegmentLengthMin, double SegmentLengthMin); - inline void clear(){path_.clear();} - inline bool isPathEmpty(){return path_.empty();} - inline void addEdge(Pose p1, Pose p2) {path_.push_back(Edge(p1, p2));} - inline void addEdge(Edge Edge) {path_.push_back(Edge);} - inline void addEdge(Pose p2) {if(!path_.empty()&&!isPoseExisted(p2)) - path_.push_back(Edge(path_.back().getP2(),p2));} - - bool isNewPoseOnEdge(Pose p, double delta_angle_th); - - inline void setP2LastEdgeOnPath(Pose p2) - { - path_.back().setP2(p2); - } - - void setEdgeOnPath(uint32_t line_index, Pose p1, Pose p2); - - inline vector getPosesOnPath(){return posesOnPath_;} - - void syncPosesAndPath(); - - void SavePathAsFile(const string& file_name); - - void LoadPathFromFile(const string& file_name); - - vector findIntersections(Edge L); - - vector> findIntersections(Edge L1, Edge L2); - - void testprint() - { - if(!path_.empty()){ - int i =0; - for(auto &edge : path_) - { - cout<<"edge "< -#include -#include -#include -#include -#include -#include + #include -using namespace std; namespace custom_planner{ class Pose { private: - double x_, y_, yaw_; + double x_, y_, yaw_; // [m], [m], [rad] — yaw giữ trong [-pi, pi] qua modifyYaw() void modifyYaw(void) { while (yaw_ < -M_PI) @@ -30,7 +23,7 @@ public: Pose(double x, double y, double yaw): x_(x), y_(y), yaw_(yaw) {}; - ~Pose() {}; + ~Pose() = default; inline void setX(double x) { x_ = x; } inline void setY(double y) { y_ = y; } @@ -41,12 +34,10 @@ public: inline double getX(void) { return x_; } inline double getY(void) { return y_; } inline double getYaw(void) { return yaw_; } - inline Pose getPose(void) { return Pose(x_, y_, yaw_); } - bool SavePoseAsFile(const string& file_name); - bool LoadPoseFromFile(const string& file_name); + inline Pose getPose(void) { return Pose(x_, y_, yaw_); } }; // class Pose } -#endif \ No newline at end of file +#endif diff --git a/package.xml b/package.xml index 801546d..4608e44 100644 --- a/package.xml +++ b/package.xml @@ -1,55 +1,27 @@ - + + custom_planner - 0.7.10 + 1.0.0 - custom_planner is the second generation of the transform library, which lets - the user keep track of multiple coordinate frames over time. custom_planner - maintains the relationship between coordinate frames in a tree - structure buffered in time, and lets the user transform points, - vectors, etc between any two coordinate frames at any desired - point in time. + Global planner materializes a VDA5050 Order (nodes/edges with NURBS + trajectories) into a dense plan for robot_nav_core. It is a route + materializer, not a search planner: the plain makePlan(start, goal) + contract is intentionally unsupported so the runtime falls back to a + search-based backup planner for bare goals. - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD + duongtd + Proprietary - http://www.ros.org/wiki/custom_planner - - catkin + catkin - robot_costmap_2d - robot_costmap_2d - - robot_nav_core - robot_nav_core - - robot_geometry_msgs - robot_geometry_msgs - - robot_nav_msgs - robot_nav_msgs - - robot_std_msgs - robot_std_msgs - - robot_tf3_geometry_msgs - robot_tf3_geometry_msgs - - robot_cpp - robot_cpp - - robot_protocol_msgs - robot_protocol_msgs - - robot_time - robot_time - - robot_visualization_msgs - robot_visualization_msgs - - data_convert - data_convert - - \ No newline at end of file + robot_costmap_2d + robot_nav_core + robot_geometry_msgs + robot_tf3_geometry_msgs + robot_cpp + robot_protocol_msgs + robot_time + data_convert + eigen + boost + diff --git a/src/Curve_common.cpp b/src/Curve_common.cpp index bcf294c..f00106b 100755 --- a/src/Curve_common.cpp +++ b/src/Curve_common.cpp @@ -1,7 +1,4 @@ #include "custom_planner/Curve_common.h" -#include "custom_planner/conversion.h" - -#include #include @@ -10,287 +7,11 @@ Curve_common::Curve_common() } -robot_nav_msgs::Path Curve_common::Generate_Line(robot_geometry_msgs::Point start_point, robot_geometry_msgs::Point end_point, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path line_result; - robot_geometry_msgs::PoseStamped current_pose; - - line_result.header.frame_id = frame_id; - line_result.header.stamp = robot::Time::now(); - - current_pose.header.frame_id = frame_id; - - int segment = 1 / t_intervel; - double line_parameter = 0; - - for(int i = 0; i < segment; i++) - { - current_pose.header.seq = i; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = start_point.x * (1 - line_parameter) + end_point.x * (line_parameter); - current_pose.pose.position.y = start_point.y * (1 - line_parameter) + end_point.y * (line_parameter); - - line_result.poses.push_back(current_pose); - line_parameter += t_intervel; - } - - std::cout << "End cacluation" << "\n"; - return line_result; -} - -robot_nav_msgs::Path Curve_common::Generate_BezierCurve(EigenTrajectoryPoint::Vector control_point, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path bezier_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - EigenTrajectoryPoint::Vector temp_control_point_vec; - - bezier_curve_result.header.frame_id = frame_id; - bezier_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int segment = 1 / t_intervel; - int control_point_length = control_point.size(); - double curve_parameter = 0; - temp_control_point_vec.reserve(control_point_length); - - for(int i = 0; i <= segment; i++) - { - temp_control_point_vec.assign(control_point.begin(), control_point.end()); - - for(int j = 1; j <= control_point_length - 1; j++) - { - for(int k = 1; k <= control_point_length - j; k++) - { - temp_control_point_vec.at(k - 1).position(0) = temp_control_point_vec.at(k - 1).position(0) * (1 - curve_parameter) + temp_control_point_vec.at(k).position(0) * curve_parameter; - temp_control_point_vec.at(k - 1).position(1) = temp_control_point_vec.at(k - 1).position(1) * (1 - curve_parameter) + temp_control_point_vec.at(k).position(1) * curve_parameter; - } - } - current_pose.header.seq = i; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = temp_control_point_vec.at(0).position(0); - current_pose.pose.position.y = temp_control_point_vec.at(0).position(1); - bezier_curve_result.poses.push_back(current_pose); - curve_parameter += t_intervel; - } - - std::cout << "End calculate Bezier Curve" << "\n"; - return bezier_curve_result; -} - -void Curve_common::ReadDiscreate2DPointFromLaunch(EigenTrajectoryPoint::Vector *input_point, std::vector file_discreate_point) -{ - int index = 0; - Eigen::Vector3d read_point; - EigenTrajectoryPoint eigen_discreate_point; - input_point->reserve(static_cast(file_discreate_point.size()) / 2); - - for(int i = 0; i < static_cast(file_discreate_point.size()); i++) - { - if(i % 2 == 0) - { - read_point(0) = file_discreate_point[i]; - } - else - { - read_point(1) = file_discreate_point[i]; - eigen_discreate_point.position = read_point; - //input_point->emplace_back(dis_control_point); //I don't know why have error - input_point->push_back(eigen_discreate_point); - index++; - } - } - - //Debug use - // std::cout << "input control point size : " << input_control_point->size() << "\n"; - // for(int i = 0; i < input_control_point->size(); i++) - // { - // std::cout << "control point x : " << input_control_point->at(i).position(0) << "\n"; - // std::cout << "control point y : " << input_control_point->at(i).position(1) << "\n"; - // } -} - -void Curve_common::ReadDiscreate2DPointFromLaunch(std::vector > *input_point, std::vector file_discreate_point) -{ - Eigen::Vector3d read_point; - input_point->reserve(static_cast(file_discreate_point.size()) / 2); - - for(int i = 0; i < static_cast(file_discreate_point.size()); i++) - { - if(i % 2 == 0) - { - read_point(0) = file_discreate_point[i]; - } - else - { - read_point(1) = file_discreate_point[i]; - input_point->push_back(read_point); - } - } - - //Debug use - // std::cout << "input control point size : " << input_point->size() << "\n"; - // for(int i = 0; i < input_point->size(); i++) - // { - // std::cout << "control point x : " << input_point->at(i)(0) << "\n"; - // std::cout << "control point y : " << input_point->at(i)(1) << "\n"; - // } -} - -robot_visualization_msgs::Marker Curve_common::ShowDiscreatePoint(std::vector > discreate_point, const std::string& frame_id, const std::string& name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - //waypoints_marker.color = color; - waypoints_marker.color.r = 1; - waypoints_marker.color.g = 1; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(static_cast(discreate_point.size())); - - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker Curve_common::ShowDiscreatePoint2(std::vector > discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - waypoints_marker.color = point_color; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(static_cast(discreate_point.size())); - - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker Curve_common::ShowDiscreatePoint(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, const std::string& name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - //waypoints_marker.color = color; - waypoints_marker.color.r = 1; - waypoints_marker.color.g = 1; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(static_cast(discreate_point.size())); - - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -robot_visualization_msgs::Marker Curve_common::ShowDiscreatePoint2(EigenTrajectoryPoint::Vector& discreate_point, const std::string& frame_id, robot_std_msgs::ColorRGBA point_color, const std::string& name, double scale) -{ - robot_visualization_msgs::Marker waypoints_marker; - - waypoints_marker.header.frame_id = frame_id; - waypoints_marker.header.stamp = robot::Time::now(); - waypoints_marker.type = robot_visualization_msgs::Marker::SPHERE_LIST; - waypoints_marker.color = point_color; - // waypoints_marker.color.r = r; - // waypoints_marker.color.g = g; - // waypoints_marker.color.b = b; - waypoints_marker.color.a = 0.75; - waypoints_marker.ns = name; - waypoints_marker.scale.x = scale; - waypoints_marker.scale.y = scale; - waypoints_marker.scale.z = scale; - - waypoints_marker.points.reserve(static_cast(discreate_point.size())); - - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - waypoints_marker.points.push_back(view_point); - } - - return waypoints_marker; -} - -void Curve_common::ShowDiscreatePoint(robot_visualization_msgs::Marker *points, EigenTrajectoryPoint::Vector discreate_point) -{ - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i).position(0); - view_point.y = discreate_point.at(i).position(1); - points->points.push_back(view_point); - } -} - -void Curve_common::ShowDiscreatePoint(robot_visualization_msgs::Marker *points, std::vector > discreate_point) -{ - robot_geometry_msgs::Point view_point; - for(int i = 0; i < static_cast(discreate_point.size()); i++) - { - view_point.x = discreate_point.at(i)(0); - view_point.y = discreate_point.at(i)(1); - points->points.push_back(view_point); - } -} - void Curve_common::ReadSplineInf(Spline_Inf *bspline_inf, int order, std::vector > control_point, std::vector knot_vector) { bspline_inf->order = order; bspline_inf->knot_vector.assign(knot_vector.begin(), knot_vector.end()); bspline_inf->control_point.assign(control_point.begin(), control_point.end()); - - //Debug use - // std::cout << "knot vector size : " << bspline_inf->knot_vector.size() << "\n"; - // for(int i = 0; i < bspline_inf->knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf->knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf->control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf->control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf->control_point.at(i)(0) << ", y = " << bspline_inf->control_point.at(i)(1) << "\n"; - // } } void Curve_common::ReadSplineInf(Spline_Inf *spline_inf, std::vector weight_vector, bool use_limit_derivative_fitting) @@ -310,850 +31,6 @@ void Curve_common::ReadSplineInf(Spline_Inf *spline_inf, std::vector wei } spline_inf->weight.assign(weight_vector.begin(), weight_vector.end()); - - - //Debug use - // std::cout << "knot vector size : " << spline_inf->knot_vector.size() << "\n"; - // for(int i = 0; i < spline_inf->knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << spline_inf->knot_vector.at(i) << "\n"; - // } - - // std::cout << "control point size : " << static_cast(spline_inf->control_point.size()) << "\n"; - // for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - // { - // std::cout << "control point x : " << spline_inf->control_point.at(i)(0) << ", y = " << spline_inf->control_point.at(i)(1) << "\n"; - // } -} - -robot_nav_msgs::Path Curve_common::Generate_BsplineCurve(Spline_Inf bspline_inf, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path bspline_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - - bspline_curve_result.header.frame_id = frame_id; - bspline_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - //TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; //The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 100; - double curve_parameter = 0; - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double sum_x = 0, sum_y = 0; - std::vector curve_parameter_vec; - Eigen::VectorXd temp_basic_function; - std::vector > temp_basic_function_eigen; - - //Debug use - // for(int i = 0; i < bspline_inf.knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf.knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf.control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf.control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf.control_point.at(i)(0) << ", y = " << bspline_inf.control_point.at(i)(1) << "\n"; - // } - - //TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for(int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - bspline_inf.N.clear(); - temp_basic_function.resize(segment); - - //TODO: Check basic function boundary is correct - //Calculate degree = 0's basic function - for(int i = 0; i < m; i++) - { - if(bspline_inf.knot_vector.at(i) != bspline_inf.knot_vector.at(n)) - { - for(int u = 0; u < segment; u++) - { - if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < bspline_inf.knot_vector.at(i+1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - //std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - else - { - for(int u = 0; u < segment; u++) - { - if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i+1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - //std::cout << "temp basic function index : " << u << "temp basic function value : " << temp_basic_function(u) << "\n"; - //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - - - // if(bspline_inf.knot_vector.at(i) < bspline_inf.knot_vector.at(i+1)) - // { - // if(bspline_inf.knot_vector.at(i) != bspline_inf.knot_vector.at(n)) - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - // else - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "n basic function index : " << u << " n basic function value : " << temp_basic_function(u) << "\n"; - // //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - // } - // else - // { - // for(int u = 0; u < segment; u++) - // { - // if(bspline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= bspline_inf.knot_vector.at(i+1)) - // temp_basic_function(u) = 1; - // else - // temp_basic_function(u) = 0; - - // std::cout << "temp basic function index : " << u << " temp basic function value : " << temp_basic_function(u) << "\n"; - // } - // } - bspline_inf.N.push_back(temp_basic_function); - //std::cout << i << "'s bspline_inf Ni,0 size " << temp_basic_function.size() << "\n"; - } - - //Calculate the rest of basic function - for(int p = 1; p <= p_degree; p++) - { - temp_basic_function_eigen.clear(); - for(int i = 0; i < (m - p); i++) - { - for(int u = 0; u < segment; u++) - { - left_denom = bspline_inf.knot_vector.at(p+i) - bspline_inf.knot_vector.at(i); - right_denom = bspline_inf.knot_vector.at(i+p+1) - bspline_inf.knot_vector.at(i+1); - - if(left_denom == 0) - left_term = 0; - else - left_term = (curve_parameter_vec[u] - bspline_inf.knot_vector.at(i)) * bspline_inf.N.at(i)(u) / left_denom; - - if(right_denom == 0) - right_term = 0; - else - right_term = (bspline_inf.knot_vector.at(i+p+1) - curve_parameter_vec[u]) * bspline_inf.N.at(i+1)(u) / right_denom; - - temp_basic_function(u) = left_term + right_term; - } - temp_basic_function_eigen.push_back(temp_basic_function); - } - bspline_inf.N = temp_basic_function_eigen; - } - - for(int u = 0; u < segment; u++) - { - sum_x = 0; - sum_y = 0; - for(int i = 0; i < static_cast(bspline_inf.N.size()); i++) - { - sum_x += bspline_inf.control_point.at(i)(0) * bspline_inf.N.at(i)(u); - sum_y += bspline_inf.control_point.at(i)(1) * bspline_inf.N.at(i)(u); - //std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; - } - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = sum_x; - current_pose.pose.position.y = sum_y; - bspline_curve_result.poses.push_back(current_pose); - } - - std::cout << "End Calculate" << "\n"; - return bspline_curve_result; -} - -robot_nav_msgs::Path Curve_common::Generate_NURBSCurve(Spline_Inf spline_inf, double t_intervel, std::string frame_id) -{ - robot_nav_msgs::Path nurbs_curve_result; - robot_geometry_msgs::PoseStamped current_pose; - - nurbs_curve_result.header.frame_id = frame_id; - nurbs_curve_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = spline_inf.order - 1; - int n = spline_inf.control_point.size() - 1; - //TODO: Check knot vector size and sequence is correect - int m = spline_inf.knot_vector.size() - 1; //The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 100; - double curve_parameter = 0; - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double sum_nurbs_denom = 0; - double sum_x = 0, sum_y = 0; - std::vector curve_parameter_vec; - Eigen::VectorXd temp_basic_function; - std::vector > temp_basic_function_eigen; - - //Debug use - // for(int i = 0; i < bspline_inf.knot_vector.size(); i++) - // { - // std::cout << "knot vector x : " << bspline_inf.knot_vector.at(i) << "\n"; - // } - - // std::cout << "input control point size : " << bspline_inf.control_point.size() << "\n"; - // for(int i = 0; i < bspline_inf.control_point.size(); i++) - // { - // std::cout << "control point x : " << bspline_inf.control_point.at(i)(0) << ", y = " << bspline_inf.control_point.at(i)(1) << "\n"; - // } - - if(spline_inf.weight.size() == 0) - { - std::cout << "weight vector size is zero, please call read ReadSplineInf function" << "\n"; - return nurbs_curve_result; - } - - //TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for(int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - spline_inf.N.clear(); - temp_basic_function.resize(segment); - - //TODO: Check basic function boundary is correct - //Calculate degree = 0's basic function - for(int i = 0; i < m; i++) - { - //if(spline_inf.knot_vector.at(i) != spline_inf.knot_vector.at(n)) - if(spline_inf.knot_vector.at(i) != spline_inf.knot_vector.at(i+1)) - { - for(int u = 0; u < segment; u++) - { - if(spline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] < spline_inf.knot_vector.at(i+1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - //std::cout << "small temp basic function index : " << u << " small temp basic function value : " << temp_basic_function(u) << "\n"; - //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - else - { - for(int u = 0; u < segment; u++) - { - if(spline_inf.knot_vector.at(i) <= curve_parameter_vec[u] && curve_parameter_vec[u] <= spline_inf.knot_vector.at(i+1)) - temp_basic_function(u) = 1; - else - temp_basic_function(u) = 0; - - //std::cout << "temp basic function index : " << u << "temp basic function value : " << temp_basic_function(u) << "\n"; - //std::cout << "small temp basic function value : " << temp_basic_function(u) << "\n"; - } - } - - spline_inf.N.push_back(temp_basic_function); - //std::cout << i << "'s bspline_inf Ni,0 size " << temp_basic_function.size() << "\n"; - } - - //Calculate the rest of basic function - for(int p = 1; p <= p_degree; p++) - { - temp_basic_function_eigen.clear(); - for(int i = 0; i < (m - p); i++) //m-p is calculate how many region between basis function - { - for(int u = 0; u < segment; u++) - { - left_denom = spline_inf.knot_vector.at(p+i) - spline_inf.knot_vector.at(i); - right_denom = spline_inf.knot_vector.at(i+p+1) - spline_inf.knot_vector.at(i+1); - - if(left_denom == 0) - left_term = 0; - else - left_term = (curve_parameter_vec[u] - spline_inf.knot_vector.at(i)) * spline_inf.N.at(i)(u) / left_denom; - - if(right_denom == 0) - right_term = 0; - else - right_term = (spline_inf.knot_vector.at(i+p+1) - curve_parameter_vec[u]) * spline_inf.N.at(i+1)(u) / right_denom; - - temp_basic_function(u) = left_term + right_term; - } - temp_basic_function_eigen.push_back(temp_basic_function); - } - spline_inf.N = temp_basic_function_eigen; - } - - for(int u = 0; u < segment; u++) - { - sum_nurbs_denom = 0; - sum_x = 0; - sum_y = 0; - for(int i = 0; i < static_cast(spline_inf.N.size()); i++) - { - sum_nurbs_denom += spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - sum_x += spline_inf.control_point.at(i)(0) * spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - sum_y += spline_inf.control_point.at(i)(1) * spline_inf.N.at(i)(u) * spline_inf.weight.at(i); - //std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; - } - sum_x /= sum_nurbs_denom; - sum_y /= sum_nurbs_denom; - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = sum_x; - current_pose.pose.position.y = sum_y; - nurbs_curve_result.poses.push_back(current_pose); - } - - std::cout << "End calculate NURBS function" << "\n"; - return nurbs_curve_result; -} - -void Curve_common::CalculateDerivativeBasisFunc(Spline_Inf *spline_inf, double u_data, int differential_times) -{ - int p_degree = spline_inf->order - 1; - int n = static_cast(spline_inf->control_point.size()) - 1; - //TODO: Check knot vector size and sequence is correect - int m = spline_inf->knot_vector.size() - 1; //The last knot vector index number - double left_denom = 0, right_denom = 0; - double left_term = 0, right_term = 0; - double derivative_left_term = 0, derivative_right_term = 0; - double derivative_value = 0; - std::vector temp_basic_function; - Eigen::VectorXd derivative_temp_basic_function; - double degree_basis_value; - std::vector > derivative_basic_function_eigen; - - //Calculate degree = 0's basic function - spline_inf->N_double_vec.clear(); - spline_inf->N_double_vec.resize(m); - for(int i = 0; i < m; i++) - { - // if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(n)) - if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(i+1)) - { - if(spline_inf->knot_vector.at(i) <= u_data && u_data < spline_inf->knot_vector.at(i+1)) - degree_basis_value = 1; - else - degree_basis_value = 0; - } - else - { - if(spline_inf->knot_vector.at(i) <= u_data && u_data <= spline_inf->knot_vector.at(i+1)) - degree_basis_value = 1; - else - degree_basis_value = 0; - } - - spline_inf->N_double_vec.at(i) = degree_basis_value; - } - - //Calculate the rest of basic function - spline_inf->dN.clear(); - for(int p = 1; p <= p_degree; p++) - { - temp_basic_function.clear(); - derivative_temp_basic_function.resize(m-p); - for(int i = 0; i < (m - p); i++) - { - left_denom = spline_inf->knot_vector.at(p+i) - spline_inf->knot_vector.at(i); - right_denom = spline_inf->knot_vector.at(i+p+1) - spline_inf->knot_vector.at(i+1); - - if(left_denom == 0) - { - left_term = 0; - derivative_left_term = 0; - } - else - { - left_term = (u_data - spline_inf->knot_vector.at(i)) * spline_inf->N_double_vec.at(i) / left_denom; - derivative_left_term = spline_inf->N_double_vec.at(i) / left_denom; - } - - if(right_denom == 0) - { - right_term = 0; - derivative_right_term = 0; - } - else - { - right_term = (spline_inf->knot_vector.at(i+p+1) - u_data) * spline_inf->N_double_vec.at(i+1) / right_denom; - derivative_right_term = spline_inf->N_double_vec.at(i+1) / right_denom; - } - - derivative_value = p * (derivative_left_term - derivative_right_term); - temp_basic_function.push_back(left_term + right_term); //Calculate Ni,p - derivative_temp_basic_function(i) = derivative_value; //Calculate dNi,p - } - spline_inf->N_double_vec.assign(temp_basic_function.begin(), temp_basic_function.end()); - spline_inf->dN.push_back(derivative_temp_basic_function); - } - - if(differential_times > 1) - { - spline_inf->ddN.clear(); - for(int p = 2; p <= p_degree; p++) - { - derivative_temp_basic_function.resize(m-p); - for(int i = 0; i < (m - p); i++) - { - left_denom = spline_inf->knot_vector.at(p+i) - spline_inf->knot_vector.at(i); - right_denom = spline_inf->knot_vector.at(i+p+1) - spline_inf->knot_vector.at(i+1); - - if(left_denom == 0) - derivative_left_term = 0; - else - derivative_left_term = spline_inf->dN.at(p-2)(i) / left_denom; - - if(right_denom == 0) - derivative_right_term = 0; - else - derivative_right_term = spline_inf->dN.at(p-2)(i+1) / right_denom; - - derivative_value = p * (derivative_left_term - derivative_right_term); - derivative_temp_basic_function(i) = derivative_value; //Calculate ddNi,p - } - spline_inf->ddN.push_back(derivative_temp_basic_function); - } - } -} - -robot_geometry_msgs::Point Curve_common::CalculateDerivativeCurvePoint(Spline_Inf *spline_inf, double u_data, int differential_times, bool UsingNURBS) -{ - robot_geometry_msgs::Point derivative_curve_point; - int p_degree = spline_inf->order - 1; - double sum_x = 0, sum_y = 0; - double sum_denom = 0; - double sum_derivative_once_denom = 0; - double sum_derivative_twice_denom = 0; - double R_fraction = 0; - double dR_left_term_fraction = 0; - double dR_right_term = 0; - double ddR_left_term_fraction = 0; - double ddR_median_term_fraction = 0; - double ddR_right_term_fraction = 0; - - spline_inf->R_double_vec.clear(); - spline_inf->dR_double_vec.clear(); - spline_inf->ddR_double_vec.clear(); - - //Debug use - // std::cout << "N_double_vec :" << "\n"; - // for(int i = 0; i < spline_inf->N_double_vec.size(); i++) - // { - // std::cout << spline_inf->N_double_vec.at(i) << " "; - // } - // std::cout << "\n"; - - // std::cout << "dN :" << "\n"; - // for(int i = 0; i < spline_inf->dN.back().size(); i++) - // { - // std::cout << spline_inf->dN.back()(i) << " "; - // } - // std::cout << "\n"; - - //TODO: Safety check - if(UsingNURBS == false) - { - if(differential_times == 1) - { - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->dN.back()(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->dN.back()(i); - // std::cout << i << "'s spline_inf.dN : " << spline_inf->dN.back()(i) << "\n"; - } - } - if(differential_times == 2) - { - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->ddN.back()(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->ddN.back()(i); - // std::cout << i << "'s spline_inf.ddN : " << spline_inf->ddN.back()(i) << "\n"; - } - } - } - else - { - //TODO: Safety check differential_times - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - sum_denom += spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - sum_derivative_once_denom += spline_inf->dN.back()(i) * spline_inf->weight.at(i); - if(differential_times == 2) - sum_derivative_twice_denom += spline_inf->ddN.back()(i) * spline_inf->weight.at(i); - } - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - if(sum_denom != 0) - { - R_fraction = spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - - dR_left_term_fraction = spline_inf->dN.back()(i) * spline_inf->weight.at(i); - dR_right_term = R_fraction * sum_derivative_once_denom / std::pow(sum_denom, 2); - - if(differential_times == 2) - { - ddR_left_term_fraction = spline_inf->ddN.back()(i) * spline_inf->weight.at(i); - ddR_median_term_fraction = 2 * dR_left_term_fraction * sum_derivative_once_denom + R_fraction * sum_derivative_twice_denom; - ddR_right_term_fraction = 2 * R_fraction * std::pow(sum_derivative_once_denom, 2); - spline_inf->ddR_double_vec.push_back( (ddR_left_term_fraction / sum_denom) - (ddR_median_term_fraction / std::pow(sum_denom, 2)) + (ddR_right_term_fraction / std::pow(sum_denom, 3)) ); - } - - spline_inf->R_double_vec.push_back(R_fraction / sum_denom); - spline_inf->dR_double_vec.push_back((dR_left_term_fraction / sum_denom) - dR_right_term); - } - else - { - spline_inf->R_double_vec.push_back(0); - spline_inf->dR_double_vec.push_back(0); - spline_inf->ddR_double_vec.push_back(0); - } - } - - if(differential_times == 1) - { - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->dR_double_vec.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->dR_double_vec.at(i); - //std::cout << i << "'s spline_inf.dN : " << spline_inf->dN.back()(i) << "\n"; - } - } - if(differential_times == 2) - { - for(int i = 0; i < static_cast(spline_inf->control_point.size()); i++) - { - sum_x += spline_inf->control_point.at(i)(0) * spline_inf->ddR_double_vec.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->ddR_double_vec.at(i); - } - } - } - - derivative_curve_point.x = sum_x; - derivative_curve_point.y = sum_y; - derivative_curve_point.z = 0; - - //Debug use - // std::cout << u_data << "'s derivative current_pose x : " << derivative_curve_point.x << "\n"; - // std::cout << u_data << "'s derivative current_pose y : " << derivative_curve_point.y << "\n"; - - return derivative_curve_point; -} - -robot_nav_msgs::Path Curve_common::Generate_DerivativeBsplineCurve(Spline_Inf bspline_inf, int differential_times, double t_intervel, std::string frame_id) -{ - robot_geometry_msgs::Point derivative_point_result; - robot_nav_msgs::Path bspline_derivative_result; - robot_geometry_msgs::PoseStamped current_pose; - - bspline_derivative_result.header.frame_id = frame_id; - bspline_derivative_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - //TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; //The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 0; - double curve_parameter = 0; - std::vector curve_parameter_vec; - - //TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for(int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - //TODO: Can support high order derivative in loop - for(int u = 0; u < segment; u++) - { - CalculateDerivativeBasisFunc(&bspline_inf, curve_parameter_vec[u], differential_times); - derivative_point_result = CalculateDerivativeCurvePoint(&bspline_inf, curve_parameter_vec[u], differential_times, false); - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = derivative_point_result.x; - current_pose.pose.position.y = derivative_point_result.y; - bspline_derivative_result.poses.push_back(current_pose); - } - - return bspline_derivative_result; -} - -robot_nav_msgs::Path Curve_common::Generate_DerivativeBasisFuncCurve(Spline_Inf bspline_inf, int differential_times, int index, double t_intervel, std::string frame_id) -{ - robot_geometry_msgs::Point derivative_point_result; - robot_nav_msgs::Path derivative_basis_result; - robot_geometry_msgs::PoseStamped current_pose; - - derivative_basis_result.header.frame_id = frame_id; - derivative_basis_result.header.stamp = robot::Time::now(); - current_pose.header.frame_id = frame_id; - - //TODO: Add error ckeck function(below code with error) - // if(differential_times == 0 && index < bspline_inf.N_double_vec.size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.N_double_vec.size() << "\n"; - // return derivative_basis_result; - // } - // if(differential_times == 1 && index < bspline_inf.dN.back().size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.dN.back().size() << "\n"; - // return derivative_basis_result; - // } - // if(differential_times == 2 && index < bspline_inf.ddN.back().size()) - // { - // std::cout << "Without this index's basis function, vector size is :" << bspline_inf.ddN.back().size() << "\n"; - // return derivative_basis_result; - // } - - int p_degree = bspline_inf.order - 1; - int n = bspline_inf.control_point.size() - 1; - //TODO: Check knot vector size and sequence is correect - int m = bspline_inf.knot_vector.size() - 1; //The last knot vector index number - int segment = 1 / t_intervel; - double delta_t = 0; - double curve_parameter = 0; - std::vector curve_parameter_vec; - - //TODO: Can optimal this part code - delta_t = 1 / (double)(segment - 1); - curve_parameter_vec.resize(segment); - for(int u = 0; u < segment; u++) - { - curve_parameter_vec[u] = curve_parameter; - curve_parameter += delta_t; - } - - //TODO: Can support high order derivative in loop - for(int u = 0; u < segment; u++) - { - CalculateDerivativeBasisFunc(&bspline_inf, curve_parameter_vec[u], differential_times); - current_pose.header.seq = u; - current_pose.header.stamp = robot::Time::now(); - current_pose.pose.position.x = curve_parameter_vec[u]; - if(differential_times == 0) - current_pose.pose.position.y = bspline_inf.N_double_vec.at(index); - else if(differential_times == 1) - current_pose.pose.position.y = bspline_inf.dN.back()(index); - else - current_pose.pose.position.y = bspline_inf.ddN.back()(index); - derivative_basis_result.poses.push_back(current_pose); - } - - return derivative_basis_result; -} - -double Curve_common::CalculateCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - if(u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return 0; - } - - if(u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - double curvature = 0; - double fraction = 0; - double denominator = 0; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - fraction = derivative_once_point.cross(derivative_twice_point).lpNorm<2>(); - denominator = std::pow(derivative_once_point.lpNorm<2>(), 3); - - if(denominator == 0) - curvature = 0; - else - curvature = fraction / denominator; - - //TODO: Check curvature direction (but in nurbs planner not useful) - // Eigen::Vector3d direction_vector; //curvature direction - // direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - // if(direction_vector(0) < 0 && direction_vector(1) < 0 || direction_vector(0) > 0 && direction_vector(1) < 0) - // curvature *= -1; - - return curvature; -} - -double Curve_common::CalculateSignedCurvature(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - if(u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return 0; - } - - if(u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - double curvature = 0; - double fraction = 0; - double denominator = 0; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - fraction = derivative_once_point.cross(derivative_twice_point).lpNorm<2>(); - denominator = std::pow(derivative_once_point.lpNorm<2>(), 3); - - if(denominator == 0) - curvature = 0; - else - curvature = fraction / denominator; - - //TODO: Check curvature direction (but in nurbs planner not useful) - Eigen::Vector3d direction_vector; //curvature direction - direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - if(direction_vector(0) < 0 && direction_vector(1) < 0 || direction_vector(0) > 0 && direction_vector(1) < 0) - curvature *= -1; - - return curvature; -} - -Eigen::Vector3d Curve_common::CalculateCurvatureDirectionVector(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - Eigen::Vector3d direction_vector; - if(u_data < 0) - { - std::cout << "Error, u_data need bigger than 0" << "\n"; - std::cout << "error u_data value is: " << u_data << "\n"; - return direction_vector; - } - - if(u_data > 1) - { - std::cout << "Error!! because u_data bigger than 1, maybe is program numerical error" << "\n"; - u_data = 1; - } - - - Eigen::Vector3d derivative_once_point; - Eigen::Vector3d derivative_twice_point; - - CalculateDerivativeBasisFunc(&spline_inf, u_data, 2); - derivative_once_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 1, UsingNURBS)); - derivative_twice_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_data, 2, UsingNURBS)); - - direction_vector = derivative_once_point.cross(derivative_twice_point.cross(derivative_once_point)); - // std::cout << "direction vector x: " << direction_vector(0) << "\n"; - // std::cout << "direction vector y: " << direction_vector(1) << "\n"; - // std::cout << "direction vector z: " << direction_vector(2) << "\n"; - - return direction_vector; -} - -double Curve_common::CalculateCurvatureRadius(Spline_Inf spline_inf, double u_data, bool UsingNURBS) -{ - double curvature_radius = 0; - double curvature = 0; - - curvature = CalculateCurvature(spline_inf, u_data, UsingNURBS); - - if(curvature == 0) - return curvature_radius = 0; - else - return curvature_radius = 1 / curvature; -} - -double Curve_common::CalculateCurveLength(Spline_Inf spline_inf, double start_u, double end_u, int sub_intervals, bool UsingNURBS) -{ - if(sub_intervals % 2 != 0) - { - std::cout << "Error! sub_intervals value is a even number" << "\n"; - return 0; - } - - Eigen::Vector3d eigen_derivative_point; - double sum_length = 0; - double interval = 0; - double u_index = 0; - - interval = (end_u - start_u) / (double)sub_intervals; - - for(int i = 0; i <= sub_intervals; i++) - { - u_index = start_u + interval * i; - CalculateDerivativeBasisFunc(&spline_inf, u_index, 1); - eigen_derivative_point = EigenVecter3dFromPointMsg(CalculateDerivativeCurvePoint(&spline_inf, u_index, 1, UsingNURBS)); - - if(i == 0 || i == sub_intervals) - sum_length += eigen_derivative_point.lpNorm<2>(); - else if((i % 2) == 1) - sum_length += 4 * eigen_derivative_point.lpNorm<2>(); - else if((i % 2) == 0) - sum_length += 2 * eigen_derivative_point.lpNorm<2>(); - } - - sum_length *= interval / 3; - - return sum_length; } robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_inf, double u_data, bool UsingNURBS) @@ -1162,7 +39,6 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ robot_geometry_msgs::Point curve_point; int p_degree = spline_inf->order - 1; - int n = static_cast(spline_inf->control_point.size()) - 1; //TODO: Check knot vector size and sequence is correect int m = spline_inf->knot_vector.size() - 1; //The last knot vector index number double left_denom = 0, right_denom = 0; @@ -1170,24 +46,23 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ std::vector temp_basic_function; double degree_basis_value; double sum_nurbs_denom = 0; - double sum_x = 0, sum_y = 0; + double sum_x = 0, sum_y = 0; //Calculate degree = 0's basic function spline_inf->N_double_vec.clear(); spline_inf->N_double_vec.resize(m); for(int i = 0; i < m; i++) { - // if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(n)) if(spline_inf->knot_vector.at(i) != spline_inf->knot_vector.at(i+1)) { - if(spline_inf->knot_vector.at(i) <= u_data && u_data < spline_inf->knot_vector.at(i+1)) + if(spline_inf->knot_vector.at(i) <= u_data && u_data < spline_inf->knot_vector.at(i+1)) degree_basis_value = 1; else degree_basis_value = 0; } else - { - if(spline_inf->knot_vector.at(i) <= u_data && u_data <= spline_inf->knot_vector.at(i+1)) + { + if(spline_inf->knot_vector.at(i) <= u_data && u_data <= spline_inf->knot_vector.at(i+1)) degree_basis_value = 1; else degree_basis_value = 0; @@ -1198,7 +73,7 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ //Calculate the rest of basic function for(int p = 1; p <= p_degree; p++) - { + { temp_basic_function.clear(); for(int i = 0; i < (m - p); i++) { @@ -1208,20 +83,20 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ if(left_denom == 0) { left_term = 0; - } + } else { left_term = (u_data - spline_inf->knot_vector.at(i)) * spline_inf->N_double_vec.at(i) / left_denom; } - + if(right_denom == 0) { right_term = 0; - } + } else { right_term = (spline_inf->knot_vector.at(i+p+1) - u_data) * spline_inf->N_double_vec.at(i+1) / right_denom; - } + } temp_basic_function.push_back(left_term + right_term); //Calculate Ni,p } spline_inf->N_double_vec.assign(temp_basic_function.begin(), temp_basic_function.end()); @@ -1230,15 +105,12 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ if(!UsingNURBS) { for(int i = 0; i < static_cast(spline_inf->N_double_vec.size()); i++) - { + { sum_x += spline_inf->control_point.at(i)(0) * spline_inf->N_double_vec.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i); - //std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; + sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i); } - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; curve_point.x = sum_x; - curve_point.y = sum_y; + curve_point.y = sum_y; } else { @@ -1246,24 +118,21 @@ robot_geometry_msgs::Point Curve_common::CalculateCurvePoint(Spline_Inf *spline_ { std::cout << "weight vector size is zero, please call read ReadSplineInf function" << "\n"; curve_point.x = 0; - curve_point.y = 0; + curve_point.y = 0; return curve_point; } for(int i = 0; i < static_cast(spline_inf->N_double_vec.size()); i++) - { + { sum_nurbs_denom += spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); sum_x += spline_inf->control_point.at(i)(0) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); - //std::cout << i << "'s ," << u <<"'s bspline_inf value : " << bspline_inf.N.at(i)(u) << "\n"; + sum_y += spline_inf->control_point.at(i)(1) * spline_inf->N_double_vec.at(i) * spline_inf->weight.at(i); } sum_x /= sum_nurbs_denom; sum_y /= sum_nurbs_denom; - // std::cout << u << "'s current_pose x : " << sum_x << "\n"; - // std::cout << u << "'s current_pose y : " << sum_y << "\n"; curve_point.x = sum_x; - curve_point.y = sum_y; + curve_point.y = sum_y; } - + return curve_point; -} \ No newline at end of file +} diff --git a/src/custom_planner.cpp b/src/custom_planner.cpp index dd633cd..4dbb9b9 100755 --- a/src/custom_planner.cpp +++ b/src/custom_planner.cpp @@ -1,8 +1,5 @@ #include -#include #include -#include -#include #include using namespace std; @@ -10,9 +7,7 @@ using namespace std; namespace custom_planner { CustomPlanner::CustomPlanner() - : input_spline_inf_(nullptr), - CurveDesign_(nullptr), - initialized_(false), + : initialized_(false), costmap_robot_(nullptr), current_env_width_(0), current_env_height_(0) @@ -20,9 +15,7 @@ namespace custom_planner } CustomPlanner::CustomPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot) - : input_spline_inf_(nullptr), - CurveDesign_(nullptr), - initialized_(false), + : initialized_(false), costmap_robot_(nullptr), current_env_width_(0), current_env_height_(0) @@ -30,12 +23,6 @@ namespace custom_planner 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_) @@ -49,12 +36,14 @@ namespace custom_planner return false; } - robot::NodeHandle private_nh("~/" + name); - robot::NodeHandle p_nh("~"); + // KHÔNG dùng "~/" + name: NodeHandle không resolve segment "~", âm thầm rơi + // về root và mọi getParam trả default. Namespace trần "" mới khớp + // root key "CustomPlanner:" trong custom_global_params.yaml. + robot::NodeHandle private_nh(name); robot::log_info("Name is %s", name.c_str()); - input_spline_inf_ = new Spline_Inf(); - CurveDesign_ = new Curve_common(); + config_.load(private_nh); + merge_path_calc_.desired_point_spacing_ = config_.nurbs_point_spacing; name_ = name; costmap_robot_ = costmap_robot; @@ -128,8 +117,8 @@ namespace custom_planner merge_path_calc_.store_start_nearest_idx_ = nearest_idx; // ===== STEP 5: CALCULATE DISTANCES ===== - const double DISTANCE_THRESHOLD = 0.1; - + const double DISTANCE_THRESHOLD = config_.pathway_attach_distance; + robot::Time plan_time = robot::Time::now(); // Calculate distance from start to nearest pathway point @@ -346,41 +335,11 @@ namespace custom_planner plan[i].header.seq = i; } - // Publish plan for visualization - robot_nav_msgs::Path gui_path; - gui_path.header.frame_id = costmap_robot_->getGlobalFrameID(); - gui_path.header.stamp = plan_time; - gui_path.poses = plan; - // plan_pub_.publish(gui_path); - robot::log_info("[custom_planner] Generated plan with %zu waypoints", plan.size()); return true; } - void CustomPlanner::transformFootprintToEdges(const robot_geometry_msgs::Pose &robot_pose, - const std::vector &footprint, - std::vector &out_footprint) - { - out_footprint.resize(2 * footprint.size()); - double yaw = data_convert::getYaw(robot_pose.orientation); - for (unsigned int i = 0; i < footprint.size(); i++) - { - out_footprint[2 * i].x = robot_pose.position.x + cos(yaw) * footprint[i].x - sin(yaw) * footprint[i].y; - out_footprint[2 * i].y = robot_pose.position.y + sin(yaw) * footprint[i].x + cos(yaw) * footprint[i].y; - if (i == 0) - { - out_footprint.back().x = out_footprint[i].x; - out_footprint.back().y = out_footprint[i].y; - } - else - { - out_footprint[2 * i - 1].x = out_footprint[2 * i].x; - out_footprint[2 * i - 1].y = out_footprint[2 * i].y; - } - } - } - - bool CustomPlanner::makePlanWithOrder(robot_protocol_msgs::Order msg, + bool CustomPlanner::makePlanWithOrder(robot_protocol_msgs::Order msg, const robot_geometry_msgs::PoseStamped& start, const robot_geometry_msgs::PoseStamped& goal) { @@ -401,7 +360,7 @@ namespace custom_planner double delta_x = start.pose.position.x - goal.pose.position.x; double delta_y = start.pose.position.y - goal.pose.position.y; double distance_start_to_goal = std::hypot(delta_x, delta_y); - if(distance_start_to_goal > 0.2) { + if(distance_start_to_goal > config_.bare_goal_max_distance) { return false; } else { posesOnPathWay_.push_back(Pose(start.pose.position.x, start.pose.position.y, data_convert::getYaw(start.pose.orientation))); @@ -494,16 +453,16 @@ namespace custom_planner if(curveIsValid(degree, knot_vector, control_points)) { - double t_intervel = 0.01; + double t_intervel = config_.nurbs_length_t_interval; order = degree + 1; - input_spline_inf_->control_point.clear(); - input_spline_inf_->knot_vector.clear(); - input_spline_inf_->weight.clear(); - CurveDesign_->ReadSplineInf(input_spline_inf_, order, control_points, knot_vector); - CurveDesign_->ReadSplineInf(input_spline_inf_, weight_vector, false); + input_spline_inf_.control_point.clear(); + input_spline_inf_.knot_vector.clear(); + input_spline_inf_.weight.clear(); + CurveDesign_.ReadSplineInf(&input_spline_inf_, order, control_points, knot_vector); + CurveDesign_.ReadSplineInf(&input_spline_inf_, weight_vector, false); //Tính độ dài của cạnh thứ i - double edge_length = merge_path_calc_.calculateNURBSLength(CurveDesign_, input_spline_inf_, t_intervel); + double edge_length = merge_path_calc_.calculateNURBSLength(&CurveDesign_, &input_spline_inf_, t_intervel); //Tính step của cạnh thứ i if (!costmap_robot_ || !costmap_robot_->getCostmap()) { return false; @@ -516,7 +475,7 @@ namespace custom_planner for(double u_test = 0; u_test <= 1; u_test += t_intervel_new) { robot_geometry_msgs::Point curve_point; - curve_point = CurveDesign_->CalculateCurvePoint(input_spline_inf_, u_test, true); + curve_point = CurveDesign_.CalculateCurvePoint(&input_spline_inf_, u_test, true); if(!std::isnan(curve_point.x)&&!std::isnan(curve_point.y)) posesOnEdge.push_back(Pose(curve_point.x, curve_point.y, 0)); } @@ -537,7 +496,7 @@ namespace custom_planner double delta_angle = fabs(fabs(angle_1) - fabs(angle_2)); bool found_intersection = false; if((int)edges_info_.size() > 0) - if(edges_info_.back().isCurve || delta_angle > EPSILON) + if(edges_info_.back().isCurve || delta_angle > kEpsilon) for (int idx_segment_A = 0; idx_segment_A + 1 < (int)savePosesOnEdge.size(); ++idx_segment_A) { robot_geometry_msgs::Point gp1 ; @@ -618,7 +577,7 @@ namespace custom_planner } // Gán isCurve - edge_info.isCurve = (delta_angle >= EPSILON); + edge_info.isCurve = (delta_angle >= kEpsilon); // Thêm vào vector edges_info_.push_back(edge_info); @@ -722,7 +681,7 @@ namespace custom_planner if (idx0 >= 0 && idx1 >= 0 && idx2 < (int)savePosesOnEdge.size()) { double angle = merge_path_calc_.signedAngle(savePosesOnEdge[idx0], savePosesOnEdge[idx1], savePosesOnEdge[idx2]); - skipEdge_flag_ = (fabs(angle) < 0.15 * M_PI); + skipEdge_flag_ = (fabs(angle) < config_.skip_edge_angle); } } @@ -757,10 +716,10 @@ namespace custom_planner } // Hàm phụ để tính cost - auto calc_cost = [&](double angle) -> int + auto calc_cost = [&](double angle) -> int { - if (fabs(angle) <= (0.1 * M_PI)) return 20; - if (fabs(angle) < (0.45 * M_PI)) return 10; + if (fabs(angle) <= config_.cost_angle_tight) return 20; + if (fabs(angle) < config_.cost_angle_wide) return 10; return 0; }; @@ -783,7 +742,7 @@ namespace custom_planner double delta_angle_1 = fabs(angle_check_2) - fabs(angle_check_1); double delta_angle_2 = fabs(angle_check_4) - fabs(angle_check_3); - if (delta_angle_1 > EPSILON || delta_angle_2 > EPSILON) cost += 20; + if (delta_angle_1 > kEpsilon || delta_angle_2 > kEpsilon) cost += 20; else { // Kiểm tra dấu @@ -990,23 +949,23 @@ namespace custom_planner savePoseTMP[idx_2], savePoseTMP[idx_3]); // Cần tính lại các góc quay - if(fabs(delta_Angle) > (0.45 * M_PI) && fabs(delta_Angle) < (0.85 * M_PI)) - { + if(fabs(delta_Angle) > config_.rotation_insert_min && fabs(delta_Angle) < config_.rotation_insert_max) + { MatrixPose[i].clear(); - int max_step = (int)((M_PI - fabs(delta_Angle)) / (0.05 * M_PI)); - for(int j = 0; j <= max_step; j++) + int max_step = (int)((M_PI - fabs(delta_Angle)) / config_.rotation_step); + for(int j = 0; j <= max_step; j++) { Pose intermediate_pose; intermediate_pose.setX(savePoseTMP[edges_info_[i].start_edge_idx].getX()); intermediate_pose.setY(savePoseTMP[edges_info_[i].start_edge_idx].getY()); - if(delta_Angle < 0) + if(delta_Angle < 0) { - intermediate_pose.setYaw(savePoseTMP[edges_info_[i-1].end_edge_idx].getYaw() + j * (0.05 * M_PI)); - } - else + intermediate_pose.setYaw(savePoseTMP[edges_info_[i-1].end_edge_idx].getYaw() + j * config_.rotation_step); + } + else { - intermediate_pose.setYaw(savePoseTMP[edges_info_[i-1].end_edge_idx].getYaw() - j * (0.05 * M_PI)); + intermediate_pose.setYaw(savePoseTMP[edges_info_[i-1].end_edge_idx].getYaw() - j * config_.rotation_step); } // intermediate_pose.getX(), intermediate_pose.getY(), intermediate_pose.getYaw()); MatrixPose[i].push_back(intermediate_pose); @@ -1046,18 +1005,19 @@ namespace custom_planner savePosesOnEdge[idx_3]); delta_Angle = delta_Angle - M_PI; - if(fabs(delta_Angle) > (0.05 * M_PI)) + // Chỉ chèn khi lệch quá một bước xoay — dưới đó coi như thẳng hàng. + if(fabs(delta_Angle) > config_.rotation_step) { MatrixPose[i].clear(); - int max_step = (int)((M_PI - fabs(delta_Angle)) / (0.05 * M_PI)); + int max_step = (int)((M_PI - fabs(delta_Angle)) / config_.rotation_step); for(int j = 0; j <= max_step; j++) { Pose intermediate_pose; intermediate_pose.setX(savePosesOnEdge[edges_info_[i].start_edge_idx].getX()); intermediate_pose.setY(savePosesOnEdge[edges_info_[i].start_edge_idx].getY()); if(delta_Angle > 0) { - intermediate_pose.setYaw(savePosesOnEdge[edges_info_[i-1].end_edge_idx].getYaw() + j * (0.05 * M_PI)); + intermediate_pose.setYaw(savePosesOnEdge[edges_info_[i-1].end_edge_idx].getYaw() + j * config_.rotation_step); } else { - intermediate_pose.setYaw(savePosesOnEdge[edges_info_[i-1].end_edge_idx].getYaw() - j * (0.05 * M_PI)); + intermediate_pose.setYaw(savePosesOnEdge[edges_info_[i-1].end_edge_idx].getYaw() - j * config_.rotation_step); } MatrixPose[i].push_back(intermediate_pose); } @@ -1135,14 +1095,6 @@ namespace custom_planner return P; } - bool CustomPlanner::isThetaValid(double theta) - { - bool result = false; - if(theta < -M_PI || theta > M_PI) result = false; - else result = true; - return result; - } - bool CustomPlanner::curveIsValid(int degree, const std::vector &knot_vector, vector>& control_points) { @@ -1221,17 +1173,19 @@ 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); - // robot::log_info("[custom_planner] DEBUG: angle: %f; yaw_goal: %f",angle, yaw_goal); - // nomalize angle to [-pi, pi] - auto normalizeAngle = [](double a) { + + auto wrapToPi = [](double a) { while (a > M_PI) a -= 2 * M_PI; while (a < -M_PI) a += 2 * M_PI; return a; }; - 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); - return (delta_angle > (0.5 * M_PI)); + // Lệch góc thật giữa yaw goal và hướng cạnh cuối. KHÔNG dùng + // fabs(|a|-|b|): nó xoá dấu nên cặp góc trái dấu cùng độ lớn (vd ±pi/2, + // lệch thật = pi) cho delta = 0 — planner chọn nhầm đi tiến và robot + // quay đầu thay vì lùi. + double delta_angle = std::fabs(wrapToPi(yaw_goal - angle)); + return (delta_angle > config_.backward_decision_angle); } // Export factory function diff --git a/src/custom_planner_config.cpp b/src/custom_planner_config.cpp index e69de29..8bffd21 100644 --- a/src/custom_planner_config.cpp +++ b/src/custom_planner_config.cpp @@ -0,0 +1,75 @@ +#include + +#include + +namespace custom_planner +{ +namespace +{ + +void clampParam(double& value, double lo, double hi, const char* name) +{ + if (value < lo || value > hi) + { + const double clamped = std::clamp(value, lo, hi); + robot::log_warning("[custom_planner] param %s=%.4f ngoài range [%.4f, %.4f], kẹp về %.4f", + name, value, lo, hi, clamped); + value = clamped; + } +} + +} // namespace + +void CustomPlannerConfig::load(robot::NodeHandle& nh) +{ + nh.getParam("pathway_attach_distance", pathway_attach_distance, pathway_attach_distance); + nh.getParam("bare_goal_max_distance", bare_goal_max_distance, bare_goal_max_distance); + nh.getParam("nurbs_length_t_interval", nurbs_length_t_interval, nurbs_length_t_interval); + nh.getParam("nurbs_point_spacing", nurbs_point_spacing, nurbs_point_spacing); + nh.getParam("skip_edge_angle", skip_edge_angle, skip_edge_angle); + nh.getParam("cost_angle_tight", cost_angle_tight, cost_angle_tight); + nh.getParam("cost_angle_wide", cost_angle_wide, cost_angle_wide); + nh.getParam("rotation_insert_min", rotation_insert_min, rotation_insert_min); + nh.getParam("rotation_insert_max", rotation_insert_max, rotation_insert_max); + nh.getParam("rotation_step", rotation_step, rotation_step); + nh.getParam("backward_decision_angle", backward_decision_angle, backward_decision_angle); + + validate(); + + robot::log_info( + "[custom_planner] config: pathway_attach_distance=%.3f[m] bare_goal_max_distance=%.3f[m] " + "nurbs_length_t_interval=%.4f nurbs_point_spacing=%.3f[m] skip_edge_angle=%.4f[rad] " + "cost_angle_tight=%.4f[rad] cost_angle_wide=%.4f[rad] rotation_insert=[%.4f, %.4f][rad] " + "rotation_step=%.4f[rad] backward_decision_angle=%.4f[rad]", + pathway_attach_distance, bare_goal_max_distance, nurbs_length_t_interval, + nurbs_point_spacing, skip_edge_angle, cost_angle_tight, cost_angle_wide, + rotation_insert_min, rotation_insert_max, rotation_step, backward_decision_angle); +} + +void CustomPlannerConfig::validate() +{ + clampParam(pathway_attach_distance, 0.0, 5.0, "pathway_attach_distance"); + clampParam(bare_goal_max_distance, 0.0, 10.0, "bare_goal_max_distance"); + clampParam(nurbs_length_t_interval, 1e-4, 0.5, "nurbs_length_t_interval"); + clampParam(nurbs_point_spacing, 1e-3, 1.0, "nurbs_point_spacing"); + clampParam(skip_edge_angle, 0.0, M_PI, "skip_edge_angle"); + clampParam(cost_angle_tight, 0.0, M_PI, "cost_angle_tight"); + clampParam(cost_angle_wide, 0.0, M_PI, "cost_angle_wide"); + clampParam(rotation_insert_min, 0.0, M_PI, "rotation_insert_min"); + clampParam(rotation_insert_max, 0.0, M_PI, "rotation_insert_max"); + clampParam(rotation_step, 1e-3, M_PI, "rotation_step"); + clampParam(backward_decision_angle, 0.0, M_PI, "backward_decision_angle"); + + if (cost_angle_wide < cost_angle_tight) + { + robot::log_warning("[custom_planner] cost_angle_wide < cost_angle_tight, nâng wide lên bằng tight"); + cost_angle_wide = cost_angle_tight; + } + if (rotation_insert_max < rotation_insert_min) + { + robot::log_warning("[custom_planner] rotation_insert_max < rotation_insert_min, nâng max lên bằng min"); + rotation_insert_max = rotation_insert_min; + } +} + +} // namespace custom_planner diff --git a/src/merge_path_calc.cpp b/src/merge_path_calc.cpp index afa2aa8..4553230 100755 --- a/src/merge_path_calc.cpp +++ b/src/merge_path_calc.cpp @@ -1,16 +1,11 @@ #include"custom_planner/merge_path_calc.h" +using std::vector; + namespace custom_planner { - MergePathCalc::MergePathCalc(){ - curve_design = new Curve_common(); - spline_inf = new Spline_Inf(); - } - MergePathCalc::~MergePathCalc(){ - // Giải phóng bộ nhớ - delete curve_design; - delete spline_inf; - } + MergePathCalc::MergePathCalc() = default; + MergePathCalc::~MergePathCalc() = default; std::vector MergePathCalc::calculateNURBSPath(vector& control_points, bool reverse) { @@ -46,22 +41,21 @@ namespace custom_planner { // Điều chỉnh weights để tăng ảnh hưởng của các control points std::vector weights(control_points.size(), 1.0); - spline_inf->knot_vector.clear(); - spline_inf->control_point.clear(); - spline_inf->weight.clear(); + spline_inf.knot_vector.clear(); + spline_inf.control_point.clear(); + spline_inf.weight.clear(); // Cài đặt thông số cho spline - curve_design->ReadSplineInf(spline_inf, degree + 1, eigen_control_points, knot_vector); - curve_design->ReadSplineInf(spline_inf, weights, false); + curve_design.ReadSplineInf(&spline_inf, degree + 1, eigen_control_points, knot_vector); + curve_design.ReadSplineInf(&spline_inf, weights, false); // Tính độ dài đường cong để xác định số điểm cần lấy mẫu - double NURBS_length = calculateNURBSLength(curve_design, spline_inf, 0.01); - double desired_spacing = 0.05; // Khoảng cách mong muốn giữa các điểm - double step = calculateAdaptiveStep(NURBS_length, desired_spacing); + double NURBS_length = calculateNURBSLength(&curve_design, &spline_inf, 0.01); + double step = calculateAdaptiveStep(NURBS_length, desired_point_spacing_); - for(double t = 0.0; t <= 1.0; t += step) + for(double t = 0.0; t <= 1.0; t += step) { - robot_geometry_msgs::Point point = curve_design->CalculateCurvePoint(spline_inf, t, true); + robot_geometry_msgs::Point point = curve_design.CalculateCurvePoint(&spline_inf, t, true); if(!std::isnan(point.x) && !std::isnan(point.y)) { robot_geometry_msgs::PoseStamped pose; diff --git a/src/pathway.cc b/src/pathway.cc deleted file mode 100755 index 4bf0185..0000000 --- a/src/pathway.cc +++ /dev/null @@ -1,291 +0,0 @@ -#include "custom_planner/pathway.h" - -using namespace custom_planner; - -bool Pathway::onSegment(Pose p, Pose q, Pose r) -{ - if (q.getX() <= max(p.getX(), r.getX()) && q.getX() >= min(p.getX(), r.getX()) && - q.getY() <= max(p.getY(), r.getY()) && q.getY() >= min(p.getY(), r.getY())) - return true; - - return false; -} - -int Pathway::orientation(Pose p, Pose q, Pose r) -{ - int val = (q.getY() - p.getY()) * (r.getX() - q.getX()) - - (q.getX() - p.getX()) * (r.getY() - q.getY()); - - if (val == 0) return 0; // collinear - - return (val > 0)? 1: 2; // clock or counterclock wise -} - -bool Pathway::doIntersect(Pose p1, Pose q1, Pose p2, Pose q2) -{ - // Find the four orientations needed for general and - // special cases - int o1 = orientation(p1, q1, p2); - int o2 = orientation(p1, q1, q2); - int o3 = orientation(p2, q2, p1); - int o4 = orientation(p2, q2, q1); - - // General case - if (o1 != o2 && o3 != o4) - return true; - - // Special Cases - // p1, q1 and p2 are collinear and p2 lies on segment p1q1 - if (o1 == 0 && onSegment(p1, p2, q1)) return true; - - // p1, q1 and q2 are collinear and q2 lies on segment p1q1 - if (o2 == 0 && onSegment(p1, q2, q1)) return true; - - // p2, q2 and p1 are collinear and p1 lies on segment p2q2 - if (o3 == 0 && onSegment(p2, p1, q2)) return true; - - // p2, q2 and q1 are collinear and q1 lies on segment p2q2 - if (o4 == 0 && onSegment(p2, q1, q2)) return true; - - return false; // Doesn't fall in any of the above cases -} - -bool Pathway::isIntersect(Edge L) { - for (auto& segment : path_) { - if (doIntersect(L.getP1(), L.getP2(), segment.getP1(), segment.getP2())) { - return true; - } - } - return false; -} -bool Pathway::isPoseExisted(Pose p) -{ - for(auto& pose : posesOnPath_) - { - if(p.getX()==pose.getX() && p.getY()==pose.getY()) return true; - } - return false; -} -double Pathway::calculateAngle(Pose p1, Pose p2, Pose p3) -{ - // Tính vector 1 - double vector1x = p2.getX() - p1.getX(); - double vector1y = p2.getY() - p1.getY(); - - // Tính vector 2 - double vector2x = p3.getX() - p2.getX(); - double vector2y = p3.getY() - p2.getY(); - - // Tính độ dài của hai vector - double lengthVector1 = sqrt(vector1x * vector1x + vector1y * vector1y); - double lengthVector2 = sqrt(vector2x * vector2x + vector2y * vector2y); - - // Tính góc giữa hai vector - double dotProduct = vector1x * vector2x + vector1y * vector2y; - double cosTheta = dotProduct / (lengthVector1 * lengthVector2); - if(cosTheta>1) cosTheta = 1; - else if(cosTheta<(-1)) cosTheta = -1; - // Đổi radian sang độ - double angle = acos(cosTheta) * 180.0 / M_PI; - - return angle; -} -void Pathway::RecordPath(Pose startPose, Pose currentPose, double delta_angle_th, double InitialSegmentLengthMin, double SegmentLengthMin) -{ - if(!isPathInitilized_) - { - double InitialSegmentLength = sqrt(pow(currentPose.getX() - startPose.getX(), 2) + pow(currentPose.getY() - startPose.getY(), 2)); - if(InitialSegmentLength>=InitialSegmentLengthMin) - { - addEdge(startPose, currentPose); - isPathInitilized_ = true; - printf("path is initialized\n"); - } - - } - if(!path_.empty()) - { - double distanceCheck = sqrt(pow(currentPose.getX() - path_.back().getP2().getX(), 2) + pow(currentPose.getY() - path_.back().getP2().getY(), 2)); - if(distanceCheck>=SegmentLengthMin) - { - if(isNewPoseOnEdge(currentPose, delta_angle_th)){ - setP2LastEdgeOnPath(currentPose); - printf("add new pose on segment into path\n"); - } - else{ - addEdge(currentPose); - printf("add new segment into path\n"); - } - printf("Number of segment on path: %d\n",(int)path_.size()); - } - } - -} - -void Pathway::ResetAndRecordPath(Pose startPose, Pose currentPose, double delta_angle_th, double InitialSegmentLengthMin, double SegmentLengthMin) -{ - if(!isPathClear_){ - path_.clear(); - isPathClear_ = true; - } - RecordPath(startPose, currentPose, delta_angle_th, InitialSegmentLengthMin, SegmentLengthMin); -} - -bool Pathway::isNewPoseOnEdge(Pose p, double delta_angle_th) -{ - if(!path_.empty()) - { - double deltaAngle = calculateAngle(path_.back().getP1(), path_.back().getP2(), p); - // ROS_WARN("deltaAngle: %f",deltaAngle); - if(deltaAngle<=delta_angle_th) return true; - } - return false; -} - -void Pathway::setEdgeOnPath(uint32_t line_index, Pose p1, Pose p2){ - if(!path_.empty()&&line_index<=path_.size()) - { - path_.at(line_index).setEdge(p1, p2); - } -} - -void Pathway::syncPosesAndPath() -{ - if(!path_.empty()) - { - posesOnPath_.clear(); - for(auto& edge : path_) - { - if(!isPoseExisted(edge.getP1())) posesOnPath_.push_back(edge.getP1()); - if(!isPoseExisted(edge.getP2())) posesOnPath_.push_back(edge.getP2()); - } - } - else posesOnPath_.clear(); -} - -void Pathway::SavePathAsFile(const string& file_name) -{ - ofstream file(file_name); - - if (file.is_open()) - { - for (auto &edge : path_) - { - file << edge.getP1().getX() << " " << edge.getP1().getY() << " " << edge.getP1().getYaw() - << edge.getP2().getX() << " " << edge.getP2().getY() << " " << edge.getP2().getYaw() << "\n"; - } - - file.close(); - cout << "Pathway saved to file: " <> x1 >> y1 >> yaw1 >> x2 >> y2 >> yaw2) - { - Pose p1(x1, y1, yaw1); - Pose p2(x2, y2, yaw2); - - addEdge(p1, p2); - } - - file.close(); - cout << "Pathway loaded from file: " <=0&&alpha<=1&&beta>=0&&beta<=1) - { - double x0 = x1 + alpha*(x2 - x1); - double y0 = y1 + alpha*(y2 - y1); - resultPoint->setPoint(x0,y0); - return true; - } - else return false; -} - -vector Pathway::findIntersections(Edge L) { - vector intersectionPoints; - if(!path_.empty()){ - for (auto& segment : path_){ - Point result; - if(findIntersection(L,segment,&result)==true) - { - intersectionPoints.push_back(result); - } - } - } - return intersectionPoints; -} - -vector> Pathway::findIntersections(Edge L1, Edge L2) { - vector> intersectionPoints; - vector intersectionPointsL1; - vector intersectionPointsL2; - if(!path_.empty()){ - for (auto& segment : path_) { - Point result1; - if(findIntersection(L1,segment,&result1)==true) - { - intersectionPointsL1.push_back(result1); - } - Point result2; - if(findIntersection(L2,segment,&result2)==true) - { - intersectionPointsL2.push_back(result2); - } - } - } - intersectionPoints.push_back(intersectionPointsL1); - intersectionPoints.push_back(intersectionPointsL2); - - return intersectionPoints; -} \ No newline at end of file diff --git a/src/plan_for_retry.cpp b/src/plan_for_retry.cpp deleted file mode 100755 index 1473ec9..0000000 --- a/src/plan_for_retry.cpp +++ /dev/null @@ -1,686 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace std; - -inline double calculateAngle(double xA, double yA, double xB, double yB) { - double deltaX = xB - xA; - double deltaY = yB - yA; - double angleRad = 0; - if(deltaX!=0) - { - angleRad = atan2(deltaY, deltaX); - // double angleDeg = angleRad * 180.0 / M_PI; - } - return angleRad; -} - -inline double getYaw(double x, double y, double z, double w){ - // yaw (z-axis rotation) - double siny_cosp = 2 * (w * z + x * y); - double cosy_cosp = 1 - 2 * (y * y + z * z); - double yaw = std::atan2(siny_cosp, cosy_cosp); - return yaw; -} - -bool isThetaValid(double theta) -{ - bool result = false; - if(theta < -M_PI || theta > M_PI) result = false; - else result = true; - return result; -} - -double computeDeltaAngleStartOfPlan(double theta, robot_geometry_msgs::Pose& startPose, robot_geometry_msgs::Pose& next_Pose) -{ - double delta_angle = 0; - if(isThetaValid(theta)) - { - double xAB = next_Pose.position.x - startPose.position.x; - double yAB = next_Pose.position.y - startPose.position.y; - double d = sqrt(xAB*xAB + yAB*yAB); - double xC = startPose.position.x + d*cos(theta); - double yC = startPose.position.y + d*sin(theta); - double xAC = xC-startPose.position.x; - double yAC = yC-startPose.position.y; - double dAB = sqrt(xAB*xAB + yAB*yAB); - double cos_a = (xAB*xAC + yAB*yAC)/(dAB*d); - if(cos_a>1) cos_a = 1; - else if(cos_a<(-1)) cos_a = -1; - delta_angle = acos(cos_a); - // delta_angle = delta_angle*180/M_PI; - // ROS_WARN("xC: %f, yC: %f", xC, yC); - // ROS_WARN("dAB: %f", dAB); - // ROS_WARN("delta_angle: %f", delta_angle); - } - return delta_angle; -} - -double computeDeltaAngleEndOfPlan(double theta, robot_geometry_msgs::Pose& endPose, robot_geometry_msgs::Pose& prev_Pose) -{ - double delta_angle = 0; - if(isThetaValid(theta)) - { - double xAB =endPose.position.x-prev_Pose.position.x; - double yAB = endPose.position.y-prev_Pose.position.y; - double d = sqrt(xAB*xAB + yAB*yAB); - double xC =endPose.position.x + d*cos(theta); - double yC = endPose.position.y + d*sin(theta); - double xBC = xC-endPose.position.x; - double yBC = yC-endPose.position.y; - double dAB = sqrt(xAB*xAB + yAB*yAB); - double cos_a = (xAB*xBC + yAB*yBC)/(dAB*d); - if(cos_a>1) cos_a = 1; - else if(cos_a<(-1)) cos_a = -1; - delta_angle = acos(cos_a); - // delta_angle = delta_angle*180/M_PI; - // ROS_WARN("xC: %f, yC: %f", xC, yC); - // ROS_WARN("dAB: %f", dAB); - // ROS_WARN("delta_angle: %f", delta_angle); - } - return delta_angle; -} - -// Hàm chia đoạn thẳng AB thành các đoạn có độ dài d -std::vector divideSegment(robot_geometry_msgs::PoseStamped& A, robot_geometry_msgs::PoseStamped& B, double d) { - std::vector Poses; - double xAB = B.pose.position.x - A.pose.position.x; - double yAB = B.pose.position.y - A.pose.position.y; - double length = sqrt(xAB*xAB + yAB*yAB); - if(length > d) - { - Poses.push_back(A); // Thêm điểm A vào vector trước khi chia - - int segments = length / d; - - // Tính toán tọa độ của các điểm trên đoạn AB - double ratio = d / length; - for (int i = 1; i <= segments; ++i) { - robot_geometry_msgs::PoseStamped p; - double p_x = A.pose.position.x + (B.pose.position.x - A.pose.position.x) * ratio * i; - double p_y = A.pose.position.y + (B.pose.position.y - A.pose.position.y) * ratio * i; - p.pose.position.x = p_x; - p.pose.position.y = p_y; - Poses.push_back(p); - } - - if(!Poses.empty()&&(Poses.back().pose.position.x!=B.pose.position.x || Poses.back().pose.position.y!=B.pose.position.y)) - { - Poses.push_back(B); // Thêm điểm B vào vector sau khi chia - } - - // Tính góc cho từng pose trên đoạn AB - if(//computeDeltaAngleStartOfPlan(getYaw(A.pose.orientation.x, A.pose.orientation.y, A.pose.orientation.z, A.pose.orientation.w), - //Poses.front().pose, Poses[1].pose) <= 0.872664626 && - computeDeltaAngleEndOfPlan(getYaw(B.pose.orientation.x, B.pose.orientation.y, B.pose.orientation.z, B.pose.orientation.w), - Poses.back().pose, Poses[Poses.size() - 2].pose) <= 1.3962634016) // <= 80 degree - { - double theta_tmp = 0; - for(int i = 0; i<((int)Poses.size()-1); i++) - { - if(Poses[i].pose.position.x!=Poses[i+1].pose.position.x) - { - double theta = calculateAngle(Poses[i].pose.position.x, Poses[i].pose.position.y, - Poses[i+1].pose.position.x, Poses[i+1].pose.position.y); - Poses[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - Poses[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - Poses.back().pose.orientation = B.pose.orientation; - } - else if(//computeDeltaAngleStartOfPlan(getYaw(A.pose.orientation.x, A.pose.orientation.y, A.pose.orientation.z, A.pose.orientation.w), - //Poses.front().pose, Poses[1].pose) >= 2.2689280276 && - computeDeltaAngleEndOfPlan(getYaw(B.pose.orientation.x, B.pose.orientation.y, B.pose.orientation.z, B.pose.orientation.w), - Poses.back().pose, Poses[Poses.size() - 2].pose) >= 1.7453292526) // >= 100 degree - { - double theta_tmp = 0; - for(int i = (int)Poses.size() -1; i>0; i--) - { - if(Poses[i].pose.position.x!=Poses[i-1].pose.position.x) - { - double theta = calculateAngle(Poses[i].pose.position.x, Poses[i].pose.position.y, - Poses[i-1].pose.position.x, Poses[i-1].pose.position.y); - Poses[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - Poses[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - Poses.front().pose.orientation = A.pose.orientation; - } - } - else - { - Poses.push_back(A); - Poses.push_back(B); - } - return Poses; -} - -// Hàm gọi make plan : tạo tuyến đường đi quay lại điểm retry có trong plan hiện tại và đi tới điểm goal mới theo cung tròn. -// khi tạo thành công plan thì hàm trả về True, không thành công thì trả về False và có hiện cảnh báo nguyên nhân. - // current_plan: vector chứa plan hiện tại - // pose_A: điểm quay lại để retry - // pose_B: điểm goal mới, có hướng thẳng với palet hiện tại - // pose_C: tâm của cung tròn AB - // result_plan: vector chứa plan kết quả - -bool makePlanForRetry(std::vector& current_plan, - int indexOfPoseA, robot_geometry_msgs::PoseStamped& pose_B, robot_geometry_msgs::PoseStamped& pose_B_behind, - robot_geometry_msgs::PoseStamped& pose_C, std::vector& result_plan) - { - bool result = false; - std::vector PlanRetry_1; - std::vector PlanRetry_2; - std::vector PlanRetry_3; - - if(current_plan.empty()||current_plan.size()<2) - { - ROS_WARN("current_plan is empty"); - return false; - } - - robot_geometry_msgs::PoseStamped pose_A; - pose_A = current_plan[indexOfPoseA]; - - // Tính ra PlanRetry_1 điểm retry tại Pose_A - - PlanRetry_1.assign(current_plan.begin()+indexOfPoseA, current_plan.end()); - - if(!PlanRetry_1.empty()){ - std::reverse(PlanRetry_1.begin(), PlanRetry_1.end()); - } - - // Tính ra PlanRetry_2 với biên dạng cung tròn đi qua pose_A và pose_B, có tâm tại pose_C - - double xAB = pose_B.pose.position.x - pose_A.pose.position.x; - double yAB = pose_B.pose.position.y - pose_A.pose.position.y; - double d_AB = sqrt(xAB*xAB + yAB*yAB); - if(d_AB<=0.1) - { - ROS_WARN("Curve AB is too short, cannot compute plan"); - return false; - } - - // nếu hướng của vector AB và hướng của pose_B tạo với nhau một góc ~0 độ hoặc ~180 độ -> cung tròn AB sẽ gần như là một đọan thẳng - if((computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 3.13 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= M_PI) || - (computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= 0.1745 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 0)) - { - std::vector planSegment_AB; - planSegment_AB = divideSegment(pose_A, pose_B, 0.1); - PlanRetry_2.assign(planSegment_AB.begin(), planSegment_AB.end()); - } - else - { - double xCA = pose_A.pose.position.x - pose_C.pose.position.x; - double yCA = pose_A.pose.position.y - pose_C.pose.position.y; - double xCB = pose_B.pose.position.x - pose_C.pose.position.x; - double yCB = pose_B.pose.position.y - pose_C.pose.position.y; - double rCA = sqrt(xCA*xCA + yCA*yCA); - double rCB = sqrt(xCB*xCB + yCB*yCB); - if(abs(rCA-rCB)>0.008) - { - ROS_WARN("pose_C is not Center of Curve AB"); - return false; - } - - double cos_ACB = (xCA*xCB + yCA*yCB)/(rCA*rCB); - if(cos_ACB>1) cos_ACB = 1; - else if(cos_ACB<(-1)) cos_ACB = -1; - double angleACB = acos(cos_ACB); - double angle_interval = 0.005; - // tính góc của vector CA: - double angleCA = atan2(yCA, xCA); - - // check thử xem chiều góc quét từ A -> B thì angleCA + delta_angle hay angleCA - delta_angle - bool is_increase_angle = false; - double check_angle = angleCA + 50*angle_interval*angleACB; - double xA1 = pose_C.pose.position.x + rCA*cos(check_angle); - double yA1 = pose_C.pose.position.y + rCA*sin(check_angle); - double xCA1 = xA1 - pose_C.pose.position.x; - double yCA1 = yA1 - pose_C.pose.position.y; - double cos_A1CB = (xCA1*xCB + yCA1*yCB)/(rCA*rCB); - if(cos_A1CB>1) cos_A1CB = 1; - else if(cos_A1CB<(-1)) cos_A1CB = -1; - double angleA1CB = acos(cos_A1CB); - if(angleA1CB>angleACB) - { - is_increase_angle = false; - } - else if(angleA1CB2) - { - for(int i = 0 ; i < PlanRetry_2.size(); i++) - { - ROS_INFO("Pose %d in PlanRetry : %f, %f", i, PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y); - } - if(/*computeDeltaAngleStartOfPlan(getYaw(pose_A.pose.orientation.x, pose_A.pose.orientation.y, pose_A.pose.orientation.z, pose_A.pose.orientation.w), - PlanRetry_2.front().pose, PlanRetry_2[1].pose) <= 1.3962634016 &&*/ - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - PlanRetry_2.back().pose, PlanRetry_2[PlanRetry_2.size() - 2].pose) <= 1.3962634016 - ) // <= 80 degree - { - double theta_tmp = 0; - for(int i = 0; i<((int)PlanRetry_2.size()-1); i++) - { - if(PlanRetry_2[i].pose.position.x!=PlanRetry_2[i+1].pose.position.x) - { - double theta = calculateAngle(PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y, - PlanRetry_2[i+1].pose.position.x, PlanRetry_2[i+1].pose.position.y); - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - PlanRetry_2.back().pose.orientation = pose_B.pose.orientation; - } - else if(/*computeDeltaAngleStartOfPlan(getYaw(pose_A.pose.orientation.x, pose_A.pose.orientation.y, pose_A.pose.orientation.z, pose_A.pose.orientation.w), - PlanRetry_2.front().pose, PlanRetry_2[1].pose) >= 1.745329252 &&*/ - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - PlanRetry_2.back().pose, PlanRetry_2[PlanRetry_2.size() - 2].pose) >= 1.745329252) // >= 100 degree - { - double theta_tmp = 0; - for(int i = (int)PlanRetry_2.size() -1; i>0; i--) - { - if(PlanRetry_2[i].pose.position.x!=PlanRetry_2[i-1].pose.position.x) - { - double theta = calculateAngle(PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y, - PlanRetry_2[i-1].pose.position.x, PlanRetry_2[i-1].pose.position.y); - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - PlanRetry_2.front().pose.orientation = PlanRetry_2[1].pose.orientation; - } - else - { - ROS_WARN("Pose_A yaw or Pose_B yaw is invalid value"); - return false; - } - } - else - { - ROS_WARN("Curve AB is too short, cannot compute plan"); - return false; - } - } - - // Tạo đoạn đường từ poseB -> poseB_behind - PlanRetry_3 = divideSegment(pose_B, pose_B_behind, 0.1); - - ros::Time plan_time = ros::Time::now(); - if(!PlanRetry_1.empty()&&!PlanRetry_2.empty()&&!PlanRetry_3.empty()) - { - for(int i = 0; i < (int)PlanRetry_1.size(); i++) - { - PlanRetry_1[i].header.stamp = plan_time; - result_plan.push_back(PlanRetry_1[i]); - } - for(int i = 0; i < (int)PlanRetry_2.size(); i++) - { - PlanRetry_2[i].header.stamp = plan_time; - PlanRetry_2[i].header.frame_id = PlanRetry_1.front().header.frame_id; - result_plan.push_back(PlanRetry_2[i]); - } - for(int i = 0; i < (int)PlanRetry_3.size(); i++) - { - PlanRetry_3[i].header.stamp = plan_time; - PlanRetry_3[i].header.frame_id = PlanRetry_1.front().header.frame_id; - result_plan.push_back(PlanRetry_3[i]); - } - result = true; - } - else{ - if(PlanRetry_3.empty()) - { - ROS_WARN("PlanRetry_3 is empty"); - } - if(PlanRetry_2.empty()) - { - ROS_WARN("PlanRetry_2 is empty"); - } - if(PlanRetry_1.empty()) - { - ROS_WARN("PlanRetry_1 is empty"); - } - } - return result; -} - -// Hàm gọi make plan : tạo tuyến đường đi quay lại điểm retry có trong plan hiện tại và đi tới điểm goal mới theo cung tròn. -// khi tạo thành công plan thì hàm trả về True, không thành công thì trả về False và có hiện cảnh báo nguyên nhân. - // current_plan: vector chứa plan hiện tại - // pose_A: điểm quay lại để retry - // pose_B: điểm goal mới, có hướng thẳng với palet hiện tại - // pose_C: tâm của cung tròn AB - // result_plan: vector chứa plan kết quả - -bool makePlanForRetry(robot_geometry_msgs::PoseStamped& pose_A, robot_geometry_msgs::PoseStamped& pose_B, robot_geometry_msgs::PoseStamped& pose_B_behind, - robot_geometry_msgs::PoseStamped& pose_C, std::vector& result_plan) - { - bool result = false; - std::vector PlanRetry_1; - std::vector PlanRetry_2; - std::vector PlanRetry_3; - - ROS_INFO("[makePlanForRetry] pose_A: %f, %f, %f pose_B: %f, %f, %f pose_C: %f, %f", - pose_A.pose.position.x, pose_A.pose.position.y, - getYaw(pose_A.pose.orientation.x, pose_A.pose.orientation.y, pose_A.pose.orientation.z, pose_A.pose.orientation.w), - pose_B.pose.position.x, pose_B.pose.position.y, - getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w)); - - // Tính ra PlanRetry_1 điểm retry tại Pose_A - - PlanRetry_1 = divideSegment(pose_B, pose_A, 0.1); - - // Tính ra PlanRetry_2 với biên dạng cung tròn đi qua pose_A và pose_B, có tâm tại pose_C - - double xAB = pose_B.pose.position.x - pose_A.pose.position.x; - double yAB = pose_B.pose.position.y - pose_A.pose.position.y; - double d_AB = sqrt(xAB*xAB + yAB*yAB); - if(d_AB<=0.1) - { - ROS_WARN("Curve AB is too short, cannot compute plan"); - return false; - } - - // nếu hướng của vector AB và hướng của pose_B tạo với nhau một góc ~0 độ hoặc ~180 độ -> cung tròn AB sẽ gần như là một đọan thẳng - if((computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 3.13 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= M_PI) || - (computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= 0.1745 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 0)) - { - std::vector planSegment_AB; - planSegment_AB = divideSegment(pose_A, pose_B, 0.1); - PlanRetry_2.assign(planSegment_AB.begin(), planSegment_AB.end()); - } - else - { - double xCA = pose_A.pose.position.x - pose_C.pose.position.x; - double yCA = pose_A.pose.position.y - pose_C.pose.position.y; - double xCB = pose_B.pose.position.x - pose_C.pose.position.x; - double yCB = pose_B.pose.position.y - pose_C.pose.position.y; - double rCA = sqrt(xCA*xCA + yCA*yCA); - double rCB = sqrt(xCB*xCB + yCB*yCB); - if(abs(rCA-rCB)>0.008) - { - ROS_WARN("pose_C is not Center of Curve AB"); - return false; - } - - double cos_ACB = (xCA*xCB + yCA*yCB)/(rCA*rCB); - if(cos_ACB>1) cos_ACB = 1; - else if(cos_ACB<(-1)) cos_ACB = -1; - double angleACB = acos(cos_ACB); - double angle_interval = 0.005; - // tính góc của vector CA: - double angleCA = atan2(yCA, xCA); - - // check thử xem chiều góc quét từ A -> B thì angleCA + delta_angle hay angleCA - delta_angle - bool is_increase_angle = false; - double check_angle = angleCA + 50*angle_interval*angleACB; - double xA1 = pose_C.pose.position.x + rCA*cos(check_angle); - double yA1 = pose_C.pose.position.y + rCA*sin(check_angle); - double xCA1 = xA1 - pose_C.pose.position.x; - double yCA1 = yA1 - pose_C.pose.position.y; - double cos_A1CB = (xCA1*xCB + yCA1*yCB)/(rCA*rCB); - if(cos_A1CB>1) cos_A1CB = 1; - else if(cos_A1CB<(-1)) cos_A1CB = -1; - double angleA1CB = acos(cos_A1CB); - if(angleA1CB>angleACB) - { - is_increase_angle = false; - } - else if(angleA1CB2) - { - for(int i = 0 ; i < PlanRetry_2.size(); i++) - { - ROS_INFO("Pose %d in PlanRetry : %f, %f", i, PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y); - } - if(/*computeDeltaAngleStartOfPlan(getYaw(pose_A.pose.orientation.x, pose_A.pose.orientation.y, pose_A.pose.orientation.z, pose_A.pose.orientation.w), - PlanRetry_2.front().pose, PlanRetry_2[1].pose) <= 1.3962634016 &&*/ - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - PlanRetry_2.back().pose, PlanRetry_2[PlanRetry_2.size() - 2].pose) <= 1.3962634016 - ) // <= 80 degree - { - double theta_tmp = 0; - for(int i = 0; i<((int)PlanRetry_2.size()-1); i++) - { - if(PlanRetry_2[i].pose.position.x!=PlanRetry_2[i+1].pose.position.x) - { - double theta = calculateAngle(PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y, - PlanRetry_2[i+1].pose.position.x, PlanRetry_2[i+1].pose.position.y); - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - PlanRetry_2.back().pose.orientation = pose_B.pose.orientation; - } - else if(/*computeDeltaAngleStartOfPlan(getYaw(pose_A.pose.orientation.x, pose_A.pose.orientation.y, pose_A.pose.orientation.z, pose_A.pose.orientation.w), - PlanRetry_2.front().pose, PlanRetry_2[1].pose) >= 1.745329252 &&*/ - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - PlanRetry_2.back().pose, PlanRetry_2[PlanRetry_2.size() - 2].pose) >= 1.745329252) // >= 100 degree - { - double theta_tmp = 0; - for(int i = (int)PlanRetry_2.size() -1; i>0; i--) - { - if(PlanRetry_2[i].pose.position.x!=PlanRetry_2[i-1].pose.position.x) - { - double theta = calculateAngle(PlanRetry_2[i].pose.position.x, PlanRetry_2[i].pose.position.y, - PlanRetry_2[i-1].pose.position.x, PlanRetry_2[i-1].pose.position.y); - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta); - theta_tmp = theta; - } - else - { - PlanRetry_2[i].pose.orientation = tf::createQuaternionMsgFromYaw(theta_tmp); - } - } - PlanRetry_2.front().pose.orientation = PlanRetry_2[1].pose.orientation; - } - else - { - ROS_WARN("Pose_A yaw or Pose_B yaw is invalid value"); - return false; - } - } - else - { - ROS_WARN("Curve AB is too short, cannot compute plan"); - return false; - } - } - - // Tạo đoạn đường từ poseB -> poseB_behind - PlanRetry_3 = divideSegment(pose_B, pose_B_behind, 0.1); - - ros::Time plan_time = ros::Time::now(); - if(!PlanRetry_1.empty()&&!PlanRetry_2.empty()&&!PlanRetry_3.empty()) - { - for(int i = 0; i < (int)PlanRetry_1.size(); i++) - { - PlanRetry_1[i].header.stamp = plan_time; - result_plan.push_back(PlanRetry_1[i]); - } - for(int i = 0; i < (int)PlanRetry_2.size(); i++) - { - PlanRetry_2[i].header.stamp = plan_time; - PlanRetry_2[i].header.frame_id = PlanRetry_1.front().header.frame_id; - result_plan.push_back(PlanRetry_2[i]); - } - for(int i = 0; i < (int)PlanRetry_3.size(); i++) - { - PlanRetry_3[i].header.stamp = plan_time; - PlanRetry_3[i].header.frame_id = PlanRetry_1.front().header.frame_id; - result_plan.push_back(PlanRetry_3[i]); - } - result = true; - } - else{ - if(PlanRetry_3.empty()) - { - ROS_WARN("PlanRetry_3 is empty"); - } - if(PlanRetry_2.empty()) - { - ROS_WARN("PlanRetry_2 is empty"); - } - if(PlanRetry_1.empty()) - { - ROS_WARN("PlanRetry_1 is empty"); - } - } - return result; -} - -// Hàm Tìm tâm C của cung tròn AB khi biết Pose tại điểm B: khi tìm thành công điểm C thì hàm trả về True - // pose_A: điểm start của cung tròn - // pose_B: điểm đích trên cung tròn - // pose_C: tâm của cung tròn AB (kết quả) - -bool findCenterOfCurve(robot_geometry_msgs::PoseStamped& pose_A, robot_geometry_msgs::PoseStamped& pose_B, robot_geometry_msgs::PoseStamped& pose_C) -{ - // nếu hướng của vector AB và hướng của pose_B tạo với nhau một góc ~0 độ hoặc ~180 độ -> điểm C sẽ gần xấp xỉ với trung điểm của đoạn thẳng AB. - if((computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 3.13 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= M_PI) || - (computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) <= 0.1745 && - computeDeltaAngleEndOfPlan(getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w), - pose_B.pose, pose_A.pose) >= 0)) - { - pose_C.pose.position.x = (pose_A.pose.position.x + pose_B.pose.position.x)/2; - pose_C.pose.position.y = (pose_A.pose.position.y + pose_B.pose.position.y)/2; - } - else - { - double x_R = pose_A.pose.position.x; - double y_R = pose_A.pose.position.y; - double x_G = pose_B.pose.position.x; - double y_G = pose_B.pose.position.y; - double phi_vG = getYaw(pose_B.pose.orientation.x, pose_B.pose.orientation.y, pose_B.pose.orientation.z, pose_B.pose.orientation.w); - double x_H = (x_R+x_G)/2; - double y_H = (y_R+y_G)/2; - double m_vG = tan(phi_vG); - double m_G_n_vG = -1/m_vG; - double b_G_n_vG = y_G-m_G_n_vG*x_G; - double m_RG =(y_G-y_R)/(x_G-x_R); - double b_RG = y_R-m_RG*x_R; - double m_H_n_RG = -1/m_RG; - double b_H_n_RG = y_H-m_H_n_RG*x_H; - pose_C.pose.position.x = (b_H_n_RG-b_G_n_vG)/(m_G_n_vG-m_H_n_RG); - pose_C.pose.position.y = (b_H_n_RG*m_G_n_vG-b_G_n_vG*m_H_n_RG)/(m_G_n_vG-m_H_n_RG); - } - return true; -} diff --git a/src/pose.cc b/src/pose.cc deleted file mode 100755 index 63978f0..0000000 --- a/src/pose.cc +++ /dev/null @@ -1,42 +0,0 @@ -#include - -namespace custom_planner -{ - -bool Pose::SavePoseAsFile(const string& file_name) -{ - bool result = false; - ofstream file(file_name); - if (file.is_open()) - { - file << x_ << " " << y_ << " "<< yaw_ << "\n"; - file.close(); - result = true; - } - else - { - result = false; - } - return result; -} - -bool Pose::LoadPoseFromFile(const string& file_name) -{ - bool result = false; - ifstream file(file_name); - if (file.is_open()) - { - double x, y, yaw; - file >> x >> y >> yaw; - setPose(x, y, yaw); - file.close(); - result = true; - } - else - { - result = false; - } - return result; -} - -} \ No newline at end of file