Line Clipping

Write a program to implement Line Clipping.


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

#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8

#define INSIDE(a) (!a)
#define REJECT(a,b) (a&b)
#define ACCEPT(a,b) (!(a|b))

int gd=DETECT,gm;
struct wc
{
	float x,y;
}pt1,pt2;

struct dc
{
	float x,y;
}winmin,winmax;

int encode(struct wc pt,struct dc winmin,struct dc winmax)
{
	int code=0x00;
	if(pt.x<winmin.x)
		code=code|LEFT;
	if(pt.x>winmax.x)
		code=code|RIGHT;
	if(pt.y<winmin.y)
		code=code|BOTTOM;
	if(pt.y>winmax.y)
		code=code|TOP;
	return(code);
}
void swapPts(struct wc *p1,struct wc *p2)
{
	struct wc temp;
	temp=*p1;
	*p1=*p2;
	*p2=temp;
}
void swapCode(int *c1,int *c2)
{
	int temp;
	temp=*c1;
	*c1=*c2;
	*c2=temp;
}
int main()
{
	int x,y,draw=0,code1,code2,c,done=0;
	float m;
	int poly[10]={150,200,350,200,350,400,150,400,150,200};
	initgraph(&gd,&gm,"c:\\tc\\bgi");
	printf("\nEnter the coordinates of the first point: ");
	scanf("%d%d",&x,&y);
	pt1.x=x;
	pt1.y=y;
	printf("\nEnter the coordinates of he second point: ");
	scanf("%d%d",&x,&y);
	pt2.x=x;
	pt2.y=y;

	setcolor(3);
	line(pt1.x,pt1.y,pt2.x,pt2.y);
	drawpoly(5,poly);
	winmin.x=150;
	winmax.x=350;
	winmin.y=200;
	winmax.y=400;
	printf("\n1.CLIP\n2.EXIT\nENTER UR CHOICE:\t");
	scanf("%d",&c);
	switch(c)
	{
		case 1:
			while(!done)
			{
				code1=encode(pt1,winmin,winmax);
				code2=encode(pt2,winmin,winmax);
				if(ACCEPT(code1,code2))
				{
					done=1;
					draw=1;
				}
				else if(REJECT(code1,code2))
					done=1;
				else
				{
					if(INSIDE(code1))
					{
						swapPts(&pt1,&pt2);
						swapCode(&code1,&code2);
					}
					if(pt2.x!=pt1.x)
						m=(pt2.y-pt1.y)/(pt2.x-pt1.x);
					if(code1 & LEFT)
					{
						pt1.y+=(winmin.x-pt1.x)*m;
						pt1.x=winmin.x;
					}
					else if(code1 & RIGHT)
					{
						pt1.y+=(winmax.x-pt1.x)*m;
						pt1.x=winmax.x;
					}
					else if(code1 & BOTTOM)
					{
					   if(pt2.x!=pt1.x)
						pt1.x+=(winmin.y-pt1.y)*m;
						pt1.y=winmin.y;
					}
					else if(code1 & TOP)
					{
					    if(pt2.x!=pt1.x)
						pt1.x+=(winmax.y-pt1.y)*m;
						pt1.x=winmax.y;
					}
				}
			}

			if(draw)
			{
				//clrscr();
				//initgraph(&gd,&gm,"c:\\tc\\bgi");
				setcolor(WHITE);
				drawpoly(5,poly);
				line(pt1.x,pt1.y,pt2.x,pt2.y);
			}
			break;
		case 2:
			break;
		default:
			printf("\nINVALID OPTION");
	}
	getch();
	return(0);
}


Output
1

Leave a Reply

Your email address will not be published. Required fields are marked *