cgv
Loading...
Searching...
No Matches
bresenham.h
1#pragma once
2
3#include <vector>
4
5#include "fvec.h"
6
8namespace cgv {
9namespace math {
10
15static std::vector<fvec<int, 2>> bresenham(fvec<int, 2> origin, fvec<int, 2> destination) {
16
17 bool flip = std::abs(destination.y() - origin.y()) >= std::abs(destination.x() - origin.x());
18
19 if(flip) {
20 std::swap(origin.x(), origin.y());
21 std::swap(destination.x(), destination.y());
22 }
23
24 if(origin.x() > destination.x())
25 std::swap(origin, destination);
26
27 fvec<int, 2> d = destination - origin;
28
29 int yi = 1;
30 if(d.y() < 0) {
31 yi = -1;
32 d.y() = -d.y();
33 }
34 int D = (2 * d.y()) - d.x();
35 int y = origin.y();
36
37 std::vector<fvec<int, 2>> points;
38
39 for(int x = origin.x(); x <= destination.x(); ++x) {
40 flip ? points.emplace_back(y, x) : points.emplace_back(x, y);
41 if(D > 0) {
42 y = y + yi;
43 D = D + (2 * (d.y() - d.x()));
44 } else {
45 D = D + 2 * d.y();
46 }
47 }
48
49 return points;
50};
51
53private:
54 fvec<int, 2> origin_ = fvec<int, 2>(0);
55 fvec<int, 2> destination_ = fvec<int, 2>(0);
56 fvec<int, 2> position_ = fvec<int, 2>(0);
57 bool done_ = false;
58
59 int dx = 0;
60 int sx = 0;
61 int dy = 0;
62 int sy = 0;
63 int error = 0;
64
65public:
66 bresenham_traverser(fvec<int, 2> origin, fvec<int, 2> destination) : origin_(origin), destination_(destination) {
67
68 position_ = origin_;
69
70 if(origin_ == destination_)
71 done_ = true;
72
73 dx = std::abs(destination_.x() - origin_.x());
74 sx = origin_.x() < destination_.x() ? 1 : -1;
75 dy = -std::abs(destination_.y() - origin_.y());
76 sy = origin_.y() < destination_.y() ? 1 : -1;
77 error = dx + dy;
78 }
79
80 bool done() const {
81
82 return done_;
83 }
84
85 fvec<int, 2> position() const {
86
87 return position_;
88 }
89
90 fvec<int, 2> origin() const {
91
92 return origin_;
93 }
94
95 fvec<int, 2> destination() const {
96
97 return destination_;
98 }
99
100 void step() {
101
102 int e2 = 2 * error;
103
104 if(e2 >= dy) {
105 error += dy;
106 position_.x() += sx;
107 }
108
109 if(e2 <= dx) {
110 error += dx;
111 position_.y() += sy;
112 }
113
114 if(position_ == destination_)
115 done_ = true;
116 }
117
118 void operator++() {
119
120 step();
121 }
122};
123
124} // namespace math
125} // namespace cgv
A vector with zero based index.
Definition fvec.h:26
T & y()
second element
Definition fvec.h:159
T & x()
first element
Definition fvec.h:155
the cgv namespace
Definition print.h:11