src/bezier_curve.cpp

changeset 373
e34d6a30b96d
equal deleted inserted replaced
372:b2914aaeec1a 373:e34d6a30b96d
1 #include "bezier_curve.h"
2
3 /**
4 * @brief computes the point on a Bezier curve
5 * @param curve
6 * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3
7 * @return point on curve
8 */
9 glm::vec3 point_on_bezier_curve(const struct bezier_curve &curve, float t)
10 {
11 // clamp t as rounding errors might make it slightly out of bounds
12 t = std::clamp(t, 0.0f, 1.0f);
13 const float t_squared = t * t;
14 const float t_cubed = t * t * t;
15 const float coefficients[3] = {
16 -1*t_cubed +3*t_squared -3*t +1,
17 +3*t_cubed -6*t_squared +3*t,
18 -3*t_cubed +3*t_squared,
19 };
20 return coefficients[0] * curve.points[0]
21 + coefficients[1] * curve.points[1]
22 + coefficients[2] * curve.points[2]
23 + t_cubed * curve.points[3];
24 }
25
26 /**
27 * @brief computes the derivative of a point on a Bezier curve
28 * @param curve
29 * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3
30 * @return point on curve
31 */
32 glm::vec3 derivate_on_bezier_curve(const struct bezier_curve &curve, float t)
33 {
34 // clamp t as rounding errors might make it slightly out of bounds
35 t = std::clamp(t, 0.0f, 1.0f);
36 const float t_cubed = t * t;
37 const float coefficients[4] = {
38 -3*t_cubed + 6*t -3,
39 +9*t_cubed -12*t +3,
40 -9*t_cubed + 6*t,
41 +3*t_cubed
42 };
43 return coefficients[0] * curve.points[0]
44 + coefficients[1] * curve.points[1]
45 + coefficients[2] * curve.points[2]
46 + coefficients[3] * curve.points[3];
47 }

mercurial