Write a Program for Cohen Sutherland line Clipping in C

/*
    Cohen Sutherland line Clipping
*/
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>

void main()
{

    int gd=DETECT,gm;
    int x1,y1,x2,y2,i,j,flag;
    int code1[4]={0},code2[4]={0};
    float m;
    clrscr();

    printf("\n\n Viewing area Coordinates: ");
    printf("(100,200)-(400,200) \n (100,200)-(100,400)  \n (100,400)-(400,400) \n (400,200)-(400,400)");
    printf("\n\n Enter the coordinates of line to clip: ");
    scanf("%d%d%d%d",&x1,&y1,&x2,&y2);

    initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
    outtextxy(150,175,"Before Clipping");
    line(100,200,400,200);
    line(100,200,100,400);
    line(100,400,400,400);
    line(400,200,400,400);
    line(x1,y1,x2,y2);
    delay(1000);

    cleardevice();

    outtextxy(150,175,"After Clipping");
    line(100,200,400,200);
    line(100,200,100,400);
    line(100,400,400,400);
    line(400,200,400,400);

    m=(x2-x1)/(y2-y1); //Slope


//TBRL A
    if(x1>100 && x1<400 && y1<200) // Top
    {
code1[0]=1;
code1[1]=0;
code1[2]=0;
code1[3]=0;
    }
    else if(x1>100 && x1<400 && y1>400) // Bottom
    {
code1[0]=0;
code1[1]=1;
code1[2]=0;
code1[3]=0;
    }
    else if(x1<100 && y1<400 && y1>200) // Left
    {
code1[0]=0;
code1[1]=0;
code1[2]=0;
code1[3]=1;
    }
    else if(x1>400 && y1<400 && y1>200) // Right
    {
code1[0]=0;
code1[1]=0;
code1[2]=1;
code1[3]=0;
    }

//TBRL B
    if(x2>100 && x2<400 && y2<200) // Top
    {
code2[0]=1;
code2[1]=0;
code2[2]=0;
code2[3]=0;
    }
    else if(x2>100 && x2<400 && y2>400) // Bottom
    {
code2[0]=0;
code2[1]=1;
code2[2]=0;
code2[3]=0;
    }
    else if(x2<100 && y2<400 && y2>200) // Left
    {
code2[0]=0;
code2[1]=0;
code2[2]=0;
code2[3]=1;
    }
    else if(x2>400 && y2<400 && y2>200) // Right
    {
code2[0]=0;
code2[1]=0;
code2[2]=1;
code2[3]=0;
    }

    flag=0;
    for(i=0;i<4;i++)   //0000
    {
if(code1[i]==0 && code2[i]==0)
{
}
else
{

  flag=1;
  break;
}
    }

    printf("\n\n Outcodes are for A ");
    for(i=0;i<4;i++)
       printf(" %d ",code1[i] );

    printf("\n\n Outcodes are for B ");
    for(i=0;i<4;i++)
       printf(" %d ",code2[i] );

    line(x1,y1,x2,y2);
    getch();
    closegraph();
}

Previous
Next Post »