For lesson 10 beginner - Line Code

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
Stigma
Posts: 2
Joined: June 15th, 2014, 10:54 pm

For lesson 10 beginner - Line Code

Post by Stigma » June 19th, 2014, 12:57 am

Guys the following code is a very good DrawLine code that incorporates Bresenham algorithm along with MS-Paint algorithm. Try it out if you like.

Code: Select all

void D3DGraphics::Drawline(int xStart, int yStart, int xEnd, int yEnd, int r, int g, int b)
{
    int dx, dy, inx, iny, e;
     
    dx = xEnd - xStart;
    dy = yEnd - yStart;
    inx = dx > 0 ? 1 : -1;
    iny = dy > 0 ? 1 : -1;
 
    dx = abs(dx);
    dy = abs(dy);
     
    if(dx >= dy) {
        dy <<= 1;
        e = dy - dx;
        dx <<= 1;
        while (xStart != xEnd) {
            PutPixel(xStart, yStart, r,g,b);
            if(e >= 0) {
                yStart += iny;
                e-= dx;
            }
            e += dy; xStart += inx;
        }
    } else {
        dx <<= 1;
        e = dx - dy;
        dy <<= 1;
        while (yStart != yEnd) {
            PutPixel(xStart, yStart, r,g,b);
            if(e >= 0) {
                xStart += inx;
                e -= dy;
            }
            e += dx; yStart += iny;
        }
    }
    PutPixel(xStart, yStart, r,g,b);
}

User avatar
chili
Site Admin
Posts: 3948
Joined: December 31st, 2011, 4:53 pm
Location: Japan
Contact:

Re: For lesson 10 beginner - Line Code

Post by chili » June 19th, 2014, 1:00 pm

Nice bro, I'm going to use this. I've been considering upgrading the algorithm in the framework to bresenham, but I didn't give quite enough fucks.

Since I was upgrading the line algorithm, I decided to do the circle one as well. The derivation for the recursive form of the equation is pretty hot shit.

Code: Select all

void D3DGraphics::DrawCircle( int centerX,int centerY,int radius,Color color )
{
	int x = radius,y = 0;
	int radiusError = 1 - x;
	while( x >= y )
	{
		PutPixel( centerX + x,centerY + y,color );
		PutPixel( centerX - x,centerY + y,color );
		PutPixel( centerX + x,centerY - y,color );
		PutPixel( centerX - x,centerY - y,color );
		PutPixel( centerX + y,centerY + x,color );
		PutPixel( centerX + y,centerY - x,color );
		PutPixel( centerX - y,centerY + x,color );
		PutPixel( centerX - y,centerY - x,color );

		y++;

		if( radiusError < 0 )
		{
			radiusError += 2 * y + 1;
		}
		else
		{
			x--;
			radiusError += 2 * ( y - x + 1 );
		}
	}
}
http://en.wikipedia.org/wiki/Midpoint_circle_algorithm

Although I wonder if the branch here is better than the square root. Probably is, since the square root would block the pipeline until it completes.
Chili

Post Reply