### Write a program to clip a line using Liang - Barsky line clipping algorithm.

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

#define ROUND(a)    ( (int) (a+0.5))

#define TRUE  1
#define FALSE 0

int xMin, xMax, yMin, yMax;

int  test(float, float, float *, float *);
void clip(int, int, int, int);

void  main()
{
int gdriver=DETECT, gmode;
int x1,y1,x2,y2;

initgraph(&gdriver,&gmode,"c:\\tc\\bgi");
cleardevice();

printf("Enter the End-Points of the LINE...\n\n");
printf("Enter the (x1,y1) : ");
scanf("%d %d",&x1,&y1);
printf("Enter the (x2,y2) : ");
scanf("%d %d",&x2,&y2);

printf("\n\n\nEnter the Corner-Points of the Clip-Rectangle...\n\n");
printf("Enter the (xMin,yMin) : ");
scanf("%d %d",&xMin,&yMin);
printf("Enter the (xMax,yMax) : ");
scanf("%d %d",&xMax,&yMax);

cleardevice();
line(x1,y1,x2,y2);
rectangle(xMin,yMin,xMax,yMax);

getch();
setcolor(0);    line(x1,y1,x2,y2);
clip(x1,y1,x2,y2);

getch();
closegraph();
}

void clip(int x1, int y1, int x2, int y2)
{
float u1=0.0, u2=1.0;
int   dx=x2-x1, dy;

if( test(-dx, x1-xMin, &u1, &u2) )
if( test(dx, xMax-x1, &u1, &u2) )
{
dy = y2 - y1;
if( test(-dy, y1-yMin, &u1, &u2) )
if( test( dy, yMax-y1, &u1, &u2) )
{
if(u2 < 1.0)
{
x2 = x1 + u2 * dx;
y2 = y1 + u2 * dy;
}
if(u1 > 0.0)
{
x1 += u1 * dx;
y1 += u1 * dy;
}
setcolor(4);
line(ROUND(x1), ROUND(y1), ROUND(x2), ROUND(y2));
}
}
}

int test(float p, float q, float *u1, float *u2)
{
float r = q / p;

if(p < 0.0)
{
if(r > *u2)
return FALSE;
else if(r > *u1)
*u1 = r;
}

else if(p > 0.0)
{
if(r < *u1)
return FALSE;
else if(r < *u2)
*u2 = r;
}

else if(q < 0.0)
return FALSE;

return TRUE;
}