World's most popular travel blog for travel bloggers.

# Write a program in C/C++ to implement DDA line drawing algorithm.

, ,
#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

float X1=200, Y1=2, X2=200, Y2=200;

float round_value(float v)
{
return v;// floor(v + 0.5);
}
void LineDDA(void)
{
float dx = (X2 - X1);
float dy = (Y2 - Y1);
float steps;
float xInc, yInc, x = X1, y = Y1;

steps = ((dx)>(dy)) ? ((dx)) : ((dy));
xInc = dx / (float)steps;
yInc = dy / (float)steps;

/* Clears buffers to preset values */
glClear(GL_COLOR_BUFFER_BIT);

/* Plot the points */
glBegin(GL_POINTS);
/* Plot the first point */
glVertex2d(x, y);
int k;
/* For every step, find an intermediate vertex */
for (k = 0; k<steps; k++)
{
x += xInc;
y += yInc;
/* printf("%0.6lf %0.6lf\n",floor(x), floor(y)); */
glVertex2d(round_value(x), round_value(y));
}
glEnd();

glFlush();
}
void Init()
{
/* Set clear color to white */
glClearColor(0.0, 0.0, 0.0, 0);
/* Set fill color to black */
glColor3f(1.0, 1.0, 0.0);
/* glViewport(0 , 0 , 640 , 480); */
/* glMatrixMode(GL_PROJECTION); */
gluOrtho2D(0, 640, 0, 480);
}
void main(int argc, char **argv)
{

glutInit(&argc, argv);
/* Set the initial display mode */
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
/* Set the initial window position and size */
glutInitWindowPosition(0, 0);
glutInitWindowSize(640, 480);
/* Create the window with title "DDA_Line" */
glutCreateWindow("DDA_Line");
/* Initialize drawing colors */
Init();
/* Call the displaying function */
glutDisplayFunc(LineDDA);
/* Keep displaying untill the program is closed */
glutMainLoop();
}