ifc_lite_geometry/math/
v2.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Plane vectors and ring primitives over `[f64; 2]`: the one home for the
6//! 2D kit that `geom2d`, `bool2d`, `scan_outline`, the triangulator, the
7//! export plates and the processing PDF/scan code each used to carry a copy
8//! of (#7773). Every function is FMA-free with the op order written out; see
9//! the [module conventions](super).
10//!
11//! Rings are *implicitly closed* (edge `i` runs `ring[i] -> ring[(i + 1) % n]`).
12//! The `_by` forms take an index accessor instead of a slice so a flat
13//! `[x0, y0, x1, y1, ..]` buffer, a nalgebra `Point2` contour or a half-edge
14//! cycle run through the very same loop without being copied first.
15//!
16//! The exact (Shewchuk) predicates live in [`geom2d`](super::geom2d); nothing
17//! here is adaptive.
18
19/// A plane point or vector.
20pub type P2 = [f64; 2];
21
22#[inline]
23pub fn add(a: P2, b: P2) -> P2 {
24    [a[0] + b[0], a[1] + b[1]]
25}
26
27#[inline]
28pub fn sub(a: P2, b: P2) -> P2 {
29    [a[0] - b[0], a[1] - b[1]]
30}
31
32#[inline]
33pub fn scale(a: P2, s: f64) -> P2 {
34    [a[0] * s, a[1] * s]
35}
36
37/// `a0*b0 + a1*b1`, never fused.
38#[inline]
39pub fn dot(a: P2, b: P2) -> f64 {
40    a[0] * b[0] + a[1] * b[1]
41}
42
43/// The z component of the 3D cross product: `a0*b1 - a1*b0`, never fused.
44#[inline]
45pub fn cross(a: P2, b: P2) -> f64 {
46    a[0] * b[1] - a[1] * b[0]
47}
48
49/// Euclidean length, `dot(a, a).sqrt()`.
50#[inline]
51pub fn norm(a: P2) -> f64 {
52    dot(a, a).sqrt()
53}
54
55/// Distance via `hypot` (no intermediate overflow).
56#[inline]
57pub fn dist(a: P2, b: P2) -> f64 {
58    (a[0] - b[0]).hypot(a[1] - b[1])
59}
60
61/// Squared distance, `dx*dx + dy*dy`.
62#[inline]
63pub fn dist2(a: P2, b: P2) -> f64 {
64    let dx = a[0] - b[0];
65    let dy = a[1] - b[1];
66    dx * dx + dy * dy
67}
68
69/// Twice the signed shoelace area of the closed ring `at(0..n)`: positive for
70/// counter-clockwise. No degenerate guard (`n < 3` sums to zero or the
71/// caller's own NaN); [`polygon_area`] adds it.
72#[inline]
73pub fn shoelace2_by(n: usize, at: impl Fn(usize) -> P2) -> f64 {
74    shoelace2_edges((0..n).map(|i| (at(i), at((i + 1) % n))))
75}
76
77/// [`shoelace2_by`] over explicit directed edges `(from, to)`, for a cycle
78/// that is not stored as a vertex array (a half-edge loop).
79#[inline]
80pub fn shoelace2_edges(edges: impl IntoIterator<Item = (P2, P2)>) -> f64 {
81    let mut acc = 0.0;
82    for (p, q) in edges {
83        acc += p[0] * q[1] - q[0] * p[1];
84    }
85    acc
86}
87
88/// Area centroid of a ring whose signed area is `area` (non-zero): the
89/// `(p + q) * cross` moment sum over six times the area. Non-finite when the
90/// area is zero; the caller screens that.
91pub fn area_centroid(poly: &[P2], area: f64) -> P2 {
92    let (mut cx, mut cy) = (0.0, 0.0);
93    for i in 0..poly.len() {
94        let p = poly[i];
95        let q = poly[(i + 1) % poly.len()];
96        let cross = p[0] * q[1] - q[0] * p[1];
97        cx += (p[0] + q[0]) * cross;
98        cy += (p[1] + q[1]) * cross;
99    }
100    [cx / (6.0 * area), cy / (6.0 * area)]
101}
102
103/// Signed shoelace area of the closed ring `at(0..n)`; `0` below three
104/// vertices. Non-finite coordinates propagate as NaN.
105#[inline]
106pub fn signed_area_by(n: usize, at: impl Fn(usize) -> P2) -> f64 {
107    if n < 3 {
108        return 0.0;
109    }
110    shoelace2_by(n, at) * 0.5
111}
112
113/// Signed shoelace area: positive for a counter-clockwise ring, `0` below
114/// three vertices.
115pub fn polygon_area(pts: &[P2]) -> f64 {
116    signed_area_by(pts.len(), |i| pts[i])
117}
118
119/// Even-odd ray cast of `p` against the closed ring `at(0..n)`; `false` below
120/// three vertices. A point on the boundary is decided by the half-open
121/// crossing rule (an edge counts when exactly one endpoint is above `p.y` and
122/// `p.x` is strictly left of the crossing), and a NaN comparison never counts
123/// as a crossing.
124#[inline]
125pub fn point_in_ring_by(p: P2, n: usize, at: impl Fn(usize) -> P2) -> bool {
126    if n < 3 {
127        return false;
128    }
129    let mut inside = false;
130    let mut j = n - 1;
131    for i in 0..n {
132        let (pi, pj) = (at(i), at(j));
133        let (xi, yi) = (pi[0], pi[1]);
134        let (xj, yj) = (pj[0], pj[1]);
135        if ((yi > p[1]) != (yj > p[1])) && (p[0] < (xj - xi) * (p[1] - yi) / (yj - yi) + xi) {
136            inside = !inside;
137        }
138        j = i;
139    }
140    inside
141}
142
143/// Ray-cast point-in-polygon for an arbitrary simple ring.
144pub fn point_in_polygon(p: P2, poly: &[P2]) -> bool {
145    point_in_ring_by(p, poly.len(), |i| poly[i])
146}
147
148/// Bounding box `[min_x, min_y, max_x, max_y]` of `points`; the empty set
149/// gives `[+INF, +INF, -INF, -INF]`. `f64::min`/`max` skip NaN, so a NaN
150/// coordinate never poisons the box.
151pub fn bbox(points: impl IntoIterator<Item = P2>) -> [f64; 4] {
152    let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];
153    for p in points {
154        b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])];
155    }
156    b
157}
158
159/// Distance from `p` to the closed segment `a-b` (the point distance when
160/// the segment is a point).
161pub fn point_segment_distance(p: P2, a: P2, b: P2) -> f64 {
162    let d = [b[0] - a[0], b[1] - a[1]];
163    let q = [p[0] - a[0], p[1] - a[1]];
164    let n = d[0] * d[0] + d[1] * d[1];
165    let t = if n == 0. {
166        0.
167    } else {
168        ((q[0] * d[0] + q[1] * d[1]) / n).clamp(0., 1.)
169    };
170    (q[0] - t * d[0]).hypot(q[1] - t * d[1])
171}