Skip to content

Instantly share code, notes, and snippets.

@KPB3rd
Created July 19, 2022 16:06
Show Gist options
  • Select an option

  • Save KPB3rd/7f281a7343a65c260ac995297d3fb707 to your computer and use it in GitHub Desktop.

Select an option

Save KPB3rd/7f281a7343a65c260ac995297d3fb707 to your computer and use it in GitHub Desktop.
Bezier code for path planning
// https://github.com/Rezonality/mutils/blob/6adc3fa9d160f455092637032cb6fcd6162d0b93/include/mutils/math/math_utils.h#L124
template <typename T>
inline T Bezier(float t, T p0, T p1, T p2, T p3) {
return std::pow(1 - t, 3) * p0 + 3 * std::pow(1 - t, 2) * t * p1 + 3 * (1 - t) * (t * t) * p2 + std::pow(t, 3) * p3;
}
template <typename T>
inline T BezierPt(float t, T p0, T p1, T p2, T p3)
{
return T(Bezier(t, p0.x(), p1.x(), p2.x(), p3.x()), Bezier(t, p0.y(), p1.y(), p2.y(), p3.y()));
}
template <typename T>
inline T BezierDerivative(float t, T p0, T p1, T p2, T p3)
{
return 3 * pow(1 - t, 2) * (p1 - p0) + 6 * (1 - t) * t * (p2 - p1) + 3 * (t * t) * (p3 - p2);
}
template <typename T>
inline T BezierDerivativeVec(float t, const T& p0, const T& p1, const T& p2, const T& p3)
{
return T(BezierDerivative(t, p0.x(), p1.x(), p2.x(), p3.x()), BezierDerivative(t, p0.y(), p1.y(), p2.y(), p3.y()));
}
template <typename T>
inline T BezierSecondDerivative(float t, T p0, T p1, T p2, T p3)
{
return 6 * (1 - t) * (p2 - 2*p1 + p0) + 6 * t * (p3 - 2 * p2 + p1);
}
// Tangent
template <typename T>
inline T BezierSecondDerivativeVec(float t, const T& p0, const T& p1, const T& p2, const T& p3)
{
return T(BezierSecondDerivative(t, p0.x(), p1.x(), p2.x(), p3.x()), BezierSecondDerivative(t, p0.y(), p1.y(), p2.y(), p3.y()));
}
// https://math24.net/curvature-radius.html
template <typename T>
inline double CalcCurvature(float t, const T& p0, const T& p1, const T& p2, const T& p3) {
auto first_dir = BezierDerivativeVec(t, p0, p1, p2, p3);
auto second_dir = BezierSecondDerivativeVec(t, p0, p1, p2, p3);
double k = fabs(first_dir.x() * second_dir.y() - first_dir.y() * second_dir.x()) /
std::pow(first_dir.x() * first_dir.x() + first_dir.y() * first_dir.y(), 3. / 2);
double radius_of_curvature = 1.0 / k;
return radius_of_curvature;
}
template <typename T>
inline double computeCurvature(T p0, T p1, T p2) {
double dx1 = p1.x() - p0.x();
double dy1 = p1.y() - p0.y();
double dx2 = p2.x() - p0.x();
double dy2 = p2.y() - p0.y();
double area = 0.5 * (dx1 * dy2 - dy1 * dx2);
double len0 = p0.DistanceTo2D(p1);
double len1 = p1.DistanceTo2D(p2);
double len2 = p2.DistanceTo2D(p0);
return 4 * area / (len0 * len1 * len2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment