pyrucast 0.9.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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
//! Mesh — collection of homogeneous submeshes (one element type per
//! submesh).
//!
//! Hierarchy:
//!
//! - [`SubMesh`] — every cell of a single [`ElementType`]. Stores the
//!   connectivity flat (`Vec<NodeId>`, length `cell_count * nodes_per_cell`).
//!   RAII referencing: `add_cell` increments the node refcounts in the
//!   `Coords`; the `SubMesh`'s `Drop` decrements every referenced
//!   node.
//! - [`Mesh`] — aggregate of SubMeshes attached to the same `Coords`.
//!
//! The POI1 case is deliberately degenerate: a POI1 submesh is exactly a
//! list of nodes.
//!
//! # Example
//!
//! ```
//! use pyrucast::coords::Coords;
//! use pyrucast::atoms::ElementType;
//! use pyrucast::containers::mesh::SubMesh;
//! use pyrucast::atoms::Node;
//! use pyrucast::handle::Handle;
//!
//! let coords = Handle::new(Coords::new(2).unwrap());
//! 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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
//!
//! let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
//! sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
//! assert_eq!(sm.cell_count(), 1);
//!
//! // The SubMesh holds refs on the 3 nodes, in addition to the `Node`s.
//! assert_eq!(coords.read().refcount(a.id()), 2);
//! drop(sm);  // decrements the referenced nodes
//! assert_eq!(coords.read().refcount(a.id()), 1);
//! ```

use crate::aggregate::Aggregate;
use crate::atoms::{Cell, CellIter, ElementType, Node, NodeId, RgbColor};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::OnceLock;

// ─── SubMesh ────────────────────────────────────────────────────────────────

/// Submesh: every cell of a single [`ElementType`].
///
/// The connectivity is stored flat; each cell occupies
/// `element_type.nodes_per_cell()` contiguous entries.
///
/// A [`RgbColor`] is attached as the **face colour** used by the
/// visualization layer (`viz` feature); it has no effect on numerics and
/// defaults to a light blue.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// // A homogeneous zone: one element type, one frame, a flat connectivity.
/// // It freezes as soon as a consumer captures it.
/// assert_eq!(sm.element_type(), ElementType::TRI3);
/// assert_eq!(sm.cell_count(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct SubMesh {
    element_type: ElementType,
    coords: Handle<Coords>,
    /// Flat connectivity: cell `i` occupies `[i*npc, (i+1)*npc)`.
    connectivity: Vec<NodeId>,
    /// Face colour used by the viz layer. `serde(default)` keeps older
    /// snapshots (without the field) readable.
    #[serde(default)]
    face_color: RgbColor,
    /// Once **sealed**, the connectivity is frozen: [`SubMesh::add_cell`] and
    /// [`SubMesh::add_cell_taking`] refuse to run. A submesh is sealed the
    /// first time a non-mesh consumer (finite-element space, field, matrix, …)
    /// captures its handle, so those consumers can never be left referencing
    /// stale cells. The seal is permanent for the object's lifetime.
    /// `serde(default)` keeps older snapshots (without the field) readable.
    #[serde(default)]
    sealed: bool,
    /// Lazily-built `NodeId → index` map over the **distinct** nodes of the
    /// connectivity, in first-appearance order. Consumers that need a node
    /// lookup (node fields, …) read it in place while holding their store
    /// guard on this submesh — no copy — so the O(n) build is paid once and
    /// mutualised across every field on this support. Not serialized — it is
    /// derived from `connectivity` and rebuilt on demand after a reload.
    /// Dropped by every connectivity mutation (see `invalidate_caches`), so it
    /// can never go stale.
    #[serde(skip)]
    node_index: OnceLock<HashMap<NodeId, usize>>,
    /// Lazily-built **canonical POI1 companion**: the node cloud of this
    /// submesh's distinct nodes, materialised once and shared. Every consumer
    /// that projects this submesh to its nodes ([`SubMesh::to_poi1`]) gets the
    /// *same* store slot, so their node fields pair under
    /// [`same_support`](crate::containers::field::SubField::same_support) — a
    /// stiffness block's support, a `restrict` onto this mesh, and a
    /// `divergence`/`flux` output over it all land on one handle and combine
    /// directly. Not serialized (derived from `connectivity`, rebuilt on
    /// demand). Dropped by every connectivity mutation (see
    /// `invalidate_caches`): the companion answers for **one** state of this
    /// submesh, and the fields already sitting on it keep it alive on their
    /// own — they stay valid, on that earlier node cloud.
    #[serde(skip)]
    poi1_companion: OnceLock<Handle<SubMesh>>,
}

impl SubMesh {
    /// Create an empty submesh for the given element type, attached to `coords`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // A zone is **homogeneous**: a single element type, a single frame.
    /// let mut z = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// z.add_cell(&[n[0].id(), n[1].id()])?;
    /// assert_eq!(z.cell_count(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(coords: Handle<Coords>, element_type: ElementType) -> Self {
        Self {
            element_type,
            coords,
            connectivity: Vec::new(),
            face_color: RgbColor::default(),
            sealed: false,
            node_index: OnceLock::new(),
            poi1_companion: OnceLock::new(),
        }
    }

    /// Build a submesh from a **whole flat connectivity** at once: cell `i`
    /// occupies `connectivity[i*npc..(i+1)*npc]`, so its length must be a
    /// multiple of the element type's node count.
    ///
    /// The buffer is **moved in, not copied**: an operator lays out the
    /// connectivity it is going to produce and hands the vector over, so the
    /// only pass over it is the one that validates and increfs its nodes.
    ///
    /// The bulk twin of [`add_cell`](SubMesh::add_cell), and the seam every
    /// operator that produces a big mesh should sit on. `add_cell` takes the
    /// `Coords` write lock and drops the derived caches **once per cell**;
    /// on a million cells that, not the connectivity itself, is the cost. Here
    /// the nodes are validated and increfed in a single locked pass — one unit
    /// per occurrence, as always — and the caches are simply never built.
    ///
    /// Nothing is increfed unless every id names a live node, so a rejected
    /// call leaves the `Coords` exactly as it was.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::SubMesh;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// // Two triangles laid down in one go, flat connectivity.
    /// let ids: Vec<_> = n.iter().map(|x| x.id()).collect();
    /// let sm = SubMesh::from_connectivity(
    ///     coords.clone(),
    ///     ElementType::TRI3,
    ///     vec![ids[0], ids[1], ids[2], ids[1], ids[3], ids[2]],
    /// )?;
    /// assert_eq!(sm.cell_count(), 2);
    /// // One unit per occurrence: node 2 serves twice, plus its `Node`.
    /// assert_eq!(coords.read().refcount(ids[2]), 3);
    /// // A length that does not divide evenly by the element type is refused.
    /// assert!(SubMesh::from_connectivity(coords.clone(), ElementType::TRI3, vec![ids[0]]).is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn from_connectivity(
        coords: Handle<Coords>,
        element_type: ElementType,
        connectivity: Vec<NodeId>,
    ) -> Result<Self> {
        let npc = element_type.nodes_per_cell();
        if npc == 0 || !connectivity.len().is_multiple_of(npc) {
            return Err(PyrucastError::Message(format!(
                "from_connectivity({element_type}): {} node(s) is not a multiple of {npc}",
                connectivity.len()
            )));
        }
        coords.write().incref_all(&connectivity)?;
        Ok(Self {
            element_type,
            coords,
            connectivity,
            face_color: RgbColor::default(),
            sealed: false,
            node_index: OnceLock::new(),
            poi1_companion: OnceLock::new(),
        })
    }

    /// Whether this submesh is sealed (connectivity frozen).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// let mesh = Mesh::from_submesh(sm);
    /// assert!(!mesh.get(0)?.read().is_sealed());
    /// // Le premier consommateur non-maillage scelle la zone.
    /// let _fes = FiniteElementSpace::lagrange1(&mesh)?;
    /// assert!(mesh.get(0)?.read().is_sealed());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn is_sealed(&self) -> bool {
        self.sealed
    }

    /// `NodeId → index` map over the **distinct** nodes of the connectivity,
    /// in first-appearance order (the order [`SubNodeField`](crate::containers::node_field::SubNodeField) snapshots its
    /// support in). Built once and cached; callers keep their read guard on
    /// this submesh while using the returned reference — no copy.
    ///
    /// The map is derived from `connectivity`, and every mutator drops it, so
    /// it can never go stale. (It is queried through a sealed support in
    /// practice — a field's, which can no longer move at all.)
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // `NodeId → rank`, over the **distinct** nodes, in order of first
    /// // appearance: that is what gives the fields their addressing.
    /// sm.seal();
    /// assert_eq!(sm.node_index()[&n[1].id()], 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn node_index(&self) -> &HashMap<NodeId, usize> {
        self.node_index.get_or_init(|| {
            let mut map = HashMap::with_capacity(self.connectivity.len());
            for &nid in &self.connectivity {
                let next = map.len();
                map.entry(nid).or_insert(next);
            }
            map
        })
    }

    /// Drop the caches derived from the connectivity — the `NodeId → index`
    /// map and the POI1 companion. Called by every mutator, right after the
    /// connectivity moves.
    ///
    /// Dropping the companion handle does **not** invalidate the node fields
    /// built on it: they hold it themselves, so it stays alive, sealed, with
    /// its node refcounts. They are simply defined on the node cloud of the
    /// submesh as it was; the next [`SubMesh::to_poi1`] materialises a fresh
    /// companion for the new state, and
    /// [`restrict`](fn@crate::ops::node_field::restrict) carries a field from
    /// one to the other.
    fn invalidate_caches(&mut self) {
        self.node_index = OnceLock::new();
        self.poi1_companion = OnceLock::new();
    }

    /// Seal this submesh: freeze its connectivity permanently. After this,
    /// [`SubMesh::add_cell`] / [`SubMesh::add_cell_taking`] return
    /// [`PyrucastError::MeshSealed`]. Idempotent.
    ///
    /// Called by the container layer whenever a non-mesh object captures the
    /// submesh — see the free function [`seal`]. A bare [`Mesh`] holding the
    /// submesh does **not** seal it (a mesh may keep growing until consumed).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // Sealing by hand: the connectivity freezes, and for good.
    /// sm.seal();
    /// assert!(sm.is_sealed());
    /// assert!(sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).is_err());
    /// sm.seal(); // idempotent
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn seal(&mut self) {
        self.sealed = true;
    }

    /// Face colour used when this submesh is drawn (no numerical effect).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::atoms::RgbColor;
    /// // A display colour, with no numerical effect.
    /// sm.set_face_color(RgbColor::new(220, 60, 60));
    /// assert_eq!(sm.face_color().r, 220);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn face_color(&self) -> RgbColor {
        self.face_color
    }

    /// Replace the face colour used when this submesh is drawn.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::atoms::RgbColor;
    /// let rouge = RgbColor::new(220, 60, 60);
    /// sm.set_face_color(rouge);
    /// assert_eq!(sm.face_color(), rouge);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn set_face_color(&mut self, color: RgbColor) {
        self.face_color = color;
    }

    /// Add a cell. The length of `nodes` must equal
    /// `element_type.nodes_per_cell()`, and each node must be alive in the
    /// `Coords`; each node is increfed. On increment failure
    /// (invalid / collected id), the increfs already performed for this
    /// cell are rolled back.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // Shortcut of the single-zone case: adds into the one zone.
    /// assert_eq!(mesh.cell_count(), 1);
    /// ```
    pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.sealed {
            return Err(PyrucastError::MeshSealed);
        }
        let npc = self.element_type.nodes_per_cell();
        if nodes.len() != npc {
            return Err(PyrucastError::Message(format!(
                "add_cell({}): expected {} nodes, got {}",
                self.element_type,
                npc,
                nodes.len()
            )));
        }
        {
            let mut c = self.coords.write();
            for (acquired, &n) in nodes.iter().enumerate() {
                if let Err(e) = c.incref(n) {
                    // Roll back the increfs already done for this cell.
                    for &m in &nodes[..acquired] {
                        let _ = c.decref(m);
                    }
                    return Err(e);
                }
            }
        }
        let idx = self.connectivity.len() / npc;
        self.connectivity.extend_from_slice(nodes);
        // After the `Coords` guard above is released: dropping the previous
        // companion decrefs its nodes, which takes that same lock.
        self.invalidate_caches();
        Ok(idx)
    }

    /// Add a cell whose nodes are **already owned** by the caller (one
    /// refcount unit per node). The SubMesh adopts those units without
    /// increfing further; its `Drop` will decref as usual, which
    /// balances the donation.
    ///
    /// Typical use: a freshly created node (`Coords::add_node`
    /// returns refcount = 1) is handed directly to a POI1 SubMesh which
    /// then becomes its sole owner.
    ///
    /// The caller is responsible for the ownership claim; this method
    /// only checks that the cell length matches the element type and
    /// that the nodes are alive at the moment of the call.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // The variant that **takes** ownership instead of acquiring it: for a
    /// // freshly created node, whose counter is already 1.
    /// let id = coords.write().add_node(&[2.0, 2.0])?;
    /// let mut poi = SubMesh::new(coords.clone(), ElementType::POI1);
    /// poi.add_cell_taking(&[id])?;
    /// assert_eq!(poi.cell_count(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn add_cell_taking(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.sealed {
            return Err(PyrucastError::MeshSealed);
        }
        let npc = self.element_type.nodes_per_cell();
        if nodes.len() != npc {
            return Err(PyrucastError::Message(format!(
                "add_cell_taking({}): expected {} nodes, got {}",
                self.element_type,
                npc,
                nodes.len()
            )));
        }
        {
            let c = self.coords.read();
            for &n in nodes {
                if !c.is_alive(n) {
                    return Err(PyrucastError::Message(format!(
                        "add_cell_taking: node {} is not alive",
                        n
                    )));
                }
            }
        }
        let idx = self.connectivity.len() / npc;
        self.connectivity.extend_from_slice(nodes);
        self.invalidate_caches();
        Ok(idx)
    }

    /// Deep-copy this submesh into a **fresh, unsealed** one: same element
    /// type, same `Coords`, same connectivity (each referenced node increfed
    /// anew) and same face colour — but never inheriting the seal.
    ///
    /// This is the escape hatch for the seal: once a consumer has frozen a
    /// submesh, `duplicate()` hands back an independent copy you can keep
    /// editing with [`SubMesh::add_cell`]. The two share the same `Coords`
    /// (nodes are not cloned, only their refcounts bumped).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // The way out of the seal: an independent copy, never sealed, sharing
    /// // the **same** nodes (only their counters go up).
    /// sm.seal();
    /// let mut copie = sm.duplicate()?;
    /// assert!(!copie.is_sealed());
    /// copie.add_cell(&[n[0].id(), n[1].id(), n[2].id()])?;
    /// assert_eq!(copie.cell_count(), 2);
    /// assert_eq!(sm.cell_count(), 1); // l'original n'a pas bougé
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn duplicate(&self) -> Result<SubMesh> {
        // One locked pass for the whole connectivity, increfs included.
        let mut copy = SubMesh::from_connectivity(
            self.coords.clone(),
            self.element_type,
            self.connectivity.clone(),
        )?;
        copy.face_color = self.face_color;
        Ok(copy)
    }

    /// Rename this submesh's nodes **in place**, through `map`.
    ///
    /// Every node id that `map` mentions is replaced by its image wherever it
    /// appears in the connectivity; ids absent from the map (and images equal
    /// to their key) are left alone. Returns the number of rewritten slots.
    ///
    /// This is a **renaming**, not an edit of the mesh structure: the element
    /// type, the number of cells and the cell order are untouched, so every
    /// index a caller holds on this submesh (cell numbers, and therefore the
    /// element fields keyed on them) stays valid. That is what makes an
    /// in-place rewrite defensible on a container that otherwise only ever
    /// grows — it is the seam [`merge_nodes(…, in_place = true)`](fn@crate::ops::mesh::merge_nodes)
    /// welds shared meshes through.
    ///
    /// Refcounts follow the rename: each rewritten slot increfs its new node
    /// and decrefs the old one (the connectivity owns one unit per
    /// *occurrence*). Nothing is written unless every incref succeeds, so a
    /// dead or invalid image leaves the submesh exactly as it was. The lazily
    /// built caches ([`node_index`](SubMesh::node_index),
    /// [`to_poi1`](SubMesh::to_poi1)'s companion) are derived from the
    /// connectivity and are therefore dropped.
    ///
    /// Refuses with [`PyrucastError::MeshSealed`] on a **sealed** submesh: a
    /// consumer (finite-element space, field, matrix) has captured it, and its
    /// node numbering must not move under it. Use
    /// [`duplicate`](SubMesh::duplicate) to get an editable copy.
    ///
    /// Node **positions** are never touched — this only rewrites which node a
    /// cell refers to.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use std::collections::HashMap;
    /// // Rewriting **which node** a cell refers to — the positions do not
    /// // move. Refused on a sealed zone: its numbering is held.
    /// let autre = Node::create_in(coords.clone(), &[5.0, 5.0])?;
    /// let map = HashMap::from([(n[2].id(), autre.id())]);
    /// assert_eq!(sm.remap_nodes(&map)?, 1);
    /// sm.seal();
    /// assert!(sm.remap_nodes(&map).is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn remap_nodes(&mut self, map: &HashMap<NodeId, NodeId>) -> Result<usize> {
        self.remap_with(|old| map.get(&old).copied().unwrap_or(old))
    }

    /// The rename [`merge_nodes`](fn@crate::ops::mesh::merge_nodes) welds
    /// with: the same contract as [`remap_nodes`](SubMesh::remap_nodes), read
    /// off a **dense table** indexed by `NodeId.0` (`table[i] == i` for a node
    /// that stays) instead of a `HashMap`. On a ten-million-cell weld the map
    /// alone is the cost — `NodeId` is already an index into the `Coords`.
    ///
    /// The table must cover the whole `Coords` this submesh sits in; indexing
    /// it is the caller's contract, as it is for
    /// [`Coords::position_alive`](crate::coords::Coords).
    pub(crate) fn remap_nodes_dense(&mut self, table: &[u32]) -> Result<usize> {
        self.remap_with(|old| NodeId(table[old.0 as usize]))
    }

    /// The shared body of the two renames: rewrite every slot whose image
    /// differs from it, moving one refcount unit per rewritten slot.
    ///
    /// One `Coords` lock for the whole submesh, and no list of changes built
    /// on the side: the images are validated first, inside that same lock, so
    /// the increments that follow cannot fail and the run stays
    /// all-or-nothing without a rollback path.
    fn remap_with(&mut self, image: impl Fn(NodeId) -> NodeId) -> Result<usize> {
        if self.sealed {
            return Err(PyrucastError::MeshSealed);
        }

        let mut rewritten = 0;
        {
            let mut c = self.coords.write();
            // Nothing is written until every image is known to be live.
            for &old in &self.connectivity {
                let new = image(old);
                if new != old && !c.is_alive(new) {
                    return Err(PyrucastError::Message(format!(
                        "remap_nodes: node {} is not found or collected",
                        new.0
                    )));
                }
            }
            for slot in &mut self.connectivity {
                let new = image(*slot);
                if new != *slot {
                    c.incref(new)?;
                    c.decref(*slot)?;
                    *slot = new;
                    rewritten += 1;
                }
            }
        }

        if rewritten > 0 {
            // Both caches are derived from the connectivity that just moved.
            self.invalidate_caches();
        }
        Ok(rewritten)
    }

    /// Element type of the submesh.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(sm.element_type(), ElementType::TRI3);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_type(&self) -> ElementType {
        self.element_type
    }

    /// Number of cells in the submesh.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(sm.cell_count(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn cell_count(&self) -> usize {
        self.connectivity.len() / self.element_type.nodes_per_cell()
    }

    /// Flat connectivity buffer (all cells concatenated).
    pub(crate) fn connectivity(&self) -> &[NodeId] {
        &self.connectivity
    }

    /// Handle to the owning `Coords` (internal clone).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::handle::Handle as H;
    /// assert!(H::same_object(&sm.coords(), &coords)); // shared, not copied
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn coords(&self) -> Handle<Coords> {
        self.coords.clone()
    }

    /// Build a POI1 submesh with **one cell per [`Node`]**, in the given
    /// order. The [`Coords`] is taken from the nodes themselves
    /// (every [`Node`] carries its own — project convention). Errors if
    /// `nodes` is empty (no Coords to attach to).
    ///
    /// Lower-level form when you already hold the ids and the coords:
    /// [`SubMesh::poi1_from_node_ids`]. The canonical, parent-level form is
    /// the operator
    /// [`ops::mesh::poi1_from_nodes`](crate::ops::mesh::poi1_from_nodes()).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // A point cloud: one POI1 cell per node, in the given order. The
    /// // canonical form is the `ops::mesh::poi1_from_nodes` operator.
    /// let nuage = SubMesh::poi1_from_nodes(&n)?;
    /// assert_eq!(nuage.cell_count(), 3);
    /// assert!(SubMesh::poi1_from_nodes(&[]).is_err()); // no frame to attach to
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn poi1_from_nodes(nodes: &[Node]) -> Result<SubMesh> {
        let coords = nodes
            .first()
            .ok_or_else(|| {
                PyrucastError::Message("SubMesh::poi1_from_nodes: nodes must not be empty".into())
            })?
            .coords();
        let ids: Vec<NodeId> = nodes.iter().map(|n| n.id()).collect();
        SubMesh::poi1_from_node_ids(coords, &ids)
    }

    /// Build a POI1 submesh with **one cell per node id** in `nodes`, in the
    /// given order. Each node is increfed; on failure the partial submesh's
    /// `Drop` rolls back the increfs already done. The caller is responsible
    /// for any de-duplication (see [`SubMesh::to_poi1`] for the deduped
    /// variant) and supplies the owning `coords` explicitly. When you have
    /// [`Node`] objects, prefer [`SubMesh::poi1_from_nodes`].
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // The low form when one already holds the identifiers and the frame.
    /// let ids: Vec<_> = n.iter().map(|x| x.id()).collect();
    /// let nuage = SubMesh::poi1_from_node_ids(coords.clone(), &ids)?;
    /// assert_eq!(nuage.element_type(), ElementType::POI1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn poi1_from_node_ids(coords: Handle<Coords>, nodes: &[NodeId]) -> Result<SubMesh> {
        // One POI1 cell per id, so the id list *is* the connectivity — and it
        // costs one lock, not one per node: this is the path every model
        // construction takes through `to_poi1`.
        SubMesh::from_connectivity(coords, ElementType::POI1, nodes.to_vec())
    }

    /// Canonical POI1 node cloud of this submesh — its nodes **de-duplicated in
    /// order of first appearance** (one POI1 cell per unique node), as a sealed
    /// [`SubMesh`] handle.
    ///
    /// **Cached, per submesh.** The companion is built at most once per state
    /// of the connectivity, and every later call returns the *same* store slot,
    /// so all the node fields that project this submesh to its nodes pair under
    /// [`same_support`](crate::containers::field::SubField::same_support): a
    /// stiffness block's support (built this way in every physics' `new`), a
    /// [`restrict`](fn@crate::ops::node_field::restrict) onto this mesh, and a
    /// `divergence`/`flux`/`internal_forces` output over it all share one handle
    /// and combine directly by the field operators. This is what lets
    /// `solve(K, f) - restrict(g, mesh)` and `&K * &restrict(f, mesh)` line up.
    ///
    /// The cache does **not** require `self` to be sealed: every mutator drops
    /// it (see `invalidate_caches`), so a submesh that keeps growing simply
    /// hands out a new companion afterwards. The companion itself is always
    /// sealed — it is what node fields index their rows by. Shared building
    /// block: [`crate::ops::mesh::to_poi1()`] applies it submesh-by-submesh.
    pub fn to_poi1(&self) -> Result<Handle<SubMesh>> {
        if let Some(h) = self.poi1_companion.get() {
            return Ok(h.clone());
        }
        // De-duplicate in **order of first appearance**. The membership test goes
        // through a hash set, not a linear scan of `seen`: this runs on every
        // model construction, and a `Vec::contains` here made the whole operator
        // quadratic (640 k QUA4 took ~8 min, versus ~40 ms now).
        let mut seen: Vec<NodeId> = Vec::with_capacity(self.connectivity.len());
        let mut known: HashSet<NodeId> = HashSet::with_capacity(self.connectivity.len());
        for &nid in &self.connectivity {
            if known.insert(nid) {
                seen.push(nid);
            }
        }
        // Build (write-locks `Coords`) and seal the companion. `self` is behind
        // the caller's read guard on this submesh — a different slot than the
        // POI1 companion and `Coords` — so no lock inversion (same discipline
        // the previous `Handle::new(sm.read().to_poi1()?)` idiom already relied on).
        // `seen` is **handed over**, not lent: it is already the companion's
        // connectivity, one POI1 cell per id.
        let handle = Handle::new(SubMesh::from_connectivity(
            self.coords.clone(),
            ElementType::POI1,
            seen,
        )?);
        seal(&handle);
        // Memoize. On a race the loser drops its build and everyone reads the
        // winner's slot. Mutating `self` later drops this slot, so what is
        // cached always answers for the current connectivity.
        let _ = self.poi1_companion.set(handle);
        Ok(self
            .poi1_companion
            .get()
            .expect("populated on this path")
            .clone())
    }

    /// Visualize this submesh.
    ///
    /// - `view = None` ⇒ [`crate::viz::View::default`] (isometric).
    /// - `save = None` ⇒ open an interactive window (requires feature
    ///   `viz-interactive`).
    /// - `save = Some(path)` ⇒ write an image file; the format is inferred
    ///   from the extension (`.png`, `.svg`, or `.svgz` for the same SVG
    ///   gzipped — around a tenth of the bytes on disk).
    ///
    /// Every supported element type is rendered: POI1 as dots, SEG2 as
    /// segments, TRI3 / QUA4 as filled polygons, and TET4 / HEX8 as their
    /// outer skin (boundary faces) under the painter's algorithm.
    #[cfg(feature = "viz")]
    pub fn plot(&self, view: crate::viz::View, save: Option<&std::path::Path>) -> Result<()> {
        self.plot_styled(view, save, crate::viz::MeshStyle::default(), None)
    }

    /// Like [`SubMesh::plot`] but choosing the [`crate::viz::MeshStyle`]:
    /// `Surface` (opaque skin) or `Wireframe` (all edges, see-through).
    /// `title`, if given, names the interactive window and is drawn as a
    /// caption at the bottom of a saved PNG/SVG.
    #[cfg(feature = "viz")]
    pub fn plot_styled(
        &self,
        view: crate::viz::View,
        save: Option<&std::path::Path>,
        style: crate::viz::MeshStyle,
        title: Option<&str>,
    ) -> Result<()> {
        crate::viz::render_submesh_styled(self, view, save, style, title)
    }
}

/// Seal the submesh behind `handle`, freezing its connectivity.
///
/// This is the seam every non-mesh consumer goes through when it captures a
/// [`SubMesh`] handle (finite-element space, node field, matrix support, …):
/// from that point on the submesh can no longer grow, so the consumer's
/// cell-indexed view can never go stale. Idempotent; returns the same handle
/// (cloned) for ergonomic chaining at a constructor's capture site.
///
/// **Already-sealed fast path takes only a read lock.** This matters now that
/// [`SubMesh::to_poi1`] is cached: a `restrict` onto a mesh can land on the very
/// support a source field already sits on (the shared POI1 companion), so
/// `from_poi1` may `seal` a support while the caller still holds a *read* guard
/// on it (a field `view`). Sealing is idempotent, so when the submesh is already
/// sealed we skip the write entirely — a read lock coexists with that reader,
/// whereas a write lock would deadlock against it. Taking a write lock while a
/// **write** guard on the same slot is held is still a deadlock (the slot lock is
/// not reentrant — see [`crate::handle`]); only the sealed-read case is relaxed.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # use pyrucast::containers::mesh::seal;
/// // Sealing through the free function rather than the method: it takes the
/// // write lock **only if needed**, which lets it seal a support a reader
/// // already holds — a field's `view`.
/// let zone = maillage.get(0)?;
/// assert!(!zone.read().is_sealed());
/// seal(&zone);
/// assert!(zone.read().is_sealed());
/// // Idempotent, and without a write the second time: the read guard below
/// // coexists, where a write lock would deadlock.
/// let lecteur = zone.read();
/// seal(&zone);
/// assert!(lecteur.is_sealed());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn seal(handle: &Handle<SubMesh>) -> Handle<SubMesh> {
    if handle.read().is_sealed() {
        return handle.clone();
    }
    handle.write().seal();
    handle.clone()
}

impl Drop for SubMesh {
    fn drop(&mut self) {
        // One lock acquisition for all decrefs.
        let mut c = self.coords.write();
        for &n in &self.connectivity {
            let _ = c.decref(n);
        }
    }
}

impl fmt::Debug for SubMesh {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Bounded structure only — the per-cell connectivity lives in `dump()`.
        f.debug_struct("SubMesh")
            .field("element_type", &self.element_type)
            .field("coords", &self.coords)
            .field("cell_count", &self.cell_count())
            .field("face_color", &self.face_color)
            .field("sealed", &self.sealed)
            .finish()
    }
}

impl fmt::Display for SubMesh {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SubMesh<{}>: {} cell(s)",
            self.element_type,
            self.cell_count()
        )
    }
}

impl crate::dump::Dump for SubMesh {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        use crate::dump::table;
        let npc = self.element_type.nodes_per_cell();
        let mut headers = vec!["cell".to_string()];
        headers.extend((0..npc).map(|i| format!("n{i}")));
        let rows: Vec<Vec<String>> = if npc > 0 {
            self.connectivity
                .chunks(npc)
                .enumerate()
                .map(|(i, chunk)| {
                    let mut row = vec![i.to_string()];
                    row.extend(chunk.iter().map(|nid| nid.to_string()));
                    row
                })
                .collect()
        } else {
            Vec::new()
        };
        // The metadata `Display` does not say, before the content: without it
        // the "content" level would tell **less** than the "structure" level
        // (`CONVENTIONS.md` § "Trois niveaux d'affichage"). `sealed` in
        // particular explains why an `add_cell` will fail.
        format!(
            "{self}\n  coords: {}, face_color: {:?}, sealed: {}\n{}",
            self.coords,
            self.face_color,
            self.sealed,
            table(&headers, &rows, opts)
        )
    }
}

// ─── Mesh ───────────────────────────────────────────────────────────────────

/// Mesh: aggregate of submeshes. Each submesh carries its own
/// `Handle<Coords>`; the mesh itself imposes no constraint on
/// `Coords` homogeneity.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::{NodeField, SubNodeField};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// // The aggregate of zones: each homogeneous, the whole not being so. That
/// // is what lets a mesh mix triangles and quadrangles without anything
/// // downstream having to care.
/// assert_eq!(maillage.len(), 1);
/// assert_eq!(maillage.cell_count(), 1);
/// assert_eq!(maillage.element_types()?, vec![ElementType::TRI3]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize, Default)]
pub struct Mesh {
    subs: Vec<Handle<SubMesh>>,
}

crate::impl_aggregate!(Mesh, SubMesh, submesh, "submesh(es)", {
    fn display_extra(&self) -> Option<String> {
        Some(format!(", {} cell(s) total", self.cell_count()))
    }
    fn check_push(&self, h: &Handle<SubMesh>) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }
        let a = self.coords()?;
        let b = h.read().coords();
        if !a.same_object(&b) {
            Err(PyrucastError::Message("mismatched Coords".into()))
        } else {
            Ok(())
        }
    }
});

crate::impl_aggregate_dump!(Mesh);

// ─── Building POI1 point meshes by union ─────────────────────────────────────
//
// `node.union(node)` and (unitary POI1) `mesh.union_node(node)` both yield a
// fresh unitary POI1 `Mesh` — a points mesh grown one node at a time. Exposed
// to Python as `node | node` and `mesh | node` (the same `|` as the
// aggregates' union). See also [`SubMesh::poi1_from_nodes`].

impl Node {
    /// `node.union(other)` → a unitary POI1 [`Mesh`] over both nodes.
    /// Python: `node | node`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// // The same `|` as the aggregates', applied to two nodes: a one-zone
    /// // POI1 mesh, which one then grows node by node.
    /// let deux = n[0].union(&n[1])?;
    /// assert_eq!(deux.cell_count(), 2);
    /// assert_eq!(deux.element_types()?, vec![ElementType::POI1]);
    /// assert_eq!(deux.union_node(&n[2])?.cell_count(), 3);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn union(&self, other: &Node) -> Result<Mesh> {
        let sm = SubMesh::poi1_from_nodes(&[self.clone(), other.clone()])?;
        Ok(Mesh::from_submesh(sm))
    }
}

impl Mesh {
    /// `mesh.union_node(node)` → a unitary POI1 [`Mesh`] holding this mesh's
    /// points plus `node`. Errors unless `self` is **unitary and POI1**
    /// (exactly one POI1 submesh). Python: `mesh | node`.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// // The left operand must be a **one-zone POI1 cloud**: this is a union
    /// // of points, not the addition of a point to an arbitrary mesh.
    /// let nuage = pyrucast::ops::mesh::poi1_from_nodes(&[n[0].clone()]).unwrap();
    /// let deux_points = nuage.union_node(&n[1]).unwrap();
    /// assert_eq!(deux_points.cell_count(), 2);
    /// ```
    pub fn union_node(&self, node: &Node) -> Result<Mesh> {
        let sub = self.unit()?;
        let (et, coords, mut ids) = {
            let s = sub.read();
            (s.element_type(), s.coords(), s.connectivity().to_vec())
        };
        if et != ElementType::POI1 {
            return Err(PyrucastError::Message(
                "Mesh | Node: expected a unitary POI1 mesh".into(),
            ));
        }
        ids.push(node.id());
        Ok(Mesh::from_submesh(SubMesh::poi1_from_node_ids(
            coords, &ids,
        )?))
    }
}

impl Mesh {
    /// Total cells in the mesh (sum across submeshes).
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(mesh.cell_count(), 1); // toutes zones confondues
    /// ```
    pub fn cell_count(&self) -> usize {
        let mut total = 0usize;
        for sm in self {
            total += sm.read().cell_count();
        }
        total
    }

    /// Handle to the `Coords` of the first submesh.
    ///
    /// Returns an error if the mesh has no submeshes.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::handle::Handle as H;
    /// // The mesh does not carry the `Coords`: it finds it through its zones.
    /// assert!(H::same_object(&mesh.coords().unwrap(), &coords));
    /// ```
    pub fn coords(&self) -> Result<Handle<Coords>> {
        let sm = self
            .items()
            .first()
            .ok_or_else(|| PyrucastError::Message("coords: mesh has no submeshes".into()))?;
        Ok(sm.read().coords())
    }

    /// Create a mesh wrapping a single `SubMesh`. Config-free at the Mesh
    /// level: the submesh already carries its `Coords` (a Mesh is a
    /// pure aggregate of submeshes). The submesh is moved into the store.
    ///
    /// ```
    /// # use pyrucast::atoms::ElementType;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # use pyrucast::aggregate::Aggregate;
    /// // The shortcut of the single-zone case.
    /// let mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
    /// assert_eq!(mesh.len(), 1);
    /// ```
    pub fn from_submesh(sub: SubMesh) -> Self {
        let mut mesh = Self::default();
        mesh.subs.push(Handle::new(sub));
        mesh
    }

    /// Deep-copy the whole mesh: every submesh is [`SubMesh::duplicate`]d
    /// into a fresh, unsealed submesh under a new handle. The copy is fully
    /// editable even when the source's submeshes have been sealed by their
    /// consumers; nodes are shared (same `Coords`), only their refcounts grow.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// FiniteElementSpace::lagrange1(&mesh).unwrap(); // scelle la zone
    /// let mut copie = mesh.duplicate().unwrap(); // neuve, modifiable
    /// copie.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(copie.cell_count(), 2);
    /// ```
    pub fn duplicate(&self) -> Result<Mesh> {
        let mut copy = Self::default();
        for sm in self {
            let dup = sm.read().duplicate()?;
            copy.subs.push(Handle::new(dup));
        }
        Ok(copy)
    }

    /// Paint **every** submesh with the same face colour, and hand the mesh
    /// back so the call chains — `mesh::circle(…)?.set_face_color(rouge)`.
    ///
    /// What comes back holds the very **same** zones (the same handles), not
    /// copies of them: it *is* this mesh, and the two are interchangeable.
    /// The colour is viz metadata — [`SubMesh::set_face_color`] on each zone —
    /// so a **sealed** mesh takes it without complaint; the seal freezes the
    /// connectivity, not the way it is drawn.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node, RgbColor};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let seg = { let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// #     sm.add_cell(&[n[0].id(), n[1].id()]).unwrap(); Handle::new(sm) };
    /// # mesh.add_sub(seg).unwrap();
    /// // One colour for every zone, without a loop — and the mesh comes back,
    /// // to chain on.
    /// let rouge = RgbColor::new(220, 60, 60);
    /// assert_eq!(mesh.set_face_color(rouge).cell_count(), 2);
    /// assert!(mesh.iter().all(|z| z.read().face_color() == rouge));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn set_face_color(&self, color: RgbColor) -> Mesh {
        let mut same = Self::default();
        for sub in self {
            sub.write().set_face_color(color);
            same.subs.push(sub.clone());
        }
        same
    }

    /// Add a cell directly when the mesh has exactly one submesh.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::node_field::{NodeField, SubNodeField};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::ops::mesh;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// // The shortcut of the **single-zone** case: it adds into the one zone,
    /// // and refuses as soon as there are several — the ambiguity would be
    /// // silent.
    /// let mut m = maillage;
    /// m.add_cell(&[n[0].id(), n[1].id(), n[2].id()])?;
    /// assert_eq!(m.cell_count(), 2);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.len() != 1 {
            return Err(PyrucastError::Message(
                "add_cell: mesh must have exactly one submesh".into(),
            ));
        }
        self.subs[0].write().add_cell(nodes)
    }

    /// Element type of each submesh, in order.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(mesh.element_types().unwrap(), vec![ElementType::TRI3]);
    /// ```
    pub fn element_types(&self) -> Result<Vec<ElementType>> {
        self.iter().map(|sm| Ok(sm.read().element_type())).collect()
    }

    /// Cell count of each submesh, in order.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(mesh.cell_counts().unwrap(), vec![1]); // one entry per zone
    /// ```
    pub fn cell_counts(&self) -> Result<Vec<usize>> {
        self.iter().map(|sm| Ok(sm.read().cell_count())).collect()
    }

    /// The mesh node closest (Euclidean distance) to `point`.
    ///
    /// `point` must have the mesh `Coords` spatial dimension. Only nodes
    /// actually referenced by a cell are considered; ties are broken by the
    /// smaller `NodeId`, so the result does not depend on iteration order.
    ///
    /// The natural way to pick a node to pin a boundary condition on, or to
    /// read a result at, when you know roughly *where* it is but not its id.
    ///
    /// Errors if the mesh has no submeshes, references no nodes, or if
    /// `point`'s length does not match the coordinate dimension.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// // The node nearest to an arbitrary point, Euclidean distance.
    /// let proche = mesh.nearest_node(&[0.9, 0.1]).unwrap();
    /// assert_eq!(proche.position().unwrap(), vec![1.0, 0.0]);
    /// ```
    pub fn nearest_node(&self, point: &[f64]) -> Result<Node> {
        let coords_handle = self.coords()?;

        // Gather the unique node ids the mesh references, across all submeshes.
        let mut seen: HashSet<NodeId> = HashSet::new();
        for sm in self {
            let s = sm.read();
            for &nid in s.connectivity() {
                seen.insert(nid);
            }
        }

        let best = {
            let c = coords_handle.read();
            if point.len() != c.dim() as usize {
                return Err(PyrucastError::Message(format!(
                    "nearest_node: point has {} coordinates, mesh is {}-D",
                    point.len(),
                    c.dim()
                )));
            }
            let mut best: Option<(NodeId, f64)> = None;
            for &nid in &seen {
                let x = c.position(nid)?;
                let d2: f64 = x.iter().zip(point).map(|(a, b)| (a - b) * (a - b)).sum();
                // Strictly-less keeps the first (smallest id) on a tie, but `seen`
                // is a set with no stable order, so compare ids explicitly.
                match best {
                    Some((bid, bd2)) if bd2 < d2 || (bd2 == d2 && bid.0 <= nid.0) => {}
                    _ => best = Some((nid, d2)),
                }
            }
            best
        };

        let (nid, _) = best.ok_or_else(|| {
            PyrucastError::Message("nearest_node: mesh references no nodes".into())
        })?;
        Node::acquire(coords_handle, nid)
    }

    /// Node at position `node_idx` in cell `cell_idx` of submesh `submesh_idx`.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// let a = mesh.node(0, 0, 0).unwrap(); // zone 0, cellule 0, sommet 0
    /// assert_eq!(a.position().unwrap(), vec![0.0, 0.0]);
    /// ```
    pub fn node(&self, submesh_idx: usize, cell_idx: usize, node_idx: usize) -> Result<Node> {
        let sm = self.get(submesh_idx)?;
        let (nid, coords) = {
            let s = sm.read();
            let npc = s.element_type.nodes_per_cell();
            let n = s.cell_count();
            if cell_idx >= n {
                return Err(PyrucastError::Message(format!(
                    "node: cell index {} ≥ cell_count {}",
                    cell_idx, n
                )));
            }
            let nid = s
                .connectivity()
                .get(cell_idx * npc + node_idx)
                .copied()
                .ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "node: node index {} ≥ nodes_per_cell {}",
                        node_idx, npc
                    ))
                })?;
            (nid, s.coords())
        };
        Node::acquire(coords, nid)
    }

    /// Return a `Cell` view on cell `cell_idx` of submesh `submesh_idx`.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// let c = mesh.cell(0, 0).unwrap();
    /// assert_eq!(c.nodes_per_cell(), 3);
    /// ```
    pub fn cell(&self, submesh_idx: usize, cell_idx: usize) -> Result<Cell> {
        let sm = self.get(submesh_idx)?;
        Cell::new(sm, cell_idx)
    }

    /// Iterator over every cell of submesh `submesh_idx`.
    ///
    /// ```
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
    /// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// assert_eq!(mesh.cells(0).unwrap().count(), 1);
    /// ```
    pub fn cells(&self, submesh_idx: usize) -> Result<CellIter> {
        let sm = self.get(submesh_idx)?;
        let end = sm.read().cell_count();
        Ok(CellIter::new(sm, end))
    }

    /// Visualize this mesh — every submesh is drawn, each in its own
    /// [`SubMesh::face_color`]. See [`SubMesh::plot`] for the meaning of
    /// `view` and `save` and the supported element types.
    #[cfg(feature = "viz")]
    pub fn plot(&self, view: crate::viz::View, save: Option<&std::path::Path>) -> Result<()> {
        self.plot_styled(view, save, crate::viz::MeshStyle::default(), None)
    }

    /// Like [`Mesh::plot`] but choosing the [`crate::viz::MeshStyle`]:
    /// `Surface` (opaque skin) or `Wireframe` (all edges, see-through).
    /// Each submesh is drawn in its own `face_color`. `title`, if given,
    /// names the interactive window and is drawn as a caption at the bottom
    /// of a saved PNG/SVG.
    #[cfg(feature = "viz")]
    pub fn plot_styled(
        &self,
        view: crate::viz::View,
        save: Option<&std::path::Path>,
        style: crate::viz::MeshStyle,
        title: Option<&str>,
    ) -> Result<()> {
        crate::viz::render_mesh_styled(self, view, save, style, title)
    }

    /// Visualize this mesh coloured by a field component — a
    /// [`crate::containers::node_field::NodeField`] **or** an
    /// [`crate::containers::element_field::ElementField`], uniformly via
    /// [`crate::viz::FieldArg`].
    ///
    /// Per-cell colour comes from the cell's nodal values (read directly
    /// for a node field; fitted per element from the Gauss values for an
    /// element field — inter-element discontinuities stay visible).
    /// `component = None` selects the field's first component.
    ///
    /// The interactive window draws a clickable button at the top
    /// showing the current component and value range; clicking it (or
    /// pressing `Tab`) cycles through the field's components. A colorbar
    /// is drawn on the right edge; `scale` pins its bounds (default:
    /// the data's own min/max).
    ///
    /// For a single submesh, use
    /// [`crate::viz::render_submesh_with_field`] with the submesh handle.
    // Eight orthogonal rendering options, all optional at the Python layer:
    // grouping them into a struct would only move the argument list.
    #[allow(clippy::too_many_arguments)]
    #[cfg(feature = "viz")]
    pub fn plot_with_field(
        &self,
        view: crate::viz::View,
        save: Option<&std::path::Path>,
        field: crate::viz::FieldArg<'_>,
        component: Option<&str>,
        scale: crate::viz::ColorScale,
        smooth: usize,
        title: Option<&str>,
    ) -> Result<()> {
        crate::viz::render_mesh_with_field(self, field, component, scale, smooth, view, save, title)
    }
}

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

// ─── Archive ────────────────────────────────────────────────────────────────

impl crate::archive::Archivable for SubMesh {
    const TAG: &'static str = "SubMesh";

    /// Re-increment the nodes this submesh uses.
    ///
    /// `Drop` decrements them, so without this the counts would go negative the
    /// day the reloaded mesh dies. The owning `Coords` has already been decoded
    /// and zeroed — that is what the post-order is for.
    fn on_load(&mut self) {
        let mut coords = self.coords.write();
        for &n in &self.connectivity {
            let _ = coords.incref(n);
        }
    }
}

impl crate::archive::Archivable for Mesh {
    const TAG: &'static str = "Mesh";
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handle::Handle;

    #[test]
    fn submesh_poi1_is_node_list() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        sm.add_cell(&[b.id()]).unwrap();
        assert_eq!(sm.cell_count(), 2);
        assert_eq!(sm.connectivity()[0], a.id());
        assert_eq!(sm.connectivity()[1], b.id());
    }

    #[test]
    fn poi1_from_nodes_derives_config_and_builds() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();

        // Node-based form: Coords is taken from the nodes themselves.
        let sm = SubMesh::poi1_from_nodes(&[a.clone(), b.clone()]).unwrap();
        assert_eq!(sm.element_type(), ElementType::POI1);
        assert_eq!(sm.cell_count(), 2);
        assert_eq!(sm.connectivity(), &[a.id(), b.id()]);
        // Matches the id-based form on the same nodes.
        let sm2 = SubMesh::poi1_from_node_ids(coords.clone(), &[a.id(), b.id()]).unwrap();
        assert_eq!(sm.connectivity(), sm2.connectivity());
    }

    #[test]
    fn poi1_from_nodes_empty_is_error() {
        assert!(SubMesh::poi1_from_nodes(&[]).is_err());
    }

    #[test]
    fn submesh_tri3_increfs_and_drop_decrefs() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        // SubMesh increfed each of the 3 nodes, in addition to the Nodes.
        {
            let cf = coords.read();
            assert_eq!(cf.refcount(a.id()), 2);
            assert_eq!(cf.refcount(b.id()), 2);
            assert_eq!(cf.refcount(c.id()), 2);
        }
        drop(sm);
        {
            let cf = coords.read();
            assert_eq!(cf.refcount(a.id()), 1);
            assert_eq!(cf.refcount(b.id()), 1);
            assert_eq!(cf.refcount(c.id()), 1);
        }
    }

    #[test]
    fn node_index_maps_distinct_nodes_in_first_appearance_order() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();

        // Two QUA4 cells sharing the edge (b, c): b and c appear twice.
        let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
        sm.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();
        let e = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let f = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
        sm.add_cell(&[b.id(), e.id(), f.id(), c.id()]).unwrap();

        let map = sm.node_index();
        // Distinct nodes, indexed by first appearance in the connectivity.
        assert_eq!(map.len(), 6);
        assert_eq!(map[&a.id()], 0);
        assert_eq!(map[&b.id()], 1);
        assert_eq!(map[&c.id()], 2);
        assert_eq!(map[&d.id()], 3);
        assert_eq!(map[&e.id()], 4);
        assert_eq!(map[&f.id()], 5);
        // Cached: a second call returns the same populated map.
        assert_eq!(sm.node_index().len(), 6);
    }

    #[test]
    fn sealed_submesh_refuses_add_cell() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        assert!(!sm.is_sealed());
        sm.seal();
        assert!(sm.is_sealed());
        // Both mutating paths are now blocked with MeshSealed.
        assert!(matches!(
            sm.add_cell(&[b.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
        assert!(matches!(
            sm.add_cell_taking(&[b.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
        assert_eq!(sm.cell_count(), 1);
        // The refused cell left no lingering incref on b.
        assert_eq!(coords.read().refcount(b.id()), 1);
    }

    #[test]
    fn seal_via_handle_and_is_idempotent() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let h = Handle::new({
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[a.id()]).unwrap();
            sm
        });
        seal(&h);
        seal(&h); // idempotent
        assert!(h.read().is_sealed());
        assert!(matches!(
            h.write().add_cell(&[a.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
    }

    #[test]
    fn duplicate_is_unsealed_and_reincrefs() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        sm.seal();

        let mut copy = sm.duplicate().unwrap();
        // Copy carries the same connectivity but is not sealed.
        assert!(!copy.is_sealed());
        assert_eq!(copy.connectivity(), sm.connectivity());
        // Each node is now referenced by the original AND the copy (+ Node).
        {
            let cf = coords.read();
            assert_eq!(cf.refcount(a.id()), 3);
        }
        // The copy is editable even though the source is frozen.
        let d = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        copy.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
        assert_eq!(copy.cell_count(), 2);
        assert_eq!(sm.cell_count(), 1);
    }

    #[test]
    fn remap_nodes_rewrites_connectivity_and_moves_refcounts() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
        let b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b2.id(), c.id()]).unwrap();
        sm.add_cell(&[b2.id(), c.id(), a.id()]).unwrap();

        // b2 appears twice in the connectivity: two units, plus its Node.
        assert_eq!(coords.read().refcount(b2.id()), 3);
        assert_eq!(coords.read().refcount(b.id()), 1);

        let map = HashMap::from([(b2.id(), b.id()), (a.id(), a.id())]);
        assert_eq!(sm.remap_nodes(&map).unwrap(), 2, "two slots rewritten");

        assert_eq!(sm.cell_count(), 2, "renaming never changes the cells");
        assert_eq!(sm.connectivity()[1], b.id());
        assert_eq!(sm.connectivity()[3], b.id());
        // The two units moved from b2 to b; the identity entry moved nothing.
        assert_eq!(coords.read().refcount(b2.id()), 1);
        assert_eq!(coords.read().refcount(b.id()), 3);

        // Re-applying the same map is a no-op (idempotent by construction).
        assert_eq!(sm.remap_nodes(&map).unwrap(), 0);
    }

    #[test]
    fn remap_nodes_drops_the_derived_caches() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[a.id(), b2.id()]).unwrap();
        // Populate the node_index cache before the rename.
        assert!(sm.node_index().contains_key(&b2.id()));

        sm.remap_nodes(&HashMap::from([(b2.id(), b.id())])).unwrap();
        let index = sm.node_index();
        assert!(
            index.contains_key(&b.id()),
            "cache rebuilt on the new nodes"
        );
        assert!(!index.contains_key(&b2.id()));
    }

    #[test]
    fn remap_nodes_refuses_a_sealed_submesh() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 b2 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[a.id(), b2.id()]).unwrap();
        sm.seal();

        assert!(matches!(
            sm.remap_nodes(&HashMap::from([(b2.id(), b.id())]))
                .unwrap_err(),
            PyrucastError::MeshSealed
        ));
        assert_eq!(sm.connectivity()[1], b2.id(), "left untouched");
    }

    #[test]
    fn mesh_duplicate_yields_editable_copy() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        sm.seal();
        let mesh = Mesh::from_submesh(sm);

        let mut copy = mesh.duplicate().unwrap();
        assert_eq!(copy.cell_count(), 1);
        // A fresh submesh handle: editable.
        copy.add_cell(&[b.id()]).unwrap();
        assert_eq!(copy.cell_count(), 2);
    }

    #[test]
    fn submesh_add_cell_invalid_arity() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        let err = sm.add_cell(&[a.id()]).unwrap_err();
        assert!(matches!(err, PyrucastError::Message(_)));
        // No increment should have survived the failure.
        assert_eq!(coords.read().refcount(a.id()), 1);
    }

    #[test]
    fn submesh_add_cell_collected_node_rollback() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let dead_id = coords.write().add_node(&[2.0]).unwrap();
        // dead_id starts at refcount=1; decrement then collect.
        {
            let mut c = coords.write();
            c.decref(dead_id).unwrap();
            assert_eq!(c.gc(), 1);
        }

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        // a (live), b (live), dead_id (collected) → add_cell fails after
        // increfing a and b. The rollback must undo those increfs.
        let err = sm.add_cell(&[a.id(), b.id(), dead_id]).unwrap_err();
        assert!(matches!(err, PyrucastError::Message(_)));
        {
            let cf = coords.read();
            assert_eq!(cf.refcount(a.id()), 1, "a must be rolled back");
            assert_eq!(cf.refcount(b.id()), 1, "b must be rolled back");
        }
        assert_eq!(sm.cell_count(), 0);
    }

    #[test]
    fn from_connectivity_refuses_a_dead_node_without_increfing_anything() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let dead_id = coords.write().add_node(&[2.0]).unwrap();
        {
            let mut c = coords.write();
            c.decref(dead_id).unwrap();
            assert_eq!(c.gc(), 1);
        }

        let err = SubMesh::from_connectivity(
            coords.clone(),
            ElementType::TRI3,
            vec![a.id(), b.id(), dead_id],
        )
        .unwrap_err();
        assert!(matches!(err, PyrucastError::Message(_)));
        // Validation comes first: nothing was increfed on the way out.
        let cf = coords.read();
        assert_eq!((cf.refcount(a.id()), cf.refcount(b.id())), (1, 1));
    }

    #[test]
    fn mesh_aggregates_submeshes_same_config() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 cc = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let sm_pts = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[a.id()]).unwrap();
            sm.add_cell(&[b.id()]).unwrap();
            Handle::new(sm)
        };
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), cc.id()]).unwrap();
            Handle::new(sm)
        };

        let mut mesh = Mesh::empty();
        mesh.add_sub(sm_pts).unwrap();
        mesh.add_sub(sm_tri).unwrap();
        assert_eq!(mesh.len(), 2);
        assert_eq!(mesh.cell_count(), 3); // 2 points + 1 triangle
    }

    #[test]
    fn mesh_element_types_and_cell_counts() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m.add_cell(&[a.id()]).unwrap();
        m.add_cell(&[b.id()]).unwrap();
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
            Handle::new(sm)
        };
        m.add_sub(sm_tri).unwrap();

        assert_eq!(
            m.element_types().unwrap(),
            vec![ElementType::POI1, ElementType::TRI3]
        );
        assert_eq!(m.cell_counts().unwrap(), vec![2, 1]);
    }

    #[test]
    fn mesh_index_and_iter_sugar() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m.add_cell(&[a.id()]).unwrap();
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
            Handle::new(sm)
        };
        m.add_sub(sm_tri).unwrap();

        let et0 = m[0].read().element_type();
        let et1 = m[1].read().element_type();
        assert_eq!(et0, ElementType::POI1);
        assert_eq!(et1, ElementType::TRI3);

        let types: Vec<ElementType> = (&m).into_iter().map(|h| h.read().element_type()).collect();
        assert_eq!(types, vec![ElementType::POI1, ElementType::TRI3]);
    }

    #[test]
    fn mesh_node_access_by_indices() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        let n = m.node(0, 0, 0).unwrap();
        assert_eq!(n.id(), a.id()); // node 0 of element 0 = a
        assert!(m.node(1, 0, 0).is_err()); // submesh out of bounds
        assert!(m.node(0, 1, 0).is_err()); // cell out of bounds
        assert!(m.node(0, 0, 3).is_err()); // node out of bounds (TRI3: indices 0..2)
    }

    #[test]
    fn mesh_merge_combines_submeshes() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut m1 = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m1.add_cell(&[a.id()]).unwrap();
        m1.add_cell(&[b.id()]).unwrap();

        let mut m2 = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m2.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        let merged = m1.union(&m2).unwrap();
        assert_eq!(merged.len(), 2);
        assert_eq!(merged.cell_count(), 3); // 2 POI1 + 1 TRI3
    }

    #[test]
    fn debug_and_display_submesh_and_mesh() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        let d = format!("{:?}", sm);
        let s = format!("{}", sm);
        assert!(d.contains("SubMesh"));
        assert!(s.contains("SEG2"));

        let mesh = Mesh::empty();
        assert!(format!("{:?}", mesh).contains("Mesh"));
        assert!(format!("{}", mesh).contains("submesh"));
    }

    #[test]
    fn aggregate_union_sub_and_sub_union_sub() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 s1 = Handle::new(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let s2 = Handle::new(SubMesh::poi1_from_nodes(std::slice::from_ref(&b)).unwrap());

        // sub | sub → Mesh
        let m = Mesh::union_subs(&s1, &s2).unwrap();
        assert_eq!(m.len(), 2);

        // aggregate | sub → Mesh
        let s3 = Handle::new(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let m2 = m.union_sub(&s3).unwrap();
        assert_eq!(m2.len(), 3);
    }

    #[test]
    fn node_union_node_and_mesh_union_node() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();

        let m = a.union(&b).unwrap();
        assert_eq!(m.len(), 1);
        assert_eq!(m.unit().unwrap().read().cell_count(), 2);

        let m2 = m.union_node(&c).unwrap();
        assert_eq!(m2.unit().unwrap().read().cell_count(), 3);
    }

    #[test]
    fn mesh_union_node_rejects_non_unitary_poi1() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
        let mut tri = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        tri.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        // Non-POI1 → error.
        assert!(tri.union_node(&a).is_err());
    }

    #[test]
    fn to_poi1_caches_companion_even_unsealed() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let h = Handle::new(sm);

        // Unsealed, and still memoized: the companion answers for the current
        // connectivity, and a mutation drops it.
        let u1 = h.read().to_poi1().unwrap();
        let u2 = h.read().to_poi1().unwrap();
        assert!(
            u1.same_object(&u2),
            "companion memoized on an unsealed submesh"
        );
        assert!(
            !h.read().is_sealed(),
            "asking for the companion does not seal"
        );
        assert!(u1.read().is_sealed(), "the companion itself is sealed");
        assert_eq!(u1.read().element_type(), ElementType::POI1);
        assert_eq!(u1.read().cell_count(), 3); // three distinct nodes

        // Sealing changes nothing: same slot.
        seal(&h);
        assert!(h.read().to_poi1().unwrap().same_object(&u1));
    }

    #[test]
    fn growing_a_submesh_drops_its_poi1_companion() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let d = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let h = Handle::new(sm);

        let before = h.read().to_poi1().unwrap();
        assert_eq!(before.read().cell_count(), 3);

        // One more cell ⇒ a different node cloud, so a different companion.
        h.write().add_cell(&[b.id(), d.id(), c.id()]).unwrap();
        let after = h.read().to_poi1().unwrap();
        assert!(
            !before.same_object(&after),
            "the stale companion was dropped"
        );
        assert_eq!(after.read().cell_count(), 4);
        // The old one is untouched — whoever holds it (a field) still reads
        // the three nodes it was built on.
        assert_eq!(before.read().cell_count(), 3);
        // And its node_index went with it.
        assert_eq!(h.read().node_index()[&d.id()], 3);
    }
}

#[cfg(test)]
mod nearest_node_tests {
    use super::*;
    use crate::atoms::ElementType;
    use crate::atoms::Node;
    use crate::containers::mesh::SubMesh;
    use crate::coords::Coords;
    use crate::handle::Handle;

    #[test]
    fn nearest_on_grid() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let n00 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let n10 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let n11 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[n00.id(), n10.id(), n11.id()]).unwrap();
        let mesh = Mesh::from_submesh(sm);

        // Closest to a point just past the far corner is n11.
        let found = mesh.nearest_node(&[0.9, 0.9]).unwrap();
        assert_eq!(found.id(), n11.id());

        // Closest to the origin is n00.
        let found = mesh.nearest_node(&[-0.2, 0.1]).unwrap();
        assert_eq!(found.id(), n00.id());
    }

    #[test]
    fn set_face_color_paints_every_zone_even_sealed() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let seg = {
            let mut sm = SubMesh::new(coords, ElementType::SEG2);
            sm.add_cell(&[a.id(), b.id()]).unwrap();
            sm.set_face_color(RgbColor::new(1, 2, 3));
            Handle::new(sm)
        };
        mesh.add_sub(seg).unwrap();
        // The seal freezes the connectivity, not the way it is drawn.
        crate::containers::finite_element_space::FiniteElementSpace::lagrange1(&mesh).unwrap();
        assert!(mesh.get(0).unwrap().read().is_sealed());

        let rouge = RgbColor::new(220, 60, 60);
        let retour = mesh.set_face_color(rouge);

        assert_eq!(retour.len(), 2);
        for i in 0..2 {
            // The same zones, not copies: the mesh returned is this one.
            assert!(retour.get(i).unwrap().same_object(&mesh.get(i).unwrap()));
            assert_eq!(mesh.get(i).unwrap().read().face_color(), rouge);
        }
    }

    #[test]
    fn dimension_mismatch_errors() {
        let coords = Handle::new(Coords::new(2).unwrap());
        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 mut sm = SubMesh::new(coords, ElementType::SEG2);
        sm.add_cell(&[a.id(), b.id()]).unwrap();
        let mesh = Mesh::from_submesh(sm);
        assert!(mesh.nearest_node(&[0.0, 0.0, 0.0]).is_err());
    }
}