sgl-3d 0.7.0

Caller-driven 3D rendering for SGL games, native and in the browser (WebGPU)
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
//! Material images: decoded RGBA8 texels, or a block-compressed mip chain as
//! a game's export step stores it, read from KTX2 as Bevy 9d12036 reads it
//! (`crates/bevy_image/src/ktx2.rs`, `ktx2_buffer_to_image`: its stored
//! levels, Zstandard supercompression, and block formats sampled as sRGB
//! or linear by the channel that uses it). MIT OR Apache-2.0
//! (src/LICENSE-bevy.txt).
use std::borrow::Cow;

use super::asset::Result;
use super::load_budget::{Budget, DEFAULT_LOAD_BYTES, LoadBudget, MAX_IMAGE_SIDE};

/// An image materials sample. Its colour space belongs to each channel that
/// samples it: base and emissive maps read it as sRGB, the others as linear
/// data.
#[derive(Clone, Debug)]
pub enum Image {
    /// Decoded texels. The scene filters their mip chain when it adds them,
    /// in linear light for a channel that samples them as colour.
    Rgba8(image::RgbaImage),
    /// A block-compressed mip chain, uploaded as stored. Adding it needs
    /// the format’s matching BC, ETC2 or ASTC device feature.
    Compressed(CompressedImage),
    /// RGBA8 levels prepared on a caller-owned worker, uploaded without filtering.
    Rgba8Mips(Rgba8MipChain),
}

/// A block-compressed image's encoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompressedFormat {
    /// BC7: 16 bytes per block of 4x4 RGBA texels.
    Bc7,
    /// ETC2 RGB with EAC alpha: 16 bytes per 4x4 block.
    Etc2Rgba8,
    /// ASTC LDR RGBA: 16 bytes per 4x4 block.
    Astc4x4,
}

/// A block-compressed mip chain. A scene adds it when its sides are
/// multiples of the block size and no larger than 16384, and it holds one
/// to a full chain of levels, each of the size its level needs; otherwise
/// it refuses it with
/// `SceneError::InvalidCompressedImage`.
#[derive(Clone, Debug)]
pub struct CompressedImage {
    pub format: CompressedFormat,
    /// Level 0's width in texels.
    pub width: u32,
    /// Level 0's height in texels.
    pub height: u32,
    /// The stored levels, level 0 first and each next one half the size
    /// (at least one texel): each one's blocks row by row, a level's edge
    /// blocks whole. Filter a colour image's levels in linear light.
    pub levels: Vec<Vec<u8>>,
    /// ETC2/ASTC level 0 decoded by the game's offline export tool, in the
    /// same encoded-channel RGBA8 space as the compressed raster texture.
    /// Optional for raster-only material images. Required for rays and decals,
    /// and must match width/height when present. SGL checks
    /// shape, not pixel equivalence. Costs four additional bytes per texel.
    /// BC7 must leave this `None`: its rays continue to decode the blocks.
    pub decoded_level_0: Option<image::RgbaImage>,
}

/// Invalid caller-authored image preparation input.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageError {
    /// A side is zero or greater than the content limit of 16384 texels.
    InvalidDimensions,
    /// Generated levels exceed the load budget, or the float filtering
    /// scratch image cannot fit one addressable allocation.
    BudgetExceeded,
}

impl std::fmt::Display for ImageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::InvalidDimensions => "image sides must be between 1 and 16384 texels",
            Self::BudgetExceeded => "prepared mip chains exceed the load budget or addressable filtering allocation; split or resize the image",
        })
    }
}
impl std::error::Error for ImageError {}

/// Immutable RGBA8 mip chains prepared without a device or library thread.
/// The same image may serve colour and data channels: RGB is filtered in
/// linear light for colour and directly for data; alpha is always linear.
/// Retains both chains (approximately twice a full RGBA8 chain). Games can
/// prepare this `Send` value on their own worker before adding materials.
/// Retained generated bytes are bounded by the content load budget (4 GiB
/// native, 1 GiB wasm). Filtering scratch, the source and allocator capacity
/// are additional; this is not a peak-memory guarantee.
#[derive(Clone, Debug)]
pub struct Rgba8MipChain {
    color: Vec<image::RgbaImage>,
    data: Vec<image::RgbaImage>,
}

impl Rgba8MipChain {
    /// Builds complete colour and data chains, with level 0 unchanged.
    pub fn new(image: image::RgbaImage) -> std::result::Result<Self, ImageError> {
        check_mip_allocation(image.dimensions(), DEFAULT_LOAD_BYTES, isize::MAX as u64)?;
        Ok(Self {
            color: rgba8_levels(&image, true),
            data: rgba8_levels(&image, false),
        })
    }

    /// Level 0 first, followed by the stored half-size levels down to 1x1.
    /// `srgb` selects the linear-light colour chain rather than the data chain.
    pub fn levels(&self, srgb: bool) -> &[image::RgbaImage] {
        if srgb { &self.color } else { &self.data }
    }
}

/// Bound expansion before any generated level or float scratch is allocated.
fn check_mip_allocation(
    (width, height): (u32, u32),
    budget: u64,
    allocation_max: u64,
) -> std::result::Result<(), ImageError> {
    if width == 0 || height == 0 || width.max(height) > MAX_IMAGE_SIDE {
        return Err(ImageError::InvalidDimensions);
    }
    let mut retained = 0u64;
    let (mut w, mut h) = (width, height);
    loop {
        retained = retained
            .checked_add(u64::from(w) * u64::from(h) * 8)
            .ok_or(ImageError::BudgetExceeded)?;
        if w == 1 && h == 1 {
            break;
        }
        w = (w / 2).max(1);
        h = (h / 2).max(1);
    }
    let scratch = if width.max(height) > 1 {
        u64::from(width) * u64::from(height) * 16
    } else {
        0
    };
    if retained > budget || scratch > allocation_max {
        return Err(ImageError::BudgetExceeded);
    }
    Ok(())
}

/// CPU-only mip filtering, shared by preparation and the convenience upload.
pub(crate) fn rgba8_levels(image: &image::RgbaImage, srgb: bool) -> Vec<image::RgbaImage> {
    let mut levels = vec![image.clone()];
    while levels
        .last()
        .unwrap()
        .width()
        .max(levels.last().unwrap().height())
        > 1
    {
        let mip = levels.last().unwrap();
        let mut linear = image::Rgba32FImage::new(mip.width(), mip.height());
        for (to, from) in linear.pixels_mut().zip(mip.pixels()) {
            for c in 0..4 {
                let x = from[c] as f32 / 255.0;
                to[c] = if srgb && c < 3 {
                    super::srgb::to_linear(x)
                } else {
                    x
                };
            }
        }
        let small = image::imageops::resize(
            &linear,
            (mip.width() / 2).max(1),
            (mip.height() / 2).max(1),
            image::imageops::FilterType::Triangle,
        );
        let mut mip = image::RgbaImage::new(small.width(), small.height());
        for (to, from) in mip.pixels_mut().zip(small.pixels()) {
            for c in 0..4 {
                let x = if srgb && c < 3 {
                    super::srgb::from_linear(from[c])
                } else {
                    from[c]
                };
                to[c] = (x.clamp(0.0, 1.0) * 255.0).round() as u8;
            }
        }
        levels.push(mip);
    }
    levels
}

/// Texels on each side of a block.
const BLOCK: u32 = 4;
/// Bytes of a BC7 block.
const BLOCK_BYTES: usize = 16;

/// ktx2 0.5.0 eagerly parses the DFD, incrementing dimension bytes in u8.
/// Check its block bounds and unsupported 256-texel dimensions before that
/// parser. KTX 2.0 section 3.10 / Khronos Data Format 1.4 define this layout.
fn check_ktx2_dfd(bytes: &[u8]) -> Result<()> {
    let raw = bytes
        .get(..ktx2::Header::LENGTH)
        .ok_or("invalid KTX2 file: truncated header")?;
    let header = ktx2::Header::from_bytes(raw.try_into()?)
        .map_err(|error| format!("invalid KTX2 file: {error}"))?;
    let index = header.index;
    let end = index
        .dfd_byte_offset
        .checked_add(index.dfd_byte_length)
        .ok_or("invalid KTX2 data format descriptor: range overflow")?;
    let descriptor = bytes
        .get(index.dfd_byte_offset as usize..end as usize)
        .ok_or("invalid KTX2 data format descriptor: truncated section")?;
    let mut blocks = descriptor
        .get(4..)
        .ok_or("invalid KTX2 data format descriptor: truncated size")?;
    while !blocks.is_empty() {
        let header = blocks
            .get(..ktx2::dfd::BlockHeader::LENGTH)
            .ok_or("invalid KTX2 data format descriptor: truncated block header")?;
        let size = u16::from_le_bytes(header[6..8].try_into()?) as usize;
        if size < ktx2::dfd::BlockHeader::LENGTH {
            return Err(
                "invalid KTX2 data format descriptor: block shorter than its header".into(),
            );
        }
        let block = blocks
            .get(..size)
            .ok_or("invalid KTX2 data format descriptor: truncated block")?;
        // Match the same vendor/type/version as ktx2's basic-block parser;
        // other descriptor blocks have different layouts.
        if header[..6] == ktx2::dfd::BlockHeader::BASIC.as_bytes(0)[..6] {
            let dimensions = block
                .get(12..16)
                .ok_or("invalid KTX2 data format descriptor: truncated dimensions")?;
            if dimensions.contains(&0xff) {
                return Err(
                    "invalid KTX2 data format descriptor: unsupported texel-block dimension".into(),
                );
            }
        }
        blocks = &blocks[size..];
    }
    Ok(())
}

impl Image {
    /// Retained caller-supplied bytes count in the same decoded budget as
    /// imported geometry and decoded images, including both prepared mip
    /// chains and compressed images' offline-decoded companions.
    pub(super) fn charge_bytes(&self, budget: &mut Budget) -> Result<()> {
        match self {
            Self::Rgba8(image) => budget.charge(image.as_raw().len() as u64),
            Self::Rgba8Mips(image) => {
                for level in image.color.iter().chain(&image.data) {
                    budget.charge(level.as_raw().len() as u64)?;
                }
                Ok(())
            }
            Self::Compressed(image) => {
                for level in &image.levels {
                    budget.charge(level.len() as u64)?;
                }
                if let Some(decoded) = &image.decoded_level_0 {
                    budget.charge(decoded.as_raw().len() as u64)?;
                }
                Ok(())
            }
        }
    }

    /// Level 0's width and height in texels.
    pub(crate) fn size(&self) -> [u32; 2] {
        match self {
            Self::Rgba8(image) => [image.width(), image.height()],
            Self::Rgba8Mips(image) => [
                image.levels(false)[0].width(),
                image.levels(false)[0].height(),
            ],
            Self::Compressed(image) => [image.width, image.height],
        }
    }

    /// Level 0's texels for the decal atlas. BC7 decodes its own blocks;
    /// ETC2/ASTC return none without their offline decoded companion.
    pub(crate) fn texels(&self) -> Option<Cow<'_, image::RgbaImage>> {
        Some(match self {
            Self::Rgba8(image) => Cow::Borrowed(image),
            Self::Rgba8Mips(image) => Cow::Borrowed(&image.levels(false)[0]),
            Self::Compressed(image) => match &image.decoded_level_0 {
                Some(texels) => Cow::Borrowed(texels),
                None if image.format == CompressedFormat::Bc7 => Cow::Owned(image.decode_level_0()),
                None => return None,
            },
        })
    }
}

impl CompressedImage {
    /// The image a KTX2 file holds: one 2D image of BC7, ETC2 RGBA8 or
    /// ASTC 4x4 blocks (the channel
    /// that samples it picks sRGB or linear, as Bevy's loader does), with
    /// its stored levels, uncompressed or supercompressed with Zstandard.
    /// ETC2/ASTC used by material rays or decals need an offline companion
    /// supplied through `from_ktx2_with_decoded_level_0` instead.
    /// Refuses malformed data format descriptors, sides above 16384,
    /// invalid block dimensions or mip counts,
    /// and levels whose declared or decoded size differs from their block
    /// size. The total decoded chain is budgeted before level allocation;
    /// the decoder bounds regenerated blocks before buffer growth.
    pub fn from_ktx2(bytes: &[u8]) -> Result<Self> {
        Self::from_ktx2_with_budget(bytes, LoadBudget::default())
    }

    /// Read a supported block format with explicit source and decoded safety caps. The entire
    /// KTX2 source slice is checked before parsing, and the decoded chain
    /// before allocating levels. Caps do not raise dimension/device limits
    /// or guarantee sufficient memory. Use the same budget in the enclosing
    /// glTF's `LoadOptions` when supplying this image to an import.
    pub fn from_ktx2_with_budget(bytes: &[u8], budget: LoadBudget) -> Result<Self> {
        Budget::source(budget).charge(bytes.len() as u64)?;
        Self::read_ktx2(bytes, &mut Budget::decoded(budget))
    }

    /// Reads ETC2 RGBA8 or ASTC LDR 4x4 with the game's offline-decoded
    /// level 0 for ray materials and decals. The companion must decode these
    /// exact compressed blocks, with unchanged encoded-channel RGBA8 bytes.
    /// Shape and combined decoded-byte budget are checked; pixel equivalence
    /// is the exporter's responsibility. Refuses a companion for BC7.
    pub fn from_ktx2_with_decoded_level_0(bytes: &[u8], decoded: image::RgbaImage) -> Result<Self> {
        Self::from_ktx2_with_decoded_level_0_and_budget(bytes, decoded, LoadBudget::default())
    }

    /// Read ETC2/ASTC with explicit source and decoded safety caps. The
    /// decoded cap includes both stored block levels and the RGBA8 companion.
    /// As with `from_ktx2_with_budget`, allocation working memory is additional.
    pub fn from_ktx2_with_decoded_level_0_and_budget(
        bytes: &[u8],
        decoded: image::RgbaImage,
        budget: LoadBudget,
    ) -> Result<Self> {
        Budget::source(budget).charge(bytes.len() as u64)?;
        Self::read_ktx2_with_decoded(bytes, Some(decoded), &mut Budget::decoded(budget))
    }

    fn read_ktx2(bytes: &[u8], budget: &mut Budget) -> Result<Self> {
        Self::read_ktx2_with_decoded(bytes, None, budget)
    }

    fn read_ktx2_with_decoded(
        bytes: &[u8],
        decoded_level_0: Option<image::RgbaImage>,
        budget: &mut Budget,
    ) -> Result<Self> {
        check_ktx2_dfd(bytes)?;
        let reader =
            ktx2::Reader::new(bytes).map_err(|error| format!("invalid KTX2 file: {error}"))?;
        let header = reader.header();
        let format = match header.format {
            Some(ktx2::Format::BC7_UNORM_BLOCK | ktx2::Format::BC7_SRGB_BLOCK) => {
                CompressedFormat::Bc7
            }
            Some(
                ktx2::Format::ETC2_R8G8B8A8_UNORM_BLOCK | ktx2::Format::ETC2_R8G8B8A8_SRGB_BLOCK,
            ) => CompressedFormat::Etc2Rgba8,
            Some(ktx2::Format::ASTC_4x4_UNORM_BLOCK | ktx2::Format::ASTC_4x4_SRGB_BLOCK) => {
                CompressedFormat::Astc4x4
            }
            other => {
                return Err(format!(
                    "KTX2 format {other:?} is not supported; store BC7, ETC2 RGBA8 or ASTC LDR 4x4"
                )
                .into());
            }
        };
        if header.pixel_depth > 1 || header.layer_count > 1 || header.face_count != 1 {
            return Err("a KTX2 material image must be one 2D image".into());
        }
        if header.level_count == 0 {
            return Err("the KTX2 file asks for generated mips; store its mip chain".into());
        }
        let mut image = Self {
            format,
            width: header.pixel_width,
            height: header.pixel_height.max(1),
            levels: Vec::new(),
            decoded_level_0,
        };
        let full = 32 - image.width.max(image.height).leading_zeros();
        if image.width == 0
            || image.width > MAX_IMAGE_SIDE
            || image.height > MAX_IMAGE_SIDE
            || !image.width.is_multiple_of(BLOCK)
            || !image.height.is_multiple_of(BLOCK)
            || header.level_count > full
        {
            return Err(format!("invalid KTX2 dimensions or mip count; store block-aligned sides no larger than {MAX_IMAGE_SIDE} and at most a full mip chain").into());
        }
        if !image.companion_is_valid() {
            return Err("BC7 must have no decoded companion; any ETC2/ASTC decoded level 0 must match the compressed dimensions".into());
        }
        if let Some(decoded) = &image.decoded_level_0 {
            budget.charge(decoded.as_raw().len() as u64)?;
        }
        // Validate every declared level and the whole chain before allocating
        // any decoded level. Header bounds above also make level_bytes safe.
        for (index, level) in reader.levels().enumerate() {
            let expected = image.level_bytes(index);
            if level.uncompressed_byte_length != expected as u64 {
                return Err(format!(
                    "KTX2 level {index} declares {} decoded bytes; expected {expected}",
                    level.uncompressed_byte_length
                )
                .into());
            }
            budget.charge(expected as u64)?;
        }
        image.levels = reader
            .levels()
            .enumerate()
            .map(|(index, level)| {
                let expected = image.level_bytes(index);
                let decoded = match header.supercompression_scheme {
                    None => {
                        if level.data.len() != expected {
                            return Err(format!(
                                "KTX2 level {index} has {} bytes; expected {expected}",
                                level.data.len()
                            )
                            .into());
                        }
                        level.data.to_vec()
                    }
                    Some(ktx2::SupercompressionScheme::Zstandard) => {
                        // Unlike a streaming history buffer, this one-shot
                        // decoder bounds growth before literals/sequences are
                        // written and never allocates the advertised window.
                        let mut decoded = Vec::new();
                        crate::content::zstandard::decompress(
                            level.data,
                            expected + 1,
                            &mut decoded,
                        )
                        .map_err(|error| format!("KTX2 level {index}: {error}"))?;
                        decoded
                    }
                    Some(other) => return Err(format!(
                        "KTX2 supercompression {other:?} is not supported; use Zstandard or none"
                    )
                    .into()),
                };
                if decoded.len() != expected {
                    return Err(format!(
                        "KTX2 level {index} decoded to {} bytes; expected {expected}",
                        decoded.len()
                    )
                    .into());
                }
                Ok(decoded)
            })
            .collect::<Result<Vec<_>>>()?;
        Ok(image)
    }

    /// The bytes level `level` holds: its blocks, a partial edge block whole.
    pub(crate) fn level_bytes(&self, level: usize) -> usize {
        let side = |size: u32| (size >> level).max(1).div_ceil(BLOCK) as usize;
        side(self.width) * side(self.height) * BLOCK_BYTES
    }

    /// Whether the scene can upload it: sides that are multiples of the
    /// block size (wgpu's rule for a block-compressed level 0) no larger
    /// than KTX2 loading allows, which also keeps `level_bytes` within a
    /// 32-bit `usize`, and one to a full chain of levels, each of its size.
    pub(crate) fn is_valid(&self) -> bool {
        let full = (32 - self.width.max(self.height).leading_zeros()) as usize;
        self.width > 0
            && self.height > 0
            && self.companion_is_valid()
            && self.width.is_multiple_of(BLOCK)
            && self.height.is_multiple_of(BLOCK)
            && self.width <= MAX_IMAGE_SIDE
            && self.height <= MAX_IMAGE_SIDE
            && (1..=full).contains(&self.levels.len())
            && self
                .levels
                .iter()
                .enumerate()
                .all(|(level, bytes)| bytes.len() == self.level_bytes(level))
    }

    /// Companion shape is part of the image invariant, even for caller-built data.
    fn companion_is_valid(&self) -> bool {
        match (self.format, &self.decoded_level_0) {
            (_, None) => true,
            (CompressedFormat::Etc2Rgba8 | CompressedFormat::Astc4x4, Some(decoded)) => {
                decoded.dimensions() == (self.width, self.height)
            }
            _ => false,
        }
    }

    /// BC7 level 0 decoded with bcdec (MIT) as the GPU decodes it.
    /// A valid image only.
    fn decode_level_0(&self) -> image::RgbaImage {
        let mut texels = image::RgbaImage::new(self.width, self.height);
        let pitch = self.width as usize * 4;
        let blocks_wide = (self.width / BLOCK) as usize;
        let rows = texels.chunks_exact_mut(pitch * BLOCK as usize);
        for (blocks, row) in self.levels[0]
            .chunks_exact(blocks_wide * BLOCK_BYTES)
            .zip(rows)
        {
            for (column, block) in blocks.chunks_exact(BLOCK_BYTES).enumerate() {
                let at = column * BLOCK as usize * 4;
                match self.format {
                    CompressedFormat::Bc7 => bcdec_rs::bc7(block, &mut row[at..], pitch),
                    _ => unreachable!("browser formats require a predecoded companion"),
                }
            }
        }
        texels
    }
}

#[cfg(all(test, target_arch = "wasm32"))]
#[allow(dead_code)]
#[path = "../../tests/fixtures/ktx2_writer.rs"]
mod ktx2_writer;

#[cfg(test)]
mod tests {
    #[cfg(target_arch = "wasm32")]
    use super::ktx2_writer::ktx2;
    use super::*;
    #[cfg(not(target_arch = "wasm32"))]
    use crate::test_support::ktx2;
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test(unsupported = test)]
    fn explicit_ktx2_budgets_cover_source_chain_and_companion() {
        for zstd in [false, true] {
            let levels = vec![vec![11; 16], vec![22; 16]];
            let file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &levels, zstd);
            let bytes = file.len() as u64;
            let error = CompressedImage::from_ktx2_with_budget(
                &file,
                LoadBudget::new(bytes - 1, 32).unwrap(),
            )
            .unwrap_err()
            .to_string();
            assert!(
                error.contains("source load budget")
                    && error.contains(&format!("requested {bytes} bytes")),
                "{error}"
            );
            let error =
                CompressedImage::from_ktx2_with_budget(&file, LoadBudget::new(bytes, 31).unwrap())
                    .unwrap_err()
                    .to_string();
            assert!(
                error.contains("decoded load budget") && error.contains("limit 31 bytes"),
                "{error}"
            );
            let image =
                CompressedImage::from_ktx2_with_budget(&file, LoadBudget::new(bytes, 32).unwrap())
                    .unwrap();
            assert_eq!(image.levels, levels);

            let file = ktx2(
                ktx2::Format::ASTC_4x4_UNORM_BLOCK,
                [4; 2],
                &[vec![7; 16]],
                zstd,
            );
            let companion = image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 30, 40, 255]));
            let error = CompressedImage::from_ktx2_with_decoded_level_0_and_budget(
                &file,
                companion.clone(),
                LoadBudget::new(file.len() as u64, 79).unwrap(),
            )
            .unwrap_err()
            .to_string();
            assert!(
                error.contains("decoded load budget") && error.contains("limit 79 bytes"),
                "{error}"
            );
            let image = CompressedImage::from_ktx2_with_decoded_level_0_and_budget(
                &file,
                companion.clone(),
                LoadBudget::new(file.len() as u64, 80).unwrap(),
            )
            .unwrap();
            assert_eq!(image.decoded_level_0.as_ref(), Some(&companion));
        }
    }

    #[wasm_bindgen_test(unsupported = test)]
    fn raised_ktx2_budgets_never_relax_structure_validation() {
        let budget = LoadBudget::new(isize::MAX as u64, isize::MAX as u64).unwrap();
        let file = ktx2(
            ktx2::Format::BC7_UNORM_BLOCK,
            [16388, 4],
            &[vec![0; 16]],
            false,
        );
        let error = CompressedImage::from_ktx2_with_budget(&file, budget)
            .unwrap_err()
            .to_string();
        assert!(error.contains("dimensions"), "{error}");
        let mut file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &[vec![0; 16]], false);
        let decoded_at = ktx2::Header::LENGTH + 16;
        file[decoded_at..decoded_at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
        let error = CompressedImage::from_ktx2_with_budget(&file, budget)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("declares 18446744073709551615 decoded bytes; expected 16"),
            "{error}"
        );
    }

    #[wasm_bindgen_test(unsupported = test)]
    fn mip_expansion_is_preflighted_without_allocating_images() {
        assert_eq!(
            check_mip_allocation((2, 2), 39, u64::MAX),
            Err(ImageError::BudgetExceeded)
        );
        assert_eq!(
            check_mip_allocation((2, 2), 40, 63),
            Err(ImageError::BudgetExceeded)
        );
        assert_eq!(check_mip_allocation((2, 2), 40, 64), Ok(()));
        assert_eq!(
            check_mip_allocation((16384, 16384), 1 << 30, u32::MAX as u64),
            Err(ImageError::BudgetExceeded)
        );
        assert_eq!(
            check_mip_allocation((16384, 16384), 4 << 30, 4 << 30),
            Ok(())
        );
        assert_eq!(
            check_mip_allocation((16385, 1), u64::MAX, u64::MAX),
            Err(ImageError::InvalidDimensions)
        );
    }

    #[wasm_bindgen_test(unsupported = test)]
    fn prepared_rgba_mips_filter_colour_and_data_separately() {
        fn send<T: Send>() {}
        send::<Rgba8MipChain>();
        send::<ImageError>();
        assert!(Rgba8MipChain::new(image::RgbaImage::new(0, 4)).is_err());
        assert!(Rgba8MipChain::new(image::RgbaImage::new(16385, 1)).is_err());
        let source =
            image::RgbaImage::from_fn(2, 1, |x, _| image::Rgba([if x == 0 { 0 } else { 255 }; 4]));
        let prepared = Rgba8MipChain::new(source.clone()).unwrap();
        assert_eq!(prepared.levels(true)[0], source);
        assert_eq!(prepared.levels(false)[0], source);
        assert_eq!(prepared.levels(false)[1].get_pixel(0, 0).0, [128; 4]);
        assert_eq!(
            prepared.levels(true)[1].get_pixel(0, 0).0,
            [188, 188, 188, 128]
        );
        let odd = Rgba8MipChain::new(image::RgbaImage::new(7, 5)).unwrap();
        assert_eq!(
            odd.levels(false)
                .iter()
                .map(|m| m.dimensions())
                .collect::<Vec<_>>(),
            [(7, 5), (3, 2), (1, 1)]
        );
    }

    #[wasm_bindgen_test(unsupported = test)]
    fn browser_compressed_levels_allow_optional_budgeted_matching_companions() {
        for format in [
            ktx2::Format::ETC2_R8G8B8A8_UNORM_BLOCK,
            ktx2::Format::ASTC_4x4_SRGB_BLOCK,
        ] {
            for zstd in [false, true] {
                let levels = vec![vec![0xff; 16], vec![0; 16], vec![42; 16]];
                let file = ktx2(format, [4; 2], &levels, zstd);
                let raster = CompressedImage::from_ktx2(&file).unwrap();
                assert_eq!(raster.levels, levels);
                assert!(raster.decoded_level_0.is_none());
                assert!(raster.is_valid());
                assert!(Image::Compressed(raster).texels().is_none());
                let decoded = image::RgbaImage::from_pixel(4, 4, image::Rgba([20, 60, 100, 128]));
                let image = CompressedImage::from_ktx2_with_decoded_level_0(&file, decoded.clone())
                    .unwrap();
                assert_eq!(image.levels, levels);
                assert_eq!(image.decoded_level_0.as_ref(), Some(&decoded));
                assert!(image.is_valid());
                assert_eq!(
                    Image::Compressed(image).texels().unwrap().as_ref(),
                    &decoded
                );
                let wrong = image::RgbaImage::new(8, 4);
                assert!(CompressedImage::from_ktx2_with_decoded_level_0(&file, wrong).is_err());
                // 48 compressed bytes + 64 companion bytes, not just either part.
                let error = CompressedImage::read_ktx2_with_decoded(
                    &file,
                    Some(decoded),
                    &mut Budget::new(111, "decoded"),
                )
                .unwrap_err();
                assert!(error.to_string().contains("budget"));
            }
        }
        let file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &[vec![0; 16]], false);
        assert!(
            CompressedImage::from_ktx2_with_decoded_level_0(&file, image::RgbaImage::new(4, 4))
                .is_err()
        );
    }

    // ASTC contents are opaque at runtime: hostile blocks never enter a CPU
    // codec, including on wasm (where a panic cannot be caught).
    #[wasm_bindgen_test(unsupported = test)]
    fn hostile_astc_payloads_are_stored_without_cpu_decoding() {
        let mut seed = 17u64;
        for _ in 0..256 {
            let mut block = vec![0; 16];
            for byte in &mut block {
                seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
                *byte = (seed >> 32) as u8;
            }
            let file = ktx2(
                ktx2::Format::ASTC_4x4_UNORM_BLOCK,
                [4; 2],
                &[block.clone()],
                false,
            );
            let decoded = image::RgbaImage::new(4, 4);
            let loaded =
                CompressedImage::from_ktx2_with_decoded_level_0(&file, decoded.clone()).unwrap();
            assert_eq!(loaded.levels[0], block);
            assert_eq!(
                Image::Compressed(loaded).texels().unwrap().as_ref(),
                &decoded
            );
        }
    }

    // A DFD stores each block dimension minus one. 0xff makes ktx2's
    // u8 increment overflow; malformed bytes must fail the public loader.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_invalid_descriptor_dimensions_return_an_error() {
        let valid = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &[vec![0; 16]], false);
        assert!(CompressedImage::from_ktx2(&valid).is_ok());
        let dfd = u32::from_le_bytes(valid[48..52].try_into().unwrap()) as usize;
        for axis in 0..4 {
            let mut file = valid.clone();
            file[dfd + 16 + axis] = 0xff;
            let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
            assert!(error.contains("data format descriptor"), "{error}");
        }
    }

    // The BC7 format independently requires one 16-byte block for 4x4.
    // A 64 KiB Zstandard payload lies about its decoded size. Its own frame
    // header declares that expansion, so it must fail at the decoder cap
    // before any oversized block or output is allocated.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_zstandard_output_is_bounded_by_the_expected_size() {
        let mut file = ktx2(
            ktx2::Format::BC7_UNORM_BLOCK,
            [4; 2],
            &[vec![0; 65536]],
            true,
        );
        // KTX2 level index uncompressedByteLength, independently laid out
        // in KTX 2.0 section 3.9: 80-byte header, then three u64 fields.
        file[96..104].copy_from_slice(&16u64.to_le_bytes());
        let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
        assert!(error.contains("level 0: output limit exceeded"), "{error}");
        let short = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &[vec![0; 15]], true);
        let mut short = short;
        short[96..104].copy_from_slice(&16u64.to_le_bytes());
        let error = CompressedImage::from_ktx2(&short).unwrap_err().to_string();
        assert!(
            error.contains("decoded to 15 bytes; expected 16"),
            "{error}"
        );
    }

    // A 1 GiB advertised window must not force a history allocation before
    // a 16-byte level can refuse a 128 KiB RLE block. The whole source is
    // ten bytes; RFC 8878's window/block headers independently define it.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_large_zstandard_window_does_not_allocate_before_output_refusal() {
        let frame = [0x28, 0xb5, 0x2f, 0xfd, 0x00, 0xa0, 0x03, 0x00, 0x10, 42];
        let file = with_frame([4; 2], 16, &frame);
        let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
        assert!(
            error.contains("level 0") && error.contains("output limit exceeded"),
            "{error}"
        );
        // Observe the API's actual output allocation as well as its error:
        // rejecting after regenerating then truncating this block would keep
        // the oversized capacity and fail this assertion.
        let mut output = Vec::new();
        assert_eq!(
            crate::content::zstandard::decompress(&frame, 17, &mut output),
            Err(crate::content::zstandard::Error::OutputLimit)
        );
        assert_eq!(output.capacity(), 0);
    }

    // A compressed block encodes two one-byte literals and two matches of
    // 131074 bytes each (ML code52 +16 extra bits). Its 262150 regenerated
    // bytes exceed RFC 8878's 128 KiB block maximum even though the level's
    // own 262144-byte budget is large enough for either first sequence.
    // Checking only the frame window or collecting output cannot enforce it.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_malformed_sequence_expansion_is_refused_before_output() {
        let frame = [
            0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x38, // 128 KiB window, no size
            0x6d, 0x00, 0x00, // Last compressed block: 13 stored bytes
            0x10, b'A', b'A', // Two raw literals
            2, 0x54, 1, 0, 52, // Two sequences; RLE LL=1, OF=0, ML=52
            0xff, 0xff, 0xff, 0xff, 1, // Two 16-bit extras + end marker
        ];
        let file = with_frame([512; 2], 262144, &frame);
        let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
        assert!(error.contains("Block_Maximum_Size"), "{error}");
        let mut output = Vec::new();
        assert!(matches!(
            crate::content::zstandard::decompress(&frame, 262144, &mut output),
            Err(crate::content::zstandard::Error::Corrupt(
                "block regenerates more than Block_Maximum_Size"
            ))
        ));
        assert_eq!(output.capacity(), 0);
    }

    // RLE literals have their own scratch buffer: their regenerated header
    // must be checked against the block bound before allocating that buffer.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_malformed_literal_expansion_is_refused_before_scratch_growth() {
        let frame = [
            0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x38, 0x2d, 0,
            0, // Last compressed block: 5 stored bytes
            0xfd, 0xff, 0x3f, b'A', 0, // RLE literals: 262143 bytes; no sequences
        ];
        let file = with_frame([512; 2], 262144, &frame);
        let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
        assert!(error.contains("literals larger than a block"), "{error}");
    }

    fn with_frame(size: [u32; 2], expected: u64, frame: &[u8]) -> Vec<u8> {
        let mut file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, size, &[vec![0; 16]], true);
        let at = u64::from_le_bytes(file[80..88].try_into().unwrap()) as usize;
        file[88..96].copy_from_slice(&(frame.len() as u64).to_le_bytes());
        file[96..104].copy_from_slice(&expected.to_le_bytes());
        file.truncate(at);
        file.extend_from_slice(frame);
        file
    }

    // A 4x4 BC7 chain with two levels holds 32 bytes. A budget of 24 must
    // reject the whole chain before it notices deliberately broken level 0.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_charges_the_whole_chain_before_decompressing() {
        let mut file = ktx2(
            ktx2::Format::BC7_UNORM_BLOCK,
            [4; 2],
            &[vec![0; 16], vec![0; 16]],
            true,
        );
        let at = u64::from_le_bytes(file[80..88].try_into().unwrap()) as usize;
        file[at] = 0; // Break the Zstandard magic.
        let error = CompressedImage::read_ktx2(&file, &mut Budget::new(24, "decoded"))
            .unwrap_err()
            .to_string();
        assert!(error.contains("budget"), "{error}");
    }

    // The loader must reject dimensions/mips before it decodes bad payloads,
    // including oversized sides whose expected sizes could overflow wasm32.
    #[wasm_bindgen_test(unsupported = test)]
    fn ktx2_rejects_invalid_shapes_and_level_sizes_during_load() {
        for size in [[3, 4], [20000, 20000], [u32::MAX; 2]] {
            let file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, size, &[vec![0; 16]], true);
            let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
            assert!(error.contains("dimensions"), "{error}");
        }
        let file = ktx2(
            ktx2::Format::BC7_UNORM_BLOCK,
            [4; 2],
            &vec![vec![0; 16]; 4],
            false,
        );
        let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
        assert!(error.contains("mip count"), "{error}");
        for zstd in [false, true] {
            let file = ktx2(ktx2::Format::BC7_UNORM_BLOCK, [4; 2], &[vec![0; 15]], zstd);
            let error = CompressedImage::from_ktx2(&file).unwrap_err().to_string();
            assert!(
                error.contains("declares 15 decoded bytes; expected 16"),
                "{error}"
            );
        }
    }

    // A game-built image skips `from_ktx2`'s side bound. On wasm32 the 4 GiB
    // level 0 of a 65536-texel square passes `usize`, so sizing it to check
    // its level overflowed (a panic) instead of refusing the image.
    #[wasm_bindgen_test(unsupported = test)]
    fn a_game_built_image_past_the_side_bound_is_invalid() {
        let image = CompressedImage {
            format: CompressedFormat::Bc7,
            decoded_level_0: None,
            width: 65536,
            height: 65536,
            levels: vec![vec![0; 16]],
        };
        assert!(!image.is_valid());
    }
}