/*
* THIS IS A C PROGRAM THAT IMPLEMENTS DIGITAL DIFFERENCE ANALYZER (DDA) LINE DRAWING ALGORITHM
*/
#include"compgrap.h"
void implementdda(int, int, int, int) ;
int sign(float) ;
int main(void)
{
int x1, y1, x2, y2 ;
initialize(); /* basic initialization */
printf("\n Enter the coordinates of the first point: ");
scanf("%d%d",&x1,&y1) ;
printf("\n Enter the coordinates of the second point: ");
scanf("%d%d",&x2,&y2) ;
clrscr();
cleardevice() ;
/* creating a grid */
creategrid(DARKGRAY, DARKGRAY) ;
/* setting shading style and highlight color of a pixel */
setfillstyle(1, DARKGRAY) ;
implementdda(x1, y1, x2, y2) ; /* drawing approximated straight line by DDA algorithm */
/* drawing an actual line segment from (x1,y1) to (x2,y2) */
setcolor(WHITE);
drawline(x1, y1, x2, y2) ;
getch();
closegraph(); /* closing the graph */
return 0;
}
/* Implementation of DDA algorithm */
void implementdda(int x1, int y1, int x2, int y2)
{
int i, length, s1, s2 ;
float dx, dy, x, y ;
/* since drawing straight lines should be very rapid, we skip the overhead of
* computing the pixels, when the straight line will be an exact horizontal or
* vertical one or with slope = +1/-1. We keep provisions for checking whether a straight line will be
* vertical/horizontal one or if its slope is +1 ot -1 . */
if(y1==y2) /* for a horizontal line */
{
x = min(x1, x2);
y = y1;
while(x<=max(x1,x2))
{
plot(x,y);
x+=1;
}
}
else if(x1==x2) /* for a vertical line */
{
y = min(y1, y2);
x = x1;
while(y<=max(y1,y2))
{
plot(x,y);
y+=1;
}
}
else if(abs(x2-x1)==abs(y2-y1)) /* for lines with slopes +1 or -1 */
{
x=x1;
y=y1;
do
{
plot(x,y);
x+=sign(x2-x1);
y+=sign(y2-y1);
}while(x!=x2 && y!=y2);
plot(x,y);
}
else /* for straight lines with other slopes */
{
length = max(abs(x2-x1), abs(y2-y1)) ;
dx = (float)(x2-x1)/length ;
dy = (float)(y2-y1)/length ;
s1 = sign(dx);
s2 = sign(dy) ;
x = x1 + 0.5*s1 ;
y = y1 + 0.5*s2 ;
i = 1 ;
while(i<=length)
{
plot(floor(x),floor(y));
x+=dx ;
y+=dy;
i++;
}
}
}
/* function returns +1, -1 or 0 according as the argument is
* positive, negative or zero */
int sign(float a)
{
return a>0 ? 1:(a<0 ? -1:0) ;
}
No comments:
Post a Comment
Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.