From 238ce2c2d24d84bf01aa92b7fdffbeffb24a1f93 Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Wed, 30 Mar 2022 14:35:23 -0700 Subject: [PATCH] add bresenham line algo, lfutility and Point struct --- include/lfmath.h | 6 ++++++ include/lfutility.h | 9 +++++++++ src/lfinput.c | 6 ++++-- src/lfmath.c | 38 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 2 deletions(-) create mode 100644 include/lfutility.h diff --git a/include/lfmath.h b/include/lfmath.h index 3bcf36f..34542bb 100644 --- a/include/lfmath.h +++ b/include/lfmath.h @@ -1,6 +1,8 @@ #ifndef LIBFLINT_H_MATH #define LIBFLINT_H_MATH +#include "lfutility.h" + int max_int(int a, int b); int min_int(int a, int b); @@ -9,4 +11,8 @@ int clamp_int(int i, int low, int high); int binstr_to_int(const char *s); +Point *bresenham(int x0, int y0, int x1, int y1, size_t *sz); + +Point *bresenham_p(Point p1, Point p2, size_t *sz); + #endif // LIBFLINT_H_MATH diff --git a/include/lfutility.h b/include/lfutility.h new file mode 100644 index 0000000..41d9b3e --- /dev/null +++ b/include/lfutility.h @@ -0,0 +1,9 @@ +#ifndef LIBFLINT_H_UTILITY +#define LIBFLINT_H_UTILITY + +typedef struct Point { + int x; + int y; +} Point; + +#endif // LIBFLINT_H_UTILITY diff --git a/src/lfinput.c b/src/lfinput.c index 07c0663..71b47b3 100644 --- a/src/lfinput.c +++ b/src/lfinput.c @@ -71,8 +71,10 @@ int *get_ints(const char *path, size_t *sz) { const char *errstr; n = (int) strtonum(lines[idx], INT_MIN, INT_MAX, &errstr); if (errstr) { - printf("Failed to convert %s to int. Returning NULL\n", lines[idx]); - exit(1); + fprintf(stderr, "Failed to convert %s to int. Returning NULL\n", lines[idx]); + free(i); + del_lines(lines); + return NULL; } i[idx] = n; } diff --git a/src/lfmath.c b/src/lfmath.c index ec685ce..380ec50 100644 --- a/src/lfmath.c +++ b/src/lfmath.c @@ -1,4 +1,5 @@ #include +#include #include "lfmath.h" @@ -35,3 +36,40 @@ int binstr_to_int(const char *s) { } return n; } + +Point *bresenham(int x0, int y0, int x1, int y1, size_t *sz) { + Point *line = NULL; + size_t n = 0; + *sz = 0; + + int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + int dy = abs(y1 - y0), sy = y0 < y1 ? 1 : -1; + int err = (dx > dy ? dx : -dy) / 2, e2; + + for (;;) { + line = realloc(line, sizeof(Point) * ++n); + ++*sz; + line[n - 1].x = x0; + line[n - 1].y = y0; + + if (x0 == x1 && y0 == y1) { + break; + } + + e2 = err; + if (e2 > -dx) { + err -= dy; + x0 += sx; + } + if (e2 < dy) { + err += dx; + y0 += sy; + } + } + + return line; +} + +Point *bresenham_p(Point p1, Point p2, size_t *sz) { + return bresenham(p1.x, p1.y, p2.x, p2.y, sz); +} \ No newline at end of file