pyrucast 0.14.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//! Frontal paving of a closed contour into quadrangles.
//!
//! Where [`triangulate_surface`](fn@super::triangulate_surface) triangulates by
//! constrained Delaunay and can only *recombine* triangles into quadrangles
//! afterwards, `pave_surface` lays quadrangles down directly, in rows walking
//! inward from the boundary. That is the whole point: the rows follow the
//! contour, which is where finite-element accuracy is usually decided, and the
//! result is quadrangular by construction rather than by luck of pairing.
//!
//! Pipeline per domain (one outer counter-clockwise loop and its clockwise
//! holes, parsed by `contour`):
//!
//! 1. Seed the advancing front with the domain's boundary loops.
//! 2. Lay a whole row of quadrangles along a loop (`paving::row`): each
//!    front node is given as many quadrangles as its interior angle asks for,
//!    at the local element size.
//! 3. Refuse and retreat if the row would produce a quadrangle that is not
//!    strictly convex, or edges that cross the front. Every such test runs on
//!    the exact predicates of `predicates`.
//! 4. Seam front nodes that have come within touching distance — which splits
//!    a loop where the domain is concave and joins two loops where a hole is
//!    being swallowed.
//! 5. Close small loops with quadrangles (`paving::close`).
//! 6. Smooth, under a validity guard that never moves a contour node.
//!
//! A 3-D contour is fitted to its best plane, paved there, and lifted back.
//!
//! ## The contour is untouchable
//!
//! Every node of the contour comes back in the mesh, at its own position, and
//! **no node is ever added on a boundary edge**. The boundary discretisation
//! is the caller's: it usually carries the boundary conditions, and a node
//! silently inserted in the middle of a segment would be a node nobody asked
//! for. Nothing in the paver may split a boundary edge, and the seam — the one
//! operation that discards a node — refuses to discard a contour one.
//!
//! The corollary is that a contour the paver cannot work with is reported, not
//! worked around. There are two such cases and both come back as an error
//! naming the problem:
//!
//! - `prefer_quads` on a loop with an **odd** number of segments. A polygon with
//!   an odd number of sides has no filling by quadrangles alone, paving
//!   provably cannot change that parity — a row preserves it, a seam removes
//!   two nodes — and evening the count out would mean adding a boundary node.
//! - a contour so coarse or so uneven for the requested size that the
//!   advancing front **folds onto itself**, leaving a region that cannot be
//!   filled. The error names where.
//!
//! Left to itself (`prefer_quads = false`) an odd loop simply costs one triangle,
//! returned in a separate `TRI3` submesh, along with the few cells a distorted
//! leftover polygon could not make square — the closure prefers a pair of
//! triangles to a cell with a negative Jacobian, and validity is never traded
//! away.
//!
//! `prefer_quads` removes the first kind of triangle, not the second. The odd
//! loop is the caller's input, so it is refused and can be fixed; a distorted
//! leftover polygon is born inside the paving, and is still closed by
//! triangles. Fewer triangles, then — none is not promised.

use crate::atoms::ElementType;
use crate::containers::mesh::Mesh;
use crate::error::{PyrucastError, Result};
use crate::interrupt::{Cancel, NoCancel};
use crate::ops::mesh::paving::FrontRelax;
use crate::ops::mesh::{contour, paving};

/// Pave the interior of `contour` — one or more closed `SEG2` loops, counter-
/// clockwise outer and clockwise holes, per [`super::border()`]'s convention —
/// with `element_type` cells.
///
/// `element_type` is `QUA4`, `QUA8` or `QUA9`; the quadratic forms are derived
/// from the `QUA4` mesh. `target_size` sets the wanted edge length, `None`
/// takes each domain's mean boundary edge length. `prefer_quads` refuses a
/// boundary loop of odd length — the caller's to fix — and keeps the front even
/// all the way in; a few triangles may still be left where a quadrangle would
/// come out inverted, so it is a preference, not a guarantee.
///
/// Contour nodes are reused as they are and never moved. The result carries a
/// `QUA4` submesh and, only when triangles were left over, a `TRI3` one.
///
/// This is the uninterruptible convenience form; for a long mesh a caller may
/// want to stop early, use [`pave_surface_cancellable`].
///
///
/// `relax` chooses what the front may do to itself between two rows — see
/// [`FrontRelax`]. The default, [`FrontRelax::Free`], is the historical
/// behaviour; [`FrontRelax::Along`] keeps the front's corners, which is what
/// lets a rectilinear domain stay structured to its core.
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let cote = |a: &[f64], b: &[f64]| mesh::line(
/// #     &Node::create_in(coords.clone(), a).unwrap(),
/// #     &Node::create_in(coords.clone(), b).unwrap(), 2, ElementType::SEG2).unwrap();
/// # let quatre = cote(&[0.0, 0.0], &[2.0, 0.0])
/// #     .union(&cote(&[2.0, 0.0], &[2.0, 2.0])).unwrap()
/// #     .union(&cote(&[2.0, 2.0], &[0.0, 2.0])).unwrap()
/// #     .union(&cote(&[0.0, 2.0], &[0.0, 0.0])).unwrap();
/// # mesh::merge_nodes(&quatre, 1e-6, true).unwrap();
/// # let contour = mesh::consolidate(&quatre).unwrap();
/// // Frontal paving: quadrangles laid in rows that follow the
/// // contour, rather than triangles paired afterwards.
/// let m = mesh::pave_surface(&contour, ElementType::QUA4, Some(0.5), false, mesh::FrontRelax::Free)?;
/// assert!(m.cell_count() > 0);
/// // `prefer_quads` demands that nothing stay triangular — which is not
/// // possible que si le contour a un nombre **pair** de segments.
/// assert!(mesh::pave_surface(&contour, ElementType::QUA4, Some(0.5), true, mesh::FrontRelax::Free).is_ok());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn pave_surface(
    contour: &Mesh,
    element_type: ElementType,
    target_size: Option<f64>,
    prefer_quads: bool,
    relax: FrontRelax,
) -> Result<Mesh> {
    pave_surface_cancellable(
        contour,
        element_type,
        target_size,
        prefer_quads,
        relax,
        &NoCancel,
    )
}

/// Like [`pave_surface`], but polls `cancel` between rows so meshing can be
/// stopped early (returning [`PyrucastError::Interrupted`]).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let cote = |a: &[f64], b: &[f64]| mesh::line(
/// #     &Node::create_in(coords.clone(), a).unwrap(),
/// #     &Node::create_in(coords.clone(), b).unwrap(), 2, ElementType::SEG2).unwrap();
/// # let quatre = cote(&[0.0, 0.0], &[2.0, 0.0])
/// #     .union(&cote(&[2.0, 0.0], &[2.0, 2.0])).unwrap()
/// #     .union(&cote(&[2.0, 2.0], &[0.0, 2.0])).unwrap()
/// #     .union(&cote(&[0.0, 2.0], &[0.0, 0.0])).unwrap();
/// # mesh::merge_nodes(&quatre, 1e-6, true).unwrap();
/// # let contour = mesh::consolidate(&quatre).unwrap();
/// # use std::sync::atomic::{AtomicBool, Ordering};
/// // The token is polled at the mesher's checkpoints: armed in advance, the
/// // call stops at the first of them.
/// let stop = AtomicBool::new(true);
/// assert!(mesh::pave_surface_cancellable(
///     &contour, ElementType::QUA4, Some(0.5), false, mesh::FrontRelax::Free, &stop).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn pave_surface_cancellable(
    contour: &Mesh,
    element_type: ElementType,
    target_size: Option<f64>,
    prefer_quads: bool,
    relax: FrontRelax,
    cancel: &dyn Cancel,
) -> Result<Mesh> {
    if !matches!(
        element_type,
        ElementType::QUA4 | ElementType::QUA8 | ElementType::QUA9
    ) {
        return Err(PyrucastError::Message(format!(
            "pave_surface: element_type must be QUA4, QUA8 or QUA9, got {element_type}"
        )));
    }
    if let Some(h) = target_size
        && (h <= 0.0 || h.is_nan())
    {
        return Err(PyrucastError::Message(format!(
            "pave_surface: target_size must be > 0, got {h}"
        )));
    }

    let parsed = contour::parse(contour, "pave_surface")?;
    let mut fabrics = Vec::with_capacity(parsed.domains.len());
    for d in &parsed.domains {
        fabrics.push(paving::pave(
            d,
            target_size,
            prefer_quads,
            relax,
            cancel,
            "pave_surface",
        )?);
    }

    let qua4 = paving::materialize(&parsed, fabrics, "pave_surface")?;
    // The quad family only; the up-front validation above already rejected
    // anything else, so the error arm is unreachable here.
    super::sweep::finish_surface(qua4, element_type, "pave_surface")
}

// ─── Unit tests ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::{Node, NodeId, Point2};
    use crate::containers::mesh::SubMesh;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::named::Named;
    use std::collections::HashMap;
    use std::sync::atomic::AtomicBool;

    /// A closed SEG2 loop through `pts`, in the order given.
    fn loop_mesh(coords: crate::handle::Handle<Coords>, pts: &[(f64, f64)]) -> Mesh {
        let ids: Vec<NodeId> = pts
            .iter()
            .map(|&(x, y)| Node::create_in(coords.clone(), &[x, y]).unwrap().id())
            .collect();
        let mut sm = SubMesh::new(coords, ElementType::SEG2);
        let n = ids.len();
        for i in 0..n {
            sm.add_cell(&[ids[i], ids[(i + 1) % n]]).unwrap();
        }
        Mesh::from_submesh(sm)
    }

    fn rect_loop(w: f64, h: f64, nx: usize, ny: usize) -> Vec<(f64, f64)> {
        let mut v = Vec::new();
        for i in 0..nx {
            v.push((w * i as f64 / nx as f64, 0.0));
        }
        for i in 0..ny {
            v.push((w, h * i as f64 / ny as f64));
        }
        for i in 0..nx {
            v.push((w - w * i as f64 / nx as f64, h));
        }
        for i in 0..ny {
            v.push((0.0, h - h * i as f64 / ny as f64));
        }
        v
    }

    fn circle_loop(cx: f64, cy: f64, r: f64, n: usize, clockwise: bool) -> Vec<(f64, f64)> {
        (0..n)
            .map(|i| {
                let mut t = i as f64 / n as f64 * std::f64::consts::TAU;
                if clockwise {
                    t = -t;
                }
                (cx + r * t.cos(), cy + r * t.sin())
            })
            .collect()
    }

    /// Cell counts, areas and the conformity of the produced mesh.
    struct Report {
        quads: usize,
        tris: usize,
        area: f64,
        min_quality: f64,
        non_conforming: usize,
        /// Edges carried by one cell only. A sound mesh has exactly the
        /// contour's, so anything more is a hole in the middle of it.
        boundary: usize,
    }

    fn inspect(mesh: &Mesh) -> Report {
        use crate::ops::mesh::paving::geom::{orient, quad_quality, tri_quality};
        let coords = mesh.coords().unwrap();
        let c = coords.read();
        let at = |id: NodeId| {
            let v = c.position(id).unwrap();
            Point2::new(v[0], v[1])
        };
        let mut r = Report {
            quads: 0,
            tris: 0,
            area: 0.0,
            min_quality: f64::INFINITY,
            non_conforming: 0,
            boundary: 0,
        };
        let mut edges: HashMap<(NodeId, NodeId), usize> = HashMap::new();
        let mut bump = |a: NodeId, b: NodeId| {
            let k = if a.0 < b.0 { (a, b) } else { (b, a) };
            *edges.entry(k).or_insert(0) += 1;
        };
        for sm in mesh {
            let s = sm.read();
            let npc = s.element_type().nodes_per_cell();
            for cell in s.connectivity().chunks(npc) {
                for i in 0..npc {
                    bump(cell[i], cell[(i + 1) % npc]);
                }
                let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
                if npc == 4 {
                    r.quads += 1;
                    r.area += 0.5 * (orient(p[0], p[1], p[2]) + orient(p[0], p[2], p[3]));
                    r.min_quality = r.min_quality.min(quad_quality([p[0], p[1], p[2], p[3]]));
                } else {
                    r.tris += 1;
                    r.area += 0.5 * orient(p[0], p[1], p[2]);
                    r.min_quality = r.min_quality.min(tri_quality(p[0], p[1], p[2]));
                }
            }
        }
        r.non_conforming = edges.values().filter(|&&v| v > 2).count();
        r.boundary = edges.values().filter(|&&v| v == 1).count();
        r
    }

    #[test]
    fn a_square_is_paved_with_quadrangles_only() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 8, 8));
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.125),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let r = inspect(&mesh);
        assert_eq!(r.tris, 0, "{} quads, {} tris", r.quads, r.tris);
        assert!((r.area - 1.0).abs() < 1e-9, "area {}", r.area);
        assert_eq!(r.non_conforming, 0);
        assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
    }

    /// A closed loop of points, cut into whole cells.
    type Loop = Vec<(f64, f64)>;

    /// A rectangular frame: the outer wall, and a crenellated inner boundary
    /// as a hole. The shape a box wall has, and where the front runs into
    /// itself along a straight boundary.
    fn crenellated_frame(
        width: f64,
        height: f64,
        inset: f64,
        teeth: usize,
        tooth_w: f64,
        tooth_d: f64,
        h: f64,
    ) -> (Loop, Loop) {
        let cut = |corners: &[(f64, f64)]| {
            let mut pts: Loop = Vec::new();
            let n = corners.len();
            for i in 0..n {
                let (a, b) = (corners[i], corners[(i + 1) % n]);
                let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
                let k = ((len / h).round() as usize).max(1);
                for j in 0..k {
                    let t = j as f64 / k as f64;
                    pts.push((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)));
                }
            }
            pts
        };
        let outer = cut(&[(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)]);
        let mut inner = vec![(inset, inset)];
        let pitch = (width - 2.0 * inset) / teeth as f64;
        for i in 0..teeth {
            let x0 = inset + pitch * i as f64 + 0.5 * (pitch - tooth_w);
            inner.extend([
                (x0, inset),
                (x0, inset - tooth_d),
                (x0 + tooth_w, inset - tooth_d),
                (x0 + tooth_w, inset),
            ]);
        }
        inner.extend([
            (width - inset, inset),
            (width - inset, height - inset),
            (inset, height - inset),
        ]);
        let mut inner = cut(&inner);
        inner.reverse();
        (outer, inner)
    }

    /// Area of every cell carrying one of `loop_pts`' segments, smallest
    /// first — the layer the front laid straight onto that boundary.
    fn wall_layer(mesh: &Mesh, loop_pts: &[(f64, f64)]) -> Vec<f64> {
        let bits = |x: f64, y: f64| (x.to_bits(), y.to_bits());
        let n = loop_pts.len();
        let mut wall: std::collections::HashSet<((u64, u64), (u64, u64))> = Default::default();
        for i in 0..n {
            let (a, b) = (loop_pts[i], loop_pts[(i + 1) % n]);
            let (x, y) = (bits(a.0, a.1), bits(b.0, b.1));
            wall.insert(if x < y { (x, y) } else { (y, x) });
        }
        let coords = mesh.coords().unwrap();
        let c = coords.read();
        let mut out = Vec::new();
        for sm in mesh {
            let s = sm.read();
            let npc = s.element_type().nodes_per_cell();
            for cell in s.connectivity().chunks(npc) {
                let p: Vec<Point2> = cell
                    .iter()
                    .map(|&id| {
                        let v = c.position(id).unwrap();
                        Point2::new(v[0], v[1])
                    })
                    .collect();
                let touches = (0..npc).any(|i| {
                    let (u, v) = (p[i], p[(i + 1) % npc]);
                    let (x, y) = (bits(u.x, u.y), bits(v.x, v.y));
                    wall.contains(&if x < y { (x, y) } else { (y, x) })
                });
                if touches {
                    let a: f64 = (0..npc)
                        .map(|i| p[i].x * p[(i + 1) % npc].y - p[(i + 1) % npc].x * p[i].y)
                        .sum();
                    out.push(0.5 * a.abs());
                }
            }
        }
        out.sort_by(|a, b| a.partial_cmp(b).unwrap());
        out
    }

    #[test]
    fn every_boundary_gets_its_first_row_before_any_gets_a_second() {
        // The worklist of loops still to advance is a stack, so a loop that
        // has just been advanced is taken up again at once and driven all the
        // way in. On a domain with more than one boundary that means the last
        // loop seeded sweeps the whole thing, and the outer contour only gets
        // its first row once the other front is already half a cell from it.
        // That row is then squeezed into what is left — a lens of cells a
        // fifth of the height asked for, laid flat against the boundary that
        // should have carried the cleanest row of the mesh.
        //
        // Seeding first costs nothing: the same rows, in a different order.
        // Measured on the wall of this frame, the smallest cell touching the
        // outer contour went from a quarter of the target area to three
        // quarters of it.
        let h = 1.0;
        for (w, height, inset, teeth, tw, td) in [
            (16.0, 10.0, 3.0, 5, 1.4, 1.5),
            (24.0, 14.0, 4.0, 6, 1.8, 1.5),
        ] {
            let (outer, inner) = crenellated_frame(w, height, inset, teeth, tw, td, h);
            let coords = Handle::new(Coords::new(2).unwrap());
            let contour = loop_mesh(coords.clone(), &outer)
                .union(&loop_mesh(coords, &inner))
                .unwrap();
            let mesh = pave_surface(
                &contour,
                ElementType::QUA4,
                Some(h),
                false,
                FrontRelax::Free,
            )
            .unwrap();
            let layer = wall_layer(&mesh, &outer);
            assert!(!layer.is_empty());
            assert!(
                layer[0] > 0.6 * h * h,
                "the {teeth}-toothed frame has a cell of {:.3} h² on its outer wall",
                layer[0] / (h * h)
            );
        }
    }

    #[test]
    fn a_seam_beside_a_leftover_triangle_does_not_crack_the_mesh() {
        // Two ways the seam used to break the mesh, and the same shape shows
        // both: a frame whose inner wall is crenellated, which is what a box
        // wall looks like.
        //
        // A seam identifies two front vertices and rewrites onto the survivor
        // every quadrangle that used the other — but not the **triangles**,
        // which are not indexed by vertex. One left pointing at the discarded
        // vertex is a cell hanging off a node nothing else touches: three
        // cracks at once.
        //
        // And the survivor may be a contour node, which it must be whenever
        // the other side is one. Two seams running one after the other can
        // land the two ends of a single edge on two contour nodes that have a
        // third between them; that edge then runs along the boundary skipping
        // a node the contour has, and the lens left between them is a crack
        // no weld can close, since every node of it is a contour node.
        //
        // A sound mesh carries one cell on each of the contour's segments and
        // two on everything else, so the boundary count is the whole test.
        //
        // One frame per fault: the first used to lose a lens to a chord over
        // the contour, the second a triangle to a seam beside it.
        let h = 1.0;
        for (w, height, inset, teeth, tw, td) in [
            (16.0, 10.0, 3.0, 5, 1.4, 1.5),
            (24.0, 14.0, 4.0, 6, 1.8, 1.5),
        ] {
            let (outer, inner) = crenellated_frame(w, height, inset, teeth, tw, td, h);
            let coords = Handle::new(Coords::new(2).unwrap());
            let contour = loop_mesh(coords.clone(), &outer)
                .union(&loop_mesh(coords, &inner))
                .unwrap();
            let mesh = pave_surface(
                &contour,
                ElementType::QUA4,
                Some(h),
                false,
                FrontRelax::Free,
            )
            .unwrap();
            let r = inspect(&mesh);
            assert_eq!(
                r.boundary,
                outer.len() + inner.len(),
                "holes: the mesh of the {teeth}-toothed frame is not whole"
            );
            assert_eq!(r.non_conforming, 0);
            assert!(r.min_quality > 0.0, "quality {}", r.min_quality);
        }
    }

    #[test]
    fn a_plate_with_a_hole_is_paved_and_covers_its_area() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let outer = loop_mesh(coords.clone(), &rect_loop(3.0, 1.0, 30, 10));
        let hole = loop_mesh(coords, &circle_loop(2.25, 0.5, 0.35, 32, true));
        let contour = outer.union(&hole).unwrap();
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.1),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let r = inspect(&mesh);
        // Seaming discards one of two vertices, so the contour has to be
        // checked here too — this is the geometry where the outer front and
        // the hole's front meet and get seamed together.
        {
            let all: std::collections::HashSet<NodeId> = mesh
                .into_iter()
                .flat_map(|sm| sm.read().connectivity().to_vec())
                .collect();
            for sub in [&outer[0], &hole[0]] {
                for n in sub.read().connectivity() {
                    assert!(all.contains(n), "contour node {n:?} was seamed away");
                }
            }
        }
        let expect = 3.0 - std::f64::consts::PI * 0.35 * 0.35;
        println!(
            "plate: {} quads, {} tris, area {:.6} (hole polygon {:.6}), q_min {:.3}",
            r.quads, r.tris, r.area, expect, r.min_quality
        );
        assert_eq!(r.non_conforming, 0);
        assert!(r.min_quality > 0.0);
        // The hole is a 32-gon, so a little larger than the disc it samples.
        assert!((r.area - expect).abs() < 0.01, "area {}", r.area);
    }

    #[test]
    fn cancellable_stops_on_a_preset_flag() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 20, 20));
        let flag = AtomicBool::new(true);
        let err = pave_surface_cancellable(
            &contour,
            ElementType::QUA4,
            Some(0.02),
            false,
            FrontRelax::Free,
            &flag,
        )
        .unwrap_err();
        assert!(matches!(err, PyrucastError::Interrupted));
    }

    #[test]
    fn relaxing_the_front_along_itself_keeps_a_square_square() {
        // What the relaxation costs, on the shape where the cost is exactly
        // measurable. A 20 × 20 square at size 1 holds 400 unit cells and the
        // paver ought to lay them: the front is square, its four corners are
        // ends, and an end is what makes a row shed the eight nodes the
        // perimeter loses. `Free` rounds those corners off in two rows, after
        // which the front sheds nothing at all, keeps every node it has while
        // its perimeter shrinks, and pays with 600 cells whose innermost are
        // at 0.43 of the area asked. Kept along the front, the relaxation
        // still evens the spacing out and no longer cuts a corner.
        let (side, h) = (20.0, 1.0);
        let n = (side / h) as usize;
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords, &rect_loop(side, side, n, n));

        let free = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(h),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let along = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(h),
            false,
            FrontRelax::Along,
        )
        .unwrap();
        assert!(free.cell_count() > 500, "{}", free.cell_count());
        assert_eq!(along.cell_count(), 400);
        // And every one of them a unit square, to the last digit the
        // smoothing leaves.
        for si in 0..along.len() {
            for cell in along.cells(si).unwrap() {
                let p: Vec<Point2> = cell
                    .nodes()
                    .unwrap()
                    .iter()
                    .map(|nd| {
                        let v = nd.position().unwrap();
                        Point2::new(v[0], v[1])
                    })
                    .collect();
                assert_eq!(p.len(), 4);
                let area = 0.5
                    * (0..4)
                        .map(|i| p[i].x * p[(i + 1) % 4].y - p[(i + 1) % 4].x * p[i].y)
                        .sum::<f64>();
                assert!((area.abs() - 1.0).abs() < 1e-9, "area {area}");
            }
        }
    }

    #[test]
    fn an_unknown_relaxation_name_is_not_read_as_the_default() {
        assert_eq!(FrontRelax::from_name("along"), Some(FrontRelax::Along));
        assert_eq!(FrontRelax::from_name("none"), Some(FrontRelax::Off));
        // Case no longer matters, and `off` is an alias of `none`.
        assert_eq!(FrontRelax::from_name("Along"), Some(FrontRelax::Along));
        assert_eq!(FrontRelax::from_name("OFF"), Some(FrontRelax::Off));
        assert_eq!(FrontRelax::from_name("nope"), None);
        assert_eq!(FrontRelax::from_name(""), None);
        for m in [FrontRelax::Free, FrontRelax::Along, FrontRelax::Off] {
            assert_eq!(FrontRelax::from_name(m.name()), Some(m));
        }
    }

    #[test]
    fn a_concave_l_shape_is_paved_without_leaving_the_material() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let mut pts = Vec::new();
        let step = 0.1;
        for i in 0..20 {
            pts.push((i as f64 * step, 0.0));
        }
        for i in 0..10 {
            pts.push((2.0, i as f64 * step));
        }
        for i in 0..15 {
            pts.push((2.0 - i as f64 * step, 1.0));
        }
        for i in 0..10 {
            pts.push((0.5, 1.0 + i as f64 * step));
        }
        for i in 0..5 {
            pts.push((0.5 - i as f64 * step, 2.0));
        }
        for i in 0..20 {
            pts.push((0.0, 2.0 - i as f64 * step));
        }
        let contour = loop_mesh(coords, &pts);
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.1),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let r = inspect(&mesh);
        assert_eq!(r.non_conforming, 0);
        assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
        // 2×1 foot plus 0.5×1 leg. A hair of tolerance: where two parts of
        // the front graze each other the remnant between them is dropped
        // rather than filled with cells no solver could integrate.
        assert!((r.area - 2.5).abs() < 1e-3, "area {}", r.area);
    }

    #[test]
    fn narrow_bands_meeting_head_on_do_not_turn_the_front_inside_out() {
        // A crenellated profile: two full-height towers with a run of shallow
        // notches between them. Every band under a notch is only a handful of
        // cells deep, so the front coming up from the base and the one coming
        // down from the notch meet head-on all along it, leaving slithers
        // behind. A row laid on a slither used to reverse its loop, after
        // which every further row inflated it until it left the material
        // entirely — reported, much later and far away, as a fold.
        let coords = Handle::new(Coords::new(2).unwrap());
        let (u, v) = (0.6 / 9.0, 0.3 / 40.0);
        let levels = [40.0, 3.0, 6.0, 4.0, 6.0, 4.0, 6.0, 3.0, 40.0];
        let mut corners: Vec<(f64, f64)> = vec![(0.0, 0.0), (0.6, 0.0)];
        for (i, l) in levels.iter().enumerate().rev() {
            corners.push(((i + 1) as f64 * u, l * v));
            corners.push((i as f64 * u, l * v));
        }

        let size = 2.0 * v / 4.0; // four cells across the shortest step
        let mut pts = Vec::new();
        let n = corners.len();
        for i in 0..n {
            let (a, b) = (corners[i], corners[(i + 1) % n]);
            let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
            let k = (len / size).round().max(4.0) as usize;
            for j in 0..k {
                let t = j as f64 / k as f64;
                pts.push((a.0 + t * (b.0 - a.0), a.1 + t * (b.1 - a.1)));
            }
        }

        let contour = loop_mesh(coords, &pts);
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(size),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let r = inspect(&mesh);
        assert_eq!(r.non_conforming, 0);
        assert!(r.min_quality > 0.0, "min quality {}", r.min_quality);
        // 0.6 × 0.3 towers over a 0.6-wide base, minus the notches.
        let area: f64 = levels.iter().map(|l| u * l * v).sum();
        assert!((r.area - area).abs() < 1e-3, "area {} for {area}", r.area);
    }

    #[test]
    fn all_quad_on_an_odd_contour_is_an_error_rather_than_a_silent_triangle() {
        // 4 + 4 + 4 + 5 = 17 segments. A polygon with an odd number of sides
        // has no filling by quadrangles alone, and the contour is the
        // caller's: nothing here may add a node to it to even the count out.
        // So the honest answer is to say so.
        let coords = Handle::new(Coords::new(2).unwrap());
        let mut pts = rect_loop(1.0, 1.0, 4, 4);
        pts.push((0.0, 0.125));
        assert_eq!(pts.len() % 2, 1);
        let contour = loop_mesh(coords, &pts);

        let err = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.25),
            true,
            FrontRelax::Free,
        )
        .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.starts_with("pave_surface:"), "{msg}");
        assert!(
            msg.contains("17 segments"),
            "the count should be named: {msg}"
        );
        assert!(msg.contains("odd"), "{msg}");

        // Left to itself the same contour meshes fine, paying the one
        // triangle that parity makes unavoidable.
        let r = inspect(
            &pave_surface(
                &contour,
                ElementType::QUA4,
                Some(0.25),
                false,
                FrontRelax::Free,
            )
            .unwrap(),
        );
        assert!(r.tris <= 1, "odd parity costs at most one: {}", r.tris);
        assert_eq!(r.non_conforming, 0);
        assert!((r.area - 1.0).abs() < 2e-2, "area {}", r.area);
    }

    #[test]
    fn the_contour_nodes_come_back_untouched() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let pts = rect_loop(1.0, 1.0, 6, 6);
        let contour = loop_mesh(coords.clone(), &pts);
        let before: Vec<(NodeId, Vec<f64>)> = {
            let c = coords.read();
            let s = contour[0].read();
            s.connectivity()
                .iter()
                .map(|&n| (n, c.position(n).unwrap().to_vec()))
                .collect()
        };
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.15),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let c = coords.read();
        for (id, coord) in &before {
            assert_eq!(
                &c.position(*id).unwrap().to_vec(),
                coord,
                "node {id:?} moved"
            );
        }
        // And they are still the ones the mesh is built on.
        let used: HashMap<NodeId, ()> = mesh
            .into_iter()
            .flat_map(|sm| sm.read().connectivity().to_vec())
            .map(|n| (n, ()))
            .collect();
        for (id, _) in &before {
            assert!(used.contains_key(id), "contour node {id:?} was abandoned");
        }
    }

    #[test]
    fn the_mesh_boundary_is_exactly_the_contour() {
        // The strongest statement of the contract: every contour segment is a
        // boundary edge of the mesh, and there is no other boundary edge —
        // so no node was added on the boundary, none was dropped, and no hole
        // was left anywhere inside.
        let coords = Handle::new(Coords::new(2).unwrap());
        let pts = rect_loop(3.0, 1.0, 30, 10);
        let contour = loop_mesh(coords, &pts);
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.1),
            false,
            FrontRelax::Free,
        )
        .unwrap();

        let mut used: HashMap<(NodeId, NodeId), usize> = HashMap::new();
        for sm in &mesh {
            let s = sm.read();
            let npc = s.element_type().nodes_per_cell();
            for cell in s.connectivity().chunks(npc) {
                for i in 0..npc {
                    let (a, b) = (cell[i], cell[(i + 1) % npc]);
                    let key = if a.0 < b.0 { (a, b) } else { (b, a) };
                    *used.entry(key).or_insert(0) += 1;
                }
            }
        }
        let contour_conn = contour[0].read();
        for seg in contour_conn.connectivity().chunks(2) {
            let key = if seg[0].0 < seg[1].0 {
                (seg[0], seg[1])
            } else {
                (seg[1], seg[0])
            };
            assert_eq!(
                used.get(&key),
                Some(&1),
                "contour segment {key:?} is not on the boundary"
            );
        }
        let boundary = used.values().filter(|&&u| u == 1).count();
        assert_eq!(
            boundary,
            pts.len(),
            "the mesh boundary has {boundary} edges for {} contour segments",
            pts.len()
        );
    }

    #[test]
    fn a_planar_contour_in_3d_is_paved_in_its_own_plane() {
        // The tutorial benchmark lives in the y = 0 plane of a 3-D Coords.
        let coords = Handle::new(Coords::new(3).unwrap());
        let ids: Vec<NodeId> = rect_loop(1.0, 1.0, 6, 6)
            .iter()
            .map(|&(x, z)| Node::create_in(coords.clone(), &[x, 0.0, z]).unwrap().id())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        let n = ids.len();
        for i in 0..n {
            sm.add_cell(&[ids[i], ids[(i + 1) % n]]).unwrap();
        }
        let contour = Mesh::from_submesh(sm);
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.2),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let c = coords.read();
        for sm in &mesh {
            for &node in sm.read().connectivity() {
                assert!(
                    c.position(node).unwrap()[1].abs() < 1e-12,
                    "a node left the y = 0 plane"
                );
            }
        }
    }

    #[test]
    fn quadratic_forms_are_derived_from_the_quadrangles() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 4, 4));
        for (et, npc) in [(ElementType::QUA8, 8), (ElementType::QUA9, 9)] {
            let mesh = pave_surface(&contour, et, Some(0.25), true, FrontRelax::Free).unwrap();
            assert_eq!(mesh.element_types().unwrap(), vec![et]);
            assert_eq!(mesh[0].read().element_type().nodes_per_cell(), npc);
        }
    }

    #[test]
    fn bad_input_is_rejected_with_a_named_error() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords.clone(), &rect_loop(1.0, 1.0, 4, 4));
        for err in [
            pave_surface(&contour, ElementType::TRI3, None, false, FrontRelax::Free).unwrap_err(),
            pave_surface(
                &contour,
                ElementType::QUA4,
                Some(0.0),
                false,
                FrontRelax::Free,
            )
            .unwrap_err(),
            pave_surface(
                &contour,
                ElementType::QUA4,
                Some(-1.0),
                false,
                FrontRelax::Free,
            )
            .unwrap_err(),
        ] {
            assert!(
                format!("{err}").starts_with("pave_surface:"),
                "unhelpful error: {err}"
            );
        }
        // A contour of the wrong element type is caught by the shared parser,
        // which still names this operator.
        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let d = Node::create_in(coords, &[0.0, 1.0]).unwrap();
        sm.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
        let err = pave_surface(
            &Mesh::from_submesh(sm),
            ElementType::QUA4,
            None,
            false,
            FrontRelax::Free,
        )
        .unwrap_err();
        assert!(format!("{err}").starts_with("pave_surface:"), "{err}");
    }

    #[test]
    fn the_default_size_follows_the_contour_discretisation() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let contour = loop_mesh(coords, &rect_loop(1.0, 1.0, 10, 10));
        let mesh =
            pave_surface(&contour, ElementType::QUA4, None, false, FrontRelax::Free).unwrap();
        let r = inspect(&mesh);
        assert_eq!(r.non_conforming, 0);
        assert!((r.area - 1.0).abs() < 1e-9);
        // Boundary spacing 0.1 over a unit square: of the order of 100 cells.
        assert!(
            (40..400).contains(&(r.quads + r.tris)),
            "{} cells",
            r.quads + r.tris
        );
    }

    /// Throughput and shape, on the plate-with-a-hole benchmark. Not part of
    /// the normal run: `cargo test --release -- --ignored`.
    #[test]
    #[ignore = "performance check, run explicitly with --ignored"]
    fn perf_and_quality_plate_with_hole_under_30s() {
        use crate::ops::mesh::paving::geom::{quad_quality, tri_quality};
        let coords = Handle::new(Coords::new(2).unwrap());
        let outer = loop_mesh(coords.clone(), &rect_loop(0.30, 0.10, 60, 20));
        let hole = loop_mesh(coords, &circle_loop(0.225, 0.05, 0.035, 64, true));
        let contour = outer.union(&hole).unwrap();

        let t0 = std::time::Instant::now();
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(0.00029),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let dt = t0.elapsed();

        let c = mesh.coords().unwrap().read();
        let at = |id: NodeId| {
            let v = c.position(id).unwrap();
            Point2::new(v[0], v[1])
        };
        let (mut nq, mut nt) = (0usize, 0usize);
        let mut worst = f64::INFINITY;
        let mut under = 0usize;
        for sm in &mesh {
            let s = sm.read();
            let npc = s.element_type().nodes_per_cell();
            for cell in s.connectivity().chunks(npc) {
                let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
                let q = if npc == 4 {
                    nq += 1;
                    quad_quality([p[0], p[1], p[2], p[3]])
                } else {
                    nt += 1;
                    tri_quality(p[0], p[1], p[2])
                };
                worst = worst.min(q);
                if q < 0.5 {
                    under += 1;
                }
            }
        }
        let total = nq + nt;
        let rate = total as f64 / dt.as_secs_f64();
        println!(
            "pave_surface: {total} cells ({nq} QUA4 + {nt} TRI3) in {:.2} s\n\
             \x20 rate {:.0} cells/s | quads {:.1} % | worst scaled Jacobian {:.3} | below 0.5: {:.2} %",
            dt.as_secs_f64(),
            rate,
            100.0 * nq as f64 / total as f64,
            worst,
            100.0 * under as f64 / total as f64,
        );
        assert!(dt.as_secs_f64() < 30.0, "took {:?}", dt);
        assert!(rate > 10_000.0, "only {rate:.0} cells/s");
        assert!(worst > 0.0, "an inverted cell got through: {worst}");
        assert!(
            nq as f64 / total as f64 > 0.95,
            "only {:.1} % quadrangles",
            100.0 * nq as f64 / total as f64
        );
    }

    /// A full quality read-out on the plate benchmark, for judging the mesh
    /// rather than merely asserting it is valid. Run explicitly:
    /// `cargo test --release -- --ignored quality_report --nocapture`.
    #[test]
    #[ignore = "reporting run, not an assertion"]
    fn quality_report_plate_with_hole() {
        use crate::ops::mesh::paving::geom::{quad_quality, tri_quality};
        let coords = Handle::new(Coords::new(2).unwrap());
        let outer = loop_mesh(coords.clone(), &rect_loop(0.30, 0.10, 60, 20));
        let hole = loop_mesh(coords, &circle_loop(0.225, 0.05, 0.035, 64, true));
        let contour = outer.union(&hole).unwrap();
        let target = 0.0016;

        let t0 = std::time::Instant::now();
        let mesh = pave_surface(
            &contour,
            ElementType::QUA4,
            Some(target),
            false,
            FrontRelax::Free,
        )
        .unwrap();
        let dt = t0.elapsed();

        let c = mesh.coords().unwrap().read();
        let at = |id: NodeId| {
            let v = c.position(id).unwrap();
            Point2::new(v[0], v[1])
        };

        let mut jac: Vec<f64> = Vec::new();
        let mut angles: Vec<f64> = Vec::new();
        let mut aspect: Vec<f64> = Vec::new();
        let mut edges: Vec<f64> = Vec::new();
        let mut valence: HashMap<NodeId, usize> = HashMap::new();
        let mut edge_use: HashMap<(NodeId, NodeId), usize> = HashMap::new();
        let (mut nq, mut nt) = (0usize, 0usize);

        for sm in &mesh {
            let s = sm.read();
            let npc = s.element_type().nodes_per_cell();
            for cell in s.connectivity().chunks(npc) {
                let p: Vec<Point2> = cell.iter().map(|&n| at(n)).collect();
                if npc == 4 {
                    nq += 1;
                    jac.push(quad_quality([p[0], p[1], p[2], p[3]]));
                } else {
                    nt += 1;
                    jac.push(tri_quality(p[0], p[1], p[2]));
                }
                let mut lo = f64::INFINITY;
                let mut hi: f64 = 0.0;
                for i in 0..npc {
                    let (prev, cur, next) = (p[(i + npc - 1) % npc], p[i], p[(i + 1) % npc]);
                    let (u, w) = (prev - cur, next - cur);
                    let ang = (u.dot(&w) / (u.norm() * w.norm())).clamp(-1.0, 1.0).acos();
                    angles.push(ang.to_degrees());
                    let l = w.norm();
                    lo = lo.min(l);
                    hi = hi.max(l);
                    edges.push(l);
                    *valence.entry(cell[i]).or_insert(0) += 1;
                    let (a, b) = (cell[i], cell[(i + 1) % npc]);
                    let key = if a.0 < b.0 { (a, b) } else { (b, a) };
                    *edge_use.entry(key).or_insert(0) += 1;
                }
                aspect.push(hi / lo);
            }
        }

        let pct = |v: &mut Vec<f64>, q: f64| {
            v.sort_by(|a, b| a.partial_cmp(b).unwrap());
            v[((v.len() - 1) as f64 * q) as usize]
        };
        let total = nq + nt;
        let boundary: usize = edge_use.values().filter(|&&u| u == 1).count();
        let interior_nodes: Vec<NodeId> = {
            let mut on_boundary: std::collections::HashSet<NodeId> =
                std::collections::HashSet::new();
            for ((a, b), &u) in &edge_use {
                if u == 1 {
                    on_boundary.insert(*a);
                    on_boundary.insert(*b);
                }
            }
            valence
                .keys()
                .filter(|n| !on_boundary.contains(n))
                .copied()
                .collect()
        };
        let mut hist: HashMap<usize, usize> = HashMap::new();
        for n in &interior_nodes {
            *hist.entry(valence[n]).or_insert(0) += 1;
        }
        let irregular = interior_nodes.iter().filter(|n| valence[n] != 4).count();

        println!("\n┌─ pave_surface — plaque 30 × 10 cm, trou r = 3,5 cm, taille visée {target} m");
        println!("│");
        println!(
            "│  mailles          {total}  ({nq} QUA4 + {nt} TRI3, {:.2} % quadrangles)",
            100.0 * nq as f64 / total as f64
        );
        println!(
            "│  temps            {:.2} s  ({:.0} mailles/s)",
            dt.as_secs_f64(),
            total as f64 / dt.as_secs_f64()
        );
        println!(
            "│  nœuds            {}  (dont {} intérieurs)",
            valence.len(),
            interior_nodes.len()
        );
        println!("│  arêtes de bord   {boundary}");
        println!(
            "│  conformité       {}",
            if edge_use.values().all(|&u| u <= 2) {
                "OK — aucune arête à plus de 2 mailles"
            } else {
                "ROMPUE"
            }
        );
        println!("│");
        println!("│  Jacobien normalisé (1 = carré, ≤ 0 = inintégrable)");
        println!(
            "│    min {:.3}   p1 {:.3}   p5 {:.3}   médiane {:.3}   moyenne {:.3}",
            pct(&mut jac.clone(), 0.0),
            pct(&mut jac.clone(), 0.01),
            pct(&mut jac.clone(), 0.05),
            pct(&mut jac.clone(), 0.5),
            jac.iter().sum::<f64>() / jac.len() as f64
        );
        for seuil in [0.0, 0.2, 0.5, 0.7] {
            println!(
                "│    sous {seuil:.1} : {:.3} %  ({} mailles)",
                100.0 * jac.iter().filter(|&&j| j < seuil).count() as f64 / total as f64,
                jac.iter().filter(|&&j| j < seuil).count()
            );
        }
        println!("│");
        println!("│  Angles (degrés)");
        println!(
            "│    min {:.1}   p1 {:.1}   médiane {:.1}   p99 {:.1}   max {:.1}",
            pct(&mut angles.clone(), 0.0),
            pct(&mut angles.clone(), 0.01),
            pct(&mut angles.clone(), 0.5),
            pct(&mut angles.clone(), 0.99),
            pct(&mut angles.clone(), 1.0)
        );
        println!(
            "│    sous 30° : {:.2} %      au-dessus de 150° : {:.2} %",
            100.0 * angles.iter().filter(|&&a| a < 30.0).count() as f64 / angles.len() as f64,
            100.0 * angles.iter().filter(|&&a| a > 150.0).count() as f64 / angles.len() as f64
        );
        println!("│");
        println!("│  Élancement (arête la plus longue / la plus courte)");
        println!(
            "│    médiane {:.2}   p99 {:.2}   max {:.2}",
            pct(&mut aspect.clone(), 0.5),
            pct(&mut aspect.clone(), 0.99),
            pct(&mut aspect.clone(), 1.0)
        );
        println!("│");
        println!("│  Taille d'arête (visée {target})");
        println!(
            "│    p1 {:.5}   médiane {:.5}   p99 {:.5}",
            pct(&mut edges.clone(), 0.01),
            pct(&mut edges.clone(), 0.5),
            pct(&mut edges.clone(), 0.99)
        );
        println!("│");
        println!("│  Valence des nœuds intérieurs (4 = régulier)");
        let mut ks: Vec<usize> = hist.keys().copied().collect();
        ks.sort_unstable();
        for k in ks {
            println!(
                "│    {k} : {:>6}  ({:.2} %)",
                hist[&k],
                100.0 * hist[&k] as f64 / interior_nodes.len() as f64
            );
        }
        println!(
            "│    irréguliers : {irregular} sur {} ({:.2} %)",
            interior_nodes.len(),
            100.0 * irregular as f64 / interior_nodes.len() as f64
        );
        println!("└─");
    }
}