--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/bezier_curve.cpp Mon Apr 10 14:46:36 2023 +0300 @@ -0,0 +1,47 @@ +#include "bezier_curve.h" + +/** + * @brief computes the point on a Bezier curve + * @param curve + * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3 + * @return point on curve + */ +glm::vec3 point_on_bezier_curve(const struct bezier_curve &curve, float t) +{ + // clamp t as rounding errors might make it slightly out of bounds + t = std::clamp(t, 0.0f, 1.0f); + const float t_squared = t * t; + const float t_cubed = t * t * t; + const float coefficients[3] = { + -1*t_cubed +3*t_squared -3*t +1, + +3*t_cubed -6*t_squared +3*t, + -3*t_cubed +3*t_squared, + }; + return coefficients[0] * curve.points[0] + + coefficients[1] * curve.points[1] + + coefficients[2] * curve.points[2] + + t_cubed * curve.points[3]; +} + +/** + * @brief computes the derivative of a point on a Bezier curve + * @param curve + * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3 + * @return point on curve + */ +glm::vec3 derivate_on_bezier_curve(const struct bezier_curve &curve, float t) +{ + // clamp t as rounding errors might make it slightly out of bounds + t = std::clamp(t, 0.0f, 1.0f); + const float t_cubed = t * t; + const float coefficients[4] = { + -3*t_cubed + 6*t -3, + +9*t_cubed -12*t +3, + -9*t_cubed + 6*t, + +3*t_cubed + }; + return coefficients[0] * curve.points[0] + + coefficients[1] * curve.points[1] + + coefficients[2] * curve.points[2] + + coefficients[3] * curve.points[3]; +}