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
// src/ops/coverage/mod.rs
//! Polygonal coverages and noded linework: [`coverage_validate`] (with an
//! optional narrow-gap check, [`coverage_validate_with_gap`]),
//! [`coverage_union`], and [`polygonize_noded`].
//!
//! # Why these belong here
//!
//! Every operation in this module works on input that is **already exactly
//! noded**: adjacent polygons share their vertices bit for bit, and lines meet
//! only at shared endpoints. So every output coordinate is an input
//! coordinate. Nothing is intersected, rounded or moved. The versions that
//! node general input first, and therefore construct coordinates, belong to
//! a constructive crate rather than this one.
//!
//! # The two exact building blocks
//!
//! ## Edge identity
//!
//! Two directed edges are the same undirected edge when
//! their endpoint pairs are equal, in either order, by exact coordinate
//! equality (`-0.0` equals `0.0`, as coordinates do everywhere in this
//! crate).
//!
//! ## **Angular order at a vertex**
//!
//! This is the one numerical primitive the module adds. The edges leaving a
//! vertex `v` are sorted *counterclockwise* from the `+x` direction:
//!
//! 1. Each direction `a − v` is classified into a half-turn: the upper
//! half `[0, π)` (`dy > 0`, or `dy = 0` and `dx > 0`) or the lower half
//! `[π, 2π)`. The signs of `dx = fl(a.x − v.x)` and `dy` are the signs of
//! the exact differences: subtraction is correctly rounded, rounding
//! never changes a sign, and a nonzero difference never rounds to zero
//! (a difference too small to be normal is exact, by gradual underflow).
//! Opposite directions always fall in different halves.
//! 2. Within one half, every pair of directions spans less than a half
//! turn, so `b` comes after `a` exactly when the exact predicate
//! `orient2d(v, a, b) > 0` holds.
//!
//! Nothing is constructed, no angle is computed, and every comparison is
//! exact. Two distinct edges in the same direction from `v` would overlap
//! collinearly; the validations exclude that before the order is used.
//!
//! # Tracing faces
//!
//! Faces are traced with the face on the left of each directed edge: from
//! the edge `u → v`, the next edge is the one **first clockwise** from the
//! reverse direction `v → u` among the edges leaving `v`, which is the
//! tightest left turn. (That is the standard half-edge successor; the next edge
//! *counterclockwise* from the reverse would trace faces on the right.)
//!
//! A face whose boundary touches itself (a hole touching its exterior at a
//! vertex, two parts of a union meeting at a corner) has **one** boundary
//! walk that visits the touching vertex twice; no turn rule can split it,
//! because the walk is a property of the embedding. So each walk is split at
//! repeated vertices into simple closed loops, and each loop is classified
//! by the certified sign of its area: positive (counterclockwise) is an
//! exterior, negative (clockwise) a hole. Rings that touch at a vertex are
//! valid, so the split loops are the valid rings OGC asks for.
//!
//! Holes are assigned to the innermost exterior that contains them, by exact
//! ring placement ([`place_ring`](crate::exact::place_ring)); "innermost" is
//! decided by placement too, never by comparing approximate areas.
pub
use crateGeometryError;
use crate;
// ===========================================================================
// Coverage validation
// ===========================================================================
/// One reason a set of polygons is not a valid coverage.
///
/// Indices refer to the input slice: `polygon` and `other` are positions in
/// it, `ring` is `0` for the exterior and `1..` for the holes in order, and
/// `edge` is the edge starting at that ring's vertex `edge`.
/// Every reason `polys` is not a valid polygonal coverage, sorted; empty
/// when it is one.
///
/// A coverage is valid when every ring is simple
/// ([`CoverageIssue::NonSimpleRing`]), no two interiors meet
/// ([`CoverageIssue::Overlap`]), and every shared stretch of boundary is made
/// of identical edges ([`CoverageIssue::UnmatchedEdge`]), so adjacent
/// polygons share their vertices bit for bit. Gaps between polygons are allowed; use
/// [`coverage_validate_with_gap`] to find narrow ones.
///
/// Exact: overlaps by `relate`, edge identity by coordinate equality,
/// collinearity and vertex-on-edge by `orient2d` on stored coordinates.
/// Candidate pairs come from a box index (no false negatives).
///
/// ```
/// use geometres::ops::coverage_validate;
/// use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
///
/// let square = |x: f64| -> Result<Polygon, geometres::GeometryError> {
/// Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
/// Coord2d::new(x, 0.0), Coord2d::new(x + 1.0, 0.0),
/// Coord2d::new(x + 1.0, 1.0), Coord2d::new(x, 1.0),
/// ]))?)
/// };
/// // Two unit squares sharing the edge x = 1: a valid coverage.
/// assert!(coverage_validate(&[square(0.0)?, square(1.0)?]).is_empty());
/// # Ok::<(), geometres::GeometryError>(())
/// ```
/// [`coverage_validate`], plus [`CoverageIssue::NarrowGap`] for every pair
/// of boundary edges of different polygons that lie within `width` of each
/// other (distance `≤ width`, decided exactly), are not the same edge, and
/// do not touch.
///
/// The test is `ops::distance`'s exact segment-to-segment composition: the
/// edges do not touch, so their distance is attained at an endpoint of one
/// of them, and each endpoint-to-segment comparison is `arithmetica`'s exact
/// predicate. "This gap is narrower than `width`" is therefore never decided
/// in `f64`. Candidates come from each edge's box grown by `width` and
/// rounded outward: a box rounded inward could miss a pair, while one
/// rounded outward only adds candidates, which the exact test rejects.
///
/// Gap detection is finding narrow gaps of at most a maximum gap width, including
/// gaps separating disjoint coverage regions and narrow gores. `width = 0` reports
/// no gap (a distance of zero means the edges touch).
///
/// # Errors
///
/// [`GeometryError::InvalidTolerance`] if `width` is negative or not
/// finite.
// ===========================================================================
// Coverage union
// ===========================================================================
/// The union of a valid coverage, by removing shared edges. It takes no
/// overlay and no intersection, and adds no vertex.
///
/// Every ring edge is collected with its direction. In a valid coverage an
/// edge shared by two polygons appears exactly twice, in opposite
/// directions (exteriors run counterclockwise and holes clockwise, so the
/// interior is always on the left), and lies inside the union: it is
/// dropped. An edge appearing once is on the union's boundary. The boundary
/// edges are traced into rings with the union's interior on the left (the
/// module documentation), classified by the certified sign of their area,
/// and holes are assigned to exteriors by exact placement. The result is
/// built through `Polygon::new` and `MultiPolygon::new`.
///
/// Collinear vertices left on a dissolved boundary are **kept**: removing
/// them would be simplification, and every output vertex is an input
/// vertex, bit for bit.
///
/// # Errors
///
/// - [`GeometryError::InvalidCoverage`] carrying the first issue
/// [`coverage_validate`] finds, if the input is not a valid coverage. For
/// general input, use a constructive union.
/// - [`GeometryError::NonFiniteResult`] if a ring of the union has a signed
/// area beyond the range of `f64`. Every input polygon has a finite area,
/// but their union can exceed it (coordinates near 1e154 and beyond), and
/// no `Polygon` can carry such a ring.
// ===========================================================================
// Polygonize noded linework
// ===========================================================================
/// What [`polygonize_noded`] returns: the faces of a noded line arrangement,
/// and the linework that bounds no face.
/// The faces of the noded linework of `lines`, as polygons, with their
/// by-products: dangles, cut edges and invalid rings.
///
/// The linework is every segment of every line and ring in `lines`
/// (points are ignored); identical segments, in either direction, are one
/// edge, and **every vertex is a node**.
///
/// **The linework must be noded:** two segments may meet only at an endpoint of
/// both, with no crossing, no collinear overlap, and no endpoint in the
/// interior of another segment. That is checked exactly before anything is
/// traced.
///
/// Dangles are removed repeatedly; then cut edges (edges whose two sides
/// trace the same face); the remaining faces are traced with the face on
/// the left. A face's outer loop is its exterior; the loops of components
/// nested inside it are its holes, assigned by exact placement. The faces
/// of a nested component are output as well: a hole and the island in it
/// are both faces. Every output coordinate is an input coordinate.
///
/// # Errors
///
/// [`GeometryError::NotNoded`], naming the first offending pair of
/// segments, if the linework is not noded. Node the input first with a
/// constructive operation.