Cohen sutherland line clipping algorithm

Cohen sutherland line clipping Algorithm

//Write a program to implement Cohen Sutherland line clipping algorithm.
#include<graphics.h>
#include<conio.h>
#include<stdio.h>
const int t=1,b=2,r=2,l=8;
float xmin,ymin,xmax,ymax;
int calcode(float x,float y)
{
    int code=0;
    if(y>ymax)
    code |=t;
    else if(y<ymin)
    code|=b;
    else if(x>xmax)
    code|=r;
    else if(x<xmin)
    code|=l;
    return(code);
}
void lineclip(float x1,float y1,float x2,float y2)
{
    unsigned int code1,code2,codeout;
    int accept=0,done=0;
    code1=calcode(x1,y1);
    code2=calcode(x2,y2);
    do
    {
        if(!(code1|code2))
        {
            accept=1;
            done=1;
        }
        else if(code1 & code2)
            done=1;
        else
        {
            float x,y;
            codeout=code1?code1:code2;
            if(codeout& t)
            {
                x=x1+(x2-x1)*(ymax-y1)/(y2-y1);
                y=ymax;
            }
            else if(codeout& b)
            {
                x=x1+(x2-x1)*(ymin-y1)/(y2-y1);
                y=ymin;
            }
            else if(codeout& r)
            {
                y=y1+(y2-y1)*(xmax-x1)/(x2-x1);
                x=xmax;
            }
            else
            {
                y=y1+(y2-y1)*(xmin-x1)/(x2-x1);
                x=xmin;
            }
            if(codeout==code1)
            {
                x1=x;
                y1=y;
                code1=calcode(x1,y1);
            }
            else
            {
                x2=x;
                y2=y;
                code2=calcode(x2,y2);
            }
        }
    }
    while(done==0);
    if(accept)
    line(x1,y1,x2,y2);
    rectangle(xmin,ymin,xmax,ymax);
}
main()
{
    float x1,y1,x2,y2;
    int gd=DETECT,gm;
    clrscr();
    initgraph(&gd,&gm,"C:\\TurboC3\\BGI");
    printf("Enter the co-ordinates of line ::::\n\t x1");
    scanf("%f",&x1);
    printf("\n\t y1:");
    scanf("%f",&y1);
    printf("\n\t x2:");
    scanf("%f",&x2);
    printf("\n\t y2:");
    scanf("%f",&y2);
    printf("Enter the co-ordinates of window :::\n");
    printf("\n\txmin");
    scanf("%f",&xmin);
    printf("\n\tymin");
    scanf("%f",&ymin);
    printf("\n\txmax");
    scanf("%f",&xmax);
    printf("\n\tymax");
    scanf("%f",&ymax);
    clrscr();
    line(x1,y1,x2,y2);
    rectangle(xmin,ymin,xmax,ymax);
    getch();
    clrscr();
    lineclip(x1,y1,x2,y2);
    getch();
    closegraph();
    return 0;
}


File

© Copyright - 2018 - 2022 | All rights reserved at Funda of Web IT