Cohen-Sutherland裁减算法#defineLEFT1#defineRIGHT2#defineBOTTOM4#defineTOP8intencode(floatx,floaty){intc=0;if(xXL)c|=LEFT;if(xXR)c|=RIGHT;if(xYB)c|=BOTTOM;if(xYT)c|=TOP;retrunc;}voidCS_LineClip(x1,y1,x2,y2,XL,XR,YB,YT)floatx1,y1,x2,y2,XL,XR,YB,YT;//(x1,y1)(x2,y2)为线段的端点坐标,其他四个参数定义窗口的边界{intcode1,code2,code;code1=encode(x1,y1);code2=encode(x2,y2);while(code1!=0||code2!=0)//都为0,在窗口内,则取,直接绘制此直线.{if(code1&code2!=0)return;//与运算不为0,在窗口外,则弃,不需处理code=code1;if(code1==0)code=code2;//选择窗口外的端点if(LEFT&code!=0)//该位编码不为0,与对应窗口边界求交{x=XL;y=y1+(y2-y1)*(XL-x1)/(x2-x1);}elseif(RIGHT&code!=0){x=XR;y=y1+(y2-y1)*(XR-x1)/(x2-x1);}elseif(BOTTOM&code!=0){y=YB;x=x1+(x2-x1)*(YB-y1)/(y2-y1);}elseif(TOP&code!=0){y=YT;x=x1+(x2-x1)*(YT-y1)/(y2-y1);}if(code==code1)//用交点替换窗口外的端点,继续处理余下的线段.{x1=x;y1=y;code1=encode(x,y);}else{x2=x;y2=y;code2=encode(x,y);}}displayline(x1,y1,x2,y2);}动画演示:Cohen-Sutherland直线段裁剪算法动画演示:Cohen-Sutherland算法和中点分割算法的比较Liang-Barskey算法voidLB_LineClip(x1,y1,x2,y2,XL,XR,YB,YT)floatx1,y1,x2,y2,XL,XR,YB,YT;{floatdx,dy,u1,u2;ul=0;u2=1;dx=x2-x1;dy=y2-y1;if(ClipT(-dx,x1-Xl,&u1,&u2)if(ClipT(dx,XR-x1,&u1,&u2)if(ClipT(-dy,y1-YB,&u1,&u2)if(ClipT(dy,YT-y1,&u1,&u2){displayline(x1+u1*dx,y1+u1*dy,x1+u2*dx,y1+u2*dy)return;}}boolClipT(p,q,u1,u2)floatp,q,*u1,*u2;{floatr;if(p0){r=q/p;if(r*u2)returnFALSE;elseif(r*u1){*u1=r;returnTRUE;}}elseif(p0){r=q/p;if(r*u1)returnFALSE;elseif(r*u2){*u2=r;returnTRUE;}}elseif(q0)returnFALSE;returnTRUE;}