Skip to content

Instantly share code, notes, and snippets.

@cjlano
Forked from anonymous/bezier.c.c
Created February 28, 2013 14:57
Show Gist options
  • Save cjlano/5057335 to your computer and use it in GitHub Desktop.
Save cjlano/5057335 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
struct image {
uint32_t size_x;
uint32_t size_y;
uint8_t* pixels;
};
struct point {
double x;
double y;
};
int print_pbm(struct image * i)
{
uint32_t x, y;
uint8_t* pixel = i->pixels;
printf("P1\n");
printf("%u %u\n", i->size_x, i->size_y);
for (x = 0; x < i->size_x; x++) {
for (y = 0; y < i->size_y; y++) {
if (*(pixel++))
printf("1 ");
else
printf("0 ");
}
printf("\n");
}
return 0;
}
int image_addpoint(struct image * img, struct point * pt)
{
uint32_t x, y;
x = (uint32_t) round(pt->x);
y = (uint32_t) round(pt->y);
if ((x > img->size_x) || (y > img->size_y))
return -1;
*(img->pixels + y*img->size_x + x) = 1;
return 0;
}
struct segment {
struct point p0;
struct point p1;
};
//struct point bezier1(double t, struct segment * s)
struct point bezier1(struct point p0, struct point p1, double t)
{
struct point res;
res.x = p0.x +t*(p1.x - p0.x);
res.y = p0.y +t*(p1.y - p0.y);
//printf("(%lf,%lf)\n",res.x, res.y);
return res;
}
struct point bezierN(uint8_t N, struct point * pts, double t)
{
int i, n;
struct point q;
struct point * res = malloc(sizeof(struct point)*N);
for (i = 0; i < N; i++)
res[i] = pts[i];
for (n = N; n > 1; n--) {
for (i = 0; i < n-1; i++) {
q = bezier1(res[i], res[i+1], t);
res[i] = q;
}
}
q = res[0];
free(res);
return q;
}
#define IMG_X (100)
#define IMG_Y (100)
int main(void)
{
struct image img;
struct point pt1, pt2, a,b,c, p0, p1;
struct point pts[4];
double t;
img.size_x = IMG_X;
img.size_y = IMG_Y;
img.pixels = malloc(IMG_X*IMG_Y);
memset(img.pixels, 0, img.size_x*img.size_y);
pts[0].x = 10;
pts[0].y = 90;
pts[1].x = 5;
pts[1].y = 40;
pts[2].x = 60;
pts[2].y = 40;
pts[3].x = 90;
pts[3].y = 90;
for (t = 0.0; t < 1.0; t += 0.01) {
pt1 = bezierN(4, pts, t);
/*p0 = bezier1(a, b, t);
p1 = bezier1(b, c, t);
pt1 = bezier1(p0, p1, t);*/
image_addpoint(&img, &pt1);
//printf("((%u,%u))\n",pt1.x, pt1.y);
}
print_pbm(&img);
free(img.pixels);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment