I have been looking at homemade CNC and have been wondering how curves are drawn, so I looked into it and found this cool article. I then decided to try coming up with a bezier curve algorithm in C. It seems to work ok, and while I haven't tried plotting points with this exact implementation, it seems to match up with results from a previous implementation that I did plot points with.
#include <stdint.h>
static long double bbezier(long double t, long double p0, long double p1){
return ((p1 - p0) * t) + p0;
}
long double bezier(long double t, uint64_t *points, uint64_t n){
long double p0 = points[0], p1 = points[1];
if(n == 1) return bbezier(t, p0, p1);
long double q0 = bezier(t, points, n - 1),
q1 = bezier(t, points + 1, n - 1);
return bbezier(t, q0, q1);
}
I then quickly wrote this test program in C++.
#include <iostream>
extern "C" long double bezier(long double, uint64_t *, uint64_t);
uint64_t pointsx[] = {
0, 40, 100, 200
};
uint64_t pointsy[] = {
0, 150, 60, 100
};
int main(){
for(uint64_t i = 0; i <= 10000; ++i){
long double ii = i;
long double j = ii/10000;
long double x = bezier(j, pointsx, 3);
long double y = bezier(j, pointsy, 3);
std::cout << "X: " << x << ", Y: " << y << '\n';
}
return 0;
}
I wrote an implementation running in javascript from a lightly modified w3 schools canvas tutorial here to understand how bezier curves work but it only supports 3rd degree curves. It does plot the points though, and that's what I based the above implementation on.
It doesn't make any checks to ensure t is between 0 and 1 and n != 0 but I'm not too worried. The only thing I'm worried about is segfaults in cases where n is so high that you get a stack overflow but that will be a pretty crazy curve. Anyway, how does it look?