knipsa 0.1.0

A test-first, idiomatic Rust polygon clipping engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! Checked, allocation-transparent geometry primitives.

use crate::{Error, PathKind};

/// An integer point used by the exact-coordinate API.
///
/// Integer operations preserve these coordinates exactly. Paths are ordinary
/// Rust vectors, so they can be built with `vec![]` and passed by slice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct Point64 {
    /// Horizontal coordinate.
    pub x: i64,
    /// Vertical coordinate.
    pub y: i64,
}

impl Point64 {
    /// Creates an integer point.
    #[must_use]
    pub const fn new(x: i64, y: i64) -> Self {
        Self { x, y }
    }
}

/// A double-precision point used by the floating-point API.
///
/// [`crate::boolean_opd`] accepts finite `f64` coordinates. The arrangement
/// kernel keeps the input values exact while it computes intersections, then
/// converts the result back to `f64`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct PointD {
    /// Horizontal coordinate.
    pub x: f64,
    /// Vertical coordinate.
    pub y: f64,
}

impl PointD {
    /// Creates a floating-point point.
    #[must_use]
    pub const fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}

/// A sequence of points describing one path.
///
/// The path does not need to repeat its first point at the end. Whether the
/// final point connects to the first is selected with [`PathKind`]. Boolean
/// and triangulation inputs are closed paths; open paths are used by line
/// offsets.
pub type Path64 = Vec<Point64>;

/// A collection of integer paths, usually polygon rings.
pub type Paths64 = Vec<Path64>;

/// A floating-point sequence of points.
pub type PathD = Vec<PointD>;

/// A collection of floating-point paths, usually polygon rings.
pub type PathsD = Vec<PathD>;

/// The orientation of three points in Cartesian coordinates.
///
/// For points `a`, `b`, and `c`, the result describes the turn from `a -> b`
/// to `b -> c`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Orientation {
    /// The points turn clockwise.
    Clockwise,
    /// The points are collinear.
    Collinear,
    /// The points turn counter-clockwise.
    CounterClockwise,
}

/// The result of testing a point against a closed path.
///
/// [`point_in_polygon`] uses the even-odd rule for this classification.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointLocation {
    /// The point is outside the filled path.
    Outside,
    /// The point is inside the filled path.
    Inside,
    /// The point lies on the path boundary.
    Boundary,
}

/// Validates an integer path's shape contract and coordinate type.
///
/// Empty paths are valid and represent no geometry. A closed path requires at
/// least three points; an open path requires at least two.
///
/// # Errors
///
/// Returns [`Error::InvalidPath`] when a non-empty path is shorter than the
/// minimum for its kind.
pub fn validate_path64(path: &[Point64], kind: PathKind) -> Result<(), Error> {
    let minimum_vertices = match kind {
        PathKind::Closed => 3,
        PathKind::Open => 2,
    };
    if path.is_empty() || path.len() >= minimum_vertices {
        Ok(())
    } else {
        Err(Error::InvalidPath { kind, minimum_vertices, actual_vertices: path.len() })
    }
}

/// Validates every integer path in a collection.
///
/// # Errors
///
/// Returns the first path-shape error found.
pub fn validate_paths64(paths: &[Path64], kind: PathKind) -> Result<(), Error> {
    for path in paths {
        validate_path64(path, kind)?;
    }
    Ok(())
}

/// Validates a floating-point path's shape and finiteness.
///
/// Empty paths are valid. Closed paths require three points and open paths
/// require two. Consecutive duplicate points are accepted here and can be
/// removed with [`normalize_pathd`].
///
/// # Errors
///
/// Returns [`Error::InvalidPath`] for a too-short path or
/// [`Error::NonFiniteCoordinate`] for NaN/infinite coordinates.
pub fn validate_pathd(path: &[PointD], kind: PathKind) -> Result<(), Error> {
    let minimum_vertices = match kind {
        PathKind::Closed => 3,
        PathKind::Open => 2,
    };
    if !path.is_empty() && path.len() < minimum_vertices {
        return Err(Error::InvalidPath { kind, minimum_vertices, actual_vertices: path.len() });
    }
    for (point_index, point) in path.iter().enumerate() {
        if !point.x.is_finite() || !point.y.is_finite() {
            return Err(Error::NonFiniteCoordinate { point_index });
        }
    }
    Ok(())
}

/// Validates every floating-point path in a collection.
///
/// This is the collection counterpart to [`validate_pathd`]. Empty paths are
/// valid and every coordinate in a non-empty path must be finite.
///
/// # Errors
///
/// Returns the first path-shape or coordinate-finiteness error found.
pub fn validate_paths_d(paths: &[PathD], kind: PathKind) -> Result<(), Error> {
    for path in paths {
        validate_pathd(path, kind)?;
    }
    Ok(())
}

/// Removes consecutive duplicates and, for closed paths, a repeated closing
/// point. The input is never modified.
///
/// This is a shape normalization helper, not a validity check: a normalized
/// path can still be too short or collinear for a particular operation.
#[must_use]
pub fn normalize_path64(path: &[Point64], kind: PathKind) -> Path64 {
    let mut normalized = Vec::with_capacity(path.len());
    for &point in path {
        if normalized.last().copied() != Some(point) {
            normalized.push(point);
        }
    }
    if kind == PathKind::Closed && normalized.len() > 1 && normalized.first() == normalized.last() {
        normalized.pop();
    }
    normalized
}

/// Removes consecutive duplicate floating-point points and a repeated closing
/// point for closed paths.
///
/// This is a shape normalization helper, not a validity check: a normalized
/// path can still be too short or collinear for a particular operation.
#[must_use]
pub fn normalize_pathd(path: &[PointD], kind: PathKind) -> PathD {
    let mut normalized = Vec::with_capacity(path.len());
    for &point in path {
        if normalized.last().copied() != Some(point) {
            normalized.push(point);
        }
    }
    if kind == PathKind::Closed && normalized.len() > 1 && normalized.first() == normalized.last() {
        normalized.pop();
    }
    normalized
}

/// Returns twice the signed area of an integer path using checked `i128`
/// arithmetic.
///
/// A positive result means counter-clockwise winding in the usual Cartesian
/// coordinate system; a negative result means clockwise winding. Paths with
/// fewer than three points have area zero.
///
/// # Errors
///
/// Returns [`Error::ArithmeticOverflow`] if the exact sum does not fit in an
/// `i128`.
pub fn signed_area2(path: &[Point64]) -> Result<i128, Error> {
    if path.len() < 3 {
        return Ok(0);
    }
    let mut area = 0_i128;
    for (a, b) in path.iter().copied().zip(path.iter().copied().cycle().skip(1)).take(path.len()) {
        let term = i128::from(a.x)
            .checked_mul(i128::from(b.y))
            .and_then(|left| {
                i128::from(a.y)
                    .checked_mul(i128::from(b.x))
                    .and_then(|right| left.checked_sub(right))
            })
            .ok_or(Error::ArithmeticOverflow)?;
        area = area.checked_add(term).ok_or(Error::ArithmeticOverflow)?;
    }
    Ok(area)
}

/// Returns the orientation of three integer points.
///
/// # Errors
///
/// Returns [`Error::ArithmeticOverflow`] if the exact cross product does not
/// fit in an `i128`.
pub fn orientation(a: Point64, b: Point64, c: Point64) -> Result<Orientation, Error> {
    let cross = checked_cross(a, b, c)?;
    Ok(match cross.cmp(&0) {
        core::cmp::Ordering::Less => Orientation::Clockwise,
        core::cmp::Ordering::Equal => Orientation::Collinear,
        core::cmp::Ordering::Greater => Orientation::CounterClockwise,
    })
}

/// Classifies an integer point against a closed path using the even-odd rule.
///
/// An empty path has no filled region, so every point is [`PointLocation::Outside`].
///
/// # Errors
///
/// Returns [`Error::InvalidPath`] for a non-empty path with fewer than three
/// points or [`Error::ArithmeticOverflow`] if a cross product overflows.
pub fn point_in_polygon(point: Point64, path: &[Point64]) -> Result<PointLocation, Error> {
    validate_path64(path, PathKind::Closed)?;
    if path.is_empty() {
        return Ok(PointLocation::Outside);
    }

    let mut inside = false;
    for (a, b) in path.iter().copied().zip(path.iter().copied().cycle().skip(1)).take(path.len()) {
        if point_on_segment(point, a, b)? {
            return Ok(PointLocation::Boundary);
        }

        if (a.y > point.y) != (b.y > point.y) {
            let cross = checked_cross(a, b, point)?;
            let crosses_right = if b.y > a.y { cross > 0 } else { cross < 0 };
            if crosses_right {
                inside = !inside;
            }
        }
    }
    Ok(if inside { PointLocation::Inside } else { PointLocation::Outside })
}

fn checked_cross(a: Point64, b: Point64, c: Point64) -> Result<i128, Error> {
    let first_x = i128::from(b.x) - i128::from(a.x);
    let first_y = i128::from(b.y) - i128::from(a.y);
    let second_x = i128::from(c.x) - i128::from(a.x);
    let second_y = i128::from(c.y) - i128::from(a.y);
    first_x
        .checked_mul(second_y)
        .and_then(|left| first_y.checked_mul(second_x).and_then(|right| left.checked_sub(right)))
        .ok_or(Error::ArithmeticOverflow)
}

fn point_on_segment(point: Point64, a: Point64, b: Point64) -> Result<bool, Error> {
    if checked_cross(a, b, point)? != 0 {
        return Ok(false);
    }
    let px = i128::from(point.x);
    let py = i128::from(point.y);
    let min_x = i128::from(a.x).min(i128::from(b.x));
    let max_x = i128::from(a.x).max(i128::from(b.x));
    let min_y = i128::from(a.y).min(i128::from(b.y));
    let max_y = i128::from(a.y).max(i128::from(b.y));
    Ok(px >= min_x && px <= max_x && py >= min_y && py <= max_y)
}

#[cfg(test)]
mod tests {
    use super::*;

    const A: Point64 = Point64::new(0, 0);
    const B: Point64 = Point64::new(10, 0);
    const C: Point64 = Point64::new(10, 10);

    #[test]
    fn validates_empty_and_minimum_shapes() {
        assert!(validate_path64(&[], PathKind::Closed).is_ok());
        assert!(validate_path64(&[A], PathKind::Closed).is_err());
        assert!(validate_path64(&[A, B], PathKind::Closed).is_err());
        assert!(validate_path64(&[A, B], PathKind::Open).is_ok());
        assert!(validate_path64(&[A], PathKind::Open).is_err());
        assert!(validate_paths64(&[vec![A, B]], PathKind::Open).is_ok());
        assert!(validate_paths64(&[vec![A]], PathKind::Closed).is_err());

        assert!(validate_paths_d(&[], PathKind::Closed).is_ok());
        assert!(
            validate_paths_d(&[vec![PointD::new(0.0, 0.0), PointD::new(1.0, 0.0)]], PathKind::Open)
                .is_ok()
        );
        assert!(validate_paths_d(&[vec![PointD::new(0.0, 0.0)]], PathKind::Closed).is_err());
    }

    #[test]
    fn validates_double_finiteness() {
        assert!(validate_pathd(&[], PathKind::Closed).is_ok());
        assert!(validate_pathd(&[PointD::new(0.0, 0.0)], PathKind::Closed).is_err());
        assert!(
            validate_pathd(&[PointD::new(0.0, 0.0), PointD::new(1.0, 0.0)], PathKind::Open).is_ok()
        );
        let error = validate_pathd(
            &[PointD::new(0.0, 0.0), PointD::new(f64::NAN, 0.0), PointD::new(1.0, 1.0)],
            PathKind::Closed,
        )
        .expect_err("NaN must be rejected");
        assert_eq!(error, Error::NonFiniteCoordinate { point_index: 1 });
        assert!(
            validate_pathd(
                &[PointD::new(0.0, 0.0), PointD::new(1.0, 0.0), PointD::new(f64::INFINITY, 1.0),],
                PathKind::Closed,
            )
            .is_err()
        );
        assert!(
            validate_pathd(
                &[PointD::new(0.0, 0.0), PointD::new(1.0, 0.0), PointD::new(0.0, f64::INFINITY)],
                PathKind::Closed,
            )
            .is_err()
        );
    }

    #[test]
    fn normalizes_integer_and_double_paths() {
        let input = [A, A, B, B, C, A, A];
        assert_eq!(normalize_path64(&input, PathKind::Closed), vec![A, B, C]);
        assert_eq!(normalize_path64(&[A, B, C], PathKind::Closed), vec![A, B, C]);
        assert_eq!(normalize_path64(&input, PathKind::Open), vec![A, B, C, A]);
        assert!(normalize_path64(&[], PathKind::Closed).is_empty());

        let doubles = [PointD::new(0.0, 0.0), PointD::new(0.0, 0.0), PointD::new(1.0, 0.0)];
        assert_eq!(normalize_pathd(&doubles, PathKind::Open).len(), 2);
        let closed_doubles = [
            PointD::new(0.0, 0.0),
            PointD::new(1.0, 0.0),
            PointD::new(0.0, 1.0),
            PointD::new(0.0, 0.0),
        ];
        assert_eq!(normalize_pathd(&closed_doubles, PathKind::Closed).len(), 3);
        assert_eq!(
            normalize_pathd(
                &[PointD::new(0.0, 0.0), PointD::new(1.0, 0.0), PointD::new(0.0, 1.0)],
                PathKind::Closed,
            )
            .len(),
            3
        );
        assert_eq!(normalize_pathd(&[], PathKind::Closed), Vec::<PointD>::new());
    }

    #[test]
    fn computes_area_and_orientation() {
        let square = vec![A, B, C, Point64::new(0, 10)];
        assert_eq!(signed_area2(&square), Ok(200));
        let mut reverse = square.clone();
        reverse.reverse();
        assert_eq!(signed_area2(&reverse), Ok(-200));
        assert_eq!(signed_area2(&[A, B]), Ok(0));
        assert_eq!(orientation(A, B, C), Ok(Orientation::CounterClockwise));
        assert_eq!(orientation(C, B, A), Ok(Orientation::Clockwise));
        assert_eq!(orientation(A, B, Point64::new(20, 0)), Ok(Orientation::Collinear));
    }

    #[test]
    fn reports_arithmetic_overflow() {
        let extreme = vec![
            Point64::new(i64::MAX, i64::MAX),
            Point64::new(i64::MIN, i64::MAX),
            Point64::new(i64::MIN, i64::MIN),
            Point64::new(i64::MAX, i64::MIN),
        ];
        assert_eq!(signed_area2(&extreme), Err(Error::ArithmeticOverflow));
        assert_eq!(
            signed_area2(&[
                Point64::new(i64::MIN, i64::MIN),
                Point64::new(i64::MIN, 1),
                Point64::new(i64::MAX, i64::MIN),
            ]),
            Err(Error::ArithmeticOverflow)
        );
        assert_eq!(
            orientation(
                Point64::new(i64::MIN, i64::MIN),
                Point64::new(i64::MAX, i64::MAX),
                Point64::new(i64::MIN, i64::MAX)
            ),
            Err(Error::ArithmeticOverflow)
        );
        assert_eq!(
            checked_cross(
                Point64::new(i64::MIN, i64::MIN),
                Point64::new(i64::MIN, i64::MAX),
                Point64::new(i64::MAX, i64::MIN),
            ),
            Err(Error::ArithmeticOverflow)
        );
        assert_eq!(
            checked_cross(
                Point64::new(i64::MIN, -1),
                Point64::new(-1, i64::MIN),
                Point64::new(i64::MAX, i64::MAX),
            ),
            Err(Error::ArithmeticOverflow)
        );
    }

    #[test]
    fn classifies_points_and_empty_paths() {
        let square = vec![A, B, C, Point64::new(0, 10)];
        assert_eq!(point_in_polygon(Point64::new(5, 5), &square), Ok(PointLocation::Inside));
        assert_eq!(point_in_polygon(Point64::new(15, 5), &square), Ok(PointLocation::Outside));
        assert_eq!(point_in_polygon(Point64::new(20, 0), &square), Ok(PointLocation::Outside));
        assert_eq!(point_in_polygon(Point64::new(-1, 0), &square), Ok(PointLocation::Outside));
        assert_eq!(point_in_polygon(Point64::new(10, 20), &square), Ok(PointLocation::Outside));
        assert_eq!(point_in_polygon(Point64::new(10, -1), &square), Ok(PointLocation::Outside));
        assert_eq!(point_in_polygon(Point64::new(10, 5), &square), Ok(PointLocation::Boundary));
        assert_eq!(point_in_polygon(A, &[]), Ok(PointLocation::Outside));
        assert!(point_in_polygon(A, &[A, B]).is_err());
    }
}