ltk_texture 0.6.3

Texture decoding/encoding utilities for League Toolkit
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
use byteorder::{ReadBytesExt, LE};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use std::{borrow::Cow, io};

mod bc5_snorm;
mod encode;
mod error;
mod format;
mod surface;
mod write;

pub use encode::*;
pub use error::*;
pub use format::*;
pub use surface::*;

use super::ReadError;

/// Signature of `texture2ddecoder`'s surface decode functions
type Texture2dDecodeFn = fn(&[u8], usize, usize, &mut [u32]) -> Result<(), &'static str>;

/// League extended texture file (.tex)
#[derive(Debug)]
pub struct Tex {
    pub width: u16,
    pub height: u16,
    /// Number of z-slices; `1` for everything but volume textures.
    pub depth: u8,
    pub format: Format,
    pub resource_type: ResourceType,
    pub flags: TextureFlags,
    pub mip_count: u32,
    data: Vec<u8>,
}

impl Tex {
    pub const MAGIC: u32 = u32::from_le_bytes(*b"TEX\0");

    /// Checks the texture flags for whether the texture contains mipmaps
    pub fn has_mipmaps(&self) -> bool {
        self.flags.contains(TextureFlags::HasMipMaps)
    }

    /// Encode a new Tex from an RGBA image with encoding options
    ///
    /// # Example
    /// ```no_run
    /// use ltk_texture::Tex;
    /// use ltk_texture::tex::{EncodeFormat, EncodeOptions, MipmapFilter};
    /// use image::RgbaImage;
    ///
    /// let img = RgbaImage::new(256, 256);
    /// let format = EncodeFormat::Bc3 { weigh_colour_by_alpha: false };
    ///
    /// // Without mipmaps
    /// let tex = Tex::encode_rgba_image(&img, EncodeOptions::new(format)).unwrap();
    ///
    /// // With mipmaps
    /// let tex_mips = Tex::encode_rgba_image(
    ///     &img,
    ///     EncodeOptions::new(format).with_mipmaps()
    /// ).unwrap();
    ///
    /// // With mipmaps and custom filter
    /// let tex_lanczos = Tex::encode_rgba_image(
    ///     &img,
    ///     EncodeOptions::new(format)
    ///         .with_mipmaps()
    ///         .with_mipmap_filter(MipmapFilter::Lanczos3)
    /// ).unwrap();
    /// ```
    pub fn encode_rgba_image(
        img: &image::RgbaImage,
        options: EncodeOptions,
    ) -> Result<Self, EncodeError> {
        let (width, height) = img.dimensions();
        if width == 0 || height == 0 {
            return Err(EncodeError::ZeroSizedImage);
        }

        let (data, mip_count, flags) = if options.generate_mipmaps {
            let (mip_data, mip_count) = encode_rgba_with_mipmaps(img, &options)?;
            (mip_data, mip_count, TextureFlags::HasMipMaps)
        } else {
            let rgba_data = img.as_raw();
            let encoded = encode_rgba(width, height, rgba_data, &options)?;
            (encoded, 1, TextureFlags::empty())
        };

        Ok(Self {
            width: width as u16,
            height: height as u16,
            depth: 1,
            format: options.format.into(),
            resource_type: ResourceType::Texture,
            flags,
            mip_count,
            data,
        })
    }

    /// Encode a new Tex from a DynamicImage with encoding options
    ///
    /// # Example
    /// ```no_run
    /// use ltk_texture::Tex;
    /// use ltk_texture::tex::{EncodeFormat, EncodeOptions};
    ///
    /// let img = image::open("texture.png").unwrap();
    /// let format = EncodeFormat::Bc3 { weigh_colour_by_alpha: false };
    /// let tex = Tex::encode_dynamic_image(
    ///     img,
    ///     EncodeOptions::new(format).with_mipmaps()
    /// ).unwrap();
    /// ```
    pub fn encode_dynamic_image(
        img: image::DynamicImage,
        options: EncodeOptions,
    ) -> Result<Self, EncodeError> {
        Self::encode_rgba_image(&img.to_rgba8(), options)
    }
}

impl Tex {
    /// Try to decode a single mipmap, where 0 is full resolution, and [Self::mip_count] is the smallest
    /// mip (1x1).
    ///
    /// For volume textures this decodes z-slice 0; use [Self::decode_mipmap_slice] for the rest.
    pub fn decode_mipmap(&self, level: u32) -> Result<TexSurface<'_>, DecodeErr> {
        self.decode_mipmap_slice(level, 0)
    }

    /// Mip dimensions halve per level with a floor of 1.
    fn mip_dims(&self, level: u32) -> (usize, usize, usize) {
        (
            ((self.width as usize) >> level).max(1),
            ((self.height as usize) >> level).max(1),
            ((self.depth as usize).max(1) >> level).max(1),
        )
    }

    /// Byte size of a single z-slice of a mip.
    fn slice_bytes(&self, w: usize, h: usize) -> usize {
        let (block_w, block_h) = self.format.block_size();
        w.div_ceil(block_w) * h.div_ceil(block_h) * self.format.bytes_per_block()
    }

    /// Byte size of a whole mip, all z-slices.
    fn mip_bytes(&self, level: u32) -> usize {
        let (w, h, d) = self.mip_dims(level);
        self.slice_bytes(w, h) * d
    }

    /// How many mips the payload actually holds, counted from the smallest.
    ///
    /// Less than [`Self::mip_count`] when the data is a truncated low-res
    /// prefix; `mip_count - available_mip_count()` is the first decodable level.
    #[must_use]
    pub fn available_mip_count(&self) -> u32 {
        let mut remaining = self.data.len();
        let mut available = 0;
        for level in (0..self.mip_count).rev() {
            let bytes = self.mip_bytes(level);
            if bytes > remaining {
                break;
            }
            remaining -= bytes;
            available += 1;
        }
        available
    }

    /// Try to decode a single z-slice of a mipmap. For 2D textures the only valid slice is 0.
    ///
    /// - Mip dimensions halve per level with a floor of 1
    /// - Mip slices are stored sequentially, matching the D3D volume texture layout
    /// - Mip levels are stored in reverse order, smallest to largest
    pub fn decode_mipmap_slice(&self, level: u32, slice: u32) -> Result<TexSurface<'_>, DecodeErr> {
        let level = level.min(self.mip_count - 1);

        // size of mip
        let (w, h, d) = self.mip_dims(level);
        if slice as usize >= d {
            return Err(DecodeErr::SliceOutOfBounds { slice, depth: d });
        }

        // sum all mips before our one
        // (league sorts mips smallest -> largest so our iterator counts up)
        let slice_len = self.slice_bytes(w, h);
        let off = (level + 1..self.mip_count)
            .map(|level| self.mip_bytes(level))
            .sum::<usize>()
            + slice as usize * slice_len;

        let mip_data = self
            .data
            .get(off..off + slice_len)
            .ok_or(DecodeErr::MipOutOfBounds {
                level,
                start: off,
                end: off + slice_len,
                len: self.data.len(),
            })?;

        // decodes a block-compressed mip to RGBA8 via image_dds
        let decode_image_dds = |image_format| -> Result<Vec<u8>, DecodeErr> {
            let surface = image_dds::Surface {
                width: w as u32,
                height: h as u32,
                depth: 1,
                layers: 1,
                mipmaps: 1,
                image_format,
                data: mip_data,
            };
            Ok(surface.decode_layers_mipmaps_rgba8(0..1, 0..1)?.data)
        };

        // decodes a mip to BGRA8 via texture2ddecoder
        let decode_texture2d = |decode: Texture2dDecodeFn| -> Result<Vec<u8>, DecodeErr> {
            let mut data = vec![0u32; w * h];
            decode(mip_data, w, h, &mut data)
                .map_err(|reason| DecodeErr::Decode(self.format, reason))?;
            // the u32 pixels are BGRA8 packed as little-endian
            Ok(data.into_iter().flat_map(u32::to_le_bytes).collect())
        };

        use image_dds::ImageFormat as IF;
        let (format, data): (PixelFormat, Cow<'_, [u8]>) = match self.format {
            // TODO: test me (this is likely wrong)
            Format::Bgra8 => (PixelFormat::Bgra8Unorm, Cow::Borrowed(mip_data)),
            Format::Bc1 => (
                PixelFormat::Rgba8Unorm,
                decode_image_dds(IF::BC1RgbaUnorm)?.into(),
            ),
            Format::Bc3 => (
                PixelFormat::Rgba8Unorm,
                decode_image_dds(IF::BC3RgbaUnorm)?.into(),
            ),
            Format::Bc7 => (
                PixelFormat::Rgba8Unorm,
                decode_image_dds(IF::BC7RgbaUnormSrgb)?.into(),
            ),
            // image_dds/texture2ddecoder only decode *unsigned* BC5, so we do it ourselves
            Format::Bc5Snorm => (
                PixelFormat::Rg8Snorm,
                bc5_snorm::decode_bc5_snorm(mip_data, w, h).into(),
            ),
            Format::Rgba16Float => (PixelFormat::Rgba16Float, Cow::Borrowed(mip_data)),
            Format::Rgba32Float => (PixelFormat::Rgba32Float, Cow::Borrowed(mip_data)),
            Format::Etc1 => (
                PixelFormat::Bgra8Unorm,
                decode_texture2d(texture2ddecoder::decode_etc1)?.into(),
            ),
            Format::Etc2Eac => (
                PixelFormat::Bgra8Unorm,
                decode_texture2d(texture2ddecoder::decode_etc2_rgba8)?.into(),
            ),
        };

        Ok(TexSurface {
            width: w as _,
            height: h as _,
            format,
            data,
        })
    }

    pub fn from_reader<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, ReadError> {
        let magic = reader.read_u32::<LE>()?; // skip magic
        if magic != Self::MAGIC {
            return Err(ReadError::UnexpectedMagic {
                expected: Self::MAGIC,
                got: magic,
            });
        }

        Ok(Self::from_reader_no_magic(reader)?)
    }
    pub fn from_reader_no_magic<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, Error> {
        let (width, height) = (reader.read_u16::<LE>()?, reader.read_u16::<LE>()?);

        let depth = reader.read_u8()?;
        let format = Format::from_u8(reader.read_u8()?)?;
        let resource_type = ResourceType::from_u8(reader.read_u8()?)?;

        let flags = reader.read_u8()?;
        let flags = TextureFlags::from_bits(flags).ok_or(Error::InvalidTextureFlags(flags))?;

        let mut data = Vec::new();
        reader.read_to_end(&mut data)?;

        Ok(Self {
            width,
            height,
            depth,
            format,
            flags,
            resource_type,
            data,
            mip_count: match flags.contains(TextureFlags::HasMipMaps) {
                true => (height.max(width).max(depth as u16).max(1) as u32).ilog2() + 1,
                false => 1,
            },
        })
    }
}

/// GPU resource type, as stored in the TEX header.
/// Only regular and volume textures can be found in live builds of the game.
#[derive(TryFromPrimitive, IntoPrimitive, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum ResourceType {
    /// A regular 2D texture (`depth == 1`)
    Texture = 0,
    /// Six 2D faces (This resource type is assumed by reverse engineering)
    Cubemap = 1,
    /// A bare 2D image (This resource type is assumed by reverse engineering)
    Surface = 2,
    /// A 3D texture: [`Tex::depth`] z-slices per mip level, stored sequentially
    VolumeTexture = 3,
}

impl ResourceType {
    pub fn from_u8(resource_type: u8) -> Result<Self, Error> {
        Self::try_from(resource_type).map_err(|_| Error::UnknownResourceType(resource_type))
    }

    pub fn to_u8(&self) -> u8 {
        (*self).into()
    }
}

bitflags::bitflags! {
    #[derive(Debug, Clone, Copy)]
    pub struct TextureFlags: u8 {
        const HasMipMaps = 1;
        const Mystery = 2;
    }
}

#[derive(TryFromPrimitive, IntoPrimitive, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum TextureFilter {
    None,
    Nearest,
    Linear,
}

#[derive(TryFromPrimitive, IntoPrimitive, Clone, Copy, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum TextureAddress {
    Wrap,
    Clamp,
}

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

    #[test]
    fn parses_new_format_ids() {
        assert_eq!(Format::from_u8(13).unwrap(), Format::Bc7);
        assert_eq!(Format::from_u8(14).unwrap(), Format::Bc5Snorm);
        assert_eq!(Format::from_u8(22).unwrap(), Format::Rgba32Float);
        assert_eq!(Format::Bc7.to_u8(), 13);
        assert_eq!(Format::Bc5Snorm.to_u8(), 14);
        assert_eq!(Format::Rgba32Float.to_u8(), 22);
    }

    fn tex_file(format: u8, data: &[u8]) -> Vec<u8> {
        let mut file = Vec::new();
        file.extend_from_slice(b"TEX\0");
        file.extend_from_slice(&4u16.to_le_bytes()); // width
        file.extend_from_slice(&4u16.to_le_bytes()); // height
        file.push(1); // depth
        file.push(format);
        file.push(0); // resource type: texture
        file.push(0); // flags: no mipmaps
        file.extend_from_slice(data);
        file
    }

    #[test]
    fn write_roundtrips_header_bytes() {
        let file = tex_file(20, &[0u8; 64]);
        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.depth, 1);
        assert_eq!(tex.resource_type, ResourceType::Texture);

        let mut out = Vec::new();
        tex.write(&mut out).unwrap();
        assert_eq!(out, file);
    }

    #[test]
    fn decodes_volume_texture_slices() {
        // 2x2x2 BGRA8 volume texture, no mips: two sequential 16-byte z-slices
        let mut file = Vec::new();
        file.extend_from_slice(b"TEX\0");
        file.extend_from_slice(&2u16.to_le_bytes()); // width
        file.extend_from_slice(&2u16.to_le_bytes()); // height
        file.push(2); // depth
        file.push(20); // Bgra8
        file.push(3); // resource type: volume texture
        file.push(0); // flags: no mipmaps
        file.extend_from_slice(&[0x11; 16]); // slice 0
        file.extend_from_slice(&[0x22; 16]); // slice 1

        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.depth, 2);
        assert_eq!(tex.resource_type, ResourceType::VolumeTexture);

        assert_eq!(&*tex.decode_mipmap_slice(0, 0).unwrap().data, &[0x11; 16]);
        assert_eq!(&*tex.decode_mipmap_slice(0, 1).unwrap().data, &[0x22; 16]);
        // decode_mipmap is slice 0
        assert_eq!(&*tex.decode_mipmap(0).unwrap().data, &[0x11; 16]);
        assert!(matches!(
            tex.decode_mipmap_slice(0, 2),
            Err(DecodeErr::SliceOutOfBounds { slice: 2, depth: 2 })
        ));
    }

    #[test]
    fn reads_and_decodes_bc5_snorm_tex() {
        // one BC5 block: red = constant 1.0 (endpoints 127/-127, all indices 0),
        // green = constant -1.0 (endpoints -127/-127)
        let mut block = Vec::new();
        block.extend_from_slice(&[127, 0x81, 0, 0, 0, 0, 0, 0]);
        block.extend_from_slice(&[0x81, 0x81, 0, 0, 0, 0, 0, 0]);
        let file = tex_file(14, &block);

        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.format, Format::Bc5Snorm);
        assert_eq!(tex.mip_count, 1);

        // the decoded surface preserves the signed data
        let surface = tex.decode_mipmap(0).unwrap();
        assert_eq!(surface.format, PixelFormat::Rg8Snorm);
        assert_eq!(surface.as_pixels::<[i8; 2]>().unwrap(), [[127, -127]; 16]);

        // ...while the image conversion remaps to [0, 255]
        let img = surface.into_rgba_image().unwrap();
        assert_eq!(img.dimensions(), (4, 4));
        for pixel in img.pixels() {
            assert_eq!(pixel.0, [255, 0, 0, 255]);
        }
    }

    #[test]
    fn reads_and_decodes_rgba16_float_tex() {
        // 4x4 RGBA16F: every pixel (0.5, -1.0, 2.0, 1.0) — out-of-[0,1] values must
        // survive decoding intact and only clamp in the image conversion
        let pixel = [
            half::f16::from_f32(0.5),
            half::f16::from_f32(-1.0),
            half::f16::from_f32(2.0),
            half::f16::from_f32(1.0),
        ];
        let data: Vec<u8> = std::iter::repeat_n(pixel, 16)
            .flatten()
            .flat_map(half::f16::to_le_bytes)
            .collect();
        let file = tex_file(21, &data);

        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.format, Format::Rgba16Float);

        let surface = tex.decode_mipmap(0).unwrap();
        assert_eq!(surface.format, PixelFormat::Rgba16Float);
        assert_eq!(surface.as_pixels::<[half::f16; 4]>().unwrap(), [pixel; 16]);

        let img = surface.into_rgba_image().unwrap();
        for p in img.pixels() {
            assert_eq!(p.0, [128, 0, 255, 255]);
        }
    }

    #[test]
    fn rgba16_float_encode_roundtrips() {
        let mut img = image::RgbaImage::new(4, 4);
        img.pixels_mut().for_each(|p| p.0 = [0, 51, 204, 255]);

        let tex =
            Tex::encode_rgba_image(&img, EncodeOptions::new(EncodeFormat::Rgba16Float)).unwrap();
        assert_eq!(tex.format, Format::Rgba16Float);

        let decoded = tex.decode_mipmap(0).unwrap().into_rgba_image().unwrap();
        assert_eq!(decoded.pixels().next().unwrap().0, [0, 51, 204, 255]);
    }

    #[test]
    fn reads_and_decodes_rgba32_float_tex() {
        // 4x4 RGBA32F: every pixel (0.5, -1.0, 2.0, 1.0) — out-of-[0,1] values must
        // survive decoding intact and only clamp in the image conversion
        let pixel = [0.5f32, -1.0, 2.0, 1.0];
        let data: Vec<u8> = std::iter::repeat_n(pixel, 16)
            .flatten()
            .flat_map(f32::to_le_bytes)
            .collect();
        let file = tex_file(22, &data);

        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.format, Format::Rgba32Float);

        let surface = tex.decode_mipmap(0).unwrap();
        assert_eq!(surface.format, PixelFormat::Rgba32Float);
        assert_eq!(surface.as_pixels::<[f32; 4]>().unwrap(), [pixel; 16]);

        let img = surface.into_rgba_image().unwrap();
        for p in img.pixels() {
            assert_eq!(p.0, [128, 0, 255, 255]);
        }
    }

    #[test]
    fn rgba32_float_encode_roundtrips() {
        let mut img = image::RgbaImage::new(4, 4);
        img.pixels_mut().for_each(|p| p.0 = [0, 51, 204, 255]);

        let tex =
            Tex::encode_rgba_image(&img, EncodeOptions::new(EncodeFormat::Rgba32Float)).unwrap();
        assert_eq!(tex.format, Format::Rgba32Float);

        let decoded = tex.decode_mipmap(0).unwrap().into_rgba_image().unwrap();
        assert_eq!(decoded.pixels().next().unwrap().0, [0, 51, 204, 255]);
    }

    /// The texpresso BC1/BC3 backend: a solid color that's exact in RGB565 must
    /// round-trip unchanged, including through the masked partial blocks and
    /// non-block-aligned mip levels of a 10x6 NPOT chain.
    #[test]
    fn texpresso_bc_encode_roundtrips() {
        let mut img = image::RgbaImage::new(10, 6);
        img.pixels_mut().for_each(|p| p.0 = [255, 0, 0, 255]);

        for format in [
            EncodeFormat::Bc1 {
                weigh_colour_by_alpha: false,
            },
            EncodeFormat::Bc3 {
                weigh_colour_by_alpha: false,
            },
        ] {
            let tex =
                Tex::encode_rgba_image(&img, EncodeOptions::new(format).with_mipmaps()).unwrap();
            assert_eq!(tex.mip_count, 4); // 10x6 -> 5x3 -> 2x1 -> 1x1

            for level in 0..tex.mip_count {
                let surface = tex.decode_mipmap(level).unwrap();
                assert_eq!(surface.width, (10 >> level).max(1));
                assert_eq!(surface.height, (6 >> level).max(1));
                for p in surface.into_rgba_image().unwrap().pixels() {
                    assert_eq!(p.0, [255, 0, 0, 255], "{format:?} level {level}");
                }
            }
        }
    }

    #[test]
    fn zero_sized_image_errors() {
        let img = image::RgbaImage::new(0, 0);
        assert!(matches!(
            Tex::encode_rgba_image(&img, EncodeOptions::new(EncodeFormat::Bgra8)),
            Err(EncodeError::ZeroSizedImage)
        ));
        assert!(matches!(
            Tex::encode_rgba_image(&img, EncodeOptions::new(EncodeFormat::Bgra8).with_mipmaps()),
            Err(EncodeError::ZeroSizedImage)
        ));
    }

    #[test]
    fn available_mip_count_tracks_a_truncated_mip_chain() {
        // 8x8 Bgra8 with mips: smallest-first sizes are 4, 16, 64, 256 bytes
        let mut file = Vec::new();
        file.extend_from_slice(b"TEX\0");
        file.extend_from_slice(&8u16.to_le_bytes()); // width
        file.extend_from_slice(&8u16.to_le_bytes()); // height
        file.push(1); // depth
        file.push(20); // Bgra8
        file.push(0); // resource type: texture
        file.push(1); // flags: has mipmaps
        file.extend_from_slice(&[0u8; 340]);

        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert_eq!(tex.mip_count, 4);
        assert_eq!(tex.available_mip_count(), 4);

        // 1x1 and 2x2 survive; a byte into 4x4 does not make it available
        for (len, available) in [(12, 0), (12 + 4, 1), (12 + 20, 2), (12 + 21, 2)] {
            let tex = Tex::from_reader(&mut &file[..len]).unwrap();
            assert_eq!(tex.available_mip_count(), available, "prefix len {len}");
        }
    }

    /// A low-res subchunk prefix: full header, mip chain cut at a mip
    /// boundary. Surviving mips must decode identically to the full parse.
    #[test]
    fn prefix_decodes_surviving_mips_identically() {
        let mut img = image::RgbaImage::new(16, 16);
        img.pixels_mut().for_each(|p| p.0 = [255, 0, 0, 255]);
        let format = EncodeFormat::Bc1 {
            weigh_colour_by_alpha: false,
        };
        let full = Tex::encode_rgba_image(&img, EncodeOptions::new(format).with_mipmaps()).unwrap();
        assert_eq!(full.mip_count, 5);

        let mut file = Vec::new();
        full.write(&mut file).unwrap();

        // keep the three smallest BC1 mips: one 8-byte block each
        let prefix = &file[..12 + 24];
        let tex = Tex::from_reader(&mut &prefix[..]).unwrap();
        assert_eq!(tex.mip_count, full.mip_count);
        assert_eq!(tex.available_mip_count(), 3);

        for level in 2..5 {
            let low = tex.decode_mipmap(level).unwrap();
            let all = full.decode_mipmap(level).unwrap();
            assert_eq!(low.data, all.data, "mip {level}");
        }
        assert!(matches!(
            tex.decode_mipmap(1),
            Err(DecodeErr::MipOutOfBounds { .. })
        ));
    }

    #[test]
    fn truncated_data_errors_instead_of_panicking() {
        let file = tex_file(13, &[0; 4]); // BC7 4x4 needs a full 16-byte block
        let tex = Tex::from_reader(&mut file.as_slice()).unwrap();
        assert!(matches!(
            tex.decode_mipmap(0),
            Err(DecodeErr::MipOutOfBounds { .. })
        ));
    }
}

//#[cfg(test)]
//mod old_tests {
//    use super::*;
//    use image::codecs::png::PngEncoder;
//    use io::BufWriter;
//    use std::fs;
//    use test_log::test;
//
//    #[test]
//    fn tex() {
//        let mut file = fs::File::open("/home/alan/Downloads/ashe_base_2011_tx_cm.tex").unwrap();
//        let tex = Tex::from_reader(&mut file).unwrap();
//
//        dbg!(tex.format);
//        dbg!(tex.width, tex.height);
//        dbg!(tex.has_mipmaps());
//        dbg!(tex.mip_count);
//        for i in 0..tex.mip_count {
//            let tex = tex.decode_mipmap(i).unwrap();
//            let img = tex.into_rgba_image().unwrap();
//
//            let out = PngEncoder::new(
//                std::fs::File::create(format!("./out_{i}.png"))
//                    .map(BufWriter::new)
//                    .unwrap(),
//            );
//            img.write_with_encoder(out).unwrap();
//        }
//        panic!("success");
//    }
//}