Merge dev updates and simplify joint-only arm configurations

Keep dev EtherCAT/TCHL/Eyou implementations and unified RobotModel; preserve Lingkong CAN grouping and existing client APIs. Simplify TCHL dual arm, Lingkong neck and Eyou dual arm following the tchl_arm template. Retain legacy hand configuration compatibility alongside the new touch devices. Disable repository device defaults. Validate Release cmvr_es, eight offline/simulation test suites, and arm protobuf configuration parsing.
This commit is contained in:
xtkuang 2026-11-19 09:57:46 +08:00
commit 55736f58ff
317 changed files with 2375844 additions and 15304 deletions

View File

@ -69,7 +69,7 @@ function(setup_external_libs ARCH)
set(HAS_LIB TRUE)
# Collect shared libs for install: *.so and *.so.*
file(GLOB _SO_FILES
file(GLOB _SO_FILES CONFIGURE_DEPENDS
"${FULL_PATH}/lib/*.so"
"${FULL_PATH}/lib/*.so.*"
)
@ -91,7 +91,7 @@ function(setup_external_libs ARCH)
set(HAS_LIB TRUE)
# Only install Linux shared libs from base dir
file(GLOB _SO_FILES2
file(GLOB _SO_FILES2 CONFIGURE_DEPENDS
"${FULL_PATH}/*.so"
"${FULL_PATH}/*.so.*"
)

View File

@ -8,6 +8,7 @@ add_subdirectory(environment)
add_subdirectory(algorithms)
add_subdirectory(simulate)
add_subdirectory(devices)
add_subdirectory(safety)
add_subdirectory(manager/device_manager)
add_subdirectory(manager/media_source_hub)
add_subdirectory(service/quic_edge)

View File

@ -1,4 +1,3 @@
add_subdirectory(motion_planner)
add_subdirectory(planner)
add_subdirectory(smoother)
add_subdirectory(kinematics/ik_solver)

View File

@ -1,52 +1,3 @@
add_library(self_collision_checker SHARED
self_collision/src/self_collision_checker.cpp
self_collision/src/distance_sampling_policy.cpp
)
target_include_directories(self_collision_checker PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
)
target_compile_definitions(self_collision_checker PRIVATE
PINOCCHIO_ENABLE_TEMPLATE_INSTANTIATION
PINOCCHIO_WITH_HPP_FCL
COAL_DISABLE_HPP_FCL_WARNINGS
)
target_link_libraries(self_collision_checker PUBLIC
pinocchio_default
pinocchio_parsers
pinocchio_collision
coal
)
add_library(cmvr_es::self_collision_checker ALIAS self_collision_checker)
add_executable(self_collision_checker_test
self_collision/test/self_collision_checker_test.cpp
)
target_link_libraries(self_collision_checker_test PRIVATE
cmvr_es::self_collision_checker
gtest
gtest_main
pthread
)
target_compile_definitions(self_collision_checker_test PRIVATE
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
)
add_executable(self_collision_benchmark
self_collision/benchmark/self_collision_benchmark.cpp
)
target_link_libraries(self_collision_benchmark PRIVATE
cmvr_es::self_collision_checker
)
target_compile_definitions(self_collision_benchmark PRIVATE
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
)
install(TARGETS self_collision_checker LIBRARY DESTINATION lib)
add_library(collision_checker SHARED
src/collision_checker.cpp
src/distance_sampling_policy.cpp
@ -81,13 +32,13 @@ target_compile_definitions(collision_checker_test PRIVATE
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
)
add_executable(lgv_collision_benchmark
add_executable(self_collision_benchmark
benchmark/collision_benchmark.cpp
)
target_link_libraries(lgv_collision_benchmark PRIVATE
target_link_libraries(self_collision_benchmark PRIVATE
cmvr_es::collision_checker
)
target_compile_definitions(lgv_collision_benchmark PRIVATE
target_compile_definitions(self_collision_benchmark PRIVATE
CMVR_ES_SOURCE_DIR="${PROJECT_SOURCE_DIR}"
)

View File

@ -14,7 +14,7 @@ struct DistanceSamplingOptions {
double max_check_period_s{0.01};
};
class LgvDistanceSamplingPolicy {
class DistanceSamplingPolicy {
public:
using Clock = std::chrono::steady_clock;

View File

@ -1,53 +0,0 @@
#include <algorithm>
#include <chrono>
#include <iostream>
#include <string>
#include <vector>
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
int main()
{
const std::string urdf_path = std::string(CMVR_ES_SOURCE_DIR) +
"/model/xiaoyan_description/dual_arm_collision.urdf";
const std::vector<std::string> joint_names{
"R_SHOULDER_P", "R_SHOULDER_R", "R_SHOULDER_Y", "R_ELBOW_R",
"R_WRIST_P", "R_WRIST_Y", "R_WRIST_R",
};
cmvr::SelfCollisionChecker checker;
std::string error;
if (!checker.init(urdf_path, joint_names, {}, &error)) {
std::cerr << "Initialization failed: " << error << '\n';
return 1;
}
constexpr std::size_t kIterations = 2000;
std::vector<double> samples_us;
samples_us.reserve(kIterations);
std::vector<double> q(joint_names.size(), 0.0);
for (std::size_t iteration = 0; iteration < kIterations; ++iteration) {
q[0] = 0.2 * static_cast<double>(iteration % 100) / 100.0;
const auto begin = std::chrono::steady_clock::now();
const auto result = checker.check(q);
const auto end = std::chrono::steady_clock::now();
if (!result.valid) {
std::cerr << "Collision check failed: " << result.error << '\n';
return 1;
}
samples_us.push_back(std::chrono::duration<double, std::micro>(end - begin).count());
}
std::sort(samples_us.begin(), samples_us.end());
double total_us = 0.0;
for (const double sample : samples_us) {
total_us += sample;
}
const std::size_t p99_index = static_cast<std::size_t>(0.99 * (samples_us.size() - 1));
std::cout << "active_pairs=" << checker.activePairCount() << '\n'
<< "iterations=" << samples_us.size() << '\n'
<< "average_us=" << total_us / samples_us.size() << '\n'
<< "p99_us=" << samples_us[p99_index] << '\n'
<< "max_us=" << samples_us.back() << '\n';
return 0;
}

View File

@ -1,46 +0,0 @@
#ifndef CMVR_ES_DISTANCE_SAMPLING_POLICY_H
#define CMVR_ES_DISTANCE_SAMPLING_POLICY_H
#include <chrono>
#include <string>
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
namespace cmvr {
struct DistanceSamplingOptions {
double max_geometry_displacement_m{0.002};
double max_check_period_s{0.01};
};
class DistanceSamplingPolicy {
public:
using Clock = std::chrono::steady_clock;
bool configure(const DistanceSamplingOptions& options,
std::string* error = nullptr);
bool shouldCheck(const CollisionGeometrySnapshot& current,
Clock::time_point now) const;
void markChecked(const CollisionGeometrySnapshot& current,
Clock::time_point now);
void reset();
double displacementSinceLastCheck(
const CollisionGeometrySnapshot& current) const;
bool hasBaseline() const { return has_baseline_; }
private:
DistanceSamplingOptions options_{};
CollisionGeometrySnapshot last_checked_{};
Clock::time_point last_check_time_{};
bool configured_{false};
bool has_baseline_{false};
};
} // namespace cmvr
#endif // CMVR_ES_DISTANCE_SAMPLING_POLICY_H

View File

@ -1,82 +0,0 @@
#ifndef CMVR_ES_SELF_COLLISION_CHECKER_H
#define CMVR_ES_SELF_COLLISION_CHECKER_H
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
#include <Eigen/Geometry>
namespace cmvr {
struct CollisionPair {
std::string first;
std::string second;
};
struct SelfCollisionOptions {
std::vector<CollisionPair> ignored_pairs;
};
struct CollisionObjectPose {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
std::size_t geometry_index{0};
Eigen::Vector3d position{Eigen::Vector3d::Zero()};
Eigen::Quaterniond orientation{Eigen::Quaterniond::Identity()};
double bounding_radius_m{0.0};
};
struct CollisionGeometrySnapshot {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
std::vector<CollisionObjectPose, Eigen::aligned_allocator<CollisionObjectPose>> objects;
};
struct SelfCollisionResult {
bool valid{false};
bool in_collision{false};
double minimum_distance_m{0.0};
std::string first;
std::string second;
std::string error;
};
// Instances cache Pinocchio work data and are not thread-safe.
class SelfCollisionChecker {
public:
SelfCollisionChecker();
~SelfCollisionChecker();
SelfCollisionChecker(SelfCollisionChecker&&) noexcept;
SelfCollisionChecker& operator=(SelfCollisionChecker&&) noexcept;
SelfCollisionChecker(const SelfCollisionChecker&) = delete;
SelfCollisionChecker& operator=(const SelfCollisionChecker&) = delete;
bool init(const std::string& urdf_path,
const std::vector<std::string>& active_joint_names,
const SelfCollisionOptions& options,
std::string* error = nullptr);
bool makeSnapshot(const std::vector<double>& joint_positions,
CollisionGeometrySnapshot* snapshot,
std::string* error = nullptr);
SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot);
SelfCollisionResult check(const std::vector<double>& joint_positions);
bool initialized() const;
std::size_t dof() const;
std::size_t activePairCount() const;
const std::vector<std::string>& jointNames() const;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace cmvr
#endif // CMVR_ES_SELF_COLLISION_CHECKER_H

View File

@ -1,100 +0,0 @@
#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h"
#include <algorithm>
#include <cmath>
#include <limits>
namespace cmvr {
namespace {
void setError(std::string* error, const std::string& message)
{
if (error) {
*error = message;
}
}
double rotationAngle(const Eigen::Quaterniond& first,
const Eigen::Quaterniond& second)
{
const double dot = std::clamp(
std::abs(first.normalized().dot(second.normalized())), 0.0, 1.0);
return 2.0 * std::acos(dot);
}
} // namespace
bool DistanceSamplingPolicy::configure(const DistanceSamplingOptions& options,
std::string* error)
{
if (!std::isfinite(options.max_geometry_displacement_m) ||
options.max_geometry_displacement_m <= 0.0) {
setError(error, "max_geometry_displacement_m must be finite and positive");
return false;
}
if (!std::isfinite(options.max_check_period_s) ||
options.max_check_period_s <= 0.0) {
setError(error, "max_check_period_s must be finite and positive");
return false;
}
options_ = options;
configured_ = true;
reset();
if (error) {
error->clear();
}
return true;
}
bool DistanceSamplingPolicy::shouldCheck(const CollisionGeometrySnapshot& current,
const Clock::time_point now) const
{
if (!configured_ || !has_baseline_) {
return true;
}
const double elapsed_s = std::chrono::duration<double>(now - last_check_time_).count();
if (elapsed_s >= options_.max_check_period_s) {
return true;
}
return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m;
}
void DistanceSamplingPolicy::markChecked(const CollisionGeometrySnapshot& current,
const Clock::time_point now)
{
last_checked_ = current;
last_check_time_ = now;
has_baseline_ = true;
}
void DistanceSamplingPolicy::reset()
{
last_checked_.objects.clear();
last_check_time_ = Clock::time_point{};
has_baseline_ = false;
}
double DistanceSamplingPolicy::displacementSinceLastCheck(
const CollisionGeometrySnapshot& current) const
{
if (!has_baseline_ || current.objects.size() != last_checked_.objects.size()) {
return std::numeric_limits<double>::infinity();
}
double maximum_displacement = 0.0;
for (std::size_t index = 0; index < current.objects.size(); ++index) {
const auto& previous = last_checked_.objects[index];
const auto& now = current.objects[index];
if (previous.geometry_index != now.geometry_index) {
return std::numeric_limits<double>::infinity();
}
const double translation = (now.position - previous.position).norm();
const double radius = std::max(previous.bounding_radius_m, now.bounding_radius_m);
const double swept_distance =
translation + radius * rotationAngle(previous.orientation, now.orientation);
maximum_displacement = std::max(maximum_displacement, swept_distance);
}
return maximum_displacement;
}
} // namespace cmvr

View File

@ -1,403 +0,0 @@
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <limits>
#include <set>
#include <sstream>
#include <unordered_set>
#include <utility>
#include <pinocchio/algorithm/geometry.hpp>
#include <pinocchio/algorithm/joint-configuration.hpp>
#include <pinocchio/collision/distance.hpp>
#include <pinocchio/multibody/data.hpp>
#include <pinocchio/multibody/geometry.hpp>
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/parsers/urdf.hpp>
namespace cmvr {
namespace {
using LinkPairKey = std::pair<std::string, std::string>;
LinkPairKey canonicalPair(std::string first, std::string second)
{
if (second < first) {
std::swap(first, second);
}
return {std::move(first), std::move(second)};
}
void setError(std::string* error, const std::string& message)
{
if (error) {
*error = message;
}
}
} // namespace
class SelfCollisionChecker::Impl {
public:
bool init(const std::string& urdf_path,
const std::vector<std::string>& active_joint_names,
const SelfCollisionOptions& options,
std::string* error)
{
reset();
if (urdf_path.empty()) {
setError(error, "URDF path is empty");
return false;
}
if (!std::filesystem::is_regular_file(urdf_path)) {
setError(error, "URDF file does not exist: " + urdf_path);
return false;
}
if (active_joint_names.empty()) {
setError(error, "Active joint list is empty");
return false;
}
try {
pinocchio::urdf::buildModel(urdf_path, model_);
pinocchio::urdf::buildGeom(
model_, urdf_path, pinocchio::COLLISION, geometry_model_);
} catch (const std::exception& exception) {
setError(error, "Failed to load collision URDF: " + std::string(exception.what()));
reset();
return false;
}
if (geometry_model_.ngeoms == 0) {
setError(error, "URDF contains no collision geometry: " + urdf_path);
reset();
return false;
}
std::unordered_set<pinocchio::JointIndex> active_joint_ids;
std::unordered_set<std::string> unique_joint_names;
joint_names_.reserve(active_joint_names.size());
joint_q_indices_.reserve(active_joint_names.size());
for (const auto& joint_name : active_joint_names) {
if (joint_name.empty() || !unique_joint_names.insert(joint_name).second) {
setError(error, "Active joint names must be non-empty and unique");
reset();
return false;
}
if (!model_.existJointName(joint_name)) {
setError(error, "Joint not found in URDF: " + joint_name);
reset();
return false;
}
const pinocchio::JointIndex joint_id = model_.getJointId(joint_name);
const auto& joint = model_.joints[joint_id];
if (joint.nq() != 1) {
setError(error, "Only one-DoF active joints are supported: " + joint_name);
reset();
return false;
}
active_joint_ids.insert(joint_id);
joint_names_.push_back(joint_name);
joint_q_indices_.push_back(joint.idx_q());
}
geometry_link_names_.resize(geometry_model_.ngeoms);
std::unordered_set<std::string> selected_link_names;
for (pinocchio::GeomIndex geometry_id = 0;
geometry_id < geometry_model_.ngeoms;
++geometry_id) {
auto& geometry = geometry_model_.geometryObjects[geometry_id];
const std::string link_name = geometry.parentFrame < model_.frames.size()
? model_.frames[geometry.parentFrame].name
: geometry.name;
geometry_link_names_[geometry_id] = link_name;
const bool is_static = geometry.parentJoint == 0;
const bool belongs_to_active_arm = active_joint_ids.count(geometry.parentJoint) != 0;
if (!is_static && !belongs_to_active_arm) {
continue;
}
if (!geometry.geometry) {
setError(error, "Collision geometry is null for link: " + link_name);
reset();
return false;
}
geometry.geometry->computeLocalAABB();
selected_geometry_indices_.push_back(geometry_id);
selected_link_names.insert(link_name);
}
if (selected_geometry_indices_.size() < 2) {
setError(error, "Fewer than two collision geometries remain after arm filtering");
reset();
return false;
}
std::set<LinkPairKey> ignored_pairs;
for (const auto& pair : options.ignored_pairs) {
if (pair.first.empty() || pair.second.empty() || pair.first == pair.second) {
setError(error, "Ignored collision pairs require two different non-empty links");
reset();
return false;
}
if (!selected_link_names.count(pair.first) || !selected_link_names.count(pair.second)) {
setError(error,
"Ignored collision pair references an inactive or unknown link: " +
pair.first + ", " + pair.second);
reset();
return false;
}
ignored_pairs.insert(canonicalPair(pair.first, pair.second));
}
geometry_model_.removeAllCollisionPairs();
for (std::size_t first_index = 0;
first_index < selected_geometry_indices_.size();
++first_index) {
const auto first_geometry_id = selected_geometry_indices_[first_index];
const auto& first_geometry = geometry_model_.geometryObjects[first_geometry_id];
for (std::size_t second_index = first_index + 1;
second_index < selected_geometry_indices_.size();
++second_index) {
const auto second_geometry_id = selected_geometry_indices_[second_index];
const auto& second_geometry = geometry_model_.geometryObjects[second_geometry_id];
if (first_geometry.parentJoint == second_geometry.parentJoint) {
continue;
}
if (model_.parents[first_geometry.parentJoint] == second_geometry.parentJoint ||
model_.parents[second_geometry.parentJoint] == first_geometry.parentJoint) {
continue;
}
const auto link_pair = canonicalPair(
geometry_link_names_[first_geometry_id],
geometry_link_names_[second_geometry_id]);
if (ignored_pairs.count(link_pair)) {
continue;
}
geometry_model_.addCollisionPair(
pinocchio::CollisionPair(first_geometry_id, second_geometry_id));
}
}
if (geometry_model_.collisionPairs.empty()) {
setError(error, "No active collision pairs remain after filtering");
reset();
return false;
}
data_ = std::make_unique<pinocchio::Data>(model_);
geometry_data_ = std::make_unique<pinocchio::GeometryData>(geometry_model_);
for (auto& request : geometry_data_->distanceRequests) {
request.enable_signed_distance = true;
}
neutral_q_ = pinocchio::neutral(model_);
initialized_ = true;
if (error) {
error->clear();
}
return true;
}
bool makeSnapshot(const std::vector<double>& joint_positions,
CollisionGeometrySnapshot* snapshot,
std::string* error)
{
if (!initialized_) {
setError(error, "SelfCollisionChecker is not initialized");
return false;
}
if (!snapshot) {
setError(error, "Collision snapshot output is null");
return false;
}
if (joint_positions.size() != joint_names_.size()) {
std::ostringstream stream;
stream << "Joint position size mismatch: expected " << joint_names_.size()
<< ", got " << joint_positions.size();
setError(error, stream.str());
return false;
}
Eigen::VectorXd q = neutral_q_;
for (std::size_t index = 0; index < joint_positions.size(); ++index) {
if (!std::isfinite(joint_positions[index])) {
setError(error, "Joint position contains a non-finite value: " + joint_names_[index]);
return false;
}
q[joint_q_indices_[index]] = joint_positions[index];
}
try {
pinocchio::updateGeometryPlacements(
model_, *data_, geometry_model_, *geometry_data_, q);
} catch (const std::exception& exception) {
setError(error, "Failed to update collision geometry: " + std::string(exception.what()));
return false;
}
snapshot->objects.clear();
snapshot->objects.reserve(selected_geometry_indices_.size());
for (const auto geometry_id : selected_geometry_indices_) {
const auto& placement = geometry_data_->oMg[geometry_id];
const auto& geometry = geometry_model_.geometryObjects[geometry_id];
CollisionObjectPose pose;
pose.geometry_index = geometry_id;
pose.position = placement.translation();
pose.orientation = Eigen::Quaterniond(placement.rotation()).normalized();
pose.bounding_radius_m = std::max(0.0, geometry.geometry->aabb_radius);
snapshot->objects.push_back(std::move(pose));
}
if (error) {
error->clear();
}
return true;
}
SelfCollisionResult check(const CollisionGeometrySnapshot& snapshot)
{
SelfCollisionResult result;
if (!initialized_) {
result.error = "SelfCollisionChecker is not initialized";
return result;
}
if (snapshot.objects.size() != selected_geometry_indices_.size()) {
result.error = "Collision snapshot size does not match initialized geometry";
return result;
}
for (std::size_t index = 0; index < snapshot.objects.size(); ++index) {
const auto& pose = snapshot.objects[index];
if (pose.geometry_index != selected_geometry_indices_[index] ||
pose.geometry_index >= geometry_data_->oMg.size()) {
result.error = "Collision snapshot geometry order is invalid";
return result;
}
if (!pose.position.allFinite() || !pose.orientation.coeffs().allFinite() ||
pose.orientation.norm() <= std::numeric_limits<double>::epsilon()) {
result.error = "Collision snapshot contains an invalid pose";
return result;
}
geometry_data_->oMg[pose.geometry_index] = pinocchio::SE3(
pose.orientation.normalized().toRotationMatrix(), pose.position);
}
try {
const std::size_t pair_index =
pinocchio::computeDistances(geometry_model_, *geometry_data_);
if (pair_index >= geometry_model_.collisionPairs.size()) {
result.error = "Collision distance computation returned no active pair";
return result;
}
const auto& pair = geometry_model_.collisionPairs[pair_index];
result.minimum_distance_m = geometry_data_->distanceResults[pair_index].min_distance;
result.first = geometry_link_names_[pair.first];
result.second = geometry_link_names_[pair.second];
result.in_collision = result.minimum_distance_m <= 0.0;
result.valid = std::isfinite(result.minimum_distance_m);
if (!result.valid) {
result.error = "Collision distance is not finite";
}
} catch (const std::exception& exception) {
result.error = "Collision distance computation failed: " + std::string(exception.what());
}
return result;
}
SelfCollisionResult check(const std::vector<double>& joint_positions)
{
CollisionGeometrySnapshot snapshot;
std::string error;
if (!makeSnapshot(joint_positions, &snapshot, &error)) {
SelfCollisionResult result;
result.error = std::move(error);
return result;
}
return check(snapshot);
}
void reset()
{
initialized_ = false;
joint_names_.clear();
joint_q_indices_.clear();
selected_geometry_indices_.clear();
geometry_link_names_.clear();
geometry_data_.reset();
data_.reset();
model_ = pinocchio::Model{};
geometry_model_ = pinocchio::GeometryModel{};
neutral_q_.resize(0);
}
bool initialized_{false};
std::vector<std::string> joint_names_;
std::vector<int> joint_q_indices_;
std::vector<pinocchio::GeomIndex> selected_geometry_indices_;
std::vector<std::string> geometry_link_names_;
pinocchio::Model model_;
pinocchio::GeometryModel geometry_model_;
std::unique_ptr<pinocchio::Data> data_;
std::unique_ptr<pinocchio::GeometryData> geometry_data_;
Eigen::VectorXd neutral_q_;
};
SelfCollisionChecker::SelfCollisionChecker()
: impl_(std::make_unique<Impl>())
{
}
SelfCollisionChecker::~SelfCollisionChecker() = default;
SelfCollisionChecker::SelfCollisionChecker(SelfCollisionChecker&&) noexcept = default;
SelfCollisionChecker& SelfCollisionChecker::operator=(SelfCollisionChecker&&) noexcept = default;
bool SelfCollisionChecker::init(const std::string& urdf_path,
const std::vector<std::string>& active_joint_names,
const SelfCollisionOptions& options,
std::string* error)
{
return impl_->init(urdf_path, active_joint_names, options, error);
}
bool SelfCollisionChecker::makeSnapshot(const std::vector<double>& joint_positions,
CollisionGeometrySnapshot* snapshot,
std::string* error)
{
return impl_->makeSnapshot(joint_positions, snapshot, error);
}
SelfCollisionResult SelfCollisionChecker::check(const CollisionGeometrySnapshot& snapshot)
{
return impl_->check(snapshot);
}
SelfCollisionResult SelfCollisionChecker::check(const std::vector<double>& joint_positions)
{
return impl_->check(joint_positions);
}
bool SelfCollisionChecker::initialized() const
{
return impl_->initialized_;
}
std::size_t SelfCollisionChecker::dof() const
{
return impl_->joint_names_.size();
}
std::size_t SelfCollisionChecker::activePairCount() const
{
return impl_->geometry_model_.collisionPairs.size();
}
const std::vector<std::string>& SelfCollisionChecker::jointNames() const
{
return impl_->joint_names_;
}
} // namespace cmvr

View File

@ -1,236 +0,0 @@
#include <chrono>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "algorithms/collision_detection/self_collision/include/distance_sampling_policy.h"
#include "algorithms/collision_detection/self_collision/include/self_collision_checker.h"
namespace cmvr {
namespace {
const std::vector<std::string> kRightArmJoints{
"R_SHOULDER_P",
"R_SHOULDER_R",
"R_SHOULDER_Y",
"R_ELBOW_R",
"R_WRIST_P",
"R_WRIST_Y",
"R_WRIST_R",
};
const std::vector<std::string> kGen2RightArmJoints{
"right_arm_J1",
"right_arm_J2",
"right_arm_J3",
"right_arm_J4",
"right_arm_J5",
"right_arm_J6",
"right_arm_J7",
};
const std::vector<double> kGen2SetupPose{
0.0, -0.50, 1.5708, 1.5708, -0.041, 0.0, 0.0,
};
const std::vector<double> kGen2WarningPose{
2.45028525340088,
0.413065394330014,
-1.78610031118294,
2.3232081721811,
-2.96828882895788,
-1.59350098130002,
0.582912411114367,
};
const std::vector<double> kGen2StopPose{
2.13758633436379,
1.61835160165575,
-2.3836142221041,
0.964538527544213,
-0.00382525077004825,
1.74586899135531,
-0.336868659266887,
};
const std::vector<double> kGen2CollisionPose{
-0.42656969579233,
1.41426471041774,
-2.67949400419915,
2.45814854129954,
-2.35907388079205,
1.14125209449898,
1.53232912981414,
};
const std::vector<double> kGen2TorsoCollisionPose{
1.57607137794121,
2.06613762981425,
-1.76915077905899,
0.959251437141443,
-0.725973209527894,
1.79390262120717,
0.2223354372144,
};
std::string collisionUrdfPath()
{
return std::string(CMVR_ES_SOURCE_DIR) +
"/model/xiaoyan_description/dual_arm_collision.urdf";
}
std::string gen2CollisionUrdfPath()
{
return std::string(CMVR_ES_SOURCE_DIR) +
"/model/gen2/collision/robot_collision.urdf";
}
SelfCollisionOptions gen2CollisionOptions()
{
SelfCollisionOptions options;
options.ignored_pairs.push_back({"arm_link_5_2", "arm_link_7_2"});
options.ignored_pairs.push_back({"body_link", "arm_link_2_2"});
return options;
}
CollisionGeometrySnapshot singleObjectSnapshot(double x,
double angle,
double radius)
{
CollisionGeometrySnapshot snapshot;
CollisionObjectPose pose;
pose.geometry_index = 1;
pose.position = Eigen::Vector3d(x, 0.0, 0.0);
pose.orientation = Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ());
pose.bounding_radius_m = radius;
snapshot.objects.push_back(pose);
return snapshot;
}
TEST(SelfCollisionCheckerTest, LoadsRightArmFromDualArmUrdf)
{
SelfCollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
EXPECT_EQ(checker.dof(), 7U);
EXPECT_GT(checker.activePairCount(), 0U);
CollisionGeometrySnapshot snapshot;
ASSERT_TRUE(checker.makeSnapshot(std::vector<double>(7, 0.0), &snapshot, &error)) << error;
EXPECT_EQ(snapshot.objects.size(), 11U);
const SelfCollisionResult result = checker.check(snapshot);
ASSERT_TRUE(result.valid) << result.error;
EXPECT_TRUE(result.first.rfind("L_", 0) != 0);
EXPECT_TRUE(result.second.rfind("L_", 0) != 0);
}
TEST(SelfCollisionCheckerTest, RejectsWrongJointVectorSize)
{
SelfCollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
CollisionGeometrySnapshot snapshot;
EXPECT_FALSE(checker.makeSnapshot(std::vector<double>(6, 0.0), &snapshot, &error));
EXPECT_NE(error.find("size mismatch"), std::string::npos);
}
TEST(SelfCollisionCheckerTest, RemovesConfiguredIgnoredPair)
{
SelfCollisionChecker baseline;
SelfCollisionChecker filtered;
std::string error;
ASSERT_TRUE(baseline.init(collisionUrdfPath(), kRightArmJoints, {}, &error)) << error;
SelfCollisionOptions options;
options.ignored_pairs.push_back({"base_link", "R_ELBOW_R_S"});
ASSERT_TRUE(filtered.init(collisionUrdfPath(), kRightArmJoints, options, &error)) << error;
EXPECT_EQ(filtered.activePairCount() + 1, baseline.activePairCount());
}
TEST(SelfCollisionCheckerTest, LoadsGen2RightArmCollisionModel)
{
SelfCollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(
gen2CollisionUrdfPath(),
kGen2RightArmJoints,
gen2CollisionOptions(),
&error)) << error;
EXPECT_EQ(checker.dof(), 7U);
EXPECT_EQ(checker.activePairCount(), 19U);
CollisionGeometrySnapshot snapshot;
ASSERT_TRUE(checker.makeSnapshot(kGen2SetupPose, &snapshot, &error)) << error;
EXPECT_EQ(snapshot.objects.size(), 8U);
const SelfCollisionResult setup_result = checker.check(snapshot);
ASSERT_TRUE(setup_result.valid) << setup_result.error;
EXPECT_FALSE(setup_result.in_collision);
EXPECT_GT(setup_result.minimum_distance_m, 0.02);
}
TEST(SelfCollisionCheckerTest, ClassifiesGen2SafetyDistances)
{
SelfCollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(
gen2CollisionUrdfPath(),
kGen2RightArmJoints,
gen2CollisionOptions(),
&error)) << error;
const SelfCollisionResult warning_result = checker.check(kGen2WarningPose);
ASSERT_TRUE(warning_result.valid) << warning_result.error;
EXPECT_FALSE(warning_result.in_collision);
EXPECT_GT(warning_result.minimum_distance_m, 0.005);
EXPECT_LE(warning_result.minimum_distance_m, 0.02);
const SelfCollisionResult stop_result = checker.check(kGen2StopPose);
ASSERT_TRUE(stop_result.valid) << stop_result.error;
EXPECT_FALSE(stop_result.in_collision);
EXPECT_GT(stop_result.minimum_distance_m, 0.0);
EXPECT_LE(stop_result.minimum_distance_m, 0.005);
const SelfCollisionResult collision_result = checker.check(kGen2CollisionPose);
ASSERT_TRUE(collision_result.valid) << collision_result.error;
EXPECT_TRUE(collision_result.in_collision);
EXPECT_LE(collision_result.minimum_distance_m, 0.0);
const SelfCollisionResult torso_result =
checker.check(kGen2TorsoCollisionPose);
ASSERT_TRUE(torso_result.valid) << torso_result.error;
EXPECT_TRUE(torso_result.in_collision);
EXPECT_LE(torso_result.minimum_distance_m, 0.0);
EXPECT_TRUE(torso_result.first == "body_link" ||
torso_result.second == "body_link");
}
TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement)
{
DistanceSamplingPolicy policy;
DistanceSamplingOptions options;
options.max_geometry_displacement_m = 0.002;
options.max_check_period_s = 0.01;
std::string error;
ASSERT_TRUE(policy.configure(options, &error)) << error;
const auto start = DistanceSamplingPolicy::Clock::now();
const auto initial = singleObjectSnapshot(0.0, 0.0, 0.2);
EXPECT_TRUE(policy.shouldCheck(initial, start));
policy.markChecked(initial, start);
EXPECT_FALSE(policy.shouldCheck(
singleObjectSnapshot(0.001, 0.0, 0.2), start + std::chrono::milliseconds(1)));
EXPECT_TRUE(policy.shouldCheck(
singleObjectSnapshot(0.0021, 0.0, 0.2), start + std::chrono::milliseconds(2)));
EXPECT_TRUE(policy.shouldCheck(
singleObjectSnapshot(0.0, 0.011, 0.2), start + std::chrono::milliseconds(2)));
EXPECT_TRUE(policy.shouldCheck(
initial, start + std::chrono::milliseconds(10)));
}
} // namespace
} // namespace cmvr

View File

@ -24,7 +24,7 @@ double rotationAngle(const Eigen::Quaterniond& first,
} // namespace
bool LgvDistanceSamplingPolicy::configure(const DistanceSamplingOptions& options,
bool DistanceSamplingPolicy::configure(const DistanceSamplingOptions& options,
std::string* error)
{
if (!std::isfinite(options.max_geometry_displacement_m) ||
@ -46,7 +46,7 @@ bool LgvDistanceSamplingPolicy::configure(const DistanceSamplingOptions& options
return true;
}
bool LgvDistanceSamplingPolicy::shouldCheck(const std::vector<CollisionBody>& current,
bool DistanceSamplingPolicy::shouldCheck(const std::vector<CollisionBody>& current,
const Clock::time_point now) const
{
if (!configured_ || !has_baseline_) {
@ -59,7 +59,7 @@ bool LgvDistanceSamplingPolicy::shouldCheck(const std::vector<CollisionBody>& cu
return displacementSinceLastCheck(current) >= options_.max_geometry_displacement_m;
}
void LgvDistanceSamplingPolicy::markChecked(const std::vector<CollisionBody>& current,
void DistanceSamplingPolicy::markChecked(const std::vector<CollisionBody>& current,
const Clock::time_point now)
{
last_checked_ = current;
@ -67,14 +67,14 @@ void LgvDistanceSamplingPolicy::markChecked(const std::vector<CollisionBody>& cu
has_baseline_ = true;
}
void LgvDistanceSamplingPolicy::reset()
void DistanceSamplingPolicy::reset()
{
last_checked_.clear();
last_check_time_ = Clock::time_point{};
has_baseline_ = false;
}
double LgvDistanceSamplingPolicy::displacementSinceLastCheck(
double DistanceSamplingPolicy::displacementSinceLastCheck(
const std::vector<CollisionBody>& current) const
{
if (!has_baseline_ || current.size() != last_checked_.size()) {

View File

@ -1,3 +1,4 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
@ -5,15 +6,20 @@
#include <fstream>
#include <initializer_list>
#include <limits>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>
#include <pinocchio/fwd.hpp>
#include <coal/shape/geometric_shapes.h>
#include <gtest/gtest.h>
#include <unistd.h>
#include "algorithms/collision_detection/include/distance_sampling_policy.h"
#include "algorithms/collision_detection/include/collision_checker.h"
#include "cmvr/config/self_collision_task_config/self_collision_task_config.pb.h"
#include "common/io/proto_file_io.h"
#include "common/types/arm/arm_types.h"
#include "environment/include/robot_model.h"
@ -459,6 +465,183 @@ TEST(CollisionCheckerTest, LoadsRightArmFromDualArmUrdf)
EXPECT_TRUE(result.second.rfind("L_", 0) != 0);
}
TEST(CollisionCheckerTest, XiaozhaoSourceKinematicsAndGeneratedGeometrySelectOnlyRequestedArm)
{
const std::string model_root = std::string(CMVR_ES_SOURCE_DIR) + "/model/xiaozhao/";
for (const std::string side : {"left", "right"}) {
SCOPED_TRACE(side);
RobotModel model;
std::set<std::string> expected_links{"base_link"};
for (int joint = 1; joint <= 7; ++joint) {
model.joint_names.push_back("joint" + std::to_string(joint) + "-" + side);
expected_links.insert("link" + std::to_string(joint) + "-" + side);
}
const auto selected_joints = model.joint_names;
ASSERT_TRUE(model.loadUrdf(model_root + "urdf/xiaozhao.urdf"));
ASSERT_TRUE(model.loadCollisionGeometry(
model_root + "collision/xiaozhao_collision.urdf"));
EXPECT_EQ(model.joint_names, selected_joints);
EXPECT_EQ(model.dof, 7U);
CollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(model, selected_joints, {}, &error)) << error;
EXPECT_EQ(checker.jointNames(), selected_joints);
EXPECT_EQ(checker.dof(), 7U);
EXPECT_GT(checker.activePairCount(), 0U);
const auto bodies = checker.collisionBodies(std::vector<double>(7, 0.0));
std::set<std::string> selected_links;
for (const auto& body : bodies) {
ASSERT_NE(body.geometry, nullptr);
EXPECT_TRUE(body.position.allFinite());
EXPECT_TRUE(body.orientation.coeffs().allFinite());
selected_links.insert(body.link_name);
const bool is_link2 = body.link_name == "link2-" + side;
if (is_link2 || body.link_name == "link4-" + side) {
ASSERT_EQ(body.geometry->getNodeType(), coal::GEOM_CYLINDER);
const auto& cylinder = static_cast<const coal::Cylinder&>(*body.geometry);
if (is_link2) {
EXPECT_NEAR(cylinder.radius, side == "left" ? 0.0410593 : 0.04152965, 1e-6);
EXPECT_NEAR(2.0 * cylinder.halfLength, 0.155, 1e-6);
} else {
EXPECT_NEAR(cylinder.radius, side == "left" ? 0.04156748 : 0.04203374, 1e-6);
EXPECT_NEAR(2.0 * cylinder.halfLength, 0.12400011, 1e-6);
}
// At zero, the local Y axes of joints 2 and 4 are parallel to base Y.
const Eigen::Vector3d axis = body.orientation * Eigen::Vector3d::UnitZ();
EXPECT_NEAR(std::abs(axis.y()), 1.0, 1e-9);
}
if (body.link_name == "link5-" + side) {
EXPECT_EQ(body.geometry->getNodeType(), coal::GEOM_BOX);
}
}
const auto piece_count = [&](const std::string& link) {
return std::count_if(bodies.begin(), bodies.end(), [&](const auto& body) {
return body.link_name == link;
});
};
EXPECT_EQ(piece_count("link2-" + side), 1);
EXPECT_EQ(piece_count("link4-" + side), 1);
EXPECT_EQ(piece_count("link5-" + side), 3);
// Root geometry participates, but the opposite arm, moving neck and
// geometry-free TCP frames must not enter this single-arm query.
EXPECT_EQ(selected_links, expected_links);
for (const auto& link : std::vector<std::string>{
"base_link", "link7-" + side}) {
EXPECT_GT(piece_count(link), 1) << "Expected multiple collision pieces for " << link;
}
const auto result = checker.check(bodies);
ASSERT_TRUE(result.valid) << result.error;
EXPECT_TRUE(std::isfinite(result.minimum_distance_m));
EXPECT_EQ(expected_links.count(result.first), 1U);
EXPECT_EQ(expected_links.count(result.second), 1U);
}
}
TEST(CollisionCheckerTest, XiaozhaoWristBoxesAndConfiguredPairExclusions)
{
const std::string path = std::string(CMVR_ES_SOURCE_DIR) +
"/model/xiaozhao/collision/xiaozhao_collision.urdf";
for (const std::string side : {"left", "right"}) {
SCOPED_TRACE(side);
std::vector<std::string> joints;
for (int joint = 1; joint <= 7; ++joint) {
joints.push_back("joint" + std::to_string(joint) + "-" + side);
}
CollisionChecker checker;
std::string error;
ASSERT_TRUE(checker.init(path, joints, {}, &error)) << error;
const std::string wrist = "link5-" + side;
const std::string hand = "link7-" + side;
const auto isolated_wrist_bodies = [&](const std::vector<double>& q) {
auto bodies = checker.collisionBodies(q);
// Preserve the actual FK and all pieces of both wrist links. Move
// every other geometry far apart so shoulder padding cannot mask
// wrist regressions.
for (std::size_t index = 0; index < bodies.size(); ++index) {
auto& body = bodies[index];
if (body.link_name != wrist && body.link_name != hand) {
body.position = Eigen::Vector3d(
10.0 * static_cast<double>(index + 1), 10.0, 10.0);
}
}
return bodies;
};
const auto is_wrist_pair = [&](const CollisionResult& result) {
return (result.first == wrist && result.second == hand) ||
(result.first == hand && result.second == wrist);
};
// Preserve the physical all-zero pose from before the J3/J5 origins
// gained pi. This is a geometry reference, not a motion target or a
// claim that the new all-zero pose (or the whole robot) is collision-free.
const double pi = std::acos(-1.0);
const std::vector<double> historical_zero{0.0, 0.0, pi, 0.0, pi, 0.0, 0.0};
const auto historical = checker.check(isolated_wrist_bodies(historical_zero));
ASSERT_TRUE(historical.valid) << historical.error;
EXPECT_TRUE(is_wrist_pair(historical));
EXPECT_TRUE(std::isfinite(historical.minimum_distance_m));
if (side == "right") {
// Merging the inner supports and outer cheeks closes the historical
// gap. Keep the overlap within the 1 mm fitting margin.
EXPECT_GE(historical.minimum_distance_m, -0.001);
// Frozen reference: original STL triangle queries independently
// confirmed wrist interference here. Do not read task config;
// choosing a new touch initialization must not invalidate this test.
// J3/J5 use new coordinates: q_new = wrap(q_old - pi).
const std::vector<double> known_interference{
1.8648861126, 0.8084619160, 2.727417567789793, 1.6622227972,
1.810335360989793, -0.2423592867, -1.0088169947,
};
const auto full = checker.check(known_interference);
ASSERT_TRUE(full.valid) << full.error;
EXPECT_TRUE(full.in_collision);
const auto isolated = checker.check(isolated_wrist_bodies(known_interference));
ASSERT_TRUE(isolated.valid) << isolated.error;
EXPECT_TRUE(is_wrist_pair(isolated));
EXPECT_TRUE(isolated.in_collision);
EXPECT_TRUE(std::isfinite(isolated.minimum_distance_m));
EXPECT_LE(isolated.minimum_distance_m, 0.0);
}
const auto root = std::filesystem::path(CMVR_ES_SOURCE_DIR);
const auto task_path = root / "cmvr-es/config/tasks/self_collision_task" /
("self_collision_task_xiaozhao_" + side + ".pb.txt");
config::SelfCollisionTaskRootConfig task;
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(task_path.string(), &task));
auto config = task.self_collision_task().checker();
config.set_urdf_path((root / config.urdf_path()).string());
CollisionChecker filtered;
ASSERT_TRUE(filtered.init(config, joints, &error)) << error;
const auto filtered_zero = filtered.check(isolated_wrist_bodies(historical_zero));
ASSERT_TRUE(filtered_zero.valid) << filtered_zero.error;
EXPECT_FALSE(filtered_zero.in_collision);
EXPECT_FALSE(is_wrist_pair(filtered_zero));
std::vector<double> bent_wrist(7, 0.0);
bent_wrist[5] = side == "left" ? 0.45 : -0.45;
const auto bodies = isolated_wrist_bodies(bent_wrist);
const auto raw = checker.check(bodies);
ASSERT_TRUE(raw.valid) << raw.error;
ASSERT_TRUE(is_wrist_pair(raw));
ASSERT_TRUE(raw.in_collision);
const auto monitored = filtered.check(bodies);
ASSERT_TRUE(monitored.valid) << monitored.error;
EXPECT_FALSE(monitored.in_collision);
EXPECT_FALSE(is_wrist_pair(monitored));
const auto piece_count = [&](const std::string& link) {
return std::count_if(bodies.begin(), bodies.end(),
[&](const auto& body) { return body.link_name == link; });
};
EXPECT_EQ(checker.activePairCount() - filtered.activePairCount(),
piece_count(wrist) * piece_count(hand));
}
}
TEST(CollisionCheckerTest, RejectsWrongJointVectorSize)
{
CollisionChecker checker;
@ -814,14 +997,14 @@ TEST(CollisionCheckerTest, ValidationRejectsMalformedInputAndCallbackFailure)
TEST(DistanceSamplingPolicyTest, SamplesByAccumulatedGeometryDisplacement)
{
LgvDistanceSamplingPolicy policy;
DistanceSamplingPolicy policy;
DistanceSamplingOptions options;
options.max_geometry_displacement_m = 0.002;
options.max_check_period_s = 0.01;
std::string error;
ASSERT_TRUE(policy.configure(options, &error)) << error;
const auto start = LgvDistanceSamplingPolicy::Clock::now();
const auto start = DistanceSamplingPolicy::Clock::now();
const auto initial = singleBody(0.0, 0.0, 0.2);
EXPECT_TRUE(policy.shouldCheck(initial, start));
policy.markChecked(initial, start);

View File

@ -1,6 +1,3 @@
add_subdirectory(arm_control)
#find_package(VISP REQUIRED)
# 如果报 relocation ... can not be used when making a shared object; recompile with -fPIC ,说明SRC 中包含了test文件 ,test

View File

@ -1,17 +0,0 @@
add_library(arm_control SHARED
src/cartesian_velocity_controller.cpp
)
target_include_directories(arm_control PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(arm_control
PUBLIC
cmvr_es::algorithms::arm_motion
)
add_library(cmvr_es::algorithms::arm_control ALIAS arm_control)
install(TARGETS arm_control LIBRARY DESTINATION lib)
add_executable(cartesian_velocity_controller_test src/cartesian_velocity_controller_test.cpp)
target_link_libraries(cartesian_velocity_controller_test PRIVATE
cmvr_es::algorithms::arm_control gtest gtest_main pthread)

View File

@ -1,92 +0,0 @@
#ifndef CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H
#define CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <thread>
#include <vector>
#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h"
#include "common/types/arm/arm_types.h"
namespace cmvr::device {
class CartesianVelocityController {
public:
struct Config {
double control_period_s{0.001};
double stop_twist_norm{1e-9};
double stop_command_velocity_norm{1e-3};
double stop_measured_velocity_norm{1e-2};
double stop_acceleration{0.5};
double stop_timeout_s{2.0};
};
using ReadStateCallback = std::function<bool(std::vector<double>& q, std::vector<double>& qd)>;
using SendVelocityCallback = std::function<Result(const JointVelocityCommand& velocity, double acceleration)>;
CartesianVelocityController(Config config,
std::shared_ptr<CartesianMotionPlanner> planner,
std::size_t dof,
ReadStateCallback read_state,
SendVelocityCallback send_velocity);
~CartesianVelocityController();
CartesianVelocityController(const CartesianVelocityController&) = delete;
CartesianVelocityController& operator=(const CartesianVelocityController&) = delete;
Result speedL(const CartesianVelocity& velocity,
double acceleration,
double duration,
FrameType frame);
Result stop(std::optional<double> acceleration = std::nullopt);
Result speedL(const CartesianVelocity& velocity, const SpeedLOptions& options,
double duration, FrameType frame);
SpeedLReference getReference() const;
void shutdown();
bool busy() const { return busy_.load(); }
double stopTimeoutS() const { return config_.stop_timeout_s; }
CartesianVelocity getCommandTwistBase() const;
private:
void ensureWorkerStarted_();
void workerLoop_();
void requestStop_(std::optional<double> acceleration = std::nullopt);
void abortCommand_();
void sendZero_();
static double velocityNorm_(const std::vector<double>& velocity);
static double twistNorm_(const CartesianVelocity& velocity);
private:
Config config_;
std::shared_ptr<CartesianMotionPlanner> planner_;
std::size_t dof_{0};
ReadStateCallback read_state_;
SendVelocityCallback send_velocity_;
std::unique_ptr<std::thread> worker_;
mutable std::mutex mutex_;
std::condition_variable cv_;
std::atomic<bool> stop_requested_{false};
bool command_active_{false};
CartesianVelocity target_twist_{};
FrameType target_frame_{FrameType::Base};
double target_acceleration_{0.25};
SpeedLOptions target_options_{};
SpeedLReference reference_{};
CartesianVelocity command_twist_snapshot_{};
std::uint64_t command_version_{0};
std::atomic<bool> busy_{false};
};
} // namespace cmvr::device
#endif // CMVR_ES_CARTESIAN_VELOCITY_CONTROLLER_H

View File

@ -1,379 +0,0 @@
#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h"
#include <chrono>
#include <cmath>
#include <thread>
#include <utility>
#include "common/base/logging/logger.h"
namespace cmvr::device {
namespace {
CartesianVelocityController::Config normalizeConfig(CartesianVelocityController::Config config)
{
const CartesianVelocityController::Config defaults;
if (config.control_period_s <= 0.0) {
config.control_period_s = defaults.control_period_s;
}
if (config.stop_twist_norm <= 0.0) {
config.stop_twist_norm = defaults.stop_twist_norm;
}
if (config.stop_command_velocity_norm <= 0.0) {
config.stop_command_velocity_norm = defaults.stop_command_velocity_norm;
}
if (config.stop_measured_velocity_norm <= 0.0) {
config.stop_measured_velocity_norm = defaults.stop_measured_velocity_norm;
}
if (config.stop_acceleration <= 0.0) {
config.stop_acceleration = defaults.stop_acceleration;
}
if (!std::isfinite(config.stop_timeout_s) || config.stop_timeout_s <= 0.0) {
config.stop_timeout_s = defaults.stop_timeout_s;
}
return config;
}
} // namespace
CartesianVelocityController::CartesianVelocityController(
Config config,
std::shared_ptr<CartesianMotionPlanner> planner,
const std::size_t dof,
ReadStateCallback read_state,
SendVelocityCallback send_velocity)
: config_(normalizeConfig(config)),
planner_(std::move(planner)),
dof_(dof),
read_state_(std::move(read_state)),
send_velocity_(std::move(send_velocity))
{
}
CartesianVelocityController::~CartesianVelocityController()
{
shutdown();
}
Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
const double acceleration,
const double duration,
const FrameType frame)
{
SpeedLOptions options;
options.acceleration = acceleration;
return speedL(velocity, options, duration, frame);
}
Result CartesianVelocityController::speedL(const CartesianVelocity& velocity,
const SpeedLOptions& options,
const double duration, const FrameType frame)
{
const double acceleration = options.acceleration;
if (!planner_ || !read_state_ || !send_velocity_ || dof_ == 0 ||
!std::isfinite(acceleration) || acceleration <= 0.0 ||
!std::isfinite(duration) || duration < 0.0 || !std::isfinite(twistNorm_(velocity)) ||
(options.linear_jerk && (!std::isfinite(*options.linear_jerk) || *options.linear_jerk <= 0.0))) {
return Result::failure(ArmErrorCode::InvalidArgument, "speedL invalid input");
}
if (!worker_ || !worker_->joinable()) {
if (busy_.exchange(true)) {
return Result::failure(ArmErrorCode::RobotNotReady, "arm is busy");
}
}
ensureWorkerStarted_();
std::uint64_t command_version = 0;
{
std::lock_guard<std::mutex> lock(mutex_);
target_twist_ = velocity;
target_acceleration_ = acceleration;
target_frame_ = frame;
target_options_ = options;
reference_ = {};
command_active_ = true;
busy_.store(true);
command_version = ++command_version_;
}
cv_.notify_all();
if (duration > 0.0) {
std::this_thread::sleep_for(std::chrono::duration<double>(duration));
bool should_stop = false;
{
std::lock_guard<std::mutex> lock(mutex_);
if (command_version_ == command_version) {
target_twist_ = {};
target_frame_ = FrameType::Base;
command_active_ = true;
++command_version_;
should_stop = true;
}
}
if (should_stop) {
cv_.notify_all();
}
}
return Result::success();
}
Result CartesianVelocityController::stop(const std::optional<double> acceleration)
{
if (!worker_ || !worker_->joinable()) {
return Result::success();
}
// A completed speedL command leaves the worker thread joinable but idle.
// Do not turn that idle worker into a new command just because a caller
// requests a stop during a task transition.
if (!busy_.load()) {
return Result::success();
}
requestStop_(acceleration);
return Result::success();
}
void CartesianVelocityController::shutdown()
{
if (!worker_ || !worker_->joinable()) {
busy_.store(false);
return;
}
{
std::lock_guard<std::mutex> lock(mutex_);
stop_requested_.store(true);
command_active_ = false;
target_twist_ = {};
target_frame_ = FrameType::Base;
}
cv_.notify_all();
worker_->join();
worker_.reset();
stop_requested_.store(false);
busy_.store(false);
}
CartesianVelocity CartesianVelocityController::getCommandTwistBase() const
{
std::lock_guard<std::mutex> lock(mutex_);
return command_twist_snapshot_;
}
SpeedLReference CartesianVelocityController::getReference() const
{
std::lock_guard<std::mutex> lock(mutex_);
return reference_;
}
void CartesianVelocityController::ensureWorkerStarted_()
{
if (worker_ && worker_->joinable()) {
return;
}
stop_requested_.store(false);
worker_ = std::make_unique<std::thread>(&CartesianVelocityController::workerLoop_, this);
}
void CartesianVelocityController::workerLoop_()
{
const double dt = config_.control_period_s;
auto next_tick = std::chrono::steady_clock::now();
while (true) {
CartesianVelocity target_twist;
double acceleration = 0.25;
FrameType target_frame = FrameType::Base;
SpeedLOptions options;
std::uint64_t applied_version = 0;
bool capture_reference = false;
{
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [&]() {
return stop_requested_.load() || command_active_;
});
if (stop_requested_.load()) {
break;
}
target_twist = target_twist_;
acceleration = target_acceleration_;
target_frame = target_frame_;
}
next_tick = std::chrono::steady_clock::now();
while (true) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (stop_requested_.load()) {
sendZero_();
busy_.store(false);
return;
}
if (!command_active_) {
break;
}
target_twist = target_twist_;
acceleration = target_acceleration_;
target_frame = target_frame_;
options = target_options_;
options.acceleration = acceleration;
applied_version = command_version_;
capture_reference = options.capture_reference && !reference_.valid;
}
if (!planner_->updateSpeedLLimits(options)) {
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
abortCommand_();
break;
}
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] updateSpeedLAcceleration failed, acceleration="
<< acceleration;
requestStop_();
continue;
}
std::vector<double> q_now;
std::vector<double> qd_now;
if (!read_state_(q_now, qd_now)) {
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] read_state failed";
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
abortCommand_();
break;
}
requestStop_();
continue;
}
std::vector<double> qd_cmd;
SpeedLReference reference;
if (capture_reference &&
!planner_->captureSpeedLReference(q_now, target_twist, target_frame, reference)) {
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] cannot capture motion reference";
abortCommand_();
break;
}
if (!planner_->speedLStep(target_twist, dt, q_now, qd_now, qd_cmd, target_frame)) {
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] speedLStep failed, target_twist=["
<< target_twist.vx << ", " << target_twist.vy << ", "
<< target_twist.vz << ", " << target_twist.wx << ", "
<< target_twist.wy << ", " << target_twist.wz
<< "], frame=" << (target_frame == FrameType::Tool ? "Tool" : "Base");
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
abortCommand_();
break;
}
requestStop_();
continue;
}
JointVelocityCommand velocity_command;
velocity_command.velocity = qd_cmd;
const auto send_result = send_velocity_(velocity_command, acceleration);
if (!send_result.ok()) {
CMVR_LOG(ERROR) << "[CartesianVelocityController][speedL] send_velocity failed: "
<< send_result.message;
if (twistNorm_(target_twist) < config_.stop_twist_norm) {
abortCommand_();
break;
}
requestStop_();
continue;
}
{
std::lock_guard<std::mutex> lock(mutex_);
command_twist_snapshot_ = planner_->getSpeedLCommandTwistBase();
if (capture_reference && command_version_ == applied_version) {
reference.command_version = applied_version;
reference_ = reference;
// Lock a captured Tool-frame translation in Base for the
// entire command, matching its distance reference axis.
target_twist_ = reference.target_base;
target_frame_ = FrameType::Base;
}
}
if (twistNorm_(target_twist) < config_.stop_twist_norm &&
velocityNorm_(qd_cmd) < config_.stop_command_velocity_norm &&
velocityNorm_(qd_now) < config_.stop_measured_velocity_norm) {
{
std::lock_guard<std::mutex> lock(mutex_);
// A newer target may have arrived during planning/I/O.
if (command_version_ != applied_version) continue;
command_active_ = false;
// Serialize the final zero and busy transition with new
// submissions, not only the version comparison.
sendZero_();
busy_.store(false);
}
break;
}
next_tick += std::chrono::duration_cast<std::chrono::steady_clock::duration>(
std::chrono::duration<double>(dt));
std::this_thread::sleep_until(next_tick);
}
}
sendZero_();
busy_.store(false);
}
void CartesianVelocityController::requestStop_(const std::optional<double> acceleration)
{
{
std::lock_guard<std::mutex> lock(mutex_);
target_twist_ = {};
target_frame_ = FrameType::Base;
target_acceleration_ = acceleration.has_value() ? *acceleration
: config_.stop_acceleration;
target_options_.acceleration = target_acceleration_;
target_options_.capture_reference = false;
command_active_ = true;
++command_version_;
}
cv_.notify_all();
}
void CartesianVelocityController::abortCommand_()
{
{
std::lock_guard<std::mutex> lock(mutex_);
command_active_ = false;
target_twist_ = {};
target_frame_ = FrameType::Base;
sendZero_();
busy_.store(false);
}
}
void CartesianVelocityController::sendZero_()
{
if (!send_velocity_) {
return;
}
JointVelocityCommand zero;
zero.velocity.assign(dof_, 0.0);
(void)send_velocity_(zero, 0.0);
}
double CartesianVelocityController::velocityNorm_(const std::vector<double>& velocity)
{
double value = 0.0;
for (const double item : velocity) {
value += item * item;
}
return std::sqrt(value);
}
double CartesianVelocityController::twistNorm_(const CartesianVelocity& velocity)
{
return std::sqrt(velocity.vx * velocity.vx +
velocity.vy * velocity.vy +
velocity.vz * velocity.vz +
velocity.wx * velocity.wx +
velocity.wy * velocity.wy +
velocity.wz * velocity.wz);
}
} // namespace cmvr::device

View File

@ -1,131 +0,0 @@
#include <gtest/gtest.h>
#include "algorithms/controllers/arm_control/include/cartesian_velocity_controller.h"
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <limits>
namespace cmvr::device {
namespace {
using namespace std::chrono_literals;
class Planner final : public CartesianMotionPlanner {
public:
bool configureSpeedL(const config::SpeedLPlannerConfig&, std::size_t) override { return true; }
bool configureMoveL(const config::MoveLPlannerConfig&) override { return true; }
bool planMoveL(const CartesianPose&, const std::vector<double>&, const std::vector<double>&,
double, double, double, FrameType, CartesianJointTrajectory&) override { return false; }
bool updateSpeedLAcceleration(double) override { return true; }
bool updateSpeedLLimits(const SpeedLOptions& options) override {
applied_reversal.store(options.continuous_linear_reversal.value_or(false));
applied_jerk.store(options.linear_jerk.value_or(10.0)); return true;
}
bool captureSpeedLReference(const std::vector<double>&, const CartesianVelocity& target,
FrameType, SpeedLReference& ref) override {
ref.valid = true;
ref.tcp_pose_base.y = .5;
ref.target_base.vx = target.vy;
return true;
}
bool speedLStep(const CartesianVelocity& v, double, const std::vector<double>&,
const std::vector<double>&, std::vector<double>& out, FrameType) override {
current = v; out = {v.vy}; return true;
}
CartesianVelocity getSpeedLCommandTwistBase() const override { return current; }
CartesianVelocity current;
std::atomic<double> applied_jerk{0.0};
std::atomic<bool> applied_reversal{false};
};
TEST(CartesianVelocityController, CompletedStopCannotClearNewReversal) {
std::mutex mutex;
std::condition_variable cv;
bool forward_sent = false, block_zero = false, zero_entered = false;
bool release_zero = false, reverse_sent = false;
auto planner = std::make_shared<Planner>();
CartesianVelocityController controller({}, planner, 1,
[](auto& q, auto& qd) { q = {0}; qd = {0}; return true; },
[&](const JointVelocityCommand& command, double) {
std::unique_lock<std::mutex> lock(mutex);
forward_sent |= command.velocity[0] > 0;
reverse_sent |= command.velocity[0] < 0;
if (command.velocity[0] == 0 && block_zero && !zero_entered) {
zero_entered = true; cv.notify_all();
cv.wait_for(lock, 2s, [&] { return release_zero; });
}
cv.notify_all(); return Result::success();
});
CartesianVelocity v; v.vy = .08;
ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok());
{
std::unique_lock<std::mutex> lock(mutex);
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return forward_sent; }));
block_zero = true;
}
ASSERT_TRUE(controller.stop(3).ok());
{
std::unique_lock<std::mutex> lock(mutex);
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return zero_entered; }));
}
v.vy = -.08;
ASSERT_TRUE(controller.speedL(v, 3, 0, FrameType::Base).ok());
{
std::unique_lock<std::mutex> lock(mutex);
release_zero = true; cv.notify_all();
EXPECT_TRUE(cv.wait_for(lock, 1s, [&] { return reverse_sent; }));
}
EXPECT_TRUE(controller.busy());
controller.shutdown();
}
TEST(CartesianVelocityController, PublishesReferenceAfterSendAndKeepsCommandLimits) {
std::mutex mutex;
std::condition_variable cv;
bool entered = false, release = false;
auto planner = std::make_shared<Planner>();
CartesianVelocityController controller({}, planner, 1,
[](auto& q, auto& qd) { q = {0}; qd = {0}; return true; },
[&](const JointVelocityCommand&, double) {
std::unique_lock<std::mutex> lock(mutex);
if (!entered) {
entered = true; cv.notify_all();
cv.wait_for(lock, 2s, [&] { return release; });
}
return Result::success();
});
CartesianVelocity v; v.vy = -.08;
SpeedLOptions options;
options.acceleration = 3;
options.linear_jerk = 60;
options.continuous_linear_reversal = true;
options.capture_reference = true;
ASSERT_TRUE(controller.speedL(v, options, 0, FrameType::Tool).ok());
{
std::unique_lock<std::mutex> lock(mutex);
ASSERT_TRUE(cv.wait_for(lock, 1s, [&] { return entered; }));
EXPECT_FALSE(controller.getReference().valid);
release = true; cv.notify_all();
}
const auto deadline = std::chrono::steady_clock::now() + 1s;
while (!controller.getReference().valid && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(1ms);
const auto ref = controller.getReference();
EXPECT_TRUE(ref.valid);
EXPECT_GT(ref.command_version, 0U);
EXPECT_DOUBLE_EQ(ref.tcp_pose_base.y, .5);
EXPECT_DOUBLE_EQ(ref.target_base.vx, -.08);
EXPECT_DOUBLE_EQ(planner->applied_jerk.load(), 60);
EXPECT_TRUE(planner->applied_reversal.load());
controller.shutdown();
}
TEST(CartesianVelocityController, RejectsInvalidMotionLimitsBeforeStarting) {
auto planner = std::make_shared<Planner>();
CartesianVelocityController controller({}, planner, 1,
[](auto&, auto&) { return false; },
[](const auto&, double) { return Result::success(); });
SpeedLOptions options;
options.linear_jerk = std::numeric_limits<double>::quiet_NaN();
EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok());
options.linear_jerk = -1;
EXPECT_FALSE(controller.speedL({}, options, 0, FrameType::Base).ok());
EXPECT_FALSE(controller.busy());
}
}
}

View File

@ -9,7 +9,8 @@
#include "common/types/arm/arm_types.h"
namespace cmvr {
namespace cmvr
{
/**
* @brief 基于相对 3D 位姿的 PBVS 控制器。
@ -44,7 +45,6 @@ namespace cmvr {
* 姿态误差:
*
* R_err = R_des * R_cur^T
*
* e_R = Log(R_err)^vee
*
* 控制律:
@ -60,9 +60,11 @@ namespace cmvr {
* - IK
* - speedL 下发
*/
class PbvsController {
class PbvsController
{
public:
enum class ComputeStatus {
enum class ComputeStatus
{
OK = 0,
TARGET_NOT_SET,
INVALID_INPUT,
@ -71,36 +73,25 @@ public:
INVALID_CURRENT_POSE
};
struct Output {
struct Output
{
// 当前位置误差,单位 m
Eigen::Vector3d position_error_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d position_error_G{Eigen::Vector3d::Zero()};
// 当前姿态误差 rotation-vector,单位 rad
Eigen::Vector3d rotation_error_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d rotation_error_G{Eigen::Vector3d::Zero()};
// PBVS 计算得到的原始线速度,单位 m/s
Eigen::Vector3d raw_linear_velocity_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d raw_linear_velocity_G{Eigen::Vector3d::Zero()};
// PBVS 计算得到的原始角速度,单位 rad/s
Eigen::Vector3d raw_angular_velocity_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d raw_angular_velocity_G{Eigen::Vector3d::Zero()};
// 经过限幅 / 加速度 / 滤波后的线速度
Eigen::Vector3d linear_velocity_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d linear_velocity_G{Eigen::Vector3d::Zero()};
// 经过限幅 / 加速度 / 滤波后的角速度
Eigen::Vector3d angular_velocity_G{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d angular_velocity_G{Eigen::Vector3d::Zero()};
// 可直接取出的 CartesianVelocity。
//
@ -111,7 +102,6 @@ public:
bool position_reached{false};
bool orientation_reached{false};
bool reached{false};
bool valid{false};
};
@ -123,8 +113,7 @@ public:
*
* @param T_G_P_des TCP(P) 相对于 ScreenTag(G) 的目标位姿。
*/
bool setTargetPose(
const Eigen::Matrix4d& T_G_P_des);
bool setTargetPose(const Eigen::Matrix4d& T_G_P_des);
/**
* @brief 使用目标位置 + 目标姿态设置期望位姿。
@ -136,16 +125,12 @@ public:
/**
* @brief 当前是否已经设置有效目标。
*/
bool hasTarget() const {
return target_valid_;
}
bool hasTarget() const { return target_valid_; }
/**
* @brief 获取目标位姿。
*/
const Eigen::Matrix4d& targetPose() const {
return T_G_P_des_;
}
const Eigen::Matrix4d& targetPose() const { return T_G_P_des_; }
/**
* @brief 根据当前 TCP 位姿计算 PBVS 速度命令。
@ -176,16 +161,14 @@ public:
*
* x/y/z 分别控制。
*/
void setPositionGain(
const Eigen::Vector3d& kp);
void setPositionGain(const Eigen::Vector3d& kp);
/**
* @brief 设置姿态比例增益。
*
* rx/ry/rz 分别控制。
*/
void setRotationGain(
const Eigen::Vector3d& kr);
void setRotationGain(const Eigen::Vector3d& kr);
/**
* @brief 设置六维速度上限。
@ -195,8 +178,7 @@ public:
* 前三维 m/s;
* 后三维 rad/s。
*/
void setVelocityLimit6(
const std::array<double, 6>& vmax6);
void setVelocityLimit6(const std::array<double, 6>& vmax6);
/**
* @brief 设置六维加速度限制。
@ -206,8 +188,7 @@ public:
*
* <= 0 表示对应维度不限制。
*/
void setAccelerationLimit6(
const std::array<double, 6>& amax6);
void setAccelerationLimit6(const std::array<double, 6>& amax6);
/**
* @brief 设置六维误差阈值。
@ -217,21 +198,16 @@ public:
* 前三维 m;
* 后三维 rad。
*/
void setTolerance6(
const std::array<double, 6>& tolerance6);
void setTolerance6(const std::array<double, 6>& tolerance6);
/**
* @brief 设置一阶低通 alpha。
*
* alpha = 1:
* 不滤波。
* alpha = 1:不滤波。
*
* 0 < alpha < 1:
*
* cmd =
* alpha * current
* +
* (1-alpha) * previous
* cmd = alpha * current + (1 - alpha) * previous
*/
void setTwistFilterAlpha(double alpha);
@ -244,8 +220,7 @@ public:
*
* enabled[5] = false;
*/
void setAxisEnabled(
const std::array<bool, 6>& enabled);
void setAxisEnabled(const std::array<bool, 6>& enabled);
/**
* @brief 清空速度历史,但保留目标。
@ -257,70 +232,42 @@ public:
*/
void reset();
ComputeStatus lastComputeStatus() const {
return last_compute_status_;
}
ComputeStatus lastComputeStatus() const { return last_compute_status_; }
static const char* statusToString(
ComputeStatus status);
static const char* statusToString(ComputeStatus status);
const Eigen::Vector3d& lastPositionError() const {
return last_position_error_G_;
}
const Eigen::Vector3d& lastPositionError() const { return last_position_error_G_; }
const Eigen::Vector3d& lastRotationError() const { return last_rotation_error_G_; }
const Eigen::Vector3d& lastRotationError() const {
return last_rotation_error_G_;
}
const Eigen::Vector3d& positionGain() const { return kp_position_; }
const Eigen::Vector3d& rotationGain() const { return kp_rotation_; }
const Eigen::Vector3d& positionGain() const {
return kp_position_;
}
const std::array<double, 6>& velocityLimit6() const { return vmax6_; }
const std::array<double, 6>& accelerationLimit6() const { return amax6_; }
const std::array<double, 6>& tolerance6() const { return tolerance6_; }
const Eigen::Vector3d& rotationGain() const {
return kp_rotation_;
}
double twistFilterAlpha() const { return twist_lpf_alpha_; }
const std::array<double, 6>& velocityLimit6() const {
return vmax6_;
}
const std::array<double, 6>& accelerationLimit6() const {
return amax6_;
}
const std::array<double, 6>& tolerance6() const {
return tolerance6_;
}
double twistFilterAlpha() const {
return twist_lpf_alpha_;
}
const Eigen::Matrix<double, 6, 1>&
lastTwistCommandG() const {
const Eigen::Matrix<double, 6, 1>& lastTwistCommandG() const
{
return last_twist_cmd_G_;
}
bool lastReached() const {
return last_reached_;
}
bool lastReached() const { return last_reached_; }
private:
static bool isFiniteTransform(
const Eigen::Matrix4d& T);
static bool isFiniteTransform(const Eigen::Matrix4d& T);
static bool hasValidBottomRow(
const Eigen::Matrix4d& T,
double tolerance = 1e-6);
static bool isValidTransform(
const Eigen::Matrix4d& T);
static bool isValidTransform(const Eigen::Matrix4d& T);
/**
* @brief 将可能有微小数值误差的旋转矩阵投影到 SO(3)。
*/
static Eigen::Matrix3d projectToSO3(
const Eigen::Matrix3d& R);
static Eigen::Matrix3d projectToSO3(const Eigen::Matrix3d& R);
/**
* @brief 计算空间旋转误差,在 G frame 表达。
@ -333,43 +280,27 @@ private:
const Eigen::Matrix3d& R_des,
const Eigen::Matrix3d& R_cur);
static double clampValue(
double value,
double lower,
double upper);
static double clampValue(double value, double lower, double upper);
static device::CartesianVelocity
toCartesianVelocity(
static device::CartesianVelocity toCartesianVelocity(
const Eigen::Matrix<double, 6, 1>& twist);
private:
// ---------------- target ----------------
Eigen::Matrix4d T_G_P_des_{
Eigen::Matrix4d::Identity()
};
Eigen::Matrix4d T_G_P_des_{Eigen::Matrix4d::Identity()};
bool target_valid_{false};
// ---------------- gains ----------------
Eigen::Vector3d kp_position_{
2.0,
2.0,
1.5
};
Eigen::Vector3d kp_rotation_{
1.5,
1.5,
1.5
};
Eigen::Vector3d kp_position_{2.0, 2.0, 1.5};
Eigen::Vector3d kp_rotation_{1.5, 1.5, 1.5};
// ---------------- velocity limits ----------------
//
// [vx vy vz wx wy wz]
//
std::array<double, 6> vmax6_{{
0.10,
0.10,
@ -393,13 +324,12 @@ private:
// ---------------- tolerance ----------------
std::array<double, 6> tolerance6_{{
0.0015, // x 1.5 mm
0.0015, // y 1.5 mm
0.0020, // z 2.0 mm
0.05, // rx ~2.9 deg
0.05, // ry
0.05 // rz
0.0015, // x 1.5 mm
0.0015, // y 1.5 mm
0.0020, // z 2.0 mm
0.05, // rx ~2.9 deg
0.05, // ry
0.05 // rz
}};
// ---------------- axis enable ----------------
@ -419,33 +349,24 @@ private:
// ---------------- command history ----------------
Eigen::Matrix<double, 6, 1>
previous_twist_cmd_G_{
Eigen::Matrix<double, 6, 1>::Zero()
};
Eigen::Matrix<double, 6, 1> previous_twist_cmd_G_{
Eigen::Matrix<double, 6, 1>::Zero()
};
bool has_previous_twist_{false};
// ---------------- last output ----------------
Eigen::Vector3d last_position_error_G_{
Eigen::Vector3d::Zero()
};
Eigen::Vector3d last_position_error_G_{Eigen::Vector3d::Zero()};
Eigen::Vector3d last_rotation_error_G_{Eigen::Vector3d::Zero()};
Eigen::Vector3d last_rotation_error_G_{
Eigen::Vector3d::Zero()
Eigen::Matrix<double, 6, 1> last_twist_cmd_G_{
Eigen::Matrix<double, 6, 1>::Zero()
};
Eigen::Matrix<double, 6, 1>
last_twist_cmd_G_{
Eigen::Matrix<double, 6, 1>::Zero()
};
bool last_reached_{false};
ComputeStatus last_compute_status_{
ComputeStatus::TARGET_NOT_SET
};
ComputeStatus last_compute_status_{ComputeStatus::TARGET_NOT_SET};
};
} // namespace cmvr

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,6 @@
#include <vector>
#include <Eigen/Core>
#include <pinocchio/multibody/model.hpp>
#include "environment/include/robot_model.h"
@ -82,21 +81,6 @@ public:
const std::string& tip_frame_name,
ChainInfo& out,
std::string* error = nullptr);
// Compatibility for linbo_dev callers that own a standalone parser.
bool loadModel(const std::string& path, std::string* error = nullptr) {
if (legacy_model_.loadUrdf(path)) return true;
if (error) *error = "failed to load URDF: " + path;
return false;
}
bool extractChain(const std::string& base, const std::string& tip,
ChainInfo& out, std::string* error = nullptr) const {
return extractChain(legacy_model_, base, tip, out, error);
}
const pinocchio::Model& model() const { return legacy_model_.kinematics(); }
bool loaded() const { return legacy_model_.hasKinematics(); }
private:
RobotModel legacy_model_;
};
} // namespace cmvr

View File

@ -1,2 +0,0 @@
add_subdirectory(base_motion)
add_subdirectory(arm_motion)

View File

@ -1,35 +0,0 @@
add_library(arm_motion SHARED
cartesian_motion/pinocchio/src/pinocchio_cartesian_motion_planner.cpp
joint_motion/toppra/src/toppra_joint_motion_planner.cpp
)
target_include_directories(arm_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(arm_motion
PUBLIC
cmvr_es::ik_solver
cmvr_es::base_motion
)
add_library(cmvr_es::arm_motion ALIAS arm_motion)
add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion)
install(TARGETS arm_motion LIBRARY DESTINATION lib)
add_executable(toppra_joint_motion_planner_test
joint_motion/toppra/test/toppra_joint_motion_planner_test.cpp
)
target_link_libraries(toppra_joint_motion_planner_test
PRIVATE
cmvr_es::algorithms::arm_motion
gtest
gtest_main
)
add_executable(pinocchio_speedl_limits_test
cartesian_motion/pinocchio/test/pinocchio_speedl_limits_test.cpp
)
target_compile_definitions(pinocchio_speedl_limits_test PRIVATE
CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
target_link_libraries(pinocchio_speedl_limits_test PRIVATE
cmvr_es::algorithms::arm_motion gtest gtest_main)

View File

@ -1,58 +0,0 @@
#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_H
#define CMVR_ES_CARTESIAN_MOTION_PLANNER_H
#include <string>
#include <vector>
#include "cmvr/config/arm_config/arm_config.pb.h"
#include "common/types/arm/arm_types.h"
namespace cmvr::device {
struct CartesianJointTrajectory {
std::vector<std::vector<double>> position;
std::vector<std::vector<double>> velocity;
std::vector<double> time;
double planned_path_length{0.0};
double executable_path_length{0.0};
bool truncated{false};
std::string truncation_reason;
};
class CartesianMotionPlanner {
public:
virtual ~CartesianMotionPlanner() = default;
virtual bool configureSpeedL(const config::SpeedLPlannerConfig& config,
std::size_t dof) = 0;
virtual bool configureMoveL(const config::MoveLPlannerConfig& config) = 0;
virtual bool planMoveL(const CartesianPose& target,
const std::vector<double>& q_start,
const std::vector<double>& qd_max,
double velocity,
double acceleration,
double jerk,
FrameType frame,
CartesianJointTrajectory& trajectory) = 0;
virtual bool speedLStep(const CartesianVelocity& target_velocity,
double dt,
const std::vector<double>& q_measured,
const std::vector<double>& qd_measured,
std::vector<double>& qd_command,
FrameType frame) = 0;
virtual bool updateSpeedLAcceleration(double acceleration) = 0;
virtual bool updateSpeedLLimits(const SpeedLOptions& options) {
return !options.linear_jerk && !options.continuous_linear_reversal.value_or(false) &&
updateSpeedLAcceleration(options.acceleration);
}
virtual bool captureSpeedLReference(const std::vector<double>&,
const CartesianVelocity&, FrameType, SpeedLReference&) { return false; }
virtual CartesianVelocity getSpeedLCommandTwistBase() const = 0;
};
} // namespace cmvr::device
#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_H

View File

@ -1,63 +0,0 @@
#ifndef CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H
#define CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H
#include <memory>
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h"
#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h"
#include "algorithms/motion_planner/arm_motion/cartesian_motion/cartesian_motion_planner.h"
#include "cmvr/config/arm_config/arm_config.pb.h"
namespace cmvr::device {
class CartesianMotionPlannerFactory {
public:
static std::shared_ptr<CartesianMotionPlanner> create(
const config::MoveLConfig& move_l,
const config::SpeedLConfig& speed_l,
const std::shared_ptr<cmvr::PinocchioIKBase>& solver)
{
if (!solver) {
return nullptr;
}
switch (move_l.algorithm_case()) {
case config::MoveLConfig::kPinocchioCartesianMotionPlanner:
if (speed_l.algorithm_case() !=
config::SpeedLConfig::kPinocchioCartesianMotionPlanner) {
return nullptr;
}
return std::make_shared<PinocchioCartesianMotionPlanner>(solver);
case config::MoveLConfig::ALGORITHM_NOT_SET:
default:
return nullptr;
}
}
static const config::SpeedLPlannerConfig* speedLConfig(
const config::SpeedLConfig& cfg)
{
switch (cfg.algorithm_case()) {
case config::SpeedLConfig::kPinocchioCartesianMotionPlanner:
return &cfg.pinocchio_cartesian_motion_planner();
case config::SpeedLConfig::ALGORITHM_NOT_SET:
default:
return nullptr;
}
}
static const config::MoveLPlannerConfig* moveLConfig(
const config::MoveLConfig& cfg)
{
switch (cfg.algorithm_case()) {
case config::MoveLConfig::kPinocchioCartesianMotionPlanner:
return &cfg.pinocchio_cartesian_motion_planner();
case config::MoveLConfig::ALGORITHM_NOT_SET:
default:
return nullptr;
}
}
};
} // namespace cmvr::device
#endif // CMVR_ES_CARTESIAN_MOTION_PLANNER_FACTORY_H

View File

@ -1,117 +0,0 @@
#ifndef CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H
#define CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H
#include <Eigen/Core>
#include <memory>
#include <vector>
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_ik_base.h"
#include "../../cartesian_motion_planner.h"
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
namespace cmvr::device {
class PinocchioCartesianMotionPlanner final : public CartesianMotionPlanner {
public:
explicit PinocchioCartesianMotionPlanner(std::shared_ptr<cmvr::PinocchioIKBase> solver);
bool configureSpeedL(const config::SpeedLPlannerConfig& config,
std::size_t dof) override;
bool configureMoveL(const config::MoveLPlannerConfig& config) override;
bool planMoveL(const CartesianPose& target,
const std::vector<double>& q_start,
const std::vector<double>& qd_max,
double velocity,
double acceleration,
double jerk,
FrameType frame,
CartesianJointTrajectory& trajectory) override;
bool speedLStep(const CartesianVelocity& target_velocity,
double dt,
const std::vector<double>& q_measured,
const std::vector<double>& qd_measured,
std::vector<double>& qd_command,
FrameType frame) override;
bool updateSpeedLAcceleration(double acceleration) override;
bool updateSpeedLLimits(const SpeedLOptions& options) override;
bool captureSpeedLReference(const std::vector<double>& q, const CartesianVelocity& target,
FrameType frame, SpeedLReference& reference) override;
CartesianVelocity getSpeedLCommandTwistBase() const override;
private:
bool refreshJointAccelerationLimits_();
Eigen::VectorXd applyJointAccelerationLimits_(const Eigen::VectorXd& qdot,
const Eigen::VectorXd& reference,
double dt) const;
bool checkMoveLPlanLineDeviation_(const Eigen::Vector3d& p_start,
const Eigen::Vector3d& line_direction,
const Eigen::Vector3d& p_current,
double traveled,
bool& deviation_warned,
bool& direction_warned,
std::string& stop_reason) const;
bool checkMoveLPlanJointContinuity_(const Eigen::VectorXd& q_current,
const Eigen::VectorXd& q_next,
const Eigen::VectorXd& qdot,
const Eigen::VectorXd& prev_qdot,
double dt,
double path_position,
std::string& stop_reason) const;
bool checkMoveLPlanJointPositionLimits_(const Eigen::VectorXd& q_current,
const Eigen::VectorXd& q_next,
const Eigen::VectorXd& qdot,
double dt,
double path_position,
std::string& stop_reason) const;
bool checkMoveLPlanCartesianStepFeasibility_(
const Eigen::Matrix<double, 6, 1>& desired_twist,
const Eigen::Matrix<double, 6, 1>& achieved_twist,
double path_position,
std::string& stop_reason) const;
bool updateAndValidateSpeedLLineDeviation_(const std::vector<double>& q_measured,
bool is_stop_command,
const Eigen::Vector3d& command_linear_base);
bool validateSpeedLJointVelocityCommand_(const Eigen::VectorXd& qdot,
const Eigen::VectorXd& reference,
double dt) const;
bool validateSpeedLPredictedJointPositionLimits_(const std::vector<double>& q_measured,
const Eigen::VectorXd& qdot,
double dt) const;
bool validateSpeedLCartesianVelocityFeasibility_(
const Eigen::Matrix<double, 6, 1>& desired_twist,
const Eigen::Matrix<double, 6, 1>& achieved_twist,
const Eigen::VectorXd& q_current,
const Eigen::VectorXd& qdot) const;
std::string describeJointLimitCandidates_(const Eigen::VectorXd& q_current,
const Eigen::VectorXd& qdot) const;
std::shared_ptr<cmvr::PinocchioIKBase> solver_{nullptr};
config::MoveLPlannerConfig movel_config_{};
config::SpeedLPlannerConfig speedl_config_{};
cmvr::CartesianTwistLimiter twist_limiter_{};
Eigen::VectorXd joint_acceleration_limits_;
std::vector<double> prev_qdot_command_;
Eigen::Matrix<double, 6, 1> speedl_command_twist_base_{Eigen::Matrix<double, 6, 1>::Zero()};
Eigen::Vector3d speedl_line_start_tcp_base_{Eigen::Vector3d::Zero()};
Eigen::Vector3d speedl_line_direction_base_{Eigen::Vector3d::Zero()};
double speedl_applied_acceleration_{0.25};
double speedl_applied_angular_acceleration_{0.25};
double speedl_applied_linear_jerk_{-1.0};
bool speedl_line_check_active_{false};
bool speedl_line_deviation_warned_{false};
bool speedl_line_direction_warned_{false};
// speedL 是否已经进入停止阶段。
// 停止阶段不要每 1 ms 用 measured twist 重新点燃 Cartesian planner。
bool speedl_stop_active_{false};
bool speedl_configured_{false};
};
} // namespace cmvr::device
#endif // CMVR_ES_PINOCCHIO_QP_CARTESIAN_MOTION_PLANNER_H

View File

@ -1,213 +0,0 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <limits>
#include "algorithms/kinematics/ik_solver/pinocchio/include/pinocchio_dls_ik_solver.h"
#include "algorithms/motion_planner/arm_motion/cartesian_motion/pinocchio/include/pinocchio_cartesian_motion_planner.h"
#include "common/io/proto_file_io.h"
#include "common/math/transform_math.h"
namespace cmvr::device {
namespace {
constexpr double kDt = .001;
using Twist = Eigen::Matrix<double, 6, 1>;
// Exercise the production planner and real URDF kinematics, without motor I/O.
class PinocchioSpeedLLimits : public ::testing::Test {
protected:
void SetUp() override {
const auto root = std::filesystem::path(CMVR_TEST_SOURCE_DIR);
config::ArmRootConfig arms;
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(
(root / "cmvr-es/config/devices/arm/arm.pb.txt").string(), &arms));
ASSERT_GT(arms.arm().robot_arms_size(), 0);
auto ik = arms.arm().robot_arms(0).kinematics().pinocchio_dls_ik_solver();
ik.set_urdf_path((root / "model/xiaoyan_description/dual_arm.urdf").string());
solver_ = std::make_shared<PinocchioDlsIKSolver>(ik);
ASSERT_TRUE(solver_->init());
planner_ = std::make_unique<PinocchioCartesianMotionPlanner>(solver_);
limits_.set_linear_velocity_max(.2);
limits_.set_linear_acceleration_max(.4);
limits_.set_linear_jerk_max(2);
limits_.set_angular_velocity_max(1);
limits_.set_angular_acceleration_max(.8);
limits_.set_angular_jerk_max(4);
limits_.set_enforce_joint_acceleration_limits(false);
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
}
struct Peaks { double velocity{0}, acceleration{0}, jerk{0}; };
Peaks sample(const CartesianVelocity& target, const SpeedLOptions& options,
bool angular = false, int steps = 2200, bool legacy_api = false) {
Peaks peaks;
Twist previous = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
Twist previous_acceleration = Twist::Zero();
for (int i = 0; i < steps; ++i) {
const bool updated = legacy_api
? planner_->updateSpeedLAcceleration(options.acceleration)
: planner_->updateSpeedLLimits(options);
if (!updated || !planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base)) {
ADD_FAILURE() << "Planning failed at sample " << i;
break;
}
const Twist velocity = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
const Twist acceleration = (velocity - previous) / kDt;
const Twist jerk = (acceleration - previous_acceleration) / kDt;
const int offset = angular ? 3 : 0;
peaks.velocity = std::max(peaks.velocity, velocity.segment<3>(offset).norm());
peaks.acceleration = std::max(peaks.acceleration, acceleration.segment<3>(offset).norm());
peaks.jerk = std::max(peaks.jerk, jerk.segment<3>(offset).norm());
previous = velocity;
previous_acceleration = acceleration;
}
return peaks;
}
void expectPeaks(const Peaks& p, double velocity, double acceleration, double jerk) {
// These trajectories contain plateaus: limits must be reached, as well
// as obeyed, so an unintended smaller cap cannot pass the test.
EXPECT_NEAR(p.velocity, velocity, 1e-8);
EXPECT_NEAR(p.acceleration, acceleration, 1e-8);
EXPECT_NEAR(p.jerk, jerk, 1e-6);
}
std::shared_ptr<PinocchioDlsIKSolver> solver_;
std::unique_ptr<PinocchioCartesianMotionPlanner> planner_;
config::SpeedLPlannerConfig limits_;
const std::vector<double> q_{.25, 1, M_PI / 2, M_PI / 2, -M_PI / 2, 0, 0};
const std::vector<double> qd_ = std::vector<double>(7, 0);
std::vector<double> command_;
};
TEST_F(PinocchioSpeedLLimits, ExcessiveRequestsRespectAllLinearLimits) {
SpeedLOptions options;
options.acceleration = 60;
options.linear_jerk = 60;
CartesianVelocity target;
target.vx = .6;
target.vy = .8;
expectPeaks(sample(target, options), .2, .4, 2);
}
TEST_F(PinocchioSpeedLLimits, LowerRequestsRemainEffective) {
SpeedLOptions options;
options.acceleration = .15;
options.linear_jerk = .8;
CartesianVelocity target;
target.vy = 1;
expectPeaks(sample(target, options), .2, .15, .8);
}
TEST_F(PinocchioSpeedLLimits, OmittedJerkRestoresArmLimit) {
SpeedLOptions options;
options.acceleration = .4;
options.linear_jerk = .3;
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
options.linear_jerk.reset();
CartesianVelocity target;
target.vy = 1;
expectPeaks(sample(target, options), .2, .4, 2);
}
TEST_F(PinocchioSpeedLLimits, LegacyAccelerationAndStopAreCapped) {
SpeedLOptions options;
options.acceleration = 60;
CartesianVelocity target;
target.vy = 1;
expectPeaks(sample(target, options, false, 1200, true), .2, .4, 2);
const auto stop = sample({}, options, false, 1200, true);
EXPECT_LE(stop.velocity, .2);
EXPECT_NEAR(stop.acceleration, .4, 1e-8);
EXPECT_NEAR(stop.jerk, 2, 1e-6);
EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-12);
}
TEST_F(PinocchioSpeedLLimits, AngularAccelerationHasItsOwnCapAndCache) {
limits_.set_linear_acceleration_max(.2);
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
SpeedLOptions options;
options.acceleration = .3;
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
// Linear effective acceleration stays at .2, but angular must change.
options.acceleration = .6;
CartesianVelocity target;
target.wy = 2;
expectPeaks(sample(target, options, true), 1, .6, 4);
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
options.acceleration = 60;
expectPeaks(sample(target, options, true), 1, .8, 4);
}
TEST_F(PinocchioSpeedLLimits, InvalidRequestsAreRejectedBeforeClamping) {
for (double invalid : {0.0, -1.0, std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::quiet_NaN()}) {
SpeedLOptions options;
options.acceleration = invalid;
EXPECT_FALSE(planner_->updateSpeedLLimits(options));
EXPECT_FALSE(planner_->updateSpeedLAcceleration(invalid));
options.acceleration = .3;
options.linear_jerk = invalid;
EXPECT_FALSE(planner_->updateSpeedLLimits(options));
}
}
TEST_F(PinocchioSpeedLLimits, StreamingAlignmentOverridesGlobalReversalPolicy) {
for (const double jerk : {10.0, 30.0}) {
SCOPED_TRACE(jerk);
limits_.set_continuous_linear_reversal(true);
limits_.set_linear_acceleration_max(5);
limits_.set_linear_jerk_max(jerk);
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
SpeedLOptions options;
options.acceleration = .5;
CartesianVelocity target;
target.vy = .02;
sample(target, options, false, 300);
ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10);
// Same acceleration/jerk: the policy override must bypass their cache.
options.continuous_linear_reversal = false;
double min_speed = .02;
double max_error = 0;
for (int i = 0; i < 2000; ++i) {
const double angle = (i / 20) * .01;
target.vx = .02 * std::sin(angle);
target.vy = .02 * std::cos(angle);
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
const Twist actual = common::math::velocityToVector(planner_->getSpeedLCommandTwistBase());
min_speed = std::min(min_speed, actual.head<3>().norm());
max_error = std::max(max_error, (actual - common::math::velocityToVector(target)).norm());
}
EXPECT_NEAR(min_speed, .02, 1e-10);
EXPECT_LT(max_error, 1e-10);
}
}
TEST_F(PinocchioSpeedLLimits, ContactReversalStillCrossesZeroAfterStreamingAlignment) {
limits_.set_linear_acceleration_max(1);
limits_.set_linear_jerk_max(4);
ASSERT_TRUE(planner_->configureSpeedL(limits_, q_.size()));
SpeedLOptions options;
options.acceleration = 1;
options.continuous_linear_reversal = false;
CartesianVelocity target;
target.vy = .02;
sample(target, options, false, 300);
ASSERT_NEAR(planner_->getSpeedLCommandTwistBase().vy, .02, 1e-10);
options.continuous_linear_reversal = true;
target.vy = -.02;
for (int i = 0; i < 100; ++i) {
ASSERT_TRUE(planner_->updateSpeedLLimits(options));
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
}
EXPECT_NEAR(planner_->getSpeedLCommandTwistBase().vy, 0, 1e-10);
ASSERT_TRUE(planner_->speedLStep(target, kDt, q_, qd_, command_, FrameType::Base));
EXPECT_LT(planner_->getSpeedLCommandTwistBase().vy, -.0003);
}
} // namespace
} // namespace cmvr::device

View File

@ -1,55 +0,0 @@
#ifndef CMVR_ES_TWIST_LIMITER_CONFIG_H
#define CMVR_ES_TWIST_LIMITER_CONFIG_H
#include <algorithm>
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
#include "cmvr/config/arm_config/arm_config.pb.h"
#include "common/config/config_files.h"
namespace cmvr::device::cartesian_motion {
inline void configureTwistLimiterFromSpeedLConfig(
cmvr::CartesianTwistLimiter& limiter,
const config::SpeedLPlannerConfig& config)
{
using cmvr::common::config::positiveOr;
limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
positiveOr(config.linear_acceleration_max(), 5.0),
positiveOr(config.linear_jerk_max(), 10.0));
limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
positiveOr(config.angular_acceleration_max(), 5.0),
positiveOr(config.angular_jerk_max(), 12.0));
limiter.setLinearTargetReplanThreshold(
positiveOr(config.linear_target_replan_threshold(), 1e-4));
limiter.setAngularTargetReplanThreshold(
positiveOr(config.angular_target_replan_threshold(), 1e-4));
limiter.setLinearReverseSwitchPolicy(
config.linear_reverse_cos_threshold() != 0.0
? config.linear_reverse_cos_threshold()
: -0.8660254037844386,
positiveOr(config.linear_reverse_switch_speed_threshold(), 1e-3));
limiter.setContinuousLinearReversal(!config.has_continuous_linear_reversal() ||
config.continuous_linear_reversal());
limiter.initialize(Eigen::Matrix<double, 6, 1>::Zero());
}
inline void updateTwistLimiterAcceleration(
cmvr::CartesianTwistLimiter& limiter,
const config::SpeedLPlannerConfig& config,
const double acceleration)
{
using cmvr::common::config::positiveOr;
limiter.setLinearConstraints(positiveOr(config.linear_velocity_max(), 0.55),
std::min(acceleration, positiveOr(config.linear_acceleration_max(), 5.0)),
positiveOr(config.linear_jerk_max(), 10.0));
limiter.setAngularConstraints(positiveOr(config.angular_velocity_max(), 1.0),
std::min(acceleration, positiveOr(config.angular_acceleration_max(), 5.0)),
positiveOr(config.angular_jerk_max(), 12.0));
}
} // namespace cmvr::device::cartesian_motion
#endif // CMVR_ES_TWIST_LIMITER_CONFIG_H

View File

@ -1,156 +0,0 @@
#ifndef CMVR_ES_JOINT_MOTION_PLANNER_H
#define CMVR_ES_JOINT_MOTION_PLANNER_H
#include <algorithm>
#include <cmath>
#include <vector>
#include "common/base/logging/logger.h"
#include "common/types/arm/arm_types.h"
namespace cmvr::device {
class JointMotionPlanner {
public:
virtual ~JointMotionPlanner() = default;
virtual bool init() = 0;
virtual bool planMoveJ(const std::vector<double>& start,
const JointPositionCommand& target,
const MotionOptions& options,
double speed_scaling,
JointTrajectory& trajectory) = 0;
virtual bool planReplay(const std::vector<double>& current_position,
const JointTrajectory& recorded_trajectory,
const MotionOptions& options,
JointTrajectory& replay_trajectory) = 0;
bool validateJointTrajectory(const JointTrajectory& trajectory,
std::size_t expected_dof,
const MotionOptions& limits) const;
};
inline bool JointMotionPlanner::validateJointTrajectory(
const JointTrajectory& trajectory,
const std::size_t expected_dof,
const MotionOptions& limits) const
{
if (trajectory.size() < 2 || expected_dof == 0) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory must contain at least "
"two points and have a non-zero DOF";
return false;
}
if (!std::isfinite(limits.velocity) || limits.velocity <= 0.0 ||
!std::isfinite(limits.acceleration) || limits.acceleration <= 0.0) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity or acceleration limit is invalid";
return false;
}
if (!limits.joint_velocity_limits.empty() &&
limits.joint_velocity_limits.size() != expected_dof) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] joint velocity limit count does not match DOF";
return false;
}
constexpr double kVelocityTolerance = 1e-6;
constexpr double kAccelerationTolerance = 1e-3;
double maximum_velocity = 0.0;
double maximum_acceleration = 0.0;
double maximum_position_velocity = 0.0;
double maximum_position_acceleration = 0.0;
double maximum_jerk = 0.0;
std::vector<double> previous_position_velocity(expected_dof, 0.0);
std::vector<double> previous_acceleration(expected_dof, 0.0);
for (std::size_t i = 0; i < trajectory.size(); ++i) {
const auto& point = trajectory[i];
if (!std::isfinite(point.time_s) ||
point.position.size() != expected_dof ||
point.velocity.size() != expected_dof) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid trajectory point at index=" << i;
return false;
}
double dt = 0.0;
if (i > 0) {
dt = point.time_s - trajectory[i - 1].time_s;
if (!std::isfinite(dt) || dt <= 0.0) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] trajectory time is not increasing at index="
<< i;
return false;
}
}
for (std::size_t joint = 0; joint < expected_dof; ++joint) {
if (!std::isfinite(point.position[joint]) ||
!std::isfinite(point.velocity[joint])) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] non-finite trajectory value at point="
<< i << ", joint=" << joint;
return false;
}
const double velocity = std::abs(point.velocity[joint]);
const double velocity_limit = limits.joint_velocity_limits.empty()
? limits.velocity
: limits.joint_velocity_limits[joint];
if (!std::isfinite(velocity_limit) || velocity_limit <= 0.0) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] invalid velocity limit for joint="
<< joint;
return false;
}
maximum_velocity = std::max(maximum_velocity, velocity);
if (velocity > velocity_limit + kVelocityTolerance) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] velocity limit exceeded at point="
<< i << ", joint=" << joint
<< ", actual=" << velocity
<< ", limit=" << velocity_limit;
return false;
}
if (i > 0) {
const double position_velocity =
(point.position[joint] - trajectory[i - 1].position[joint]) / dt;
const double acceleration =
(point.velocity[joint] - trajectory[i - 1].velocity[joint]) / dt;
maximum_position_velocity = std::max(
maximum_position_velocity, std::abs(position_velocity));
maximum_acceleration = std::max(
maximum_acceleration, std::abs(acceleration));
if (std::abs(acceleration) >
limits.acceleration + kAccelerationTolerance) {
CMVR_LOG(ERROR) << "[JointMotionPlanner] acceleration limit exceeded at point="
<< i << ", joint=" << joint
<< ", actual=" << std::abs(acceleration)
<< ", limit=" << limits.acceleration;
return false;
}
if (i > 1) {
maximum_position_acceleration = std::max(
maximum_position_acceleration,
std::abs(position_velocity -
previous_position_velocity[joint]) / dt);
maximum_jerk = std::max(
maximum_jerk,
std::abs(acceleration - previous_acceleration[joint]) / dt);
}
previous_position_velocity[joint] = position_velocity;
previous_acceleration[joint] = acceleration;
}
}
}
CMVR_LOG(INFO) << "[JointMotionPlanner] trajectory validated"
<< ", points=" << trajectory.size()
<< ", max_velocity_rad_s=" << maximum_velocity
<< ", max_discrete_acceleration_rad_s2=" << maximum_acceleration
<< ", max_position_velocity_rad_s=" << maximum_position_velocity
<< ", max_position_acceleration_rad_s2="
<< maximum_position_acceleration
<< ", max_discrete_jerk_rad_s3=" << maximum_jerk;
return true;
}
} // namespace cmvr::device
#endif // CMVR_ES_JOINT_MOTION_PLANNER_H

View File

@ -1,55 +0,0 @@
#ifndef CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H
#define CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H
#include <memory>
#include "algorithms/motion_planner/arm_motion/joint_motion/joint_motion_planner.h"
#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h"
#include "cmvr/config/arm_config/arm_config.pb.h"
namespace cmvr::device {
class JointMotionPlannerFactory {
public:
static std::shared_ptr<JointMotionPlanner> create(
const config::MoveJConfig& cfg)
{
if (!cfg.has_toppra_joint_motion_planner()) {
return nullptr;
}
cmvr::PathType path_type;
switch (cfg.toppra_joint_motion_planner().path_type()) {
case config::TOPPRA_PATH_TYPE_LINEAR:
path_type = cmvr::PathType::Linear;
break;
case config::TOPPRA_PATH_TYPE_CUBIC_HERMITE:
path_type = cmvr::PathType::CubicHermite;
break;
case config::TOPPRA_PATH_TYPE_QUINTIC:
path_type = cmvr::PathType::Quintic;
break;
case config::TOPPRA_PATH_TYPE_NATURAL:
path_type = cmvr::PathType::Natural;
break;
case config::TOPPRA_PATH_TYPE_UNKNOWN:
default:
return nullptr;
}
const auto& toppra = cfg.toppra_joint_motion_planner();
auto planner = std::make_shared<ToppraJointMotionPlanner>(
path_type,
toppra.sample_period_s(),
toppra.grid_size(),
toppra.high_grid_size());
if (!planner->init()) {
return nullptr;
}
return planner;
}
};
} // namespace cmvr::device
#endif // CMVR_ES_JOINT_MOTION_PLANNER_FACTORY_H

View File

@ -1,46 +0,0 @@
#ifndef CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H
#define CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H
#include <memory>
#include "../../joint_motion_planner.h"
#include "../../../../base_motion/joint_trajectory/joint_trajectory_planner.h"
namespace cmvr::device {
class ToppraJointMotionPlanner final : public JointMotionPlanner {
public:
ToppraJointMotionPlanner(cmvr::PathType path_type,
double sample_period_s,
int grid_size,
int high_grid_size);
bool init() override;
bool planMoveJ(const std::vector<double>& start,
const JointPositionCommand& target,
const MotionOptions& options,
double speed_scaling,
JointTrajectory& trajectory) override;
bool planReplay(const std::vector<double>& current_position,
const JointTrajectory& recorded_trajectory,
const MotionOptions& options,
JointTrajectory& replay_trajectory) override;
private:
bool sampleTrajectory_(
const std::shared_ptr<cmvr::JointTrajectoryPlanner>& planner,
const cmvr::TrajPtr& raw_trajectory,
JointTrajectory& trajectory) const;
std::shared_ptr<cmvr::JointTrajectoryPlanner> planner_;
cmvr::PathType path_type_{cmvr::PathType::Quintic};
double sample_period_s_{0.001};
int grid_size_{150};
int high_grid_size_{300};
};
} // namespace cmvr::device
#endif // CMVR_ES_TOPPRA_JOINT_MOTION_PLANNER_H

View File

@ -1,258 +0,0 @@
#include "algorithms/motion_planner/arm_motion/joint_motion/toppra/include/toppra_joint_motion_planner.h"
#include <cmath>
#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
#include "common/base/logging/logger.h"
namespace cmvr::device {
namespace {
std::vector<double> toStdVector(const Eigen::VectorXd& value)
{
std::vector<double> result;
result.reserve(static_cast<std::size_t>(value.size()));
for (int i = 0; i < value.size(); ++i) {
result.push_back(value[i]);
}
return result;
}
} // namespace
ToppraJointMotionPlanner::ToppraJointMotionPlanner(const cmvr::PathType path_type,
const double sample_period_s,
const int grid_size,
const int high_grid_size)
: path_type_(path_type)
, sample_period_s_(sample_period_s)
, grid_size_(grid_size)
, high_grid_size_(high_grid_size)
{
}
bool ToppraJointMotionPlanner::init()
{
if (sample_period_s_ <= 0.0 || grid_size_ <= 0 || high_grid_size_ < grid_size_) {
return false;
}
planner_ = std::make_shared<cmvr::ToppraJointTrajectoryPlanner>(path_type_);
planner_->setGridSizes(grid_size_, high_grid_size_);
return true;
}
bool ToppraJointMotionPlanner::sampleTrajectory_(
const std::shared_ptr<cmvr::JointTrajectoryPlanner>& planner,
const cmvr::TrajPtr& raw_trajectory,
JointTrajectory& trajectory) const
{
const auto raw_samples = planner->sampleTrajectory(
raw_trajectory, sample_period_s_);
if (raw_samples.size() < 2) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] trajectory sampling returned fewer than "
"two points: count="
<< raw_samples.size();
return false;
}
trajectory.clear();
trajectory.reserve(raw_samples.size());
for (std::size_t i = 0; i < raw_samples.size(); ++i) {
const auto& sample = raw_samples[i];
if (!std::isfinite(sample.t) || !sample.q.allFinite() ||
!sample.qd.allFinite()) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner] sampled trajectory contains "
"a non-finite value at point="
<< i;
trajectory.clear();
return false;
}
JointTrajectoryPoint point;
point.time_s = sample.t;
point.position = toStdVector(sample.q);
point.velocity = toStdVector(sample.qd);
trajectory.push_back(std::move(point));
}
return true;
}
bool ToppraJointMotionPlanner::planMoveJ(const std::vector<double>& start,
const JointPositionCommand& target,
const MotionOptions& options,
const double speed_scaling,
JointTrajectory& trajectory)
{
trajectory.clear();
if (!planner_ || start.empty() || start.size() != target.position.size() ||
options.velocity <= 0.0 || options.acceleration <= 0.0) {
return false;
}
cmvr::TrajPtr raw_trajectory;
planner_->setPathType(path_type_);
planner_->setGridSizes(grid_size_, high_grid_size_);
planner_->setSymmetricLimits(
std::vector<double>(start.size(), options.velocity * speed_scaling),
std::vector<double>(start.size(), options.acceleration));
if (!planner_->plan(start, target.position, raw_trajectory)) {
return false;
}
return sampleTrajectory_(planner_, raw_trajectory, trajectory);
}
bool ToppraJointMotionPlanner::planReplay(
const std::vector<double>& current_position,
const JointTrajectory& recorded_trajectory,
const MotionOptions& options,
JointTrajectory& replay_trajectory)
{
replay_trajectory.clear();
if (current_position.empty() || recorded_trajectory.size() < 2 ||
options.velocity <= 0.0 ||
options.acceleration <= 0.0 || !std::isfinite(options.velocity) ||
!std::isfinite(options.acceleration)) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid trajectory or options";
return false;
}
const std::size_t dof = current_position.size();
if (!options.joint_velocity_limits.empty() &&
options.joint_velocity_limits.size() != dof) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid DOF or joint limits";
return false;
}
for (const double position : current_position) {
if (!std::isfinite(position)) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite current position";
return false;
}
}
for (std::size_t i = 0; i < recorded_trajectory.size(); ++i) {
const auto& point = recorded_trajectory[i];
if (!std::isfinite(point.time_s) || point.position.size() != dof ||
(i > 0 && point.time_s <= recorded_trajectory[i - 1].time_s)) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid recorded point: "
<< i;
return false;
}
for (std::size_t joint = 0; joint < dof; ++joint) {
if (!std::isfinite(point.position[joint])) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] non-finite recorded point: "
<< i;
return false;
}
}
}
std::vector<double> velocity_limits = options.joint_velocity_limits;
if (velocity_limits.empty()) {
velocity_limits.assign(dof, options.velocity);
}
for (std::size_t joint = 0; joint < velocity_limits.size(); ++joint) {
const double limit = velocity_limits[joint];
if (!std::isfinite(limit) || limit <= 0.0) {
CMVR_LOG(ERROR) << "[ToppraJointMotionPlanner][planReplay] invalid joint velocity limit";
return false;
}
}
const double ramp_duration_s = std::max(
sample_period_s_, options.velocity / options.acceleration);
replay_trajectory.reserve(recorded_trajectory.size() + 2);
replay_trajectory.push_back(JointTrajectoryPoint{
0.0, current_position, std::vector<double>(dof, 0.0)});
double replay_time_s = ramp_duration_s;
replay_trajectory.push_back(JointTrajectoryPoint{
replay_time_s,
recorded_trajectory.back().position,
std::vector<double>(dof, 0.0)});
for (std::size_t i = recorded_trajectory.size() - 1; i > 0; --i) {
replay_time_s += recorded_trajectory[i].time_s -
recorded_trajectory[i - 1].time_s;
replay_trajectory.push_back(JointTrajectoryPoint{
replay_time_s,
recorded_trajectory[i - 1].position,
std::vector<double>(dof, 0.0)});
}
replay_time_s += ramp_duration_s;
replay_trajectory.push_back(JointTrajectoryPoint{
replay_time_s,
recorded_trajectory.front().position,
std::vector<double>(dof, 0.0)});
const auto update_velocities = [&] {
for (auto& point : replay_trajectory) {
std::fill(point.velocity.begin(), point.velocity.end(), 0.0);
}
for (std::size_t i = 1; i + 1 < replay_trajectory.size(); ++i) {
const double dt = replay_trajectory[i + 1].time_s -
replay_trajectory[i - 1].time_s;
for (std::size_t joint = 0; joint < dof; ++joint) {
replay_trajectory[i].velocity[joint] =
(replay_trajectory[i + 1].position[joint] -
replay_trajectory[i - 1].position[joint]) / dt;
}
}
};
for (int iteration = 0; iteration < 3; ++iteration) {
update_velocities();
double required_scale = 1.0;
std::vector<double> previous_position_velocity(dof, 0.0);
for (std::size_t i = 0; i < replay_trajectory.size(); ++i) {
const auto& point = replay_trajectory[i];
for (std::size_t joint = 0; joint < dof; ++joint) {
required_scale = std::max(
required_scale,
std::abs(point.velocity[joint]) / velocity_limits[joint]);
if (i == 0) {
continue;
}
const double dt = point.time_s -
replay_trajectory[i - 1].time_s;
const double position_velocity =
(point.position[joint] -
replay_trajectory[i - 1].position[joint]) / dt;
const double acceleration =
(point.velocity[joint] -
replay_trajectory[i - 1].velocity[joint]) / dt;
required_scale = std::max(
required_scale,
std::abs(position_velocity) / velocity_limits[joint]);
required_scale = std::max(
required_scale,
std::sqrt(std::abs(acceleration) /
options.acceleration));
if (i > 1) {
const double position_acceleration =
(position_velocity -
previous_position_velocity[joint]) / dt;
required_scale = std::max(
required_scale,
std::sqrt(std::abs(position_acceleration) /
options.acceleration));
}
previous_position_velocity[joint] = position_velocity;
}
}
if (required_scale <= 1.0 + 1e-9) {
break;
}
required_scale *= 1.001;
for (auto& point : replay_trajectory) {
point.time_s *= required_scale;
}
}
update_velocities();
if (!validateJointTrajectory(replay_trajectory, dof, options)) {
replay_trajectory.clear();
return false;
}
return true;
}
} // namespace cmvr::device

View File

@ -1,139 +0,0 @@
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <limits>
#include <vector>
#include <gtest/gtest.h>
#include "joint_motion/toppra/include/toppra_joint_motion_planner.h"
namespace cmvr::device {
namespace {
constexpr std::size_t kDof = 7;
JointTrajectory makeRecordedTrajectory(const std::size_t point_count)
{
JointTrajectory trajectory;
trajectory.reserve(point_count);
for (std::size_t i = 0; i < point_count; ++i) {
const double s = static_cast<double>(i) /
static_cast<double>(point_count - 1);
JointTrajectoryPoint point;
point.time_s = static_cast<double>(i) * 0.002;
point.position = {
0.40 * s,
-0.25 * s + 0.03 * std::sin(3.141592653589793 * s),
0.20 * s * s,
0.30 * std::sin(1.5707963267948966 * s),
-0.12 * s,
0.15 * s,
-0.08 * std::sin(3.141592653589793 * s),
};
point.velocity.assign(kDof, 0.0);
trajectory.push_back(std::move(point));
}
return trajectory;
}
double maximumPositionError(const std::vector<double>& lhs,
const std::vector<double>& rhs)
{
if (lhs.size() != rhs.size()) {
return std::numeric_limits<double>::infinity();
}
double maximum = 0.0;
for (std::size_t i = 0; i < lhs.size(); ++i) {
maximum = std::max(maximum, std::abs(lhs[i] - rhs[i]));
}
return maximum;
}
TEST(ToppraJointMotionPlannerTest, PlansBoundedReverseReplay)
{
ToppraJointMotionPlanner planner(
cmvr::PathType::Quintic, 0.001, 150, 300);
ASSERT_TRUE(planner.init());
const JointTrajectory recorded = makeRecordedTrajectory(300);
MotionOptions options;
options.velocity = 0.15;
options.acceleration = 5.0;
JointTrajectory replay;
ASSERT_TRUE(planner.planReplay(
recorded.back().position, recorded, options, replay));
ASSERT_EQ(replay.size(), recorded.size() + 2);
EXPECT_LT(maximumPositionError(
replay.front().position, recorded.back().position),
1e-9);
EXPECT_LT(maximumPositionError(
replay.back().position, recorded.front().position),
1e-9);
for (std::size_t i = 0; i < recorded.size(); ++i) {
EXPECT_LT(maximumPositionError(
replay[i + 1].position,
recorded[recorded.size() - 1 - i].position),
1e-9);
}
double maximum_velocity = 0.0;
double maximum_acceleration = 0.0;
for (std::size_t i = 0; i < replay.size(); ++i) {
ASSERT_EQ(replay[i].position.size(), kDof);
ASSERT_EQ(replay[i].velocity.size(), kDof);
for (std::size_t joint = 0; joint < kDof; ++joint) {
maximum_velocity = std::max(
maximum_velocity, std::abs(replay[i].velocity[joint]));
if (i > 0) {
const double dt = replay[i].time_s - replay[i - 1].time_s;
ASSERT_GT(dt, 0.0);
maximum_acceleration = std::max(
maximum_acceleration,
std::abs(replay[i].velocity[joint] -
replay[i - 1].velocity[joint]) / dt);
}
}
}
EXPECT_LE(maximum_velocity, options.velocity + 1e-6);
EXPECT_LE(maximum_acceleration, options.acceleration + 1e-3);
}
TEST(ToppraJointMotionPlannerTest, RejectsNonIncreasingRecordedTime)
{
ToppraJointMotionPlanner planner(
cmvr::PathType::Quintic, 0.001, 150, 300);
ASSERT_TRUE(planner.init());
JointTrajectory recorded = makeRecordedTrajectory(10);
recorded[5].time_s = recorded[4].time_s;
MotionOptions options;
options.velocity = 0.15;
options.acceleration = 5.0;
JointTrajectory replay;
EXPECT_FALSE(planner.planReplay(
recorded.back().position, recorded, options, replay));
EXPECT_TRUE(replay.empty());
}
TEST(ToppraJointMotionPlannerTest, ValidationRejectsInvalidOutputTrajectory)
{
ToppraJointMotionPlanner planner(
cmvr::PathType::Quintic, 0.001, 150, 300);
MotionOptions options;
options.velocity = 0.15;
options.acceleration = 5.0;
JointTrajectory trajectory = makeRecordedTrajectory(10);
trajectory[5].velocity[2] = options.velocity + 0.01;
EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options));
trajectory[5].velocity[2] = 0.0;
trajectory[5].time_s = trajectory[4].time_s;
EXPECT_FALSE(planner.validateJointTrajectory(trajectory, kDof, options));
}
} // namespace
} // namespace cmvr::device

View File

@ -1,49 +0,0 @@
add_library(base_motion SHARED
joint_trajectory/toppra/src/toppra_joint_trajectory_planner.cpp
motion_profile/s_curve/src/s_curve.cpp
motion_profile/s_curve/src/s_curve_position_planner.cpp
motion_profile/s_curve/src/s_curve_velocity_planner.cpp
cartesian_velocity/twist_limiter/src/cartesian_twist_limiter.cpp
)
target_include_directories(base_motion PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(base_motion PUBLIC
OsqpEigen
tinyxml2
fcl
toppra
cmvr_es::common
)
add_library(cmvr_es::base_motion ALIAS base_motion)
add_executable(cartesian_twist_limiter_reversal_test
cartesian_velocity/twist_limiter/test/cartesian_twist_limiter_reversal_test.cpp)
target_link_libraries(cartesian_twist_limiter_reversal_test PRIVATE
cmvr_es::base_motion gtest gtest_main)
install(TARGETS base_motion LIBRARY DESTINATION lib)
add_executable(toppra_multi_waypoint_test
joint_trajectory/toppra/test/toppra_multi_waypoint_test.cpp
)
target_link_libraries(toppra_multi_waypoint_test
PRIVATE
cmvr_es::base_motion
gtest
gtest_main
)
add_executable(s_curve_velocity_planner_stop_test
motion_profile/s_curve/test/s_curve_velocity_planner_stop_test.cpp
)
target_link_libraries(s_curve_velocity_planner_stop_test
PRIVATE
cmvr_es::base_motion
gtest
gtest_main
)

View File

@ -1,249 +0,0 @@
#pragma once
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h"
namespace cmvr
{
enum class CartesianFrame
{
Base = 0,
Tool = 1
};
/**
* @brief 6维末端 twist 在线限幅器(基于 SCurveVelocityPlanner1D)
*
* 线速度部分:
* - 固定轴上的有符号速度使用 SCurveVelocityPlanner1D 做 jerk-limited 规划
* - 同轴反向连续过零,保留加速度;可显式选择旧的停止后换向策略
* - 运动中锁定当前方向,不做方向插值
* - 若目标方向与当前方向不共线,则采用“先减速到0,再切方向”的 switch policy
*
* 角速度部分:
* - 与线速度独立
* - 模长使用 SCurveVelocityPlanner1D 做 jerk-limited 速度规划
* - 运动中锁定当前旋转轴,不做方向插值
*
* 接口语义:
* - setTargetTwist(...):设置目标 twist
* - synchronizeToMeasuredTwistBase(...):用测量 twist 同步当前状态
* - update(dt, base_R_tool):根据当前目标与当前状态生成下一拍命令 twist
*/
class CartesianTwistLimiter
{
public:
using Twist = Eigen::Matrix<double, 6, 1>;
CartesianTwistLimiter();
void setLinearConstraints(double max_velocity,
double max_acceleration,
double max_jerk);
void setAngularConstraints(double max_velocity,
double max_acceleration,
double max_jerk);
void setLinearTargetReplanThreshold(double threshold);
void setAngularTargetReplanThreshold(double threshold);
/**
* @brief 设置线速度方向最大转动角速度(rad/s)
*/
void setLinearDirectionRateLimit(double max_rate_rad_s);
/**
* @brief 设置角速度方向最大转动角速度(rad/s)
*/
void setAngularDirectionRateLimit(double max_rate_rad_s);
/**
* @brief 设置线速度反向切换策略
*
* @param cos_threshold 近反向判定阈值,范围 [-1, 1]
* @param switch_speed_threshold 线速度模长低于该阈值后,允许切到目标方向
*/
void setLinearReverseSwitchPolicy(double cos_threshold,
double switch_speed_threshold);
// Same-axis reversal uses a signed velocity without resetting acceleration
// at zero. Disable for streaming direction tracking (e.g. visual alignment).
void setContinuousLinearReversal(bool enabled);
bool continuousLinearReversalEnabled() const { return continuous_linear_reversal_; }
/**
* @brief 初始化当前 twist 状态
*
* 注意:
* - 初始 twist 视为 base 坐标系下
*/
void initialize(const Twist& initial_twist = Twist::Zero());
void reset();
/**
* @brief 设置目标 twist
*
* @param target_twist 目标 twist
* @param frame 输入目标的坐标系(Base 或 Tool)
*/
void setTargetTwist(const Twist& target_twist, CartesianFrame frame);
/**
* @brief 平滑停下
*/
void stop();
/**
* @brief 急停
*
* 使用更大的减速度/jerk 约束把当前线速度/角速度平滑拉回 0。
* 当前运动停止后,会自动恢复到常规约束。
*
* @param emergency_acceleration 急停减速度幅值
* @param emergency_jerk 急停 jerk 幅值
*/
void emergencyStop(double emergency_acceleration,
double emergency_jerk);
/**
* @brief 急停(分别指定线速度/角速度减速度与 jerk)
*
* @param emergency_linear_acceleration 线速度急停减速度幅值
* @param emergency_linear_jerk 线速度急停 jerk 幅值
* @param emergency_angular_acceleration 角速度急停减速度幅值
* @param emergency_angular_jerk 角速度急停 jerk 幅值
*/
void emergencyStop(double emergency_linear_acceleration,
double emergency_linear_jerk,
double emergency_angular_acceleration,
double emergency_angular_jerk);
/**
* @brief 用测得的 base-frame twist 同步当前状态
*
* 作用:
* - 更新当前执行方向
* - 线速度使用固定轴投影(保留正负号),角速度使用模长
* - keep_target=true 时:
* - 若测量状态仍贴着当前 profile,则保持当前 profile
* - 否则由 planner 内部从测量状态重规划到当前目标
* - keep_target=false 时:
* - 清掉旧 profile,仅覆盖状态
*
* @param measured_twist_base 当前测得实际 twist(base 系)
* @param dt 与上一次测量同步的时间间隔
* @param keep_target 是否保留当前目标模长
*/
void synchronize(const Twist& measured_twist_base,
double dt,
bool keep_target = true);
/**
* @brief 更新一步,返回 base 坐标系下的执行 twist 命令
*/
Twist update(double dt, const Eigen::Matrix3d& base_R_tool);
const Twist& getTwistBase() const { return twist_base_; }
const Twist& getCommandedTwistBase() const { return twist_base_; }
const Twist& getTargetTwistBase() const { return target_twist_base_; }
const Twist& getAccelerationBase() const { return acceleration_base_; }
const Twist& getJerkBase() const { return jerk_base_; }
bool isMoving() const;
private:
static constexpr double EPSILON = 1e-12;
static constexpr double DEFAULT_LINEAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s
static constexpr double DEFAULT_ANGULAR_DIR_RATE_LIMIT = 3.14159265358979323846; // 180 deg/s
static constexpr double DEFAULT_LINEAR_REVERSE_COS_THRESHOLD = -0.8660254037844386; // cos(150 deg)
static constexpr double DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD = 1e-3;
static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999;
static constexpr double DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD = 1e-3;
// 模长 planner
SCurveVelocityPlanner1D linear_norm_planner_;
SCurveVelocityPlanner1D angular_norm_planner_;
// 常规约束缓存。急停结束后恢复到这里。
double linear_max_velocity_;
double linear_max_acceleration_;
double linear_max_jerk_;
double angular_max_velocity_;
double angular_max_acceleration_;
double angular_max_jerk_;
// 方向变化率限制(rad/s)
double linear_direction_rate_limit_;
double angular_direction_rate_limit_;
// 线速度 reverse policy
double linear_reverse_cos_threshold_;
double linear_reverse_switch_speed_threshold_;
double angular_switch_speed_threshold_;
bool emergency_stop_active_;
bool continuous_linear_reversal_{true};
// 目标/当前状态
Twist target_twist_input_;
Twist target_twist_base_;
Twist twist_base_;
Twist acceleration_base_;
Twist jerk_base_;
Twist prev_twist_base_;
Twist prev_acceleration_base_;
CartesianFrame input_frame_;
// 当前执行方向
Eigen::Vector3d current_linear_dir_base_;
Eigen::Vector3d current_angular_dir_base_;
// 最近一次非零目标方向(目标变0时用于平滑停下)
Eigen::Vector3d last_target_linear_dir_base_;
Eigen::Vector3d last_target_angular_dir_base_;
// 测量同步用缓存
bool has_measured_sync_;
Twist last_measured_twist_base_;
Twist last_measured_acceleration_base_;
double prev_measured_linear_norm_;
double prev_measured_angular_norm_;
static Twist transformTwistToolToBase(const Twist& twist_tool,
const Eigen::Matrix3d& base_R_tool);
static Eigen::Vector3d chooseDirection(const Eigen::Vector3d& target_vec,
const Eigen::Vector3d& fallback);
static Eigen::Vector3d rotateDirectionToward(const Eigen::Vector3d& current_dir,
const Eigen::Vector3d& target_dir,
double max_rate_rad_s,
double dt);
static Eigen::Vector3d rotateAroundAxis(const Eigen::Vector3d& v,
const Eigen::Vector3d& axis_unit,
double angle_rad);
static Eigen::Vector3d chooseOrthogonalUnit(const Eigen::Vector3d& v);
void applyLinearConstraints(double max_velocity,
double max_acceleration,
double max_jerk);
void applyAngularConstraints(double max_velocity,
double max_acceleration,
double max_jerk);
void restoreNominalConstraints();
static bool isZeroTwist(const Twist& twist);
static double clamp(double value, double lo, double hi)
{
return std::max(lo, std::min(hi, value));
}
};
} // namespace cmvr

View File

@ -1,573 +0,0 @@
#include "../include/cartesian_twist_limiter.h"
#include <algorithm>
#include <cmath>
namespace cmvr
{
CartesianTwistLimiter::CartesianTwistLimiter()
: linear_norm_planner_(1.0, 1.0, 5.0)
, angular_norm_planner_(1.0, 1.0, 5.0)
, linear_max_velocity_(1.0)
, linear_max_acceleration_(1.0)
, linear_max_jerk_(5.0)
, angular_max_velocity_(1.0)
, angular_max_acceleration_(1.0)
, angular_max_jerk_(5.0)
, linear_direction_rate_limit_(DEFAULT_LINEAR_DIR_RATE_LIMIT)
, angular_direction_rate_limit_(DEFAULT_ANGULAR_DIR_RATE_LIMIT)
, linear_reverse_cos_threshold_(DEFAULT_LINEAR_REVERSE_COS_THRESHOLD)
, linear_reverse_switch_speed_threshold_(DEFAULT_LINEAR_REVERSE_SWITCH_SPEED_THRESHOLD)
, angular_switch_speed_threshold_(DEFAULT_ANGULAR_SWITCH_SPEED_THRESHOLD)
, emergency_stop_active_(false)
, target_twist_input_(Twist::Zero())
, target_twist_base_(Twist::Zero())
, twist_base_(Twist::Zero())
, acceleration_base_(Twist::Zero())
, jerk_base_(Twist::Zero())
, prev_twist_base_(Twist::Zero())
, prev_acceleration_base_(Twist::Zero())
, input_frame_(CartesianFrame::Base)
, current_linear_dir_base_(Eigen::Vector3d::Zero())
, current_angular_dir_base_(Eigen::Vector3d::Zero())
, last_target_linear_dir_base_(Eigen::Vector3d::Zero())
, last_target_angular_dir_base_(Eigen::Vector3d::Zero())
, has_measured_sync_(false)
, last_measured_twist_base_(Twist::Zero())
, last_measured_acceleration_base_(Twist::Zero())
, prev_measured_linear_norm_(0.0)
, prev_measured_angular_norm_(0.0)
{
}
void CartesianTwistLimiter::applyLinearConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
linear_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk);
}
void CartesianTwistLimiter::applyAngularConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
angular_norm_planner_.setConstraints(max_velocity, max_acceleration, max_jerk);
}
void CartesianTwistLimiter::setLinearConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
linear_max_velocity_ = std::abs(max_velocity);
linear_max_acceleration_ = std::abs(max_acceleration);
linear_max_jerk_ = std::abs(max_jerk);
if (!emergency_stop_active_) {
applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_);
}
}
void CartesianTwistLimiter::setAngularConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
angular_max_velocity_ = std::abs(max_velocity);
angular_max_acceleration_ = std::abs(max_acceleration);
angular_max_jerk_ = std::abs(max_jerk);
if (!emergency_stop_active_) {
applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_);
}
}
void CartesianTwistLimiter::setLinearTargetReplanThreshold(double threshold)
{
linear_norm_planner_.setTargetReplanThreshold(threshold);
}
void CartesianTwistLimiter::setAngularTargetReplanThreshold(double threshold)
{
angular_norm_planner_.setTargetReplanThreshold(threshold);
}
void CartesianTwistLimiter::setLinearDirectionRateLimit(double max_rate_rad_s)
{
linear_direction_rate_limit_ = std::max(0.0, max_rate_rad_s);
}
void CartesianTwistLimiter::setAngularDirectionRateLimit(double max_rate_rad_s)
{
angular_direction_rate_limit_ = std::max(0.0, max_rate_rad_s);
}
void CartesianTwistLimiter::setLinearReverseSwitchPolicy(double cos_threshold,
double switch_speed_threshold)
{
linear_reverse_cos_threshold_ = clamp(cos_threshold, -1.0, 1.0);
linear_reverse_switch_speed_threshold_ = std::max(0.0, switch_speed_threshold);
}
void CartesianTwistLimiter::setContinuousLinearReversal(bool enabled)
{
if (continuous_linear_reversal_ == enabled) return;
if (!enabled) {
const double velocity = linear_norm_planner_.getVelocity();
const double acceleration = linear_norm_planner_.getAcceleration();
// The streaming policy stores a speed magnitude and a physical direction.
// Convert a negative signed state without reversing its physical motion or
// dropping its acceleration when a command changes policy mid-retraction.
if (velocity < 0.0 || (std::abs(velocity) <= EPSILON && acceleration < 0.0)) {
current_linear_dir_base_ = -current_linear_dir_base_;
linear_norm_planner_.overwriteState(-velocity, -acceleration, false);
prev_measured_linear_norm_ = -prev_measured_linear_norm_;
}
}
continuous_linear_reversal_ = enabled;
}
void CartesianTwistLimiter::initialize(const Twist& initial_twist)
{
restoreNominalConstraints();
emergency_stop_active_ = false;
const Eigen::Vector3d v0 = initial_twist.head<3>();
const Eigen::Vector3d w0 = initial_twist.tail<3>();
const double v0_norm = v0.norm();
const double w0_norm = w0.norm();
linear_norm_planner_.initialize(v0_norm, 0.0);
angular_norm_planner_.initialize(w0_norm, 0.0);
target_twist_input_ = initial_twist;
target_twist_base_ = initial_twist;
twist_base_ = initial_twist;
acceleration_base_.setZero();
jerk_base_.setZero();
prev_twist_base_ = initial_twist;
prev_acceleration_base_.setZero();
// current_linear_dir_base_ =
// (v0_norm > EPSILON) ? (v0 / v0_norm) : Eigen::Vector3d::Zero();
// current_angular_dir_base_ =
// (w0_norm > EPSILON) ? (w0 / w0_norm) : Eigen::Vector3d::Zero();
current_linear_dir_base_.setZero();
current_angular_dir_base_.setZero();
if (v0_norm > EPSILON) {
current_linear_dir_base_ = v0 / v0_norm;
} else {
}
if (w0_norm > EPSILON) {
current_angular_dir_base_ = w0 / w0_norm;
} else {
}
last_target_linear_dir_base_ = current_linear_dir_base_;
last_target_angular_dir_base_ = current_angular_dir_base_;
has_measured_sync_ = false;
last_measured_twist_base_ = initial_twist;
last_measured_acceleration_base_.setZero();
prev_measured_linear_norm_ = v0_norm;
prev_measured_angular_norm_ = w0_norm;
}
void CartesianTwistLimiter::reset()
{
restoreNominalConstraints();
emergency_stop_active_ = false;
linear_norm_planner_.reset();
angular_norm_planner_.reset();
target_twist_input_.setZero();
target_twist_base_.setZero();
twist_base_.setZero();
acceleration_base_.setZero();
jerk_base_.setZero();
prev_twist_base_.setZero();
prev_acceleration_base_.setZero();
input_frame_ = CartesianFrame::Base;
current_linear_dir_base_.setZero();
current_angular_dir_base_.setZero();
last_target_linear_dir_base_.setZero();
last_target_angular_dir_base_.setZero();
has_measured_sync_ = false;
last_measured_twist_base_.setZero();
last_measured_acceleration_base_.setZero();
prev_measured_linear_norm_ = 0.0;
prev_measured_angular_norm_ = 0.0;
}
void CartesianTwistLimiter::setTargetTwist(const Twist& target_twist, CartesianFrame frame)
{
if (emergency_stop_active_ && !isZeroTwist(target_twist)) {
restoreNominalConstraints();
emergency_stop_active_ = false;
}
target_twist_input_ = target_twist;
input_frame_ = frame;
}
void CartesianTwistLimiter::stop()
{
// target_twist_input_.setZero();
target_twist_input_.setZero();
target_twist_base_.setZero();
linear_norm_planner_.setTargetVelocity(0.0);
angular_norm_planner_.setTargetVelocity(0.0);
}
void CartesianTwistLimiter::emergencyStop(double emergency_acceleration,
double emergency_jerk)
{
emergencyStop(emergency_acceleration,
emergency_jerk,
emergency_acceleration,
emergency_jerk);
}
void CartesianTwistLimiter::emergencyStop(double emergency_linear_acceleration,
double emergency_linear_jerk,
double emergency_angular_acceleration,
double emergency_angular_jerk)
{
const double linear_stop_acceleration =
std::max(std::abs(emergency_linear_acceleration), linear_max_acceleration_);
const double linear_stop_jerk =
std::max(std::abs(emergency_linear_jerk), linear_max_jerk_);
const double angular_stop_acceleration =
std::max(std::abs(emergency_angular_acceleration), angular_max_acceleration_);
const double angular_stop_jerk =
std::max(std::abs(emergency_angular_jerk), angular_max_jerk_);
applyLinearConstraints(linear_max_velocity_, linear_stop_acceleration, linear_stop_jerk);
applyAngularConstraints(angular_max_velocity_, angular_stop_acceleration, angular_stop_jerk);
emergency_stop_active_ = true;
target_twist_input_.setZero();
target_twist_base_.setZero();
linear_norm_planner_.setTargetVelocity(0.0);
angular_norm_planner_.setTargetVelocity(0.0);
}
void CartesianTwistLimiter::synchronize(const Twist& measured_twist_base,
double dt,
bool keep_target)
{
const Eigen::Vector3d v_meas = measured_twist_base.head<3>();
const Eigen::Vector3d w_meas = measured_twist_base.tail<3>();
const bool signed_linear = continuous_linear_reversal_ && current_linear_dir_base_.norm() > EPSILON;
const double v_norm = signed_linear ? v_meas.dot(current_linear_dir_base_) : v_meas.norm();
const double w_norm = w_meas.norm();
double v_acc = 0.0;
double w_acc = 0.0;
if (dt > EPSILON && has_measured_sync_) {
v_acc = (v_norm - prev_measured_linear_norm_) / dt;
w_acc = (w_norm - prev_measured_angular_norm_) / dt;
acceleration_base_ = (measured_twist_base - last_measured_twist_base_) / dt;
jerk_base_ = (acceleration_base_ - last_measured_acceleration_base_) / dt;
last_measured_acceleration_base_ = acceleration_base_;
} else {
acceleration_base_.setZero();
jerk_base_.setZero();
last_measured_acceleration_base_.setZero();
}
prev_measured_linear_norm_ = v_norm;
prev_measured_angular_norm_ = w_norm;
last_measured_twist_base_ = measured_twist_base;
has_measured_sync_ = true;
// 线速度按固定轴投影保留正负号;角速度仍按模长同步 planner。
// keep_target=true:
// - 若测量值仍贴着当前 profile,则继续沿旧 profile 走
// - 否则从测量状态重规划到当前目标
// keep_target=false:
// - 仅覆盖状态并清掉旧 profile,不保留当前目标
if (keep_target) {
linear_norm_planner_.synchronizeAndReplan(v_norm, v_acc);
angular_norm_planner_.synchronizeAndReplan(w_norm, w_acc);
} else {
linear_norm_planner_.overwriteState(v_norm, v_acc, false);
angular_norm_planner_.overwriteState(w_norm, w_acc, false);
target_twist_input_.setZero();
target_twist_base_.setZero();
}
if (!signed_linear && v_norm > EPSILON) {
current_linear_dir_base_ = v_meas / v_norm;
last_target_linear_dir_base_ = current_linear_dir_base_;
}
if (w_norm > EPSILON) {
current_angular_dir_base_ = w_meas / w_norm;
last_target_angular_dir_base_ = current_angular_dir_base_;
}
twist_base_ = measured_twist_base;
prev_twist_base_ = measured_twist_base;
prev_acceleration_base_ = acceleration_base_;
}
CartesianTwistLimiter::Twist
CartesianTwistLimiter::transformTwistToolToBase(const Twist& twist_tool,
const Eigen::Matrix3d& base_R_tool)
{
Twist twist_base;
twist_base.head<3>() = base_R_tool * twist_tool.head<3>();
twist_base.tail<3>() = base_R_tool * twist_tool.tail<3>();
return twist_base;
}
Eigen::Vector3d CartesianTwistLimiter::chooseDirection(const Eigen::Vector3d& target_vec,
const Eigen::Vector3d& fallback)
{
const double n = target_vec.norm();
if (n > EPSILON) {
return target_vec / n;
}
return fallback;
}
Eigen::Vector3d CartesianTwistLimiter::rotateAroundAxis(const Eigen::Vector3d& v,
const Eigen::Vector3d& axis_unit,
double angle_rad)
{
const double c = std::cos(angle_rad);
const double s = std::sin(angle_rad);
return c * v + s * (axis_unit.cross(v)) + (1.0 - c) * axis_unit.dot(v) * axis_unit;
}
Eigen::Vector3d CartesianTwistLimiter::chooseOrthogonalUnit(const Eigen::Vector3d& v)
{
Eigen::Vector3d ref;
if (std::abs(v.x()) < 0.8) {
ref = Eigen::Vector3d::UnitX();
} else if (std::abs(v.y()) < 0.8) {
ref = Eigen::Vector3d::UnitY();
} else {
ref = Eigen::Vector3d::UnitZ();
}
Eigen::Vector3d ortho = ref - ref.dot(v) * v;
const double n = ortho.norm();
if (n > EPSILON) {
return ortho / n;
}
return Eigen::Vector3d::UnitX();
}
void CartesianTwistLimiter::restoreNominalConstraints()
{
applyLinearConstraints(linear_max_velocity_, linear_max_acceleration_, linear_max_jerk_);
applyAngularConstraints(angular_max_velocity_, angular_max_acceleration_, angular_max_jerk_);
}
bool CartesianTwistLimiter::isZeroTwist(const Twist& twist)
{
return twist.head<3>().squaredNorm() <= EPSILON && twist.tail<3>().squaredNorm() <= EPSILON;
}
Eigen::Vector3d CartesianTwistLimiter::rotateDirectionToward(const Eigen::Vector3d& current_dir,
const Eigen::Vector3d& target_dir,
double max_rate_rad_s,
double dt)
{
if (dt <= 0.0) {
return current_dir;
}
const double cur_n = current_dir.norm();
const double tgt_n = target_dir.norm();
if (tgt_n <= EPSILON) {
return current_dir;
}
if (cur_n <= EPSILON) {
return target_dir;
}
const Eigen::Vector3d u = current_dir / cur_n;
const Eigen::Vector3d v = target_dir / tgt_n;
const double dot_uv = clamp(u.dot(v), -1.0, 1.0);
const double angle = std::acos(dot_uv);
if (angle <= 1e-9) {
return v;
}
const double max_step = std::max(0.0, max_rate_rad_s) * dt;
if (max_step <= 0.0) {
return u;
}
if (angle <= max_step) {
return v;
}
Eigen::Vector3d axis = u.cross(v);
const double axis_n = axis.norm();
if (axis_n > EPSILON) {
axis /= axis_n;
return rotateAroundAxis(u, axis, max_step).normalized();
}
if (dot_uv > 0.0) {
return v;
}
const Eigen::Vector3d ortho_axis = chooseOrthogonalUnit(u);
return rotateAroundAxis(u, ortho_axis, max_step).normalized();
}
CartesianTwistLimiter::Twist
CartesianTwistLimiter::update(double dt, const Eigen::Matrix3d& base_R_tool)
{
if (emergency_stop_active_ && isZeroTwist(target_twist_input_) &&
!linear_norm_planner_.isMoving() && !angular_norm_planner_.isMoving()) {
restoreNominalConstraints();
emergency_stop_active_ = false;
}
if (input_frame_ == CartesianFrame::Base) {
target_twist_base_ = target_twist_input_;
} else {
target_twist_base_ = transformTwistToolToBase(target_twist_input_, base_R_tool);
}
// ==================== 线速度:方向锁定 + 标量 planner ====================
const Eigen::Vector3d v_des = target_twist_base_.head<3>();
const double v_des_norm = v_des.norm();
const Eigen::Vector3d v_target_dir =
chooseDirection(v_des,
current_linear_dir_base_.norm() > EPSILON
? current_linear_dir_base_
: last_target_linear_dir_base_);
if (v_des_norm > EPSILON) {
last_target_linear_dir_base_ = v_target_dir;
}
const double v_cur_norm = linear_norm_planner_.getVelocity();
const bool has_current_linear_dir = current_linear_dir_base_.norm() > EPSILON;
if (!has_current_linear_dir) {
if (v_des_norm > EPSILON) {
current_linear_dir_base_ = v_target_dir;
linear_norm_planner_.setTargetVelocity(v_des_norm);
} else {
linear_norm_planner_.setTargetVelocity(0.0);
}
} else if (v_des_norm <= EPSILON) {
linear_norm_planner_.setTargetVelocity(0.0);
} else {
const double dir_dot =
clamp(current_linear_dir_base_.dot(v_target_dir), -1.0, 1.0);
const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD;
const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD;
const bool same_axis = axis_aligned || reverse_aligned;
const bool must_switch_axis =
!same_axis || dir_dot < linear_reverse_cos_threshold_;
if (continuous_linear_reversal_ && same_axis) {
// Keep the axis fixed: the scalar profile carries the direction sign.
// Crossing zero is an interior point, with continuous acceleration.
linear_norm_planner_.setTargetVelocity(v_des.dot(current_linear_dir_base_));
} else if (continuous_linear_reversal_ &&
(std::abs(v_cur_norm) > EPSILON ||
std::abs(linear_norm_planner_.getAcceleration()) > EPSILON ||
linear_norm_planner_.hasActiveProfile())) {
// A different axis may only be adopted after the old profile settles.
linear_norm_planner_.setTargetVelocity(0.0);
} else if (!continuous_linear_reversal_ && must_switch_axis &&
v_cur_norm > linear_reverse_switch_speed_threshold_) {
linear_norm_planner_.setTargetVelocity(0.0);
} else {
current_linear_dir_base_ = v_target_dir;
linear_norm_planner_.setTargetVelocity(v_des_norm);
}
}
const double v_exec_norm = linear_norm_planner_.update(dt);
twist_base_.head<3>() = current_linear_dir_base_ * v_exec_norm;
// ==================== 角速度:方向锁定 + 标量 planner ====================
const Eigen::Vector3d w_des = target_twist_base_.tail<3>();
const double w_des_norm = w_des.norm();
const Eigen::Vector3d w_target_dir =
chooseDirection(w_des,
current_angular_dir_base_.norm() > EPSILON
? current_angular_dir_base_
: last_target_angular_dir_base_);
if (w_des_norm > EPSILON) {
last_target_angular_dir_base_ = w_target_dir;
}
const double w_cur_norm = angular_norm_planner_.getVelocity();
const bool has_current_angular_dir = current_angular_dir_base_.norm() > EPSILON;
if (!has_current_angular_dir) {
if (w_des_norm > EPSILON) {
current_angular_dir_base_ = w_target_dir;
angular_norm_planner_.setTargetVelocity(w_des_norm);
} else {
angular_norm_planner_.setTargetVelocity(0.0);
}
} else if (w_des_norm <= EPSILON) {
angular_norm_planner_.setTargetVelocity(0.0);
} else {
const double dir_dot =
clamp(current_angular_dir_base_.dot(w_target_dir), -1.0, 1.0);
const bool axis_aligned = dir_dot >= AXIS_LOCK_COS_THRESHOLD;
const bool reverse_aligned = dir_dot <= -AXIS_LOCK_COS_THRESHOLD;
const bool same_axis = axis_aligned || reverse_aligned;
// 角速度与线速度一致:反向同轴也必须先减速到 0,再切方向。
const bool must_switch_axis = !same_axis || reverse_aligned;
if (must_switch_axis && w_cur_norm > angular_switch_speed_threshold_) {
angular_norm_planner_.setTargetVelocity(0.0);
} else {
current_angular_dir_base_ = w_target_dir;
angular_norm_planner_.setTargetVelocity(w_des_norm);
}
}
const double w_exec_norm = angular_norm_planner_.update(dt);
twist_base_.tail<3>() = current_angular_dir_base_ * w_exec_norm;
// ==================== 对最终 twist 做差分得到 acc / jerk ====================
if (dt > EPSILON) {
acceleration_base_ = (twist_base_ - prev_twist_base_) / dt;
jerk_base_ = (acceleration_base_ - prev_acceleration_base_) / dt;
} else {
acceleration_base_.setZero();
jerk_base_.setZero();
}
prev_twist_base_ = twist_base_;
prev_acceleration_base_ = acceleration_base_;
return twist_base_;
}
bool CartesianTwistLimiter::isMoving() const
{
return linear_norm_planner_.isMoving() || angular_norm_planner_.isMoving();
}
} // namespace cmvr

View File

@ -1,118 +0,0 @@
#include <gtest/gtest.h>
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
namespace cmvr {
namespace {
using Twist = CartesianTwistLimiter::Twist;
constexpr double dt = .001;
Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; }
struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; };
Motion reverse(bool continuous, int approach_ticks) {
CartesianTwistLimiter limiter;
limiter.setLinearConstraints(.55, 5, 10);
limiter.setContinuousLinearReversal(continuous);
limiter.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero());
limiter.setTargetTwist(y(.08), CartesianFrame::Base);
for (int i = 0; i < approach_ticks; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
limiter.setLinearConstraints(.55, 3, 10);
limiter.setTargetTwist(y(-.08), CartesianFrame::Base);
Motion result;
double position = 0;
for (int i = 1; i <= 1500; ++i) {
const auto v = limiter.update(dt, Eigen::Matrix3d::Identity());
position += v.y() * dt;
result.peak = std::max(result.peak, position);
if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt;
if (result.reverse_time > 0 && position <= 0 && result.return_time < 0) result.return_time = i * dt;
if (continuous) {
EXPECT_LE(limiter.getAccelerationBase().norm(), 3.0 + 1e-7);
EXPECT_LE(limiter.getJerkBase().norm(), 10.0 + 1e-6);
EXPECT_NEAR(v.x(), 0, 1e-12);
EXPECT_NEAR(v.z(), 0, 1e-12);
}
}
EXPECT_NEAR(limiter.getTwistBase().y(), -.08, 1e-9);
return result;
}
TEST(CartesianTwistReversal, ContinuousReversalReducesTimeAndForwardTravel) {
for (const int ticks : {0, 80, 120}) {
SCOPED_TRACE(ticks);
const auto legacy = reverse(false, ticks);
const auto continuous = reverse(true, ticks);
EXPECT_GT(continuous.reverse_time, 0);
EXPECT_LT(continuous.reverse_time, legacy.reverse_time);
EXPECT_LT(continuous.return_time, legacy.return_time);
EXPECT_LT(continuous.peak, legacy.peak);
}
}
TEST(CartesianTwistReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
CartesianTwistLimiter limiter;
limiter.setLinearConstraints(1, 1, 4);
limiter.initialize(y(.02));
limiter.setTargetTwist(y(-.02), CartesianFrame::Base);
for (int i = 0; i < 100; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
EXPECT_NEAR(limiter.getTwistBase().y(), 0, 1e-12);
EXPECT_TRUE(limiter.isMoving());
EXPECT_LT(limiter.getAccelerationBase().y(), -.39);
EXPECT_LT(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.0003);
}
TEST(CartesianTwistReversal, StopFromEitherDirectionSettlesWithoutReversing) {
for (double v : {.08, -.08}) {
CartesianTwistLimiter limiter;
limiter.setLinearConstraints(1, 3, 10);
limiter.initialize(y(v));
limiter.stop();
for (int i = 0; i < 1000; ++i) {
EXPECT_GE(limiter.update(dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
}
EXPECT_FALSE(limiter.isMoving());
EXPECT_NEAR(limiter.getTwistBase().norm(), 0, 1e-12);
}
}
TEST(CartesianTwistReversal, FeedbackPreservesNegativeVelocityOnLockedAxis) {
CartesianTwistLimiter limiter;
limiter.setLinearConstraints(1, 3, 10);
limiter.initialize(y(.08));
limiter.setTargetTwist(y(-.08), CartesianFrame::Base);
for (int i = 0; i < 400; ++i) limiter.update(dt, Eigen::Matrix3d::Identity());
for (int i = 0; i < 10; ++i) {
limiter.synchronize(y(-.08), dt, true);
EXPECT_NEAR(limiter.update(dt, Eigen::Matrix3d::Identity()).y(), -.08, 1e-9);
}
}
TEST(CartesianTwistReversal, NonCollinearChangeStopsBeforeSwitchingAxis) {
CartesianTwistLimiter limiter;
limiter.setLinearConstraints(1, 3, 10);
limiter.initialize(y(.08));
Twist x = Twist::Zero(); x.x() = .08;
limiter.setTargetTwist(x, CartesianFrame::Base);
for (int i = 0; i < 1000; ++i) {
const auto v = limiter.update(dt, Eigen::Matrix3d::Identity());
EXPECT_FALSE(v.x() > 1e-9 && std::abs(v.y()) > 1e-9);
EXPECT_LE(limiter.getJerkBase().norm(), 10 + 1e-6);
}
EXPECT_NEAR(limiter.getTwistBase().x(), .08, 1e-9);
}
TEST(CartesianTwistReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
for (const int reverse_ticks : {150, 250, 500}) {
SCOPED_TRACE(reverse_ticks);
CartesianTwistLimiter reference;
reference.setLinearConstraints(1, 3, 10);
reference.initialize(y(.08));
reference.setTargetTwist(y(-.08), CartesianFrame::Base);
for (int i = 0; i < reverse_ticks; ++i) reference.update(dt, Eigen::Matrix3d::Identity());
ASSERT_LT(reference.getTwistBase().y(), 0);
auto streaming = reference;
streaming.setContinuousLinearReversal(false);
EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12);
for (int i = 0; i < 500; ++i) {
const auto expected = reference.update(dt, Eigen::Matrix3d::Identity());
const auto actual = streaming.update(dt, Eigen::Matrix3d::Identity());
EXPECT_NEAR((actual - expected).norm(), 0, 1e-9);
EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6);
}
}
}
}
}

View File

@ -1,90 +0,0 @@
//
// Created by lgv on 11/7/25.
//
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <Eigen/Dense>
#include <toppra/geometric_path/piecewise_poly_path.hpp>
#include <toppra/parametrizer/const_accel.hpp>
#include <toppra/parametrizer/spline.hpp>
namespace cmvr {
// 统一轨迹接口
struct ITrajectory {
virtual ~ITrajectory() = default;
virtual toppra::Bound timeInterval() const = 0;
virtual Eigen::VectorXd q(double t) const = 0;
virtual Eigen::VectorXd qd(double t) const = 0;
virtual Eigen::VectorXd qdd(double t) const = 0;
};
using TrajPtr = std::shared_ptr<ITrajectory>;
struct TrajSample {
double t{};
Eigen::VectorXd q; // DoF x 1
Eigen::VectorXd qd; // DoF x 1
Eigen::VectorXd qdd; // DoF x 1
};
// 三种几何路径
enum class PathType { Linear,
CubicHermite,
Quintic,
// 三次B样条
Natural };
class JointTrajectoryPlanner {
public:
explicit JointTrajectoryPlanner(PathType p):path_type_(p){};
JointTrajectoryPlanner()=default;
virtual ~JointTrajectoryPlanner() = default;
virtual bool plan(const std::vector<double>& start_joints,
const std::vector<double>& goal_joints,
TrajPtr& traj) {
return false;
}
virtual bool plan(const std::vector<std::vector<double>>& waypoints, TrajPtr& traj){
return false;
}
// 采样函数:从 ITrajectory 生成采样序列 dt(s)
virtual std::vector<TrajSample> sampleTrajectory(const TrajPtr& traj, double dt) {
return {};
}
virtual bool writeTrajectoryCsv(const std::string& filename,const std::vector<TrajSample>& samples) {
return false;
}
// 对称限:[-v_max, v_max]、[-a_max, a_max]
virtual void setSymmetricLimits(const std::vector<double> &v_max,const std::vector<double> &a_max){
v_max_ = v_max;
a_max_ = a_max;
}
// 可调网格密度(默认 150/300)
virtual void setGridSizes(int N, int N_high)
{
N_grid_ = N;
N_grid_high_ = N_high;
}
// 切换几何路径类型
virtual void setPathType(PathType p){path_type_ = p;}
protected:
PathType path_type_{PathType::Quintic};
int N_grid_ = 150;
int N_grid_high_ = 300;
std::vector<double> v_max_, a_max_;
};
}

View File

@ -1,209 +0,0 @@
#pragma once
#include <memory>
#include <vector>
#include <Eigen/Dense>
#include "../../joint_trajectory_planner.h"
#include <toppra/geometric_path/piecewise_poly_path.hpp>
#include <toppra/parametrizer/const_accel.hpp>
#include <toppra/parametrizer/spline.hpp>
namespace cmvr {
// 适配器:ConstAccel
class ConstAccelTraj : public ITrajectory {
public:
explicit ConstAccelTraj(std::shared_ptr<toppra::parametrizer::ConstAccel> p);
toppra::Bound timeInterval() const override;
Eigen::VectorXd q(double t) const override;
Eigen::VectorXd qd(double t) const override;
Eigen::VectorXd qdd(double t) const override;
private:
std::shared_ptr<toppra::parametrizer::ConstAccel> impl_;
};
// 适配器:Spline
class SplineTraj : public ITrajectory {
public:
SplineTraj(const std::shared_ptr<toppra::PiecewisePolyPath> &path,
const toppra::Vector &grid,
const toppra::Vector &vsq);
toppra::Bound timeInterval() const override;
Eigen::VectorXd q(double t) const override;
Eigen::VectorXd qd(double t) const override;
Eigen::VectorXd qdd(double t) const override;
private:
toppra::parametrizer::Spline impl_;
};
// 具体规划器:一次/三次/五次可切换;ConstAccel 校验失败自动回退 Spline
class ToppraJointTrajectoryPlanner : public JointTrajectoryPlanner {
public:
explicit ToppraJointTrajectoryPlanner(PathType type = PathType::Quintic);
// 统一入口:两点/多点皆可
bool plan(const std::vector<std::vector<double> > &waypoints, TrajPtr &traj_out) override;
// 兼容旧 API(可选):转发为两点的统一入口
bool plan(const std::vector<double> &start_joints,
const std::vector<double> &goal_joints,
TrajPtr &traj_out) override;
std::vector<TrajSample> sampleTrajectory(const TrajPtr &traj, double dt) override;
bool writeTrajectoryCsv(const std::string &filename, const std::vector<TrajSample> &samples) override;
private:
// —— 几何路径统一分发 ——
std::shared_ptr<toppra::PiecewisePolyPath>
buildPathUnified(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S);
// 二点专用
std::shared_ptr<toppra::PiecewisePolyPath>
buildTwoPointPath(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
std::shared_ptr<toppra::PiecewisePolyPath>
buildLinearTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
std::shared_ptr<toppra::PiecewisePolyPath>
buildCubicHermiteTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
std::shared_ptr<toppra::PiecewisePolyPath>
buildQuinticRestToRestTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
std::shared_ptr<toppra::PiecewisePolyPath>
buildNaturalTwo(const Eigen::VectorXd &q0, const Eigen::VectorXd &q1);
// 多点
std::shared_ptr<toppra::PiecewisePolyPath>
buildLinearMulti(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S);
std::shared_ptr<toppra::PiecewisePolyPath>
buildCubicHermiteMulti(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S);
std::shared_ptr<toppra::PiecewisePolyPath>
buildQuinticC2Multi(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S);
std::shared_ptr<toppra::PiecewisePolyPath>
buildNaturalMulti(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S);
// —— 工具:限幅/参数/估计 ——
bool ensureLimitsSized(std::size_t DoF);
static void sanitizeVsq(toppra::Vector &v);
// Joint-space chord length keeps the parameterization independent of
// how densely the same geometric path is sampled.
static std::vector<toppra::value_type>
makeSChordLength(const std::vector<Eigen::VectorXd> &q) {
const size_t M = q.size();
std::vector<toppra::value_type> S(M, 0.0);
for (size_t i = 1; i < M; ++i) {
S[i] = S[i - 1] + (q[i] - q[i - 1]).norm();
}
return S;
}
// Catmull–Rom(centripetal)估计结点几何速度 v(端点=0)
static std::vector<Eigen::VectorXd>
estimateVelsCatmull(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S) {
const size_t M = q.size();
const int DoF = static_cast<int>(q[0].size());
std::vector<Eigen::VectorXd> v(M, Eigen::VectorXd::Zero(DoF));
if (M <= 2) return v;
for (size_t i = 1; i + 1 < M; ++i) {
double ds0 = std::max<double>(S[i] - S[i - 1], 1e-12);
double ds1 = std::max<double>(S[i + 1] - S[i], 1e-12);
v[i] = ((q[i + 1] - q[i]) / ds1 * ds0 + (q[i] - q[i - 1]) / ds0 * ds1) / (ds0 + ds1);
}
return v;
}
// 对内点几何速度限幅,抑制过冲(k∈[0.5,1.0])
static void clampNodeVels(std::vector<Eigen::VectorXd> &v,
const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S,
double k = 1.0) {
const size_t M = q.size();
if (M <= 2) return;
for (size_t i = 1; i + 1 < M; ++i) {
const double ds0 = std::max<double>(S[i] - S[i - 1], 1e-12);
const double ds1 = std::max<double>(S[i + 1] - S[i], 1e-12);
const double slope0 = (q[i] - q[i - 1]).norm() / ds0;
const double slope1 = (q[i + 1] - q[i]).norm() / ds1;
const double vmax = k * std::min(slope0, slope1);
double n = v[i].norm();
if (n > vmax) v[i] *= (vmax / n);
}
}
// 估计结点几何加速度 a(端点=0;中点二阶差分,按 s 尺度)
static std::vector<Eigen::VectorXd>
estimateAccelsSecondDiff(const std::vector<Eigen::VectorXd> &q,
const std::vector<toppra::value_type> &S) {
const size_t M = q.size();
const int DoF = static_cast<int>(q[0].size());
std::vector<Eigen::VectorXd> a(M, Eigen::VectorXd::Zero(DoF));
if (M <= 2) return a;
for (size_t i = 1; i + 1 < M; ++i) {
double h0 = std::max<double>(S[i] - S[i - 1], 1e-12); // 左间距
double h1 = std::max<double>(S[i + 1] - S[i], 1e-12); // 右间距
double denom = 0.5 * (h0 + h1); // 局部尺度
// 非均匀中心二阶差分(更精确):
// a ≈ 2 * [ (q_{i+1}-q_i)/h1 - (q_i - q_{i-1})/h0 ] / (h0 + h1)
a[i] = 2.0 * ((q[i + 1] - q[i]) / h1 - (q[i] - q[i - 1]) / h0) / (h0 + h1);
}
return a;
}
// τ→s 变元:把局部 Quintic(τ) 的系数 c_tau[0..5](τ^0..τ^5)
// 变成全局 s 的系数 alpha[0..5](s^0..s^5),其中 τ = (s - S_k) / ds
static inline void localQuinticToGlobalCoeffs(
const std::array<Eigen::VectorXd, 6> &c_tau, // c0..c5(DoF维向量)
double Sk, double ds,
std::array<Eigen::VectorXd, 6> &alpha // α0..α5(DoF维向量)
) {
static const double C[6][6] = {
// binomial(n,m)
{1, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0},
{1, 2, 1, 0, 0, 0},
{1, 3, 3, 1, 0, 0},
{1, 4, 6, 4, 1, 0},
{1, 5, 10, 10, 5, 1}
};
const double eps = 1e-12;
ds = std::max(ds, eps);
for (int m = 0; m <= 5; ++m) alpha[m].setZero(c_tau[0].size());
// α_m = Σ_{n=m..5} c_n * C(n,m) * (-S_k)^{n-m} / ds^{n}
for (int n = 0; n <= 5; ++n) {
double invdsn = std::pow(ds, -n);
for (int m = 0; m <= n; ++m) {
double factor = C[n][m] * std::pow(-Sk, n - m) * invdsn;
alpha[m].noalias() += factor * c_tau[n];
}
}
}
};
} // namespace cmvr

View File

@ -1,527 +0,0 @@
#include <toppra/algorithm/toppra.hpp>
#include <toppra/constraint/linear_joint_velocity.hpp>
#include <toppra/constraint/linear_joint_acceleration.hpp>
#include <toppra/solver/seidel.hpp>
#include <toppra/toppra.hpp>
#include "algorithms/motion_planner/base_motion/joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
namespace cmvr {
namespace {
class TimeScaledTrajectory final : public ITrajectory {
public:
TimeScaledTrajectory(TrajPtr source, const double scale)
: source_(std::move(source)), scale_(scale), source_interval_(source_->timeInterval())
{
}
toppra::Bound timeInterval() const override
{
toppra::Bound interval;
interval << source_interval_[0],
source_interval_[0] +
(source_interval_[1] - source_interval_[0]) * scale_;
return interval;
}
Eigen::VectorXd q(const double t) const override
{
return source_->q(sourceTime_(t));
}
Eigen::VectorXd qd(const double t) const override
{
return source_->qd(sourceTime_(t)) / scale_;
}
Eigen::VectorXd qdd(const double t) const override
{
return source_->qdd(sourceTime_(t)) / (scale_ * scale_);
}
private:
double sourceTime_(const double output_time) const
{
return std::clamp(
source_interval_[0] +
(output_time - source_interval_[0]) / scale_,
source_interval_[0],
source_interval_[1]);
}
TrajPtr source_;
double scale_{1.0};
toppra::Bound source_interval_;
};
bool enforceSampledLimits(const TrajPtr& source,
const std::vector<double>& velocity_limits,
const std::vector<double>& acceleration_limits,
const std::size_t waypoint_count,
TrajPtr& output)
{
if (!source || velocity_limits.empty() ||
velocity_limits.size() != acceleration_limits.size()) {
return false;
}
const auto interval = source->timeInterval();
const double duration = interval[1] - interval[0];
if (!std::isfinite(duration) || duration <= 0.0) {
return false;
}
const std::size_t time_samples = static_cast<std::size_t>(
std::ceil(duration / 0.001)) + 1;
const std::size_t path_samples = waypoint_count * 20;
const std::size_t sample_count = std::clamp<std::size_t>(
std::max({std::size_t{1000}, time_samples, path_samples}),
std::size_t{1000},
std::size_t{200000});
double required_scale = 1.0;
for (std::size_t sample = 0; sample < sample_count; ++sample) {
const double ratio = static_cast<double>(sample) /
static_cast<double>(sample_count - 1);
const double time = interval[0] + duration * ratio;
const Eigen::VectorXd velocity = source->qd(time);
const Eigen::VectorXd acceleration = source->qdd(time);
if (!velocity.allFinite() || !acceleration.allFinite() ||
velocity.size() != static_cast<Eigen::Index>(velocity_limits.size()) ||
acceleration.size() !=
static_cast<Eigen::Index>(acceleration_limits.size())) {
return false;
}
for (Eigen::Index joint = 0; joint < velocity.size(); ++joint) {
const std::size_t index = static_cast<std::size_t>(joint);
required_scale = std::max(
required_scale,
std::abs(velocity[joint]) / velocity_limits[index]);
required_scale = std::max(
required_scale,
std::sqrt(std::abs(acceleration[joint]) /
acceleration_limits[index]));
}
}
constexpr double kNumericalMargin = 1.001;
output = std::make_shared<TimeScaledTrajectory>(
source, required_scale * kNumericalMargin);
return true;
}
} // namespace
// ===== ConstAccelTraj =====
ConstAccelTraj::ConstAccelTraj(std::shared_ptr<toppra::parametrizer::ConstAccel> p)
: impl_(std::move(p)) {
}
toppra::Bound ConstAccelTraj::timeInterval() const { return impl_->pathInterval(); }
Eigen::VectorXd ConstAccelTraj::q(double t) const { return impl_->eval_single(t, 0); }
Eigen::VectorXd ConstAccelTraj::qd(double t) const { return impl_->eval_single(t, 1); }
Eigen::VectorXd ConstAccelTraj::qdd(double t) const { return impl_->eval_single(t, 2); }
// ===== SplineTraj =====
SplineTraj::SplineTraj(const std::shared_ptr<toppra::PiecewisePolyPath> &path,
const toppra::Vector &grid,
const toppra::Vector &vsq)
: impl_(path, grid, vsq) {
}
toppra::Bound SplineTraj::timeInterval() const { return impl_.pathInterval(); }
Eigen::VectorXd SplineTraj::q(double t) const { return impl_.eval_single(t, 0); }
Eigen::VectorXd SplineTraj::qd(double t) const { return impl_.eval_single(t, 1); }
Eigen::VectorXd SplineTraj::qdd(double t) const { return impl_.eval_single(t, 2); }
// ===== ToppraJointTrajectoryPlanner =====
ToppraJointTrajectoryPlanner::ToppraJointTrajectoryPlanner(PathType type) :JointTrajectoryPlanner(type) {
}
bool ToppraJointTrajectoryPlanner::ensureLimitsSized(std::size_t DoF) {
if (v_max_.size() != DoF) v_max_.assign(DoF, 1.5);
if (a_max_.size() != DoF) a_max_.assign(DoF, 3.0);
return true;
}
void ToppraJointTrajectoryPlanner::sanitizeVsq(toppra::Vector &v) {
for (int i = 0; i < v.size(); ++i) if (v[i] < 0 && v[i] > -1e-10) v[i] = 0;
if (v.size() > 0) {
v[0] = 0;
v[v.size() - 1] = 0;
}
}
// ===== 统一入口:两点/多点 =====
bool ToppraJointTrajectoryPlanner::plan(const std::vector<std::vector<double>>& waypoints,
TrajPtr& traj_out) {
traj_out.reset();
if (waypoints.size() < 2) return false;
const size_t DoF = waypoints.front().size();
if (DoF == 0) return false;
for (const auto& w : waypoints) {
if (w.size() != DoF) return false;
for (const double value : w) {
if (!std::isfinite(value)) return false;
}
}
if (!ensureLimitsSized(DoF)) return false;
for (size_t joint = 0; joint < DoF; ++joint) {
if (!std::isfinite(v_max_[joint]) || v_max_[joint] <= 0.0 ||
!std::isfinite(a_max_[joint]) || a_max_[joint] <= 0.0) {
return false;
}
}
std::vector<Eigen::VectorXd> q;
q.reserve(waypoints.size());
constexpr double kDuplicateDistance = 1e-10;
for (const auto& waypoint : waypoints) {
Eigen::VectorXd value = Eigen::Map<const Eigen::VectorXd>(
waypoint.data(), static_cast<Eigen::Index>(DoF));
if (q.empty() || (value - q.back()).norm() > kDuplicateDistance) {
q.push_back(std::move(value));
}
}
if (q.size() < 2) return false;
const size_t M = q.size();
const std::vector<toppra::value_type> S = M == 2
? std::vector<toppra::value_type>{0.0, 1.0}
: makeSChordLength(q);
// 几何路径
auto path = buildPathUnified(q, S);
if (!path) return false;
// 约束
Eigen::VectorXd vmax(DoF), amax(DoF);
for (size_t i=0;i<DoF;++i) { vmax[i]=v_max_[i]; amax[i]=a_max_[i]; }
auto vel = std::make_shared<toppra::constraint::LinearJointVelocity>(-vmax, vmax);
auto acc = std::make_shared<toppra::constraint::LinearJointAcceleration>(-amax, amax);
vel->discretizationType(toppra::DiscretizationType::Collocation);
acc->discretizationType(toppra::DiscretizationType::Interpolation);
toppra::LinearConstraintPtrs constraints{vel, acc};
// TOPPRA
toppra::algorithm::TOPPRA algo{constraints, path};
auto solve_once = [&](const int requested_intervals)->bool{
const int segment_count = static_cast<int>(M - 1);
const int subdivisions = std::max(
1, (requested_intervals + segment_count - 1) / segment_count);
toppra::Vector grid(segment_count * subdivisions + 1);
Eigen::Index index = 0;
for (int segment = 0; segment < segment_count; ++segment) {
const double start = S[static_cast<size_t>(segment)];
const double length = S[static_cast<size_t>(segment + 1)] - start;
for (int subdivision = 0; subdivision < subdivisions; ++subdivision) {
grid[index++] = start + length *
static_cast<double>(subdivision) /
static_cast<double>(subdivisions);
}
}
grid[index] = S.back();
algo.setGridpoints(grid);
algo.solver(std::make_shared<toppra::solver::Seidel>());
return algo.computePathParametrization(0.0, 0.0) == toppra::ReturnCode::OK;
};
if (!solve_once(N_grid_)) {
if (!solve_once(N_grid_high_)) return false;
}
const auto data = algo.getParameterizationData();
toppra::Vector grid = data.gridpoints;
toppra::Vector vsq = data.parametrization;
TrajPtr candidate;
auto ca = std::make_shared<toppra::parametrizer::ConstAccel>(path, grid, vsq);
if (ca->validate()) {
candidate = std::make_shared<ConstAccelTraj>(std::move(ca));
} else {
sanitizeVsq(vsq);
try {
candidate = std::make_shared<SplineTraj>(path, grid, vsq);
(void) candidate->timeInterval();
} catch (...) {
return false;
}
}
return enforceSampledLimits(candidate, v_max_, a_max_, M, traj_out);
}
bool ToppraJointTrajectoryPlanner::plan(const std::vector<double>& start_joints,
const std::vector<double>& goal_joints,
TrajPtr& traj_out) {
if (start_joints.empty() || start_joints.size()!=goal_joints.size()) return false;
std::vector<std::vector<double>> wpts{start_joints, goal_joints};
return plan(wpts, traj_out);
}
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildPathUnified(const std::vector<Eigen::VectorXd>& q,
const std::vector<toppra::value_type>& S) {
const size_t M = q.size();
if (M == 2) return buildTwoPointPath(q[0], q[1]);
switch (path_type_) {
case PathType::Linear: return buildLinearMulti(q, S);
case PathType::CubicHermite: return buildCubicHermiteMulti(q, S);
case PathType::Natural: return buildNaturalMulti(q, S);
case PathType::Quintic:
default: return buildQuinticC2Multi(q, S);
}
}
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildTwoPointPath(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
switch (path_type_) {
case PathType::Linear: return buildLinearTwo(q0, q1);
case PathType::CubicHermite: return buildCubicHermiteTwo(q0, q1);
case PathType::Natural: return buildNaturalTwo(q0, q1);
case PathType::Quintic:
default: return buildQuinticRestToRestTwo(q0, q1);
}
}
// 二点:Linear ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildLinearTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
const size_t DoF = static_cast<size_t>(q0.size());
toppra::Matrix seg(2, DoF);
seg.row(0) = (q1 - q0).transpose();
seg.row(1) = q0.transpose();
return std::make_shared<toppra::PiecewisePolyPath>(
toppra::Matrices{seg}, std::vector<double>{0.0, 1.0});
}
// 二点:Cubic Hermite(端点速度 0) ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildCubicHermiteTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
toppra::Vectors pos{q0, q1};
toppra::Vectors vel{Eigen::VectorXd::Zero(q0.size()),
Eigen::VectorXd::Zero(q1.size())};
std::vector<toppra::value_type> s{0.0, 1.0};
auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, s);
return std::make_shared<toppra::PiecewisePolyPath>(herm);
}
// 二点:Quintic rest-to-rest ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildQuinticRestToRestTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
const size_t DoF = static_cast<size_t>(q0.size());
const Eigen::VectorXd dq = q1 - q0;
toppra::Matrix seg(6, DoF); // x^5..x^0
seg.row(0) = ( 6.0 * dq).transpose();
seg.row(1) = (-15.0 * dq).transpose();
seg.row(2) = (10.0 * dq).transpose();
seg.row(3).setZero(); seg.row(4).setZero();
seg.row(5) = q0.transpose();
return std::make_shared<toppra::PiecewisePolyPath>(
toppra::Matrices{seg}, std::vector<double>{0.0, 1.0});
}
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildNaturalTwo(const Eigen::VectorXd& q0, const Eigen::VectorXd& q1) {
using PWP = toppra::PiecewisePolyPath;
// positions(两点)
toppra::Vectors pos{ q0, q1 };
// 自变量S:两点用等距最简单
toppra::Vector S(2);
S[0] = 0.0; S[1] = 1.0;
toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"),
toppra::BoundaryCond("clamped") };
auto path = PWP::CubicSpline(pos, S, bcA);
return std::make_shared<PWP>(path);
// 手动指定二阶导为 0
// const int DoF = static_cast<int>(q0.size());
// toppra::BoundaryCondFull bcB = {
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)),
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF))
// };
// auto path2 = PWP::CubicSpline(pos, S, bcB);
// return std::make_shared<PWP>(path2);
}
// —— 多点:Linear ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildLinearMulti(const std::vector<Eigen::VectorXd>& q,
const std::vector<toppra::value_type>& S) {
const size_t M = q.size(), DoF = q[0].size();
toppra::Matrices segs; segs.reserve(M-1);
for (size_t k=0;k+1<M;++k) {
double ds = std::max<double>(S[k+1]-S[k], 1e-12);
toppra::Matrix seg(2, DoF);
Eigen::RowVectorXd A1 = ((q[k+1]-q[k])/ds).transpose();
Eigen::RowVectorXd A0 = q[k].transpose();
seg.row(0)=A1; seg.row(1)=A0;
segs.emplace_back(std::move(seg));
}
return std::make_shared<toppra::PiecewisePolyPath>(segs, std::vector<double>(S.begin(), S.end()));
}
// —— 多点:Cubic Hermite ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildCubicHermiteMulti(const std::vector<Eigen::VectorXd>& q,
const std::vector<toppra::value_type>& S) {
auto v = estimateVelsCatmull(q, S);
clampNodeVels(v, q, S, /*k=*/1.0);
toppra::Vectors pos(q.begin(), q.end());
toppra::Vectors vel(v.begin(), v.end());
auto herm = toppra::PiecewisePolyPath::CubicHermiteSpline(pos, vel, S);
return std::make_shared<toppra::PiecewisePolyPath>(herm);
}
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildNaturalMulti(const std::vector<Eigen::VectorXd>& q,
const std::vector<toppra::value_type>& S) {
using PWP = toppra::PiecewisePolyPath;
const size_t M = q.size();
if (M < 2 || M != S.size()) return nullptr;
// positions
toppra::Vectors pos(q.begin(), q.end());
// times(全局自变量,需严格递增)
toppra::Vector times(static_cast<int>(M));
for (size_t i = 0; i < M; ++i) times[static_cast<int>(i)] = S[i];
//Natural
toppra::BoundaryCondFull bcA = { toppra::BoundaryCond("clamped"),
toppra::BoundaryCond("clamped") };
auto path = PWP::CubicSpline(pos, times, bcA);
return std::make_shared<PWP>(path);
// 手动指定二阶导为 0 ——
// const int DoF = static_cast<int>(q[0].size());
// toppra::BoundaryCondFull bcB = {
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF)),
// toppra::BoundaryCond(2, Eigen::VectorXd::Zero(DoF))
// };
// auto path2 = PWP::CubicSpline(pos, times, bcB);
// return std::make_shared<PWP>(path2);
}
// —— 多点:Quintic C² ——
std::shared_ptr<toppra::PiecewisePolyPath>
ToppraJointTrajectoryPlanner::buildQuinticC2Multi(const std::vector<Eigen::VectorXd>& q,
const std::vector<toppra::value_type>& S) {
const size_t M = q.size(), DoF = q[0].size();
auto v = estimateVelsCatmull(q, S);
clampNodeVels(v, q, S, /*k=*/1.0);
auto a = estimateAccelsSecondDiff(q, S);
toppra::Matrices segs; segs.reserve(M-1);
for (size_t k=0;k+1<M;++k) {
const double ds = std::max<double>(S[k+1]-S[k], 1e-12);
const Eigen::VectorXd& q0=q[k]; const Eigen::VectorXd& q1=q[k+1];
const Eigen::VectorXd& v0=v[k]; const Eigen::VectorXd& v1=v[k+1];
const Eigen::VectorXd& a0=a[k]; const Eigen::VectorXd& a1=a[k+1];
const Eigen::VectorXd dq = q1-q0;
Eigen::VectorXd A0 = q0;
Eigen::VectorXd A1 = v0 * ds;
Eigen::VectorXd A2 = a0 * (ds*ds) / 2.0;
Eigen::VectorXd C3 = ( 10.0*dq - (6.0*A1 + 1.5*(a0*ds*ds)) - (4.0*(v1*ds) - 0.5*(a1*ds*ds)) );
Eigen::VectorXd C4 = (-15.0*dq + (8.0*A1 + 1.5*(a0*ds*ds)) + (7.0*(v1*ds) - 1.0*(a1*ds*ds)) );
Eigen::VectorXd C5 = ( 6.0*dq - (3.0*A1 + 0.5*(a0*ds*ds)) - (3.0*(v1*ds) - 0.5*(a1*ds*ds)) );
toppra::Matrix seg(6, DoF);
seg.row(0)=(C5 / std::pow(ds, 5)).transpose();
seg.row(1)=(C4 / std::pow(ds, 4)).transpose();
seg.row(2)=(C3 / std::pow(ds, 3)).transpose();
seg.row(3)=(a0 / 2.0).transpose();
seg.row(4)=v0.transpose();
seg.row(5)=A0.transpose();
segs.emplace_back(std::move(seg));
}
return std::make_shared<toppra::PiecewisePolyPath>(segs, std::vector<double>(S.begin(), S.end()));
}
std::vector<TrajSample> ToppraJointTrajectoryPlanner::sampleTrajectory(const TrajPtr &traj, double dt) {
std::vector<TrajSample> out;
if (!traj) return out;
auto I = traj->timeInterval();
const double t0 = I[0];
const double t1 = I[1];
if (!(t1 > t0)) return out;
// 2) 生成时间序列(含端点,考虑浮点误差)
constexpr double EPS = 1e-12;
std::vector<double> ts;
ts.reserve(static_cast<size_t>(std::max(2.0, std::ceil((t1 - t0) / dt) + 1.0)));
// 起点
ts.push_back(t0);
// 中间等间隔点
for (double t = t0 + dt; t <= t1 - EPS; t += dt) {
// 防守式:避免因累积误差越过 t1
ts.push_back((t > t1) ? t1 : t);
}
// 终点(若未加入)
if (ts.empty() || std::fabs(ts.back() - t1) > EPS) {
ts.push_back(t1);
} else {
// 若最后一个点因误差“很接近 t1”,直接覆盖为 t1
ts.back() = t1;
}
// 3) 采样
out.reserve(ts.size());
for (double t: ts) {
TrajSample s;
s.t = t;
s.q = traj->q(t);
s.qd = traj->qd(t);
s.qdd = traj->qdd(t);
out.emplace_back(std::move(s));
}
return out;
}
bool ToppraJointTrajectoryPlanner::writeTrajectoryCsv(const std::string &filename, const std::vector<TrajSample> &samples) {
if (samples.empty()) return false;
const int dof = static_cast<int>(samples.front().q.size());
std::ofstream ofs(filename);
if (!ofs) return false;
ofs.setf(std::ios::fixed);
ofs << std::setprecision(10);
// 表头
ofs << "t";
for (int j=1;j<=dof;++j) ofs << ",q" << j;
for (int j=1;j<=dof;++j) ofs << ",qd" << j;
for (int j=1;j<=dof;++j) ofs << ",qdd" << j;
ofs << "\n";
// 内容
for (const auto& s : samples) {
ofs << s.t;
for (int j=0;j<dof;++j) ofs << "," << s.q[j];
for (int j=0;j<dof;++j) ofs << "," << s.qd[j];
for (int j=0;j<dof;++j) ofs << "," << s.qdd[j];
ofs << "\n";
}
return true;
}
} // namespace cmvr

View File

@ -1,228 +0,0 @@
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <limits>
#include <vector>
#include <gtest/gtest.h>
#include "joint_trajectory/toppra/include/toppra_joint_trajectory_planner.h"
namespace cmvr {
namespace {
constexpr std::size_t kDof = 7;
constexpr double kVelocityLimit = 0.15;
constexpr double kAccelerationLimit = 0.3;
constexpr double kSamplePeriodS = 0.002;
std::vector<std::vector<double>> makeSmoothWaypoints(const std::size_t count)
{
constexpr double kPi = 3.14159265358979323846;
std::vector<std::vector<double>> waypoints;
waypoints.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
const double s = static_cast<double>(i) /
static_cast<double>(count - 1);
std::vector<double> q(kDof, 0.0);
q[0] = 0.40 * s + 0.03 * std::sin(2.0 * kPi * s);
q[1] = -0.25 * s + 0.04 * std::sin(kPi * s);
q[2] = 0.20 * s * s;
q[3] = 0.30 * std::sin(0.5 * kPi * s);
q[4] = -0.12 * s + 0.02 * std::sin(3.0 * kPi * s);
q[5] = 0.15 * s;
q[6] = -0.08 * std::sin(kPi * s);
waypoints.push_back(std::move(q));
}
return waypoints;
}
double maxAbs(const Eigen::VectorXd& value)
{
double result = 0.0;
for (Eigen::Index i = 0; i < value.size(); ++i) {
result = std::max(result, std::abs(value[i]));
}
return result;
}
double positionError(const Eigen::VectorXd& actual,
const std::vector<double>& expected)
{
if (actual.size() != static_cast<Eigen::Index>(expected.size())) {
return std::numeric_limits<double>::infinity();
}
double squared_error = 0.0;
for (Eigen::Index i = 0; i < actual.size(); ++i) {
const double error = actual[i] - expected[static_cast<std::size_t>(i)];
squared_error += error * error;
}
return std::sqrt(squared_error);
}
struct PlanMetrics {
bool success{false};
double planning_ms{0.0};
double duration_s{0.0};
double max_velocity{0.0};
double max_acceleration{0.0};
double max_waypoint_error{0.0};
double start_error{0.0};
double end_error{0.0};
std::size_t sample_count{0};
};
PlanMetrics planAndMeasure(const std::vector<std::vector<double>>& waypoints,
const PathType path_type = PathType::Linear)
{
PlanMetrics metrics;
ToppraJointTrajectoryPlanner planner(path_type);
planner.setSymmetricLimits(
std::vector<double>(kDof, kVelocityLimit),
std::vector<double>(kDof, kAccelerationLimit));
planner.setGridSizes(150, 300);
TrajPtr trajectory;
const auto start = std::chrono::steady_clock::now();
metrics.success = planner.plan(waypoints, trajectory);
metrics.planning_ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - start).count();
if (!metrics.success || !trajectory) {
return metrics;
}
const auto interval = trajectory->timeInterval();
metrics.duration_s = interval[1] - interval[0];
const auto samples = planner.sampleTrajectory(trajectory, kSamplePeriodS);
metrics.sample_count = samples.size();
if (samples.empty()) {
metrics.success = false;
return metrics;
}
metrics.start_error = positionError(samples.front().q, waypoints.front());
metrics.end_error = positionError(samples.back().q, waypoints.back());
for (const auto& sample : samples) {
if (!std::isfinite(sample.t) || !sample.q.allFinite() ||
!sample.qd.allFinite() || !sample.qdd.allFinite()) {
metrics.success = false;
return metrics;
}
metrics.max_velocity = std::max(metrics.max_velocity, maxAbs(sample.qd));
metrics.max_acceleration = std::max(
metrics.max_acceleration, maxAbs(sample.qdd));
}
std::size_t sample_index = 0;
for (const auto& waypoint : waypoints) {
while (sample_index + 1 < samples.size() &&
positionError(samples[sample_index + 1].q, waypoint) <=
positionError(samples[sample_index].q, waypoint)) {
++sample_index;
}
metrics.max_waypoint_error = std::max(
metrics.max_waypoint_error,
positionError(samples[sample_index].q, waypoint));
}
return metrics;
}
const char* pathTypeName(const PathType path_type)
{
switch (path_type) {
case PathType::Linear: return "Linear";
case PathType::CubicHermite: return "CubicHermite";
case PathType::Quintic: return "Quintic";
case PathType::Natural: return "Natural";
}
return "Unknown";
}
void printMetrics(const std::size_t waypoint_count, const PlanMetrics& metrics)
{
std::cout << "[ToppraMultiWaypointTest] waypoints=" << waypoint_count
<< ", success=" << metrics.success
<< ", planning_ms=" << metrics.planning_ms
<< ", duration_s=" << metrics.duration_s
<< ", samples=" << metrics.sample_count
<< ", max_qd=" << metrics.max_velocity
<< ", max_qdd=" << metrics.max_acceleration
<< ", max_waypoint_error=" << metrics.max_waypoint_error
<< ", start_error=" << metrics.start_error
<< ", end_error=" << metrics.end_error
<< std::endl;
}
TEST(ToppraMultiWaypointTest, SmoothSevenDofPathScalesToThousandsOfWaypoints)
{
double reference_duration_s = 0.0;
for (const std::size_t count : {10U, 100U, 300U, 1000U, 3000U}) {
const auto metrics = planAndMeasure(makeSmoothWaypoints(count));
printMetrics(count, metrics);
ASSERT_TRUE(metrics.success) << "waypoint_count=" << count;
EXPECT_GT(metrics.duration_s, 0.0) << "waypoint_count=" << count;
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6)
<< "waypoint_count=" << count;
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5)
<< "waypoint_count=" << count;
EXPECT_LT(metrics.max_waypoint_error, 0.002)
<< "waypoint_count=" << count;
if (reference_duration_s == 0.0) {
reference_duration_s = metrics.duration_s;
} else {
EXPECT_NEAR(metrics.duration_s, reference_duration_s,
reference_duration_s * 0.10)
<< "waypoint_count=" << count;
}
}
}
TEST(ToppraMultiWaypointTest, RepeatedWaypointsRemainPlannable)
{
const auto smooth = makeSmoothWaypoints(300);
std::vector<std::vector<double>> repeated;
repeated.reserve(smooth.size() * 2);
for (const auto& waypoint : smooth) {
repeated.push_back(waypoint);
repeated.push_back(waypoint);
}
const auto metrics = planAndMeasure(repeated);
printMetrics(repeated.size(), metrics);
EXPECT_TRUE(metrics.success);
if (metrics.success) {
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6);
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5);
EXPECT_LT(metrics.max_waypoint_error, 0.002);
}
}
TEST(ToppraMultiWaypointTest, CompareInterpolationModesAtThreeHundredWaypoints)
{
const auto waypoints = makeSmoothWaypoints(300);
for (const auto path_type : {
PathType::CubicHermite,
PathType::Quintic,
PathType::Natural}) {
const auto metrics = planAndMeasure(waypoints, path_type);
std::cout << "[ToppraMultiWaypointTest] path_type="
<< pathTypeName(path_type) << std::endl;
printMetrics(waypoints.size(), metrics);
EXPECT_TRUE(metrics.success) << pathTypeName(path_type);
if (metrics.success) {
EXPECT_LE(metrics.max_velocity, kVelocityLimit + 1e-6)
<< pathTypeName(path_type);
EXPECT_LE(metrics.max_acceleration, kAccelerationLimit + 1e-5)
<< pathTypeName(path_type);
EXPECT_LT(metrics.max_waypoint_error, 0.002)
<< pathTypeName(path_type);
EXPECT_LT(metrics.start_error, 1e-9) << pathTypeName(path_type);
EXPECT_LT(metrics.end_error, 1e-9) << pathTypeName(path_type);
}
}
}
} // namespace
} // namespace cmvr

View File

@ -1,167 +0,0 @@
//
// Created by lgv on 2026/3/2.
//
/**
* @file s_curve.h
* @brief 严格点到点位置 S 曲线轨迹生成器
*
* 实现标准 7 段式位置 S 曲线速度剖面:
* 1. 加加速度上升段(加速度逐渐增大)
* 2. 匀加速段
* 3. 加加速度下降段(加速度逐渐降到 0)
* 4. 匀速巡航段
* 5. 加加速度下降段(减速度逐渐增大)
* 6. 匀减速段
* 7. 加加速度上升段(减速度逐渐降到 0)
*
* 本类只负责严格点到点 profile 规划与采样,不负责实时目标跟踪。
*/
#pragma once
#include <algorithm>
#include <cmath>
#include <vector>
namespace cmvr
{
/**
* @brief 单次点到点运动的 S 曲线剖面参数
*/
struct SCurveProfile
{
// 7 个阶段的持续时间
double t1; // 加加速度上升时间(加速阶段)
double t2; // 匀加速时间
double t3; // 加加速度下降时间(加速阶段结束)
double t4; // 匀速时间(巡航)
double t5; // 加加速度下降时间(减速阶段)
double t6; // 匀减速时间
double t7; // 加加速度上升时间(减速阶段结束)
double total_time;
// 运动约束
double j_max; // 最大加加速度 (rad/s³)
double a_max; // 最大加速度 (rad/s²)
double v_max; // 最大速度 (rad/s)
// 运动参数
double distance; // 运动总距离
double direction; // +1 或 -1
double v_cruise; // 实际达到的巡航速度
double a_limit; // 实际达到的加速度上限
// 初始条件
double p0; // 初始位置
double v0; // 初始速度
double a0; // 初始加速度
double vf; // 终止速度
SCurveProfile()
: t1(0), t2(0), t3(0), t4(0), t5(0), t6(0), t7(0)
, total_time(0)
, j_max(50.0), a_max(10.0), v_max(3.0)
, distance(0), direction(1.0), v_cruise(0), a_limit(0)
, p0(0), v0(0), a0(0), vf(0)
{}
};
/**
* @brief 严格点到点位置 S 曲线规划器
*/
class SCurve
{
public:
/**
* @brief 构造函数(带运动约束)
* @param max_velocity 最大速度 (rad/s)
* @param max_acceleration 最大加速度 (rad/s²)
* @param max_jerk 最大加加速度 (rad/s³)
*/
SCurve(double max_velocity = 3.0,
double max_acceleration = 10.0,
double max_jerk = 50.0);
/**
* @brief 设置运动约束
*/
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
/**
* @brief 获取当前运动约束
*/
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
/**
* @brief 计算点到点运动的完整 S 曲线剖面
* @param start_position 起始位置
* @param end_position 终止位置
* @param start_velocity 起始速度(默认 0)
* @param end_velocity 终止速度(默认 0)
* @return 计算得到的剖面参数
*/
SCurveProfile calculateProfile(double start_position, double end_position,
double start_velocity = 0.0, double end_velocity = 0.0);
/**
* @brief 给定剖面下,获取时刻 t 的位置
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的位置
*/
double getPositionAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的速度
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的速度
*/
double getVelocityAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加速度
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的加速度
*/
double getAccelerationAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加加速度
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的加加速度
*/
double getJerkAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 按固定时间间隔生成轨迹点
* @param profile S 曲线剖面
* @param dt 轨迹点时间间隔
* @param positions 输出:每个时间点的位置
* @param velocities 输出:每个时间点的速度
* @param accelerations 输出:每个时间点的加速度
*/
void generateTrajectory(const SCurveProfile& profile, double dt,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& accelerations) const;
private:
double max_velocity_;
double max_acceleration_;
double max_jerk_;
static constexpr double EPSILON = 1e-9;
static constexpr double VELOCITY_THRESHOLD = 1e-6;
double computeSegmentJerk(const SCurveProfile& profile, double t) const;
void calculateShortProfile(SCurveProfile& profile) const;
void calculateLongProfile(SCurveProfile& profile) const;
};
} // namespace cmvr

View File

@ -1,100 +0,0 @@
//
// Created by lgv on 2026/3/10.
//
#pragma once
#include "s_curve_velocity_planner.h"
#include <algorithm>
#include <cmath>
namespace cmvr
{
struct SCurvePositionPlannerState
{
double position;
double velocity;
double acceleration;
double jerk;
double target_position;
bool is_moving;
SCurvePositionPlannerState()
: position(0.0)
, velocity(0.0)
, acceleration(0.0)
, jerk(0.0)
, target_position(0.0)
, is_moving(false)
{}
};
/**
* @brief 单轴位置跟踪规划器
*
* 结构:
* - 外环:position_error -> desired_velocity
* - 内环:SCurveVelocityPlanner1D 负责 jerk-limited 速度规划
*
* 这个类用于高频变化目标的位置跟踪,不承担严格点到点 profile 语义。
*/
class SCurvePositionPlanner1D
{
public:
SCurvePositionPlanner1D(double max_velocity = 3.0,
double max_acceleration = 10.0,
double max_jerk = 50.0);
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
void setPositionGain(double position_gain);
double getPositionGain() const { return position_gain_; }
void initialize(double position, double velocity = 0.0, double acceleration = 0.0);
void reset();
void setTarget(double target_position);
double update(double dt);
const SCurvePositionPlannerState& getState() const { return state_; }
double getPosition() const { return state_.position; }
double getVelocity() const { return state_.velocity; }
double getAcceleration() const { return state_.acceleration; }
double getJerk() const { return state_.jerk; }
double getTargetPosition() const { return state_.target_position; }
bool isMoving() const { return state_.is_moving; }
private:
double max_velocity_;
double max_acceleration_;
double max_jerk_;
SCurvePositionPlannerState state_;
SCurveVelocityPlanner1D velocity_planner_;
double position_gain_;
static constexpr double EPSILON = 1e-9;
static constexpr double VELOCITY_THRESHOLD = 1e-6;
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
static constexpr double POSITION_THRESHOLD = 1e-7;
double computeDesiredVelocity(double position_error) const;
double computePlannerStoppingDistance(double velocity, double acceleration) const;
static double clamp(double value, double min_val, double max_val)
{
return std::max(min_val, std::min(max_val, value));
}
static double sign(double value)
{
if (value > EPSILON) return 1.0;
if (value < -EPSILON) return -1.0;
return 0.0;
}
};
} // namespace cmvr

View File

@ -1,240 +0,0 @@
//
// Created by lgv on 2026/3/9.
//
#pragma once
#include <algorithm>
#include <cmath>
#include <vector>
namespace cmvr
{
/**
* @brief 单次速度切换的 S 曲线剖面参数
*
* 本类表示从任意 (v0, a0) 连续规划到 (vf, 0) 的 3 段 jerk-limited profile:
*
* seg1: jerk = j1, duration = t1
* seg2: jerk = j2, duration = t2 (当前实现 j2 = 0)
* seg3: jerk = j3, duration = t3
*
* 其中 j1/j3 为 ±j_max,j2 为 0。
*/
struct SCurveVelocityProfile
{
double t1;
double t2;
double t3;
double total_time;
double j1;
double j2;
double j3;
double v0;
double a0;
double vf;
bool valid;
SCurveVelocityProfile()
: t1(0.0), t2(0.0), t3(0.0)
, total_time(0.0)
, j1(0.0), j2(0.0), j3(0.0)
, v0(0.0), a0(0.0), vf(0.0)
, valid(false)
{}
};
/**
* @brief S 曲线速度规划器状态
*/
struct SCurveVelocityPlannerState
{
double velocity;
double acceleration;
double jerk;
double target_velocity;
double elapsed_time;
bool has_active_profile;
bool is_moving;
SCurveVelocityPlannerState()
: velocity(0.0)
, acceleration(0.0)
, jerk(0.0)
, target_velocity(0.0)
, elapsed_time(0.0)
, has_active_profile(false)
, is_moving(false)
{}
};
/**
* @brief 单轴速度型 S 曲线规划器
*
* 语义:
* - setTargetVelocity(v): 设置新目标并重规划
* - update(dt): 只采样当前 active profile
* - overwriteState(v,a): 仅覆盖当前状态并清掉旧 profile
* - synchronizeAndReplan(v,a): 用测量状态同步,并按当前目标重规划
*
* 数学目标:
* - 从任意 (v0, a0) 连续规划到 (vf, 0)
* - 满足 |v| <= v_max, |a| <= a_max, |j| <= j_max
*/
class SCurveVelocityPlanner1D
{
public:
SCurveVelocityPlanner1D(double max_velocity = 1.0,
double max_acceleration = 1.0,
double max_jerk = 5.0);
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
/**
* @brief 设置目标变化阈值
*
* 目标变化量小于该阈值时,不触发重规划。
*/
void setTargetReplanThreshold(double threshold);
/**
* @brief 设置同步反馈时的重规划阈值
*
* 测量速度与当前 profile 采样状态的偏差小于该阈值时,
* synchronizeAndReplan() 只对齐当前状态,不打断现有 profile。
*/
void setSynchronizeReplanThreshold(double threshold);
void initialize(double velocity = 0.0, double acceleration = 0.0);
void reset();
/**
* @brief 仅覆盖当前状态,并清掉旧 profile
*
* 注意:
* - 这个接口不会自动重规划
* - 用于初始化、调试、或显式中断旧轨迹
*/
void overwriteState(double velocity,
double acceleration = 0.0,
bool keep_target_velocity = true);
/**
* @brief 用测量状态同步,并按当前目标重新规划
*
* 这是闭环场景真正该用的接口。
*/
void synchronizeAndReplan(double velocity,
double acceleration = 0.0);
/**
* @brief 设置目标速度,并立即重规划
*/
void setTargetVelocity(double target_velocity);
/**
* @brief 平滑停下
*/
void stop() { setTargetVelocity(0.0); }
/**
* @brief 更新一步(只采样)
* @param dt 时间步长
* @return 当前采样后的速度
*/
double update(double dt);
/**
* @brief 计算单次速度切换剖面
*/
SCurveVelocityProfile calculateProfile(double start_velocity,
double end_velocity,
double start_acceleration = 0.0) const;
/**
* @brief 给定剖面下,获取时刻 t 的速度
*/
double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加速度
*/
double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的 jerk
*/
double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 按固定时间间隔生成轨迹点
*/
void generateTrajectory(const SCurveVelocityProfile& profile, double dt,
std::vector<double>& velocities,
std::vector<double>& accelerations,
std::vector<double>& jerks) const;
const SCurveVelocityPlannerState& getState() const { return state_; }
const SCurveVelocityProfile& getActiveProfile() const { return active_profile_; }
double getVelocity() const { return state_.velocity; }
double getAcceleration() const { return state_.acceleration; }
double getJerk() const { return state_.jerk; }
double getTargetVelocity() const { return state_.target_velocity; }
bool hasActiveProfile() const { return state_.has_active_profile; }
bool isMoving() const { return state_.is_moving; }
private:
double max_velocity_;
double max_acceleration_;
double max_jerk_;
double target_replan_threshold_;
double synchronize_replan_threshold_;
SCurveVelocityPlannerState state_;
SCurveVelocityProfile active_profile_;
static constexpr double EPSILON = 1e-9;
static constexpr double VELOCITY_THRESHOLD = 1e-6;
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
static constexpr double DEFAULT_TARGET_REPLAN_THRESHOLD = 1e-9;
static constexpr double DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD = 5e-2;
private:
void updateIsMovingFlag();
/**
* @brief 判断 profile 是否满足速度上限
*/
bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const;
/**
* @brief 计算完整剖面终点状态
*/
void integrateWholeProfile(const SCurveVelocityProfile& profile,
double& v_end,
double& a_end) const;
static double clamp(double value, double min_val, double max_val)
{
return std::max(min_val, std::min(max_val, value));
}
static double sign(double value)
{
if (value > EPSILON) return 1.0;
if (value < -EPSILON) return -1.0;
return 0.0;
}
};
} // namespace cmvr

View File

@ -1,542 +0,0 @@
//
// Created by lgv on 2026/3/2.
//
/**
* @file s_curve_generator.cpp
* @brief S 曲线轨迹生成器实现
*/
#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve.h"
#include <cmath>
#include <algorithm>
#include <stdexcept>
namespace cmvr
{
SCurve::SCurve(double max_velocity, double max_acceleration, double max_jerk)
: max_velocity_(std::abs(max_velocity))
, max_acceleration_(std::abs(max_acceleration))
, max_jerk_(std::abs(max_jerk))
{}
void SCurve::setConstraints(double max_velocity, double max_acceleration, double max_jerk)
{
max_velocity_ = std::abs(max_velocity);
max_acceleration_ = std::abs(max_acceleration);
max_jerk_ = std::abs(max_jerk);
}
void SCurve::getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const
{
max_velocity = max_velocity_;
max_acceleration = max_acceleration_;
max_jerk = max_jerk_;
}
SCurveProfile SCurve::calculateProfile(double start_position, double end_position,
double start_velocity, double end_velocity)
{
SCurveProfile profile;
profile.j_max = max_jerk_;
profile.a_max = max_acceleration_;
profile.v_max = max_velocity_;
profile.p0 = start_position;
profile.v0 = start_velocity;
profile.a0 = 0.0; // Assume starting from zero acceleration
profile.vf = end_velocity;
double displacement = end_position - start_position;
profile.distance = std::abs(displacement);
profile.direction = (displacement >= 0) ? 1.0 : -1.0;
if (profile.distance < EPSILON) {
// 无需运动
profile.total_time = 0.0;
return profile;
}
const double start_speed = profile.direction * start_velocity;
const double end_speed = profile.direction * end_velocity;
if (start_speed < -VELOCITY_THRESHOLD || end_speed < -VELOCITY_THRESHOLD) {
profile.total_time = 0.0;
return profile;
}
if (std::abs(start_speed) > VELOCITY_THRESHOLD ||
std::abs(end_speed) > VELOCITY_THRESHOLD) {
auto calc_transition = [&](double v_from, double v_to,
double& t_j, double& t_a,
double& duration, double& distance) {
t_j = 0.0;
t_a = 0.0;
duration = 0.0;
distance = 0.0;
const double dv = std::abs(v_to - v_from);
if (dv <= 1e-12 || profile.a_max <= 1e-12 || profile.j_max <= 1e-12) {
return;
}
const double dv_switch = profile.a_max * profile.a_max / profile.j_max;
if (dv < dv_switch) {
t_j = std::sqrt(dv / profile.j_max);
t_a = 0.0;
} else {
t_j = profile.a_max / profile.j_max;
t_a = dv / profile.a_max - t_j;
}
duration = 2.0 * t_j + t_a;
distance = 0.5 * (v_from + v_to) * duration;
};
const double v_cap = std::max({profile.v_max, start_speed, end_speed});
const double v_peak_min = std::max(start_speed, end_speed);
double acc_tj = 0.0, acc_ta = 0.0, acc_duration = 0.0, acc_distance = 0.0;
double dec_tj = 0.0, dec_ta = 0.0, dec_duration = 0.0, dec_distance = 0.0;
calc_transition(start_speed, v_peak_min,
acc_tj, acc_ta, acc_duration, acc_distance);
calc_transition(v_peak_min, end_speed,
dec_tj, dec_ta, dec_duration, dec_distance);
const double d_min = acc_distance + dec_distance;
if (profile.distance + EPSILON < d_min) {
profile.total_time = 0.0;
return profile;
}
calc_transition(start_speed, v_cap,
acc_tj, acc_ta, acc_duration, acc_distance);
calc_transition(v_cap, end_speed,
dec_tj, dec_ta, dec_duration, dec_distance);
const double d_cap = acc_distance + dec_distance;
double v_peak = v_cap;
double t4 = 0.0;
if (profile.distance > d_cap + EPSILON) {
t4 = (profile.distance - d_cap) / std::max(v_peak, EPSILON);
} else {
double lo = v_peak_min;
double hi = v_cap;
for (int iter = 0; iter < 80; ++iter) {
const double mid = 0.5 * (lo + hi);
double mid_acc_tj = 0.0, mid_acc_ta = 0.0, mid_acc_duration = 0.0, mid_acc_distance = 0.0;
double mid_dec_tj = 0.0, mid_dec_ta = 0.0, mid_dec_duration = 0.0, mid_dec_distance = 0.0;
calc_transition(start_speed, mid,
mid_acc_tj, mid_acc_ta, mid_acc_duration, mid_acc_distance);
calc_transition(mid, end_speed,
mid_dec_tj, mid_dec_ta, mid_dec_duration, mid_dec_distance);
const double d_mid = mid_acc_distance + mid_dec_distance;
if (d_mid < profile.distance) {
lo = mid;
} else {
hi = mid;
}
}
v_peak = hi;
calc_transition(start_speed, v_peak,
acc_tj, acc_ta, acc_duration, acc_distance);
calc_transition(v_peak, end_speed,
dec_tj, dec_ta, dec_duration, dec_distance);
}
profile.t1 = acc_tj;
profile.t2 = acc_ta;
profile.t3 = acc_tj;
profile.t4 = t4;
profile.t5 = dec_tj;
profile.t6 = dec_ta;
profile.t7 = dec_tj;
profile.v_cruise = v_peak;
profile.a_limit = std::max(profile.j_max * profile.t1, profile.j_max * profile.t5);
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
profile.t5 + profile.t6 + profile.t7;
return profile;
}
const double j = profile.j_max;
const double a = profile.a_max;
const double v = profile.v_max;
const double t_j_a = a / j;
if (v < a * t_j_a) {
const double t_j_v = std::sqrt(v / j);
const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v;
if (profile.distance > s_min + EPSILON) {
calculateLongProfile(profile);
} else {
calculateShortProfile(profile);
}
} else {
const double t_a_v = v / a - t_j_a;
const double s_half_v =
a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a_v + 0.5 * t_a_v * t_a_v);
const double s_min = 2.0 * s_half_v;
if (profile.distance > s_min + EPSILON) {
calculateLongProfile(profile);
} else {
calculateShortProfile(profile);
}
}
return profile;
}
void SCurve::calculateShortProfile(SCurveProfile& profile) const
{
// 短距离:无巡航段(t4 = 0)。
const double j = profile.j_max;
const double a = profile.a_max;
const double v = profile.v_max;
const double d = profile.distance;
const double t_j_a = a / j;
if (v < a * t_j_a) {
// 达不到 a_max:极短距离时只有 4 个 jerk 段。
const double t1 = std::cbrt(d / (2.0 * j));
profile.t1 = t1;
profile.t2 = 0.0;
profile.t3 = t1;
profile.t4 = 0.0;
profile.t5 = t1;
profile.t6 = 0.0;
profile.t7 = t1;
profile.v_cruise = j * t1 * t1;
profile.a_limit = j * t1;
} else {
// 能达到 a_max,但达不到 v_max:求无巡航的匀加速持续时间。
const double D = t_j_a * t_j_a + 4.0 * (d / a);
double t2 = (-3.0 * t_j_a + std::sqrt(std::max(0.0, D))) * 0.5;
if (t2 < 0.0) {
const double t1 = std::cbrt(d / (2.0 * j));
profile.t1 = t1;
profile.t2 = 0.0;
profile.t3 = t1;
profile.t4 = 0.0;
profile.t5 = t1;
profile.t6 = 0.0;
profile.t7 = t1;
profile.v_cruise = j * t1 * t1;
profile.a_limit = j * t1;
} else {
profile.t1 = t_j_a;
profile.t2 = t2;
profile.t3 = t_j_a;
profile.t4 = 0.0;
profile.t5 = t_j_a;
profile.t6 = t2;
profile.t7 = t_j_a;
profile.v_cruise = a * (t2 + t_j_a);
profile.a_limit = a;
}
}
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
profile.t5 + profile.t6 + profile.t7;
}
void SCurve::calculateLongProfile(SCurveProfile& profile) const
{
// 含巡航段的完整 7 段式 S 曲线;与 SCurveProfile1D 的 full-profile 公式一致。
const double j = profile.j_max;
const double a = profile.a_max;
const double v = profile.v_max;
const double d = profile.distance;
const double t_j_a = a / j;
if (v < a * t_j_a) {
// 达不到 a_max,但可以达到 v_max 并进入巡航。
const double t_j_v = std::sqrt(v / j);
const double s_min = 2.0 * j * t_j_v * t_j_v * t_j_v;
profile.t1 = t_j_v;
profile.t2 = 0.0;
profile.t3 = t_j_v;
profile.t4 = std::max(0.0, (d - s_min) / v);
profile.t5 = t_j_v;
profile.t6 = 0.0;
profile.t7 = t_j_v;
profile.v_cruise = v;
profile.a_limit = j * t_j_v;
} else {
// 能达到 a_max 和 v_max。
const double t_a = v / a - t_j_a;
const double s_half =
a * (t_j_a * t_j_a + 1.5 * t_j_a * t_a + 0.5 * t_a * t_a);
const double s_min = 2.0 * s_half;
profile.t1 = t_j_a;
profile.t2 = t_a;
profile.t3 = t_j_a;
profile.t4 = std::max(0.0, (d - s_min) / v);
profile.t5 = t_j_a;
profile.t6 = t_a;
profile.t7 = t_j_a;
profile.v_cruise = v;
profile.a_limit = a;
}
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
profile.t5 + profile.t6 + profile.t7;
}
double SCurve::computeSegmentJerk(const SCurveProfile& profile, double t) const
{
double j = profile.j_max * profile.direction;
// 判断所处阶段
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
double t_end3 = t_end2 + profile.t3;
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
// double t_end7 = t_end6 + profile.t7; // = total_time
if (t < t_end1) {
return j; // 段 1:正加加速度(加速)
} else if (t < t_end2) {
return 0.0; // 段 2:加加速度为 0(匀加速)
} else if (t < t_end3) {
return -j; // 段 3:负加加速度(减小加速度)
} else if (t < t_end4) {
return 0.0; // 段 4:加加速度为 0(巡航)
} else if (t < t_end5) {
return -j; // 段 5:负加加速度(开始减速)
} else if (t < t_end6) {
return 0.0; // 段 6:加加速度为 0(匀减速)
} else {
return j; // 段 7:正加加速度(减速结束)
}
}
double SCurve::getPositionAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0) return profile.p0;
if (t >= profile.total_time) return profile.p0 + profile.distance * profile.direction;
double j = profile.j_max * profile.direction;
double p = profile.p0;
double v = profile.v0;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
double t_end3 = t_end2 + profile.t3;
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
// 依次处理各阶段
auto processSegment = [&](double dt, double jerk) {
p += v * dt + 0.5 * a * dt * dt + (1.0/6.0) * jerk * dt * dt * dt;
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
// 段 1
if (t <= t_end1) {
processSegment(t, j);
return p;
}
processSegment(profile.t1, j);
// 段 2
if (t <= t_end2) {
processSegment(t - t_end1, 0.0);
return p;
}
processSegment(profile.t2, 0.0);
// 段 3
if (t <= t_end3) {
processSegment(t - t_end2, -j);
return p;
}
processSegment(profile.t3, -j);
// 段 4(巡航)
if (t <= t_end4) {
processSegment(t - t_end3, 0.0);
return p;
}
processSegment(profile.t4, 0.0);
// 段 5
if (t <= t_end5) {
processSegment(t - t_end4, -j);
return p;
}
processSegment(profile.t5, -j);
// 段 6
if (t <= t_end6) {
processSegment(t - t_end5, 0.0);
return p;
}
processSegment(profile.t6, 0.0);
// 段 7
processSegment(t - t_end6, j);
return p;
}
double SCurve::getVelocityAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0) return profile.v0;
if (t >= profile.total_time) return profile.vf;
double j = profile.j_max * profile.direction;
double v = profile.v0;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
double t_end3 = t_end2 + profile.t3;
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
auto processSegment = [&](double dt, double jerk) {
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
if (t <= t_end1) {
v += a * t + 0.5 * j * t * t;
return v;
}
processSegment(profile.t1, j);
if (t <= t_end2) {
v += a * (t - t_end1);
return v;
}
processSegment(profile.t2, 0.0);
if (t <= t_end3) {
double dt = t - t_end2;
v += a * dt + 0.5 * (-j) * dt * dt;
return v;
}
processSegment(profile.t3, -j);
if (t <= t_end4) {
v += a * (t - t_end3);
return v;
}
processSegment(profile.t4, 0.0);
if (t <= t_end5) {
double dt = t - t_end4;
v += a * dt + 0.5 * (-j) * dt * dt;
return v;
}
processSegment(profile.t5, -j);
if (t <= t_end6) {
v += a * (t - t_end5);
return v;
}
processSegment(profile.t6, 0.0);
double dt = t - t_end6;
v += a * dt + 0.5 * j * dt * dt;
return v;
}
double SCurve::getAccelerationAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0 || t >= profile.total_time) return 0.0;
double j = profile.j_max * profile.direction;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
double t_end3 = t_end2 + profile.t3;
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
if (t <= t_end1) {
return a + j * t;
}
a += j * profile.t1;
if (t <= t_end2) {
return a;
}
if (t <= t_end3) {
return a + (-j) * (t - t_end2);
}
a += (-j) * profile.t3;
if (t <= t_end4) {
return a; // Should be ~0
}
if (t <= t_end5) {
return a + (-j) * (t - t_end4);
}
a += (-j) * profile.t5;
if (t <= t_end6) {
return a;
}
return a + j * (t - t_end6);
}
double SCurve::getJerkAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0.0 || t >= profile.total_time) {
return 0.0;
}
return computeSegmentJerk(profile, t);
}
void SCurve::generateTrajectory(const SCurveProfile& profile, double dt,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& accelerations) const
{
positions.clear();
velocities.clear();
accelerations.clear();
if (profile.total_time <= 0 || dt <= 0) {
positions.push_back(profile.p0);
velocities.push_back(profile.v0);
accelerations.push_back(profile.a0);
return;
}
int num_points = static_cast<int>(std::ceil(profile.total_time / dt)) + 1;
positions.reserve(num_points);
velocities.reserve(num_points);
accelerations.reserve(num_points);
for (double t = 0; t <= profile.total_time; t += dt) {
positions.push_back(getPositionAtTime(profile, t));
velocities.push_back(getVelocityAtTime(profile, t));
accelerations.push_back(getAccelerationAtTime(profile, t));
}
// 确保包含最终点
if (positions.empty() ||
std::abs(positions.back() - (profile.p0 + profile.distance * profile.direction)) > EPSILON) {
positions.push_back(profile.p0 + profile.distance * profile.direction);
velocities.push_back(profile.vf);
accelerations.push_back(0.0);
}
}
}

View File

@ -1,191 +0,0 @@
//
// Created by lgv on 2026/3/10.
//
#include "../include/s_curve_position_planner.h"
#include <algorithm>
#include <cmath>
namespace cmvr
{
SCurvePositionPlanner1D::SCurvePositionPlanner1D(double max_velocity,
double max_acceleration,
double max_jerk)
: max_velocity_(std::abs(max_velocity))
, max_acceleration_(std::abs(max_acceleration))
, max_jerk_(std::abs(max_jerk))
, velocity_planner_(max_velocity_, max_acceleration_, max_jerk_)
, position_gain_(1.0)
{
velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_));
reset();
}
void SCurvePositionPlanner1D::setConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
max_velocity_ = std::abs(max_velocity);
max_acceleration_ = std::abs(max_acceleration);
max_jerk_ = std::abs(max_jerk);
velocity_planner_.setConstraints(max_velocity_, max_acceleration_, max_jerk_);
velocity_planner_.setTargetReplanThreshold(std::max(1e-3, 0.02 * max_velocity_));
}
void SCurvePositionPlanner1D::getConstraints(double& max_velocity,
double& max_acceleration,
double& max_jerk) const
{
max_velocity = max_velocity_;
max_acceleration = max_acceleration_;
max_jerk = max_jerk_;
}
void SCurvePositionPlanner1D::setPositionGain(double position_gain)
{
position_gain_ = std::max(0.0, position_gain);
}
void SCurvePositionPlanner1D::initialize(double position, double velocity, double acceleration)
{
state_.position = position;
velocity_planner_.initialize(velocity, acceleration);
state_.velocity = velocity_planner_.getVelocity();
state_.acceleration = velocity_planner_.getAcceleration();
state_.jerk = 0.0;
state_.target_position = position;
state_.is_moving = false;
}
void SCurvePositionPlanner1D::reset()
{
state_ = SCurvePositionPlannerState();
velocity_planner_.reset();
}
void SCurvePositionPlanner1D::setTarget(double target_position)
{
state_.target_position = target_position;
}
double SCurvePositionPlanner1D::update(double dt)
{
if (dt <= 0.0 || dt > 0.1) {
return state_.position;
}
const double position_error = state_.target_position - state_.position;
if (std::abs(position_error) < POSITION_THRESHOLD &&
std::abs(velocity_planner_.getVelocity()) < VELOCITY_THRESHOLD &&
std::abs(velocity_planner_.getAcceleration()) < ACCELERATION_THRESHOLD) {
velocity_planner_.overwriteState(0.0, 0.0, false);
state_.position = state_.target_position;
state_.velocity = 0.0;
state_.acceleration = 0.0;
state_.jerk = 0.0;
state_.is_moving = false;
return state_.position;
}
velocity_planner_.setTargetVelocity(computeDesiredVelocity(position_error));
const double old_velocity = velocity_planner_.getVelocity();
const double new_velocity = velocity_planner_.update(dt);
state_.velocity = new_velocity;
state_.acceleration = velocity_planner_.getAcceleration();
state_.jerk = velocity_planner_.getJerk();
state_.position += 0.5 * (old_velocity + new_velocity) * dt;
const double updated_error = state_.target_position - state_.position;
if (std::abs(updated_error) < POSITION_THRESHOLD &&
std::abs(state_.velocity) < VELOCITY_THRESHOLD &&
std::abs(state_.acceleration) < ACCELERATION_THRESHOLD) {
velocity_planner_.overwriteState(0.0, 0.0, false);
state_.position = state_.target_position;
state_.velocity = 0.0;
state_.acceleration = 0.0;
state_.jerk = 0.0;
state_.is_moving = false;
return state_.position;
}
state_.is_moving = velocity_planner_.isMoving() ||
std::abs(updated_error) > POSITION_THRESHOLD;
return state_.position;
}
double SCurvePositionPlanner1D::computeDesiredVelocity(double position_error) const
{
if (std::abs(position_error) <= POSITION_THRESHOLD) {
return 0.0;
}
const double proportional_velocity =
clamp(position_gain_ * position_error, -max_velocity_, max_velocity_);
const double current_velocity = velocity_planner_.getVelocity();
const double current_acceleration = velocity_planner_.getAcceleration();
const double stopping_distance =
computePlannerStoppingDistance(current_velocity, current_acceleration);
if (std::abs(current_velocity) > VELOCITY_THRESHOLD &&
sign(current_velocity) != sign(position_error)) {
return 0.0;
}
if (std::abs(current_velocity) > VELOCITY_THRESHOLD &&
sign(current_velocity) == sign(position_error) &&
std::abs(position_error) <= std::abs(stopping_distance) * 1.05) {
return 0.0;
}
double low = 0.0;
double high = max_velocity_;
for (int i = 0; i < 40; ++i) {
const double mid = 0.5 * (low + high);
const double distance =
std::abs(computePlannerStoppingDistance(sign(position_error) * mid, 0.0));
if (distance <= std::abs(position_error)) {
low = mid;
} else {
high = mid;
}
}
return sign(position_error) *
std::min(std::abs(proportional_velocity), low);
}
double SCurvePositionPlanner1D::computePlannerStoppingDistance(double velocity,
double acceleration) const
{
if (std::abs(velocity) <= VELOCITY_THRESHOLD &&
std::abs(acceleration) <= ACCELERATION_THRESHOLD) {
return 0.0;
}
const auto profile = velocity_planner_.calculateProfile(velocity, 0.0, acceleration);
if (!profile.valid || profile.total_time <= EPSILON) {
return 0.0;
}
const int steps = std::max(16, static_cast<int>(std::ceil(profile.total_time / 0.002)));
const double dt = profile.total_time / static_cast<double>(steps);
double distance = 0.0;
double previous_time = 0.0;
double previous_velocity = velocity_planner_.getVelocityAtTime(profile, 0.0);
for (int i = 1; i <= steps; ++i) {
const double t = (i == steps) ? profile.total_time : i * dt;
const double current_velocity = velocity_planner_.getVelocityAtTime(profile, t);
distance += 0.5 * (previous_velocity + current_velocity) * (t - previous_time);
previous_time = t;
previous_velocity = current_velocity;
}
return distance;
}
} // namespace cmvr

View File

@ -1,578 +0,0 @@
//
// Created by lgv on 2026/3/9.
//
#include "../include/s_curve_velocity_planner.h"
#include <cmath>
#include <limits>
namespace cmvr
{
SCurveVelocityPlanner1D::SCurveVelocityPlanner1D(double max_velocity,
double max_acceleration,
double max_jerk)
: max_velocity_(std::abs(max_velocity))
, max_acceleration_(std::abs(max_acceleration))
, max_jerk_(std::abs(max_jerk))
, target_replan_threshold_(DEFAULT_TARGET_REPLAN_THRESHOLD)
, synchronize_replan_threshold_(DEFAULT_SYNCHRONIZE_REPLAN_THRESHOLD)
{
reset();
}
void SCurveVelocityPlanner1D::setConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
max_velocity_ = std::abs(max_velocity);
max_acceleration_ = std::abs(max_acceleration);
max_jerk_ = std::abs(max_jerk);
state_.velocity = clamp(state_.velocity, -max_velocity_, max_velocity_);
state_.acceleration = clamp(state_.acceleration, -max_acceleration_, max_acceleration_);
state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_);
if (state_.has_active_profile) {
active_profile_ = calculateProfile(state_.velocity,
state_.target_velocity,
state_.acceleration);
state_.elapsed_time = 0.0;
state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON;
}
updateIsMovingFlag();
}
void SCurveVelocityPlanner1D::getConstraints(double& max_velocity,
double& max_acceleration,
double& max_jerk) const
{
max_velocity = max_velocity_;
max_acceleration = max_acceleration_;
max_jerk = max_jerk_;
}
void SCurveVelocityPlanner1D::setTargetReplanThreshold(double threshold)
{
target_replan_threshold_ = std::max(0.0, threshold);
}
void SCurveVelocityPlanner1D::setSynchronizeReplanThreshold(double threshold)
{
synchronize_replan_threshold_ = std::max(0.0, threshold);
}
void SCurveVelocityPlanner1D::initialize(double velocity, double acceleration)
{
state_ = SCurveVelocityPlannerState();
state_.velocity = clamp(velocity, -max_velocity_, max_velocity_);
state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_);
state_.jerk = 0.0;
state_.target_velocity = state_.velocity;
state_.elapsed_time = 0.0;
state_.has_active_profile = false;
active_profile_ = SCurveVelocityProfile();
active_profile_.v0 = state_.velocity;
active_profile_.a0 = state_.acceleration;
active_profile_.vf = state_.velocity;
active_profile_.valid = false;
updateIsMovingFlag();
}
void SCurveVelocityPlanner1D::reset()
{
state_ = SCurveVelocityPlannerState();
active_profile_ = SCurveVelocityProfile();
}
void SCurveVelocityPlanner1D::overwriteState(double velocity,
double acceleration,
bool keep_target_velocity)
{
state_.velocity = clamp(velocity, -max_velocity_, max_velocity_);
state_.acceleration = clamp(acceleration, -max_acceleration_, max_acceleration_);
state_.jerk = 0.0;
state_.elapsed_time = 0.0;
state_.has_active_profile = false;
if (!keep_target_velocity) {
state_.target_velocity = state_.velocity;
} else {
state_.target_velocity = clamp(state_.target_velocity, -max_velocity_, max_velocity_);
}
active_profile_ = SCurveVelocityProfile();
active_profile_.v0 = state_.velocity;
active_profile_.a0 = state_.acceleration;
active_profile_.vf = state_.target_velocity;
active_profile_.valid = false;
updateIsMovingFlag();
}
void SCurveVelocityPlanner1D::synchronizeAndReplan(double velocity,
double acceleration)
{
const double measured_velocity = clamp(velocity, -max_velocity_, max_velocity_);
double measured_acceleration =
clamp(acceleration, -max_acceleration_, max_acceleration_);
// When the target is zero this planner is also used for Cartesian speed
// magnitudes. A magnitude is non-negative, while the finite-difference
// derivative of the measured magnitude is signed. Feeding a large negative
// measured acceleration into a signed 1-D velocity planner can generate a
// profile that crosses through zero and becomes negative before returning to
// zero. The twist limiter then multiplies that negative "norm" by the
// current direction, which reverses and amplifies the Cartesian command.
//
// For feedback resynchronization during a stop, synchronize the measured
// speed only and restart the stop profile with zero scalar acceleration.
// This avoids noise-sensitive stop replans and preserves a non-overshooting
// deceleration profile for speed-magnitude users.
if (std::abs(state_.target_velocity) <= VELOCITY_THRESHOLD) {
measured_acceleration = 0.0;
}
if (!state_.has_active_profile &&
std::abs(measured_velocity - state_.target_velocity) <= VELOCITY_THRESHOLD) {
state_.velocity = state_.target_velocity;
state_.acceleration = 0.0;
state_.jerk = 0.0;
updateIsMovingFlag();
return;
}
// 如果测量值已经基本落在当前采样状态上,就继续沿现有 profile 走。
// 否则每拍都从同一目标重规划,会把已经进入的 jerk phase 反复打断。
if (state_.has_active_profile &&
std::abs(measured_velocity - state_.velocity) <= synchronize_replan_threshold_) {
state_.velocity = measured_velocity;
state_.acceleration = measured_acceleration;
state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time);
updateIsMovingFlag();
return;
}
state_.velocity = measured_velocity;
state_.acceleration = measured_acceleration;
state_.jerk = 0.0;
active_profile_ = calculateProfile(state_.velocity,
state_.target_velocity,
state_.acceleration);
state_.elapsed_time = 0.0;
state_.has_active_profile = active_profile_.total_time > EPSILON;
updateIsMovingFlag();
}
void SCurveVelocityPlanner1D::setTargetVelocity(double target_velocity)
{
const double new_target = clamp(target_velocity, -max_velocity_, max_velocity_);
const bool same_target =
std::abs(new_target - state_.target_velocity) <= target_replan_threshold_;
if (same_target &&
state_.has_active_profile) {
return;
}
if (same_target &&
!state_.has_active_profile &&
std::abs(state_.velocity - new_target) <= VELOCITY_THRESHOLD &&
std::abs(state_.acceleration) <= ACCELERATION_THRESHOLD) {
return;
}
state_.target_velocity = new_target;
active_profile_ = calculateProfile(state_.velocity,
state_.target_velocity,
state_.acceleration);
state_.elapsed_time = 0.0;
state_.has_active_profile = active_profile_.valid && active_profile_.total_time > EPSILON;
updateIsMovingFlag();
}
double SCurveVelocityPlanner1D::getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return profile.v0;
}
if (t <= 0.0) {
return profile.v0;
}
if (t >= profile.total_time) {
return profile.vf;
}
double v = profile.v0;
double a = profile.a0;
auto process_segment = [&](double dt, double jerk) {
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
// seg1
if (t <= profile.t1) {
process_segment(t, profile.j1);
return v;
}
process_segment(profile.t1, profile.j1);
// seg2
const double t_after_1 = t - profile.t1;
if (t_after_1 <= profile.t2) {
process_segment(t_after_1, profile.j2);
return v;
}
process_segment(profile.t2, profile.j2);
// seg3
const double t_after_2 = t_after_1 - profile.t2;
process_segment(t_after_2, profile.j3);
return v;
}
double SCurveVelocityPlanner1D::getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return profile.a0;
}
if (t <= 0.0) {
return profile.a0;
}
if (t >= profile.total_time) {
return 0.0;
}
double a = profile.a0;
auto process_segment = [&](double dt, double jerk) {
a += jerk * dt;
};
// seg1
if (t <= profile.t1) {
process_segment(t, profile.j1);
return a;
}
process_segment(profile.t1, profile.j1);
// seg2
const double t_after_1 = t - profile.t1;
if (t_after_1 <= profile.t2) {
process_segment(t_after_1, profile.j2);
return a;
}
process_segment(profile.t2, profile.j2);
// seg3
const double t_after_2 = t_after_1 - profile.t2;
process_segment(t_after_2, profile.j3);
return a;
}
double SCurveVelocityPlanner1D::getJerkAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return 0.0;
}
if (t <= 0.0 || t >= profile.total_time) {
return 0.0;
}
if (t <= profile.t1) {
return profile.j1;
}
if (t <= profile.t1 + profile.t2) {
return profile.j2;
}
return profile.j3;
}
void SCurveVelocityPlanner1D::integrateWholeProfile(const SCurveVelocityProfile& profile,
double& v_end,
double& a_end) const
{
double v = profile.v0;
double a = profile.a0;
auto process_segment = [&](double dt, double jerk) {
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
process_segment(profile.t1, profile.j1);
process_segment(profile.t2, profile.j2);
process_segment(profile.t3, profile.j3);
v_end = v;
a_end = a;
}
bool SCurveVelocityPlanner1D::isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const
{
if (!profile.valid) {
return true;
}
std::vector<double> check_times;
check_times.reserve(8);
check_times.push_back(0.0);
check_times.push_back(profile.t1);
check_times.push_back(profile.t1 + profile.t2);
check_times.push_back(profile.total_time);
// seg1 内部若 acceleration 过零,则 velocity 可能在段内出现极值
if (std::abs(profile.j1) > EPSILON && profile.t1 > EPSILON) {
const double tz = -profile.a0 / profile.j1;
if (tz > EPSILON && tz < profile.t1 - EPSILON) {
check_times.push_back(tz);
}
}
for (double t : check_times) {
const double v = getVelocityAtTime(profile, t);
if (std::abs(v) > max_velocity_ + 1e-7) {
return false;
}
}
return true;
}
SCurveVelocityProfile SCurveVelocityPlanner1D::calculateProfile(double start_velocity,
double end_velocity,
double start_acceleration) const
{
SCurveVelocityProfile best;
best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_);
best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_);
best.vf = clamp(end_velocity, -max_velocity_, max_velocity_);
if (max_jerk_ <= EPSILON || max_acceleration_ <= EPSILON) {
// 退化情况:这里不做特殊退化规划,直接返回 invalid
return best;
}
const double v0 = best.v0;
const double a0 = best.a0;
const double vf = best.vf;
// 目标方向坐标:尽量统一到“signed frame 下 Δv >= 0”
double s = sign(vf - v0);
if (std::abs(vf - v0) <= VELOCITY_THRESHOLD) {
s = 1.0;
}
const double dv = s * (vf - v0); // >= 0
const double a0s = s * a0; // signed frame 下的初始 acceleration
const double j = max_jerk_;
const double amax = max_acceleration_;
auto normalize_nonnegative = [](double x) {
return (x < 0.0 && x > -1e-10) ? 0.0 : x;
};
auto try_candidate = [&](double t1, double t2, double t3,
double j1s, double j2s, double j3s) {
t1 = normalize_nonnegative(t1);
t2 = normalize_nonnegative(t2);
t3 = normalize_nonnegative(t3);
if (t1 < 0.0 || t2 < 0.0 || t3 < 0.0) {
return;
}
SCurveVelocityProfile cand;
cand.t1 = t1;
cand.t2 = t2;
cand.t3 = t3;
cand.total_time = t1 + t2 + t3;
cand.j1 = s * j1s;
cand.j2 = s * j2s;
cand.j3 = s * j3s;
cand.v0 = v0;
cand.a0 = a0;
cand.vf = vf;
cand.valid = true;
double vend = 0.0;
double aend = 0.0;
integrateWholeProfile(cand, vend, aend);
if (std::abs(vend - vf) > 1e-5) {
return;
}
if (std::abs(aend) > 1e-5) {
return;
}
if (!isVelocityLimitSatisfied(cand)) {
return;
}
if (!best.valid || cand.total_time < best.total_time) {
best = cand;
}
};
// ---------------- UDU 三角形(无平台) ----------------
{
// Δv = (2A^2 - a0^2)/(2j)
const double A2 = 0.5 * (2.0 * j * dv + a0s * a0s);
if (A2 >= -1e-10) {
const double A = std::sqrt(std::max(0.0, A2));
if (A <= amax + 1e-10 && A >= a0s - 1e-10) {
const double t1 = (A - a0s) / j;
const double t2 = 0.0;
const double t3 = A / j;
try_candidate(t1, t2, t3, +j, 0.0, -j);
}
}
}
// ---------------- UDU 梯形(有平台) ----------------
{
const double A = amax;
if (A > EPSILON && A >= a0s - 1e-10) {
const double base = (2.0 * A * A - a0s * a0s) / (2.0 * j);
const double t1 = (A - a0s) / j;
const double t2 = (dv - base) / A;
const double t3 = A / j;
try_candidate(t1, t2, t3, +j, 0.0, -j);
}
}
// ---------------- DUD 三角形(无平台) ----------------
{
// Δv = (a0^2 - 2B^2)/(2j)
const double B2 = 0.5 * (a0s * a0s - 2.0 * j * dv);
if (B2 >= -1e-10) {
const double B = std::sqrt(std::max(0.0, B2));
if (B <= amax + 1e-10 && B >= -a0s - 1e-10) {
const double t1 = (a0s + B) / j;
const double t2 = 0.0;
const double t3 = B / j;
try_candidate(t1, t2, t3, -j, 0.0, +j);
}
}
}
// ---------------- DUD 梯形(有平台) ----------------
{
const double B = amax;
if (B > EPSILON && B >= -a0s - 1e-10) {
const double base = (a0s * a0s - 2.0 * B * B) / (2.0 * j);
const double t1 = (a0s + B) / j;
const double t2 = (base - dv) / B;
const double t3 = B / j;
try_candidate(t1, t2, t3, -j, 0.0, +j);
}
}
// 已到终点附近
if (!best.valid &&
std::abs(vf - v0) <= VELOCITY_THRESHOLD &&
std::abs(a0) <= ACCELERATION_THRESHOLD) {
best.valid = false;
best.total_time = 0.0;
best.v0 = v0;
best.a0 = a0;
best.vf = vf;
}
return best;
}
void SCurveVelocityPlanner1D::generateTrajectory(const SCurveVelocityProfile& profile, double dt,
std::vector<double>& velocities,
std::vector<double>& accelerations,
std::vector<double>& jerks) const
{
velocities.clear();
accelerations.clear();
jerks.clear();
if (!profile.valid || profile.total_time <= 0.0 || dt <= 0.0) {
velocities.push_back(profile.v0);
accelerations.push_back(profile.a0);
jerks.push_back(0.0);
return;
}
const int num_points = static_cast<int>(std::ceil(profile.total_time / dt)) + 1;
velocities.reserve(num_points);
accelerations.reserve(num_points);
jerks.reserve(num_points);
for (double t = 0.0; t <= profile.total_time; t += dt) {
velocities.push_back(getVelocityAtTime(profile, t));
accelerations.push_back(getAccelerationAtTime(profile, t));
jerks.push_back(getJerkAtTime(profile, t));
}
if (velocities.empty() || std::abs(velocities.back() - profile.vf) > VELOCITY_THRESHOLD) {
velocities.push_back(profile.vf);
accelerations.push_back(0.0);
jerks.push_back(0.0);
}
}
double SCurveVelocityPlanner1D::update(double dt)
{
if (dt <= 0.0) {
return state_.velocity;
}
if (!state_.has_active_profile || !active_profile_.valid) {
state_.jerk = 0.0;
updateIsMovingFlag();
return state_.velocity;
}
state_.elapsed_time += dt;
if (state_.elapsed_time >= active_profile_.total_time) {
state_.elapsed_time = active_profile_.total_time;
state_.velocity = active_profile_.vf;
state_.acceleration = 0.0;
state_.jerk = 0.0;
state_.has_active_profile = false;
updateIsMovingFlag();
return state_.velocity;
}
state_.velocity = getVelocityAtTime(active_profile_, state_.elapsed_time);
state_.acceleration = getAccelerationAtTime(active_profile_, state_.elapsed_time);
state_.jerk = getJerkAtTime(active_profile_, state_.elapsed_time);
updateIsMovingFlag();
return state_.velocity;
}
void SCurveVelocityPlanner1D::updateIsMovingFlag()
{
state_.is_moving =
state_.has_active_profile ||
std::abs(state_.velocity) > VELOCITY_THRESHOLD ||
std::abs(state_.target_velocity) > VELOCITY_THRESHOLD ||
std::abs(state_.acceleration) > ACCELERATION_THRESHOLD;
}
} // namespace cmvr

View File

@ -1,77 +0,0 @@
#include <algorithm>
#include <gtest/gtest.h>
#include "algorithms/motion_planner/base_motion/motion_profile/s_curve/include/s_curve_velocity_planner.h"
namespace cmvr {
namespace {
void finishActiveProfile(SCurveVelocityPlanner1D& planner, double dt)
{
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
planner.update(dt);
}
ASSERT_FALSE(planner.hasActiveProfile());
}
TEST(SCurveVelocityPlannerStopTest, FeedbackResyncDoesNotReverseSpeedMagnitude)
{
SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0);
constexpr double kDt = 0.001;
constexpr double kInitialSpeed = 0.04;
planner.initialize(kInitialSpeed, 0.0);
planner.setTargetVelocity(0.0);
finishActiveProfile(planner, kDt);
// Reproduce the speedL stop feedback case: the command profile has already
// reached zero, but the measured TCP still has residual speed. A 1 kHz
// finite difference may report a large negative scalar acceleration.
planner.synchronizeAndReplan(kInitialSpeed, -3.0);
double max_speed = planner.getVelocity();
double min_speed = planner.getVelocity();
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
const double speed = planner.update(kDt);
max_speed = std::max(max_speed, speed);
min_speed = std::min(min_speed, speed);
}
EXPECT_GE(min_speed, -1e-9);
EXPECT_LE(max_speed, kInitialSpeed + 1e-9);
EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9);
}
TEST(SCurveVelocityPlannerStopTest, LargerMeasuredDecelerationDoesNotIncreaseStopSpeed)
{
constexpr double kDt = 0.001;
constexpr double kInitialSpeed = 0.04;
const double measured_accelerations[] = {-0.5, -1.0, -2.0, -3.0};
for (const double measured_acceleration : measured_accelerations) {
SCurveVelocityPlanner1D planner(0.55, 3.0, 10.0);
planner.initialize(kInitialSpeed, 0.0);
planner.setTargetVelocity(0.0);
finishActiveProfile(planner, kDt);
planner.synchronizeAndReplan(kInitialSpeed, measured_acceleration);
double max_speed = planner.getVelocity();
double min_speed = planner.getVelocity();
for (int i = 0; i < 10000 && planner.hasActiveProfile(); ++i) {
const double speed = planner.update(kDt);
max_speed = std::max(max_speed, speed);
min_speed = std::min(min_speed, speed);
}
EXPECT_GE(min_speed, -1e-9) << "measured_acceleration=" << measured_acceleration;
EXPECT_LE(max_speed, kInitialSpeed + 1e-9)
<< "measured_acceleration=" << measured_acceleration;
EXPECT_NEAR(planner.getVelocity(), 0.0, 1e-9)
<< "measured_acceleration=" << measured_acceleration;
}
}
} // namespace
} // namespace cmvr

View File

@ -1,20 +1,20 @@
add_library(lgv_base_motion SHARED
add_library(base_motion SHARED
cartesian/s_curve/src/s_curve_planner.cpp)
target_include_directories(lgv_base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
target_link_libraries(lgv_base_motion PUBLIC
target_include_directories(base_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
target_link_libraries(base_motion PUBLIC
cmvr_es::curves OsqpEigen tinyxml2 fcl cmvr_es::common)
add_library(cmvr_es::lgv_base_motion ALIAS lgv_base_motion)
install(TARGETS lgv_base_motion LIBRARY DESTINATION lib)
add_library(cmvr_es::base_motion ALIAS base_motion)
install(TARGETS base_motion LIBRARY DESTINATION lib)
add_library(lgv_arm_motion SHARED
add_library(arm_motion SHARED
cartesian/pinocchio/src/pinocchio_cartesian_trajectory_planner.cpp
cartesian/pinocchio/src/pinocchio_cartesian_velocity_planner.cpp)
target_include_directories(lgv_arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
target_link_libraries(lgv_arm_motion PUBLIC
cmvr_es::ik_solver cmvr_es::lgv_base_motion cmvr_es::curves)
add_library(cmvr_es::lgv_arm_motion ALIAS lgv_arm_motion)
add_library(cmvr_es::algorithms::lgv_arm_motion ALIAS lgv_arm_motion)
install(TARGETS lgv_arm_motion LIBRARY DESTINATION lib)
target_include_directories(arm_motion PUBLIC "${PROJECT_SOURCE_DIR}/cmvr-es")
target_link_libraries(arm_motion PUBLIC
cmvr_es::ik_solver cmvr_es::base_motion cmvr_es::curves)
add_library(cmvr_es::arm_motion ALIAS arm_motion)
add_library(cmvr_es::algorithms::arm_motion ALIAS arm_motion)
install(TARGETS arm_motion LIBRARY DESTINATION lib)
add_library(joint_path_planner SHARED
joint/ompl/src/rrt_connect.cpp)
@ -26,14 +26,14 @@ install(TARGETS joint_path_planner LIBRARY DESTINATION lib)
add_executable(s_curve_planner_reversal_test
cartesian/s_curve/test/s_curve_planner_reversal_test.cpp)
target_link_libraries(s_curve_planner_reversal_test PRIVATE
cmvr_es::lgv_base_motion gtest gtest_main)
cmvr_es::base_motion gtest gtest_main)
add_executable(lgv_pinocchio_speedl_limits_test
add_executable(pinocchio_speedl_limits_test
cartesian/pinocchio/test/pinocchio_speedl_limits_test.cpp)
target_compile_definitions(lgv_pinocchio_speedl_limits_test PRIVATE
target_compile_definitions(pinocchio_speedl_limits_test PRIVATE
CMVR_TEST_SOURCE_DIR="${PROJECT_SOURCE_DIR}")
target_link_libraries(lgv_pinocchio_speedl_limits_test PRIVATE
cmvr_es::algorithms::lgv_arm_motion gtest gtest_main)
target_link_libraries(pinocchio_speedl_limits_test PRIVATE
cmvr_es::algorithms::arm_motion gtest gtest_main)
add_executable(rrt_connect_test
joint/ompl/test/rrt_connect_test.cpp)

View File

@ -61,7 +61,7 @@ private:
std::shared_ptr<cmvr::PinocchioIKBase> solver_{nullptr};
config::SpeedLPlannerConfig speedl_config_{};
struct State {
cmvr::LgvSCurvePlanner s_curve_planner_{};
cmvr::SCurvePlanner s_curve_planner_{};
Eigen::VectorXd joint_acceleration_limits_;
std::vector<double> prev_qdot_command_;
Eigen::Matrix<double, 6, 1> speedl_command_twist_base_{Eigen::Matrix<double, 6, 1>::Zero()};

View File

@ -167,8 +167,8 @@ bool PinocchioCartesianTrajectoryPlanner::planMoveL(const CartesianPose& target,
return true;
}
cmvr::LgvSCurve curve(velocity, acceleration, jerk);
const cmvr::LgvSCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0);
cmvr::SCurve curve(velocity, acceleration, jerk);
const cmvr::SCurveProfile profile = curve.calculatePositionProfile(0.0, path_length, 0.0, 0.0);
if (profile.total_time <= 0.0) {
return false;
}

View File

@ -104,7 +104,7 @@ bool PinocchioCartesianVelocityPlanner::configureSpeedL(const config::SpeedLPlan
if (solver_dof != 0 && solver_dof != dof) {
return false;
}
cmvr::LgvSCurvePlanner planner;
cmvr::SCurvePlanner planner;
try {
cartesian_motion::configureSCurvePlannerFromSpeedLConfig(planner, config);
} catch (const std::invalid_argument& error) {
@ -358,7 +358,7 @@ double PinocchioCartesianVelocityPlanner::adaptiveScale_(
const double a_max = offset == 0 ? state_.speedl_applied_acceleration_ : state_.speedl_applied_angular_acceleration_;
const double j_max = offset == 0 ? positiveOr(state_.speedl_applied_linear_jerk_, 10.0)
: positiveOr(speedl_config_.angular_jerk_max(), 12.0);
const auto stop = LgvSCurve(speed + acceleration * acceleration / (2.0 * j_max) + 1.0, a_max, j_max).calculateVelocityProfile(
const auto stop = SCurve(speed + acceleration * acceleration / (2.0 * j_max) + 1.0, a_max, j_max).calculateVelocityProfile(
speed, 0.0, std::min(acceleration, a_max));
if (stop.valid) horizon = std::max(horizon, stop.total_time + 2.0 * dt);
}
@ -567,7 +567,7 @@ CartesianVelocityStep PinocchioCartesianVelocityPlanner::stepImpl_(
}
state_.speedl_command_twist_base_ = state_.s_curve_planner_.plan(
plan_target, state_.speedl_frame_ == FrameType::Tool ? LgvCartesianFrame::Tool : LgvCartesianFrame::Base,
plan_target, state_.speedl_frame_ == FrameType::Tool ? CartesianFrame::Tool : CartesianFrame::Base,
dt, base_R_tool);
} catch (const std::invalid_argument& error) {
return failure(ArmErrorCode::InvalidArgument, error.what());

View File

@ -8,14 +8,14 @@
namespace cmvr
{
enum class LgvCartesianFrame
enum class CartesianFrame
{
Base = 0,
Tool = 1
};
/**
* @brief 基于 LgvSCurve 的六维末端在线速度规划器。
* @brief 基于 SCurve 的六维末端在线速度规划器。
*
* initialize() 设置初始 Base 系速度,plan() 每周期生成下一拍 Base 系命令。
* 同轴线速度可连续过零;转向使用完整速度向量的连续过渡。
@ -24,7 +24,7 @@ enum class LgvCartesianFrame
* 非法输入抛出 std::invalid_argument,无可行标量曲线抛出 std::runtime_error。
* 失败保留原规划状态;方向重规划不可行时继续已验证的原曲线。
*/
class LgvSCurvePlanner
class SCurvePlanner
{
public:
using Twist = Eigen::Matrix<double, 6, 1>;
@ -46,7 +46,7 @@ public:
void initialize(const Twist& initial_twist = Twist::Zero());
// 每周期调用一次。Tool 目标按当拍 base_R_tool 转到 Base 系。
Twist plan(const Twist& target_twist, LgvCartesianFrame frame,
Twist plan(const Twist& target_twist, CartesianFrame frame,
double dt, const Eigen::Matrix3d& base_R_tool);
const Twist& getTwistBase() const { return twist_base_; }
@ -58,7 +58,7 @@ private:
static constexpr double EPSILON = 1e-12;
static constexpr double AXIS_LOCK_COS_THRESHOLD = 0.999;
// 保存一维速度曲线的运行状态;数学计算由 LgvSCurve 完成。
// 保存一维速度曲线的运行状态;数学计算由 SCurve 完成。
struct VelocityState {
struct Sample {
double velocity{0.0};
@ -84,9 +84,9 @@ private:
private:
void replan();
LgvSCurve curve_{1.0, 1.0, 5.0};
SCurve curve_{1.0, 1.0, 5.0};
Sample state_;
LgvSCurveVelocityProfile active_profile_;
SCurveVelocityProfile active_profile_;
double target_replan_threshold_{1e-9};
static constexpr double VELOCITY_THRESHOLD = 1e-6;
};

View File

@ -11,7 +11,7 @@
namespace cmvr::device::cartesian_motion {
inline void configureSCurvePlannerFromSpeedLConfig(
cmvr::LgvSCurvePlanner& planner,
cmvr::SCurvePlanner& planner,
const config::SpeedLPlannerConfig& config)
{
using cmvr::common::config::positiveOr;

View File

@ -9,7 +9,7 @@ namespace cmvr
namespace {
void validateLimits(double velocity, double acceleration, double jerk)
{
// LgvSCurve's solver treats acceleration/jerk <= 1e-9 as degenerate.
// SCurve's solver treats acceleration/jerk <= 1e-9 as degenerate.
if (!std::isfinite(velocity) || velocity <= 1e-9 ||
!std::isfinite(acceleration) || acceleration <= 1e-9 ||
!std::isfinite(jerk) || jerk <= 1e-9) {
@ -23,14 +23,14 @@ bool withinLimit(double value, double limit)
}
} // namespace
std::array<double, 3> LgvSCurvePlanner::VelocityState::limits() const
std::array<double, 3> SCurvePlanner::VelocityState::limits() const
{
std::array<double, 3> result;
curve_.getConstraints(result[0], result[1], result[2]);
return result;
}
void LgvSCurvePlanner::VelocityState::setConstraints(double max_velocity,
void SCurvePlanner::VelocityState::setConstraints(double max_velocity,
double max_acceleration,
double max_jerk)
{
@ -49,7 +49,7 @@ void LgvSCurvePlanner::VelocityState::setConstraints(double max_velocity,
*this = std::move(staged);
}
void LgvSCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold)
void SCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold)
{
if (!std::isfinite(threshold) || threshold < 0.0) {
throw std::invalid_argument("S-curve replan threshold must be nonnegative and finite");
@ -57,7 +57,7 @@ void LgvSCurvePlanner::VelocityState::setTargetReplanThreshold(double threshold)
target_replan_threshold_ = threshold;
}
void LgvSCurvePlanner::VelocityState::initialize(double velocity, double acceleration)
void SCurvePlanner::VelocityState::initialize(double velocity, double acceleration)
{
const auto bounds = limits();
if (!withinLimit(std::abs(velocity), bounds[0]) ||
@ -68,10 +68,10 @@ void LgvSCurvePlanner::VelocityState::initialize(double velocity, double acceler
state_.velocity = velocity;
state_.acceleration = acceleration;
state_.target_velocity = velocity;
active_profile_ = LgvSCurveVelocityProfile();
active_profile_ = SCurveVelocityProfile();
}
void LgvSCurvePlanner::VelocityState::setTargetVelocity(double target_velocity)
void SCurvePlanner::VelocityState::setTargetVelocity(double target_velocity)
{
const double velocity_limit = limits()[0];
const double new_target = std::clamp(target_velocity, -velocity_limit, velocity_limit);
@ -85,7 +85,7 @@ void LgvSCurvePlanner::VelocityState::setTargetVelocity(double target_velocity)
replan();
}
void LgvSCurvePlanner::VelocityState::replan()
void SCurvePlanner::VelocityState::replan()
{
const auto candidate = curve_.calculateVelocityProfile(
state_.velocity, state_.target_velocity, state_.acceleration);
@ -113,7 +113,7 @@ void LgvSCurvePlanner::VelocityState::replan()
state_.has_active_profile = true;
}
double LgvSCurvePlanner::VelocityState::update(double dt)
double SCurvePlanner::VelocityState::update(double dt)
{
if (!state_.has_active_profile) {
if (state_.acceleration != 0.0 ||
@ -137,20 +137,20 @@ double LgvSCurvePlanner::VelocityState::update(double dt)
return state_.velocity;
}
bool LgvSCurvePlanner::VelocityState::isSettled() const
bool SCurvePlanner::VelocityState::isSettled() const
{
return !state_.has_active_profile &&
std::abs(state_.velocity) <= VELOCITY_THRESHOLD &&
state_.acceleration == 0.0;
}
bool LgvSCurvePlanner::VelocityState::isMoving() const
bool SCurvePlanner::VelocityState::isMoving() const
{
return !isSettled() || std::abs(state_.target_velocity) > VELOCITY_THRESHOLD;
}
std::pair<Eigen::Vector3d, Eigen::Vector3d>
LgvSCurvePlanner::DirectionProfile::sample(double time) const
SCurvePlanner::DirectionProfile::sample(double time) const
{
const double u = std::clamp(time / duration, 0.0, 1.0);
const double r = 1.0 - u;
@ -162,7 +162,7 @@ LgvSCurvePlanner::DirectionProfile::sample(double time) const
return {velocity, acceleration};
}
bool LgvSCurvePlanner::DirectionProfile::fits(const std::array<double, 3>& bounds) const
bool SCurvePlanner::DirectionProfile::fits(const std::array<double, 3>& bounds) const
{
if (!std::isfinite(duration) || duration <= 0.0) return false;
std::array<Eigen::Vector3d, 3> acceleration;
@ -180,7 +180,7 @@ bool LgvSCurvePlanner::DirectionProfile::fits(const std::array<double, 3>& bound
return true;
}
LgvSCurvePlanner::DirectionProfile LgvSCurvePlanner::DirectionProfile::remaining() const
SCurvePlanner::DirectionProfile SCurvePlanner::DirectionProfile::remaining() const
{
auto result = *this;
auto work = control;
@ -196,7 +196,7 @@ LgvSCurvePlanner::DirectionProfile LgvSCurvePlanner::DirectionProfile::remaining
return result;
}
void LgvSCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile,
void SCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& profile,
double velocity, double acceleration, double jerk)
{
validateLimits(velocity, acceleration, jerk);
@ -208,27 +208,27 @@ void LgvSCurvePlanner::setConstraints(VelocityState& scalar, DirectionProfile& p
scalar.setConstraints(velocity, acceleration, jerk);
}
void LgvSCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk)
void SCurvePlanner::setLinearConstraints(double velocity, double acceleration, double jerk)
{
setConstraints(linear_velocity_, linear_direction_profile_, velocity, acceleration, jerk);
}
void LgvSCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk)
void SCurvePlanner::setAngularConstraints(double velocity, double acceleration, double jerk)
{
setConstraints(angular_velocity_, angular_direction_profile_, velocity, acceleration, jerk);
}
void LgvSCurvePlanner::setLinearTargetReplanThreshold(double threshold)
void SCurvePlanner::setLinearTargetReplanThreshold(double threshold)
{
linear_velocity_.setTargetReplanThreshold(threshold);
}
void LgvSCurvePlanner::setAngularTargetReplanThreshold(double threshold)
void SCurvePlanner::setAngularTargetReplanThreshold(double threshold)
{
angular_velocity_.setTargetReplanThreshold(threshold);
}
void LgvSCurvePlanner::setContinuousLinearReversal(bool enabled)
void SCurvePlanner::setContinuousLinearReversal(bool enabled)
{
if (continuous_linear_reversal_ == enabled) return;
if (!enabled && !linear_direction_profile_.active) {
@ -243,7 +243,7 @@ void LgvSCurvePlanner::setContinuousLinearReversal(bool enabled)
continuous_linear_reversal_ = enabled;
}
void LgvSCurvePlanner::initialize(const Twist& initial_twist)
void SCurvePlanner::initialize(const Twist& initial_twist)
{
const Eigen::Vector3d v0 = initial_twist.head<3>();
const Eigen::Vector3d w0 = initial_twist.tail<3>();
@ -268,7 +268,7 @@ void LgvSCurvePlanner::initialize(const Twist& initial_twist)
*this = std::move(staged);
}
bool LgvSCurvePlanner::planDirection(const Eigen::Vector3d& velocity,
bool SCurvePlanner::planDirection(const Eigen::Vector3d& velocity,
const Eigen::Vector3d& acceleration,
const Eigen::Vector3d& target, double dt,
const std::array<double, 3>& bounds,
@ -301,7 +301,7 @@ bool LgvSCurvePlanner::planDirection(const Eigen::Vector3d& velocity,
return false;
}
Eigen::Vector3d LgvSCurvePlanner::planVelocity(VelocityState& scalar,
Eigen::Vector3d SCurvePlanner::planVelocity(VelocityState& scalar,
DirectionProfile& profile,
Eigen::Vector3d& direction,
const Eigen::Vector3d& target, double dt,
@ -368,21 +368,21 @@ Eigen::Vector3d LgvSCurvePlanner::planVelocity(VelocityState& scalar,
return velocity;
}
LgvSCurvePlanner::Twist
LgvSCurvePlanner::plan(const Twist& target_twist, LgvCartesianFrame frame,
SCurvePlanner::Twist
SCurvePlanner::plan(const Twist& target_twist, CartesianFrame frame,
double dt, const Eigen::Matrix3d& base_R_tool)
{
// Smaller periods cannot reliably support command differences in double precision.
if (!std::isfinite(dt) || dt < 1e-9) {
throw std::invalid_argument("S-curve period must be finite and at least 1e-9 seconds");
}
if ((frame != LgvCartesianFrame::Base && frame != LgvCartesianFrame::Tool) ||
if ((frame != CartesianFrame::Base && frame != CartesianFrame::Tool) ||
!target_twist.allFinite() ||
(frame == LgvCartesianFrame::Tool && !base_R_tool.allFinite())) {
(frame == CartesianFrame::Tool && !base_R_tool.allFinite())) {
throw std::invalid_argument("invalid S-curve target, frame or tool rotation");
}
Twist target_base = target_twist;
if (frame == LgvCartesianFrame::Tool) {
if (frame == CartesianFrame::Tool) {
target_base.head<3>() = base_R_tool * target_twist.head<3>();
target_base.tail<3>() = base_R_tool * target_twist.tail<3>();
}
@ -411,7 +411,7 @@ LgvSCurvePlanner::plan(const Twist& target_twist, LgvCartesianFrame frame,
return twist_base_;
}
bool LgvSCurvePlanner::isMoving() const
bool SCurvePlanner::isMoving() const
{
return linear_direction_profile_.active || angular_direction_profile_.active ||
linear_velocity_.isMoving() || angular_velocity_.isMoving();

View File

@ -8,21 +8,21 @@
namespace cmvr {
namespace {
using Twist = LgvSCurvePlanner::Twist;
using Twist = SCurvePlanner::Twist;
constexpr double dt = .001;
Twist y(double v) { Twist t = Twist::Zero(); t.y() = v; return t; }
struct Motion { double peak{0}, reverse_time{-1}, return_time{-1}; };
Motion reverse(bool continuous, int approach_ticks) {
LgvSCurvePlanner planner;
SCurvePlanner planner;
planner.setLinearConstraints(.55, 5, 10);
planner.setContinuousLinearReversal(continuous);
planner.initialize(approach_ticks == 0 ? y(.08) : Twist::Zero());
for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
for (int i = 0; i < approach_ticks; ++i) planner.plan(y(.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
planner.setLinearConstraints(.55, 3, 10);
Motion result;
double position = 0;
for (int i = 1; i <= 1500; ++i) {
const auto v = planner.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto v = planner.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
position += v.y() * dt;
result.peak = std::max(result.peak, position);
if (v.y() < 0 && result.reverse_time < 0) result.reverse_time = i * dt;
@ -37,7 +37,7 @@ Motion reverse(bool continuous, int approach_ticks) {
EXPECT_NEAR(planner.getTwistBase().y(), -.08, 1e-9);
return result;
}
TEST(LgvSCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) {
TEST(SCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) {
for (const int ticks : {0, 80, 120}) {
SCOPED_TRACE(ticks);
const auto legacy = reverse(false, ticks);
@ -48,35 +48,35 @@ TEST(LgvSCurvePlannerReversal, ContinuousReversalReducesTimeAndForwardTravel) {
EXPECT_LT(continuous.peak, legacy.peak);
}
}
TEST(LgvSCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
LgvSCurvePlanner planner;
TEST(SCurvePlannerReversal, ExactZeroCrossingIsStillMovingAndKeepsAcceleration) {
SCurvePlanner planner;
planner.setLinearConstraints(1, 1, 4);
planner.initialize(y(.02));
for (int i = 0; i < 100; ++i) planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
for (int i = 0; i < 100; ++i) planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
EXPECT_NEAR(planner.getTwistBase().y(), 0, 1e-12);
EXPECT_TRUE(planner.isMoving());
EXPECT_LT(planner.getAccelerationBase().y(), -.39);
EXPECT_LT(planner.plan(y(-.02), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003);
EXPECT_LT(planner.plan(y(-.02), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y(), -.0003);
}
TEST(LgvSCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) {
TEST(SCurvePlannerReversal, StopFromEitherDirectionSettlesWithoutReversing) {
for (double v : {.08, -.08}) {
LgvSCurvePlanner planner;
SCurvePlanner planner;
planner.setLinearConstraints(1, 3, 10);
planner.initialize(y(v));
for (int i = 0; i < 1000; ++i) {
EXPECT_GE(planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
EXPECT_GE(planner.plan(Twist::Zero(), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()).y() * v, -1e-12);
}
EXPECT_FALSE(planner.isMoving());
EXPECT_NEAR(planner.getTwistBase().norm(), 0, 1e-12);
}
}
TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) {
TEST(SCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJerkLimits) {
for (bool continuous : {true, false}) {
for (int offset : {0, 3}) {
for (bool accelerating : {false, true}) {
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
<< " angular=" << (offset == 3) << " accelerating=" << accelerating);
LgvSCurvePlanner planner;
SCurvePlanner planner;
planner.setLinearConstraints(1, 3, 10);
planner.setAngularConstraints(1, 3, 10);
planner.setContinuousLinearReversal(continuous);
@ -85,7 +85,7 @@ TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJ
target[offset] = .08;
if (accelerating) {
planner.initialize();
planner.plan(initial, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
planner.plan(initial, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
ASSERT_LT(planner.getTwistBase().norm(), 1e-3);
ASSERT_GT(planner.getAccelerationBase().norm(), 1e-3);
} else {
@ -95,7 +95,7 @@ TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJ
Twist previous = planner.getTwistBase();
Twist previous_acceleration = planner.getAccelerationBase();
for (int i = 0; i < 1000; ++i) {
const auto v = planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto v = planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const Twist acceleration = (v - previous) / dt;
const Twist jerk = (acceleration - previous_acceleration) / dt;
EXPECT_LE(acceleration.norm(), 3 + 1e-6);
@ -113,7 +113,7 @@ TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJ
// has the same direction, including legacy linear streaming.
target *= 1.5;
for (int i = 0; i < 500; ++i) {
EXPECT_GE(planner.plan(target, LgvCartesianFrame::Base, dt,
EXPECT_GE(planner.plan(target, CartesianFrame::Base, dt,
Eigen::Matrix3d::Identity())[offset], .08 - 1e-9);
}
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-9);
@ -122,7 +122,7 @@ TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJ
target = -target;
max_acceleration = max_jerk = 0;
for (int i = 0; i < 1000; ++i) {
planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
max_acceleration = std::max(max_acceleration, planner.getAccelerationBase().norm());
max_jerk = std::max(max_jerk, planner.getJerkBase().norm());
}
@ -135,13 +135,13 @@ TEST(LgvSCurvePlannerReversal, NonCollinearChangePreservesVectorAccelerationAndJ
}
}
TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) {
TEST(SCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPeriodicallyStop) {
for (bool continuous : {true, false}) {
for (int offset : {0, 3}) {
for (double max_velocity : {.08, 1.}) {
SCOPED_TRACE(::testing::Message() << "continuous=" << continuous
<< " angular=" << (offset == 3) << " vmax=" << max_velocity);
LgvSCurvePlanner planner;
SCurvePlanner planner;
planner.setLinearConstraints(max_velocity, 3, 10);
planner.setAngularConstraints(max_velocity, 3, 10);
planner.setContinuousLinearReversal(continuous);
@ -157,7 +157,7 @@ TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPerio
rotation(0, 0) = rotation(1, 1) = std::cos(angle);
rotation(0, 1) = -std::sin(angle);
rotation(1, 0) = std::sin(angle);
const Twist v = planner.plan(target, LgvCartesianFrame::Tool, dt, rotation);
const Twist v = planner.plan(target, CartesianFrame::Tool, dt, rotation);
const Twist a = (v - previous) / dt;
const Twist j = (a - previous_acceleration) / dt;
EXPECT_LE(v.norm(), max_velocity + 1e-9);
@ -169,7 +169,7 @@ TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPerio
}
EXPECT_GT(min_speed, .072);
for (int i = 0; i < 1500; ++i) {
const Twist v = planner.plan(Twist::Zero(), LgvCartesianFrame::Base, dt,
const Twist v = planner.plan(Twist::Zero(), CartesianFrame::Base, dt,
Eigen::Matrix3d::Identity());
const Twist a = (v - previous) / dt;
EXPECT_LE(a.norm(), 3 + 1e-6);
@ -184,77 +184,77 @@ TEST(LgvSCurvePlannerReversal, SmallDirectionStepAndRotatingToolDoNotJumpOrPerio
}
}
TEST(LgvSCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
TEST(SCurvePlannerReversal, SwitchingToStreamingPreservesNegativePhysicalVelocity) {
for (const int reverse_ticks : {150, 250, 500}) {
SCOPED_TRACE(reverse_ticks);
LgvSCurvePlanner reference;
SCurvePlanner reference;
reference.setLinearConstraints(1, 3, 10);
reference.initialize(y(.08));
for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
for (int i = 0; i < reverse_ticks; ++i) reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
ASSERT_LT(reference.getTwistBase().y(), 0);
auto streaming = reference;
streaming.setContinuousLinearReversal(false);
EXPECT_NEAR((streaming.getTwistBase() - reference.getTwistBase()).norm(), 0, 1e-12);
for (int i = 0; i < 500; ++i) {
const auto expected = reference.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto actual = streaming.plan(y(-.08), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto expected = reference.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto actual = streaming.plan(y(-.08), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
EXPECT_NEAR((actual - expected).norm(), 0, 1e-9);
EXPECT_LE(streaming.getJerkBase().norm(), 10 + 1e-6);
}
}
}
TEST(LgvSCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) {
LgvSCurvePlanner planner;
TEST(SCurvePlannerReversal, SmallDirectionChangeWithLowJerkEventuallyReachesTarget) {
SCurvePlanner planner;
planner.setLinearConstraints(1, 3, .01);
planner.initialize(y(.08));
Twist target = Twist::Zero();
target.x() = .08 * std::sin(1e-4);
target.y() = .08 * std::cos(1e-4);
for (int i = 0; i < 1000; ++i) {
planner.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
planner.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
EXPECT_LE(planner.getAccelerationBase().norm(), 3 + 1e-7);
EXPECT_LE(planner.getJerkBase().norm(), .01 + 1e-7);
}
EXPECT_NEAR((planner.getTwistBase() - target).norm(), 0, 1e-10);
}
TEST(LgvSCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) {
LgvSCurvePlanner planner;
TEST(SCurvePlannerReversal, ChangingPeriodUsesAccelerationSampleTimesForJerk) {
SCurvePlanner planner;
planner.setLinearConstraints(1, 3, 10);
for (int i = 0; i < 100; ++i) {
const double period = i % 2 ? .0005 : .001;
planner.plan(y(.08), LgvCartesianFrame::Base, period, Eigen::Matrix3d::Identity());
planner.plan(y(.08), CartesianFrame::Base, period, Eigen::Matrix3d::Identity());
EXPECT_NEAR(planner.getJerkBase().y(), 10, 1e-7);
}
}
TEST(LgvSCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) {
LgvSCurvePlanner actual;
TEST(SCurvePlannerReversal, SmallNonzeroAccelerationCannotMakeInvalidProfileLookSettled) {
SCurvePlanner actual;
actual.setLinearConstraints(.05, 1e-6, .001);
actual.initialize(y(.0499995));
actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
auto reference = actual;
// Removing the small acceleration with this jerk would exceed vmax.
// A numerical "near zero" test must not accept and freeze this state.
EXPECT_THROW(actual.setLinearConstraints(.05, 1e-6, 1e-8), std::runtime_error);
for (int i = 0; i < 1000; ++i) {
const Twist a = actual.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const Twist b = reference.plan(y(.05), LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const Twist a = actual.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const Twist b = reference.plan(y(.05), CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
EXPECT_DOUBLE_EQ((a - b).norm(), 0);
EXPECT_LE(actual.getJerkBase().norm(), .001 + 1e-7);
}
EXPECT_NEAR(actual.getTwistBase().y(), .05, 1e-12);
}
TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) {
LgvSCurvePlanner seed;
TEST(SCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureState) {
SCurvePlanner seed;
seed.setLinearConstraints(1, 3, 10);
seed.setAngularConstraints(1, 3, 10);
Twist target = y(.08);
target[5] = .12;
for (int i = 0; i < 80; ++i)
seed.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
seed.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto expect_unchanged = [&](auto operation) {
auto expected = seed;
@ -269,8 +269,8 @@ TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureS
};
compare_state();
for (int i = 0; i < 200; ++i) {
const auto expected_twist = expected.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto actual_twist = actual.plan(target, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto expected_twist = expected.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
const auto actual_twist = actual.plan(target, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity());
EXPECT_DOUBLE_EQ((actual_twist - expected_twist).norm(), 0);
compare_state();
}
@ -286,7 +286,7 @@ TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureS
expect_unchanged([&](auto& p) { p.setLinearConstraints(limits[0], limits[1], limits[2]); });
expect_unchanged([&](auto& p) { p.setAngularConstraints(limits[0], limits[1], limits[2]); });
}
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); });
expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Base, invalid, Eigen::Matrix3d::Identity()); });
if (invalid != 0) {
expect_unchanged([&](auto& p) { p.setLinearTargetReplanThreshold(invalid); });
expect_unchanged([&](auto& p) { p.setAngularTargetReplanThreshold(invalid); });
@ -297,11 +297,11 @@ TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureS
Twist invalid_twist = target;
invalid_twist[index] = invalid;
expect_unchanged([&](auto& p) { p.initialize(invalid_twist); });
expect_unchanged([&](auto& p) { p.plan(invalid_twist, LgvCartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); });
expect_unchanged([&](auto& p) { p.plan(invalid_twist, CartesianFrame::Base, dt, Eigen::Matrix3d::Identity()); });
}
Eigen::Matrix3d invalid_rotation = Eigen::Matrix3d::Identity();
invalid_rotation(1, 2) = invalid;
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Tool, dt, invalid_rotation); });
expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Tool, dt, invalid_rotation); });
}
// Over-limit initialization must not clamp only the internal scalar or
// reset linear motion before discovering an invalid angular component.
@ -312,8 +312,8 @@ TEST(LgvSCurvePlannerReversal, InvalidInputThrowsWithoutChangingCurrentOrFutureS
}
expect_unchanged([&](auto& p) { p.setLinearConstraints(.001, 3, 10); });
expect_unchanged([&](auto& p) { p.setLinearConstraints(1, .01, 10); });
expect_unchanged([&](auto& p) { p.plan(target, LgvCartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); });
expect_unchanged([&](auto& p) { p.plan(target, static_cast<LgvCartesianFrame>(9), dt, Eigen::Matrix3d::Identity()); });
expect_unchanged([&](auto& p) { p.plan(target, CartesianFrame::Base, 1e-300, Eigen::Matrix3d::Identity()); });
expect_unchanged([&](auto& p) { p.plan(target, static_cast<CartesianFrame>(9), dt, Eigen::Matrix3d::Identity()); });
}
}

View File

@ -5,7 +5,6 @@
#include <Eigen/Dense>
#include "algorithms/motion_planner/base_motion/cartesian_velocity/twist_limiter/include/cartesian_twist_limiter.h"
#include "common/types/arm/arm_types.h"
namespace cmvr::common::math {
@ -83,12 +82,6 @@ inline device::CartesianVelocity vectorToVelocity(const Eigen::Matrix<double, 6,
return {velocity[0], velocity[1], velocity[2], velocity[3], velocity[4], velocity[5]};
}
inline cmvr::CartesianFrame toPlannerFrame(const device::FrameType frame)
{
return frame == device::FrameType::Tool ? cmvr::CartesianFrame::Tool
: cmvr::CartesianFrame::Base;
}
} // namespace cmvr::common::math
#endif // CMVR_ES_COMMON_MATH_TRANSFORM_MATH_H

View File

@ -57,6 +57,25 @@ arm {
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
@ -66,12 +85,6 @@ arm {
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
@ -116,9 +129,17 @@ arm {
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
@ -217,12 +238,23 @@ arm {
}
motion {
move_j {
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
ignored_pairs { first: "L_WRIST_P_S" second: "L_WRIST_R_S" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
@ -268,9 +300,17 @@ arm {
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01

View File

@ -56,6 +56,26 @@ arm {
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/gen2/collision/robot_collision.urdf"
ignored_pairs { first: "arm_link_5_2" second: "arm_link_7_2" }
ignored_pairs { first: "body_link" second: "arm_link_2_2" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
@ -65,12 +85,6 @@ arm {
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
@ -115,9 +129,17 @@ arm {
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01

View File

@ -57,7 +57,28 @@ arm {
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
# 轨迹关节位置限位检查的数值容差,单位 rad;0 表示严格检查。
joint_limit_tolerance_rad: 0.00001
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
@ -66,12 +87,6 @@ arm {
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
@ -116,9 +131,17 @@ arm {
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01

View File

@ -58,6 +58,25 @@ arm {
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
@ -67,12 +86,6 @@ arm {
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
@ -111,15 +124,23 @@ arm {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 2.0
linear_acceleration_max: 15.0
linear_jerk_max: 60.0
linear_jerk_max: 500.0
angular_velocity_max: 1.0
angular_acceleration_max: 5.0
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.005

View File

@ -58,6 +58,25 @@ arm {
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaoyan_description/dual_arm_collision.urdf"
ignored_pairs { first: "R_WRIST_P_S" second: "R_WRIST_R_S" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
@ -67,12 +86,6 @@ arm {
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
@ -111,15 +124,23 @@ arm {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 0.8
linear_acceleration_max: 10.0
linear_jerk_max: 60.0
linear_jerk_max: 200.0
angular_velocity_max: 1.0
angular_acceleration_max: 5.0
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
adaptive_speed {
# 启用接近关节限位时的提前降速;降低后的目标仍经过 S 曲线平滑。
# 关闭此开关不影响失解后的制动。
enable: true
# 预判时间,单位秒;0.15 即 150 ms,实际窗口还会考虑 S 曲线停止时间。
lookahead_s: 0.15
# 允许速度低于原目标的 10% 时,平滑停稳后报错;0 关闭此阈值。
# 这是停止阈值,不会强行维持最低速度,也不限制启动阶段的瞬时速度。
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01

View File

@ -1,7 +1,7 @@
# Joint-only minimal configuration; MoveJ follows joint_names order.
arm {
robot_arms {
id: "right_ethercat_arm"
motor {
motor_system_id: "dual_arm_ethercat_motors"
motor_group_ids: "dual_arm_ethercat_motors"
@ -14,296 +14,50 @@ arm {
joint_names: "right_arm_J6"
joint_names: "right_arm_J7"
upd_freq: 1000
buffer_size: 50
default_vel: 1.0
default_acc: 2.0
}
kinematics {
pinocchio_dls_ik_solver {
urdf_path: "model/gen2/robot.urdf"
base_frame_name: "body_link"
flange_frame_name: "arm_link_7_2"
max_iters: 100
pos_eps: 1e-6
rot_eps: 1e-6
damping: 1e-6
joint_limit_policy {
limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "right_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
joints { joint_name: "right_arm_J7" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
}
soft_limit {
enable: true
margin_ratio: 0.01
min_margin_rad: 0.01
}
avoidance {
enable: false
gain: 0.2
margin_ratio: 0.15
max_push: 0.25
}
}
}
}
motion {
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.1
}
}
move_j {
# MoveJ 轨迹完成后等待关节稳定的最长时间,单位为秒。
settle_timeout_s: 2.0
# MoveJ 完成时允许的最大关节位置误差,单位为弧度。
settle_position_tolerance_rad: 0.002
# MoveJ 完成时允许的最大关节速度,单位为弧度/秒。
settle_velocity_tolerance_rad_s: 0.02
# 位置和速度连续满足条件的采样次数。
settle_stable_sample_count: 3
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
pinocchio_cartesian_motion_planner {
sample_period_s: 0.001
position_gain: 4.0
rotation_gain: 4.0
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.01
}
joint_continuity_check {
enable: true
max_joint_delta_rad: 0.05
max_joint_velocity_rad_s: 10.0
max_joint_acceleration_rad_s2: 5000.0
}
cartesian_step_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 45.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 45.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
}
speed_l {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 0.55
linear_acceleration_max: 5.0
linear_jerk_max: 10.0
angular_velocity_max: 1.0
angular_acceleration_max: 5.0
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.01
}
joint_velocity_check {
enable: true
max_joint_velocity_rad_s: 30.0
max_joint_acceleration_rad_s2: 10000.0
}
cartesian_velocity_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 5.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 5.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
speed_l_controller {
cartesian_velocity_controller {
control_period_s: 0.001
stop_twist_norm: 1e-9
stop_command_velocity_norm: 1e-3
stop_measured_velocity_norm: 1e-2
stop_acceleration: 10
# 等待 Cartesian 速度运动停止的最长时间,单位为秒。
stop_timeout_s: 2.0
}
}
}
}
}
robot_arms {
id: "left_ethercat_arm"
motor {
motor_system_id: "dual_arm_ethercat_motors"
motor_group_ids: "dual_arm_ethercat_motors"
dof: 7
joint_names: "left_arm_J1"
joint_names: "left_arm_J2"
joint_names: "left_arm_J3"
joint_names: "left_arm_J4"
joint_names: "left_arm_J5"
joint_names: "left_arm_J6"
joint_names: "left_arm_J7"
upd_freq: 1000
buffer_size: 50
default_vel: 1.0
default_acc: 2.0
}
kinematics {
pinocchio_dls_ik_solver {
urdf_path: "model/gen2/robot.urdf"
base_frame_name: "body_link"
flange_frame_name: "arm_link_7"
max_iters: 100
pos_eps: 1e-6
rot_eps: 1e-6
damping: 1e-6
joint_limit_policy {
limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "left_arm_J1" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J2" q_lb: -1.64 q_ub: 1.64 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J3" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J4" q_lb: -1.60 q_ub: 1.60 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J5" q_lb: -3.14 q_ub: 3.14 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J6" q_lb: -0.37 q_ub: 0.79 qd: 5.0 qdd: 10.0 }
joints { joint_name: "left_arm_J7" q_lb: -0.61 q_ub: 0.58 qd: 5.0 qdd: 10.0 }
}
soft_limit {
enable: true
margin_ratio: 0.01
min_margin_rad: 0.01
}
avoidance {
enable: false
gain: 0.2
margin_ratio: 0.15
max_push: 0.25
}
}
}
}
motion {
move_j {
toppra_joint_motion_planner {
path_type: TOPPRA_PATH_TYPE_QUINTIC
sample_period_s: 0.001
grid_size: 150
high_grid_size: 300
}
}
move_l {
pinocchio_cartesian_motion_planner {
sample_period_s: 0.001
position_gain: 4.0
rotation_gain: 4.0
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.01
}
joint_continuity_check {
enable: true
max_joint_delta_rad: 0.05
max_joint_velocity_rad_s: 10.0
max_joint_acceleration_rad_s2: 5000.0
}
cartesian_step_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 45.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 45.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
}
speed_l {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 0.55
linear_acceleration_max: 5.0
linear_jerk_max: 10.0
angular_velocity_max: 1.0
angular_acceleration_max: 5.0
angular_jerk_max: 12.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
linear_reverse_cos_threshold: -0.8660254037844386
linear_reverse_switch_speed_threshold: 1e-3
enforce_joint_acceleration_limits: true
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.01
}
joint_velocity_check {
enable: true
max_joint_velocity_rad_s: 30.0
max_joint_acceleration_rad_s2: 10000.0
}
cartesian_velocity_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 5.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 5.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
speed_l_controller {
cartesian_velocity_controller {
control_period_s: 0.001
stop_twist_norm: 1e-9
stop_command_velocity_norm: 1e-3
stop_measured_velocity_norm: 1e-2
stop_acceleration: 10
}
}
}
id: "left_ethercat_arm"
motor {
motor_system_id: "dual_arm_ethercat_motors"
motor_group_ids: "dual_arm_ethercat_motors"
dof: 7
joint_names: "left_arm_J1"
joint_names: "left_arm_J2"
joint_names: "left_arm_J3"
joint_names: "left_arm_J4"
joint_names: "left_arm_J5"
joint_names: "left_arm_J6"
joint_names: "left_arm_J7"
upd_freq: 1000
}
motion {
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.1
}
}
move_j {
settle_timeout_s: 2.0
settle_position_tolerance_rad: 0.002
settle_velocity_tolerance_rad_s: 0.02
settle_stable_sample_count: 3
}
}
}
}

View File

@ -1,5 +1,4 @@
# Three-axis joint-only group. MoveJ positions follow joint_names order (rad).
# CAN commands are sent per axis; this is not hardware-triggered synchronization.
# Joint-only minimal configuration; MoveJ follows joint_names order.
arm {
robot_arms {
id: "lingkong_arm"

View File

@ -1,5 +1,4 @@
# Three-axis joint-only group. MoveJ positions follow joint_names order (rad).
# CAN commands are sent per axis; this is not hardware-triggered synchronization.
# Joint-only minimal configuration; MoveJ follows joint_names order.
arm {
robot_arms {
id: "lingkong_mixed_arm"

View File

@ -1,8 +1,7 @@
# 双臂七轴纯关节运动配置;MoveJ 顺序遵循各臂 joint_names。
# Joint-only minimal configuration; MoveJ follows joint_names order.
arm {
robot_arms {
id: "right_tchl_arm"
motor {
motor_system_id: "tchl_dual_arm_motors"
motor_group_ids: "tchl_dual_arm_motors"
@ -16,15 +15,13 @@ arm {
joint_names: "right_arm_J7"
upd_freq: 1000
}
motion {
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
control_point_spacing_rad: 0.1
}
}
move_j {
settle_timeout_s: 2.0
settle_position_tolerance_rad: 0.002
@ -35,7 +32,6 @@ arm {
}
robot_arms {
id: "left_tchl_arm"
motor {
motor_system_id: "tchl_dual_arm_motors"
motor_group_ids: "tchl_dual_arm_motors"
@ -49,15 +45,13 @@ arm {
joint_names: "left_arm_J7"
upd_freq: 1000
}
motion {
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
control_point_spacing_rad: 0.1
}
}
move_j {
settle_timeout_s: 2.0
settle_position_tolerance_rad: 0.002

View File

@ -0,0 +1,331 @@
# xiaozhao 双臂 MuJoCo 控制,所有关节位置使用 rad。
# TCP 与第七连杆同向,局部偏移左 (0.007, 0.23, -0.045) m、右 (0.007, -0.23, -0.045) m。
# 两臂分别规划 MoveP,检测本臂与固定基座的碰撞体,最小间距为 20 mm。
arm {
robot_arms {
id: "xiaozhao_left_arm"
motor {
motor_system_id: "xiaozhao_left_arm_motors"
motor_group_ids: "xiaozhao_left_arm_motors"
dof: 7
joint_names: "joint1-left"
joint_names: "joint2-left"
joint_names: "joint3-left"
joint_names: "joint4-left"
joint_names: "joint5-left"
joint_names: "joint6-left"
joint_names: "joint7-left"
upd_freq: 1000
buffer_size: 50
default_vel: 0.5
default_acc: 2.0
}
kinematics {
pinocchio_qp_ik_solver {
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
base_frame_name: "base_link"
flange_frame_name: "link7-left"
tcp_frame_name: "tcp-left"
lambda: 1e-4
w_posrot: 0.5
max_iters: 100
tol: 1e-6
qp_time_limit: 1e-2
joint_limit_policy {
limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-left" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
}
soft_limit {
enable: true
margin_ratio: 0.01
min_margin_rad: 0.01
}
avoidance {
enable: false
}
}
}
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs { first: "link5-left" second: "link7-left" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
settle_timeout_s: 3.0
settle_position_tolerance_rad: 0.002
settle_velocity_tolerance_rad_s: 0.02
settle_stable_sample_count: 3
}
move_l {
pinocchio_cartesian_motion_planner {
sample_period_s: 0.001
position_gain: 4.0
rotation_gain: 4.0
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.005
}
joint_continuity_check {
enable: true
max_joint_delta_rad: 0.05
max_joint_velocity_rad_s: 1.0
max_joint_acceleration_rad_s2: 5.0
}
cartesian_step_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 10.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 10.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
}
speed_l {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 0.1
linear_acceleration_max: 0.5
linear_jerk_max: 5.0
angular_velocity_max: 0.5
angular_acceleration_max: 2.0
angular_jerk_max: 10.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
enforce_joint_acceleration_limits: true
adaptive_speed {
enable: true
lookahead_s: 0.15
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.005
}
joint_velocity_check {
enable: true
max_joint_velocity_rad_s: 1.0
max_joint_acceleration_rad_s2: 5.0
}
cartesian_velocity_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 10.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 10.0
min_desired_linear_speed: 0.01
min_desired_angular_speed: 1e-4
}
}
speed_l_controller {
cartesian_velocity_controller {
control_period_s: 0.001
stop_twist_norm: 1e-9
stop_command_velocity_norm: 1e-3
stop_measured_velocity_norm: 1e-2
stop_acceleration: 2.0
stop_timeout_s: 2.0
}
}
}
}
}
robot_arms {
id: "xiaozhao_right_arm"
motor {
motor_system_id: "xiaozhao_right_arm_motors"
motor_group_ids: "xiaozhao_right_arm_motors"
dof: 7
joint_names: "joint1-right"
joint_names: "joint2-right"
joint_names: "joint3-right"
joint_names: "joint4-right"
joint_names: "joint5-right"
joint_names: "joint6-right"
joint_names: "joint7-right"
upd_freq: 1000
buffer_size: 50
default_vel: 0.5
default_acc: 2.0
}
kinematics {
pinocchio_qp_ik_solver {
urdf_path: "model/xiaozhao/urdf/xiaozhao.urdf"
base_frame_name: "base_link"
flange_frame_name: "link7-right"
tcp_frame_name: "tcp-right"
lambda: 1e-4
w_posrot: 0.5
max_iters: 100
tol: 1e-6
qp_time_limit: 1e-2
joint_limit_policy {
limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
}
soft_limit {
enable: true
margin_ratio: 0.01
min_margin_rad: 0.01
}
avoidance {
enable: false
}
}
}
}
motion {
joint_path {
algorithm: RRT_CONNECT
rrt_connect {
timeout_s: 2.0
range_rad: 0.2
collision_check_step_rad: 0.02
}
collision_checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs { first: "link5-right" second: "link7-right" }
}
minimum_distance_m: 0.01
}
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
settle_timeout_s: 3.0
settle_position_tolerance_rad: 0.002
settle_velocity_tolerance_rad_s: 0.02
settle_stable_sample_count: 3
}
move_l {
pinocchio_cartesian_motion_planner {
sample_period_s: 0.001
position_gain: 4.0
rotation_gain: 4.0
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.005
}
joint_continuity_check {
enable: true
max_joint_delta_rad: 0.05
max_joint_velocity_rad_s: 1.0
max_joint_acceleration_rad_s2: 5.0
}
cartesian_step_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 10.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 10.0
min_desired_linear_speed: 1e-4
min_desired_angular_speed: 1e-4
}
}
}
speed_l {
pinocchio_cartesian_motion_planner {
linear_velocity_max: 0.1
linear_acceleration_max: 0.5
linear_jerk_max: 5.0
angular_velocity_max: 0.5
angular_acceleration_max: 2.0
angular_jerk_max: 10.0
linear_target_replan_threshold: 1e-4
angular_target_replan_threshold: 1e-4
enforce_joint_acceleration_limits: true
adaptive_speed {
enable: true
lookahead_s: 0.15
min_speed_ratio: 0.10
}
line_deviation_check {
enable: true
line_deviation_warn_m: 0.01
line_deviation_stop_m: 0.03
line_direction_warn_deg: 20.0
line_direction_stop_deg: 45.0
line_direction_reset_deg: 10.0
line_check_min_distance_m: 0.005
}
joint_velocity_check {
enable: true
max_joint_velocity_rad_s: 1.0
max_joint_acceleration_rad_s2: 5.0
}
cartesian_velocity_feasibility_check {
enable: true
min_linear_speed_ratio: 0.2
max_linear_direction_deviation_deg: 10.0
min_angular_speed_ratio: 0.2
max_angular_direction_deviation_deg: 10.0
min_desired_linear_speed: 0.01
min_desired_angular_speed: 1e-4
}
}
speed_l_controller {
cartesian_velocity_controller {
control_period_s: 0.001
stop_twist_norm: 1e-9
stop_command_velocity_norm: 1e-3
stop_measured_velocity_norm: 1e-2
stop_acceleration: 2.0
stop_timeout_s: 2.0
}
}
}
}
}
}

View File

@ -0,0 +1,35 @@
# xiaozhao 三轴颈部按 RobotArm 注册,仅使用关节空间控制。
# MoveJ 目标顺序为 neck-joint1、neck-joint2、neck-joint3,单位为弧度。
arm {
robot_arms {
id: "xiaozhao_head"
motor {
motor_system_id: "xiaozhao_head_motors"
motor_group_ids: "xiaozhao_head_motors"
dof: 3
joint_names: "neck-joint1"
joint_names: "neck-joint2"
joint_names: "neck-joint3"
upd_freq: 1000
buffer_size: 50
default_vel: 0.25
default_acc: 0.5
}
motion {
joint_trajectory_smoother {
sample_period_s: 0.001
quintic_bspline {
control_point_spacing_rad: 0.05
}
}
move_j {
settle_timeout_s: 3.0
settle_position_tolerance_rad: 0.002
settle_velocity_tolerance_rad_s: 0.02
settle_stable_sample_count: 3
}
}
}
}

View File

@ -0,0 +1,63 @@
# xiaozhao 触屏仿真相机。手相机保持 1280x720 点击像素坐标。
# 头部相机使用 2560x1440,提高 16 mm 屏幕 Tag 的像素尺寸与姿态估计稳定性。
camera {
cameras {
id: "mujoco_hand_cam"
mujoco {
world_id: "mujoco_world"
camera_name: "hand_cam"
render {
width: 1280
height: 720
fps: 30
stream_mode: STREAM_MODE_RGBD
}
encoder {
width: 480
height: 320
fps: 30
codec: "H264"
enable_stream_timestamp: true
buffer_size: 30
}
consume_new_frame_only: false
viewer_pip {
enable: false
left: -10
bottom: 10
width: 320
height: 180
}
}
}
cameras {
id: "mujoco_external_touch_cam"
mujoco {
world_id: "mujoco_world"
camera_name: "external_touch_cam"
render {
width: 2560
height: 1440
fps: 30
stream_mode: STREAM_MODE_RGBD
}
encoder {
width: 480
height: 320
fps: 30
codec: "H264"
enable_stream_timestamp: true
buffer_size: 30
}
consume_new_frame_only: false
viewer_pip {
enable: false
left: 10
bottom: 10
width: 320
height: 180
}
}
}
}

View File

@ -70,7 +70,7 @@ dexhand {
tactile_finger: "INDEX"
tactile_region: "TIP"
sensor_name: "Paxini Gen3末端压力"
polling_read_mode: PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE
polling_read_mode: LEGACY_PX_6AX_GEN3_POLLING_READ_MODE_RESULTANT_FORCE
auto_calibrate: false
}
}

View File

@ -0,0 +1,87 @@
# MuJoCo 仿真限值:位置范围与 xiaozhao/config/joint_limits.csv 一致。
# URDF 的 velocity/effort 为占位值,速度和加速度在这里显式设置。
motor {
id: "xiaozhao_motors"
motor_groups {
id: "xiaozhao_left_arm_motors"
bus_type: MOTOR_BUS_MUJOCO
vendor: MOTOR_VENDOR_MUJOCO
protocol: MOTOR_PROTOCOL_MUJOCO
mujoco {
world_id: "mujoco_world"
}
joint_limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-left" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-left" q_lb: 0 q_ub: 2.35 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-left" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-left" q_lb: -0.785 q_ub: 0.45 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-left" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
}
motors {
motors { id: 1 joint_name: "joint1-left" }
motors { id: 2 joint_name: "joint2-left" }
motors { id: 3 joint_name: "joint3-left" }
motors { id: 4 joint_name: "joint4-left" }
motors { id: 5 joint_name: "joint5-left" }
motors { id: 6 joint_name: "joint6-left" }
motors { id: 7 joint_name: "joint7-left" }
}
}
motor_groups {
id: "xiaozhao_right_arm_motors"
bus_type: MOTOR_BUS_MUJOCO
vendor: MOTOR_VENDOR_MUJOCO
protocol: MOTOR_PROTOCOL_MUJOCO
mujoco {
world_id: "mujoco_world"
}
joint_limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "joint1-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint2-right" q_lb: -1.57 q_ub: 1.57 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint3-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint4-right" q_lb: -2.35 q_ub: 0 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint5-right" q_lb: -3.14 q_ub: 3.14 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint6-right" q_lb: -0.45 q_ub: 0.785 qd: 1.0 qdd: 5.0 }
joints { joint_name: "joint7-right" q_lb: -1.05 q_ub: 1.05 qd: 1.0 qdd: 5.0 }
}
motors {
motors { id: 1 joint_name: "joint1-right" }
motors { id: 2 joint_name: "joint2-right" }
motors { id: 3 joint_name: "joint3-right" }
motors { id: 4 joint_name: "joint4-right" }
motors { id: 5 joint_name: "joint5-right" }
motors { id: 6 joint_name: "joint6-right" }
motors { id: 7 joint_name: "joint7-right" }
}
}
motor_groups {
id: "xiaozhao_head_motors"
bus_type: MOTOR_BUS_MUJOCO
vendor: MOTOR_VENDOR_MUJOCO
protocol: MOTOR_PROTOCOL_MUJOCO
mujoco {
world_id: "mujoco_world"
}
joint_limits {
enable: true
source: JOINT_LIMIT_SOURCE_CUSTOM
joints { joint_name: "neck-joint1" q_lb: -1.57 q_ub: 1.57 qd: 0.5 qdd: 2.0 }
joints { joint_name: "neck-joint2" q_lb: -1.57 q_ub: 0.44 qd: 0.5 qdd: 2.0 }
joints { joint_name: "neck-joint3" q_lb: -0.44 q_ub: 0.44 qd: 0.5 qdd: 2.0 }
}
motors {
motors { id: 1 joint_name: "neck-joint1" }
motors { id: 2 joint_name: "neck-joint2" }
motors { id: 3 joint_name: "neck-joint3" }
}
}
}

View File

@ -0,0 +1,7 @@
worlds {
id: "mujoco_world"
model_path: "model/xiaozhao/xml/scene.xml"
timestep_s: 0.001
realtime_factor: 1.0
require_actuator: true
}

View File

@ -0,0 +1,17 @@
touch {
touches {
id: "paxini_tip_1"
px_6ax_genx_can {
# 系统预先配置 can0 为 1 Mbps;设备以约 2 ms 为目标采读并主动发送有效值,非严格周期。
channel_id: 0
force_can_id: 0x600
# 按主机本地接收时间计算的最大有效期;超过此时间无有效报文则报不可用。
max_sample_age_ms: 300
}
}
touches {
id: "mujoco_zero_touch"
zero_sim {}
}
}

View File

@ -2,10 +2,53 @@ device_manager {
name: "cmvr_es"
version: "0.1"
description: "cmvr edge system version 0.1"
# xiaozhao 双臂、颈部与右臂触屏仿真:先创建 world,再创建电机、机械臂、viewer 和传感器。
devices {
id: "mujoco_world"
type: DEVICE_TYPE_MUJOCO_WORLD
config_file: "devices/mujoco/right_arm_eye_to_hand_world.pb.txt"
config_file: "devices/mujoco/xiaozhao_world.pb.txt"
enable: false
}
devices {
id: "xiaozhao_left_arm_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/xiaozhao_motors.pb.txt"
enable: false
}
devices {
id: "xiaozhao_right_arm_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/xiaozhao_motors.pb.txt"
enable: false
}
devices {
id: "xiaozhao_head_motors"
type: DEVICE_TYPE_MOTOR_SYSTEM
config_file: "devices/motor/xiaozhao_motors.pb.txt"
enable: false
}
devices {
id: "xiaozhao_left_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_arm.pb.txt"
enable: false
}
devices {
id: "xiaozhao_right_arm"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_arm.pb.txt"
enable: false
}
devices {
id: "xiaozhao_head"
type: DEVICE_TYPE_ROBOT_ARM
config_file: "devices/arm/xiaozhao_head.pb.txt"
enable: false
}
@ -33,14 +76,14 @@ device_manager {
devices {
id: "mujoco_hand_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
config_file: "devices/camera/xiaozhao_camera.pb.txt"
enable: false
}
devices {
id: "mujoco_external_touch_cam"
type: DEVICE_TYPE_CAMERA
config_file: "devices/camera/camera.pb.txt"
config_file: "devices/camera/xiaozhao_camera.pb.txt"
enable: false
}
@ -82,15 +125,15 @@ device_manager {
devices {
id: "paxini_tip_1"
type: DEVICE_TYPE_DEXHAND
config_file: "devices/dexhand/dexhand.pb.txt"
type: DEVICE_TYPE_TOUCH
config_file: "devices/touch/touch.pb.txt"
enable: false
}
devices {
id: "mujoco_zero_touch_dexhand"
type: DEVICE_TYPE_DEXHAND
config_file: "devices/dexhand/dexhand.pb.txt"
id: "mujoco_zero_touch"
type: DEVICE_TYPE_TOUCH
config_file: "devices/touch/touch.pb.txt"
enable: false
}

View File

@ -1,11 +1,12 @@
task_manager {
# xiaozhao 触屏仿真:初始化时头部 MoveJ 到预设位,随后等待 gRPC touch 请求。
tasks {
id: "touch_screen"
type: TASK_TYPE_TOUCH_SCREEN
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.001
config_file: "tasks/touch_screen_task/touch_screen_task.pb.txt"
enable: false
config_file: "tasks/touch_screen_task/touch_screen_task_xiaozhao_mujoco.pb.txt"
enable: true
}
tasks {
id: "grpc_server"
@ -22,6 +23,23 @@ task_manager {
config_file: "tasks/self_collision_task/self_collision_task.pb.txt"
enable: false
}
# 小赵 MuJoCo 当前仅启用右臂实时自碰撞监控。
tasks {
id: "xiaozhao_left_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_left.pb.txt"
enable: false
}
tasks {
id: "xiaozhao_right_arm_self_collision"
type: TASK_TYPE_SELF_COLLISION
run_mode: TASK_RUN_MODE_PERIODIC_STEP
control_period_s: 0.002
config_file: "tasks/self_collision_task/self_collision_task_xiaozhao_right.pb.txt"
enable: true
}
tasks {
id: "quic_edge"
type: TASK_TYPE_QUIC_EDGE

View File

@ -0,0 +1,33 @@
# 小赵左臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
self_collision_task {
id: "xiaozhao_left_arm_self_collision"
arm_id: "xiaozhao_left_arm"
checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs {
first: "link5-left"
second: "link7-left"
}
}
sampling {
max_geometry_displacement_m: 0.002
max_check_period_s: 0.01
}
# 距离阈值作用于简化碰撞体之间的最小间距。
safety {
warning_distance_m: 0.02
stop_distance_m: 0.005
}
recovery {
clear_distance_m: 0.025
stable_period_s: 0.1
max_joint_velocity_rad_s: 0.15
max_joint_acceleration_rad_s2: 0.3
history_duration_s: 10.0
max_distance_regression_m: 0.001
}
}

View File

@ -0,0 +1,33 @@
# 小赵右臂独立自碰撞检测:仅本臂 + 固定 base,排除另一臂与活动头部。
self_collision_task {
id: "xiaozhao_right_arm_self_collision"
arm_id: "xiaozhao_right_arm"
checker {
urdf_path: "model/xiaozhao/collision/xiaozhao_collision.urdf"
ignored_pairs {
first: "link5-right"
second: "link7-right"
}
}
sampling {
max_geometry_displacement_m: 0.002
max_check_period_s: 0.01
}
# 距离阈值作用于简化碰撞体之间的最小间距。
safety {
warning_distance_m: 0.02
stop_distance_m: 0.005
}
recovery {
clear_distance_m: 0.025
stable_period_s: 0.1
max_joint_velocity_rad_s: 0.15
max_joint_acceleration_rad_s2: 0.3
history_duration_s: 10.0
max_distance_regression_m: 0.001
}
}

View File

@ -7,15 +7,19 @@ touch_screen_task {
devices {
arm_id: "right_arm"
dexhand_id: "paxini_tip_1"
# devices/touch/touch.pb.txt 中的 PX6AXGenXCan,使用 CAN 合力数据,单位为 N。
touch_id: "paxini_tip_1"
# 手部相机和外部相机的 DeviceManager ID。
camera_id: "right_hand_cam"
external_camera_id: "left_hand_cam"
}
initialization {
# 开始前使用 MoveJ 回到初始关节位置。
before_start: false
# 正常完成后使用 MoveP 回到初始关节位置。
after_finish: true
after_failure: true
joint_positions { joint_name: "R_SHOULDER_P" rad: -0.338732 }
joint_positions { joint_name: "R_SHOULDER_R" rad: 1.265943 }
joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.572396 }
@ -25,9 +29,9 @@ touch_screen_task {
joint_positions { joint_name: "R_WRIST_R" rad: 0.1347 }
velocity: 1.0
acceleration: 2.0
# 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
skip_position_tolerance_rad: 0.01
# 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
skip_velocity_tolerance_rad_s: 0.1
}
@ -88,20 +92,18 @@ touch_screen_task {
stable_frames: 2
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
timeout_s: 20.0
# 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
pause_when_reached: false
}
touch {
speed_l {
twist_tool { x: 0.0 y: -0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 5.0
linear_jerk: 10.0
linear_jerk: 50.0
max_distance_m: 0.03
}
tactile {
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
region: TOUCH_SCREEN_TACTILE_REGION_TIP
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
force_threshold: 0.1 # N
}
@ -109,9 +111,9 @@ touch_screen_task {
}
retract {
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
twist_tool { x: 0.0 y: 0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 8.0
linear_jerk: 40.0 # m/s^3,约束接触后的减速和连续换向。
linear_jerk: 100.0 # m/s^3,约束接触后的减速和连续换向。
# TCP 后退目标距离,单位为米。
distance_m: 0.01
}

View File

@ -7,15 +7,19 @@ touch_screen_task {
devices {
arm_id: "mujoco_right_arm"
dexhand_id: "mujoco_zero_touch_dexhand"
# ZeroSimTouch 始终返回零力,用于测试无接触时的前进限距和回撤流程。
touch_id: "mujoco_zero_touch"
# 手部相机和外部相机的 DeviceManager ID。
camera_id: "mujoco_hand_cam"
external_camera_id: "mujoco_external_touch_cam"
}
initialization {
# 开始前使用 MoveJ 回到初始关节位置。
before_start: true
# 正常完成后使用 MoveP 回到初始关节位置。
after_finish: true
after_failure: true
joint_positions { joint_name: "R_SHOULDER_P" rad: -0.2423 }
joint_positions { joint_name: "R_SHOULDER_R" rad: 1.2929 }
joint_positions { joint_name: "R_SHOULDER_Y" rad: 1.61 }
@ -25,22 +29,23 @@ touch_screen_task {
joint_positions { joint_name: "R_WRIST_R" rad: -0.08 }
velocity: 2.0
acceleration: 3.0
# 当前关节位置误差小于该值时跳过初始化 MoveJ,单位为弧度。
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
skip_position_tolerance_rad: 0.001
# 当前关节速度小于该值时才允许跳过初始化 MoveJ,单位为弧度/秒。
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
skip_velocity_tolerance_rad_s: 0.01
}
perception {
# 屏幕 Tag G 与手部 Tag H 的 ID 和物理边长,单位为米。
# 屏幕 Tag G 与手部 Tag H 的 ID 和黑框外缘边长(不含外围白边),单位为米。
# 当前 MuJoCo 标签整张含白边为 20 mm,黑框外缘为 16 mm。
tags {
screen {
id: 1
size_m: 0.03
size_m: 0.016
}
hand {
id: 0
size_m: 0.03
size_m: 0.016
}
}
# 手部相机:用于点击目标点和手部目标跟踪。
@ -51,6 +56,17 @@ touch_screen_task {
}
}
approach {
# MoveP 复用 alignment.target,position_offset_G 表达在屏幕 G 坐标系。
enable: true
velocity: 0.65 # rad/s
acceleration: 1.7 # rad/s^2
jerk: 30.0 # rad/s^3
timeout_s: 10.0
# TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。
minimum_clearance_m: 0.01
}
alignment {
calibration {
# TCP P 相对于屏幕 Hand Tag H 的目标姿态
@ -97,20 +113,19 @@ touch_screen_task {
stable_frames: 5
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
timeout_s: 20.0
# 到位后暂停;暂停超时结束任务,after_finish 为 true 时尝试回初始位置。
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
pause_when_reached: false
}
touch {
speed_l {
twist_tool { x: 0.0 y: -0.04 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 6.0
linear_jerk: 60.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。
twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 10.0
linear_jerk: 100.0 # m/s^3,接近阶段请求值,受机械臂 linear_jerk_max 限制。
# 零力不会触发接触;达到此距离后回撤,最终状态为 TOUCH_FORWARD_TIMEOUT。
max_distance_m: 0.02
}
tactile {
finger: TOUCH_SCREEN_FINGER_TYPE_INDEX
region: TOUCH_SCREEN_TACTILE_REGION_TIP
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
force_threshold: 0.1 # N
}
@ -118,10 +133,10 @@ touch_screen_task {
}
retract {
twist_tool { x: 0.0 y: 0.06 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 4.0
linear_jerk: 60.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 10.0
linear_jerk: 500.0 # m/s^3,保持仿真机械臂原有的 jerk 上限。
# TCP 后退目标距离,单位为米。
distance_m: 0.05
distance_m: 0.02
}
}

View File

@ -0,0 +1,160 @@
# xiaozhao 右臂视觉触屏流程仿真;ZeroSimTouch 不模拟真实接触力。
touch_screen_task {
id: "touch_screen"
# 是否在外部相机编码后的 gRPC 视频流中绘制 G/H 坐标系,仅影响显示帧;未配置时默认开启。
debug_draw_coordinate_frames: true
# G/H 坐标轴长度,单位为米。
debug_coordinate_axis_length_m: 0.02
devices {
arm_id: "xiaozhao_right_arm"
head_id: "xiaozhao_head"
# ZeroSimTouch 始终返回零力,用于测试无接触时的前进限距和回撤流程。
touch_id: "mujoco_zero_touch"
# 手部相机和外部相机的 DeviceManager ID。
camera_id: "mujoco_hand_cam"
external_camera_id: "mujoco_external_touch_cam"
}
# 任务 init() 时同步执行一次头部 MoveJ,到位后任务才进入 IDLE。
# 后续每次 touch 请求不重复移动头部。角度单位 rad,顺序通过关节名匹配。
head_initialization {
enable: true
# 头部朝向使外部相机同时看到屏幕和手背的 AprilTag。
joint_positions { joint_name: "neck-joint1" rad: 0.0 }
joint_positions { joint_name: "neck-joint2" rad: -0.1 }
joint_positions { joint_name: "neck-joint3" rad: 0.1 }
velocity: 0.25
acceleration: 0.5
}
initialization {
# 三个开关决定何时回初始位。启用的回位动作使用 USE_MOVEJ 或 USE_MOVEP。
motion_method: USE_MOVEJ
before_start: true
after_finish: true
after_failure: true
# S05 场景中 TCP 距屏幕正面约 57 mm。手相机 1280×720 原图的测试点为 (739, 673)。
joint_positions { joint_name: "joint1-right" rad: 2.11258599 }
joint_positions { joint_name: "joint2-right" rad: 0.76424120 }
joint_positions { joint_name: "joint3-right" rad: -0.89182957 }
joint_positions { joint_name: "joint4-right" rad: -1.46915085 }
joint_positions { joint_name: "joint5-right" rad: -0.98091181 }
joint_positions { joint_name: "joint6-right" rad: -0.17745411 }
joint_positions { joint_name: "joint7-right" rad: -0.36598028 }
velocity: 0.5 # rad/s
acceleration: 1.0 # rad/s^2
jerk: 300.0 # rad/s^3,沿用原回位默认值。
# 当前关节位置误差小于该值时跳过初始位置回位,单位为弧度。
skip_position_tolerance_rad: 0.001
# 当前关节速度小于该值时才允许跳过初始位置回位,单位为弧度/秒。
skip_velocity_tolerance_rad_s: 0.01
}
perception {
# 屏幕 Tag G 与手部 Tag H 的 ID 和黑框外缘边长(不含外围白边),单位为米。
# 当前 MuJoCo 标签整张含白边为 20 mm,黑框外缘为 16 mm。
tags {
screen {
id: 1
size_m: 0.016
}
hand {
id: 0
size_m: 0.016
}
}
# 手部相机:用于点击目标点和手部目标跟踪。
hand_camera {
depth_policy: TOUCH_SCREEN_DEPTH_POLICY_NONE
target_point_method: TOUCH_SCREEN_TARGET_POINT_METHOD_TAG_PLANE
}
}
approach {
# MoveP 先将 TCP 移至点击点前方 50 mm,再进入 PBVS 视觉对齐。
enable: true
velocity: 0.65 # rad/s
acceleration: 1.7 # rad/s^2
jerk: 30.0 # rad/s^3
timeout_s: 10.0
# TCP 沿屏幕外法向的最小距离,仅检查 TCP,不覆盖整臂碰撞。
minimum_clearance_m: 0.01
}
alignment {
calibration {
# 手部 Tag H 到 TCP P 的固定安装变换 T_H_P,来自 xiaozhao MJCF。
hand_tag_to_tcp {
m00: 1.0 m01: 0.0 m02: 0.0 m03: -0.0275
m10: 0.0 m11: 0.0 m12: -1.0 m13: 0.081
m20: 0.0 m21: 1.0 m22: 0.0 m23: -0.1354
m30: 0.0 m31: 0.0 m32: 0.0 m33: 1.0
}
}
pbvs {
position_gain { x: 2.0 y: 2.0 z: 1.5 }
rotation_gain { x: 1.5 y: 1.5 z: 1.5 }
vmax6 { x: 0.03 y: 0.03 z: 0.02 rx: 0.15 ry: 0.15 rz: 0.15 }
amax6 { x: 0.10 y: 0.10 z: 0.10 rx: 0.50 ry: 0.50 rz: 0.50 }
twist_filter_alpha: 1.0
}
target {
# Hand Tag H 相对于屏幕 Tag G 的目标姿态,单位为弧度。
# rx、ry、rz 表示绕固定 G 坐标轴 X、Y、Z 依次旋转。
# 旋转组合为 R_G_H = Rz(rz) * Ry(ry) * Rx(rx)。
# PBVS 会结合上面的 T_H_P 将该目标转换为 TCP P 的目标姿态。
hand_orientation_G {
rx: 0.0
ry: 0.0
# 使用检测得到的 G:屏幕纹理使 G 相对 MJCF body 绕 Z 旋转 pi,H 与 body 同向。
# 因此这里的 pi 对应物理手部正立、TCP +Z 沿屏幕向上;设为 0 反而会翻转手腕。
rz: 3.141592653589793
}
# 点击目标点到 TCP 预对齐位置的偏移,表达在 G 坐标系,单位为米。
position_offset_G {
x: 0.0
y: 0.0
z: 0.05
}
mode: TOUCH_SCREEN_ALIGN_MODE_RX_RY_AND_POSITION
}
error_threshold {
x: 0.005
y: 0.005
z: 0.005
rx: 0.08726646259971647
ry: 0.08726646259971647
rz: 0.08726646259971647
}
stable_frames: 5
# 对齐及到位暂停各自的超时时间(秒);暂停从对齐成功时重新计时。
timeout_s: 30.0
# 到位后暂停;暂停超时结束任务,after_failure 为 true 时尝试回初始位置。
pause_when_reached: false
}
touch {
speed_l {
twist_tool { x: 0.0 y: -0.02 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 10
linear_jerk: 100.0 # m/s^3,不超过小赵 SpeedL 的 5.0 上限。
# 零力不会触发接触;达到此距离后回撤,最终状态为 TOUCH_FORWARD_TIMEOUT。
max_distance_m: 0.02
}
tactile {
criterion: TOUCH_SCREEN_TACTILE_CRITERION_FZ
force_threshold: 0.1 # N
}
dwell_time_s: 0.0
}
retract {
twist_tool { x: 0.0 y: 0.08 z: 0.0 rx: 0.0 ry: 0.0 rz: 0.0 }
acceleration: 10
linear_jerk: 100.0 # m/s^3
# TCP 后退目标距离,单位为米。
distance_m: 0.02
}
}

View File

@ -31,7 +31,7 @@ namespace cmvr
/**
* @brief 单次点到点运动的 S 曲线剖面参数
*/
struct LgvSCurveProfile
struct SCurveProfile
{
// 7 个阶段的持续时间
double t1; // 加加速度上升时间(加速阶段)
@ -41,27 +41,27 @@ struct LgvSCurveProfile
double t5; // 加加速度下降时间(减速阶段)
double t6; // 匀减速时间
double t7; // 加加速度上升时间(减速阶段结束)
double total_time;
// 运动约束
double j_max; // 最大加加速度 (rad/s³)
double a_max; // 最大加速度 (rad/s²)
double v_max; // 最大速度 (rad/s)
// 运动参数
double distance; // 运动总距离
double direction; // +1 或 -1
double v_cruise; // 实际达到的巡航速度
double a_limit; // 实际达到的加速度上限
// 初始条件
double p0; // 初始位置
double v0; // 初始速度
double a0; // 初始加速度
double vf; // 终止速度
LgvSCurveProfile()
SCurveProfile()
: t1(0), t2(0), t3(0), t4(0), t5(0), t6(0), t7(0)
, total_time(0)
, j_max(50.0), a_max(10.0), v_max(3.0)
@ -81,7 +81,7 @@ struct LgvSCurveProfile
*
* 其中 j1/j3 为 ±j_max,j2 为 0。
*/
struct LgvSCurveVelocityProfile
struct SCurveVelocityProfile
{
double t1;
double t2;
@ -99,7 +99,7 @@ struct LgvSCurveVelocityProfile
bool valid;
LgvSCurveVelocityProfile()
SCurveVelocityProfile()
: t1(0.0), t2(0.0), t3(0.0)
, total_time(0.0)
, j1(0.0), j2(0.0), j3(0.0)
@ -111,7 +111,7 @@ struct LgvSCurveVelocityProfile
/**
* @brief 位置与速度 S 曲线的数学计算和采样,不保存运行状态
*/
class LgvSCurve
class SCurve
{
public:
/**
@ -120,20 +120,20 @@ public:
* @param max_acceleration 最大加速度 (rad/s²)
* @param max_jerk 最大加加速度 (rad/s³)
*/
LgvSCurve(double max_velocity = 3.0,
SCurve(double max_velocity = 3.0,
double max_acceleration = 10.0,
double max_jerk = 50.0);
/**
* @brief 设置运动约束
*/
void setConstraints(double max_velocity, double max_acceleration, double max_jerk);
/**
* @brief 获取当前运动约束
*/
void getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const;
/**
* @brief 计算点到点运动的完整 S 曲线剖面
* @param start_position 起始位置
@ -142,33 +142,33 @@ public:
* @param end_velocity 终止速度(默认 0)
* @return 计算得到的剖面参数
*/
LgvSCurveProfile calculatePositionProfile(double start_position, double end_position,
SCurveProfile calculatePositionProfile(double start_position, double end_position,
double start_velocity = 0.0,
double end_velocity = 0.0) const;
/**
* @brief 给定剖面下,获取时刻 t 的位置
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的位置
*/
double getPositionAtTime(const LgvSCurveProfile& profile, double t) const;
double getPositionAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的速度
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的速度
*/
double getVelocityAtTime(const LgvSCurveProfile& profile, double t) const;
double getVelocityAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加速度
* @param profile S 曲线剖面
* @param t 从起点开始的时间
* @return 时刻 t 的加速度
*/
double getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const;
double getAccelerationAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加加速度
@ -176,8 +176,8 @@ public:
* @param t 从起点开始的时间
* @return 时刻 t 的加加速度
*/
double getJerkAtTime(const LgvSCurveProfile& profile, double t) const;
double getJerkAtTime(const SCurveProfile& profile, double t) const;
/**
* @brief 按固定时间间隔生成轨迹点
* @param profile S 曲线剖面
@ -186,7 +186,7 @@ public:
* @param velocities 输出:每个时间点的速度
* @param accelerations 输出:每个时间点的加速度
*/
void generateTrajectory(const LgvSCurveProfile& profile, double dt,
void generateTrajectory(const SCurveProfile& profile, double dt,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& accelerations) const;
@ -194,29 +194,29 @@ public:
/**
* @brief 计算单次速度切换剖面
*/
LgvSCurveVelocityProfile calculateVelocityProfile(double start_velocity,
SCurveVelocityProfile calculateVelocityProfile(double start_velocity,
double end_velocity,
double start_acceleration = 0.0) const;
/**
* @brief 给定剖面下,获取时刻 t 的速度
*/
double getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
double getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的加速度
*/
double getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
double getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 给定剖面下,获取时刻 t 的 jerk
*/
double getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const;
double getJerkAtTime(const SCurveVelocityProfile& profile, double t) const;
/**
* @brief 按固定时间间隔生成轨迹点
*/
void generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt,
void generateTrajectory(const SCurveVelocityProfile& profile, double dt,
std::vector<double>& velocities,
std::vector<double>& accelerations,
std::vector<double>& jerks) const;
@ -230,19 +230,19 @@ private:
static constexpr double VELOCITY_THRESHOLD = 1e-6;
static constexpr double ACCELERATION_THRESHOLD = 1e-6;
double computeSegmentJerk(const LgvSCurveProfile& profile, double t) const;
void calculateShortProfile(LgvSCurveProfile& profile) const;
void calculateLongProfile(LgvSCurveProfile& profile) const;
double computeSegmentJerk(const SCurveProfile& profile, double t) const;
void calculateShortProfile(SCurveProfile& profile) const;
void calculateLongProfile(SCurveProfile& profile) const;
/**
* @brief 判断 profile 是否满足速度上限
*/
bool isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const;
bool isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const;
/**
* @brief 计算完整剖面终点状态
*/
void integrateWholeProfile(const LgvSCurveVelocityProfile& profile,
void integrateWholeProfile(const SCurveVelocityProfile& profile,
double& v_end,
double& a_end) const;

View File

@ -15,30 +15,30 @@
namespace cmvr
{
LgvSCurve::LgvSCurve(double max_velocity, double max_acceleration, double max_jerk)
SCurve::SCurve(double max_velocity, double max_acceleration, double max_jerk)
: max_velocity_(std::abs(max_velocity))
, max_acceleration_(std::abs(max_acceleration))
, max_jerk_(std::abs(max_jerk))
{}
void LgvSCurve::setConstraints(double max_velocity, double max_acceleration, double max_jerk)
void SCurve::setConstraints(double max_velocity, double max_acceleration, double max_jerk)
{
max_velocity_ = std::abs(max_velocity);
max_acceleration_ = std::abs(max_acceleration);
max_jerk_ = std::abs(max_jerk);
}
void LgvSCurve::getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const
void SCurve::getConstraints(double& max_velocity, double& max_acceleration, double& max_jerk) const
{
max_velocity = max_velocity_;
max_acceleration = max_acceleration_;
max_jerk = max_jerk_;
}
LgvSCurveProfile LgvSCurve::calculatePositionProfile(double start_position, double end_position,
SCurveProfile SCurve::calculatePositionProfile(double start_position, double end_position,
double start_velocity, double end_velocity) const
{
LgvSCurveProfile profile;
SCurveProfile profile;
profile.j_max = max_jerk_;
profile.a_max = max_acceleration_;
profile.v_max = max_velocity_;
@ -46,11 +46,11 @@ LgvSCurveProfile LgvSCurve::calculatePositionProfile(double start_position, doub
profile.v0 = start_velocity;
profile.a0 = 0.0; // Assume starting from zero acceleration
profile.vf = end_velocity;
double displacement = end_position - start_position;
profile.distance = std::abs(displacement);
profile.direction = (displacement >= 0) ? 1.0 : -1.0;
if (profile.distance < EPSILON) {
// 无需运动
profile.total_time = 0.0;
@ -181,11 +181,11 @@ LgvSCurveProfile LgvSCurve::calculatePositionProfile(double start_position, doub
calculateShortProfile(profile);
}
}
return profile;
}
void LgvSCurve::calculateShortProfile(LgvSCurveProfile& profile) const
void SCurve::calculateShortProfile(SCurveProfile& profile) const
{
// 短距离:无巡航段(t4 = 0)。
const double j = profile.j_max;
@ -234,14 +234,14 @@ void LgvSCurve::calculateShortProfile(LgvSCurveProfile& profile) const
profile.a_limit = a;
}
}
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
profile.t5 + profile.t6 + profile.t7;
}
void LgvSCurve::calculateLongProfile(LgvSCurveProfile& profile) const
void SCurve::calculateLongProfile(SCurveProfile& profile) const
{
// 含巡航段的完整 7 段式 S 曲线;与 LgvSCurveProfile1D 的 full-profile 公式一致。
// 含巡航段的完整 7 段式 S 曲线;与 SCurveProfile1D 的 full-profile 公式一致。
const double j = profile.j_max;
const double a = profile.a_max;
const double v = profile.v_max;
@ -278,15 +278,15 @@ void LgvSCurve::calculateLongProfile(LgvSCurveProfile& profile) const
profile.v_cruise = v;
profile.a_limit = a;
}
profile.total_time = profile.t1 + profile.t2 + profile.t3 + profile.t4 +
profile.t5 + profile.t6 + profile.t7;
}
double LgvSCurve::computeSegmentJerk(const LgvSCurveProfile& profile, double t) const
double SCurve::computeSegmentJerk(const SCurveProfile& profile, double t) const
{
double j = profile.j_max * profile.direction;
// 判断所处阶段
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
@ -295,7 +295,7 @@ double LgvSCurve::computeSegmentJerk(const LgvSCurveProfile& profile, double t)
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
// double t_end7 = t_end6 + profile.t7; // = total_time
if (t < t_end1) {
return j; // 段 1:正加加速度(加速)
} else if (t < t_end2) {
@ -313,16 +313,16 @@ double LgvSCurve::computeSegmentJerk(const LgvSCurveProfile& profile, double t)
}
}
double LgvSCurve::getPositionAtTime(const LgvSCurveProfile& profile, double t) const
double SCurve::getPositionAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0) return profile.p0;
if (t >= profile.total_time) return profile.p0 + profile.distance * profile.direction;
double j = profile.j_max * profile.direction;
double p = profile.p0;
double v = profile.v0;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
@ -330,70 +330,70 @@ double LgvSCurve::getPositionAtTime(const LgvSCurveProfile& profile, double t) c
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
// 依次处理各阶段
auto processSegment = [&](double dt, double jerk) {
p += v * dt + 0.5 * a * dt * dt + (1.0/6.0) * jerk * dt * dt * dt;
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
// 段 1
if (t <= t_end1) {
processSegment(t, j);
return p;
}
processSegment(profile.t1, j);
// 段 2
if (t <= t_end2) {
processSegment(t - t_end1, 0.0);
return p;
}
processSegment(profile.t2, 0.0);
// 段 3
if (t <= t_end3) {
processSegment(t - t_end2, -j);
return p;
}
processSegment(profile.t3, -j);
// 段 4(巡航)
if (t <= t_end4) {
processSegment(t - t_end3, 0.0);
return p;
}
processSegment(profile.t4, 0.0);
// 段 5
if (t <= t_end5) {
processSegment(t - t_end4, -j);
return p;
}
processSegment(profile.t5, -j);
// 段 6
if (t <= t_end6) {
processSegment(t - t_end5, 0.0);
return p;
}
processSegment(profile.t6, 0.0);
// 段 7
processSegment(t - t_end6, j);
return p;
}
double LgvSCurve::getVelocityAtTime(const LgvSCurveProfile& profile, double t) const
double SCurve::getVelocityAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0) return profile.v0;
if (t >= profile.total_time) return profile.vf;
double j = profile.j_max * profile.direction;
double v = profile.v0;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
@ -401,62 +401,62 @@ double LgvSCurve::getVelocityAtTime(const LgvSCurveProfile& profile, double t) c
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
auto processSegment = [&](double dt, double jerk) {
v += a * dt + 0.5 * jerk * dt * dt;
a += jerk * dt;
};
if (t <= t_end1) {
v += a * t + 0.5 * j * t * t;
return v;
}
processSegment(profile.t1, j);
if (t <= t_end2) {
v += a * (t - t_end1);
return v;
}
processSegment(profile.t2, 0.0);
if (t <= t_end3) {
double dt = t - t_end2;
v += a * dt + 0.5 * (-j) * dt * dt;
return v;
}
processSegment(profile.t3, -j);
if (t <= t_end4) {
v += a * (t - t_end3);
return v;
}
processSegment(profile.t4, 0.0);
if (t <= t_end5) {
double dt = t - t_end4;
v += a * dt + 0.5 * (-j) * dt * dt;
return v;
}
processSegment(profile.t5, -j);
if (t <= t_end6) {
v += a * (t - t_end5);
return v;
}
processSegment(profile.t6, 0.0);
double dt = t - t_end6;
v += a * dt + 0.5 * j * dt * dt;
return v;
}
double LgvSCurve::getAccelerationAtTime(const LgvSCurveProfile& profile, double t) const
double SCurve::getAccelerationAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0 || t >= profile.total_time) return 0.0;
double j = profile.j_max * profile.direction;
double a = profile.a0;
// 时间边界
double t_end1 = profile.t1;
double t_end2 = t_end1 + profile.t2;
@ -464,38 +464,38 @@ double LgvSCurve::getAccelerationAtTime(const LgvSCurveProfile& profile, double
double t_end4 = t_end3 + profile.t4;
double t_end5 = t_end4 + profile.t5;
double t_end6 = t_end5 + profile.t6;
if (t <= t_end1) {
return a + j * t;
}
a += j * profile.t1;
if (t <= t_end2) {
return a;
}
if (t <= t_end3) {
return a + (-j) * (t - t_end2);
}
a += (-j) * profile.t3;
if (t <= t_end4) {
return a; // Should be ~0
}
if (t <= t_end5) {
return a + (-j) * (t - t_end4);
}
a += (-j) * profile.t5;
if (t <= t_end6) {
return a;
}
return a + j * (t - t_end6);
}
double LgvSCurve::getJerkAtTime(const LgvSCurveProfile& profile, double t) const
double SCurve::getJerkAtTime(const SCurveProfile& profile, double t) const
{
if (t <= 0.0 || t >= profile.total_time) {
return 0.0;
@ -503,7 +503,7 @@ double LgvSCurve::getJerkAtTime(const LgvSCurveProfile& profile, double t) const
return computeSegmentJerk(profile, t);
}
void LgvSCurve::generateTrajectory(const LgvSCurveProfile& profile, double dt,
void SCurve::generateTrajectory(const SCurveProfile& profile, double dt,
std::vector<double>& positions,
std::vector<double>& velocities,
std::vector<double>& accelerations) const
@ -511,27 +511,27 @@ void LgvSCurve::generateTrajectory(const LgvSCurveProfile& profile, double dt,
positions.clear();
velocities.clear();
accelerations.clear();
if (profile.total_time <= 0 || dt <= 0) {
positions.push_back(profile.p0);
velocities.push_back(profile.v0);
accelerations.push_back(profile.a0);
return;
}
int num_points = static_cast<int>(std::ceil(profile.total_time / dt)) + 1;
positions.reserve(num_points);
velocities.reserve(num_points);
accelerations.reserve(num_points);
for (double t = 0; t <= profile.total_time; t += dt) {
positions.push_back(getPositionAtTime(profile, t));
velocities.push_back(getVelocityAtTime(profile, t));
accelerations.push_back(getAccelerationAtTime(profile, t));
}
// 确保包含最终点
if (positions.empty() ||
if (positions.empty() ||
std::abs(positions.back() - (profile.p0 + profile.distance * profile.direction)) > EPSILON) {
positions.push_back(profile.p0 + profile.distance * profile.direction);
velocities.push_back(profile.vf);
@ -539,7 +539,7 @@ void LgvSCurve::generateTrajectory(const LgvSCurveProfile& profile, double dt,
}
}
double LgvSCurve::getVelocityAtTime(const LgvSCurveVelocityProfile& profile, double t) const
double SCurve::getVelocityAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return profile.v0;
@ -581,7 +581,7 @@ double LgvSCurve::getVelocityAtTime(const LgvSCurveVelocityProfile& profile, dou
return v;
}
double LgvSCurve::getAccelerationAtTime(const LgvSCurveVelocityProfile& profile, double t) const
double SCurve::getAccelerationAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return profile.a0;
@ -621,7 +621,7 @@ double LgvSCurve::getAccelerationAtTime(const LgvSCurveVelocityProfile& profile,
return a;
}
double LgvSCurve::getJerkAtTime(const LgvSCurveVelocityProfile& profile, double t) const
double SCurve::getJerkAtTime(const SCurveVelocityProfile& profile, double t) const
{
if (!profile.valid) {
return 0.0;
@ -640,7 +640,7 @@ double LgvSCurve::getJerkAtTime(const LgvSCurveVelocityProfile& profile, double
return profile.j3;
}
void LgvSCurve::integrateWholeProfile(const LgvSCurveVelocityProfile& profile,
void SCurve::integrateWholeProfile(const SCurveVelocityProfile& profile,
double& v_end,
double& a_end) const
{
@ -660,7 +660,7 @@ void LgvSCurve::integrateWholeProfile(const LgvSCurveVelocityProfile& profile,
a_end = a;
}
bool LgvSCurve::isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile) const
bool SCurve::isVelocityLimitSatisfied(const SCurveVelocityProfile& profile) const
{
if (!profile.valid) {
return true;
@ -692,11 +692,11 @@ bool LgvSCurve::isVelocityLimitSatisfied(const LgvSCurveVelocityProfile& profile
return true;
}
LgvSCurveVelocityProfile LgvSCurve::calculateVelocityProfile(double start_velocity,
SCurveVelocityProfile SCurve::calculateVelocityProfile(double start_velocity,
double end_velocity,
double start_acceleration) const
{
LgvSCurveVelocityProfile best;
SCurveVelocityProfile best;
best.v0 = clamp(start_velocity, -max_velocity_, max_velocity_);
best.a0 = clamp(start_acceleration, -max_acceleration_, max_acceleration_);
best.vf = clamp(end_velocity, -max_velocity_, max_velocity_);
@ -735,7 +735,7 @@ LgvSCurveVelocityProfile LgvSCurve::calculateVelocityProfile(double start_veloci
return;
}
LgvSCurveVelocityProfile cand;
SCurveVelocityProfile cand;
cand.t1 = t1;
cand.t2 = t2;
cand.t3 = t3;
@ -837,7 +837,7 @@ LgvSCurveVelocityProfile LgvSCurve::calculateVelocityProfile(double start_veloci
return best;
}
void LgvSCurve::generateTrajectory(const LgvSCurveVelocityProfile& profile, double dt,
void SCurve::generateTrajectory(const SCurveVelocityProfile& profile, double dt,
std::vector<double>& velocities,
std::vector<double>& accelerations,
std::vector<double>& jerks) const

View File

@ -3,6 +3,7 @@ add_subdirectory(agv)
add_subdirectory(speaker)
add_subdirectory(microphone)
add_subdirectory(dexhand)
add_subdirectory(touch)
add_subdirectory(biohead)
add_subdirectory(arm)
add_subdirectory(canbus)

View File

@ -363,9 +363,6 @@ AuboArm::AuboArm(const config::RobotArmConfig& cfg)
const auto dof = vendor_cfg_.dof() > 0 ? static_cast<std::size_t>(vendor_cfg_.dof()) : 6U;
model_.name = vendor_cfg_.model().empty() ? "AuboARM" : vendor_cfg_.model();
model_.manufacturer = vendorBrandName(vendor_cfg_.brand());
model_.description_id = model_.name;
model_.default_base_frame = vendor_cfg_.base_frame();
model_.default_tcp_frame = vendor_cfg_.tool_frame();
model_.dof = dof;
model_.joint_names.assign(vendor_cfg_.joint_names().begin(), vendor_cfg_.joint_names().end());
if (model_.joint_names.empty()) {
@ -1892,12 +1889,9 @@ Result AuboArm::connect(const std::string& ip, const int port)
const std::string sdk_subtype = robot_config->getRobotSubType();
if (!sdk_model.empty()) {
model_.name = sdk_model;
model_.description_id = sdk_model;
model_.subtype = sdk_subtype;
model_.detected_from_sdk = true;
CMVR_LOG(INFO) << "[AuboArm] SDK detected model, id=" << id_
<< ", model=" << model_.name
<< ", subtype=" << model_.subtype;
<< ", subtype=" << sdk_subtype;
}
}
} catch (const std::exception& e) {

View File

@ -96,9 +96,6 @@ HuayanRobot::HuayanRobot(const config::RobotArmConfig& cfg)
const auto dof = vendor_cfg_.dof() > 0 ? static_cast<std::size_t>(vendor_cfg_.dof()) : 6U;
model_.name = vendor_cfg_.model().empty() ? "HuayanRobot" : vendor_cfg_.model();
model_.manufacturer = "Huayan";
model_.description_id = model_.name;
model_.default_base_frame = ucs_name_;
model_.default_tcp_frame = tcp_name_;
model_.dof = dof;
model_.joint_names.assign(vendor_cfg_.joint_names().begin(), vendor_cfg_.joint_names().end());
if (model_.joint_names.empty()) {
@ -648,8 +645,6 @@ Result HuayanRobot::connect(const std::string& ip, const int port)
const int model_result = HRIF_ReadRobotModel(box_id_, sdk_model);
if (model_result == 0 && !sdk_model.empty()) {
model_.name = sdk_model;
model_.description_id = sdk_model;
model_.detected_from_sdk = true;
CMVR_LOG(INFO) << "[HuayanRobot] SDK detected model, id=" << id_
<< ", model=" << model_.name;
} else {

View File

@ -9,7 +9,7 @@ target_link_libraries(motor_robot_arm
PUBLIC
cmvr_es::proto
PRIVATE
cmvr_es::algorithms::lgv_arm_motion
cmvr_es::algorithms::arm_motion
cmvr_es::ik_solver
cmvr_es::joint_path_planner
cmvr_es::joint_trajectory_smoother

View File

@ -197,7 +197,8 @@ ArmState MotorRobotArm::getRobotState() const
state.protective_stopped = protective_stopped;
state.emergency_stopped = emergency_stopped;
state.speed_scaling = speed_scaling_.load();
state.robot_mode = isFault() ? RobotMode::Fault : (busy() ? RobotMode::Running : RobotMode::Idle);
state.robot_mode = !state.connected ? RobotMode::Disconnected
: isFault() ? RobotMode::Fault : (state.moving ? RobotMode::Running : RobotMode::Idle);
state.fault = isFault();
state.safety_mode = getSafetyMode();
state.control_mode = ControlMode::Position;
@ -252,6 +253,9 @@ JointGroupState MotorRobotArm::getJointState() const
for (const auto& motor : motors) {
state.current.push_back(static_cast<double>(motor->getCurrent()));
}
if (!motor_manager_ || !motor_manager_->readFeedbacksAtomic(motors, state.position, state.velocity))
return {};
state.effort.assign(motors.size(), 0.0);
return state;
}

View File

@ -5,6 +5,7 @@
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <functional>
#include <iostream>
@ -19,6 +20,7 @@
#include <Eigen/Geometry>
#include <gtest/gtest.h>
#include "common/config/config_files.h"
#include "common/io/proto_file_io.h"
#include "common/math/transform_math.h"
#include "manager/device_manager/include/device_manager.h"
@ -138,6 +140,8 @@ protected:
DeviceManager::destroyInstance();
project_root_ = findProjectRoot();
ASSERT_FALSE(project_root_.empty());
ConfigHelper::setConfigRootFromFile(
(project_root_ / "cmvr-es/config/cmvr_es.pb.txt").string());
config::MujocoWorldRootConfig world_root_config;
ASSERT_TRUE(ProtoMessageIo::getProtoFromAsciiFile(
@ -460,17 +464,20 @@ TEST_F(MotorRobotArmGen2MujocoTest, MoveL)
TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
{
MuJocoViewer viewer(world_);
viewer.setupCamera(2.5, -160.0, -20.0);
std::unique_ptr<MuJocoViewer> viewer;
if (std::getenv("CMVR_MUJOCO_HEADLESS") == nullptr) {
viewer = std::make_unique<MuJocoViewer>(world_);
viewer->setupCamera(2.5, -160.0, -20.0);
}
struct CollisionCaseOutcome {
std::string name;
Result setup_move{Result::failure(ArmErrorCode::UnknownError, "not run")};
Result collision_move{Result::failure(ArmErrorCode::UnknownError, "not run")};
Result recovery{Result::failure(ArmErrorCode::UnknownError, "not run")};
task::SelfCollisionTaskStatus initial_status;
task::SelfCollisionTaskStatus stop_status;
task::SelfCollisionTaskStatus recovered_status;
safety::SelfCollisionStatus initial_status;
safety::SelfCollisionStatus stop_status;
safety::SelfCollisionStatus recovered_status;
CartesianPose start_tcp;
CartesianPose final_tcp;
std::vector<double> final_position;
@ -553,7 +560,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
name + " start: " + collision_task.detailStatusString());
}
outcome.initial_status = collision_task.latestStatus();
if (outcome.initial_status.level != task::CollisionSafetyLevel::SAFE) {
if (outcome.initial_status.level != safety::CollisionSafetyLevel::SAFE) {
throw std::runtime_error(
name + " setup pose is not SAFE: " +
collision_task.detailStatusString());
@ -579,9 +586,24 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
});
outcome.collision_move = start_motion();
const auto simulation_time = [&] {
std::lock_guard<std::mutex> lock(world_->mutex());
return world_->data()->time;
};
const double wait_start_sim_s = simulation_time();
const auto wait_start_wall = std::chrono::steady_clock::now();
// Online control can slow simulation below real time in Debug.
// Bound motion time in simulation, with a wall-clock watchdog.
waitFor([&] {
return stop_seen.load() || !monitor_ok.load();
}, stop_timeout);
return stop_seen.load() || !monitor_ok.load() ||
simulation_time() - wait_start_sim_s >=
std::chrono::duration<double>(stop_timeout).count();
}, stop_timeout * 4);
std::cout << "[MotorRobotArmGen2MujocoTest] collision " << name
<< " wait_sim_s=" << simulation_time() - wait_start_sim_s
<< ", wait_wall_s=" << std::chrono::duration<double>(
std::chrono::steady_clock::now() - wait_start_wall).count()
<< std::endl;
if (!stop_seen.load()) {
arm_->stopMotion();
monitor_running = false;
@ -689,12 +711,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
worker_error = error.what();
}
std::this_thread::sleep_for(std::chrono::seconds(3));
viewer.requestStop();
if (viewer) {
std::this_thread::sleep_for(std::chrono::seconds(3));
viewer->requestStop();
}
});
viewer.setRunning(true);
viewer.run();
if (viewer) {
viewer->setRunning(true);
viewer->run();
}
scenario.join();
EXPECT_TRUE(worker_error.empty()) << worker_error;
@ -703,16 +729,16 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
<< outcome.name << ": " << outcome.setup_move.message;
EXPECT_TRUE(outcome.task_initialized) << outcome.name;
EXPECT_TRUE(outcome.task_started) << outcome.name;
EXPECT_EQ(outcome.initial_status.level, task::CollisionSafetyLevel::SAFE)
EXPECT_EQ(outcome.initial_status.level, safety::CollisionSafetyLevel::SAFE)
<< outcome.name;
EXPECT_TRUE(outcome.monitor_ok) << outcome.name;
EXPECT_TRUE(outcome.stop_seen) << outcome.name;
EXPECT_EQ(outcome.stop_status.level, task::CollisionSafetyLevel::STOP)
EXPECT_EQ(outcome.stop_status.level, safety::CollisionSafetyLevel::STOP)
<< outcome.name;
EXPECT_TRUE(outcome.stop_status.stop_latched) << outcome.name;
EXPECT_NE(outcome.stop_status.event_id, 0U) << outcome.name;
EXPECT_EQ(outcome.stop_status.recovery_state,
task::ProtectiveRecoveryState::AVAILABLE)
safety::ProtectiveRecoveryState::AVAILABLE)
<< outcome.name;
EXPECT_GE(outcome.stop_status.recovery_sample_count, 2U)
<< outcome.name;
@ -725,7 +751,7 @@ TEST_F(MotorRobotArmGen2MujocoTest, SelfCollisionProtectiveStopMoveJMoveLSpeedL)
<< outcome.name << ": " << outcome.recovery.message;
EXPECT_FALSE(outcome.recovered_status.stop_latched) << outcome.name;
EXPECT_EQ(outcome.recovered_status.recovery_state,
task::ProtectiveRecoveryState::SUCCEEDED)
safety::ProtectiveRecoveryState::SUCCEEDED)
<< outcome.name;
EXPECT_GE(outcome.recovered_status.result.minimum_distance_m, 0.025)
<< outcome.name;

View File

@ -4,6 +4,7 @@
#pragma once
#include <atomic>
#include <cstdint>
#include <condition_variable>
#include <chrono>
@ -55,9 +56,16 @@ public:
void getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics) override;
bool startStreaming() override;
void stopStreaming() override;
void getEncodedFrame(StreamFrameData& frame_data, size_t& index) override;
bool waitEncodedFrame(StreamFrameData& frame_data,
size_t& index,
std::chrono::milliseconds timeout) override;
bool getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index) override;
bool requestKeyFrame() override;
private:
bool startImpl_();
bool stopImpl_();
bool fetch(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics& intrinsics);
void fillIntrinsics(int width, int height, Rs2Intrinsics& intrinsics) const;
bool initOffscreen_();
@ -81,11 +89,19 @@ private:
cv::Mat depth;
Rs2Intrinsics intrinsics{};
uint64_t frame_id{0};
uint64_t capture_sequence{0};
int64_t capture_monotonic_ns{0};
int64_t capture_utc_ns{0};
bool valid{false};
};
bool encodeCachedFrame_(const CachedFrame& captured,
StreamFrameData& frame_data,
size_t& next_index);
private:
FetchRgbdFn fetch_rgbd_fn_;
std::mutex lifecycle_mtx_;
mutable std::mutex mtx_;
config::MujocoCameraConfig config_;
std::weak_ptr<simulate::MujocoWorld> world_;
@ -110,12 +126,19 @@ private:
uint64_t last_frame_id_{0};
bool has_last_frame_id_{false};
size_t stream_frame_index_{0};
bool streaming_{false};
std::atomic<bool> streaming_{false};
std::mutex stream_mtx_;
size_t streaming_refs_{0};
uint64_t stream_epoch_{0};
bool force_key_frame_{false};
std::atomic<uint64_t> encoded_capture_sequence_{0};
StreamFrameData latest_encoded_frame_;
std::shared_ptr<FfmpegEncoderInfo> rgb_encoder_;
mutable std::mutex cache_mtx_;
std::condition_variable cache_cv_;
CachedFrame latest_frame_;
uint64_t capture_sequence_{0};
std::thread render_thread_;
bool render_thread_running_{false};
bool render_stop_requested_{false};

View File

@ -134,6 +134,12 @@ bool MujocoCamera::init()
}
bool MujocoCamera::start()
{
std::lock_guard<std::mutex> lock(lifecycle_mtx_);
return startImpl_();
}
bool MujocoCamera::startImpl_()
{
bool initialized = false;
{
@ -208,7 +214,7 @@ bool MujocoCamera::start()
const bool has_frame = latest_frame_.valid;
cache_lock.unlock();
if (!ready || !has_frame) {
stop();
stopImpl_();
if (ready) {
setError_("[MujocoCamera] render thread stopped before producing a frame");
} else {
@ -220,6 +226,12 @@ bool MujocoCamera::start()
}
bool MujocoCamera::stop()
{
std::lock_guard<std::mutex> lock(lifecycle_mtx_);
return stopImpl_();
}
bool MujocoCamera::stopImpl_()
{
{
std::lock_guard<std::mutex> lock(cache_mtx_);
@ -238,6 +250,15 @@ bool MujocoCamera::stop()
thread_to_join.join();
}
{
std::lock_guard<std::mutex> lock(stream_mtx_);
streaming_.store(false);
streaming_refs_ = 0;
force_key_frame_ = false;
encoded_capture_sequence_.store(0);
latest_encoded_frame_ = StreamFrameData{};
rgb_encoder_.reset();
}
{
std::lock_guard<std::mutex> lock(cache_mtx_);
render_thread_running_ = false;
@ -249,13 +270,14 @@ bool MujocoCamera::stop()
void MujocoCamera::setFetchRgbdFn(FetchRgbdFn fetch_rgbd_fn)
{
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mtx_);
bool render_thread_active = false;
{
std::lock_guard<std::mutex> lock(cache_mtx_);
render_thread_active = render_thread_running_;
}
if (render_thread_active) {
stop();
stopImpl_();
}
std::lock_guard<std::mutex> lock(mtx_);
@ -308,37 +330,144 @@ void MujocoCamera::getRGBDImages(cv::Mat& color, cv::Mat& depth, Rs2Intrinsics&
bool MujocoCamera::startStreaming()
{
if (!start()) {
std::lock_guard<std::mutex> lifecycle_lock(lifecycle_mtx_);
if (!startImpl_()) {
return false;
}
std::lock_guard<std::mutex> lock(mtx_);
streaming_ = true;
state_.is_streaming = true;
{
std::lock_guard<std::mutex> lock(stream_mtx_);
if (streaming_refs_++ == 0) {
++stream_epoch_;
force_key_frame_ = false;
encoded_capture_sequence_.store(0);
latest_encoded_frame_ = StreamFrameData{};
rgb_encoder_.reset();
}
streaming_.store(true);
std::lock_guard<std::mutex> state_lock(mtx_);
state_.is_streaming = true;
}
cache_cv_.notify_all();
return true;
}
void MujocoCamera::stopStreaming()
{
std::lock_guard<std::mutex> lock(mtx_);
streaming_ = false;
state_.is_streaming = false;
stream_frame_index_ = 0;
rgb_encoder_.reset();
{
std::lock_guard<std::mutex> lock(stream_mtx_);
if (streaming_refs_ == 0 || --streaming_refs_ != 0) {
return;
}
streaming_.store(false);
force_key_frame_ = false;
encoded_capture_sequence_.store(0);
latest_encoded_frame_ = StreamFrameData{};
rgb_encoder_.reset();
std::lock_guard<std::mutex> state_lock(mtx_);
state_.is_streaming = false;
}
cache_cv_.notify_all();
}
void MujocoCamera::getEncodedFrame(StreamFrameData& frame_data, size_t& index)
{
(void)waitEncodedFrame(frame_data, index, std::chrono::milliseconds::zero());
}
bool MujocoCamera::waitEncodedFrame(StreamFrameData& frame_data,
size_t& index,
const std::chrono::milliseconds timeout)
{
const auto deadline = std::chrono::steady_clock::now() +
std::max(timeout, std::chrono::milliseconds::zero());
uint64_t last_attempted_capture = 0;
while (true) {
uint64_t encoded_capture = 0;
{
std::lock_guard<std::mutex> lock(stream_mtx_);
if (!streaming_.load()) {
return false;
}
if (latest_encoded_frame_.sequence > index) {
frame_data = latest_encoded_frame_;
index = static_cast<size_t>(frame_data.sequence);
return true;
}
encoded_capture = encoded_capture_sequence_.load();
}
CachedFrame captured;
{
std::unique_lock<std::mutex> lock(cache_mtx_);
const uint64_t min_capture = std::max(encoded_capture, last_attempted_capture);
const bool ready = cache_cv_.wait_until(lock, deadline, [&] {
return !streaming_.load() || render_stop_requested_ || !render_thread_running_ ||
(latest_frame_.valid && latest_frame_.capture_sequence > min_capture);
});
if (!ready || !streaming_.load() || render_stop_requested_ ||
!render_thread_running_ || !latest_frame_.valid) {
return false;
}
captured = latest_frame_;
}
StreamFrameData encoded;
size_t next_index = index;
if (encodeCachedFrame_(captured, encoded, next_index) && next_index > index) {
frame_data = std::move(encoded);
index = next_index;
return true;
}
last_attempted_capture = std::max(last_attempted_capture, captured.capture_sequence);
if (std::chrono::steady_clock::now() >= deadline) {
return false;
}
}
}
bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& next_index)
{
if (!streaming_) {
CachedFrame captured;
{
std::lock_guard<std::mutex> lock(cache_mtx_);
if (!latest_frame_.valid || latest_frame_.color.empty()) {
return false;
}
captured = latest_frame_;
}
return encodeCachedFrame_(captured, frame_data, next_index);
}
bool MujocoCamera::requestKeyFrame()
{
std::lock_guard<std::mutex> lock(stream_mtx_);
if (!streaming_.load()) {
return false;
}
force_key_frame_ = true;
return true;
}
bool MujocoCamera::encodeCachedFrame_(const CachedFrame& captured,
StreamFrameData& frame_data,
size_t& next_index)
{
std::lock_guard<std::mutex> lock(stream_mtx_);
if (!streaming_.load() || !captured.valid || captured.color.empty()) {
return false;
}
if (latest_encoded_frame_.sequence != 0 &&
captured.capture_sequence <= encoded_capture_sequence_.load()) {
frame_data = latest_encoded_frame_;
next_index = static_cast<size_t>(frame_data.sequence);
return true;
}
cv::Mat color;
cv::Mat depth;
Rs2Intrinsics intrinsics{};
if (!fetch(color, depth, intrinsics) || color.empty()) {
return false;
}
const cv::Mat& color = captured.color;
const cv::Mat& depth = captured.depth;
const Rs2Intrinsics& intrinsics = captured.intrinsics;
cv::Mat color_to_encode = color;
if (encode_width_ > 0 && encode_height_ > 0 &&
@ -351,33 +480,59 @@ bool MujocoCamera::getLatestEncodedFrame(StreamFrameData& frame_data, size_t& ne
return false;
}
frame_data.rgbImage = color.clone();
frame_data.intrinsics = intrinsics;
StreamFrameData encoded;
// Published capture buffers are immutable. Keep a reference instead of
// copying full-resolution images for every encoded RGB frame.
encoded.rgbImage = color;
encoded.intrinsics = intrinsics;
CameraStreamEncodeOptions encode_options;
encode_options.draw_timestamp = enable_stream_timestamp_;
encode_options.overlay = streamOverlay();
const Rs2Intrinsics encode_intrinsics = scaleIntrinsics(
intrinsics, color.cols, color.rows, color_to_encode.cols, color_to_encode.rows);
if (!CameraStreamEncoder::encode(rgb_encoder_,
color_to_encode,
frame_data.rgbFrame,
frame_data.bKey,
encode_intrinsics,
encode_options)) {
rgb_encoder_->frame->pict_type = force_key_frame_
? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
const bool encoded_ok = CameraStreamEncoder::encode(rgb_encoder_,
color_to_encode,
encoded.rgbFrame,
encoded.bKey,
encode_intrinsics,
encode_options);
rgb_encoder_->frame->pict_type = AV_PICTURE_TYPE_NONE;
if (!encoded_ok) {
return false;
}
if (encoded.bKey) {
force_key_frame_ = false;
}
if (!depth.empty()) {
frame_data.depthImage = depth.clone();
encoded.depthImage = depth;
const auto* depth_begin = reinterpret_cast<const uint8_t*>(depth.data);
const auto* depth_end = depth_begin + depth.total() * depth.elemSize();
frame_data.depthFrame.assign(depth_begin, depth_end);
encoded.depthFrame.assign(depth_begin, depth_end);
encoded.depth_width = depth.cols;
encoded.depth_height = depth.rows;
}
frame_data.width = color_to_encode.cols;
frame_data.height = color_to_encode.rows;
frame_data.fps = fps;
frame_data.codec = codec_;
frame_data.depthKey = true;
next_index = ++stream_frame_index_;
encoded.width = color_to_encode.cols;
encoded.height = color_to_encode.rows;
encoded.fps = fps;
encoded.codec = codec_;
encoded.depthKey = !depth.empty();
encoded.stream_epoch = stream_epoch_;
encoded.sequence = ++stream_frame_index_;
encoded.source_frame_number = captured.frame_id;
encoded.capture_monotonic_ns = captured.capture_monotonic_ns;
encoded.capture_utc_ns = captured.capture_utc_ns;
encoded.pts = rgb_encoder_->frame_pts - 1;
encoded.dts = encoded.pts;
encoded.time_base_num = 1;
encoded.time_base_den = fps;
encoded.duration = 1;
encoded_capture_sequence_.store(captured.capture_sequence);
latest_encoded_frame_ = std::move(encoded);
frame_data = latest_encoded_frame_;
next_index = static_cast<size_t>(frame_data.sequence);
return true;
}
@ -599,21 +754,37 @@ void MujocoCamera::renderLoop_()
}
if (got_frame) {
const auto captured_at = std::chrono::steady_clock::now();
const auto captured_utc = std::chrono::system_clock::now();
bool published_frame = false;
{
std::lock_guard<std::mutex> lock(cache_mtx_);
latest_frame_.color = std::move(color);
latest_frame_.depth = std::move(depth);
latest_frame_.intrinsics = intrinsics;
latest_frame_.frame_id = use_external_frames && external_frame_id != 0
? external_frame_id
: latest_frame_.frame_id + 1;
latest_frame_.valid = true;
if (!use_external_frames || external_frame_id == 0 ||
!latest_frame_.valid || latest_frame_.frame_id != external_frame_id) {
latest_frame_.color = std::move(color);
latest_frame_.depth = std::move(depth);
latest_frame_.intrinsics = intrinsics;
latest_frame_.frame_id = use_external_frames && external_frame_id != 0
? external_frame_id
: latest_frame_.frame_id + 1;
latest_frame_.capture_sequence = ++capture_sequence_;
latest_frame_.capture_monotonic_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(
captured_at.time_since_epoch()).count();
latest_frame_.capture_utc_ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(
captured_utc.time_since_epoch()).count();
latest_frame_.valid = true;
published_frame = true;
}
}
{
std::lock_guard<std::mutex> lock(mtx_);
clear_error_();
}
cache_cv_.notify_all();
if (published_frame) {
cache_cv_.notify_all();
}
}
next_tick += period_ticks;
@ -624,7 +795,9 @@ void MujocoCamera::renderLoop_()
const auto now = std::chrono::steady_clock::now();
if (next_tick < now) {
next_tick = now + period_ticks;
// The previous capture already ran past its deadline. Retry on
// the next loop rather than adding a second frame period of idle.
next_tick = now;
}
}

View File

@ -1,10 +1,156 @@
#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <vector>
#include "devices/camera/mujoco_camera/include/mujoco_camera.h"
#include "simulate/mujoco/mujoco_world/include/mujoco_world.h"
namespace {
bool beginsWithAnnexBStartCode(const std::vector<uint8_t>& bytes)
{
return bytes.size() >= 4 && bytes[0] == 0 && bytes[1] == 0 &&
(bytes[2] == 1 || (bytes[2] == 0 && bytes[3] == 1));
}
bool containsH264IdrNal(const std::vector<uint8_t>& bytes)
{
for (size_t i = 0; i + 4 < bytes.size(); ++i) {
if (bytes[i] != 0 || bytes[i + 1] != 0) {
continue;
}
const size_t start_code_size = bytes[i + 2] == 1 ? 3 :
(bytes[i + 2] == 0 && bytes[i + 3] == 1 ? 4 : 0);
if (start_code_size != 0 && i + start_code_size < bytes.size() &&
(bytes[i + start_code_size] & 0x1f) == 5) {
return true;
}
}
return false;
}
TEST(MujocoCameraTest, WaitEncodedFramePublishesEachExternalFrameOncePerSubscriber)
{
constexpr int kWidth = 64;
constexpr int kHeight = 48;
std::atomic<uint64_t> available_frame_id{1};
cmvr::config::MujocoCameraConfig config;
config.set_id("mujoco_external_stream_test_cam");
auto* render = config.mutable_render();
render->set_width(kWidth);
render->set_height(kHeight);
render->set_fps(30);
render->set_stream_mode(cmvr::config::STREAM_MODE_RGBD);
auto* encoder = config.mutable_encoder();
encoder->set_width(kWidth);
encoder->set_height(kHeight);
encoder->set_fps(30);
encoder->set_codec("H264");
// The deployed external camera permits repeated reads of its last raw
// image. Encoded subscribers must still advance only on a new frame ID.
config.set_consume_new_frame_only(false);
cmvr::device::MujocoCamera camera(config);
camera.setFetchRgbdFn([&](std::vector<unsigned char>& rgb,
std::vector<float>& depth,
int& width,
int& height,
uint64_t& frame_id) {
frame_id = available_frame_id.load();
if (frame_id == 0) {
return false;
}
width = kWidth;
height = kHeight;
rgb.assign(kWidth * kHeight * 3, static_cast<unsigned char>(frame_id * 40));
depth.assign(kWidth * kHeight, static_cast<float>(frame_id));
return true;
});
cmvr::device::AbstractCamera* base = &camera;
ASSERT_TRUE(camera.init());
ASSERT_TRUE(base->startStreaming());
size_t first_cursor = 0;
cmvr::device::StreamFrameData first;
ASSERT_TRUE(base->waitEncodedFrame(first, first_cursor, std::chrono::seconds(2)));
EXPECT_EQ(first_cursor, 1U);
EXPECT_EQ(first.sequence, 1U);
EXPECT_EQ(first.codec, "H264");
EXPECT_EQ(first.width, kWidth);
EXPECT_EQ(first.height, kHeight);
EXPECT_TRUE(first.bKey);
EXPECT_TRUE(beginsWithAnnexBStartCode(first.rgbFrame));
EXPECT_TRUE(containsH264IdrNal(first.rgbFrame));
// Each subscriber owns a cursor; reading once must not consume the frame
// for another subscriber, or run the encoder again for the same image.
size_t second_cursor = 0;
cmvr::device::StreamFrameData same_first;
ASSERT_TRUE(base->waitEncodedFrame(same_first, second_cursor, std::chrono::milliseconds(100)));
EXPECT_EQ(second_cursor, first_cursor);
EXPECT_EQ(same_first.sequence, first.sequence);
EXPECT_EQ(same_first.rgbFrame, first.rgbFrame);
size_t latest_cursor = 0;
cmvr::device::StreamFrameData latest;
ASSERT_TRUE(base->getLatestEncodedFrame(latest, latest_cursor));
EXPECT_EQ(latest_cursor, first_cursor);
EXPECT_EQ(latest.sequence, first.sequence);
EXPECT_EQ(latest.rgbFrame, first.rgbFrame);
// Releasing one of two stream leases must not stop the other subscriber.
ASSERT_TRUE(base->startStreaming());
base->stopStreaming();
cmvr::device::StreamFrameData repeated;
EXPECT_FALSE(base->waitEncodedFrame(repeated, first_cursor, std::chrono::milliseconds(150)));
EXPECT_EQ(first_cursor, 1U);
available_frame_id.store(2);
cmvr::device::StreamFrameData second;
ASSERT_TRUE(base->waitEncodedFrame(second, first_cursor, std::chrono::seconds(2)));
EXPECT_EQ(first_cursor, 2U);
EXPECT_EQ(second.sequence, first.sequence + 1);
EXPECT_FALSE(second.rgbFrame.empty());
EXPECT_EQ(second.rgbImage.at<cv::Vec3b>(0, 0), cv::Vec3b(80, 80, 80));
cmvr::device::StreamFrameData same_second;
ASSERT_TRUE(base->waitEncodedFrame(same_second, second_cursor, std::chrono::milliseconds(100)));
EXPECT_EQ(second_cursor, first_cursor);
EXPECT_EQ(same_second.sequence, second.sequence);
EXPECT_EQ(same_second.rgbFrame, second.rgbFrame);
// The gRPC stream requests an IDR after dropping its pending frames.
// The next captured image must recover decoder continuity immediately.
ASSERT_TRUE(base->requestKeyFrame());
available_frame_id.store(3);
cmvr::device::StreamFrameData recovered;
ASSERT_TRUE(base->waitEncodedFrame(recovered, first_cursor, std::chrono::seconds(2)));
EXPECT_TRUE(recovered.bKey);
EXPECT_TRUE(containsH264IdrNal(recovered.rgbFrame));
EXPECT_EQ(recovered.sequence, second.sequence + 1);
// Keep the caller's cursor across a streaming restart. The new epoch must
// begin with a decodable key frame and a strictly newer sequence.
base->stopStreaming();
ASSERT_TRUE(base->startStreaming());
cmvr::device::StreamFrameData restarted;
ASSERT_TRUE(base->waitEncodedFrame(restarted, first_cursor, std::chrono::seconds(2)));
EXPECT_GT(first_cursor, second_cursor);
EXPECT_GT(restarted.sequence, second.sequence);
EXPECT_GT(restarted.stream_epoch, second.stream_epoch);
EXPECT_TRUE(restarted.bKey);
EXPECT_TRUE(beginsWithAnnexBStartCode(restarted.rgbFrame));
base->stopStreaming();
EXPECT_TRUE(camera.stop());
}
TEST(MujocoCameraTest, CapturesOffscreenRgbdFrame)
{
cmvr::config::MujocoWorldConfig world_config;

View File

@ -21,11 +21,16 @@ namespace cmvr::device {
uint8_t data[8];
/// Time stamp
struct timeval timestamp;
/// CAN frame flags, kept separately from the numeric message id.
bool is_extended;
bool is_remote;
bool is_error;
/**
* @brief Constructor
*/
CanFrame() : id(0), len(0), timestamp{0} {
CanFrame() : id(0), len(0), timestamp{0},
is_extended(false), is_remote(false), is_error(false) {
std::memset(data, 0, sizeof(data));
}

View File

@ -11,7 +11,11 @@
#include "socket_can_client_raw.h"
#include "absl/strings/str_cat.h"
#include <algorithm>
#include <cerrno>
#include <limits>
#include <poll.h>
namespace cmvr {
namespace device {
@ -53,20 +57,13 @@ namespace cmvr {
stop();
}
bool SocketCanClientRaw::configureReceiveTimeout(int fd) {
// CanReceiver::Stop joins before closing the bus. A silent CAN bus
// must therefore return periodically so its stop flag is observed.
const timeval timeout{0, 20000}; // 20 ms, not a protocol reply timeout.
return ::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) == 0;
}
bool SocketCanClientRaw::start() {
if (is_started_) {
status_ = ErrorCode::OK;
return true;
}
struct sockaddr_can addr;
struct ifreq ifr;
struct sockaddr_can addr {};
struct ifreq ifr {};
// open device
// guss net is the device minor number, if one card is 0,1
@ -79,12 +76,12 @@ namespace cmvr {
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
return false;
}
if (!configureReceiveTimeout(dev_handler_)) {
CMVR_LOG(ERROR) << "Cannot configure CAN receive timeout: " << std::strerror(errno);
stop();
const auto fail_start = [this]() {
::close(dev_handler_);
dev_handler_ = -1;
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
return false;
}
};
// init config and state
int ret;
@ -102,22 +99,12 @@ namespace cmvr {
sizeof(filter));
if (ret < 0) {
CMVR_LOG(ERROR) << "add receive msg id filter error code: " << ret;
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
stop();
return false;
return fail_start();
}
}
// 2. enable reception of can frames.
int enable = 1;
ret = ::setsockopt(dev_handler_, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable,
sizeof(enable));
if (ret < 0) {
CMVR_LOG(ERROR) << "enable reception of can frame error code: " << ret;
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
stop();
return false;
}
// CAN_RAW_FD_FRAMES is disabled by default. CanFrame holds only
// classical CAN's eight data bytes, so never enable CAN FD here.
std::string interface_prefix;
if (interface_ == CANCardParameter::VIRTUAL) {
@ -130,12 +117,10 @@ namespace cmvr {
}
const std::string can_name = absl::StrCat(interface_prefix, port_);
std::strncpy(ifr.ifr_name, can_name.c_str(), IFNAMSIZ);
std::strncpy(ifr.ifr_name, can_name.c_str(), IFNAMSIZ - 1);
if (ioctl(dev_handler_, SIOCGIFINDEX, &ifr) < 0) {
CMVR_LOG(ERROR) << "ioctl error";
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
stop();
return false;
return fail_start();
}
// bind socket to network interface
@ -147,9 +132,7 @@ namespace cmvr {
if (ret < 0) {
CMVR_LOG(ERROR) << "bind socket to network interface error code: " << ret;
status_ = ErrorCode::CAN_CLIENT_ERROR_BASE;
stop();
return false;
return fail_start();
}
is_started_ = true;
@ -162,7 +145,6 @@ namespace cmvr {
if (dev_handler_ >= 0) {
const int fd = dev_handler_;
dev_handler_ = -1;
int ret = close(fd);
if (ret < 0) {
CMVR_LOG(ERROR) << "close error code:" << ret << ", " << getErrorString(ret);
@ -216,46 +198,107 @@ namespace cmvr {
return ErrorCode::OK;
}
// buf size must be 8 bytes, every time, we receive only one frame
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) {
if (!frames || !frame_num) return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
const int32_t capacity = *frame_num;
frames->clear();
return receive(frames, frame_num, std::chrono::milliseconds{-1});
}
ErrorCode SocketCanClientRaw::receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num,
std::chrono::milliseconds timeout) {
if (frame_num == nullptr) {
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
}
const int32_t requested = *frame_num;
*frame_num = 0;
if (frames == nullptr) {
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (!is_started_) {
CMVR_LOG(ERROR) << "Nvidia can client is not init! Please init first!";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (capacity > MAX_CAN_RECV_FRAME_LEN || capacity < 0) {
if (requested > MAX_CAN_RECV_FRAME_LEN || requested < 0) {
CMVR_LOG(ERROR) << "recv can frame num not in range[0, " << MAX_CAN_RECV_FRAME_LEN
<< "], frame_num:" << capacity;
// TODO(Authors): check the difference of returning frame_num/error_code
<< "], frame_num:" << requested;
return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;
}
for (int32_t i = 0; i < capacity; ++i) {
CanFrame cf;
// Wait only for the first frame; drain a batch without waiting
// for it to fill. No-data and interrupted reads are not errors.
auto ret = ::recv(dev_handler_, &recv_frames_[i], sizeof(recv_frames_[i]),
i == 0 ? 0 : MSG_DONTWAIT);
if (ret < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) break;
CMVR_LOG(ERROR) << "receive message failed: " << std::strerror(errno);
return ErrorCode::CAN_CLIENT_ERROR_BASE;
const bool bounded = timeout.count() >= 0;
const auto started = std::chrono::steady_clock::now();
bool first_poll = true;
while (*frame_num < requested) {
int wait_ms = -1;
if (bounded) {
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - started);
if (!first_poll && elapsed >= timeout) {
return ErrorCode::OK;
}
const auto remaining = timeout > elapsed ? timeout - elapsed
: std::chrono::milliseconds{0};
wait_ms = static_cast<int>(std::min<int64_t>(
remaining.count(), std::numeric_limits<int>::max()));
}
if (ret != sizeof(can_frame)) return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
if (recv_frames_[i].can_dlc > CANBUS_MESSAGE_LENGTH ||
recv_frames_[i].can_dlc < 0) {
first_poll = false;
struct pollfd descriptor {dev_handler_, POLLIN, 0};
const int ready = ::poll(&descriptor, 1, wait_ms);
if (ready < 0) {
if (errno == EINTR) {
continue;
}
CMVR_LOG(ERROR) << "poll can socket failed: " << std::strerror(errno);
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (ready == 0) {
if (!bounded) {
continue;
}
// A long timeout may need several poll calls (poll takes int).
if (std::chrono::steady_clock::now() - started < timeout) {
continue;
}
return ErrorCode::OK;
}
if (descriptor.revents & (POLLERR | POLLHUP | POLLNVAL)) {
CMVR_LOG(ERROR) << "can socket poll error flags: " << descriptor.revents;
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (!(descriptor.revents & POLLIN)) {
continue;
}
const int32_t i = *frame_num;
// Do not block after poll if another reader consumed the packet.
// recvmsg also identifies truncated/FD packets even if the
// socket reports only the length copied into our CAN buffer.
struct iovec buffer {&recv_frames_[i], sizeof(recv_frames_[i])};
struct msghdr message {};
message.msg_iov = &buffer;
message.msg_iovlen = 1;
const auto ret = ::recvmsg(dev_handler_, &message, MSG_DONTWAIT);
if (ret < 0) {
if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
continue;
}
CMVR_LOG(ERROR) << "receive message failed: " << std::strerror(errno);
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (ret != CAN_MTU || (message.msg_flags & MSG_TRUNC)) {
CMVR_LOG(ERROR) << "received non-classical or incomplete CAN frame: " << ret;
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
if (recv_frames_[i].can_dlc > CANBUS_MESSAGE_LENGTH) {
CMVR_LOG(ERROR) << "recv_frames_[" << i
<< "].can_dlc = " << recv_frames_[i].can_dlc
<< ", which is not equal to can message data length ("
<< CANBUS_MESSAGE_LENGTH << ").";
return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;
}
CanFrame cf;
cf.is_extended = (recv_frames_[i].can_id & CAN_EFF_FLAG) != 0;
cf.is_remote = (recv_frames_[i].can_id & CAN_RTR_FLAG) != 0;
cf.is_error = (recv_frames_[i].can_id & CAN_ERR_FLAG) != 0;
if (recv_frames_[i].can_id > CAN_STANDARD_MAX_ID) {
cf.id = enable_can_err_check_
? recv_frames_[i].can_id & CAN_EFF_MASK | CAN_ERR_FLAG

View File

@ -15,6 +15,7 @@
#include <linux/can/raw.h>
#include <cstdio>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <string>
@ -61,14 +62,22 @@ namespace cmvr {
cmvr::msgs::ErrorCode receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num) override;
/**
* @brief Receive up to frame_num messages within one timeout.
* @param frame_num Requested count on input, actual appended count on output.
* @param timeout Maximum wait for the whole call; negative waits indefinitely.
* @return OK on timeout, including when no frames were received.
*/
cmvr::msgs::ErrorCode receive(std::vector<CanFrame> *const frames,
int32_t *const frame_num,
std::chrono::milliseconds timeout);
/**
* @brief Get the error string.
* @param status The status to get the error string.
*/
std::string getErrorString(const int32_t status) override;
private:
friend class SocketCanClientRawTestPeer;
static bool configureReceiveTimeout(int fd);
int dev_handler_ = -1;
cmvr::msgs::CANCardParameter::CANChannelId port_;
cmvr::msgs::CANCardParameter::CANInterface interface_;

View File

@ -24,6 +24,7 @@ namespace cmvr::device {
MujocoWorld,
Robot,
Speaker,
Touch,
};
inline std::string toString(DeviceKind kind) {
@ -58,6 +59,8 @@ namespace cmvr::device {
return "Robot";
case DeviceKind::Speaker:
return "Speaker";
case DeviceKind::Touch:
return "Touch";
case DeviceKind::Unknown:
default:
return "Unknown";

View File

@ -10,7 +10,7 @@ target_include_directories(dexhand INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(dexhand
INTERFACE
cmvr_es::device::rh56dftp_dexhand
cmvr_es::device::px_6ax_gen3
cmvr_es::device::legacy_px_6ax_gen3
cmvr_es::device::zero_sim_touch_dexhand
cmvr_es::device::oymotion_ap001
cmvr_es::proto

View File

@ -15,6 +15,7 @@
#include <vector>
#include "devices/abstract_device.h"
#include "devices/touch/touch_types.h"
#include "common/base/logging/logger.h"
namespace cmvr::device {
@ -22,38 +23,10 @@ namespace cmvr::device {
public:
DeviceKind kind() const noexcept override { return DeviceKind::DexHand; }
struct TactilePoint {
int32_t fx{0};
int32_t fy{0};
int32_t fz{0};
static TactilePoint fromFz(const int32_t value) {
return TactilePoint{0, 0, value};
}
double magnitude() const {
return std::sqrt(static_cast<double>(fx) * static_cast<double>(fx) +
static_cast<double>(fy) * static_cast<double>(fy) +
static_cast<double>(fz) * static_cast<double>(fz));
}
bool isZero() const {
return fx == 0 && fy == 0 && fz == 0;
}
};
using TactilePoint = cmvr::device::TactilePoint;
using ResultantForce = TactilePoint;
// Physical force, separate from device-specific integer tactile data.
struct ForceNewtons {
double fx{0.0};
double fy{0.0};
double fz{0.0};
double magnitude() const {
return std::hypot(fx, fy, fz);
}
};
using ForceNewtons = cmvr::device::ForceNewtons;
using TactileMatrixView = cmvr::device::TactileMatrixView;
enum class FingerType {
PINKY,
@ -74,28 +47,6 @@ namespace cmvr::device {
using TactileRegionKey = std::pair<FingerType, TactileRegion>;
struct TactileMatrixView {
const TactilePoint* data{nullptr};
int rows{0};
int cols{0};
bool valid() const {
return data != nullptr && rows > 0 && cols > 0;
}
int pointCount() const {
return rows * cols;
}
const TactilePoint* rowData(int row) const {
return data + row * cols;
}
TactilePoint at(int row, int col) const {
return data[row * cols + col];
}
};
class TactileRegionData {
public:
TactileRegionData() = default;

View File

@ -33,7 +33,7 @@ public:
break;
case config::DexHandDeviceConfig::kPx6AxGen3:
device = std::make_shared<PX6AXGen3>(
device = std::make_shared<LegacyPX6AXGen3>(
backendWithId_(cfg.id(), cfg.px_6ax_gen3()));
break;

View File

@ -1,23 +1,23 @@
add_library(px_6ax_gen3 SHARED src/px_6ax_gen3.cpp)
add_library(legacy_px_6ax_gen3 SHARED src/px_6ax_gen3.cpp)
target_include_directories(px_6ax_gen3 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(legacy_px_6ax_gen3 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
add_library(cmvr_es::device::px_6ax_gen3 ALIAS px_6ax_gen3)
add_library(cmvr_es::device::legacy_px_6ax_gen3 ALIAS legacy_px_6ax_gen3)
target_link_libraries(px_6ax_gen3
target_link_libraries(legacy_px_6ax_gen3
PUBLIC cmvr_es::hardware
PRIVATE
cmvr_es::proto
glog
)
install(TARGETS px_6ax_gen3 LIBRARY DESTINATION lib)
install(TARGETS legacy_px_6ax_gen3 LIBRARY DESTINATION lib)
# Sensor-only executable: no DeviceManager, arm initialization or calibration.
add_executable(px_6ax_gen3_real_test src/px_6ax_gen3_real_test.cpp)
target_link_libraries(px_6ax_gen3_real_test PRIVATE
px_6ax_gen3 cmvr_es::proto cmvr_es::logging pthread)
add_executable(legacy_px_6ax_gen3_real_test src/px_6ax_gen3_real_test.cpp)
target_link_libraries(legacy_px_6ax_gen3_real_test PRIVATE
legacy_px_6ax_gen3 cmvr_es::proto cmvr_es::logging pthread)
add_executable(px_6ax_gen3_test src/px_6ax_gen3_test.cpp)
target_link_libraries(px_6ax_gen3_test PRIVATE
px_6ax_gen3 cmvr_es::proto cmvr_es::logging gtest gtest_main pthread)
add_executable(legacy_px_6ax_gen3_test src/px_6ax_gen3_test.cpp)
target_link_libraries(legacy_px_6ax_gen3_test PRIVATE
legacy_px_6ax_gen3 cmvr_es::proto cmvr_es::logging gtest gtest_main pthread)

Some files were not shown because too many files have changed in this diff Show More