Skip to content

Instantly share code, notes, and snippets.

@assyrianic
Last active May 15, 2023 18:50
Show Gist options
  • Save assyrianic/ec7e63cad63e0837459a003ad0008908 to your computer and use it in GitHub Desktop.
Save assyrianic/ec7e63cad63e0837459a003ad0008908 to your computer and use it in GitHub Desktop.
/// Bresenham's algorithm in simplistic C
void drawline(int const x0, int const y0, int const x1, int const y1) {
int const dx = x1 - x0;
int const dy = y1 - y0;
int p = 2 * dy - dx;
for( int x = x0, y = y0; x < x1; x++ ) {
if( p >= 0 ) {
putpixel(x, y, 7);
y++;
p += 2 * dy - 2 * dx;
} else {
putpixel(x, y, 7);
p += 2 * dy;
}
}
}
@assyrianic
Copy link
Author

assyrianic commented Jan 6, 2022

Struct Version.

struct Vec2 { int x,y; };
void drawline(struct Vec2 const origin1, struct Vec2 const origin2) {
	struct Vec2 const d = { origin2.x - origin1.x, origin2.y - origin1.y };
	int p = 2 * d.y - d.x;
	for( int x = origin1.x, y = origin1.y; x < origin2.x; x++ ) {
		if( p >= 0 ) {
			putpixel(x, y, 7);
			y++;
			p += 2 * d.y - 2 * d.x;
		} else {
			putpixel(x, y, 7);
			p += 2 * d.y;
		}
	}
}

Golang version:

func drawline(x0, y0, x1, y1 int) {
	dx, dy := x1 - x0, y1 - y0
	p, y := 2 * dy - dx, y0
	for x := x0; x < x1; x++ {
		if p >= 0 {
			putpixel(x, y, 7)
			y++
			p += 2 * dy - 2 * dx
		} else {
			putpixel(x, y, 7)
			p += 2 * dy
		}
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment