1 /**
2 Copyright: Copyright (c) 2017-2018 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module voxelman.geometry.bresenham;
7 
8 void bresenham(int x1, int y1, const int x2, const int y2, scope void delegate(int x, int y) plot)
9 {
10 	int delta_x = x2 - x1;
11 	immutable int ix = (delta_x > 0) - (delta_x < 0);
12 	delta_x = (delta_x < 0 ? -delta_x : delta_x) << 1; // 2 * abs(delta_x)
13 
14 	int delta_y = y2 - y1;
15 	immutable int iy = (delta_y > 0) - (delta_y < 0);
16 	delta_y = (delta_y < 0 ? -delta_y : delta_y) << 1; // 2 * abs(delta_y)
17 
18 	plot(x1, y1);
19 
20 	if (delta_x >= delta_y)
21 	{
22 		int error = delta_y - (delta_x >> 1);
23 
24 		while (x1 != x2)
25 		{
26 			if ((error > 0) || (!error && (ix > 0)))
27 			{
28 				error -= delta_x;
29 				y1 += iy;
30 			}
31 
32 			error += delta_y;
33 			x1 += ix;
34 
35 			plot(x1, y1);
36 		}
37 	}
38 	else
39 	{
40 		int error = delta_x - (delta_y >> 1);
41 
42 		while (y1 != y2)
43 		{
44 			if ((error > 0) || (!error && (iy > 0)))
45 			{
46 				error -= delta_y;
47 				x1 += ix;
48 			}
49 
50 			error += delta_x;
51 			y1 += iy;
52 
53 			plot(x1, y1);
54 		}
55 	}
56 }