dcmnorm 0.23.1

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
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
//! Volume rendering (3D): a CPU ray caster over a [`Volume`], supported alongside MPR
//! (`super::volume`'s `reformat_plane`) with the same shape - a parameter struct, a raw-values
//! entry point, a pixels entry point, and an encoded (`RenderFrameOutput`) entry point.
//!
//! Rays are cast in patient (LPS) millimeters from an orthographic (or optionally perspective)
//! camera, then marched in the volume's own voxel-index space (cheap: the volume's row / column
//! / slice axes are orthonormal, so world -> index is one affine map per ray), which respects
//! anisotropic voxel spacing and oriented (oblique) acquisitions. An irregularly spaced stack is
//! sampled by real slice position through a small lookup table.
//!
//! Modes: maximum / minimum intensity projection, average (a ray-sum, DRR-like) and composite
//! direct volume rendering (DVR) through a [`TransferFunction`] - color and opacity control
//! points over the modality-LUT values (Hounsfield units for CT), with built-in presets and
//! optional gradient (Blinn-Phong headlight) shading. Composite rays stop early once nearly
//! opaque, and a coarse min/max block grid skips fully transparent regions (composite) or
//! regions that cannot raise the running maximum (MIP) / lower the running minimum (MinIP).
//!
//! Parallelized over output rows with rayon on native targets; sequential on wasm32.

use std::error::Error;
use std::fmt;

#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;

use super::render::{apply_explicit_window, encode_rendered_frame, RenderedFramePixels};
pub use super::render::{RenderFrameOutput, RenderOutputFormat};
use super::types::RenderError;
use super::volume::{canonical_view_basis, rotate_basis, Interpolation, Volume};

type Vec3 = [f64; 3];

/// How samples along each ray combine into one output pixel.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VolumeRenderMode {
    /// Maximum intensity projection (grayscale).
    MaximumIntensity,
    /// Minimum intensity projection (grayscale).
    MinimumIntensity,
    /// Mean of the samples along the ray inside the volume - a ray-sum / DRR-like projection
    /// (grayscale).
    Average,
    /// Front-to-back alpha compositing through a transfer function (RGBA).
    Composite,
}

impl VolumeRenderMode {
    /// Parses `mip`, `minip`, `average` (alias `avg`) or `composite` (alias `dvr`).
    pub fn parse(value: &str) -> Result<Self, VolumeRenderError> {
        match value.trim().to_ascii_lowercase().as_str() {
            "mip" => Ok(Self::MaximumIntensity),
            "minip" => Ok(Self::MinimumIntensity),
            "average" | "avg" => Ok(Self::Average),
            "composite" | "dvr" => Ok(Self::Composite),
            other => Err(VolumeRenderError::InvalidOptions(format!(
                "unknown volume render mode '{other}'; expected 'mip', 'minip', 'average' or 'composite'"
            ))),
        }
    }

    /// The canonical name (`mip`, `minip`, `average`, `composite`).
    pub fn name(self) -> &'static str {
        match self {
            Self::MaximumIntensity => "mip",
            Self::MinimumIntensity => "minip",
            Self::Average => "average",
            Self::Composite => "composite",
        }
    }
}

#[derive(Debug)]
pub enum VolumeRenderError {
    /// An invalid option (unknown view, malformed transfer function, conflicting settings, ...).
    InvalidOptions(String),
    /// Output width/height of zero or above 65535.
    InvalidOutputDimensions,
    /// Encoding the rendered image (PNG/JPEG) failed.
    Render(RenderError),
}

impl fmt::Display for VolumeRenderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidOptions(message) => write!(formatter, "{message}"),
            Self::InvalidOutputDimensions => write!(
                formatter,
                "volume render output width/height must be between 1 and 65535"
            ),
            Self::Render(error) => {
                write!(formatter, "failed to encode the volume rendering: {error}")
            }
        }
    }
}

impl Error for VolumeRenderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Render(error) => Some(error),
            _ => None,
        }
    }
}

impl From<RenderError> for VolumeRenderError {
    fn from(value: RenderError) -> Self {
        Self::Render(value)
    }
}

fn invalid(message: impl Into<String>) -> VolumeRenderError {
    VolumeRenderError::InvalidOptions(message.into())
}

// ---------------------------------------------------------------------------------------------
// Transfer functions
// ---------------------------------------------------------------------------------------------

/// One transfer-function control point: at `value` (or, when `relative`, at `value` percent of
/// the way from the volume's minimum to its maximum), the color is `color` (0-255 RGB) and the
/// opacity `opacity` (0-1, per millimeter of ray travel). Between points both interpolate
/// linearly; below the first / above the last point the end point's values hold.
#[derive(Clone, Debug, PartialEq)]
pub struct TransferFunctionPoint {
    pub value: f64,
    pub relative: bool,
    pub color: [u8; 3],
    pub opacity: f64,
}

/// A color + opacity transfer function over modality-LUT values (HU for CT). The text form,
/// used by the CLI and every binding, is `VALUE:R,G,B,A;VALUE:R,G,B,A;...` - `VALUE` a number
/// (or a percentage of the volume's value range, e.g. `40%`), `R,G,B` 0-255 and `A` an opacity
/// 0-1 per millimeter (so a rendering looks the same whatever `--vr-step` is).
#[derive(Clone, Debug, PartialEq)]
pub struct TransferFunction {
    pub points: Vec<TransferFunctionPoint>,
}

/// The built-in transfer-function presets: `(name, description, specification)`.
pub const VOLUME_RENDER_PRESETS: &[(&str, &str, &str)] = &[
    (
        "ct-bone",
        "CT bone: soft tissue transparent, bone ivory to white",
        "-1000:0,0,0,0;150:0,0,0,0;220:190,120,80,0.08;400:230,200,160,0.55;800:245,235,215,0.85;3000:255,255,255,0.95",
    ),
    (
        "ct-soft-tissue",
        "CT soft tissue: faint skin and fat, muscle and organs red-brown, bone white",
        "-1000:0,0,0,0;-500:0,0,0,0;-200:200,150,120,0;-60:210,160,120,0.01;20:190,80,60,0.06;80:210,90,70,0.18;200:230,180,150,0.35;600:245,235,220,0.75;3000:255,255,255,0.9",
    ),
    (
        "ct-lung",
        "CT lung: air and soft tissue transparent, lung parenchyma pale pink, bone faint",
        "-1000:0,0,0,0;-950:0,0,0,0;-900:200,140,140,0.02;-700:225,170,160,0.08;-500:230,190,170,0.12;-350:200,120,110,0;250:240,230,220,0;500:245,240,230,0.08;3000:255,255,255,0.1",
    ),
    (
        "ct-angio",
        "CT angiography: contrast-filled vessels red, bone white",
        "-1000:0,0,0,0;120:0,0,0,0;180:170,20,20,0.15;300:220,60,50,0.6;500:245,210,190,0.8;1000:250,245,240,0.9;3000:255,255,255,0.95",
    ),
    (
        "mr-default",
        "MR default: relative to the volume's value range, dark background transparent",
        "0%:0,0,0,0;10%:0,0,0,0;20%:150,90,70,0.02;40%:210,160,130,0.15;70%:240,220,200,0.5;100%:255,255,255,0.8",
    ),
];

/// Names of the built-in transfer-function presets.
pub fn volume_render_preset_names() -> Vec<&'static str> {
    VOLUME_RENDER_PRESETS
        .iter()
        .map(|(name, _, _)| *name)
        .collect()
}

impl TransferFunction {
    /// Parses the `VALUE:R,G,B,A;...` text form (see the type's own doc). Points may be listed in
    /// any order; they are sorted by value when the function is applied.
    pub fn parse(spec: &str) -> Result<Self, VolumeRenderError> {
        let mut points = Vec::new();
        for segment in spec.split(';') {
            let segment = segment.trim();
            if segment.is_empty() {
                continue;
            }
            let bad = |why: &str| {
                invalid(format!(
                    "invalid transfer function point '{segment}': {why} (expected VALUE:R,G,B,A, e.g. 300:255,240,220,0.8)"
                ))
            };
            let (value_text, color_text) =
                segment.split_once(':').ok_or_else(|| bad("missing ':'"))?;
            let value_text = value_text.trim();
            let (number_text, relative) = match value_text.strip_suffix('%') {
                Some(stripped) => (stripped.trim(), true),
                None => (value_text, false),
            };
            let value: f64 = number_text
                .parse()
                .ok()
                .filter(|value: &f64| value.is_finite())
                .ok_or_else(|| bad("VALUE is not a number"))?;
            let parts: Vec<&str> = color_text.split(',').map(str::trim).collect();
            if parts.len() != 4 {
                return Err(bad("expected four comma-separated numbers after ':'"));
            }
            let mut color = [0u8; 3];
            for (slot, part) in color.iter_mut().zip(&parts[..3]) {
                let component: f64 = part
                    .parse()
                    .ok()
                    .filter(|value: &f64| (0.0..=255.0).contains(value))
                    .ok_or_else(|| bad("R, G and B must be numbers from 0 to 255"))?;
                *slot = component.round() as u8;
            }
            let opacity: f64 = parts[3]
                .parse()
                .ok()
                .filter(|value: &f64| (0.0..=1.0).contains(value))
                .ok_or_else(|| bad("A (opacity) must be a number from 0 to 1"))?;
            points.push(TransferFunctionPoint {
                value,
                relative,
                color,
                opacity,
            });
        }
        if points.is_empty() {
            return Err(invalid(
                "transfer function has no points (expected VALUE:R,G,B,A;VALUE:R,G,B,A;...)",
            ));
        }
        Ok(Self { points })
    }

    /// A built-in preset by name (see [`VOLUME_RENDER_PRESETS`]).
    pub fn preset(name: &str) -> Result<Self, VolumeRenderError> {
        let wanted = name.trim().to_ascii_lowercase();
        VOLUME_RENDER_PRESETS
            .iter()
            .find(|(preset, _, _)| *preset == wanted)
            .map(|(_, _, spec)| Self::parse(spec).expect("built-in presets parse"))
            .ok_or_else(|| {
                invalid(format!(
                    "unknown volume render preset '{name}'; expected one of: {}",
                    volume_render_preset_names().join(", ")
                ))
            })
    }

    /// The preset used when composite rendering is asked for without one: `ct-bone` for CT,
    /// `mr-default` (range-relative, so it suits any modality) otherwise.
    pub fn default_for_modality(modality: Option<&str>) -> Self {
        let name = match modality.map(str::trim) {
            Some(value) if value.eq_ignore_ascii_case("CT") => "ct-bone",
            _ => "mr-default",
        };
        Self::preset(name).expect("built-in presets exist")
    }

    /// The `VALUE:R,G,B,A;...` text form of this function.
    pub fn to_spec_string(&self) -> String {
        self.points
            .iter()
            .map(|point| {
                format!(
                    "{}{}:{},{},{},{}",
                    point.value,
                    if point.relative { "%" } else { "" },
                    point.color[0],
                    point.color[1],
                    point.color[2],
                    point.opacity
                )
            })
            .collect::<Vec<_>>()
            .join(";")
    }

    /// Resolves relative points against `[data_min, data_max]` and sorts by value.
    fn resolve(&self, data_min: f64, data_max: f64) -> Vec<(f64, [f32; 3], f32)> {
        let mut resolved: Vec<(f64, [f32; 3], f32)> = self
            .points
            .iter()
            .map(|point| {
                let value = if point.relative {
                    data_min + (data_max - data_min) * point.value / 100.0
                } else {
                    point.value
                };
                (
                    value,
                    point.color.map(|c| f32::from(c) / 255.0),
                    point.opacity as f32,
                )
            })
            .collect();
        resolved.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
        resolved
    }
}

const LUT_SIZE: usize = 4096;

/// A transfer function sampled into a fixed-size table for the inner loop: `rgba[i]` holds the
/// color (0-1) and the opacity already corrected for the ray step.
struct TransferLut {
    low: f32,
    scale: f32,
    rgba: Vec<[f32; 4]>,
    /// `nonzero_prefix[i]` = number of entries `< i` with non-zero opacity.
    nonzero_prefix: Vec<u32>,
}

impl TransferLut {
    fn new(function: &TransferFunction, data_min: f64, data_max: f64, step_mm: f64) -> Self {
        let points = function.resolve(data_min, data_max);
        let low = points[0].0;
        let high = points[points.len() - 1].0;
        let span = (high - low).max(1e-6);
        let mut rgba = Vec::with_capacity(LUT_SIZE);
        let mut segment = 0usize;
        for index in 0..LUT_SIZE {
            let value = low + span * index as f64 / (LUT_SIZE - 1) as f64;
            while segment + 1 < points.len() && points[segment + 1].0 < value {
                segment += 1;
            }
            let (color, opacity) = if points.len() == 1 || value <= points[0].0 {
                (points[0].1, points[0].2)
            } else if segment + 1 >= points.len() {
                let last = points[points.len() - 1];
                (last.1, last.2)
            } else {
                let (v0, c0, a0) = points[segment];
                let (v1, c1, a1) = points[segment + 1];
                let t = if v1 > v0 {
                    ((value - v0) / (v1 - v0)).clamp(0.0, 1.0) as f32
                } else {
                    1.0
                };
                (
                    [0, 1, 2].map(|k| c0[k] + (c1[k] - c0[k]) * t),
                    a0 + (a1 - a0) * t,
                )
            };
            // Opacity is specified per millimeter; a step of `step_mm` accumulates
            // 1 - (1 - a)^step_mm, so changing the step changes quality, not brightness.
            let corrected = if opacity <= 0.0 {
                0.0
            } else if opacity >= 1.0 {
                1.0
            } else {
                1.0 - (1.0 - opacity).powf(step_mm as f32)
            };
            rgba.push([color[0], color[1], color[2], corrected]);
        }
        let mut nonzero_prefix = Vec::with_capacity(LUT_SIZE + 1);
        let mut count = 0u32;
        nonzero_prefix.push(0);
        for entry in &rgba {
            if entry[3] > 0.0 {
                count += 1;
            }
            nonzero_prefix.push(count);
        }
        Self {
            low: low as f32,
            scale: ((LUT_SIZE - 1) as f64 / span) as f32,
            rgba,
            nonzero_prefix,
        }
    }

    #[inline(always)]
    fn index(&self, value: f32) -> usize {
        let position = (value - self.low) * self.scale + 0.5;
        if position <= 0.0 {
            0
        } else {
            (position as usize).min(LUT_SIZE - 1)
        }
    }

    #[inline(always)]
    fn lookup(&self, value: f32) -> [f32; 4] {
        self.rgba[self.index(value)]
    }

    /// Whether every value in `[min, max]` maps to zero opacity.
    fn transparent_between(&self, min: f32, max: f32) -> bool {
        let low = self.index(min);
        let high = self.index(max);
        self.nonzero_prefix[high + 1] == self.nonzero_prefix[low]
    }
}

// ---------------------------------------------------------------------------------------------
// Camera / parameters
// ---------------------------------------------------------------------------------------------

/// Canonical camera views, named for where the viewer stands: `anterior` looks from the front
/// (patient's right on the image left, head up - the coronal convention), `posterior` from
/// behind, `left` / `right` from the patient's left / right side (head up), `superior` from
/// above the head (anterior up) and `inferior` from below the feet (anterior up, patient's right
/// on the image left - the axial convention). MPR's `coronal`, `sagittal` and `axial` are
/// accepted as aliases of `anterior`, `left` and the volume's own native axial basis. Returns
/// `(row_dir, col_dir)`: image right and image down, in patient (LPS) space; rays travel along
/// `cross(row_dir, col_dir)`.
pub fn volume_render_view_basis(
    view: &str,
    volume: &Volume,
) -> Result<(Vec3, Vec3), VolumeRenderError> {
    match view.trim().to_ascii_lowercase().as_str() {
        "anterior" | "front" => Ok(([1.0, 0.0, 0.0], [0.0, 0.0, -1.0])),
        "posterior" | "back" => Ok(([-1.0, 0.0, 0.0], [0.0, 0.0, -1.0])),
        "left" => Ok(([0.0, 1.0, 0.0], [0.0, 0.0, -1.0])),
        "right" => Ok(([0.0, -1.0, 0.0], [0.0, 0.0, -1.0])),
        "superior" | "top" => Ok(([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0])),
        "inferior" | "bottom" => Ok(([1.0, 0.0, 0.0], [0.0, 1.0, 0.0])),
        "coronal" => canonical_view_basis("coronal", volume).map_err(|e| invalid(e.to_string())),
        "sagittal" => canonical_view_basis("sagittal", volume).map_err(|e| invalid(e.to_string())),
        "axial" => canonical_view_basis("axial", volume).map_err(|e| invalid(e.to_string())),
        other => Err(invalid(format!(
            "unknown volume render view '{other}'; expected anterior, posterior, left, right, superior, inferior (or coronal, sagittal, axial)"
        ))),
    }
}

/// Orbits a camera basis by `degrees` about its own screen-vertical axis (`col_dir`), through
/// the render center - one step of a turntable. Positive angles move the camera toward the image
/// right.
pub fn orbit_basis(row_dir: Vec3, col_dir: Vec3, degrees: f64) -> (Vec3, Vec3) {
    if degrees.abs() < 1e-12 {
        return (row_dir, col_dir);
    }
    let axis = normalize3(col_dir);
    let (sin, cos) = degrees.to_radians().sin_cos();
    let v = row_dir;
    let rotated = add3(
        add3(scale3(v, cos), scale3(cross3(axis, v), sin)),
        scale3(axis, dot3(axis, v) * (1.0 - cos)),
    );
    (normalize3(rotated), col_dir)
}

/// Fully resolved volume rendering parameters. Most callers build these with
/// [`resolve_volume_render_params`] from a [`VolumeRenderOptions`]; every field is public for
/// callers that drive the camera themselves.
#[derive(Clone, Debug)]
pub struct VolumeRenderParams {
    pub mode: VolumeRenderMode,
    /// World (patient/LPS mm) point at the center of the output image - the camera target.
    pub center: Vec3,
    /// Unit vector: image right (direction of travel as the output column index increases).
    pub row_dir: Vec3,
    /// Unit vector: image down. Rays travel along `cross(row_dir, col_dir)`.
    pub col_dir: Vec3,
    pub output_width: u32,
    pub output_height: u32,
    /// Size of one output pixel at the center plane, mm (isotropic).
    pub spacing_mm: f64,
    /// Distance between samples along each ray, mm.
    pub step_mm: f64,
    /// `None` for orthographic projection, else a perspective camera with this vertical field of
    /// view in degrees, placed so the center plane keeps `spacing_mm` per pixel.
    pub perspective_fov_deg: Option<f64>,
    /// Composite mode's transfer function (required for composite, ignored otherwise).
    pub transfer_function: Option<TransferFunction>,
    /// Gradient (Blinn-Phong headlight) shading in composite mode.
    pub shading: bool,
    /// VOI window for the grayscale modes (MIP/MinIP/average), applied exactly as given (values
    /// below it are black, above it white); without it the output spans the rendered values' own
    /// range, as MPR does.
    pub window_center: Option<f64>,
    pub window_width: Option<f64>,
    /// Clip box in voxel indices, inclusive: `[col_min, col_max, row_min, row_max, slice_min,
    /// slice_max]`.
    pub crop_voxels: Option<[f64; 6]>,
    /// Clip box in patient (LPS) mm, axis-aligned: `[x_min, x_max, y_min, y_max, z_min, z_max]`.
    pub crop_mm: Option<[f64; 6]>,
    /// Composite output's background color (encoded output is composited over it).
    pub background: [u8; 3],
    pub interpolation: Interpolation,
}

/// Loosely typed volume rendering options, shared by the CLI and every binding so they all
/// validate the same way. Unset fields take the defaults documented on each field.
#[derive(Clone, Debug, Default)]
pub struct VolumeRenderOptions {
    /// `mip`, `minip`, `average` (`avg`) or `composite` (`dvr`). Default `composite`.
    pub mode: Option<String>,
    /// A canonical view (see [`volume_render_view_basis`]). Default `anterior`.
    pub view: Option<String>,
    /// Extra yaw, pitch, roll (degrees, about the patient Z, X and Y axes - the same convention
    /// as `--mpr YAW,PITCH,ROLL`) applied on top of `view`.
    pub rotation_deg: Option<[f64; 3]>,
    /// Turntable angle: orbits the camera about the screen-vertical axis after `rotation_deg`.
    pub orbit_deg: Option<f64>,
    /// Camera target, patient mm. Default: the crop box's center, else the volume's center.
    pub center: Option<Vec3>,
    /// Output pixel size, mm. Default: the volume's smallest voxel spacing (scaled up to honor
    /// `max_dim`).
    pub spacing_mm: Option<f64>,
    /// Magnification: divides the spacing while keeping the output size. Default 1.
    pub zoom: Option<f64>,
    /// Output size. Default: large enough to show the whole (cropped) volume from this camera.
    pub output_width: Option<u32>,
    pub output_height: Option<u32>,
    /// Caps the longer default output side (ignored when width/height or spacing are given).
    pub max_dim: Option<u32>,
    /// Sample step, mm. Default: half the volume's smallest voxel spacing.
    pub step_mm: Option<f64>,
    /// A built-in transfer-function preset name (composite only).
    pub preset: Option<String>,
    /// A custom transfer function, `VALUE:R,G,B,A;...` (composite only).
    pub transfer_function: Option<String>,
    /// Gradient shading (composite only). Default on.
    pub shading: Option<bool>,
    /// Perspective field of view in degrees (0 < fov < 180). Default orthographic.
    pub perspective_fov_deg: Option<f64>,
    pub crop_voxels: Option<[f64; 6]>,
    pub crop_mm: Option<[f64; 6]>,
    /// Grayscale modes only.
    pub window_center: Option<f64>,
    pub window_width: Option<f64>,
    /// Composite background. Default black.
    pub background: Option<[u8; 3]>,
    /// `trilinear` (default) or `nearest`.
    pub interpolation: Option<String>,
}

/// Parses an on/off style boolean (`on`/`off`, `true`/`false`, `yes`/`no`, `1`/`0`).
pub fn parse_on_off(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "on" | "true" | "yes" | "1" => Some(true),
        "off" | "false" | "no" | "0" => Some(false),
        _ => None,
    }
}

fn validate_box(values: &[f64; 6], what: &str) -> Result<(), VolumeRenderError> {
    for axis in 0..3 {
        let (low, high) = (values[axis * 2], values[axis * 2 + 1]);
        if !low.is_finite() || !high.is_finite() || low > high {
            return Err(invalid(format!(
                "{what} must give MIN <= MAX on each axis (got {low}..{high})"
            )));
        }
    }
    Ok(())
}

/// Resolves loosely typed options against `volume` into concrete render parameters, applying
/// every default and validation in one place.
pub fn resolve_volume_render_params(
    volume: &Volume,
    options: &VolumeRenderOptions,
) -> Result<VolumeRenderParams, VolumeRenderError> {
    resolve_params(volume, options, false)
}

/// Like [`resolve_volume_render_params`], for a turntable: the default output size (and, under
/// `max_dim`, spacing) fits the (cropped) volume at EVERY angle of an orbit about the
/// screen-vertical axis, not just the starting view, so one framing serves every frame. Render
/// frame `i` of `n` with the basis `orbit_basis(params.row_dir, params.col_dir, 360 * i / n)`.
/// An explicit output size, spacing or zoom is kept as given.
pub fn resolve_turntable_volume_render_params(
    volume: &Volume,
    options: &VolumeRenderOptions,
) -> Result<VolumeRenderParams, VolumeRenderError> {
    resolve_params(volume, options, true)
}

/// One framing point (a corner of the cropped volume) in camera coordinates around the render
/// center: `u` along image right, `v` along image down, `depth` along the view direction
/// (negative = toward the camera). For a turntable, `u` and `depth` change with the angle but
/// `radius = hypot(u, depth)` (the distance from the orbit axis) does not.
struct FramingPoint {
    u: f64,
    v: f64,
    depth: f64,
    radius: f64,
}

/// Default framing: the half-extents of the image (mm at the center plane) that show every
/// framing point, for an orthographic or perspective camera, from one view or over a full orbit.
struct Framing {
    points: Vec<FramingPoint>,
    /// `tan(fov / 2)` for a perspective camera.
    perspective_tan: Option<f64>,
    orbit: bool,
}

impl Framing {
    /// The point's nearest depth: as given, or over an orbit the nearest it ever comes.
    fn near_depth(&self, point: &FramingPoint) -> f64 {
        if self.orbit {
            -point.radius
        } else {
            point.depth
        }
    }

    fn orthographic_half_u(&self) -> f64 {
        self.points
            .iter()
            .map(|point| {
                if self.orbit {
                    point.radius
                } else {
                    point.u.abs()
                }
            })
            .fold(0.0, f64::max)
    }

    /// The default half-height: for a perspective camera, the smallest one whose camera (at
    /// `half_height / tan`) sees every point within the vertical field of view - and stays
    /// outside the volume.
    fn half_v(&self) -> f64 {
        let orthographic = self.points.iter().map(|p| p.v.abs()).fold(0.0, f64::max);
        let Some(tan) = self.perspective_tan else {
            return orthographic;
        };
        // |v| / (distance + near_depth) <= tan  <=>  distance >= |v| / tan - near_depth.
        let mut distance: f64 = 0.0;
        let mut nearest: f64 = 0.0;
        let mut extent: f64 = 0.0;
        for point in &self.points {
            let near = self.near_depth(point);
            distance = distance.max(point.v.abs() / tan - near);
            nearest = nearest.max(-near);
            extent = extent.max(point.radius).max(point.v.abs());
        }
        // Keep the camera clear of the nearest point even where the volume is flat.
        distance = distance.max(nearest + extent * 0.01 + 1e-3);
        distance * tan
    }

    /// The half-width for an image `half_height` mm tall at the center plane; for a perspective
    /// camera that fixes the camera distance. `None` when that camera would sit inside (or too
    /// close to) the volume.
    fn half_u(&self, half_height: f64) -> Option<f64> {
        let Some(tan) = self.perspective_tan else {
            return Some(self.orthographic_half_u());
        };
        let distance = half_height / tan;
        let mut half: f64 = 0.0;
        for point in &self.points {
            if distance + self.near_depth(point) <= 1e-6 * distance.max(1.0) {
                return None;
            }
            let projected = if self.orbit {
                // The widest the point ever looks over the orbit: the tangent from the eye to
                // the circle it travels, projected onto the center plane.
                point.radius * distance / (distance * distance - point.radius * point.radius).sqrt()
            } else {
                point.u.abs() * distance / (distance + point.depth)
            };
            half = half.max(projected);
        }
        Some(half)
    }
}

fn resolve_params(
    volume: &Volume,
    options: &VolumeRenderOptions,
    orbit_framing: bool,
) -> Result<VolumeRenderParams, VolumeRenderError> {
    let mode = VolumeRenderMode::parse(options.mode.as_deref().unwrap_or("composite"))?;
    let composite = mode == VolumeRenderMode::Composite;

    if !composite {
        if options.preset.is_some() || options.transfer_function.is_some() {
            return Err(invalid(
                "a transfer function / preset only applies to composite volume rendering",
            ));
        }
        if options.shading.is_some() {
            return Err(invalid(
                "shading only applies to composite volume rendering",
            ));
        }
        if options.background.is_some() {
            return Err(invalid(
                "a background color only applies to composite volume rendering",
            ));
        }
    } else if options.window_center.is_some() || options.window_width.is_some() {
        return Err(invalid(
            "window center/width only apply to the mip, minip and average volume render modes",
        ));
    }
    if options.window_center.is_some() != options.window_width.is_some() {
        return Err(invalid(
            "window center and window width must be given together",
        ));
    }
    if options.preset.is_some() && options.transfer_function.is_some() {
        return Err(invalid(
            "give either a transfer function preset or a custom transfer function, not both",
        ));
    }

    let transfer_function = if composite {
        Some(match (&options.preset, &options.transfer_function) {
            (Some(name), None) => TransferFunction::preset(name)?,
            (None, Some(spec)) => TransferFunction::parse(spec)?,
            _ => TransferFunction::default_for_modality(volume.modality.as_deref()),
        })
    } else {
        None
    };

    let interpolation = match options.interpolation.as_deref().map(str::trim) {
        None | Some("trilinear") => Interpolation::Trilinear,
        Some("nearest") => Interpolation::Nearest,
        Some(other) => {
            return Err(invalid(format!(
                "invalid interpolation '{other}'; expected 'trilinear' or 'nearest'"
            )))
        }
    };

    if let Some(crop) = &options.crop_voxels {
        validate_box(crop, "the voxel crop box")?;
    }
    if let Some(crop) = &options.crop_mm {
        validate_box(crop, "the millimeter crop box")?;
    }

    let (mut row_dir, mut col_dir) =
        volume_render_view_basis(options.view.as_deref().unwrap_or("anterior"), volume)?;
    if let Some([yaw, pitch, roll]) = options.rotation_deg {
        if !(yaw.is_finite() && pitch.is_finite() && roll.is_finite()) {
            return Err(invalid("rotation angles must be finite numbers"));
        }
        (row_dir, col_dir) = rotate_basis(row_dir, col_dir, yaw, pitch, roll);
    }
    if let Some(orbit) = options.orbit_deg {
        if !orbit.is_finite() {
            return Err(invalid("the orbit angle must be a finite number"));
        }
        (row_dir, col_dir) = orbit_basis(row_dir, col_dir, orbit);
    }

    let geometry = Geometry::new(volume);
    let (box_low, box_high) = geometry.clip_box(options.crop_voxels.as_ref())?;
    let corners = geometry.box_corners_world(box_low, box_high, options.crop_mm.as_ref());

    let center = match options.center {
        Some(center) => {
            if !center.iter().all(|value| value.is_finite()) {
                return Err(invalid("the render center must be finite numbers"));
            }
            center
        }
        None if options.crop_voxels.is_some() || options.crop_mm.is_some() => {
            let mut sum = [0.0; 3];
            for corner in &corners {
                sum = add3(sum, *corner);
            }
            scale3(sum, 1.0 / corners.len().max(1) as f64)
        }
        None => volume.center(),
    };

    if let Some(fov) = options.perspective_fov_deg {
        if !(fov > 0.0 && fov < 180.0) {
            return Err(invalid(
                "the perspective field of view must be between 0 and 180 degrees (exclusive)",
            ));
        }
    }

    // The (cropped) volume's corners around `center`, in camera coordinates.
    let view_dir = normalize3(cross3(row_dir, col_dir));
    let framing = Framing {
        points: corners
            .iter()
            .map(|corner| {
                let rel = sub3(*corner, center);
                let (u, depth) = (dot3(rel, row_dir), dot3(rel, view_dir));
                FramingPoint {
                    u,
                    v: dot3(rel, col_dir),
                    depth,
                    radius: u.hypot(depth),
                }
            })
            .collect(),
        perspective_tan: options
            .perspective_fov_deg
            .map(|fov| (fov.to_radians() / 2.0).tan()),
        orbit: orbit_framing,
    };
    let half_v = framing.half_v();

    let base_spacing = volume.min_spacing_mm().max(1e-4);
    if let Some(spacing) = options.spacing_mm {
        if !(spacing > 0.0) || !spacing.is_finite() {
            return Err(invalid("the output spacing must be greater than zero"));
        }
    }
    let zoom = options.zoom.unwrap_or(1.0);
    if !(zoom > 0.0) || !zoom.is_finite() {
        return Err(invalid("zoom must be greater than zero"));
    }

    let mut spacing_mm = options.spacing_mm.unwrap_or(base_spacing);
    let fit = |spacing: f64, half: f64| ((2.0 * half / spacing).ceil() as u32).saturating_add(1);
    // The default width follows the actual image height, which (for a perspective camera) sets
    // the camera distance. A camera an explicit height puts inside the volume (a fly-through)
    // has no finite fit, so the width falls back to the orthographic extent.
    let half_u = |height: u32, spacing: f64| {
        let height = options.output_height.unwrap_or(height);
        framing
            .half_u(f64::from(height) * spacing / 2.0)
            .unwrap_or_else(|| framing.orthographic_half_u())
    };
    let mut height = fit(spacing_mm, half_v);
    let mut width = fit(spacing_mm, half_u(height, spacing_mm));
    if options.spacing_mm.is_none() {
        if let Some(cap) = options.max_dim.filter(|&cap| cap > 0) {
            let longest = width.max(height);
            if longest > cap {
                spacing_mm *= f64::from(longest) / f64::from(cap);
                height = fit(spacing_mm, half_v).min(cap);
                width = fit(spacing_mm, half_u(height, spacing_mm)).min(cap);
            }
        }
    }
    let output_width = options.output_width.unwrap_or(width);
    let output_height = options.output_height.unwrap_or(height);
    validate_output_dimensions(output_width, output_height)?;
    spacing_mm /= zoom;

    let step_mm = options.step_mm.unwrap_or(base_spacing * 0.5);
    if !(step_mm > 0.0) || !step_mm.is_finite() {
        return Err(invalid("the sample step must be greater than zero"));
    }
    validate_sample_budget(&geometry, box_low, box_high, step_mm)?;

    Ok(VolumeRenderParams {
        mode,
        center,
        row_dir,
        col_dir,
        output_width,
        output_height,
        spacing_mm,
        step_mm,
        perspective_fov_deg: options.perspective_fov_deg,
        transfer_function,
        shading: composite && options.shading.unwrap_or(true),
        window_center: options.window_center,
        window_width: options.window_width,
        crop_voxels: options.crop_voxels,
        crop_mm: options.crop_mm,
        background: options.background.unwrap_or([0, 0, 0]),
        interpolation,
    })
}

/// The most output pixels one volume rendering may have (100 MP, the same budget as
/// [`super::wsi::DEFAULT_WSI_MAX_OUTPUT_PIXELS`]): a composite needs 4 bytes per pixel for its
/// RGBA buffer, a projection ~13 (raw `f32` values, an `f64` copy to window and the 8-bit
/// result), so this keeps a render under ~1.3 GB and every length within `usize` on wasm32.
pub const MAX_VOLUME_RENDER_OUTPUT_PIXELS: u64 = 100_000_000;

/// The most samples a single ray may take (2^18 = 262,144): 128 times what the default step
/// needs to cross a 1024-voxel-diagonal volume. A smaller `step_mm` is rejected rather than
/// overflowing the sample count or stalling an average projection.
pub const MAX_VOLUME_RENDER_SAMPLES_PER_RAY: u64 = 1 << 18;

fn validate_output_dimensions(width: u32, height: u32) -> Result<(), VolumeRenderError> {
    if width == 0 || height == 0 || width > u16::MAX as u32 || height > u16::MAX as u32 {
        return Err(VolumeRenderError::InvalidOutputDimensions);
    }
    let pixels = u64::from(width) * u64::from(height);
    if pixels > MAX_VOLUME_RENDER_OUTPUT_PIXELS {
        return Err(invalid(format!(
            "a {width}x{height} volume rendering ({pixels} pixels) exceeds the {MAX_VOLUME_RENDER_OUTPUT_PIXELS}-pixel output limit"
        )));
    }
    Ok(())
}

/// Rejects a sample step that would give some ray more than
/// [`MAX_VOLUME_RENDER_SAMPLES_PER_RAY`] samples through the clip box (`low..high`, uniform voxel
/// coordinates). The box's summed edge lengths bound any straight path through it.
fn validate_sample_budget(
    geometry: &Geometry<'_>,
    low: Vec3,
    high: Vec3,
    step_mm: f64,
) -> Result<(), VolumeRenderError> {
    let spacings = [
        geometry.col_spacing,
        geometry.row_spacing,
        geometry.slice_spacing,
    ];
    let longest_path_mm: f64 = (0..3)
        .map(|axis| (high[axis] - low[axis]).max(0.0) * spacings[axis])
        .sum();
    let samples = longest_path_mm / step_mm + 1.0;
    if !(samples <= MAX_VOLUME_RENDER_SAMPLES_PER_RAY as f64) {
        return Err(invalid(format!(
            "the sample step {step_mm} mm is too small for this volume: rays up to {longest_path_mm:.1} mm long would take more than {MAX_VOLUME_RENDER_SAMPLES_PER_RAY} samples (use a step of at least {:.4} mm)",
            longest_path_mm / (MAX_VOLUME_RENDER_SAMPLES_PER_RAY - 1) as f64
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------------------------
// Ray casting
// ---------------------------------------------------------------------------------------------

/// The volume's world <-> voxel-index mapping and voxel access, prepared once per render.
struct Geometry<'a> {
    samples: &'a [f32],
    cols: usize,
    rows: usize,
    slices: usize,
    origin: Vec3,
    row_vector: Vec3,
    col_vector: Vec3,
    slice_normal: Vec3,
    col_spacing: f64,
    row_spacing: f64,
    /// Nominal slice spacing (uniform-index units), mm.
    slice_spacing: f64,
    /// For an irregularly spaced stack: the real slice positions, mapping a uniform slice
    /// coordinate to the exact real fractional slice index.
    irregular: Option<SlicePositions>,
}

/// Exact uniform-coordinate -> real-slice-index lookup for an irregularly spaced stack. `zs` holds
/// every slice's position in uniform-index units (`(z - z0) / nominal_spacing`), and
/// `interval_at[c]` the last slice at or below uniform coordinate `c / SLICE_CELLS_PER_UNIT`, so a
/// lookup starts at the right interval and only steps over the (few) slices sharing one cell:
/// every real slice position is a breakpoint, however close its neighbors are.
struct SlicePositions {
    zs: Vec<f32>,
    interval_at: Vec<u32>,
}

const SLICE_CELLS_PER_UNIT: usize = 8;

impl SlicePositions {
    fn new(slice_zs: &[f64], nominal_spacing: f64) -> Self {
        let first = slice_zs[0];
        let zs: Vec<f32> = slice_zs
            .iter()
            .map(|&z| ((z - first) / nominal_spacing) as f32)
            .collect();
        let last_interval = zs.len().saturating_sub(2);
        let cells = (f64::from(zs[zs.len() - 1]).max(0.0) * SLICE_CELLS_PER_UNIT as f64).ceil()
            as usize
            + 1;
        let mut interval_at = Vec::with_capacity(cells);
        let mut k = 0usize;
        for cell in 0..cells {
            let u = cell as f32 / SLICE_CELLS_PER_UNIT as f32;
            while k < last_interval && zs[k + 1] <= u {
                k += 1;
            }
            interval_at.push(k as u32);
        }
        Self { zs, interval_at }
    }

    /// Real fractional slice index at uniform slice coordinate `u` (linear within each real
    /// interval, extrapolated past the ends - callers clamp).
    #[inline(always)]
    fn real_index(&self, u: f32) -> f32 {
        let zs = &self.zs;
        let last_interval = zs.len() - 2;
        let cell =
            ((u.max(0.0) * SLICE_CELLS_PER_UNIT as f32) as usize).min(self.interval_at.len() - 1);
        let mut k = self.interval_at[cell] as usize;
        while k < last_interval && zs[k + 1] <= u {
            k += 1;
        }
        let gap = (zs[k + 1] - zs[k]).max(1e-6);
        k as f32 + (u - zs[k]) / gap
    }

    /// Uniform slice coordinate of real fractional slice index `r` (the inverse of
    /// [`Self::real_index`]; nominal spacing beyond the ends).
    fn uniform_coordinate(&self, r: f64) -> f64 {
        let zs = &self.zs;
        let last = zs.len() - 1;
        if r <= 0.0 {
            return f64::from(zs[0]) + r;
        }
        if r >= last as f64 {
            return f64::from(zs[last]) + (r - last as f64);
        }
        let k = (r.floor() as usize).min(last - 1);
        let t = r - k as f64;
        f64::from(zs[k]) + (f64::from(zs[k + 1]) - f64::from(zs[k])) * t
    }
}
const BLOCK_SHIFT: usize = 3;
const BLOCK: usize = 1 << BLOCK_SHIFT;

impl<'a> Geometry<'a> {
    fn new(volume: &'a Volume) -> Self {
        let slices = volume.num_slices.max(1) as usize;
        let nominal = volume.nominal_slice_spacing_mm();
        let slice_spacing = if nominal > 0.0 { nominal } else { 1.0 };
        let irregular = (volume.has_irregular_spacing() && slices >= 3)
            .then(|| SlicePositions::new(&volume.slice_zs, slice_spacing));
        Self {
            samples: &volume.samples,
            cols: volume.cols.max(1) as usize,
            rows: volume.rows.max(1) as usize,
            slices,
            origin: volume.origin,
            row_vector: volume.row_vector,
            col_vector: volume.col_vector,
            slice_normal: volume.slice_normal,
            col_spacing: volume.col_spacing_mm,
            row_spacing: volume.row_spacing_mm,
            slice_spacing,
            irregular,
        }
    }

    /// World point -> continuous (uniform) voxel index `[col, row, slice]`.
    fn world_to_index(&self, world: Vec3) -> Vec3 {
        let delta = sub3(world, self.origin);
        [
            dot3(delta, self.row_vector) / self.col_spacing,
            dot3(delta, self.col_vector) / self.row_spacing,
            dot3(delta, self.slice_normal) / self.slice_spacing,
        ]
    }

    /// World direction -> voxel-index direction.
    fn direction_to_index(&self, direction: Vec3) -> Vec3 {
        [
            dot3(direction, self.row_vector) / self.col_spacing,
            dot3(direction, self.col_vector) / self.row_spacing,
            dot3(direction, self.slice_normal) / self.slice_spacing,
        ]
    }

    fn index_to_world(&self, index: Vec3) -> Vec3 {
        add3(
            add3(
                add3(
                    self.origin,
                    scale3(self.row_vector, index[0] * self.col_spacing),
                ),
                scale3(self.col_vector, index[1] * self.row_spacing),
            ),
            scale3(self.slice_normal, index[2] * self.slice_spacing),
        )
    }

    /// The renderable box in (uniform) voxel-index space: every voxel's footprint (half a voxel
    /// beyond the outer voxel centers), tightened by the voxel crop box. A crop box that misses
    /// the volume on any axis is an error (it would otherwise leave reversed bounds that render
    /// clamped edge voxels); one that partly overlaps keeps the intersection.
    fn clip_box(&self, crop: Option<&[f64; 6]>) -> Result<(Vec3, Vec3), VolumeRenderError> {
        let mut low: Vec3 = [-0.5; 3];
        let mut high = [
            self.cols as f64 - 0.5,
            self.rows as f64 - 0.5,
            self.slices as f64 - 0.5,
        ];
        if let Some(crop) = crop {
            for axis in 0..3 {
                let (mut crop_low, mut crop_high) =
                    (crop[axis * 2] - 0.5, crop[axis * 2 + 1] + 0.5);
                if axis == 2 {
                    // The crop's slice range is in real slice indices; the box is in uniform
                    // coordinates, which only coincide on a uniformly spaced stack.
                    if let Some(positions) = &self.irregular {
                        crop_low = positions.uniform_coordinate(crop_low);
                        crop_high = positions.uniform_coordinate(crop_high);
                    }
                }
                low[axis] = low[axis].max(crop_low);
                high[axis] = high[axis].min(crop_high);
                if !(low[axis] < high[axis]) {
                    let (name, size) = match axis {
                        0 => ("column", self.cols),
                        1 => ("row", self.rows),
                        _ => ("slice", self.slices),
                    };
                    return Err(invalid(format!(
                        "the voxel crop box's {name} range {}..{} does not overlap the volume's {size} {name}s (0..{})",
                        crop[axis * 2],
                        crop[axis * 2 + 1],
                        size.saturating_sub(1)
                    )));
                }
            }
        }
        Ok((low, high))
    }

    /// World corners of the index box, clamped into the millimeter crop box when given (used for
    /// default framing only, so an approximation is fine).
    fn box_corners_world(&self, low: Vec3, high: Vec3, crop_mm: Option<&[f64; 6]>) -> Vec<Vec3> {
        let mut corners = Vec::with_capacity(8);
        for &x in &[low[0], high[0]] {
            for &y in &[low[1], high[1]] {
                for &z in &[low[2], high[2]] {
                    let mut world = self.index_to_world([x, y, z]);
                    if let Some(crop) = crop_mm {
                        for axis in 0..3 {
                            world[axis] = world[axis].clamp(crop[axis * 2], crop[axis * 2 + 1]);
                        }
                    }
                    corners.push(world);
                }
            }
        }
        corners
    }

    #[inline(always)]
    fn voxel(&self, col: usize, row: usize, slice: usize) -> f32 {
        // SAFETY-free indexing: callers clamp every coordinate into range first.
        self.samples[(slice * self.rows + row) * self.cols + col]
    }

    /// Maps a uniform slice coordinate to the real fractional slice index.
    #[inline(always)]
    fn real_slice(&self, z: f32) -> f32 {
        match &self.irregular {
            None => z,
            Some(positions) => positions.real_index(z),
        }
    }

    /// Clamped integer base coordinates and fractions of a sample at a uniform index.
    #[inline(always)]
    fn cell(&self, x: f32, y: f32, z: f32) -> ([usize; 3], [f32; 3]) {
        let z = self.real_slice(z);
        let clamp = |value: f32, size: usize| -> (usize, f32) {
            let max = (size - 1) as f32;
            let value = value.clamp(0.0, max);
            let base = (value as usize).min(size.saturating_sub(2));
            (base, value - base as f32)
        };
        let (x0, fx) = clamp(x, self.cols);
        let (y0, fy) = clamp(y, self.rows);
        let (z0, fz) = clamp(z, self.slices);
        ([x0, y0, z0], [fx, fy, fz])
    }

    #[inline(always)]
    fn sample_cell(&self, base: [usize; 3], frac: [f32; 3], nearest: bool) -> f32 {
        let [x0, y0, z0] = base;
        let x1 = (x0 + 1).min(self.cols - 1);
        let y1 = (y0 + 1).min(self.rows - 1);
        let z1 = (z0 + 1).min(self.slices - 1);
        let [fx, fy, fz] = frac;
        if nearest {
            return self.voxel(
                if fx >= 0.5 { x1 } else { x0 },
                if fy >= 0.5 { y1 } else { y0 },
                if fz >= 0.5 { z1 } else { z0 },
            );
        }
        let plane = self.rows * self.cols;
        let s = self.samples;
        let i000 = (z0 * self.rows + y0) * self.cols;
        let i010 = (z0 * self.rows + y1) * self.cols;
        let i001 = i000 + (z1 - z0) * plane;
        let i011 = i010 + (z1 - z0) * plane;
        let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
        let c00 = lerp(s[i000 + x0], s[i000 + x1], fx);
        let c10 = lerp(s[i010 + x0], s[i010 + x1], fx);
        let c01 = lerp(s[i001 + x0], s[i001 + x1], fx);
        let c11 = lerp(s[i011 + x0], s[i011 + x1], fx);
        lerp(lerp(c00, c10, fy), lerp(c01, c11, fy), fz)
    }

    #[inline(always)]
    fn sample(&self, x: f32, y: f32, z: f32, nearest: bool) -> f32 {
        let (base, frac) = self.cell(x, y, z);
        self.sample_cell(base, frac, nearest)
    }

    /// Value gradient at a uniform index position, in value units per mm, in world space.
    fn gradient_world(&self, x: f32, y: f32, z: f32) -> Vec3 {
        let gx = (self.sample(x + 1.0, y, z, false) - self.sample(x - 1.0, y, z, false)) as f64
            / (2.0 * self.col_spacing);
        let gy = (self.sample(x, y + 1.0, z, false) - self.sample(x, y - 1.0, z, false)) as f64
            / (2.0 * self.row_spacing);
        let gz = (self.sample(x, y, z + 1.0, false) - self.sample(x, y, z - 1.0, false)) as f64
            / (2.0 * self.slice_spacing);
        add3(
            add3(scale3(self.row_vector, gx), scale3(self.col_vector, gy)),
            scale3(self.slice_normal, gz),
        )
    }
}

/// Per-block (8x8x8 voxels, overlapping their +1 neighbor so trilinear samples stay inside)
/// value range, for empty-space skipping.
struct BlockGrid {
    nx: usize,
    ny: usize,
    min: Vec<f32>,
    max: Vec<f32>,
}

impl BlockGrid {
    fn new(geometry: &Geometry<'_>) -> Self {
        let nx = geometry.cols.div_ceil(BLOCK);
        let ny = geometry.rows.div_ceil(BLOCK);
        let nz = geometry.slices.div_ceil(BLOCK);
        let per_layer = nx * ny;
        let mut min = vec![f32::INFINITY; per_layer * nz];
        let mut max = vec![f32::NEG_INFINITY; per_layer * nz];
        let fill_layer = |(bz, (min_layer, max_layer)): (usize, (&mut [f32], &mut [f32]))| {
            let z_start = bz * BLOCK;
            let z_end = ((bz + 1) * BLOCK).min(geometry.slices - 1);
            for z in z_start..=z_end {
                for y in 0..geometry.rows {
                    let by = y >> BLOCK_SHIFT;
                    // A row on a block boundary also belongs to the block above it.
                    let also_above = y > 0 && y % BLOCK == 0;
                    let row_offset = (z * geometry.rows + y) * geometry.cols;
                    let row = &geometry.samples[row_offset..row_offset + geometry.cols];
                    for bx in 0..nx {
                        let x_start = bx * BLOCK;
                        let x_end = ((bx + 1) * BLOCK).min(geometry.cols - 1);
                        let mut low = f32::INFINITY;
                        let mut high = f32::NEG_INFINITY;
                        for &value in &row[x_start..=x_end] {
                            low = low.min(value);
                            high = high.max(value);
                        }
                        let mut update = |index: usize| {
                            min_layer[index] = min_layer[index].min(low);
                            max_layer[index] = max_layer[index].max(high);
                        };
                        update(by * nx + bx);
                        if also_above {
                            update((by - 1) * nx + bx);
                        }
                    }
                }
            }
        };
        // Each layer also needs the first slice of the next layer (the +1 overlap), which
        // `z_end` already includes.
        #[cfg(not(target_arch = "wasm32"))]
        min.par_chunks_mut(per_layer)
            .zip(max.par_chunks_mut(per_layer))
            .enumerate()
            .for_each(fill_layer);
        #[cfg(target_arch = "wasm32")]
        min.chunks_mut(per_layer)
            .zip(max.chunks_mut(per_layer))
            .enumerate()
            .for_each(fill_layer);
        Self { nx, ny, min, max }
    }

    #[inline(always)]
    fn index(&self, base: [usize; 3]) -> usize {
        ((base[2] >> BLOCK_SHIFT) * self.ny + (base[1] >> BLOCK_SHIFT)) * self.nx
            + (base[0] >> BLOCK_SHIFT)
    }

    fn value_range(&self) -> (f32, f32) {
        let low = self.min.iter().copied().fold(f32::INFINITY, f32::min);
        let high = self.max.iter().copied().fold(f32::NEG_INFINITY, f32::max);
        (low, high)
    }
}

/// One ray, in uniform voxel-index space, clipped to the renderable region: samples at
/// `start + k * step` for `k in 0..count`.
struct Ray {
    start: [f32; 3],
    step: [f32; 3],
    count: usize,
    /// Unit world direction (for shading).
    direction: Vec3,
}

/// Camera + clip state shared by every ray of one render.
struct Caster<'a> {
    geometry: Geometry<'a>,
    params: &'a VolumeRenderParams,
    box_low: Vec3,
    box_high: Vec3,
    view_dir: Vec3,
    row_dir: Vec3,
    col_dir: Vec3,
    eye: Option<Vec3>,
}

impl<'a> Caster<'a> {
    fn new(volume: &'a Volume, params: &'a VolumeRenderParams) -> Result<Self, VolumeRenderError> {
        let geometry = Geometry::new(volume);
        let (box_low, box_high) = geometry.clip_box(params.crop_voxels.as_ref())?;
        validate_sample_budget(&geometry, box_low, box_high, params.step_mm)?;
        let row_dir = normalize3(params.row_dir);
        // Re-orthogonalize col against row so a slightly skewed caller basis still works.
        let col_dir = normalize3(sub3(
            params.col_dir,
            scale3(row_dir, dot3(params.col_dir, row_dir)),
        ));
        let view_dir = normalize3(cross3(row_dir, col_dir));
        let eye = params.perspective_fov_deg.map(|fov| {
            let half_height = params.output_height as f64 * params.spacing_mm / 2.0;
            let distance = half_height / (fov.to_radians() / 2.0).tan();
            sub3(params.center, scale3(view_dir, distance))
        });
        Ok(Self {
            geometry,
            params,
            box_low,
            box_high,
            view_dir,
            row_dir,
            col_dir,
            eye,
        })
    }

    fn ray(&self, px: usize, py: usize) -> Option<Ray> {
        let params = self.params;
        let half_width = params.output_width as f64 / 2.0;
        let half_height = params.output_height as f64 / 2.0;
        // Same pixel convention as `reformat_plane_values`: pixel (W/2, H/2) is the center.
        let pixel = add3(
            params.center,
            add3(
                scale3(self.row_dir, (px as f64 - half_width) * params.spacing_mm),
                scale3(self.col_dir, (py as f64 - half_height) * params.spacing_mm),
            ),
        );
        let (origin, direction, mut t_enter, mut t_exit) = match self.eye {
            Some(eye) => (eye, normalize3(sub3(pixel, eye)), 0.0, f64::INFINITY),
            None => (pixel, self.view_dir, f64::NEG_INFINITY, f64::INFINITY),
        };

        let index_origin = self.geometry.world_to_index(origin);
        let index_direction = self.geometry.direction_to_index(direction);
        for axis in 0..3 {
            clip_slab(
                index_origin[axis],
                index_direction[axis],
                self.box_low[axis],
                self.box_high[axis],
                &mut t_enter,
                &mut t_exit,
            )?;
        }
        if let Some(crop) = &params.crop_mm {
            for axis in 0..3 {
                clip_slab(
                    origin[axis],
                    direction[axis],
                    crop[axis * 2],
                    crop[axis * 2 + 1],
                    &mut t_enter,
                    &mut t_exit,
                )?;
            }
        }
        if !(t_exit >= t_enter) || !t_enter.is_finite() || !t_exit.is_finite() {
            return None;
        }

        // Samples sit on a fixed grid along the ray (planes parallel to the image in the
        // orthographic case), so neighboring rays sample consistent depths - no wood-grain.
        let step_mm = params.step_mm;
        let first = (t_enter / step_mm).ceil() * step_mm;
        if first > t_exit {
            return None;
        }
        // `validate_sample_budget` already bounds this; the `min` keeps the cast exact regardless.
        let count = ((t_exit - first) / step_mm)
            .floor()
            .min(MAX_VOLUME_RENDER_SAMPLES_PER_RAY as f64) as usize
            + 1;
        let start = add3(index_origin, scale3(index_direction, first));
        let step = scale3(index_direction, step_mm);
        Some(Ray {
            start: start.map(|v| v as f32),
            step: step.map(|v| v as f32),
            count,
            direction,
        })
    }
}

/// Narrows `[t_enter, t_exit]` to where `origin + t * direction` lies within `[low, high]` on one
/// axis; `None` when the ray misses.
fn clip_slab(
    origin: f64,
    direction: f64,
    low: f64,
    high: f64,
    t_enter: &mut f64,
    t_exit: &mut f64,
) -> Option<()> {
    if direction.abs() < 1e-12 {
        if origin < low || origin > high {
            return None;
        }
        return Some(());
    }
    let mut t0 = (low - origin) / direction;
    let mut t1 = (high - origin) / direction;
    if t0 > t1 {
        std::mem::swap(&mut t0, &mut t1);
    }
    *t_enter = t_enter.max(t0);
    *t_exit = t_exit.min(t1);
    if *t_enter > *t_exit {
        return None;
    }
    Some(())
}

/// How many whole steps along `step` (from `position`, whose clamped cell is `base`) it takes to
/// leave `base`'s block - at least 1. Only valid for a uniform (non-LUT) slice axis.
#[inline(always)]
fn steps_to_leave_block(base: [usize; 3], position: [f32; 3], step: [f32; 3]) -> usize {
    let mut steps = f32::INFINITY;
    for axis in 0..3 {
        let d = step[axis];
        let block_start = ((base[axis] >> BLOCK_SHIFT) << BLOCK_SHIFT) as f32;
        let to_exit = if d > 1e-9 {
            (block_start + BLOCK as f32 - position[axis]) / d
        } else if d < -1e-9 {
            // The cell's base drops below `block_start` once the position does.
            (position[axis] - block_start) / -d + 1e-4
        } else {
            continue;
        };
        steps = steps.min(to_exit);
    }
    if steps.is_finite() && steps > 1.0 {
        steps.ceil() as usize
    } else {
        1
    }
}

fn cast_projection(caster: &Caster<'_>, blocks: &BlockGrid, ray: &Ray) -> Option<f32> {
    let geometry = &caster.geometry;
    let nearest = caster.params.interpolation == Interpolation::Nearest;
    let can_jump = geometry.irregular.is_none();
    let [x0, y0, z0] = ray.start;
    let [dx, dy, dz] = ray.step;
    let mode = caster.params.mode;
    let mut best = match mode {
        VolumeRenderMode::MinimumIntensity => f32::INFINITY,
        _ => f32::NEG_INFINITY,
    };
    if ray.count == 0 {
        return None;
    }
    if mode == VolumeRenderMode::Average {
        let mut sum = 0.0f64;
        for i in 0..ray.count {
            let t = i as f32;
            let (base, frac) = geometry.cell(x0 + dx * t, y0 + dy * t, z0 + dz * t);
            sum += f64::from(geometry.sample_cell(base, frac, nearest));
        }
        return Some((sum / ray.count as f64) as f32);
    }
    let maximum = mode == VolumeRenderMode::MaximumIntensity;
    let mut i = 0usize;
    while i < ray.count {
        let t = i as f32;
        let position = [x0 + dx * t, y0 + dy * t, z0 + dz * t];
        let (base, frac) = geometry.cell(position[0], position[1], position[2]);
        let block = blocks.index(base);
        // A block whose range cannot beat the running extreme is skipped whole.
        let skip = if maximum {
            blocks.max[block] <= best
        } else {
            blocks.min[block] >= best
        };
        if skip {
            i += if can_jump {
                steps_to_leave_block(base, position, ray.step)
            } else {
                1
            };
            continue;
        }
        let value = geometry.sample_cell(base, frac, nearest);
        best = if maximum {
            best.max(value)
        } else {
            best.min(value)
        };
        i += 1;
    }
    Some(best)
}

const AMBIENT: f32 = 0.25;
const DIFFUSE: f32 = 0.75;
const SPECULAR: f32 = 0.3;
const SHININESS: i32 = 24;
const OPAQUE: f32 = 0.99;

fn cast_composite(
    caster: &Caster<'_>,
    blocks: &BlockGrid,
    lut: &TransferLut,
    transparent_blocks: &[bool],
    ray: &Ray,
) -> [f32; 4] {
    let geometry = &caster.geometry;
    let nearest = caster.params.interpolation == Interpolation::Nearest;
    let shading = caster.params.shading;
    let light = scale3(ray.direction, -1.0);
    let can_jump = geometry.irregular.is_none();
    let [x0, y0, z0] = ray.start;
    let [dx, dy, dz] = ray.step;
    let mut color = [0.0f32; 3];
    let mut alpha = 0.0f32;
    let mut i = 0usize;
    while i < ray.count {
        let t = i as f32;
        let (sx, sy, sz) = (x0 + dx * t, y0 + dy * t, z0 + dz * t);
        let (base, frac) = geometry.cell(sx, sy, sz);
        if transparent_blocks[blocks.index(base)] {
            i += if can_jump {
                steps_to_leave_block(base, [sx, sy, sz], ray.step)
            } else {
                1
            };
            continue;
        }
        i += 1;
        let value = geometry.sample_cell(base, frac, nearest);
        let [r, g, b, a] = lut.lookup(value);
        if a <= 0.0 {
            continue;
        }
        let mut sample_color = [r, g, b];
        if shading {
            let gradient = geometry.gradient_world(sx, sy, sz);
            let magnitude = norm3(gradient);
            if magnitude > 1e-6 {
                // Two-sided headlight: the light sits at the eye, so the half vector is the light.
                let n_dot_l = (dot3(gradient, light) / magnitude).abs() as f32;
                let diffuse = AMBIENT + DIFFUSE * n_dot_l;
                let specular = SPECULAR * n_dot_l.powi(SHININESS);
                sample_color = sample_color.map(|c| (c * diffuse + specular).min(1.0));
            }
        }
        let weight = (1.0 - alpha) * a;
        for k in 0..3 {
            color[k] += weight * sample_color[k];
        }
        alpha += weight;
        if alpha >= OPAQUE {
            break;
        }
    }
    [color[0], color[1], color[2], alpha]
}

/// Runs `per_pixel` for every output pixel, writing `channels` values per pixel, in parallel
/// over rows on native targets.
fn for_each_pixel<T: Copy + Send + Sync + Default>(
    width: usize,
    height: usize,
    channels: usize,
    per_pixel: impl Fn(usize, usize, &mut [T]) + Send + Sync,
) -> Vec<T> {
    let mut out = vec![T::default(); width * height * channels];
    let row_len = width * channels;
    let fill_row = |(py, row): (usize, &mut [T])| {
        for px in 0..width {
            per_pixel(px, py, &mut row[px * channels..(px + 1) * channels]);
        }
    };
    #[cfg(not(target_arch = "wasm32"))]
    out.par_chunks_mut(row_len).enumerate().for_each(fill_row);
    #[cfg(target_arch = "wasm32")]
    out.chunks_mut(row_len).enumerate().for_each(fill_row);
    out
}

fn validate_params(params: &VolumeRenderParams) -> Result<(), VolumeRenderError> {
    validate_output_dimensions(params.output_width, params.output_height)?;
    if !(params.spacing_mm > 0.0) || !params.spacing_mm.is_finite() {
        return Err(invalid("the output spacing must be greater than zero"));
    }
    if !(params.step_mm > 0.0) || !params.step_mm.is_finite() {
        return Err(invalid("the sample step must be greater than zero"));
    }
    if norm3(cross3(params.row_dir, params.col_dir)) < 1e-6 {
        return Err(invalid(
            "the camera row and column directions must not be parallel",
        ));
    }
    if let Some(fov) = params.perspective_fov_deg {
        if !(fov > 0.0 && fov < 180.0) {
            return Err(invalid(
                "the perspective field of view must be between 0 and 180 degrees (exclusive)",
            ));
        }
    }
    Ok(())
}

/// Casts the grayscale projection modes (MIP, MinIP, average) and returns the RAW projected
/// values (e.g. HU) row-major, `output_width * output_height` long - no windowing. Rays that miss
/// the (cropped) volume take the smallest projected value, the same background convention as
/// `reformat_plane_values`. Composite mode has no scalar result and is rejected.
pub fn render_volume_values(
    volume: &Volume,
    params: &VolumeRenderParams,
) -> Result<Vec<f32>, VolumeRenderError> {
    validate_params(params)?;
    if params.mode == VolumeRenderMode::Composite {
        return Err(invalid(
            "composite volume rendering produces colors, not values; use render_volume_pixels",
        ));
    }
    let caster = Caster::new(volume, params)?;
    let blocks = BlockGrid::new(&caster.geometry);
    let values: Vec<f32> = for_each_pixel(
        params.output_width as usize,
        params.output_height as usize,
        1,
        |px, py, out: &mut [f32]| {
            out[0] = caster
                .ray(px, py)
                .and_then(|ray| cast_projection(&caster, &blocks, &ray))
                .unwrap_or(f32::NAN);
        },
    );
    let background = values
        .iter()
        .copied()
        .filter(|value| !value.is_nan())
        .fold(f32::INFINITY, f32::min);
    let background = if background.is_finite() {
        background
    } else {
        0.0
    };
    Ok(values
        .into_iter()
        .map(|value| if value.is_nan() { background } else { value })
        .collect())
}

/// A rendered image: 8-bit grayscale (`samples_per_pixel == 1`, the projection modes, windowed)
/// or RGBA with straight (non-premultiplied) alpha (`samples_per_pixel == 4`, composite).
#[derive(Clone, Debug)]
pub struct VolumeRenderPixels {
    pub width: u32,
    pub height: u32,
    pub samples_per_pixel: u16,
    pub pixels: Vec<u8>,
}

impl VolumeRenderPixels {
    /// Expands to RGBA (grayscale gets alpha 255), e.g. for a canvas `ImageData`.
    pub fn to_rgba(&self) -> Vec<u8> {
        match self.samples_per_pixel {
            4 => self.pixels.clone(),
            _ => self
                .pixels
                .iter()
                .flat_map(|&value| [value, value, value, 255])
                .collect(),
        }
    }

    /// Flattens onto an opaque `background`: grayscale stays grayscale, RGBA becomes RGB.
    pub fn flatten(&self, background: [u8; 3]) -> (u16, Vec<u8>) {
        match self.samples_per_pixel {
            4 => (
                3,
                self.pixels
                    .chunks_exact(4)
                    .flat_map(|pixel| {
                        let alpha = f32::from(pixel[3]) / 255.0;
                        [0, 1, 2].map(|k| {
                            (f32::from(pixel[k]) * alpha + f32::from(background[k]) * (1.0 - alpha))
                                .round()
                                .clamp(0.0, 255.0) as u8
                        })
                    })
                    .collect(),
            ),
            spp => (spp, self.pixels.clone()),
        }
    }
}

/// Renders `volume` to 8-bit pixels: windowed grayscale for MIP/MinIP/average (like
/// `reformat_plane_pixels`), straight-alpha RGBA for composite.
pub fn render_volume_pixels(
    volume: &Volume,
    params: &VolumeRenderParams,
) -> Result<VolumeRenderPixels, VolumeRenderError> {
    validate_params(params)?;
    let width = params.output_width as usize;
    let height = params.output_height as usize;
    if params.mode != VolumeRenderMode::Composite {
        let values = render_volume_values(volume, params)?;
        let filled: Vec<f64> = values.into_iter().map(f64::from).collect();
        return Ok(VolumeRenderPixels {
            width: params.output_width,
            height: params.output_height,
            samples_per_pixel: 1,
            pixels: apply_explicit_window(&filled, params.window_center, params.window_width),
        });
    }

    let function = params
        .transfer_function
        .clone()
        .unwrap_or_else(|| TransferFunction::default_for_modality(volume.modality.as_deref()));
    let caster = Caster::new(volume, params)?;
    let blocks = BlockGrid::new(&caster.geometry);
    let (data_min, data_max) = blocks.value_range();
    let lut = TransferLut::new(
        &function,
        f64::from(data_min),
        f64::from(data_max),
        params.step_mm,
    );
    let transparent_blocks: Vec<bool> = blocks
        .min
        .iter()
        .zip(&blocks.max)
        .map(|(&low, &high)| low > high || lut.transparent_between(low, high))
        .collect();
    let pixels: Vec<u8> = for_each_pixel(width, height, 4, |px, py, out: &mut [u8]| {
        let Some(ray) = caster.ray(px, py) else {
            return;
        };
        let [r, g, b, a] = cast_composite(&caster, &blocks, &lut, &transparent_blocks, &ray);
        if a <= 0.0 {
            return;
        }
        // Straight alpha: un-premultiply the accumulated color.
        let to_byte = |value: f32| (value * 255.0).round().clamp(0.0, 255.0) as u8;
        out[0] = to_byte(r / a);
        out[1] = to_byte(g / a);
        out[2] = to_byte(b / a);
        out[3] = to_byte(a);
    });
    Ok(VolumeRenderPixels {
        width: params.output_width,
        height: params.output_height,
        samples_per_pixel: 4,
        pixels,
    })
}

/// Renders `volume` and encodes it like a normal 2D render (`RenderFrameOutput`, PNG / JPEG /
/// raw): grayscale for the projection modes, RGB composited over `params.background` for
/// composite.
pub fn render_volume(
    volume: &Volume,
    params: &VolumeRenderParams,
    output_format: RenderOutputFormat,
    jpeg_quality: u8,
) -> Result<RenderFrameOutput, VolumeRenderError> {
    let rendered = render_volume_pixels(volume, params)?;
    let (samples_per_pixel, bytes) = rendered.flatten(params.background);
    let frame = RenderedFramePixels {
        width: rendered.width as u16,
        height: rendered.height as u16,
        samples_per_pixel,
        bytes,
    };
    Ok(encode_rendered_frame(&frame, output_format, jpeg_quality)?)
}

// ---------------------------------------------------------------------------------------------
// Small vector helpers (volume.rs keeps its own private copies)
// ---------------------------------------------------------------------------------------------

fn dot3(a: Vec3, b: Vec3) -> f64 {
    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}

fn cross3(a: Vec3, b: Vec3) -> Vec3 {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}

fn sub3(a: Vec3, b: Vec3) -> Vec3 {
    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}

fn add3(a: Vec3, b: Vec3) -> Vec3 {
    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}

fn scale3(a: Vec3, s: f64) -> Vec3 {
    [a[0] * s, a[1] * s, a[2] * s]
}

fn norm3(a: Vec3) -> f64 {
    dot3(a, a).sqrt()
}

fn normalize3(a: Vec3) -> Vec3 {
    let length = norm3(a).max(1e-12);
    scale3(a, 1.0 / length)
}