wbtopology 0.1.2

A pure-Rust topology suite inspired by JTS
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
use wbtopology::{
    buffer_linestring,
    buffer_linestring_with_precision,
    buffer_point,
    buffer_point_with_precision,
    buffer_polygon,
    buffer_polygon_multi,
    buffer_polygon_with_precision,
    contains,
    is_valid_polygon,
    make_valid_polygon,
    offset_linestring,
    polygonize_closed_linestrings,
    BufferCapStyle,
    BufferJoinStyle,
    BufferOptions,
    Coord,
    Geometry,
    LineString,
    LinearRing,
    OffsetCurveOptions,
    OffsetSide,
    PrecisionModel,
    Polygon,
};

fn ring_area_abs(coords: &[Coord]) -> f64 {
    if coords.len() < 4 {
        return 0.0;
    }
    let mut s = 0.0;
    for i in 0..(coords.len() - 1) {
        s += coords[i].x * coords[i + 1].y - coords[i + 1].x * coords[i].y;
    }
    (0.5 * s).abs()
}

#[test]
fn make_valid_polygon_drops_hole_outside_shell() {
    let poly = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![LinearRing::new(vec![
            Coord::xy(20.0, 20.0),
            Coord::xy(21.0, 20.0),
            Coord::xy(21.0, 21.0),
            Coord::xy(20.0, 21.0),
        ])],
    );

    let out = make_valid_polygon(&poly, 1.0e-9);
    assert_eq!(out.len(), 1);
    assert_eq!(out[0].holes.len(), 0);
}

#[test]
fn polygonize_closed_linestrings_builds_shell_and_hole() {
    let shell = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 10.0),
        Coord::xy(0.0, 10.0),
        Coord::xy(0.0, 0.0),
    ]);
    let hole = LineString::new(vec![
        Coord::xy(3.0, 3.0),
        Coord::xy(7.0, 3.0),
        Coord::xy(7.0, 7.0),
        Coord::xy(3.0, 7.0),
        Coord::xy(3.0, 3.0),
    ]);

    let polys = polygonize_closed_linestrings(&[shell, hole], 1.0e-9);
    assert_eq!(polys.len(), 1);
    assert_eq!(polys[0].holes.len(), 1);
}

#[test]
fn point_buffer_has_reasonable_area() {
    let p = Coord::xy(0.0, 0.0);
    let r = 2.0;
    let poly = buffer_point(
        p,
        r,
        BufferOptions {
            quadrant_segments: 16,
            ..Default::default()
        },
    );

    let area = ring_area_abs(&poly.exterior.coords);
    let exact = std::f64::consts::PI * r * r;
    let rel_err = (area - exact).abs() / exact;
    assert!(rel_err < 0.03, "relative error too high: {}", rel_err);
}

#[test]
fn make_valid_polygon_splits_simple_bow_tie() {
    let bow_tie = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(2.0, 2.0),
            Coord::xy(0.0, 2.0),
            Coord::xy(2.0, 0.0),
        ]),
        vec![],
    );

    let out = make_valid_polygon(&bow_tie, 1.0e-9);
    assert_eq!(out.len(), 2);
}

#[test]
fn make_valid_polygon_intersection_point_interpolates_z() {
    let bow_tie = Polygon::new(
        LinearRing::new(vec![
            Coord::xyz(0.0, 0.0, 0.0),
            Coord::xyz(2.0, 2.0, 20.0),
            Coord::xyz(0.0, 2.0, 40.0),
            Coord::xyz(2.0, 0.0, 60.0),
        ]),
        vec![],
    );

    let out = make_valid_polygon(&bow_tie, 1.0e-9);
    assert_eq!(out.len(), 2);

    let mut found = false;
    for poly in &out {
        for c in &poly.exterior.coords {
            if (c.x - 1.0).abs() <= 1.0e-9 && (c.y - 1.0).abs() <= 1.0e-9 {
                assert_eq!(c.z, Some(10.0));
                found = true;
            }
        }
    }
    assert!(found, "expected split intersection vertex at (1, 1)");
}

#[test]
fn linestring_buffer_with_square_caps_has_area() {
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(10.0, 0.0)]);
    let poly = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            quadrant_segments: 12,
            cap_style: BufferCapStyle::Square,
            ..Default::default()
        },
    );

    assert!(ring_area_abs(&poly.exterior.coords) > 0.0);
}

#[test]
fn polygon_buffer_grows_area_for_positive_distance() {
    let p = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(4.0, 0.0),
            Coord::xy(4.0, 4.0),
            Coord::xy(0.0, 4.0),
        ]),
        vec![],
    );
    let base = ring_area_abs(&p.exterior.coords);
    let buffered = buffer_polygon(&p, 0.5, BufferOptions::default());
    let grew = ring_area_abs(&buffered.exterior.coords);
    assert!(grew > base);
}

#[test]
fn polygon_buffer_zero_distance_preserves_simple_polygon() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(4.0, 0.0),
            Coord::xy(4.0, 4.0),
            Coord::xy(0.0, 4.0),
        ]),
        vec![],
    );

    let buf = buffer_polygon(&src, 0.0, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf.clone());

    assert!(contains(&gpoly, &Geometry::Point(Coord::xy(2.0, 2.0))));
    assert!((ring_area_abs(&buf.exterior.coords) - ring_area_abs(&src.exterior.coords)).abs() < 1.0e-9);
}

#[test]
fn polygon_buffer_negative_distance_shrinks_square() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(4.0, 0.0),
            Coord::xy(4.0, 4.0),
            Coord::xy(0.0, 4.0),
        ]),
        vec![],
    );

    let buf = buffer_polygon(&src, -0.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf.clone());

    assert!(ring_area_abs(&buf.exterior.coords) < ring_area_abs(&src.exterior.coords));
    assert!(contains(&gpoly, &Geometry::Point(Coord::xy(2.0, 2.0))));
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(0.2, 0.2))));
}

#[test]
fn make_valid_polygon_splits_triple_crossing_ring() {
    // Figure-of-eight with an extra crossing: three line segments that all
    // pass through near the origin, creating 3+ self-intersections.
    // The ring visits (0,0)→(4,4)→(0,4)→(4,0)→(2,3)→(2,0)→(0,0).
    // We just assert we get ≥1 simple polygon back, not zero.
    let star = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(4.0, 4.0),
            Coord::xy(0.0, 4.0),
            Coord::xy(4.0, 0.0),
            Coord::xy(2.0, 5.0),
            Coord::xy(2.0, -1.0),
        ]),
        vec![],
    );

    let out = make_valid_polygon(&star, 1.0e-9);
    assert!(!out.is_empty(), "expected at least one valid polygon from split");
}

#[test]
fn linestring_buffer_contains_all_source_vertices() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(5.0, 0.0),
        Coord::xy(5.0, 5.0),
    ]);
    let buf = buffer_linestring(&ls, 1.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf);

    for v in &ls.coords {
        assert!(
            contains(&gpoly, &Geometry::Point(*v)),
            "vertex {:?} not inside buffer",
            v
        );
    }
}

#[test]
fn polygon_buffer_contains_source_ring_vertices() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(1.0, 1.0),
            Coord::xy(5.0, 1.0),
            Coord::xy(5.0, 5.0),
            Coord::xy(1.0, 5.0),
        ]),
        vec![],
    );
    let buf = buffer_polygon(&src, 1.0, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf);

    for v in &src.exterior.coords {
        assert!(
            contains(&gpoly, &Geometry::Point(*v)),
            "source vertex {:?} not inside polygon buffer",
            v
        );
    }
}

#[test]
fn linestring_buffer_l_shape_does_not_fill_convex_hull_corner() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(5.0, 0.0),
        Coord::xy(5.0, 5.0),
    ]);
    let buf = buffer_linestring(&ls, 1.0, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf);

    // Distance from (3,3) to the polyline is 2.0, so it should be outside a d=1 buffer.
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(3.0, 3.0))));
}

#[test]
fn closed_linestring_buffer_preserves_interior_hole() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 6.0),
        Coord::xy(0.0, 6.0),
        Coord::xy(0.0, 0.0),
    ]);

    let buf = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Round,
            ..Default::default()
        },
    );
    let gpoly = Geometry::Polygon(buf.clone());

    assert!(is_valid_polygon(&buf));
    assert_eq!(buf.holes.len(), 1, "closed loop line buffer should retain one interior hole");
    assert!(
        !contains(&gpoly, &Geometry::Point(Coord::xy(5.0, 3.0))),
        "centre of buffered loop should remain outside due to interior hole"
    );
    assert!(
        contains(&gpoly, &Geometry::Point(Coord::xy(-0.5, 3.0))),
        "outer corridor should still exist outside the loop"
    );
}

#[test]
fn near_closed_linestring_buffer_preserves_interior_hole() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 6.0),
        Coord::xy(0.0, 6.0),
        Coord::xy(0.0, 0.00000001),
    ]);

    let buf = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Round,
            ..Default::default()
        },
    );
    let gpoly = Geometry::Polygon(buf.clone());

    assert!(is_valid_polygon(&buf));
    assert_eq!(buf.holes.len(), 1, "near-closed loop line buffer should retain one interior hole");
    assert!(
        !contains(&gpoly, &Geometry::Point(Coord::xy(5.0, 3.0))),
        "centre of near-closed buffered loop should remain outside due to interior hole"
    );
}

#[test]
fn exact_streetcentreline_loop_buffer_preserves_interior_hole() {
    let ls = LineString::new(vec![
        Coord::xy(565230.8119999999, 4817282.9957),
        Coord::xy(565228.9401000002, 4817302.0011),
        Coord::xy(565212.8797000004, 4817353.000399999),
        Coord::xy(565199.5022, 4817403.0002999995),
        Coord::xy(565195.7501999997, 4817409.500600001),
        Coord::xy(565183.3761999998, 4817410.5001),
        Coord::xy(565172.7553000003, 4817403.9997000005),
        Coord::xy(565127.1873000003, 4817371.4979),
        Coord::xy(565126.8718999997, 4817360.9999),
        Coord::xy(565129.9397999998, 4817347.5035999995),
        Coord::xy(565153.9382999996, 4817271.498199999),
        Coord::xy(565158.3740999997, 4817260.000700001),
        Coord::xy(565164.8787000002, 4817260.500399999),
        Coord::xy(565172.0630999999, 4817261.4999),
        Coord::xy(565230.8119999999, 4817282.9957),
    ]);

    let buf = buffer_linestring(
        &ls,
        15.0,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Round,
            ..Default::default()
        },
    );

    assert!(is_valid_polygon(&buf));
    assert_eq!(
        buf.holes.len(),
        1,
        "street centreline closed loop buffer should retain one interior hole"
    );
}

#[test]
fn linestring_buffer_mitre_join_extends_farther_than_bevel() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(5.0, 0.0),
        Coord::xy(5.0, 5.0),
    ]);

    let mitre = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            join_style: BufferJoinStyle::Mitre,
            ..Default::default()
        },
    );
    let bevel = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            join_style: BufferJoinStyle::Bevel,
            ..Default::default()
        },
    );

    let mitre_max_x = mitre
        .exterior
        .coords
        .iter()
        .map(|c| c.x)
        .fold(f64::NEG_INFINITY, f64::max);
    let bevel_max_x = bevel
        .exterior
        .coords
        .iter()
        .map(|c| c.x)
        .fold(f64::NEG_INFINITY, f64::max);

    assert!(mitre_max_x >= bevel_max_x);
}

#[test]
fn polygon_buffer_preserves_concavity_better_than_hull() {
    // Concave "L" polygon; point (3,3) is in the notch and far from boundary.
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(6.0, 0.0),
            Coord::xy(6.0, 2.0),
            Coord::xy(2.0, 2.0),
            Coord::xy(2.0, 6.0),
            Coord::xy(0.0, 6.0),
        ]),
        vec![],
    );

    let buf = buffer_polygon(&src, 0.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf);

    // This point was incorrectly included by old hull-based buffer.
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(3.0, 3.0))));
}

#[test]
fn polygon_buffer_shrinks_hole_for_small_distance() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![LinearRing::new(vec![
            Coord::xy(3.0, 3.0),
            Coord::xy(7.0, 3.0),
            Coord::xy(7.0, 7.0),
            Coord::xy(3.0, 7.0),
        ])],
    );

    let buf = buffer_polygon(&src, 0.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf.clone());

    // Point just outside original hole should become filled after shrink.
    assert!(contains(&gpoly, &Geometry::Point(Coord::xy(3.2, 5.0))));
    // Hole center should still be excluded for small buffer distance.
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(5.0, 5.0))));
    assert_eq!(buf.holes.len(), 1);
}

#[test]
fn polygon_buffer_drops_hole_when_it_collapses() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![LinearRing::new(vec![
            Coord::xy(3.0, 3.0),
            Coord::xy(7.0, 3.0),
            Coord::xy(7.0, 7.0),
            Coord::xy(3.0, 7.0),
        ])],
    );

    let buf = buffer_polygon(&src, 2.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf.clone());

    // Hole width is 4.0, so shrinking by 2.5 should remove it.
    assert!(contains(&gpoly, &Geometry::Point(Coord::xy(5.0, 5.0))));
    assert!(buf.holes.is_empty());
}

#[test]
fn polygon_buffer_negative_distance_expands_hole() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![LinearRing::new(vec![
            Coord::xy(4.0, 4.0),
            Coord::xy(6.0, 4.0),
            Coord::xy(6.0, 6.0),
            Coord::xy(4.0, 6.0),
        ])],
    );

    let buf = buffer_polygon(&src, -0.5, BufferOptions::default());
    let gpoly = Geometry::Polygon(buf.clone());

    assert_eq!(buf.holes.len(), 1);
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(3.75, 5.0))));
    assert!(!contains(&gpoly, &Geometry::Point(Coord::xy(5.0, 5.0))));
    assert!(contains(&gpoly, &Geometry::Point(Coord::xy(2.0, 2.0))));
}

#[test]
fn polygon_buffer_negative_distance_returns_empty_when_hole_consumes_shell() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![LinearRing::new(vec![
            Coord::xy(4.0, 4.0),
            Coord::xy(6.0, 4.0),
            Coord::xy(6.0, 6.0),
            Coord::xy(4.0, 6.0),
        ])],
    );

    let buf = buffer_polygon(&src, -2.0, BufferOptions::default());
    assert!(buf.exterior.coords.is_empty());
}

#[test]
fn linestring_buffer_sharp_angle_is_valid_polygon() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(4.0, 0.0),
        Coord::xy(4.2, 5.0),
    ]);

    let buf = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Mitre,
            ..Default::default()
        },
    );

    assert!(is_valid_polygon(&buf));
}

#[test]
fn linestring_buffer_round_sharp_angle_keeps_outer_arc_and_inner_corridor() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(4.0, 0.0),
        Coord::xy(4.2, 5.0),
    ]);

    let buf = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Round,
            ..Default::default()
        },
    );
    let gpoly = Geometry::Polygon(buf.clone());

    assert!(is_valid_polygon(&buf));
    assert!(
        contains(&gpoly, &Geometry::Point(Coord::xy(3.28, 0.69))),
        "outer round-join lobe near the sharp bend should be preserved"
    );
    assert!(
        contains(&gpoly, &Geometry::Point(Coord::xy(4.80, -0.60))),
        "inner corridor near the sharp bend should not be clipped away"
    );
}

#[test]
fn polygon_buffer_sharp_concavity_is_valid_polygon() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(8.0, 0.0),
            Coord::xy(8.0, 1.0),
            Coord::xy(1.2, 1.0),
            Coord::xy(1.0, 8.0),
            Coord::xy(0.0, 8.0),
        ]),
        vec![],
    );

    let buf = buffer_polygon(
        &src,
        0.8,
        BufferOptions {
            quadrant_segments: 12,
            join_style: BufferJoinStyle::Round,
            ..Default::default()
        },
    );

    assert!(is_valid_polygon(&buf));
}

#[test]
fn linestring_buffer_mitre_limit_clamps_spike_extent() {
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(5.0, 0.0),
        Coord::xy(5.5, 5.0),
    ]);

    let high = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            join_style: BufferJoinStyle::Mitre,
            mitre_limit: 10.0,
            ..Default::default()
        },
    );
    let low = buffer_linestring(
        &ls,
        1.0,
        BufferOptions {
            join_style: BufferJoinStyle::Mitre,
            mitre_limit: 1.2,
            ..Default::default()
        },
    );

    let high_max_x = high
        .exterior
        .coords
        .iter()
        .map(|c| c.x)
        .fold(f64::NEG_INFINITY, f64::max);
    let low_max_x = low
        .exterior
        .coords
        .iter()
        .map(|c| c.x)
        .fold(f64::NEG_INFINITY, f64::max);

    assert!(high_max_x >= low_max_x);
}

#[test]
fn precision_aware_buffer_snaps_output_grid() {
    let pm = PrecisionModel::Fixed { scale: 10.0 }; // 0.1 grid

    let point_buf = buffer_point_with_precision(
        Coord::xy(0.03, 0.07),
        1.0,
        BufferOptions::default(),
        pm,
    );

    for c in &point_buf.exterior.coords {
        let sx = c.x * 10.0;
        let sy = c.y * 10.0;
        assert!((sx - sx.round()).abs() < 1.0e-9);
        assert!((sy - sy.round()).abs() < 1.0e-9);
    }

    let ls = LineString::new(vec![Coord::xy(0.02, 0.03), Coord::xy(5.07, 0.04)]);
    let _ = buffer_linestring_with_precision(&ls, 0.5, BufferOptions::default(), pm);

    let poly = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.01, 0.01),
            Coord::xy(2.09, 0.01),
            Coord::xy(2.09, 2.09),
            Coord::xy(0.01, 2.09),
        ]),
        vec![],
    );
    let _ = buffer_polygon_with_precision(&poly, 0.3, BufferOptions::default(), pm);
}

// --- buffer_polygon_multi tests ---

#[test]
fn buffer_polygon_multi_positive_distance_returns_single_polygon() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(4.0, 0.0),
            Coord::xy(4.0, 4.0),
            Coord::xy(0.0, 4.0),
        ]),
        vec![],
    );
    let result = buffer_polygon_multi(&src, 1.0, BufferOptions::default());
    assert_eq!(result.len(), 1);
    // Expanded shell must be larger than the original 4x4 square.
    assert!(ring_area_abs(&result[0].exterior.coords) > 16.0);
}

#[test]
fn buffer_polygon_multi_zero_distance_returns_repaired_copy() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(6.0, 0.0),
            Coord::xy(6.0, 6.0),
            Coord::xy(0.0, 6.0),
        ]),
        vec![],
    );
    let result = buffer_polygon_multi(&src, 0.0, BufferOptions::default());
    assert_eq!(result.len(), 1);
    let area = ring_area_abs(&result[0].exterior.coords);
    assert!((area - 36.0).abs() < 0.1);
}

#[test]
fn buffer_polygon_multi_negative_distance_shrinks_square() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![],
    );
    let result = buffer_polygon_multi(&src, -1.0, BufferOptions::default());
    assert_eq!(result.len(), 1);
    // Eroded 10x10 square by 1 unit all sides -> roughly 8x8 = 64.
    let area = ring_area_abs(&result[0].exterior.coords);
    assert!(area > 60.0 && area < 68.0);
}

#[test]
fn buffer_polygon_multi_negative_fully_eroded_returns_empty() {
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(2.0, 0.0),
            Coord::xy(2.0, 2.0),
            Coord::xy(0.0, 2.0),
        ]),
        vec![],
    );
    // Erosion by more than the inradius of the square.
    let result = buffer_polygon_multi(&src, -2.0, BufferOptions::default());
    assert!(result.is_empty());
}

#[test]
fn buffer_polygon_multi_simple_concave_erosion_stays_single_component() {
    // An L-shaped polygon: mild erosion shrinks it but does not split it.
    let src = Polygon::new(
        LinearRing::new(vec![
            Coord::xy(0.0, 0.0),
            Coord::xy(10.0, 0.0),
            Coord::xy(10.0, 6.0),
            Coord::xy(6.0, 6.0),
            Coord::xy(6.0, 10.0),
            Coord::xy(0.0, 10.0),
        ]),
        vec![],
    );
    let result = buffer_polygon_multi(&src, -0.5, BufferOptions::default());
    assert_eq!(result.len(), 1);
    assert!(ring_area_abs(&result[0].exterior.coords) > 0.0);
}

#[test]
fn buffer_polygon_multi_returns_components_for_deeply_eroded_h_shape() {
    // An H-shape can split into two rectangles under sufficient erosion of the
    // narrow connecting bar.  The outer box is 30x20; two rectangular notches
    // cut from the left and right sides leave only a 4-unit-wide central bar.
    //
    //  +---------+   +---------+
    //  |         |   |         |
    //  |  left   +---+  right  |
    //  |  notch     bar notch  |
    //  |         +---+         |
    //  |         |   |         |
    //  +---------+   +---------+
    //
    // Outer box 30x20.
    let outer = LinearRing::new(vec![
        Coord::xy(0.0,  0.0),
        Coord::xy(30.0, 0.0),
        Coord::xy(30.0, 20.0),
        Coord::xy(0.0,  20.0),
    ]);
    // Left notch hole removes columns 0-13, rows 6-14 (8-unit-wide slot).
    let left_notch = LinearRing::new(vec![
        Coord::xy(0.0,  6.0),
        Coord::xy(13.0, 6.0),
        Coord::xy(13.0, 14.0),
        Coord::xy(0.0,  14.0),
    ]);
    // Right notch hole removes columns 17-30, rows 6-14.
    let right_notch = LinearRing::new(vec![
        Coord::xy(17.0, 6.0),
        Coord::xy(30.0, 6.0),
        Coord::xy(30.0, 14.0),
        Coord::xy(17.0, 14.0),
    ]);
    let src = Polygon::new(outer, vec![left_notch, right_notch]);

    // Eroding by 3 units consumes the 4-unit-wide bar (inradius ~2), leaving
    // two separate side rectangles.
    let result = buffer_polygon_multi(&src, -3.0, BufferOptions::default());

    // At least one component must survive.
    assert!(!result.is_empty());
    // Every surviving component must have non-trivial area.
    for comp in &result {
        assert!(ring_area_abs(&comp.exterior.coords) > 1.0);
    }
}

// Regression test: buffer of a real-world concave building footprint (CW ring
// from an ESRI shapefile) must produce a polygon that fully contains the source
// polygon and extends to roughly distance=5 on all sides.
#[test]
fn buffer_problem_building_cw_ring() {
    // CW ring as read from ESRI shapefile (negative signed area).
    // IMPORTANT: shapefile exterior rings are CW; wbtopology must handle them.
    let coords = vec![
        Coord::xy(562637.537417164, 4818648.0372987),
        Coord::xy(562644.815914335, 4818647.60529134),
        Coord::xy(562644.928259569, 4818649.42786198),
        Coord::xy(562654.188202102, 4818648.86993476),
        Coord::xy(562653.642237858, 4818639.80165489),
        Coord::xy(562650.180841506, 4818640.01375644),
        Coord::xy(562649.83002479,  4818634.29045826),
        Coord::xy(562638.621044375, 4818634.96351884),
        Coord::xy(562638.991254563, 4818641.20901904),
        Coord::xy(562637.131244156, 4818641.31386885),
        Coord::xy(562637.537417164, 4818648.0372987),  // closing vertex
    ];
    let poly = Polygon::new(LinearRing::new(coords), vec![]);
    let distance = 5.0;
    let options = BufferOptions {
        quadrant_segments: 8,
        cap_style: BufferCapStyle::Round,
        join_style: BufferJoinStyle::Round,
        mitre_limit: 5.0,
    };

    // The result must be a single polygon (one component).
    let result = buffer_polygon_multi(&poly, distance, options);
    assert_eq!(result.len(), 1, "Expected 1 buffer component, got {}", result.len());

    let buf = &result[0];
    // The buffer must be valid.
    assert!(is_valid_polygon(buf), "Buffer polygon is invalid");

    // The buffer must extend to roughly distance=5 on all sides of the input bbox.
    // Input bbox: x=[562637.131, 562654.188], y=[4818634.290, 4818649.428]
    let min_x = buf.exterior.coords.iter().map(|c| c.x).fold(f64::INFINITY, f64::min);
    let max_x = buf.exterior.coords.iter().map(|c| c.x).fold(f64::NEG_INFINITY, f64::max);
    let min_y = buf.exterior.coords.iter().map(|c| c.y).fold(f64::INFINITY, f64::min);
    let max_y = buf.exterior.coords.iter().map(|c| c.y).fold(f64::NEG_INFINITY, f64::max);

    // Should extend at least 4m outward on every side (allow minor rounding).
    assert!(min_x < 562637.131 - 4.0, "Buffer too narrow on left: min_x={}", min_x);
    assert!(max_x > 562654.188 + 4.0, "Buffer too narrow on right: max_x={}", max_x);
    assert!(min_y < 4818634.290 - 4.0, "Buffer too narrow on bottom: min_y={}", min_y);
    assert!(max_y > 4818649.428 + 4.0, "Buffer too narrow on top: max_y={}", max_y);
    let buf_area = ring_area_abs(&buf.exterior.coords);
    assert!(buf_area > 400.0, "Buffer area {} too small (source ~201 m²)", buf_area);
}

// ── offset_linestring tests ─────────────────────────────────────────────────

#[test]
fn offset_linestring_left_horizontal() {
    // Horizontal line along x-axis; left side at distance 3.0 should be y=3.
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(10.0, 0.0)]);
    let opts = OffsetCurveOptions::default();
    let result = offset_linestring(&ls, 3.0, OffsetSide::Left, opts);
    assert_eq!(result.coords.len(), 2, "Expected 2 coords for simple horizontal line");
    for c in &result.coords {
        assert!((c.y - 3.0).abs() < 1.0e-9, "Left offset of horizontal line should have y≈3, got {}", c.y);
    }
    assert!((result.coords[0].x - 0.0).abs() < 1.0e-9);
    assert!((result.coords[1].x - 10.0).abs() < 1.0e-9);
}

#[test]
fn offset_linestring_right_horizontal() {
    // Horizontal line; right side at distance 3.0 should be y=-3.
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(10.0, 0.0)]);
    let opts = OffsetCurveOptions::default();
    let result = offset_linestring(&ls, 3.0, OffsetSide::Right, opts);
    assert_eq!(result.coords.len(), 2);
    for c in &result.coords {
        assert!((c.y - (-3.0)).abs() < 1.0e-9, "Right offset should have y≈-3, got {}", c.y);
    }
}

#[test]
fn offset_linestring_returns_open_not_closed() {
    // Result must be an open linestring (first ≠ last).
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 10.0),
    ]);
    let result = offset_linestring(&ls, 2.0, OffsetSide::Left, OffsetCurveOptions::default());
    assert!(result.coords.len() >= 2, "Result should have at least 2 coords");
    let first = result.coords.first().unwrap();
    let last  = result.coords.last().unwrap();
    let dist2 = (first.x - last.x).powi(2) + (first.y - last.y).powi(2);
    assert!(dist2 > 1.0e-6, "Offset linestring should be open (first ≠ last)");
}

#[test]
fn offset_linestring_preserves_direction() {
    // Left offset of a north-going line should be to the west (negative x).
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(0.0, 10.0)]);
    let result = offset_linestring(&ls, 2.0, OffsetSide::Left, OffsetCurveOptions::default());
    assert_eq!(result.coords.len(), 2);
    for c in &result.coords {
        assert!(c.x < -1.9, "Left of north-going line should be west (x < 0), got {}", c.x);
    }
}

#[test]
fn offset_linestring_right_preserves_direction() {
    // Right offset of a north-going line should be to the east (positive x).
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(0.0, 10.0)]);
    let result = offset_linestring(&ls, 2.0, OffsetSide::Right, OffsetCurveOptions::default());
    assert_eq!(result.coords.len(), 2);
    for c in &result.coords {
        assert!(c.x > 1.9, "Right of north-going line should be east (x > 0), got {}", c.x);
    }
}

#[test]
fn offset_linestring_mitre_join_style() {
    // L-shaped line; Mitre join should produce a single sharp corner point.
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 10.0),
    ]);
    let opts = OffsetCurveOptions {
        join_style: BufferJoinStyle::Mitre,
        ..Default::default()
    };
    let result = offset_linestring(&ls, 2.0, OffsetSide::Left, opts);
    // 3 input points → 3 output points with Mitre (no arc insertion).
    assert_eq!(result.coords.len(), 3, "Mitre join should produce 3 coords, got {}", result.coords.len());
}

#[test]
fn offset_linestring_round_join_adds_arc_vertices() {
    // L-shaped line; Round join should produce more than 3 output coords.
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(10.0, 10.0),
    ]);
    let opts = OffsetCurveOptions {
        join_style: BufferJoinStyle::Round,
        quadrant_segments: 8,
        ..Default::default()
    };
    let result = offset_linestring(&ls, 2.0, OffsetSide::Left, opts);
    assert!(result.coords.len() > 3, "Round join should insert arc vertices (got {})", result.coords.len());
}

#[test]
fn offset_linestring_zero_distance_returns_empty() {
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(10.0, 0.0)]);
    let result = offset_linestring(&ls, 0.0, OffsetSide::Left, OffsetCurveOptions::default());
    assert!(result.coords.is_empty(), "Zero distance should return empty linestring");
}

#[test]
fn offset_linestring_negative_distance_returns_empty() {
    let ls = LineString::new(vec![Coord::xy(0.0, 0.0), Coord::xy(10.0, 0.0)]);
    let result = offset_linestring(&ls, -1.0, OffsetSide::Left, OffsetCurveOptions::default());
    assert!(result.coords.is_empty(), "Negative distance should return empty linestring");
}

#[test]
fn offset_linestring_single_point_returns_empty() {
    let ls = LineString::new(vec![Coord::xy(5.0, 5.0)]);
    let result = offset_linestring(&ls, 1.0, OffsetSide::Left, OffsetCurveOptions::default());
    assert!(result.coords.is_empty(), "Single-point input should return empty linestring");
}

#[test]
fn offset_linestring_multipoint_preserves_vertex_count_mitre() {
    // 5-point path with Mitre joins should produce exactly 5 output coords.
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 5.0),
        Coord::xy(20.0, 0.0),
        Coord::xy(30.0, 5.0),
        Coord::xy(40.0, 0.0),
    ]);
    let opts = OffsetCurveOptions {
        join_style: BufferJoinStyle::Mitre,
        ..Default::default()
    };
    let result = offset_linestring(&ls, 2.0, OffsetSide::Left, opts);
    assert_eq!(result.coords.len(), 5, "5-point path with Mitre should have 5 output coords, got {}", result.coords.len());
}

#[test]
fn offset_linestring_left_right_symmetric_about_centreline() {
    // For a horizontal line the left and right offsets should be mirror images
    // about y=0 (i.e. left.y == -right.y for corresponding coords).
    let ls = LineString::new(vec![
        Coord::xy(0.0, 0.0),
        Coord::xy(10.0, 0.0),
        Coord::xy(20.0, 0.0),
    ]);
    let opts = OffsetCurveOptions { join_style: BufferJoinStyle::Mitre, ..Default::default() };
    let left  = offset_linestring(&ls, 3.0, OffsetSide::Left,  opts);
    let right = offset_linestring(&ls, 3.0, OffsetSide::Right, opts);
    assert_eq!(left.coords.len(), right.coords.len(), "Left and right should have same vertex count");
    for (l, r) in left.coords.iter().zip(right.coords.iter()) {
        assert!((l.x - r.x).abs() < 1.0e-9, "x-coords should match: {} vs {}", l.x, r.x);
        assert!((l.y + r.y).abs() < 1.0e-9, "left.y + right.y should be 0: {} + {}", l.y, r.y);
    }
}