upload
This commit is contained in:
101
libs/vslam_common/src/clock.cc
Normal file
101
libs/vslam_common/src/clock.cc
Normal file
@@ -0,0 +1,101 @@
|
||||
#include "vslam/clock.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
class SystemClock : public Clock {
|
||||
public:
|
||||
UnixTime Now() const override { return UnixTime::now(); }
|
||||
|
||||
SteadyPoint Steady() const override { return std::chrono::steady_clock::now(); }
|
||||
|
||||
void SleepUntil(SteadyPoint tp) override {
|
||||
std::this_thread::sleep_until(tp);
|
||||
}
|
||||
|
||||
bool is_virtual() const override { return false; }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
ClockPtr MakeSystemClock() { return std::make_shared<SystemClock>(); }
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
struct ReplayClock::Impl {
|
||||
mutable std::mutex mu;
|
||||
UnixTime now;
|
||||
SteadyPoint steady_origin;
|
||||
std::chrono::nanoseconds steady_offset{0};
|
||||
double speed = 0.0; // 0 = chay nhanh nhat, khong ngu that
|
||||
};
|
||||
|
||||
ReplayClock::ReplayClock(UnixTime start) : impl_(std::make_unique<Impl>()) {
|
||||
impl_->now = start;
|
||||
impl_->steady_origin = std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
ReplayClock::~ReplayClock() = default;
|
||||
|
||||
UnixTime ReplayClock::Now() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->now;
|
||||
}
|
||||
|
||||
Clock::SteadyPoint ReplayClock::Steady() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->steady_origin + impl_->steady_offset;
|
||||
}
|
||||
|
||||
void ReplayClock::SleepUntil(SteadyPoint tp) {
|
||||
double speed;
|
||||
SteadyPoint current;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
speed = impl_->speed;
|
||||
current = impl_->steady_origin + impl_->steady_offset;
|
||||
if (tp > current) {
|
||||
// Thoi gian ao luon tien toi moc yeu cau, ke ca khi khong ngu that.
|
||||
impl_->steady_offset += (tp - current);
|
||||
}
|
||||
}
|
||||
if (speed > 0.0 && tp > current) {
|
||||
const auto wall = std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
(tp - current) / speed);
|
||||
std::this_thread::sleep_for(wall);
|
||||
}
|
||||
}
|
||||
|
||||
void ReplayClock::SetNow(UnixTime t, bool allow_backward) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
if (!allow_backward && t < impl_->now) {
|
||||
// Lui thoi gian la dau hieu ban ghi bi xao tron thu tu. Bao chu khong
|
||||
// im lang chap nhan -- neu im lang thi moi phep timeout sau do deu sai.
|
||||
VSLAM_WARN("ReplayClock: tu choi lui thoi gian " << impl_->now.toString()
|
||||
<< " -> " << t.toString());
|
||||
return;
|
||||
}
|
||||
impl_->now = t;
|
||||
}
|
||||
|
||||
void ReplayClock::Advance(Duration d) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
impl_->now = impl_->now + d;
|
||||
impl_->steady_offset += std::chrono::nanoseconds(d.toNSec());
|
||||
}
|
||||
|
||||
void ReplayClock::SetSpeed(double speed) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
impl_->speed = speed < 0.0 ? 0.0 : speed;
|
||||
}
|
||||
|
||||
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start) {
|
||||
return std::make_shared<ReplayClock>(start);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
234
libs/vslam_common/src/config.cc
Normal file
234
libs/vslam_common/src/config.cc
Normal file
@@ -0,0 +1,234 @@
|
||||
#include "vslam/config.h"
|
||||
|
||||
#include <yaml-cpp/yaml.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
struct ConfigNode::Impl {
|
||||
YAML::Node node;
|
||||
std::string path; // "safety.scan.stop_distance"
|
||||
std::string origin; // ten file
|
||||
|
||||
Impl() = default;
|
||||
Impl(YAML::Node n, std::string p, std::string o)
|
||||
: node(std::move(n)), path(std::move(p)), origin(std::move(o)) {}
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
std::string JoinPath(const std::string& base, const std::string& key) {
|
||||
return base.empty() ? key : base + "." + key;
|
||||
}
|
||||
|
||||
// Thong bao loi luon co ba manh: file, duong dan key day du, va ly do.
|
||||
// Thieu bat cu manh nao la nguoi doc phai di tim, va do chinh la thu lam
|
||||
// viec sua config trong ban ROS ton thoi gian.
|
||||
//
|
||||
// Nhan chuoi chu khong nhan ConfigNode::Impl: Impl la kieu private, ham tu do
|
||||
// trong namespace vo danh khong goi ten no duoc.
|
||||
std::string Where(const std::string& origin, const std::string& path,
|
||||
const std::string& key) {
|
||||
std::ostringstream oss;
|
||||
oss << origin << ": " << JoinPath(path, key);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ConfigNode::ConfigNode() : impl_(std::make_unique<Impl>()) {}
|
||||
|
||||
ConfigNode::ConfigNode(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
|
||||
|
||||
ConfigNode::ConfigNode(const ConfigNode& o) : impl_(std::make_unique<Impl>(*o.impl_)) {}
|
||||
|
||||
ConfigNode::ConfigNode(ConfigNode&&) noexcept = default;
|
||||
|
||||
ConfigNode& ConfigNode::operator=(const ConfigNode& o) {
|
||||
if (this != &o) impl_ = std::make_unique<Impl>(*o.impl_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
ConfigNode& ConfigNode::operator=(ConfigNode&&) noexcept = default;
|
||||
|
||||
ConfigNode::~ConfigNode() = default;
|
||||
|
||||
ConfigNode ConfigNode::LoadFile(const std::string& path) {
|
||||
try {
|
||||
YAML::Node root = YAML::LoadFile(path);
|
||||
return ConfigNode(std::make_unique<Impl>(std::move(root), "", path));
|
||||
} catch (const YAML::BadFile&) {
|
||||
throw ConfigError("khong mo duoc file cau hinh: " + path);
|
||||
} catch (const YAML::Exception& e) {
|
||||
throw ConfigError("YAML sai cu phap trong " + path + ": " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
ConfigNode ConfigNode::LoadString(const std::string& yaml, std::string origin) {
|
||||
try {
|
||||
YAML::Node root = YAML::Load(yaml);
|
||||
return ConfigNode(std::make_unique<Impl>(std::move(root), "", std::move(origin)));
|
||||
} catch (const YAML::Exception& e) {
|
||||
throw ConfigError("YAML sai cu phap trong " + origin + ": " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
ConfigNode ConfigNode::operator[](const std::string& key) const {
|
||||
// Key thieu tra node Null thay vi nem, de chuoi a["b"]["c"] khong no giua
|
||||
// chung. Nguoi goi kiem IsNull() hoac dung require() o buoc cuoi.
|
||||
if (!impl_->node || !impl_->node.IsMap()) {
|
||||
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
|
||||
JoinPath(impl_->path, key), impl_->origin));
|
||||
}
|
||||
return ConfigNode(std::make_unique<Impl>(impl_->node[key],
|
||||
JoinPath(impl_->path, key), impl_->origin));
|
||||
}
|
||||
|
||||
ConfigNode ConfigNode::at(size_t index) const {
|
||||
std::ostringstream oss;
|
||||
oss << impl_->path << "[" << index << "]";
|
||||
if (!impl_->node || !impl_->node.IsSequence() || index >= impl_->node.size()) {
|
||||
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
|
||||
oss.str(), impl_->origin));
|
||||
}
|
||||
return ConfigNode(std::make_unique<Impl>(impl_->node[index], oss.str(), impl_->origin));
|
||||
}
|
||||
|
||||
bool ConfigNode::IsNull() const {
|
||||
return !impl_->node || impl_->node.IsNull() ||
|
||||
impl_->node.Type() == YAML::NodeType::Undefined;
|
||||
}
|
||||
bool ConfigNode::IsMap() const { return impl_->node && impl_->node.IsMap(); }
|
||||
bool ConfigNode::IsSequence() const { return impl_->node && impl_->node.IsSequence(); }
|
||||
bool ConfigNode::IsScalar() const { return impl_->node && impl_->node.IsScalar(); }
|
||||
size_t ConfigNode::size() const { return impl_->node ? impl_->node.size() : 0; }
|
||||
|
||||
const std::string& ConfigNode::path() const { return impl_->path; }
|
||||
const std::string& ConfigNode::origin() const { return impl_->origin; }
|
||||
|
||||
// --- Doc gia tri -----------------------------------------------------------
|
||||
|
||||
template <typename T>
|
||||
T ConfigNode::get(const std::string& key, const T& fallback) const {
|
||||
const ConfigNode child = (*this)[key];
|
||||
if (child.IsNull()) return fallback;
|
||||
try {
|
||||
return child.impl_->node.template as<T>();
|
||||
} catch (const YAML::Exception&) {
|
||||
// Sai KIEU luon la loi, khac han voi THIEU key. Thieu key co the co y
|
||||
// (dung default); sai kieu thi khong bao gio co y.
|
||||
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T ConfigNode::require(const std::string& key) const {
|
||||
const ConfigNode child = (*this)[key];
|
||||
if (child.IsNull()) {
|
||||
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": thieu key bat buoc");
|
||||
}
|
||||
try {
|
||||
return child.impl_->node.template as<T>();
|
||||
} catch (const YAML::Exception&) {
|
||||
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T ConfigNode::as() const {
|
||||
if (IsNull()) {
|
||||
throw ConfigError(impl_->origin + ": " + impl_->path + ": thieu gia tri");
|
||||
}
|
||||
try {
|
||||
return impl_->node.template as<T>();
|
||||
} catch (const YAML::Exception&) {
|
||||
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
T ConfigNode::as(const T& fallback) const {
|
||||
if (IsNull()) return fallback;
|
||||
try {
|
||||
return impl_->node.template as<T>();
|
||||
} catch (const YAML::Exception&) {
|
||||
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Kiem key la -----------------------------------------------------------
|
||||
|
||||
std::vector<std::string> ConfigNode::Keys() const {
|
||||
std::vector<std::string> out;
|
||||
if (!IsMap()) return out;
|
||||
for (const auto& kv : impl_->node) {
|
||||
out.push_back(kv.first.as<std::string>());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::vector<std::string> ConfigNode::UnknownKeys(
|
||||
const std::vector<std::string>& known) const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& k : Keys()) {
|
||||
if (std::find(known.begin(), known.end(), k) == known.end()) {
|
||||
out.push_back(JoinPath(impl_->path, k));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool ConfigNode::WarnUnknownKeys(const std::vector<std::string>& known) const {
|
||||
const auto unknown = UnknownKeys(known);
|
||||
for (const auto& k : unknown) {
|
||||
// ERROR chu khong phai WARN: mot key la gan nhu luon la go sai ten cua
|
||||
// mot key that, nghia la gia tri nguoi dung DINH dat dang khong co tac
|
||||
// dung. "stop_distence" thay vi "stop_distance" van cho robot chay, chi
|
||||
// la chay voi khoang cach dung mac dinh.
|
||||
VSLAM_ERROR(impl_->origin << ": key khong nhan ra: " << k);
|
||||
}
|
||||
return unknown.empty();
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::string, std::string>> ConfigNode::AsStringMap() const {
|
||||
std::vector<std::pair<std::string, std::string>> out;
|
||||
if (!IsMap()) return out;
|
||||
for (const auto& kv : impl_->node) {
|
||||
// Giu nguyen van ca khoa lan gia tri. Khoi `rtabmap:` trong slam.yaml di
|
||||
// thang vao rtabmap::ParametersMap, noi moi gia tri deu la chuoi -- kiem
|
||||
// kieu o day se lam hong "true"/"0.05" thanh bool/double roi in lai khac.
|
||||
out.emplace_back(kv.first.as<std::string>(), kv.second.as<std::string>());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- Khoi tao tuong minh ---------------------------------------------------
|
||||
|
||||
#define VSLAM_CONFIG_DEFINE(T) \
|
||||
template T ConfigNode::get<T>(const std::string&, const T&) const; \
|
||||
template T ConfigNode::require<T>(const std::string&) const; \
|
||||
template T ConfigNode::as<T>() const; \
|
||||
template T ConfigNode::as<T>(const T&) const;
|
||||
|
||||
VSLAM_CONFIG_DEFINE(bool)
|
||||
VSLAM_CONFIG_DEFINE(int)
|
||||
VSLAM_CONFIG_DEFINE(unsigned int)
|
||||
VSLAM_CONFIG_DEFINE(float)
|
||||
VSLAM_CONFIG_DEFINE(double)
|
||||
VSLAM_CONFIG_DEFINE(std::string)
|
||||
#undef VSLAM_CONFIG_DEFINE
|
||||
|
||||
template std::vector<double> ConfigNode::get<std::vector<double>>(
|
||||
const std::string&, const std::vector<double>&) const;
|
||||
template std::vector<double> ConfigNode::require<std::vector<double>>(
|
||||
const std::string&) const;
|
||||
template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
|
||||
const std::string&, const std::vector<std::string>&) const;
|
||||
template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
|
||||
const std::string&) const;
|
||||
|
||||
} // namespace vslam
|
||||
235
libs/vslam_common/src/geometry.cc
Normal file
235
libs/vslam_common/src/geometry.cc
Normal file
@@ -0,0 +1,235 @@
|
||||
#include "vslam/geometry.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
constexpr double kTwoPi = 2.0 * kPi;
|
||||
|
||||
} // namespace
|
||||
|
||||
// --- Goc -------------------------------------------------------------------
|
||||
|
||||
double NormalizeAngle(double a) {
|
||||
// Port tu wheel_odom_node.cpp:45-50. Ban goc dung vong while; std::fmod
|
||||
// nhanh hon va khong treo khi input la mot so rat lon (vd NaN lan vao tu
|
||||
// encoder hong -> vong while chay vo han).
|
||||
if (!std::isfinite(a)) return 0.0;
|
||||
a = std::fmod(a + kPi, kTwoPi);
|
||||
if (a < 0.0) a += kTwoPi;
|
||||
return a - kPi;
|
||||
}
|
||||
|
||||
// --- Quaternion ------------------------------------------------------------
|
||||
|
||||
Quaternion QuaternionFromYaw(double yaw) {
|
||||
const double h = yaw * 0.5;
|
||||
return Quaternion{0.0, 0.0, std::sin(h), std::cos(h)};
|
||||
}
|
||||
|
||||
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw) {
|
||||
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
|
||||
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
|
||||
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
|
||||
Quaternion q;
|
||||
q.w = cr * cp * cy + sr * sp * sy;
|
||||
q.x = sr * cp * cy - cr * sp * sy;
|
||||
q.y = cr * sp * cy + sr * cp * sy;
|
||||
q.z = cr * cp * sy - sr * sp * cy;
|
||||
return q;
|
||||
}
|
||||
|
||||
double YawFromQuaternion(const Quaternion& q) {
|
||||
const double siny = 2.0 * (q.w * q.z + q.x * q.y);
|
||||
const double cosy = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
|
||||
return std::atan2(siny, cosy);
|
||||
}
|
||||
|
||||
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw) {
|
||||
const double sinr = 2.0 * (q.w * q.x + q.y * q.z);
|
||||
const double cosr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
|
||||
if (roll) *roll = std::atan2(sinr, cosr);
|
||||
|
||||
// Kep truoc khi asin: sai so lam tron co the day gia tri ra ngoai [-1,1]
|
||||
// va asin tra NaN. NaN o pitch lan vao gravity_align roi vao TF la mot
|
||||
// trong nhung duong lan truyen loi kho truy nhat.
|
||||
double sinp = 2.0 * (q.w * q.y - q.z * q.x);
|
||||
sinp = std::max(-1.0, std::min(1.0, sinp));
|
||||
if (pitch) *pitch = std::asin(sinp);
|
||||
|
||||
if (yaw) *yaw = YawFromQuaternion(q);
|
||||
}
|
||||
|
||||
Quaternion QuaternionNormalized(const Quaternion& q) {
|
||||
const double n = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
|
||||
if (n < 1e-12) return Quaternion{0.0, 0.0, 0.0, 1.0};
|
||||
const double inv = 1.0 / n;
|
||||
return Quaternion{q.x * inv, q.y * inv, q.z * inv, q.w * inv};
|
||||
}
|
||||
|
||||
Quaternion QuaternionInverse(const Quaternion& q) {
|
||||
// Gia dinh q da chuan hoa -> nghich dao = lien hop.
|
||||
return Quaternion{-q.x, -q.y, -q.z, q.w};
|
||||
}
|
||||
|
||||
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b) {
|
||||
Quaternion r;
|
||||
r.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
|
||||
r.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;
|
||||
r.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x;
|
||||
r.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w;
|
||||
return r;
|
||||
}
|
||||
|
||||
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t) {
|
||||
t = std::max(0.0, std::min(1.0, t));
|
||||
|
||||
double dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
|
||||
|
||||
// Lat dau de di duong ngan. Thieu buoc nay thi noi suy qua mot goc gan 360
|
||||
// do thay vi goc nho -- TF se "quay nguoc" mot cach ngoan muc.
|
||||
Quaternion bb = b;
|
||||
if (dot < 0.0) {
|
||||
bb = Quaternion{-b.x, -b.y, -b.z, -b.w};
|
||||
dot = -dot;
|
||||
}
|
||||
|
||||
// Gan trung nhau: LERP roi chuan hoa, tranh chia cho sin(theta) ~ 0.
|
||||
if (dot > 0.9995) {
|
||||
Quaternion r{a.x + (bb.x - a.x) * t, a.y + (bb.y - a.y) * t,
|
||||
a.z + (bb.z - a.z) * t, a.w + (bb.w - a.w) * t};
|
||||
return QuaternionNormalized(r);
|
||||
}
|
||||
|
||||
const double theta_0 = std::acos(dot);
|
||||
const double theta = theta_0 * t;
|
||||
const double sin_theta_0 = std::sin(theta_0);
|
||||
const double s0 = std::cos(theta) - dot * std::sin(theta) / sin_theta_0;
|
||||
const double s1 = std::sin(theta) / sin_theta_0;
|
||||
|
||||
return Quaternion{a.x * s0 + bb.x * s1, a.y * s0 + bb.y * s1,
|
||||
a.z * s0 + bb.z * s1, a.w * s0 + bb.w * s1};
|
||||
}
|
||||
|
||||
Vector3 RotateVector(const Quaternion& q, const Vector3& v) {
|
||||
// v' = v + 2w(u x v) + 2(u x (u x v)), voi u la phan vector cua q.
|
||||
// Re hon chuyen sang ma tran quay khi chi xoay mot vai vector.
|
||||
const double ux = q.x, uy = q.y, uz = q.z, w = q.w;
|
||||
const double cx = uy * v.z - uz * v.y;
|
||||
const double cy = uz * v.x - ux * v.z;
|
||||
const double cz = ux * v.y - uy * v.x;
|
||||
const double ccx = uy * cz - uz * cy;
|
||||
const double ccy = uz * cx - ux * cz;
|
||||
const double ccz = ux * cy - uy * cx;
|
||||
return Vector3{v.x + 2.0 * (w * cx + ccx),
|
||||
v.y + 2.0 * (w * cy + ccy),
|
||||
v.z + 2.0 * (w * cz + ccz)};
|
||||
}
|
||||
|
||||
// --- Transform -------------------------------------------------------------
|
||||
|
||||
Transform TransformIdentity() {
|
||||
Transform t;
|
||||
t.translation = Vector3{0.0, 0.0, 0.0};
|
||||
t.rotation = Quaternion{0.0, 0.0, 0.0, 1.0};
|
||||
return t;
|
||||
}
|
||||
|
||||
Transform TransformCompose(const Transform& a, const Transform& b) {
|
||||
Transform r;
|
||||
r.rotation = QuaternionMultiply(a.rotation, b.rotation);
|
||||
const Vector3 rb = RotateVector(a.rotation, b.translation);
|
||||
r.translation = a.translation + rb;
|
||||
return r;
|
||||
}
|
||||
|
||||
Transform TransformInverse(const Transform& t) {
|
||||
Transform r;
|
||||
r.rotation = QuaternionInverse(t.rotation);
|
||||
const Vector3 neg{-t.translation.x, -t.translation.y, -t.translation.z};
|
||||
r.translation = RotateVector(r.rotation, neg);
|
||||
return r;
|
||||
}
|
||||
|
||||
Point TransformPoint(const Transform& t, const Point& p) {
|
||||
const Vector3 v{p.x, p.y, p.z};
|
||||
const Vector3 r = RotateVector(t.rotation, v) + t.translation;
|
||||
return Point{r.x, r.y, r.z};
|
||||
}
|
||||
|
||||
Vector3 TransformVector(const Transform& t, const Vector3& v) {
|
||||
return RotateVector(t.rotation, v) + t.translation;
|
||||
}
|
||||
|
||||
Transform TransformInterpolate(const Transform& a, const Transform& b, double t) {
|
||||
Transform r;
|
||||
r.translation = Lerp(a.translation, b.translation, t);
|
||||
r.rotation = QuaternionSlerp(a.rotation, b.rotation, t);
|
||||
return r;
|
||||
}
|
||||
|
||||
// --- SE(2) -----------------------------------------------------------------
|
||||
|
||||
Pose2D Pose2DFromPose(const Pose& p) {
|
||||
return Pose2D{p.position.x, p.position.y, YawFromQuaternion(p.orientation)};
|
||||
}
|
||||
|
||||
Pose PoseFromPose2D(const Pose2D& p, double z) {
|
||||
Pose out;
|
||||
out.position = Point{p.x, p.y, z};
|
||||
out.orientation = QuaternionFromYaw(p.theta);
|
||||
return out;
|
||||
}
|
||||
|
||||
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b) {
|
||||
const double c = std::cos(a.theta), s = std::sin(a.theta);
|
||||
return Pose2D{a.x + c * b.x - s * b.y,
|
||||
a.y + s * b.x + c * b.y,
|
||||
NormalizeAngle(a.theta + b.theta)};
|
||||
}
|
||||
|
||||
Pose2D Pose2DInverse(const Pose2D& p) {
|
||||
const double c = std::cos(p.theta), s = std::sin(p.theta);
|
||||
return Pose2D{-(c * p.x + s * p.y),
|
||||
-(-s * p.x + c * p.y),
|
||||
NormalizeAngle(-p.theta)};
|
||||
}
|
||||
|
||||
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b) {
|
||||
// a^-1 * b, viet truc tiep thay vi ghep hai ham -- it phep tinh hon va
|
||||
// day la duong nong khi tinh delta giua hai keyframe.
|
||||
const double c = std::cos(a.theta), s = std::sin(a.theta);
|
||||
const double dx = b.x - a.x, dy = b.y - a.y;
|
||||
return Pose2D{c * dx + s * dy,
|
||||
-s * dx + c * dy,
|
||||
NormalizeAngle(b.theta - a.theta)};
|
||||
}
|
||||
|
||||
Transform TransformFromPose2D(const Pose2D& p, double z) {
|
||||
Transform t;
|
||||
t.translation = Vector3{p.x, p.y, z};
|
||||
t.rotation = QuaternionFromYaw(p.theta);
|
||||
return t;
|
||||
}
|
||||
|
||||
Pose2D Pose2DFromTransform(const Transform& t) {
|
||||
return Pose2D{t.translation.x, t.translation.y, YawFromQuaternion(t.rotation)};
|
||||
}
|
||||
|
||||
Transform TransformFromPose(const Pose& p) {
|
||||
Transform t;
|
||||
t.translation = Vector3{p.position.x, p.position.y, p.position.z};
|
||||
t.rotation = p.orientation;
|
||||
return t;
|
||||
}
|
||||
|
||||
Pose PoseFromTransform(const Transform& t) {
|
||||
Pose p;
|
||||
p.position = Point{t.translation.x, t.translation.y, t.translation.z};
|
||||
p.orientation = t.rotation;
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
65
libs/vslam_common/src/json_parse.cc
Normal file
65
libs/vslam_common/src/json_parse.cc
Normal file
@@ -0,0 +1,65 @@
|
||||
#include "vslam/json_parse.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Tra ve vi tri ngay sau dau ':' cua "key", hoac npos.
|
||||
size_t FindValue(const std::string& body, const std::string& key) {
|
||||
const std::string pat = "\"" + key + "\"";
|
||||
size_t p = body.find(pat);
|
||||
if (p == std::string::npos) return std::string::npos;
|
||||
p += pat.size();
|
||||
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
|
||||
if (p >= body.size() || body[p] != ':') return std::string::npos;
|
||||
++p;
|
||||
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
|
||||
return p < body.size() ? p : std::string::npos;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool JsonGetNumber(const std::string& body, const std::string& key, double* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos) return false;
|
||||
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(body.c_str() + p, &end);
|
||||
if (end == body.c_str() + p) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool JsonGetBool(const std::string& body, const std::string& key, bool* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos) return false;
|
||||
if (body.compare(p, 4, "true") == 0) { *out = true; return true; }
|
||||
if (body.compare(p, 5, "false") == 0) { *out = false; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
bool JsonGetString(const std::string& body, const std::string& key, std::string* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos || body[p] != '"') return false;
|
||||
|
||||
out->clear();
|
||||
for (size_t i = p + 1; i < body.size(); ++i) {
|
||||
if (body[i] == '\\' && i + 1 < body.size()) {
|
||||
++i;
|
||||
switch (body[i]) {
|
||||
case 'n': out->push_back('\n'); break;
|
||||
case 't': out->push_back('\t'); break;
|
||||
case 'r': out->push_back('\r'); break;
|
||||
default: out->push_back(body[i]); break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (body[i] == '"') return true;
|
||||
out->push_back(body[i]);
|
||||
}
|
||||
return false; // chuoi khong dong
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
141
libs/vslam_common/src/log.cc
Normal file
141
libs/vslam_common/src/log.cc
Normal file
@@ -0,0 +1,141 @@
|
||||
#include "vslam/log.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <mutex>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
std::atomic<int> g_level{static_cast<int>(LogLevel::kInfo)};
|
||||
std::atomic<bool> g_color{false};
|
||||
std::atomic<bool> g_color_init{false};
|
||||
|
||||
std::mutex& SinkMutex() {
|
||||
static std::mutex m;
|
||||
return m;
|
||||
}
|
||||
|
||||
LogSink& SinkRef() {
|
||||
static LogSink sink; // rong = dung sink mac dinh ra stderr
|
||||
return sink;
|
||||
}
|
||||
|
||||
const char* ColorFor(LogLevel l) {
|
||||
switch (l) {
|
||||
case LogLevel::kDebug: return "\033[2m"; // mo
|
||||
case LogLevel::kInfo: return "";
|
||||
case LogLevel::kWarn: return "\033[33m"; // vang
|
||||
case LogLevel::kError: return "\033[31m"; // do
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Chi lay ten file, bo duong dan. __FILE__ trong build tree rat dai.
|
||||
const char* BaseName(const char* path) {
|
||||
const char* slash = std::strrchr(path, '/');
|
||||
return slash != nullptr ? slash + 1 : path;
|
||||
}
|
||||
|
||||
bool ColorEnabled() {
|
||||
if (!g_color_init.load(std::memory_order_relaxed)) {
|
||||
g_color.store(::isatty(STDERR_FILENO) != 0, std::memory_order_relaxed);
|
||||
g_color_init.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
return g_color.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const char* LogLevelName(LogLevel l) {
|
||||
switch (l) {
|
||||
case LogLevel::kDebug: return "DEBUG";
|
||||
case LogLevel::kInfo: return "INFO";
|
||||
case LogLevel::kWarn: return "WARN";
|
||||
case LogLevel::kError: return "ERROR";
|
||||
case LogLevel::kOff: return "OFF";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
bool ParseLogLevel(const std::string& s, LogLevel* out) {
|
||||
if (s == "debug" || s == "DEBUG") { *out = LogLevel::kDebug; return true; }
|
||||
if (s == "info" || s == "INFO") { *out = LogLevel::kInfo; return true; }
|
||||
if (s == "warn" || s == "WARN") { *out = LogLevel::kWarn; return true; }
|
||||
if (s == "error" || s == "ERROR") { *out = LogLevel::kError; return true; }
|
||||
if (s == "off" || s == "OFF") { *out = LogLevel::kOff; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
void SetLogLevel(LogLevel l) { g_level.store(static_cast<int>(l), std::memory_order_relaxed); }
|
||||
|
||||
LogLevel GetLogLevel() {
|
||||
return static_cast<LogLevel>(g_level.load(std::memory_order_relaxed));
|
||||
}
|
||||
|
||||
void SetLogSink(LogSink sink) {
|
||||
std::lock_guard<std::mutex> lk(SinkMutex());
|
||||
SinkRef() = std::move(sink);
|
||||
}
|
||||
|
||||
void SetLogColor(bool on) {
|
||||
g_color.store(on, std::memory_order_relaxed);
|
||||
g_color_init.store(true, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
namespace detail {
|
||||
|
||||
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(SinkMutex());
|
||||
if (SinkRef()) {
|
||||
SinkRef()(level, file, line, msg);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Sink mac dinh: stderr, mot lan fwrite co khoa. Dinh dang:
|
||||
// HH:MM:SS.mmm WARN scan_sanitizer.cc:88 noi dung
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const auto t = system_clock::to_time_t(now);
|
||||
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
|
||||
|
||||
std::tm tm_buf{};
|
||||
::localtime_r(&t, &tm_buf);
|
||||
|
||||
char stamp[32];
|
||||
std::snprintf(stamp, sizeof(stamp), "%02d:%02d:%02d.%03d", tm_buf.tm_hour,
|
||||
tm_buf.tm_min, tm_buf.tm_sec, static_cast<int>(ms));
|
||||
|
||||
const bool color = ColorEnabled();
|
||||
const char* c_on = color ? ColorFor(level) : "";
|
||||
const char* c_off = (color && c_on[0] != '\0') ? "\033[0m" : "";
|
||||
|
||||
static std::mutex out_mu;
|
||||
std::lock_guard<std::mutex> lk(out_mu);
|
||||
std::fprintf(stderr, "%s%s %-5s %s:%d %s%s\n", c_on, stamp,
|
||||
LogLevelName(level), BaseName(file), line, msg.c_str(), c_off);
|
||||
}
|
||||
|
||||
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec) {
|
||||
// steady_clock, KHONG phai stamp du lieu. Neu dung stamp thi khi replay
|
||||
// nhanh (speed=0) moi dong se bi bop nham.
|
||||
const auto now = std::chrono::steady_clock::now().time_since_epoch();
|
||||
const int64_t now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
|
||||
const int64_t period_ns = static_cast<int64_t>(period_sec * 1e9);
|
||||
|
||||
int64_t last = state->load(std::memory_order_relaxed);
|
||||
if (last != 0 && now_ns - last < period_ns) return false;
|
||||
|
||||
// CAS: neu hai luong cung toi day thi chi mot luong duoc in.
|
||||
return state->compare_exchange_strong(last, now_ns, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
} // namespace vslam
|
||||
43
libs/vslam_common/src/node_constants.cc
Normal file
43
libs/vslam_common/src/node_constants.cc
Normal file
@@ -0,0 +1,43 @@
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Tra ve $name neu co va khong rong, khong thi `fallback`.
|
||||
std::string EnvOr(const char* name, const char* fallback) {
|
||||
const char* v = std::getenv(name);
|
||||
if (v != nullptr && v[0] != '\0') return std::string(v);
|
||||
return std::string(fallback);
|
||||
}
|
||||
|
||||
std::string Join(const std::string& dir, const std::string& rel) {
|
||||
if (dir.empty()) return rel;
|
||||
if (dir.back() == '/') return dir + rel;
|
||||
return dir + "/" + rel;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
|
||||
|
||||
std::string ResourceDir() { return EnvOr(kResourceDirEnv, kResourceDirectory); }
|
||||
|
||||
std::string ConfigPath(const std::string& file_name) {
|
||||
return Join(ConfigDir(), file_name);
|
||||
}
|
||||
|
||||
std::string ResourcePath(const std::string& rel) { return Join(ResourceDir(), rel); }
|
||||
|
||||
std::string MapDir() { return Join(ResourceDir(), "maps"); }
|
||||
|
||||
std::string RecordDir() { return Join(ResourceDir(), "records"); }
|
||||
|
||||
std::string CorpusDir() {
|
||||
const char* v = std::getenv(kCorpusDirEnv);
|
||||
if (v != nullptr && v[0] != '\0') return std::string(v);
|
||||
return MapDir();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
222
libs/vslam_common/src/robot_model.cc
Normal file
222
libs/vslam_common/src/robot_model.cc
Normal file
@@ -0,0 +1,222 @@
|
||||
#include "vslam/robot_model.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <set>
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Doc mot chuoi 3 so tu node YAML. Tra false kem duong day du khi hong --
|
||||
// mot phep bien doi sai im lang la ca ban do lech.
|
||||
bool ReadVec3(const ConfigNode& n, double out[3], std::string* err) {
|
||||
if (n.IsNull()) {
|
||||
*err = "thieu";
|
||||
return false;
|
||||
}
|
||||
if (!n.IsSequence() || n.size() != 3) {
|
||||
*err = "phai la chuoi 3 so, " + n.path();
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < 3; ++i) {
|
||||
out[i] = n.at(i).as<double>();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
RobotModel::RobotModel() : tree_(new TransformTree) {}
|
||||
RobotModel::~RobotModel() = default;
|
||||
|
||||
StatusResponse RobotModel::LoadFile(const std::string& path) {
|
||||
// ConfigNode::LoadFile nem ConfigError khi file thieu hoac YAML hong. Mot
|
||||
// file config sai khong duoc phep lam sap tien trinh -- doi thanh loi doc
|
||||
// duoc de nguoi goi quyet dinh.
|
||||
try {
|
||||
return Load(ConfigNode::LoadFile(path));
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml (" + path + "): " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
StatusResponse RobotModel::Load(const ConfigNode& root) {
|
||||
// --- geometry ---
|
||||
const ConfigNode g = root["geometry"];
|
||||
if (!g.IsNull()) {
|
||||
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `wheel_base`
|
||||
// thay vi `wheel_separation` nghia la moi phep quay sai ti le, va khong
|
||||
// co gi bao.
|
||||
const std::vector<std::string> unknown = g.UnknownKeys(
|
||||
{"wheel_radius", "wheel_separation", "robot_radius", "body_half_width"});
|
||||
if (!unknown.empty()) {
|
||||
std::string m = "robot.yaml geometry: khoa la:";
|
||||
for (const auto& k : unknown) m += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
|
||||
}
|
||||
geometry_.wheel_radius = g.get<double>("wheel_radius", geometry_.wheel_radius);
|
||||
geometry_.wheel_separation =
|
||||
g.get<double>("wheel_separation", geometry_.wheel_separation);
|
||||
geometry_.robot_radius = g.get<double>("robot_radius", geometry_.robot_radius);
|
||||
geometry_.body_half_width =
|
||||
g.get<double>("body_half_width", geometry_.body_half_width);
|
||||
}
|
||||
if (!(geometry_.wheel_radius > 0.0) || !(geometry_.wheel_separation > 0.0)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml: wheel_radius va wheel_separation "
|
||||
"phai duong");
|
||||
}
|
||||
|
||||
// --- base ---
|
||||
const ConfigNode b = root["base"];
|
||||
if (!b.IsNull()) {
|
||||
const std::vector<std::string> unknown = b.UnknownKeys(
|
||||
{"max_linear", "max_angular", "accel_limit", "cmd_timeout"});
|
||||
if (!unknown.empty()) {
|
||||
std::string m = "robot.yaml base: khoa la:";
|
||||
for (const auto& k : unknown) m += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
|
||||
}
|
||||
base_.max_linear = b.get<double>("max_linear", base_.max_linear);
|
||||
base_.max_angular = b.get<double>("max_angular", base_.max_angular);
|
||||
base_.accel_limit = b.get<double>("accel_limit", base_.accel_limit);
|
||||
base_.cmd_timeout = b.get<double>("cmd_timeout", base_.cmd_timeout);
|
||||
}
|
||||
|
||||
// --- wheel_odom ---
|
||||
const ConfigNode w = root["wheel_odom"];
|
||||
if (!w.IsNull()) {
|
||||
const std::vector<std::string> unknown =
|
||||
w.UnknownKeys({"sigma_x_per_m", "sigma_y_per_m", "sigma_yaw_per_rad",
|
||||
"slip_threshold", "slip_sigma_is_measured"});
|
||||
if (!unknown.empty()) {
|
||||
std::string m = "robot.yaml wheel_odom: khoa la:";
|
||||
for (const auto& k : unknown) m += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
|
||||
}
|
||||
wheel_odom_.sigma_x_per_m =
|
||||
w.get<double>("sigma_x_per_m", wheel_odom_.sigma_x_per_m);
|
||||
wheel_odom_.sigma_y_per_m =
|
||||
w.get<double>("sigma_y_per_m", wheel_odom_.sigma_y_per_m);
|
||||
wheel_odom_.sigma_yaw_per_rad =
|
||||
w.get<double>("sigma_yaw_per_rad", wheel_odom_.sigma_yaw_per_rad);
|
||||
wheel_odom_.slip_threshold =
|
||||
w.get<double>("slip_threshold", wheel_odom_.slip_threshold);
|
||||
wheel_odom_.slip_sigma_is_measured =
|
||||
w.get<bool>("slip_sigma_is_measured", wheel_odom_.slip_sigma_is_measured);
|
||||
}
|
||||
|
||||
// --- frames ---
|
||||
const ConfigNode frames = root["frames"];
|
||||
if (frames.IsNull() || !frames.IsSequence() || frames.size() == 0) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml: thieu khoi `frames:` -- khong co "
|
||||
"no thi khong stage nao dat duoc cam bien vao "
|
||||
"dau");
|
||||
}
|
||||
|
||||
// Mot `child` chi duoc xuat hien MOT lan. Hai dong cung child thi dong sau
|
||||
// am tham thang, va nua so doc file se tin dong dau.
|
||||
std::set<std::string> seen_children;
|
||||
|
||||
for (size_t i = 0; i < frames.size(); ++i) {
|
||||
const ConfigNode f = frames.at(i);
|
||||
const std::vector<std::string> unknown =
|
||||
f.UnknownKeys({"parent", "child", "xyz", "rpy"});
|
||||
if (!unknown.empty()) {
|
||||
std::string m = "robot.yaml frames[" + std::to_string(i) + "]: khoa la:";
|
||||
for (const auto& k : unknown) m += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
|
||||
}
|
||||
|
||||
const std::string parent = f.require<std::string>("parent");
|
||||
const std::string child = f.require<std::string>("child");
|
||||
if (parent == child) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml frames[" + std::to_string(i) +
|
||||
"]: parent trung child (" + parent + ")");
|
||||
}
|
||||
if (!seen_children.insert(child).second) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"robot.yaml: frame `" + child +
|
||||
"` duoc khai hai lan -- lan sau am tham thang, va do la lop bug "
|
||||
"ma file nay sinh ra de xoa");
|
||||
}
|
||||
|
||||
double xyz[3] = {0, 0, 0}, rpy[3] = {0, 0, 0};
|
||||
std::string err;
|
||||
if (!ReadVec3(f["xyz"], xyz, &err)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml frames[" + std::to_string(i) +
|
||||
"].xyz: " + err);
|
||||
}
|
||||
if (!ReadVec3(f["rpy"], rpy, &err)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml frames[" + std::to_string(i) +
|
||||
"].rpy: " + err);
|
||||
}
|
||||
|
||||
Transform tf = TransformIdentity();
|
||||
tf.translation = Vector3{xyz[0], xyz[1], xyz[2]};
|
||||
tf.rotation = QuaternionFromRPY(rpy[0], rpy[1], rpy[2]);
|
||||
|
||||
// SetStatic nem ConfigError khi tao vong -- bat lai va tra ve loi doc
|
||||
// duoc, vi mot file config sai khong duoc phep lam sap tien trinh.
|
||||
try {
|
||||
const StatusResponse st = tree_->SetStatic(parent, child, tf);
|
||||
if (!st.ok()) return st;
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml frames[" + std::to_string(i) +
|
||||
"] " + parent + " -> " + child + ": " +
|
||||
e.what());
|
||||
}
|
||||
|
||||
if (parent == kBaseLinkFrame && child == kCameraFrame) {
|
||||
camera_z_in_base_link_ = xyz[2];
|
||||
camera_pitch_ = rpy[1];
|
||||
have_camera_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
VSLAM_INFO("robot: " << frames.size() << " canh tinh, banh r="
|
||||
<< geometry_.wheel_radius << " d=" << geometry_.wheel_separation
|
||||
<< (have_camera_
|
||||
? ", camera cao " + std::to_string(camera_height_above_floor()) +
|
||||
" m so voi san"
|
||||
: ", KHONG co camera_link"));
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
bool RobotModel::StaticTransform(const std::string& target,
|
||||
const std::string& source, Transform* out) const {
|
||||
// Canh tinh khong co dau thoi gian, nen LookupLatest la dung: no dung mau
|
||||
// moi nhat cua tung canh, va voi canh tinh thi chi co mot mau.
|
||||
//
|
||||
// `Find` chu khong `Resolve`: tra cuu mot frame chua ton tai phai TRA FALSE
|
||||
// chu khong duoc am tham tao ra no. Resolve() tao frame moi, va mot frame
|
||||
// go sai ten se thanh mot nhanh roi ma khong ai bao.
|
||||
const FrameId t = tree_->Find(target);
|
||||
const FrameId s = tree_->Find(source);
|
||||
if (t == kInvalidFrame || s == kInvalidFrame) return false;
|
||||
return tree_->LookupLatest(t, s, out);
|
||||
}
|
||||
|
||||
double RobotModel::camera_height_above_floor() const {
|
||||
// base_link o tam truc, cach san dung bang ban kinh banh.
|
||||
//
|
||||
// Day la ly do `cliff_detect.nominal_tz` KHONG duoc go tay: no la mot HE
|
||||
// QUA cua hai so khac, va go tay lan thu hai la cho mot trong hai duoc
|
||||
// phep lech.
|
||||
return camera_z_in_base_link_ + geometry_.wheel_radius;
|
||||
}
|
||||
|
||||
double RobotModel::camera_pitch() const { return camera_pitch_; }
|
||||
|
||||
} // namespace vslam
|
||||
150
libs/vslam_common/src/stats.cc
Normal file
150
libs/vslam_common/src/stats.cc
Normal file
@@ -0,0 +1,150 @@
|
||||
#include "vslam/stats.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
int64_t ToNs(std::chrono::steady_clock::time_point tp) {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// --- RateMonitor -----------------------------------------------------------
|
||||
|
||||
RateMonitor::RateMonitor(double window_sec) : window_sec_(window_sec) {}
|
||||
|
||||
void RateMonitor::Tick(std::chrono::steady_clock::time_point now) {
|
||||
const int64_t ns = ToNs(now);
|
||||
count_.fetch_add(1, std::memory_order_relaxed);
|
||||
last_ns_.store(ns, std::memory_order_relaxed);
|
||||
|
||||
const int64_t first = first_ns_.load(std::memory_order_relaxed);
|
||||
if (first == 0) {
|
||||
first_ns_.store(ns, std::memory_order_relaxed);
|
||||
window_count_.store(1, std::memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
|
||||
const uint64_t wc = window_count_.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const double elapsed = static_cast<double>(ns - first) * 1e-9;
|
||||
if (elapsed >= window_sec_) {
|
||||
hz_.store(elapsed > 0.0 ? static_cast<double>(wc) / elapsed : 0.0,
|
||||
std::memory_order_relaxed);
|
||||
// Mo cua so moi. Khong dung cua so truot that (deque timestamp) vi o
|
||||
// 200 Hz thi chi phi bo nho va khoa khong dang -- sai so cua cua so nhay
|
||||
// la chap nhan duoc cho muc dich chan doan.
|
||||
first_ns_.store(ns, std::memory_order_relaxed);
|
||||
window_count_.store(0, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
void RateMonitor::Tick() { Tick(std::chrono::steady_clock::now()); }
|
||||
|
||||
double RateMonitor::hz() const { return hz_.load(std::memory_order_relaxed); }
|
||||
|
||||
double RateMonitor::age_sec(std::chrono::steady_clock::time_point now) const {
|
||||
const int64_t last = last_ns_.load(std::memory_order_relaxed);
|
||||
if (last == 0) return std::numeric_limits<double>::infinity();
|
||||
return static_cast<double>(ToNs(now) - last) * 1e-9;
|
||||
}
|
||||
|
||||
void RateMonitor::Reset() {
|
||||
count_.store(0, std::memory_order_relaxed);
|
||||
first_ns_.store(0, std::memory_order_relaxed);
|
||||
last_ns_.store(0, std::memory_order_relaxed);
|
||||
window_count_.store(0, std::memory_order_relaxed);
|
||||
hz_.store(0.0, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// --- LatencyMonitor --------------------------------------------------------
|
||||
|
||||
struct LatencyMonitor::Impl {
|
||||
mutable std::mutex mu;
|
||||
std::vector<double> ring;
|
||||
size_t head = 0;
|
||||
size_t filled = 0;
|
||||
double max_seen = 0.0;
|
||||
double last = 0.0;
|
||||
uint64_t count = 0;
|
||||
|
||||
explicit Impl(size_t window) : ring(window, 0.0) {}
|
||||
|
||||
// Goi khi da giu mu.
|
||||
double PercentileLocked(double p) const {
|
||||
if (filled == 0) return 0.0;
|
||||
std::vector<double> tmp(ring.begin(), ring.begin() + static_cast<long>(filled));
|
||||
const size_t idx = static_cast<size_t>(p * static_cast<double>(filled - 1));
|
||||
std::nth_element(tmp.begin(), tmp.begin() + static_cast<long>(idx), tmp.end());
|
||||
return tmp[idx];
|
||||
}
|
||||
};
|
||||
|
||||
LatencyMonitor::LatencyMonitor(size_t window)
|
||||
: impl_(std::make_unique<Impl>(window == 0 ? 1 : window)) {}
|
||||
|
||||
LatencyMonitor::~LatencyMonitor() = default;
|
||||
|
||||
void LatencyMonitor::Add(double ms) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
impl_->ring[impl_->head] = ms;
|
||||
impl_->head = (impl_->head + 1) % impl_->ring.size();
|
||||
if (impl_->filled < impl_->ring.size()) impl_->filled++;
|
||||
if (ms > impl_->max_seen) impl_->max_seen = ms;
|
||||
impl_->last = ms;
|
||||
impl_->count++;
|
||||
}
|
||||
|
||||
double LatencyMonitor::p50() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->PercentileLocked(0.50);
|
||||
}
|
||||
|
||||
double LatencyMonitor::p95() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->PercentileLocked(0.95);
|
||||
}
|
||||
|
||||
double LatencyMonitor::max() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->max_seen;
|
||||
}
|
||||
|
||||
double LatencyMonitor::last() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->last;
|
||||
}
|
||||
|
||||
uint64_t LatencyMonitor::count() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->count;
|
||||
}
|
||||
|
||||
void LatencyMonitor::Reset() {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
std::fill(impl_->ring.begin(), impl_->ring.end(), 0.0);
|
||||
impl_->head = 0;
|
||||
impl_->filled = 0;
|
||||
impl_->max_seen = 0.0;
|
||||
impl_->last = 0.0;
|
||||
impl_->count = 0;
|
||||
}
|
||||
|
||||
// --- ScopedLatency ---------------------------------------------------------
|
||||
|
||||
ScopedLatency::ScopedLatency(LatencyMonitor* m, const Clock* clock)
|
||||
: m_(m), t0_(clock != nullptr ? clock->Steady() : std::chrono::steady_clock::now()) {}
|
||||
|
||||
ScopedLatency::~ScopedLatency() {
|
||||
if (m_ == nullptr) return;
|
||||
const auto dt = std::chrono::steady_clock::now() - t0_;
|
||||
m_->Add(std::chrono::duration<double, std::milli>(dt).count());
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
262
libs/vslam_common/src/teleop_model.cc
Normal file
262
libs/vslam_common/src/teleop_model.cc
Normal file
@@ -0,0 +1,262 @@
|
||||
#include "vslam/teleop_model.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
double Clamp(double v, double lo, double hi) { return std::max(lo, std::min(v, hi)); }
|
||||
|
||||
void ValidateFinite(const char* name, double v) {
|
||||
if (!std::isfinite(v)) {
|
||||
throw std::invalid_argument(std::string(name) + " must be a finite number");
|
||||
}
|
||||
}
|
||||
|
||||
void ValidateRange(const char* name, double minimum, double maximum, double step) {
|
||||
ValidateFinite(name, minimum);
|
||||
ValidateFinite(name, maximum);
|
||||
ValidateFinite(name, step);
|
||||
if (minimum < 0.0) {
|
||||
throw std::invalid_argument(std::string("minimum ") + name +
|
||||
" must be non-negative");
|
||||
}
|
||||
if (maximum < minimum) {
|
||||
throw std::invalid_argument(std::string("maximum ") + name +
|
||||
" must not be less than its minimum");
|
||||
}
|
||||
if (step <= 0.0) {
|
||||
throw std::invalid_argument(std::string(name) + " step must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
void ValidateCommandRange(const char* name, double minimum, double maximum) {
|
||||
ValidateFinite(name, minimum);
|
||||
ValidateFinite(name, maximum);
|
||||
if (minimum > 0.0) {
|
||||
throw std::invalid_argument(std::string("minimum ") + name +
|
||||
" must be zero or negative");
|
||||
}
|
||||
if (maximum < 0.0) {
|
||||
throw std::invalid_argument(std::string("maximum ") + name +
|
||||
" must be zero or positive");
|
||||
}
|
||||
if (minimum >= maximum) {
|
||||
throw std::invalid_argument(std::string("minimum ") + name +
|
||||
" must be less than its maximum");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ParseTeleopKey(const std::string& name, TeleopKey* out) {
|
||||
if (name == "Up") { *out = TeleopKey::kUp; return true; }
|
||||
if (name == "Down") { *out = TeleopKey::kDown; return true; }
|
||||
if (name == "Left") { *out = TeleopKey::kLeft; return true; }
|
||||
if (name == "Right") { *out = TeleopKey::kRight; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* TeleopKeyName(TeleopKey k) {
|
||||
switch (k) {
|
||||
case TeleopKey::kUp: return "Up";
|
||||
case TeleopKey::kDown: return "Down";
|
||||
case TeleopKey::kLeft: return "Left";
|
||||
case TeleopKey::kRight: return "Right";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
TeleopModel::TeleopModel(TeleopConfig cfg) {
|
||||
ValidateRange("linear speed", cfg.min_linear_speed, cfg.max_linear_speed,
|
||||
cfg.linear_step);
|
||||
ValidateRange("angular speed", cfg.min_angular_speed, cfg.max_angular_speed,
|
||||
cfg.angular_step);
|
||||
ValidateFinite("linear_speed", cfg.linear_speed);
|
||||
ValidateFinite("angular_speed", cfg.angular_speed);
|
||||
|
||||
// Mac dinh: gioi han duoi doi xung voi gioi han tren.
|
||||
const double min_lin_cmd =
|
||||
cfg.has_min_linear_command ? cfg.min_linear_command : -cfg.max_linear_speed;
|
||||
const double min_ang_cmd =
|
||||
cfg.has_min_angular_command ? cfg.min_angular_command : -cfg.max_angular_speed;
|
||||
|
||||
ValidateCommandRange("linear command", min_lin_cmd, cfg.max_linear_speed);
|
||||
ValidateCommandRange("angular command", min_ang_cmd, cfg.max_angular_speed);
|
||||
|
||||
linear_step_ = cfg.linear_step;
|
||||
angular_step_ = cfg.angular_step;
|
||||
min_linear_speed_ = cfg.min_linear_speed;
|
||||
max_linear_speed_ = cfg.max_linear_speed;
|
||||
min_angular_speed_ = cfg.min_angular_speed;
|
||||
max_angular_speed_ = cfg.max_angular_speed;
|
||||
min_linear_command_ = min_lin_cmd;
|
||||
min_angular_command_ = min_ang_cmd;
|
||||
linear_speed_ = Clamp(cfg.linear_speed, min_linear_speed_, max_linear_speed_);
|
||||
angular_speed_ = Clamp(cfg.angular_speed, min_angular_speed_, max_angular_speed_);
|
||||
}
|
||||
|
||||
// --- Nguon nhap ------------------------------------------------------------
|
||||
|
||||
bool TeleopModel::SetKey(TeleopKey key, bool pressed) {
|
||||
if (pressed) {
|
||||
// Bam phim GIAI PHONG lenh manual. Khong bao gio tron hai nguon.
|
||||
ReleaseManualControl();
|
||||
keys_.insert(key);
|
||||
} else {
|
||||
keys_.erase(key);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void TeleopModel::ClearKeys() { keys_.clear(); }
|
||||
|
||||
void TeleopModel::SetJoystick(double horizontal, double vertical) {
|
||||
ValidateFinite("joystick horizontal axis", horizontal);
|
||||
ValidateFinite("joystick vertical axis", vertical);
|
||||
joy_h_ = Clamp(horizontal, -1.0, 1.0);
|
||||
joy_v_ = Clamp(vertical, -1.0, 1.0);
|
||||
joystick_active_ = true;
|
||||
ReleaseManualControl();
|
||||
}
|
||||
|
||||
void TeleopModel::ReleaseJoystick() { joystick_active_ = false; }
|
||||
|
||||
void TeleopModel::ClearMotion() {
|
||||
ClearKeys();
|
||||
ReleaseJoystick();
|
||||
ReleaseManualControl();
|
||||
}
|
||||
|
||||
std::pair<double, double> TeleopModel::SetManualCommand(const double* linear_x,
|
||||
const double* angular_z) {
|
||||
double cur_lin, cur_ang;
|
||||
if (!manual_active_) {
|
||||
const auto c = Command();
|
||||
cur_lin = c.first;
|
||||
cur_ang = c.second;
|
||||
} else {
|
||||
cur_lin = manual_lin_;
|
||||
cur_ang = manual_ang_;
|
||||
}
|
||||
|
||||
if (linear_x != nullptr) {
|
||||
ValidateFinite("manual linear command", *linear_x);
|
||||
cur_lin = *linear_x;
|
||||
}
|
||||
if (angular_z != nullptr) {
|
||||
ValidateFinite("manual angular command", *angular_z);
|
||||
cur_ang = *angular_z;
|
||||
}
|
||||
|
||||
ClearKeys();
|
||||
ReleaseJoystick();
|
||||
const auto clamped = ClampCommand(cur_lin, cur_ang);
|
||||
manual_lin_ = clamped.first;
|
||||
manual_ang_ = clamped.second;
|
||||
manual_active_ = true;
|
||||
return clamped;
|
||||
}
|
||||
|
||||
void TeleopModel::ReleaseManualControl() { manual_active_ = false; }
|
||||
|
||||
// --- Ket qua ---------------------------------------------------------------
|
||||
|
||||
std::pair<double, double> TeleopModel::ClampCommand(double linear_x,
|
||||
double angular_z) const {
|
||||
return {Clamp(linear_x, min_linear_command_, max_linear_speed_),
|
||||
Clamp(angular_z, min_angular_command_, max_angular_speed_)};
|
||||
}
|
||||
|
||||
void TeleopModel::ClampManualCommand() {
|
||||
if (!manual_active_) return;
|
||||
const auto c = ClampCommand(manual_lin_, manual_ang_);
|
||||
manual_lin_ = c.first;
|
||||
manual_ang_ = c.second;
|
||||
}
|
||||
|
||||
std::pair<double, double> TeleopModel::Command() const {
|
||||
// Thu tu uu tien: manual > joystick > phim.
|
||||
if (manual_active_) return {manual_lin_, manual_ang_};
|
||||
|
||||
if (joystick_active_) {
|
||||
return ClampCommand(-joy_v_ * linear_speed_, -joy_h_ * angular_speed_);
|
||||
}
|
||||
|
||||
const int linear_axis = static_cast<int>(keys_.count(TeleopKey::kUp)) -
|
||||
static_cast<int>(keys_.count(TeleopKey::kDown));
|
||||
const int angular_axis = static_cast<int>(keys_.count(TeleopKey::kLeft)) -
|
||||
static_cast<int>(keys_.count(TeleopKey::kRight));
|
||||
return ClampCommand(linear_axis * linear_speed_, angular_axis * angular_speed_);
|
||||
}
|
||||
|
||||
std::pair<double, double> TeleopModel::JoystickPosition() const {
|
||||
if (joystick_active_) return {joy_h_, joy_v_};
|
||||
const int h = static_cast<int>(keys_.count(TeleopKey::kRight)) -
|
||||
static_cast<int>(keys_.count(TeleopKey::kLeft));
|
||||
const int v = static_cast<int>(keys_.count(TeleopKey::kDown)) -
|
||||
static_cast<int>(keys_.count(TeleopKey::kUp));
|
||||
return {static_cast<double>(h), static_cast<double>(v)};
|
||||
}
|
||||
|
||||
// --- Chinh toc do ----------------------------------------------------------
|
||||
|
||||
double TeleopModel::AdjustLinearSpeed(double direction) {
|
||||
return SetLinearSpeed(linear_speed_ + direction * linear_step_);
|
||||
}
|
||||
|
||||
double TeleopModel::AdjustAngularSpeed(double direction) {
|
||||
return SetAngularSpeed(angular_speed_ + direction * angular_step_);
|
||||
}
|
||||
|
||||
double TeleopModel::SetLinearSpeed(double value) {
|
||||
ValidateFinite("linear speed", value);
|
||||
linear_speed_ = Clamp(value, min_linear_speed_, max_linear_speed_);
|
||||
return linear_speed_;
|
||||
}
|
||||
|
||||
double TeleopModel::SetAngularSpeed(double value) {
|
||||
ValidateFinite("angular speed", value);
|
||||
angular_speed_ = Clamp(value, min_angular_speed_, max_angular_speed_);
|
||||
return angular_speed_;
|
||||
}
|
||||
|
||||
double TeleopModel::SetMaxLinearSpeed(double value) {
|
||||
ValidateFinite("maximum linear speed", value);
|
||||
max_linear_speed_ = std::max(min_linear_speed_, value);
|
||||
linear_speed_ = std::min(linear_speed_, max_linear_speed_);
|
||||
ClampManualCommand();
|
||||
return max_linear_speed_;
|
||||
}
|
||||
|
||||
double TeleopModel::SetMaxAngularSpeed(double value) {
|
||||
ValidateFinite("maximum angular speed", value);
|
||||
max_angular_speed_ = std::max(min_angular_speed_, value);
|
||||
angular_speed_ = std::min(angular_speed_, max_angular_speed_);
|
||||
ClampManualCommand();
|
||||
return max_angular_speed_;
|
||||
}
|
||||
|
||||
double TeleopModel::SetMinLinearCommand(double value) {
|
||||
ValidateFinite("minimum linear command", value);
|
||||
min_linear_command_ = std::min(0.0, value);
|
||||
if (min_linear_command_ >= max_linear_speed_) {
|
||||
min_linear_command_ = std::min(0.0, max_linear_speed_ - linear_step_);
|
||||
}
|
||||
ClampManualCommand();
|
||||
return min_linear_command_;
|
||||
}
|
||||
|
||||
double TeleopModel::SetMinAngularCommand(double value) {
|
||||
ValidateFinite("minimum angular command", value);
|
||||
min_angular_command_ = std::min(0.0, value);
|
||||
if (min_angular_command_ >= max_angular_speed_) {
|
||||
min_angular_command_ = std::min(0.0, max_angular_speed_ - angular_step_);
|
||||
}
|
||||
ClampManualCommand();
|
||||
return min_angular_command_;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
485
libs/vslam_common/src/transform_tree.cc
Normal file
485
libs/vslam_common/src/transform_tree.cc
Normal file
@@ -0,0 +1,485 @@
|
||||
#include "vslam/transform_tree.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/geometry.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/stats.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr size_t kMaxDepth = 32; // cay that co 5 muc; 32 la chan an toan
|
||||
|
||||
struct Sample {
|
||||
UnixTime stamp;
|
||||
Transform tf;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// Mot canh = quan he cha-con. Canh tinh giu mot Transform; canh dong giu ring
|
||||
// buffer cac mau theo thoi gian.
|
||||
struct Edge {
|
||||
FrameId parent = kInvalidFrame;
|
||||
bool is_static = false;
|
||||
|
||||
Transform static_tf; // chi co nghia khi is_static
|
||||
|
||||
std::vector<Sample> ring;
|
||||
size_t head = 0; // vi tri se ghi tiep
|
||||
size_t filled = 0;
|
||||
uint64_t samples = 0;
|
||||
RateMonitor rate{2.0};
|
||||
|
||||
const Sample& at(size_t i) const { return ring[i % ring.size()]; }
|
||||
|
||||
// Mau moi nhat. Goi phai bao dam filled > 0.
|
||||
const Sample& newest() const { return ring[(head + ring.size() - 1) % ring.size()]; }
|
||||
|
||||
// Mau cu nhat con song.
|
||||
const Sample& oldest() const {
|
||||
return filled < ring.size() ? ring[0] : ring[head % ring.size()];
|
||||
}
|
||||
};
|
||||
|
||||
struct TransformTree::Impl {
|
||||
mutable std::mutex mu;
|
||||
|
||||
std::unordered_map<std::string, FrameId> name_to_id;
|
||||
std::vector<std::string> id_to_name;
|
||||
|
||||
// Chi muc theo frame CON: moi frame co dung mot cha, nen mot canh la du.
|
||||
// Day chinh la gia dinh cho phep bo toan bo may tra cuu tong quat cua tf2.
|
||||
std::unordered_map<FrameId, Edge> edges;
|
||||
|
||||
double history_sec;
|
||||
size_t slots_per_edge;
|
||||
double extrapolation_limit = 0.1;
|
||||
|
||||
std::string empty_name;
|
||||
|
||||
// Duong di tu `frame` len goc. Tra ve so muc, hoac 0 neu vuot kMaxDepth.
|
||||
size_t PathToRoot(FrameId frame, FrameId* out) const {
|
||||
size_t n = 0;
|
||||
FrameId cur = frame;
|
||||
while (n < kMaxDepth) {
|
||||
out[n++] = cur;
|
||||
auto it = edges.find(cur);
|
||||
if (it == edges.end()) return n; // toi goc
|
||||
cur = it->second.parent;
|
||||
}
|
||||
return 0; // vong hoac qua sau
|
||||
}
|
||||
|
||||
// To tien chung gan nhat cua a va b. kInvalidFrame neu hai frame khong noi.
|
||||
bool CommonAncestor(FrameId a, FrameId b, FrameId* pa, size_t* na, FrameId* pb,
|
||||
size_t* nb, FrameId* lca) const {
|
||||
*na = PathToRoot(a, pa);
|
||||
*nb = PathToRoot(b, pb);
|
||||
if (*na == 0 || *nb == 0) return false;
|
||||
|
||||
for (size_t i = 0; i < *na; ++i) {
|
||||
for (size_t j = 0; j < *nb; ++j) {
|
||||
if (pa[i] == pb[j]) {
|
||||
*lca = pa[i];
|
||||
*na = i; // so canh phai di tu a len lca
|
||||
*nb = j;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Bien doi canh don parent<-child tai `stamp`, noi suy neu can.
|
||||
bool EdgeAt(const Edge& e, UnixTime stamp, bool latest, Transform* out,
|
||||
std::string* err) const {
|
||||
if (e.is_static) {
|
||||
*out = e.static_tf;
|
||||
return true;
|
||||
}
|
||||
if (e.filled == 0) {
|
||||
if (err) *err = "canh chua co mau nao";
|
||||
return false;
|
||||
}
|
||||
|
||||
const Sample& newest = e.newest();
|
||||
if (latest) {
|
||||
*out = newest.tf;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ngoai suy ve tuong lai: tu choi neu vuot gioi han.
|
||||
// tf2 nem ExtrapolationException o day va rat nhieu code goi bat roi bo
|
||||
// qua im lang; tra false + dien err de goi khong the lo.
|
||||
if (stamp > newest.stamp) {
|
||||
const double ahead = SecondsBetween(stamp, newest.stamp);
|
||||
if (ahead > extrapolation_limit) {
|
||||
if (err) {
|
||||
std::ostringstream oss;
|
||||
oss << "ngoai suy " << ahead << " s vuot gioi han "
|
||||
<< extrapolation_limit << " s";
|
||||
*err = oss.str();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
*out = newest.tf;
|
||||
return true;
|
||||
}
|
||||
|
||||
const Sample& oldest = e.oldest();
|
||||
if (stamp < oldest.stamp) {
|
||||
if (err) {
|
||||
std::ostringstream oss;
|
||||
oss << "stamp cu hon lich su " << SecondsBetween(oldest.stamp, stamp) << " s";
|
||||
*err = oss.str();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tim hai mau kep stamp. Ring nho (512) va truy van gan dau moi nen quet
|
||||
// nguoc tu moi nhat nhanh hon tim nhi phan tren bo dem vong.
|
||||
const size_t n = e.filled;
|
||||
const size_t base = e.filled < e.ring.size() ? 0 : e.head;
|
||||
for (size_t k = n; k-- > 1;) {
|
||||
const Sample& hi = e.at(base + k);
|
||||
const Sample& lo = e.at(base + k - 1);
|
||||
if (stamp >= lo.stamp && stamp <= hi.stamp) {
|
||||
const int64_t span = hi.stamp.toNSec() - lo.stamp.toNSec();
|
||||
if (span <= 0) {
|
||||
*out = hi.tf;
|
||||
return true;
|
||||
}
|
||||
const double t =
|
||||
static_cast<double>(stamp.toNSec() - lo.stamp.toNSec()) /
|
||||
static_cast<double>(span);
|
||||
*out = TransformInterpolate(lo.tf, hi.tf, t);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
*out = newest.tf;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TransformTree::TransformTree(double history_sec, size_t slots_per_edge)
|
||||
: impl_(std::make_unique<Impl>()) {
|
||||
impl_->history_sec = history_sec;
|
||||
impl_->slots_per_edge = slots_per_edge == 0 ? 1 : slots_per_edge;
|
||||
}
|
||||
|
||||
TransformTree::~TransformTree() = default;
|
||||
|
||||
FrameId TransformTree::Resolve(const std::string& name) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
auto it = impl_->name_to_id.find(name);
|
||||
if (it != impl_->name_to_id.end()) return it->second;
|
||||
const FrameId id = static_cast<FrameId>(impl_->id_to_name.size());
|
||||
impl_->id_to_name.push_back(name);
|
||||
impl_->name_to_id.emplace(name, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
FrameId TransformTree::Find(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
auto it = impl_->name_to_id.find(name);
|
||||
return it == impl_->name_to_id.end() ? kInvalidFrame : it->second;
|
||||
}
|
||||
|
||||
const std::string& TransformTree::Name(FrameId id) const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
if (id >= impl_->id_to_name.size()) return impl_->empty_name;
|
||||
return impl_->id_to_name[id];
|
||||
}
|
||||
|
||||
size_t TransformTree::frame_count() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->id_to_name.size();
|
||||
}
|
||||
|
||||
StatusResponse TransformTree::SetStatic(FrameId parent, FrameId child,
|
||||
const Transform& tf) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
|
||||
// Kiem vong truoc khi ghi: di tu `parent` len goc, neu gap `child` thi viec
|
||||
// dat canh nay se tao vong va moi lookup sau do se treo.
|
||||
FrameId cur = parent;
|
||||
for (size_t i = 0; i < kMaxDepth; ++i) {
|
||||
if (cur == child) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"SetStatic tao vong trong cay TF: " + impl_->id_to_name[child]);
|
||||
}
|
||||
auto it = impl_->edges.find(cur);
|
||||
if (it == impl_->edges.end()) break;
|
||||
cur = it->second.parent;
|
||||
}
|
||||
|
||||
Edge& e = impl_->edges[child];
|
||||
if (!e.is_static && e.samples > 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"canh " + impl_->id_to_name[child] + " da la canh dong, khong the dat tinh");
|
||||
}
|
||||
e.parent = parent;
|
||||
e.is_static = true;
|
||||
e.static_tf = tf;
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
StatusResponse TransformTree::SetStatic(const std::string& parent,
|
||||
const std::string& child,
|
||||
const Transform& tf) {
|
||||
return SetStatic(Resolve(parent), Resolve(child), tf);
|
||||
}
|
||||
|
||||
bool TransformTree::SetTransform(FrameId parent, FrameId child, UnixTime stamp,
|
||||
const Transform& tf) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
|
||||
Edge& e = impl_->edges[child];
|
||||
if (e.is_static) {
|
||||
VSLAM_WARN_THROTTLE(5.0, "SetTransform tren canh tinh "
|
||||
<< impl_->id_to_name[child] << ", bo qua");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (e.parent != kInvalidFrame && e.parent != parent) {
|
||||
// Doi cha giua chung la dau hieu hai nguoi cung ghi mot canh -- vi pham
|
||||
// quy tac "moi canh dung mot nguoi ghi". Bao to, dung im lang.
|
||||
VSLAM_ERROR_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
|
||||
<< " doi cha tu " << impl_->id_to_name[e.parent]
|
||||
<< " sang " << impl_->id_to_name[parent]);
|
||||
return false;
|
||||
}
|
||||
e.parent = parent;
|
||||
|
||||
if (e.ring.empty()) e.ring.resize(impl_->slots_per_edge);
|
||||
|
||||
if (e.filled > 0 && stamp < e.newest().stamp) {
|
||||
// Lui thoi gian: ban ghi bi xao tron thu tu, hoac hai nguoi ghi. Noi suy
|
||||
// tren ring khong con don dieu nua nen moi lookup sau do se sai.
|
||||
VSLAM_WARN_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
|
||||
<< ": stamp lui " << e.newest().stamp.toString()
|
||||
<< " -> " << stamp.toString() << ", bo qua");
|
||||
return false;
|
||||
}
|
||||
|
||||
e.ring[e.head] = Sample{stamp, tf};
|
||||
e.head = (e.head + 1) % e.ring.size();
|
||||
if (e.filled < e.ring.size()) e.filled++;
|
||||
e.samples++;
|
||||
e.rate.Tick();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TransformTree::Lookup(FrameId target, FrameId source, UnixTime stamp,
|
||||
Transform* out, std::string* err) const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
|
||||
if (target == source) {
|
||||
*out = TransformIdentity();
|
||||
return true;
|
||||
}
|
||||
|
||||
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
|
||||
size_t na = 0, nb = 0;
|
||||
if (!impl_->CommonAncestor(source, target, pa, &na, pb, &nb, &lca)) {
|
||||
if (err) {
|
||||
*err = "khong co duong noi " + impl_->id_to_name[source] + " -> " +
|
||||
impl_->id_to_name[target];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool latest = stamp.isZero();
|
||||
|
||||
// source -> lca: ghep xuoi cac canh child->parent.
|
||||
Transform src_to_lca = TransformIdentity();
|
||||
for (size_t i = 0; i < na; ++i) {
|
||||
auto it = impl_->edges.find(pa[i]);
|
||||
if (it == impl_->edges.end()) break;
|
||||
Transform e;
|
||||
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
|
||||
if (err) *err = impl_->id_to_name[pa[i]] + ": " + *err;
|
||||
return false;
|
||||
}
|
||||
src_to_lca = TransformCompose(e, src_to_lca);
|
||||
}
|
||||
|
||||
// target -> lca, roi lay nghich dao.
|
||||
Transform tgt_to_lca = TransformIdentity();
|
||||
for (size_t i = 0; i < nb; ++i) {
|
||||
auto it = impl_->edges.find(pb[i]);
|
||||
if (it == impl_->edges.end()) break;
|
||||
Transform e;
|
||||
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
|
||||
if (err) *err = impl_->id_to_name[pb[i]] + ": " + *err;
|
||||
return false;
|
||||
}
|
||||
tgt_to_lca = TransformCompose(e, tgt_to_lca);
|
||||
}
|
||||
|
||||
*out = TransformCompose(TransformInverse(tgt_to_lca), src_to_lca);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TransformTree::Lookup(const std::string& target, const std::string& source,
|
||||
UnixTime stamp, Transform* out, std::string* err) const {
|
||||
const FrameId t = Find(target), s = Find(source);
|
||||
if (t == kInvalidFrame || s == kInvalidFrame) {
|
||||
if (err) *err = "frame chua dang ky: " + (t == kInvalidFrame ? target : source);
|
||||
return false;
|
||||
}
|
||||
return Lookup(t, s, stamp, out, err);
|
||||
}
|
||||
|
||||
bool TransformTree::LookupLatest(FrameId target, FrameId source, Transform* out,
|
||||
std::string* err) const {
|
||||
return Lookup(target, source, kTimeZero, out, err);
|
||||
}
|
||||
|
||||
UnixTime TransformTree::LatestCommonTime(FrameId a, FrameId b) const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
|
||||
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
|
||||
size_t na = 0, nb = 0;
|
||||
if (!impl_->CommonAncestor(a, b, pa, &na, pb, &nb, &lca)) return kTimeZero;
|
||||
|
||||
// Thoi diem chung moi nhat = MIN cua cac mau moi nhat tren duong di.
|
||||
// Canh tinh khong gioi han gi nen bo qua.
|
||||
UnixTime best = kTimeMax;
|
||||
bool any_dynamic = false;
|
||||
|
||||
auto scan = [&](const FrameId* path, size_t n) {
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
auto it = impl_->edges.find(path[i]);
|
||||
if (it == impl_->edges.end() || it->second.is_static) continue;
|
||||
if (it->second.filled == 0) {
|
||||
best = kTimeZero;
|
||||
return;
|
||||
}
|
||||
any_dynamic = true;
|
||||
const UnixTime s = it->second.newest().stamp;
|
||||
if (s < best) best = s;
|
||||
}
|
||||
};
|
||||
scan(pa, na);
|
||||
if (best.isZero()) return kTimeZero;
|
||||
scan(pb, nb);
|
||||
|
||||
if (!any_dynamic) return kTimeZero; // toan canh tinh: moi luc deu hop le
|
||||
return best.isZero() ? kTimeZero : best;
|
||||
}
|
||||
|
||||
bool TransformTree::CanTransform(FrameId target, FrameId source,
|
||||
UnixTime stamp) const {
|
||||
Transform tmp;
|
||||
return Lookup(target, source, stamp, &tmp, nullptr);
|
||||
}
|
||||
|
||||
void TransformTree::SetExtrapolationLimit(double sec) {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
impl_->extrapolation_limit = sec;
|
||||
}
|
||||
|
||||
double TransformTree::extrapolation_limit() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
return impl_->extrapolation_limit;
|
||||
}
|
||||
|
||||
std::vector<TransformTree::EdgeStatus> TransformTree::EdgeStatuses() const {
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
std::vector<EdgeStatus> out;
|
||||
out.reserve(impl_->edges.size());
|
||||
for (const auto& kv : impl_->edges) {
|
||||
EdgeStatus s;
|
||||
s.child = impl_->id_to_name[kv.first];
|
||||
s.parent = kv.second.parent < impl_->id_to_name.size()
|
||||
? impl_->id_to_name[kv.second.parent]
|
||||
: "?";
|
||||
s.is_static = kv.second.is_static;
|
||||
s.samples = kv.second.samples;
|
||||
s.hz = kv.second.rate.hz();
|
||||
if (kv.second.filled > 0) s.latest = kv.second.newest().stamp;
|
||||
out.push_back(std::move(s));
|
||||
}
|
||||
std::sort(out.begin(), out.end(),
|
||||
[](const EdgeStatus& a, const EdgeStatus& b) { return a.child < b.child; });
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string TransformTree::DumpTree() const {
|
||||
// Thay rqt_tf_tree. In ra dang cay, danh dau canh tinh/dong kem tan so.
|
||||
const auto edges = EdgeStatuses();
|
||||
|
||||
std::lock_guard<std::mutex> lk(impl_->mu);
|
||||
std::unordered_map<std::string, std::vector<const EdgeStatus*>> children;
|
||||
std::vector<std::string> roots;
|
||||
|
||||
for (const auto& e : edges) children[e.parent].push_back(&e);
|
||||
for (const auto& name : impl_->id_to_name) {
|
||||
if (impl_->edges.find(impl_->name_to_id.at(name)) == impl_->edges.end()) {
|
||||
roots.push_back(name);
|
||||
}
|
||||
}
|
||||
|
||||
std::ostringstream oss;
|
||||
std::function<void(const std::string&, int)> walk = [&](const std::string& node,
|
||||
int depth) {
|
||||
oss << std::string(static_cast<size_t>(depth) * 2, ' ') << node;
|
||||
if (depth > 0) {
|
||||
for (const auto& e : edges) {
|
||||
if (e.child != node) continue;
|
||||
if (e.is_static) {
|
||||
oss << " [tinh]";
|
||||
} else {
|
||||
oss << " [dong " << e.hz << " Hz, " << e.samples << " mau]";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
oss << "\n";
|
||||
auto it = children.find(node);
|
||||
if (it == children.end()) return;
|
||||
for (const auto* c : it->second) walk(c->child, depth + 1);
|
||||
};
|
||||
|
||||
for (const auto& r : roots) walk(r, 0);
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
// --- TfBridge --------------------------------------------------------------
|
||||
|
||||
TfBridge::TfBridge(std::string tracking_frame, double lookup_timeout_sec,
|
||||
std::shared_ptr<const TransformTree> tree)
|
||||
: tracking_frame_(std::move(tracking_frame)),
|
||||
lookup_timeout_sec_(lookup_timeout_sec),
|
||||
tree_(std::move(tree)) {}
|
||||
|
||||
bool TfBridge::LookupToTracking(UnixTime time, FrameId frame, Transform* out) const {
|
||||
const FrameId tracking = tree_->Find(tracking_frame_);
|
||||
if (tracking == kInvalidFrame) return false;
|
||||
std::string err;
|
||||
if (tree_->Lookup(tracking, frame, time, out, &err)) return true;
|
||||
VSLAM_DEBUG_THROTTLE(2.0, "TfBridge: " << err);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TfBridge::LookupToTracking(UnixTime time, const std::string& frame,
|
||||
Transform* out) const {
|
||||
const FrameId id = tree_->Find(frame);
|
||||
if (id == kInvalidFrame) return false;
|
||||
return LookupToTracking(time, id, out);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
15
libs/vslam_common/src/unix_time.cc
Normal file
15
libs/vslam_common/src/unix_time.cc
Normal file
@@ -0,0 +1,15 @@
|
||||
#include "vslam/unix_time.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
std::string UnixTime::toString() const {
|
||||
// In nguyen ven sec.nsec thay vi qua double: double chi co 53 bit mantissa,
|
||||
// khong du de giu ca 1.7e9 giay lan do phan giai nanosecond.
|
||||
char buf[32];
|
||||
std::snprintf(buf, sizeof(buf), "%u.%09u", sec, nsec);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user