primase-foundations 0.3.6

Checked byte readers, game-file hashes, vertex decoding, texture sampling and the compression codecs (LZ4, deflate, zstd, LZMA, Brotli, LZO2A, Oodle) game files use
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
//! Sampling a decoded texture: each policy the caller's, stated. Bilinear filtering between texel centres (a texel
//! `i` covering `[i, i + 1)`, `uv` scaled by the level's size, minus a half), each axis's address mode (a border reads
//! the colour the caller states, [`Addressing`]), the colour's
//! transfer before filtering, at a level the caller picks. Two precisions, each a fixed order of operations: f64
//! ([`Levels::bilinear`]) and f32 over texels decoded once ([`Decoded::bilinear`]). The texel a coordinate falls in
//! ([`Levels::point`], [`Decoded::point`]). A level of detail from a sample's footprint ([`footprint_lod`]), and the
//! two levels around it mixed ([`Levels::trilinear`]) or the nearest one taken ([`Levels::nearest_level`]).
//!
//! [`Decoded`] is one level of float texels, 2D or 3D: an RGBA8 level decoded once ([`Levels::decoded`]), or texels a
//! caller holds as floats ([`Decoded::from_texels`], [`Decoded::volume`]). A volume filters linearly between the eight
//! texels about a coordinate ([`Decoded::linear_3d`]) or takes the one it falls in ([`Decoded::point_3d`]).

use crate::color::srgb8_to_linear;

/// Why a sample or a texture's levels are refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
    /// The texture or coordinate is invalid; the message says how.
    #[error("invalid image: {0}")]
    Invalid(String),
}

/// A result with this module's [`Error`].
pub type Result<T> = std::result::Result<T, Error>;

/// Where a texel index outside the texture reads (the address modes of Direct3D's `D3D11_TEXTURE_ADDRESS_MODE`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Address {
    /// Repeats the texture.
    Wrap,
    /// The edge texel.
    Clamp,
    /// Repeats the texture, every other copy mirrored.
    Mirror,
    /// Mirrored once about the origin, then the edge texel.
    MirrorOnce,
    /// No texel: an index outside the texture reads the border colour ([`Addressing::border`]).
    Border,
}

impl Address {
    /// The texel index `i` reads along an axis of `size` texels, or none where it is outside a border axis.
    fn index(self, i: i64, size: u32) -> Option<usize> {
        let n = i64::from(size.max(1));
        let (last, period) = (n.saturating_sub(1), n.saturating_mul(2));
        let at = match self {
            Address::Wrap => i.rem_euclid(n),
            Address::Clamp => i.clamp(0, last),
            // texel -1 is texel 0 mirrored, -2 is 1, ...: the pattern 0 1 .. n-1 n-1 .. 0 repeats every 2n texels
            Address::Mirror => {
                let m = i.rem_euclid(period);
                if m < n {
                    m
                } else {
                    period.saturating_sub(1).saturating_sub(m)
                }
            }
            // mirrored once about the origin (-1 reads 0, -2 reads 1, ...), then the edge texel
            Address::MirrorOnce => (if i < 0 { (-1i64).saturating_sub(i) } else { i }).clamp(0, last),
            Address::Border if (0..n).contains(&i) => i,
            Address::Border => return None,
        };
        // every arm lands in 0..n, and n is a u32
        Some(usize::try_from(at).unwrap_or_default())
    }
}

/// How a sample addresses a texture: each axis's [`Address`], and the colour an index outside the texture reads along
/// a [`Address::Border`] axis. An array of addresses is addressing with no border colour (`[Address::Clamp; 2].into()`),
/// so every filter takes either.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Addressing<const N: usize> {
    /// The address mode of each axis (u, v, then w).
    pub axes: [Address; N],
    /// The colour (red, green, blue, alpha) a border reads: a value of the filtered domain, taken as it is (the
    /// [`Transfer`] decodes stored texels, not this). A sample with a border axis and no colour is refused.
    pub border: Option<[f32; 4]>,
}

impl<const N: usize> From<[Address; N]> for Addressing<N> {
    fn from(axes: [Address; N]) -> Addressing<N> {
        Addressing { axes, border: None }
    }
}

impl<const N: usize> Addressing<N> {
    /// `axes`, a border reading `border`.
    pub fn bordered(axes: [Address; N], border: [f32; 4]) -> Addressing<N> {
        Addressing {
            axes,
            border: Some(border),
        }
    }

    /// The colour a border reads, checked once per sample: a border axis with no colour, or a colour that isn't finite,
    /// is refused. Zero where no axis is a border (no index then reads it).
    fn border_colour(&self) -> Result<[f32; 4]> {
        match self.border {
            Some(c) if c.iter().any(|v| !v.is_finite()) => Err(Error::Invalid(format!(
                "sampled texture: border colour {c:?} is not finite"
            ))),
            Some(c) => Ok(c),
            None if self.axes.contains(&Address::Border) => Err(Error::Invalid(
                "sampled texture: border addressing with no border colour".into(),
            )),
            None => Ok([0.0; 4]),
        }
    }

    /// The texel indices `at` reads in a texture of `size` texels along each axis, or none where one is outside a
    /// border axis.
    fn indices(&self, at: [i64; N], size: [u32; N]) -> Option<[usize; N]> {
        let mut out = [0usize; N];
        for (o, ((a, i), n)) in out.iter_mut().zip(self.axes.iter().zip(at).zip(size)) {
            *o = a.index(i, n)?;
        }
        Some(out)
    }
}

/// A texel channel's value before filtering.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transfer {
    /// `x / 255`.
    Stored,
    /// Red, green and blue decoded from sRGB to linear (as a GPU's sRGB view), alpha `x / 255`.
    SrgbColour,
}

impl Transfer {
    /// Channel `c` (0-3: red, green, blue, alpha) of a texel stored as `byte`, before filtering, in f64.
    pub fn channel(self, c: usize, byte: u8) -> f64 {
        match self {
            Transfer::SrgbColour if c < 3 => srgb8_to_linear(byte),
            _ => f64::from(byte) / 255.0,
        }
    }
}

/// An RGBA8 texture's mip levels, each stored row by row, four bytes a texel. Level `n` is the base size halved `n`
/// times (at least 1); [`Levels::size`] gives it.
#[derive(Clone, Debug)]
pub struct Levels {
    /// The base level's width in texels.
    pub width: u32,
    /// The base level's height in texels.
    pub height: u32,
    /// The RGBA8 bytes of each level, base level first. The fields are public, so the sampling methods check the
    /// level they read: one that is missing, or does not hold exactly its [`Levels::size`] in texels, is refused.
    pub levels: Vec<Vec<u8>>,
}

impl Levels {
    /// One level of RGBA8 texels.
    pub fn one(width: u32, height: u32, rgba: Vec<u8>) -> Result<Levels> {
        let count = (width as usize)
            .checked_mul(height as usize)
            .filter(|&n| n > 0)
            .ok_or_else(|| Error::Invalid("sampled texture: invalid dimensions".into()))?;
        if count.checked_mul(4) != Some(rgba.len()) {
            return Err(Error::Invalid("sampled texture: RGBA length mismatch".into()));
        }
        Ok(Levels {
            width,
            height,
            levels: vec![rgba],
        })
    }

    /// Each level's rows in reverse order, for a texture stored bottom row first when row 0 is wanted at v = 0:
    /// addressing then applies about that texture's own origin. A level that isn't its size's whole rows is refused.
    pub fn rows_reversed(mut self) -> Result<Levels> {
        for i in 0..self.levels.len() {
            let row = self.level(i)?.row_bytes;
            let Some(level) = self.levels.get_mut(i) else {
                continue;
            };
            *level = level.chunks_exact(row).rev().flatten().copied().collect();
        }
        Ok(self)
    }

    /// Level `level`'s size: the base halved per level, at least 1.
    pub fn size(&self, level: usize) -> (u32, u32) {
        let s = u32::try_from(level).unwrap_or(31);
        (
            (self.width >> s.min(31)).max(1),
            (self.height >> s.min(31)).max(1),
        )
    }

    /// Level `level`'s bytes if it is stored and holds exactly its size's texels, else refused.
    fn level(&self, level: usize) -> Result<Level<'_>> {
        let (w, h) = self.size(level);
        let bytes = self.levels.get(level).ok_or_else(|| {
            Error::Invalid(format!(
                "sampled texture: level {level} requested, expected one of the {} stored levels",
                self.levels.len()
            ))
        })?;
        let row_bytes = (w as usize).checked_mul(4);
        let want = row_bytes.and_then(|r| r.checked_mul(h as usize));
        match (row_bytes, want) {
            (Some(row_bytes), Some(want)) if want == bytes.len() && want > 0 => Ok(Level {
                bytes,
                row_bytes,
                width: w,
                height: h,
            }),
            _ => Err(Error::Invalid(format!(
                "sampled texture: level {level} holds {} bytes, expected {h} rows of {w} RGBA8 texels",
                bytes.len()
            ))),
        }
    }

    /// The texel at (x, y) of level `level`, addressed by `address`. A level that is not stored, or does not hold
    /// its size's bytes, is refused, as is a coordinate outside a [`Address::Border`] axis (it reads no stored texel).
    pub fn texel(&self, level: usize, x: i64, y: i64, address: [Address; 2]) -> Result<[u8; 4]> {
        self.level(level)?
            .texel(x, y, &Addressing::from(address))?
            .ok_or_else(|| {
                Error::Invalid(format!(
                    "sampled texture: texel ({x}, {y}) is outside a border axis"
                ))
            })
    }

    /// Bilinear at `uv` of level `level`, in f64: weights `(1 - tx)(1 - ty)`, `tx (1 - ty)`, `(1 - tx) ty`, `tx ty`
    /// summed in that order, a texel outside a border axis the border colour. A coordinate that isn't finite or past an
    /// i32's range is refused, as is a border axis with no colour ([`Addressing::border`]).
    pub fn bilinear(
        &self,
        level: usize,
        uv: [f64; 2],
        address: impl Into<Addressing<2>>,
        transfer: Transfer,
    ) -> Result<[f64; 4]> {
        let address: Addressing<2> = address.into();
        let border = address.border_colour()?;
        let (w, h) = self.size(level);
        let level = self.level(level)?;
        let (x, y) = texel_coordinate([uv[0] * f64::from(w) - 0.5, uv[1] * f64::from(h) - 0.5])?;
        let (fx, fy) = (x.floor(), y.floor());
        let (tx, ty) = (x - fx, y - fy);
        let (ix, iy) = (floor_f64(fx), floor_f64(fy));
        let mut out = [0.0; 4];
        for (dx, dy, wt) in [
            (0, 0, (1.0 - tx) * (1.0 - ty)),
            (1, 0, tx * (1.0 - ty)),
            (0, 1, (1.0 - tx) * ty),
            (1, 1, tx * ty),
        ] {
            let t = level.texel(ix.saturating_add(dx), iy.saturating_add(dy), &address)?;
            for (c, o) in out.iter_mut().enumerate() {
                *o += wt * texel_channel(t, c, transfer, border);
            }
        }
        Ok(out)
    }

    /// The texel of level `level` that `uv` falls in (texel `i` covering `[i, i + 1)` after scaling by the level's
    /// size), in f64: point filtering; outside a border axis, the border colour. A coordinate that isn't finite or past
    /// an i32's range is refused, as is a border axis with no colour.
    pub fn point(
        &self,
        level: usize,
        uv: [f64; 2],
        address: impl Into<Addressing<2>>,
        transfer: Transfer,
    ) -> Result<[f64; 4]> {
        let address: Addressing<2> = address.into();
        let border = address.border_colour()?;
        let (w, h) = self.size(level);
        let level = self.level(level)?;
        let (x, y) = texel_coordinate([uv[0] * f64::from(w), uv[1] * f64::from(h)])?;
        let t = level.texel(floor_f64(x), floor_f64(y), &address)?;
        Ok(std::array::from_fn(|c| texel_channel(t, c, transfer, border)))
    }

    /// Level `level` decoded once to f32 by `transfer`, for [`Decoded::bilinear`]. A level that is not stored, or does
    /// not hold its size's bytes, is refused.
    pub fn decoded(&self, level: usize, transfer: Transfer) -> Result<Decoded> {
        let l = self.level(level)?;
        let texels = l
            .bytes
            .as_chunks::<4>()
            .0
            .iter()
            .map(|p| {
                let mut texel = [0f32; 4];
                for (c, (out, &byte)) in texel.iter_mut().zip(p).enumerate() {
                    *out = match transfer {
                        Transfer::SrgbColour if c < 3 => to_f32(srgb8_to_linear(byte)),
                        _ => f32::from(byte) / 255.0,
                    };
                }
                texel
            })
            .collect();
        Ok(Decoded {
            width: l.width,
            height: l.height,
            depth: 1,
            texels,
        })
    }
}

/// One stored level that holds exactly its size's texels (checked by [`Levels::level`]).
struct Level<'a> {
    bytes: &'a [u8],
    row_bytes: usize,
    width: u32,
    height: u32,
}

/// Channel `c` of a stored texel through `transfer`, or of the border colour where the texel is outside a border axis.
fn texel_channel(texel: Option<[u8; 4]>, c: usize, transfer: Transfer, border: [f32; 4]) -> f64 {
    match texel {
        Some(t) => transfer.channel(c, t.get(c).copied().unwrap_or_default()),
        None => f64::from(border.get(c).copied().unwrap_or_default()),
    }
}

impl Level<'_> {
    /// The stored texel at addressed (x, y), or none where it is outside a border axis.
    fn texel(&self, x: i64, y: i64, address: &Addressing<2>) -> Result<Option<[u8; 4]>> {
        let Some([x, y]) = address.indices([x, y], [self.width, self.height]) else {
            return Ok(None);
        };
        let i = y
            .checked_mul(self.row_bytes)
            .and_then(|row| row.checked_add(x.checked_mul(4)?));
        i.and_then(|i| self.bytes.get(i..)?.first_chunk::<4>())
            .copied()
            .map(Some)
            .ok_or_else(|| {
                Error::Invalid(format!(
                    "sampled texture: texel ({x}, {y}) outside the level's {} bytes",
                    self.bytes.len()
                ))
            })
    }
}

/// A texel coordinate `[x, y]` that is finite and within an i32's range, else refused.
fn texel_coordinate([x, y]: [f64; 2]) -> Result<(f64, f64)> {
    if !x.is_finite() || !y.is_finite() || x.abs() >= 2147483520.0 || y.abs() >= 2147483520.0 {
        return Err(Error::Invalid(
            "sampled texture: nonfinite or excessive texel coordinate".into(),
        ));
    }
    Ok((x, y))
}

/// The level of detail of a footprint: the UV's screen derivatives `gradients` (d/dx, then d/dy) in texels of a
/// `width` x `height` base level, the longer one's base-2 logarithm (Direct3D's isotropic rule), plus `bias`. A
/// footprint of no extent gives negative infinity (the finest level, whatever the bias).
pub fn footprint_lod(width: u32, height: u32, gradients: [[f64; 2]; 2], bias: f64) -> f64 {
    let texels = |d: [f64; 2]| (d[0] * f64::from(width)).hypot(d[1] * f64::from(height));
    texels(gradients[0]).max(texels(gradients[1])).log2() + bias
}

impl Levels {
    /// Trilinear at `uv`: the level of detail `lod` clamped to the stored levels, the bilinear values
    /// ([`Levels::bilinear`]) of the level below it and the next mixed by its fraction (`a + (b - a) f`); a level
    /// of detail that isn't a number, or a coordinate or addressing [`Levels::bilinear`] refuses, is refused.
    pub fn trilinear(
        &self,
        uv: [f64; 2],
        lod: f64,
        address: impl Into<Addressing<2>>,
        transfer: Transfer,
    ) -> Result<[f64; 4]> {
        let address: Addressing<2> = address.into();
        if lod.is_nan() {
            return Err(Error::Invalid(
                "sampled texture: a level of detail that isn't a number".into(),
            ));
        }
        let last = self.levels.len().saturating_sub(1);
        let lod = lod.clamp(0.0, last as f64);
        let below = lod.floor();
        let (l0, f) = (level_number(below), lod - below);
        let a = self.bilinear(l0, uv, address, transfer)?;
        if f == 0.0 {
            return Ok(a);
        }
        let b = self.bilinear(l0.saturating_add(1).min(last), uv, address, transfer)?;
        let mut mixed = [0.0; 4];
        for (m, (a, b)) in mixed.iter_mut().zip(a.into_iter().zip(b)) {
            *m = a + (b - a) * f;
        }
        Ok(mixed)
    }

    /// The stored level nearest the level of detail `lod`, as a point mip filter picks it: `floor(lod + 0.5)` (a half
    /// rounds up), clamped to the stored levels. A level of detail that isn't a number is refused.
    pub fn nearest_level(&self, lod: f64) -> Result<usize> {
        if lod.is_nan() {
            return Err(Error::Invalid(
                "sampled texture: a level of detail that isn't a number".into(),
            ));
        }
        let last = self.levels.len().saturating_sub(1);
        Ok(level_number((lod + 0.5).floor().clamp(0.0, last as f64)))
    }
}

/// How finely a bilinear filter resolves where a sample falls between texels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Subtexel {
    /// The position in f32, as computed.
    Exact,
    /// Direct3D 11's filtering: the texel coordinate (after scaling by the texture's size) truncated to 8 fractional
    /// bits, 256 subdivisions of a texel, before the weights are taken. The D3D11.3 functional specification requires
    /// at least 8 bits of sub-texel precision (7.18.16.1, Texture Addressing and LOD Precision;
    /// `D3D11_SUBTEXEL_FRACTIONAL_BIT_COUNT` = 8). Microsoft's WARP software rasterizer truncates at 8, as measured
    /// against it.
    D3d11,
}

impl Subtexel {
    /// `x` resolved to this precision: unchanged, or truncated to 1/256.
    fn resolve(self, x: f32) -> f32 {
        match self {
            Subtexel::Exact => x,
            Subtexel::D3d11 => (x * 256.).floor() / 256.,
        }
    }
}

/// One level's texels in f32, their transfer applied: a 2D level (`depth` 1) or a volume, row by row and slice by
/// slice.
#[derive(Clone, Debug)]
pub struct Decoded {
    width: u32,
    height: u32,
    depth: u32,
    texels: Vec<[f32; 4]>,
}

/// A texel coordinate in f32 that is finite and within an i32's range, else refused.
fn texel_coordinate_f32(x: f32) -> Result<f32> {
    if !x.is_finite() || x.abs() >= 2147483520.0 {
        return Err(Error::Invalid(
            "sampled texture: nonfinite or excessive texel coordinate".into(),
        ));
    }
    Ok(x)
}

impl Decoded {
    /// A 2D level of `width` x `height` float texels, row 0 first, as the caller holds them (no transfer: the values
    /// are filtered as they are). No texel, or a count other than the size's, is refused.
    pub fn from_texels(width: u32, height: u32, texels: Vec<[f32; 4]>) -> Result<Decoded> {
        Decoded::volume(width, height, 1, texels)
    }

    /// A volume of `width` x `height` x `depth` float texels, slice 0 first and each slice row 0 first. No texel, or a
    /// count other than the size's, is refused.
    pub fn volume(width: u32, height: u32, depth: u32, texels: Vec<[f32; 4]>) -> Result<Decoded> {
        let count = (width as usize)
            .checked_mul(height as usize)
            .and_then(|n| n.checked_mul(depth as usize))
            .filter(|&n| n > 0)
            .ok_or_else(|| Error::Invalid("sampled texture: invalid dimensions".into()))?;
        if texels.len() != count {
            return Err(Error::Invalid(format!(
                "sampled texture: {} texels for {width} x {height} x {depth}",
                texels.len()
            )));
        }
        Ok(Decoded {
            width,
            height,
            depth,
            texels,
        })
    }

    /// The level's `[width, height]` in texels.
    pub fn dimensions(&self) -> [usize; 2] {
        [self.width as usize, self.height as usize]
    }
    /// The slices of a volume: 1 for a 2D level.
    pub fn depth(&self) -> usize {
        self.depth as usize
    }
    /// The memory the decoded texels take, in bytes (16 a texel).
    pub fn decoded_bytes(&self) -> usize {
        self.texels.len().saturating_mul(16)
    }

    /// The texel at (x, y, z) if the level holds one there.
    fn get(&self, x: usize, y: usize, z: usize) -> Option<[f32; 4]> {
        let index = z
            .checked_mul(self.height as usize)?
            .checked_add(y)?
            .checked_mul(self.width as usize)?
            .checked_add(x)?;
        self.texels.get(index).copied()
    }

    /// The texel at (x, y, z), if the level holds one there: no addressing, a load's view of the level.
    pub fn texel(&self, x: i64, y: i64, z: i64) -> Option<[f32; 4]> {
        let inside = |i: i64, n: u32| usize::try_from(i).ok().filter(|&i| i < n as usize);
        self.get(
            inside(x, self.width)?,
            inside(y, self.height)?,
            inside(z, self.depth)?,
        )
    }

    /// The texel at addressed (x, y, z): addressing reduces each into the level, so a miss means the texels do not
    /// match the size, which the constructors rule out.
    fn at(&self, x: usize, y: usize, z: usize) -> Result<[f32; 4]> {
        self.get(x, y, z).ok_or_else(|| {
            Error::Invalid(format!(
                "sampled texture: texel ({x}, {y}, {z}) outside the {} texels of a {} x {} x {} level",
                self.texels.len(),
                self.width,
                self.height,
                self.depth
            ))
        })
    }

    /// A 2D sample of a volume is refused: which slice it reads is not the level's to say.
    fn plane(&self) -> Result<()> {
        if self.depth == 1 {
            Ok(())
        } else {
            Err(Error::Invalid(format!(
                "sampled texture: a 2D sample of a volume of {} slices",
                self.depth
            )))
        }
    }

    /// Bilinear at `uv`, in f32 (the coordinate, the weights `(1 - t)` and `t` per axis, and the sum over the four
    /// texels row by row), a texel outside a border axis the border colour; a coordinate that isn't finite or past an
    /// i32's range is refused, as is a border axis with no colour.
    pub fn bilinear(&self, uv: [f32; 2], address: impl Into<Addressing<2>>) -> Result<[f32; 4]> {
        self.bilinear_at(uv, address, Subtexel::Exact)
    }
    /// [`Decoded::bilinear`] with the texel coordinate resolved to `subtexel` precision before the weights are taken.
    pub fn bilinear_at(
        &self,
        uv: [f32; 2],
        address: impl Into<Addressing<2>>,
        subtexel: Subtexel,
    ) -> Result<[f32; 4]> {
        let address: Addressing<2> = address.into();
        let border = address.border_colour()?;
        self.plane()?;
        let [u, v] = uv;
        let x = texel_coordinate_f32(subtexel.resolve(u * self.width as f32 - 0.5))?;
        let y = texel_coordinate_f32(subtexel.resolve(v * self.height as f32 - 0.5))?;
        let (ix, iy) = (floor_f32(x), floor_f32(y));
        let (tx, ty) = (x - ix as f32, y - iy as f32);
        let mut result = [0.; 4];
        for dy in 0..2 {
            for dx in 0..2 {
                let weight = (if dx == 1 { tx } else { 1. - tx }) * (if dy == 1 { ty } else { 1. - ty });
                let texel = match address.indices(
                    [ix.saturating_add(dx), iy.saturating_add(dy)],
                    [self.width, self.height],
                ) {
                    Some([xx, yy]) => self.at(xx, yy, 0)?,
                    None => border,
                };
                for (out, t) in result.iter_mut().zip(texel) {
                    *out += t * weight;
                }
            }
        }
        Ok(result)
    }

    /// The texel `uv` falls in (texel `i` covering `[i, i + 1)` after scaling by the size), addressed, in f32: point
    /// filtering; outside a border axis, the border colour. A coordinate that isn't finite or past an i32's range is
    /// refused, as is a border axis with no colour.
    pub fn point(&self, uv: [f32; 2], address: impl Into<Addressing<2>>) -> Result<[f32; 4]> {
        let address: Addressing<2> = address.into();
        let border = address.border_colour()?;
        self.plane()?;
        let [u, v] = uv;
        let x = texel_coordinate_f32(u * self.width as f32)?;
        let y = texel_coordinate_f32(v * self.height as f32)?;
        match address.indices([floor_f32(x), floor_f32(y)], [self.width, self.height]) {
            Some([xx, yy]) => self.at(xx, yy, 0),
            None => Ok(border),
        }
    }

    /// The texel of a volume (or a 2D level, one slice) that `uvw` falls in, addressed along each axis, in f32; outside
    /// a border axis, the border colour.
    pub fn point_3d(&self, uvw: [f32; 3], address: impl Into<Addressing<3>>) -> Result<[f32; 4]> {
        let address: Addressing<3> = address.into();
        let border = address.border_colour()?;
        let [u, v, w] = uvw;
        let axis = |c: f32, n: u32| -> Result<i64> { Ok(floor_f32(texel_coordinate_f32(c * n as f32)?)) };
        let at = [axis(u, self.width)?, axis(v, self.height)?, axis(w, self.depth)?];
        match address.indices(at, [self.width, self.height, self.depth]) {
            Some([x, y, z]) => self.at(x, y, z),
            None => Ok(border),
        }
    }

    /// Linear between the eight texels about `uvw` in a volume, in f32: the coordinate per axis (scaled by the size,
    /// minus a half, resolved to `subtexel` precision), the weights `(1 - t)` and `t` per axis multiplied x, then y,
    /// then z, and the sum over the texels slice by slice, row by row. A coordinate that isn't finite or past an i32's
    /// range is refused.
    pub fn linear_3d(
        &self,
        uvw: [f32; 3],
        address: impl Into<Addressing<3>>,
        subtexel: Subtexel,
    ) -> Result<[f32; 4]> {
        let address: Addressing<3> = address.into();
        let border = address.border_colour()?;
        let [u, v, w] = uvw;
        let (sw, sh, sd) = (self.width, self.height, self.depth);
        let axis = |c: f32, n: u32| -> Result<(i64, f32)> {
            let t = texel_coordinate_f32(subtexel.resolve(c * n as f32 - 0.5))?;
            let base = floor_f32(t);
            Ok((base, t - base as f32))
        };
        let ((bx, tx), (by, ty), (bz, tz)) = (axis(u, sw)?, axis(v, sh)?, axis(w, sd)?);
        let weight = |d: i64, t: f32| if d == 1 { t } else { 1. - t };
        let mut result = [0.; 4];
        for dz in 0..2 {
            for dy in 0..2 {
                for dx in 0..2 {
                    let texel = match address.indices(
                        [
                            bx.saturating_add(dx),
                            by.saturating_add(dy),
                            bz.saturating_add(dz),
                        ],
                        [sw, sh, sd],
                    ) {
                        Some([x, y, z]) => self.at(x, y, z)?,
                        None => border,
                    };
                    let wt = weight(dx, tx) * weight(dy, ty) * weight(dz, tz);
                    for (out, t) in result.iter_mut().zip(texel) {
                        *out += t * wt;
                    }
                }
            }
        }
        Ok(result)
    }
}

/// The floor of an f32 coordinate that [`texel_coordinate_f32`] has checked to lie within an i32's range.
#[allow(
    clippy::cast_possible_truncation,
    reason = "the caller checked the coordinate is finite and within an i32's range"
)]
fn floor_f32(x: f32) -> i64 {
    x.floor() as i64
}

/// The floor of an f64 coordinate that [`texel_coordinate`] has checked to lie within an i32's range.
#[allow(
    clippy::cast_possible_truncation,
    reason = "the caller checked the coordinate is finite and within an i32's range"
)]
fn floor_f64(x: f64) -> i64 {
    x.floor() as i64
}

/// A decoded sRGB value narrowed to the f32 a decoded texel holds.
#[allow(
    clippy::cast_possible_truncation,
    reason = "rounding the f64 curve value to the f32 texel is the documented decode"
)]
fn to_f32(x: f64) -> f32 {
    x as f32
}

/// A level number from a level of detail already clamped to `0..=last`.
#[allow(
    clippy::cast_possible_truncation,
    reason = "the caller clamped the value to a stored level number"
)]
fn level_number(lod: f64) -> usize {
    lod as usize
}

#[cfg(test)]
#[allow(clippy::unwrap_used, reason = "test fixtures")]
mod tests {
    use super::*;

    /// Texel indices out of range, worked by hand for four texels: repeat, mirrored repeat (-1 reads 0, 4 reads 3, the
    /// pattern 0 1 2 3 3 2 1 0 repeating), clamp, and mirrored once about the origin then the edge.
    #[test]
    fn addressing_out_of_range() {
        let read = |a: Address, from: i64, to: i64| -> Vec<usize> {
            (from..=to).map(|i| a.index(i, 4).unwrap()).collect()
        };
        assert_eq!(read(Address::Wrap, -5, 5), [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1]);
        assert_eq!(
            read(Address::Mirror, -5, 8),
            [3, 3, 2, 1, 0, 0, 1, 2, 3, 3, 2, 1, 0, 0]
        );
        assert_eq!(read(Address::Clamp, -2, 5), [0, 0, 0, 1, 2, 3, 3, 3]);
        assert_eq!(
            read(Address::MirrorOnce, -5, 5),
            [3, 3, 2, 1, 0, 0, 1, 2, 3, 3, 3]
        );
        // a border axis reads the texels inside, and no texel outside
        let border: Vec<Option<usize>> = (-2..=5).map(|i| Address::Border.index(i, 4)).collect();
        assert_eq!(
            border,
            [None, None, Some(0), Some(1), Some(2), Some(3), None, None]
        );
    }

    /// Border addressing reads the stated colour outside the texture, in both precisions and every filter: a 2 x 1
    /// texture, black then white, sampled past its left edge reads the border there; bilinear at the left edge mixes
    /// half the border with half the black texel; inside, the texels. The colour is taken as it is (no transfer). A
    /// border axis with no colour, or a colour that isn't finite, is refused; an array of addresses has none.
    #[test]
    fn border_addressing_reads_the_stated_colour() {
        let l = Levels::one(2, 1, vec![0, 0, 0, 255, 255, 255, 255, 255]).unwrap();
        let axes = [Address::Border, Address::Clamp];
        let (zero, one) = (
            Addressing::bordered(axes, [0.0; 4]),
            Addressing::bordered(axes, [1.0; 4]),
        );
        // point, past the left edge: the border; inside: the texel
        assert_eq!(
            l.point(0, [-0.25, 0.5], zero, Transfer::Stored).unwrap(),
            [0.0; 4]
        );
        assert_eq!(l.point(0, [-0.25, 0.5], one, Transfer::Stored).unwrap(), [1.0; 4]);
        assert_eq!(
            l.point(0, [0.25, 0.5], one, Transfer::Stored).unwrap(),
            [0.0, 0.0, 0.0, 1.0]
        );
        // bilinear at u = 0: half a texel left of the black texel's centre, half the border and half black
        assert_eq!(
            l.bilinear(0, [0.0, 0.5], one, Transfer::Stored).unwrap(),
            [0.5, 0.5, 0.5, 1.0]
        );
        assert_eq!(
            l.bilinear(0, [0.0, 0.5], zero, Transfer::Stored).unwrap(),
            [0.0, 0.0, 0.0, 0.5]
        );
        // the colour is not decoded by the transfer
        let grey = Addressing::bordered(axes, [0.5; 4]);
        assert_eq!(
            l.point(0, [-0.25, 0.5], grey, Transfer::SrgbColour).unwrap(),
            [0.5; 4]
        );
        assert_eq!(
            l.trilinear([-1.0, 0.5], 0.0, one, Transfer::Stored).unwrap(),
            [1.0; 4]
        );
        // f32 texels, 2D and volumes
        let d = l.decoded(0, Transfer::Stored).unwrap();
        assert_eq!(d.point([1.5, 0.5], one).unwrap(), [1.0; 4]);
        assert_eq!(d.bilinear([0.0, 0.5], one).unwrap(), [0.5, 0.5, 0.5, 1.0]);
        assert_eq!(d.bilinear([0.0, 0.5], zero).unwrap(), [0.0, 0.0, 0.0, 0.5]);
        let v = Decoded::volume(1, 1, 2, vec![[0.25; 4], [0.75; 4]]).unwrap();
        let volume = Addressing::bordered([Address::Clamp, Address::Clamp, Address::Border], [1.0; 4]);
        assert_eq!(v.point_3d([0.5, 0.5, 1.5], volume).unwrap(), [1.0; 4]);
        assert_eq!(v.point_3d([0.5, 0.5, 0.25], volume).unwrap(), [0.25; 4]);
        // halfway between the far slice's centre and the border beyond it
        assert_eq!(
            v.linear_3d([0.5, 0.5, 1.0], volume, Subtexel::Exact).unwrap(),
            [0.875; 4]
        );
        // a border axis needs a colour, a finite one; the stored texel past a border is none
        assert!(l.point(0, [0.25, 0.5], axes, Transfer::Stored).is_err());
        assert!(d.bilinear([0.5, 0.5], axes).is_err());
        let nan = Addressing::bordered(axes, [f32::NAN, 0.0, 0.0, 0.0]);
        assert!(l.bilinear(0, [0.5, 0.5], nan, Transfer::Stored).is_err());
        assert!(l.texel(0, -1, 0, axes).is_err());
        assert_eq!(l.texel(0, 1, 0, axes).unwrap(), [255; 4]);
        // an array of addresses is addressing with no border colour
        assert_eq!(
            Addressing::from([Address::Wrap; 2]),
            Addressing {
                axes: [Address::Wrap; 2],
                border: None
            }
        );
    }

    /// Direct3D 11's sub-texel precision truncates the texel coordinate to 1/256: a sample 0.3 of the way from black to
    /// white weighs white 76/256 (0.3 * 256 = 76.8, truncated), where the exact filter weighs it 0.3; on a 1/256 step
    /// both agree.
    #[test]
    fn d3d11_subtexel_precision_truncates_to_eight_bits() {
        let d = Levels::one(2, 1, vec![0, 0, 0, 255, 255, 255, 255, 255])
            .unwrap()
            .decoded(0, Transfer::Stored)
            .unwrap();
        let clamp = [Address::Clamp; 2];
        // texel coordinate 0.3: u = (0.3 + 0.5) / 2
        let u = 0.4f32;
        let exact = d.bilinear_at([u, 0.5], clamp, Subtexel::Exact).unwrap()[0];
        let d3d = d.bilinear_at([u, 0.5], clamp, Subtexel::D3d11).unwrap()[0];
        assert!((exact - 0.3).abs() < 1e-6, "{exact}");
        assert_eq!(d3d, 76. / 256.);
        let on_step = (64. / 256. + 0.5) / 2.;
        assert_eq!(
            d.bilinear_at([on_step, 0.5], clamp, Subtexel::D3d11).unwrap(),
            d.bilinear_at([on_step, 0.5], clamp, Subtexel::Exact).unwrap()
        );
    }

    /// A 2 x 1 texture, black then white: halfway between the texel centres is half white; at the left texel's centre
    /// black; wrapped, the left edge blends the right texel in, clamped it doesn't; sRGB colour decoded before
    /// filtering (a half of white's linear 1), alpha as stored.
    #[test]
    fn bilinear_between_texel_centres() {
        let l = Levels::one(2, 1, vec![0, 0, 0, 0, 255, 255, 255, 255]).unwrap();
        let wrap = [Address::Wrap; 2];
        let clamp = [Address::Clamp; 2];
        assert_eq!(
            l.bilinear(0, [0.5, 0.5], wrap, Transfer::Stored).unwrap(),
            [0.5; 4]
        );
        assert_eq!(
            l.bilinear(0, [0.25, 0.5], wrap, Transfer::Stored).unwrap(),
            [0.0; 4]
        );
        assert_eq!(
            l.bilinear(0, [0.0, 0.5], wrap, Transfer::Stored).unwrap(),
            [0.5; 4]
        );
        assert_eq!(
            l.bilinear(0, [0.0, 0.5], clamp, Transfer::Stored).unwrap(),
            [0.0; 4]
        );
        let d = l.decoded(0, Transfer::SrgbColour).unwrap();
        let half = d.bilinear([0.5, 0.5], wrap).unwrap();
        assert!(half.iter().all(|c| (c - 0.5).abs() < 1e-6), "{half:?}");
        // a 50% grey texel: its sRGB colour decodes to linear 0.2158...; its alpha stays 128/255
        let g = Levels::one(1, 1, vec![128, 128, 128, 128]).unwrap();
        let c = g.bilinear(0, [0.5, 0.5], wrap, Transfer::SrgbColour).unwrap();
        assert!(
            (c[0] - crate::color::srgb_to_linear(128.0 / 255.0)).abs() < 1e-15
                && (c[3] - 128.0 / 255.0).abs() < 1e-15
        );
    }

    /// A footprint of one base texel is level 0, of four texels level 2 (the longer derivative counts, in texels of
    /// each axis's size); trilinear between levels 0 (black) and 1 (white) gives the fraction, and clamps to the
    /// stored levels.
    #[test]
    fn trilinear_at_a_footprint() {
        assert_eq!(
            footprint_lod(8, 4, [[1.0 / 8.0, 0.0], [0.0, 1.0 / 4.0]], 0.0),
            0.0
        );
        assert_eq!(footprint_lod(8, 4, [[0.0, 0.0], [0.0, 1.0]], 0.0), 2.0);
        assert_eq!(footprint_lod(8, 4, [[0.0; 2]; 2], 3.0), f64::NEG_INFINITY);
        let l = Levels {
            width: 2,
            height: 2,
            levels: vec![vec![0; 16], vec![255; 4]],
        };
        let wrap = [Address::Wrap; 2];
        let at = |lod| l.trilinear([0.5, 0.5], lod, wrap, Transfer::Stored).unwrap()[0];
        assert_eq!((at(-1.0), at(0.25), at(1.0), at(7.0)), (0.0, 0.25, 1.0, 1.0));
        assert!(l.trilinear([0.5, 0.5], f64::NAN, wrap, Transfer::Stored).is_err());
    }

    /// Point filtering takes the texel a coordinate falls in, addressed, its transfer applied; the nearest level
    /// rounds a half up and clamps to the stored levels; reversed rows put the bottom row at v = 0 in every level.
    #[test]
    fn point_filtering_nearest_levels_and_reversed_rows() {
        // 2 x 2, rows top first: black, white / grey, white; then a 1 x 1 level
        let l = Levels {
            width: 2,
            height: 2,
            levels: vec![[[0; 4], [255; 4], [128; 4], [255; 4]].concat(), vec![64; 4]],
        };
        let (wrap, clamp) = ([Address::Wrap; 2], [Address::Clamp; 2]);
        let at = |l: &Levels, uv: [f64; 2], a| l.point(0, uv, a, Transfer::Stored).unwrap()[0];
        assert_eq!(at(&l, [0.25, 0.25], wrap), 0.0);
        assert_eq!(at(&l, [0.5, 0.25], wrap), 1.0);
        assert_eq!(at(&l, [0.25, 0.75], wrap), 128.0 / 255.0);
        // past the left edge: wrapped to the right texel, clamped to the left one
        assert_eq!(
            (at(&l, [-0.25, 0.25], wrap), at(&l, [-0.25, 0.25], clamp)),
            (1.0, 0.0)
        );
        let c = l.point(0, [0.25, 0.75], wrap, Transfer::SrgbColour).unwrap();
        assert_eq!(c[0], crate::color::srgb8_to_linear(128));
        assert!(l.point(0, [f64::NAN, 0.0], wrap, Transfer::Stored).is_err());
        assert_eq!(
            [-3.0, 0.49, 0.5, 1.2, 9.0].map(|lod| l.nearest_level(lod).unwrap()),
            [0, 0, 1, 1, 1]
        );
        assert!(l.nearest_level(f64::NAN).is_err());
        let up = l.clone().rows_reversed().unwrap();
        assert_eq!(at(&up, [0.25, 0.25], wrap), 128.0 / 255.0);
        assert_eq!(at(&up, [0.25, 0.75], wrap), 0.0);
        assert_eq!(up.levels[1], vec![64; 4]);
        let short = Levels {
            width: 2,
            height: 2,
            levels: vec![vec![0; 12]],
        };
        assert!(short.rows_reversed().is_err());
    }

    /// Float texels as held: a 2 x 2 level point-sampled (the texel a coordinate falls in, addressed) and bilinear
    /// (the middle is the mean of the four); a count other than the size's, or no texel, is refused; a 2D sample of a
    /// volume is refused.
    #[test]
    fn float_texels_point_and_bilinear() {
        let red_green = vec![
            [0.0, 0.0, 0.0, 1.0],
            [1.0, 0.0, 0.0, 1.0],
            [0.0, 1.0, 0.0, 1.0],
            [1.0, 1.0, 0.0, 1.0],
        ];
        let d = Decoded::from_texels(2, 2, red_green.clone()).unwrap();
        let (wrap, clamp) = ([Address::Wrap; 2], [Address::Clamp; 2]);
        assert_eq!(d.point([0.25, 0.25], clamp).unwrap(), [0.0, 0.0, 0.0, 1.0]);
        assert_eq!(d.point([0.75, 0.25], clamp).unwrap(), [1.0, 0.0, 0.0, 1.0]);
        assert_eq!(d.point([0.25, 0.75], clamp).unwrap(), [0.0, 1.0, 0.0, 1.0]);
        // past the edges: clamped to the edge texel, wrapped round
        assert_eq!(d.point([1.75, -3.0], clamp).unwrap(), [1.0, 0.0, 0.0, 1.0]);
        assert_eq!(d.point([1.25, 0.25], wrap).unwrap(), [0.0, 0.0, 0.0, 1.0]);
        assert_eq!(d.point([-0.25, 0.25], wrap).unwrap(), [1.0, 0.0, 0.0, 1.0]);
        assert_eq!(d.bilinear([0.5, 0.5], clamp).unwrap(), [0.5, 0.5, 0.0, 1.0]);
        assert_eq!(d.bilinear([0.375, 0.25], clamp).unwrap(), [0.25, 0.0, 0.0, 1.0]);
        // values past 0..1 are filtered as they are
        let hdr = Decoded::from_texels(2, 1, vec![[-2.0; 4], [6.0; 4]]).unwrap();
        assert_eq!(hdr.bilinear([0.5, 0.5], clamp).unwrap(), [2.0; 4]);
        assert!(Decoded::from_texels(2, 2, red_green[..3].to_vec()).is_err());
        assert!(Decoded::from_texels(0, 2, Vec::new()).is_err());
        assert!(d.point([f32::NAN, 0.5], clamp).is_err());
        let volume = Decoded::volume(1, 1, 2, vec![[0.0; 4], [1.0; 4]]).unwrap();
        assert!(volume.point([0.5, 0.5], clamp).is_err());
        assert!(volume.bilinear([0.5, 0.5], clamp).is_err());
    }

    /// A 2 x 2 x 2 volume whose texel (x, y, z) is (x, y, z, 1): point sampling takes the texel a coordinate falls in;
    /// linear filtering between the eight texels gives the coordinate's position between their centres, clamped at the
    /// edges and wrapped round; the texel a load reads is the one at its index, none past the size.
    #[test]
    fn volumes_point_linear_and_texels() {
        let texels: Vec<[f32; 4]> = (0..8)
            .map(|i| [(i % 2) as f32, (i / 2 % 2) as f32, (i / 4) as f32, 1.0])
            .collect();
        let v = Decoded::volume(2, 2, 2, texels).unwrap();
        assert_eq!(v.depth(), 2);
        let (wrap, clamp) = ([Address::Wrap; 3], [Address::Clamp; 3]);
        assert_eq!(
            v.point_3d([0.75, 0.25, 0.75], clamp).unwrap(),
            [1.0, 0.0, 1.0, 1.0]
        );
        assert_eq!(
            v.point_3d([0.25, 1.25, -0.25], wrap).unwrap(),
            [0.0, 0.0, 1.0, 1.0]
        );
        // halfway between the centres on every axis, a quarter of the way along x, at a corner's centre
        let exact = Subtexel::Exact;
        assert_eq!(v.linear_3d([0.5; 3], clamp, exact).unwrap(), [0.5, 0.5, 0.5, 1.0]);
        assert_eq!(
            v.linear_3d([0.375, 0.25, 0.25], clamp, exact).unwrap(),
            [0.25, 0.0, 0.0, 1.0]
        );
        assert_eq!(
            v.linear_3d([0.25, 0.25, 0.75], clamp, exact).unwrap(),
            [0.0, 0.0, 1.0, 1.0]
        );
        // at the left edge: clamped it is the edge texel, wrapped it blends the far one in
        assert_eq!(v.linear_3d([0.0, 0.25, 0.25], clamp, exact).unwrap()[0], 0.0);
        assert_eq!(v.linear_3d([0.0, 0.25, 0.25], wrap, exact).unwrap()[0], 0.5);
        assert!(v.linear_3d([0.5, f32::INFINITY, 0.5], clamp, exact).is_err());
        assert_eq!(v.texel(1, 0, 1), Some([1.0, 0.0, 1.0, 1.0]));
        assert_eq!(v.texel(2, 0, 0), None);
        assert_eq!(v.texel(0, -1, 0), None);
        assert_eq!(v.texel(0, 0, 2), None);
        // a 2D level is one slice
        let d = Decoded::from_texels(1, 1, vec![[3.0; 4]]).unwrap();
        assert_eq!(d.point_3d([0.5; 3], clamp).unwrap(), [3.0; 4]);
        assert_eq!(d.texel(0, 0, 0), Some([3.0; 4]));
        assert_eq!(d.texel(0, 0, 1), None);
    }

    /// A coordinate that isn't finite, or whose texel is past an i32's range, is refused, never sampled (NaN texels)
    /// and never an overflow: in both precisions.
    #[test]
    fn nonfinite_or_excessive_coordinates_are_refused() {
        let l = Levels::one(2, 2, vec![10; 16]).unwrap();
        let wrap = [Address::Wrap; 2];
        for uv in [[f64::NAN, 0.5], [0.5, f64::INFINITY], [1e300, 0.5], [0.5, -1e12]] {
            assert!(l.bilinear(0, uv, wrap, Transfer::Stored).is_err(), "{uv:?}");
            assert!(l.trilinear(uv, 0.0, wrap, Transfer::Stored).is_err(), "{uv:?}");
            assert!(
                l.decoded(0, Transfer::Stored)
                    .unwrap()
                    .bilinear(uv.map(|v| v as f32), wrap)
                    .is_err(),
                "{uv:?}"
            );
        }
        assert!(l.trilinear([1e8, -1e8], 0.0, wrap, Transfer::Stored).is_ok());
    }
}