You are on page 1of 4

XTHANGBM

iu hng

Lp Trnh > C/C++ >

Trang chu ha: Cohen Sutherland Clipping DsWeb o Danh #include <iostream.h> sch np #include <conio.h> bi Web #include <stdlib.h> Lp Trnh #include <dos.h> o Assembly #include <graphics.h> o C/C++ #define TRUE 1 o Pascal #define FALSE 0 #define LEFT 1 Lt truy cp #define RIGHT 2 #define TOP 4 #define BOTTOM 8 typedef struct { int x, y; }POINT; typedef struct { int Left, Top, Right, Bottom; }RECT; typedef int CODE; #define Accept(a,b) (!(a|b)) #define Reject(a,b) (a&b) void EnCode(POINT P, CODE &c, RECT rWin) // Tra ve ma vung cua P la c { c = 0; if(P.x < rWin.Left) c |= LEFT; if(P.x > rWin.Right) c |= RIGHT; if(P.y < rWin.Top) c |= TOP; if(P.y > rWin.Bottom) c |= BOTTOM; } void SwapPoint(POINT& P1, POINT &P2, CODE &c1, CODE &c2) // Hoan vi hai diem P1 va P2 sao cho p1 luon nam ngoai cua so { if(!c1) { POINT P; P = P1; P1 = P2;

P2 = P; CODE c; c = c1; c1 = c2; c2 = c; } } int CohenSutherlandClipping(POINT P1, POINT P2, POINT &Q1, POINT &Q2, RECT rWin) //Tra ve TRUE neu co cat cua so. Nguoc lai tra ve FALSE { int fStop = FALSE, fResult = FALSE; CODE c1, c2; while(!fStop) { EnCode(P1,c1,rWin); EnCode(P2,c2,rWin); if(Accept(c1,c2)) //Neu duong thang nam hoan toan trong cua so { fStop = TRUE; fResult = TRUE; } else if(Reject(c1,c2)) fStop = TRUE; //Neu duong thang nam hoan toan ben ngoai cua so else { fResult = TRUE; SwapPoint(P1,P2,c1,c2); float m; if(P2.x!=P1.x) m = float(P2.y-P1.y)/(P2.x-P1.x); if(c1 & LEFT) { P1.y += (rWin.Left-P1.x)*m; P1.x = rWin.Left; } else if(c1 & RIGHT) { P1.y += (rWin.Right-P1.x)*m; P1.x = rWin.Right; } else if(c1 & TOP) { if(P2.x!=P1.x) P1.x += (rWin.Top - P1.y)/m; P1.y = rWin.Top; }

else { if(P2.x!=P1.x) P1.x += (rWin.Bottom - P1.y)/m; P1.y = rWin.Bottom; } } } Q1 = P1; Q2 = P2; return (fResult); } void kddohoa() { int gd=DETECT, gm, error; initgraph(&gd,&gm,"C:\\TC\\BGI"); error=graphresult(); if (error!=grOk) { cout<<"Loi do hoa: "<<grapherrormsg(error); getch(); exit(1); } } void ktdohoa() { getch(); closegraph(); } void nhap(POINT &P1, POINT &P2, RECT &rWin) { cout<<"NHAP CUA SO\n"; cout<<"Nhap Left: "; cin>>rWin.Left; cout<<"Nhap Right: "; cin>>rWin.Right; cout<<"Nhap Top: "; cin>>rWin.Top; cout<<"Nhap Bottom: "; cin>>rWin.Bottom; cout<<"NHAP DUONG THANG\n"; cout<<"Toa do diem 1: "; cin>>P1.x>>P1.y; cout<<"Toa do diem 2: "; cin>>P2.x>>P2.y; clrscr();

} void ve(POINT P1, POINT P2, RECT rWin) { rectangle(rWin.Left,rWin.Top,rWin.Right,rWin.Bottom); line(P1.x,P1.y,P2.x,P2.y); } void main() { POINT P1,P2,Q1,Q2; RECT rWin; kddohoa(); nhap(P1,P2,rWin); ve(P1,P2,rWin); setcolor(2); if (CohenSutherlandClipping(P1,P2,Q1,Q2,rWin)) line(Q1.x,Q1.y,Q2.x,Q2.y); ktdohoa(); } Bo co lm dng|Xa quyn truy cp|c cung cp bi Google Sites

You might also like