rsplot 0.5.0

silx-style scientific plotting for egui, rendered with wgpu
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
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
//! 3D data items — the `silx.gui.plot3d.items` port.
//!
//! Items hold data plus presentation state (colormap, marker, size) and emit
//! their geometry into a [`Scene3dGeometry`] via [`append_to`](Scatter3D::append_to),
//! the analogue of silx's scene-primitive build. The GPU primitives themselves
//! live in [`crate::render::gpu_scene3d`]; this module is the headless item layer
//! (color mapping + bounds), unit-tested without a GPU.

use std::collections::BTreeSet;

use egui::Color32;

use crate::core::colormap::{AutoscaleMode, Colormap, ColormapName};
use crate::core::complex::ComplexMode;
use crate::core::scatter_viz::delaunay;
use crate::core::scene3d::marching_cubes::isosurface as marching_cubes_isosurface;
use crate::core::scene3d::mat4::{Mat4, Vec3, mat4_rotate};
use crate::core::scene3d::plane::{Plane, box_plane_intersect, segment_plane_intersect};
use crate::core::scene3d::transform::Item3DTransform;
use crate::render::gpu_scene3d::{
    ImageInterpolation, PointMarker, Scene3dGeometry, Scene3dImageLayer, Scene3dTexturedMesh,
    flat_normal,
};

/// silx's default plot symbol size in pixels (`_config.DEFAULT_PLOT_SYMBOL_SIZE`).
pub const DEFAULT_SCATTER3D_SIZE: f32 = 6.0;

/// The autoscale mode a colormapped 3D item uses to refresh its auto bounds on
/// data change — silx's default `Colormap.MINMAX` (`Colormap._DEFAULT_MODE`).
const DEFAULT_COLORMAP_AUTOSCALE_MODE: AutoscaleMode = AutoscaleMode::MinMax;

/// Append `build`'s raw geometry through `transform` — the single owner of the
/// bake-time transform application. silx applies the `DataItem3D` transform
/// stack in the scene graph at render time (`items/core.py:288-315`); this
/// port bakes the composed matrix into the channels
/// ([`Scene3dGeometry::apply_transform`]) when the item appends, so rendering
/// and the CPU pick traversal read the same transformed positions by
/// construction. `raw_bounds` are the item's untransformed data bounds,
/// against which bbox-relative rotation centres resolve
/// (`items/core.py:376-405`).
fn append_with_transform(
    transform: &Item3DTransform,
    raw_bounds: Option<(Vec3, Vec3)>,
    geometry: &mut Scene3dGeometry,
    build: impl FnOnce(&mut Scene3dGeometry),
) {
    if transform.is_identity() {
        build(geometry);
    } else {
        let mut local = Scene3dGeometry::new();
        build(&mut local);
        local.apply_transform(&transform.composed_matrix(raw_bounds));
        geometry.extend_from(&local);
    }
}

/// Generate the transform-stack accessors of a 3D item. The stack itself —
/// with the silx public setters `set_scale`/`set_translation`/
/// `set_rotation_center`/`set_rotation`/`set_matrix`
/// (`items/core.py:335-485`) — is [`Item3DTransform`], reached through
/// `transform()`/`transform_mut()` (the names stay on the transform type
/// because some items already use `set_scale` for their 2D pixel scale).
macro_rules! impl_item3d_transform {
    ($ty:ty) => {
        impl $ty {
            /// The item's transform stack (silx `DataItem3D` transforms,
            /// `items/core.py:288-315`).
            pub fn transform(&self) -> &Item3DTransform {
                &self.transform
            }

            /// Mutable access to the transform stack — e.g.
            /// `item.transform_mut().set_scale(2.0, 2.0, 1.0)` (silx
            /// `setScale`, `items/core.py:335-345`). Applied on the next
            /// `append_to`; [`Self::bounds`] reflects it immediately.
            pub fn transform_mut(&mut self) -> &mut Item3DTransform {
                &mut self.transform
            }
        }
    };
}

/// A 3D scatter plot: per-point `(x, y, z)` positions coloured by a per-point
/// `value` through a [`Colormap`], drawn as [`PointMarker`] sprites of one size.
///
/// Port of silx `plot3d.items.Scatter3D` (`DataItem3D` + `ColormapMixIn` +
/// `SymbolMixIn`). silx colours points on the GPU from a colormap texture; here
/// the mapping is done on the CPU via [`Colormap::color_at`] when building the
/// geometry — simpler, and points are few relative to image rasters.
#[derive(Clone, Debug)]
pub struct Scatter3D {
    x: Vec<f32>,
    y: Vec<f32>,
    z: Vec<f32>,
    values: Vec<f64>,
    colormap: Colormap,
    marker: PointMarker,
    size: f32,
    transform: Item3DTransform,
}

impl Default for Scatter3D {
    fn default() -> Self {
        Self::new()
    }
}

impl Scatter3D {
    /// An empty scatter with silx defaults: the gray colormap over `[0, 1]`,
    /// circle markers at [`DEFAULT_SCATTER3D_SIZE`].
    pub fn new() -> Self {
        Self {
            x: Vec::new(),
            y: Vec::new(),
            z: Vec::new(),
            values: Vec::new(),
            colormap: Colormap::autoscale(ColormapName::Gray),
            marker: PointMarker::Circle,
            size: DEFAULT_SCATTER3D_SIZE,
            transform: Item3DTransform::default(),
        }
    }

    /// Replace the point data (silx `Scatter3D.setData`). The four arrays must be
    /// the same length; on a length mismatch the data is left unchanged and
    /// `false` is returned (silx asserts equal lengths).
    pub fn set_data(&mut self, x: &[f32], y: &[f32], z: &[f32], values: &[f64]) -> bool {
        let n = x.len();
        if y.len() != n || z.len() != n || values.len() != n {
            return false;
        }
        self.x = x.to_vec();
        self.y = y.to_vec();
        self.z = z.to_vec();
        self.values = values.to_vec();
        self.resolve_colormap();
        true
    }

    /// Builder form of [`set_data`](Self::set_data); a length mismatch leaves the
    /// data empty.
    pub fn with_data(mut self, x: &[f32], y: &[f32], z: &[f32], values: &[f64]) -> Self {
        self.set_data(x, y, z, values);
        self
    }

    /// Set the colormap (silx `ColormapMixIn.setColormap`). An autoscale
    /// colormap immediately resolves its range to the current data.
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
        self.resolve_colormap();
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.set_colormap(colormap);
        self
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap (e.g. to set the value range directly).
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Refresh the autoscale bounds of the colormap from the current values —
    /// silx `_syncSceneColormap` pushing `getColormapRange(data)` on every data
    /// or colormap change. A no-op for a fully pinned colormap.
    fn resolve_colormap(&mut self) {
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &self.values);
    }

    /// Fit the colormap's value range to the current data with `mode` (silx's
    /// colormap autoscale over the value array), returning the new `(vmin, vmax)`.
    /// With no data the range falls back to the autoscale default, matching
    /// [`AutoscaleMode::range`].
    pub fn autoscale_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        let (vmin, vmax) = self.colormap.autoscale_range(mode, &self.values);
        self.colormap.vmin = vmin;
        self.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// Set the marker shape (silx `SymbolMixIn.setSymbol`).
    pub fn set_marker(&mut self, marker: PointMarker) {
        self.marker = marker;
    }

    /// Builder form of [`set_marker`](Self::set_marker).
    pub fn with_marker(mut self, marker: PointMarker) -> Self {
        self.marker = marker;
        self
    }

    /// Set the marker size in pixels (silx `SymbolMixIn.setSymbolSize`), clamped
    /// to be non-negative.
    pub fn set_size(&mut self, size: f32) {
        self.size = size.max(0.0);
    }

    /// Builder form of [`set_size`](Self::set_size).
    pub fn with_size(mut self, size: f32) -> Self {
        self.set_size(size);
        self
    }

    /// Number of points.
    pub fn len(&self) -> usize {
        self.x.len()
    }

    /// True when there are no points.
    pub fn is_empty(&self) -> bool {
        self.x.is_empty()
    }

    /// Raw (untransformed) data bounds over the points.
    fn raw_bounds(&self) -> Option<(Vec3, Vec3)> {
        if self.is_empty() {
            return None;
        }
        let mut min = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
        let mut max = Vec3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
        for i in 0..self.len() {
            let (px, py, pz) = (self.x[i], self.y[i], self.z[i]);
            min.x = min.x.min(px);
            min.y = min.y.min(py);
            min.z = min.z.min(pz);
            max.x = max.x.max(px);
            max.y = max.y.max(py);
            max.z = max.z.max(pz);
        }
        Some((min, max))
    }

    /// Axis-aligned scene bounds `(min, max)` over the points, through the
    /// item's transform (silx `DataItem3D` bounds, `transformed=True`), or
    /// `None` when empty. Useful to frame a
    /// [`crate::widget::scene_widget::SceneWidget`].
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(self.raw_bounds())
    }

    /// Append this scatter's points (coloured through the colormap) to
    /// `geometry`, ready to upload via [`crate::render::gpu_scene3d::set_scene3d`].
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        append_with_transform(&self.transform, self.raw_bounds(), geometry, |g| {
            for i in 0..self.len() {
                let [r, gr, b, a] = self.colormap.color_at(self.values[i]);
                g.add_point(
                    [self.x[i], self.y[i], self.z[i]],
                    Color32::from_rgba_unmultiplied(r, gr, b, a),
                    self.size,
                    self.marker,
                );
            }
        });
    }
}

impl_item3d_transform!(Scatter3D);

/// silx default line width for a [`Scatter2D`] in LINES mode
/// (`Scatter2D.__init__`: `self._lineWidth = 1.0`).
pub const DEFAULT_SCATTER2D_LINE_WIDTH: f32 = 1.0;

/// How a [`Scatter2D`]'s `(x, y, value)` data is drawn (silx
/// `ScatterVisualizationMixIn.Visualization`, restricted to the three modes
/// `Scatter2D` supports).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Scatter2DVisualization {
    /// A marker sprite at each point, coloured by its value (silx `POINTS` —
    /// uses `symbol` + `symbolSize`).
    #[default]
    Points,
    /// The edges of the points' Delaunay triangulation, coloured by value (silx
    /// `LINES` — uses `lineWidth`).
    Lines,
    /// The filled Delaunay triangles, coloured by value (silx `SOLID`).
    Solid,
}

/// A 2D scatter `(x, y, value)` placed in the 3D scene: the points lie on the
/// `z = 0` plane, or are lifted to `z = value` in height-map mode. The value
/// drives a [`Colormap`], and the data is drawn as markers, triangulation edges,
/// or filled triangles per its [`Scatter2DVisualization`].
///
/// Port of silx `plot3d.items.Scatter2D` (`DataItem3D` + `ColormapMixIn` +
/// `SymbolMixIn` + `ScatterVisualizationMixIn`). The LINES/SOLID modes triangulate
/// `(x, y)` with [`delaunay`] (silx's matplotlib `Triangulation`); as for
/// [`Scatter3D`] the value→colour mapping is done on the CPU via
/// [`Colormap::color_at`] rather than silx's GPU colormap texture. SOLID uses one
/// flat face normal per triangle (silx's per-triangle normals in height-map mode;
/// the `(0, 0, 1)` plane normal when flat).
#[derive(Clone, Debug)]
pub struct Scatter2D {
    x: Vec<f64>,
    y: Vec<f64>,
    values: Vec<f64>,
    colormap: Colormap,
    marker: PointMarker,
    size: f32,
    line_width: f32,
    height_map: bool,
    visualization: Scatter2DVisualization,
    transform: Item3DTransform,
}

impl Default for Scatter2D {
    fn default() -> Self {
        Self::new()
    }
}

impl Scatter2D {
    /// An empty scatter with silx defaults: the gray colormap over `[0, 1]`,
    /// circle markers at [`DEFAULT_SCATTER3D_SIZE`], POINTS visualization, flat
    /// (not height-map).
    pub fn new() -> Self {
        Self {
            x: Vec::new(),
            y: Vec::new(),
            values: Vec::new(),
            colormap: Colormap::autoscale(ColormapName::Gray),
            marker: PointMarker::Circle,
            size: DEFAULT_SCATTER3D_SIZE,
            line_width: DEFAULT_SCATTER2D_LINE_WIDTH,
            height_map: false,
            visualization: Scatter2DVisualization::Points,
            transform: Item3DTransform::default(),
        }
    }

    /// Replace the point data (silx `Scatter2D.setData`). The three arrays must be
    /// the same length; on a length mismatch the data is left unchanged and
    /// `false` is returned (silx asserts equal lengths).
    pub fn set_data(&mut self, x: &[f64], y: &[f64], values: &[f64]) -> bool {
        let n = x.len();
        if y.len() != n || values.len() != n {
            return false;
        }
        self.x = x.to_vec();
        self.y = y.to_vec();
        self.values = values.to_vec();
        self.resolve_colormap();
        true
    }

    /// Builder form of [`set_data`](Self::set_data); a length mismatch leaves the
    /// data empty.
    pub fn with_data(mut self, x: &[f64], y: &[f64], values: &[f64]) -> Self {
        self.set_data(x, y, values);
        self
    }

    /// Set the colormap (silx `ColormapMixIn.setColormap`). An autoscale
    /// colormap immediately resolves its range to the current data.
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
        self.resolve_colormap();
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.set_colormap(colormap);
        self
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap (e.g. to set the value range directly).
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Refresh the colormap's autoscale bounds from the current values (silx
    /// `_syncSceneColormap`); a no-op for a pinned colormap.
    fn resolve_colormap(&mut self) {
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &self.values);
    }

    /// Fit the colormap's value range to the current data with `mode`, returning
    /// the new `(vmin, vmax)` (as [`Scatter3D::autoscale_colormap`]).
    pub fn autoscale_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        let (vmin, vmax) = self.colormap.autoscale_range(mode, &self.values);
        self.colormap.vmin = vmin;
        self.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// Set the visualization mode (silx `ScatterVisualizationMixIn.setVisualization`).
    pub fn set_visualization(&mut self, visualization: Scatter2DVisualization) {
        self.visualization = visualization;
    }

    /// Builder form of [`set_visualization`](Self::set_visualization).
    pub fn with_visualization(mut self, visualization: Scatter2DVisualization) -> Self {
        self.visualization = visualization;
        self
    }

    /// The current visualization mode.
    pub fn visualization(&self) -> Scatter2DVisualization {
        self.visualization
    }

    /// Display the value as the `z` coordinate (silx `Scatter2D.setHeightMap`);
    /// when `false` the points lie on the `z = 0` plane.
    pub fn set_height_map(&mut self, height_map: bool) {
        self.height_map = height_map;
    }

    /// Builder form of [`set_height_map`](Self::set_height_map).
    pub fn with_height_map(mut self, height_map: bool) -> Self {
        self.height_map = height_map;
        self
    }

    /// Whether the value is displayed as a height map (silx `isHeightMap`).
    pub fn is_height_map(&self) -> bool {
        self.height_map
    }

    /// Set the marker shape used in POINTS mode (silx `SymbolMixIn.setSymbol`).
    pub fn set_marker(&mut self, marker: PointMarker) {
        self.marker = marker;
    }

    /// Builder form of [`set_marker`](Self::set_marker).
    pub fn with_marker(mut self, marker: PointMarker) -> Self {
        self.marker = marker;
        self
    }

    /// Set the marker size in pixels used in POINTS mode
    /// (silx `SymbolMixIn.setSymbolSize`), clamped to be non-negative.
    pub fn set_size(&mut self, size: f32) {
        self.size = size.max(0.0);
    }

    /// Builder form of [`set_size`](Self::set_size).
    pub fn with_size(mut self, size: f32) -> Self {
        self.set_size(size);
        self
    }

    /// Set the line width in pixels used in LINES mode (silx
    /// `Scatter2D.setLineWidth`), clamped to silx's `>= 1.0`.
    pub fn set_line_width(&mut self, width: f32) {
        self.line_width = width.max(1.0);
    }

    /// Builder form of [`set_line_width`](Self::set_line_width).
    pub fn with_line_width(mut self, width: f32) -> Self {
        self.set_line_width(width);
        self
    }

    /// The line width used in LINES mode.
    pub fn line_width(&self) -> f32 {
        self.line_width
    }

    /// Number of points.
    pub fn len(&self) -> usize {
        self.x.len()
    }

    /// True when there are no points.
    pub fn is_empty(&self) -> bool {
        self.x.is_empty()
    }

    /// The `z` coordinate of point `i`: its value in height-map mode, else the
    /// `z = 0` plane (silx `_updateScene`: `z = value if heightMap else 0.0`).
    fn z(&self, i: usize) -> f32 {
        if self.height_map {
            self.values[i] as f32
        } else {
            0.0
        }
    }

    /// World position of point `i`.
    fn position(&self, i: usize) -> [f32; 3] {
        [self.x[i] as f32, self.y[i] as f32, self.z(i)]
    }

    /// Linear-premultiplied RGBA of point `i` through the colormap.
    fn color_rgba(&self, i: usize) -> [f32; 4] {
        let [r, g, b, a] = self.colormap.color_at(self.values[i]);
        egui::Rgba::from(Color32::from_rgba_unmultiplied(r, g, b, a)).to_array()
    }

    /// Raw (untransformed) data bounds over the points.
    fn raw_bounds(&self) -> Option<(Vec3, Vec3)> {
        if self.is_empty() {
            return None;
        }
        let positions: Vec<[f32; 3]> = (0..self.len()).map(|i| self.position(i)).collect();
        positions_bounds(&positions)
    }

    /// Axis-aligned scene bounds `(min, max)` over the points, through the
    /// item's transform (silx `DataItem3D` bounds, `transformed=True`), or
    /// `None` when empty. In flat mode raw `z` collapses to `[0, 0]`; in
    /// height-map mode it spans the value range.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(self.raw_bounds())
    }

    /// Append this scatter's geometry to `geometry` per its visualization mode,
    /// ready to upload via [`crate::render::gpu_scene3d::set_scene3d`]. LINES and
    /// SOLID triangulate `(x, y)`; a degenerate input (fewer than 3 points or all
    /// collinear) yields an empty triangulation and so draws nothing, matching
    /// silx skipping the renderer when the Delaunay tesselation fails.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.is_empty() {
            return;
        }
        append_with_transform(&self.transform, self.raw_bounds(), geometry, |g| {
            self.append_raw(g)
        });
    }

    /// Build the raw (untransformed) geometry — see [`Self::append_to`].
    fn append_raw(&self, geometry: &mut Scene3dGeometry) {
        match self.visualization {
            Scatter2DVisualization::Points => {
                for i in 0..self.len() {
                    let [r, g, b, a] = self.colormap.color_at(self.values[i]);
                    geometry.add_point(
                        self.position(i),
                        Color32::from_rgba_unmultiplied(r, g, b, a),
                        self.size,
                        self.marker,
                    );
                }
            }
            Scatter2DVisualization::Lines => {
                let tri = delaunay(&self.x, &self.y);
                // Unique undirected edges of the triangulation (silx
                // `triangleToLineIndices(unicity=True)`), sorted for determinism.
                let mut edges: BTreeSet<(usize, usize)> = BTreeSet::new();
                for &[i0, i1, i2] in &tri.triangles {
                    for (a, b) in [(i0, i1), (i1, i2), (i2, i0)] {
                        edges.insert((a.min(b), a.max(b)));
                    }
                }
                for (a, b) in edges {
                    geometry.add_line_gradient(
                        self.position(a),
                        self.position(b),
                        self.color_rgba(a),
                        self.color_rgba(b),
                    );
                }
                // silx picks LINES mode at the data points (5 px square), not
                // along the segments (items/scatter.py:509-511 → _pickPoints
                // threshold=5.0); anchor every data point for the pick path.
                for i in 0..self.len() {
                    geometry.add_line_pick_anchor(self.position(i));
                }
            }
            Scatter2DVisualization::Solid => {
                let tri = delaunay(&self.x, &self.y);
                for &[i0, i1, i2] in &tri.triangles {
                    let p = [self.position(i0), self.position(i1), self.position(i2)];
                    let rgba = [
                        self.color_rgba(i0),
                        self.color_rgba(i1),
                        self.color_rgba(i2),
                    ];
                    let normal = flat_normal(p[0], p[1], p[2]);
                    geometry.add_mesh_triangle_rgba(p, rgba, [normal; 3]);
                }
            }
        }
    }
}

impl_item3d_transform!(Scatter2D);

/// How a mesh's flat vertex stream is grouped into triangles (silx
/// `Mesh.setData` `mode`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum MeshDrawMode {
    /// Independent triangles: vertices `(0,1,2), (3,4,5), …`.
    #[default]
    Triangles,
    /// Triangle strip: vertices `(0,1,2), (1,2,3), (2,3,4), …`.
    TriangleStrip,
    /// Triangle fan: vertices `(0,1,2), (0,2,3), (0,3,4), …`.
    Fan,
}

/// Mesh vertex colouring (silx accepts a single colour or one colour per vertex).
#[derive(Clone, Debug)]
pub enum MeshColor {
    /// One colour shared by every vertex.
    Uniform(Color32),
    /// One colour per vertex (must match the vertex count).
    PerVertex(Vec<Color32>),
}

/// Expand a draw mode into triangles of *vertex indices*. When `indices` is given
/// the vertex stream is `indices` (unindexed); otherwise it is `0..n_vertices` in
/// order. Mirrors silx `utils.unindexArrays` + the per-mode reshape/expand in
/// `_MeshBase._pickFull` (triangle `i` uses stream `i, i+1, i+2` for strips; the
/// shared apex `0` plus `i, i+1` for fans). The single owner of mesh topology so
/// [`Mesh3D`] and [`ColormapMesh3D`] expand identically.
fn expand_triangles(
    mode: MeshDrawMode,
    n_vertices: usize,
    indices: Option<&[u32]>,
) -> Vec<[usize; 3]> {
    let stream: Vec<usize> = match indices {
        Some(idx) => idx.iter().map(|&i| i as usize).collect(),
        None => (0..n_vertices).collect(),
    };
    let n = stream.len();
    let mut tris = Vec::new();
    match mode {
        MeshDrawMode::Triangles => {
            for c in stream.chunks_exact(3) {
                tris.push([c[0], c[1], c[2]]);
            }
        }
        MeshDrawMode::TriangleStrip => {
            for i in 0..n.saturating_sub(2) {
                tris.push([stream[i], stream[i + 1], stream[i + 2]]);
            }
        }
        MeshDrawMode::Fan => {
            for i in 1..n.saturating_sub(1) {
                tris.push([stream[0], stream[i], stream[i + 1]]);
            }
        }
    }
    tris
}

/// Common length/range validation for mesh `setData`: per-vertex `normals` (if
/// any) must match the vertex count, and every `index` (if any) must be in range.
fn mesh_attrs_valid(n: usize, normals: Option<&[[f32; 3]]>, indices: Option<&[u32]>) -> bool {
    if let Some(ns) = normals
        && ns.len() != n
    {
        return false;
    }
    if let Some(idx) = indices
        && idx.iter().any(|&i| i as usize >= n)
    {
        return false;
    }
    true
}

/// Axis-aligned bounds `(min, max)` over a `(N, 3)` position array, or `None`
/// when empty (silx `DataItem3D.getBounds`).
fn positions_bounds(positions: &[[f32; 3]]) -> Option<(Vec3, Vec3)> {
    if positions.is_empty() {
        return None;
    }
    let mut min = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
    let mut max = Vec3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
    for &[px, py, pz] in positions {
        min.x = min.x.min(px);
        min.y = min.y.min(py);
        min.z = min.z.min(pz);
        max.x = max.x.max(px);
        max.y = max.y.max(py);
        max.z = max.z.max(pz);
    }
    Some((min, max))
}

/// A triangle mesh with solid (per-vertex or uniform) vertex colours.
///
/// Port of silx `plot3d.items.Mesh` (a `DataItem3D` wrapping a
/// `scene.primitives.Mesh3D`). Vertices carry positions, colours and optional
/// normals; when no normals are supplied the geometric flat face normal is used
/// per triangle (via `flat_normal`), so the headlight still shades the surface.
/// Strips and fans are expanded to a triangle list on the CPU since the GPU path
/// is `TriangleList` only.
#[derive(Clone, Debug)]
pub struct Mesh3D {
    positions: Vec<[f32; 3]>,
    colors: MeshColor,
    normals: Option<Vec<[f32; 3]>>,
    mode: MeshDrawMode,
    indices: Option<Vec<u32>>,
    transform: Item3DTransform,
}

impl Default for Mesh3D {
    fn default() -> Self {
        Self::new()
    }
}

impl Mesh3D {
    /// An empty mesh (white, `Triangles` mode).
    pub fn new() -> Self {
        Self {
            positions: Vec::new(),
            colors: MeshColor::Uniform(Color32::WHITE),
            normals: None,
            mode: MeshDrawMode::Triangles,
            indices: None,
            transform: Item3DTransform::default(),
        }
    }

    /// Set the mesh geometry (silx `Mesh.setData`). Returns `false` (leaving the
    /// mesh unchanged) when the attributes are inconsistent: per-vertex colours or
    /// normals not matching the vertex count, or an out-of-range index. An empty
    /// `positions` clears the mesh and returns `true` (silx treats it as no mesh).
    pub fn set_data(
        &mut self,
        positions: &[[f32; 3]],
        colors: MeshColor,
        normals: Option<&[[f32; 3]]>,
        mode: MeshDrawMode,
        indices: Option<&[u32]>,
    ) -> bool {
        let n = positions.len();
        if let MeshColor::PerVertex(cs) = &colors
            && cs.len() != n
        {
            return false;
        }
        if !mesh_attrs_valid(n, normals, indices) {
            return false;
        }
        self.positions = positions.to_vec();
        self.colors = colors;
        self.normals = normals.map(<[[f32; 3]]>::to_vec);
        self.mode = mode;
        self.indices = indices.map(<[u32]>::to_vec);
        true
    }

    /// Builder form of [`set_data`](Self::set_data); inconsistent attributes leave
    /// the mesh empty.
    pub fn with_data(
        mut self,
        positions: &[[f32; 3]],
        colors: MeshColor,
        normals: Option<&[[f32; 3]]>,
        mode: MeshDrawMode,
        indices: Option<&[u32]>,
    ) -> Self {
        self.set_data(positions, colors, normals, mode, indices);
        self
    }

    /// The drawing mode.
    pub fn mode(&self) -> MeshDrawMode {
        self.mode
    }

    /// Number of vertices.
    pub fn len(&self) -> usize {
        self.positions.len()
    }

    /// True when there are no vertices.
    pub fn is_empty(&self) -> bool {
        self.positions.is_empty()
    }

    /// Axis-aligned scene bounds `(min, max)` through the item's transform
    /// (silx `DataItem3D` bounds, `transformed=True`), or `None` when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform
            .transform_bounds(positions_bounds(&self.positions))
    }

    /// Append this mesh's triangles to `geometry` for upload via
    /// [`crate::render::gpu_scene3d::set_scene3d`].
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        append_with_transform(
            &self.transform,
            positions_bounds(&self.positions),
            geometry,
            |g| {
                for [i0, i1, i2] in
                    expand_triangles(self.mode, self.positions.len(), self.indices.as_deref())
                {
                    let p = [self.positions[i0], self.positions[i1], self.positions[i2]];
                    let normals = match &self.normals {
                        Some(ns) => [ns[i0], ns[i1], ns[i2]],
                        None => [flat_normal(p[0], p[1], p[2]); 3],
                    };
                    let rgba = match &self.colors {
                        MeshColor::Uniform(c) => [egui::Rgba::from(*c).to_array(); 3],
                        MeshColor::PerVertex(cs) => [
                            egui::Rgba::from(cs[i0]).to_array(),
                            egui::Rgba::from(cs[i1]).to_array(),
                            egui::Rgba::from(cs[i2]).to_array(),
                        ],
                    };
                    g.add_mesh_triangle_rgba(p, rgba, normals);
                }
            },
        );
    }
}

impl_item3d_transform!(Mesh3D);

/// A triangle mesh whose vertex colours come from a per-vertex scalar `value`
/// mapped through a [`Colormap`].
///
/// Port of silx `plot3d.items.ColormapMesh` (`_MeshBase` + `ColormapMixIn`,
/// wrapping a `scene.primitives.ColormapMesh3D`). silx maps values to colours on
/// the GPU from a colormap texture; here the mapping is done on the CPU via
/// [`Colormap::color_at`] when building the geometry (as for [`Scatter3D`]).
#[derive(Clone, Debug)]
pub struct ColormapMesh3D {
    positions: Vec<[f32; 3]>,
    values: Vec<f64>,
    normals: Option<Vec<[f32; 3]>>,
    mode: MeshDrawMode,
    indices: Option<Vec<u32>>,
    colormap: Colormap,
    transform: Item3DTransform,
}

impl Default for ColormapMesh3D {
    fn default() -> Self {
        Self::new()
    }
}

impl ColormapMesh3D {
    /// An empty colormap mesh with silx defaults: the gray colormap over
    /// `[0, 1]`, `Triangles` mode.
    pub fn new() -> Self {
        Self {
            positions: Vec::new(),
            values: Vec::new(),
            normals: None,
            mode: MeshDrawMode::Triangles,
            indices: None,
            colormap: Colormap::autoscale(ColormapName::Gray),
            transform: Item3DTransform::default(),
        }
    }

    /// Set the mesh geometry (silx `ColormapMesh.setData`). Returns `false`
    /// (leaving the mesh unchanged) when `values`, per-vertex `normals`, or
    /// `indices` are inconsistent with the vertex count. An empty `positions`
    /// clears the mesh and returns `true`.
    pub fn set_data(
        &mut self,
        positions: &[[f32; 3]],
        values: &[f64],
        normals: Option<&[[f32; 3]]>,
        mode: MeshDrawMode,
        indices: Option<&[u32]>,
    ) -> bool {
        let n = positions.len();
        if values.len() != n {
            return false;
        }
        if !mesh_attrs_valid(n, normals, indices) {
            return false;
        }
        self.positions = positions.to_vec();
        self.values = values.to_vec();
        self.normals = normals.map(<[[f32; 3]]>::to_vec);
        self.mode = mode;
        self.indices = indices.map(<[u32]>::to_vec);
        self.resolve_colormap();
        true
    }

    /// Builder form of [`set_data`](Self::set_data); inconsistent attributes leave
    /// the mesh empty.
    pub fn with_data(
        mut self,
        positions: &[[f32; 3]],
        values: &[f64],
        normals: Option<&[[f32; 3]]>,
        mode: MeshDrawMode,
        indices: Option<&[u32]>,
    ) -> Self {
        self.set_data(positions, values, normals, mode, indices);
        self
    }

    /// Set the colormap (silx `ColormapMixIn.setColormap`). An autoscale
    /// colormap immediately resolves its range to the current data.
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
        self.resolve_colormap();
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.set_colormap(colormap);
        self
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap.
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Refresh the colormap's autoscale bounds from the current values (silx
    /// `_syncSceneColormap`); a no-op for a pinned colormap.
    fn resolve_colormap(&mut self) {
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &self.values);
    }

    /// Fit the colormap's value range to the current data with `mode`, returning
    /// the new `(vmin, vmax)` (as [`Scatter3D::autoscale_colormap`]).
    pub fn autoscale_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        let (vmin, vmax) = self.colormap.autoscale_range(mode, &self.values);
        self.colormap.vmin = vmin;
        self.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// The drawing mode.
    pub fn mode(&self) -> MeshDrawMode {
        self.mode
    }

    /// Number of vertices.
    pub fn len(&self) -> usize {
        self.positions.len()
    }

    /// True when there are no vertices.
    pub fn is_empty(&self) -> bool {
        self.positions.is_empty()
    }

    /// Axis-aligned scene bounds `(min, max)` through the item's transform
    /// (silx `DataItem3D` bounds, `transformed=True`), or `None` when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform
            .transform_bounds(positions_bounds(&self.positions))
    }

    /// Append this mesh's triangles (coloured through the colormap) to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        append_with_transform(
            &self.transform,
            positions_bounds(&self.positions),
            geometry,
            |g| {
                let rgba_at = |i: usize| {
                    let [r, gr, b, a] = self.colormap.color_at(self.values[i]);
                    egui::Rgba::from(Color32::from_rgba_unmultiplied(r, gr, b, a)).to_array()
                };
                for [i0, i1, i2] in
                    expand_triangles(self.mode, self.positions.len(), self.indices.as_deref())
                {
                    let p = [self.positions[i0], self.positions[i1], self.positions[i2]];
                    let normals = match &self.normals {
                        Some(ns) => [ns[i0], ns[i1], ns[i2]],
                        None => [flat_normal(p[0], p[1], p[2]); 3],
                    };
                    g.add_mesh_triangle_rgba(p, [rgba_at(i0), rgba_at(i1), rgba_at(i2)], normals);
                }
            },
        );
    }
}

impl_item3d_transform!(ColormapMesh3D);

/// Build the rotation matrix for a silx `Rotate(angle_deg, x, y, z)`: degrees →
/// radians about the normalized axis. A zero angle or zero axis is the identity
/// (silx's default `(0, (0,0,0))`).
fn rotation_matrix(angle_deg: f32, axis: [f32; 3]) -> Mat4 {
    let a = Vec3::from_array(axis);
    let len = a.length();
    if angle_deg == 0.0 || len == 0.0 {
        return Mat4::IDENTITY;
    }
    let n = a * (1.0 / len);
    mat4_rotate(angle_deg.to_radians(), n.x, n.y, n.z)
}

/// `numpy.linspace(0, 2Ï€, n_seg + 1)`: `n_seg` equal angular segments closing the
/// full turn (the edge angles of a [`_cylindrical_volume_mesh`]).
fn linspace_angles(n_seg: usize) -> Vec<f32> {
    (0..=n_seg)
        .map(|i| std::f32::consts::TAU * i as f32 / n_seg as f32)
        .collect()
}

/// Build the triangle mesh of a rotational volume swept around z — the port of
/// silx `items.mesh._CylindricalVolume._setData`.
///
/// For each angular segment `[angles[i], angles[i+1]]` a 12-vertex / 4-triangle
/// wedge is built (bottom cap, two side triangles, top cap) from the six corners
/// `c1..c6` (centres ±h/2 and the two radial edge points top & bottom), each
/// passed through `rotation`. With `flat_faces` every vertex gets its triangle's
/// geometric normal (faceted, for Box/Hexagon); otherwise the side vertices get
/// radial normals (smooth, for Cylinder) while the caps stay faceted. The wedge
/// set is then replicated and translated to each centre `position`; `color` is
/// one shared colour (`len == 1`) or one per position. Vertex normals reproduce
/// silx's expressions; silx's one degenerate term `(c6−c5)×(c5−c5)` is written as
/// the zero vector it always evaluates to (`c5−c5 = 0`).
fn cylindrical_volume_mesh(
    positions: &[[f32; 3]],
    radius: f32,
    height: f32,
    angles: &[f32],
    color: &[Color32],
    flat_faces: bool,
    rotation: Mat4,
) -> Mesh3D {
    if positions.is_empty() || angles.len() < 2 {
        return Mesh3D::new();
    }
    let n_seg = angles.len() - 1;
    let hz = height / 2.0;
    let edge = |r: f32, a: f32, z: f32| {
        rotation.transform_point(Vec3::new(r * a.cos(), r * a.sin(), z), false)
    };

    // One wedge set (shared by every position), as in silx's `volume`/`normal`.
    let mut wedge_verts: Vec<Vec3> = Vec::with_capacity(n_seg * 12);
    let mut wedge_normals: Vec<Vec3> = Vec::with_capacity(n_seg * 12);
    for i in 0..n_seg {
        let (a0, a1) = (angles[i], angles[i + 1]);
        let c1 = rotation.transform_point(Vec3::new(0.0, 0.0, -hz), false);
        let c2 = edge(radius, a0, -hz);
        let c3 = edge(radius, a1, -hz);
        let c4 = edge(radius, a0, hz);
        let c5 = edge(radius, a1, hz);
        let c6 = rotation.transform_point(Vec3::new(0.0, 0.0, hz), false);
        wedge_verts.extend_from_slice(&[c1, c3, c2, c2, c3, c4, c3, c5, c4, c4, c5, c6]);
        if flat_faces {
            wedge_normals.extend_from_slice(&[
                (c3 - c1).cross(c2 - c1),
                (c2 - c3).cross(c1 - c3),
                (c1 - c2).cross(c3 - c2),
                (c3 - c2).cross(c4 - c2),
                (c4 - c3).cross(c2 - c3),
                (c2 - c4).cross(c3 - c4),
                (c5 - c3).cross(c4 - c3),
                (c4 - c5).cross(c3 - c5),
                (c3 - c4).cross(c5 - c4),
                (c5 - c4).cross(c6 - c4),
                Vec3::new(0.0, 0.0, 0.0), // silx `cross(c6-c5, c5-c5)` ≡ 0
                (c4 - c6).cross(c5 - c6),
            ]);
        } else {
            wedge_normals.extend_from_slice(&[
                (c3 - c1).cross(c2 - c1),
                (c2 - c3).cross(c1 - c3),
                (c1 - c2).cross(c3 - c2),
                c2 - c1,
                c3 - c1,
                c4 - c6,
                c3 - c1,
                c5 - c6,
                c4 - c6,
                (c5 - c4).cross(c6 - c4),
                Vec3::new(0.0, 0.0, 0.0), // silx `cross(c6-c5, c5-c5)` ≡ 0
                (c4 - c6).cross(c5 - c6),
            ]);
        }
    }

    let total = wedge_verts.len() * positions.len();
    let mut out_pos = Vec::with_capacity(total);
    let mut out_norm = Vec::with_capacity(total);
    let mut out_color = Vec::with_capacity(total);
    for (k, &p) in positions.iter().enumerate() {
        let pv = Vec3::from_array(p);
        let color_k = if color.len() == 1 { color[0] } else { color[k] };
        for (v, n) in wedge_verts.iter().zip(&wedge_normals) {
            out_pos.push((*v + pv).to_array());
            out_norm.push(n.to_array());
            out_color.push(color_k);
        }
    }

    Mesh3D::new().with_data(
        &out_pos,
        MeshColor::PerVertex(out_color),
        Some(&out_norm),
        MeshDrawMode::Triangles,
        None,
    )
}

/// True when `color` is one shared colour or exactly one per position (silx
/// asserts `ndim(color) == 1 or len(color) == len(position)`).
fn volume_color_valid(color: &[Color32], n_positions: usize) -> bool {
    color.len() == 1 || color.len() == n_positions
}

/// One or many axis-aligned boxes (silx `items.mesh.Box`), a four-segment
/// `cylindrical_volume_mesh` with faceted faces.
#[derive(Clone, Debug)]
pub struct Box3D {
    size: [f32; 3],
    colors: Vec<Color32>,
    positions: Vec<[f32; 3]>,
    mesh: Mesh3D,
}

impl Default for Box3D {
    fn default() -> Self {
        Self::new()
    }
}

impl Box3D {
    /// A single unit box at the origin, white (silx `Box` defaults).
    pub fn new() -> Self {
        let mut b = Self {
            size: [1.0, 1.0, 1.0],
            colors: vec![Color32::WHITE],
            positions: vec![[0.0, 0.0, 0.0]],
            mesh: Mesh3D::new(),
        };
        b.rebuild((0.0, [0.0, 0.0, 0.0]));
        b
    }

    /// Set box geometry (silx `Box.setData`): `size` (dx, dy, dz), `color` (one
    /// shared or one per box), `positions` (box centres), and `rotation`
    /// `(angle_degrees, axis)`. Returns `false` (unchanged) on an invalid colour
    /// count.
    pub fn set_data(
        &mut self,
        size: [f32; 3],
        color: &[Color32],
        positions: &[[f32; 3]],
        rotation: (f32, [f32; 3]),
    ) -> bool {
        if !volume_color_valid(color, positions.len()) {
            return false;
        }
        self.size = size;
        self.colors = color.to_vec();
        self.positions = positions.to_vec();
        self.rebuild(rotation);
        true
    }

    fn rebuild(&mut self, rotation: (f32, [f32; 3])) {
        let [dx, dy, dz] = self.size;
        // silx Box.setData: four side faces whose edge angles are derived from the
        // box aspect ratio, then shifted by −α/2 so a face aligns with +x.
        let diagonal = (dx * dx + dy * dy).sqrt();
        let alpha = 2.0 * (dy / diagonal).asin();
        let beta = 2.0 * (dx / diagonal).asin();
        let angles: Vec<f32> = [
            0.0,
            alpha,
            alpha + beta,
            alpha + beta + alpha,
            std::f32::consts::TAU,
        ]
        .iter()
        .map(|a| a - 0.5 * alpha)
        .collect();
        // The item transform lives on the inner mesh; carry it across rebuilds.
        let transform = *self.mesh.transform();
        self.mesh = cylindrical_volume_mesh(
            &self.positions,
            diagonal / 2.0,
            dz,
            &angles,
            &self.colors,
            true,
            rotation_matrix(rotation.0, rotation.1),
        );
        *self.mesh.transform_mut() = transform;
    }

    /// Box centre position(s).
    pub fn positions(&self) -> &[[f32; 3]] {
        &self.positions
    }

    /// Box size (dx, dy, dz).
    pub fn size(&self) -> [f32; 3] {
        self.size
    }

    /// Box colour(s).
    pub fn colors(&self) -> &[Color32] {
        &self.colors
    }

    /// Axis-aligned bounds `(min, max)` of the box mesh (through the item's
    /// transform), or `None` when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.mesh.bounds()
    }

    /// Append the box triangles to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        self.mesh.append_to(geometry);
    }

    /// The item's transform stack (silx `DataItem3D` transforms,
    /// `items/core.py:288-315`), delegated to the underlying mesh so bounds
    /// and geometry follow it by construction.
    pub fn transform(&self) -> &Item3DTransform {
        self.mesh.transform()
    }

    /// Mutable access to the transform stack (silx setters,
    /// `items/core.py:335-485`).
    pub fn transform_mut(&mut self) -> &mut Item3DTransform {
        self.mesh.transform_mut()
    }
}

/// One or many cylinders (silx `items.mesh.Cylinder`), an `nb_faces`-segment
/// `cylindrical_volume_mesh` with smooth (radial-normal) sides.
#[derive(Clone, Debug)]
pub struct Cylinder3D {
    radius: f32,
    height: f32,
    nb_faces: usize,
    colors: Vec<Color32>,
    positions: Vec<[f32; 3]>,
    mesh: Mesh3D,
}

impl Default for Cylinder3D {
    fn default() -> Self {
        Self::new()
    }
}

impl Cylinder3D {
    /// A single unit cylinder at the origin (radius 1, height 1, 20 faces, white).
    pub fn new() -> Self {
        let mut c = Self {
            radius: 1.0,
            height: 1.0,
            nb_faces: 20,
            colors: vec![Color32::WHITE],
            positions: vec![[0.0, 0.0, 0.0]],
            mesh: Mesh3D::new(),
        };
        c.rebuild((0.0, [0.0, 0.0, 0.0]));
        c
    }

    /// Set cylinder geometry (silx `Cylinder.setData`): `radius`, `height`,
    /// `color` (one shared or one per cylinder), `nb_faces` (≥3 for a closed
    /// surface), `positions` (centres), `rotation` `(angle_degrees, axis)`.
    /// Returns `false` (unchanged) on an invalid colour count.
    pub fn set_data(
        &mut self,
        radius: f32,
        height: f32,
        color: &[Color32],
        nb_faces: usize,
        positions: &[[f32; 3]],
        rotation: (f32, [f32; 3]),
    ) -> bool {
        if !volume_color_valid(color, positions.len()) {
            return false;
        }
        self.radius = radius;
        self.height = height;
        self.nb_faces = nb_faces;
        self.colors = color.to_vec();
        self.positions = positions.to_vec();
        self.rebuild(rotation);
        true
    }

    fn rebuild(&mut self, rotation: (f32, [f32; 3])) {
        let angles = linspace_angles(self.nb_faces);
        // The item transform lives on the inner mesh; carry it across rebuilds.
        let transform = *self.mesh.transform();
        self.mesh = cylindrical_volume_mesh(
            &self.positions,
            self.radius,
            self.height,
            &angles,
            &self.colors,
            false,
            rotation_matrix(rotation.0, rotation.1),
        );
        *self.mesh.transform_mut() = transform;
    }

    /// Cylinder centre position(s).
    pub fn positions(&self) -> &[[f32; 3]] {
        &self.positions
    }

    /// Cylinder radius.
    pub fn radius(&self) -> f32 {
        self.radius
    }

    /// Cylinder height.
    pub fn height(&self) -> f32 {
        self.height
    }

    /// Cylinder colour(s).
    pub fn colors(&self) -> &[Color32] {
        &self.colors
    }

    /// Axis-aligned bounds `(min, max)` of the cylinder mesh (through the
    /// item's transform), or `None` if empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.mesh.bounds()
    }

    /// Append the cylinder triangles to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        self.mesh.append_to(geometry);
    }

    /// The item's transform stack (silx `DataItem3D` transforms,
    /// `items/core.py:288-315`), delegated to the underlying mesh so bounds
    /// and geometry follow it by construction.
    pub fn transform(&self) -> &Item3DTransform {
        self.mesh.transform()
    }

    /// Mutable access to the transform stack (silx setters,
    /// `items/core.py:335-485`).
    pub fn transform_mut(&mut self) -> &mut Item3DTransform {
        self.mesh.transform_mut()
    }
}

/// One or many uniform hexagonal prisms (silx `items.mesh.Hexagon`), a
/// six-segment `cylindrical_volume_mesh` with faceted faces.
#[derive(Clone, Debug)]
pub struct Hexagon3D {
    radius: f32,
    height: f32,
    colors: Vec<Color32>,
    positions: Vec<[f32; 3]>,
    mesh: Mesh3D,
}

impl Default for Hexagon3D {
    fn default() -> Self {
        Self::new()
    }
}

impl Hexagon3D {
    /// A single unit hexagonal prism at the origin (radius 1, height 1, white).
    pub fn new() -> Self {
        let mut h = Self {
            radius: 1.0,
            height: 1.0,
            colors: vec![Color32::WHITE],
            positions: vec![[0.0, 0.0, 0.0]],
            mesh: Mesh3D::new(),
        };
        h.rebuild((0.0, [0.0, 0.0, 0.0]));
        h
    }

    /// Set hexagonal-prism geometry (silx `Hexagon.setData`): external `radius`,
    /// `height`, `color` (one shared or one per prism), `positions` (centres),
    /// `rotation` `(angle_degrees, axis)`. Returns `false` (unchanged) on an
    /// invalid colour count.
    pub fn set_data(
        &mut self,
        radius: f32,
        height: f32,
        color: &[Color32],
        positions: &[[f32; 3]],
        rotation: (f32, [f32; 3]),
    ) -> bool {
        if !volume_color_valid(color, positions.len()) {
            return false;
        }
        self.radius = radius;
        self.height = height;
        self.colors = color.to_vec();
        self.positions = positions.to_vec();
        self.rebuild(rotation);
        true
    }

    fn rebuild(&mut self, rotation: (f32, [f32; 3])) {
        // silx Hexagon.setData: angles = linspace(0, 2π, 7) → six faces.
        let angles = linspace_angles(6);
        // The item transform lives on the inner mesh; carry it across rebuilds.
        let transform = *self.mesh.transform();
        self.mesh = cylindrical_volume_mesh(
            &self.positions,
            self.radius,
            self.height,
            &angles,
            &self.colors,
            true,
            rotation_matrix(rotation.0, rotation.1),
        );
        *self.mesh.transform_mut() = transform;
    }

    /// Prism centre position(s).
    pub fn positions(&self) -> &[[f32; 3]] {
        &self.positions
    }

    /// Prism external radius.
    pub fn radius(&self) -> f32 {
        self.radius
    }

    /// Prism height.
    pub fn height(&self) -> f32 {
        self.height
    }

    /// Prism colour(s).
    pub fn colors(&self) -> &[Color32] {
        &self.colors
    }

    /// Axis-aligned bounds `(min, max)` of the prism mesh (through the item's
    /// transform), or `None` when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.mesh.bounds()
    }

    /// Append the prism triangles to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        self.mesh.append_to(geometry);
    }

    /// The item's transform stack (silx `DataItem3D` transforms,
    /// `items/core.py:288-315`), delegated to the underlying mesh so bounds
    /// and geometry follow it by construction.
    pub fn transform(&self) -> &Item3DTransform {
        self.mesh.transform()
    }

    /// Mutable access to the transform stack (silx setters,
    /// `items/core.py:335-485`).
    pub fn transform_mut(&mut self) -> &mut Item3DTransform {
        self.mesh.transform_mut()
    }
}

/// Premultiplied-linear RGBA8 for a [`Color32`] — the image-layer pixel format
/// (same linear/premultiplied convention as the geometry colour path, so an
/// image's sampled colour matches a triangle of the same `Color32`).
fn premul_linear_rgba8(c: Color32) -> [u8; 4] {
    let [r, g, b, a] = egui::Rgba::from(c).to_array();
    [
        (r * 255.0).round() as u8,
        (g * 255.0).round() as u8,
        (b * 255.0).round() as u8,
        (a * 255.0).round() as u8,
    ]
}

/// World bounds `(min, max)` of an image quad of `width × height` pixels at
/// `origin` with per-pixel `scale`, in the `z = origin.z` plane, or `None` when
/// empty.
fn image_bounds(
    width: usize,
    height: usize,
    origin: [f32; 3],
    scale: [f32; 2],
) -> Option<(Vec3, Vec3)> {
    if width == 0 || height == 0 {
        return None;
    }
    let min = Vec3::from_array(origin);
    let max = Vec3::new(
        origin[0] + width as f32 * scale[0],
        origin[1] + height as f32 * scale[1],
        origin[2],
    );
    Some((min, max))
}

/// A 2D scalar image displayed as a flat colormapped quad (silx
/// `plot3d.items.ImageData`). The data is a row-major `width × height` array;
/// each pixel is coloured through a [`Colormap`] (CPU [`Colormap::color_at`], as
/// for the other colormapped 3D items) into one image-layer texture.
#[derive(Clone, Debug)]
pub struct ImageData3D {
    data: Vec<f64>,
    width: usize,
    height: usize,
    colormap: Colormap,
    origin: [f32; 3],
    scale: [f32; 2],
    interpolation: ImageInterpolation,
    transform: Item3DTransform,
}

impl Default for ImageData3D {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageData3D {
    /// An empty image with silx defaults: gray over `[0, 1]`, origin `(0,0,0)`,
    /// unit pixel scale, nearest sampling.
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            width: 0,
            height: 0,
            colormap: Colormap::autoscale(ColormapName::Gray),
            origin: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0],
            interpolation: ImageInterpolation::Nearest,
            transform: Item3DTransform::default(),
        }
    }

    /// Set the scalar image data (silx `ImageData.setData`), row-major. Returns
    /// `false` (unchanged) when `data.len() != width * height`.
    pub fn set_data(&mut self, data: &[f64], width: usize, height: usize) -> bool {
        if data.len() != width * height {
            return false;
        }
        self.data = data.to_vec();
        self.width = width;
        self.height = height;
        self.resolve_colormap();
        true
    }

    /// Builder form of [`set_data`](Self::set_data).
    pub fn with_data(mut self, data: &[f64], width: usize, height: usize) -> Self {
        self.set_data(data, width, height);
        self
    }

    /// Set the colormap. An autoscale colormap immediately resolves its range to
    /// the current data.
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
        self.resolve_colormap();
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.set_colormap(colormap);
        self
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap.
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Refresh the colormap's autoscale bounds from the current data (silx
    /// `_syncSceneColormap`); a no-op for a pinned colormap.
    fn resolve_colormap(&mut self) {
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &self.data);
    }

    /// Fit the colormap's value range to the current data with `mode`, returning
    /// the new `(vmin, vmax)`.
    pub fn autoscale_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        let (vmin, vmax) = self.colormap.autoscale_range(mode, &self.data);
        self.colormap.vmin = vmin;
        self.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// Set the world position of pixel-corner `(0, 0)`.
    pub fn set_origin(&mut self, origin: [f32; 3]) {
        self.origin = origin;
    }

    /// Builder form of [`set_origin`](Self::set_origin).
    pub fn with_origin(mut self, origin: [f32; 3]) -> Self {
        self.origin = origin;
        self
    }

    /// Set the world size of one pixel along x and y.
    pub fn set_scale(&mut self, scale: [f32; 2]) {
        self.scale = scale;
    }

    /// Builder form of [`set_scale`](Self::set_scale).
    pub fn with_scale(mut self, scale: [f32; 2]) -> Self {
        self.scale = scale;
        self
    }

    /// Set the texture filtering.
    pub fn set_interpolation(&mut self, interpolation: ImageInterpolation) {
        self.interpolation = interpolation;
    }

    /// Builder form of [`set_interpolation`](Self::set_interpolation).
    pub fn with_interpolation(mut self, interpolation: ImageInterpolation) -> Self {
        self.interpolation = interpolation;
        self
    }

    /// Image dimensions `(width, height)` in pixels.
    pub fn dimensions(&self) -> (usize, usize) {
        (self.width, self.height)
    }

    /// True when there is no image data.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// World bounds `(min, max)` of the image quad through the item's
    /// transform (silx `DataItem3D` bounds, `transformed=True`), or `None`
    /// when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(image_bounds(
            self.width,
            self.height,
            self.origin,
            self.scale,
        ))
    }

    /// Append this image as a colormapped layer to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.is_empty() {
            return;
        }
        let raw_bounds = image_bounds(self.width, self.height, self.origin, self.scale);
        append_with_transform(&self.transform, raw_bounds, geometry, |g| {
            let mut pixels = Vec::with_capacity(self.data.len() * 4);
            for &v in &self.data {
                let [r, gr, b, a] = self.colormap.color_at(v);
                pixels.extend_from_slice(&premul_linear_rgba8(Color32::from_rgba_unmultiplied(
                    r, gr, b, a,
                )));
            }
            g.add_image_layer(Scene3dImageLayer {
                pixels,
                width: self.width as u32,
                height: self.height as u32,
                origin: self.origin,
                scale: self.scale,
                interpolation: self.interpolation,
            });
        });
    }
}

impl_item3d_transform!(ImageData3D);

/// A 2D RGB(A) image displayed as a flat quad (silx `plot3d.items.ImageRgba`).
/// Pixels are given directly as [`Color32`] (row-major); no colormap.
#[derive(Clone, Debug)]
pub struct ImageRgba3D {
    pixels: Vec<Color32>,
    width: usize,
    height: usize,
    origin: [f32; 3],
    scale: [f32; 2],
    interpolation: ImageInterpolation,
    transform: Item3DTransform,
}

impl Default for ImageRgba3D {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageRgba3D {
    /// An empty RGBA image with silx defaults: origin `(0,0,0)`, unit pixel scale,
    /// nearest sampling.
    pub fn new() -> Self {
        Self {
            pixels: Vec::new(),
            width: 0,
            height: 0,
            origin: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0],
            interpolation: ImageInterpolation::Nearest,
            transform: Item3DTransform::default(),
        }
    }

    /// Set the RGBA image data (silx `ImageRgba.setData`), row-major. Returns
    /// `false` (unchanged) when `pixels.len() != width * height`.
    pub fn set_data(&mut self, pixels: &[Color32], width: usize, height: usize) -> bool {
        if pixels.len() != width * height {
            return false;
        }
        self.pixels = pixels.to_vec();
        self.width = width;
        self.height = height;
        true
    }

    /// Builder form of [`set_data`](Self::set_data).
    pub fn with_data(mut self, pixels: &[Color32], width: usize, height: usize) -> Self {
        self.set_data(pixels, width, height);
        self
    }

    /// Set the world position of pixel-corner `(0, 0)`.
    pub fn set_origin(&mut self, origin: [f32; 3]) {
        self.origin = origin;
    }

    /// Builder form of [`set_origin`](Self::set_origin).
    pub fn with_origin(mut self, origin: [f32; 3]) -> Self {
        self.origin = origin;
        self
    }

    /// Set the world size of one pixel along x and y.
    pub fn set_scale(&mut self, scale: [f32; 2]) {
        self.scale = scale;
    }

    /// Builder form of [`set_scale`](Self::set_scale).
    pub fn with_scale(mut self, scale: [f32; 2]) -> Self {
        self.scale = scale;
        self
    }

    /// Set the texture filtering.
    pub fn set_interpolation(&mut self, interpolation: ImageInterpolation) {
        self.interpolation = interpolation;
    }

    /// Builder form of [`set_interpolation`](Self::set_interpolation).
    pub fn with_interpolation(mut self, interpolation: ImageInterpolation) -> Self {
        self.interpolation = interpolation;
        self
    }

    /// Image dimensions `(width, height)` in pixels.
    pub fn dimensions(&self) -> (usize, usize) {
        (self.width, self.height)
    }

    /// True when there is no image data.
    pub fn is_empty(&self) -> bool {
        self.pixels.is_empty()
    }

    /// World bounds `(min, max)` of the image quad through the item's
    /// transform (silx `DataItem3D` bounds, `transformed=True`), or `None`
    /// when empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(image_bounds(
            self.width,
            self.height,
            self.origin,
            self.scale,
        ))
    }

    /// Append this image as an RGBA layer to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.is_empty() {
            return;
        }
        let raw_bounds = image_bounds(self.width, self.height, self.origin, self.scale);
        append_with_transform(&self.transform, raw_bounds, geometry, |g| {
            let mut pixels = Vec::with_capacity(self.pixels.len() * 4);
            for &c in &self.pixels {
                pixels.extend_from_slice(&premul_linear_rgba8(c));
            }
            g.add_image_layer(Scene3dImageLayer {
                pixels,
                width: self.width as u32,
                height: self.height as u32,
                origin: self.origin,
                scale: self.scale,
                interpolation: self.interpolation,
            });
        });
    }
}

impl_item3d_transform!(ImageRgba3D);

/// Nearest-neighbour source index for destination index `i` of `dst_len`, onto a
/// source axis of `src_len` (the silx height-map resample, `floor(i·src/dst)`),
/// clamped into range.
fn nearest_src_index(i: usize, dst_len: usize, src_len: usize) -> usize {
    ((i as f64 * src_len as f64 / dst_len as f64).floor() as usize).min(src_len.saturating_sub(1))
}

/// World bounds `(min, max)` of a height-field point grid: x ∈ [0, width−1],
/// y ∈ [0, height−1], z over the height values. `None` when empty.
fn height_grid_bounds(heights: &[f32], width: usize, height: usize) -> Option<(Vec3, Vec3)> {
    if heights.is_empty() || width == 0 || height == 0 {
        return None;
    }
    let mut zmin = f32::INFINITY;
    let mut zmax = f32::NEG_INFINITY;
    for &z in heights {
        zmin = zmin.min(z);
        zmax = zmax.max(z);
    }
    Some((
        Vec3::new(0.0, 0.0, zmin),
        Vec3::new((width - 1) as f32, (height - 1) as f32, zmax),
    ))
}

/// A 2D height field coloured by a colormapped dataset (silx
/// `plot3d.items.HeightMapData`). Each height-field pixel `(row, col)` becomes a
/// square point at world `(col, row, height)`, coloured through a [`Colormap`]
/// over the (separately set) `colormapped` data — silx renders height maps as a
/// set of size-1 `'s'` points, so this reuses the point-sprite path directly.
///
/// When the colormapped data and the height field differ in size the data is
/// nearest-neighbour resampled to the height grid. (silx's resample indexes the
/// *column* axis by the field *height* — image.py:318 — which mis-samples
/// non-square data; this port indexes the column by the field *width*, the
/// evident intent. For equal-sized data the two agree.)
#[derive(Clone, Debug)]
pub struct HeightMapData {
    heights: Vec<f32>,
    h_width: usize,
    h_height: usize,
    values: Vec<f64>,
    v_width: usize,
    v_height: usize,
    colormap: Colormap,
    transform: Item3DTransform,
}

impl Default for HeightMapData {
    fn default() -> Self {
        Self::new()
    }
}

impl HeightMapData {
    /// An empty height map with gray over `[0, 1]`.
    pub fn new() -> Self {
        Self {
            heights: Vec::new(),
            h_width: 0,
            h_height: 0,
            values: Vec::new(),
            v_width: 0,
            v_height: 0,
            colormap: Colormap::autoscale(ColormapName::Gray),
            transform: Item3DTransform::default(),
        }
    }

    /// Set the height field (silx `_HeightMap.setData`), row-major. Returns `false`
    /// (unchanged) when `heights.len() != width * height`.
    pub fn set_data(&mut self, heights: &[f32], width: usize, height: usize) -> bool {
        if heights.len() != width * height {
            return false;
        }
        self.heights = heights.to_vec();
        self.h_width = width;
        self.h_height = height;
        true
    }

    /// Builder form of [`set_data`](Self::set_data).
    pub fn with_data(mut self, heights: &[f32], width: usize, height: usize) -> Self {
        self.set_data(heights, width, height);
        self
    }

    /// Set the colormapped data (silx `HeightMapData.setColormappedData`),
    /// row-major. May differ in size from the height field (nearest-neighbour
    /// resampled). Returns `false` when `data.len() != width * height`.
    pub fn set_colormapped_data(&mut self, data: &[f64], width: usize, height: usize) -> bool {
        if data.len() != width * height {
            return false;
        }
        self.values = data.to_vec();
        self.v_width = width;
        self.v_height = height;
        self.resolve_colormap();
        true
    }

    /// Builder form of [`set_colormapped_data`](Self::set_colormapped_data).
    pub fn with_colormapped_data(mut self, data: &[f64], width: usize, height: usize) -> Self {
        self.set_colormapped_data(data, width, height);
        self
    }

    /// Set the colormap. An autoscale colormap immediately resolves its range to
    /// the current colormapped data.
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
        self.resolve_colormap();
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.set_colormap(colormap);
        self
    }

    /// Refresh the colormap's autoscale bounds from the current colormapped data
    /// (silx `_syncSceneColormap`); a no-op for a pinned colormap.
    fn resolve_colormap(&mut self) {
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &self.values);
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap.
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Fit the colormap's value range to the colormapped data with `mode`.
    pub fn autoscale_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        let (vmin, vmax) = self.colormap.autoscale_range(mode, &self.values);
        self.colormap.vmin = vmin;
        self.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// Height-field dimensions `(width, height)`.
    pub fn dimensions(&self) -> (usize, usize) {
        (self.h_width, self.h_height)
    }

    /// True when nothing would be drawn (no height field or no colour data).
    pub fn is_empty(&self) -> bool {
        self.heights.is_empty() || self.values.is_empty()
    }

    /// World bounds `(min, max)` of the height-field point grid through the
    /// item's transform (silx `DataItem3D` bounds, `transformed=True`), or
    /// `None` when the height field is empty (independent of whether colour
    /// data is set).
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(height_grid_bounds(
            &self.heights,
            self.h_width,
            self.h_height,
        ))
    }

    /// Append the height field as colormapped square points to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.is_empty() {
            return;
        }
        let raw_bounds = height_grid_bounds(&self.heights, self.h_width, self.h_height);
        append_with_transform(&self.transform, raw_bounds, geometry, |g| {
            for row in 0..self.h_height {
                let vr = nearest_src_index(row, self.h_height, self.v_height);
                for col in 0..self.h_width {
                    let vc = nearest_src_index(col, self.h_width, self.v_width);
                    let z = self.heights[row * self.h_width + col];
                    let [r, gr, b, a] = self.colormap.color_at(self.values[vr * self.v_width + vc]);
                    g.add_point(
                        [col as f32, row as f32, z],
                        Color32::from_rgba_unmultiplied(r, gr, b, a),
                        1.0,
                        PointMarker::Square,
                    );
                }
            }
        });
    }
}

impl_item3d_transform!(HeightMapData);

/// A 2D height field coloured by an RGB(A) image (silx
/// `plot3d.items.HeightMapRGBA`). Like [`HeightMapData`] but each square point is
/// coloured directly by the (separately set, nearest-neighbour resampled) image
/// pixel rather than through a colormap.
#[derive(Clone, Debug)]
pub struct HeightMapRGBA {
    heights: Vec<f32>,
    h_width: usize,
    h_height: usize,
    colors: Vec<Color32>,
    c_width: usize,
    c_height: usize,
    transform: Item3DTransform,
}

impl Default for HeightMapRGBA {
    fn default() -> Self {
        Self::new()
    }
}

impl HeightMapRGBA {
    /// An empty RGBA height map.
    pub fn new() -> Self {
        Self {
            heights: Vec::new(),
            h_width: 0,
            h_height: 0,
            colors: Vec::new(),
            c_width: 0,
            c_height: 0,
            transform: Item3DTransform::default(),
        }
    }

    /// Set the height field (silx `_HeightMap.setData`), row-major. Returns `false`
    /// (unchanged) when `heights.len() != width * height`.
    pub fn set_data(&mut self, heights: &[f32], width: usize, height: usize) -> bool {
        if heights.len() != width * height {
            return false;
        }
        self.heights = heights.to_vec();
        self.h_width = width;
        self.h_height = height;
        true
    }

    /// Builder form of [`set_data`](Self::set_data).
    pub fn with_data(mut self, heights: &[f32], width: usize, height: usize) -> Self {
        self.set_data(heights, width, height);
        self
    }

    /// Set the RGB(A) image (silx `HeightMapRGBA.setColorData`), row-major. May
    /// differ in size from the height field (nearest-neighbour resampled, by width
    /// for the column axis — see [`HeightMapData`]). Returns `false` when
    /// `colors.len() != width * height`.
    pub fn set_color_data(&mut self, colors: &[Color32], width: usize, height: usize) -> bool {
        if colors.len() != width * height {
            return false;
        }
        self.colors = colors.to_vec();
        self.c_width = width;
        self.c_height = height;
        true
    }

    /// Builder form of [`set_color_data`](Self::set_color_data).
    pub fn with_color_data(mut self, colors: &[Color32], width: usize, height: usize) -> Self {
        self.set_color_data(colors, width, height);
        self
    }

    /// Height-field dimensions `(width, height)`.
    pub fn dimensions(&self) -> (usize, usize) {
        (self.h_width, self.h_height)
    }

    /// True when nothing would be drawn (no height field or no colour image).
    pub fn is_empty(&self) -> bool {
        self.heights.is_empty() || self.colors.is_empty()
    }

    /// World bounds `(min, max)` of the height-field point grid through the
    /// item's transform (silx `DataItem3D` bounds, `transformed=True`), or
    /// `None` when the height field is empty.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(height_grid_bounds(
            &self.heights,
            self.h_width,
            self.h_height,
        ))
    }

    /// Append the height field as RGBA square points to `geometry`.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.is_empty() {
            return;
        }
        let raw_bounds = height_grid_bounds(&self.heights, self.h_width, self.h_height);
        append_with_transform(&self.transform, raw_bounds, geometry, |g| {
            for row in 0..self.h_height {
                let cr = nearest_src_index(row, self.h_height, self.c_height);
                for col in 0..self.h_width {
                    let cc = nearest_src_index(col, self.h_width, self.c_width);
                    let z = self.heights[row * self.h_width + col];
                    let color = self.colors[cr * self.c_width + cc];
                    g.add_point([col as f32, row as f32, z], color, 1.0, PointMarker::Square);
                }
            }
        });
    }
}

impl_item3d_transform!(HeightMapRGBA);

/// silx's default isosurface colour `#FFD700FF` (gold), `Isosurface.__init__`.
pub const DEFAULT_ISOSURFACE_COLOR: Color32 = Color32::from_rgb(0xFF, 0xD7, 0x00);

/// silx's documented default auto-level: `mean(data) + std(data)` over the finite
/// samples (`volume.py` `setAutoLevelFunction` example, the value
/// `ScalarFieldView` seeds its first isosurface with). Returns NaN when there are
/// no finite samples.
pub fn mean_plus_std(data: &[f32]) -> f32 {
    let finite: Vec<f64> = data
        .iter()
        .filter(|v| v.is_finite())
        .map(|&v| v as f64)
        .collect();
    if finite.is_empty() {
        return f32::NAN;
    }
    let n = finite.len() as f64;
    let mean = finite.iter().sum::<f64>() / n;
    let var = finite.iter().map(|v| (v - mean) * (v - mean)).sum::<f64>() / n;
    (mean + var.sqrt()) as f32
}

/// One iso-surface of a [`ScalarField3D`]: an iso-level and a solid colour.
///
/// Port of silx `plot3d.items.volume.Isosurface`. The level is either a fixed
/// value or computed from the parent field by an auto-level function (silx
/// `setAutoLevelFunction`; e.g. [`mean_plus_std`]); the resolved value is stored
/// in `level` and refreshed by the owning [`ScalarField3D`] whenever the data
/// changes. The surface itself is built and emitted by the parent (the data lives
/// there), as a lit solid-colour mesh through the P1.2 mesh path.
#[derive(Clone, Debug)]
pub struct Isosurface {
    level: f32,
    auto: Option<fn(&[f32]) -> f32>,
    color: Color32,
    /// Whether the surface is emitted (silx `Item3D.setVisible`,
    /// `items/core.py:183-231`; default `True`). Hiding a surface keeps its
    /// level/colour while suppressing its geometry — the counterpart of the
    /// sibling owned child [`CutPlane`]'s `visible` flag.
    visible: bool,
}

impl Isosurface {
    /// A fixed-level iso-surface in the given colour.
    pub fn new(level: f32, color: Color32) -> Self {
        Self {
            level,
            auto: None,
            color,
            visible: true,
        }
    }

    /// An auto-level iso-surface: `level` is recomputed by `auto(data)` each time
    /// the parent field changes (silx `setAutoLevelFunction`).
    pub fn new_auto(auto: fn(&[f32]) -> f32, color: Color32) -> Self {
        Self {
            level: f32::NAN,
            auto: Some(auto),
            color,
            visible: true,
        }
    }

    /// The resolved iso-level (NaN if an auto-level has not yet been computed
    /// against data).
    pub fn level(&self) -> f32 {
        self.level
    }

    /// Set a fixed iso-level, clearing any auto-level function (silx `setLevel`).
    pub fn set_level(&mut self, level: f32) {
        self.level = level;
        self.auto = None;
    }

    /// Set the auto-level function (silx `setAutoLevelFunction`); takes effect on
    /// the next parent data update.
    pub fn set_auto_level(&mut self, auto: fn(&[f32]) -> f32) {
        self.auto = Some(auto);
    }

    /// True when the level is computed by an auto-level function.
    pub fn is_auto_level(&self) -> bool {
        self.auto.is_some()
    }

    /// The iso-surface colour.
    pub fn color(&self) -> Color32 {
        self.color
    }

    /// Set the iso-surface colour (silx `setColor`).
    pub fn set_color(&mut self, color: Color32) {
        self.color = color;
    }

    /// Whether the surface is emitted (silx `Item3D.isVisible`, default `true`).
    pub fn is_visible(&self) -> bool {
        self.visible
    }

    /// Show or hide the surface (silx `Item3D.setVisible`): a hidden surface
    /// keeps its level/colour but contributes no geometry.
    pub fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// Re-resolve an auto-level against `data` (called by the parent on data
    /// change). Fixed levels are left unchanged.
    fn resolve(&mut self, data: &[f32]) {
        if let Some(f) = self.auto {
            self.level = f(data);
        }
    }
}

/// Default cut-plane grid resolution: the slice is rasterised onto a
/// `resolution × resolution` texture (see [`CutPlane`]).
pub const DEFAULT_CUT_PLANE_RESOLUTION: usize = 256;

/// A colormapped cutting plane through a [`ScalarField3D`] (silx
/// `plot3d.items.volume.CutPlane`). It carries only presentation state — the
/// plane geometry, the [`Colormap`], the sampling [`ImageInterpolation`], and a
/// visibility flag — and reads the field samples from its owning `ScalarField3D`
/// (silx wires the data with `copy=False`; the data has one owner). Hidden by
/// default, matching silx (`ScalarField3D` creates its cut plane with
/// `setVisible(False)`).
///
/// Rendering (built by the owner in [`ScalarField3D::append_to`]): the plane is
/// intersected with the volume box `(0,0,0)..(width,height,depth)` to get the
/// contour polygon ([`box_plane_intersect`]); the slice is sampled on a
/// `resolution × resolution` grid in the plane, each sample coloured through the
/// colormap (CPU [`Colormap::color_at`], as the other 3D items), and the polygon
/// is fan-triangulated and emitted as one [`Scene3dTexturedMesh`].
///
/// Documented simplification: silx samples the 3D data texture per fragment
/// (continuous); this port rasterises the slice onto a 2D grid texture, so the
/// slice sharpness is bounded by `resolution` (the same CPU-colormap deviation as
/// P1.1–P2.1). The CPU sampler matches silx's texture convention — voxel centre
/// `(ix,iy,iz)` sits at world `(ix+0.5, iy+0.5, iz+0.5)` — with clamp-to-edge
/// outside the box; `interpolation` selects nearest vs trilinear sampling and is
/// also applied to the 2D texture.
#[derive(Clone, Debug)]
pub struct CutPlane {
    plane: Plane,
    colormap: Colormap,
    interpolation: ImageInterpolation,
    resolution: usize,
    visible: bool,
    /// Colour of the plane/box intersection contour (silx `PlaneInGroup` line
    /// colour, `primitives.py:1008` — default white `(1., 1., 1., 1.)`).
    stroke_color: Color32,
    /// Whether the contour is drawn (silx `PlaneInGroup.strokeVisible`,
    /// default `True`, `primitives.py:1010`).
    stroke_visible: bool,
    /// Whether samples at/below the colormap minimum are drawn (silx
    /// `CutPlane.getDisplayValuesBelowMin`, `volume.py:134-150`, default `True`).
    /// When `false`, silx's colormap GLSL runs `if (value == 0.) { discard; }`
    /// after normalization (`function.py:462-466, 516-520`), punching every texel
    /// whose normalized value clamps to 0 (raw ≤ vmin) out of the slice.
    display_values_below_min: bool,
}

impl Default for CutPlane {
    fn default() -> Self {
        Self::new()
    }
}

impl CutPlane {
    /// A hidden cut plane with silx defaults: normal `(0, 1, 0)` through the
    /// origin, the gray autoscale colormap, linear interpolation, and a visible
    /// white contour stroke. The range autoscales to the volume when the owning
    /// [`ScalarField3D`] sets data (silx `ScalarFieldView` re-autoscales the
    /// cut-plane colormap on `_updateData`).
    pub fn new() -> Self {
        Self {
            plane: Plane::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
            colormap: Colormap::autoscale(ColormapName::Gray),
            interpolation: ImageInterpolation::Linear,
            resolution: DEFAULT_CUT_PLANE_RESOLUTION,
            visible: false,
            stroke_color: Color32::WHITE,
            stroke_visible: true,
            display_values_below_min: true,
        }
    }

    /// The cutting plane (point + unit normal).
    pub fn plane(&self) -> &Plane {
        &self.plane
    }

    /// Mutable access to the cutting plane (point/normal setters).
    pub fn plane_mut(&mut self) -> &mut Plane {
        &mut self.plane
    }

    /// Set a point the plane passes through (silx `PlaneMixIn.setPoint`).
    pub fn set_point(&mut self, point: Vec3) {
        self.plane.set_point(point);
    }

    /// Set the plane normal; the zero vector leaves the plane unoriented
    /// (silx `PlaneMixIn.setNormal`).
    pub fn set_normal(&mut self, normal: Vec3) {
        self.plane.set_normal(normal);
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap (e.g. to set its value range directly).
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Set the colormap (silx `ColormapMixIn.setColormap`).
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
    }

    /// Builder form of [`set_colormap`](Self::set_colormap).
    pub fn with_colormap(mut self, colormap: Colormap) -> Self {
        self.colormap = colormap;
        self
    }

    /// The texture interpolation (silx `InterpolationMixIn`).
    pub fn interpolation(&self) -> ImageInterpolation {
        self.interpolation
    }

    /// Set the texture interpolation (silx `setInterpolation`).
    pub fn set_interpolation(&mut self, interpolation: ImageInterpolation) {
        self.interpolation = interpolation;
    }

    /// The grid resolution (texels per axis of the slice texture).
    pub fn resolution(&self) -> usize {
        self.resolution
    }

    /// Set the grid resolution (clamped to ≥ 1).
    pub fn set_resolution(&mut self, resolution: usize) {
        self.resolution = resolution.max(1);
    }

    /// Whether the cut plane is drawn (silx `setVisible`).
    pub fn is_visible(&self) -> bool {
        self.visible
    }

    /// Show or hide the cut plane (silx `setVisible`).
    pub fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// The colour of the plane's border stroke — the plane/box intersection
    /// contour (silx `ScalarFieldView.getStrokeColor`,
    /// `ScalarFieldView.py:555-557`).
    pub fn stroke_color(&self) -> Color32 {
        self.stroke_color
    }

    /// Set the colour of the plane's border stroke (silx
    /// `ScalarFieldView.setStrokeColor`, `ScalarFieldView.py:559-570`).
    pub fn set_stroke_color(&mut self, color: Color32) {
        self.stroke_color = color;
    }

    /// Whether the border stroke is drawn (silx `PlaneInGroup.strokeVisible`,
    /// `primitives.py:1047-1050`).
    pub fn is_stroke_visible(&self) -> bool {
        self.stroke_visible
    }

    /// Show or hide the border stroke (silx `PlaneInGroup.strokeVisible`
    /// setter, `primitives.py:1052-1056`).
    pub fn set_stroke_visible(&mut self, visible: bool) {
        self.stroke_visible = visible;
    }

    /// Whether samples at/below the colormap minimum are drawn (silx
    /// `CutPlane.getDisplayValuesBelowMin`, `volume.py:134-141`, default `True`).
    pub fn display_values_below_min(&self) -> bool {
        self.display_values_below_min
    }

    /// Show or hide samples at/below the colormap minimum (silx
    /// `CutPlane.setDisplayValuesBelowMin`, `volume.py:143-150`). When `false`,
    /// texels whose normalized value clamps to 0 (raw ≤ vmin) are punched out of
    /// the slice — silx's `discard` mask mode.
    pub fn set_display_values_below_min(&mut self, display: bool) {
        self.display_values_below_min = display;
    }
}

/// An orthonormal in-plane basis `(e1, e2)` for the plane with unit `normal`:
/// `e1 ⟂ normal`, `e2 = normal × e1`. The seed axis is whichever of x/y is least
/// aligned with `normal`, so the cross product never collapses.
fn plane_basis(normal: Vec3) -> (Vec3, Vec3) {
    let seed = if normal.x.abs() < 0.9 {
        Vec3::new(1.0, 0.0, 0.0)
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    };
    let e1 = normal.cross(seed).normalized();
    let e2 = normal.cross(e1).normalized();
    (e1, e2)
}

/// Sample the `(depth, height, width)` field (`zyx`, `width` contiguous) at world
/// point `p`, following silx's texture convention: voxel centre `(ix,iy,iz)` is
/// at world `(ix+0.5, iy+0.5, iz+0.5)`, and coordinates clamp to the edge voxel
/// outside the box. `Nearest` rounds to the nearest voxel; `Linear` trilinearly
/// interpolates the eight surrounding voxels.
fn sample_field_value(
    data: &[f32],
    depth: usize,
    height: usize,
    width: usize,
    p: Vec3,
    interpolation: ImageInterpolation,
) -> f32 {
    let idx = |ix: usize, iy: usize, iz: usize| data[(iz * height + iy) * width + ix];
    // World → continuous voxel coordinate (voxel centre at integer position).
    let (fx, fy, fz) = (p.x - 0.5, p.y - 0.5, p.z - 0.5);
    match interpolation {
        ImageInterpolation::Nearest => {
            let clamp = |f: f32, n: usize| (f.round().max(0.0) as usize).min(n - 1);
            idx(clamp(fx, width), clamp(fy, height), clamp(fz, depth))
        }
        ImageInterpolation::Linear => {
            // Clamp the centre coordinate to [0, n-1] (clamp-to-edge), then
            // interpolate towards the next voxel.
            let lo = |f: f32, n: usize| -> (usize, usize, f32) {
                let c = f.clamp(0.0, (n - 1) as f32);
                let i0 = c.floor() as usize;
                let i1 = (i0 + 1).min(n - 1);
                (i0, i1, c - i0 as f32)
            };
            let (x0, x1, dx) = lo(fx, width);
            let (y0, y1, dy) = lo(fy, height);
            let (z0, z1, dz) = lo(fz, depth);
            let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
            let c00 = lerp(idx(x0, y0, z0), idx(x1, y0, z0), dx);
            let c10 = lerp(idx(x0, y1, z0), idx(x1, y1, z0), dx);
            let c01 = lerp(idx(x0, y0, z1), idx(x1, y0, z1), dx);
            let c11 = lerp(idx(x0, y1, z1), idx(x1, y1, z1), dx);
            lerp(lerp(c00, c10, dy), lerp(c01, c11, dy), dz)
        }
    }
}

/// Build the cut-plane textured mesh for `cut_plane` over the `(depth, height,
/// width)` field, or `None` when the plane does not slice the volume (fewer than
/// three contour vertices) or the field is empty. The single owner of the
/// cut-plane geometry, called from [`ScalarField3D::append_to`].
fn build_cut_plane_mesh(
    data: &[f32],
    depth: usize,
    height: usize,
    width: usize,
    cut_plane: &CutPlane,
) -> Option<Scene3dTexturedMesh> {
    if data.is_empty() {
        return None;
    }
    let normal = cut_plane.plane.normal();
    let bounds = (
        Vec3::new(0.0, 0.0, 0.0),
        Vec3::new(width as f32, height as f32, depth as f32),
    );
    let contour = box_plane_intersect(bounds, normal, cut_plane.plane.point());
    if contour.len() < 3 {
        return None;
    }

    // Plane-space coordinates (s along e1, t along e2) of every contour vertex,
    // measured from the first vertex.
    let (e1, e2) = plane_basis(normal);
    let origin = contour[0];
    let st: Vec<(f32, f32)> = contour
        .iter()
        .map(|&v| {
            let d = v - origin;
            (d.dot(e1), d.dot(e2))
        })
        .collect();
    let (mut smin, mut smax) = (f32::INFINITY, f32::NEG_INFINITY);
    let (mut tmin, mut tmax) = (f32::INFINITY, f32::NEG_INFINITY);
    for &(s, t) in &st {
        smin = smin.min(s);
        smax = smax.max(s);
        tmin = tmin.min(t);
        tmax = tmax.max(t);
    }
    let sspan = (smax - smin).max(f32::MIN_POSITIVE);
    let tspan = (tmax - tmin).max(f32::MIN_POSITIVE);

    // Rasterise the slice onto a res×res grid (row-major, row 0 = t at tmin),
    // colouring each sample through the colormap → premultiplied-linear RGBA8.
    let res = cut_plane.resolution.max(1);
    let mut pixels = Vec::with_capacity(res * res * 4);
    for j in 0..res {
        let t = tmin + (j as f32 + 0.5) / res as f32 * tspan;
        for i in 0..res {
            let s = smin + (i as f32 + 0.5) / res as f32 * sspan;
            let p = origin + e1 * s + e2 * t;
            let value = sample_field_value(data, depth, height, width, p, cut_plane.interpolation);
            // silx's colormap GLSL discards texels whose *normalized* value clamps
            // to 0 (raw ≤ vmin) when displayValuesBelowMin is off — the discard
            // runs after normalization but before the isnan test, so NaN still
            // takes nancolor rather than being punched out (`function.py:462-520`).
            let color = if !cut_plane.display_values_below_min
                && !(value as f64).is_nan()
                && cut_plane.colormap.normalize(value as f64) == 0.0
            {
                Color32::TRANSPARENT
            } else {
                let [r, g, b, a] = cut_plane.colormap.color_at(value as f64);
                Color32::from_rgba_unmultiplied(r, g, b, a)
            };
            pixels.extend_from_slice(&premul_linear_rgba8(color));
        }
    }

    // Fan-triangulate the contour; each vertex's UV is its plane coordinate
    // normalised to the grid's bounding rect.
    let uv = |k: usize| [(st[k].0 - smin) / sspan, (st[k].1 - tmin) / tspan];
    let mut vertices = Vec::with_capacity((contour.len() - 2) * 3);
    let mut uvs = Vec::with_capacity((contour.len() - 2) * 3);
    for k in 1..contour.len() - 1 {
        for &idx in &[0usize, k, k + 1] {
            vertices.push(contour[idx].to_array());
            uvs.push(uv(idx));
        }
    }
    Some(Scene3dTexturedMesh {
        pixels,
        width: res as u32,
        height: res as u32,
        vertices,
        uvs,
        interpolation: cut_plane.interpolation,
    })
}

/// A 3D scalar field on a regular grid, rendered as marching-cubes iso-surfaces.
///
/// Port of silx `plot3d.items.volume.ScalarField3D`. Holds the `(depth, height,
/// width)` field (`zyx`, `width` contiguous) and a list of [`Isosurface`]s. Each
/// iso-surface is extracted with [marching cubes](marching_cubes_isosurface) and
/// emitted as a lit solid-colour mesh; the marching-cubes `(z,y,x)` vertices are
/// mapped to world `(x+0.5, y+0.5, z+0.5)` (and normals `(nz,ny,nx)→(nx,ny,nz)`),
/// reproducing silx's `_isogroup` swap matrix + `Translate(0.5,0.5,0.5)`. The
/// field bounds are the full volume box `(0,0,0)..(width,height,depth)` (silx
/// `BoundedGroup`), independent of any iso-surface extent.
///
/// It also owns one [`CutPlane`] (silx `ScalarField3D` owns a single cut plane),
/// hidden by default; when visible, [`append_to`](Self::append_to) builds its
/// colormapped slice from the field data (the data has one owner, as silx wires
/// the plane with `copy=False`).
#[derive(Clone, Debug)]
pub struct ScalarField3D {
    data: Vec<f32>,
    depth: usize,
    height: usize,
    width: usize,
    data_range: Option<(f32, f32, f32)>,
    isosurfaces: Vec<Isosurface>,
    cut_plane: CutPlane,
    transform: Item3DTransform,
}

impl Default for ScalarField3D {
    fn default() -> Self {
        Self::new()
    }
}

impl ScalarField3D {
    /// An empty scalar field with no iso-surfaces and a hidden cut plane.
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            depth: 0,
            height: 0,
            width: 0,
            data_range: None,
            isosurfaces: Vec::new(),
            cut_plane: CutPlane::new(),
            transform: Item3DTransform::default(),
        }
    }

    /// Set the 3D scalar field, `data` row-major as `(depth, height, width)` with
    /// `width` contiguous. Returns `false` (leaving the field unchanged) when
    /// `data.len() != depth*height*width` or any dimension is `< 2` (silx asserts
    /// `min(shape) >= 2`). Setting data re-resolves every auto-level iso-surface.
    pub fn set_data(&mut self, data: &[f32], depth: usize, height: usize, width: usize) -> bool {
        if depth < 2 || height < 2 || width < 2 || data.len() != depth * height * width {
            return false;
        }
        self.data = data.to_vec();
        self.depth = depth;
        self.height = height;
        self.width = width;
        self.data_range = compute_data_range(&self.data);
        let data = std::mem::take(&mut self.data);
        for iso in &mut self.isosurfaces {
            iso.resolve(&data);
        }
        self.data = data;
        self.resolve_cut_plane_colormap();
        true
    }

    /// Builder form of [`set_data`](Self::set_data); inconsistent data leaves the
    /// field empty.
    pub fn with_data(mut self, data: &[f32], depth: usize, height: usize, width: usize) -> Self {
        self.set_data(data, depth, height, width);
        self
    }

    /// Field dimensions `(depth, height, width)`.
    pub fn dimensions(&self) -> (usize, usize, usize) {
        (self.depth, self.height, self.width)
    }

    /// Read-only access to the field samples (`zyx`, `width` contiguous).
    pub fn data(&self) -> &[f32] {
        &self.data
    }

    /// The data range as `(min, min_positive, max)` over finite samples, or
    /// `None` when empty / all non-finite (silx `getDataRange`; `min_positive` is
    /// NaN when no sample is positive).
    pub fn data_range(&self) -> Option<(f32, f32, f32)> {
        self.data_range
    }

    /// True when no field data is set.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Add a fixed-level iso-surface, returning its index (silx `addIsosurface`).
    pub fn add_isosurface(&mut self, level: f32, color: Color32) -> usize {
        self.isosurfaces.push(Isosurface::new(level, color));
        self.isosurfaces.len() - 1
    }

    /// Add an auto-level iso-surface (silx `addIsosurface` with a callable),
    /// resolving the level against the current data immediately. Returns its
    /// index.
    pub fn add_auto_isosurface(&mut self, auto: fn(&[f32]) -> f32, color: Color32) -> usize {
        let mut iso = Isosurface::new_auto(auto, color);
        if !self.data.is_empty() {
            iso.resolve(&self.data);
        }
        self.isosurfaces.push(iso);
        self.isosurfaces.len() - 1
    }

    /// All iso-surfaces, in insertion order.
    pub fn isosurfaces(&self) -> &[Isosurface] {
        &self.isosurfaces
    }

    /// Mutable access to one iso-surface (e.g. to change its level or colour).
    pub fn isosurface_mut(&mut self, index: usize) -> Option<&mut Isosurface> {
        self.isosurfaces.get_mut(index)
    }

    /// Remove the iso-surface at `index` (silx `removeIsosurface`); out-of-range
    /// is a no-op returning `false`.
    pub fn remove_isosurface(&mut self, index: usize) -> bool {
        if index < self.isosurfaces.len() {
            self.isosurfaces.remove(index);
            true
        } else {
            false
        }
    }

    /// Remove all iso-surfaces (silx `clearIsosurfaces`).
    pub fn clear_isosurfaces(&mut self) {
        self.isosurfaces.clear();
    }

    /// Read-only access to the cut plane (silx `getCutPlanes()[0]`).
    pub fn cut_plane(&self) -> &CutPlane {
        &self.cut_plane
    }

    /// Mutable access to the cut plane — set its position/normal, colormap,
    /// interpolation, resolution, or visibility.
    pub fn cut_plane_mut(&mut self) -> &mut CutPlane {
        &mut self.cut_plane
    }

    /// Set the cut plane's colormap and resolve its autoscale bounds against the
    /// field (silx `ScalarFieldView.setColormap` → `_syncSceneColormap`). Prefer
    /// this over `cut_plane_mut().set_colormap`, which cannot see the volume and
    /// so leaves an autoscale colormap at its placeholder range.
    pub fn set_cut_plane_colormap(&mut self, colormap: Colormap) {
        self.cut_plane.colormap = colormap;
        self.resolve_cut_plane_colormap();
    }

    /// Refresh only the cut plane colormap's autoscale bounds from the volume
    /// (silx re-autoscales the cut plane on `_updateData`); a no-op for a pinned
    /// colormap or an empty field.
    fn resolve_cut_plane_colormap(&mut self) {
        if self.data.is_empty() || !self.cut_plane.colormap.is_autoscale() {
            return;
        }
        let values: Vec<f64> = self.data.iter().map(|&v| v as f64).collect();
        self.cut_plane.colormap = self
            .cut_plane
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &values);
    }

    /// Fit the cut plane's colormap range to the field with `mode` (silx
    /// autoscales the cut-plane colormap over the volume data), returning the new
    /// `(vmin, vmax)`. A no-op leaving the range unchanged when the field is
    /// empty.
    pub fn autoscale_cut_plane_colormap(&mut self, mode: AutoscaleMode) -> (f64, f64) {
        if self.data.is_empty() {
            let cm = &self.cut_plane.colormap;
            return (cm.vmin, cm.vmax);
        }
        let values: Vec<f64> = self.data.iter().map(|&v| v as f64).collect();
        let (vmin, vmax) = self.cut_plane.colormap.autoscale_range(mode, &values);
        self.cut_plane.colormap.vmin = vmin;
        self.cut_plane.colormap.vmax = vmax;
        (vmin, vmax)
    }

    /// The raw volume box `(0,0,0)..(width,height,depth)` in the object (voxel)
    /// frame, or `None` when no data is set.
    fn raw_bounds(&self) -> Option<(Vec3, Vec3)> {
        if self.data.is_empty() {
            return None;
        }
        Some((
            Vec3::new(0.0, 0.0, 0.0),
            Vec3::new(self.width as f32, self.height as f32, self.depth as f32),
        ))
    }

    /// The volume bounding box through the item's transform (silx
    /// `BoundedGroup` data bounds under the `DataItem3D` transform stack), or
    /// `None` when no data is set.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.transform.transform_bounds(self.raw_bounds())
    }

    /// Map a scene-frame position into the object (voxel) frame: identity fast
    /// path, else through the inverse of the composed item transform. `None`
    /// when the composed matrix is singular (e.g. a zero scale) — nothing is
    /// pickable then.
    fn scene_to_object(&self, p: Vec3) -> Option<Vec3> {
        if self.transform.is_identity() {
            return Some(p);
        }
        let inv = self
            .transform
            .composed_matrix(self.raw_bounds())
            .inverse()?;
        Some(inv.transform_point(p, false))
    }

    /// [`value_at`](Self::value_at) with `obj` already in the object (voxel)
    /// frame — the single box test + sampler both pick paths share.
    fn value_at_object(&self, obj: Vec3) -> Option<f32> {
        let (min, max) = self.raw_bounds()?;
        if obj.x < min.x
            || obj.y < min.y
            || obj.z < min.z
            || obj.x > max.x
            || obj.y > max.y
            || obj.z > max.z
        {
            return None;
        }
        Some(sample_field_value(
            &self.data,
            self.depth,
            self.height,
            self.width,
            obj,
            self.cut_plane.interpolation(),
        ))
    }

    /// Sample the field value at scene position `world` (inverse-mapped through
    /// the item transform into the voxel frame), or `None` when the field is
    /// empty or the position lies outside the volume box. Uses the cut plane's
    /// interpolation (nearest vs trilinear) so a picked value matches the slice
    /// the user sees. The single field sampler (`sample_field_value`, the same
    /// owner the cut-plane raster uses), with an explicit box test so a point
    /// past the edge reads `None` rather than the clamped edge voxel.
    pub fn value_at(&self, world: Vec3) -> Option<f32> {
        self.value_at_object(self.scene_to_object(world)?)
    }

    /// Intersect the picking `segment` (`(near, far)` in scene space) with the
    /// cut plane, returning the scene position of the hit when the cut plane is
    /// **visible** and the hit lies inside the volume box, else `None`. Port of
    /// silx `items.volume.CutPlane._pickFull` (segment/plane intersection, then
    /// a data-bounds test — silx converts the pick ray into each object's frame
    /// first, so the segment is mapped through the inverse item transform and
    /// the hit mapped back). Pair with [`value_at`](Self::value_at) for the
    /// sampled value at the hit — the value the colormapped slice shows there.
    pub fn pick_cut_plane(&self, segment: (Vec3, Vec3)) -> Option<Vec3> {
        if !self.cut_plane.is_visible() || self.data.is_empty() {
            return None;
        }
        let a = self.scene_to_object(segment.0)?;
        let b = self.scene_to_object(segment.1)?;
        let plane = self.cut_plane.plane();
        let hit = segment_plane_intersect(a, b, plane.normal(), plane.point())
            .into_iter()
            .find(|&hit| self.value_at_object(hit).is_some())?;
        Some(if self.transform.is_identity() {
            hit
        } else {
            self.transform
                .composed_matrix(self.raw_bounds())
                .transform_point(hit, false)
        })
    }

    /// Append every iso-surface's triangles to `geometry`. Iso-surfaces are
    /// emitted from highest level to lowest (silx `_updateIsosurfaces` sorts by
    /// `-level`); a non-finite level or an empty surface is skipped.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.data.is_empty() {
            return;
        }
        append_with_transform(&self.transform, self.raw_bounds(), geometry, |g| {
            self.append_raw(g)
        });
    }

    /// Build the raw (voxel-frame) geometry — see [`Self::append_to`]. The
    /// iso-surface and cut-plane emission is factored into free helpers so
    /// [`ComplexField3D`] can reuse them with per-child mode projections.
    fn append_raw(&self, geometry: &mut Scene3dGeometry) {
        append_solid_isosurfaces(
            geometry,
            &self.data,
            self.depth,
            self.height,
            self.width,
            &self.isosurfaces,
        );
        append_cut_plane(
            geometry,
            &self.data,
            self.depth,
            self.height,
            self.width,
            &self.cut_plane,
            self.raw_bounds(),
        );
    }
}

/// Map a marching-cubes triangle to world-space vertex positions: each zyx voxel
/// vertex becomes xyz with the 0.5 cell-centre offset (silx `_isogroup`
/// transform).
fn iso_triangle_positions(vertices: &[[f32; 3]], tri: &[u32]) -> [[f32; 3]; 3] {
    [0usize, 1, 2].map(|k| {
        let v = vertices[tri[k] as usize];
        [v[2] + 0.5, v[1] + 0.5, v[0] + 0.5]
    })
}

/// Map a marching-cubes triangle's per-vertex normals from zyx to xyz.
fn iso_triangle_normals(normals: &[[f32; 3]], tri: &[u32]) -> [[f32; 3]; 3] {
    [0usize, 1, 2].map(|k| {
        let nm = normals[tri[k] as usize];
        [nm[2], nm[1], nm[0]]
    })
}

/// Emit solid iso-surfaces of a `(depth, height, width)` field to `geometry`,
/// geometry sampled from `data`. Surfaces are drawn from highest level to lowest
/// (silx `_updateIsosurfaces` sorts by `-level`); a non-finite level or an empty
/// surface is skipped. Shared by [`ScalarField3D`] and [`ComplexField3D`] (silx
/// extracts every surface from the parent-mode field).
fn append_solid_isosurfaces(
    geometry: &mut Scene3dGeometry,
    data: &[f32],
    depth: usize,
    height: usize,
    width: usize,
    isosurfaces: &[Isosurface],
) {
    let mut order: Vec<usize> = (0..isosurfaces.len()).collect();
    order.sort_by(|&a, &b| isosurfaces[b].level.total_cmp(&isosurfaces[a].level));
    for i in order {
        let iso = &isosurfaces[i];
        if !iso.visible || !iso.level.is_finite() {
            continue;
        }
        let Some((vertices, normals, indices)) =
            marching_cubes_isosurface(data, depth, height, width, iso.level, true)
        else {
            continue;
        };
        for tri in indices.chunks_exact(3) {
            let p = iso_triangle_positions(&vertices, tri);
            let n = iso_triangle_normals(&normals, tri);
            geometry.add_mesh_triangle(p, iso.color, n);
        }
    }
}

/// Emit one colormapped iso-surface (silx `ComplexIsosurface` with a colour mode
/// ≠ NONE): the surface geometry is extracted from `geom_data` (the field mode)
/// at `iso`'s level, then each vertex is coloured by trilinearly sampling
/// `color_data` (the iso's own colour mode) and mapping through `iso`'s colormap,
/// with alpha forced to the iso's alpha (silx `mesh.alpha = color[3]`).
/// `geom_data` and `color_data` share the `(depth, height, width)` grid `dims`.
fn append_colormapped_isosurface(
    geometry: &mut Scene3dGeometry,
    geom_data: &[f32],
    color_data: &[f32],
    dims: (usize, usize, usize),
    iso: &ComplexIsosurface,
) {
    let level = iso.level();
    if !iso.is_visible() || !level.is_finite() {
        return;
    }
    let (depth, height, width) = dims;
    let Some((vertices, normals, indices)) =
        marching_cubes_isosurface(geom_data, depth, height, width, level, true)
    else {
        return;
    };
    let (colormap, alpha) = (iso.colormap(), iso.alpha());
    for tri in indices.chunks_exact(3) {
        let p = iso_triangle_positions(&vertices, tri);
        let n = iso_triangle_normals(&normals, tri);
        let rgba = [0usize, 1, 2].map(|k| {
            // The colour value is sampled at the surface vertex's voxel location
            // (silx `interp3d(values, vertices, method="linear")`); the world
            // point is the same 0.5-offset xyz used for the geometry.
            let v = vertices[tri[k] as usize];
            let world = Vec3::new(v[2] + 0.5, v[1] + 0.5, v[0] + 0.5);
            let value = sample_field_value(
                color_data,
                depth,
                height,
                width,
                world,
                ImageInterpolation::Linear,
            ) as f64;
            let [r, g, b, _a] = colormap.color_at(value);
            egui::Rgba::from(Color32::from_rgba_unmultiplied(r, g, b, alpha)).to_array()
        });
        geometry.add_mesh_triangle_rgba(p, rgba, n);
    }
}

/// Emit the cut-plane slice (a colormapped textured mesh) and its border stroke
/// for `cut_plane`, sampling the slice from `data`. `raw_bounds` is the field's
/// voxel-frame bounding box, used for the plane/box intersection contour. Shared
/// by [`ScalarField3D`] and [`ComplexField3D`], which passes a different mode's
/// projection as `data` when the cut plane carries its own complex mode (silx
/// `ComplexCutPlane._syncDataWithParent`).
fn append_cut_plane(
    geometry: &mut Scene3dGeometry,
    data: &[f32],
    depth: usize,
    height: usize,
    width: usize,
    cut_plane: &CutPlane,
    raw_bounds: Option<(Vec3, Vec3)>,
) {
    if !cut_plane.visible {
        return;
    }
    if let Some(mesh) = build_cut_plane_mesh(data, depth, height, width, cut_plane) {
        geometry.add_textured_mesh(mesh);
    }
    // Border stroke: the plane/box intersection contour as a closed line loop
    // (silx PlaneInGroup.contourVertices, primitives.py:1082-1101
    // `boxPlaneIntersect` over the parent data bounds → `Lines(mode="loop")`).
    // Drawn 1px like the rest of the line chrome; the contour is built in the
    // voxel frame like the slice itself.
    if cut_plane.stroke_visible
        && let Some(bounds) = raw_bounds
    {
        let contour =
            box_plane_intersect(bounds, cut_plane.plane.normal(), cut_plane.plane.point());
        if contour.len() >= 3 {
            for (i, &a) in contour.iter().enumerate() {
                let b = contour[(i + 1) % contour.len()];
                geometry.add_line(a.to_array(), b.to_array(), cut_plane.stroke_color);
            }
        }
    }
}

impl_item3d_transform!(ScalarField3D);

/// Compute `(min, min_positive, max)` over the finite samples (silx
/// `ScalarField3D._computeRangeFromData` via `min_max(..., min_positive=True,
/// finite=True)`). `min_positive` is NaN when no sample is `> 0`; returns `None`
/// when there are no finite samples.
fn compute_data_range(data: &[f32]) -> Option<(f32, f32, f32)> {
    let mut min = f32::INFINITY;
    let mut max = f32::NEG_INFINITY;
    let mut min_pos = f32::INFINITY;
    let mut any = false;
    for &v in data {
        if !v.is_finite() {
            continue;
        }
        any = true;
        min = min.min(v);
        max = max.max(v);
        if v > 0.0 {
            min_pos = min_pos.min(v);
        }
    }
    if !any {
        return None;
    }
    let min_pos = if min_pos.is_finite() {
        min_pos
    } else {
        f32::NAN
    };
    Some((min, min_pos, max))
}

/// One colormapped iso-surface of a [`ComplexField3D`]: the surface geometry is
/// extracted from the field's own [`ComplexMode`] (like a solid [`Isosurface`]),
/// but the surface is *coloured* by a second, independent mode's values through a
/// [`Colormap`].
///
/// Port of silx `plot3d.items.volume.ComplexIsosurface` with a colour mode ≠
/// `NONE` (`volume.py:711-801`): `_syncDataWithParent` takes the surface from
/// `parent.getData(mode=parent.getComplexMode())` and the colours from
/// `parent.getData(mode=self.getComplexMode())`, building a
/// `primitives.ColormapMesh3D` whose `alpha` is the iso colour's alpha channel.
/// The classic "iso-surface of amplitude coloured by phase". A solid
/// iso-surface (silx colour mode `NONE`) stays a plain [`Isosurface`] on the
/// field; this type is only the colormapped variant.
#[derive(Clone, Debug)]
pub struct ComplexIsosurface {
    /// Carries the iso level / auto-level; its colour's **alpha** channel is the
    /// surface alpha (silx `mesh.alpha = self._color[3]`), the RGB is unused.
    iso: Isosurface,
    /// The mode whose values colour the surface (silx `self.getComplexMode()`).
    color_mode: ComplexMode,
    /// The colormap applied to `color_mode`'s values.
    colormap: Colormap,
}

impl ComplexIsosurface {
    /// A fixed-level colormapped iso-surface. `color`'s alpha is the surface
    /// translucency (silx `mesh.alpha`); its RGB is ignored — the colormap
    /// supplies colour.
    pub fn new(level: f32, color_mode: ComplexMode, colormap: Colormap, color: Color32) -> Self {
        Self {
            iso: Isosurface::new(level, color),
            color_mode,
            colormap,
        }
    }

    /// An auto-level colormapped iso-surface: the level is recomputed by
    /// `auto(data)` against the field's own-mode projection on each data change
    /// (silx `setAutoLevelFunction`).
    pub fn new_auto(
        auto: fn(&[f32]) -> f32,
        color_mode: ComplexMode,
        colormap: Colormap,
        color: Color32,
    ) -> Self {
        Self {
            iso: Isosurface::new_auto(auto, color),
            color_mode,
            colormap,
        }
    }

    /// The resolved iso-level (NaN before an auto level is computed).
    pub fn level(&self) -> f32 {
        self.iso.level()
    }

    /// Set a fixed iso-level, clearing any auto-level function (silx `setLevel`).
    pub fn set_level(&mut self, level: f32) {
        self.iso.set_level(level);
    }

    /// Set the auto-level function (silx `setAutoLevelFunction`).
    pub fn set_auto_level(&mut self, auto: fn(&[f32]) -> f32) {
        self.iso.set_auto_level(auto);
    }

    /// True when the level is computed by an auto-level function.
    pub fn is_auto_level(&self) -> bool {
        self.iso.is_auto_level()
    }

    /// Whether the surface is emitted (silx `Item3D.isVisible`, default `true`).
    pub fn is_visible(&self) -> bool {
        self.iso.is_visible()
    }

    /// Show or hide the surface (silx `Item3D.setVisible`).
    pub fn set_visible(&mut self, visible: bool) {
        self.iso.set_visible(visible);
    }

    /// The colour mode used to colour the surface.
    pub fn color_mode(&self) -> ComplexMode {
        self.color_mode
    }

    /// Set the colour mode (silx `setComplexMode`).
    pub fn set_color_mode(&mut self, mode: ComplexMode) {
        self.color_mode = mode;
    }

    /// The surface alpha (silx `self._color[3]`).
    pub fn alpha(&self) -> u8 {
        self.iso.color().a()
    }

    /// Set the surface alpha (silx `setColor` alpha channel).
    pub fn set_alpha(&mut self, alpha: u8) {
        let c = self.iso.color();
        self.iso
            .set_color(Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), alpha));
    }

    /// Read-only access to the colormap.
    pub fn colormap(&self) -> &Colormap {
        &self.colormap
    }

    /// Mutable access to the colormap.
    pub fn colormap_mut(&mut self) -> &mut Colormap {
        &mut self.colormap
    }

    /// Set the colormap (silx `ColormapMixIn.setColormap`).
    pub fn set_colormap(&mut self, colormap: Colormap) {
        self.colormap = colormap;
    }

    /// Re-resolve against the parent field: the auto level against `geom_data`
    /// (the field's own-mode projection, which the surface is extracted from) and
    /// an autoscale colormap against `color_data` (the colour mode's projection,
    /// silx `_setColormappedData` → `_syncSceneColormap`). Fixed levels and
    /// pinned colormaps are left unchanged.
    fn resolve(&mut self, geom_data: &[f32], color_data: &[f32]) {
        self.iso.resolve(geom_data);
        let values: Vec<f64> = color_data.iter().map(|&v| f64::from(v)).collect();
        self.colormap = self
            .colormap
            .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &values);
    }
}

/// A 3D complex field on a regular grid, visualised by projecting each sample to
/// a real scalar (the [`ComplexMode`]) and then reusing the [`ScalarField3D`]
/// machinery — marching-cubes iso-surfaces and the colormapped cut plane.
///
/// Port of silx `plot3d.items.volume.ComplexField3D` (+ `ComplexMixIn`). Holds
/// the `(depth, height, width)` complex field as parallel real/imaginary arrays
/// (`zyx`, `width` contiguous) and an inner `ScalarField3D` carrying the current
/// projection. [`set_complex_mode`](Self::set_complex_mode) reprojects and, as in
/// silx, clears every iso-surface (their levels were tied to the old mode's
/// range); the cut plane persists across a mode change. Solid iso-surfaces and
/// the cut plane's geometry/colormap are reached through
/// [`field`](Self::field) / [`field_mut`](Self::field_mut).
///
/// Per-child complex modes (silx `ComplexCutPlane` / `ComplexIsosurface`, both
/// `ComplexMixIn`s) let a child show a *different* mode than the field:
/// [`set_cut_plane_mode`](Self::set_cut_plane_mode) slices e.g. PHASE through an
/// ABSOLUTE volume, and [`add_colormapped_isosurface`](Self::add_colormapped_isosurface)
/// extracts a surface from the field mode but colours it by another mode's values
/// through a [`Colormap`] (the classic "iso-surface of amplitude coloured by
/// phase"). Solid iso-surfaces (silx colour mode NONE) stay plain [`Isosurface`]s
/// on the inner field; colormapped ones are [`ComplexIsosurface`]s owned here.
///
/// The mode is the shared silx `ComplexMode` ([`crate::core::complex`]); the six
/// scalar modes (`Absolute`, `Phase`, `Real`, `Imaginary`, `SquareAmplitude`,
/// `Log10Amplitude`) project to a real field. Documented simplification (matches
/// the rest of the port): silx's two hue-display modes (`AmplitudePhase`,
/// `Log10AmplitudePhase`) colour an iso-surface by phase rather than extract a
/// scalar; they are not ported and project to an all-zero field
/// ([`ComplexMode::to_scalar`] returns `0.0` for them).
#[derive(Clone, Debug)]
pub struct ComplexField3D {
    re: Vec<f32>,
    im: Vec<f32>,
    depth: usize,
    height: usize,
    width: usize,
    mode: ComplexMode,
    /// The cut plane's own complex mode (silx `ComplexCutPlane`, a `ComplexMixIn`):
    /// `None` follows the field's `mode`, `Some(m)` slices `m`'s projection so the
    /// slice can show e.g. PHASE while the iso-surfaces sit on ABSOLUTE.
    cut_plane_mode: Option<ComplexMode>,
    /// Colormapped iso-surfaces (silx `ComplexIsosurface` with colour mode ≠
    /// NONE): geometry from the field's `mode`, colour from each surface's own
    /// mode. Solid iso-surfaces live on the inner `field` (colour mode NONE).
    colormapped_isosurfaces: Vec<ComplexIsosurface>,
    field: ScalarField3D,
}

impl Default for ComplexField3D {
    fn default() -> Self {
        Self::new()
    }
}

impl ComplexField3D {
    /// An empty complex field with the default mode (amplitude, silx
    /// `ABSOLUTE`) and a hidden cut plane.
    pub fn new() -> Self {
        Self {
            re: Vec::new(),
            im: Vec::new(),
            mode: ComplexMode::Absolute,
            depth: 0,
            height: 0,
            width: 0,
            cut_plane_mode: None,
            colormapped_isosurfaces: Vec::new(),
            field: ScalarField3D::new(),
        }
    }

    /// Set the complex field from parallel real/imaginary arrays, both row-major
    /// `(depth, height, width)` with `width` contiguous. Returns `false` (leaving
    /// the field unchanged) when the lengths disagree, `re.len() !=
    /// depth*height*width`, or any dimension is `< 2` (silx asserts
    /// `min(shape) >= 2`). The current mode's projection is pushed into the inner
    /// field (re-resolving auto-level iso-surfaces).
    pub fn set_data(
        &mut self,
        re: &[f32],
        im: &[f32],
        depth: usize,
        height: usize,
        width: usize,
    ) -> bool {
        if depth < 2 || height < 2 || width < 2 {
            return false;
        }
        let n = depth * height * width;
        if re.len() != n || im.len() != n {
            return false;
        }
        self.re = re.to_vec();
        self.im = im.to_vec();
        self.depth = depth;
        self.height = height;
        self.width = width;
        self.reproject();
        true
    }

    /// Builder form of [`set_data`](Self::set_data); inconsistent data leaves the
    /// field empty.
    pub fn with_data(
        mut self,
        re: &[f32],
        im: &[f32],
        depth: usize,
        height: usize,
        width: usize,
    ) -> Self {
        self.set_data(re, im, depth, height, width);
        self
    }

    /// The current complex visualisation mode.
    pub fn complex_mode(&self) -> ComplexMode {
        self.mode
    }

    /// Set the complex visualisation mode (silx `setComplexMode`). Changing it
    /// clears every iso-surface — solid and colormapped (their levels were tied
    /// to the previous mode's value range) — and reprojects the field; the cut
    /// plane is kept. A no-op when the mode is unchanged.
    pub fn set_complex_mode(&mut self, mode: ComplexMode) {
        if mode == self.mode {
            return;
        }
        self.mode = mode;
        self.field.clear_isosurfaces();
        self.colormapped_isosurfaces.clear();
        self.reproject();
    }

    /// The projected real field of `mode` (silx `getData(mode=…)`), or `None`
    /// when no data is set.
    pub fn projected_data(&self, mode: ComplexMode) -> Option<Vec<f32>> {
        if self.re.is_empty() {
            return None;
        }
        Some(
            self.re
                .iter()
                .zip(&self.im)
                .map(|(&r, &i)| mode.to_scalar(r, i))
                .collect(),
        )
    }

    /// The `(min, min_positive, max)` range of `mode`'s projection over finite
    /// samples (silx `getDataRange(mode=…)`), or `None` when empty / all
    /// non-finite.
    pub fn data_range_for(&self, mode: ComplexMode) -> Option<(f32, f32, f32)> {
        let data = self.projected_data(mode)?;
        compute_data_range(&data)
    }

    /// Field dimensions `(depth, height, width)`.
    pub fn dimensions(&self) -> (usize, usize, usize) {
        (self.depth, self.height, self.width)
    }

    /// True when no field data is set.
    pub fn is_empty(&self) -> bool {
        self.re.is_empty()
    }

    /// Read-only access to the inner scalar field (the current projection, its
    /// iso-surfaces, and the cut plane).
    pub fn field(&self) -> &ScalarField3D {
        &self.field
    }

    /// Mutable access to the inner scalar field — add/remove *solid* iso-surfaces
    /// (silx colour mode NONE), set the cut plane's geometry/colormap/stroke. The
    /// field data itself is owned here and refreshed on
    /// `set_data`/`set_complex_mode`; do not call its `set_data` directly.
    /// Colormapped iso-surfaces and the cut plane's own complex mode are managed
    /// through this type's own methods, not the inner field.
    pub fn field_mut(&mut self) -> &mut ScalarField3D {
        &mut self.field
    }

    /// The cut plane's own complex mode (silx `ComplexCutPlane.getComplexMode`):
    /// `None` follows the field's mode, `Some(m)` slices `m`'s projection.
    pub fn cut_plane_mode(&self) -> Option<ComplexMode> {
        self.cut_plane_mode
    }

    /// Give the cut plane its own complex mode (silx `ComplexCutPlane.setComplexMode`)
    /// so it can show a different projection than the iso-surfaces — e.g. a PHASE
    /// slice through an ABSOLUTE iso-surface. `None` (the default) makes the slice
    /// follow the field's own mode.
    pub fn set_cut_plane_mode(&mut self, mode: Option<ComplexMode>) {
        self.cut_plane_mode = mode;
    }

    /// Add a colormapped iso-surface (silx `ComplexIsosurface` with colour mode ≠
    /// NONE); returns its index. The surface geometry is taken from the field's
    /// own mode; the colour from `iso`'s mode. The auto-level and an autoscale
    /// colormap are resolved immediately against the current data.
    pub fn add_colormapped_isosurface(&mut self, mut iso: ComplexIsosurface) -> usize {
        if !self.re.is_empty() {
            let color_data = self.projected_data(iso.color_mode).unwrap_or_default();
            iso.resolve(self.field.data(), &color_data);
        }
        self.colormapped_isosurfaces.push(iso);
        self.colormapped_isosurfaces.len() - 1
    }

    /// The colormapped iso-surfaces (silx colour mode ≠ NONE).
    pub fn colormapped_isosurfaces(&self) -> &[ComplexIsosurface] {
        &self.colormapped_isosurfaces
    }

    /// Mutable access to a colormapped iso-surface by index, or `None` when out of
    /// range. Level/colormap edits take effect on the next data change or append.
    pub fn colormapped_isosurface_mut(&mut self, index: usize) -> Option<&mut ComplexIsosurface> {
        self.colormapped_isosurfaces.get_mut(index)
    }

    /// Remove a colormapped iso-surface by index (a no-op when out of range).
    pub fn remove_colormapped_isosurface(&mut self, index: usize) {
        if index < self.colormapped_isosurfaces.len() {
            self.colormapped_isosurfaces.remove(index);
        }
    }

    /// Remove every colormapped iso-surface.
    pub fn clear_colormapped_isosurfaces(&mut self) {
        self.colormapped_isosurfaces.clear();
    }

    /// The volume bounding box through the item's transform, or `None` when no
    /// data is set.
    pub fn bounds(&self) -> Option<(Vec3, Vec3)> {
        self.field.bounds()
    }

    /// Append the field's geometry to `geometry`: solid iso-surfaces (from the
    /// field's own mode), colormapped iso-surfaces (geometry from the field mode,
    /// colour from each surface's own mode), then the cut plane (sliced from its
    /// own mode when set, otherwise the field mode). The iso-surface geometry and
    /// cut-plane slice are built through the same free helpers as
    /// [`ScalarField3D::append_to`], with the per-child mode projections silx's
    /// `ComplexCutPlane`/`ComplexIsosurface` supply.
    pub fn append_to(&self, geometry: &mut Scene3dGeometry) {
        if self.field.data().is_empty() {
            return;
        }
        append_with_transform(
            self.field.transform(),
            self.field.raw_bounds(),
            geometry,
            |g| self.append_raw(g),
        );
    }

    /// Build the raw (voxel-frame) geometry — see [`Self::append_to`].
    fn append_raw(&self, geometry: &mut Scene3dGeometry) {
        let (depth, height, width) = (self.depth, self.height, self.width);
        // Solid iso-surfaces (silx colour mode NONE), geometry from the field's
        // own-mode projection held by the inner field.
        append_solid_isosurfaces(
            geometry,
            self.field.data(),
            depth,
            height,
            width,
            &self.field.isosurfaces,
        );
        // Colormapped iso-surfaces: geometry from the field mode, colour from each
        // surface's own mode (silx `ComplexIsosurface._updateScenePrimitive`).
        for iso in &self.colormapped_isosurfaces {
            let Some(color_data) = self.projected_data(iso.color_mode) else {
                continue;
            };
            append_colormapped_isosurface(
                geometry,
                self.field.data(),
                &color_data,
                (depth, height, width),
                iso,
            );
        }
        // The cut plane. With its own mode set (silx `ComplexCutPlane`), it slices
        // that mode's projection AND takes that mode's data range
        // (`_syncDataWithParent`: `getData(mode)` + `getDataRange(mode)`), so an
        // autoscale slice colormap re-ranges to the override mode's data. When no
        // own mode is set (or it equals the field mode) the inner field's slice
        // and colormap are used directly.
        match self.cut_plane_mode {
            Some(mode) if mode != self.mode => {
                if let Some(data) = self.projected_data(mode) {
                    let mut cut_plane = self.field.cut_plane().clone();
                    let values: Vec<f64> = data.iter().map(|&v| f64::from(v)).collect();
                    *cut_plane.colormap_mut() = self
                        .field
                        .cut_plane()
                        .colormap()
                        .resolved(DEFAULT_COLORMAP_AUTOSCALE_MODE, &values);
                    append_cut_plane(
                        geometry,
                        &data,
                        depth,
                        height,
                        width,
                        &cut_plane,
                        self.field.raw_bounds(),
                    );
                }
            }
            _ => append_cut_plane(
                geometry,
                self.field.data(),
                depth,
                height,
                width,
                self.field.cut_plane(),
                self.field.raw_bounds(),
            ),
        }
    }

    /// The item's transform stack (silx `DataItem3D` transforms,
    /// `items/core.py:288-315`), delegated to the inner [`ScalarField3D`] so
    /// bounds, geometry, and the cut-plane pick follow it by construction.
    pub fn transform(&self) -> &Item3DTransform {
        self.field.transform()
    }

    /// Mutable access to the transform stack (silx setters,
    /// `items/core.py:335-485`).
    pub fn transform_mut(&mut self) -> &mut Item3DTransform {
        self.field.transform_mut()
    }

    /// Push the current mode's projection into the inner scalar field, then
    /// re-resolve every colormapped iso-surface: its auto level against the
    /// field-mode geometry and an autoscale colormap against its own colour
    /// mode's projection (silx `ComplexIsosurface._syncDataWithParent`).
    fn reproject(&mut self) {
        let data: Vec<f32> = self
            .re
            .iter()
            .zip(&self.im)
            .map(|(&r, &i)| self.mode.to_scalar(r, i))
            .collect();
        self.field
            .set_data(&data, self.depth, self.height, self.width);
        for i in 0..self.colormapped_isosurfaces.len() {
            let color_mode = self.colormapped_isosurfaces[i].color_mode;
            let color_data = self.projected_data(color_mode).unwrap_or_default();
            self.colormapped_isosurfaces[i].resolve(&data, &color_data);
        }
    }
}

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

    /// A 3×3×3 ramp field whose value equals its `z` index (so a known world
    /// position has a predictable sample): `data[z][y][x] = z`.
    fn ramp_field() -> ScalarField3D {
        let (d, h, w) = (3usize, 3usize, 3usize);
        let mut data = vec![0.0f32; d * h * w];
        for z in 0..d {
            for y in 0..h {
                for x in 0..w {
                    data[(z * h + y) * w + x] = z as f32;
                }
            }
        }
        ScalarField3D::new().with_data(&data, d, h, w)
    }

    #[test]
    fn colormapped_items_default_to_gray_autoscale_like_silx() {
        // silx ColormapMixIn items default to gray + autoscale
        // (vmin=vmax=None): the range must track the data, not a fixed [0, 1].
        assert!(Scatter3D::new().colormap().is_autoscale());
        assert!(Scatter2D::new().colormap().is_autoscale());
        assert!(ColormapMesh3D::new().colormap().is_autoscale());
        assert!(ImageData3D::new().colormap().is_autoscale());
        assert!(HeightMapData::new().colormap().is_autoscale());
        assert!(CutPlane::new().colormap().is_autoscale());
        // Gray palette (silx `ColormapMixIn` default colormap name).
        assert_eq!(
            Scatter3D::new().colormap().lut,
            Colormap::new(ColormapName::Gray, 0.0, 1.0).lut
        );
    }

    #[test]
    fn set_data_resolves_the_default_colormap_to_the_data_range() {
        // A default (autoscale) colormap fed out-of-[0,1] data resolves its
        // range to the data min/max — silx `_syncSceneColormap` on data change.
        let mut s = Scatter3D::new();
        s.set_data(&[0.0, 1.0, 2.0], &[0.0; 3], &[0.0; 3], &[10.0, 30.0, 20.0]);
        assert_eq!((s.colormap().vmin, s.colormap().vmax), (10.0, 30.0));

        let mut img = ImageData3D::new();
        img.set_data(&[-5.0, 0.0, 5.0, 15.0], 2, 2);
        assert_eq!((img.colormap().vmin, img.colormap().vmax), (-5.0, 15.0));
    }

    #[test]
    fn set_data_leaves_a_pinned_colormap_untouched() {
        // A user-pinned colormap must NOT be re-ranged by data (silx keeps a
        // set vmin/vmax across data updates).
        let mut s = Scatter3D::new();
        s.set_colormap(Colormap::new(ColormapName::Viridis, 0.0, 1.0));
        s.set_data(&[0.0, 1.0], &[0.0; 2], &[0.0; 2], &[100.0, 200.0]);
        assert_eq!((s.colormap().vmin, s.colormap().vmax), (0.0, 1.0));
    }

    #[test]
    fn cut_plane_autoscales_to_the_volume_on_set_data() {
        // The cut-plane colormap defaults to autoscale and, per silx
        // ScalarFieldView, re-ranges to the volume when data is set. The ramp
        // field spans z = 0..2, so MINMAX → (0, 2).
        let field = ramp_field();
        let cm = field.cut_plane().colormap();
        assert_eq!((cm.vmin, cm.vmax), (0.0, 2.0));
    }

    #[test]
    fn set_cut_plane_colormap_resolves_against_the_volume() {
        // Swapping to another autoscale colormap re-ranges against the field
        // (not the placeholder [0, 1]).
        let mut field = ramp_field();
        field.set_cut_plane_colormap(Colormap::autoscale(ColormapName::Viridis));
        let cm = field.cut_plane().colormap();
        assert_eq!(cm.lut, Colormap::new(ColormapName::Viridis, 0.0, 1.0).lut);
        assert_eq!((cm.vmin, cm.vmax), (0.0, 2.0));
    }

    #[test]
    fn value_at_samples_inside_and_rejects_outside_the_box() {
        let field = ramp_field();
        // Voxel-centre convention: world (·,·,1.5) is exactly z-index 1 → value 1.0
        // (the cut plane's default interpolation is trilinear).
        let v = field
            .value_at(Vec3::new(1.5, 1.5, 1.5))
            .expect("inside the box");
        assert!((v - 1.0).abs() < 1e-5, "sampled {v}");
        // World z = 2.0 is half-way between z-index 1 (=1) and 2 (=2) → 1.5.
        let mid = field.value_at(Vec3::new(1.5, 1.5, 2.0)).expect("inside");
        assert!((mid - 1.5).abs() < 1e-5, "sampled {mid}");
        // The voxel centre at z-index 2 reads exactly 2.0.
        let top = field.value_at(Vec3::new(1.5, 1.5, 2.5)).expect("inside");
        assert!((top - 2.0).abs() < 1e-5, "sampled {top}");
        // Outside the (0,0,0)..(3,3,3) box → None (no edge-clamp leak).
        assert!(field.value_at(Vec3::new(3.5, 1.0, 1.0)).is_none());
        assert!(field.value_at(Vec3::new(-0.1, 1.0, 1.0)).is_none());
        // Empty field → None.
        assert!(
            ScalarField3D::new()
                .value_at(Vec3::new(1.0, 1.0, 1.0))
                .is_none()
        );
    }

    #[test]
    fn pick_cut_plane_hidden_is_none_visible_hits_inside_box() {
        let mut field = ramp_field();
        // Default cut plane: normal (0,1,0) through the origin — through y = 0.
        // Move it to y = 1.5 (mid-volume) so a ray along -Y crosses it inside the box.
        field.cut_plane_mut().set_point(Vec3::new(0.0, 1.5, 0.0));

        // A segment piercing the plane at world (1.5, 1.5, 1.5).
        let seg = (Vec3::new(1.5, 3.0, 1.5), Vec3::new(1.5, 0.0, 1.5));

        // Hidden by default → no pick.
        assert!(field.pick_cut_plane(seg).is_none());

        field.cut_plane_mut().set_visible(true);
        let hit = field
            .pick_cut_plane(seg)
            .expect("visible plane is crossed inside the box");
        assert!((hit.y - 1.5).abs() < 1e-5, "hit on the plane: {hit:?}");
        // The sampled value there matches value_at: world z = 1.5 is z-index 1 → 1.0.
        let value = field.value_at(hit).expect("hit is inside the box");
        assert!((value - 1.0).abs() < 1e-5, "value {value}");
    }

    #[test]
    fn pick_cut_plane_outside_box_is_none() {
        let mut field = ramp_field();
        field.cut_plane_mut().set_visible(true);
        // Plane at y = 1.5, but the ray crosses it far outside the x/z box extent.
        field.cut_plane_mut().set_point(Vec3::new(0.0, 1.5, 0.0));
        let seg = (Vec3::new(9.0, 3.0, 9.0), Vec3::new(9.0, 0.0, 9.0));
        assert!(field.pick_cut_plane(seg).is_none());
    }

    #[test]
    fn field_transform_moves_bounds_value_and_cut_plane_pick_together() {
        // A translated field (silx DataItem3D setTranslation): bounds, the
        // scene-frame value sampler, and the cut-plane pick must all read the
        // same composed transform — one owner, no per-path drift.
        let mut field = ramp_field();
        field.transform_mut().set_translation(10.0, 0.0, 0.0);

        // Bounds follow the transform.
        let (lo, hi) = field.bounds().expect("has data");
        assert_eq!(lo, Vec3::new(10.0, 0.0, 0.0));
        assert_eq!(hi, Vec3::new(13.0, 3.0, 3.0));

        // value_at takes scene coordinates: the voxel-frame sample (1.5,1.5,1.5)
        // (= value 1.0) now lives at x + 10; the raw location reads None.
        let v = field
            .value_at(Vec3::new(11.5, 1.5, 1.5))
            .expect("inside the translated box");
        assert!((v - 1.0).abs() < 1e-5, "sampled {v}");
        assert!(field.value_at(Vec3::new(1.5, 1.5, 1.5)).is_none());

        // Cut plane at voxel-frame y = 1.5: a scene-frame segment over the
        // translated box hits it, and the hit comes back in scene coordinates.
        field.cut_plane_mut().set_visible(true);
        field.cut_plane_mut().set_point(Vec3::new(0.0, 1.5, 0.0));
        let seg = (Vec3::new(11.5, 3.0, 1.5), Vec3::new(11.5, 0.0, 1.5));
        let hit = field.pick_cut_plane(seg).expect("crosses inside the box");
        assert!(
            (hit.x - 11.5).abs() < 1e-4 && (hit.y - 1.5).abs() < 1e-4,
            "scene-frame hit: {hit:?}"
        );
        // Feeding the returned scene position back into value_at agrees.
        let value = field.value_at(hit).expect("hit inside the box");
        assert!((value - 1.0).abs() < 1e-5, "value {value}");

        // The same segment placed over the RAW (untransformed) box misses.
        let raw_seg = (Vec3::new(1.5, 3.0, 1.5), Vec3::new(1.5, 0.0, 1.5));
        assert!(field.pick_cut_plane(raw_seg).is_none());
    }

    #[test]
    fn set_data_rejects_length_mismatch() {
        let mut s = Scatter3D::new();
        assert!(!s.set_data(&[0.0, 1.0], &[0.0], &[0.0, 1.0], &[0.0, 1.0]));
        assert!(s.is_empty(), "rejected data must not be partially stored");
        assert!(s.set_data(&[0.0, 1.0], &[2.0, 3.0], &[4.0, 5.0], &[6.0, 7.0]));
        assert_eq!(s.len(), 2);
    }

    #[test]
    fn append_to_colours_each_point_through_the_colormap() {
        // A ramp colormap over [0, 4]: value 0 → LUT index 0, value 4 → index 255.
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 4.0);
        let s = Scatter3D::new()
            .with_colormap(cmap.clone())
            .with_marker(PointMarker::Square)
            .with_size(8.0)
            .with_data(
                &[0.0, 1.0, 2.0],
                &[0.0, 0.0, 0.0],
                &[0.0, 0.0, 0.0],
                &[0.0, 2.0, 4.0],
            );

        let mut g = Scene3dGeometry::new();
        s.append_to(&mut g);

        // One point per datum, each at its position, all square, all size 8.
        assert_eq!(g.points.len(), 3);
        assert_eq!(g.points[1].pos, [1.0, 0.0, 0.0]);
        for p in &g.points {
            assert_eq!(p.size, 8.0);
            assert_eq!(p.marker, PointMarker::Square.id());
        }

        // Colors match the colormap LUT lookup (premultiplied at upload).
        let expect = |v: f64| {
            let [r, gg, b, a] = cmap.color_at(v);
            egui::Rgba::from(Color32::from_rgba_unmultiplied(r, gg, b, a)).to_array()
        };
        assert_eq!(g.points[0].color, expect(0.0));
        assert_eq!(g.points[2].color, expect(4.0));
        // The endpoints differ (the value actually drives the color).
        assert_ne!(g.points[0].color, g.points[2].color);
    }

    #[test]
    fn autoscale_colormap_fits_value_range() {
        let mut s =
            Scatter3D::new().with_data(&[0.0, 1.0, 2.0], &[0.0; 3], &[0.0; 3], &[-5.0, 0.0, 10.0]);
        let (vmin, vmax) = s.autoscale_colormap(AutoscaleMode::MinMax);
        assert_eq!((vmin, vmax), (-5.0, 10.0));
        assert_eq!(s.colormap().vmin, -5.0);
        assert_eq!(s.colormap().vmax, 10.0);
    }

    #[test]
    fn bounds_brackets_the_points() {
        assert!(Scatter3D::new().bounds().is_none());
        let s = Scatter3D::new().with_data(
            &[-1.0, 2.0, 0.5],
            &[3.0, -2.0, 1.0],
            &[0.0, 4.0, -1.0],
            &[0.0; 3],
        );
        let (min, max) = s.bounds().expect("non-empty bounds");
        assert_eq!((min.x, min.y, min.z), (-1.0, -2.0, -1.0));
        assert_eq!((max.x, max.y, max.z), (2.0, 3.0, 4.0));
    }

    #[test]
    fn scatter2d_set_data_rejects_length_mismatch() {
        let mut s = Scatter2D::new();
        assert!(!s.set_data(&[0.0, 1.0], &[0.0], &[0.0, 1.0]));
        assert!(s.is_empty(), "rejected data must not be partially stored");
        assert!(s.set_data(&[0.0, 1.0], &[2.0, 3.0], &[4.0, 5.0]));
        assert_eq!(s.len(), 2);
    }

    #[test]
    fn scatter2d_points_mode_lies_on_z0_plane_or_lifts_to_value() {
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 4.0);
        // Flat (default): z = 0 for every point.
        let flat = Scatter2D::new()
            .with_colormap(cmap.clone())
            .with_marker(PointMarker::Square)
            .with_size(8.0)
            .with_data(&[0.0, 1.0, 2.0], &[0.0, 0.0, 0.0], &[0.0, 2.0, 4.0]);
        let mut g = Scene3dGeometry::new();
        flat.append_to(&mut g);
        assert_eq!(g.points.len(), 3);
        for p in &g.points {
            assert_eq!(p.pos[2], 0.0, "flat scatter sits on z=0");
            assert_eq!(p.size, 8.0);
            assert_eq!(p.marker, PointMarker::Square.id());
        }
        // Colour is driven by value (same CPU colormap lookup as Scatter3D).
        let expect = |v: f64| {
            let [r, gg, b, a] = cmap.color_at(v);
            egui::Rgba::from(Color32::from_rgba_unmultiplied(r, gg, b, a)).to_array()
        };
        assert_eq!(g.points[0].color, expect(0.0));
        assert_eq!(g.points[2].color, expect(4.0));
        assert_ne!(g.points[0].color, g.points[2].color);

        // Height-map mode: z = value.
        let hm = Scatter2D::new()
            .with_data(&[0.0, 1.0, 2.0], &[0.0, 0.0, 0.0], &[0.0, 2.0, 4.0])
            .with_height_map(true);
        let mut g2 = Scene3dGeometry::new();
        hm.append_to(&mut g2);
        assert_eq!(g2.points[0].pos[2], 0.0);
        assert_eq!(g2.points[1].pos[2], 2.0);
        assert_eq!(g2.points[2].pos[2], 4.0);
    }

    #[test]
    fn scatter2d_lines_mode_emits_unique_triangulation_edges() {
        // Unit square → 2 Delaunay triangles sharing a diagonal → 5 unique edges.
        let s = Scatter2D::new()
            .with_data(
                &[0.0, 1.0, 0.0, 1.0],
                &[0.0, 0.0, 1.0, 1.0],
                &[0.0, 1.0, 2.0, 3.0],
            )
            .with_visualization(Scatter2DVisualization::Lines);
        let mut g = Scene3dGeometry::new();
        s.append_to(&mut g);
        // 5 segments, two vertices each; all flat on z = 0.
        assert_eq!(g.lines.len(), 10);
        for v in &g.lines {
            assert_eq!(v.pos[2], 0.0);
        }
        // The first edge is (index 0, index 1); its endpoints carry their own
        // colormap colour, so the segment gradients (values 0 vs 1 differ).
        assert_ne!(g.lines[0].color, g.lines[1].color);
        // Nothing emitted to the point / mesh channels.
        assert!(g.points.is_empty());
        assert!(g.meshes.is_empty());
    }

    #[test]
    fn scatter2d_solid_mode_fills_triangles_coloured_by_value() {
        let s = Scatter2D::new()
            .with_data(
                &[0.0, 1.0, 0.0, 1.0],
                &[0.0, 0.0, 1.0, 1.0],
                &[0.0, 1.0, 2.0, 3.0],
            )
            .with_visualization(Scatter2DVisualization::Solid);
        let mut g = Scene3dGeometry::new();
        s.append_to(&mut g);
        // 2 triangles × 3 vertices.
        assert_eq!(g.meshes.len(), 6);
        for v in &g.meshes {
            assert_eq!(v.pos[2], 0.0, "flat solid sits on z=0");
            // Flat z=0 triangles → the ±Z plane normal (winding-agnostic check).
            assert!(
                (v.normal[2].abs() - 1.0).abs() < 1e-5,
                "expected plane normal, got {:?}",
                v.normal
            );
        }
        assert!(g.points.is_empty());
        assert!(g.lines.is_empty());
    }

    #[test]
    fn scatter2d_degenerate_input_draws_nothing_in_triangulated_modes() {
        // Collinear points → empty Delaunay → no edges / triangles (silx skips the
        // renderer when the tesselation fails).
        let collinear =
            Scatter2D::new().with_data(&[0.0, 1.0, 2.0], &[0.0, 1.0, 2.0], &[0.0, 1.0, 2.0]);
        let mut g = Scene3dGeometry::new();
        collinear
            .clone()
            .with_visualization(Scatter2DVisualization::Lines)
            .append_to(&mut g);
        assert!(g.lines.is_empty());
        let mut g2 = Scene3dGeometry::new();
        collinear
            .with_visualization(Scatter2DVisualization::Solid)
            .append_to(&mut g2);
        assert!(g2.meshes.is_empty());
    }

    #[test]
    fn scatter2d_bounds_flat_collapses_z_height_map_spans_value() {
        assert!(Scatter2D::new().bounds().is_none());
        // Flat: the z bracket collapses to [0, 0].
        let flat = Scatter2D::new().with_data(&[-1.0, 2.0], &[3.0, -2.0], &[5.0, 10.0]);
        let (min, max) = flat.bounds().expect("non-empty");
        assert_eq!((min.x, min.y, min.z), (-1.0, -2.0, 0.0));
        assert_eq!((max.x, max.y, max.z), (2.0, 3.0, 0.0));
        // Height map: z spans the value range.
        let (min, max) = flat.with_height_map(true).bounds().expect("non-empty");
        assert_eq!((min.z, max.z), (5.0, 10.0));
    }

    // A flat, camera-facing triangle in the z=0 plane (CCW seen from +z).
    fn flat_tri() -> [[f32; 3]; 3] {
        [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    }

    #[test]
    fn mesh_triangles_mode_emits_one_triangle_with_flat_normal() {
        let [a, b, c] = flat_tri();
        let mut m = Mesh3D::new();
        assert!(m.set_data(
            &[a, b, c],
            MeshColor::Uniform(Color32::from_rgb(255, 0, 0)),
            None,
            MeshDrawMode::Triangles,
            None,
        ));

        let mut g = Scene3dGeometry::new();
        m.append_to(&mut g);

        // Three mesh vertices (one triangle).
        assert_eq!(g.meshes.len(), 3);
        // No normals supplied → geometric flat normal (b−a)×(c−a) = +z, unit.
        for v in &g.meshes {
            assert_eq!(v.normal, [0.0, 0.0, 1.0]);
            assert_eq!(
                v.color,
                egui::Rgba::from(Color32::from_rgb(255, 0, 0)).to_array()
            );
        }
        assert_eq!(g.meshes[1].pos, b);
    }

    #[test]
    fn mesh_set_data_rejects_inconsistent_attributes() {
        let [a, b, c] = flat_tri();
        let mut m = Mesh3D::new();
        // Per-vertex colours shorter than the vertices.
        assert!(!m.set_data(
            &[a, b, c],
            MeshColor::PerVertex(vec![Color32::RED, Color32::GREEN]),
            None,
            MeshDrawMode::Triangles,
            None,
        ));
        // Normals not matching the vertex count.
        assert!(!m.set_data(
            &[a, b, c],
            MeshColor::Uniform(Color32::WHITE),
            Some(&[[0.0, 0.0, 1.0]]),
            MeshDrawMode::Triangles,
            None,
        ));
        // Index out of range.
        assert!(!m.set_data(
            &[a, b, c],
            MeshColor::Uniform(Color32::WHITE),
            None,
            MeshDrawMode::Triangles,
            Some(&[0, 1, 3]),
        ));
        assert!(m.is_empty(), "rejected data must not be partially stored");
        // A consistent per-vertex set is accepted.
        assert!(m.set_data(
            &[a, b, c],
            MeshColor::PerVertex(vec![Color32::RED, Color32::GREEN, Color32::BLUE]),
            Some(&[[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]),
            MeshDrawMode::Triangles,
            Some(&[0, 1, 2]),
        ));
        assert_eq!(m.len(), 3);
    }

    #[test]
    fn mesh_strip_and_fan_expand_to_triangle_lists() {
        // Four collinear-in-index vertices; strip → 2 tris, fan → 2 tris.
        let p = [
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
        ];

        let mut strip = Scene3dGeometry::new();
        Mesh3D::new()
            .with_data(
                &p,
                MeshColor::Uniform(Color32::WHITE),
                None,
                MeshDrawMode::TriangleStrip,
                None,
            )
            .append_to(&mut strip);
        // strip over 4 verts → (0,1,2),(1,2,3) → 2 triangles → 6 vertices.
        assert_eq!(strip.meshes.len(), 6);
        // Second triangle is vertices 1,2,3.
        assert_eq!(strip.meshes[3].pos, p[1]);
        assert_eq!(strip.meshes[4].pos, p[2]);
        assert_eq!(strip.meshes[5].pos, p[3]);

        let mut fan = Scene3dGeometry::new();
        Mesh3D::new()
            .with_data(
                &p,
                MeshColor::Uniform(Color32::WHITE),
                None,
                MeshDrawMode::Fan,
                None,
            )
            .append_to(&mut fan);
        // fan over 4 verts → (0,1,2),(0,2,3) → 2 triangles → 6 vertices.
        assert_eq!(fan.meshes.len(), 6);
        assert_eq!(fan.meshes[3].pos, p[0]); // shared apex
        assert_eq!(fan.meshes[4].pos, p[2]);
        assert_eq!(fan.meshes[5].pos, p[3]);
    }

    #[test]
    fn mesh_indices_unindex_before_expansion() {
        // Two stored vertices reused by indices to form one triangle.
        let p = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]];
        let mut g = Scene3dGeometry::new();
        Mesh3D::new()
            .with_data(
                &p,
                MeshColor::Uniform(Color32::WHITE),
                None,
                MeshDrawMode::Triangles,
                Some(&[0, 1, 0]),
            )
            .append_to(&mut g);
        assert_eq!(g.meshes.len(), 3);
        assert_eq!(g.meshes[0].pos, p[0]);
        assert_eq!(g.meshes[1].pos, p[1]);
        assert_eq!(g.meshes[2].pos, p[0]);
    }

    #[test]
    fn colormap_mesh_colours_vertices_through_the_colormap() {
        let [a, b, c] = flat_tri();
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 2.0);
        let mut m = ColormapMesh3D::new().with_colormap(cmap.clone());
        assert!(m.set_data(
            &[a, b, c],
            &[0.0, 1.0, 2.0],
            None,
            MeshDrawMode::Triangles,
            None
        ));

        let mut g = Scene3dGeometry::new();
        m.append_to(&mut g);
        assert_eq!(g.meshes.len(), 3);

        let expect = |v: f64| {
            let [r, gg, bb, al] = cmap.color_at(v);
            egui::Rgba::from(Color32::from_rgba_unmultiplied(r, gg, bb, al)).to_array()
        };
        assert_eq!(g.meshes[0].color, expect(0.0));
        assert_eq!(g.meshes[2].color, expect(2.0));
        assert_ne!(g.meshes[0].color, g.meshes[2].color);
        // No normals → flat +z normal for the camera-facing triangle.
        assert_eq!(g.meshes[0].normal, [0.0, 0.0, 1.0]);
    }

    #[test]
    fn colormap_mesh_rejects_value_length_mismatch_and_autoscales() {
        let [a, b, c] = flat_tri();
        let mut m = ColormapMesh3D::new();
        assert!(!m.set_data(&[a, b, c], &[0.0, 1.0], None, MeshDrawMode::Triangles, None));
        assert!(m.is_empty());
        assert!(m.set_data(
            &[a, b, c],
            &[-3.0, 0.0, 7.0],
            None,
            MeshDrawMode::Triangles,
            None
        ));
        let (vmin, vmax) = m.autoscale_colormap(AutoscaleMode::MinMax);
        assert_eq!((vmin, vmax), (-3.0, 7.0));
    }

    fn bounds_close(got: (Vec3, Vec3), min: [f32; 3], max: [f32; 3]) {
        let eps = 1e-4;
        let (g_min, g_max) = got;
        for (a, b) in [(g_min.x, min[0]), (g_min.y, min[1]), (g_min.z, min[2])] {
            assert!((a - b).abs() < eps, "min {a} vs {b}");
        }
        for (a, b) in [(g_max.x, max[0]), (g_max.y, max[1]), (g_max.z, max[2])] {
            assert!((a - b).abs() < eps, "max {a} vs {b}");
        }
    }

    #[test]
    fn box3d_default_is_a_centred_unit_cube() {
        let b = Box3D::new();
        let mut g = Scene3dGeometry::new();
        b.append_to(&mut g);
        // 4 side segments × 12 vertices = 48 vertices (16 triangles).
        assert_eq!(g.meshes.len(), 48);
        // A unit box centred at the origin spans ±0.5 on each axis.
        bounds_close(
            b.bounds().expect("box bounds"),
            [-0.5, -0.5, -0.5],
            [0.5, 0.5, 0.5],
        );
        assert_eq!(b.size(), [1.0, 1.0, 1.0]);
    }

    #[test]
    fn box3d_rejects_bad_colour_count_and_tiles_per_position() {
        let mut b = Box3D::new();
        // Two positions but three colours → invalid.
        assert!(!b.set_data(
            [1.0, 1.0, 1.0],
            &[Color32::RED, Color32::GREEN, Color32::BLUE],
            &[[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]],
            (0.0, [0.0, 0.0, 0.0]),
        ));
        // One colour shared across two boxes → valid, doubles the vertex count.
        assert!(b.set_data(
            [1.0, 1.0, 1.0],
            &[Color32::RED],
            &[[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]],
            (0.0, [0.0, 0.0, 0.0]),
        ));
        let mut g = Scene3dGeometry::new();
        b.append_to(&mut g);
        assert_eq!(g.meshes.len(), 96);
        // The two boxes span x from −0.5 (first box) to 3.5 (second centre +0.5).
        bounds_close(
            b.bounds().expect("bounds"),
            [-0.5, -0.5, -0.5],
            [3.5, 0.5, 0.5],
        );
    }

    #[test]
    fn cylinder3d_default_has_radial_side_normals() {
        let c = Cylinder3D::new();
        let mut g = Scene3dGeometry::new();
        c.append_to(&mut g);
        // 20 faces × 12 vertices = 240.
        assert_eq!(g.meshes.len(), 240);
        bounds_close(
            c.bounds().expect("cyl bounds"),
            [-1.0, -1.0, -0.5],
            [1.0, 1.0, 0.5],
        );
        // Smooth sides: the first side vertex (wedge index 3, segment 0) gets the
        // radial normal c2−c1 = (radius, 0, 0) = (1, 0, 0), not a faceted normal.
        assert_eq!(g.meshes[3].normal, [1.0, 0.0, 0.0]);
    }

    #[test]
    fn hexagon3d_default_spans_its_hexagonal_footprint() {
        let h = Hexagon3D::new();
        let mut g = Scene3dGeometry::new();
        h.append_to(&mut g);
        // 6 faces × 12 vertices = 72.
        assert_eq!(g.meshes.len(), 72);
        // Vertices at 0°,60°,…,300°: x ∈ [−1, 1], y ∈ [−sin60°, sin60°].
        let s60 = (std::f32::consts::TAU / 6.0).sin();
        bounds_close(
            h.bounds().expect("hex bounds"),
            [-1.0, -s60, -0.5],
            [1.0, s60, 0.5],
        );
        assert_eq!((h.radius(), h.height()), (1.0, 1.0));
    }

    #[test]
    fn cylinder3d_face_count_controls_resolution() {
        let mut c = Cylinder3D::new();
        assert!(c.set_data(
            2.0,
            4.0,
            &[Color32::WHITE],
            8,
            &[[0.0, 0.0, 0.0]],
            (0.0, [0.0, 0.0, 0.0]),
        ));
        let mut g = Scene3dGeometry::new();
        c.append_to(&mut g);
        assert_eq!(g.meshes.len(), 8 * 12);
        bounds_close(
            c.bounds().expect("bounds"),
            [-2.0, -2.0, -2.0],
            [2.0, 2.0, 2.0],
        );
    }

    #[test]
    fn image_data3d_builds_a_colormapped_layer() {
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 3.0);
        let mut img = ImageData3D::new().with_colormap(cmap.clone());
        // 2×2 image, row-major.
        assert!(img.set_data(&[0.0, 1.0, 2.0, 3.0], 2, 2));
        assert_eq!(img.dimensions(), (2, 2));

        let mut g = Scene3dGeometry::new();
        img.append_to(&mut g);
        assert_eq!(g.images.len(), 1);
        let layer = &g.images[0];
        assert_eq!((layer.width, layer.height), (2, 2));
        assert_eq!(layer.pixels.len(), 2 * 2 * 4);

        // Each pixel is the colormap lookup, premultiplied-linear.
        let expect = |v: f64| {
            let [r, gg, b, a] = cmap.color_at(v);
            premul_linear_rgba8(Color32::from_rgba_unmultiplied(r, gg, b, a))
        };
        assert_eq!(&layer.pixels[0..4], &expect(0.0)); // (row0,col0)
        assert_eq!(&layer.pixels[12..16], &expect(3.0)); // (row1,col1)
        assert_ne!(&layer.pixels[0..4], &layer.pixels[12..16]);
    }

    #[test]
    fn image_data3d_rejects_size_mismatch_and_bounds_follow_origin_scale() {
        let mut img = ImageData3D::new();
        assert!(!img.set_data(&[0.0, 1.0, 2.0], 2, 2));
        assert!(img.is_empty());
        assert!(img.bounds().is_none());

        let img = ImageData3D::new()
            .with_data(&[0.0; 6], 3, 2)
            .with_origin([10.0, 20.0, -1.0])
            .with_scale([2.0, 5.0]);
        // Quad spans origin → origin + (w·sx, h·sy) at z = origin.z.
        let (min, max) = img.bounds().expect("bounds");
        assert_eq!((min.x, min.y, min.z), (10.0, 20.0, -1.0));
        assert_eq!(
            (max.x, max.y, max.z),
            (10.0 + 3.0 * 2.0, 20.0 + 2.0 * 5.0, -1.0)
        );
    }

    #[test]
    fn image_rgba3d_passes_pixels_through_premultiplied() {
        let cols = [Color32::RED, Color32::GREEN, Color32::BLUE, Color32::WHITE];
        let mut img = ImageRgba3D::new();
        assert!(img.set_data(&cols, 2, 2));

        let mut g = Scene3dGeometry::new();
        img.append_to(&mut g);
        assert_eq!(g.images.len(), 1);
        let layer = &g.images[0];
        assert_eq!((layer.width, layer.height), (2, 2));
        for (i, &c) in cols.iter().enumerate() {
            assert_eq!(&layer.pixels[i * 4..i * 4 + 4], &premul_linear_rgba8(c));
        }
    }

    #[test]
    fn image_rgba3d_rejects_size_mismatch() {
        let mut img = ImageRgba3D::new();
        assert!(!img.set_data(&[Color32::RED, Color32::GREEN], 2, 2));
        assert!(img.is_empty());
        assert!(img.set_data(&[Color32::RED; 4], 2, 2));
        assert_eq!(img.dimensions(), (2, 2));
    }

    #[test]
    fn height_map_data_emits_one_square_point_per_pixel() {
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 3.0);
        let heights = [0.0_f32, 1.0, 2.0, 3.0]; // 2×2 field
        let mut hm = HeightMapData::new().with_colormap(cmap.clone());
        assert!(hm.set_data(&heights, 2, 2));
        assert!(hm.set_colormapped_data(&[0.0, 1.0, 2.0, 3.0], 2, 2));

        let mut g = Scene3dGeometry::new();
        hm.append_to(&mut g);
        assert_eq!(g.points.len(), 4);
        for p in &g.points {
            assert_eq!(p.size, 1.0);
            assert_eq!(p.marker, PointMarker::Square.id());
        }
        // Point (row=1, col=1) — index row*width+col = 3 — sits at world (1, 1, 3).
        let p11 = &g.points[3];
        assert_eq!(p11.pos, [1.0, 1.0, 3.0]);
        let expect = |v: f64| {
            let [r, gg, b, a] = cmap.color_at(v);
            egui::Rgba::from(Color32::from_rgba_unmultiplied(r, gg, b, a)).to_array()
        };
        assert_eq!(g.points[0].color, expect(0.0));
        assert_eq!(p11.color, expect(3.0));
    }

    #[test]
    fn height_map_data_empty_without_both_fields_and_bounds_from_heights() {
        let mut hm = HeightMapData::new();
        assert!(hm.set_data(&[0.0, 5.0, 2.0, 1.0], 2, 2));
        // Height field set, no colour data → draws nothing, but has spatial bounds.
        assert!(hm.is_empty());
        let mut g = Scene3dGeometry::new();
        hm.append_to(&mut g);
        assert!(g.points.is_empty());
        let (min, max) = hm.bounds().expect("bounds from heights");
        assert_eq!((min.x, min.y, min.z), (0.0, 0.0, 0.0)); // z min = 0.0
        assert_eq!((max.x, max.y, max.z), (1.0, 1.0, 5.0)); // grid 0..1, z max = 5.0
    }

    #[test]
    fn height_map_data_resamples_columns_by_width() {
        // 4×2 height field, 2×2 colour data: columns 0,1 → colour col 0; 2,3 → col 1.
        // This distinguishes width-based resample (correct) from silx's
        // height-based column indexing.
        let cmap = Colormap::new(ColormapName::Viridis, 0.0, 1.0);
        let heights = [0.0_f32; 8]; // 4 wide × 2 tall
        // colour data 2×2: col 0 = value 0.0, col 1 = value 1.0 (both rows).
        let values = [0.0, 1.0, 0.0, 1.0];
        let hm = HeightMapData::new()
            .with_colormap(cmap.clone())
            .with_data(&heights, 4, 2)
            .with_colormapped_data(&values, 2, 2);

        let mut g = Scene3dGeometry::new();
        hm.append_to(&mut g);
        assert_eq!(g.points.len(), 8);

        let c0 = egui::Rgba::from({
            let [r, gg, b, a] = cmap.color_at(0.0);
            Color32::from_rgba_unmultiplied(r, gg, b, a)
        })
        .to_array();
        // Row 0: cols 0,1 sample value-col 0 (0.0); cols 2,3 sample value-col 1.
        assert_eq!(g.points[0].color, c0); // col 0
        assert_eq!(g.points[1].color, c0); // col 1 → still value-col 0 (width-based)
        assert_ne!(g.points[2].color, c0); // col 2 → value-col 1
    }

    #[test]
    fn height_map_rgba_colours_points_directly() {
        let heights = [0.0_f32, 1.0, 2.0, 3.0];
        let cols = [Color32::RED, Color32::GREEN, Color32::BLUE, Color32::WHITE];
        let mut hm = HeightMapRGBA::new();
        assert!(hm.set_data(&heights, 2, 2));
        assert!(hm.set_color_data(&cols, 2, 2));

        let mut g = Scene3dGeometry::new();
        hm.append_to(&mut g);
        assert_eq!(g.points.len(), 4);
        for (i, &c) in cols.iter().enumerate() {
            assert_eq!(g.points[i].color, egui::Rgba::from(c).to_array());
            assert_eq!(g.points[i].marker, PointMarker::Square.id());
        }
        assert_eq!(g.points[3].pos, [1.0, 1.0, 3.0]);
    }

    // --- ScalarField3D / Isosurface (P2.1b) ---

    /// A central high block in a 5×5×5 field at level 0.5 (rest 0).
    fn blob_field() -> (Vec<f32>, usize, usize, usize) {
        let (d, h, w) = (5usize, 5usize, 5usize);
        let mut data = vec![0.0f32; d * h * w];
        for z in 1..4 {
            for y in 1..4 {
                for x in 1..4 {
                    data[(z * h + y) * w + x] = 1.0;
                }
            }
        }
        (data, d, h, w)
    }

    #[test]
    fn scalar_field_rejects_bad_shape() {
        let mut sf = ScalarField3D::new();
        // Wrong length.
        assert!(!sf.set_data(&[0.0; 7], 2, 2, 2));
        // A dimension < 2 (silx asserts min(shape) >= 2).
        assert!(!sf.set_data(&[0.0; 2], 1, 2, 1));
        assert!(sf.is_empty());
        // Valid.
        assert!(sf.set_data(&[0.0; 8], 2, 2, 2));
        assert_eq!(sf.dimensions(), (2, 2, 2));
    }

    #[test]
    fn scalar_field_data_range_and_bounds() {
        let (data, d, h, w) = blob_field();
        let sf = ScalarField3D::new().with_data(&data, d, h, w);
        let (min, min_pos, max) = sf.data_range().expect("range");
        assert_eq!(min, 0.0);
        assert_eq!(max, 1.0);
        assert_eq!(min_pos, 1.0, "smallest positive sample is 1.0");
        // Volume box (0,0,0)..(width,height,depth).
        let (lo, hi) = sf.bounds().expect("bounds");
        assert_eq!(lo.to_array(), [0.0, 0.0, 0.0]);
        assert_eq!(hi.to_array(), [5.0, 5.0, 5.0]);
    }

    #[test]
    fn data_range_min_positive_nan_when_no_positive() {
        let sf = ScalarField3D::new().with_data(&[-1.0; 8], 2, 2, 2);
        let (min, min_pos, max) = sf.data_range().unwrap();
        assert_eq!(min, -1.0);
        assert_eq!(max, -1.0);
        assert!(min_pos.is_nan(), "no positive sample → NaN min positive");
    }

    #[test]
    fn add_remove_clear_isosurfaces() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        let i0 = sf.add_isosurface(0.5, Color32::RED);
        let i1 = sf.add_isosurface(0.25, DEFAULT_ISOSURFACE_COLOR);
        assert_eq!((i0, i1), (0, 1));
        assert_eq!(sf.isosurfaces().len(), 2);
        assert_eq!(sf.isosurfaces()[0].level(), 0.5);
        assert_eq!(sf.isosurfaces()[1].color(), DEFAULT_ISOSURFACE_COLOR);

        sf.isosurface_mut(0).unwrap().set_level(0.75);
        assert_eq!(sf.isosurfaces()[0].level(), 0.75);

        assert!(sf.remove_isosurface(0));
        assert!(!sf.remove_isosurface(5));
        assert_eq!(sf.isosurfaces().len(), 1);
        sf.clear_isosurfaces();
        assert!(sf.isosurfaces().is_empty());
    }

    #[test]
    fn auto_level_resolves_on_data_and_on_add() {
        let (data, d, h, w) = blob_field();
        // mean = 27/125 = 0.216; std = sqrt(mean*(1-mean)) for a 0/1 field.
        let expect = mean_plus_std(&data);
        assert!(expect.is_finite() && expect > 0.0);

        // Auto added before data → NaN until data is set, then resolved.
        let mut sf = ScalarField3D::new();
        sf.add_auto_isosurface(mean_plus_std, DEFAULT_ISOSURFACE_COLOR);
        assert!(sf.isosurfaces()[0].level().is_nan());
        assert!(sf.set_data(&data, d, h, w));
        assert!((sf.isosurfaces()[0].level() - expect).abs() < 1e-6);

        // Auto added after data → resolved immediately.
        let mut sf2 = ScalarField3D::new().with_data(&data, d, h, w);
        sf2.add_auto_isosurface(mean_plus_std, DEFAULT_ISOSURFACE_COLOR);
        assert!((sf2.isosurfaces()[0].level() - expect).abs() < 1e-6);
        assert!(sf2.isosurfaces()[0].is_auto_level());
    }

    #[test]
    fn mean_plus_std_ignores_non_finite_and_empty() {
        assert!(mean_plus_std(&[]).is_nan());
        assert!(mean_plus_std(&[f32::NAN, f32::INFINITY]).is_nan());
        // Constant field: std 0 → level == the constant.
        assert!((mean_plus_std(&[2.0, 2.0, 2.0]) - 2.0).abs() < 1e-6);
    }

    #[test]
    fn isosurface_emits_swapped_offset_triangles() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        sf.add_isosurface(0.5, DEFAULT_ISOSURFACE_COLOR);

        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);

        // The closed surface of a 3×3×3 block has triangles (3 mesh vertices each).
        assert!(!g.meshes.is_empty(), "isosurface produced triangles");
        assert_eq!(g.meshes.len() % 3, 0, "triangles");

        let gold = egui::Rgba::from(DEFAULT_ISOSURFACE_COLOR).to_array();
        // All vertices: gold colour, inside the volume box, unit normals.
        for v in &g.meshes {
            assert_eq!(v.color, gold);
            for k in 0..3 {
                assert!(
                    v.pos[k] >= 0.0 && v.pos[k] <= 5.0,
                    "inside box: {:?}",
                    v.pos
                );
            }
            let n = v.normal;
            let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
            assert!((len - 1.0).abs() < 1e-4, "unit normal, got {len}");
        }
        // The block spans index [1,3]; crossings sit at 0.5 and 3.5 → world
        // [1.0, 4.0] after +0.5, so every coordinate is within [1.0, 4.0].
        let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
        for v in &g.meshes {
            for k in 0..3 {
                lo = lo.min(v.pos[k]);
                hi = hi.max(v.pos[k]);
            }
        }
        assert!(
            lo >= 1.0 - 1e-4 && hi <= 4.0 + 1e-4,
            "surface in [1,4]: {lo}..{hi}"
        );
    }

    #[test]
    fn hidden_isosurface_emits_no_geometry_but_keeps_level_and_colour() {
        // R3-8: silx Item3D.setVisible(False) suppresses a surface's geometry
        // while keeping its level/colour — the CutPlane visibility contract now
        // extended to isosurfaces.
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        let idx = sf.add_isosurface(0.5, DEFAULT_ISOSURFACE_COLOR);

        let mut visible = Scene3dGeometry::new();
        sf.append_to(&mut visible);
        assert!(
            !visible.meshes.is_empty(),
            "visible surface emits triangles"
        );

        sf.isosurface_mut(idx).unwrap().set_visible(false);
        assert!(!sf.isosurfaces()[idx].is_visible());
        // Level and colour are retained across the hide.
        assert_eq!(sf.isosurfaces()[idx].level(), 0.5);
        assert_eq!(sf.isosurfaces()[idx].color(), DEFAULT_ISOSURFACE_COLOR);

        let mut hidden = Scene3dGeometry::new();
        sf.append_to(&mut hidden);
        assert!(hidden.meshes.is_empty(), "hidden surface emits no geometry");
    }

    #[test]
    fn non_finite_level_emits_nothing() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        sf.add_isosurface(f32::NAN, DEFAULT_ISOSURFACE_COLOR);
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        assert!(g.meshes.is_empty(), "NaN level → no triangles");
    }

    #[test]
    fn cut_plane_hidden_by_default_emits_nothing() {
        let (data, d, h, w) = blob_field();
        let sf = ScalarField3D::new().with_data(&data, d, h, w);
        assert!(!sf.cut_plane().is_visible(), "cut plane hidden by default");
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        assert!(g.textured_meshes.is_empty(), "hidden cut plane → no mesh");
    }

    #[test]
    fn cut_plane_config_setters() {
        let mut sf = ScalarField3D::new();
        let cp = sf.cut_plane_mut();
        cp.set_visible(true);
        cp.set_point(Vec3::new(1.0, 2.0, 3.0));
        cp.set_normal(Vec3::new(0.0, 0.0, 2.0)); // normalised to (0,0,1)
        cp.set_interpolation(ImageInterpolation::Nearest);
        cp.set_resolution(0); // clamps to ≥1
        assert!(sf.cut_plane().is_visible());
        assert_eq!(sf.cut_plane().plane().point().to_array(), [1.0, 2.0, 3.0]);
        assert_eq!(sf.cut_plane().plane().normal().to_array(), [0.0, 0.0, 1.0]);
        assert_eq!(sf.cut_plane().interpolation(), ImageInterpolation::Nearest);
        assert_eq!(sf.cut_plane().resolution(), 1);
    }

    #[test]
    fn plane_basis_is_orthonormal() {
        for n in [
            Vec3::new(0.0, 0.0, 1.0),
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(1.0, 0.0, 0.0),
            Vec3::new(1.0, 2.0, 3.0).normalized(),
        ] {
            let (e1, e2) = plane_basis(n);
            assert!((e1.length() - 1.0).abs() < 1e-5, "e1 unit");
            assert!((e2.length() - 1.0).abs() < 1e-5, "e2 unit");
            assert!(e1.dot(n).abs() < 1e-5, "e1 ⟂ n");
            assert!(e2.dot(n).abs() < 1e-5, "e2 ⟂ n");
            assert!(e1.dot(e2).abs() < 1e-5, "e1 ⟂ e2");
        }
    }

    #[test]
    fn sample_field_value_nearest_and_linear() {
        // 2×2×2 field with distinct values: data[(z*2+y)*2+x] = index.
        let data: Vec<f32> = (0..8).map(|i| i as f32).collect();
        let (d, h, w) = (2usize, 2usize, 2usize);
        // Sample exactly at voxel centre (1,0,1) → world (1.5, 0.5, 1.5).
        let v = sample_field_value(
            &data,
            d,
            h,
            w,
            Vec3::new(1.5, 0.5, 1.5),
            ImageInterpolation::Nearest,
        );
        assert_eq!(v, data[h * w + 1]); // (z=1, y=0, x=1) → (1*h+0)*w+1
        // Midway between the two x-voxels at y=0, z=0: world x=1.0 → fx=0.5.
        let v = sample_field_value(
            &data,
            d,
            h,
            w,
            Vec3::new(1.0, 0.5, 0.5),
            ImageInterpolation::Linear,
        );
        assert!((v - 0.5).abs() < 1e-5, "midpoint trilinear, got {v}");
        // Clamp-to-edge: far outside the box → the far-corner voxel (1,1,1).
        let v = sample_field_value(
            &data,
            d,
            h,
            w,
            Vec3::new(99.0, 99.0, 99.0),
            ImageInterpolation::Nearest,
        );
        assert_eq!(v, data[7], "clamps to far-corner voxel");
    }

    #[test]
    fn visible_axis_cut_plane_emits_textured_mesh() {
        let (data, d, h, w) = blob_field(); // 5×5×5, central 3×3×3 block = 1.0
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        sf.autoscale_cut_plane_colormap(AutoscaleMode::MinMax);
        {
            let cp = sf.cut_plane_mut();
            cp.set_normal(Vec3::new(0.0, 0.0, 1.0));
            cp.set_point(Vec3::new(2.5, 2.5, 2.5));
            cp.set_resolution(16);
            cp.set_visible(true);
        }
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        assert_eq!(g.textured_meshes.len(), 1, "one cut-plane mesh");
        let m = &g.textured_meshes[0];
        // The z=2.5 plane ∩ the box is a square (4 contour verts) → fan = 2
        // triangles = 6 vertices.
        assert_eq!(m.vertices.len(), 6);
        assert_eq!(m.uvs.len(), 6);
        assert_eq!((m.width, m.height), (16, 16));
        assert_eq!(m.pixels.len(), 16 * 16 * 4, "res×res premultiplied RGBA8");
        // Every vertex lies on z=2.5 and the contour spans the full box face.
        let (mut lo, mut hi) = ([f32::INFINITY; 3], [f32::NEG_INFINITY; 3]);
        for v in &m.vertices {
            assert!((v[2] - 2.5).abs() < 1e-4, "on the z=2.5 plane");
            for k in 0..3 {
                lo[k] = lo[k].min(v[k]);
                hi[k] = hi[k].max(v[k]);
            }
        }
        assert_eq!([lo[0], lo[1]], [0.0, 0.0]);
        assert_eq!([hi[0], hi[1]], [5.0, 5.0]);
    }

    #[test]
    fn cut_plane_discards_below_min_texels_when_display_off() {
        // R2-51: silx CutPlane.setDisplayValuesBelowMin(False) runs `if (value ==
        // 0.) { discard; }` on the normalized value, punching texels whose raw
        // value clamps to vmin (or below) out of the slice.
        let (data, d, h, w) = blob_field(); // background 0.0, central block 1.0
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        {
            let cp = sf.cut_plane_mut();
            // vmin 0.5 → the 0.0 background (and the block/background trilinear
            // fringe below 0.5) normalizes to 0.
            cp.set_colormap(Colormap::new(ColormapName::Gray, 0.5, 1.0));
            cp.set_normal(Vec3::new(0.0, 0.0, 1.0));
            cp.set_point(Vec3::new(2.5, 2.5, 2.5)); // z=2.5 slices the block
            cp.set_resolution(16);
            cp.set_visible(true);
        }
        let transparent = |sf: &ScalarField3D| -> usize {
            let mut g = Scene3dGeometry::new();
            sf.append_to(&mut g);
            g.textured_meshes[0]
                .pixels
                .chunks_exact(4)
                .filter(|c| c[3] == 0)
                .count()
        };
        // Default (display on): below-min texels are drawn opaque, none discarded.
        assert_eq!(transparent(&sf), 0, "default draws below-min texels opaque");
        sf.cut_plane_mut().set_display_values_below_min(false);
        let holes = transparent(&sf);
        assert!(holes > 0, "below-min discard punches transparent texels");
        // The above-vmin block core stays opaque (not everything discarded).
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        let opaque = g.textured_meshes[0]
            .pixels
            .chunks_exact(4)
            .filter(|c| c[3] == 255)
            .count();
        assert!(opaque > 0, "above-min block texels stay opaque");
    }

    #[test]
    fn cut_plane_display_values_below_min_defaults_true() {
        // silx CutPlane default (volume.py:134-150).
        assert!(CutPlane::new().display_values_below_min());
    }

    #[test]
    fn autoscale_cut_plane_colormap_fits_data_range() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        let (vmin, vmax) = sf.autoscale_cut_plane_colormap(AutoscaleMode::MinMax);
        assert_eq!((vmin, vmax), (0.0, 1.0));
        assert_eq!(sf.cut_plane().colormap().vmin, 0.0);
        assert_eq!(sf.cut_plane().colormap().vmax, 1.0);
    }

    #[test]
    fn cut_plane_not_slicing_the_volume_emits_nothing() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        {
            let cp = sf.cut_plane_mut();
            cp.set_normal(Vec3::new(0.0, 0.0, 1.0));
            cp.set_point(Vec3::new(2.5, 2.5, 100.0)); // z=100, outside the box
            cp.set_visible(true);
        }
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        assert!(
            g.textured_meshes.is_empty(),
            "plane misses the volume → no mesh"
        );
        assert!(g.lines.is_empty(), "plane misses the volume → no stroke");
    }

    #[test]
    fn visible_cut_plane_emits_white_contour_stroke() {
        // silx PlaneInGroup: the visible plane draws its plane/box intersection
        // as a closed white line loop (primitives.py:1082-1126).
        let (data, d, h, w) = blob_field(); // 5×5×5
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        {
            let cp = sf.cut_plane_mut();
            cp.set_normal(Vec3::new(0.0, 0.0, 1.0));
            cp.set_point(Vec3::new(2.5, 2.5, 2.5));
            cp.set_visible(true);
        }
        assert!(sf.cut_plane().is_stroke_visible(), "stroke on by default");
        assert_eq!(sf.cut_plane().stroke_color(), Color32::WHITE);

        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        // z=2.5 ∩ box = a square → 4 contour vertices → 4 loop segments.
        assert_eq!(g.lines.len(), 8, "4 closed-loop segments, 2 verts each");
        let white = egui::Rgba::from(Color32::WHITE).to_array();
        for v in &g.lines {
            assert_eq!(v.color, white, "stroke is white by default");
            assert!((v.pos[2] - 2.5).abs() < 1e-4, "stroke lies on the plane");
        }
        // Closed loop: every endpoint appears exactly twice.
        let mut counts: Vec<([i32; 3], usize)> = Vec::new();
        for v in &g.lines {
            let key = [0, 1, 2].map(|k| (v.pos[k] * 1024.0).round() as i32);
            match counts.iter_mut().find(|(p, _)| *p == key) {
                Some((_, n)) => *n += 1,
                None => counts.push((key, 1)),
            }
        }
        assert_eq!(counts.len(), 4, "four distinct corners");
        assert!(
            counts.iter().all(|&(_, n)| n == 2),
            "each corner shared by two segments (closed loop): {counts:?}"
        );
    }

    #[test]
    fn cut_plane_stroke_color_and_visibility_api() {
        let (data, d, h, w) = blob_field();
        let mut sf = ScalarField3D::new().with_data(&data, d, h, w);
        {
            let cp = sf.cut_plane_mut();
            cp.set_normal(Vec3::new(0.0, 0.0, 1.0));
            cp.set_point(Vec3::new(2.5, 2.5, 2.5));
            cp.set_visible(true);
            cp.set_stroke_color(Color32::RED); // ScalarFieldView.setStrokeColor
        }
        let mut g = Scene3dGeometry::new();
        sf.append_to(&mut g);
        let red = egui::Rgba::from(Color32::RED).to_array();
        assert!(!g.lines.is_empty());
        assert!(g.lines.iter().all(|v| v.color == red));

        // strokeVisible = False suppresses the contour but keeps the slice.
        sf.cut_plane_mut().set_stroke_visible(false);
        let mut g2 = Scene3dGeometry::new();
        sf.append_to(&mut g2);
        assert!(g2.lines.is_empty(), "stroke hidden → no loop");
        assert_eq!(g2.textured_meshes.len(), 1, "slice still drawn");

        // Hidden plane: neither slice nor stroke.
        sf.cut_plane_mut().set_stroke_visible(true);
        sf.cut_plane_mut().set_visible(false);
        let mut g3 = Scene3dGeometry::new();
        sf.append_to(&mut g3);
        assert!(g3.lines.is_empty() && g3.textured_meshes.is_empty());
    }

    /// A 2×2×2 complex field with one distinctive sample (`3 + 4i`) so each
    /// projection is checkable; the rest are zero.
    fn complex_field() -> (Vec<f32>, Vec<f32>, usize, usize, usize) {
        let (d, h, w) = (2usize, 2usize, 2usize);
        let mut re = vec![0.0f32; d * h * w];
        let mut im = vec![0.0f32; d * h * w];
        re[0] = 3.0;
        im[0] = 4.0;
        (re, im, d, h, w)
    }

    #[test]
    fn complex_mode_projections() {
        // 3 + 4i: |z| = 5, |z|² = 25, phase = atan2(4,3), re = 3, im = 4.
        assert_eq!(ComplexMode::Absolute.to_scalar(3.0, 4.0), 5.0);
        assert_eq!(ComplexMode::SquareAmplitude.to_scalar(3.0, 4.0), 25.0);
        assert_eq!(ComplexMode::Real.to_scalar(3.0, 4.0), 3.0);
        assert_eq!(ComplexMode::Imaginary.to_scalar(3.0, 4.0), 4.0);
        assert!((ComplexMode::Phase.to_scalar(3.0, 4.0) - 4.0f32.atan2(3.0)).abs() < 1e-6);
        // The two hue-display modes have no scalar (project to 0.0).
        assert_eq!(ComplexMode::AmplitudePhase.to_scalar(3.0, 4.0), 0.0);
    }

    #[test]
    fn complex_field_rejects_bad_shape() {
        let mut cf = ComplexField3D::new();
        // re/im length disagree.
        assert!(!cf.set_data(&[0.0; 8], &[0.0; 7], 2, 2, 2));
        // Wrong length for the dims.
        assert!(!cf.set_data(&[0.0; 7], &[0.0; 7], 2, 2, 2));
        // A dimension < 2.
        assert!(!cf.set_data(&[0.0; 2], &[0.0; 2], 1, 2, 1));
        assert!(cf.is_empty());
        // Valid.
        assert!(cf.set_data(&[0.0; 8], &[0.0; 8], 2, 2, 2));
        assert_eq!(cf.dimensions(), (2, 2, 2));
    }

    #[test]
    fn complex_field_projects_into_inner_field_per_mode() {
        let (re, im, d, h, w) = complex_field();
        let cf = ComplexField3D::new().with_data(&re, &im, d, h, w);
        // Default amplitude: sample 0 → 5, the rest 0 → range (0, 5, 5).
        assert_eq!(cf.complex_mode(), ComplexMode::Absolute);
        assert_eq!(cf.field().data()[0], 5.0);
        assert_eq!(
            cf.data_range_for(ComplexMode::Absolute),
            Some((0.0, 5.0, 5.0))
        );
        assert_eq!(
            cf.data_range_for(ComplexMode::SquareAmplitude),
            Some((0.0, 25.0, 25.0))
        );
        // projected_data is independent of the current mode.
        assert_eq!(cf.projected_data(ComplexMode::Real).unwrap()[0], 3.0);
        assert_eq!(cf.projected_data(ComplexMode::Imaginary).unwrap()[0], 4.0);
    }

    #[test]
    fn set_complex_mode_reprojects_and_clears_isosurfaces() {
        let (re, im, d, h, w) = complex_field();
        let mut cf = ComplexField3D::new().with_data(&re, &im, d, h, w);
        cf.field_mut().add_isosurface(2.0, DEFAULT_ISOSURFACE_COLOR);
        assert_eq!(cf.field().isosurfaces().len(), 1);
        assert_eq!(cf.field().data()[0], 5.0); // amplitude

        // Switching mode reprojects the inner field and clears iso-surfaces.
        cf.set_complex_mode(ComplexMode::SquareAmplitude);
        assert_eq!(cf.complex_mode(), ComplexMode::SquareAmplitude);
        assert_eq!(cf.field().data()[0], 25.0);
        assert!(
            cf.field().isosurfaces().is_empty(),
            "mode change clears iso-surfaces (silx setComplexMode)"
        );

        // Same-mode set is a no-op (keeps any newly added iso-surfaces).
        cf.field_mut()
            .add_isosurface(10.0, DEFAULT_ISOSURFACE_COLOR);
        cf.set_complex_mode(ComplexMode::SquareAmplitude);
        assert_eq!(
            cf.field().isosurfaces().len(),
            1,
            "unchanged mode is a no-op"
        );
    }

    #[test]
    fn complex_field_cut_plane_persists_across_mode_change() {
        let (re, im, d, h, w) = complex_field();
        let mut cf = ComplexField3D::new().with_data(&re, &im, d, h, w);
        cf.field_mut().cut_plane_mut().set_visible(true);
        cf.set_complex_mode(ComplexMode::Phase);
        assert!(
            cf.field().cut_plane().is_visible(),
            "the cut plane survives a mode change (only iso-surfaces are cleared)"
        );
    }

    /// A 3×3×3 complex field with `re = z` and `im = x`, so the projections have
    /// distinct spatial structure and ranges: `Real = z ∈ [0, 2]`,
    /// `Imaginary = x ∈ [0, 2]`, `Absolute = sqrt(z² + x²) ∈ [0, √8]`.
    fn ramp_complex_3() -> (Vec<f32>, Vec<f32>) {
        let (d, h, w) = (3usize, 3usize, 3usize);
        let mut re = vec![0.0f32; d * h * w];
        let mut im = vec![0.0f32; d * h * w];
        for z in 0..d {
            for y in 0..h {
                for x in 0..w {
                    re[(z * h + y) * w + x] = z as f32;
                    im[(z * h + y) * w + x] = x as f32;
                }
            }
        }
        (re, im)
    }

    #[test]
    fn colormapped_iso_colormap_tracks_its_own_colour_mode() {
        // R2-49: an iso-surface's geometry is the field mode (Absolute), but its
        // colour comes from its own mode. An autoscale colormap must range over
        // the COLOUR mode's data (Real, 0..2), not the field mode (Absolute).
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        let i = cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Real,
            Colormap::autoscale(ColormapName::Viridis),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));
        let cm = cf.colormapped_isosurfaces()[i].colormap();
        assert_eq!((cm.vmin, cm.vmax), (0.0, 2.0));
    }

    #[test]
    fn colormapped_iso_colormap_re_resolves_on_data_change() {
        // Added before data (unresolved), then resolved by the first set_data and
        // re-resolved when data changes (silx `_syncDataWithParent` on reproject).
        let mut cf = ComplexField3D::new();
        cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Real,
            Colormap::autoscale(ColormapName::Viridis),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));
        let (re, im) = ramp_complex_3();
        cf.set_data(&re, &im, 3, 3, 3);
        assert_eq!(
            {
                let cm = cf.colormapped_isosurfaces()[0].colormap();
                (cm.vmin, cm.vmax)
            },
            (0.0, 2.0)
        );
        // Double every Real value (re *= 2) → Real range 0..4.
        let re2: Vec<f32> = re.iter().map(|&v| v * 2.0).collect();
        cf.set_data(&re2, &im, 3, 3, 3);
        let cm = cf.colormapped_isosurfaces()[0].colormap();
        assert_eq!((cm.vmin, cm.vmax), (0.0, 4.0));
    }

    #[test]
    fn colormapped_iso_pinned_colormap_survives_data() {
        // A pinned range is not touched by autoscale on set_data.
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Real,
            Colormap::new(ColormapName::Viridis, -10.0, 10.0),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));
        let cm = cf.colormapped_isosurfaces()[0].colormap();
        assert_eq!((cm.vmin, cm.vmax), (-10.0, 10.0));
    }

    #[test]
    fn set_complex_mode_clears_colormapped_isosurfaces() {
        // silx clears every iso-surface on a mode change — colormapped included.
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Real,
            Colormap::autoscale(ColormapName::Viridis),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));
        assert_eq!(cf.colormapped_isosurfaces().len(), 1);
        cf.set_complex_mode(ComplexMode::Real);
        assert!(cf.colormapped_isosurfaces().is_empty());
    }

    #[test]
    fn cut_plane_mode_defaults_to_none_and_round_trips() {
        let mut cf = ComplexField3D::new();
        assert_eq!(cf.cut_plane_mode(), None);
        cf.set_cut_plane_mode(Some(ComplexMode::Phase));
        assert_eq!(cf.cut_plane_mode(), Some(ComplexMode::Phase));
        cf.set_cut_plane_mode(None);
        assert_eq!(cf.cut_plane_mode(), None);
    }

    #[test]
    fn colormapped_iso_emits_a_lit_mesh_coloured_by_its_mode() {
        // The surface (Absolute crosses 1.5) is emitted as lit triangles whose
        // colours vary with the colour mode (Imaginary = x) along the surface.
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Imaginary,
            Colormap::autoscale(ColormapName::Viridis),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));
        let mut g = Scene3dGeometry::new();
        cf.append_to(&mut g);
        assert!(
            !g.meshes.is_empty(),
            "colormapped iso-surface emits lit mesh triangles"
        );
        let colours: std::collections::HashSet<[u32; 4]> =
            g.meshes.iter().map(|v| v.color.map(f32::to_bits)).collect();
        assert!(
            colours.len() > 1,
            "a colormapped surface is not a single solid colour"
        );
    }

    #[test]
    fn hidden_colormapped_isosurface_emits_no_geometry() {
        // R3-8: the visibility flag reaches ComplexField3D's colormapped
        // isosurfaces too (via the embedded Isosurface).
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        let idx = cf.add_colormapped_isosurface(ComplexIsosurface::new(
            1.5,
            ComplexMode::Imaginary,
            Colormap::autoscale(ColormapName::Viridis),
            Color32::from_rgba_unmultiplied(0, 0, 0, 128),
        ));

        let mut visible = Scene3dGeometry::new();
        cf.append_to(&mut visible);
        assert!(
            !visible.meshes.is_empty(),
            "visible surface emits triangles"
        );

        cf.colormapped_isosurface_mut(idx)
            .unwrap()
            .set_visible(false);
        assert!(!cf.colormapped_isosurfaces()[idx].is_visible());

        let mut hidden = Scene3dGeometry::new();
        cf.append_to(&mut hidden);
        assert!(hidden.meshes.is_empty(), "hidden surface emits no geometry");
    }

    #[test]
    fn cut_plane_with_its_own_mode_reslices_and_reranges() {
        // R2-49 branch 1: the cut plane can show a different projection than the
        // iso-surfaces. Overriding its mode changes the sliced texture; the same
        // mode as the field falls back to the field slice.
        let (re, im) = ramp_complex_3();
        let mut cf = ComplexField3D::new().with_data(&re, &im, 3, 3, 3);
        cf.field_mut().cut_plane_mut().set_visible(true);
        cf.field_mut()
            .cut_plane_mut()
            .set_point(Vec3::new(0.0, 1.5, 0.0));

        let mut g_default = Scene3dGeometry::new();
        cf.append_to(&mut g_default);
        assert_eq!(g_default.textured_meshes.len(), 1, "field-mode slice");

        cf.set_cut_plane_mode(Some(ComplexMode::Real));
        let mut g_real = Scene3dGeometry::new();
        cf.append_to(&mut g_real);
        assert_eq!(g_real.textured_meshes.len(), 1);
        assert_ne!(
            g_default.textured_meshes[0].pixels, g_real.textured_meshes[0].pixels,
            "own-mode slice differs from the field-mode slice"
        );

        // Own mode == field mode (Absolute) short-circuits to the field slice.
        cf.set_cut_plane_mode(Some(ComplexMode::Absolute));
        let mut g_same = Scene3dGeometry::new();
        cf.append_to(&mut g_same);
        assert_eq!(
            g_same.textured_meshes[0].pixels, g_default.textured_meshes[0].pixels,
            "own mode equal to the field mode uses the field slice"
        );
    }
}