1use core::cmp::Ordering;
4use core::ops::{Add, AddAssign, Neg, Range, Sub, SubAssign};
5use std::collections::HashMap;
6use std::iter::once;
7
8use geo_types::Coord;
9
10use crate::TileError;
11use crate::geom::signed_area_2x;
12
13const FRAC: u32 = 8;
15const ONE: i64 = 1 << FRAC;
17const HALF: i64 = ONE / 2;
19
20type Fixed = Coord<i64>;
22type Pixel = Coord<i32>;
24
25#[derive(Debug, Default, Clone)]
38pub struct Quantizer {
39 fixed: Vec<Fixed>,
40 fixed_ends: Vec<usize>,
41 fixed_polygon_ends: Vec<usize>,
42 rounded_at: Vec<Option<usize>>,
43 near_other_ring: Vec<bool>,
44 vertices: Vec<Pixel>,
45 ring_ends: Vec<usize>,
46 polygon_ends: Vec<usize>,
47 segs: Vec<Seg>,
48 lines: Vec<(Fixed, Fixed)>,
49 grid: Grid,
50 groups: PartGroups,
51 group: Option<Box<Self>>,
52}
53
54#[derive(Debug, Default, Clone)]
56struct PartGroups {
57 boxes: Vec<(Pixel, Pixel)>,
58 starts: Vec<i32>,
59 ends: Vec<i32>,
60 roots: Vec<usize>,
61 order: Vec<usize>,
62 active: Vec<usize>,
63 grouped: Vec<(usize, usize)>,
64}
65
66impl PartGroups {
67 fn group(&mut self, fixed: &[Fixed], ring_ends: &[usize], polygon_ends: &[usize]) -> &[(usize, usize)] {
74 let Self {
75 boxes,
76 starts,
77 ends,
78 roots,
79 order,
80 active,
81 grouped,
82 } = self;
83 boxes.clear();
84 for rings in spans(polygon_ends) {
85 let vertices = span(ring_ends, rings.start).start..ring_ends[rings.end - 1];
86 let (min, max) = bounds(fixed[vertices].iter().copied()).expect("a part keeps its exterior");
87 boxes.push((pixel(min), pixel(max)));
88 }
89 let along_x = sweep_checks(boxes, |(lo, hi)| (lo.x, hi.x), starts, ends);
90 let along_y = sweep_checks(boxes, |(lo, hi)| (lo.y, hi.y), starts, ends);
91 if along_y < along_x {
92 for (lo, hi) in boxes.iter_mut() {
93 (*lo, *hi) = (Coord { x: lo.y, y: lo.x }, Coord { x: hi.y, y: hi.x });
94 }
95 }
96 roots.clear();
97 roots.extend(0..boxes.len());
98 order.clear();
99 order.extend(0..boxes.len());
100 order.sort_unstable_by_key(|&p| boxes[p].0.x);
101 active.clear();
102 for &p in &*order {
103 let (lo, hi) = boxes[p];
104 active.retain(|&q| boxes[q].1.x >= lo.x);
105 for &q in &*active {
106 if boxes[q].0.y <= hi.y && lo.y <= boxes[q].1.y {
107 let (a, b) = (root(roots, p), root(roots, q));
108 roots[a.max(b)] = a.min(b);
109 }
110 }
111 active.push(p);
112 }
113 grouped.clear();
114 for p in 0..boxes.len() {
115 let r = root(roots, p);
116 grouped.push((r, p));
117 }
118 grouped.sort_unstable();
119 grouped
120 }
121}
122
123fn sweep_checks(
126 boxes: &[(Pixel, Pixel)],
127 axis: fn(&(Pixel, Pixel)) -> (i32, i32),
128 starts: &mut Vec<i32>,
129 ends: &mut Vec<i32>,
130) -> usize {
131 starts.clear();
132 ends.clear();
133 for b in boxes {
134 let (start, end) = axis(b);
135 starts.push(start);
136 ends.push(end);
137 }
138 starts.sort_unstable();
139 ends.sort_unstable();
140 starts
141 .iter()
142 .enumerate()
143 .map(|(i, &start)| i - ends.partition_point(|&end| end < start))
144 .sum()
145}
146
147fn root(roots: &mut [usize], mut p: usize) -> usize {
149 while roots[p] != p {
150 roots[p] = roots[roots[p]];
151 p = roots[p];
152 }
153 p
154}
155
156#[derive(Debug, Clone, Copy)]
158pub struct Quantized<'a> {
159 quantizer: &'a Quantizer,
160}
161
162#[derive(Debug, Clone, Copy)]
164struct Seg {
165 a: Pixel,
166 b: Pixel,
167 ring: usize,
168 ring_start: usize,
169 ring_len: usize,
170}
171
172impl Seg {
173 fn line(self) -> (Fixed, Fixed) {
175 (widen(self.a), widen(self.b))
176 }
177}
178
179#[derive(Debug, Clone, Copy)]
181struct FixedEdge {
182 a: Fixed,
183 b: Fixed,
184 winding: Winding,
185}
186
187#[derive(Debug, Clone, Copy)]
189struct NetEdge {
190 a: Pixel,
191 b: Pixel,
192 winding: Winding,
193}
194
195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
197struct Winding {
198 exterior: i32,
199 holes: i32,
200}
201
202impl Winding {
203 const EXTERIOR: Self = Self { exterior: 1, holes: 0 };
205 const HOLE: Self = Self { exterior: 0, holes: 1 };
207
208 fn inside(self) -> bool {
210 self.exterior != 0 && self.holes == 0
211 }
212
213 fn in_some_part(self) -> bool {
215 self.exterior + self.holes > 0
216 }
217}
218
219impl Add for Winding {
220 type Output = Self;
221
222 fn add(self, other: Self) -> Self {
223 Self {
224 exterior: self.exterior + other.exterior,
225 holes: self.holes + other.holes,
226 }
227 }
228}
229
230impl Sub for Winding {
231 type Output = Self;
232
233 fn sub(self, other: Self) -> Self {
234 self + -other
235 }
236}
237
238impl Neg for Winding {
239 type Output = Self;
240
241 fn neg(self) -> Self {
242 Self {
243 exterior: -self.exterior,
244 holes: -self.holes,
245 }
246 }
247}
248
249impl AddAssign for Winding {
250 fn add_assign(&mut self, other: Self) {
251 *self = *self + other;
252 }
253}
254
255impl SubAssign for Winding {
256 fn sub_assign(&mut self, other: Self) {
257 *self = *self - other;
258 }
259}
260
261impl Quantizer {
262 #[must_use]
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn polygon<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
274 where
275 R: IntoIterator,
276 R::Item: IntoIterator<Item = Coord<f64>>,
277 {
278 self.read(once(rings))?;
279 self.finish(Self::rounding_kept_valid, Winding::inside);
280 debug_assert!(
281 self.output_is_valid(),
282 "Quantizer::polygon was given an invalid polygon"
283 );
284 Ok(Quantized { quantizer: self })
285 }
286
287 pub fn multi_polygon<P>(&mut self, polygons: P) -> Result<Quantized<'_>, TileError>
297 where
298 P: IntoIterator,
299 P::Item: IntoIterator,
300 <P::Item as IntoIterator>::Item: IntoIterator<Item = Coord<f64>>,
301 {
302 self.read(polygons)?;
303 let parts = self.fixed_polygon_ends.len();
304 let mut groups = std::mem::take(&mut self.groups);
305 let grouped: &[(usize, usize)] = if parts <= 1 {
306 &[]
307 } else {
308 groups.group(&self.fixed, &self.fixed_ends, &self.fixed_polygon_ends)
309 };
310 if grouped
311 .first()
312 .is_none_or(|&(first, _)| grouped.iter().all(|g| g.0 == first))
313 {
314 self.finish_group(parts);
315 } else {
316 let mut group = self.group.take().unwrap_or_default();
317 self.vertices.clear();
318 self.ring_ends.clear();
319 self.polygon_ends.clear();
320 for members in grouped.chunk_by(|a, b| a.0 == b.0) {
321 group.fixed.clear();
322 group.fixed_ends.clear();
323 group.fixed_polygon_ends.clear();
324 for &(_, p) in members {
325 for r in span(&self.fixed_polygon_ends, p) {
326 group.fixed.extend_from_slice(&self.fixed[span(&self.fixed_ends, r)]);
327 group.fixed_ends.push(group.fixed.len());
328 }
329 group.fixed_polygon_ends.push(group.fixed_ends.len());
330 }
331 group.finish_group(members.len());
332 let (vertex_offset, ring_offset) = (self.vertices.len(), self.ring_ends.len());
333 self.vertices.extend_from_slice(&group.vertices);
334 self.ring_ends.extend(group.ring_ends.iter().map(|e| e + vertex_offset));
335 self.polygon_ends
336 .extend(group.polygon_ends.iter().map(|e| e + ring_offset));
337 }
338 self.group = Some(group);
339 }
340 self.groups = groups;
341 debug_assert!(
342 self.output_is_valid(),
343 "Quantizer::multi_polygon was given a polygon that is not valid on its own"
344 );
345 Ok(Quantized { quantizer: self })
346 }
347
348 pub fn make_valid<R>(&mut self, rings: R) -> Result<Quantized<'_>, TileError>
356 where
357 R: IntoIterator,
358 R::Item: IntoIterator<Item = Coord<f64>>,
359 {
360 self.read(once(rings))?;
361 self.finish(Self::rounded_is_valid, Winding::inside);
362 debug_assert!(self.output_is_valid(), "Quantizer::make_valid gave an invalid polygon");
363 Ok(Quantized { quantizer: self })
364 }
365
366 fn finish(&mut self, still_valid: fn(&mut Self) -> bool, inside: fn(Winding) -> bool) {
369 self.round();
370 if !self.ring_ends.is_empty() {
371 if still_valid(self) {
372 self.keep();
373 } else {
374 self.repair(inside);
375 }
376 }
377 }
378
379 fn finish_group(&mut self, parts: usize) {
382 if parts == 1 {
383 self.finish(Self::rounding_kept_valid, Winding::inside);
384 } else {
385 self.finish(
386 |q| q.rounded_rings_apart() && q.output_is_valid(),
387 Winding::in_some_part,
388 );
389 }
390 }
391
392 fn read<P>(&mut self, polygons: P) -> Result<(), TileError>
394 where
395 P: IntoIterator,
396 P::Item: IntoIterator,
397 <P::Item as IntoIterator>::Item: IntoIterator<Item = Coord<f64>>,
398 {
399 self.fixed.clear();
400 self.fixed_ends.clear();
401 self.fixed_polygon_ends.clear();
402 for rings in polygons {
403 self.read_polygon(rings)?;
404 }
405 Ok(())
406 }
407
408 fn read_polygon<R>(&mut self, rings: R) -> Result<(), TileError>
412 where
413 R: IntoIterator,
414 R::Item: IntoIterator<Item = Coord<f64>>,
415 {
416 let first_ring = self.fixed_ends.len();
417 for (i, ring) in rings.into_iter().enumerate() {
418 let start = self.fixed.len();
419 for c in ring {
420 let c = Coord {
421 x: to_fixed(c.x)?,
422 y: to_fixed(c.y)?,
423 };
424 push_new(&mut self.fixed, start, c);
425 }
426 drop_closing(&mut self.fixed, start);
427 if self.fixed.len() - start < 3 {
428 self.fixed.truncate(start);
429 if i == 0 {
430 return Ok(());
431 }
432 continue;
433 }
434 let area = fixed_area_2x(&self.fixed[start..]);
435 if (i == 0 && area < 0) || (i > 0 && area > 0) {
436 self.fixed[start..].reverse();
437 }
438 self.fixed_ends.push(self.fixed.len());
439 }
440 if self.fixed_ends.len() > first_ring {
441 self.fixed_polygon_ends.push(self.fixed_ends.len());
442 }
443 Ok(())
444 }
445
446 fn output_is_valid(&self) -> bool {
448 let vertices: Vec<Fixed> = self.vertices.iter().map(|&p| widen(p)).collect();
449 is_valid(&vertices, &self.ring_ends, &self.polygon_ends)
450 }
451
452 fn round(&mut self) {
455 self.vertices.clear();
456 self.ring_ends.clear();
457 self.polygon_ends.clear();
458 self.rounded_at.clear();
459 for rings in spans(&self.fixed_polygon_ends) {
460 let first_ring = self.ring_ends.len();
461 for r in rings.clone() {
462 let start = self.vertices.len();
463 let from = self.rounded_at.len();
464 for &c in &self.fixed[span(&self.fixed_ends, r)] {
465 push_new(&mut self.vertices, start, pixel(c));
466 self.rounded_at.push(Some(self.vertices.len() - 1));
467 }
468 if drop_closing(&mut self.vertices, start) {
469 let last = Some(self.vertices.len());
470 for at in &mut self.rounded_at[from..] {
471 if *at == last {
472 *at = Some(start);
473 }
474 }
475 }
476 if self.vertices.len() - start < 3 {
477 self.vertices.truncate(start);
478 if r == rings.start {
479 self.rounded_at.truncate(from);
480 self.rounded_at.resize(self.fixed_ends[rings.end - 1], None);
481 break;
482 }
483 self.rounded_at[from..].fill(None);
484 continue;
485 }
486 self.ring_ends.push(self.vertices.len());
487 }
488 if self.ring_ends.len() > first_ring {
489 self.polygon_ends.push(self.ring_ends.len());
490 }
491 }
492 }
493
494 fn keep(&mut self) {
496 for rings in spans(&self.polygon_ends) {
497 for r in rings.clone() {
498 let ring = &mut self.vertices[span(&self.ring_ends, r)];
499 if (signed_area_2x(ring) > 0) != (r == rings.start) {
500 ring.reverse();
501 }
502 }
503 }
504 }
505
506 fn rounded_edges(&mut self) -> bool {
508 self.segs.clear();
509 for (ring, span) in spans(&self.ring_ends).enumerate() {
510 let ring_start = span.start;
511 let verts = &self.vertices[span];
512 let ring_len = verts.len();
513 for (k, &at) in verts.iter().enumerate() {
514 let (prev, next) = (verts[(k + ring_len - 1) % ring_len], verts[(k + 1) % ring_len]);
515 if folds(widen(prev), widen(at), widen(next)) {
516 return false;
517 }
518 self.segs.push(Seg {
519 a: at,
520 b: next,
521 ring,
522 ring_start,
523 ring_len,
524 });
525 }
526 }
527 true
528 }
529
530 fn rounding_kept_valid(&mut self) -> bool {
533 if !self.rounded_edges() {
534 return false;
535 }
536 self.near_other_ring.clear();
537 self.near_other_ring.resize(self.fixed.len(), false);
538 let Self {
539 fixed,
540 fixed_ends,
541 rounded_at,
542 near_other_ring,
543 segs,
544 grid,
545 ..
546 } = self;
547 let segs = &*segs;
548 let incident = |r: usize| {
549 let s = segs[r];
550 [
551 if r == s.ring_start {
552 s.ring_start + s.ring_len - 1
553 } else {
554 r - 1
555 },
556 r,
557 ]
558 };
559 let apart = |x: usize, y: usize| {
560 x == y || adjacent(segs, x, y) || contact(segs[x].line(), segs[y].line()) == Contact::Apart
561 };
562 let planar = near_vertices(fixed, fixed_ends, grid, |v, a, b| {
563 let (Some(rv), Some(ra)) = (rounded_at[v], rounded_at[a]) else {
564 return true;
565 };
566 if !edges_at_clear_of(fixed, fixed_ends, v, a, b) {
567 return false;
568 }
569 if segs[rv].ring != segs[ra].ring {
570 near_other_ring[v] = true;
571 }
572 let image = if rounded_at[b] == Some(ra) {
573 incident(ra)
574 } else {
575 [ra, ra]
576 };
577 incident(rv).iter().all(|&x| image.iter().all(|&y| apart(x, y)))
578 });
579 planar
580 && rings_of(rounded_at, fixed_ends)
581 .zip(rings_of(near_other_ring, fixed_ends))
582 .all(|(r, near)| r[0].is_none() || near.contains(&false))
583 }
584
585 fn rounded_rings_apart(&mut self) -> bool {
588 if !self.rounded_edges() {
589 return false;
590 }
591 let segs = &self.segs;
592 self.lines.clear();
593 self.lines.extend(segs.iter().map(|s| s.line()));
594 let lines = &self.lines;
595 near_pairs(lines, &mut self.grid, |i, j| {
596 adjacent(segs, i, j) || contact(lines[i], lines[j]) == Contact::Apart
597 })
598 }
599
600 fn rounded_is_valid(&mut self) -> bool {
603 if !self.rounded_rings_apart() {
604 return false;
605 }
606 let (segs, lines) = (&self.segs, &self.lines);
607 if self.ring_ends.len() == 1 {
608 return true;
609 }
610 let edges: Vec<(Fixed, Fixed)> = lines.iter().map(|&(a, b)| left_first(a, b)).collect();
611 let hole_starts = &self.ring_ends[..self.ring_ends.len() - 1];
612 let queries: Vec<Fixed> = hole_starts.iter().map(|&s| widen(self.vertices[s]) * 2).collect();
613 let mut hits = Vec::new();
614 rays_up(&edges, &queries, |q, e| {
615 if segs[e].ring != q + 1 {
616 hits.push((q, segs[e].ring));
617 }
618 });
619 let around = odd_runs(hits);
620 around.len() == queries.len()
621 && around
622 .iter()
623 .enumerate()
624 .all(|(q, &(hole, ring))| hole == q && ring == 0)
625 }
626
627 fn repair(&mut self, inside: fn(Winding) -> bool) {
629 self.vertices.clear();
630 self.ring_ends.clear();
631 self.polygon_ends.clear();
632 let mut edges = Vec::new();
633 for rings in spans(&self.fixed_polygon_ends) {
634 for r in rings.clone() {
635 let ring = &self.fixed[span(&self.fixed_ends, r)];
636 let winding = if r == rings.start {
637 Winding::EXTERIOR
638 } else {
639 Winding::HOLE
640 };
641 for (k, &a) in ring.iter().enumerate() {
642 let b = ring[(k + 1) % ring.len()];
643 edges.push(FixedEdge { a, b, winding });
644 }
645 }
646 }
647 let hot = hot_pixels(&edges);
648 let net = net_edges(&edges, &hot);
649 let rings = trace(boundary(&net, inside));
650 self.assemble(rings);
651 }
652
653 fn assemble(&mut self, rings: Vec<Vec<Pixel>>) {
655 let (shells, holes): (Vec<_>, Vec<_>) = rings.into_iter().partition(|r| signed_area_2x(r) > 0);
656 let mut owner = vec![Some(0); holes.len()];
657 if shells.len() > 1 && !holes.is_empty() {
658 let mut edges = Vec::new();
659 let mut ring_of = Vec::new();
660 for (s, shell) in shells.iter().enumerate() {
661 for (k, &a) in shell.iter().enumerate() {
662 edges.push(left_first(widen(a), widen(shell[(k + 1) % shell.len()])));
663 ring_of.push(s);
664 }
665 }
666 let queries: Vec<Fixed> = holes.iter().map(|h| widen(h[0]) + widen(h[1])).collect();
667 let mut hits = Vec::new();
668 rays_up(&edges, &queries, |q, e| hits.push((q, ring_of[e])));
669 let areas: Vec<i128> = shells.iter().map(|s| signed_area_2x(s)).collect();
670 owner.fill(None);
671 for (hole, shell) in odd_runs(hits) {
672 if owner[hole].is_none_or(|o| areas[shell] < areas[o]) {
673 owner[hole] = Some(shell);
674 }
675 }
676 }
677 for (s, shell) in shells.iter().enumerate() {
678 self.vertices.extend_from_slice(shell);
679 self.ring_ends.push(self.vertices.len());
680 for (hole, _) in holes.iter().zip(&owner).filter(|&(_, &o)| o == Some(s)) {
681 self.vertices.extend_from_slice(hole);
682 self.ring_ends.push(self.vertices.len());
683 }
684 self.polygon_ends.push(self.ring_ends.len());
685 }
686 }
687}
688
689fn push_new<T: PartialEq>(verts: &mut Vec<T>, start: usize, v: T) {
691 if verts.len() == start || verts.last() != Some(&v) {
692 verts.push(v);
693 }
694}
695
696fn drop_closing<T: PartialEq>(verts: &mut Vec<T>, start: usize) -> bool {
698 let closes = verts.len() > start + 1 && verts.last() == verts.get(start);
699 if closes {
700 verts.pop();
701 }
702 closes
703}
704
705fn edges_at_clear_of(verts: &[Fixed], ends: &[usize], v: usize, a: usize, b: usize) -> bool {
708 let ring = span(ends, ends.partition_point(|&e| e <= v));
709 let prev = if v == ring.start { ring.end - 1 } else { v - 1 };
710 let next = if v + 1 == ring.end { ring.start } else { v + 1 };
711 let same_ring = ring.contains(&a);
712 [(prev, v), (v, next)]
713 .into_iter()
714 .all(|(x, y)| match contact((verts[x], verts[y]), (verts[a], verts[b])) {
715 Contact::Apart => true,
716 Contact::Point => !same_ring || x == b || y == a,
717 Contact::Cross | Contact::Overlap => false,
718 })
719}
720
721fn adjacent(segs: &[Seg], i: usize, j: usize) -> bool {
723 segs[i].ring == segs[j].ring && (i.abs_diff(j) == 1 || i.abs_diff(j) == segs[i].ring_len - 1)
724}
725
726impl<'a> Quantized<'a> {
727 pub fn polygons(self) -> impl Iterator<Item = impl Iterator<Item = &'a [Pixel]> + 'a> + 'a {
732 let q = self.quantizer;
733 spans(&q.polygon_ends).map(move |rings| rings.map(move |r| &q.vertices[span(&q.ring_ends, r)]))
734 }
735}
736
737fn span(ends: &[usize], i: usize) -> Range<usize> {
739 let start = if i == 0 { 0 } else { ends[i - 1] };
740 start..ends[i]
741}
742
743fn spans(ends: &[usize]) -> impl Iterator<Item = Range<usize>> + '_ {
745 (0..ends.len()).map(|i| span(ends, i))
746}
747
748fn rings_of<'a, T>(verts: &'a [T], ends: &'a [usize]) -> impl Iterator<Item = &'a [T]> {
750 spans(ends).map(|span| &verts[span])
751}
752
753#[expect(clippy::cast_possible_truncation, reason = "range-checked before the cast")]
755#[expect(clippy::cast_precision_loss, reason = "ONE and HALF are small powers of two")]
756fn to_fixed(v: f64) -> Result<i64, TileError> {
757 const ROUND: f64 = 6_755_399_441_055_744.0;
759 let scaled = v * ONE as f64;
760 let mut f = (scaled + ROUND) - ROUND;
761 #[expect(
762 clippy::float_cmp,
763 reason = "exact on purpose: only a rounded `f` may move off a half"
764 )]
765 let rounded_onto_a_half = f != scaled && f.rem_euclid(ONE as f64) == HALF as f64;
766 if rounded_onto_a_half {
767 f += (scaled - f).signum();
768 }
769 let lo = f64::from(i32::MIN) * ONE as f64 - HALF as f64;
770 let hi = (f64::from(i32::MAX) + 1.0) * ONE as f64 - HALF as f64;
771 if f >= lo && f < hi {
772 Ok(f as i64)
773 } else {
774 Err(TileError::Overflow)
775 }
776}
777
778#[expect(clippy::cast_possible_truncation, reason = "to_fixed keeps every pixel in i32")]
781fn pixel(c: Fixed) -> Pixel {
782 let unit = |v: i64| ((v + HALF - 1 + ((v >> FRAC) & 1)) >> FRAC) as i32;
784 Coord {
785 x: unit(c.x),
786 y: unit(c.y),
787 }
788}
789
790fn round_ratio(numerator: i128, denominator: i128) -> i128 {
792 let quotient = numerator.div_euclid(denominator);
793 let remainder = numerator.rem_euclid(denominator);
794 match (2 * remainder).cmp(&denominator) {
795 Ordering::Less => quotient,
796 Ordering::Greater => quotient + 1,
797 Ordering::Equal => quotient + quotient.rem_euclid(2),
798 }
799}
800
801fn widen(p: Pixel) -> Coord<i64> {
803 Coord {
804 x: i64::from(p.x),
805 y: i64::from(p.y),
806 }
807}
808
809fn bounds(mut points: impl Iterator<Item = Fixed>) -> Option<(Fixed, Fixed)> {
811 let first = points.next()?;
812 Some(points.fold((first, first), |(min, max), c| {
813 (
814 Coord {
815 x: min.x.min(c.x),
816 y: min.y.min(c.y),
817 },
818 Coord {
819 x: max.x.max(c.x),
820 y: max.y.max(c.y),
821 },
822 )
823 }))
824}
825
826#[derive(Debug, Default, Clone)]
828struct Grid {
829 cells: Vec<(u64, usize)>,
830 lengths: Vec<i64>,
831 columns: Vec<usize>,
832 points: Vec<(usize, usize)>,
833}
834
835fn near_pairs(lines: &[(Coord<i64>, Coord<i64>)], grid: &mut Grid, mut test: impl FnMut(usize, usize) -> bool) -> bool {
838 let Grid { cells, lengths, .. } = grid;
839 cells.clear();
840 lengths.clear();
841 let Some((min, max)) = bounds(lines.iter().flat_map(|&(a, b)| [a, b])) else {
842 return true;
843 };
844 lengths.extend(lines.iter().map(|&(a, b)| (b.x - a.x).abs().max((b.y - a.y).abs())));
845 let size = cell_size(lengths, min, max, 1);
846 let cell = |v: i64, o: i64| u64::try_from((v - o) / size).unwrap_or(0);
847 let rows = cell(max.y, min.y) + 1;
848 for (i, &(a, b)) in lines.iter().enumerate() {
849 let (a, b) = if a.x <= b.x { (a, b) } else { (b, a) };
850 let (lo, hi) = (a.y.min(b.y), a.y.max(b.y));
851 let (c0, c1) = (cell(a.x, min.x), cell(b.x, min.x));
852 if c0 == c1 {
853 for cy in cell(lo, min.y)..=cell(hi, min.y) {
854 cells.push((c0 * rows + cy, i));
855 }
856 continue;
857 }
858 #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
859 let at = |x: i64| a.y as f64 + (b.y - a.y) as f64 * ((x - a.x) as f64 / (b.x - a.x) as f64);
860 let mut x0 = a.x;
861 for cx in c0..=c1 {
862 let x1 = (min.x + i64::try_from(cx + 1).unwrap_or(i64::MAX).saturating_mul(size)).min(b.x);
863 let (left, right) = (at(x0), at(x1));
864 #[expect(clippy::cast_possible_truncation, reason = "clamped to the segment's own span")]
865 let (y0, y1) = (
866 (left.min(right).floor() as i64 - 1).max(lo),
867 (left.max(right).ceil() as i64 + 1).min(hi),
868 );
869 for cy in cell(y0, min.y)..=cell(y1, min.y) {
870 cells.push((cx * rows + cy, i));
871 }
872 x0 = x1;
873 }
874 }
875 cells.sort_unstable_by_key(|c| c.0);
876 for group in cells.chunk_by(|p, q| p.0 == q.0) {
877 for (k, p) in group.iter().enumerate() {
878 for q in &group[k + 1..] {
879 if !test(p.1, q.1) {
880 return false;
881 }
882 }
883 }
884 }
885 true
886}
887
888fn cell_size(lengths: &mut [i64], min: Fixed, max: Fixed, floor: i64) -> i64 {
891 let mid = lengths.len() / 2;
892 let median = *lengths.select_nth_unstable(mid).1;
893 let n = i64::try_from(lengths.len()).unwrap_or(i64::MAX);
894 median
895 .max((max.x - min.x).max(max.y - min.y) / n.saturating_mul(2))
896 .max(floor)
897}
898
899const GRID_MIN_VERTICES: usize = 32;
902
903fn near_vertices(
906 verts: &[Fixed],
907 ends: &[usize],
908 grid: &mut Grid,
909 mut test: impl FnMut(usize, usize, usize) -> bool,
910) -> bool {
911 let Grid {
912 lengths,
913 columns,
914 points,
915 ..
916 } = grid;
917 let edges = || {
918 spans(ends)
919 .flat_map(|Range { start, end }| (start..end).map(move |k| (k, if k + 1 == end { start } else { k + 1 })))
920 };
921 if verts.len() <= GRID_MIN_VERTICES {
922 return edges().all(|(a, b)| {
923 let (p, q) = (verts[a], verts[b]);
924 verts
925 .iter()
926 .enumerate()
927 .all(|(v, &c)| v == a || v == b || !passes_near(p, q, c) || test(v, a, b))
928 });
929 }
930 lengths.clear();
931 columns.clear();
932 points.clear();
933 let Some((min, max)) = bounds(verts.iter().copied()) else {
934 return true;
935 };
936 lengths.extend(edges().map(|(a, b)| {
937 let d = verts[b] - verts[a];
938 d.x.abs().max(d.y.abs())
939 }));
940 let shift = cell_size(lengths, min, max, ONE)
941 .unsigned_abs()
942 .next_power_of_two()
943 .trailing_zeros()
944 + 1;
945 let cell = |v: i64, o: i64| usize::try_from((v - o) >> shift).unwrap_or(0);
946 let (cols, rows) = (cell(max.x, min.x) + 1, cell(max.y, min.y) + 1);
947 let (column, row) = (
948 |x: i64| cell(x, min.x).min(cols - 1),
949 |y: i64| cell(y, min.y).min(rows - 1),
950 );
951 columns.resize(cols + 1, 0);
952 for c in verts {
953 columns[column(c.x) + 1] += 1;
954 }
955 for k in 1..=cols {
956 columns[k] += columns[k - 1];
957 }
958 points.resize(verts.len(), (0, 0));
959 for (i, c) in verts.iter().enumerate() {
960 let next = &mut columns[column(c.x)];
961 points[*next] = (row(c.y), i);
962 *next += 1;
963 }
964 columns.pop();
965 columns.insert(0, 0);
966 for k in 0..cols {
967 points[columns[k]..columns[k + 1]].sort_unstable_by_key(|p| p.0);
968 }
969 for (a, b) in edges() {
970 let (p, q) = (verts[a], verts[b]);
971 let (l, r) = if p.x <= q.x { (p, q) } else { (q, p) };
972 let (lo, hi) = (l.y.min(r.y), l.y.max(r.y));
973 #[expect(clippy::cast_precision_loss, reason = "a unit of error is allowed for")]
974 let at = |x: i64| l.y as f64 + (r.y - l.y) as f64 * ((x - l.x) as f64 / (r.x - l.x) as f64);
975 let (c0, c1) = (column(l.x - ONE), column(r.x + ONE));
976 for cx in c0..=c1 {
977 #[expect(clippy::cast_possible_truncation, reason = "clamped to the edge's own span")]
978 let (y0, y1) = if c1 - c0 <= 2 {
979 (lo, hi)
980 } else {
981 let x0 = min.x + (i64::try_from(cx).unwrap_or(i64::MAX) << shift);
982 let (xa, xb) = ((x0 - ONE).clamp(l.x, r.x), (x0 + (1 << shift) + ONE).clamp(l.x, r.x));
983 let (ya, yb) = (at(xa), at(xb));
984 ((ya.min(yb) as i64 - 2).max(lo), (ya.max(yb) as i64 + 2).min(hi))
985 };
986 let (r0, r1) = (row(y0 - ONE), row(y1 + ONE));
987 let col = &points[columns[cx]..columns[cx + 1]];
988 for &(y, v) in &col[col.partition_point(|p| p.0 < r0)..] {
989 if y > r1 {
990 break;
991 }
992 if v != a && v != b && passes_near(p, q, verts[v]) && !test(v, a, b) {
993 return false;
994 }
995 }
996 }
997 }
998 true
999}
1000
1001fn passes_near(a: Fixed, b: Fixed, v: Fixed) -> bool {
1003 if a.x.min(b.x) > v.x + ONE || a.x.max(b.x) < v.x - ONE || a.y.min(b.y) > v.y + ONE || a.y.max(b.y) < v.y - ONE {
1004 return false;
1005 }
1006 let d = b - a;
1007 cross(d, v - a).abs() <= i128::from(ONE) * i128::from(d.x.abs() + d.y.abs())
1008}
1009
1010#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1012enum Contact {
1013 Apart,
1015 Point,
1017 Cross,
1019 Overlap,
1021}
1022
1023fn contact((p1, p2): (Fixed, Fixed), (q1, q2): (Fixed, Fixed)) -> Contact {
1025 let boxed = |c: Fixed, a: Fixed, b: Fixed| {
1026 c.x >= a.x.min(b.x) && c.x <= a.x.max(b.x) && c.y >= a.y.min(b.y) && c.y <= a.y.max(b.y)
1027 };
1028 let side = |a: Fixed, b: Fixed, c: Fixed| cross(b - a, c - a).signum();
1029 let (s1, s2) = (side(p1, p2, q1), side(p1, p2, q2));
1030 let (s3, s4) = (side(q1, q2, p1), side(q1, q2, p2));
1031 if s1 * s2 < 0 && s3 * s4 < 0 {
1032 return Contact::Cross;
1033 }
1034 if s1 == 0 && s2 == 0 {
1035 let key = |c: Fixed| if p1.x == p2.x { c.y } else { c.x };
1036 let lo = key(p1).min(key(p2)).max(key(q1).min(key(q2)));
1037 let hi = key(p1).max(key(p2)).min(key(q1).max(key(q2)));
1038 return match lo.cmp(&hi) {
1039 Ordering::Less => Contact::Overlap,
1040 Ordering::Equal => Contact::Point,
1041 Ordering::Greater => Contact::Apart,
1042 };
1043 }
1044 let touches = (s1 == 0 && boxed(q1, p1, p2))
1045 || (s2 == 0 && boxed(q2, p1, p2))
1046 || (s3 == 0 && boxed(p1, q1, q2))
1047 || (s4 == 0 && boxed(p2, q1, q2));
1048 if touches { Contact::Point } else { Contact::Apart }
1049}
1050
1051fn is_valid(verts: &[Fixed], ring_ends: &[usize], polygon_ends: &[usize]) -> bool {
1054 let mut lines = Vec::new();
1055 let mut ring_of = Vec::new();
1056 for (r, ring) in rings_of(verts, ring_ends).enumerate() {
1057 let n = ring.len();
1058 if n < 3 {
1059 return false;
1060 }
1061 for k in 0..n {
1062 let (prev, at, next) = (ring[(k + n - 1) % n], ring[k], ring[(k + 1) % n]);
1063 if folds(prev, at, next) {
1064 return false;
1065 }
1066 lines.push((at, next));
1067 ring_of.push(r);
1068 }
1069 }
1070 let ring_len = |r: usize| span(ring_ends, r).len();
1071 let simple = near_pairs(&lines, &mut Grid::default(), |i, j| match contact(lines[i], lines[j]) {
1072 Contact::Apart => true,
1073 Contact::Point => ring_of[i] != ring_of[j] || i.abs_diff(j) == 1 || i.abs_diff(j) == ring_len(ring_of[i]) - 1,
1074 Contact::Cross | Contact::Overlap => false,
1075 });
1076 if !simple {
1077 return false;
1078 }
1079 let mut polygon_of = Vec::new();
1080 let mut shell_of = Vec::new();
1081 for (p, rings) in spans(polygon_ends).enumerate() {
1082 polygon_of.extend(core::iter::repeat_n(p, rings.len()));
1083 shell_of.extend(core::iter::repeat_n(rings.start, rings.len()));
1084 }
1085 let edges: Vec<(Fixed, Fixed)> = lines.iter().map(|&(a, b)| left_first(a, b)).collect();
1086 let queries: Vec<Fixed> = rings_of(verts, ring_ends).map(|r| r[0] + r[1]).collect();
1087 let mut hits = Vec::new();
1088 rays_up(&edges, &queries, |q, e| {
1089 if ring_of[e] != q {
1090 hits.push((q, ring_of[e]));
1091 }
1092 });
1093 let around = odd_runs(hits);
1094 let mut held = vec![false; queries.len()];
1095 for group in around.chunk_by(|a, b| a.0 == b.0 && polygon_of[a.1] == polygon_of[b.1]) {
1096 let (q, r) = group[0];
1097 if polygon_of[r] != polygon_of[q] {
1098 if group.len() != 2 || shell_of[r] != r {
1099 return false;
1100 }
1101 } else if shell_of[q] == q || group != [(q, shell_of[q])] {
1102 return false;
1103 } else {
1104 held[q] = true;
1105 }
1106 }
1107 (0..queries.len()).all(|q| shell_of[q] == q || held[q])
1108}
1109
1110fn folds(prev: Fixed, at: Fixed, next: Fixed) -> bool {
1112 let (back, ahead) = (prev - at, next - at);
1113 cross(back, ahead) == 0 && dot(back, ahead) > 0
1114}
1115
1116fn left_first(a: Fixed, b: Fixed) -> (Fixed, Fixed) {
1118 if (a.x, a.y) <= (b.x, b.y) { (a, b) } else { (b, a) }
1119}
1120
1121fn cross(a: Fixed, b: Fixed) -> i128 {
1123 i128::from(a.x) * i128::from(b.y) - i128::from(a.y) * i128::from(b.x)
1124}
1125
1126fn dot(a: Fixed, b: Fixed) -> i128 {
1128 i128::from(a.x) * i128::from(b.x) + i128::from(a.y) * i128::from(b.y)
1129}
1130
1131fn fixed_area_2x(ring: &[Fixed]) -> i128 {
1133 let Some(&o) = ring.first() else {
1134 return 0;
1135 };
1136 ring.array_windows().map(|&[p, q]| cross(p - o, q - o)).sum()
1137}
1138
1139fn hot_pixels(edges: &[FixedEdge]) -> Vec<Pixel> {
1141 let mut hot: Vec<Pixel> = edges.iter().map(|e| pixel(e.a)).collect();
1142 let lines: Vec<(Fixed, Fixed)> = edges.iter().map(|e| (e.a, e.b)).collect();
1143 near_pairs(&lines, &mut Grid::default(), |i, j| {
1144 if contact(lines[i], lines[j]) == Contact::Cross {
1145 let ((p1, p2), (q1, q2)) = (lines[i], lines[j]);
1146 hot.push(crossing(p1, p2 - p1, q1, q2 - q1));
1147 }
1148 true
1149 });
1150 hot.sort_unstable_by_key(|p| (p.x, p.y));
1151 hot.dedup();
1152 hot
1153}
1154
1155#[expect(
1157 clippy::cast_possible_truncation,
1158 reason = "the crossing lies on both edges, so in i32"
1159)]
1160fn crossing(p: Fixed, d: Fixed, q: Fixed, e: Fixed) -> Pixel {
1161 let (mut num, mut den) = (cross(q - p, e), cross(d, e));
1162 if den < 0 {
1163 (num, den) = (-num, -den);
1164 }
1165 let at = |p: i64, d: i64| {
1166 let numerator = i128::from(p) * den + num * i128::from(d);
1167 let denominator = den * i128::from(ONE);
1168 round_ratio(numerator, denominator) as i32
1169 };
1170 Coord {
1171 x: at(p.x, d.x),
1172 y: at(p.y, d.y),
1173 }
1174}
1175
1176#[derive(Clone, Copy)]
1178struct Bound {
1179 n: i128,
1180 d: i128,
1181 open: bool,
1182}
1183
1184impl Bound {
1185 fn cmp(self, other: Self) -> Ordering {
1187 (self.n * other.d).cmp(&(other.n * self.d))
1188 }
1189}
1190
1191fn passes(p: Fixed, q: Fixed, h: Pixel) -> bool {
1193 let mut lo = Bound {
1194 n: 0,
1195 d: 1,
1196 open: false,
1197 };
1198 let mut hi = Bound {
1199 n: 1,
1200 d: 1,
1201 open: false,
1202 };
1203 for (p0, d, c) in [(p.x, q.x - p.x, h.x), (p.y, q.y - p.y, h.y)] {
1204 let (min, max) = (i64::from(c) * ONE - HALF, i64::from(c) * ONE + HALF);
1205 let open = c % 2 != 0;
1207 let inside = if open {
1208 min < p0 && p0 < max
1209 } else {
1210 min <= p0 && p0 <= max
1211 };
1212 let (from, to) = match d.cmp(&0) {
1213 Ordering::Equal if inside => continue,
1214 Ordering::Equal => return false,
1215
1216 Ordering::Greater => (
1217 Bound {
1218 n: (min - p0).into(),
1219 d: d.into(),
1220 open,
1221 },
1222 Bound {
1223 n: (max - p0).into(),
1224 d: d.into(),
1225 open,
1226 },
1227 ),
1228 Ordering::Less => (
1229 Bound {
1230 n: (p0 - max).into(),
1231 d: (-d).into(),
1232 open,
1233 },
1234 Bound {
1235 n: (p0 - min).into(),
1236 d: (-d).into(),
1237 open,
1238 },
1239 ),
1240 };
1241 match from.cmp(lo) {
1242 Ordering::Greater => lo = from,
1243 Ordering::Equal => lo.open |= from.open,
1244 Ordering::Less => {}
1245 }
1246 match to.cmp(hi) {
1247 Ordering::Less => hi = to,
1248 Ordering::Equal => hi.open |= to.open,
1249 Ordering::Greater => {}
1250 }
1251 }
1252 match lo.cmp(hi) {
1253 Ordering::Less => true,
1254 Ordering::Equal => !lo.open && !hi.open,
1255 Ordering::Greater => false,
1256 }
1257}
1258
1259fn net_edges(edges: &[FixedEdge], hot: &[Pixel]) -> Vec<NetEdge> {
1262 let mut frags = Vec::new();
1263 let mut path: Vec<(i128, Pixel)> = Vec::new();
1264 for &FixedEdge { a: p, b: q, winding } in edges {
1265 let (pp, pq) = (pixel(p), pixel(q));
1266 if pp == pq {
1267 continue;
1268 }
1269 let (lo, hi) = (
1270 pixel(Coord {
1271 x: p.x.min(q.x),
1272 y: p.y.min(q.y),
1273 }),
1274 pixel(Coord {
1275 x: p.x.max(q.x),
1276 y: p.y.max(q.y),
1277 }),
1278 );
1279 let from = hot.partition_point(|h| h.x < lo.x);
1280 let to = hot.partition_point(|h| h.x <= hi.x);
1281 path.clear();
1282 path.push((i128::MIN, pp));
1283 for &h in &hot[from..to] {
1284 if (lo.y..=hi.y).contains(&h.y) && h != pp && h != pq && passes(p, q, h) {
1285 path.push((dot(widen(h) * ONE - p, q - p), h));
1286 }
1287 }
1288 path.sort_unstable_by_key(|s| s.0);
1289 path.push((i128::MAX, pq));
1290 for [s, t] in path.array_windows() {
1291 let (a, b) = (s.1, t.1);
1292 frags.push(if (a.x, a.y) < (b.x, b.y) {
1293 NetEdge { a, b, winding }
1294 } else {
1295 NetEdge {
1296 a: b,
1297 b: a,
1298 winding: -winding,
1299 }
1300 });
1301 }
1302 }
1303 frags.sort_unstable_by_key(|f| (f.a.x, f.a.y, f.b.x, f.b.y));
1304 let mut net: Vec<NetEdge> = Vec::new();
1305 for f in frags {
1306 match net.last_mut() {
1307 Some(n) if n.a == f.a && n.b == f.b => n.winding += f.winding,
1308 _ => net.push(f),
1309 }
1310 }
1311 net.retain(|n| n.winding != Winding::default());
1312 net
1313}
1314
1315fn rays_up(edges: &[(Fixed, Fixed)], queries: &[Fixed], mut hit: impl FnMut(usize, usize)) {
1318 let x2 = |v: i64| 2 * v;
1319 let mut order: Vec<usize> = (0..edges.len()).filter(|&e| edges[e].0.x != edges[e].1.x).collect();
1320 order.sort_unstable_by_key(|&e| edges[e].0.x);
1321 let mut by_x: Vec<usize> = (0..queries.len()).collect();
1322 by_x.sort_unstable_by_key(|&q| queries[q].x);
1323 let mut active: Vec<usize> = Vec::new();
1324 let mut next = 0;
1325 for q in by_x {
1326 let m = queries[q];
1327 while next < order.len() && x2(edges[order[next]].0.x) <= m.x {
1328 active.push(order[next]);
1329 next += 1;
1330 }
1331 active.retain(|&e| x2(edges[e].1.x) > m.x);
1332 for &e in &active {
1333 let (l, r) = (edges[e].0 * 2, edges[e].1 * 2);
1334 if cross(r - l, m - l) < 0 {
1335 hit(q, e);
1336 }
1337 }
1338 }
1339}
1340
1341fn odd_runs(mut hits: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
1343 hits.sort_unstable();
1344 let mut odd: Vec<(usize, usize)> = Vec::new();
1345 for h in hits {
1346 if odd.last() == Some(&h) {
1347 odd.pop();
1348 } else {
1349 odd.push(h);
1350 }
1351 }
1352 odd
1353}
1354
1355fn boundary(net: &[NetEdge], inside: fn(Winding) -> bool) -> Vec<(Pixel, Pixel)> {
1357 let lines: Vec<(Fixed, Fixed)> = net.iter().map(|n| (widen(n.a), widen(n.b))).collect();
1358 let queries: Vec<Fixed> = lines.iter().map(|&(a, b)| a + b).collect();
1359 let mut above = vec![Winding::default(); net.len()];
1360 rays_up(&lines, &queries, |q, e| {
1361 if q != e {
1362 above[q] -= net[e].winding;
1363 }
1364 });
1365 let mut edges = Vec::new();
1366 for (n, w) in net.iter().zip(above) {
1367 let (left, right) = if n.a.x == n.b.x {
1368 (w + n.winding, w)
1369 } else {
1370 (w, w - n.winding)
1371 };
1372 match (inside(left), inside(right)) {
1373 (true, false) => edges.push((n.a, n.b)),
1374 (false, true) => edges.push((n.b, n.a)),
1375 _ => {}
1376 }
1377 }
1378 edges
1379}
1380
1381fn half_plane(d: Coord<i64>) -> u8 {
1383 u8::from(!(d.y > 0 || (d.y == 0 && d.x > 0)))
1384}
1385
1386fn by_angle(a: Coord<i64>, b: Coord<i64>) -> Ordering {
1388 half_plane(a).cmp(&half_plane(b)).then_with(|| 0.cmp(&cross(a, b)))
1389}
1390
1391fn trace(mut edges: Vec<(Pixel, Pixel)>) -> Vec<Vec<Pixel>> {
1394 edges.sort_unstable_by(|p, q| {
1395 (p.0.x, p.0.y)
1396 .cmp(&(q.0.x, q.0.y))
1397 .then_with(|| by_angle(widen(p.1) - widen(p.0), widen(q.1) - widen(q.0)))
1398 });
1399 let mut used = vec![false; edges.len()];
1400 let mut rings = Vec::new();
1401 let mut walk = Vec::new();
1402 for start in 0..edges.len() {
1403 if used[start] {
1404 continue;
1405 }
1406 walk.clear();
1407 let mut h = start;
1408 let closed = loop {
1409 used[h] = true;
1410 let (a, v) = edges[h];
1411 walk.push(a);
1412 let from = edges.partition_point(|e| (e.0.x, e.0.y) < (v.x, v.y));
1413 let to = edges.partition_point(|e| (e.0.x, e.0.y) <= (v.x, v.y));
1414 if from == to {
1415 break false;
1416 }
1417 let back = widen(a) - widen(v);
1418 let past =
1419 from + edges[from..to].partition_point(|e| by_angle(widen(e.1) - widen(v), back) == Ordering::Less);
1420 h = if past == from { to - 1 } else { past - 1 };
1421 if h == start {
1422 break true;
1423 }
1424 if used[h] {
1425 break false;
1426 }
1427 };
1428 if closed {
1429 split(&walk, &mut rings);
1430 }
1431 }
1432 rings
1433}
1434
1435fn split(walk: &[Pixel], rings: &mut Vec<Vec<Pixel>>) {
1437 let mut stack: Vec<Pixel> = Vec::new();
1438 let mut at: HashMap<(i32, i32), usize> = HashMap::new();
1439 for &v in walk {
1440 if let Some(&i) = at.get(&(v.x, v.y)) {
1441 let ring: Vec<Pixel> = stack.drain(i..).collect();
1442 for c in ring.iter().skip(1) {
1443 at.remove(&(c.x, c.y));
1444 }
1445 stack.push(v);
1446 if ring.len() >= 3 {
1447 rings.push(ring);
1448 }
1449 } else {
1450 at.insert((v.x, v.y), stack.len());
1451 stack.push(v);
1452 }
1453 }
1454 if stack.len() >= 3 {
1455 rings.push(stack);
1456 }
1457}