### Install Other Project Files Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Installs miscellaneous files such as launch files or bag files into the share destination of the ROS package. This uses the `install(FILES)` command to specify the files to be installed. ```cmake install(FILES # myfile1 # myfile2 DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} ) ``` -------------------------------- ### C++ Trajectory Optimization Setup and Execution with GCOPTER Source: https://context7.com/zju-fast-lab/gcopter/llms.txt This C++ code snippet demonstrates how to initialize, set up, and execute trajectory optimization using the GCOPTER library. It defines initial and terminal states, a safe flight corridor, constraint bounds, penalty weights, and physical parameters. The setup function configures the optimizer, and the optimize function computes the trajectory, reporting success or failure along with cost and trajectory details. ```cpp #include "gcopter/gcopter.hpp" #include "gcopter/trajectory.hpp" #include #include #include // Initialize optimizer gcopter::GCOPTER_PolytopeSFC gcopter; // Define initial and terminal states [position, velocity, acceleration] Eigen::Matrix3d initialPVA; initialPVA << 0.0, 0.0, 1.0, // position 0.0, 0.0, 0.0, // velocity 0.0, 0.0, 0.0; // acceleration Eigen::Matrix3d terminalPVA; terminalPVA << 10.0, 10.0, 2.0, // position 0.0, 0.0, 0.0, // velocity 0.0, 0.0, 0.0; // acceleration // Define safe corridor as H-representation polytopes std::vector safeCorridor; // [nx, ny, nz, d] where n'*x + d <= 0 // Set constraint bounds [v_max, omg_max, theta_max, thrust_min, thrust_max] Eigen::VectorXd magnitudeBounds(5); magnitudeBounds << 4.0, // max velocity (m/s) 2.1, // max angular velocity (rad/s) 1.05, // max tilt angle (rad) 2.0, // min thrust (N) 12.0; // max thrust (N) // Set penalty weights [pos_weight, vel_weight, omg_weight, theta_weight, thrust_weight] Eigen::VectorXd penaltyWeights(5); penaltyWeights << 1.0e4, 1.0e4, 1.0e4, 1.0e4, 1.0e5; // Set physical parameters [mass, gravity, horiz_drag, vert_drag, parasitic_drag, speed_eps] Eigen::VectorXd physicalParams(6); physicalParams << 0.61, // vehicle mass (kg) 9.8, // gravitational acceleration (m/s^2) 0.70, // horizontal drag coefficient 0.80, // vertical drag coefficient 0.01, // parasitic drag coefficient 0.0001; // speed smoothing factor // Setup optimizer if (!gcopter.setup(20.0, // time weight initialPVA, // initial state terminalPVA, // terminal state safeCorridor, // safe flight corridor INFINITY, // length per piece (use INFINITY for auto) 1.0e-2, // smoothing factor 16, // integral resolution magnitudeBounds, // magnitude bounds penaltyWeights, // penalty weights physicalParams)) // physical parameters { std::cerr << "Setup failed" << std::endl; return -1; } // Optimize trajectory Trajectory<5> trajectory; double cost = gcopter.optimize(trajectory, 1.0e-5); // relative cost tolerance if (std::isinf(cost)) { std::cerr << "Optimization failed" << std::endl; } else { std::cout << "Optimization succeeded with cost: " << cost << std::endl; std::cout << "Trajectory pieces: " << trajectory.getPieceNum() << std::endl; std::cout << "Total duration: " << trajectory.getTotalDuration() << " s" << std::endl; } ``` -------------------------------- ### Install CMake Executable Scripts (Python) Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Installs executable scripts, like Python scripts, into a specified destination within the ROS package structure. This uses the `install(PROGRAMS)` command and allows setting a custom destination, unlike `setup.py`. ```cmake install(PROGRAMS scripts/my_python_script DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) ``` -------------------------------- ### Install CMake Executable and Library Targets Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Marks executables and/or libraries for installation into standard ROS package destinations (ARCHIVE, LIBRARY, RUNTIME). This ensures that built artifacts are correctly placed for runtime access. ```cmake install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} ) ``` -------------------------------- ### Install C++ Header Files Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Installs C++ header files from a specified directory into the include destination of the ROS package. It includes options to match specific file patterns and exclude certain directories like `.svn`. ```cmake install(DIRECTORY include/${PROJECT_NAME}/ DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} FILES_MATCHING PATTERN "*.h" PATTERN ".svn" EXCLUDE ) ``` -------------------------------- ### CMake Executable Creation and Linking Source: https://github.com/zju-fast-lab/gcopter/blob/main/gcopter/CMakeLists.txt Defines the 'global_planning' executable from its source file 'src/global_planning.cpp'. It then links this executable against the required OMPL and Catkin libraries. ```cmake add_executable(global_planning src/global_planning.cpp) target_link_libraries(global_planning ${OMPL_LIBRARIES} ${catkin_LIBRARIES} ) ``` -------------------------------- ### Include Directories Configuration Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Specifies additional directories where header files can be found. It includes the local 'include' directory of the package and the include directories from found catkin packages, ensuring that all necessary header files are accessible during compilation. ```cmake ## Specify additional locations of header files ## Your package locations should be listed before other locations include_directories( include ${catkin_INCLUDE_DIRS} ) ``` -------------------------------- ### C++ ROS Global Trajectory Planning with GCopter Source: https://context7.com/zju-fast-lab/gcopter/llms.txt This C++ code snippet demonstrates the ROS integration for global trajectory planning. It initializes ROS, loads parameters from the parameter server, sets up a voxel map for obstacle representation, plans a route, generates a safe flight corridor (SFC), and optimizes a trajectory using the GCopter library. Dependencies include ROS, Eigen, and custom GCopter libraries. ```cpp #include #include #include #include "gcopter/voxel_map.hpp" #include "gcopter/sfc_gen.hpp" #include "gcopter/gcopter.hpp" // Initialize ROS node ros::init(argc, argv, "global_planning_node"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); // Load configuration from parameter server double maxVel, maxTiltAngle, minThrust, maxThrust; double vehicleMass, gravAcc, horizDrag, vertDrag, parasDrag; std::vector chiVec; nh_private.getParam("MaxVelMag", maxVel); nh_private.getParam("MaxTiltAngle", maxTiltAngle); nh_private.getParam("MinThrust", minThrust); nh_private.getParam("MaxThrust", maxThrust); nh_private.getParam("VehicleMass", vehicleMass); nh_private.getParam("GravAcc", gravAcc); nh_private.getParam("HorizDrag", horizDrag); nh_private.getParam("VertDrag", vertDrag); nh_private.getParam("ParasDrag", parasDrag); nh_private.getParam("ChiVec", chiVec); // Initialize voxel map for obstacle representation voxel_map::VoxelMap voxelMap; Eigen::Vector3i gridSize(200, 200, 20); // 200x200x20 voxels Eigen::Vector3d offset(-25.0, -25.0, 0.0); double voxelWidth = 0.25; voxelMap = voxel_map::VoxelMap(gridSize, offset, voxelWidth); // Generate path through obstacles std::vector route; Eigen::Vector3d start(0.0, 0.0, 1.0); Eigen::Vector3d goal(10.0, 10.0, 2.0); sfc_gen::planPath( start, goal, voxelMap.getOrigin(), voxelMap.getCorner(), &voxelMap, 0.01, // resolution route); // Generate safe flight corridor (SFC) from route std::vector hPolys; // H-representation polytopes std::vector pointCloud; voxelMap.getSurf(pointCloud); sfc_gen::convexCover(route, pointCloud, voxelMap.getOrigin(), voxelMap.getCorner(), 7.0, // maximum side length 3.0, // minimum side length hPolys); sfc_gen::shortCut(hPolys); // optimize corridor // Setup and optimize trajectory Eigen::Matrix3d iniState, finState; iniState << start, Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(); finState << goal, Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(); gcopter::GCOPTER_PolytopeSFC gcopter; Eigen::VectorXd magnitudeBounds(5); magnitudeBounds << maxVel, 2.1, maxTiltAngle, minThrust, maxThrust; Eigen::VectorXd penaltyWeights(5); penaltyWeights << chiVec[0], chiVec[1], chiVec[2], chiVec[3], chiVec[4]; Eigen::VectorXd physicalParams(6); physicalParams << vehicleMass, gravAcc, horizDrag, vertDrag, parasDrag, 0.0001; if (gcopter.setup(20.0, iniState, finState, hPolys, INFINITY, 1.0e-2, 16, magnitudeBounds, penaltyWeights, physicalParams)) { Trajectory<5> traj; double cost = gcopter.optimize(traj, 1.0e-5); if (!std::isinf(cost)) { ROS_INFO("Trajectory optimized successfully!"); ROS_INFO("Duration: %.2f s, Cost: %.4f", traj.getTotalDuration(), cost); } } ros::spin(); ``` -------------------------------- ### CMake Include Directories and Package Definition Source: https://github.com/zju-fast-lab/gcopter/blob/main/gcopter/CMakeLists.txt Specifies the directories to be included during compilation, such as Catkin, OMPL, Eigen3, and local 'include' directories. It also declares the package using 'catkin_package'. ```cmake include_directories( ${catkin_INCLUDE_DIRS} ${OMPL_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIRS} include ) catkin_package() ``` -------------------------------- ### Query Trajectory States and Metrics (C++) Source: https://context7.com/zju-fast-lab/gcopter/llms.txt This C++ snippet demonstrates how to query position, velocity, acceleration, and jerk of an optimized trajectory at a specific time instant. It also shows how to retrieve overall trajectory metrics like total duration, maximum velocity/acceleration rates, and waypoint positions. It assumes a pre-optimized Trajectory object is available. ```cpp #include "gcopter/trajectory.hpp" #include #include // Assuming 'trajectory' is already optimized Trajectory<5> trajectory; double t = 2.5; // query time in seconds // Query position Eigen::Vector3d position = trajectory.getPos(t); std::cout << "Position at t=" << t << ": [" << position.x() << ", " << position.y() << ", " << position.z() << "]" << std::endl; // Query velocity Eigen::Vector3d velocity = trajectory.getVel(t); std::cout << "Velocity magnitude: " << velocity.norm() << " m/s" << std::endl; // Query acceleration Eigen::Vector3d acceleration = trajectory.getAcc(t); std::cout << "Acceleration: [" << acceleration.x() << ", " << acceleration.y() << ", " << acceleration.z() << "]" << std::endl; // Query jerk Eigen::Vector3d jerk = trajectory.getJer(t); // Get trajectory metrics double totalDuration = trajectory.getTotalDuration(); double maxVel = trajectory.getMaxVelRate(); double maxAcc = trajectory.getMaxAccRate(); std::cout << "Max velocity rate: " << maxVel << " m/s" << std::endl; std::cout << "Max acceleration rate: " << maxAcc << " m/s^2" << std::endl; // Iterate through all trajectory pieces for (int i = 0; i < trajectory.getPieceNum(); i++) { const Piece<5>& piece = trajectory[i]; double duration = piece.getDuration(); std::cout << "Piece " << i << " duration: " << duration << " s" << std::endl; } // Get waypoint positions at piece boundaries Eigen::Matrix3Xd waypoints = trajectory.getPositions(); std::cout << "Number of waypoints: " << waypoints.cols() << std::endl; ``` -------------------------------- ### CMake Build Configuration for gcopter Source: https://github.com/zju-fast-lab/gcopter/blob/main/gcopter/CMakeLists.txt Sets the minimum required CMake version, project name, C++ standard, build type, and release-specific compiler flags for optimization and warnings. It then finds essential external libraries and Catkin packages. ```cmake cmake_minimum_required(VERSION 2.8.3) project(gcopter) set(CMAKE_CXX_FLAGS "-std=c++14") set(CMAKE_BUILD_TYPE "Release") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -Wall -fPIC") find_package(Eigen3 REQUIRED) find_package(ompl REQUIRED) find_package(catkin REQUIRED COMPONENTS roscpp std_msgs geometry_msgs sensor_msgs visualization_msgs ) ``` -------------------------------- ### YAML Configuration for ROS Global Planning Source: https://context7.com/zju-fast-lab/gcopter/llms.txt This YAML file defines the configuration parameters for the ROS-based global trajectory planning system. It specifies topics for map and goal data, map parameters like voxel size and bounds, vehicle constraints (velocity, tilt angle, thrust), physical parameters of the vehicle, and optimization settings. This configuration is loaded by the ROS node to customize the planning process. ```yaml # global_planning.yaml MapTopic: '/voxel_map' TargetTopic: '/move_base_simple/goal' # Map parameters DilateRadius: 0.5 # obstacle inflation radius (m) VoxelWidth: 0.25 # voxel size (m) MapBound: [-25.0, 25.0, -25.0, 25.0, 0.0, 5.0] # [xmin, xmax, ymin, ymax, zmin, zmax] # Vehicle constraints MaxVelMag: 4.0 # maximum velocity (m/s) MaxBdrMag: 2.1 # maximum angular velocity (rad/s) MaxTiltAngle: 1.05 # maximum tilt angle (rad ≈ 60°) MinThrust: 2.0 # minimum thrust (N) MaxThrust: 12.0 # maximum thrust (N) # Physical parameters VehicleMass: 0.61 # quadrotor mass (kg) GravAcc: 9.8 # gravitational acceleration (m/s²) HorizDrag: 0.70 # horizontal drag coefficient VertDrag: 0.80 # vertical drag coefficient ParasDrag: 0.01 # parasitic drag coefficient SpeedEps: 0.0001 # speed smoothing factor # Optimization parameters WeightT: 20.0 # time weight in cost function ChiVec: [1.0e+4, 1.0e+4, 1.0e+4, 1.0e+4, 1.0e+5] # penalty weights SmoothingEps: 1.0e-2 # smoothing epsilon for L1 penalty IntegralIntervs: 16 # integration intervals per piece RelCostTol: 1.0e-5 # relative cost tolerance for convergence # RRT parameters TimeoutRRT: 0.02 # RRT planning timeout (s) ``` -------------------------------- ### Set C++ Standard and Find Catkin Packages Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Sets the C++ compilation standard to C++14, which is supported in ROS Kinetic and newer distributions. It then finds essential catkin packages required for the project, including roscpp for ROS client library, pcl_ros for PCL ROS integration, and pcl_conversions for PCL data type conversions. ```cmake cmake_minimum_required(VERSION 2.8.3) project(mockamap) ## Compile as C++14, supported in ROS Kinetic and newer add_compile_options(-std=c++14) ## Find catkin macros and libraries ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) ## is used, also find other catkin packages find_package(catkin REQUIRED COMPONENTS roscpp pcl_ros pcl_conversions ) ``` -------------------------------- ### Declare C++ Executable Target Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Defines a C++ executable target for the ROS node. It uses 'file(GLOB ...)' to find all '.cpp' files in the 'src' directory and compiles them into an executable named '${PROJECT_NAME}_node'. This is a common pattern for building ROS nodes. ```cmake ## Declare a C++ executable ## With catkin_make all packages are built within a single CMake context ## The recommended prefix ensures that target names across packages don't collide file(GLOB ${PROJECT_NAME}_SRCS src/*.cpp) add_executable(${PROJECT_NAME}_node ${${PROJECT_NAME}_SRCS}) ``` -------------------------------- ### Add CMake Target Dependencies Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Specifies dependencies for a CMake executable target, ensuring that other targets, like exported targets from the project or catkin, are built before this one. This is equivalent to setting dependencies for a library. ```cmake add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) ``` -------------------------------- ### Add C++ Google Test Target Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Adds a C++ test target using Google Test and links the necessary libraries, including the project's main target. This enables running unit tests for the C++ code. ```cmake catkin_add_gtest(${PROJECT_NAME}-test test/test_mockamap.cpp) if(TARGET ${PROJECT_NAME}-test) target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}) endif() ``` -------------------------------- ### Link Libraries to CMake Executable Target Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Links the specified libraries, such as catkin libraries, to a CMake executable target. This is essential for resolving symbols and ensuring the executable can run correctly. ```cmake target_link_libraries(${PROJECT_NAME}_node ${catkin_LIBRARIES} ) ``` -------------------------------- ### Declare Catkin Package Dependencies Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Declares the catkin package and its dependencies. This macro generates CMake configuration files, allowing other catkin packages to find and use this package. It specifies include directories and the catkin packages that this project depends on. ```cmake catkin_package( INCLUDE_DIRS include # LIBRARIES mockamap CATKIN_DEPENDS roscpp pcl_ros pcl_conversions # DEPENDS system_lib ) ``` -------------------------------- ### Map Trajectory Derivatives to Control Inputs (C++) Source: https://context7.com/zju-fast-lab/gcopter/llms.txt This C++ snippet illustrates differential flatness mapping, converting trajectory derivatives (velocity, acceleration, jerk) into quadrotor control inputs such as thrust, attitude (quaternion), and body angular velocity. It requires initializing a FlatnessMap object with vehicle parameters and then using the forward mapping function. The snippet also includes checks for control constraints. ```cpp #include "gcopter/flatness.hpp" #include #include #include // Assuming 'trajectory' is defined and optimized elsewhere // Trajectory<5> trajectory; // Initialize flatness mapper with vehicle parameters flatness::FlatnessMap flatmap; flatmap.reset(0.61, // vehicle mass (kg) 9.8, // gravitational acceleration (m/s^2) 0.70, // horizontal drag coefficient 0.80, // vertical drag coefficient 0.01, // parasitic drag coefficient 0.0001); // speed smoothing factor // Get trajectory derivatives at time t double t = 1.0; Eigen::Vector3d vel = trajectory.getVel(t); Eigen::Vector3d acc = trajectory.getAcc(t); Eigen::Vector3d jer = trajectory.getJer(t); // Forward mapping: trajectory derivatives → control inputs double thrust; Eigen::Vector4d quaternion; // [w, x, y, z] Eigen::Vector3d angularVelocity; flatmap.forward(vel, // velocity acc, // acceleration jer, // jerk 0.0, // yaw angle (psi) 0.0, // yaw rate (dpsi) thrust, // output: thrust magnitude quaternion, // output: attitude quaternion angularVelocity); // output: body angular velocity // Extract useful control information double tiltAngle = acos(1.0 - 2.0 * (quaternion(1) * quaternion(1) + quaternion(2) * quaternion(2))); double bodyRateMagnitude = angularVelocity.norm(); std::cout << "Thrust: " << thrust << " N" << std::endl; std::cout << "Tilt angle: " << tiltAngle << " rad (" << tiltAngle * 180.0 / M_PI << " deg)" << std::endl; std::cout << "Body rate: " << bodyRateMagnitude << " rad/s" << std::endl; std::cout << "Angular velocity: [" << angularVelocity.x() << ", " << angularVelocity.y() << ", " << angularVelocity.z() << "]" << std::endl; // Verify constraints are satisfied if (thrust < 2.0 || thrust > 12.0) { std::cerr << "Thrust constraint violated!" << std::endl; } if (tiltAngle > 1.05) { std::cerr << "Tilt angle constraint violated!" << std::endl; } if (bodyRateMagnitude > 2.1) { std::cerr << "Angular velocity constraint violated!" << std::endl; } ``` -------------------------------- ### Add Python Nosetests Target Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Adds a test target for Python using `nosetests`. This command discovers and runs Python tests within the specified test directories. ```cmake catkin_add_nosetests(test) ``` -------------------------------- ### Sample Trajectory Points in C++ Source: https://context7.com/zju-fast-lab/gcopter/llms.txt Samples a trajectory at specified time intervals (dt) and prints the position, velocity, and acceleration at each interval. It retrieves these values using the trajectory's getPos, getVel, and getAcc methods. Requires the 'gcopter/trajectory.hpp' header and Eigen for vector operations. ```cpp #include "gcopter/trajectory.hpp" #include // Sample trajectory at regular intervals void sampleTrajectory(const Trajectory<5>& traj, double dt = 0.01) { double T = traj.getTotalDuration(); for (double t = 0.0; t <= T; t += dt) { Eigen::Vector3d pos = traj.getPos(t); Eigen::Vector3d vel = traj.getVel(t); Eigen::Vector3d acc = traj.getAcc(t); std::cout << t << " " << pos.transpose() << " " << vel.transpose() << " " << acc.transpose() << std::endl; } } ``` -------------------------------- ### Set CMake Executable Output Name Source: https://github.com/zju-fast-lab/gcopter/blob/main/map_gen/mockamap/CMakeLists.txt Configures the output name for a CMake executable target. It removes the default 'PREFIX' and sets the 'OUTPUT_NAME' to 'node', useful for simplifying ROS node execution commands. ```cmake set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "") ``` -------------------------------- ### Validate Trajectory Constraints in C++ Source: https://context7.com/zju-fast-lab/gcopter/llms.txt Validates a given trajectory against specified maximum velocity and acceleration constraints. It checks both direct calculations and uses built-in trajectory methods. Returns true if all constraints are met, false otherwise. Requires the 'gcopter/trajectory.hpp' header and Eigen for vector operations. ```cpp #include "gcopter/trajectory.hpp" #include // Validate trajectory against constraints bool validateTrajectory(const Trajectory<5>& traj, double maxVel, double maxAcc) { bool valid = true; // Check velocity constraints double actualMaxVel = traj.getMaxVelRate(); if (actualMaxVel > maxVel) { std::cerr << "Velocity constraint violated: " << actualMaxVel << " > " << maxVel << std::endl; valid = false; } // Check acceleration constraints double actualMaxAcc = traj.getMaxAccRate(); if (actualMaxAcc > maxAcc) { std::cerr << "Acceleration constraint violated: " << actualMaxAcc << " > " << maxAcc << std::endl; valid = false; } // Alternative: use built-in checkers if (!traj.checkMaxVelRate(maxVel)) { std::cerr << "Velocity check failed" << std::endl; valid = false; } if (!traj.checkMaxAccRate(maxAcc)) { std::cerr << "Acceleration check failed" << std::endl; valid = false; } return valid; } // Usage // Trajectory<5> trajectory; // ... optimize trajectory ... // if (validateTrajectory(trajectory, 4.0, 20.0)) { // std::cout << "Trajectory validation passed!" << std::endl; // } else { // std::cerr << "Trajectory validation failed!" << std::endl; // } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.