Cohen–Sutherland algorithm
In computer graphics, the Cohen–Sutherland algorithm is an algorithm used for line clipping. The algorithm divides a two-dimensional space into 9 regions and then efficiently determines the lines and portions of lines that are visible in the central region of interest.
The algorithm was developed in 1967 during flight simulator work by Danny Cohen and Ivan Sutherland.
The algorithm
The algorithm includes, excludes or partially includes the line based on whether:- Both endpoints are in the viewport region : trivial accept.
- Both endpoints share at least one non-visible region, which implies that the line does not cross the visible region. : trivial reject.
- Both endpoints are in different regions: in case of this nontrivial situation the algorithm finds one of the two points that is outside the viewport region. The intersection of the outpoint and extended viewport border is then calculated, and this new point replaces the outpoint. The algorithm repeats until a trivial accept or reject occurs.
Note that the outcodes for endpoints must be recalculated on each iteration after the clipping occurs.
The Cohen–Sutherland algorithm can be used only on a rectangular clip window.
Example C/C++ implementation
typedef int OutCode;
const int INSIDE = 0b0000;
const int LEFT = 0b0001;
const int RIGHT = 0b0010;
const int BOTTOM = 0b0100;
const int TOP = 0b1000;
// Compute the bit code for a point using the clip rectangle
// bounded diagonally by, and
// ASSUME THAT xmax, xmin, ymax and ymin are global constants.
OutCode ComputeOutCode
// Cohen–Sutherland clipping algorithm clips a line from
// P0 = to P1 = against a rectangle with
// diagonal from to.
bool CohenSutherlandLineClip