1 Attachment(s)

Cohen-Sutherland Line Clipping Problem

Hello,

I'm trying to learn how to do the Cohen-Sutherland Line Clipping algorithm by hand. I have an example 2D space below:

Attachment 31053

Now if I understand correctly, the goal is to clip everything outside of the rectangle correct? The problem I'm having is the math approach. For example the segment AD. I know the code for A and D is 0000 and 1001 respectively. Now the logical and of the two endpoints needs to not be 0 to be rejected which means if the logical and is 1 then then segment is accepted? So the logical and of AD is 0 so trivial accept correct? I have a feeling it should be rejected because the point D is outside of the viewport (rectangle).

Re: Cohen-Sutherland Line Clipping Problem

Hi,

At the very least, you need psuedo code for the algorithm. Rather than provide such, I just excerpted a Java implementation from one of my graphics programs. I hope you can read Java or at least some "C like" language. There are some subtle points in the algorithm. For example, in computing a clipped point, a division by 0 is never performed. First is a diagram of a window and a line to be clipped. Following is the Java code.

http://i60.tinypic.com/mlm9w6.png

Code:

` /* Following is an implementation of the Cohen Sutherland clip algorithm against`

a window in the "world" with lower left coordinates (wx0,wy0) and upper right

corner (wx1,xy1). If the line is completely outside the window, just return;

Otherwise, draw the clipped line.

*/

public void drawLine(Graphics2D g2,double x1,double y1,double x2,double y2) {

int c1,c2,c;

double x,y;

// code for point P1=(x1,y1)

c1=x1<wx0 ? 1 : x1>wx1 ? 2 : 0;

if (y1<wy0) c1 |=4;

else if (y1>wy1) c1 |=8;

// code for P2=(x2,y2)

c2=x2<wx0 ? 1 : x2>wx1 ? 2 : 0;

if (y2<wy0) c2 |=4;

else if (y2>wy1) c2 |=8;

while ((c1|c2)!=0) {

if ((c1&c2) != 0) return; // both points completely outside window

c=(c1!=0) ? c1 : c2;

if ((c&1)!=0 || (c&2)!=0) { // point to left or right of window

x=((c&1)!=0) ? wx0 : wx1;

y=y1+(y2-y1)/(x2-x1)*(x-x1);

}

else { // point above or below wintdow

y=((c&4)!=0) ? wy0 : wy1;

x=x1+(x2-x1)/(y2-y1)*(y-y1);

}

if (c==c1) {

x1=x; y1=y;

c1=(x1<wx0) ? 1 : (x1>wx1) ? 2 : 0;

if (y1<wy0) c1 |=4;

else if (y1>wy1) c1 |=8;

}

else {

x2=x; y2=y;

c2=(x2<wx0) ? 1 : (x2>wx1) ? 2 : 0;

if (y2<wy0) c2 |=4;

else if (y2>wy1) c2 |=8;

}

}

// if we get to here, a line needs to be drawn

// finally draw the line in Java: code omitted

}