TrajoptLib
Library for generating time-optimal trajectories for FRC robots.
Loading...
Searching...
No Matches
spline.hpp
1// Copyright (c) TrajoptLib contributors
2
3#pragma once
4
5#include <array>
6#include <cmath>
7#include <optional>
8#include <utility>
9
10#include <Eigen/Core>
11
12#include "trajopt/geometry/pose2.hpp"
13#include "trajopt/geometry/rotation2.hpp"
14#include "trajopt/geometry/translation2.hpp"
15
16namespace trajopt {
17
22template <int Degree>
23class Spline {
24 public:
26 using PoseWithCurvature = std::pair<Pose2d, double>;
27
28 virtual ~Spline() = default;
29
37 std::array<double, (Degree + 1) / 2> x;
38
40 std::array<double, (Degree + 1) / 2> y;
41 };
42
47 std::optional<PoseWithCurvature> get_point(double t) const {
48 Eigen::Vector<double, Degree + 1> polynomial_bases;
49
50 // Populate the polynomial bases
51 for (int i = 0; i <= Degree; i++) {
52 polynomial_bases(i) = std::pow(t, Degree - i);
53 }
54
55 // This simply multiplies by the coefficients. We need to divide out t some
56 // n number of times where n is the derivative we want to take.
57 Eigen::Vector<double, 6> combined = coefficients() * polynomial_bases;
58
59 double dx, dy, ddx, ddy;
60
61 // If t = 0, all other terms in the equation cancel out to zero. We can use
62 // the last x⁰ term in the equation.
63 if (t == 0.0) {
64 dx = coefficients()(2, Degree - 1);
65 dy = coefficients()(3, Degree - 1);
66 ddx = coefficients()(4, Degree - 2);
67 ddy = coefficients()(5, Degree - 2);
68 } else {
69 // Divide out t for first derivative.
70 dx = combined[2] / t;
71 dy = combined[3] / t;
72
73 // Divide out t for second derivative.
74 ddx = combined[4] / t / t;
75 ddy = combined[5] / t / t;
76 }
77
78 if (std::hypot(dx, dy) < 1e-6) {
79 return std::nullopt;
80 }
81
82 // Find the curvature.
83 const auto curvature =
84 (dx * ddy - ddx * dy) / ((dx * dx + dy * dy) * std::hypot(dx, dy));
85
86 return PoseWithCurvature{
87 {Translation2d{combined[0], combined[1]}, Rotation2d{dx, dy}},
88 curvature};
89 }
90
94 virtual const Eigen::Matrix<double, 6, Degree + 1>& coefficients() const = 0;
95
99 virtual const ControlVector& get_initial_control_vector() const = 0;
100
104 virtual const ControlVector& get_final_control_vector() const = 0;
105};
106
107} // namespace trajopt
Definition spline.hpp:23
virtual const ControlVector & get_final_control_vector() const =0
std::optional< PoseWithCurvature > get_point(double t) const
Definition spline.hpp:47
virtual const Eigen::Matrix< double, 6, Degree+1 > & coefficients() const =0
std::pair< Pose2d, double > PoseWithCurvature
Pose2d with curvature.
Definition spline.hpp:26
virtual const ControlVector & get_initial_control_vector() const =0
Definition spline.hpp:35
std::array< double,(Degree+1)/2 > y
The y components of the control vector.
Definition spline.hpp:40
std::array< double,(Degree+1)/2 > x
The x components of the control vector.
Definition spline.hpp:37