-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfdf_draw_bresenham_line.c
122 lines (109 loc) · 2.86 KB
/
fdf_draw_bresenham_line.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* fdf_draw_bresenham_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fvonsovs <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/15 12:53:09 by fvonsovs #+# #+# */
/* Updated: 2023/03/21 16:40:12 by fvonsovs ### ########.fr */
/* */
/* ************************************************************************** */
#include "fdf.h"
// calculates the direction in which line should be drawn
t_increment calculate_increment(t_line *line)
{
t_increment inc;
if (line->x1 < line->x2)
inc.x = 1;
else
inc.x = -1;
if (line->y1 < line->y2)
inc.y = 1;
else
inc.y = -1;
return (inc);
}
// error calculation for bresenhams algorithm
void update_error(t_line *line, int *coord, int error_diff, int coord_diff)
{
int diff;
if (line->dx > line->dy)
diff = line->dx;
else
diff = line->dy;
if (line->error > 0)
{
*coord += coord_diff;
line->error -= 2 * diff;
}
line->error += 2 * error_diff;
}
// another one because 25 lines is too much for 42 :))
void initialize_line_vars(t_line *line, t_increment *inc, int *x, int *y)
{
line->dx = abs(line->x2 - line->x1);
line->dy = abs(line->y2 - line->y1);
inc->x = 0;
inc->y = 0;
*inc = calculate_increment(line);
*x = line->x1;
*y = line->y1;
line->error = line->dx - line->dy;
}
// draws a line with bresenhams algorithm
// called by draw_line_wrapper function
void bresenham_line(t_data *data, t_line line, int color)
{
t_increment inc;
int x;
int y;
initialize_line_vars(&line, &inc, &x, &y);
if (line.dx > line.dy)
{
line.error = 2 * line.dy - line.dx;
while (x != line.x2)
{
mlx_pixel_put(data->mlx, data->win, x, y, color);
x += inc.x;
update_error(&line, &y, line.dy, inc.y);
}
}
else
{
line.error = 2 * line.dx - line.dy;
while (y != line.y2)
{
mlx_pixel_put(data->mlx, data->win, x, y, color);
y += inc.y;
update_error(&line, &x, line.dx, inc.x);
}
}
}
/*
// test function
void test_bresenham_line(t_data *data)
{
t_2d p1, p2;
p1.x = 300;
p1.y = 300;
p2.x = 500;
p2.y = 200;
bresenham_line (data, p1, p2, 0xFFFFFF);
p1.x = 500;
p1.y = 500;
p2.x = 400;
p2.y = 300;
bresenham_line (data, p1, p2, 0xFFFFFF);
p1.x = 900;
p1.y = 500;
p2.x = 200;
p2.y = 400;
bresenham_line (data, p1, p2, 0xFFFFFF);
p1.x = 200;
p1.y = 500;
p2.x = 200;
p2.y = 450;
bresenham_line (data, p1, p2, 0xFFFFFF);
}
*/