Saturday, August 6, 2011

Cohen Sutherland Line Clipping Algorithm

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<graphics.h>
int pixels[2][4];
float xn,yn,xn1,yn1,m;
int xmin,ymin,xmax,ymax,x1,y1,x2,y2;
//int ch,n;
void encode(int x1,int y1,int x2,int y2)
{
    int i,j,f=1;
    for(i=0;i<2;i++)
        for(j=0;j<4;j++)
            pixels[i][j]=0;
    if(y1>ymax)
        pixels[0][0]=1;
    if(y1<ymin)
        pixels[0][1]=1;
    if(x1>xmax)
        pixels[0][2]=1;
    if(x1<xmin)
        pixels[0][3]=1;
    if(y2>ymax)
        pixels[1][0]=1;
    if(y2<ymin)
        pixels[1][1]=1;
    if(x2>xmax)
        pixels[1][2]=1;
    if(x2<xmin)
        pixels[1][3]=1;
    for(j=0;j<4;j++)
    {
        if((pixels[0][j]==0)&& (pixels[1][j]==0))
            continue;
        if((pixels[0][j]==1)&& (pixels[1][j]==1))
        {
            f=2;
            break;
        }
        f=3;
    }
    switch(f)
    {
    case 1:
        cleardevice();
        rectangle(xmin,ymin,xmax,ymax);
        line(x1,y1,x2,y2);
        break;
    case 2:
        printf("\nThe line is completely outside");
        break;
    case 3:
        m=(y2-y1)/(x2-x1);
        xn=x1;xn1=x2;
        yn=y1;yn1=y2;
        if(pixels[0][0]==1)
        {
            xn=x1+(ymax-y1)/m;
            yn=ymax;
        }
        if(pixels[0][1]==1)
        {
            xn=x1+(ymin-y1)/m;
            yn=ymin;
        }
        if(pixels[0][2]==1)
        {
            yn=y1+(xmax-x1)*m;
            xn=xmax;
        }
        if(pixels[0][3]==1)
        {
            yn=y1+(xmin-x1)*m;
            xn=xmin;
        }
        if(pixels[1][0]==1)
        {
            xn1=x2+(ymax-y2)/m;
            yn1=ymax;
        }
        if(pixels[1][1]==1)
        {
            xn1=x2+(ymin-y2)/m;
            yn1=ymin;
        }
        if(pixels[1][2]==1)
        {
            yn1=y2+(xmax-x2)*m;
            xn1=xmax;
        }
        if(pixels[1][3]==1)
        {
            yn1=y2+(xmin-x2)*m;
            xn1=xmin;
        }
        cleardevice();
        rectangle(xmin,ymin,xmax,ymax);
        line(xn,yn,xn1,yn1);
        break;
        }
}
void main()
{
int gd=DETECT,gm,i,j;
initgraph(&gd,&gm,"t:\\bgi");
printf("\nEnter the co-ordinates for the window:");
scanf("%d%d%d%d",&xmin,&ymin,&xmax,&ymax);
rectangle(xmin,ymin,xmax,ymax);
printf("\nenter the line co-ordinates:");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
line(x1,y1,x2,y2);
sleep(5);
encode(x1,y1,x2,y2);
printf("\nLine After Clipping");
getch();
//closegraph();
}

4 comments:

  1. Replies
    1. thank u prashant.. if you need any clarification please mention that as comment..
      again thank u for your support..

      Delete
  2. Replies
    1. just run it on your machine.. if any problem arises get back to me

      Delete

Please put your valuable comments