Control Surface main
MIDI Control Surface library for Arduino
Loading...
Searching...
No Matches
Bresenham.hpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <AH/STL/cmath>
6#include <AH/STL/limits>
7#include <Printable.h>
8#include <Settings/SettingsWrapper.hpp>
9
11
12template <typename T>
13static constexpr inline int sgn(T val) {
14 return (T(0) < val) - (val < T(0));
15}
16
19 public:
20 using pint = int16_t;
21 struct Pixel : public Printable {
22 pint x = 0, y = 0;
23 Pixel(pint x, pint y) : x(x), y(y) {}
24 Pixel() = default;
25 size_t printTo(Print &p) const override;
26 unsigned int distanceSquared(Pixel other) const {
27 int dx = this->x - other.x;
28 int dy = this->y - other.y;
29 return dx * dx + dy * dy;
30 }
31 };
32
33 BresenhamLine(Pixel start, int cos, int sin)
34 : px(start), // Starting point
35 dx(cos), dy(sin), // cosine and sine of the slope of the line (scaled)
36 adx(std::abs(dx)),
37 ady(std::abs(dy)), // absolute values of cos and sin
38 xinc(sgn(dx)), yinc(sgn(dy)), // increment steps for x and y
39 steep(ady > adx) // whether to increment x or y on each iteration
40 {
41 if (steep)
42 error = adx - ady + adx;
43 else
44 error = ady - adx + ady;
45 }
46
47 BresenhamLine(Pixel start, float angle)
49 start,
50 BresenhamLine::cos(angle),
51 BresenhamLine::sin(angle),
52 } {}
53
54 pint getCurrentLength() const { return length; }
55
57 Pixel result = px;
58 if (steep) {
59 if (error >= 0) {
60 px.x += xinc;
61 error -= 2 * ady;
62 }
63 px.y += yinc;
64 error += 2 * adx;
65 } else {
66 if (error >= 0) {
67 px.y += yinc;
68 error -= 2 * adx;
69 }
70 px.x += xinc;
71 error += 2 * ady;
72 }
73 ++length;
74 return result;
75 }
76
77 static int cos(float angle) {
78 return std::round(static_cast<float>(errorScalingFactor) *
79 std::cos(angle));
80 }
81
82 static int sin(float angle) {
83 return std::round(static_cast<float>(errorScalingFactor) *
84 std::sin(angle));
85 }
86
87 private:
88 const static int errorScalingFactor = std::numeric_limits<int>::max() / 2;
90 int dx, dy;
91 int adx, ady;
92 int xinc, yinc;
93 bool steep;
94 int error;
96};
97
static constexpr int sgn(T val)
Definition Bresenham.hpp:13
#define END_CS_NAMESPACE
#define BEGIN_CS_NAMESPACE
Line rasterization algorithm for drawing lines to the display.
Definition Bresenham.hpp:18
BresenhamLine(Pixel start, float angle)
Definition Bresenham.hpp:47
static const int errorScalingFactor
Definition Bresenham.hpp:88
static int sin(float angle)
Definition Bresenham.hpp:82
static int cos(float angle)
Definition Bresenham.hpp:77
BresenhamLine(Pixel start, int cos, int sin)
Definition Bresenham.hpp:33
pint getCurrentLength() const
Definition Bresenham.hpp:54
Pixel(pint x, pint y)
Definition Bresenham.hpp:23
unsigned int distanceSquared(Pixel other) const
Definition Bresenham.hpp:26
size_t printTo(Print &p) const override
Definition Bresenham.cpp:5