Browse Source

add bresenham line algo, lfutility and Point struct

master
Evan Burkey 10 months ago
parent
commit
a0a43845b7
  1. 6
      include/lfmath.h
  2. 9
      include/lfutility.h
  3. 6
      src/lfinput.c
  4. 38
      src/lfmath.c

6
include/lfmath.h

@ -1,6 +1,8 @@ @@ -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); @@ -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

9
include/lfutility.h

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
#ifndef LIBFLINT_H_UTILITY
#define LIBFLINT_H_UTILITY
typedef struct Point {
int x;
int y;
} Point;
#endif // LIBFLINT_H_UTILITY

6
src/lfinput.c

@ -71,8 +71,10 @@ int *get_ints(const char *path, size_t *sz) { @@ -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;
}

38
src/lfmath.c

@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@
#include <string.h>
#include <stdlib.h>
#include "lfmath.h"
@ -35,3 +36,40 @@ int binstr_to_int(const char *s) { @@ -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);
}
Loading…
Cancel
Save