pub fn clip_line(line: LineSegment, window: Window) -> Option<LineSegment>
Expand description
Implements the Cohen-Sutherland line clipping algorithm.
Returns the clipped line if the original line intersects the clipping window, or None
if the
original line is completely outside the clipping window.
Reference: Cohen-Sutherland algorithm
The Cohen-Sutherland algorithm is a line clipping algorithm that divides the 2D plane into 9 regions and then determines the region in which the line lies. If the line lies completely outside the clipping window, it is rejected. If the line lies completely inside the clipping window, it is accepted. If the line lies partially inside the clipping window, it is clipped.
The regions are defined as follows:
1001 | 1000 | 1010 |
---|---|---|
0001 | 0000 | 0010 |
—– | —— | —– |
0101 | 0100 | 0110 |
The algorithm works as follows:
- Determine the region in which the line’s starting point lies.
- Determine the region in which the line’s ending point lies.
- If both points lie in region 0000, the line is completely inside the clipping window and should be accepted.
- If both points lie in the same region that is not 0000, the line is completely outside the clipping window and should be rejected.
- If the points lie in different regions, the line is partially inside the clipping window and should be clipped.
- Clip the line using the Cohen-Sutherland algorithm.
- Repeat the process for the clipped line.
The Cohen-Sutherland algorithm is commonly used in computer graphics to clip lines against a rectangular window.
§Examples
use cohen_sutherland::clip_line;
let line = clip_line(
Line { p1: Point { x: 0.0, y: 0.0 }, p2: Point { x: 10.0, y: 10.0 } },
Window { x_min: 1.0, x_max: 9.0, y_min: 1.0, y_max: 9.0 },
);
assert_eq!(line, Some(Line { p1: Point { x: 1.0, y: 1.0 }, p2: Point { x: 9.0, y: 9.0 } }));