c++bgibresenham

Implementation of Line Drawing Algorithm doesn't work properly


First question, I have tried to calculate the expression, di+1=di+2*Δy−2*Δx(yi+1−yi) for the four quadrants. Irrespective of the quadrant, the expression was found to be the same, including signs. Am I right, or, there has been some mistakes in my calculations (hence, I am wrong)?

Second question, if this expression is only applicable for the first octet, how can I apply this to other octets? To me, there is no way to determine which octet I am working on. Coz, the value of m always represent two opposite octets. For example, if 0<m<1, it represents 1st and 5th octet. Right?

Thirdly, how can we determine the initial/starting value of di?

#include <iostream>
#include "utils.h"

void BresenhamLine(double x1, double y1, double x2, double y2, int color)
{
    if(x1>x2 || y1>y2)
    {
        Swap(x1, x2);
        Swap(y1, y2);
    }
    double x = x1;
    double y = y1;
    double dx = x2 - x1;
    double dy = y2 - y1;
    double dt = 2 * (dy - dx);
    double ds = 2 * dy;
    double d = 2*dy - dx;

    PlotPixel(x, y, color);

    if(dx>=dy)
    {
        while(x<=x2)
        {
            x++;
            if(d<0)
            {
                d = d + ds;
            }
            else
            {
                y++;
                d = d + dt;
            }
            PlotPixel(x, y, color);
        }
    }
    else
    {
        while(y<=y2)
        {
            y++;
            if(d<0)
            {
                x++;
                d = d + dt;
            }
            else
            {               
                d = d + ds;
            }
            PlotPixel(x, y, color);
        }
    }
}

int main()
{
int gm = DETECT;
int gd = DETECT;

initgraph(&gm, &gd, "");

double x1 = 0;
double y1 = 0;
double r = 50;
double x2 = 0;
double y2 = 0;
double signx = 0;
double signy = 0;

for(int theta=0 ; theta<=360 ; theta++)
{
    x2 = r * cos(DegreeToRad((double) theta));
    y2 = r * sin(DegreeToRad((double) theta));

    x1 = 5 * cos(DegreeToRad((double) theta));
    y1 = 5 * sin(DegreeToRad((double) theta));

    BresenhamLine(x1, y1, x2, y2, YELLOW);
}

getch();
closegraph();
return 0;
}

The lines that go through 2nd and 4th quadrant are not showing up.

How to fix that with some minor changes in my code?


Solution

  • With this input: x1: 100 y1: -100 x2: -100 y2: 100

    this logic:

    if(x1>x2 || y1>y2)
    {   
        Swap(x1, x2);
        Swap(y1, y2);
    }   
    

    fails.