From e91f44430d7b829b7dc6635e08d4c5be36747320 Mon Sep 17 00:00:00 2001 From: joachimschmidt557 Date: Thu, 10 Oct 2019 18:59:06 +0200 Subject: [PATCH] Add bresenham --- bresenham/Makefile | 7 ++++ bresenham/main.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 bresenham/Makefile create mode 100644 bresenham/main.c diff --git a/bresenham/Makefile b/bresenham/Makefile new file mode 100644 index 0000000..a3504dd --- /dev/null +++ b/bresenham/Makefile @@ -0,0 +1,7 @@ +CFLAGS+=-Wall +CFLAGS+=-Wextra + +all: main + +main: main.c + $(CC) -o main main.c $(CFLAGS) diff --git a/bresenham/main.c b/bresenham/main.c new file mode 100644 index 0000000..6af260f --- /dev/null +++ b/bresenham/main.c @@ -0,0 +1,84 @@ +#include +#include + +typedef struct { + int x; + int y; +} point; + +void +bresenham(point* start, point* end, int** pixels) { + int dx = end->x - start->x; + int dy = end->y - start->y; + int x = start->x; + int y = start->y; + + pixels[x][y] = 1; + + double fehler = dx / 2.0; + + while (x < end->x) { + x++; + fehler = fehler - dy; + if (fehler < 0) { + y++; + fehler = fehler + dx; + } + pixels[x][y] = 1; + } +} + +int** +empty(int width, int height) { + int** result = malloc(width * sizeof(int*)); + for (int i = 0; i < width; i++) { + int* column = malloc(height * sizeof(int)); + result[i] = column; + for (int j = 0; j < height; j++) { + result[i][j] = 0; + } + } + return result; +} + +void +freepixels(int** pixels, int width) { + for (int i = 0; i < width; i++) { + free(pixels[i]); + } + free(pixels); +} + +void +printpixels(int** pixels, int width, int height) { + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + printf("%d", pixels[i][j]); + } + printf("\n"); + } +} + +int +main() { + int width = 11; + int height = 9; + int** pixels = empty(width, height); + + point* start = malloc(sizeof(point)); + point* end = malloc(sizeof(point)); + + start->x = 1; + start->y = 2; + end->x = 9; + end->y = 6; + + bresenham(start, end, pixels); + + printpixels(pixels, width, height); + + freepixels(pixels, width); + + free(start); + free(end); +}