line_clipping/lib.rs
1//! A rust crate to implement several line clipping algorithms. See the
2//! [documentation](https://docs.rs/line_clipping) for more information. The choice of algorithms is
3//! based on the following article which contains a good summary of the options:
4//!
5//! Matthes D, Drakopoulos V. [Line Clipping in 2D: Overview, Techniques and
6//! Algorithms](https://pmc.ncbi.nlm.nih.gov/articles/PMC9605407/). J Imaging. 2022 Oct
7//! 17;8(10):286. doi: 10.3390/jimaging8100286. PMID: 36286380; PMCID: PMC9605407.
8//!
9//! Supports:
10//!
11//! - [x] Cohen-Sutherland
12//!
13//! TODO
14//!
15//! - [ ] Cyrus-Beck
16//! - [ ] Liang-Barsky
17//! - [ ] Nicholl-Lee-Nicholl
18//! - [ ] More comprehensive testing
19//!
20//! # Installation
21//!
22//! ```shell
23//! cargo add line-clipping
24//! ```
25//!
26//! # Usage
27//!
28//! ```rust
29//! use line_clipping::{
30//! LineSegment, Point, Window,
31//! cohen_sutherland::clip_line,
32//! }
33//!
34//! let line = clip_line(
35//! LineSegment::new(Point::new(0.0, 0.0), Point::new(10.0, 10.0)),
36//! Window::new(1.0, 9.0, 1.0, 9.0),
37//! );
38//! ```
39//!
40//! # License
41//!
42//! Copyright (c) 2024 Josh McKinney
43//!
44//! This project is licensed under either of
45//!
46//! - MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
47//! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
48//! <http://www.apache.org/licenses/LICENSE-2.0>)
49//!
50//! at your option.
51//!
52//! # Contribution
53//!
54//! Contributions are welcome! Please open an issue or submit a pull request.
55//!
56//! Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in
57//! the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without
58//! any additional terms or conditions.
59pub mod cohen_sutherland;
60
61/// A point in 2D space.
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub struct Point {
64 pub x: f64,
65 pub y: f64,
66}
67
68impl Point {
69 /// Creates a new point.
70 pub fn new(x: f64, y: f64) -> Self {
71 Point { x, y }
72 }
73}
74
75/// A line segment in 2D space.
76#[derive(Debug, Clone, Copy, PartialEq)]
77pub struct LineSegment {
78 pub p1: Point,
79 pub p2: Point,
80}
81
82impl LineSegment {
83 /// Creates a new line segment.
84 pub fn new(p1: Point, p2: Point) -> Self {
85 LineSegment { p1, p2 }
86 }
87}
88
89/// A rectangular region to clip lines against.
90#[derive(Debug, Clone, Copy)]
91pub struct Window {
92 pub x_min: f64,
93 pub x_max: f64,
94 pub y_min: f64,
95 pub y_max: f64,
96}
97
98impl Window {
99 /// Creates a new window.
100 pub fn new(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> Self {
101 Window {
102 x_min,
103 x_max,
104 y_min,
105 y_max,
106 }
107 }
108}