Magical bresenham

This commit is contained in:
hodasemi 2019-05-18 20:12:51 +02:00
parent dcd85110a6
commit 4d476b510b

View file

@ -7,6 +7,8 @@
#include <algorithm> #include <algorithm>
#include <math.h> #include <math.h>
#include <iostream>
// Initialize the tool and store a reference of a canvas_buffer // Initialize the tool and store a reference of a canvas_buffer
bresenham_line_tool::bresenham_line_tool(canvas_buffer &canvas) : tool_base(canvas) bresenham_line_tool::bresenham_line_tool(canvas_buffer &canvas) : tool_base(canvas)
{ {
@ -14,8 +16,10 @@ bresenham_line_tool::bresenham_line_tool(canvas_buffer& canvas): tool_base(canva
shape = TS_LINE; shape = TS_LINE;
} }
void print_point(int x, int y)
{
std::cout << "point (" << x << ", " << y << ")" << std::endl;
}
// Draw a line from (x0, y0) to (x1, y1) // Draw a line from (x0, y0) to (x1, y1)
void bresenham_line_tool::draw(int x0, int y0, int x1, int y1) void bresenham_line_tool::draw(int x0, int y0, int x1, int y1)
@ -35,10 +39,89 @@ void bresenham_line_tool::draw(int x0, int y0, int x1, int y1)
den Standardfall her. Falls Sie den Wert zweier Variablen vertauschen den Standardfall her. Falls Sie den Wert zweier Variablen vertauschen
muessen koennen Sie dafür die Methode "std::swap(a, b)" verwenden. muessen koennen Sie dafür die Methode "std::swap(a, b)" verwenden.
*************/ *************/
std::cout << "first: " << std::endl;
print_point(x0, y0);
print_point(x1, y1);
if (x0 > x1)
{
std::swap(x0, x1);
std::swap(y0, y1);
} }
std::cout << "second: " << std::endl;
print_point(x0, y0);
print_point(x1, y1);
std::cout << std::endl;
bool swap_y = false;
if (y0 > y1)
{
swap_y = true;
std::swap(y0, y1);
}
int x = x0;
int y = y0;
float dx = static_cast<float>(abs(x1 - x0));
float dy = static_cast<float>(abs(y1 - y0));
int sR;
float f;
if (dx > dy)
{
sR = 0;
f = dx / 2.0f;
}
else
{
sR = 1;
f = dy / 2.0f;
}
int p = (2 * dy) - dx;
while (x < x1 || y < y1)
{
if (sR == 0)
{
x++;
f -= dy;
}
else
{
y++;
f -= dx;
}
if (f < 0.0f)
{
if (sR == 0)
{
y++;
f += dx;
}
else
{
x++;
f += dy;
}
}
int x_res = x;
if (swap_y)
{
x_res = x1 - (x - x0);
}
canvas.set_pixel(x_res, y);
}
}
// Put debug output into the stream "stream" to be displayed in the // Put debug output into the stream "stream" to be displayed in the
// main window // main window