Wednesday, March 19, 2014

DDA Line Drawing Algorithm in C




In computer graphics, digital differential analyzer (DDA) is used for drawing a line between a start and end point Consider an interval [(xstart, ystart), (xend, yend)] by computing for each xi the equations xi = xi-1+1/m, yi = yi-1 + m, where dx = xend − xstart and dy = yend − ystart and m = dy/dx.
A line is sampled at unit intervals in one coordinate and corresponding integer values nearest the line path are determined for other coordinates.


Case 1: |m|<=1
Considering a line with positive slope, if the slope is less than or equal to 1, we sample at unit x intervals (dx=1) and compute successive y values as
yk+1=yk+m, where k=1,2…n

Case 2: |m|>1

 For lines with slope greater than 1, we reverse the role of x and y i.e. we sample at dy=1 and calculate consecutive x values as
xk+1=xk+1/m, where k=1,2…n

Algorithm

1.       int x1, y1, x2, y2, dx, dy, step, xinc, yinc
2.       dx = x2 – x1
3.       dy = y2 – y1
4.       if (dx <= dy)
5.       step = dy
6.                 else
7.       step = dx
8.       xinc = dx / step
9.       yinc = dy / step
10.     for ( i=0; i < step; i++){
11.     putpixel(x, y, 1)
12.     x = x + xinc
13.     y = y + yinc }

Disadvantage

Round-off error in successive additions of the floating-point increment can cause the calculated pixel positions to drift away from the true line path for long line segments. Rounding operations and floating-point arithmetic in procedure are still time-consuming.



#include<stdio.h>
#include <graphics.h>
#include <conio.h>
#include<math.h>
#include<dos.h>
void main()
{
   int gdriver = DETECT, gmode;
   int x1,y1,x2,y2;
   float dx,dy,y,m,x;
   int t1,t2;
   //clrscr();
   initgraph(&gdriver,&gmode,"c:/tc/bgi");
   printf("\nEnter first point(x1,y1)=");
   scanf("%d%d",&x1,&y1);
   printf("\nEnter second point(x2,y2)=");
   scanf("%d%d",&x2,&y2);
   if(x1>x2)
   {
    t1=x1;x1=x2;x2=t1;
    t2=y1;y1=y2;y2=t2;
    printf("\n(x1,y1)=(%d,%d) & (x2,y2)=(%d,%d)",x1,y1,x2,y2);
   }
   dx=x2-x1;
   dy=y2-y1;
   if(fabs(dx)>fabs(dy))
   {
    m=dy/dx;
    y=y1;
     getpixel(x,y);
    for(x=x1;x<x2;x++)
    {     
        putpixel(x,y,2);
        delay(100);
        y=y+m;
    }
   }
   else
   {
    m=dx/dy;
    x=x1;
    if(y1<y2)
    {
        for(y=y1;y<y2;y++)
        {
            putpixel(x,y,2);
            delay(100);
            x=x+m;
        }
    }
    else
    {
        for(y=y1;y>y2;y--)
        {
            putpixel(x,y,2);
            x=x-m;
        }
    }
   }


  getch();
}



No comments:

Post a Comment