Saturday, September 17, 2016

2. Write a program to implement Bresenham’s line drawing algorithm with all values of slopes

#include<iostream>
#include<math.h>
#include<GL/glut.h>
using namespace std;
GLdouble X1, Y1, X2, Y2;

void Init()
{
    glClearColor(0.0,1.0,1.0, 0);
    glClear(GL_COLOR_BUFFER_BIT);    // Clear the color buffer (background)
    glColor3f(1.0, 0.0, 0.0);
    glViewport(0 , 0 , 640 , 480);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0 , 640 , 0 , 480);
}

void BresenhamLine(void)
{
    Init();
    int dx = abs (X1 - X2), dy = abs (Y1 - Y2);
    int p = 2 * dy - dx;
    int twoDy = 2 * dy, twoDyDx = 2 * (dy - dx);
    int x, y, xEnd, yEnd;
    if (X1==X2)
    {
         x = X1;
         y = Y1;
         yEnd = Y2;
         glBegin(GL_POINTS);
         while (y <= yEnd)
         {
            y++;
            glVertex2d(x,y);
         }
         glEnd();
    }

    if (X1 > X2)
    {
        x = X2;
        y = Y2;
        xEnd = X1;
    }
    else
    {
        x = X1;
        y = Y1;
        xEnd = X2;
    }

     glBegin(GL_POINTS);
     {
        glVertex2d(x,y);
        while (x < xEnd)
        {
            x++;
            if (p < 0)
                p += twoDy;
            else
            {
                y++;
                p += twoDyDx;
            }
            glVertex2d(x,y);
        }
     } glEnd();
    glFlush();
}

int main(int argc, char** argv) {
    cout<<"Enter Two Points for Draw Line using Bresenham's algorithm:\n";
    cout<<"\nEnter Point1( X1 , Y1):";
    cin>>X1>>Y1;
    cout<<"\nEnter Point2( X2 , Y2):";
    cin>>X2>>Y2;

   glutInit(&argc, argv);                 // Initialize GLUT
   glutCreateWindow("OpenGL Bresenham Line Algorithm");
   glutInitWindowSize(320, 320);   // Set the window's initial width & height
   glutInitWindowPosition(50, 50); // Position the window's initial top-left corner

   glutDisplayFunc(BresenhamLine); // Register display callback handler for window re-paint

   glutMainLoop();           // Enter the event-processing loop
   return 0;
}

No comments:

Post a Comment