pnkx_nav_core 1.0 — every package with a remote is a submodule, and the root CMake builds them all
A single commit on an orphan branch: the whole tree as it should land on a
robot, with no history from the branch it grew out of.
The rule applied: a package that has its own remote becomes a submodule; a
package that only ever lived inside this repository stays as ordinary files.
That comes to 29 submodules, 18 registered here for the first time. They were
sitting in the tree as plain clones, which looks right locally and is empty on
the robot - a clone of this repository would have carried the directory names
and none of the contents.
.gitignore is fixed at the source rather than patched per path. The rule
**/[Pp]ackages/* comes from the Visual Studio template and targets NuGet's
generated packages/ folder; here Packages/ is a SOURCE directory, so it hid
whole packages from git status - and a missing package then becomes invisible
to exactly the command you would use to look for one. It cost move_base2,
dock_pattern_action and sbpl_recovery, and sbpl_recovery surfaced only by
walking the tree for .git directories and diffing against .gitmodules. The
exception now re-includes src/*/Packages/** wholesale, placed immediately after
the NuGet rule so the build-artifact rules further down still win. Listing
paths one by one is what let one slip in the first place.
The root CMakeLists.txt described a tree that no longer exists. Its second half
was a migration shim that looked for a sibling Test/ directory from AMR_T800
and added packages out of it; PNKX_NAV_CORE_BUILD_TEST_PACKAGES defaults to ON,
so with the migration finished it would have hit FATAL_ERROR at configure time.
That is gone, and every package is added in dependency order at its real
in-tree path.
Three guard names are traps worth naming, because a guard that never matches
adds the subdirectory twice on a re-entrant configure:
- src/Libraries/angles is project robot_angles_prv, and a DIFFERENT package
called angles lives at src/Algorithms/Libraries/angles. Both are in the
tree; guarding on `angles` would silently skip the first.
- dock_pattern_action's library target is dock_pattern_action_handler.
- move_base2's is move_base2_core.
sbpl_recovery and dock_pattern_action had no standalone branch - catkin was
required at top level, so a build without it died at configure time pointing at
packages that are present. Both now detect the mode and name their CMake
targets directly in standalone, and both drop their plugin at the top of the
build tree, because boost::dll loads by filename and PluginLoaderHelper
resolves that against the build directory: left in a subdirectory a plugin
builds and is then invisible at runtime.
grid_map_core and image_geometry were added because hybrid_local_planner and
depth_image_proc link robot_grid_map_core and robot_image_geometry, and neither
was in the tree - found by scanning every CMakeLists for internal library names
and diffing against the targets the tree defines, then confirmed by the build.
Every submodule points at the tip of the branch it was already pinned to, not
blindly at main. costmap_2d stays on dev_cam_intel; that branch exists for a
reason, and this tree carries field calibration that does not belong on main.
config/ is flattened into config/runtime/, matching the layout the nav core
reads. The .zip snapshots of old package states are gone - manual backups, not
build inputs.
Verified: cmake configure returns 0 and a full standalone build returns 0,
producing 48 shared libraries with nothing gated off.
This commit is contained in:
162
src/Algorithms/Cores/score_algorithm/CMakeLists.txt
Normal file
162
src/Algorithms/Cores/score_algorithm/CMakeLists.txt
Normal file
@@ -0,0 +1,162 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(score_algorithm VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building score_algorithm with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building score_algorithm with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS filesystem system)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
robot_nav_core
|
||||
robot_cpp
|
||||
mkt_msgs
|
||||
angles
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
robot_nav_core
|
||||
robot_cpp
|
||||
mkt_msgs
|
||||
angles
|
||||
)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}
|
||||
CATKIN_DEPENDS robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core robot_nav_core2 robot_cpp mkt_msgs angles
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Libraries
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/score_algorithm.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME}
|
||||
PUBLIC BUILD_WITH_ROS
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::filesystem Boost::system
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::filesystem Boost::system
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Dependencies: robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core, robot_nav_core2, robot_cpp, mkt_msgs, angles, Boost")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
44
src/Algorithms/Cores/score_algorithm/README.md
Normal file
44
src/Algorithms/Cores/score_algorithm/README.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# score_algorithm
|
||||
|
||||
## Giới thiệu
|
||||
`score_algorithm` là lớp nền (base class) cho các thuật toán đánh giá và sinh lệnh điều khiển (local planning) trong `pnkx_nav_core`. Module này không tự sinh quỹ đạo cụ thể, mà cung cấp bộ khung và các hàm dùng chung để các thuật toán con triển khai.
|
||||
|
||||
## Vai trò chính
|
||||
- Chuẩn hóa giao diện (interface) cho các thuật toán tính toán quỹ đạo/lệnh.
|
||||
- Cắt đoạn `global_plan` thành đoạn con phù hợp với `local costmap`.
|
||||
- Chọn `sub-goal` và `start` để theo đuổi theo từng bước đường đi.
|
||||
- Cung cấp các hàm tiện ích: kiểm tra dừng/đi, tính quãng đường, tìm mục tiêu theo góc và khoảng cách.
|
||||
|
||||
## API chính
|
||||
Được khai báo trong `include/score_algorithm/score_algorithm.h`:
|
||||
- `initialize(...)`: khởi tạo tham số, TF, costmap, bộ sinh quỹ đạo.
|
||||
- `prepare(...)`: chuẩn bị dữ liệu dùng chung trước khi đánh giá.
|
||||
- `calculator(...)`: tính toán ra `mkt_msgs::Trajectory2D`.
|
||||
- `computePlanCommand(...)`: cắt `global_plan` thành đoạn kết quả và chọn `start/goal`.
|
||||
- `findSubGoalIndex(...)`, `getGoalIndex(...)`, `journey(...)`, `stopped(...)`: hàm phụ trợ.
|
||||
|
||||
## Nguyên lý `computePlanCommand(...)`
|
||||
Hàm này nhận `robot_pose`, `velocity`, độ dài xem trước `S` và `global_plan`, sau đó:
|
||||
1) Tìm các mốc `sub-goal` (đổi hướng / điểm gãy) bằng `findSubGoalIndex`.
|
||||
2) Khôi phục `sub_goal_index` và `sub_start_index` đã lưu (nếu có), cập nhật nếu robot đang dừng và đã vượt mốc.
|
||||
3) Tìm `start_index` gần nhất với robot trong đoạn con hợp lệ.
|
||||
4) Tìm `goal_index` dựa trên quy tắc "đi đủ xa `S` hoặc đổi hướng vượt ngưỡng".
|
||||
5) Xuất `result` là đoạn từ `closet_index` đến `goal_index`.
|
||||
|
||||
Kết quả được sử dụng bởi các local planner để sinh lệnh điều khiển tiếp theo.
|
||||
|
||||
## Sử dụng trong hệ thống
|
||||
`score_algorithm` được nạp qua pluginlib trong các local planner, ví dụ:
|
||||
- `pnkx_local_planner`
|
||||
- `pnkx_go_straight_local_planner`
|
||||
- `pnkx_rotate_local_planner`
|
||||
- `pnkx_docking_local_planner`
|
||||
|
||||
Mỗi thuật toán cụ thể sẽ kế thừa `ScoreAlgorithm` và triển khai `initialize`, `prepare`, `calculator`.
|
||||
|
||||
## Thư mục liên quan
|
||||
- `include/score_algorithm/score_algorithm.h`: giao diện chính.
|
||||
- `src/score_algorithm.cpp`: các hàm dùng chung (getGoalIndex, computePlanCommand, ...).
|
||||
|
||||
## Ghi chú
|
||||
Module này phụ thuộc vào `robot_nav_2d_msgs`, `robot_costmap_2d`, `mkt_msgs` và hệ thống TF/ROS.
|
||||
56
src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h
Executable file
56
src/Algorithms/Cores/score_algorithm/include/score_algorithm/goal_checker.h
Executable file
@@ -0,0 +1,56 @@
|
||||
#ifndef _SCORE_GOAL_CHECKER_H_INCLUDED__
|
||||
#define _SCORE_GOAL_CHECKER_H_INCLUDED__
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_geometry_msgs/Pose2D.h>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
#include <robot_nav_2d_msgs/Twist2D.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
#include <robot_nav_2d_msgs/Path2D.h>
|
||||
#include <memory>
|
||||
|
||||
namespace score_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class GoalChecker
|
||||
* @brief Function-object for checking whether a goal has been reached
|
||||
*
|
||||
* This class defines the plugin interface for determining whether you have reached
|
||||
* the goal state. This primarily consists of checking the relative positions of two poses
|
||||
* (which are presumed to be in the same frame). It can also check the velocity, as some
|
||||
* applications require that robot be stopped to be considered as having reached the goal.
|
||||
*/
|
||||
class GoalChecker
|
||||
{
|
||||
public:
|
||||
using Ptr = std::shared_ptr<score_algorithm::GoalChecker>;
|
||||
|
||||
virtual ~GoalChecker() {}
|
||||
|
||||
/**
|
||||
* @brief Initialize any parameters from the NodeHandle
|
||||
* @param nh NodeHandle for grabbing parameters
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle& nh) = 0;
|
||||
|
||||
/**
|
||||
* @brief Reset the state of the goal checker (if any)
|
||||
*/
|
||||
virtual void reset() {}
|
||||
|
||||
/**
|
||||
* @brief Check whether the goal should be considered reached
|
||||
* @param query_pose The pose to check
|
||||
* @param goal_pose The pose to check against
|
||||
*
|
||||
* @param velocity The robot's current velocity
|
||||
* @return True if goal is reached
|
||||
*/
|
||||
virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose,
|
||||
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D& velocity) = 0;
|
||||
};
|
||||
|
||||
} // namespace score_algorithm
|
||||
|
||||
#endif // _SCORE_GOAL_CHECKER_H_INCLUDED__
|
||||
178
src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h
Executable file
178
src/Algorithms/Cores/score_algorithm/include/score_algorithm/score_algorithm.h
Executable file
@@ -0,0 +1,178 @@
|
||||
#ifndef _SCORE_ALGORITHM_H_INCLUDED__
|
||||
#define _SCORE_ALGORITHM_H_INCLUDED__
|
||||
|
||||
#ifdef BUILD_WITH_ROS
|
||||
#include <ros/ros.h>
|
||||
#include <geometry_msgs/PoseStamped.h>
|
||||
#endif
|
||||
#include <robot/robot.h>
|
||||
#include <iostream>
|
||||
#include <robot_nav_2d_msgs/Twist2DStamped.h>
|
||||
#include <robot_nav_2d_msgs/Path2D.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
|
||||
#include <robot_nav_core2/common.h>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <robot_nav_core2/costmap.h>
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
#include <robot_geometry_msgs/PoseArray.h>
|
||||
#include <mkt_msgs/Trajectory2D.h>
|
||||
#include <score_algorithm/trajectory_generator.h>
|
||||
|
||||
#define FORWARD 1
|
||||
#define BACKWARD -1
|
||||
|
||||
namespace score_algorithm
|
||||
{
|
||||
class ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
using Ptr = std::shared_ptr<score_algorithm::ScoreAlgorithm>;
|
||||
|
||||
inline double smoothstep(double x)
|
||||
{
|
||||
x = std::clamp(x, 0.0, 1.0);
|
||||
return x * x * (3 - 2 * x);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param name Namespace for this planner
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
virtual void initialize(robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot,
|
||||
const score_algorithm::TrajectoryGenerator::Ptr &traj) = 0;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan,
|
||||
double &x_direction, double &y_direction, double &theta_direction) = 0;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
* @param traj
|
||||
*/
|
||||
virtual mkt_msgs::Trajectory2D calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) = 0;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() {};
|
||||
|
||||
/**
|
||||
* @brief Stoping move navigation
|
||||
*/
|
||||
virtual void stop() {};
|
||||
|
||||
/**
|
||||
* @brief resume move navigation after stopped
|
||||
*/
|
||||
virtual void resume() {};
|
||||
|
||||
std::string getName()
|
||||
{
|
||||
return name_;
|
||||
}
|
||||
|
||||
protected:
|
||||
double sign(double x)
|
||||
{
|
||||
return x < 0.0 ? -1.0 : 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get goal index
|
||||
* @param robot_pose
|
||||
* @param plan
|
||||
* @param distance
|
||||
* @param start_index
|
||||
* @param last_valid_index
|
||||
* @return goal index
|
||||
*/
|
||||
virtual unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan,
|
||||
const double distance, unsigned int start_index, unsigned int last_valid_index) const;
|
||||
|
||||
/**
|
||||
* @brief Get goal pose
|
||||
* @param robot_pose
|
||||
* @param velocity
|
||||
* @param global_plan
|
||||
* @param sub_goal
|
||||
* @param S
|
||||
* @return true if goal pose is found, false otherwise
|
||||
*/
|
||||
virtual bool computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S,
|
||||
const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result);
|
||||
|
||||
/**
|
||||
* @brief Find sub goal index
|
||||
* @param plan
|
||||
* @param index_s
|
||||
* @return true if sub goal index is found, false otherwise
|
||||
*/
|
||||
virtual bool findSubGoalIndex(const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan, std::vector<unsigned int> &seq_s, std::vector<robot_nav_2d_msgs::Pose2DStamped> &mutes);
|
||||
|
||||
/**
|
||||
* @brief Calculate journey
|
||||
* @param plan
|
||||
* @param start_index
|
||||
* @param last_valid_index
|
||||
* @return journey
|
||||
*/
|
||||
double journey(const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan, const unsigned int start_index, const unsigned int last_valid_index) const;
|
||||
|
||||
/**
|
||||
* @brief Check whether the robot is stopped or not
|
||||
* @param velocity The current odometry information for the robot
|
||||
* @param rot_stopped_velocity The rotational velocity below which the robot is considered stopped
|
||||
* @param trans_stopped_velocity The translational velocity below which the robot is considered stopped
|
||||
* @return True if the robot is stopped, false otherwise
|
||||
*/
|
||||
bool stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity);
|
||||
|
||||
void clear();
|
||||
|
||||
std::string name_;
|
||||
TFListenerPtr tf_;
|
||||
robot_costmap_2d::Costmap2DROBOT *costmap_robot_;
|
||||
TrajectoryGenerator::Ptr traj_;
|
||||
|
||||
int index_samples_;
|
||||
bool follow_step_path_;
|
||||
double xy_local_goal_tolerance_;
|
||||
double old_xy_goal_tolerance_;
|
||||
double angle_threshold_;
|
||||
|
||||
#ifdef BUILD_WITH_ROS
|
||||
ros::Publisher current_goal_pub_;
|
||||
ros::Publisher closet_robot_goal_pub_;
|
||||
#endif
|
||||
|
||||
std::vector<robot_nav_2d_msgs::Pose2DStamped> reached_intermediate_goals_;
|
||||
std::vector<unsigned int> start_index_saved_vt_;
|
||||
unsigned int sub_goal_index_saved_, sub_goal_seq_saved_;
|
||||
unsigned int sub_start_index_saved_, sub_start_seq_saved_;
|
||||
|
||||
double max_vel_x_, min_vel_x_, acc_lim_x_, decel_lim_x_;
|
||||
double max_vel_y_, min_vel_y_, acc_lim_y_, decel_lim_y_;
|
||||
double max_vel_theta_, min_vel_theta_, acc_lim_theta_, decel_lim_theta_;
|
||||
double min_speed_xy_, max_speed_xy_;
|
||||
double rot_stopped_velocity_, trans_stopped_velocity_;
|
||||
};
|
||||
} // namespace score_algorithm
|
||||
|
||||
#endif // SCORE_ALGORITHM_H_INCLUDED__
|
||||
@@ -0,0 +1,143 @@
|
||||
#ifndef _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H
|
||||
#define _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <mkt_msgs/Trajectory2D.h>
|
||||
#include <robot_nav_2d_msgs/Path2D.h>
|
||||
#include <robot_nav_2d_msgs/Twist2D.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
#include <robot_geometry_msgs/Vector3.h>
|
||||
|
||||
namespace score_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class TrajectoryGenerator
|
||||
* @brief Interface for iterating through possible velocities and creating trajectories
|
||||
*
|
||||
* This class defines the plugin interface for two separate but related components.
|
||||
*
|
||||
* First, this class provides an iterator interface for exploring all of the velocities
|
||||
* to search, given the current velocity.
|
||||
*
|
||||
* Second, the class gives an independent interface for creating a trajectory from a twist,
|
||||
* i.e. projecting it out in time and space.
|
||||
*
|
||||
* Both components rely heavily on the robot's kinematic model, and can share many parameters,
|
||||
* which is why they are grouped into a singular class.
|
||||
*/
|
||||
class TrajectoryGenerator
|
||||
{
|
||||
public:
|
||||
using Ptr = std::shared_ptr<score_algorithm::TrajectoryGenerator>;
|
||||
|
||||
virtual ~TrajectoryGenerator() {}
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle &nh) = 0;
|
||||
|
||||
/**
|
||||
* @brief Reset the state (if any) when the planner gets a new goal
|
||||
*/
|
||||
virtual void reset() {}
|
||||
|
||||
/**
|
||||
* @brief Start a new iteration based on the current velocity
|
||||
* @param current_velocity
|
||||
*/
|
||||
virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) = 0;
|
||||
|
||||
/**
|
||||
* @brief Set direct of robot based on the current velocity
|
||||
* @param direct
|
||||
*/
|
||||
virtual void setDirect(int *xytheta_direct) = 0;
|
||||
|
||||
/**
|
||||
* @brief set velocity for x, y asix of the robot
|
||||
* @param linear the velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual bool setTwistLinear(robot_geometry_msgs::Vector3 linear) = 0;
|
||||
|
||||
/**
|
||||
* @brief get velocity for x, y asix of the robot
|
||||
* @param linear The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) = 0;
|
||||
|
||||
/**
|
||||
* @brief Set velocity theta for z asix of the robot
|
||||
* @param angular the command velocity
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) = 0;
|
||||
|
||||
/**
|
||||
* @brief Get velocity theta for z asix of the robot
|
||||
* @param direct The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) = 0;
|
||||
|
||||
/**
|
||||
* @brief Test to see whether there are more twists to test
|
||||
* @return True if more twists, false otherwise
|
||||
*/
|
||||
virtual bool hasMoreTwists() = 0;
|
||||
|
||||
/**
|
||||
* @brief Return the next twist and advance the iteration
|
||||
* @return The Twist!
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0;
|
||||
|
||||
/**
|
||||
* @brief Get the current twist
|
||||
* @return The current twist
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2D getTwist() = 0;
|
||||
|
||||
/**
|
||||
* @brief Get all the twists for an iteration.
|
||||
*
|
||||
* Note: Resets the iterator if one is in process
|
||||
*
|
||||
* @param current_velocity
|
||||
* @return all the twists
|
||||
*/
|
||||
virtual std::vector<robot_nav_2d_msgs::Twist2D> getTwists(const robot_nav_2d_msgs::Twist2D ¤t_velocity)
|
||||
{
|
||||
std::vector<robot_nav_2d_msgs::Twist2D> twists;
|
||||
startNewIteration(current_velocity);
|
||||
while (hasMoreTwists())
|
||||
{
|
||||
twists.push_back(nextTwist());
|
||||
}
|
||||
return twists;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Given a cmd_vel in the robot's frame and initial conditions, generate a Trajectory2D
|
||||
* @param start_pose Current robot location
|
||||
* @param start_vel Current robot velocity
|
||||
* @param cmd_vel The desired command velocity
|
||||
*/
|
||||
virtual mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose,
|
||||
const robot_nav_2d_msgs::Path2D &transformed_plan,
|
||||
const robot_nav_2d_msgs::Twist2D &start_vel,
|
||||
const robot_nav_2d_msgs::Twist2D &cmd_vel) = 0;
|
||||
|
||||
virtual robot::NodeHandle getNodeHandle() = 0;
|
||||
|
||||
};
|
||||
|
||||
} // namespace score_algorithm
|
||||
|
||||
#endif // _SCORE_ALGORITHM_TRAJECTORY_GENERATOR_H
|
||||
37
src/Algorithms/Cores/score_algorithm/package.xml
Normal file
37
src/Algorithms/Cores/score_algorithm/package.xml
Normal file
@@ -0,0 +1,37 @@
|
||||
<package>
|
||||
<name>score_algorithm</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
score_algorithm is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. score_algorithm
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/score_algorithm</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<build_depend>robot_nav_core</build_depend>
|
||||
<build_depend>robot_nav_core2</build_depend>
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<build_depend>mkt_msgs</build_depend>
|
||||
<build_depend>angles</build_depend>
|
||||
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
<run_depend>robot_nav_core</run_depend>
|
||||
<run_depend>robot_nav_core2</run_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
<run_depend>mkt_msgs</run_depend>
|
||||
<run_depend>angles</run_depend>
|
||||
</package>
|
||||
487
src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp
Normal file
487
src/Algorithms/Cores/score_algorithm/src/score_algorithm.cpp
Normal file
@@ -0,0 +1,487 @@
|
||||
#include <robot/robot.h>
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <angles/angles.h>
|
||||
|
||||
unsigned int score_algorithm::ScoreAlgorithm::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan,
|
||||
const double distance, unsigned int start_index, unsigned int last_valid_index) const
|
||||
{
|
||||
if (start_index >= last_valid_index)
|
||||
return last_valid_index;
|
||||
|
||||
unsigned int goal_index = start_index + 1;
|
||||
const double start_direction_x = plan[goal_index].pose.x - plan[start_index].pose.x;
|
||||
const double start_direction_y = plan[goal_index].pose.y - plan[start_index].pose.y;
|
||||
if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9)
|
||||
{ // make sure that atan2 is defined
|
||||
double start_angle = atan2(start_direction_y, start_direction_x);
|
||||
double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2));
|
||||
// double angle_threshold = 0.0;
|
||||
for (unsigned int i = start_index + 1; i <= last_valid_index; i++)
|
||||
{
|
||||
const double current_direction_x = plan[i].pose.x - plan[i - 1].pose.x;
|
||||
const double current_direction_y = plan[i].pose.y - plan[i - 1].pose.y;
|
||||
const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2));
|
||||
S += dd;
|
||||
if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9)
|
||||
{
|
||||
double current_angle = atan2(current_direction_y, current_direction_x);
|
||||
goal_index = i;
|
||||
if (fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (last_valid_index - goal_index == 1)
|
||||
goal_index = last_valid_index;
|
||||
return goal_index;
|
||||
}
|
||||
|
||||
bool score_algorithm::ScoreAlgorithm::findSubGoalIndex(const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan, std::vector<unsigned int> &seq_s, std::vector<robot_nav_2d_msgs::Pose2DStamped> &mutes)
|
||||
{
|
||||
if (plan.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
double x_direction_saved = 0.0;
|
||||
robot_geometry_msgs::PoseArray poseArrayMsg;
|
||||
poseArrayMsg.header.stamp = robot::Time::now();
|
||||
poseArrayMsg.header.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped p1, p2, p3;
|
||||
|
||||
if (plan.size() < 3)
|
||||
{
|
||||
seq_s.push_back(plan.back().header.seq);
|
||||
mutes.push_back(plan.back());
|
||||
}
|
||||
else
|
||||
{
|
||||
unsigned int i = 0;
|
||||
p1 = plan[i];
|
||||
for (i = 0; i < (unsigned int)plan.size() - 2; i++)
|
||||
{
|
||||
double egde1_angle, egde2_angle;
|
||||
p2 = plan[i + 1];
|
||||
if ((fabs(p2.pose.y - p1.pose.y) > 1e-9 || fabs(p2.pose.x - p1.pose.x) > 1e-9))
|
||||
{
|
||||
egde1_angle = atan2(p2.pose.y - p1.pose.y, p2.pose.x - p1.pose.x);
|
||||
}
|
||||
else
|
||||
continue;
|
||||
|
||||
const double target_direction = cos(fabs(egde1_angle - p2.pose.theta));
|
||||
|
||||
if (target_direction * x_direction_saved < 0.0)
|
||||
{
|
||||
if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end())
|
||||
{
|
||||
seq_s.push_back(plan[i].header.seq);
|
||||
mutes.push_back(plan[i]);
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i]).pose;
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
}
|
||||
x_direction_saved = target_direction;
|
||||
|
||||
p3 = plan[i + 2];
|
||||
if ((fabs(p3.pose.y - p2.pose.y) > 1e-9 || fabs(p3.pose.x - p2.pose.x) > 1e-9))
|
||||
{
|
||||
egde2_angle = atan2(p3.pose.y - p2.pose.y, p3.pose.x - p2.pose.x);
|
||||
p1 = p2;
|
||||
}
|
||||
else
|
||||
continue;
|
||||
|
||||
double thresh_angle = 0.3;
|
||||
double angle = fabs(remainder(egde1_angle - egde2_angle, 2 * M_PI));
|
||||
if (angle >= thresh_angle || angle >= M_PI - thresh_angle)
|
||||
{
|
||||
if (std::find(seq_s.begin(), seq_s.end(), plan[i].header.seq) == seq_s.end())
|
||||
{
|
||||
seq_s.push_back(plan[i + 1].header.seq);
|
||||
mutes.push_back(plan[i + 1]);
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan[i + 1]).pose;
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
p2 = p3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seq_s.empty())
|
||||
{
|
||||
seq_s.push_back(plan.back().header.seq);
|
||||
mutes.push_back(plan.back());
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose;
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (seq_s.back() < plan.back().header.seq)
|
||||
{
|
||||
seq_s.push_back(plan.back().header.seq);
|
||||
mutes.push_back(plan.back());
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPoseStamped(plan.back()).pose;
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs::Pose2DStamped &robot_pose, const robot_nav_2d_msgs::Twist2D &velocity, const double &S,
|
||||
const robot_nav_2d_msgs::Path2D &global_plan, unsigned int &start_index_global_plan, unsigned int &goal_index_global_plan, robot_nav_2d_msgs::Path2D &result)
|
||||
{
|
||||
result.poses.clear();
|
||||
if (global_plan.poses.empty())
|
||||
{
|
||||
robot::log_error("ScoreAlgorithm: The global plan was empty.");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<unsigned int> seq_s;
|
||||
std::vector<robot_nav_2d_msgs::Pose2DStamped> mutes;
|
||||
if (!this->findSubGoalIndex(global_plan.poses, seq_s, mutes))
|
||||
{
|
||||
robot::log_error("ScoreAlgorithm: Cannot find SubGoal Index");
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned int sub_goal_index;
|
||||
unsigned int sub_start_index;
|
||||
|
||||
bool found_sub_goal_index_saved = false, found_sub_start_index_saved = false;
|
||||
for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i)
|
||||
{
|
||||
if (global_plan.poses[i].header.seq == sub_goal_seq_saved_)
|
||||
{
|
||||
sub_goal_index_saved_ = i;
|
||||
found_sub_goal_index_saved = true;
|
||||
}
|
||||
if (global_plan.poses[i].header.seq == sub_start_seq_saved_)
|
||||
{
|
||||
sub_start_index_saved_ = i;
|
||||
found_sub_start_index_saved = true;
|
||||
}
|
||||
if (found_sub_goal_index_saved && found_sub_start_index_saved)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
sub_goal_index = !found_sub_goal_index_saved ? (unsigned int)global_plan.poses.size() : sub_goal_index_saved_;
|
||||
sub_start_index = !found_sub_start_index_saved ? 0 : sub_start_index_saved_;
|
||||
|
||||
std::vector<unsigned int> index_s;
|
||||
for (auto seq : seq_s)
|
||||
{
|
||||
for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); ++i)
|
||||
{
|
||||
if (global_plan.poses[i].header.seq == seq)
|
||||
{
|
||||
index_s.push_back(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (index_s.empty())
|
||||
{
|
||||
sub_goal_index = (unsigned int)global_plan.poses.size();
|
||||
sub_goal_seq_saved_ = global_plan.poses.back().header.seq;
|
||||
}
|
||||
else
|
||||
{
|
||||
bool is_stopped = stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_);
|
||||
if (is_stopped && index_s.front() > sub_goal_index_saved_ && index_s.front() < (unsigned int)global_plan.poses.size())
|
||||
{
|
||||
// sub_goal_index = (unsigned int)index_s.front() > 0 ? (unsigned int)index_s.front() - 1 : (unsigned int)index_s.front();
|
||||
sub_goal_index = index_s.front();
|
||||
sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq;
|
||||
}
|
||||
|
||||
// Process index_s with multiple elements
|
||||
if (index_s.size() > 1)
|
||||
{
|
||||
for (size_t i = 1; i < index_s.size(); ++i)
|
||||
{
|
||||
if (index_s[i - 1] >= (unsigned int)global_plan.poses.size() || index_s[i] >= (unsigned int)global_plan.poses.size())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
double dx = robot_pose.pose.x - global_plan.poses[index_s[i - 1]].pose.x;
|
||||
double dy = robot_pose.pose.y - global_plan.poses[index_s[i - 1]].pose.y;
|
||||
double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[index_s[i - 1]].pose.theta);
|
||||
double x = cos(global_plan.poses[index_s[i - 1]].pose.theta) * dx + sin(global_plan.poses[index_s[i - 1]].pose.theta) * dy;
|
||||
double y = -sin(global_plan.poses[index_s[i - 1]].pose.theta) * dx + cos(global_plan.poses[index_s[i - 1]].pose.theta) * dy;
|
||||
|
||||
if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2)
|
||||
{
|
||||
double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
if (fabs(tolerance) <= xy_local_goal_tolerance_)
|
||||
{
|
||||
|
||||
if (index_s[i] > sub_goal_index_saved_)
|
||||
{
|
||||
sub_goal_index = (i < index_s.size() - 1) ? index_s[i] : (unsigned int)global_plan.poses.size() - 1;
|
||||
sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq;
|
||||
old_xy_goal_tolerance_ = 0.0;
|
||||
if (follow_step_path_)
|
||||
{
|
||||
sub_start_index = index_s[i - 1];
|
||||
sub_start_seq_saved_ = global_plan.poses[sub_start_index].header.seq;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Validate sub_goal_index
|
||||
if (sub_goal_index >= (unsigned int)global_plan.poses.size() - 1)
|
||||
{
|
||||
sub_goal_index = (unsigned int)global_plan.poses.size() - 1;
|
||||
sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq;
|
||||
}
|
||||
else
|
||||
{
|
||||
double dx = robot_pose.pose.x - global_plan.poses[sub_goal_index].pose.x;
|
||||
double dy = robot_pose.pose.y - global_plan.poses[sub_goal_index].pose.y;
|
||||
double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[sub_goal_index].pose.theta);
|
||||
double x = cos(global_plan.poses[sub_goal_index].pose.theta) * dx + sin(global_plan.poses[sub_goal_index].pose.theta) * dy;
|
||||
double y = -sin(global_plan.poses[sub_goal_index].pose.theta) * dx + cos(global_plan.poses[sub_goal_index].pose.theta) * dy;
|
||||
if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2)
|
||||
{
|
||||
double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
if (fabs(tolerance) <= xy_local_goal_tolerance_)
|
||||
{
|
||||
sub_goal_index = (unsigned int)global_plan.poses.size() - 1;
|
||||
sub_goal_seq_saved_ = global_plan.poses[sub_goal_index].header.seq;
|
||||
old_xy_goal_tolerance_ = 0.0;
|
||||
robot::log_info("ScoreAlgorithm: Single sub-goal reached, setting sub_goal_index to %d", sub_goal_index);
|
||||
}
|
||||
}
|
||||
else
|
||||
old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sub_start_index >= sub_goal_index)
|
||||
{
|
||||
robot::log_error("ScoreAlgorithm: Sub path is empty");
|
||||
return false;
|
||||
}
|
||||
|
||||
// find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map
|
||||
// Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map
|
||||
unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi
|
||||
unsigned int closet_index = 0;
|
||||
double distance_to_start = std::numeric_limits<double>::infinity(); // Xét giá trị là vô cùng oo
|
||||
bool started_path = false;
|
||||
for (unsigned int i = sub_start_index; i < sub_goal_index; ++i)
|
||||
{
|
||||
// Still on the costmap. Continue.
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[i].pose, robot_pose.pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét
|
||||
if (distance_to_start > distance)
|
||||
{
|
||||
start_index = i;
|
||||
closet_index = start_index;
|
||||
distance_to_start = distance;
|
||||
started_path = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Nếu khồng tìm được điểm gần với robot nhất thì trả về false
|
||||
if (!started_path)
|
||||
{
|
||||
robot::log_error("ScoreAlgorithm: None of the points of the global plan were in the local costmap.");
|
||||
return false;
|
||||
}
|
||||
std::stringstream ss;
|
||||
start_index_saved_vt_.push_back(global_plan.poses[start_index].header.seq);
|
||||
if (start_index_saved_vt_.size() > index_samples_)
|
||||
start_index_saved_vt_.erase(start_index_saved_vt_.begin());
|
||||
|
||||
unsigned num = 0;
|
||||
if (!start_index_saved_vt_.empty())
|
||||
{
|
||||
for (int i = 0; i < (int)start_index_saved_vt_.size() - 1; i++)
|
||||
{
|
||||
if (start_index_saved_vt_[i] == start_index_saved_vt_[i + 1])
|
||||
num++;
|
||||
ss << start_index_saved_vt_[i] << " ";
|
||||
}
|
||||
}
|
||||
if (num < index_samples_ - 1 && !start_index_saved_vt_.empty())
|
||||
{
|
||||
auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end()));
|
||||
unsigned int max_start_index = start_index;
|
||||
for (unsigned int i = 0; i < (unsigned int)global_plan.poses.size(); i++)
|
||||
{
|
||||
if (global_plan.poses[i].header.seq == max_iter)
|
||||
{
|
||||
max_start_index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
double S1 = journey(global_plan.poses, start_index, (unsigned int)global_plan.poses.size() - 1);
|
||||
double S2 = journey(global_plan.poses, max_start_index, (unsigned int)global_plan.poses.size() - 1);
|
||||
|
||||
if (S2 - S1)
|
||||
{
|
||||
start_index = max_start_index;
|
||||
}
|
||||
}
|
||||
// ROS_INFO_STREAM_THROTTLE(0.1, ss.str() << "\n");
|
||||
|
||||
// find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map
|
||||
// Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map
|
||||
if (start_index < 1)
|
||||
start_index = 1;
|
||||
// unsigned int last_valid_index = (unsigned int)global_plan.poses.size() - 1;
|
||||
unsigned int last_valid_index = sub_goal_index;
|
||||
|
||||
// find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point,
|
||||
// i.e. is within angle_threshold_ of the starting direction.
|
||||
// Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan
|
||||
unsigned int goal_index = start_index;
|
||||
while (goal_index < last_valid_index)
|
||||
{
|
||||
// Tìm kiếm vị trí điểm mục tiêu phù hợp
|
||||
goal_index = getGoalIndex(robot_pose.pose, global_plan.poses, S, start_index, last_valid_index);
|
||||
|
||||
// check if goal already reached
|
||||
bool goal_already_reached = false;
|
||||
|
||||
for (auto &reached_intermediate_goal : reached_intermediate_goals_)
|
||||
{
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[goal_index].pose));
|
||||
if (distance < xy_local_goal_tolerance_)
|
||||
{
|
||||
goal_already_reached = true;
|
||||
// choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again
|
||||
// (start_index is now > goal_index)
|
||||
for (start_index = goal_index; start_index < last_valid_index; ++start_index)
|
||||
{
|
||||
distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal.pose, global_plan.poses[start_index].pose);
|
||||
if (distance >= xy_local_goal_tolerance_)
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!goal_already_reached)
|
||||
{
|
||||
// new goal not in reached_intermediate_goals_
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(global_plan.poses[start_index].pose, global_plan.poses[goal_index].pose));
|
||||
if (distance < xy_local_goal_tolerance_)
|
||||
{
|
||||
// the robot has currently reached the goal
|
||||
reached_intermediate_goals_.push_back(global_plan.poses[goal_index]);
|
||||
robot::log_info("ScoreAlgorithm: Number of reached_intermediate goals: %d", reached_intermediate_goals_.size());
|
||||
}
|
||||
else
|
||||
{
|
||||
// we've found a new goal!
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (start_index > goal_index)
|
||||
start_index = goal_index;
|
||||
if (goal_index > last_valid_index)
|
||||
goal_index = last_valid_index;
|
||||
if ((unsigned int)global_plan.poses.size() == 2 && !global_plan.poses.empty())
|
||||
{
|
||||
start_index = 0;
|
||||
goal_index = 1;
|
||||
}
|
||||
|
||||
if (goal_index == (unsigned int)global_plan.poses.size() - 1)
|
||||
start_index = (unsigned int)global_plan.poses.size() - 2;
|
||||
|
||||
start_index_global_plan = start_index;
|
||||
goal_index_global_plan = goal_index;
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped sub_pose;
|
||||
sub_pose = global_plan.poses[closet_index];
|
||||
|
||||
#ifdef BUILD_WITH_ROS
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped sub_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_pose);
|
||||
geometry_msgs::PoseStamped sub_pose_stamped_ros;
|
||||
sub_pose_stamped_ros.header.stamp = ros::Time::now();
|
||||
sub_pose_stamped_ros.header.frame_id = sub_pose_stamped.header.frame_id;
|
||||
sub_pose_stamped_ros.pose.position.x = sub_pose_stamped.pose.position.x;
|
||||
sub_pose_stamped_ros.pose.position.y = sub_pose_stamped.pose.position.y;
|
||||
sub_pose_stamped_ros.pose.position.z = 0.9;
|
||||
sub_pose_stamped_ros.pose.orientation.x = sub_pose_stamped.pose.orientation.x;
|
||||
sub_pose_stamped_ros.pose.orientation.y = sub_pose_stamped.pose.orientation.y;
|
||||
sub_pose_stamped_ros.pose.orientation.z = sub_pose_stamped.pose.orientation.z;
|
||||
sub_pose_stamped_ros.pose.orientation.w = sub_pose_stamped.pose.orientation.w;
|
||||
closet_robot_goal_pub_.publish(sub_pose_stamped_ros);
|
||||
}
|
||||
#endif
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped sub_goal;
|
||||
sub_goal = global_plan.poses[goal_index];
|
||||
#ifdef BUILD_WITH_ROS
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped sub_goal_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_goal);
|
||||
geometry_msgs::PoseStamped sub_goal_stamped_ros;
|
||||
sub_goal_stamped_ros.header.stamp = ros::Time::now();
|
||||
sub_goal_stamped_ros.header.frame_id = sub_goal_stamped.header.frame_id;
|
||||
sub_goal_stamped_ros.pose.position.x = sub_goal_stamped.pose.position.x;
|
||||
sub_goal_stamped_ros.pose.position.y = sub_goal_stamped.pose.position.y;
|
||||
sub_goal_stamped_ros.pose.position.z = 0.9;
|
||||
sub_goal_stamped_ros.pose.orientation.x = sub_goal_stamped.pose.orientation.x;
|
||||
sub_goal_stamped_ros.pose.orientation.y = sub_goal_stamped.pose.orientation.y;
|
||||
sub_goal_stamped_ros.pose.orientation.z = sub_goal_stamped.pose.orientation.z;
|
||||
sub_goal_stamped_ros.pose.orientation.w = sub_goal_stamped.pose.orientation.w;
|
||||
current_goal_pub_.publish(sub_goal_stamped_ros);
|
||||
}
|
||||
#endif
|
||||
|
||||
result.header = global_plan.header;
|
||||
for (int i = closet_index; i <= goal_index; i++)
|
||||
{
|
||||
result.poses.push_back(global_plan.poses[i]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
double score_algorithm::ScoreAlgorithm::journey(const std::vector<robot_nav_2d_msgs::Pose2DStamped> &plan, const unsigned int start_index, const unsigned int last_valid_index) const
|
||||
{
|
||||
double S = 0;
|
||||
if (last_valid_index - start_index > 1)
|
||||
{
|
||||
for (int i = start_index; i < last_valid_index; i++)
|
||||
{
|
||||
S += robot_nav_2d_utils::poseDistance(plan[i].pose, plan[i + 1].pose);
|
||||
}
|
||||
}
|
||||
return S;
|
||||
}
|
||||
|
||||
bool score_algorithm::ScoreAlgorithm::stopped(const robot_nav_2d_msgs::Twist2D &velocity, const double &rot_stopped_velocity, const double &trans_stopped_velocity)
|
||||
{
|
||||
return fabs(velocity.theta) <= rot_stopped_velocity && fabs(velocity.x) <= trans_stopped_velocity && fabs(velocity.y) <= trans_stopped_velocity;
|
||||
}
|
||||
|
||||
void score_algorithm::ScoreAlgorithm::clear()
|
||||
{
|
||||
reached_intermediate_goals_.clear();
|
||||
start_index_saved_vt_.clear();
|
||||
sub_goal_index_saved_ = sub_goal_seq_saved_ = 0;
|
||||
sub_start_index_saved_, sub_start_seq_saved_ = 0;
|
||||
}
|
||||
129
src/Algorithms/Libraries/angles/CMakeLists.txt
Normal file
129
src/Algorithms/Libraries/angles/CMakeLists.txt
Normal file
@@ -0,0 +1,129 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(angles VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building angles with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building angles with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
# LIBRARIES không cần vì đây là header-only library
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Tìm tất cả header files
|
||||
file(GLOB_RECURSE HEADERS "include/angles/*.h")
|
||||
|
||||
# Tạo INTERFACE library (header-only)
|
||||
add_library(${PROJECT_NAME} INTERFACE)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
# Set include directories
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# Link dependencies (header-only, chỉ cần include paths)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
${catkin_LIBRARIES}
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# Set include directories
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME} (Header-Only)")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Headers found:")
|
||||
foreach(hdr ${HEADERS})
|
||||
message(STATUS " - ${hdr}")
|
||||
endforeach()
|
||||
message(STATUS "Dependencies: None")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
48
src/Algorithms/Libraries/angles/include/angles/angles.h
Normal file
48
src/Algorithms/Libraries/angles/include/angles/angles.h
Normal file
@@ -0,0 +1,48 @@
|
||||
#ifndef ANGLES_ANGLES_H
|
||||
#define ANGLES_ANGLES_H
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace angles
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Normalize an angle to the range [-π, π]
|
||||
* @param angle The angle in radians to normalize
|
||||
* @return The normalized angle in the range [-π, π]
|
||||
*/
|
||||
inline double normalize_angle(double angle)
|
||||
{
|
||||
while (angle > M_PI)
|
||||
angle -= 2.0 * M_PI;
|
||||
while (angle < -M_PI)
|
||||
angle += 2.0 * M_PI;
|
||||
return angle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate the shortest angular distance between two angles
|
||||
*
|
||||
* Computes the shortest angular distance from angle 'from' to angle 'to'.
|
||||
* The result is in the range [-π, π], where positive values indicate
|
||||
* counter-clockwise rotation and negative values indicate clockwise rotation.
|
||||
*
|
||||
* @param from The starting angle in radians
|
||||
* @param to The target angle in radians
|
||||
* @return The shortest angular distance in radians, in the range [-π, π]
|
||||
*
|
||||
* @code
|
||||
* double diff = angles::shortest_angular_distance(0.0, M_PI/2); // Returns π/2
|
||||
* double diff2 = angles::shortest_angular_distance(M_PI, 0.0); // Returns -π (or π, normalized)
|
||||
* @endcode
|
||||
*/
|
||||
inline double shortest_angular_distance(double from, double to)
|
||||
{
|
||||
double diff = to - from;
|
||||
return normalize_angle(diff);
|
||||
}
|
||||
|
||||
} // namespace angles
|
||||
|
||||
#endif // ANGLES_ANGLES_H
|
||||
|
||||
22
src/Algorithms/Libraries/angles/package.xml
Normal file
22
src/Algorithms/Libraries/angles/package.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<package>
|
||||
<name>angles</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
angles is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. angles
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/angles</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
</package>
|
||||
181
src/Algorithms/Libraries/kalman/CMakeLists.txt
Executable file
181
src/Algorithms/Libraries/kalman/CMakeLists.txt
Executable file
@@ -0,0 +1,181 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(kalman VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building kalman with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building kalman with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Eigen3 REQUIRED)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}
|
||||
DEPENDS Eigen3
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/kalman.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Eigen3::Eigen
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
Eigen3::Eigen
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Test executable
|
||||
# ========================================================
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/kalman-test.cpp)
|
||||
add_executable(${PROJECT_NAME}_node src/kalman-test.cpp)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_node PRIVATE
|
||||
${PROJECT_NAME}
|
||||
Eigen3::Eigen
|
||||
)
|
||||
|
||||
if(NOT BUILDING_WITH_CATKIN)
|
||||
# Configure RPATH to find libraries in devel space
|
||||
set_target_properties(${PROJECT_NAME}_node PROPERTIES
|
||||
BUILD_WITH_INSTALL_RPATH FALSE
|
||||
INSTALL_RPATH_USE_LINK_PATH TRUE
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install test executable if it exists
|
||||
if(TARGET ${PROJECT_NAME}_node)
|
||||
install(TARGETS ${PROJECT_NAME}_node
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
endif()
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install test executable if it exists
|
||||
if(TARGET ${PROJECT_NAME}_node)
|
||||
install(TARGETS ${PROJECT_NAME}_node
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
endif()
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: ${PROJECT_NAME}")
|
||||
if(TARGET ${PROJECT_NAME}_node)
|
||||
message(STATUS "Executables: ${PROJECT_NAME}_node")
|
||||
endif()
|
||||
message(STATUS "Dependencies: Eigen3")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
18
src/Algorithms/Libraries/kalman/README.md
Executable file
18
src/Algorithms/Libraries/kalman/README.md
Executable file
@@ -0,0 +1,18 @@
|
||||
Kalman Filter
|
||||
=============
|
||||
This is a basic Kalman filter implementation in C++ using the
|
||||
[Eigen](http://eigen.tuxfamily.org/) library. It implements the algorithm
|
||||
directly as found in [An Introduction to the Kalman Filter](http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf).
|
||||
|
||||
There is a test program that estimates the motion of a projectile based on
|
||||
noisy observations. To run it, use CMake:
|
||||
|
||||
cd kalman-cpp
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
make
|
||||
./kalman-test
|
||||
|
||||
Note: You may have to specify the path to your Eigen library in
|
||||
`CMakeLists.txt`.
|
||||
91
src/Algorithms/Libraries/kalman/include/kalman/kalman.h
Executable file
91
src/Algorithms/Libraries/kalman/include/kalman/kalman.h
Executable file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Kalman filter implementation using Eigen. Based on the following
|
||||
* introductory paper:
|
||||
*
|
||||
* http://www.cs.unc.edu/~welch/media/pdf/kalman_intro.pdf
|
||||
*
|
||||
* @author: Hayk Martirosyan
|
||||
* @date: 2014.11.15
|
||||
*/
|
||||
|
||||
#include <Eigen/Dense>
|
||||
|
||||
#pragma once
|
||||
|
||||
class KalmanFilter {
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* Create a Kalman filter with the specified matrices.
|
||||
* A - System dynamics matrix
|
||||
* C - Output matrix
|
||||
* Q - Process noise covariance
|
||||
* R - Measurement noise covariance
|
||||
* P - Estimate error covariance
|
||||
*/
|
||||
KalmanFilter(
|
||||
double dt,
|
||||
const Eigen::MatrixXd& A,
|
||||
const Eigen::MatrixXd& C,
|
||||
const Eigen::MatrixXd& Q,
|
||||
const Eigen::MatrixXd& R,
|
||||
const Eigen::MatrixXd& P
|
||||
);
|
||||
|
||||
/**
|
||||
* Create a blank estimator.
|
||||
*/
|
||||
KalmanFilter();
|
||||
|
||||
/**
|
||||
* Initialize the filter with initial states as zero.
|
||||
*/
|
||||
void init();
|
||||
|
||||
/**
|
||||
* Initialize the filter with a guess for initial states.
|
||||
*/
|
||||
void init(double t0, const Eigen::VectorXd& x0);
|
||||
|
||||
/**
|
||||
* Update the estimated state based on measured values. The
|
||||
* time step is assumed to remain constant.
|
||||
*/
|
||||
void update(const Eigen::VectorXd& y);
|
||||
|
||||
/**
|
||||
* Update the estimated state based on measured values,
|
||||
* using the given time step and dynamics matrix.
|
||||
*/
|
||||
void update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A);
|
||||
|
||||
/**
|
||||
* Return the current state and time.
|
||||
*/
|
||||
Eigen::VectorXd state() { return x_hat; };
|
||||
double time() { return t; };
|
||||
|
||||
private:
|
||||
|
||||
// Matrices for computation
|
||||
Eigen::MatrixXd A, C, Q, R, P, K, P0;
|
||||
|
||||
// System dimensions
|
||||
int m, n;
|
||||
|
||||
// Initial and current time
|
||||
double t0, t;
|
||||
|
||||
// Discrete time step
|
||||
double dt;
|
||||
|
||||
// Is the filter initialized?
|
||||
bool initialized;
|
||||
|
||||
// n-size identity
|
||||
Eigen::MatrixXd I;
|
||||
|
||||
// Estimated states
|
||||
Eigen::VectorXd x_hat, x_hat_new;
|
||||
};
|
||||
22
src/Algorithms/Libraries/kalman/package.xml
Normal file
22
src/Algorithms/Libraries/kalman/package.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<package>
|
||||
<name>kalman</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
kalman is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. kalman
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/kalman</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
</package>
|
||||
77
src/Algorithms/Libraries/kalman/src/kalman-test.cpp
Executable file
77
src/Algorithms/Libraries/kalman/src/kalman-test.cpp
Executable file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Test for the KalmanFilter class with 1D projectile motion.
|
||||
*
|
||||
* @author: Hayk Martirosyan
|
||||
* @date: 2014.11.15
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <Eigen/Dense>
|
||||
|
||||
#include <kalman/kalman.h>
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
|
||||
int n = 3; // Number of states
|
||||
int m = 1; // Number of measurements
|
||||
|
||||
double dt = 1.0/30; // Time step
|
||||
|
||||
Eigen::MatrixXd A(n, n); // System dynamics matrix
|
||||
Eigen::MatrixXd C(m, n); // Output matrix
|
||||
Eigen::MatrixXd Q(n, n); // Process noise covariance
|
||||
Eigen::MatrixXd R(m, m); // Measurement noise covariance
|
||||
Eigen::MatrixXd P(n, n); // Estimate error covariance
|
||||
|
||||
// Discrete LTI projectile motion, measuring position only
|
||||
A << 1, dt, 0, 0, 1, dt, 0, 0, 1;
|
||||
C << 1, 0, 0;
|
||||
|
||||
// Reasonable covariance matrices
|
||||
Q << .05, .05, .0, .05, .05, .0, .0, .0, .0;
|
||||
R << 5;
|
||||
P << .1, .1, .1, .1, 10000, 10, .1, 10, 100;
|
||||
|
||||
std::cout << "A: \n" << A << std::endl;
|
||||
std::cout << "C: \n" << C << std::endl;
|
||||
std::cout << "Q: \n" << Q << std::endl;
|
||||
std::cout << "R: \n" << R << std::endl;
|
||||
std::cout << "P: \n" << P << std::endl;
|
||||
|
||||
// Construct the filter
|
||||
KalmanFilter kf(dt,A, C, Q, R, P);
|
||||
|
||||
// List of noisy position measurements (y)
|
||||
std::vector<double> measurements = {
|
||||
1.04202710058, 1.10726790452, 1.2913511148, 1.48485250951, 1.72825901034,
|
||||
1.74216489744, 2.11672039768, 2.14529225112, 2.16029641405, 2.21269371128,
|
||||
2.57709350237, 2.6682215744, 2.51641839428, 2.76034056782, 2.88131780617,
|
||||
2.88373786518, 2.9448468727, 2.82866600131, 3.0006601946, 3.12920591669,
|
||||
2.858361783, 2.83808170354, 2.68975330958, 2.66533185589, 2.81613499531,
|
||||
2.81003612051, 2.88321849354, 2.69789264832, 2.4342229249, 2.23464791825,
|
||||
2.30278776224, 2.02069770395, 1.94393985809, 1.82498398739, 1.52526230354,
|
||||
1.86967808173, 1.18073207847, 1.10729605087, 0.916168349913, 0.678547664519,
|
||||
0.562381751596, 0.355468474885, -0.155607486619, -0.287198661013, -0.602973173813
|
||||
};
|
||||
|
||||
// Best guess of initial states
|
||||
Eigen::VectorXd x0(n);
|
||||
double t = 0;
|
||||
x0 << measurements[0], 0, -9.81;
|
||||
kf.init(t, x0);
|
||||
|
||||
// Feed measurements into filter, output estimated states
|
||||
|
||||
Eigen::VectorXd y(m);
|
||||
std::cout << "t = " << t << ", " << "x_hat[0]: " << kf.state().transpose() << std::endl;
|
||||
for(int i = 0; i < measurements.size(); i++) {
|
||||
t += dt;
|
||||
y << measurements[i];
|
||||
kf.update(y);
|
||||
std::cout << "t = " << t << ", " << "y[" << i << "] = " << y.transpose()
|
||||
<< ", x_hat[" << i << "] = " << kf.state().transpose() << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
96
src/Algorithms/Libraries/kalman/src/kalman.cpp
Executable file
96
src/Algorithms/Libraries/kalman/src/kalman.cpp
Executable file
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Implementation of KalmanFilter class.
|
||||
*
|
||||
* @author: Hayk Martirosyan
|
||||
* @date: 2014.11.15
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <kalman/kalman.h>
|
||||
|
||||
KalmanFilter::KalmanFilter(
|
||||
double dt,
|
||||
const Eigen::MatrixXd& A,
|
||||
const Eigen::MatrixXd& C,
|
||||
const Eigen::MatrixXd& Q,
|
||||
const Eigen::MatrixXd& R,
|
||||
const Eigen::MatrixXd& P)
|
||||
: A(A), C(C), Q(Q), R(R), P0(P),
|
||||
m(C.rows()), n(A.rows()), dt(dt), initialized(false),
|
||||
I(n, n), x_hat(n), x_hat_new(n)
|
||||
{
|
||||
I.setIdentity();
|
||||
}
|
||||
|
||||
KalmanFilter::KalmanFilter()
|
||||
: m(0),
|
||||
n(0),
|
||||
t0(0.0),
|
||||
t(0.0),
|
||||
dt(0.0),
|
||||
initialized(false)
|
||||
{
|
||||
}
|
||||
|
||||
void KalmanFilter::init(double t0, const Eigen::VectorXd& x0) {
|
||||
x_hat = x0;
|
||||
P = P0;
|
||||
this->t0 = t0;
|
||||
t = t0;
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
void KalmanFilter::init() {
|
||||
x_hat.setZero();
|
||||
P = P0;
|
||||
t0 = 0;
|
||||
t = t0;
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
void KalmanFilter::update(const Eigen::VectorXd& y) {
|
||||
|
||||
if(!initialized)
|
||||
throw std::runtime_error("Filter is not initialized!");
|
||||
|
||||
if (y.size() != m)
|
||||
throw std::runtime_error("KalmanFilter::update(): measurement vector has wrong size");
|
||||
|
||||
if (A.rows() != n || A.cols() != n || C.rows() != m || C.cols() != n ||
|
||||
Q.rows() != n || Q.cols() != n || R.rows() != m || R.cols() != m ||
|
||||
P.rows() != n || P.cols() != n)
|
||||
throw std::runtime_error("KalmanFilter::update(): matrix dimensions are inconsistent");
|
||||
|
||||
x_hat_new = A * x_hat;
|
||||
P = A*P*A.transpose() + Q;
|
||||
|
||||
const Eigen::MatrixXd S = C * P * C.transpose() + R;
|
||||
Eigen::LDLT<Eigen::MatrixXd> ldlt(S);
|
||||
if (ldlt.info() != Eigen::Success)
|
||||
throw std::runtime_error("KalmanFilter::update(): failed to decompose innovation covariance");
|
||||
|
||||
// K = P*C' * inv(S) -> solve(S * X = (P*C')^T)
|
||||
const Eigen::MatrixXd PCt = P * C.transpose();
|
||||
const Eigen::MatrixXd KT = ldlt.solve(PCt.transpose());
|
||||
if (ldlt.info() != Eigen::Success)
|
||||
throw std::runtime_error("KalmanFilter::update(): failed to solve for Kalman gain");
|
||||
K = KT.transpose();
|
||||
|
||||
x_hat_new += K * (y - C*x_hat_new);
|
||||
|
||||
// Joseph form: keeps P symmetric / PSD under numeric errors
|
||||
const Eigen::MatrixXd IKC = I - K * C;
|
||||
P = IKC * P * IKC.transpose() + K * R * K.transpose();
|
||||
x_hat = x_hat_new;
|
||||
|
||||
t += dt;
|
||||
}
|
||||
|
||||
void KalmanFilter::update(const Eigen::VectorXd& y, double dt, const Eigen::MatrixXd A) {
|
||||
|
||||
this->A = A;
|
||||
this->dt = dt;
|
||||
update(y);
|
||||
}
|
||||
190
src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt
Normal file
190
src/Algorithms/Libraries/mkt_algorithm/CMakeLists.txt
Normal file
@@ -0,0 +1,190 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(mkt_algorithm VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building mkt_algorithm with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building mkt_algorithm with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
find_package(Eigen3 REQUIRED)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
geometry_msgs
|
||||
score_algorithm
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
kalman
|
||||
angles
|
||||
nav_grid
|
||||
robot_costmap_2d
|
||||
robot_sensor_msgs
|
||||
robot_std_msgs
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
geometry_msgs
|
||||
score_algorithm
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
kalman
|
||||
angles
|
||||
nav_grid
|
||||
robot_costmap_2d
|
||||
robot_sensor_msgs
|
||||
robot_std_msgs
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}_diff
|
||||
CATKIN_DEPENDS geometry_msgs score_algorithm robot_nav_2d_msgs robot_nav_2d_utils kalman angles nav_grid robot_costmap_2d robot_sensor_msgs robot_std_msgs robot_cpp
|
||||
DEPENDS Boost Eigen3
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME}_diff SHARED
|
||||
src/diff/diff_predictive_trajectory.cpp
|
||||
src/diff/diff_rotate_to_goal.cpp
|
||||
src/diff/diff_go_straight.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME}_diff ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_diff
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_diff
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::system Eigen3::Eigen
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_diff
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_diff
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::system Eigen3::Eigen
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME}_diff PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}_diff
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install plugins.xml if it exists
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml)
|
||||
install(FILES plugins.xml
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
|
||||
)
|
||||
endif()
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}_diff
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install plugins.xml if it exists
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml)
|
||||
install(FILES plugins.xml
|
||||
DESTINATION share/${PROJECT_NAME}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: ${PROJECT_NAME}_diff")
|
||||
message(STATUS "Dependencies: geometry_msgs, score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, kalman, angles, nav_grid, robot_costmap_2d, robot_sensor_msgs, robot_std_msgs, robot_cpp, Boost, Eigen3")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
0
src/Algorithms/Libraries/mkt_algorithm/README.md
Normal file
0
src/Algorithms/Libraries/mkt_algorithm/README.md
Normal file
@@ -0,0 +1,108 @@
|
||||
#ifndef _NAV_ALGORITHM_BICYCLE_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_BICYCLE_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <mkt_algorithm/equation_line.h>
|
||||
#include <pluginlib/class_loader.h>
|
||||
#include <robot_geometry_msgs/PoseArray.h>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
#include <kalman/kalman.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class Bicycle
|
||||
* @brief Standard Bicycle-like ScoreAlgorithm
|
||||
*/
|
||||
class Bicycle : public score_algorithm::ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
|
||||
Bicycle() {}; //: line_generator_(nullptr) {};
|
||||
|
||||
virtual ~Bicycle() {};
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override;
|
||||
|
||||
|
||||
protected:
|
||||
|
||||
unsigned int getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector<robot_geometry_msgs::Pose2D> &plan,
|
||||
const double distance, unsigned int start_index, unsigned int last_valid_index) const;
|
||||
|
||||
double journey(const std::vector<robot_geometry_msgs::Pose2D> &plan, const unsigned int start_index, const unsigned int last_valid_index) const;
|
||||
|
||||
|
||||
bool getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal,
|
||||
double &target_direction);
|
||||
|
||||
bool findSubGoalIndex(const std::vector<robot_geometry_msgs::Pose2D> &plan, std::vector<unsigned int> &index_s);
|
||||
|
||||
robot::NodeHandle nh_priv_, nh_;
|
||||
std::string frame_id_path_;
|
||||
robot::Publisher reached_intermediate_goals_pub_, current_goal_pub_, closet_robot_goal_pub_;
|
||||
|
||||
std::vector<robot_geometry_msgs::Pose2D> reached_intermediate_goals_;
|
||||
robot_geometry_msgs::Pose2D rev_sub_goal_, sub_goal_;
|
||||
robot_geometry_msgs::Pose2D goal_;
|
||||
robot_nav_2d_msgs::Path2D global_plan_;
|
||||
|
||||
unsigned int start_index_saved_;
|
||||
unsigned int sub_goal_index_saved_, sub_start_index_saved_;
|
||||
std::vector<unsigned int> start_index_saved_vt_;
|
||||
int index_samples_;
|
||||
|
||||
double steering_fix_wheel_distance_x_;
|
||||
double steering_fix_wheel_distance_y_;
|
||||
double xy_local_goal_tolerance_;
|
||||
double xy_goal_tolerance_;
|
||||
double angle_threshold_;
|
||||
double acc_lim_theta_;
|
||||
double decel_lim_theta_;
|
||||
double x_direction_, y_direction_, theta_direction_;
|
||||
double k_d_reduce_, distance_rg_, k_ld_, ld_min_, ld_max_;
|
||||
double controller_frequency_param_name_;
|
||||
|
||||
bool follow_step_path_;
|
||||
bool is_filter_;
|
||||
boost::shared_ptr<KalmanFilter> kf_;
|
||||
robot::Publisher cmd_raw_pub_;
|
||||
robot::Time last_actuator_update_;
|
||||
}; // class Bicycle
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
|
||||
#endif //_NAV_ALGORITHM_BICYCLE_H_INCLUDED__
|
||||
@@ -0,0 +1,74 @@
|
||||
#ifndef __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__
|
||||
#define __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__
|
||||
#include <ros/ros.h>
|
||||
#include <robot_geometry_msgs/Pose2D.h>
|
||||
#include <iostream>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class NoSolution
|
||||
*/
|
||||
class NoSolution : public std::exception {
|
||||
public:
|
||||
const char * what () const throw () {
|
||||
return "Robot cannot calculate error line!";
|
||||
}
|
||||
}; // class NoSolution
|
||||
|
||||
/**
|
||||
* @class LineGenerator
|
||||
*/
|
||||
class LineGenerator
|
||||
{
|
||||
/* data */
|
||||
struct LineEquation {
|
||||
robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */
|
||||
robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */
|
||||
float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */
|
||||
};
|
||||
|
||||
/* Save data present position */
|
||||
struct PresentPosition {
|
||||
float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */
|
||||
float Yaw_degree; /* Angle of Robot (degree) */
|
||||
float Yaw_rad; /* Angle of Robot (degree) */
|
||||
float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */
|
||||
double distance_to_goal; /* The distance from query pose to goal */
|
||||
double distance_to_start; /* The distance from query pose to start*/
|
||||
double distace_start_goal;
|
||||
};
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief To caculated the equation of the line
|
||||
* @param start_point start point of the line
|
||||
* @param end_point end point of the line
|
||||
*/
|
||||
virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point);
|
||||
|
||||
/**
|
||||
* @brief Calculating error
|
||||
* @param[in] Lm The distance from the center of the wheel axis to the center line
|
||||
* @param[in] pose
|
||||
* @param[in] rev
|
||||
*/
|
||||
virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false);
|
||||
|
||||
/**
|
||||
* @brief Calculating tolerance
|
||||
* @param query_pose The pose to check
|
||||
* @param goal_pose The pose to check against
|
||||
*/
|
||||
virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose);
|
||||
|
||||
/* Properties */
|
||||
LineEquation Leq_;
|
||||
PresentPosition present_pose_;
|
||||
|
||||
}; // class LineGenerator
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif // __NAV_ALGORITHM_EQUATION_LINE_H_INCLUDED__
|
||||
@@ -0,0 +1,70 @@
|
||||
#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <pluginlib/class_loader.h>
|
||||
#include <robot_geometry_msgs/PoseArray.h>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class GoStraight
|
||||
* @brief Standard Bicycle-like ScoreAlgorithm
|
||||
*/
|
||||
class GoStraight : public score_algorithm::ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
|
||||
GoStraight() {};
|
||||
|
||||
virtual ~GoStraight() {};
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override;
|
||||
|
||||
|
||||
protected:
|
||||
robot::NodeHandle nh_;
|
||||
robot::NodeHandle nh_kinematics_;
|
||||
|
||||
double steering_fix_wheel_distance_x_;
|
||||
double steering_fix_wheel_distance_y_;
|
||||
robot_geometry_msgs::Pose2D goal_;
|
||||
robot::Time time_last_cmd_;
|
||||
|
||||
}; // class GoStraight
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
#ifndef _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/goal_checker.h>
|
||||
#include <mkt_algorithm/equation_line.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
class GoalChecker : public score_algorithm::GoalChecker
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Initialize any parameters from the NodeHandle
|
||||
* @param nh NodeHandle for grabbing parameters
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle& nh) override;
|
||||
|
||||
/**
|
||||
* @brief Reset the state of the goal checker (if any)
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Check whether the goal should be considered reached
|
||||
* @param query_pose The pose to check
|
||||
* @param goal_pose The pose to check against
|
||||
* @param velocity The robot's current velocity
|
||||
* @return True if goal is reached
|
||||
*/
|
||||
bool isGoalReached(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose,
|
||||
const std::vector<robot_geometry_msgs::PoseStamped>& path, const robot_nav_2d_msgs::Twist2D& velocity) override;
|
||||
|
||||
protected:
|
||||
|
||||
boost::shared_ptr<mkt_algorithm::LineGenerator> line_generator_;
|
||||
double yaw_goal_tolerance_;
|
||||
double xy_goal_tolerance_;
|
||||
double old_xy_goal_tolerance_;
|
||||
bool setup_;
|
||||
};
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif // _NAV_ALGORITHM_CHECKER_GOAL_H_INCLUDED__
|
||||
@@ -0,0 +1,60 @@
|
||||
#ifndef _NAV_ALGORITHM_PTA_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_PTA_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <mkt_algorithm/equation_line.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class PTA
|
||||
* @brief Standard PTA-like ScoreAlgorithm
|
||||
*/
|
||||
class PTA : public score_algorithm::ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
|
||||
PTA() : line_generator_(nullptr) {};
|
||||
|
||||
virtual ~PTA() {};
|
||||
|
||||
// Standard ScoreAlgorithm Interface
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override;
|
||||
|
||||
protected:
|
||||
|
||||
boost::shared_ptr<mkt_algorithm::LineGenerator> line_generator_;
|
||||
double pta_amplitude_max_; // (Default: 0.5 - Range: 0.1 -> 1.0) Cai dat bien do (mot phia - m) cho phep robot di chuyen trong do
|
||||
|
||||
}; // class PTA
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
|
||||
#endif //_NAV_ALGORITHM_PTA_H_INCLUDED__
|
||||
@@ -0,0 +1,74 @@
|
||||
#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <pluginlib/class_loader.h>
|
||||
#include <robot_geometry_msgs/PoseArray.h>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
/**
|
||||
* @class GoStraight
|
||||
* @brief Standard Bicycle-like ScoreAlgorithm
|
||||
*/
|
||||
class RotateToGoal : public score_algorithm::ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
|
||||
RotateToGoal() {};
|
||||
|
||||
virtual ~RotateToGoal() {};
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity) override;
|
||||
|
||||
|
||||
protected:
|
||||
robot::NodeHandle nh_;
|
||||
robot::NodeHandle nh_kinematics_;
|
||||
robot_geometry_msgs::Pose2D sub_goal_;
|
||||
|
||||
double steering_fix_wheel_distance_x_;
|
||||
double steering_fix_wheel_distance_y_;
|
||||
double angle_threshold_;
|
||||
double current_direction_;
|
||||
double velocity_rotate_min_, velocity_rotate_max_;
|
||||
robot_geometry_msgs::Pose2D goal_;
|
||||
robot::Time time_last_cmd_;
|
||||
|
||||
}; // class RotateToGoal
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
|
||||
#include <mkt_algorithm/diff/diff_predictive_trajectory.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
namespace diff
|
||||
{
|
||||
/**
|
||||
* @class GoStraight
|
||||
* @brief Standard Bicycle-like ScoreAlgorithm
|
||||
*/
|
||||
class GoStraight : public mkt_algorithm::diff::PredictiveTrajectory
|
||||
{
|
||||
public:
|
||||
GoStraight();
|
||||
|
||||
virtual ~GoStraight();
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(
|
||||
robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
* @param traj
|
||||
*/
|
||||
virtual mkt_msgs::Trajectory2D calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new GoStraight instance
|
||||
* @return A pointer to the new GoStraight instance
|
||||
*/
|
||||
static score_algorithm::ScoreAlgorithm::Ptr create();
|
||||
|
||||
}; // class GoStraight
|
||||
} // namespace diff
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif // _NAV_ALGORITHM_DIFF_ROTATE_TO_GOAL_H_INCLUDED__
|
||||
@@ -0,0 +1,433 @@
|
||||
#ifndef _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
#include <robot_geometry_msgs/PointStamped.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <robot_nav_core2/costmap.h>
|
||||
#include <nav_grid/coordinate_conversion.h>
|
||||
#include <angles/angles.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include <kalman/kalman.h>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
namespace diff
|
||||
{
|
||||
/**
|
||||
* @class PredictiveTrajectory
|
||||
* @brief Standard PredictiveTrajectory-like ScoreAlgorithm
|
||||
*/
|
||||
class PredictiveTrajectory : public score_algorithm::ScoreAlgorithm
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor
|
||||
*/
|
||||
PredictiveTrajectory();
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
virtual ~PredictiveTrajectory();
|
||||
|
||||
// Standard ScoreAlgorithm Interface
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(
|
||||
robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan,
|
||||
double &x_direction, double &y_direction, double &theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
* @param traj
|
||||
*/
|
||||
virtual mkt_msgs::Trajectory2D calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Stoping move navigation
|
||||
*/
|
||||
virtual void stop() override;
|
||||
|
||||
/**
|
||||
* @brief resume move navigation after stopped
|
||||
*/
|
||||
virtual void resume() override;
|
||||
|
||||
/**
|
||||
* @brief Create a new PredictiveTrajectory instance
|
||||
* @return A pointer to the new PredictiveTrajectory instance
|
||||
*/
|
||||
static score_algorithm::ScoreAlgorithm::Ptr create();
|
||||
|
||||
protected:
|
||||
inline double sign(double x)
|
||||
{
|
||||
return x < 0.0 ? -1.0 : 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters
|
||||
*/
|
||||
virtual void getParams();
|
||||
|
||||
/**
|
||||
* @brief Dynamically adjust look ahead distance based on the speed
|
||||
* @param velocity
|
||||
* @return look ahead distance
|
||||
*/
|
||||
double getLookAheadDistance(const robot_nav_2d_msgs::Twist2D &velocity);
|
||||
|
||||
/**
|
||||
* @brief Get lookahead point on the global plan
|
||||
* @param lookahead_dist
|
||||
* @param global_plan
|
||||
* @return lookahead point
|
||||
*/
|
||||
std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator
|
||||
getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan);
|
||||
|
||||
/**
|
||||
* @brief Prune global plan
|
||||
* @param tf
|
||||
* @param pose
|
||||
* @param global_plan
|
||||
* @param dist_behind_robot
|
||||
* @return true if plan is pruned, false otherwise
|
||||
*/
|
||||
bool pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot);
|
||||
|
||||
/**
|
||||
* @brief Transforms the global plan of the robot from the planner frame to the local frame (modified).
|
||||
*
|
||||
* The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h
|
||||
* such that the index of the current goal pose is returned as well as
|
||||
* the transformation between the global plan and the planning frame.
|
||||
* @param tf A reference to a tf buffer
|
||||
* @param global_plan The plan to be transformed
|
||||
* @param pose The pose of the robot
|
||||
* @param costmap A reference to the costmap being used so the window size for transforming can be computed
|
||||
* @param global_frame The frame to transform the plan to
|
||||
* @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!]
|
||||
* @param[out] transformed_plan Populated with the transformed plan
|
||||
* @return \c true if the global plan is transformed, \c false otherwise
|
||||
*/
|
||||
bool transformGlobalPlan(
|
||||
TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &robot_base_frame, double max_plan_length,
|
||||
robot_nav_2d_msgs::Path2D &transformed_plan);
|
||||
|
||||
/**
|
||||
* @brief Calculate max kappa
|
||||
* @param path
|
||||
* @param preview_distance
|
||||
* @return max kappa
|
||||
*/
|
||||
double calculateMaxKappa(const robot_nav_2d_msgs::Path2D &path, const double preview_distance = std::numeric_limits<double>::max());
|
||||
|
||||
/**
|
||||
* @brief Adjust speed with Hermite trajectory
|
||||
* @param velocity
|
||||
* @param trajectory
|
||||
* @param v_target
|
||||
* @param sign_x
|
||||
* @return speed
|
||||
*/
|
||||
double adjustSpeedWithHermiteTrajectory(
|
||||
const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Path2D &trajectory, double v_target, const double &sign_x
|
||||
);
|
||||
|
||||
/**
|
||||
* @brief Generate Hermite trajectory
|
||||
* @param path
|
||||
* @param drive_target
|
||||
* @param velocity
|
||||
* @param sign_x
|
||||
* @param drive_cmd
|
||||
* @return trajectory
|
||||
*/
|
||||
robot_nav_2d_msgs::Path2D generateTrajectory(
|
||||
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &drive_target,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity, const double &sign_x, robot_nav_2d_msgs::Twist2D &drive_cmd, const double &dt);
|
||||
|
||||
/**
|
||||
* @brief Generate trajectory
|
||||
* @param path
|
||||
* @param sign_x
|
||||
* @return trajectory
|
||||
*/
|
||||
robot_nav_2d_msgs::Path2D generateParallelPath(
|
||||
const robot_nav_2d_msgs::Path2D &path, const double &sign_x);
|
||||
|
||||
/**
|
||||
* @brief Generate Hermite trajectory
|
||||
* @param path
|
||||
* @param sign_x
|
||||
* @return trajectory
|
||||
*/
|
||||
robot_nav_2d_msgs::Path2D generateHermiteTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x);
|
||||
|
||||
/**
|
||||
* @brief Generate Hermite quadratic trajectory
|
||||
* @param pose
|
||||
* @param sign_x
|
||||
* @return trajectory
|
||||
*/
|
||||
robot_nav_2d_msgs::Path2D generateHermiteQuadraticTrajectory(const robot_nav_2d_msgs::Path2D &path, const double &sign_x);
|
||||
|
||||
/**
|
||||
* @brief Should rotate to path
|
||||
* @param carrot_pose
|
||||
* @param velocity
|
||||
* @param sign_x
|
||||
* @param angle_to_path
|
||||
* @return true if should rotate, false otherwise
|
||||
*/
|
||||
bool shouldRotateToPath(
|
||||
const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &carrot_pose, robot_nav_2d_msgs::Twist2D velocity, double &angle_to_path, const double &sign_x);
|
||||
|
||||
/**
|
||||
* @brief Rotate to heading
|
||||
* @param angle_to_path
|
||||
* @param velocity The velocity of the robot
|
||||
* @param cmd_vel The velocity commands to be filled
|
||||
*/
|
||||
void rotateToHeading(const double &angle_to_path, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt);
|
||||
|
||||
/**
|
||||
* @brief Check if robot should align to final heading (near goal position)
|
||||
* @param trajectory The transformed trajectory in robot frame
|
||||
* @param goal The goal pose with desired final heading
|
||||
* @param velocity Current velocity
|
||||
* @param xy_error Output: distance to goal
|
||||
* @param heading_error Output: angle difference to goal heading
|
||||
* @return true if should enter final heading alignment phase
|
||||
*/
|
||||
bool shouldAlignToFinalHeading(
|
||||
const robot_nav_2d_msgs::Path2D &trajectory,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &goal,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
double &xy_error,
|
||||
double &heading_error,
|
||||
const double &sign_x);
|
||||
|
||||
/**
|
||||
* @brief Arc Motion controller for final heading alignment
|
||||
* Smoothly reduces linear velocity while adjusting angular velocity to reach final heading
|
||||
* @param xy_error Distance to goal position
|
||||
* @param heading_error Angle difference to goal heading
|
||||
* @param velocity Current velocity
|
||||
* @param sign_x Direction of motion (forward/backward)
|
||||
* @param dt Time step
|
||||
* @param cmd_vel Output velocity command
|
||||
*/
|
||||
void alignToFinalHeading(
|
||||
const double &xy_error,
|
||||
const double &heading_error,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const double &sign_x,
|
||||
const double &dt,
|
||||
robot_nav_2d_msgs::Twist2D &cmd_vel);
|
||||
|
||||
/**
|
||||
* @brief PID controller
|
||||
* @param error
|
||||
* @param integral
|
||||
* @param last_error
|
||||
* @param dt
|
||||
* @param kp
|
||||
* @param ki
|
||||
* @param kd
|
||||
* @param output
|
||||
*/
|
||||
void pid(const double &error, double &integral, double &last_error, const double &dt, const double &kp, const double &ki, const double &kd, double &output);
|
||||
|
||||
/**
|
||||
* @brief the robot is moving acceleration limits
|
||||
* @param velocity The velocity of the robot
|
||||
* @param cmd_vel The velocity commands
|
||||
* @param cmd_vel_result The velocity commands result
|
||||
* @param dt The time step
|
||||
*/
|
||||
void moveWithAccLimits(
|
||||
const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &cmd_vel, robot_nav_2d_msgs::Twist2D &cmd_vel_result, const double &dt);
|
||||
|
||||
/**
|
||||
* @brief Stop the robot taking into account acceleration limits
|
||||
* @param pose The pose of the robot in the global frame
|
||||
* @param velocity The velocity of the robot
|
||||
* @param cmd_vel The velocity commands to be filled
|
||||
* @param dt The time step
|
||||
* @return True if a valid trajectory was found, false otherwise
|
||||
*/
|
||||
bool stopWithAccLimits(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity, robot_nav_2d_msgs::Twist2D &cmd_vel, const double &dt);
|
||||
|
||||
/**
|
||||
* @brief Compute pure pursuit
|
||||
* @param carrot_pose
|
||||
* @param drive_target
|
||||
* @param velocity
|
||||
* @param trajectory
|
||||
* @param min_approach_linear_velocity
|
||||
* @param sign_x
|
||||
* @param dt
|
||||
* @param drive_cmd
|
||||
*/
|
||||
void computePurePursuit(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &carrot_pose,
|
||||
const robot_nav_2d_msgs::Twist2D &drive_target,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const robot_nav_2d_msgs::Path2D &trajectory,
|
||||
const double &min_approach_linear_velocity,
|
||||
const double &sign_x,
|
||||
const double &dt,
|
||||
robot_nav_2d_msgs::Twist2D &drive_cmd);
|
||||
|
||||
/**
|
||||
* @brief Apply distance-based speed scaling and acceleration limits
|
||||
* @param plan The plan to be scaled
|
||||
* @param velocity Current velocity
|
||||
* @param drive_cmd Input/output velocity command
|
||||
* @param sign_x Direction of motion
|
||||
* @param dt Time step
|
||||
*/
|
||||
void applyDistanceSpeedScaling(
|
||||
const robot_nav_2d_msgs::Path2D &plan,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
robot_nav_2d_msgs::Twist2D &drive_cmd,
|
||||
const double &sign_x,
|
||||
const double &dt);
|
||||
|
||||
/**
|
||||
* @brief Interpolate footprint
|
||||
* @param pose
|
||||
* @param footprint
|
||||
* @param resolution
|
||||
* @return interpolated footprint
|
||||
*/
|
||||
std::vector<robot_geometry_msgs::Point> interpolateFootprint(
|
||||
const robot_geometry_msgs::Pose2D &pose, const std::vector<robot_geometry_msgs::Point> &footprint, const double &resolution);
|
||||
|
||||
/**
|
||||
* @brief Cost at pose
|
||||
* @param x
|
||||
* @param y
|
||||
* @return cost
|
||||
*/
|
||||
double costAtPose(const double &x, const double &y);
|
||||
|
||||
|
||||
bool initialized_;
|
||||
bool nav_stop_;
|
||||
robot::NodeHandle nh_, nh_priv_;
|
||||
std::string frame_id_path_;
|
||||
std::string robot_base_frame_;
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped goal_;
|
||||
robot_nav_2d_msgs::Path2D global_plan_;
|
||||
robot_nav_2d_msgs::Path2D compute_plan_;
|
||||
robot_nav_2d_msgs::Path2D transform_plan_;
|
||||
robot_nav_2d_msgs::Twist2D prevous_drive_cmd_;
|
||||
|
||||
double x_direction_, y_direction_, theta_direction_;
|
||||
|
||||
// Lookahead
|
||||
bool use_velocity_scaled_lookahead_dist_;
|
||||
double lookahead_time_;
|
||||
double lookahead_dist_;
|
||||
double min_lookahead_dist_;
|
||||
double max_lookahead_dist_;
|
||||
double max_lateral_accel_;
|
||||
|
||||
// journey
|
||||
double min_journey_squared_{1e9};
|
||||
double max_journey_squared_{1e9};
|
||||
|
||||
// Rotate to heading
|
||||
bool use_rotate_to_heading_;
|
||||
double rotate_to_heading_min_angle_;
|
||||
double min_path_distance_, max_path_distance_;
|
||||
|
||||
// Final heading alignment (Arc Motion)
|
||||
bool use_final_heading_alignment_;
|
||||
double final_heading_xy_tolerance_; // Distance threshold to trigger alignment
|
||||
double final_heading_angle_tolerance_; // Angle threshold to consider heading reached
|
||||
double final_heading_min_velocity_; // Minimum linear velocity during alignment
|
||||
double final_heading_kp_angular_; // Proportional gain for angular control
|
||||
double final_heading_ki_angular_;
|
||||
double final_heading_kd_angular_;
|
||||
|
||||
double near_goal_heading_integral_;
|
||||
double near_goal_heading_last_error_;
|
||||
bool near_goal_heading_was_active_;
|
||||
|
||||
double min_approach_linear_velocity_;
|
||||
|
||||
bool use_cost_regulated_linear_velocity_scaling_;
|
||||
double inflation_cost_scaling_factor_;
|
||||
double cost_scaling_dist_, cost_scaling_gain_;
|
||||
|
||||
// Control frequency
|
||||
double control_duration_;
|
||||
std::vector<robot_geometry_msgs::Point> footprint_spec_;
|
||||
|
||||
robot::Time last_actuator_update_;
|
||||
boost::shared_ptr<KalmanFilter> kf_;
|
||||
int m_, n_;
|
||||
Eigen::MatrixXd A;
|
||||
Eigen::MatrixXd C;
|
||||
Eigen::MatrixXd Q;
|
||||
Eigen::MatrixXd R;
|
||||
Eigen::MatrixXd P;
|
||||
|
||||
// Kalman filter tuning (for v and w filtering)
|
||||
double kf_q_v_;
|
||||
double kf_q_w_;
|
||||
double kf_r_v_;
|
||||
double kf_r_w_;
|
||||
double kf_p0_;
|
||||
bool kf_filter_angular_;
|
||||
#ifdef BUILD_WITH_ROS
|
||||
ros::Publisher lookahead_point_pub_;
|
||||
#endif
|
||||
|
||||
}; // class PredictiveTrajectory
|
||||
|
||||
} // namespace diff
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif //_NAV_ALGORITHM_DIFF_PREDICTIVE_TRAJECTORY_H_INCLUDED__
|
||||
@@ -0,0 +1,68 @@
|
||||
#ifndef _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__
|
||||
#define _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__
|
||||
|
||||
#include <mkt_algorithm/diff/diff_predictive_trajectory.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
namespace diff
|
||||
{
|
||||
/**
|
||||
* @class GoStraight
|
||||
* @brief Standard Bicycle-like ScoreAlgorithm
|
||||
*/
|
||||
class RotateToGoal : public mkt_algorithm::diff::PredictiveTrajectory
|
||||
{
|
||||
public:
|
||||
RotateToGoal();
|
||||
|
||||
virtual ~RotateToGoal();
|
||||
|
||||
/**
|
||||
* @brief Initialize parameters as needed
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void initialize(
|
||||
robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj) override;
|
||||
|
||||
/**
|
||||
* @brief Prior to evaluating any trajectories, look at contextual information constant across all trajectories
|
||||
*
|
||||
* Subclasses may overwrite. Return false in case there is any error.
|
||||
*
|
||||
* @param pose Current pose (costmap frame)
|
||||
* @param velocity Current velocity
|
||||
* @param goal The final goal (costmap frame)
|
||||
* @param global_plan Transformed global plan in costmap frame, possibly cropped to nearby points
|
||||
*/
|
||||
virtual bool prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan,
|
||||
double &x_direction, double &y_direction, double &theta_direction) override;
|
||||
|
||||
/**
|
||||
* @brief Reset all data
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Calculating algorithm
|
||||
* @param pose
|
||||
* @param velocity
|
||||
* @param traj
|
||||
*/
|
||||
virtual mkt_msgs::Trajectory2D calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new RotateToGoal instance
|
||||
* @return A pointer to the new RotateToGoal instance
|
||||
*/
|
||||
static score_algorithm::ScoreAlgorithm::Ptr create();
|
||||
|
||||
}; // class RotateToGoalDiff
|
||||
|
||||
} // namespace diff
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
#endif // _NAV_ALGORITHM_ROTATE_TO_GOAL_DIFF_H_INCLUDED__
|
||||
44
src/Algorithms/Libraries/mkt_algorithm/package.xml
Normal file
44
src/Algorithms/Libraries/mkt_algorithm/package.xml
Normal file
@@ -0,0 +1,44 @@
|
||||
<package>
|
||||
<name>mkt_algorithm</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
mkt_algorithm is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. mkt_algorithm
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/mkt_algorithm</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
<build_depend>geometry_msgs</build_depend>
|
||||
<build_depend>score_algorithm</build_depend>
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<build_depend>kalman</build_depend>
|
||||
<build_depend>angles</build_depend>
|
||||
<build_depend>nav_grid</build_depend>
|
||||
<build_depend>robot_costmap_2d</build_depend>
|
||||
<build_depend>robot_sensor_msgs</build_depend>
|
||||
<build_depend>robot_std_msgs</build_depend>
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
|
||||
<run_depend>geometry_msgs</run_depend>
|
||||
<run_depend>score_algorithm</run_depend>
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
<run_depend>kalman</run_depend>
|
||||
<run_depend>angles</run_depend>
|
||||
<run_depend>nav_grid</run_depend>
|
||||
<run_depend>robot_costmap_2d</run_depend>
|
||||
<run_depend>robot_sensor_msgs</run_depend>
|
||||
<run_depend>robot_std_msgs</run_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
</package>
|
||||
@@ -0,0 +1,68 @@
|
||||
#include <mkt_algorithm/go_straight.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <pluginlib/class_list_macros.h>
|
||||
#include <angles/angles.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
void GoStraight::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap)
|
||||
{
|
||||
nh_ = robot::NodeHandle(nh, name);
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
|
||||
steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1);
|
||||
steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.);
|
||||
}
|
||||
|
||||
void GoStraight::reset()
|
||||
{
|
||||
time_last_cmd_ = robot::Time::now();
|
||||
}
|
||||
|
||||
bool GoStraight::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction)
|
||||
{
|
||||
goal_ = goal;
|
||||
|
||||
const double rb_direction_x = goal_.x - pose.x;
|
||||
const double rb_direction_y = goal_.y - pose.y;
|
||||
const double rb_angle = atan2(rb_direction_y, rb_direction_x);
|
||||
double rb_dir = cos(rb_angle- pose.theta);
|
||||
x_direction = y_direction = theta_direction = rb_dir;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped GoStraight::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2DStamped result;
|
||||
result.header.stamp = robot::Time::now();
|
||||
|
||||
robot_geometry_msgs::Pose2D steer_to_baselink_pose;
|
||||
|
||||
if(!getPose("steer_link", "base_link", steer_to_baselink_pose))
|
||||
return result;
|
||||
double odom_alpha = steer_to_baselink_pose.theta;
|
||||
if(fabs(odom_alpha) > 0.03) return result;
|
||||
|
||||
double delta_x = goal_.x - pose.x;
|
||||
double delta_y = goal_.y - pose.y;
|
||||
|
||||
double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
|
||||
double d_reduce = std::min(std::max(fabs(velocity.x), 0.6), 0.9);
|
||||
double v_min = 0.03 * velocity.x / (fabs(velocity.x) + 1e-9);
|
||||
|
||||
// Van toc robot
|
||||
double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min;
|
||||
result.velocity.x = fabs(cos(fabs(0.0 - odom_alpha))) * vr / cos(std::min(M_PI/3, fabs(odom_alpha)));
|
||||
// ROS_INFO("d_rg %f d_reduce %f V = %f %f", d_rg, d_reduce,velocity.x, vr);
|
||||
return result;
|
||||
}
|
||||
|
||||
}; // namespace mkt_algorithm
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(mkt_algorithm::GoStraight, score_algorithm::ScoreAlgorithm)
|
||||
@@ -0,0 +1,641 @@
|
||||
#include <mkt_algorithm/bicycle.h>
|
||||
#include <pluginlib/class_list_macros.h>
|
||||
#include <nav_grid/coordinate_conversion.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <angles/angles.h>
|
||||
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
void Bicycle::initialize(const robot::NodeHandle& nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap)
|
||||
{
|
||||
nh_priv_ = robot::NodeHandle(nh, name);
|
||||
nh_ = robot::NodeHandle("~");
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
last_actuator_update_ = robot::Time(0);
|
||||
|
||||
nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5);
|
||||
nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5);
|
||||
nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8);
|
||||
nh_priv_.param("index_samples", index_samples_, 0);
|
||||
nh_priv_.param("filter", is_filter_, false);
|
||||
|
||||
steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_x", 1.1);
|
||||
steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "steering_fix_wheel_distance_y", 0.);
|
||||
xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "xy_goal_tolerance", 0.1);
|
||||
acc_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "acc_lim_theta", 0.1);
|
||||
decel_lim_theta_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "decel_lim_theta", 0.1);
|
||||
controller_frequency_param_name_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "controller_frequency", 10);
|
||||
if(controller_frequency_param_name_ <= 0.0)
|
||||
{
|
||||
ROS_WARN("controller_frequency is not setting lower 0.0 so will set to 1.0");
|
||||
controller_frequency_param_name_ = 1.0;
|
||||
}
|
||||
|
||||
reached_intermediate_goals_pub_ = nh_.advertise<robot_geometry_msgs::PoseArray>("reached_intermediate_goals", 1);
|
||||
current_goal_pub_ = nh_.advertise<robot_geometry_msgs::PoseStamped>("current_goal", 1);
|
||||
closet_robot_goal_pub_ = nh_.advertise<robot_geometry_msgs::PoseStamped>("closet_robot_goal", 1);
|
||||
cmd_raw_pub_ = nh_.advertise<robot_geometry_msgs::Twist>("cmd_raw", 1);
|
||||
x_direction_ = y_direction_= theta_direction_ = 0;
|
||||
|
||||
// kalman
|
||||
int n = 3; // Number of states
|
||||
int m = 1; // Number of measurements
|
||||
double dt = 1.0/controller_frequency_param_name_; // Time step
|
||||
// ROS_INFO("controller_frequency_param_name %f", controller_frequency_param_name);
|
||||
Eigen::MatrixXd A(n, n); // System dynamics matrix
|
||||
Eigen::MatrixXd C(m, n); // Output matrix
|
||||
Eigen::MatrixXd Q(n, n); // Process noise covariance
|
||||
Eigen::MatrixXd R(m, m); // Measurement noise covariance
|
||||
Eigen::MatrixXd P(n, n); // Estimate error covariance
|
||||
|
||||
// Discrete LTI projectile motion, measuring position only
|
||||
A << 1, dt, 0, 0, 1, dt, 0, 0, 1;
|
||||
C << 1, 0, 0;
|
||||
|
||||
// Reasonable covariance matrices
|
||||
double q = 0.1;
|
||||
double r = 0.6;
|
||||
double p = 0.2;
|
||||
Q << q, q, 0.0, q, q, 0.0, 0.0, 0.0, 0.0;
|
||||
R << r;
|
||||
P << p, p, p, p, 10.0, 1, p, 1, 10.0;
|
||||
|
||||
// Construct the filter
|
||||
kf_ = boost::make_shared<KalmanFilter>(dt,A, C, Q, R, P);
|
||||
// Best guess of initial states
|
||||
Eigen::VectorXd x0(n);
|
||||
x0 << 0.0, 0.0, 0.0;
|
||||
kf_->init(robot::Time::now().toSec(), x0);
|
||||
}
|
||||
|
||||
void Bicycle::reset()
|
||||
{
|
||||
reached_intermediate_goals_.clear();
|
||||
start_index_saved_vt_.clear();
|
||||
start_index_saved_ = 0;
|
||||
sub_goal_index_saved_ = 0;
|
||||
sub_start_index_saved_ = 0;
|
||||
x_direction_ = y_direction_= theta_direction_ = 0;
|
||||
follow_step_path_ = false;
|
||||
last_actuator_update_ = robot::Time(0);
|
||||
}
|
||||
|
||||
bool Bicycle::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction)
|
||||
{
|
||||
nh_priv_.param("xy_local_goal_tolerance", xy_local_goal_tolerance_, 0.5);
|
||||
nh_priv_.param("xy_local_goal_tolerance_offset", xy_local_goal_tolerance_offset_, 0.5);
|
||||
nh_priv_.param("angle_threshold", angle_threshold_, M_PI/8);
|
||||
nh_priv_.param("index_samples", index_samples_, 0);
|
||||
nh_priv_.param("distance_rg", distance_rg_, 0.1);
|
||||
nh_priv_.param("k_ld", k_ld_, 1.0);
|
||||
nh_priv_.param("k_d_reduce", k_d_reduce_, 1.0);
|
||||
nh_priv_.param("ld_min", ld_min_, 0.2);
|
||||
nh_priv_.param("ld_max", ld_max_, 1.1);
|
||||
nh_priv_.param("follow_step_path", follow_step_path_, false);
|
||||
|
||||
// ROS_INFO("%f %f %f %d", xy_local_goal_tolerance_, xy_local_goal_tolerance_offset_, angle_threshold_, index_samples_);
|
||||
frame_id_path_ = global_plan.header.frame_id;
|
||||
goal_ = goal;
|
||||
global_plan_ = global_plan;
|
||||
double rb_direction;
|
||||
if(!getGoalPose(pose, velocity,global_plan, sub_goal_, rb_direction))
|
||||
{
|
||||
ROS_ERROR("getGoalPose Failed");
|
||||
return false;
|
||||
}
|
||||
x_direction_= fabs(rb_direction)/rb_direction;
|
||||
x_direction = x_direction_;
|
||||
y_direction = y_direction_ = 0;
|
||||
theta_direction = theta_direction_;
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped Bicycle::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2DStamped result;
|
||||
result.header.stamp = robot::Time::now();
|
||||
|
||||
robot_geometry_msgs::Pose2D steer_to_baselink_pose;
|
||||
|
||||
if(!getPose("steer_link", "base_link", steer_to_baselink_pose))
|
||||
return result;
|
||||
double actual_phi_steer = steer_to_baselink_pose.theta;
|
||||
|
||||
const double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2));
|
||||
const double delta_x = sub_goal_.x - pose.x;
|
||||
const double delta_y = sub_goal_.y - pose.y;
|
||||
const double d_rg = sqrt(pow(delta_x, 2) + pow(delta_y, 2));
|
||||
|
||||
// Van toc robot
|
||||
double d_reduce = std::min(std::max(fabs(velocity.x) * k_d_reduce_, 0.6), 3.0);
|
||||
double v_min = 0.05 * velocity.x / (fabs(velocity.x) + 1e-9);
|
||||
double vr = d_rg > d_reduce? velocity.x : (velocity.x - v_min)*sin((d_rg / d_reduce) * (M_PI/2)) + v_min;
|
||||
|
||||
// Góc lái của bánh lái là: α(t)
|
||||
double alpha = atan2(delta_y,delta_x) - pose.theta;
|
||||
double ld = std::min(std::max(fabs(velocity.x)*k_ld_, ld_min_), ld_max_);
|
||||
// double ld = std::min(std::max(d_rg*k_ld_, ld_min_), ld_max_);
|
||||
|
||||
double phi_steer = atan2(2 * L * sin(alpha), ld);
|
||||
if(d_rg <= distance_rg_ && global_plan_.poses.size() > 1)
|
||||
{
|
||||
const double d_x = goal_.x - sub_goal_.x;
|
||||
const double d_y = goal_.y - sub_goal_.y;
|
||||
const double dd = sqrt(d_x * d_x + d_y * d_y);
|
||||
const double d_theta = goal_.theta - sub_goal_.theta;
|
||||
if(dd < 1e-5)
|
||||
{
|
||||
robot_geometry_msgs::Pose2D p = global_plan_.poses[global_plan_.poses.size() - 2];
|
||||
alpha = velocity.x / (fabs(velocity.x) + 1e-9)*(p.theta - pose.theta);
|
||||
phi_steer = atan2(2 * L * sin(alpha), 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
double alpha_reduce = std::min(std::max(fabs(vr), 0.6), 1.0);
|
||||
double cos_actual_phi_steer = cos( std::min(M_PI/2.3, fabs(actual_phi_steer)));
|
||||
|
||||
// limit W
|
||||
double result_W_max = 0.25;
|
||||
// double result_W_min = 0.13;
|
||||
double result_W = vr * fabs(cos(alpha)) * tan(actual_phi_steer) / L;
|
||||
double V_s = std::max(alpha_reduce, fabs(cos(alpha))) * vr / cos_actual_phi_steer;
|
||||
std::stringstream ss;
|
||||
if(fabs(result_W) > 0.02)
|
||||
{
|
||||
double d_w = fabs(result_W) - fabs(velocity.theta);
|
||||
double a = fabs(velocity.theta) > fabs(result_W) ? fabs(acc_lim_theta_/controller_frequency_param_name_) : fabs(decel_lim_theta_/controller_frequency_param_name_);
|
||||
// ss << d_w << " " << a << " ";
|
||||
double result;
|
||||
if(fabs(d_w) >= a)
|
||||
result = fabs(velocity.theta) + d_w / fabs(d_w + 1e-9) * a;
|
||||
else if (fabs(d_w) < fabs(a))
|
||||
result = fabs(velocity.theta);
|
||||
// ss << result_W << " " << velocity.theta << " ";
|
||||
result_W = result_W / (fabs(result_W) + 1e-9) * result;
|
||||
// ss << result_W << " ";
|
||||
// ROS_INFO_STREAM(ss.str());
|
||||
|
||||
double d_v = fabs(result_W * L / tan(actual_phi_steer)) - fabs(vr);
|
||||
if(fabs(d_v) >= a)
|
||||
result = velocity.x / (fabs(velocity.x) + 1e-9)* (fabs(vr) + d_v / fabs(d_v + 1e-9) * a);
|
||||
else if (fabs(d_v) < fabs(a))
|
||||
result = velocity.x / (fabs(velocity.x) + 1e-9) * fabs(vr);
|
||||
|
||||
V_s = std::max(alpha_reduce, fabs(cos(alpha)))*result/ cos_actual_phi_steer;
|
||||
}
|
||||
|
||||
if(fabs(result_W) > result_W_max)
|
||||
V_s = ( result_W / (fabs(result_W) + 1e-9) * result_W_max * L / tan(actual_phi_steer)) / cos_actual_phi_steer;
|
||||
|
||||
if(is_filter_)
|
||||
{
|
||||
robot_geometry_msgs::Twist msg;
|
||||
msg.linear.x = result.velocity.x;
|
||||
msg.angular.z = phi_steer;
|
||||
cmd_raw_pub_.publish(msg);
|
||||
|
||||
Eigen::VectorXd y(1);
|
||||
y << phi_steer;
|
||||
robot::Time current_time = robot::Time::now();
|
||||
double dt = robot::Duration(current_time - last_actuator_update_).toSec();
|
||||
last_actuator_update_ = current_time;
|
||||
Eigen::MatrixXd A(3, 3); // System dynamics matrix
|
||||
A << 1, dt, 0, 0, 1, dt, 0, 0, 1;
|
||||
kf_->update(y, dt, A);
|
||||
phi_steer = kf_->state().transpose()[0];
|
||||
}
|
||||
theta_direction_ = phi_steer !=0 ? phi_steer/(fabs(phi_steer) + 1e-9) * velocity.x/((fabs(velocity.x) + 1e-9)) : 0;
|
||||
|
||||
result.velocity.theta = phi_steer;
|
||||
result.velocity.x = fabs(cos(phi_steer - actual_phi_steer)) * V_s;
|
||||
return result;
|
||||
}
|
||||
|
||||
unsigned int Bicycle::getGoalIndex(const robot_geometry_msgs::Pose2D &robot_pose, const std::vector<robot_geometry_msgs::Pose2D> &plan,
|
||||
const double distance, unsigned int start_index, unsigned int last_valid_index) const
|
||||
{
|
||||
if (start_index >= last_valid_index)
|
||||
return last_valid_index;
|
||||
|
||||
unsigned int goal_index = start_index;
|
||||
const double start_direction_x = plan[start_index + 1].x - plan[start_index].x;
|
||||
const double start_direction_y = plan[start_index + 1].y - plan[start_index].y;
|
||||
if (fabs(start_direction_x) > 1e-9 || fabs(start_direction_y) > 1e-9) { // make sure that atan2 is defined
|
||||
double start_angle = atan2(start_direction_y, start_direction_x);
|
||||
double S = sqrt(pow(start_direction_x, 2) + pow(start_direction_y, 2));
|
||||
// double angle_threshold = 0.0;
|
||||
for (unsigned int i = start_index + 1; i <= last_valid_index; ++i)
|
||||
{
|
||||
const double current_direction_x = plan[i].x - plan[i - 1].x;
|
||||
const double current_direction_y = plan[i].y - plan[i - 1].y;
|
||||
const double dd = sqrt(pow(current_direction_x, 2) + pow(current_direction_y, 2));
|
||||
S += dd;
|
||||
if (fabs(current_direction_x) > 1e-9 || fabs(current_direction_y) > 1e-9)
|
||||
{
|
||||
double current_angle = atan2(current_direction_y, current_direction_x);
|
||||
if(fabs(remainder(start_angle - current_angle, 2 * M_PI)) >= angle_threshold_ || S >= distance)
|
||||
{
|
||||
break;
|
||||
}
|
||||
goal_index = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return goal_index;
|
||||
}
|
||||
|
||||
bool Bicycle::getGoalPose(const robot_geometry_msgs::Pose2D &robot_pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_nav_2d_msgs::Path2D &global_plan, robot_geometry_msgs::Pose2D &sub_goal,
|
||||
double &target_direction)
|
||||
{
|
||||
const robot_nav_core2::Costmap &costmap = *costmap_;
|
||||
const nav_grid::NavGridInfo &info = costmap.getInfo();
|
||||
|
||||
if (global_plan.poses.empty())
|
||||
{
|
||||
ROS_ERROR_NAMED("PathProgressCritic", "The global plan was empty.");
|
||||
return false;
|
||||
}
|
||||
// Chuyển đổi dữ liệu kế hoạch đường đi 'robot_nav_2d_msgs::Path2D' sang 'std::vector<robot_geometry_msgs::Pose2D>'
|
||||
std::vector<robot_geometry_msgs::Pose2D> plan = global_plan.poses;
|
||||
|
||||
std::vector<unsigned int> index_s;
|
||||
if(!findSubGoalIndex(plan, index_s))
|
||||
{
|
||||
ROS_ERROR_NAMED("PathProgressCritic", "Can not find SubGoal Index");
|
||||
return false;
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// std::stringstream ss;
|
||||
// for(auto i : index_s) ss << i << " ";
|
||||
// ROS_INFO_STREAM(ss.str());
|
||||
// }
|
||||
|
||||
unsigned int sub_goal_index = sub_goal_index_saved_;
|
||||
unsigned int sub_start_index = sub_start_index_saved_;
|
||||
if(index_s.empty() || index_s.size() < 1)
|
||||
{
|
||||
sub_goal_index = (unsigned int)plan.size();
|
||||
sub_goal_index_saved_ = sub_goal_index;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(index_s.front() > sub_goal_index_saved_)
|
||||
{
|
||||
sub_goal_index = (unsigned int)(index_s.front()) + 1;
|
||||
sub_goal_index_saved_ = sub_goal_index;
|
||||
}
|
||||
if(index_s.size() > 1)
|
||||
{
|
||||
for(int i = 1; i < index_s.size(); ++i)
|
||||
{
|
||||
// double tolerance = line_generator->calculateTolerance(robot_pose, plan[index_s[i-1]]);
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(robot_pose, plan[index_s[i-1]]));
|
||||
// double dx = plan[index_s[i-1]].x - robot_pose.x;
|
||||
// double dy = plan[index_s[i-1]].y - robot_pose.y;
|
||||
// if(std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_goal_tolerance_ + 0.15)
|
||||
if (distance < xy_local_goal_tolerance_offset_)
|
||||
{
|
||||
if(index_s[i] > sub_goal_index_saved_)
|
||||
{
|
||||
if(i < index_s.size()-1)
|
||||
{
|
||||
sub_goal_index = index_s[i] + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
sub_goal_index = (unsigned int)plan.size();
|
||||
}
|
||||
if(follow_step_path_)
|
||||
{
|
||||
sub_start_index = index_s[i-1];
|
||||
sub_start_index_saved_ = sub_start_index;
|
||||
}
|
||||
ROS_INFO("Tang nac path tu %d den %d boi khoang cach", sub_goal_index_saved_, sub_goal_index);
|
||||
// ROS_WARN("i %d follow_step_path_ = %x start = %d sub_goal = %d size = %d", i, follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size());
|
||||
sub_goal_index_saved_ = sub_goal_index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(plan[sub_goal_index], robot_pose));
|
||||
if(distance <= xy_local_goal_tolerance_ )
|
||||
{
|
||||
sub_goal_index = (unsigned int)plan.size();
|
||||
sub_goal_index_saved_ = sub_goal_index;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// find the "start pose", i.e. the pose on the plan closest to the robot that is also on the local map
|
||||
// Tìm điểm pose bắt đầu trên kế hoạch đường đi gần nhất với robot đồng thời có tồn tại trong local map
|
||||
unsigned int start_index = 0; // số vị trí pose trong kế hoạch đường đi
|
||||
double distance_to_start = std::numeric_limits<double>::infinity(); // Xét giá trị là vô cùng oo
|
||||
bool started_path = false;
|
||||
// for (unsigned int i = 0; i < plan.size(); i++)
|
||||
// ROS_INFO_THROTTLE(1.0, "follow_step_path_ = %x start = %d sub_goal = %d size = %d", follow_step_path_, sub_start_index, sub_goal_index, (unsigned int)plan.size());
|
||||
for (unsigned int i = sub_start_index; i < sub_goal_index; i++)
|
||||
{
|
||||
|
||||
// double g_x = plan[i].x;
|
||||
// double g_y = plan[i].y;
|
||||
// unsigned int map_x, map_y;
|
||||
// if (worldToGridBounded(info, g_x, g_y, map_x, map_y) // chuyển tọa độ từ đơn vị mét sang pixel
|
||||
// && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION)
|
||||
// {
|
||||
// Still on the costmap. Continue.
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(plan[i], robot_pose)); // Tính khoảng cách từ vị trí của robot đến pose đang xét
|
||||
if (distance_to_start > distance)
|
||||
{
|
||||
start_index = i;
|
||||
distance_to_start = distance;
|
||||
started_path = true;
|
||||
}
|
||||
// else
|
||||
// {
|
||||
// break;
|
||||
// }
|
||||
// else if (started_path)
|
||||
// {
|
||||
// // Plan is going away from the robot again. It's possible that it comes back and we would find a pose that's
|
||||
// // even closer to the robot, but then we would skip over parts of the plan.
|
||||
// break;
|
||||
// }
|
||||
// else, we have not yet found a point on the costmap, so we just continue
|
||||
}
|
||||
// Nếu khồng tìm được điểm gần với robot nhất thì trả về false
|
||||
if (!started_path)
|
||||
{
|
||||
ROS_ERROR_NAMED("PathProgressCritic", "None of the points of the global plan were in the local costmap.");
|
||||
return false;
|
||||
}
|
||||
|
||||
// find the "last valid pose", i.e. the last pose on the plan after the start pose that is still on the local map
|
||||
// Tìm điểm pose cuôi cùng sau điểm pose bắt đầu và có tồn tại trong local map
|
||||
if(start_index < 1) start_index == 1;
|
||||
// unsigned int last_valid_index = plan.size() - 1;
|
||||
unsigned int last_valid_index = sub_goal_index - 1;
|
||||
// for (unsigned int i = start_index + 1; i < sub_goal_index; i++)
|
||||
// {
|
||||
// double g_x = plan[i].x;
|
||||
// double g_y = plan[i].y;
|
||||
// unsigned int map_x, map_y;
|
||||
// if (worldToGridBounded(info, g_x, g_y, map_x, map_y) && costmap(map_x, map_y) != robot_nav_core2::Costmap::NO_INFORMATION)
|
||||
// {
|
||||
// // Still on the costmap. Continue.
|
||||
// last_valid_index = i;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// // Off the costmap after being on the costmap.
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
// find the "goal pose" by walking along the plan as long as each step leads far enough away from the starting point,
|
||||
// i.e. is within angle_threshold_ of the starting direction.
|
||||
// Tìm điểm mục tiêu chạy từ điểm start pose đến last valid pose dọc thep plan
|
||||
|
||||
unsigned int goal_index = start_index;
|
||||
robot::Rate r(30);
|
||||
while (goal_index < last_valid_index && robot::ok())
|
||||
{
|
||||
// Tìm kiếm vị trí điểm mục tiêu phù hợp
|
||||
double S;
|
||||
if(velocity.x > 0) S = std::min(4.0, std::max(0.9, fabs(velocity.x)*k_d_reduce_));
|
||||
// else if(velocity.x < 0) S = 0.5;
|
||||
else if(velocity.x < 0) S = std::min(0.7, std::max(0.5, fabs(velocity.x)*k_d_reduce_));
|
||||
else S = 0.5;
|
||||
goal_index = getGoalIndex(robot_pose, plan, S, start_index, last_valid_index);
|
||||
|
||||
// check if goal already reached
|
||||
bool goal_already_reached = false;
|
||||
|
||||
robot_geometry_msgs::PoseArray poseArrayMsg;
|
||||
poseArrayMsg.header.stamp = robot::Time::now();
|
||||
poseArrayMsg.header.frame_id = frame_id_path_;
|
||||
// std::stringstream ss;
|
||||
for (auto &reached_intermediate_goal : reached_intermediate_goals_)
|
||||
{
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index]));
|
||||
// ss << distance << " ";
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(reached_intermediate_goal);
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
reached_intermediate_goals_pub_.publish(poseArrayMsg);
|
||||
// if(!reached_intermediate_goals_.empty())
|
||||
// {
|
||||
// ROS_INFO_STREAM(ss.str());
|
||||
// }
|
||||
|
||||
for (auto &reached_intermediate_goal : reached_intermediate_goals_)
|
||||
{
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[goal_index]));
|
||||
if (distance < xy_local_goal_tolerance_)
|
||||
{
|
||||
goal_already_reached = true;
|
||||
// choose a new start_index by walking along the plan until we're outside xy_local_goal_tolerance_ and try again
|
||||
// (start_index is now > goal_index)
|
||||
for (start_index = goal_index; start_index <= last_valid_index; ++start_index)
|
||||
{
|
||||
distance = robot_nav_2d_utils::poseDistance(reached_intermediate_goal, plan[start_index]);
|
||||
if ( distance >= xy_local_goal_tolerance_offset_)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
// start_index_saved_ = start_index;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//try hiep
|
||||
unsigned num = 0;
|
||||
start_index_saved_vt_.insert(start_index_saved_vt_.begin(),start_index);
|
||||
if(start_index_saved_vt_.size() > index_samples_) start_index_saved_vt_.pop_back();
|
||||
std::stringstream ss;
|
||||
for(int i = 0; i < start_index_saved_vt_.size() - 1; i++)
|
||||
{
|
||||
double edge = 0;
|
||||
if(start_index_saved_vt_[i] != start_index_saved_vt_[i+1])
|
||||
edge = journey(plan, start_index_saved_vt_[i], start_index_saved_vt_[i+1]);
|
||||
if(edge < xy_local_goal_tolerance_) num++;
|
||||
ss << start_index_saved_vt_[i] << " ";
|
||||
}
|
||||
// ss << start_index << " ";
|
||||
|
||||
if(num < index_samples_ - 1 && !start_index_saved_vt_.empty())
|
||||
{
|
||||
auto max_iter = *(std::max_element(start_index_saved_vt_.begin(), start_index_saved_vt_.end()));
|
||||
start_index_saved_ = start_index_saved_ >= max_iter? start_index_saved_ : max_iter;
|
||||
double S1 = journey(plan, start_index, plan.size()-1 );
|
||||
double S2 = journey(plan, start_index_saved_, plan.size()-1 );
|
||||
|
||||
// ROS_INFO_STREAM(ss.str());
|
||||
if(S2 - S1 < -fabs(xy_local_goal_tolerance_))
|
||||
{
|
||||
start_index = start_index_saved_;
|
||||
}
|
||||
else start_index_saved_ = start_index;
|
||||
// ROS_INFO(" %d %d %f %d %f %f", max_iter, start_index, S1, start_index_saved_, S2, S2 - S1);
|
||||
}
|
||||
else start_index_saved_ = start_index;
|
||||
|
||||
if(start_index >= goal_index) goal_index = getGoalIndex(robot_pose, plan, S,start_index, last_valid_index);
|
||||
|
||||
if (!goal_already_reached)
|
||||
{
|
||||
// new goal not in reached_intermediate_goals_
|
||||
double distance = fabs(robot_nav_2d_utils::poseDistance(plan[goal_index], plan[start_index]));
|
||||
if (distance < xy_local_goal_tolerance_)
|
||||
{
|
||||
// ROS_INFO("goal_index %d distance %f", goal_index, distance);
|
||||
// the robot has currently reached the goal
|
||||
reached_intermediate_goals_.push_back(plan[goal_index]);
|
||||
ROS_DEBUG_NAMED("PathProgressCritic", "Number of reached_intermediate goals: %zu", reached_intermediate_goals_.size());
|
||||
}
|
||||
else
|
||||
{
|
||||
// we've found a new goal!
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
r.sleep();
|
||||
robot::spinOnce();
|
||||
}
|
||||
|
||||
if (start_index > goal_index)
|
||||
start_index = goal_index;
|
||||
ROS_ASSERT(goal_index <= last_valid_index);
|
||||
if((unsigned int)plan.size() == 2 && !plan.empty())
|
||||
{
|
||||
start_index = 0;
|
||||
goal_index = 1;
|
||||
}
|
||||
|
||||
// Tham chiếu lại đối số đầu vao
|
||||
sub_goal = plan[goal_index];
|
||||
if(goal_index > 0) rev_sub_goal_ = plan[goal_index - 1];
|
||||
else rev_sub_goal_ = plan[start_index];
|
||||
|
||||
target_direction = x_direction_;
|
||||
if(goal_index > 0 && (unsigned int)plan.size() > 1)
|
||||
{
|
||||
if(goal_index < (unsigned int)(plan.size() -1))
|
||||
{
|
||||
const robot_geometry_msgs::Pose2D p1 = plan[start_index];
|
||||
int index;
|
||||
for(index = start_index+1; index < goal_index; index++)
|
||||
{
|
||||
robot_geometry_msgs::Pose2D pose = plan[index];
|
||||
if(robot_nav_2d_utils::poseDistance(p1, pose) > xy_goal_tolerance_) break;
|
||||
}
|
||||
const robot_geometry_msgs::Pose2D p2 = plan[index];
|
||||
if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9)
|
||||
{
|
||||
const double path_angle = atan2(p2.y - p1.y, p2.x - p1.x);
|
||||
const double dir_path = cos(fabs(path_angle - p2.theta));
|
||||
if(fabs(dir_path) > 1e-9)
|
||||
target_direction = dir_path;
|
||||
// ROS_INFO("%f %f %f %f", p1.x ,p1.y, p2.x ,p2.y);
|
||||
// ROS_INFO("%d %0.2f %0.2f %0.2f", goal_index, path_angle, p2.theta, target_direction);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
const double rb_direction_x = sub_goal.x - robot_pose.x;
|
||||
const double rb_direction_y = sub_goal.y - robot_pose.y;
|
||||
const double rb_angle = atan2(rb_direction_y, rb_direction_x);
|
||||
double dir_rg = cos(rb_angle - robot_pose.theta);
|
||||
const double angle_threshold = 0.6;
|
||||
if(fabs(dir_rg) > angle_threshold)
|
||||
target_direction = dir_rg;
|
||||
}
|
||||
}
|
||||
|
||||
// Publish start_index
|
||||
robot_geometry_msgs::PoseStamped pose_st = robot_nav_2d_utils::pose2DToPoseStamped(plan[start_index], global_plan.header.frame_id, robot::Time::now());
|
||||
closet_robot_goal_pub_.publish(pose_st);
|
||||
|
||||
// Publish goal_index
|
||||
robot_geometry_msgs::PoseStamped pose_g = robot_nav_2d_utils::pose2DToPoseStamped(plan[goal_index], global_plan.header.frame_id, robot::Time::now());
|
||||
current_goal_pub_.publish(pose_g);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Bicycle::findSubGoalIndex(const std::vector<robot_geometry_msgs::Pose2D> &plan, std::vector<unsigned int> &index_s)
|
||||
{
|
||||
if (plan.empty())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
double x_direction_saved = 0.0;
|
||||
robot_geometry_msgs::PoseArray poseArrayMsg;
|
||||
poseArrayMsg.header.stamp = robot::Time::now();
|
||||
poseArrayMsg.header.frame_id = frame_id_path_;
|
||||
|
||||
for (unsigned int i = 1; i < (unsigned int)plan.size(); i++)
|
||||
{
|
||||
robot_geometry_msgs::Pose2D p1 = plan[i];
|
||||
robot_geometry_msgs::Pose2D p2 = plan[i+1];
|
||||
// robot_geometry_msgs::Pose2D p3 = plan[i+2];
|
||||
double angle1;
|
||||
if(fabs(p2.y - p1.y) > 1e-9 || fabs(p2.x - p1.x) > 1e-9)
|
||||
angle1 = atan2(p2.y - p1.y, p2.x - p1.x);
|
||||
else continue;
|
||||
// const double angle2 = atan2(p3.y - p2.y, p3.x - p2.x);
|
||||
const double target_direction = cos(fabs(angle1 - p2.theta));
|
||||
|
||||
if(target_direction * x_direction_saved < 0.0)
|
||||
{
|
||||
index_s.push_back(i);
|
||||
robot_geometry_msgs::Pose pose = robot_nav_2d_utils::pose2DToPose(plan[i]);
|
||||
poseArrayMsg.poses.push_back(pose);
|
||||
}
|
||||
x_direction_saved = target_direction;
|
||||
}
|
||||
|
||||
if(index_s.empty())
|
||||
index_s.push_back((unsigned int)plan.size() - 1);
|
||||
else
|
||||
{
|
||||
if(index_s.back() < (unsigned int)plan.size() - 1)
|
||||
index_s.push_back((unsigned int)plan.size() - 1);
|
||||
}
|
||||
reached_intermediate_goals_pub_.publish(poseArrayMsg);
|
||||
return true;
|
||||
}
|
||||
|
||||
double Bicycle::journey(const std::vector<robot_geometry_msgs::Pose2D> &plan, const unsigned int start_index, const unsigned int last_valid_index) const
|
||||
{
|
||||
double S = 0;
|
||||
if(last_valid_index - start_index > 1)
|
||||
{
|
||||
for(int i= start_index; i < last_valid_index; i++)
|
||||
{
|
||||
S += robot_nav_2d_utils::poseDistance(plan[i], plan[i+1]);
|
||||
}
|
||||
}
|
||||
return S;
|
||||
}
|
||||
|
||||
|
||||
} // namespace mkt_algorithm
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(mkt_algorithm::Bicycle, score_algorithm::ScoreAlgorithm)
|
||||
@@ -0,0 +1,78 @@
|
||||
#include <mkt_algorithm/rotate_to_goal.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <pluginlib/class_list_macros.h>
|
||||
#include <angles/angles.h>
|
||||
|
||||
namespace mkt_algorithm
|
||||
{
|
||||
|
||||
void RotateToGoal::initialize(const robot::NodeHandle & nh, std::string name, TFListenerPtr tf, robot_nav_core2::Costmap::Ptr costmap)
|
||||
{
|
||||
nh_ = robot::NodeHandle(nh, name);
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
|
||||
steering_fix_wheel_distance_x_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_x", 1.1);
|
||||
steering_fix_wheel_distance_y_ = robot_nav_2d_utils::searchAndGetParam(nh_, "steering_fix_wheel_distance_y", 0.);
|
||||
nh_.param("velocity_rotate_min", velocity_rotate_min_, 0.1);
|
||||
nh_.param("velocity_rotate_max", velocity_rotate_max_, 0.6);
|
||||
nh_.param("angle_pass_rotate", angle_threshold_, 0.02);
|
||||
}
|
||||
|
||||
void RotateToGoal::reset()
|
||||
{
|
||||
time_last_cmd_ = robot::Time::now();
|
||||
}
|
||||
|
||||
bool RotateToGoal::prepare( const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D& velocity,
|
||||
const robot_geometry_msgs::Pose2D& goal, const robot_nav_2d_msgs::Path2D& global_plan,
|
||||
double& x_direction, double& y_direction, double& theta_direction)
|
||||
{
|
||||
goal_ = goal;
|
||||
double angle = angles::shortest_angular_distance(pose.theta, goal_.theta);
|
||||
|
||||
if(angle > 0) current_direction_ = 1;
|
||||
else if(angle < 0) current_direction_ = -1;
|
||||
x_direction = y_direction = theta_direction = current_direction_;
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped RotateToGoal::calculator(const robot_geometry_msgs::Pose2D& pose, const robot_nav_2d_msgs::Twist2D velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2DStamped result;
|
||||
result.header.stamp = robot::Time::now();
|
||||
|
||||
robot_geometry_msgs::Pose2D steer_to_baselink_pose;
|
||||
|
||||
if(!getPose("steer_link", "base_link", steer_to_baselink_pose))
|
||||
return result;
|
||||
double actual_phi_steer = steer_to_baselink_pose.theta;
|
||||
|
||||
double L = sqrt(pow(steering_fix_wheel_distance_x_, 2) + pow(steering_fix_wheel_distance_y_, 2));
|
||||
|
||||
// robot::Time t = robot::Time::now();
|
||||
// double dt = time_last_cmd_.isZero() ? 0.0 : (t - time_last_cmd_).toSec();
|
||||
// time_last_cmd_ = robot::Time::now();
|
||||
|
||||
double angle_rg = angles::shortest_angular_distance(pose.theta, goal_.theta);
|
||||
double angle_reduce = std::min(std::max(fabs(velocity.theta), 0.15), velocity_rotate_max_);
|
||||
double w_min = velocity.theta / (fabs(velocity.theta) + 1e-9) * velocity_rotate_min_;
|
||||
double w_r = fabs(angle_rg) > angle_reduce? velocity.theta : (velocity.theta - w_min)*sin((fabs(angle_rg) / angle_reduce) * (M_PI/2)) + w_min;
|
||||
|
||||
int direct_rotate = (angle_rg/fabs(angle_rg));
|
||||
double target_phi_steer = direct_rotate * M_PI/2;
|
||||
if( fabs(target_phi_steer - actual_phi_steer) <= angle_threshold_)
|
||||
{
|
||||
double target_v = fabs(w_r * L);
|
||||
result.velocity.x = std::min(velocity_rotate_max_ * L, fabs(target_v));
|
||||
}
|
||||
else result.velocity.x = 0.0;
|
||||
|
||||
result.velocity.theta = target_phi_steer;
|
||||
return result;
|
||||
}
|
||||
|
||||
}; // namespace mkt_algorithm
|
||||
|
||||
PLUGINLIB_EXPORT_CLASS(mkt_algorithm::RotateToGoal, score_algorithm::ScoreAlgorithm)
|
||||
126
src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md
Normal file
126
src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.md
Normal file
@@ -0,0 +1,126 @@
|
||||
## Hermite (quỹ đạo 2D) từ robot đến look-ahead pose
|
||||
|
||||

|
||||
|
||||
### Bài toán
|
||||
Cho pose đích trong hệ tọa độ robot: `goal = (x, y, theta)`, với robot ở gốc
|
||||
`(0, 0, 0)` (hướng theo trục +x). Cần sinh quỹ đạo từ robot đến pose đích.
|
||||
|
||||
### Ý tưởng
|
||||
Dùng đường cong Hermite bậc 3 để đảm bảo:
|
||||
- Đi qua đúng điểm đầu và cuối.
|
||||
- Đúng hướng đầu và cuối.
|
||||
|
||||
Đường cong tham số `t` từ `0` đến `1`:
|
||||
|
||||
```
|
||||
p(t) = (x(t), y(t))
|
||||
```
|
||||
|
||||
Ràng buộc:
|
||||
- p(0) = (0, 0), hướng 0 rad.
|
||||
- p(1) = (x, y), hướng theta rad.
|
||||
|
||||
### Hệ số Hermite
|
||||
```
|
||||
h00 = 2t^3 - 3t^2 + 1
|
||||
h10 = t^3 - 2t^2 + t
|
||||
h01 = -2t^3 + 3t^2
|
||||
h11 = t^3 - t^2
|
||||
```
|
||||
|
||||
### Đạo hàm đầu/cuối
|
||||
Chọn độ dài đặc trưng `L` (thường L = sqrt(x^2 + y^2)) và hướng `dir`:
|
||||
```
|
||||
dir = +1 (đi xuôi)
|
||||
dir = -1 (đi ngược 180° ở cả đầu và cuối)
|
||||
```
|
||||
Khi đó:
|
||||
```
|
||||
p'(0) = (dir * L, 0)
|
||||
p'(1) = (dir * L*cos(theta), dir * L*sin(theta))
|
||||
```
|
||||
|
||||
### Công thức quỹ đạo
|
||||
```
|
||||
x(t) = h10*(dir*L) + h01*x + h11*(dir*L*cos(theta))
|
||||
y(t) = h01*y + h11*(dir*L*sin(theta))
|
||||
```
|
||||
|
||||
### Hướng (heading) trên đường cong
|
||||
Đạo hàm:
|
||||
```
|
||||
h00' = 6t^2 - 6t
|
||||
h10' = 3t^2 - 4t + 1
|
||||
h01' = -6t^2 + 6t
|
||||
h11' = 3t^2 - 2t
|
||||
|
||||
dx = h10'*(dir*L) + h01'*x + h11'*(dir*L*cos(theta))
|
||||
dy = h01'*y + h11'*(dir*L*sin(theta))
|
||||
```
|
||||
Hướng:
|
||||
```
|
||||
heading(t) = atan2(dy, dx)
|
||||
```
|
||||
|
||||
### Cách sử dụng
|
||||
Lấy mẫu `t` đều (ví dụ 50-200 điểm) để tạo danh sách điểm quỹ đạo.
|
||||
Nếu cần độ cong, có thể tính thêm từ đạo hàm bậc 2.
|
||||
|
||||
### Ví dụ code C++
|
||||
```
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
|
||||
struct Pose2D {
|
||||
double x;
|
||||
double y;
|
||||
double theta;
|
||||
};
|
||||
|
||||
std::vector<Pose2D> generateHermiteTrajectory(
|
||||
double x, double y, double theta,
|
||||
int samples = 100)
|
||||
{
|
||||
std::vector<Pose2D> path;
|
||||
path.reserve(samples + 1);
|
||||
|
||||
double L = std::sqrt(x * x + y * y);
|
||||
if (L < 1e-6) {
|
||||
path.push_back({0.0, 0.0, 0.0});
|
||||
return path;
|
||||
}
|
||||
|
||||
for (int i = 0; i <= samples; ++i) {
|
||||
double t = static_cast<double>(i) / samples;
|
||||
double t2 = t * t;
|
||||
double t3 = t2 * t;
|
||||
|
||||
double h00 = 2 * t3 - 3 * t2 + 1;
|
||||
double h10 = t3 - 2 * t2 + t;
|
||||
double h01 = -2 * t3 + 3 * t2;
|
||||
double h11 = t3 - t2;
|
||||
|
||||
double px = h10 * L + h01 * x + h11 * (L * std::cos(theta));
|
||||
double py = h01 * y + h11 * (L * std::sin(theta));
|
||||
|
||||
double dh00 = 6 * t2 - 6 * t;
|
||||
double dh10 = 3 * t2 - 4 * t + 1;
|
||||
double dh01 = -6 * t2 + 6 * t;
|
||||
double dh11 = 3 * t2 - 2 * t;
|
||||
|
||||
double dx = dh10 * L + dh01 * x + dh11 * (L * std::cos(theta));
|
||||
double dy = dh01 * y + dh11 * (L * std::sin(theta));
|
||||
|
||||
double heading = std::atan2(dy, dx);
|
||||
|
||||
path.push_back({px, py, heading});
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
```
|
||||
|
||||
### Ghi chú
|
||||
- Nếu (x, y) rất gần 0 thì quỹ đạo suy biến, chỉ trả về điểm gốc.
|
||||
- L có thể điều chỉnh lớn hơn để quỹ đạo mềm hơn.
|
||||
BIN
src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.pdf
Normal file
BIN
src/Algorithms/Libraries/mkt_algorithm/src/diff/Hermite.pdf
Normal file
Binary file not shown.
@@ -0,0 +1,224 @@
|
||||
#include <mkt_algorithm/diff/diff_go_straight.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot/robot.h>
|
||||
|
||||
mkt_algorithm::diff::GoStraight::GoStraight()
|
||||
: PredictiveTrajectory()
|
||||
{
|
||||
}
|
||||
|
||||
mkt_algorithm::diff::GoStraight::~GoStraight() {}
|
||||
|
||||
void mkt_algorithm::diff::GoStraight::initialize(
|
||||
robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
nh_ = nh;
|
||||
nh_priv_ = robot::NodeHandle(nh, name);
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
traj_ = traj;
|
||||
costmap_robot_ = costmap_robot;
|
||||
nh_.param<double>("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0);
|
||||
this->getParams();
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> footprint = costmap_robot_? costmap_robot_->getRobotFootprint() : std::vector<robot_geometry_msgs::Point>();
|
||||
if (footprint.size() > 1)
|
||||
{
|
||||
double min_length = 1e10;
|
||||
double max_length = 0.0;
|
||||
for (size_t i = 0; i < footprint.size(); ++i)
|
||||
{
|
||||
const robot_geometry_msgs::Point &p1 = footprint[i];
|
||||
const robot_geometry_msgs::Point &p2 = footprint[(i + 1) % footprint.size()]; // wrap around to first point
|
||||
double len = std::hypot(p2.x - p1.x, p2.y - p1.y) / 2.0;
|
||||
if (len > max_length)
|
||||
{
|
||||
max_length = len;
|
||||
}
|
||||
if (len < min_length)
|
||||
{
|
||||
min_length = len;
|
||||
}
|
||||
}
|
||||
this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1;
|
||||
this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1;
|
||||
}
|
||||
|
||||
// kalman
|
||||
last_actuator_update_ = robot::Time::now();
|
||||
n_ = 6; // [x, vx, ax, y, vy, ay, theta, vtheta, atheta]
|
||||
m_ = 2; // measurements: x, y, theta
|
||||
double dt = control_duration_;
|
||||
|
||||
// Khởi tạo ma trận
|
||||
A = Eigen::MatrixXd::Identity(n_, n_);
|
||||
C = Eigen::MatrixXd::Zero(m_, n_);
|
||||
Q = Eigen::MatrixXd::Zero(n_, n_);
|
||||
R = Eigen::MatrixXd::Identity(m_, m_);
|
||||
P = Eigen::MatrixXd::Identity(n_, n_);
|
||||
|
||||
for (int i = 0; i < n_; i += 3)
|
||||
{
|
||||
A(i, i + 1) = dt;
|
||||
A(i, i + 2) = 0.5 * dt * dt;
|
||||
A(i + 1, i + 2) = dt;
|
||||
}
|
||||
|
||||
C(0, 0) = 1;
|
||||
C(1, 3) = 1;
|
||||
Q(2, 2) = 0.1;
|
||||
Q(5, 5) = 0.6;
|
||||
|
||||
R(0, 0) = 0.1;
|
||||
R(1, 1) = 0.2;
|
||||
|
||||
P(3, 3) = 0.4;
|
||||
P(4, 4) = 0.4;
|
||||
P(5, 5) = 0.4;
|
||||
|
||||
kf_ = boost::make_shared<KalmanFilter>(dt, A, C, Q, R, P);
|
||||
Eigen::VectorXd x0(n_);
|
||||
x0 << 0, 0, 0, 0, 0, 0;
|
||||
kf_->init(robot::Time::now().toSec(), x0);
|
||||
|
||||
x_direction_ = y_direction_ = theta_direction_ = 0;
|
||||
initialized_ = true;
|
||||
robot::log_info("GoStraight Initialized successfully");
|
||||
}
|
||||
}
|
||||
|
||||
mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
// robot::log_info("x %f y %f theta %f", pose.pose.x, pose.pose.y, pose.pose.theta);
|
||||
mkt_msgs::Trajectory2D result;
|
||||
result.velocity.x = result.velocity.y = result.velocity.theta = 0.0;
|
||||
if (!traj_)
|
||||
return result;
|
||||
if (compute_plan_.poses.size() < 2)
|
||||
{
|
||||
robot::log_warning("Local compute plan is available");
|
||||
return result;
|
||||
}
|
||||
|
||||
robot::Time current_time = robot::Time::now();
|
||||
const double dt = (current_time - last_actuator_update_).toSec();
|
||||
last_actuator_update_ = current_time;
|
||||
|
||||
robot_nav_2d_msgs::Twist2D drive_cmd;
|
||||
double sign_x = x_direction_;
|
||||
|
||||
robot_nav_2d_msgs::Twist2D twist;
|
||||
traj_->startNewIteration(velocity); // Nhận tốc độ hiện tại từ odom
|
||||
while (robot::ok() && traj_->hasMoreTwists())
|
||||
{
|
||||
twist = traj_->nextTwist();
|
||||
}
|
||||
double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
|
||||
drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max));
|
||||
robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_;
|
||||
if (transformed_plan.poses.empty())
|
||||
{
|
||||
robot::log_warning("[%s:%d]\n Transformed plan is empty. Cannot determine a localglobal_plan.", __FILE__, __LINE__);
|
||||
stopWithAccLimits(pose, velocity, drive_cmd, dt);
|
||||
result.velocity = drive_cmd;
|
||||
prevous_drive_cmd_ = drive_cmd;
|
||||
return result;
|
||||
}
|
||||
double lookahead_dist = getLookAheadDistance(velocity);
|
||||
auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan);
|
||||
robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose);
|
||||
|
||||
// // === Final Heading Alignment Check ===
|
||||
// double xy_error = 0.0, heading_error = 0.0;
|
||||
// if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x))
|
||||
// {
|
||||
// // Use Arc Motion controller for final heading alignment
|
||||
// alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd);
|
||||
// #ifdef BUILD_WITH_ROS
|
||||
// ROS_INFO("xy_err=%.3f, heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f",
|
||||
// xy_error, heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta);
|
||||
// #endif
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// robot::log_info_at(__FILE__, __LINE__, "journey : %f lookahead_dist : %f",
|
||||
// journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1), lookahead_dist);
|
||||
if(fabs(carrot_pose.pose.y) > 0.2)
|
||||
{
|
||||
lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist);
|
||||
}
|
||||
robot_nav_2d_msgs::Twist2D drive_target;
|
||||
transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target, dt);
|
||||
carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan);
|
||||
|
||||
// Normal Pure Pursuit
|
||||
this->computePurePursuit(
|
||||
carrot_pose,
|
||||
drive_target,
|
||||
velocity,
|
||||
transformed_plan,
|
||||
min_approach_linear_velocity_,
|
||||
sign_x,
|
||||
dt,
|
||||
drive_cmd);
|
||||
// }
|
||||
applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt);
|
||||
|
||||
if (this->nav_stop_)
|
||||
{
|
||||
if (!stopped(velocity, rot_stopped_velocity_, trans_stopped_velocity_))
|
||||
{
|
||||
if (!stopWithAccLimits(pose, velocity, drive_cmd, dt))
|
||||
return result;
|
||||
}
|
||||
else
|
||||
drive_cmd = {};
|
||||
result.velocity = drive_cmd;
|
||||
return result;
|
||||
}
|
||||
|
||||
Eigen::VectorXd y(2);
|
||||
y << drive_cmd.x, drive_cmd.theta;
|
||||
|
||||
// Cập nhật lại A nếu dt thay đổi
|
||||
for (int i = 0; i < n_; ++i)
|
||||
for (int j = 0; j < n_; ++j)
|
||||
A(i, j) = (i == j ? 1.0 : 0.0);
|
||||
for (int i = 0; i < n_; i += 3)
|
||||
{
|
||||
A(i, i + 1) = dt;
|
||||
A(i, i + 2) = 0.5 * dt * dt;
|
||||
A(i + 1, i + 2) = dt;
|
||||
}
|
||||
kf_->update(y, dt, A);
|
||||
double v_min = min_approach_linear_velocity_;
|
||||
drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_max), fabs(v_max));
|
||||
drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x);
|
||||
drive_cmd.theta = std::clamp(kf_->state()[3], -max_vel_theta_, max_vel_theta_);
|
||||
|
||||
|
||||
result.poses.clear();
|
||||
result.poses.reserve(transformed_plan.poses.size());
|
||||
for (const auto &pose_stamped : transformed_plan.poses)
|
||||
{
|
||||
result.poses.push_back(pose_stamped.pose);
|
||||
if(fabs(pose_stamped.pose.x - carrot_pose.pose.x) < 1e-6 &&
|
||||
fabs(pose_stamped.pose.y - carrot_pose.pose.y) < 1e-6 &&
|
||||
fabs(pose_stamped.pose.theta - carrot_pose.pose.theta) < 1e-6)
|
||||
break;
|
||||
}
|
||||
drive_cmd.theta = std::clamp(drive_cmd.theta, -fabs(0.02), fabs(0.02));
|
||||
result.velocity = drive_cmd;
|
||||
prevous_drive_cmd_ = drive_cmd;
|
||||
return result;
|
||||
}
|
||||
|
||||
score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::GoStraight::create()
|
||||
{
|
||||
return std::make_shared<mkt_algorithm::diff::GoStraight>();
|
||||
}
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_algorithm::diff::GoStraight::create, MKTAlgorithmDiffGoStraight)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
#include <robot/robot.h>
|
||||
#include <mkt_algorithm/diff/diff_rotate_to_goal.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <angles/angles.h>
|
||||
|
||||
|
||||
mkt_algorithm::diff::RotateToGoal::RotateToGoal()
|
||||
: PredictiveTrajectory()
|
||||
{
|
||||
}
|
||||
|
||||
mkt_algorithm::diff::RotateToGoal::~RotateToGoal() {}
|
||||
|
||||
void mkt_algorithm::diff::RotateToGoal::initialize(
|
||||
robot::NodeHandle &nh, const std::string &name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot, const score_algorithm::TrajectoryGenerator::Ptr &traj)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
nh_ = robot::NodeHandle(nh, name);
|
||||
name_ = name;
|
||||
tf_ = tf;
|
||||
traj_ = traj;
|
||||
costmap_robot_ = costmap_robot;
|
||||
nh_.param<double>("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0);
|
||||
this->getParams();
|
||||
|
||||
last_actuator_update_ = robot::Time::now();
|
||||
x_direction_ = y_direction_ = theta_direction_ = 0;
|
||||
this->initialized_ = true;
|
||||
robot::log_info("[%s:%d]\n RotateToGoal Initialized successfully", __FILE__, __LINE__);
|
||||
}
|
||||
}
|
||||
|
||||
void mkt_algorithm::diff::RotateToGoal::reset()
|
||||
{
|
||||
robot::log_info("[%s:%d]\n RotateToGoal is reset", __FILE__, __LINE__);
|
||||
if (initialized_)
|
||||
{
|
||||
this->clear();
|
||||
x_direction_ = y_direction_ = theta_direction_ = 0;
|
||||
last_actuator_update_ = robot::Time::now();
|
||||
}
|
||||
}
|
||||
|
||||
bool mkt_algorithm::diff::RotateToGoal::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan,
|
||||
double &x_direction, double &y_direction, double &theta_direction)
|
||||
{
|
||||
|
||||
if (!initialized_)
|
||||
{
|
||||
robot::log_error("This planner has not been initialized, please call initialize() before using this planner");
|
||||
return false;
|
||||
}
|
||||
if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2)
|
||||
{
|
||||
robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size());
|
||||
return false;
|
||||
}
|
||||
if(robot::Time::now() - last_actuator_update_ > robot::Duration(0.5))
|
||||
{
|
||||
last_actuator_update_ = robot::Time::now();
|
||||
}
|
||||
this->getParams();
|
||||
frame_id_path_ = global_plan.header.frame_id;
|
||||
goal_ = goal;
|
||||
|
||||
double angle = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta);
|
||||
x_direction = y_direction = theta_direction = sign(angle);
|
||||
return true;
|
||||
}
|
||||
|
||||
mkt_msgs::Trajectory2D mkt_algorithm::diff::RotateToGoal::calculator(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
mkt_msgs::Trajectory2D result;
|
||||
robot_nav_2d_msgs::Twist2D drive_cmd;
|
||||
result.velocity.x = result.velocity.y = result.velocity.theta = 0.0;
|
||||
if (!traj_)
|
||||
return result;
|
||||
|
||||
robot::Time current_time = robot::Time::now();
|
||||
const double dt = (current_time - last_actuator_update_).toSec();
|
||||
last_actuator_update_ = current_time;
|
||||
double vel_yaw = velocity.theta;
|
||||
double ang_diff = angles::shortest_angular_distance(pose.pose.theta, goal_.pose.theta);
|
||||
rotateToHeading(ang_diff, velocity, drive_cmd, dt);
|
||||
|
||||
drive_cmd.x = 0.0;
|
||||
drive_cmd.y = 0.0;
|
||||
result.velocity = drive_cmd;
|
||||
return result;
|
||||
}
|
||||
|
||||
score_algorithm::ScoreAlgorithm::Ptr mkt_algorithm::diff::RotateToGoal::create()
|
||||
{
|
||||
return std::make_shared<mkt_algorithm::diff::RotateToGoal>();
|
||||
}
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_algorithm::diff::RotateToGoal::create, MKTAlgorithmDiffRotateToGoal)
|
||||
@@ -0,0 +1,40 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="720" height="420" viewBox="0 0 720 420">
|
||||
<rect width="100%" height="100%" fill="white"/>
|
||||
<g stroke="#444" stroke-width="2" fill="none">
|
||||
<line x1="80" y1="340" x2="660" y2="340"/>
|
||||
<line x1="80" y1="340" x2="80" y2="60"/>
|
||||
<polygon points="660,340 648,334 648,346" fill="#444"/>
|
||||
<polygon points="80,60 74,72 86,72" fill="#444"/>
|
||||
</g>
|
||||
|
||||
<g font-family="Arial, sans-serif" font-size="14" fill="#222">
|
||||
<text x="668" y="345">x</text>
|
||||
<text x="68" y="52">y</text>
|
||||
<text x="92" y="356">O(0,0)</text>
|
||||
</g>
|
||||
|
||||
<g stroke="#1f77b4" stroke-width="3" fill="none">
|
||||
<!-- Hermite-like curve -->
|
||||
<path d="M 80 340 C 220 310, 340 240, 460 180 S 600 110, 640 120"/>
|
||||
</g>
|
||||
|
||||
<g fill="#1f77b4">
|
||||
<circle cx="80" cy="340" r="5"/>
|
||||
<circle cx="640" cy="120" r="5"/>
|
||||
</g>
|
||||
|
||||
<g stroke="#888" stroke-width="2" fill="none">
|
||||
<!-- Start heading (0 rad) -->
|
||||
<line x1="80" y1="340" x2="140" y2="340"/>
|
||||
<polygon points="140,340 130,334 130,346" fill="#888"/>
|
||||
<!-- Goal heading (theta) - aligned with curve tangent -->
|
||||
<line x1="640" y1="120" x2="690" y2="130"/>
|
||||
<polygon points="690,130 678,124 678,136" fill="#888"/>
|
||||
</g>
|
||||
|
||||
<g font-family="Arial, sans-serif" font-size="14" fill="#222">
|
||||
<text x="150" y="334">heading 0</text>
|
||||
<text x="648" y="150">goal (x,y,theta)</text>
|
||||
<text x="470" y="210">Hermite trajectory</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
144
src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt
Normal file
144
src/Algorithms/Libraries/mkt_msgs/CMakeLists.txt
Normal file
@@ -0,0 +1,144 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(mkt_msgs VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building mkt_msgs with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building mkt_msgs with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
robot_nav_2d_msgs
|
||||
geometry_msgs
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_nav_2d_msgs
|
||||
geometry_msgs
|
||||
)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
# LIBRARIES không cần vì đây là header-only library
|
||||
CATKIN_DEPENDS robot_nav_2d_msgs geometry_msgs
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Tìm tất cả header files
|
||||
file(GLOB_RECURSE HEADERS "include/mkt_msgs/*.h")
|
||||
|
||||
# Tạo INTERFACE library (header-only)
|
||||
add_library(${PROJECT_NAME} INTERFACE)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
# Set include directories
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# Link dependencies (header-only, chỉ cần include paths)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
${catkin_LIBRARIES}
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# Set include directories
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
# Link dependencies (header-only, chỉ cần include paths)
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
INTERFACE
|
||||
${PACKAGES_DIR}
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME} (Header-Only)")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Headers found:")
|
||||
foreach(hdr ${HEADERS})
|
||||
message(STATUS " - ${hdr}")
|
||||
endforeach()
|
||||
message(STATUS "Dependencies: robot_nav_2d_msgs, geometry_msgs")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
@@ -0,0 +1,66 @@
|
||||
// Generated by gencpp from file mkt_msgs/Trajectory2D.msg
|
||||
// DO NOT EDIT!
|
||||
|
||||
#ifndef MKT_MSGS_MESSAGE_TRAJECTORY2D_H
|
||||
#define MKT_MSGS_MESSAGE_TRAJECTORY2D_H
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <robot_nav_2d_msgs/Twist2D.h>
|
||||
#include <robot_geometry_msgs/Pose2D.h>
|
||||
|
||||
namespace mkt_msgs
|
||||
{
|
||||
template <class ContainerAllocator>
|
||||
struct Trajectory2D_
|
||||
{
|
||||
typedef Trajectory2D_<ContainerAllocator> Type;
|
||||
|
||||
Trajectory2D_()
|
||||
: velocity(), poses(), time_offsets()
|
||||
{
|
||||
}
|
||||
Trajectory2D_(const ContainerAllocator &_alloc)
|
||||
: velocity(_alloc), poses(_alloc), time_offsets(_alloc)
|
||||
{
|
||||
(void)_alloc;
|
||||
}
|
||||
|
||||
typedef ::robot_nav_2d_msgs::Twist2D_<ContainerAllocator> _velocity_type;
|
||||
_velocity_type velocity;
|
||||
|
||||
typedef std::vector<robot_geometry_msgs::Pose2D, typename std::allocator_traits<ContainerAllocator>::template rebind_alloc<robot_geometry_msgs::Pose2D>> _poses_type;
|
||||
_poses_type poses;
|
||||
|
||||
typedef std::vector<robot::Duration, typename std::allocator_traits<ContainerAllocator>::template rebind_alloc<robot::Duration>> _time_offsets_type;
|
||||
_time_offsets_type time_offsets;
|
||||
|
||||
typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_<ContainerAllocator>> Ptr;
|
||||
typedef boost::shared_ptr<::mkt_msgs::Trajectory2D_<ContainerAllocator> const> ConstPtr;
|
||||
|
||||
}; // struct Trajectory2D_
|
||||
|
||||
typedef ::mkt_msgs::Trajectory2D_<std::allocator<void>> Trajectory2D;
|
||||
|
||||
typedef boost::shared_ptr<::mkt_msgs::Trajectory2D> Trajectory2DPtr;
|
||||
typedef boost::shared_ptr<::mkt_msgs::Trajectory2D const> Trajectory2DConstPtr;
|
||||
|
||||
template <typename ContainerAllocator1, typename ContainerAllocator2>
|
||||
bool operator==(const ::mkt_msgs::Trajectory2D_<ContainerAllocator1> &lhs, const ::mkt_msgs::Trajectory2D_<ContainerAllocator2> &rhs)
|
||||
{
|
||||
return lhs.velocity == rhs.velocity &&
|
||||
lhs.poses == rhs.poses &&
|
||||
lhs.time_offsets == rhs.time_offsets;
|
||||
}
|
||||
|
||||
template <typename ContainerAllocator1, typename ContainerAllocator2>
|
||||
bool operator!=(const ::mkt_msgs::Trajectory2D_<ContainerAllocator1> &lhs, const ::mkt_msgs::Trajectory2D_<ContainerAllocator2> &rhs)
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
} // namespace mkt_msgs
|
||||
|
||||
#endif // MKT_MSGS_MESSAGE_TRAJECTORY2D_H
|
||||
27
src/Algorithms/Libraries/mkt_msgs/package.xml
Normal file
27
src/Algorithms/Libraries/mkt_msgs/package.xml
Normal file
@@ -0,0 +1,27 @@
|
||||
<package>
|
||||
<name>mkt_msgs</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
mkt_msgs is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. mkt_msgs
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/mkt_msgs</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<build_depend>geometry_msgs</build_depend>
|
||||
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
<run_depend>geometry_msgs</run_depend>
|
||||
</package>
|
||||
208
src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt
Normal file
208
src/Algorithms/Libraries/mkt_plugins/CMakeLists.txt
Normal file
@@ -0,0 +1,208 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(mkt_plugins VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building mkt_plugins with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building mkt_plugins with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
score_algorithm
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_std_msgs
|
||||
robot_sensor_msgs
|
||||
angles
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
score_algorithm
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_std_msgs
|
||||
robot_sensor_msgs
|
||||
angles
|
||||
)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator
|
||||
CATKIN_DEPENDS score_algorithm robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 geometry_msgs robot_nav_msgs robot_std_msgs robot_sensor_msgs angles
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME}_goal_checker SHARED
|
||||
src/goal_checker.cpp
|
||||
src/simple_goal_checker.cpp
|
||||
src/equation_line.cpp
|
||||
)
|
||||
|
||||
add_library(${PROJECT_NAME}_standard_traj_generator SHARED
|
||||
src/kinematic_parameters.cpp
|
||||
src/xy_theta_iterator.cpp
|
||||
src/standard_traj_generator.cpp
|
||||
src/limited_accel_generator.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME}_goal_checker ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
add_dependencies(${PROJECT_NAME}_standard_traj_generator ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_goal_checker
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_standard_traj_generator
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_goal_checker
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::system
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_standard_traj_generator
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::system
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_goal_checker
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_standard_traj_generator
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_goal_checker
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::system
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_standard_traj_generator
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::system
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME}_goal_checker PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME}_standard_traj_generator PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}_goal_checker ${PROJECT_NAME}_standard_traj_generator
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: ${PROJECT_NAME}_goal_checker, ${PROJECT_NAME}_standard_traj_generator")
|
||||
message(STATUS "Dependencies: score_algorithm, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_sensor_msgs, angles, Boost")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
BIN
src/Algorithms/Libraries/mkt_plugins/doc/VelocitySpace.png
Normal file
BIN
src/Algorithms/Libraries/mkt_plugins/doc/VelocitySpace.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
BIN
src/Algorithms/Libraries/mkt_plugins/doc/lim_pv.png
Normal file
BIN
src/Algorithms/Libraries/mkt_plugins/doc/lim_pv.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 29 KiB |
BIN
src/Algorithms/Libraries/mkt_plugins/doc/std_pv.png
Normal file
BIN
src/Algorithms/Libraries/mkt_plugins/doc/std_pv.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,74 @@
|
||||
#ifndef __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__
|
||||
#define __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__
|
||||
#include <robot/robot.h>
|
||||
#include <robot_geometry_msgs/Pose2D.h>
|
||||
#include <iostream>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
/**
|
||||
* @class NoSolution
|
||||
*/
|
||||
class NoSolution : public std::exception {
|
||||
public:
|
||||
const char * what () const throw () {
|
||||
return "Robot cannot calculate error line!";
|
||||
}
|
||||
}; // class NoSolution
|
||||
|
||||
/**
|
||||
* @class LineGenerator
|
||||
*/
|
||||
class LineGenerator
|
||||
{
|
||||
/* data */
|
||||
struct LineEquation {
|
||||
robot_geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊) */
|
||||
robot_geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋) */
|
||||
float a, b, c ; /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */
|
||||
};
|
||||
|
||||
/* Save data present position */
|
||||
struct PresentPosition {
|
||||
float Gxh, Gyh; /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */
|
||||
float Yaw_degree; /* Angle of Robot (degree) */
|
||||
float Yaw_rad; /* Angle of Robot (degree) */
|
||||
float error_line; /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2) */
|
||||
double distance_to_goal; /* The distance from query pose to goal */
|
||||
double distance_to_start; /* The distance from query pose to start*/
|
||||
double distace_start_goal;
|
||||
};
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief To caculated the equation of the line
|
||||
* @param start_point start point of the line
|
||||
* @param end_point end point of the line
|
||||
*/
|
||||
virtual bool calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point);
|
||||
|
||||
/**
|
||||
* @brief Calculating error
|
||||
* @param[in] Lm The distance from the center of the wheel axis to the center line
|
||||
* @param[in] pose
|
||||
* @param[in] rev
|
||||
*/
|
||||
virtual void calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev = false);
|
||||
|
||||
/**
|
||||
* @brief Calculating tolerance
|
||||
* @param query_pose The pose to check
|
||||
* @param goal_pose The pose to check against
|
||||
*/
|
||||
virtual double calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose);
|
||||
|
||||
/* Properties */
|
||||
LineEquation Leq_;
|
||||
PresentPosition present_pose_;
|
||||
|
||||
}; // class LineGenerator
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // __MKT_PLUGINS_EQUATION_LINE_H_INCLUDED__
|
||||
@@ -0,0 +1,57 @@
|
||||
#ifndef _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__
|
||||
#define _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__
|
||||
|
||||
#include <score_algorithm/goal_checker.h>
|
||||
#include <mkt_plugins/equation_line.h>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
class GoalChecker : public score_algorithm::GoalChecker
|
||||
{
|
||||
public:
|
||||
GoalChecker();
|
||||
/**
|
||||
* @brief Initialize any parameters from the NodeHandle
|
||||
* @param nh NodeHandle for grabbing parameters
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle &nh) override;
|
||||
|
||||
/**
|
||||
* @brief Reset the state of the goal checker (if any)
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Check whether the goal should be considered reached
|
||||
* @param query_pose The pose to check
|
||||
* @param goal_pose The pose to check against
|
||||
* @param velocity The robot's current velocity
|
||||
* @return True if goal is reached
|
||||
*/
|
||||
bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose,
|
||||
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Factory function to create a GoalChecker instance
|
||||
* @return Shared pointer to a new GoalChecker instance
|
||||
*/
|
||||
static score_algorithm::GoalChecker::Ptr create();
|
||||
protected:
|
||||
/**
|
||||
* @brief Internal method to initialize parameters from NodeHandle
|
||||
* @param nh NodeHandle to load parameters from
|
||||
*
|
||||
* Loads xy_goal_tolerance and yaw_goal_tolerance parameters
|
||||
*/
|
||||
void intParam(const robot::NodeHandle &nh);
|
||||
|
||||
robot::NodeHandle nh_;
|
||||
std::shared_ptr<mkt_plugins::LineGenerator> line_generator_;
|
||||
double yaw_goal_tolerance_;
|
||||
double xy_goal_tolerance_;
|
||||
double old_xy_goal_tolerance_;
|
||||
};
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // _MKT_PLUGINS_CHECKER_GOAL_H_INCLUDED__
|
||||
@@ -0,0 +1,318 @@
|
||||
#ifndef MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_
|
||||
#define MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <memory>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
/**
|
||||
* @class KinematicParameters
|
||||
* @brief A dynamically reconfigurable class containing one representation of the robot's kinematics
|
||||
*/
|
||||
class KinematicParameters
|
||||
{
|
||||
public:
|
||||
KinematicParameters();
|
||||
virtual ~KinematicParameters();
|
||||
void initialize(const robot::NodeHandle &nh);
|
||||
|
||||
/**
|
||||
* @brief Get the direction array for X, Y, and theta movement
|
||||
* @return Pointer to an array of integers representing the direction of movement for X, Y, and theta (e.g., 1 for forward/right/clockwise, -1 for backward/left/counterclockwise, 0 for stop)
|
||||
*
|
||||
* This array controls the intended direction of the robot. Sudden changes in the theta component can cause discontinuities in odometry data, potentially leading to localization jumps in AMCL when rotating in place.
|
||||
*/
|
||||
int *getDirect();
|
||||
|
||||
/**
|
||||
* @brief Get the minimum linear velocity along the X-axis
|
||||
* @return Minimum linear velocity (m/s) for forward/backward motion
|
||||
*
|
||||
* Used to ensure the robot does not move too slowly along X, which could lead to odometry drift. Less relevant for in-place rotation issues.
|
||||
*/
|
||||
double getMinX();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear velocity along the X-axis
|
||||
* @return Maximum linear velocity (m/s) for forward/backward motion
|
||||
*
|
||||
* Ensures the robot does not exceed safe speeds along X. Not directly related to rotation-induced localization jumps.
|
||||
*/
|
||||
double getMaxX();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear acceleration along the X-axis
|
||||
* @return Maximum linear acceleration (m/s²) for forward/backward motion
|
||||
*
|
||||
* High acceleration can cause odometry errors if the robot's hardware cannot keep up. Less relevant for in-place rotation.
|
||||
*/
|
||||
double getAccX();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear deceleration along the X-axis
|
||||
* @return Maximum linear deceleration (m/s²) for forward/backward motion
|
||||
*
|
||||
* Improper deceleration may cause jerky stops, leading to minor odometry errors. Not a primary cause of rotation-induced localization jumps.
|
||||
*/
|
||||
double getDecelX();
|
||||
|
||||
/**
|
||||
* @brief Get the minimum linear velocity along the Y-axis
|
||||
* @return Minimum linear velocity (m/s) for lateral motion (if applicable)
|
||||
*
|
||||
* Typically zero for differential drive robots. Not relevant for in-place rotation.
|
||||
*/
|
||||
double getMinY();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear velocity along the Y-axis
|
||||
* @return Maximum linear velocity (m/s) for lateral motion
|
||||
*
|
||||
* Typically zero for differential drive robots. Not relevant for in-place rotation.
|
||||
*/
|
||||
double getMaxY();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear acceleration along the Y-axis
|
||||
* @return Maximum linear acceleration (m/s²) for lateral motion
|
||||
*
|
||||
* Not relevant for in-place rotation in differential drive robots.
|
||||
*/
|
||||
double getAccY();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum linear deceleration along the Y-axis
|
||||
* @return Maximum linear deceleration (m/s²) for lateral motion
|
||||
*
|
||||
* Not relevant for in-place rotation in differential drive robots.
|
||||
*/
|
||||
double getDecelY();
|
||||
|
||||
/**
|
||||
* @brief Get the minimum combined linear velocity in the XY plane
|
||||
* @return Minimum combined velocity (m/s) for motion in the XY plane
|
||||
*
|
||||
* Ensures the robot moves at a meaningful speed in the XY plane. Not directly related to in-place rotation issues.
|
||||
*/
|
||||
double getMinSpeedXY();
|
||||
|
||||
/**
|
||||
* @brief Get the minimum angular velocity for rotation
|
||||
* @return Minimum angular velocity (rad/s) for rotation around the Z-axis
|
||||
*
|
||||
* A very low value may cause the robot to struggle with stable rotation, leading to odometry errors and potential localization jumps in AMCL.
|
||||
*/
|
||||
double getMinTheta();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum angular velocity for rotation
|
||||
* @return Maximum angular velocity (rad/s) for rotation around the Z-axis
|
||||
*
|
||||
* A high value (e.g., >2.0 rad/s) can cause wheel slip or odometry errors during fast rotation, leading to localization jumps in AMCL.
|
||||
*/
|
||||
double getMaxTheta();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum angular acceleration for rotation
|
||||
* @return Maximum angular acceleration (rad/s²) for rotation around the Z-axis
|
||||
*
|
||||
* High angular acceleration can cause jerky rotation, leading to odometry errors and potential localization jumps in AMCL.
|
||||
*/
|
||||
double getAccTheta();
|
||||
|
||||
/**
|
||||
* @brief Get the maximum angular deceleration for rotation
|
||||
* @return Maximum angular deceleration (rad/s²) for rotation around the Z-axis
|
||||
*
|
||||
* Improper deceleration can cause jerky stops during rotation, leading to odometry errors and localization jumps in AMCL.
|
||||
*/
|
||||
double getDecelTheta();
|
||||
|
||||
/**
|
||||
* @brief Get the minimum angular speed for rotation
|
||||
* @return Minimum angular speed (rad/s) for rotation around the Z-axis
|
||||
*
|
||||
* Similar to getMinTheta(), a very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues.
|
||||
*/
|
||||
double getMinSpeedTheta();
|
||||
|
||||
/**
|
||||
* @brief Set the direction array for X, Y, and theta movement
|
||||
* @param xytheta_direct Pointer to an array of integers specifying the direction for X, Y, and theta
|
||||
*
|
||||
* Sets the intended direction of motion. Sudden changes in the theta component can cause discontinuities in odometry, leading to localization jumps in AMCL during in-place rotation.
|
||||
*/
|
||||
void setDirect(int *xytheta_direct);
|
||||
|
||||
/**
|
||||
* @brief Set the minimum linear velocity along the X-axis
|
||||
* @param value Minimum linear velocity (m/s) for forward/backward motion
|
||||
*
|
||||
* Ensures the robot does not move too slowly along X. Not directly related to in-place rotation issues.
|
||||
*/
|
||||
void setMinX(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear velocity along the X-axis
|
||||
* @param value Maximum linear velocity (m/s) for forward/backward motion
|
||||
*
|
||||
* Limits the robot's speed along X. Not directly related to in-place rotation issues.
|
||||
*/
|
||||
void setMaxX(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear acceleration along the X-axis
|
||||
* @param value Maximum linear acceleration (m/s²) for forward/backward motion
|
||||
*
|
||||
* High acceleration can cause odometry errors if not supported by hardware. Less relevant for in-place rotation.
|
||||
*/
|
||||
void setAccX(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear deceleration along the X-axis
|
||||
* @param value Maximum linear deceleration (m/s²) for forward/backward motion
|
||||
*
|
||||
* Improper deceleration may cause minor odometry errors. Not a primary cause of rotation-induced localization jumps.
|
||||
*/
|
||||
void setDecelX(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the minimum linear velocity along the Y-axis
|
||||
* @param value Minimum linear velocity (m/s) for lateral motion
|
||||
*
|
||||
* Typically zero for differential drive robots. Not relevant for in-place rotation.
|
||||
*/
|
||||
void setMinY(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear velocity along the Y-axis
|
||||
* @param value Maximum linear velocity (m/s) for lateral motion
|
||||
*
|
||||
* Typically zero for differential drive robots. Not relevant for in-place rotation.
|
||||
*/
|
||||
void setMaxY(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear acceleration along the Y-axis
|
||||
* @param value Maximum linear acceleration (m/s²) for lateral motion
|
||||
*
|
||||
* Not relevant for in-place rotation in differential drive robots.
|
||||
*/
|
||||
void setAccY(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum linear deceleration along the Y-axis
|
||||
* @param value Maximum linear deceleration (m/s²) for lateral motion
|
||||
*
|
||||
* Not relevant for in-place rotation in differential drive robots.
|
||||
*/
|
||||
void setDecelY(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the minimum combined linear velocity in the XY plane
|
||||
* @param value Minimum combined velocity (m/s) for motion in the XY plane
|
||||
*
|
||||
* Ensures meaningful motion in the XY plane. Not directly related to in-place rotation issues.
|
||||
*/
|
||||
void setMinSpeedXY(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum angular velocity for rotation
|
||||
* @param value Maximum angular velocity (rad/s) for rotation around the Z-axis
|
||||
*
|
||||
* A high value can cause fast rotation, leading to wheel slip or odometry errors, which may cause AMCL to jump during in-place rotation.
|
||||
*/
|
||||
void setMaxTheta(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum angular acceleration for rotation
|
||||
* @param value Maximum angular acceleration (rad/s²) for rotation around the Z-axis
|
||||
*
|
||||
* High acceleration can cause jerky rotation, leading to odometry errors and AMCL localization jumps.
|
||||
*/
|
||||
void setAccTheta(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the maximum angular deceleration for rotation
|
||||
* @param value Maximum angular deceleration (rad/s²) for rotation around the Z-axis
|
||||
*
|
||||
* Improper deceleration can cause jerky stops, leading to odometry errors and AMCL localization jumps.
|
||||
*/
|
||||
void setDecelTheta(double value);
|
||||
|
||||
/**
|
||||
* @brief Set the minimum angular speed for rotation
|
||||
* @param value Minimum angular speed (rad/s) for rotation around the Z-axis
|
||||
*
|
||||
* A very low value may cause unstable rotation, contributing to odometry errors and AMCL localization issues.
|
||||
*/
|
||||
void setMinSpeedTheta(double value);
|
||||
|
||||
/**
|
||||
* @brief Check to see whether the combined x/y/theta velocities are valid
|
||||
* @return True if the magnitude hypot(x,y) and theta are within the robot's absolute limits
|
||||
*
|
||||
* This is based on three parameters: min_speed_xy, max_speed_xy and min_speed_theta.
|
||||
* The speed is valid if
|
||||
* 1) The combined magnitude hypot(x,y) is less than max_speed_xy (or max_speed_xy is negative)
|
||||
* AND
|
||||
* 2) min_speed_xy is negative or min_speed_theta is negative or
|
||||
* hypot(x,y) is greater than min_speed_xy or fabs(theta) is greater than min_speed_theta.
|
||||
*
|
||||
* In English, it makes sure the diagonal motion is not too fast,
|
||||
* and that the velocity is moving in some meaningful direction.
|
||||
*
|
||||
* In Latin, quod si motus sit signum quaerit et movere ieiunium et significantissime comprehendite.
|
||||
*/
|
||||
bool isValidSpeed(double x, double y, double theta);
|
||||
|
||||
using Ptr = std::shared_ptr<KinematicParameters>;
|
||||
|
||||
protected:
|
||||
|
||||
/**
|
||||
* @brief Configure the kinematic parameters
|
||||
* @param nh NodeHandle
|
||||
*
|
||||
* Configures the kinematic parameters from the given NodeHandle.
|
||||
*/
|
||||
void configure(const robot::NodeHandle &nh);
|
||||
|
||||
/**
|
||||
* @brief Reconfigure the kinematic parameters
|
||||
* @param nh NodeHandle
|
||||
*
|
||||
* Reconfigures the kinematic parameters from the given NodeHandle.
|
||||
*/
|
||||
void reconfigure(const robot::NodeHandle &nh);
|
||||
|
||||
// For parameter descriptions, see cfg/KinematicParams.cfg
|
||||
int xytheta_direct_[3];
|
||||
double min_vel_x_, min_vel_y_;
|
||||
double max_vel_x_, max_vel_y_, max_vel_theta_;
|
||||
|
||||
double min_speed_xy_, max_speed_xy_;
|
||||
double min_speed_theta_;
|
||||
|
||||
double acc_lim_x_, acc_lim_y_, acc_lim_theta_;
|
||||
double decel_lim_x_, decel_lim_y_, decel_lim_theta_;
|
||||
|
||||
// Cached square values of min_speed_xy and max_speed_xy
|
||||
double min_speed_xy_sq_, max_speed_xy_sq_;
|
||||
|
||||
private:
|
||||
double original_min_vel_x_, original_min_vel_y_;
|
||||
double original_max_vel_x_, original_max_vel_y_, original_max_vel_theta_;
|
||||
|
||||
double original_min_speed_xy_, original_max_speed_xy_;
|
||||
double original_min_speed_theta_;
|
||||
|
||||
double original_acc_lim_x_, original_acc_lim_y_, original_acc_lim_theta_;
|
||||
double original_decel_lim_x_, original_decel_lim_y_, original_decel_lim_theta_;
|
||||
};
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_KINEMATIC_PARAMETERS_H_INCLUDED_
|
||||
@@ -0,0 +1,51 @@
|
||||
#ifndef MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_
|
||||
#define MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_
|
||||
|
||||
#include <mkt_plugins/standard_traj_generator.h>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
/**
|
||||
* @class LimitedAccelGenerator
|
||||
* @brief Limits the acceleration in the generated trajectories to a fraction of the simulated time.
|
||||
*/
|
||||
class LimitedAccelGenerator : public StandardTrajectoryGenerator
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor
|
||||
*/
|
||||
LimitedAccelGenerator();
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
virtual ~LimitedAccelGenerator();
|
||||
|
||||
/**
|
||||
* @brief Initialize the generator with parameters from NodeHandle
|
||||
* @param nh NodeHandle for loading acceleration_time parameter
|
||||
*
|
||||
* Loads the acceleration_time parameter which limits acceleration to a fraction
|
||||
* of the simulated time.
|
||||
*/
|
||||
void initialize(const robot::NodeHandle& nh) override;
|
||||
|
||||
/**
|
||||
* @brief Start a new iteration with current velocity
|
||||
* @param current_velocity Current velocity of the robot
|
||||
*
|
||||
* Overrides the base class to apply acceleration limits based on acceleration_time.
|
||||
*/
|
||||
void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Factory function to create a LimitedAccelGenerator instance
|
||||
* @return Shared pointer to a new LimitedAccelGenerator instance
|
||||
*/
|
||||
static score_algorithm::TrajectoryGenerator::Ptr create();
|
||||
protected:
|
||||
double acceleration_time_;
|
||||
};
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_LIMITED_ACCEL_GENERATOR_H_INCLUDED_
|
||||
@@ -0,0 +1,220 @@
|
||||
#ifndef MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_
|
||||
#define MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED_
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
const double EPSILON = 5E-2;
|
||||
|
||||
inline double exponentialFactor(double x, double k = 2.5)
|
||||
{
|
||||
x = std::clamp(x, 0.0, 1.0);
|
||||
return 1.0 - std::exp(-k * x); // tương đương (1 - e^{-kx})
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Given initial conditions and a time, figure out the end velocity
|
||||
*
|
||||
* @param v0 Initial velocity
|
||||
* @param accel The acceleration rate
|
||||
* @param decel The decceleration rate
|
||||
* @param dt Delta time - amount of time to project into the future
|
||||
* @param target target velocity
|
||||
* @return The velocity dt seconds after v0.
|
||||
*/
|
||||
inline double projectVelocity(double v0, double accel, double decel, double dt, double target)
|
||||
{
|
||||
double magnitude;
|
||||
if (fabs(v0) < EPSILON)
|
||||
{
|
||||
// Starting from standstill, always accelerate
|
||||
if (target >= 0.0)
|
||||
{
|
||||
magnitude = fabs(accel);
|
||||
}
|
||||
else
|
||||
{
|
||||
magnitude = -fabs(accel);
|
||||
}
|
||||
}
|
||||
else if (v0 > 0.0)
|
||||
{
|
||||
if (v0 < target)
|
||||
{
|
||||
// Acceleration (speed magnitude increases)
|
||||
magnitude = fabs(accel);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Deceleration (speed magnitude decreases)
|
||||
magnitude = -fabs(decel);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (v0 < target)
|
||||
{
|
||||
// Deceleration (speed magnitude decreases)
|
||||
magnitude = fabs(decel);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Acceleration (speed magnitude increases)
|
||||
magnitude = -fabs(accel);
|
||||
}
|
||||
}
|
||||
|
||||
double delta_v = fabs(target - v0);
|
||||
double max_v = std::max(fabs(target), 1e-3);
|
||||
magnitude *= exponentialFactor(delta_v / max_v, 3.0);
|
||||
double v1 = v0 + magnitude * dt;
|
||||
|
||||
if (magnitude > 0.0)
|
||||
{
|
||||
return std::min(target, v1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return std::max(target, v1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @class OneDVelocityIterator
|
||||
* @brief An iterator for generating a number of samples in a range
|
||||
*
|
||||
* In its simplest usage, this gives us N (num_samples) different velocities that are reachable
|
||||
* given our current velocity. However, there is some fancy logic around zero velocities and
|
||||
* the min/max velocities
|
||||
*
|
||||
* If the current velocity is 2 m/s, and the acceleration limit is 1 m/ss and the acc_time is 1 s,
|
||||
* this class would provide velocities between 1 m/s and 3 m/s.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
class OneDVelocityIterator
|
||||
{
|
||||
public:
|
||||
std::string name_;
|
||||
/**
|
||||
* @brief Constructor for the velocity iterator
|
||||
* @param current Current velocity of the robot
|
||||
* @param direct Direction multiplier (1 for forward, -1 for backward, 0 for stop)
|
||||
* @param min Minimum velocity allowable
|
||||
* @param max Maximum velocity allowable
|
||||
* @param acc_limit Maximum acceleration limit
|
||||
* @param decel_limit Maximum deceleration limit
|
||||
* @param acc_time Time delta for velocity projection
|
||||
* @param num_samples Number of velocity samples to generate
|
||||
*
|
||||
* Creates an iterator that generates num_samples velocities reachable from
|
||||
* current velocity within acc_time seconds, respecting acceleration/deceleration limits.
|
||||
* The velocities range from min_vel_ to max_vel_ (projected from current velocity).
|
||||
*/
|
||||
OneDVelocityIterator(
|
||||
std::string name, double current, int direct, double min, double max, double acc_limit, double decel_limit, double acc_time, int num_samples)
|
||||
: name_(name)
|
||||
{
|
||||
// if (current < min)
|
||||
// {
|
||||
// current = min;
|
||||
// }
|
||||
// else if (current > max)
|
||||
// {
|
||||
// current = max;
|
||||
// }
|
||||
max_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, max);
|
||||
min_vel_ = projectVelocity(current, acc_limit, decel_limit, acc_time, min);
|
||||
direct_ = direct;
|
||||
current_ = direct_ > 0 ? max_vel_ : min_vel_;
|
||||
reset();
|
||||
|
||||
if (min_vel_ - max_vel_ < EPSILON)
|
||||
{
|
||||
increment_ = 1.0;
|
||||
return;
|
||||
}
|
||||
num_samples = std::max(2, num_samples);
|
||||
|
||||
// e.g. for 4 samples, split distance in 3 even parts
|
||||
increment_ = (max_vel_ - min_vel_) / std::max(1, (num_samples - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the current velocity value
|
||||
* @return Current velocity value, or 0.0 if return_zero_now_ is true
|
||||
*
|
||||
* Returns the velocity at the current iterator position.
|
||||
* If the iterator is set to return zero (when crossing zero velocity),
|
||||
* returns 0.0 instead of the current value.
|
||||
*/
|
||||
double getVelocity() const
|
||||
{
|
||||
if (return_zero_now_)
|
||||
return 0.0;
|
||||
return current_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Increment the iterator to the next velocity sample
|
||||
* @return Reference to this iterator
|
||||
*
|
||||
* Moves to the next velocity sample. If the iterator crosses zero velocity
|
||||
* (from negative to positive), it will return zero velocity on the next call
|
||||
* to getVelocity() before continuing with positive velocities.
|
||||
*/
|
||||
OneDVelocityIterator &operator++()
|
||||
{
|
||||
if (return_zero_ && current_ < 0.0 && current_ + increment_ > 0.0 && current_ + increment_ <= max_vel_ + EPSILON)
|
||||
{
|
||||
return_zero_now_ = true;
|
||||
return_zero_ = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
current_ += increment_;
|
||||
return_zero_now_ = false;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reset the iterator back to the first velocity
|
||||
*
|
||||
* Resets the iterator to the starting velocity (max_vel_ if direct > 0,
|
||||
* min_vel_ if direct <= 0) and enables zero-velocity return if applicable.
|
||||
*/
|
||||
void reset()
|
||||
{
|
||||
return_zero_ = true;
|
||||
return_zero_now_ = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if all velocities for this iteration have been returned
|
||||
* @return True if the iterator has passed beyond the limit velocity
|
||||
*
|
||||
* Returns true when the current velocity has exceeded the maximum
|
||||
* (if direct > 0) or minimum (if direct <= 0) velocity limit.
|
||||
*/
|
||||
bool isFinished() const
|
||||
{
|
||||
double limit_vel = direct_ > 0? max_vel_ : min_vel_;
|
||||
return fabs(current_) > fabs(limit_vel) + EPSILON;
|
||||
}
|
||||
|
||||
private:
|
||||
bool return_zero_, return_zero_now_;
|
||||
double min_vel_, max_vel_;
|
||||
double current_;
|
||||
double direct_;
|
||||
double increment_;
|
||||
};
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_ONE_D_VELOCITY_ITERATOR_H_INCLUDED
|
||||
@@ -0,0 +1,77 @@
|
||||
#ifndef _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__
|
||||
#define _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <score_algorithm/goal_checker.h>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
/**
|
||||
* @class SimpleGoalChecker
|
||||
* @brief Goal Checker plugin that only checks the position difference
|
||||
*
|
||||
* This class can be stateful if the stateful parameter is set to true (which it is by default).
|
||||
* This means that the goal checker will not check if the xy position matches again once it is found to be true.
|
||||
*/
|
||||
class SimpleGoalChecker : public score_algorithm::GoalChecker
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Default constructor
|
||||
* Initializes default values for goal tolerances and stateful behavior
|
||||
*/
|
||||
SimpleGoalChecker();
|
||||
|
||||
/**
|
||||
* @brief Initialize the goal checker with parameters from NodeHandle
|
||||
* @param nh NodeHandle for loading parameters (xy_goal_tolerance, yaw_goal_tolerance, stateful, check_xy)
|
||||
*/
|
||||
void initialize(const robot::NodeHandle &nh) override;
|
||||
|
||||
/**
|
||||
* @brief Reset the state of the goal checker
|
||||
* Clears any cached state to allow re-checking of goal conditions
|
||||
*/
|
||||
void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Check if the goal has been reached
|
||||
* @param query_pose Current pose of the robot
|
||||
* @param goal_pose Target pose to reach
|
||||
* @param path Path to follow (not used in simple checker)
|
||||
* @param velocity Current velocity of the robot (not used in simple checker)
|
||||
* @return True if the robot is within xy_goal_tolerance and yaw_goal_tolerance of the goal
|
||||
*
|
||||
* If stateful is true, once xy position matches, it will not check xy again.
|
||||
* This prevents oscillation when the robot is close to the goal.
|
||||
*/
|
||||
bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose,
|
||||
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Factory function to create a SimpleGoalChecker instance
|
||||
* @return Shared pointer to a new SimpleGoalChecker instance
|
||||
*/
|
||||
static score_algorithm::GoalChecker::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Internal method to initialize parameters from NodeHandle
|
||||
* @param nh NodeHandle to load parameters from
|
||||
*
|
||||
* Loads xy_goal_tolerance, yaw_goal_tolerance, stateful, and check_xy parameters
|
||||
*/
|
||||
void intParam(const robot::NodeHandle& nh);
|
||||
|
||||
robot::NodeHandle nh_;
|
||||
double xy_goal_tolerance_, yaw_goal_tolerance_;
|
||||
bool stateful_, check_xy_;
|
||||
|
||||
// Cached squared xy_goal_tolerance_
|
||||
double xy_goal_tolerance_sq_;
|
||||
};
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // _MKTPLUGINS_SIMPLE_GOAL_CHECKER_H_INCLUDED__
|
||||
@@ -0,0 +1,205 @@
|
||||
#ifndef MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_
|
||||
#define MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <score_algorithm/trajectory_generator.h>
|
||||
#include <mkt_plugins/velocity_iterator.h>
|
||||
#include <mkt_plugins/kinematic_parameters.h>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
/**
|
||||
* @class StandardTrajectoryGenerator
|
||||
* @brief Standard MKT-like trajectory generator.
|
||||
*/
|
||||
class StandardTrajectoryGenerator : public score_algorithm::TrajectoryGenerator
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Constructor
|
||||
*/
|
||||
StandardTrajectoryGenerator();
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
virtual ~StandardTrajectoryGenerator();
|
||||
/**
|
||||
* @brief Initialize the trajectory generator with parameters from NodeHandle
|
||||
* @param nh NodeHandle for loading configuration parameters
|
||||
*
|
||||
* Loads parameters such as sim_time, discretize_by_time, time_granularity,
|
||||
* linear_granularity, angular_granularity, and include_last_point.
|
||||
*/
|
||||
void initialize(const robot::NodeHandle &nh) override;
|
||||
|
||||
/**
|
||||
* @brief Set the direction array for X, Y, and Theta movement
|
||||
* @param xytheta_direct Pointer to array of 3 integers representing direction
|
||||
* (1 for forward/right/clockwise, -1 for backward/left/counterclockwise)
|
||||
*/
|
||||
void setDirect(int *xytheta_direct) override;
|
||||
|
||||
/**
|
||||
* @brief set velocity for x, y asix of the robot
|
||||
* @param linear the velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override;
|
||||
|
||||
/**
|
||||
* @brief get velocity for x, y asix of the robot
|
||||
* @param linear The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override;
|
||||
|
||||
/**
|
||||
* @brief Set velocity theta for z asix of the robot
|
||||
* @param angular the command velocity
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override;
|
||||
|
||||
/**
|
||||
* @brief Get velocity theta for z asix of the robot
|
||||
* @param direct The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override;
|
||||
|
||||
/**
|
||||
* @brief Start a new iteration with current velocity
|
||||
* @param current_velocity Current velocity of the robot
|
||||
*
|
||||
* Resets the velocity iterator and prepares it to generate velocities
|
||||
* reachable from the current velocity.
|
||||
*/
|
||||
void startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Check if there are more velocity samples available
|
||||
* @return True if there are more valid velocity combinations to iterate
|
||||
*/
|
||||
bool hasMoreTwists() override;
|
||||
|
||||
/**
|
||||
* @brief Get the next velocity sample
|
||||
* @return Next valid velocity combination
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2D nextTwist() override;
|
||||
|
||||
/**
|
||||
* @brief Get the current velocity
|
||||
* @return The current velocity
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2D getTwist() override;
|
||||
|
||||
/**
|
||||
* @brief Generate a trajectory from start pose to goal
|
||||
* @param start_pose Starting pose of the robot
|
||||
* @param transformed_plan Transformed global plan (path to follow)
|
||||
* @param start_vel Starting velocity of the robot
|
||||
* @param cmd_vel Command velocity to achieve
|
||||
* @return Generated trajectory containing poses and velocities over time
|
||||
*
|
||||
* Generates a trajectory by:
|
||||
* 1. Computing velocity steps based on acceleration limits
|
||||
* 2. Projecting poses forward using kinematic model
|
||||
* 3. Sampling velocities using the velocity iterator
|
||||
*/
|
||||
mkt_msgs::Trajectory2D generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose,
|
||||
const robot_nav_2d_msgs::Path2D &transformed_plan,
|
||||
const robot_nav_2d_msgs::Twist2D &start_vel,
|
||||
const robot_nav_2d_msgs::Twist2D &cmd_vel) override;
|
||||
|
||||
/**
|
||||
* @brief Get the NodeHandle used for kinematics configuration
|
||||
* @return NodeHandle scoped to kinematics namespace
|
||||
*/
|
||||
virtual robot::NodeHandle getNodeHandle() override;
|
||||
|
||||
/**
|
||||
* @brief Factory function to create a StandardTrajectoryGenerator instance
|
||||
* @return Shared pointer to a new StandardTrajectoryGenerator instance
|
||||
*/
|
||||
static score_algorithm::TrajectoryGenerator::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Initialize the VelocityIterator pointer. Put in its own function for easy overriding
|
||||
*/
|
||||
virtual void initializeIterator(const robot::NodeHandle &nh);
|
||||
|
||||
/**
|
||||
* @brief Calculate the velocity after a set period of time, given the desired velocity and acceleration limits
|
||||
*
|
||||
* @param cmd_vel Desired velocity
|
||||
* @param start_vel starting velocity
|
||||
* @param dt amount of time in seconds
|
||||
* @return new velocity after dt seconds
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2D computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel,
|
||||
const robot_nav_2d_msgs::Twist2D &start_vel,
|
||||
const double dt);
|
||||
|
||||
/**
|
||||
* @brief Use the robot's kinematic model to predict new positions for the robot
|
||||
*
|
||||
* @param start_pose Starting pose
|
||||
* @param vel Actual robot velocity (assumed to be within acceleration limits)
|
||||
* @param dt amount of time in seconds
|
||||
* @return New pose after dt seconds
|
||||
*/
|
||||
virtual robot_geometry_msgs::Pose2D computeNewPosition(const robot_geometry_msgs::Pose2D start_pose,
|
||||
const robot_nav_2d_msgs::Twist2D &vel,
|
||||
const double dt);
|
||||
|
||||
/**
|
||||
* @brief Compute an array of time deltas between the points in the generated trajectory.
|
||||
*
|
||||
* @param cmd_vel The desired command velocity
|
||||
* @return vector of the difference between each time step in the generated trajectory
|
||||
*
|
||||
* If we are discretizing by time, the returned vector will be the same constant time_granularity
|
||||
* for all cmd_vels. Otherwise, you will get times based on the linear/angular granularity.
|
||||
*
|
||||
* Right now the vector contains a single value repeated many times, but this method could be overridden
|
||||
* to allow for dynamic spacing
|
||||
*/
|
||||
virtual std::vector<double> getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel);
|
||||
|
||||
robot::NodeHandle nh_kinematics_;
|
||||
KinematicParameters::Ptr kinematics_;
|
||||
std::shared_ptr<mkt_plugins::VelocityIterator> velocity_iterator_;
|
||||
|
||||
double sim_time_;
|
||||
|
||||
// Sampling Parameters
|
||||
bool discretize_by_time_;
|
||||
double time_granularity_; ///< If discretizing by time, the amount of time between each point in the traj
|
||||
double linear_granularity_; ///< If not discretizing by time, the amount of linear space between points
|
||||
double angular_granularity_; ///< If not discretizing by time, the amount of angular space between points
|
||||
|
||||
/* Backwards Compatibility Parameter: include_last_point
|
||||
*
|
||||
* dwa had an off-by-one error built into it.
|
||||
* It generated N trajectory points, where N = ceil(sim_time / time_delta).
|
||||
* If for example, sim_time=3.0 and time_delta=1.5, it would generate trajectories with 2 points, which
|
||||
* indeed were time_delta seconds apart. However, the points would be at t=0 and t=1.5, and thus the
|
||||
* actual sim_time was much less than advertised.
|
||||
*
|
||||
* This is remedied by adding one final point at t=sim_time, but only if include_last_point_ is true.
|
||||
*
|
||||
* Nothing I could find actually used the time_delta variable or seemed to care that the trajectories
|
||||
* were not projected out as far as they intended.
|
||||
*/
|
||||
bool include_last_point_;
|
||||
}; // class StandardTrajectoryGenerator
|
||||
|
||||
} // namespace dwb_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_STANDARD_TRAJ_GENERATOR_H_INCLUDED_
|
||||
@@ -0,0 +1,67 @@
|
||||
#ifndef MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_
|
||||
#define MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_nav_2d_msgs/Twist2D.h>
|
||||
#include <mkt_plugins/kinematic_parameters.h>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
/**
|
||||
* @class VelocityIterator
|
||||
* @brief Abstract base class for iterating over valid velocity samples
|
||||
*
|
||||
* This interface provides a way to generate and iterate through velocity samples
|
||||
* that satisfy kinematic constraints. Implementations should generate velocities
|
||||
* reachable from the current velocity within acceleration limits.
|
||||
*/
|
||||
class VelocityIterator
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Virtual destructor
|
||||
*/
|
||||
virtual ~VelocityIterator() {}
|
||||
|
||||
/**
|
||||
* @brief Initialize the iterator with parameters and kinematics
|
||||
* @param nh NodeHandle for loading configuration parameters
|
||||
* @param kinematics Shared pointer to kinematic parameters for validation
|
||||
*/
|
||||
virtual void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) = 0;
|
||||
|
||||
/**
|
||||
* @brief Start a new iteration with current velocity and time delta
|
||||
* @param current_velocity Current velocity of the robot
|
||||
* @param dt Time delta for velocity projection
|
||||
*
|
||||
* Resets the iterator and prepares it to generate velocities reachable
|
||||
* from the current velocity within dt seconds.
|
||||
*/
|
||||
virtual void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) = 0;
|
||||
|
||||
/**
|
||||
* @brief Check if there are more velocity samples available
|
||||
* @return True if there are more valid velocity combinations to iterate
|
||||
*/
|
||||
virtual bool hasMoreTwists() = 0;
|
||||
|
||||
/**
|
||||
* @brief Get the next velocity sample
|
||||
* @return Next valid velocity combination
|
||||
*
|
||||
* Returns the next velocity sample that satisfies kinematic constraints.
|
||||
* Should only be called when hasMoreTwists() returns true.
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2D nextTwist() = 0;
|
||||
|
||||
/**
|
||||
* @brief Get the current velocity
|
||||
* @return The current velocity
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2D getTwist() = 0;
|
||||
}; // class VelocityIterator
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_VELOCITY_ITERATOR_H_INCLUDED_
|
||||
@@ -0,0 +1,90 @@
|
||||
#ifndef MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_
|
||||
#define MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_
|
||||
|
||||
#include <mkt_plugins/velocity_iterator.h>
|
||||
#include <mkt_plugins/one_d_velocity_iterator.h>
|
||||
#include <memory>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
/**
|
||||
* @class XYThetaIterator
|
||||
* @brief Iterator that generates velocity samples for X, Y, and Theta dimensions
|
||||
*
|
||||
* This iterator combines three OneDVelocityIterator instances (one for each dimension)
|
||||
* to generate valid velocity combinations that satisfy kinematic constraints.
|
||||
*/
|
||||
class XYThetaIterator : public VelocityIterator
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Default constructor
|
||||
* Initializes all iterators to nullptr
|
||||
*/
|
||||
XYThetaIterator();
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*/
|
||||
virtual ~XYThetaIterator();
|
||||
|
||||
/**
|
||||
* @brief Initialize the iterator with parameters and kinematics
|
||||
* @param nh NodeHandle for loading sampling parameters (vx_samples, vy_samples, vtheta_samples)
|
||||
* @param kinematics Shared pointer to kinematic parameters for validation
|
||||
*/
|
||||
void initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) override;
|
||||
|
||||
/**
|
||||
* @brief Start a new iteration with current velocity and time delta
|
||||
* @param current_velocity Current velocity of the robot
|
||||
* @param dt Time delta for velocity projection
|
||||
*
|
||||
* Creates new OneDVelocityIterator instances for X, Y, and Theta dimensions
|
||||
* based on the current velocity and kinematic constraints.
|
||||
*/
|
||||
void startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt) override;
|
||||
|
||||
/**
|
||||
* @brief Check if there are more velocity samples to iterate
|
||||
* @return True if there are more valid velocity combinations available
|
||||
*/
|
||||
bool hasMoreTwists() override;
|
||||
|
||||
/**
|
||||
* @brief Get the next velocity sample
|
||||
* @return Next valid velocity combination (x, y, theta)
|
||||
*
|
||||
* Returns the next valid velocity that satisfies kinematic constraints.
|
||||
* Automatically iterates to the next valid velocity if current is invalid.
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2D nextTwist() override;
|
||||
|
||||
/**
|
||||
* @brief Get the current velocity
|
||||
* @return The current velocity (x, y, theta)
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2D getTwist() override;
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Check if the current velocity combination is valid
|
||||
* @return True if the current velocity (x_it_, y_it_, th_it_) satisfies kinematic constraints
|
||||
*/
|
||||
virtual bool isValidVelocity();
|
||||
|
||||
/**
|
||||
* @brief Iterate through velocity samples until a valid combination is found
|
||||
*
|
||||
* Increments the iterators (theta first, then y, then x) until a valid
|
||||
* velocity combination is found or all combinations are exhausted.
|
||||
*/
|
||||
void iterateToValidVelocity();
|
||||
|
||||
int vx_samples_, vy_samples_, vtheta_samples_;
|
||||
KinematicParameters::Ptr kinematics_;
|
||||
std::shared_ptr<OneDVelocityIterator> x_it_, y_it_, th_it_;
|
||||
};
|
||||
} // namespace mkt_plugins
|
||||
|
||||
#endif // MKT_PLUGINS_XY_THETA_ITERATOR_H_INCLUDED_
|
||||
49
src/Algorithms/Libraries/mkt_plugins/package.xml
Normal file
49
src/Algorithms/Libraries/mkt_plugins/package.xml
Normal file
@@ -0,0 +1,49 @@
|
||||
<package>
|
||||
<name>mkt_plugins</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
mkt_plugins is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. mkt_plugins
|
||||
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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/mkt_plugins</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>score_algorithm</build_depend>
|
||||
<run_depend>score_algorithm</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
|
||||
<build_depend>robot_nav_core2</build_depend>
|
||||
<run_depend>robot_nav_core2</run_depend>
|
||||
|
||||
<build_depend>geometry_msgs</build_depend>
|
||||
<run_depend>geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_msgs</build_depend>
|
||||
<run_depend>robot_nav_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_std_msgs</build_depend>
|
||||
<run_depend>robot_std_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_sensor_msgs</build_depend>
|
||||
<run_depend>robot_sensor_msgs</run_depend>
|
||||
|
||||
<build_depend>angles</build_depend>
|
||||
<run_depend>angles</run_depend>
|
||||
|
||||
</package>
|
||||
118
src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp
Normal file
118
src/Algorithms/Libraries/mkt_plugins/src/equation_line.cpp
Normal file
@@ -0,0 +1,118 @@
|
||||
#include "mkt_plugins/equation_line.h"
|
||||
#include <robot/console.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
bool LineGenerator::calculatorEquationLine(robot_geometry_msgs::Pose2D start_point, robot_geometry_msgs::Pose2D end_point)
|
||||
{
|
||||
/**
|
||||
* Phương trình đường thẳng có dạng:
|
||||
* (y - yi)/(yj - yi) = (x - xi)/(xj - xi)
|
||||
*/
|
||||
Leq_.Gi = start_point; Leq_.Gj = end_point;
|
||||
Leq_.a = (Leq_.Gj.y - Leq_.Gi.y);
|
||||
Leq_.b = (Leq_.Gi.x - Leq_.Gj.x);
|
||||
Leq_.c = (Leq_.Gj.x * Leq_.Gi.y - Leq_.Gi.x * Leq_.Gj.y);
|
||||
|
||||
return Leq_.a != 0 || Leq_.b !=0;
|
||||
}
|
||||
|
||||
void LineGenerator::calculateErrorLine(float Lm, robot_geometry_msgs::Pose2D pose, bool rev)
|
||||
{
|
||||
float pha = rev? M_PI : 0;
|
||||
float Yaw_rad = pose.theta - pha;
|
||||
|
||||
/*
|
||||
* Tính tọa độ điểm R
|
||||
*/
|
||||
float G_xr = float(pose.x);
|
||||
float G_yr = float(pose.y);
|
||||
|
||||
/*
|
||||
* Tính tọa độ điểm H
|
||||
*/
|
||||
present_pose_.Gxh = G_xr + Lm * cos(Yaw_rad);
|
||||
present_pose_.Gyh = G_yr + Lm * sin(Yaw_rad);
|
||||
|
||||
/**
|
||||
* Phương trình đường thẳng (rh) có dạng:
|
||||
* (y - yr)/(yh - yr) = (x - xr)/(xh - xr)
|
||||
*/
|
||||
float A_rh = (present_pose_.Gyh - G_yr);
|
||||
float B_rh = (G_xr - present_pose_.Gxh);
|
||||
float C_rh = (present_pose_.Gxh * G_yr - G_xr * present_pose_.Gyh);
|
||||
/*
|
||||
* Phương trình đường thẳng vuông góc (y - yr)/(yh - yr) = (x - xr)/(xh - xr)
|
||||
* và đi qua Gh có dạng:
|
||||
* -B_rh*(x - Gxh) + Arh*(y - Gyh) = 0
|
||||
*/
|
||||
float A_he = -B_rh;
|
||||
float B_he = A_rh;
|
||||
float C_he = (-B_rh) * (-present_pose_.Gxh) + A_rh * (-present_pose_.Gyh);
|
||||
/*
|
||||
* Đường thẳng (he) giao với đường thẳng (ij) tại e
|
||||
* vậy G_xe và G_ye là nghiệm của hệ phương trình 2 ẩn của 2 đường thẳng trên:
|
||||
*/
|
||||
float D = A_he * Leq_.b - Leq_.a * B_he;
|
||||
float Dx = (-C_he) * Leq_.b - (-Leq_.c) * B_he;
|
||||
float Dy = A_he * (-Leq_.c) - Leq_.a * (-C_he);
|
||||
/*
|
||||
* Tính tọa độ điểm E
|
||||
*/
|
||||
if(D == 0) {
|
||||
if(Dx + Dy == 0)
|
||||
{
|
||||
/*
|
||||
* Vì hai đường thẳng trùng nhau nên sai số giữa robot và đường đi là bằng 0
|
||||
*/
|
||||
present_pose_.error_line = 0;
|
||||
}
|
||||
else throw NoSolution();
|
||||
}
|
||||
else
|
||||
{
|
||||
float G_xe = Dx/D;
|
||||
float G_ye = Dy/D;
|
||||
/*
|
||||
* Tính khoảng cách từ điểm E đến đường thẳng (RH)
|
||||
*/
|
||||
present_pose_.error_line = -(A_rh * G_xe + B_rh * G_ye + C_rh) / (sqrt(pow(A_rh, 2) + pow(B_rh, 2)));
|
||||
}
|
||||
// present_pose_.error_line = (Leq.a * present_pose_.Gxh + Leq.b * present_pose_.Gyh + Leq.c) / (sqrt(pow(Leq.a, 2) + pow(Leq.b, 2)));
|
||||
present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - G_xr),2) + pow((Leq_.Gj.y - G_yr),2));
|
||||
present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - G_xr),2) + pow((Leq_.Gi.y - G_yr),2));
|
||||
|
||||
|
||||
}
|
||||
|
||||
double LineGenerator::calculateTolerance(const robot_geometry_msgs::Pose2D& query_pose, const robot_geometry_msgs::Pose2D& goal_pose)
|
||||
{
|
||||
/**
|
||||
* Phương trình đường thẳng có dạng:
|
||||
* (y - yi)/(yj - yi) = (x - xi)/(xj - xi)
|
||||
*/
|
||||
// LineEquation Leq;
|
||||
// Leq.Gi = query_pose; Leq.Gj = goal_pose;
|
||||
// Leq.a = (Leq.Gj.y - Leq.Gi.y);
|
||||
// Leq.b = (Leq.Gi.x - Leq.Gj.x);
|
||||
// Leq.c = (Leq.Gj.x * Leq.Gi.y - Leq.Gi.x * Leq.Gj.y);
|
||||
|
||||
/**
|
||||
* Phương trình đường thẳng vuông góc
|
||||
*/
|
||||
LineEquation Leq_l;
|
||||
Leq_l.a = -Leq_.b;
|
||||
Leq_l.b = Leq_.a;
|
||||
Leq_l.c = Leq_.b * goal_pose.x - Leq_.a * goal_pose.y;
|
||||
|
||||
present_pose_.distance_to_goal = sqrt(pow((Leq_.Gj.x - query_pose.x),2) + pow((Leq_.Gj.y - query_pose.y),2));
|
||||
present_pose_.distance_to_start = sqrt(pow((Leq_.Gi.x - query_pose.x),2) + pow((Leq_.Gi.y - query_pose.y),2));
|
||||
present_pose_.distace_start_goal = sqrt(pow((Leq_.Gj.x - Leq_.Gi.x),2) + pow((Leq_.Gj.y - Leq_.Gi.y),2));
|
||||
// ROS_INFO_THROTTLE(0.2, "Goal checker %f %f %f %f %f", Leq_.Gj.x, Leq_.Gj.y, Leq_.Gj.theta, query_pose.x, query_pose.y);
|
||||
|
||||
return (Leq_l.a * query_pose.x + Leq_l.b * query_pose.y + Leq_l.c ) / (sqrt(pow(Leq_l.a, 2) + pow(Leq_l.b, 2)));
|
||||
}
|
||||
|
||||
} // namespace mkt_plugins
|
||||
115
src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp
Normal file
115
src/Algorithms/Libraries/mkt_plugins/src/goal_checker.cpp
Normal file
@@ -0,0 +1,115 @@
|
||||
#include <robot/robot.h>
|
||||
#include <mkt_plugins/goal_checker.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <angles/angles.h>
|
||||
#include <cmath>
|
||||
|
||||
mkt_plugins::GoalChecker::GoalChecker()
|
||||
: nh_(),
|
||||
line_generator_(nullptr),
|
||||
yaw_goal_tolerance_(0.25),
|
||||
xy_goal_tolerance_(0.25),
|
||||
old_xy_goal_tolerance_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
void mkt_plugins::GoalChecker::initialize(const robot::NodeHandle &nh)
|
||||
{
|
||||
nh_ = nh;
|
||||
this->intParam(nh);
|
||||
robot::log_info_at(__FILE__, __LINE__, "[GoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f", xy_goal_tolerance_, yaw_goal_tolerance_);
|
||||
line_generator_ = std::make_shared<mkt_plugins::LineGenerator>();
|
||||
}
|
||||
|
||||
void mkt_plugins::GoalChecker::intParam(const robot::NodeHandle &nh)
|
||||
{
|
||||
if (!nh.param<double>("xy_goal_tolerance", xy_goal_tolerance_, 0.1))
|
||||
{
|
||||
xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1);
|
||||
}
|
||||
if (!nh.param<double>("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1))
|
||||
{
|
||||
yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
void mkt_plugins::GoalChecker::reset()
|
||||
{
|
||||
old_xy_goal_tolerance_ = 0;
|
||||
}
|
||||
|
||||
bool mkt_plugins::GoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &query_pose, const robot_nav_2d_msgs::Pose2DStamped &goal_pose,
|
||||
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
this->intParam(nh_);
|
||||
double dx = query_pose.pose.x - goal_pose.pose.x;
|
||||
double dy = query_pose.pose.y - goal_pose.pose.y;
|
||||
double xy_tolerance = std::abs(std::sqrt(dx * dx + dy * dy));
|
||||
|
||||
if (!path.poses.empty() && path.poses.size() > 2)
|
||||
{
|
||||
double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta);
|
||||
for(int i = path.poses.size() - 1; i >= 0; i--)
|
||||
{
|
||||
double dx = path.poses[i].pose.x - path.poses.back().pose .x;
|
||||
double dy = path.poses[i].pose.y - path.poses.back().pose.y;
|
||||
if(std::sqrt(dx * dx + dy * dy) > 0.05 // TODO: get resolution from costmap
|
||||
&& fabs(dx) > 1e-6 && fabs(dy) > 1e-6)
|
||||
{
|
||||
theta = angles::normalize_angle(query_pose.pose.theta - atan2(dy, dx));
|
||||
break;
|
||||
}
|
||||
}
|
||||
double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy;
|
||||
double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy;
|
||||
if (xy_tolerance <= xy_goal_tolerance_ + 0.1)
|
||||
{
|
||||
double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
if(fabs(tolerance) <= xy_goal_tolerance_)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "%.3f %.3f %.3f %.3f %.3f", fabs(cos(theta)), fabs(sin(theta)),xy_tolerance, xy_goal_tolerance_, yaw_goal_tolerance_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal checker 1 ok %.3f %.3f %.3f %.3f %.3f ", tolerance, old_xy_goal_tolerance_, x, y, theta);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
old_xy_goal_tolerance_ = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
|
||||
}
|
||||
else
|
||||
{
|
||||
double theta = angles::normalize_angle(query_pose.pose.theta - goal_pose.pose.theta);
|
||||
double x = cos(goal_pose.pose.theta) * dx + sin(goal_pose.pose.theta) * dy;
|
||||
double y = -sin(goal_pose.pose.theta) * dx + cos(goal_pose.pose.theta) * dy;
|
||||
if (xy_tolerance <= xy_goal_tolerance_ + 0.1)
|
||||
{
|
||||
double tolerance = fabs(x) > fabs(y) ? x : y;
|
||||
if(
|
||||
(fabs(tolerance) <= xy_goal_tolerance_ || tolerance * old_xy_goal_tolerance_ < 0)
|
||||
)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "%f %f", fabs(cos(theta)), fabs(sin(theta)));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal checker 2 ok %f %f %f %f %f ", tolerance, old_xy_goal_tolerance_, x, y, theta);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else
|
||||
old_xy_goal_tolerance_ = fabs(x) > fabs(y) ? x : y;
|
||||
}
|
||||
|
||||
if (xy_tolerance <= xy_goal_tolerance_)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal checker ok %f %f", xy_tolerance, xy_goal_tolerance_);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
score_algorithm::GoalChecker::Ptr mkt_plugins::GoalChecker::create()
|
||||
{
|
||||
return std::make_shared<mkt_plugins::GoalChecker>();
|
||||
}
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_plugins::GoalChecker::create, GoalChecker)
|
||||
@@ -0,0 +1,243 @@
|
||||
#include <mkt_plugins/kinematic_parameters.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
|
||||
|
||||
using robot_nav_2d_utils::moveDeprecatedParameter;
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
const double EPSILON = 1E-5;
|
||||
|
||||
/**
|
||||
* @brief Helper function to set the deceleration to the negative acceleration if it was not already set.
|
||||
* @param nh NodeHandle
|
||||
* @param dimension String representing the dimension, used in constructing parameter names
|
||||
*/
|
||||
void setDecelerationAsNeeded(const robot::NodeHandle &nh, const std::string dimension)
|
||||
{
|
||||
std::string decel_param = "decel_lim_" + dimension;
|
||||
if (nh.hasParam(decel_param))
|
||||
return;
|
||||
|
||||
std::string accel_param = "acc_lim_" + dimension;
|
||||
if (!nh.hasParam(accel_param))
|
||||
return;
|
||||
|
||||
double accel;
|
||||
nh.getParam(accel_param, accel);
|
||||
nh.setParam(decel_param, -accel);
|
||||
}
|
||||
|
||||
KinematicParameters::KinematicParameters()
|
||||
: xytheta_direct_(),
|
||||
min_vel_x_(0.0),
|
||||
min_vel_y_(0.0),
|
||||
max_vel_x_(0.0),
|
||||
max_vel_y_(0.0),
|
||||
max_vel_theta_(0.0),
|
||||
min_speed_xy_(0.0),
|
||||
max_speed_xy_(0.0),
|
||||
min_speed_theta_(0.0),
|
||||
acc_lim_x_(0.0),
|
||||
acc_lim_y_(0.0),
|
||||
acc_lim_theta_(0.0),
|
||||
decel_lim_x_(0.0),
|
||||
decel_lim_y_(0.0),
|
||||
decel_lim_theta_(0.0),
|
||||
min_speed_xy_sq_(0.0),
|
||||
max_speed_xy_sq_(0.0),
|
||||
original_min_vel_x_(0.0),
|
||||
original_min_vel_y_(0.0),
|
||||
original_max_vel_x_(0.0),
|
||||
original_max_vel_y_(0.0),
|
||||
original_max_vel_theta_(0.0),
|
||||
original_min_speed_xy_(0.0),
|
||||
original_max_speed_xy_(0.0),
|
||||
original_min_speed_theta_(0.0),
|
||||
original_acc_lim_x_(0.0),
|
||||
original_acc_lim_y_(0.0),
|
||||
original_acc_lim_theta_(0.0),
|
||||
original_decel_lim_x_(0.0),
|
||||
original_decel_lim_y_(0.0),
|
||||
original_decel_lim_theta_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
KinematicParameters::~KinematicParameters()
|
||||
{
|
||||
}
|
||||
|
||||
void KinematicParameters::initialize(const robot::NodeHandle &nh)
|
||||
{
|
||||
// Special handling for renamed parameters
|
||||
moveDeprecatedParameter<double>(nh, "max_vel_theta", "max_rot_vel");
|
||||
moveDeprecatedParameter<double>(nh, "min_speed_xy", "min_trans_vel");
|
||||
moveDeprecatedParameter<double>(nh, "max_speed_xy", "max_trans_vel");
|
||||
moveDeprecatedParameter<double>(nh, "min_speed_theta", "min_rot_vel");
|
||||
|
||||
// Set the deceleration parameters to negative the acceleration if the deceleration not already specified
|
||||
setDecelerationAsNeeded(nh, "x");
|
||||
setDecelerationAsNeeded(nh, "y");
|
||||
setDecelerationAsNeeded(nh, "theta");
|
||||
|
||||
configure(nh);
|
||||
xytheta_direct_[0] = xytheta_direct_[1] = xytheta_direct_[2] = 1;
|
||||
}
|
||||
|
||||
|
||||
void KinematicParameters::configure(const robot::NodeHandle &nh)
|
||||
{
|
||||
nh.param("max_vel_x", original_max_vel_x_, 0.0);
|
||||
nh.param("max_vel_y", original_max_vel_y_, 0.0);
|
||||
nh.param("max_vel_theta", original_max_vel_theta_, 0.0);
|
||||
nh.param("min_vel_x", original_min_vel_x_, 0.0);
|
||||
nh.param("min_vel_y", original_min_vel_y_, 0.0);
|
||||
nh.param("min_speed_xy", original_min_speed_xy_, 0.0);
|
||||
nh.param("max_speed_xy", original_max_speed_xy_, 0.0);
|
||||
nh.param("min_speed_theta", original_min_speed_theta_, 0.0);
|
||||
nh.param("acc_lim_x", original_acc_lim_x_, 0.0);
|
||||
nh.param("acc_lim_y", original_acc_lim_y_, 0.0);
|
||||
nh.param("acc_lim_theta", original_acc_lim_theta_, 0.0);
|
||||
nh.param("decel_lim_x", original_decel_lim_x_, 0.0);
|
||||
nh.param("decel_lim_y", original_decel_lim_y_, 0.0);
|
||||
nh.param("decel_lim_theta", original_decel_lim_theta_, 0.0);
|
||||
reconfigure(nh);
|
||||
}
|
||||
|
||||
void KinematicParameters::reconfigure(const robot::NodeHandle &nh)
|
||||
{
|
||||
nh.param("max_vel_x", max_vel_x_, 0.0);
|
||||
nh.param("max_vel_y", max_vel_y_, 0.0);
|
||||
nh.param("max_vel_theta", max_vel_theta_, 0.0);
|
||||
nh.param("min_vel_x", min_vel_x_, 0.0);
|
||||
nh.param("min_vel_y", min_vel_y_, 0.0);
|
||||
nh.param("min_speed_xy", min_speed_xy_, 0.0);
|
||||
nh.param("max_speed_xy", max_speed_xy_, 0.0);
|
||||
nh.param("min_speed_theta", min_speed_theta_, 0.0);
|
||||
nh.param("acc_lim_x", acc_lim_x_, 0.0);
|
||||
nh.param("acc_lim_y", acc_lim_y_, 0.0);
|
||||
nh.param("acc_lim_theta", acc_lim_theta_, 0.0);
|
||||
nh.param("decel_lim_x", decel_lim_x_, 0.0);
|
||||
nh.param("decel_lim_y", decel_lim_y_, 0.0);
|
||||
nh.param("decel_lim_theta", decel_lim_theta_, 0.0);
|
||||
}
|
||||
|
||||
void KinematicParameters::setDirect(int *xytheta_direct)
|
||||
{
|
||||
xytheta_direct_[0] = xytheta_direct[0];
|
||||
xytheta_direct_[1] = xytheta_direct[1];
|
||||
xytheta_direct_[2] = xytheta_direct[2];
|
||||
}
|
||||
|
||||
bool KinematicParameters::isValidSpeed(double x, double y, double theta)
|
||||
{
|
||||
double vmag_sq = x * x + y * y;
|
||||
if (max_speed_xy_ >= 0.0 && vmag_sq > max_speed_xy_sq_ + EPSILON)
|
||||
return false;
|
||||
if (min_speed_xy_ >= 0.0 && vmag_sq + EPSILON < min_speed_xy_sq_ &&
|
||||
min_speed_theta_ >= 0.0 && fabs(theta) + EPSILON < min_speed_theta_)
|
||||
return false;
|
||||
if (vmag_sq == 0.0 && theta == 0.0)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
int *KinematicParameters::getDirect() { return xytheta_direct_; }
|
||||
|
||||
double KinematicParameters::getMinX() { return min_vel_x_; }
|
||||
|
||||
double KinematicParameters::getMaxX() { return max_vel_x_; }
|
||||
|
||||
double KinematicParameters::getAccX() { return acc_lim_x_; }
|
||||
|
||||
double KinematicParameters::getDecelX() { return decel_lim_x_; }
|
||||
|
||||
double KinematicParameters::getMinY() { return min_vel_y_; }
|
||||
|
||||
double KinematicParameters::getMaxY() { return max_vel_y_; }
|
||||
|
||||
double KinematicParameters::getAccY() { return acc_lim_y_; }
|
||||
|
||||
double KinematicParameters::getDecelY() { return decel_lim_y_; }
|
||||
|
||||
double KinematicParameters::getMinSpeedXY() { return min_speed_xy_; }
|
||||
|
||||
double KinematicParameters::getMinTheta() { return -max_vel_theta_; }
|
||||
|
||||
double KinematicParameters::getMaxTheta() { return max_vel_theta_; }
|
||||
|
||||
double KinematicParameters::getAccTheta() { return acc_lim_theta_; }
|
||||
|
||||
double KinematicParameters::getDecelTheta() { return decel_lim_theta_; }
|
||||
|
||||
double KinematicParameters::getMinSpeedTheta() { return min_speed_theta_; }
|
||||
|
||||
void KinematicParameters::setMinX(double value)
|
||||
{
|
||||
min_vel_x_ = fabs(value) < fabs(original_min_vel_x_) + EPSILON ? value : min_vel_x_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMaxX(double value)
|
||||
{
|
||||
max_vel_x_ = fabs(value) <= fabs(original_max_vel_x_) + EPSILON ? value : original_max_vel_x_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setAccX(double value)
|
||||
{
|
||||
acc_lim_x_ = fabs(value) <= fabs(original_acc_lim_x_) + EPSILON ? value : acc_lim_x_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setDecelX(double value)
|
||||
{
|
||||
decel_lim_x_ = fabs(value) <= fabs(original_decel_lim_x_) + EPSILON ? value : decel_lim_x_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMinY(double value)
|
||||
{
|
||||
min_vel_y_ = fabs(value) <= fabs(original_min_vel_y_) + EPSILON ? value : min_vel_y_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMaxY(double value)
|
||||
{
|
||||
max_vel_y_ = fabs(value) <= fabs(original_max_vel_y_) + EPSILON ? value : max_vel_y_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setAccY(double value)
|
||||
{
|
||||
acc_lim_y_ = fabs(value) <= fabs(original_acc_lim_y_) + EPSILON ? value : acc_lim_y_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setDecelY(double value)
|
||||
{
|
||||
decel_lim_y_ = fabs(value) <= fabs(original_decel_lim_y_) + EPSILON ? value : decel_lim_y_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMinSpeedXY(double value)
|
||||
{
|
||||
min_speed_xy_ = fabs(value) <= fabs(original_min_speed_xy_) + EPSILON ? value : min_speed_xy_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMaxTheta(double value)
|
||||
{
|
||||
max_vel_theta_ = fabs(value) <= fabs(original_max_vel_theta_) + EPSILON? value : original_max_vel_theta_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setAccTheta(double value)
|
||||
{
|
||||
acc_lim_theta_ = fabs(value) <= fabs(original_acc_lim_theta_) + EPSILON ? value : acc_lim_theta_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setDecelTheta(double value)
|
||||
{
|
||||
decel_lim_theta_ = fabs(value) <= fabs(original_decel_lim_theta_) + EPSILON ? value : decel_lim_theta_;
|
||||
}
|
||||
|
||||
void KinematicParameters::setMinSpeedTheta(double value)
|
||||
{
|
||||
min_speed_theta_ = fabs(value) <= fabs(original_min_speed_theta_) + EPSILON ? value : min_speed_theta_;
|
||||
}
|
||||
} // namespace mkt_plugins
|
||||
@@ -0,0 +1,59 @@
|
||||
#include <robot/robot.h>
|
||||
#include <mkt_plugins/limited_accel_generator.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <vector>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
LimitedAccelGenerator::LimitedAccelGenerator()
|
||||
: StandardTrajectoryGenerator(),
|
||||
acceleration_time_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
LimitedAccelGenerator::~LimitedAccelGenerator()
|
||||
{
|
||||
}
|
||||
|
||||
void LimitedAccelGenerator::initialize(const robot::NodeHandle& nh)
|
||||
{
|
||||
StandardTrajectoryGenerator::initialize(nh);
|
||||
if (nh.hasParam("sim_period"))
|
||||
{
|
||||
nh.getParam("sim_period", acceleration_time_);
|
||||
}
|
||||
else
|
||||
{
|
||||
double controller_frequency = robot_nav_2d_utils::searchAndGetParam(nh, "controller_frequency", 20.0);
|
||||
robot::log_warning("[%s:%d] limited_accel_generator: %f", __FILE__, __LINE__, controller_frequency);
|
||||
if (controller_frequency > 0)
|
||||
{
|
||||
acceleration_time_ = 1.0 / controller_frequency;
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "A controller_frequency less than or equal to 0 has been set. "
|
||||
"Ignoring the parameter, assuming a rate of 20Hz");
|
||||
acceleration_time_ = 0.05;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void LimitedAccelGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity)
|
||||
{
|
||||
// Limit our search space to just those within the limited acceleration_time
|
||||
velocity_iterator_->startNewIteration(current_velocity, acceleration_time_);
|
||||
}
|
||||
|
||||
score_algorithm::TrajectoryGenerator::Ptr LimitedAccelGenerator::create()
|
||||
{
|
||||
return std::make_shared<LimitedAccelGenerator>();
|
||||
}
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_plugins::LimitedAccelGenerator::create, LimitedAccelGenerator)
|
||||
@@ -0,0 +1,81 @@
|
||||
#include <mkt_plugins/simple_goal_checker.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <angles/angles.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <cmath>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
SimpleGoalChecker::SimpleGoalChecker()
|
||||
: nh_(),
|
||||
xy_goal_tolerance_(0.25),
|
||||
yaw_goal_tolerance_(0.25),
|
||||
stateful_(true),
|
||||
check_xy_(true),
|
||||
xy_goal_tolerance_sq_(0.0625)
|
||||
{
|
||||
}
|
||||
|
||||
void SimpleGoalChecker::initialize(const robot::NodeHandle& nh)
|
||||
{
|
||||
nh_ = nh;
|
||||
this->intParam(nh);
|
||||
robot::log_info_at(__FILE__, __LINE__, "[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_);
|
||||
}
|
||||
|
||||
void SimpleGoalChecker::intParam(const robot::NodeHandle& nh)
|
||||
{
|
||||
if(!nh.param<double>("xy_goal_tolerance", xy_goal_tolerance_, 0.1))
|
||||
{
|
||||
xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1);
|
||||
}
|
||||
if(!nh.param<double>("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1))
|
||||
{
|
||||
yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1);
|
||||
}
|
||||
if(nh.param<bool>("stateful", stateful_, true))
|
||||
{
|
||||
stateful_ = robot_nav_2d_utils::searchAndGetParam(nh, "stateful", true);
|
||||
}
|
||||
robot::log_info_throttle(1.0,"[SimpleGoalChecker] xy_goal_tolerance %f yaw_goal_tolerance %f stateful %x check_xy_ %x" , xy_goal_tolerance_, yaw_goal_tolerance_, stateful_, check_xy_);
|
||||
xy_goal_tolerance_sq_ = xy_goal_tolerance_ * xy_goal_tolerance_;
|
||||
}
|
||||
|
||||
void SimpleGoalChecker::reset()
|
||||
{
|
||||
check_xy_ = true;
|
||||
}
|
||||
|
||||
bool SimpleGoalChecker::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& query_pose, const robot_nav_2d_msgs::Pose2DStamped& goal_pose,
|
||||
const robot_nav_2d_msgs::Path2D& path, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
this->intParam(nh_);
|
||||
if (check_xy_)
|
||||
{
|
||||
double dx = query_pose.pose.x - goal_pose.pose.x,
|
||||
dy = query_pose.pose.y - goal_pose.pose.y;
|
||||
if (dx * dx + dy * dy > 0.25)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// We are within the window
|
||||
// If we are stateful, change the state.
|
||||
if (stateful_)
|
||||
{
|
||||
check_xy_ = false;
|
||||
}
|
||||
}
|
||||
double dyaw = angles::shortest_angular_distance(query_pose.pose.theta, goal_pose.pose.theta);
|
||||
// robot::log_info_throttle(1.0, "dyaw %f yaw_goal_tolerance_ %f", fabs(dyaw), yaw_goal_tolerance_);
|
||||
return fabs(dyaw) < yaw_goal_tolerance_;
|
||||
}
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
score_algorithm::GoalChecker::Ptr mkt_plugins::SimpleGoalChecker::create()
|
||||
{
|
||||
return std::make_shared<mkt_plugins::SimpleGoalChecker>();
|
||||
}
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_plugins::SimpleGoalChecker::create, SimpleGoalChecker)
|
||||
@@ -0,0 +1,287 @@
|
||||
#include <mkt_plugins/standard_traj_generator.h>
|
||||
#include <mkt_plugins/xy_theta_iterator.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using robot_nav_2d_utils::loadParameterWithDeprecation;
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
|
||||
StandardTrajectoryGenerator::StandardTrajectoryGenerator()
|
||||
: nh_kinematics_(),
|
||||
kinematics_(nullptr),
|
||||
velocity_iterator_(nullptr),
|
||||
sim_time_(0.0),
|
||||
discretize_by_time_(false),
|
||||
time_granularity_(0.0),
|
||||
linear_granularity_(0.0),
|
||||
angular_granularity_(0.0),
|
||||
include_last_point_(false)
|
||||
{
|
||||
}
|
||||
|
||||
StandardTrajectoryGenerator::~StandardTrajectoryGenerator()
|
||||
{
|
||||
}
|
||||
|
||||
void StandardTrajectoryGenerator::initialize(const robot::NodeHandle &nh)
|
||||
{
|
||||
nh_kinematics_ = nh;
|
||||
kinematics_ = std::make_shared<mkt_plugins::KinematicParameters>();
|
||||
kinematics_->initialize(nh);
|
||||
initializeIterator(nh);
|
||||
|
||||
nh.param("sim_time", sim_time_, 1.7);
|
||||
|
||||
nh.param("include_last_point", include_last_point_, true);
|
||||
/*
|
||||
* If discretize_by_time, then sim_granularity represents the amount of time that should be between
|
||||
* two successive points on the trajectory.
|
||||
*
|
||||
* If discretize_by_time is false, then sim_granularity is the maximum amount of distance between
|
||||
* two successive points on the trajectory, and angular_sim_granularity is the maximum amount of
|
||||
* angular distance between two successive points.
|
||||
*/
|
||||
nh.param("discretize_by_time", discretize_by_time_, false);
|
||||
if (discretize_by_time_)
|
||||
{
|
||||
time_granularity_ = loadParameterWithDeprecation(nh, "time_granularity", "sim_granularity", 0.025);
|
||||
}
|
||||
else
|
||||
{
|
||||
linear_granularity_ = loadParameterWithDeprecation(nh, "linear_granularity", "sim_granularity", 0.025);
|
||||
angular_granularity_ = loadParameterWithDeprecation(nh, "angular_granularity", "angular_sim_granularity", 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
robot::NodeHandle StandardTrajectoryGenerator::getNodeHandle()
|
||||
{
|
||||
return nh_kinematics_;
|
||||
}
|
||||
|
||||
void StandardTrajectoryGenerator::initializeIterator(const robot::NodeHandle &nh)
|
||||
{
|
||||
velocity_iterator_ = std::make_shared<mkt_plugins::XYThetaIterator>();
|
||||
velocity_iterator_->initialize(nh, kinematics_);
|
||||
}
|
||||
|
||||
void StandardTrajectoryGenerator::setDirect(int *direct)
|
||||
{
|
||||
kinematics_->setDirect(direct);
|
||||
}
|
||||
|
||||
bool StandardTrajectoryGenerator::setTwistLinear(robot_geometry_msgs::Vector3 linear)
|
||||
{
|
||||
try
|
||||
{
|
||||
// ROS_INFO("Get linear %f ", linear.x);
|
||||
if (linear.x > 0)
|
||||
kinematics_->setMaxX(linear.x);
|
||||
else if (linear.x < 0)
|
||||
kinematics_->setMinX(linear.x);
|
||||
else
|
||||
{
|
||||
kinematics_->setMinX(linear.x);
|
||||
kinematics_->setMaxX(linear.x);
|
||||
}
|
||||
|
||||
if (linear.y > 0)
|
||||
kinematics_->setMaxY(linear.y);
|
||||
else if (linear.y < 0)
|
||||
kinematics_->setMinY(linear.y);
|
||||
else
|
||||
{
|
||||
kinematics_->setMinY(linear.y);
|
||||
kinematics_->setMaxY(linear.y);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw std::exception(e);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistLinear(bool direct)
|
||||
{
|
||||
robot_geometry_msgs::Vector3 linear;
|
||||
try
|
||||
{
|
||||
if (direct)
|
||||
{
|
||||
linear.x = kinematics_->getMaxX();
|
||||
linear.y = kinematics_->getMaxY();
|
||||
}
|
||||
else
|
||||
{
|
||||
linear.x = kinematics_->getMinX();
|
||||
linear.y = kinematics_->getMinY();
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw std::exception(e);
|
||||
}
|
||||
return linear;
|
||||
}
|
||||
|
||||
bool StandardTrajectoryGenerator::setTwistAngular(robot_geometry_msgs::Vector3 angular)
|
||||
{
|
||||
try
|
||||
{
|
||||
kinematics_->setMaxTheta(angular.z);
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw std::exception(e);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Vector3 StandardTrajectoryGenerator::getTwistAngular(bool direct)
|
||||
{
|
||||
robot_geometry_msgs::Vector3 angular;
|
||||
try
|
||||
{
|
||||
if (direct)
|
||||
{
|
||||
angular.z = kinematics_->getMaxTheta();
|
||||
}
|
||||
else
|
||||
{
|
||||
angular.z = kinematics_->getMinTheta();
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw std::exception(e);
|
||||
}
|
||||
return angular;
|
||||
}
|
||||
|
||||
void StandardTrajectoryGenerator::startNewIteration(const robot_nav_2d_msgs::Twist2D ¤t_velocity)
|
||||
{
|
||||
velocity_iterator_->startNewIteration(current_velocity, sim_time_);
|
||||
}
|
||||
|
||||
bool StandardTrajectoryGenerator::hasMoreTwists()
|
||||
{
|
||||
return velocity_iterator_->hasMoreTwists();
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::nextTwist()
|
||||
{
|
||||
return velocity_iterator_->nextTwist();
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::getTwist()
|
||||
{
|
||||
return velocity_iterator_->getTwist();
|
||||
}
|
||||
|
||||
std::vector<double> StandardTrajectoryGenerator::getTimeSteps(const robot_nav_2d_msgs::Twist2D &cmd_vel)
|
||||
{
|
||||
std::vector<double> steps;
|
||||
if (discretize_by_time_)
|
||||
{
|
||||
steps.resize(ceil(sim_time_ / time_granularity_));
|
||||
}
|
||||
else // discretize by distance
|
||||
{
|
||||
double vmag = hypot(cmd_vel.x, cmd_vel.y);
|
||||
|
||||
// the distance the robot would travel in sim_time if it did not change velocity
|
||||
double projected_linear_distance = vmag * sim_time_;
|
||||
|
||||
// the angle the robot would rotate in sim_time
|
||||
double projected_angular_distance = fabs(cmd_vel.theta) * sim_time_;
|
||||
|
||||
// Pick the maximum of the two
|
||||
int num_steps = ceil(std::max(projected_linear_distance / linear_granularity_,
|
||||
projected_angular_distance / angular_granularity_));
|
||||
steps.resize(num_steps);
|
||||
}
|
||||
if (steps.size() == 0)
|
||||
{
|
||||
steps.resize(1);
|
||||
}
|
||||
std::fill(steps.begin(), steps.end(), sim_time_ / steps.size());
|
||||
return steps;
|
||||
}
|
||||
|
||||
mkt_msgs::Trajectory2D StandardTrajectoryGenerator::generateTrajectory(const robot_nav_2d_msgs::Pose2DStamped &start_pose,
|
||||
const robot_nav_2d_msgs::Path2D &transformed_plan,
|
||||
const robot_nav_2d_msgs::Twist2D &start_vel,
|
||||
const robot_nav_2d_msgs::Twist2D &cmd_vel)
|
||||
{
|
||||
mkt_msgs::Trajectory2D traj;
|
||||
traj.velocity = cmd_vel;
|
||||
|
||||
// simulate the trajectory
|
||||
robot_geometry_msgs::Pose2D pose = start_pose.pose;
|
||||
robot_nav_2d_msgs::Twist2D vel = start_vel;
|
||||
double running_time = 0.0;
|
||||
std::vector<double> steps = getTimeSteps(cmd_vel);
|
||||
|
||||
for (double dt : steps)
|
||||
{
|
||||
traj.poses.push_back(pose);
|
||||
traj.time_offsets.push_back(robot::Duration(running_time));
|
||||
// calculate velocities
|
||||
vel = computeNewVelocity(cmd_vel, vel, dt);
|
||||
|
||||
// update the position of the robot using the velocities passed in
|
||||
pose = computeNewPosition(pose, vel, dt);
|
||||
running_time += dt;
|
||||
} // end for simulation steps
|
||||
|
||||
if (include_last_point_)
|
||||
{
|
||||
traj.poses.push_back(pose);
|
||||
traj.time_offsets.push_back(robot::Duration(running_time));
|
||||
}
|
||||
|
||||
return traj;
|
||||
}
|
||||
|
||||
/**
|
||||
* change vel using acceleration limits to converge towards sample_target-vel
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2D StandardTrajectoryGenerator::computeNewVelocity(const robot_nav_2d_msgs::Twist2D &cmd_vel,
|
||||
const robot_nav_2d_msgs::Twist2D &start_vel, const double dt)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D new_vel;
|
||||
new_vel.x = projectVelocity(start_vel.x, kinematics_->getAccX(), kinematics_->getDecelX(), dt, cmd_vel.x);
|
||||
new_vel.y = projectVelocity(start_vel.y, kinematics_->getAccY(), kinematics_->getDecelY(), dt, cmd_vel.y);
|
||||
new_vel.theta = projectVelocity(start_vel.theta, kinematics_->getAccTheta(), kinematics_->getDecelTheta(),
|
||||
dt, cmd_vel.theta);
|
||||
return new_vel;
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Pose2D StandardTrajectoryGenerator::computeNewPosition(const robot_geometry_msgs::Pose2D start_pose,
|
||||
const robot_nav_2d_msgs::Twist2D &vel, const double dt)
|
||||
{
|
||||
robot_geometry_msgs::Pose2D new_pose;
|
||||
new_pose.x = start_pose.x + (vel.x * cos(start_pose.theta) + vel.y * cos(M_PI_2 + start_pose.theta)) * dt;
|
||||
new_pose.y = start_pose.y + (vel.x * sin(start_pose.theta) + vel.y * sin(M_PI_2 + start_pose.theta)) * dt;
|
||||
new_pose.theta = start_pose.theta + vel.theta * dt;
|
||||
return new_pose;
|
||||
}
|
||||
|
||||
score_algorithm::TrajectoryGenerator::Ptr StandardTrajectoryGenerator::create()
|
||||
{
|
||||
return std::make_shared<StandardTrajectoryGenerator>();
|
||||
}
|
||||
} // namespace mkt_plugins
|
||||
|
||||
BOOST_DLL_ALIAS(mkt_plugins::StandardTrajectoryGenerator::create, StandardTrajectoryGenerator)
|
||||
@@ -0,0 +1,92 @@
|
||||
#include <mkt_plugins/xy_theta_iterator.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <memory>
|
||||
|
||||
namespace mkt_plugins
|
||||
{
|
||||
XYThetaIterator::XYThetaIterator()
|
||||
: vx_samples_(0),
|
||||
vy_samples_(0),
|
||||
vtheta_samples_(0),
|
||||
kinematics_(nullptr),
|
||||
x_it_(nullptr),
|
||||
y_it_(nullptr),
|
||||
th_it_(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
XYThetaIterator::~XYThetaIterator()
|
||||
{
|
||||
}
|
||||
|
||||
void XYThetaIterator::initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics)
|
||||
{
|
||||
kinematics_ = kinematics;
|
||||
nh.param("vx_samples", vx_samples_, 20);
|
||||
nh.param("vy_samples", vy_samples_, 5);
|
||||
vtheta_samples_ = robot_nav_2d_utils::loadParameterWithDeprecation(nh, "vtheta_samples", "vth_samples", 20);
|
||||
}
|
||||
|
||||
void XYThetaIterator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt)
|
||||
{
|
||||
x_it_ = std::make_shared<OneDVelocityIterator>("x_it_", current_velocity.x, kinematics_->getDirect()[0], kinematics_->getMinX(), kinematics_->getMaxX(),
|
||||
kinematics_->getAccX(), kinematics_->getDecelX(), dt, vx_samples_);
|
||||
|
||||
y_it_ = std::make_shared<OneDVelocityIterator>("y_it_", current_velocity.y, kinematics_->getDirect()[1], kinematics_->getMinY(), kinematics_->getMaxY(),
|
||||
kinematics_->getAccY(), kinematics_->getDecelY(), dt, vy_samples_);
|
||||
|
||||
th_it_ = std::make_shared<OneDVelocityIterator>("th_it_", current_velocity.theta, kinematics_->getDirect()[2], kinematics_->getMinTheta(), kinematics_->getMaxTheta(),
|
||||
kinematics_->getAccTheta(), kinematics_->getDecelTheta(), dt, vtheta_samples_);
|
||||
}
|
||||
|
||||
bool XYThetaIterator::hasMoreTwists()
|
||||
{
|
||||
return x_it_ && !x_it_->isFinished();
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2D XYThetaIterator::nextTwist()
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D velocity;
|
||||
velocity.x = x_it_->getVelocity();
|
||||
velocity.y = y_it_->getVelocity();
|
||||
velocity.theta = th_it_->getVelocity();
|
||||
iterateToValidVelocity();
|
||||
return velocity;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2D XYThetaIterator::getTwist()
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D velocity;
|
||||
velocity.x = x_it_->getVelocity();
|
||||
velocity.y = y_it_->getVelocity();
|
||||
velocity.theta = th_it_->getVelocity();
|
||||
return velocity;
|
||||
}
|
||||
|
||||
bool XYThetaIterator::isValidVelocity()
|
||||
{
|
||||
return kinematics_->isValidSpeed(x_it_->getVelocity(), y_it_->getVelocity(), th_it_->getVelocity());
|
||||
}
|
||||
|
||||
void XYThetaIterator::iterateToValidVelocity()
|
||||
{
|
||||
bool valid = false;
|
||||
while (!valid && hasMoreTwists())
|
||||
{
|
||||
++(*th_it_);
|
||||
if (th_it_->isFinished())
|
||||
{
|
||||
th_it_->reset();
|
||||
++(*y_it_);
|
||||
if (y_it_->isFinished())
|
||||
{
|
||||
y_it_->reset();
|
||||
++(*x_it_);
|
||||
}
|
||||
}
|
||||
valid = isValidVelocity();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace mkt_plugins
|
||||
|
||||
Submodule src/Algorithms/Packages/actions/dock_pattern_action added at 302dd113f3
Submodule src/Algorithms/Packages/global_planners/custom_planner added at 6eed3d8772
Submodule src/Algorithms/Packages/global_planners/dock_planner added at 1f04a95e1b
Submodule src/Algorithms/Packages/global_planners/sbpl_lattice_planner added at 6fbc29f6d8
176
src/Algorithms/Packages/global_planners/two_points_planner/CMakeLists.txt
Executable file
176
src/Algorithms/Packages/global_planners/two_points_planner/CMakeLists.txt
Executable file
@@ -0,0 +1,176 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(two_points_planner VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building two_points_planner with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building two_points_planner with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS filesystem system)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
robot_costmap_2d
|
||||
robot_nav_core
|
||||
robot_geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
tf3
|
||||
robot_tf3_geometry_msgs
|
||||
robot_time
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_costmap_2d
|
||||
robot_nav_core
|
||||
robot_geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_tf3_geometry_msgs
|
||||
robot_time
|
||||
robot_cpp
|
||||
)
|
||||
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME}
|
||||
CATKIN_DEPENDS robot_costmap_2d robot_nav_core robot_geometry_msgs robot_nav_msgs robot_tf3_geometry_msgs robot_time robot_cpp
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/two_points_planner.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::filesystem Boost::system
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::filesystem Boost::system
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME}
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Dependencies: robot_costmap_2d, robot_nav_core, robot_geometry_msgs, robot_nav_msgs, tf3, robot_tf3_geometry_msgs, robot_time, robot_cpp, Boost")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
@@ -0,0 +1,83 @@
|
||||
|
||||
#ifndef TWO_POINTS_PLANNER_H_INCLUDED
|
||||
#define TWO_POINTS_PLANNER_H_INCLUDED
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <robot_geometry_msgs/PoseStamped.h>
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
#include <robot/robot.h>
|
||||
|
||||
namespace two_points_planner
|
||||
{
|
||||
|
||||
/**
|
||||
* @class TwoPointsPlanner
|
||||
* @brief Plugin-based flexible global_planner
|
||||
*/
|
||||
class TwoPointsPlanner : public robot_nav_core::BaseGlobalPlanner
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Default constructor for the NavFnROS object
|
||||
*/
|
||||
TwoPointsPlanner();
|
||||
|
||||
virtual ~TwoPointsPlanner(){};
|
||||
|
||||
/**
|
||||
* @brief Constructor for the TwoPointsPlanner object
|
||||
* @param name The name of this planner
|
||||
* @param costmap_robot A pointer to the ROS wrapper of the costmap to use
|
||||
*/
|
||||
TwoPointsPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot);
|
||||
|
||||
/**
|
||||
* @brief Initialization function for the TwoPointsPlanner object
|
||||
* @param name The name of this planner
|
||||
* @param costmap_robot A pointer to the ROS wrapper of the costmap to use
|
||||
*/
|
||||
virtual bool initialize(std::string name,
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_robot);
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
virtual bool makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
std::vector<robot_geometry_msgs::PoseStamped>& plan);
|
||||
|
||||
/**
|
||||
* @brief Create a new TwoPointsPlanner instance
|
||||
* @return A pointer to the new TwoPointsPlanner instance
|
||||
*/
|
||||
static robot_nav_core::BaseGlobalPlanner::Ptr create();
|
||||
|
||||
protected:
|
||||
|
||||
unsigned char computeCircumscribedCost();
|
||||
unsigned char costMapCostToSBPLCost(unsigned char newcost);
|
||||
|
||||
bool initialized_;
|
||||
unsigned char lethal_obstacle_;
|
||||
unsigned char inscribed_inflated_obstacle_;
|
||||
unsigned char circumscribed_cost_;
|
||||
|
||||
bool allow_unknown_;
|
||||
|
||||
std::string name_;
|
||||
robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< manages the cost map for us */
|
||||
std::vector<robot_geometry_msgs::Point> footprint_;
|
||||
unsigned int current_env_width_;
|
||||
unsigned int current_env_height_;
|
||||
|
||||
};
|
||||
|
||||
} // namespace two_points_planner
|
||||
|
||||
#endif // TWO_POINTS_PLANNER_H_INCLUDED
|
||||
@@ -0,0 +1,52 @@
|
||||
<package>
|
||||
<name>two_points_planner</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
two_points_planner is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. two_points_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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/two_points_planner</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>robot_costmap_2d</build_depend>
|
||||
<run_depend>robot_costmap_2d</run_depend>
|
||||
|
||||
<build_depend>robot_nav_core</build_depend>
|
||||
<run_depend>robot_nav_core</run_depend>
|
||||
|
||||
<build_depend>robot_geometry_msgs</build_depend>
|
||||
<run_depend>robot_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_msgs</build_depend>
|
||||
<run_depend>robot_nav_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
|
||||
|
||||
|
||||
|
||||
<build_depend>robot_tf3_geometry_msgs</build_depend>
|
||||
<run_depend>robot_tf3_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_time</build_depend>
|
||||
<run_depend>robot_time</run_depend>
|
||||
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
|
||||
</package>
|
||||
@@ -0,0 +1,246 @@
|
||||
#include <robot/robot.h>
|
||||
#include <two_points_planner/two_points_planner.h>
|
||||
#include <robot_costmap_2d/inflation_layer.h>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <tf3/LinearMath/Quaternion.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
namespace two_points_planner
|
||||
{
|
||||
TwoPointsPlanner::TwoPointsPlanner()
|
||||
: initialized_(false),
|
||||
lethal_obstacle_(0),
|
||||
inscribed_inflated_obstacle_(0),
|
||||
circumscribed_cost_(0),
|
||||
allow_unknown_(false),
|
||||
costmap_robot_(nullptr),
|
||||
current_env_width_(0),
|
||||
current_env_height_(0)
|
||||
{
|
||||
}
|
||||
|
||||
TwoPointsPlanner::TwoPointsPlanner(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot)
|
||||
: initialized_(false), costmap_robot_(NULL)
|
||||
{
|
||||
initialize(name, costmap_robot);
|
||||
}
|
||||
|
||||
bool TwoPointsPlanner::initialize(std::string name, robot_costmap_2d::Costmap2DROBOT* costmap_robot)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
robot::NodeHandle nh_priv_("~/" + name);
|
||||
int lethal_obstacle;
|
||||
nh_priv_.getParam("lethal_obstacle", lethal_obstacle, 20);
|
||||
lethal_obstacle_ = (unsigned char)lethal_obstacle;
|
||||
inscribed_inflated_obstacle_ = lethal_obstacle_ - 1;
|
||||
|
||||
nh_priv_.getParam("allow_unknown", allow_unknown_, true);
|
||||
|
||||
name_ = name;
|
||||
costmap_robot_ = costmap_robot;
|
||||
|
||||
|
||||
|
||||
if(!costmap_robot_ || !costmap_robot_->getCostmap())
|
||||
{
|
||||
robot::log_warning("[%s:%d]TwoPointsPlanner Initialized failed", __FILE__, __LINE__);
|
||||
return false;
|
||||
}
|
||||
current_env_width_ = costmap_robot_->getCostmap()->getSizeInCellsX();
|
||||
current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY();
|
||||
footprint_ = costmap_robot_->getRobotFootprint();
|
||||
|
||||
robot::log_info("size x: %d, size y: %d, resolution: %f", costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY(), costmap_robot_->getCostmap()->getResolution());
|
||||
|
||||
robot::log_info("TwoPointsPlanner Initialized successfully");
|
||||
initialized_ = true;
|
||||
return true;
|
||||
}
|
||||
robot::log_info("[%s:%d]\n TwoPointsPlanner: Already initialized", __FILE__, __LINE__);
|
||||
return true;
|
||||
}
|
||||
|
||||
unsigned char TwoPointsPlanner::computeCircumscribedCost()
|
||||
{
|
||||
unsigned char result = 0;
|
||||
|
||||
|
||||
if (!costmap_robot_)
|
||||
{
|
||||
std::cerr << "TwoPointsPlanner: Costmap is not initialized" << std::endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Bug
|
||||
// // check if the costmap has an inflation layer
|
||||
// for (std::vector<boost::shared_ptr<robot_costmap_2d::Layer>>::const_iterator layer = costmap_robot_->getLayeredCostmap()->getPlugins()->begin();
|
||||
// layer != costmap_robot_->getLayeredCostmap()->getPlugins()->end();
|
||||
// ++layer)
|
||||
// {
|
||||
// boost::shared_ptr<robot_costmap_2d::InflationLayer> inflation_layer = boost::dynamic_pointer_cast<robot_costmap_2d::InflationLayer>(*layer);
|
||||
// if (!inflation_layer)
|
||||
// continue;
|
||||
|
||||
// result = costMapCostToSBPLCost(inflation_layer->computeCost(costmap_robot_->getLayeredCostmap()->getCircumscribedRadius() / costmap_robot_->getCostmap()->getResolution()));
|
||||
// }
|
||||
return result;
|
||||
}
|
||||
|
||||
// Taken from Sachin's sbpl_cart_planner
|
||||
// This rescales the costmap according to a rosparam which sets the obstacle cost
|
||||
unsigned char TwoPointsPlanner::costMapCostToSBPLCost(unsigned char newcost)
|
||||
{
|
||||
if (newcost == robot_costmap_2d::LETHAL_OBSTACLE || (!allow_unknown_ && newcost == robot_costmap_2d::NO_INFORMATION))
|
||||
return lethal_obstacle_;
|
||||
else if (newcost == robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
|
||||
return inscribed_inflated_obstacle_;
|
||||
else if (newcost == 0)
|
||||
return 0;
|
||||
else if (newcost == robot_costmap_2d::NO_INFORMATION)
|
||||
return robot_costmap_2d::FREE_SPACE;
|
||||
else
|
||||
{
|
||||
unsigned char cost = newcost;
|
||||
if (cost == 0)
|
||||
cost = 1;
|
||||
return cost;
|
||||
}
|
||||
}
|
||||
|
||||
bool TwoPointsPlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
|
||||
const robot_geometry_msgs::PoseStamped& goal,
|
||||
std::vector<robot_geometry_msgs::PoseStamped>& plan)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
robot::log_error("[%s:%d]\n TwoPointsPlanner: Global planner is not initialized", __FILE__, __LINE__);
|
||||
return false;
|
||||
}
|
||||
|
||||
robot::Time start_time = robot::Time::now();
|
||||
robot::Rate rate(1.0);
|
||||
while(costmap_robot_->getCostmap()->getSizeInCellsX() == 0 || costmap_robot_->getCostmap()->getSizeInCellsY() == 0){
|
||||
robot::log_warning("Waiting for costmap to be initialized...");
|
||||
rate.sleep();
|
||||
if((robot::Time::now() - start_time).toSec() > 5.0){
|
||||
robot::log_error("Costmap not initialized after 10 seconds, exiting...");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped start_2d = robot_nav_2d_utils::poseStampedToPose2D(start);
|
||||
robot_nav_2d_msgs::Pose2DStamped goal_2d = robot_nav_2d_utils::poseStampedToPose2D(goal);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Making plan from start (%.2f,%.2f,%.2f) to goal (%.2f,%.2f,%.2f)",
|
||||
start_2d.pose.x, start_2d.pose.y, start_2d.pose.theta, goal_2d.pose.x, goal_2d.pose.y, goal_2d.pose.theta);
|
||||
|
||||
bool do_init = false;
|
||||
if (current_env_width_ != costmap_robot_->getCostmap()->getSizeInCellsX() ||
|
||||
current_env_height_ != costmap_robot_->getCostmap()->getSizeInCellsY())
|
||||
{
|
||||
robot::log_warning("[%s:%d]\n TwoPointsPlanner: Costmap dimensions have changed from (%u x %u) to (%u x %u), reinitializing two_points_planner.", __FILE__, __LINE__,
|
||||
current_env_width_, current_env_height_,
|
||||
costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY());
|
||||
do_init = true;
|
||||
}
|
||||
else if (footprint_ != costmap_robot_->getRobotFootprint())
|
||||
{
|
||||
robot::log_warning("[%s:%d]\n TwoPointsPlanner: Robot footprint has changed, reinitializing two_points_planner.", __FILE__, __LINE__);
|
||||
do_init = true;
|
||||
}
|
||||
|
||||
if (do_init)
|
||||
{
|
||||
initialized_ = false;
|
||||
initialize(name_, costmap_robot_);
|
||||
}
|
||||
|
||||
plan.clear();
|
||||
// plan.push_back(start);
|
||||
|
||||
// unsigned int mx_start, my_start;
|
||||
// unsigned int mx_end, my_end;
|
||||
// if (!costmap_robot_->getCostmap()->worldToMap(start.pose.position.x,
|
||||
// start.pose.position.y,
|
||||
// mx_start, my_start)
|
||||
|
||||
// || !costmap_robot_->getCostmap()->worldToMap(goal.pose.position.x,
|
||||
// goal.pose.position.y,
|
||||
// mx_end, my_end))
|
||||
// {
|
||||
// robot::log_error("[%s:%d]\n TwoPointsPlanner: can not convert world to Map 'start point' or 'goal point'", __FILE__, __LINE__);
|
||||
// return false;
|
||||
// }
|
||||
// unsigned char start_cost = costMapCostToSBPLCost(costmap_robot_->getCostmap()->getCost(mx_start, my_start));
|
||||
// unsigned char end_cost = costMapCostToSBPLCost(costmap_robot_->getCostmap()->getCost(mx_end, my_end));
|
||||
// if (start_cost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || start_cost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
|
||||
// || end_cost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || end_cost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))
|
||||
// {
|
||||
// robot::log_error("[%s:%d]\n TwoPointsPlanner: base_pootprint in infated obstacle", __FILE__, __LINE__);
|
||||
// return false;
|
||||
// }
|
||||
robot::Time plan_time = robot::Time::now();
|
||||
// Tính toán khoảng cách giữa điểm bắt đầu và điểm đích
|
||||
const double dx = goal.pose.position.x - start.pose.position.x;
|
||||
const double dy = goal.pose.position.y - start.pose.position.y;
|
||||
const double distance = std::sqrt(dx * dx + dy * dy);
|
||||
double theta;
|
||||
// Lấy độ phân giải của costmap
|
||||
double resolution = costmap_robot_->getCostmap()->getResolution();
|
||||
|
||||
if(fabs(dx) > 1e-9 || fabs(dy) > 1e-9)
|
||||
{
|
||||
theta = std::atan2(dy, dx);
|
||||
// tf3::Quaternion goal_quat(goal.pose.orientation.x, goal.pose.orientation.y,
|
||||
// goal.pose.orientation.z, goal.pose.orientation.w);
|
||||
// double goal_theta = tf3::getYaw(goal_quat);
|
||||
double goal_theta = robot_nav_2d_utils::poseStampedToPose2D(goal).pose.theta;
|
||||
if(cos(goal_theta - theta) < 0) theta += M_PI;
|
||||
}
|
||||
else
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped pose = start;
|
||||
pose.pose.position.x += resolution * cos(theta);
|
||||
pose.pose.position.y += resolution * sin(theta);
|
||||
plan.push_back(pose);
|
||||
plan.push_back(goal);
|
||||
return true;
|
||||
}
|
||||
// Tính số điểm cần chia
|
||||
int num_points = std::ceil(distance / resolution);
|
||||
|
||||
// Chia nhỏ tuyến đường
|
||||
for (int i = 0; i <= num_points; i++)
|
||||
{
|
||||
double fraction = static_cast<double>(i) / num_points;
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped pose2d;
|
||||
pose2d.header.stamp = plan_time;
|
||||
pose2d.header.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
pose2d.pose.x = start.pose.position.x + fraction * dx;
|
||||
pose2d.pose.y = start.pose.position.y + fraction * dy;
|
||||
pose2d.pose.theta = theta;
|
||||
|
||||
// Nội suy hướng
|
||||
robot_geometry_msgs::PoseStamped pose = robot_nav_2d_utils::pose2DToPoseStamped(pose2d);
|
||||
plan.push_back(pose);
|
||||
}
|
||||
plan.push_back(goal);
|
||||
return true;
|
||||
}
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr TwoPointsPlanner::create()
|
||||
{
|
||||
return std::make_shared<TwoPointsPlanner>();
|
||||
}
|
||||
|
||||
} // namespace two_points_planner
|
||||
|
||||
// Register this planner as a GlobalPlanner plugin
|
||||
BOOST_DLL_ALIAS(two_points_planner::TwoPointsPlanner::create, TwoPointsPlanner)
|
||||
Submodule src/Algorithms/Packages/local_planners/hybrid_local_planner added at dd7f123601
Submodule src/Algorithms/Packages/local_planners/mppi_local_planner added at 19b728f8e2
@@ -0,0 +1,244 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(pnkx_local_planner VERSION 1.0.0 LANGUAGES CXX)
|
||||
|
||||
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
|
||||
set(BUILDING_WITH_CATKIN TRUE)
|
||||
message(STATUS "Building pnkx_local_planner with Catkin")
|
||||
|
||||
else()
|
||||
set(BUILDING_WITH_CATKIN FALSE)
|
||||
message(STATUS "Building pnkx_local_planner with Standalone CMake")
|
||||
endif()
|
||||
|
||||
# C++ Standard - must be set before find_package
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# Find dependencies
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
|
||||
if (NOT BUILDING_WITH_CATKIN)
|
||||
|
||||
# Enable Position Independent Code
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
# Cấu hình RPATH để tránh cycle trong runtime search path
|
||||
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
|
||||
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
|
||||
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
|
||||
|
||||
set(PACKAGES_DIR
|
||||
robot_geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_std_msgs
|
||||
robot_visualization_msgs
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
mkt_msgs
|
||||
score_algorithm
|
||||
robot_costmap_2d
|
||||
tf3
|
||||
robot_tf3_geometry_msgs
|
||||
data_convert
|
||||
robot_cpp
|
||||
angles
|
||||
)
|
||||
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
|
||||
else()
|
||||
|
||||
# ========================================================
|
||||
# Catkin specific configuration
|
||||
# ========================================================
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
robot_geometry_msgs
|
||||
robot_nav_msgs
|
||||
robot_std_msgs
|
||||
robot_visualization_msgs
|
||||
robot_nav_2d_msgs
|
||||
robot_nav_2d_utils
|
||||
robot_nav_core2
|
||||
mkt_msgs
|
||||
score_algorithm
|
||||
robot_costmap_2d
|
||||
robot_tf3_geometry_msgs
|
||||
data_convert
|
||||
robot_cpp
|
||||
angles
|
||||
)
|
||||
|
||||
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
|
||||
find_package(Boost REQUIRED COMPONENTS system)
|
||||
|
||||
catkin_package(
|
||||
INCLUDE_DIRS include
|
||||
LIBRARIES ${PROJECT_NAME} ${PROJECT_NAME}_utils
|
||||
CATKIN_DEPENDS robot_geometry_msgs robot_nav_msgs robot_std_msgs robot_visualization_msgs robot_nav_2d_msgs robot_nav_2d_utils robot_nav_core2 mkt_msgs score_algorithm robot_costmap_2d robot_tf3_geometry_msgs data_convert robot_cpp angles
|
||||
DEPENDS Boost
|
||||
)
|
||||
|
||||
include_directories(
|
||||
include
|
||||
${catkin_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${TF3_INCLUDE_DIR}
|
||||
)
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Libraries
|
||||
# ========================================================
|
||||
# Tạo thư viện utils trước
|
||||
add_library(${PROJECT_NAME}_utils SHARED
|
||||
src/transforms.cpp
|
||||
)
|
||||
|
||||
# Tạo thư viện chính
|
||||
add_library(${PROJECT_NAME} SHARED
|
||||
src/pnkx_local_planner.cpp
|
||||
src/pnkx_go_straight_local_planner.cpp
|
||||
src/pnkx_rotate_local_planner.cpp
|
||||
src/pnkx_docking_local_planner.cpp
|
||||
)
|
||||
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
add_dependencies(${PROJECT_NAME}_utils ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_utils
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_utils
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::system
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${PROJECT_NAME}_utils
|
||||
PUBLIC ${catkin_LIBRARIES}
|
||||
PRIVATE Boost::system
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
else()
|
||||
|
||||
target_include_directories(${PROJECT_NAME}_utils
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_include_directories(${PROJECT_NAME}
|
||||
PUBLIC
|
||||
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
|
||||
$<INSTALL_INTERFACE:include>
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}_utils
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::system
|
||||
)
|
||||
|
||||
target_link_libraries(${PROJECT_NAME}
|
||||
PUBLIC ${PROJECT_NAME}_utils
|
||||
PUBLIC
|
||||
${PACKAGES_DIR}
|
||||
PRIVATE
|
||||
Boost::system
|
||||
${TF3_LIBRARY}
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME}_utils PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
|
||||
BUILD_RPATH "${CMAKE_BINARY_DIR}"
|
||||
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
|
||||
)
|
||||
|
||||
endif()
|
||||
|
||||
# ========================================================
|
||||
# Install
|
||||
# ========================================================
|
||||
if(BUILDING_WITH_CATKIN)
|
||||
## Mark libraries for installation
|
||||
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
|
||||
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils
|
||||
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
|
||||
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install plugins.xml if it exists
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml)
|
||||
install(FILES plugins.xml
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
|
||||
)
|
||||
endif()
|
||||
|
||||
else()
|
||||
|
||||
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_utils
|
||||
EXPORT ${PROJECT_NAME}-targets
|
||||
ARCHIVE DESTINATION lib
|
||||
LIBRARY DESTINATION lib
|
||||
RUNTIME DESTINATION bin
|
||||
)
|
||||
|
||||
# Export targets
|
||||
install(EXPORT ${PROJECT_NAME}-targets
|
||||
FILE ${PROJECT_NAME}-targets.cmake
|
||||
NAMESPACE ${PROJECT_NAME}::
|
||||
DESTINATION lib/cmake/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
## Mark cpp header files for installation
|
||||
install(DIRECTORY include/${PROJECT_NAME}/
|
||||
DESTINATION include
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
PATTERN ".svn" EXCLUDE
|
||||
)
|
||||
|
||||
## Install plugins.xml if it exists
|
||||
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/plugins.xml)
|
||||
install(FILES plugins.xml
|
||||
DESTINATION share/${PROJECT_NAME}
|
||||
)
|
||||
endif()
|
||||
|
||||
# Print configuration info
|
||||
message(STATUS "=================================")
|
||||
message(STATUS "Project: ${PROJECT_NAME}")
|
||||
message(STATUS "Version: ${PROJECT_VERSION}")
|
||||
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
|
||||
message(STATUS "Libraries: ${PROJECT_NAME}, ${PROJECT_NAME}_utils")
|
||||
message(STATUS "Dependencies: robot_geometry_msgs, robot_nav_msgs, robot_std_msgs, robot_visualization_msgs, robot_nav_2d_msgs, robot_nav_2d_utils, robot_nav_core2, mkt_msgs, score_algorithm, robot_costmap_2d, tf3, robot_tf3_geometry_msgs, data_convert, robot_cpp, angles, Boost")
|
||||
message(STATUS "=================================")
|
||||
endif()
|
||||
@@ -0,0 +1,182 @@
|
||||
#ifndef _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_
|
||||
#define _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_
|
||||
|
||||
#include <robot_nav_core/base_global_planner.h>
|
||||
#include <pnkx_local_planner/pnkx_local_planner.h>
|
||||
#include <robot_xmlrpcpp/XmlRpcValue.h>
|
||||
|
||||
namespace pnkx_local_planner
|
||||
{
|
||||
|
||||
/**
|
||||
* @class PNKXDockingLocalPlanner
|
||||
* @brief Plugin-based flexible local_planner
|
||||
*/
|
||||
class PNKXDockingLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor that brings up pluginlib loaders
|
||||
*/
|
||||
PNKXDockingLocalPlanner();
|
||||
|
||||
virtual ~PNKXDockingLocalPlanner();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization
|
||||
* @param name Namespace for this planner
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
void initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity
|
||||
*
|
||||
* It is presumed that the global plan is already set.
|
||||
*
|
||||
* This is mostly a wrapper for the protected computeVelocityCommands
|
||||
* function which has additional debugging info.
|
||||
*
|
||||
* @param pose Current robot pose
|
||||
* @param velocity Current robot velocity
|
||||
* @return The best command for the robot to drive
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity.
|
||||
*
|
||||
* The pose that it checks against is the last pose in the current global plan.
|
||||
* The calculation is delegated to the goal_checker plugin.
|
||||
*
|
||||
* @param pose Current pose
|
||||
* @param velocity Current velocity
|
||||
* @return True if the robot should be considered as having reached the goal.
|
||||
*/
|
||||
virtual bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new instance of the PNKXDockingLocalPlanner
|
||||
* @return A shared pointer to the new instance
|
||||
*/
|
||||
static robot_nav_core2::LocalPlanner::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization other
|
||||
*/
|
||||
void initializeOthers() override;
|
||||
|
||||
/**
|
||||
* @brief get docking maker
|
||||
*/
|
||||
void getMaker();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 reset other
|
||||
*/
|
||||
void reset() override;
|
||||
|
||||
/**
|
||||
* @brief get parameters
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
void getParams(robot::NodeHandle &nh) override;
|
||||
|
||||
/**
|
||||
* @brief Helper method for preparing for the core scoring algorithm
|
||||
*
|
||||
* Runs the prepare method on all the critics with freshly transformed data
|
||||
*/
|
||||
virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Iterate through all the twists and find the best one
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
private:
|
||||
class DockingPlanner
|
||||
{
|
||||
public:
|
||||
DockingPlanner(const std::string &name);
|
||||
~DockingPlanner();
|
||||
|
||||
/**
|
||||
* @brief initialization
|
||||
* @param name Namespace for maker
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
void initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot,
|
||||
score_algorithm::TrajectoryGenerator::Ptr traj_generator);
|
||||
|
||||
bool getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal);
|
||||
|
||||
bool geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal);
|
||||
|
||||
bool getLocalPath(const robot_nav_2d_msgs::Pose2DStamped &local_pose,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path);
|
||||
|
||||
bool initialized_;
|
||||
bool is_detected_;
|
||||
bool is_goal_reached_;
|
||||
bool following_;
|
||||
bool allow_rotate_;
|
||||
|
||||
double xy_goal_tolerance_;
|
||||
double yaw_goal_tolerance_;
|
||||
double min_lookahead_dist_;
|
||||
double max_lookahead_dist_;
|
||||
double lookahead_time_;
|
||||
double angle_threshold_;
|
||||
|
||||
std::string name_;
|
||||
std::string docking_planner_name_;
|
||||
std::string docking_nav_name_;
|
||||
|
||||
robot_nav_core::BaseGlobalPlanner::Ptr docking_planner_;
|
||||
score_algorithm::ScoreAlgorithm::Ptr docking_nav_;
|
||||
|
||||
robot_geometry_msgs::Vector3 linear_;
|
||||
robot_geometry_msgs::Vector3 angular_;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Callback wall timer for detect timeout
|
||||
*/
|
||||
virtual void detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event);
|
||||
|
||||
/**
|
||||
* @brief Callback wall timer for delay
|
||||
*/
|
||||
virtual void delayCb(const ::robot::WallTimerEvent &timer_event);
|
||||
|
||||
robot::NodeHandle nh_, nh_priv_;
|
||||
TFListenerPtr tf_;
|
||||
robot_costmap_2d::Costmap2DROBOT *costmap_robot_;
|
||||
score_algorithm::TrajectoryGenerator::Ptr traj_generator_;
|
||||
std::function<robot_nav_core::BaseGlobalPlanner::Ptr()> docking_planner_loader_;
|
||||
std::function<score_algorithm::ScoreAlgorithm::Ptr()> docking_nav_loader_;
|
||||
|
||||
robot::WallTimer detected_timeout_wt_, delayed_wt_;
|
||||
bool delayed_;
|
||||
bool detected_timeout_;
|
||||
std::string robot_base_frame_, maker_goal_frame_;
|
||||
};
|
||||
|
||||
bool start_docking_;
|
||||
double original_xy_goal_tolerance_, original_yaw_goal_tolerance_;
|
||||
robot_xmlrpcpp::XmlRpcValue original_papams_;
|
||||
std::vector<DockingPlanner*> dkpl_;
|
||||
|
||||
bool dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity);
|
||||
|
||||
}; // PNKXDockingLocalPlanner
|
||||
|
||||
} // namespace pnkx_local_planner
|
||||
|
||||
#endif // _PNKX_DOCKING_LOCAL_PLANNER_H_INCLUDED_
|
||||
@@ -0,0 +1,85 @@
|
||||
#ifndef _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_
|
||||
#define _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_
|
||||
|
||||
#include <pnkx_local_planner/pnkx_local_planner.h>
|
||||
|
||||
namespace pnkx_local_planner
|
||||
{
|
||||
/**
|
||||
* @class PNKXGoStraightLocalPlanner
|
||||
* @brief Plugin-based flexible local_planner
|
||||
*/
|
||||
class PNKXGoStraightLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor that brings up pluginlib loaders
|
||||
*/
|
||||
PNKXGoStraightLocalPlanner();
|
||||
|
||||
virtual ~PNKXGoStraightLocalPlanner();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization
|
||||
* @param name Namespace for this planner
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
void initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity
|
||||
*
|
||||
* It is presumed that the global plan is already set.
|
||||
*
|
||||
* This is mostly a wrapper for the protected computeVelocityCommands
|
||||
* function which has additional debugging info.
|
||||
*
|
||||
* @param pose Current robot pose
|
||||
* @param velocity Current robot velocity
|
||||
* @return The best command for the robot to drive
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity.
|
||||
*
|
||||
* The pose that it checks against is the last pose in the current global plan.
|
||||
* The calculation is delegated to the goal_checker plugin.
|
||||
*
|
||||
* @param pose Current pose
|
||||
* @param velocity Current velocity
|
||||
* @return True if the robot should be considered as having reached the goal.
|
||||
*/
|
||||
bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new instance of the PNKXGoStraightLocalPlanner
|
||||
* @return A shared pointer to the new instance
|
||||
*/
|
||||
static robot_nav_core2::LocalPlanner::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief robot_nav_core2 reset other
|
||||
*/
|
||||
virtual void reset() override;;
|
||||
|
||||
/**
|
||||
* @brief Helper method for preparing for the core scoring algorithm
|
||||
*
|
||||
* Runs the prepare method on all the critics with freshly transformed data
|
||||
*/
|
||||
void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Iterate through all the twists and find the best one
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
};
|
||||
|
||||
} // namespace pnkx_local_planner
|
||||
#endif // _PNKX_GO_STRAIGHT_LOCAL_PLANNER_H_INCLUDED_
|
||||
@@ -0,0 +1,212 @@
|
||||
#ifndef _PNKX_LOCAL_PLANNER_H_INCLUDED_
|
||||
#define _PNKX_LOCAL_PLANNER_H_INCLUDED_
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_nav_core2/local_planner.h>
|
||||
#include <score_algorithm/trajectory_generator.h>
|
||||
#include <score_algorithm/score_algorithm.h>
|
||||
#include <score_algorithm/goal_checker.h>
|
||||
#include <pnkx_local_planner/transforms.h>
|
||||
|
||||
namespace pnkx_local_planner
|
||||
{
|
||||
|
||||
/**
|
||||
* @class PNKXLocalPlanner
|
||||
* @brief Plugin-based flexible local_planner
|
||||
*/
|
||||
class PNKXLocalPlanner : public robot_nav_core2::LocalPlanner
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor that brings up pluginlib loaders
|
||||
*/
|
||||
PNKXLocalPlanner();
|
||||
|
||||
virtual ~PNKXLocalPlanner();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization
|
||||
* @param name Namespace for this planner
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
void initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 setGoalPose - Sets the global goal pose
|
||||
* @param goal_pose The Goal Pose
|
||||
*/
|
||||
void setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 setPlan - Sets the global plan
|
||||
* @param path The global plan
|
||||
*/
|
||||
void setPlan(const robot_nav_2d_msgs::Path2D &path) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 getPlan - Gets the current global plan
|
||||
* @param path The global plan
|
||||
*/
|
||||
void getPlan(robot_nav_2d_msgs::Path2D &path) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 getGlobalPlan - Gets the current global plan
|
||||
* @param path The global plan
|
||||
*/
|
||||
void getGlobalPlan(robot_nav_2d_msgs::Path2D &path) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity
|
||||
*
|
||||
* It is presumed that the global plan is already set.
|
||||
*
|
||||
* This is mostly a wrapper for the protected computeVelocityCommands
|
||||
* function which has additional debugging info.
|
||||
*
|
||||
* @param pose Current robot pose
|
||||
* @param velocity Current robot velocity
|
||||
* @return The best command for the robot to drive
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief set velocity for x, y asix of the robot
|
||||
* @param linear the velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
bool setTwistLinear(robot_geometry_msgs::Vector3 linear) override;
|
||||
|
||||
/**
|
||||
* @brief get velocity for x, y asix of the robot
|
||||
* @param linear The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistLinear(bool direct) override;
|
||||
|
||||
/**
|
||||
* @brief Set velocity theta for z asix of the robot
|
||||
* @param angular the command velocity
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual bool setTwistAngular(robot_geometry_msgs::Vector3 angular) override;
|
||||
|
||||
/**
|
||||
* @brief Get velocity theta for z asix of the robot
|
||||
* @param direct The velocity command
|
||||
* @return True if set is done, false otherwise
|
||||
*/
|
||||
virtual robot_geometry_msgs::Vector3 getTwistAngular(bool direct) override;
|
||||
|
||||
/**
|
||||
* @brief Check if the kinematic parameters are currently locked
|
||||
* @return True if the kinematic parameters are locked, false otherwise
|
||||
*
|
||||
* This function indicates whether the kinematic parameters (e.g., velocities, accelerations, or direction settings) are in a locked state, preventing modifications. If the parameters are locked during in-place rotation, it could prevent updates to the direction or velocity, potentially causing inconsistencies in motion commands that lead to odometry errors and localization jumps in AMCL.
|
||||
*/
|
||||
virtual bool islock() override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity.
|
||||
*
|
||||
* The pose that it checks against is the last pose in the current global plan.
|
||||
* The calculation is delegated to the goal_checker plugin.
|
||||
*
|
||||
* @param pose Current pose
|
||||
* @param velocity Current velocity
|
||||
* @return True if the robot should be considered as having reached the goal.
|
||||
*/
|
||||
bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new PNKXLocalPlanner
|
||||
* @return A shared pointer to the new PNKXLocalPlanner
|
||||
*/
|
||||
static robot_nav_core2::LocalPlanner::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief Lock the kinematic parameters to prevent modifications
|
||||
*
|
||||
* This function sets the kinematic parameters to a locked state, ensuring that values such as direction (xytheta_direct), velocities, or accelerations cannot be changed until unlocked. Locking during critical operations like in-place rotation may stabilize motion commands but could cause issues if the lock persists too long, preventing necessary updates to odometry data used by AMCL.
|
||||
*/
|
||||
virtual void lock();
|
||||
|
||||
/**
|
||||
* @brief Unlock the kinematic parameters to allow modifications
|
||||
*
|
||||
* This function releases the lock on kinematic parameters, allowing changes to values such as direction, velocities, or accelerations. If the parameters are unlocked prematurely during in-place rotation, sudden changes to motion parameters (e.g., theta direction) could lead to odometry discontinuities, contributing to localization jumps in AMCL.
|
||||
*/
|
||||
virtual void unlock();
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization other
|
||||
*/
|
||||
virtual void initializeOthers();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 reset other
|
||||
*/
|
||||
virtual void reset();
|
||||
|
||||
/**
|
||||
* @brief Get parameters
|
||||
* @param nh NodeHandle to read parameters from
|
||||
*/
|
||||
virtual void getParams(robot::NodeHandle &nh);
|
||||
|
||||
/**
|
||||
* @brief Helper method for preparing for the core scoring algorithm
|
||||
*
|
||||
* Runs the prepare method on all the critics with freshly transformed data
|
||||
*/
|
||||
virtual void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity);
|
||||
|
||||
/**
|
||||
* @brief Iterate through all the twists and find the best one
|
||||
*/
|
||||
virtual robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity);
|
||||
|
||||
/**
|
||||
* @brief Helper method to transform a given pose to the local costmap frame.
|
||||
*/
|
||||
robot_nav_2d_msgs::Pose2DStamped transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose);
|
||||
|
||||
// Plugin handling
|
||||
std::function<score_algorithm::TrajectoryGenerator::Ptr()> traj_gen_loader_;
|
||||
score_algorithm::TrajectoryGenerator::Ptr traj_generator_;
|
||||
|
||||
std::function<score_algorithm::ScoreAlgorithm::Ptr()> nav_algorithm_loader_;
|
||||
score_algorithm::ScoreAlgorithm::Ptr nav_algorithm_;
|
||||
std::function<score_algorithm::ScoreAlgorithm::Ptr()> rotate_algorithm_loader_;
|
||||
score_algorithm::ScoreAlgorithm::Ptr rotate_algorithm_;
|
||||
|
||||
std::function<score_algorithm::GoalChecker::Ptr()> goal_checker_loader_;
|
||||
score_algorithm::GoalChecker::Ptr goal_checker_;
|
||||
|
||||
bool initialized_;
|
||||
TFListenerPtr tf_;
|
||||
std::string name_;
|
||||
robot::NodeHandle parent_, planner_nh_;
|
||||
robot_nav_2d_msgs::Path2D global_plan_; ///< Saved Global Plan
|
||||
robot_nav_2d_msgs::Path2D transformed_global_plan_;
|
||||
robot_nav_2d_msgs::Path2D local_plan_;
|
||||
robot_nav_2d_msgs::Pose2DStamped goal_pose_; ///< Saved Goal Pose
|
||||
|
||||
robot_costmap_2d::Costmap2D *costmap_;
|
||||
robot_costmap_2d::Costmap2DROBOT *costmap_robot_;
|
||||
nav_grid::NavGridInfo info_;
|
||||
boost::recursive_mutex configuration_mutex_;
|
||||
bool update_costmap_before_planning_;
|
||||
|
||||
bool ret_angle_, ret_nav_;
|
||||
double yaw_goal_tolerance_, xy_goal_tolerance_;
|
||||
bool lock_;
|
||||
|
||||
}; // PNKXLocalPlanner
|
||||
|
||||
} // namespace pnkx_local_planner
|
||||
|
||||
#endif // _PNKX_LOCAL_PLANNER_H_INCLUDED_
|
||||
@@ -0,0 +1,85 @@
|
||||
#ifndef _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_
|
||||
#define _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_
|
||||
|
||||
#include <pnkx_local_planner/pnkx_local_planner.h>
|
||||
|
||||
namespace pnkx_local_planner
|
||||
{
|
||||
/**
|
||||
* @class PNKXRotateLocalPlanner
|
||||
* @brief Plugin-based flexible local_planner
|
||||
*/
|
||||
class PNKXRotateLocalPlanner : public pnkx_local_planner::PNKXLocalPlanner
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor that brings up pluginlib loaders
|
||||
*/
|
||||
PNKXRotateLocalPlanner();
|
||||
|
||||
virtual ~PNKXRotateLocalPlanner();
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 initialization
|
||||
* @param name Namespace for this planner
|
||||
* @param tf TFListener pointer
|
||||
* @param costmap_robot Costmap pointer
|
||||
*/
|
||||
void initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity
|
||||
*
|
||||
* It is presumed that the global plan is already set.
|
||||
*
|
||||
* This is mostly a wrapper for the protected computeVelocityCommands
|
||||
* function which has additional debugging info.
|
||||
*
|
||||
* @param pose Current robot pose
|
||||
* @param velocity Current robot velocity
|
||||
* @return The best command for the robot to drive
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2DStamped computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief robot_nav_core2 isGoalReached - Check whether the robot has reached its goal, given the current pose & velocity.
|
||||
*
|
||||
* The pose that it checks against is the last pose in the current global plan.
|
||||
* The calculation is delegated to the goal_checker plugin.
|
||||
*
|
||||
* @param pose Current pose
|
||||
* @param velocity Current velocity
|
||||
* @return True if the robot should be considered as having reached the goal.
|
||||
*/
|
||||
bool isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Create a new instance of the PNKXRotateLocalPlanner
|
||||
* @return A shared pointer to the new instance
|
||||
*/
|
||||
static robot_nav_core2::LocalPlanner::Ptr create();
|
||||
|
||||
protected:
|
||||
/**
|
||||
* @brief robot_nav_core2 reset other
|
||||
*/
|
||||
virtual void reset() override;
|
||||
|
||||
/**
|
||||
* @brief Helper method for preparing for the core scoring algorithm
|
||||
*
|
||||
* Runs the prepare method on all the critics with freshly transformed data
|
||||
*/
|
||||
void prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
/**
|
||||
* @brief Iterate through all the twists and find the best one
|
||||
*/
|
||||
robot_nav_2d_msgs::Twist2DStamped ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) override;
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
#endif // _PNKX_ROTATE_LOCAL_PLANNER_H_INCLUDED_
|
||||
@@ -0,0 +1,50 @@
|
||||
#ifndef _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__
|
||||
#define _MKT_LOCAL_PLANNER_TRANSFORMS_CHECKER_H_INCLUDED__
|
||||
|
||||
#include <robot/robot.h>
|
||||
#include <robot_nav_2d_msgs/Pose2DStamped.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
|
||||
#include <robot_nav_core2/common.h>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
|
||||
#include <tf3/buffer_core.h>
|
||||
#include <tf3/convert.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <robot_costmap_2d/costmap_2d_robot.h>
|
||||
|
||||
namespace pnkx_local_planner
|
||||
{
|
||||
bool getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame,
|
||||
robot_nav_2d_msgs::Pose2DStamped &global_pose, double transform_tolerance = 2.0);
|
||||
|
||||
bool transformGlobalPose(TFListenerPtr tf, const std::string &global_frame,
|
||||
const robot_nav_2d_msgs::Pose2DStamped &stamped_pose, robot_nav_2d_msgs::Pose2DStamped &newer_pose);
|
||||
|
||||
double getSquareDistance(const robot_geometry_msgs::Pose2D &pose_a, const robot_geometry_msgs::Pose2D &pose_b);
|
||||
|
||||
/**
|
||||
* @brief Transforms the global plan of the robot from the planner frame to the local frame (modified).
|
||||
*
|
||||
* The method replaces transformGlobalPlan as defined in base_local_planner/goal_functions.h
|
||||
* such that the index of the current goal pose is returned as well as
|
||||
* the transformation between the global plan and the planning frame.
|
||||
* @param tf A reference to a tf buffer
|
||||
* @param global_plan The plan to be transformed
|
||||
* @param pose The pose of the robot
|
||||
* @param costmap A reference to the costmap being used so the window size for transforming can be computed
|
||||
* @param global_frame The frame to transform the plan to
|
||||
* @param max_plan_length Specify maximum length (cumulative Euclidean distances) of the transformed plan [if <=0: disabled; the length is also bounded by the local costmap size!]
|
||||
* @param[out] transformed_plan Populated with the transformed plan
|
||||
* @return \c true if the global plan is transformed, \c false otherwise
|
||||
*/
|
||||
bool transformGlobalPlan(
|
||||
TFListenerPtr tf, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_costmap_2d::Costmap2DROBOT *costmap, const std::string &global_frame, double max_plan_length,
|
||||
robot_nav_2d_msgs::Path2D &transformed_plan, const bool from_global_frame = false);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,67 @@
|
||||
<package>
|
||||
<name>pnkx_local_planner</name>
|
||||
<version>0.7.10</version>
|
||||
<description>
|
||||
pnkx_local_planner is the second generation of the transform library, which lets
|
||||
the user keep track of multiple coordinate frames over time. pnkx_local_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.
|
||||
</description>
|
||||
<author>Tully Foote</author>
|
||||
<author>Eitan Marder-Eppstein</author>
|
||||
<author>Wim Meeussen</author>
|
||||
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
|
||||
<license>BSD</license>
|
||||
|
||||
<url type="website">http://www.ros.org/wiki/pnkx_local_planner</url>
|
||||
|
||||
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
|
||||
|
||||
<build_depend>robot_geometry_msgs</build_depend>
|
||||
<run_depend>robot_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_msgs</build_depend>
|
||||
<run_depend>robot_nav_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_std_msgs</build_depend>
|
||||
<run_depend>robot_std_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_visualization_msgs</build_depend>
|
||||
<run_depend>robot_visualization_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_msgs</build_depend>
|
||||
<run_depend>robot_nav_2d_msgs</run_depend>
|
||||
|
||||
<build_depend>robot_nav_2d_utils</build_depend>
|
||||
<run_depend>robot_nav_2d_utils</run_depend>
|
||||
|
||||
<build_depend>robot_nav_core2</build_depend>
|
||||
<run_depend>robot_nav_core2</run_depend>
|
||||
|
||||
<build_depend>mkt_msgs</build_depend>
|
||||
<run_depend>mkt_msgs</run_depend>
|
||||
|
||||
<build_depend>score_algorithm</build_depend>
|
||||
<run_depend>score_algorithm</run_depend>
|
||||
|
||||
<build_depend>robot_costmap_2d</build_depend>
|
||||
<run_depend>robot_costmap_2d</run_depend>
|
||||
|
||||
|
||||
|
||||
|
||||
<build_depend>robot_tf3_geometry_msgs</build_depend>
|
||||
<run_depend>robot_tf3_geometry_msgs</run_depend>
|
||||
|
||||
<build_depend>data_convert</build_depend>
|
||||
<run_depend>data_convert</run_depend>
|
||||
|
||||
<build_depend>robot_cpp</build_depend>
|
||||
<run_depend>robot_cpp</run_depend>
|
||||
|
||||
<build_depend>angles</build_depend>
|
||||
<run_depend>angles</run_depend>
|
||||
|
||||
</package>
|
||||
@@ -0,0 +1,835 @@
|
||||
#include <pnkx_local_planner/pnkx_docking_local_planner.h>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <robot_nav_2d_utils/footprint.h>
|
||||
#include <angles/angles.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include <robot_std_msgs/Bool.h>
|
||||
#include <robot_std_msgs/UInt16.h>
|
||||
#include <robot_visualization_msgs/MarkerArray.h>
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
pnkx_local_planner::PNKXDockingLocalPlanner::PNKXDockingLocalPlanner()
|
||||
: PNKXLocalPlanner(),
|
||||
start_docking_(false),
|
||||
original_xy_goal_tolerance_(0.0),
|
||||
original_yaw_goal_tolerance_(0.0)
|
||||
{
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXDockingLocalPlanner::~PNKXDockingLocalPlanner()
|
||||
{
|
||||
if (traj_generator_)
|
||||
traj_generator_.reset();
|
||||
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_.reset();
|
||||
|
||||
if (rotate_algorithm_)
|
||||
rotate_algorithm_.reset();
|
||||
|
||||
if (goal_checker_)
|
||||
goal_checker_.reset();
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
tf_ = tf;
|
||||
name_ = name;
|
||||
costmap_robot_ = costmap_robot;
|
||||
costmap_ = costmap_robot_->getCostmap();
|
||||
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
|
||||
parent_ = parent;
|
||||
planner_nh_ = robot::NodeHandle(parent_, name);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str());
|
||||
this->getParams(planner_nh_);
|
||||
|
||||
std::string traj_generator_name;
|
||||
planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(traj_generator_name);
|
||||
traj_gen_loader_ = boost::dll::import_alias<score_algorithm::TrajectoryGenerator::Ptr()>(
|
||||
path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations);
|
||||
traj_generator_ = traj_gen_loader_();
|
||||
if (!traj_generator_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name);
|
||||
traj_generator_->initialize(nh_traj_gen);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_nav_name);
|
||||
nav_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations);
|
||||
nav_algorithm_ = nav_algorithm_loader_();
|
||||
if (!nav_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_);
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
|
||||
std::string algorithm_rotate_name;
|
||||
planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal"));
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name);
|
||||
rotate_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations);
|
||||
rotate_algorithm_ = rotate_algorithm_loader_();
|
||||
if (!rotate_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm");
|
||||
}
|
||||
rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm");
|
||||
}
|
||||
|
||||
std::string goal_checker_name;
|
||||
planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(goal_checker_name);
|
||||
goal_checker_loader_ = boost::dll::import_alias<score_algorithm::GoalChecker::Ptr()>(
|
||||
path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations);
|
||||
goal_checker_ = goal_checker_loader_();
|
||||
if (!goal_checker_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
goal_checker_->initialize(parent_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
|
||||
this->initializeOthers();
|
||||
this->getMaker();
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str());
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::getMaker()
|
||||
{
|
||||
std::string maker_name, maker_sources;
|
||||
parent_.param("maker_name", maker_name, std::string(""));
|
||||
parent_.param("maker_sources", maker_sources, std::string(""));
|
||||
robot::log_info_at(__FILE__, __LINE__, "maker_name: %s", maker_name.c_str());
|
||||
robot::log_info_at(__FILE__, __LINE__, "maker_sources: %s", maker_sources.c_str());
|
||||
std::stringstream ss(maker_sources);
|
||||
std::string source;
|
||||
|
||||
while (ss >> source)
|
||||
{
|
||||
if (maker_name == source)
|
||||
{
|
||||
robot::NodeHandle source_node(parent_, source);
|
||||
|
||||
if (source_node.hasParam("plugins"))
|
||||
{
|
||||
robot_xmlrpcpp::XmlRpcValue plugins;
|
||||
source_node.getParam("plugins", plugins);
|
||||
|
||||
if (plugins.getType() == robot_xmlrpcpp::XmlRpcValue::TypeArray)
|
||||
{
|
||||
for (int i = 0; i < plugins.size(); ++i)
|
||||
{
|
||||
if (plugins[i].getType() == robot_xmlrpcpp::XmlRpcValue::TypeStruct)
|
||||
{
|
||||
std::stringstream name;
|
||||
name << source << "/" << static_cast<std::string>(plugins[i]["name"]);
|
||||
std::string docking_planner_name = static_cast<std::string>(plugins[i]["docking_planner"]);
|
||||
std::string docking_nav_name = static_cast<std::string>(plugins[i]["docking_nav"]);
|
||||
// std::shared_ptr<DockingPlanner> dkpl = std::make_shared<DockingPlanner>(name.str());
|
||||
DockingPlanner* dkpl = new DockingPlanner(name.str());
|
||||
dkpl->docking_planner_name_ = docking_planner_name;
|
||||
dkpl->docking_nav_name_ = docking_nav_name;
|
||||
dkpl_.push_back(dkpl);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Expected 'plugins' to be an array under namespace [%s]", source.c_str());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "No 'plugins' found under namespace [%s]", source.c_str());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::initializeOthers()
|
||||
{
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
if (!parent_.getParam(algorithm_nav_name, original_papams_))
|
||||
robot::log_warning_at(__FILE__, __LINE__, "No found in %s in yaml-file, please check configuration", algorithm_nav_name.c_str());
|
||||
original_xy_goal_tolerance_ = xy_goal_tolerance_;
|
||||
original_yaw_goal_tolerance_ = yaw_goal_tolerance_;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::getParams(robot::NodeHandle &nh)
|
||||
{
|
||||
// This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window
|
||||
nh.param("update_costmap_before_planning", update_costmap_before_planning_, true);
|
||||
if (!nh.param<double>("xy_goal_tolerance", xy_goal_tolerance_, 0.1))
|
||||
{
|
||||
xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1);
|
||||
}
|
||||
if (!nh.param<double>("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1))
|
||||
{
|
||||
yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::reset()
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "New Docking Goal Received.");
|
||||
this->unlock();
|
||||
if(traj_generator_) traj_generator_->reset();
|
||||
if(goal_checker_) goal_checker_->reset();
|
||||
if(nav_algorithm_) nav_algorithm_->reset();
|
||||
if(rotate_algorithm_) rotate_algorithm_->reset();
|
||||
ret_nav_ = ret_angle_ = false;
|
||||
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
|
||||
parent_.setParam(algorithm_nav_name, original_papams_);
|
||||
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name);
|
||||
nh_algorithm.setParam("allow_rotate", false);
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
this->getParams(planner_nh_);
|
||||
if (update_costmap_before_planning_)
|
||||
{
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
}
|
||||
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose),
|
||||
local_goal_pose = this->transformPoseToLocal(goal_pose_);
|
||||
if (start_docking_)
|
||||
{
|
||||
local_goal_pose = goal_pose_;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_))
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed");
|
||||
}
|
||||
catch(const robot_nav_core2::LocalPlannerException& e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
|
||||
double x_direction, y_direction, theta_direction;
|
||||
if (!ret_nav_)
|
||||
{
|
||||
if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
}
|
||||
// else
|
||||
// ROS_INFO_THROTTLE(0.2, "chieu %f %f %f", x_direction, y_direction, theta_direction);
|
||||
|
||||
if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_)
|
||||
{
|
||||
this->lock();
|
||||
robot_geometry_msgs::Vector3 linear = dkpl_.front()->linear_;
|
||||
traj_generator_->setTwistLinear(linear);
|
||||
linear.x *= (-1);
|
||||
traj_generator_->setTwistLinear(linear);
|
||||
traj_generator_->setTwistAngular(dkpl_.front()->angular_);
|
||||
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name);
|
||||
nh_algorithm.setParam("allow_rotate", dkpl_.front()->allow_rotate_);
|
||||
nh_algorithm.setParam("min_lookahead_dist", dkpl_.front()->min_lookahead_dist_);
|
||||
nh_algorithm.setParam("max_lookahead_dist", dkpl_.front()->max_lookahead_dist_);
|
||||
nh_algorithm.setParam("lookahead_time", dkpl_.front()->lookahead_time_);
|
||||
nh_algorithm.setParam("angle_threshold", dkpl_.front()->angle_threshold_);
|
||||
|
||||
parent_.setParam("xy_goal_tolerance", dkpl_.front()->xy_goal_tolerance_);
|
||||
parent_.setParam("yaw_goal_tolerance", dkpl_.front()->yaw_goal_tolerance_);
|
||||
|
||||
if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_)
|
||||
{
|
||||
|
||||
if (dkpl_.front()->following_)
|
||||
{
|
||||
robot_nav_2d_msgs::Pose2DStamped follow_pose;
|
||||
if (dkpl_.front()->geLocalGoal(local_goal_pose))
|
||||
{
|
||||
local_goal_pose = follow_pose;
|
||||
}
|
||||
}
|
||||
if (!dkpl_.front()->docking_nav_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str());
|
||||
}
|
||||
// else
|
||||
// ROS_INFO("chieu %f %f %f", x_direction, y_direction, theta_direction);
|
||||
}
|
||||
|
||||
int xytheta_direct[3];
|
||||
xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0;
|
||||
xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0;
|
||||
xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0;
|
||||
traj_generator_->setDirect(xytheta_direct);
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
robot::log_error("DEBUG 300");
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
try
|
||||
{
|
||||
if (global_plan_.poses.empty())
|
||||
return cmd_vel;
|
||||
this->prepare(pose, velocity);
|
||||
cmd_vel = this->ScoreAlgorithm(pose, velocity);
|
||||
return cmd_vel;
|
||||
}
|
||||
catch (const robot_nav_core2::PlannerException &e)
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "%s", e.what());
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D twist;
|
||||
mkt_msgs::Trajectory2D traj;
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
cmd_vel.header.stamp = robot::Time::now();
|
||||
|
||||
if (ret_nav_ && ret_angle_)
|
||||
return cmd_vel;
|
||||
else if (!ret_nav_)
|
||||
{
|
||||
traj = nav_algorithm_->calculator(pose, velocity);
|
||||
if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_)
|
||||
{
|
||||
if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_)
|
||||
{
|
||||
traj = dkpl_.front()->docking_nav_->calculator(pose, velocity);
|
||||
}
|
||||
}
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
traj = rotate_algorithm_->calculator(pose, velocity);
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
}
|
||||
|
||||
cmd_vel.velocity = traj.velocity;
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
if (goal_pose_.header.frame_id == "")
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!");
|
||||
return false;
|
||||
}
|
||||
robot::log_error("DEBUG 400.1");
|
||||
bool dock_ok = dockingHanlde(pose, velocity);
|
||||
robot::log_error("DEBUG 400.2");
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose);
|
||||
robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_);
|
||||
robot_nav_2d_msgs::Path2D plan = transformed_global_plan_;
|
||||
if (start_docking_)
|
||||
{
|
||||
local_goal = goal_pose_;
|
||||
if (!dkpl_.empty() && dkpl_.front()->initialized_)
|
||||
{
|
||||
if (dkpl_.front()->allow_rotate_)
|
||||
plan = robot_nav_2d_msgs::Path2D();
|
||||
}
|
||||
}
|
||||
|
||||
if (!ret_nav_)
|
||||
{
|
||||
ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity);
|
||||
|
||||
if (ret_nav_)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "local_pose %f %f %f", local_pose.pose.x, local_pose.pose.y, local_pose.pose.theta);
|
||||
robot::log_info_at(__FILE__, __LINE__, "local_goal %f %f %f", local_goal.pose.x, local_goal.pose.y, local_goal.pose.theta);
|
||||
}
|
||||
}
|
||||
|
||||
if (ret_nav_ && !ret_angle_ && !dock_ok)
|
||||
{
|
||||
double delta_orient =
|
||||
fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta));
|
||||
ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_);
|
||||
if(ret_angle_)
|
||||
robot::log_warning_at(__FILE__, __LINE__, "xy_goal_tolerance %f yaw_goal_tolerance %f",xy_goal_tolerance_, yaw_goal_tolerance_);
|
||||
}
|
||||
|
||||
if (start_docking_)
|
||||
{
|
||||
double dx = local_goal.pose.x - local_pose.pose.x;
|
||||
double dy = local_goal.pose.y - local_pose.pose.y;
|
||||
double dtheta = local_goal.pose.theta - local_pose.pose.theta;
|
||||
}
|
||||
if (ret_nav_ && ret_angle_ && dock_ok)
|
||||
{
|
||||
// nh_.setParam("xy_goal_tolerance", original_xy_goal_tolerance_);
|
||||
// nh_.setParam("yaw_goal_tolerance", original_yaw_goal_tolerance_);
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name);
|
||||
parent_.setParam(algorithm_nav_name, original_papams_);
|
||||
nh_algorithm.setParam("allow_rotate", false);
|
||||
}
|
||||
return ret_nav_ && ret_angle_ && dock_ok;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
if (!dkpl_.empty())
|
||||
{
|
||||
if (ret_nav_ && ret_angle_)
|
||||
{
|
||||
if (!dkpl_.front()->is_detected_)
|
||||
{
|
||||
if (!dkpl_.front()->initialized_)
|
||||
{
|
||||
dkpl_.front()->initialize(parent_, tf_, costmap_robot_, traj_generator_);
|
||||
dkpl_.front()->initialized_ = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (dkpl_.front()->docking_planner_ && !dkpl_.front()->docking_nav_)
|
||||
{
|
||||
robot_nav_2d_msgs::Pose2DStamped local_goal;
|
||||
try
|
||||
{
|
||||
if (dkpl_.front()->geLocalGoal(local_goal))
|
||||
{
|
||||
robot::log_error("DEBUG 100");
|
||||
dkpl_.front()->is_detected_ = true;
|
||||
start_docking_ = true;
|
||||
robot_nav_msgs::Path path;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose);
|
||||
dkpl_.front()->getLocalPath(local_pose, local_goal, path);
|
||||
this->setPlan(robot_nav_2d_utils::pathToPath(path));
|
||||
this->setGoalPose(local_goal);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
else if (!dkpl_.front()->docking_planner_ && dkpl_.front()->docking_nav_)
|
||||
{
|
||||
robot_nav_2d_msgs::Pose2DStamped local_goal;
|
||||
try
|
||||
{
|
||||
if (dkpl_.front()->geLocalGoal(local_goal))
|
||||
{
|
||||
robot::log_error("DEBUG 200");
|
||||
dkpl_.front()->is_detected_ = true;
|
||||
start_docking_ = true;
|
||||
robot_nav_2d_msgs::Path2D path;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose);
|
||||
path.header.stamp = robot::Time::now();
|
||||
path.header.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
path.poses.push_back(local_pose);
|
||||
path.poses.push_back(local_goal);
|
||||
this->setPlan(path);
|
||||
this->setGoalPose(local_goal);
|
||||
}
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (dkpl_.front()->initialized_ && !dkpl_.front()->is_goal_reached_)
|
||||
{
|
||||
dkpl_.front()->is_goal_reached_ = true;
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s is goal reached", dkpl_.front()->name_.c_str());
|
||||
}
|
||||
|
||||
if (dkpl_.front()->initialized_ && dkpl_.front()->is_goal_reached_)
|
||||
{
|
||||
if(!dkpl_.empty())
|
||||
{
|
||||
// if(dkpl_.front()) delete(dkpl_.front());
|
||||
dkpl_.erase(dkpl_.begin());
|
||||
}
|
||||
start_docking_ = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
bool result = false;
|
||||
if (dkpl_.empty())
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal reached!");
|
||||
result = true;
|
||||
this->getMaker();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::DockingPlanner(const std::string &name)
|
||||
: initialized_(false),
|
||||
is_detected_(false),
|
||||
is_goal_reached_(false),
|
||||
following_(false),
|
||||
allow_rotate_(false),
|
||||
xy_goal_tolerance_(0.05),
|
||||
yaw_goal_tolerance_(0.05),
|
||||
min_lookahead_dist_(0.4),
|
||||
max_lookahead_dist_(1.0),
|
||||
lookahead_time_(1.5),
|
||||
angle_threshold_(0.4),
|
||||
name_(name),
|
||||
docking_planner_name_(),
|
||||
docking_nav_name_(),
|
||||
docking_planner_(nullptr),
|
||||
docking_nav_(nullptr),
|
||||
linear_(),
|
||||
angular_(),
|
||||
nh_(),
|
||||
nh_priv_(),
|
||||
tf_(nullptr),
|
||||
costmap_robot_(nullptr),
|
||||
traj_generator_(),
|
||||
docking_planner_loader_(),
|
||||
docking_nav_loader_(),
|
||||
detected_timeout_wt_(),
|
||||
delayed_wt_(),
|
||||
delayed_(false),
|
||||
detected_timeout_(false),
|
||||
robot_base_frame_(),
|
||||
maker_goal_frame_()
|
||||
{
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::~DockingPlanner()
|
||||
{
|
||||
detected_timeout_wt_.stop();
|
||||
delayed_wt_.stop();
|
||||
if (docking_planner_ != nullptr) {
|
||||
docking_planner_.reset();
|
||||
}
|
||||
if (docking_nav_ != nullptr) {
|
||||
docking_nav_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::initialize(robot::NodeHandle &nh, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot,
|
||||
score_algorithm::TrajectoryGenerator::Ptr traj_generator)
|
||||
{
|
||||
nh_ = nh;
|
||||
nh_priv_ = robot::NodeHandle(nh_, name_);
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
traj_generator_ = traj_generator;
|
||||
|
||||
if (docking_planner_name_ != std::string(""))
|
||||
{
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(docking_planner_name_);
|
||||
docking_planner_loader_ = boost::dll::import_alias<robot_nav_core::BaseGlobalPlanner::Ptr()>(
|
||||
path_file_so, docking_planner_name_, boost::dll::load_mode::append_decorations);
|
||||
docking_planner_ = docking_planner_loader_();
|
||||
if (!docking_planner_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create global planner \"%s\": returned null pointer", docking_planner_name_.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create global planner");
|
||||
}
|
||||
docking_planner_->initialize(name_, costmap_robot_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Created global_planner %s", docking_planner_name_.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s",
|
||||
docking_planner_name_.c_str(), ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
if (docking_nav_name_ != std::string(""))
|
||||
{
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(docking_nav_name_);
|
||||
docking_nav_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, docking_nav_name_, boost::dll::load_mode::append_decorations);
|
||||
docking_nav_ = docking_nav_loader_();
|
||||
if (!docking_nav_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create docking nav \"%s\": returned null pointer", docking_nav_name_.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create docking nav");
|
||||
}
|
||||
robot::NodeHandle nh_docking_nav = robot::NodeHandle(nh_priv_, docking_nav_name_);
|
||||
docking_nav_->initialize(nh_docking_nav, docking_nav_name_, tf_, costmap_robot_, traj_generator_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Created docking nav %s", docking_nav_name_.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s planner, are you sure it is properly registered and that the containing library is built? Exception: %s",
|
||||
docking_nav_name_.c_str(), ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
robot_base_frame_ = robot_nav_2d_utils::searchAndGetParam(nh_priv_, "robot_base_frame", std::string("base_link"));
|
||||
if (!nh_priv_.param("maker_goal_frame", maker_goal_frame_, std::string("")))
|
||||
{
|
||||
std::stringstream re;
|
||||
re << "Can not get 'maker_goal_frame' in " << name_;
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException(re.str());
|
||||
}
|
||||
|
||||
nh_priv_.param("vel_x", linear_.x, 0.5);
|
||||
nh_priv_.param("vel_theta", angular_.z, 0.5);
|
||||
nh_priv_.param("following", following_, false);
|
||||
nh_priv_.param("allow_rotate", allow_rotate_, false);
|
||||
|
||||
double delay_time, time_out;
|
||||
nh_priv_.param("delay", delay_time, 1.0);
|
||||
nh_priv_.param("timeout", time_out, 1.0);
|
||||
|
||||
nh_priv_.param("xy_goal_tolerance", xy_goal_tolerance_, 0.05);
|
||||
nh_priv_.param("yaw_goal_tolerance", yaw_goal_tolerance_, 0.05);
|
||||
|
||||
nh_priv_.param("min_lookahead_dist", min_lookahead_dist_, 0.4);
|
||||
nh_priv_.param("max_lookahead_dist", max_lookahead_dist_, 1.0);
|
||||
nh_priv_.param("lookahead_time", lookahead_time_, 1.5);
|
||||
nh_priv_.param("angle_threshold", angle_threshold_, 0.4);
|
||||
|
||||
robot::log_info("delay: %f", delay_time);
|
||||
robot::log_info("timeout: %f", time_out);
|
||||
robot::log_info("xy_goal_tolerance: %f", xy_goal_tolerance_);
|
||||
robot::log_info("yaw_goal_tolerance: %f", yaw_goal_tolerance_);
|
||||
robot::log_info("min_lookahead_dist: %f", min_lookahead_dist_);
|
||||
robot::log_info("max_lookahead_dist: %f", max_lookahead_dist_);
|
||||
robot::log_info("lookahead_time: %f", lookahead_time_);
|
||||
robot::log_info("angle_threshold: %f", angle_threshold_);
|
||||
|
||||
detected_timeout_wt_ = ::robot::WallTimer(
|
||||
::robot::WallDuration(time_out + delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb, this, false, false);
|
||||
detected_timeout_wt_.start();
|
||||
robot::log_warning_at(__FILE__, __LINE__, "%s %f time_out start %f", name_.c_str(), delay_time, robot::Time::now().toSec());
|
||||
|
||||
delayed_wt_ = ::robot::WallTimer(
|
||||
::robot::WallDuration(delay_time), &pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb, this, false, false);
|
||||
delayed_wt_.start();
|
||||
robot::log_warning_at(__FILE__, __LINE__, "%s %f delay start %f", name_.c_str(), delay_time, robot::Time::now().toSec());
|
||||
|
||||
initialized_ = true;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getMakerGoal(robot_nav_2d_msgs::Pose2DStamped &maker_goal)
|
||||
{
|
||||
if (!delayed_)
|
||||
return false;
|
||||
|
||||
bool get_pose_result = false;
|
||||
try
|
||||
{
|
||||
if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal, 2.0))
|
||||
{
|
||||
get_pose_result = true;
|
||||
detected_timeout_wt_.stop();
|
||||
}
|
||||
|
||||
if (get_pose_result)
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
if (detected_timeout_)
|
||||
{
|
||||
std::stringstream re;
|
||||
re << "No detected " << maker_goal_frame_;
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException(re.str());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::geLocalGoal(robot_nav_2d_msgs::Pose2DStamped &local_goal)
|
||||
{
|
||||
if (!delayed_)
|
||||
return false;
|
||||
bool get_pose_result = false;
|
||||
try
|
||||
{
|
||||
robot_nav_2d_msgs::Pose2DStamped maker_goal_on_robot;
|
||||
if (pnkx_local_planner::getPose(tf_, maker_goal_frame_, robot_base_frame_, maker_goal_on_robot, 2.0))
|
||||
{
|
||||
if (robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), maker_goal_on_robot, local_goal))
|
||||
{
|
||||
get_pose_result = true;
|
||||
detected_timeout_wt_.stop();
|
||||
}
|
||||
}
|
||||
|
||||
if (get_pose_result)
|
||||
return true;
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
if (detected_timeout_)
|
||||
{
|
||||
std::stringstream re;
|
||||
re << "No detected " << maker_goal_frame_;
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s", re.str().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException(re.str());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::getLocalPath(
|
||||
const robot_nav_2d_msgs::Pose2DStamped &local_pose, const robot_nav_2d_msgs::Pose2DStamped &local_goal, robot_nav_msgs::Path &local_path)
|
||||
{
|
||||
robot_geometry_msgs::PoseStamped start = robot_nav_2d_utils::pose2DToPoseStamped(local_pose);
|
||||
robot_geometry_msgs::PoseStamped goal = robot_nav_2d_utils::pose2DToPoseStamped(local_goal);
|
||||
std::vector<robot_geometry_msgs::PoseStamped> docking_plan;
|
||||
robot::log_info_at(__FILE__, __LINE__, "start %s %f %f", start.header.frame_id.c_str(), start.pose.position.x, start.pose.position.y);
|
||||
robot::log_info_at(__FILE__, __LINE__, "goal %s %f %f", goal.header.frame_id.c_str(), goal.pose.position.x, goal.pose.position.y);
|
||||
if (!docking_planner_->makePlan(start, goal, docking_plan))
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException("Making plan from goal maker is failed");
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
local_path = robot_nav_2d_utils::posesToPath(docking_plan);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::detectedTimeOutCb(const ::robot::WallTimerEvent &timer_event)
|
||||
{
|
||||
detected_timeout_ = true;
|
||||
detected_timeout_wt_.stop();
|
||||
robot::log_warning_at(__FILE__, __LINE__, "%s time_out end %f", name_.c_str(), robot::Time::now().toSec());
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXDockingLocalPlanner::DockingPlanner::delayCb(const ::robot::WallTimerEvent &timer_event)
|
||||
{
|
||||
delayed_ = true;
|
||||
delayed_wt_.stop();
|
||||
robot::log_warning_at(__FILE__, __LINE__, "%s delay end %f", name_.c_str(), robot::Time::now().toSec());
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXDockingLocalPlanner::create()
|
||||
{
|
||||
return std::make_shared<PNKXDockingLocalPlanner>();
|
||||
}
|
||||
|
||||
// register this planner as a LocalPlanner plugin
|
||||
BOOST_DLL_ALIAS(pnkx_local_planner::PNKXDockingLocalPlanner::create, PNKXDockingLocalPlanner)
|
||||
@@ -0,0 +1,260 @@
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <mkt_msgs/Trajectory2D.h>
|
||||
|
||||
// #include <g2o/core/base_binary_edge.h>
|
||||
// #include <g2o/core/base_unary_edge.h>
|
||||
// #include <g2o/core/base_multi_edge.h>
|
||||
#include <angles/angles.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include "pnkx_local_planner/pnkx_go_straight_local_planner.h"
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
pnkx_local_planner::PNKXGoStraightLocalPlanner::PNKXGoStraightLocalPlanner()
|
||||
: PNKXLocalPlanner()
|
||||
{
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXGoStraightLocalPlanner::~PNKXGoStraightLocalPlanner()
|
||||
{
|
||||
if (traj_generator_)
|
||||
traj_generator_.reset();
|
||||
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_.reset();
|
||||
|
||||
if (goal_checker_)
|
||||
goal_checker_.reset();
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXGoStraightLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str());
|
||||
if(costmap_robot == nullptr)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Costmap2DROBOT is nullptr");
|
||||
throw robot_nav_core2::LocalPlannerException("Costmap2DROBOT is nullptr");
|
||||
}
|
||||
if(tf == nullptr)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "TFListener is nullptr");
|
||||
throw robot_nav_core2::LocalPlannerException("TFListener is nullptr");
|
||||
}
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
costmap_ = costmap_robot_->getCostmap();
|
||||
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
|
||||
parent_ = parent;
|
||||
planner_nh_ = robot::NodeHandle(parent_, name);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str());
|
||||
this->getParams(planner_nh_);
|
||||
|
||||
// This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window
|
||||
std::string traj_generator_name;
|
||||
planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str());
|
||||
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(traj_generator_name);
|
||||
traj_gen_loader_ = boost::dll::import_alias<score_algorithm::TrajectoryGenerator::Ptr()>(
|
||||
path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations);
|
||||
traj_generator_ = traj_gen_loader_();
|
||||
if (!traj_generator_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name);
|
||||
traj_generator_->initialize(nh_traj_gen);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
|
||||
std::string algorithm_nav_name = std::string("pnkx_local_planner::GoStraight");
|
||||
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::GoStraight"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_nav_name);
|
||||
nav_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations);
|
||||
nav_algorithm_ = nav_algorithm_loader_();
|
||||
if (!nav_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_nav_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
|
||||
std::string goal_checker_name;
|
||||
planner_nh_.param("goal_checker_name", goal_checker_name, std::string("score_algorithm::GoalChecker"));
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(goal_checker_name);
|
||||
goal_checker_loader_ = boost::dll::import_alias<score_algorithm::GoalChecker::Ptr()>(
|
||||
path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations);
|
||||
goal_checker_ = goal_checker_loader_();
|
||||
if (!goal_checker_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name);
|
||||
goal_checker_->initialize(nh_goal_checker);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s is initialized", name.c_str());
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXGoStraightLocalPlanner::reset()
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "New Goal Received.");
|
||||
this->unlock();
|
||||
traj_generator_->reset();
|
||||
goal_checker_->reset();
|
||||
nav_algorithm_->reset();
|
||||
ret_nav_ = ret_angle_ = false;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose,
|
||||
const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
try
|
||||
{
|
||||
if (global_plan_.poses.empty())
|
||||
return cmd_vel;
|
||||
this->prepare(pose, velocity);
|
||||
cmd_vel = this->ScoreAlgorithm(pose, velocity);
|
||||
return cmd_vel;
|
||||
}
|
||||
catch (const robot_nav_core2::PlannerException &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXGoStraightLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
this->getParams(planner_nh_);
|
||||
if (update_costmap_before_planning_)
|
||||
{
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
}
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose),
|
||||
local_goal_pose = this->transformPoseToLocal(goal_pose_);
|
||||
|
||||
try
|
||||
{
|
||||
if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_))
|
||||
throw robot_nav_core2::LocalPlannerException("Transform global plan is failed");
|
||||
}
|
||||
catch(const robot_nav_core2::LocalPlannerException& e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
|
||||
double x_direction, y_direction, theta_direction;
|
||||
if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
}
|
||||
|
||||
int xytheta_direct[3];
|
||||
xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0;
|
||||
xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0;
|
||||
xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0;
|
||||
traj_generator_->setDirect(xytheta_direct);
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXGoStraightLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D twist;
|
||||
mkt_msgs::Trajectory2D traj;
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
cmd_vel.header.stamp = robot::Time::now();
|
||||
|
||||
if (ret_nav_)
|
||||
{
|
||||
local_plan_.poses.clear();
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
traj = nav_algorithm_->calculator(pose, velocity);
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
cmd_vel.velocity = traj.velocity;
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXGoStraightLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
if (goal_pose_.header.frame_id == "")
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!");
|
||||
return false;
|
||||
}
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
ret_nav_ = goal_checker_->isGoalReached(transformPoseToLocal(pose), transformPoseToLocal(goal_pose_), transformed_global_plan_, velocity);
|
||||
|
||||
if (ret_nav_)
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal reached!");
|
||||
return ret_nav_;
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXGoStraightLocalPlanner::create()
|
||||
{
|
||||
return std::make_shared<pnkx_local_planner::PNKXGoStraightLocalPlanner>();
|
||||
}
|
||||
|
||||
// register this planner as a LocalPlanner plugin
|
||||
BOOST_DLL_ALIAS(pnkx_local_planner::PNKXGoStraightLocalPlanner::create, PNKXGoStraightLocalPlanner)
|
||||
@@ -0,0 +1,494 @@
|
||||
#include <pnkx_local_planner/pnkx_local_planner.h>
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <angles/angles.h>
|
||||
|
||||
#include <tf3/convert.h>
|
||||
#include <tf3/utils.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
#include <mkt_msgs/Trajectory2D.h>
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/dll/alias.hpp>
|
||||
#include <robot/robot.h>
|
||||
|
||||
pnkx_local_planner::PNKXLocalPlanner::PNKXLocalPlanner()
|
||||
: initialized_(false),
|
||||
traj_generator_(nullptr),
|
||||
nav_algorithm_(nullptr),
|
||||
rotate_algorithm_(nullptr),
|
||||
goal_checker_(nullptr),
|
||||
tf_(nullptr),
|
||||
costmap_(nullptr),
|
||||
costmap_robot_(nullptr),
|
||||
info_(),
|
||||
update_costmap_before_planning_(false),
|
||||
ret_angle_(false),
|
||||
ret_nav_(false),
|
||||
yaw_goal_tolerance_(0.0),
|
||||
xy_goal_tolerance_(0.0),
|
||||
lock_(false)
|
||||
{
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXLocalPlanner::~PNKXLocalPlanner()
|
||||
{
|
||||
if (traj_generator_)
|
||||
traj_generator_.reset();
|
||||
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_.reset();
|
||||
|
||||
if (rotate_algorithm_)
|
||||
rotate_algorithm_.reset();
|
||||
|
||||
if (goal_checker_)
|
||||
goal_checker_.reset();
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::initialize(robot::NodeHandle &parent, const std::string &name,
|
||||
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
tf_ = tf;
|
||||
name_ = name;
|
||||
costmap_robot_ = costmap_robot;
|
||||
costmap_ = costmap_robot_->getCostmap();
|
||||
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
|
||||
parent_ = parent;
|
||||
planner_nh_ = robot::NodeHandle(parent_, name);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Planner namespace: %s, parent namespace: %s", planner_nh_.getNamespace().c_str(), parent_.getNamespace().c_str());
|
||||
this->getParams(planner_nh_);
|
||||
|
||||
std::string traj_generator_name;
|
||||
planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("StandardTrajectoryGenerator"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(traj_generator_name);
|
||||
traj_gen_loader_ = boost::dll::import_alias<score_algorithm::TrajectoryGenerator::Ptr()>(
|
||||
path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations);
|
||||
traj_generator_ = traj_gen_loader_();
|
||||
if (!traj_generator_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name);
|
||||
traj_generator_->initialize(nh_traj_gen);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized trajectory generator \"%s\"", traj_generator_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
|
||||
std::string algorithm_nav_name;
|
||||
planner_nh_.getParam("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_nav_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_nav_name);
|
||||
robot::log_info_at(__FILE__, __LINE__, "path_file_so: %s", path_file_so.c_str());
|
||||
nav_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_nav_name, boost::dll::load_mode::append_decorations);
|
||||
nav_algorithm_ = nav_algorithm_loader_();
|
||||
if (!nav_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to load algorithm %s", algorithm_nav_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
nav_algorithm_->initialize(parent_, algorithm_nav_name, tf, costmap_robot_, traj_generator_);
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_nav_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
|
||||
std::string algorithm_rotate_name;
|
||||
planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("MKTAlgorithmDiffRotateToGoal"));
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name);
|
||||
rotate_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations);
|
||||
rotate_algorithm_ = rotate_algorithm_loader_();
|
||||
if (!rotate_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create rotate algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm");
|
||||
}
|
||||
rotate_algorithm_->initialize(parent_, algorithm_rotate_name, tf, costmap_robot_, traj_generator_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized rotate algorithm \"%s\"", algorithm_rotate_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s rotate algorithm, are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create rotate algorithm");
|
||||
}
|
||||
|
||||
std::string goal_checker_name;
|
||||
planner_nh_.param("goal_checker_name", goal_checker_name, std::string("dwb_plugins::SimpleGoalChecker"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "goal_checker_name: %s", goal_checker_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(goal_checker_name);
|
||||
goal_checker_loader_ = boost::dll::import_alias<score_algorithm::GoalChecker::Ptr()>(
|
||||
path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations);
|
||||
goal_checker_ = goal_checker_loader_();
|
||||
if (!goal_checker_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
goal_checker_->initialize(parent_);
|
||||
robot::log_info_at(__FILE__, __LINE__, "Successfully initialized goal checker \"%s\"", goal_checker_name.c_str());
|
||||
}
|
||||
catch (const std::exception &ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Unexpected exception while creating goal checker \"%s\": %s", goal_checker_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
|
||||
this->initializeOthers();
|
||||
robot::log_info("[%s:%d]\n %s is sucessed", __FILE__, __LINE__, name.c_str());
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::initializeOthers()
|
||||
{
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::getParams(robot::NodeHandle &nh)
|
||||
{
|
||||
// This is needed when using the CostmapAdapter to ensure that the costmap's info matches the rolling window
|
||||
nh.param("update_costmap_before_planning", update_costmap_before_planning_, true);
|
||||
if (!nh.param<double>("xy_goal_tolerance", xy_goal_tolerance_, 0.1))
|
||||
{
|
||||
xy_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "xy_goal_tolerance", 0.1);
|
||||
}
|
||||
if (!nh.param<double>("yaw_goal_tolerance", yaw_goal_tolerance_, 0.1))
|
||||
{
|
||||
yaw_goal_tolerance_ = robot_nav_2d_utils::searchAndGetParam(nh, "yaw_goal_tolerance", 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::reset()
|
||||
{
|
||||
this->unlock();
|
||||
if(traj_generator_) traj_generator_->reset();
|
||||
if(goal_checker_) goal_checker_->reset();
|
||||
if(nav_algorithm_) nav_algorithm_->reset();
|
||||
if(rotate_algorithm_) rotate_algorithm_->reset();
|
||||
ret_nav_ = ret_angle_ = false;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose)
|
||||
{
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
robot::log_error("[PNKXLocalPlanner] Receive new goal(%f, %f)!", goal_pose.pose.x, goal_pose.pose.y);
|
||||
reset();
|
||||
goal_pose_ = goal_pose;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path)
|
||||
{
|
||||
robot::log_error("[PNKXLocalPlanner] size path: %d", (int)path.poses.size());
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
costmap_robot_->resetLayers();
|
||||
global_plan_ = path;
|
||||
if((unsigned int)global_plan_.poses.size() > 2)
|
||||
global_plan_.poses.erase(global_plan_.poses.begin());
|
||||
for (unsigned int i = 0; i < (unsigned int)global_plan_.poses.size(); i++)
|
||||
{
|
||||
global_plan_.poses[i].header.seq = i;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::getPlan(robot_nav_2d_msgs::Path2D &path)
|
||||
{
|
||||
if (local_plan_.poses.empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
path = local_plan_;
|
||||
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::getGlobalPlan(robot_nav_2d_msgs::Path2D &path)
|
||||
{
|
||||
if (global_plan_.poses.empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
path = global_plan_;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
this->getParams(planner_nh_);
|
||||
if (update_costmap_before_planning_)
|
||||
{
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
}
|
||||
|
||||
// Update time stamp of goal pose
|
||||
robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose),
|
||||
local_goal_pose = this->transformPoseToLocal(goal_pose_);
|
||||
|
||||
if (!pnkx_local_planner::transformGlobalPlan(
|
||||
tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_))
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed");
|
||||
throw robot_nav_core2::LocalPlannerException("Transform global plan is failed");
|
||||
}
|
||||
|
||||
double x_direction, y_direction, theta_direction;
|
||||
if (!ret_nav_)
|
||||
{
|
||||
if (nav_algorithm_ && !nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rotate_algorithm_ && !rotate_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", rotate_algorithm_->getName().c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
}
|
||||
}
|
||||
|
||||
int xytheta_direct[3];
|
||||
xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0;
|
||||
xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0;
|
||||
xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0;
|
||||
if(traj_generator_) traj_generator_->setDirect(xytheta_direct);
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
|
||||
const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
try
|
||||
{
|
||||
if (global_plan_.poses.empty())
|
||||
return cmd_vel;
|
||||
this->prepare(pose, velocity);
|
||||
cmd_vel = this->ScoreAlgorithm(pose, velocity);
|
||||
return cmd_vel;
|
||||
}
|
||||
catch (const robot_nav_core2::PlannerException &e)
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "PNKXLocalPlanner computing velocity commands has been broken: %s", e.what());
|
||||
throw robot_nav_core2::LocalPlannerException("computing velocity commands has been broken");
|
||||
return cmd_vel;
|
||||
}
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D twist;
|
||||
mkt_msgs::Trajectory2D traj;
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
cmd_vel.header.stamp = robot::Time::now();
|
||||
|
||||
if (ret_nav_ && ret_angle_)
|
||||
{
|
||||
return cmd_vel;
|
||||
local_plan_.poses.clear();
|
||||
}
|
||||
else if (!ret_nav_)
|
||||
{
|
||||
if(nav_algorithm_) traj = nav_algorithm_->calculator(pose, velocity);
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(rotate_algorithm_) traj = rotate_algorithm_->calculator(pose, velocity);
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
}
|
||||
|
||||
cmd_vel.velocity = traj.velocity;
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXLocalPlanner::setTwistLinear(robot_geometry_msgs::Vector3 linear)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (linear.x == 0.0 && linear.y == 0.0 && linear.z == 0.0)
|
||||
{
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_->stop();
|
||||
if (rotate_algorithm_)
|
||||
rotate_algorithm_->stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_->resume();
|
||||
if (rotate_algorithm_)
|
||||
rotate_algorithm_->resume();
|
||||
}
|
||||
|
||||
if (traj_generator_)
|
||||
return traj_generator_->setTwistLinear(linear);
|
||||
else
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to set linear");
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistLinear(bool direct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (traj_generator_)
|
||||
return traj_generator_->getTwistLinear(direct);
|
||||
else
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to get linear");
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXLocalPlanner::setTwistAngular(robot_geometry_msgs::Vector3 angular)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (traj_generator_)
|
||||
return traj_generator_->setTwistAngular(angular);
|
||||
else
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to set angular");
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
robot_geometry_msgs::Vector3 pnkx_local_planner::PNKXLocalPlanner::getTwistAngular(bool direct)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (traj_generator_)
|
||||
return traj_generator_->getTwistAngular(direct);
|
||||
else
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to get angular");
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXLocalPlanner::islock()
|
||||
{
|
||||
return lock_;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::lock()
|
||||
{
|
||||
lock_ = true;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXLocalPlanner::unlock()
|
||||
{
|
||||
lock_ = false;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
|
||||
{
|
||||
if (goal_pose_.header.frame_id == "")
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!");
|
||||
return false;
|
||||
}
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose);
|
||||
robot_nav_2d_msgs::Pose2DStamped local_goal = this->transformPoseToLocal(goal_pose_);
|
||||
robot_nav_2d_msgs::Path2D plan = transformed_global_plan_;
|
||||
if (!ret_nav_)
|
||||
{
|
||||
ret_nav_ = goal_checker_->isGoalReached(local_pose, local_goal, plan, velocity);
|
||||
}
|
||||
else
|
||||
{
|
||||
double delta_orient = fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta));
|
||||
ret_angle_ = (bool)(delta_orient <= yaw_goal_tolerance_);
|
||||
}
|
||||
|
||||
if (ret_nav_ && ret_angle_)
|
||||
{
|
||||
robot::log_info_throttle(1.0, "Goal reached!");
|
||||
}
|
||||
return ret_nav_ && ret_angle_;
|
||||
}
|
||||
|
||||
inline double getSquareDistance(const robot_nav_2d_msgs::Pose2DStamped &pose_a, const robot_nav_2d_msgs::Pose2DStamped &pose_b)
|
||||
{
|
||||
double x_diff = pose_a.pose.x - pose_b.pose.x;
|
||||
double y_diff = pose_a.pose.y - pose_b.pose.y;
|
||||
return x_diff * x_diff + y_diff * y_diff;
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped pnkx_local_planner::PNKXLocalPlanner::transformPoseToLocal(const robot_nav_2d_msgs::Pose2DStamped &pose)
|
||||
{
|
||||
robot_nav_2d_msgs::Pose2DStamped local_pose;
|
||||
robot_nav_2d_utils::transformPose(tf_, costmap_robot_->getGlobalFrameID(), pose, local_pose);
|
||||
return local_pose;
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXLocalPlanner::create()
|
||||
{
|
||||
return std::make_shared<PNKXLocalPlanner>();
|
||||
}
|
||||
|
||||
// register this planner as a LocalPlanner plugin
|
||||
BOOST_DLL_ALIAS(pnkx_local_planner::PNKXLocalPlanner::create, PNKXLocalPlanner)
|
||||
@@ -0,0 +1,247 @@
|
||||
#include "pnkx_local_planner/pnkx_rotate_local_planner.h"
|
||||
#include "pnkx_local_planner/transforms.h"
|
||||
|
||||
#include <robot_nav_core2/exceptions.h>
|
||||
#include <robot_nav_2d_utils/conversions.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/parameters.h>
|
||||
#include <mkt_msgs/Trajectory2D.h>
|
||||
|
||||
#include <angles/angles.h>
|
||||
#include <robot_nav_msgs/Path.h>
|
||||
#include <boost/dll/import.hpp>
|
||||
#include <boost/dll/alias.hpp>
|
||||
|
||||
pnkx_local_planner::PNKXRotateLocalPlanner::PNKXRotateLocalPlanner()
|
||||
: PNKXLocalPlanner()
|
||||
{
|
||||
}
|
||||
|
||||
pnkx_local_planner::PNKXRotateLocalPlanner::~PNKXRotateLocalPlanner()
|
||||
{
|
||||
if (traj_generator_)
|
||||
traj_generator_.reset();
|
||||
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_.reset();
|
||||
|
||||
if (goal_checker_)
|
||||
goal_checker_.reset();
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXRotateLocalPlanner::initialize(robot::NodeHandle& parent, const std::string& name, TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT* costmap_robot)
|
||||
{
|
||||
if (!initialized_)
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using parent name \"%s\"", name.c_str());
|
||||
tf_ = tf;
|
||||
costmap_robot_ = costmap_robot;
|
||||
costmap_ = costmap_robot_->getCostmap();
|
||||
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
parent_ = parent;
|
||||
planner_nh_ = robot::NodeHandle(parent_, name);
|
||||
|
||||
this->getParams(planner_nh_);
|
||||
|
||||
std::string traj_generator_name;
|
||||
planner_nh_.param("trajectory_generator_name", traj_generator_name, std::string("nav_plugins::StandardTrajectoryGenerator"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Trajectory Generator \"%s\"", traj_generator_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(traj_generator_name);
|
||||
traj_gen_loader_ = boost::dll::import_alias<score_algorithm::TrajectoryGenerator::Ptr()>(
|
||||
path_file_so, traj_generator_name, boost::dll::load_mode::append_decorations);
|
||||
traj_generator_ = traj_gen_loader_();
|
||||
if (!traj_generator_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create trajectory generator \"%s\": returned null pointer", traj_generator_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
robot::NodeHandle nh_traj_gen = robot::NodeHandle(parent_, traj_generator_name);
|
||||
traj_generator_->initialize(nh_traj_gen);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s traj_generator, are you sure it is properly registered and that the containing library is built? Exception: %s", traj_generator_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create traj_generator");
|
||||
}
|
||||
|
||||
std::string algorithm_rotate_name = std::string("nav_algorithm::Rotate");
|
||||
planner_nh_.param("algorithm_rotate_name", algorithm_rotate_name, std::string("nav_algorithm::Rotate"));
|
||||
robot::log_info_at(__FILE__, __LINE__, "Using Algorithm \"%s\"", algorithm_rotate_name.c_str());
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(algorithm_rotate_name);
|
||||
nav_algorithm_loader_ = boost::dll::import_alias<score_algorithm::ScoreAlgorithm::Ptr()>(
|
||||
path_file_so, algorithm_rotate_name, boost::dll::load_mode::append_decorations);
|
||||
nav_algorithm_ = nav_algorithm_loader_();
|
||||
if (!nav_algorithm_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create algorithm \"%s\": returned null pointer", algorithm_rotate_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_rotate_name);
|
||||
nav_algorithm_->initialize(nh_algorithm, algorithm_rotate_name, tf, costmap_robot_, traj_generator_);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s algorithm , are you sure it is properly registered and that the containing library is built? Exception: %s", algorithm_rotate_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create algorithm");
|
||||
}
|
||||
|
||||
std::string goal_checker_name;
|
||||
planner_nh_.param("goal_checker_name", goal_checker_name, std::string("nav_algorithm::GoalChecker"));
|
||||
try
|
||||
{
|
||||
robot::PluginLoaderHelper loader;
|
||||
std::string path_file_so = loader.findLibraryPath(goal_checker_name);
|
||||
goal_checker_loader_ = boost::dll::import_alias<score_algorithm::GoalChecker::Ptr()>(
|
||||
path_file_so, goal_checker_name, boost::dll::load_mode::append_decorations);
|
||||
goal_checker_ = goal_checker_loader_();
|
||||
if (!goal_checker_)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create goal checker \"%s\": returned null pointer", goal_checker_name.c_str());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
robot::NodeHandle nh_goal_checker = robot::NodeHandle(parent_, goal_checker_name);
|
||||
goal_checker_->initialize(nh_goal_checker);
|
||||
}
|
||||
catch (const std::exception& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "Failed to create the %s Goal checker , are you sure it is properly registered and that the containing library is built? Exception: %s", goal_checker_name.c_str(), ex.what());
|
||||
throw robot_nav_core2::LocalPlannerException("Failed to create goal checker");
|
||||
}
|
||||
|
||||
robot::log_info_at(__FILE__, __LINE__, "%s is sucessed", name.c_str());
|
||||
initialized_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXRotateLocalPlanner::reset()
|
||||
{
|
||||
robot::log_info_at(__FILE__, __LINE__, "New Goal Received.");
|
||||
this->unlock();
|
||||
if (traj_generator_)
|
||||
traj_generator_->reset();
|
||||
if (goal_checker_)
|
||||
goal_checker_->reset();
|
||||
if (nav_algorithm_)
|
||||
nav_algorithm_->reset();
|
||||
ret_nav_ = ret_angle_ = false;
|
||||
}
|
||||
|
||||
void pnkx_local_planner::PNKXRotateLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
this->getParams(planner_nh_);
|
||||
if (update_costmap_before_planning_)
|
||||
{
|
||||
info_.width = costmap_->getSizeInCellsX();
|
||||
info_.height = costmap_->getSizeInCellsY();
|
||||
info_.resolution = costmap_->getResolution();
|
||||
info_.frame_id = costmap_robot_->getGlobalFrameID();
|
||||
info_.origin_x = costmap_->getOriginX();
|
||||
info_.origin_y = costmap_->getOriginY();
|
||||
|
||||
if (!costmap_robot_->isCurrent())
|
||||
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
|
||||
}
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose),
|
||||
local_goal_pose = this->transformPoseToLocal(goal_pose_);
|
||||
try
|
||||
{
|
||||
if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_))
|
||||
throw robot_nav_core2::LocalPlannerException("Transform global plan is failed");
|
||||
}
|
||||
catch(const robot_nav_core2::LocalPlannerException& e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
|
||||
double x_direction, y_direction, theta_direction;
|
||||
if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
|
||||
}
|
||||
|
||||
int xytheta_direct[3];
|
||||
xytheta_direct[0] = x_direction != 0 ? fabs(x_direction) / x_direction : 0;
|
||||
xytheta_direct[1] = y_direction != 0 ? fabs(y_direction) / y_direction : 0;
|
||||
xytheta_direct[2] = theta_direction != 0 ? fabs(theta_direction) / theta_direction : 0;
|
||||
traj_generator_->setDirect(xytheta_direct);
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
// boost::recursive_mutex::scoped_lock l(configuration_mutex_);
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
try
|
||||
{
|
||||
if (global_plan_.poses.empty())
|
||||
return cmd_vel;
|
||||
this->prepare(pose, velocity);
|
||||
cmd_vel = this->ScoreAlgorithm(pose, velocity);
|
||||
return cmd_vel;
|
||||
}
|
||||
catch (const robot_nav_core2::PlannerException &e)
|
||||
{
|
||||
throw robot_nav_core2::LocalPlannerException(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXRotateLocalPlanner::ScoreAlgorithm(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
robot_nav_2d_msgs::Twist2D twist;
|
||||
mkt_msgs::Trajectory2D traj;
|
||||
robot_nav_2d_msgs::Twist2DStamped cmd_vel;
|
||||
cmd_vel.header.stamp = robot::Time::now();
|
||||
if (ret_nav_)
|
||||
{
|
||||
local_plan_.poses.clear();
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
traj = nav_algorithm_->calculator(pose, velocity);
|
||||
local_plan_.header.stamp = robot::Time::now();
|
||||
robot_nav_msgs::Path path = robot_nav_2d_utils::poses2DToPath(traj.poses, costmap_robot_->getBaseFrameID(), robot::Time::now());
|
||||
local_plan_ = robot_nav_2d_utils::pathToPath(path);
|
||||
cmd_vel.velocity = traj.velocity;
|
||||
return cmd_vel;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::PNKXRotateLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped& pose, const robot_nav_2d_msgs::Twist2D& velocity)
|
||||
{
|
||||
if (goal_pose_.header.frame_id == "")
|
||||
{
|
||||
robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!");
|
||||
return false;
|
||||
}
|
||||
// Update time stamp of goal pose
|
||||
// goal_pose_.header.stamp = pose.header.stamp;
|
||||
robot_nav_2d_msgs::Path2D empty;
|
||||
ret_nav_ = goal_checker_->isGoalReached(
|
||||
this->transformPoseToLocal(pose), this->transformPoseToLocal(goal_pose_), empty, velocity);
|
||||
|
||||
if (ret_nav_)
|
||||
robot::log_info_at(__FILE__, __LINE__, "Goal reached!");
|
||||
return ret_nav_;
|
||||
}
|
||||
|
||||
robot_nav_core2::LocalPlanner::Ptr pnkx_local_planner::PNKXRotateLocalPlanner::create()
|
||||
{
|
||||
return std::make_shared<pnkx_local_planner::PNKXRotateLocalPlanner>();
|
||||
}
|
||||
|
||||
// register this planner as a LocalPlanner plugin
|
||||
BOOST_DLL_ALIAS(pnkx_local_planner::PNKXRotateLocalPlanner::create, PNKXRotateLocalPlanner)
|
||||
@@ -0,0 +1,206 @@
|
||||
#include <pnkx_local_planner/transforms.h>
|
||||
#include <robot_nav_2d_utils/path_ops.h>
|
||||
#include <robot_nav_2d_utils/tf_help.h>
|
||||
#include <robot/robot.h>
|
||||
#include <data_convert/data_convert.h>
|
||||
#include <robot_tf3_geometry_msgs/tf3_geometry_msgs.h>
|
||||
|
||||
bool pnkx_local_planner::getPose(TFListenerPtr tf, std::string base_frame_id, std::string global_frame, robot_nav_2d_msgs::Pose2DStamped& global_pose, double transform_tolerance)
|
||||
{
|
||||
if (!tf)
|
||||
return false;
|
||||
|
||||
robot_geometry_msgs::PoseStamped global_pose_stamped;
|
||||
tf3::toMsg(tf3::Transform::getIdentity(), global_pose_stamped.pose);
|
||||
robot_geometry_msgs::PoseStamped robot_pose;
|
||||
tf3::toMsg(tf3::Transform::getIdentity(), robot_pose.pose);
|
||||
robot_pose.header.frame_id = base_frame_id;
|
||||
robot_pose.header.stamp = robot::Time();
|
||||
robot::Time current_time = robot::Time::now(); // save time for checking tf delay later
|
||||
|
||||
// Convert robot::Time to tf3::Time
|
||||
tf3::Time tf3_current_time = data_convert::convertTime(current_time);
|
||||
tf3::Time tf3_zero_time = data_convert::convertTime(robot::Time());
|
||||
|
||||
// get the global pose of the robot
|
||||
try
|
||||
{
|
||||
// use current time if possible (makes sure it's not in the future)
|
||||
std::string error_msg;
|
||||
if (tf->canTransform(global_frame, base_frame_id, tf3_current_time, &error_msg))
|
||||
{
|
||||
// Transform is available at current time
|
||||
tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_current_time);
|
||||
tf3::doTransform(robot_pose, global_pose_stamped, transform);
|
||||
}
|
||||
// use the latest otherwise (tf3::Time() means latest available)
|
||||
else
|
||||
{
|
||||
// Try to get latest transform
|
||||
tf3::TransformStampedMsg transform = tf->lookupTransform(global_frame, base_frame_id, tf3_zero_time);
|
||||
tf3::doTransform(robot_pose, global_pose_stamped, transform);
|
||||
}
|
||||
global_pose = robot_nav_2d_utils::poseStampedToPose2D(global_pose_stamped);
|
||||
}
|
||||
catch (tf3::LookupException& ex)
|
||||
{
|
||||
robot::log_warning_throttle(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what());
|
||||
return false;
|
||||
// throw robot_nav_core2::LocalPlannerException(ex.what());
|
||||
}
|
||||
catch (tf3::ConnectivityException& ex)
|
||||
{
|
||||
robot::log_warning_throttle(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what());
|
||||
return false;
|
||||
// throw robot_nav_core2::LocalPlannerException(ex.what());
|
||||
}
|
||||
catch (tf3::ExtrapolationException& ex)
|
||||
{
|
||||
robot::log_warning_throttle(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what());
|
||||
return false;
|
||||
// throw robot_nav_core2::LocalPlannerException(ex.what());
|
||||
}
|
||||
// check global_pose timeout
|
||||
if (!global_pose_stamped.header.stamp.isZero() && current_time.toSec() - global_pose_stamped.header.stamp.toSec() > transform_tolerance)
|
||||
{
|
||||
robot::log_warning_throttle(1.0, "Local Planner transform %s %s timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f", base_frame_id.c_str(), global_frame.c_str(),
|
||||
current_time.toSec(), global_pose_stamped.header.stamp.toSec(), transform_tolerance);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::transformGlobalPose(TFListenerPtr tf, const std::string& global_frame,
|
||||
const robot_nav_2d_msgs::Pose2DStamped& stamped_pose, robot_nav_2d_msgs::Pose2DStamped& newer_pose)
|
||||
{
|
||||
if (tf == nullptr)
|
||||
return false;
|
||||
bool result = robot_nav_2d_utils::transformPose(tf, global_frame, stamped_pose, newer_pose);
|
||||
newer_pose.header.seq = stamped_pose.header.seq;
|
||||
return result;
|
||||
}
|
||||
|
||||
double pnkx_local_planner::getSquareDistance(const robot_geometry_msgs::Pose2D& pose_a, const robot_geometry_msgs::Pose2D& pose_b)
|
||||
{
|
||||
double x_diff = pose_a.x - pose_b.x;
|
||||
double y_diff = pose_a.y - pose_b.y;
|
||||
return x_diff * x_diff + y_diff * y_diff;
|
||||
}
|
||||
|
||||
bool pnkx_local_planner::transformGlobalPlan(
|
||||
TFListenerPtr tf, const robot_nav_2d_msgs::Path2D& global_plan, const robot_nav_2d_msgs::Pose2DStamped& pose,
|
||||
const robot_costmap_2d::Costmap2DROBOT* costmap, const std::string& global_frame, double max_plan_length,
|
||||
robot_nav_2d_msgs::Path2D& transformed_plan, const bool from_global_frame)
|
||||
{
|
||||
if (global_plan.poses.size() == 0)
|
||||
{
|
||||
robot::log_warning("Received plan with zero length");
|
||||
throw robot_nav_core2::PlannerException("Received plan with zero length");
|
||||
}
|
||||
|
||||
transformed_plan.poses.clear();
|
||||
if (tf == nullptr)
|
||||
throw robot_nav_core2::PlannerException("TFListenerPtr is null");
|
||||
|
||||
if (global_plan.poses.empty())
|
||||
throw robot_nav_core2::PlannerException("Received plan with zero length");
|
||||
|
||||
try
|
||||
{
|
||||
// let's get the pose of the robot in the frame of the plan
|
||||
robot_nav_2d_msgs::Pose2DStamped robot_pose;
|
||||
if (!robot_nav_2d_utils::transformPose(tf, global_plan.header.frame_id, pose, robot_pose))
|
||||
{
|
||||
throw robot_nav_core2::PlannerTFException("transformGlobalPlan: Unable to transform robot pose into global plan's frame");
|
||||
}
|
||||
|
||||
transformed_plan.header.frame_id = costmap->getGlobalFrameID();
|
||||
transformed_plan.header.stamp = pose.header.stamp;
|
||||
|
||||
robot_nav_2d_msgs::Pose2DStamped new_pose;
|
||||
robot_nav_2d_msgs::Pose2DStamped stamped_pose;
|
||||
stamped_pose.header.frame_id = global_plan.header.frame_id;
|
||||
|
||||
for (unsigned int i = 0; i < global_plan.poses.size(); i++)
|
||||
{
|
||||
// now we'll transform until points are outside of our distance threshold
|
||||
stamped_pose = global_plan.poses[i];
|
||||
if (pnkx_local_planner::transformGlobalPose(tf, global_frame, global_plan.poses[i], new_pose))
|
||||
{
|
||||
transformed_plan.poses.push_back(new_pose);
|
||||
}
|
||||
}
|
||||
|
||||
// Prune both plans based on robot position
|
||||
// Note that this part of the algorithm assumes that the global plan starts near the robot (at one point)
|
||||
// Otherwise it may take a few iterations to converge to the proper behavior
|
||||
|
||||
// let's get the pose of the robot in the frame of the transformed_plan/costmap
|
||||
robot_nav_2d_msgs::Pose2DStamped costmap_pose;
|
||||
if (!robot_nav_2d_utils::transformPose(tf, transformed_plan.header.frame_id, pose, costmap_pose))
|
||||
{
|
||||
throw robot_nav_core2::PlannerTFException("Unable to transform robot pose into costmap's frame");
|
||||
}
|
||||
|
||||
robot::log_assert(global_plan.poses.size() >= transformed_plan.poses.size(), "Global plan size is less than transformed plan size");
|
||||
|
||||
std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator it = transformed_plan.poses.begin();
|
||||
|
||||
double sq_prune_dist = 0.1;
|
||||
|
||||
std::vector<robot_geometry_msgs::Point> footprint = costmap->getRobotFootprint();
|
||||
size_t n = footprint.size();
|
||||
if (n > 1)
|
||||
{
|
||||
double max_length = 0.0;
|
||||
for (size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const robot_geometry_msgs::Point& p1 = footprint[i];
|
||||
const robot_geometry_msgs::Point& p2 = footprint[(i + 1) % n]; // wrap around to first point
|
||||
double len = std::hypot(p2.x - p1.x, p2.y - p1.y);
|
||||
if (len > max_length)
|
||||
{
|
||||
max_length = len;
|
||||
}
|
||||
}
|
||||
sq_prune_dist += max_length;
|
||||
}
|
||||
// if(from_global_frame) sq_prune_dist = 0;
|
||||
while (it != transformed_plan.poses.end())
|
||||
{
|
||||
const robot_nav_2d_msgs::Pose2DStamped& w = *it;
|
||||
// Fixed error bound of 1 meter for now. Can reduce to a portion of the map size or based on the resolution
|
||||
if (pnkx_local_planner::getSquareDistance(costmap_pose.pose, w.pose) < sq_prune_dist)
|
||||
{
|
||||
// robot::log_debug_at(__FILE__, __LINE__, "Nearest waypoint to <%f, %f> is <%f, %f>\n",
|
||||
// costmap_pose.pose.x, costmap_pose.pose.y, w.pose.x, w.pose.y);
|
||||
break;
|
||||
}
|
||||
|
||||
it = transformed_plan.poses.erase(it);
|
||||
}
|
||||
|
||||
if (transformed_plan.poses.size() == 0)
|
||||
{
|
||||
throw robot_nav_core2::PlannerTFException("Resulting plan has 0 poses in it.");
|
||||
}
|
||||
}
|
||||
catch (tf3::LookupException& ex)
|
||||
{
|
||||
robot::log_error_at(__FILE__, __LINE__, "No Transform available Error: %s\n", ex.what());
|
||||
return false;
|
||||
}
|
||||
catch (tf3::ConnectivityException& ex)
|
||||
{
|
||||
robot::log_error("Connectivity Error: %s\n", ex.what());
|
||||
return false;
|
||||
}
|
||||
catch (tf3::ExtrapolationException& ex)
|
||||
{
|
||||
robot::log_error("Extrapolation Error: %s\n", ex.what());
|
||||
if (global_plan.poses.size() > 0)
|
||||
robot::log_error("[%s:%d]\n Robot Frame: %s Plan Frame size %d: %s\n", __FILE__, __LINE__, global_frame.c_str(), (unsigned int)global_plan.poses.size(), global_plan.header.frame_id.c_str());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
Submodule src/Algorithms/Packages/local_planners/priest_local_planner added at 86be89fec7
1
src/Algorithms/Packages/recoveries/sbpl_recovery
Submodule
1
src/Algorithms/Packages/recoveries/sbpl_recovery
Submodule
Submodule src/Algorithms/Packages/recoveries/sbpl_recovery added at d1fd7230c0
Reference in New Issue
Block a user