2D
Clipping with the CohenSutherlandAlgorithm 
Download
Applet with Source (25kb)
View
Applet online
The CohenSutherlandAlgorithm is a wellknown algorithm for clipping
lines against a rectangle in 2D space. Although it is not the fastest one, the
idea behind it is quite good and it works very well if a lot of lines lie outside
completely outside the window/rectangle.
The main idea is following: Divide the complete 2D space in 9 areas where in the window to be clipped against is in the middle and the other 8 one are around it. To each of the nine regions a 4bit code is assigned to identify it. Here a small picture to make it clear.
For every endpoint of a line, we assign a region code to it depending on its position (x,y) (as convention we declare the leftmost bit as bit 3 and the rightmost bit 0) :
Bit
3 is 1 <=> 
Point lies left from the window : x < x_{min} 
Bit
2 is 1 <=> 
Point lies right from the window : x > x_{max} 
Bit
1 is 1 <=> 
Point lies below from the window : y > y_{max} 
Bit
0 is 1 <=> 
Point lies above from the window : y < y_{min} 
This idea allows us to handle two special cases easily. Therefore let's say we have a line from point p1 to point p2:
Case 1:
The line can be trivially rejected  that means it lies completely
outside the window: code(p1) && code(p2) != 0.
Case 2:
The line can be trivially accepted  that means it lies completely
inside the window: code(p1)  code(p2) == 0.
Example:

In all other cases, if the line cannot be trivially rejected or accepted, it has to be intersected. Therefore the intersection with the four window edges is calculated step by step, the line endpoints are updated with these new ones and the trivial cases are tested again after each intersection. The intersection itself is quite easy cause the four window edges are the two horizontal lines y_{max} and y_{min} and the two vertical ones x_{max} and x_{min}. So can calculate the intersection point with some thinking and linear interpolation (see my source if you are more interested in).
So here some pseudcode:
1. Compute the region
codes for both endpoints of the line. 
Example:

Ok, so have fun with it :)
This site is part of Sunshine's Homepage