Wednesday, February 27, 2013

Cohen Sutherland Line Clipping Algorithm

#include<stdio.h>
#include<graphics.h>
#include<conio.h>

int outcode;
enum { TOP=0x1, BOTTOM=0x2, RIGHT=0x4, LEFT=0x8 };

void lineclip(x0,y0,x1,y1,xmin,ymin,xmax,ymax )
    float x0,y0,x1,y1,xmin,ymin,xmax,ymax;
    {

    int gd=0,gm;
    int code0,code1,codeout;
    int accept = 0, done=0;

    code0 = calcode(x0,y0,xmin,ymin,xmax,ymax);
    code1 = calcode(x1,y1,xmin,ymin,xmax,ymax);

    do
    {
    if(!(code0 | code1))
    { accept =1 ; done =1; }
    else
        if(code0 & code1) done = 1;
    else
    {
        float x,y;
    codeout = code0 ? code0 : code1;
    if(codeout & TOP)
    {
        x = x0 + (x1-x0)*(ymax-y0)/(y1-y0);
        y = ymax;
    }
    else
    if( codeout & BOTTOM)
    {
        x = x0 + (x1-x0)*(ymin-y0)/(y1-y0);
        y = ymin;
    }
    else
    if ( codeout & RIGHT)
    {
        y = y0+(y1-y0)*(xmax-x0)/(x1-x0);
        x = xmax;
    }
    else
    {
        y = y0 + (y1-y0)*(xmin-x0)/(x1-x0);
        x = xmin;
    }
    if( codeout == code0)
    {
        x0 = x; y0 = y;
        code0=calcode(x0,y0,xmin,ymin,xmax,ymax);
    }
    else
    {
        x1 = x; y1 = y;
        code1 = calcode(x1,y1,xmin,ymin,xmax,ymax);
    }
    }
    } while( done == 0);

    if(accept) line(x0,y0,x1,y1);

        rectangle(xmin,ymin,xmax,ymax);

    getch();

}


int calcode (x,y,xmin,ymin,xmax,ymax)
float x,y,xmin,ymin,xmax,ymax;
{
int code =0;

if(y> ymax)
code |=TOP;
else if( y<ymin)
code |= BOTTOM;
else if(x > xmax)
code |= RIGHT;
else if ( x< xmin)
code |= LEFT;

return(code);
}


main()
{

float x2,y2,x1,y1,xmin,ymin,xmax,ymax;
int gd=0,gm;

clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
 setbkcolor(0);
printf("\n\n\tEnter the co-ordinates of Line :");

printf("\n\n\tX1 Y1 : ");
scanf("%f %f",&x1,&y1);

printf("\n\n\tX2 Y2 : ");
scanf("%f %f",&x2,&y2);
//line(x1,y1,x2,y2);
getch();

printf("\n\tEnter the co_ordinates of window :\n ");
printf("\n\txwmin , ywmin : ");
scanf("%f %f",&xmin,&ymin);
printf("\n\txwmax , ywmax : ");
scanf("%f %f",&xmax,&ymax);
clrscr();
line(x1,y1,x2,y2);
rectangle(xmin,ymin,xmax,ymax);
getch();
clrscr();

lineclip(x1,y1,x2,y2,xmin,ymin,xmax,ymax );
getch();
closegraph();

}

No comments:

Post a Comment