Saturday, August 25, 2007

DDA LINE , BRESENHAM'S ALGORITHM

DDA LINE , BRESENHAM'S ALGORITHM

/*PROGRAM FOR DRAWING A LINE USING DDA ALGORITHM*/

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<graphics.h>
#include<math.h>
#include<process.h>

void main()
{
int x1,x2,y1,y2,dx,dy,i,k;
float xinc,yinc,x,y;
int round(float);
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

cleardevice();
cout<<"ENTER THE VALUE OF X1: "<<endl;
cin>>x1;
cout<<"ENTER THE VALUE OF X2: "<<endl;
cin>>x2;
cout<<"ENTER THE VALUE OF y1: "<<endl;
cin>>y1;
cout<<"ENTER THE VALUE OF y2: "<<endl;
cin>>y2;
cleardevice();
putpixel(x1,y1,1);
putpixel(x2,y2,1);
dx=x2-x1;
dy=y2-y1;

if(abs(dx) > abs(dy))
k=abs(dx);
else
k=abs(dy);
xinc=1.0*dx/k;
yinc=1.0*dy/k;
x=x2*1.0;
y=y2*1.0;
putpixel(round(x),round(y),1);

cleardevice();
cout<<"LINE GENERATED FROM THE GIVEN POINTS IS : ";
setbkcolor(6);
for(i=1;i<=k;i++)
{
x+=xinc;
y+=yinc;
putpixel(round(x),round(y),i);
}
getch();
}

int round(float p)
{
if (p-int(p)<0.5)
return floor(p);
else
return ceil(p);
}


/*PROGRAM FOR DRAWING A LINE USING BRESENHAM'S ALGORITHM*/

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<graphics.h>
#include<math.h>
#include<process.h>
#include<dos.h>

void main()
{
int x1,x2,y1,y2,dx,dy,i,k,p,xend,yend,cnt=0;
float xinc,yinc,x,y,m;
int round(float);
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

/* read result of initialization */
errorcode = graphresult();
/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

setbkcolor(5);
//cleardevice();
cout<<"ENTER THE VALUE OF X1: "<<endl;
cin>>x1;
cout<<"ENTER THE VALUE OF y1: "<<endl;
cin>>y1;

cout<<"ENTER THE VALUE OF X2: "<<endl;
cin>>x2;
cout<<"ENTER THE VALUE OF y2: "<<endl;
cin>>y2;
cleardevice();


dx=abs(x2-x1);
dy=abs(y2-y1);
p=2*dy-dx;

if (abs(dx) > abs(dy))
xend=abs(dx);
else
xend=abs(dy);

m=dy/(float)dx;
if(x2 > x1)
{
x=x1;
y=y1;

}
else
{
x=x2;
y=y2;

}


putpixel(x,y,1);

while(x < xend)
{
x=x+1;
if (p<0)
{
p=p+2*dy;
}
else
{
if(m>=0 && m<=1)
y=y+1;
else
{
if(dx==0)
x--;
y--;
}
p=p+2*(dy-dx);
}
putpixel(x,y,1);
delay(10);
cnt++;
}
getch();
closegraph();

}



No comments: