Sutherland Hodgeman Line Clipping Apr 10, 2006 • Rohit Graphics #include <iostream.h> #include <conio.h> #include <graphics.h> const int MAX=100; struct point { float x; float y; int valid; }; struct box { int xx, yx, yn, xn; }b; int inside(point p, int j) { if (j==0&&p.x<b.xn) return 0; if (j==1&&p.x>b.xx) return 0; if (j==2&&p.y<b.yn) return 0; if (j==3&&p.y>b.yx) return 0; return 1; } point intersect(point p1, point p2, int j) { float m; m=(p2.y-p1.y)/(p2.x-p1.x); point p; p.valid=1; switch(j) { case 0: { p.x=b.xn; if (p1.y==p2.y) p.y=p1.y; else p.y=p2.y+(b.xn-p2.x)*m; break; } case 1: { p.x=b.xx; if (p1.y==p2.y) p.y=p1.y; else p.y=p2.y+(b.xx-p2.x)*m; break; } case 2: { p.y=b.yn; if (p1.x==p2.x) p.x=p1.x; else p.x=p2.x+(b.yn-p2.y)/m; break; } case 3: { p.y=b.yx; if (p1.x==p2.x) p.x=p1.x; else p.x=p2.x+(b.yx-p2.y)/m; break; } } return p; } void main() { point pt[MAX],s[MAX]; int gdriver = DETECT, gmode = VGAHI; initgraph(&gdriver, &gmode, ""); b.xx=getmaxx()/4; b.xn=-getmaxx()/4; b.yn=-getmaxy()/4; b.yx=getmaxy()/4; rectangle (getmaxx()/2+b.xn,getmaxy()/2-b.yn,b.xx+getmaxx()/2,getmaxy()/2-b.yx); char cho='y'; int count=0; while (cho=='y') { cout<<"Enter x for pt "<<count+1<<" "; cin>>pt[count].x; cout<<"Enter y for pt "<<count+1<<" "; cin>>pt[count].y; pt[count].valid=1; cout<<"Enter more "; cho=getche(); count++; } setcolor(BLUE); for (int i=count;i<MAX;i++) pt[i].valid=0; int ncount=count; count=0; for (int j=0;j<4;j++) { for (i=0;i<ncount;i++) { if (inside(pt[i],j)&&inside(pt[(i+1)%ncount],j)) { s[count++]=pt[(i+1)%ncount]; } else if (inside(pt[i],j)&&!inside(pt[(i+1)%ncount],j)) { s[count++]=intersect(pt[i],pt[(i+1)%ncount],j); } else if (!inside(pt[i],j)&&inside(pt[(i+1)%ncount],j)) { s[count++]=intersect(pt[i],pt[(i+1)%ncount],j); s[count++]=pt[(i+1)%ncount]; } } for (int k=0;k<count;k++) pt[k]=s[k]; for (k=count;k<MAX;k++) pt[k].valid=0; ncount=count; count=0; } for (i=0;i<ncount;i++) line(getmaxx()/2+pt[i].x,getmaxy()/2-pt[i].y,getmaxx()/2+pt[(i+1)%ncount].x,getmaxy()/2-pt[(i+1)%ncount].y); } Add reply Click here to reply to the blog post instead Send