Formats: inline repeated micro-tile copies when detiling textures #603

Merged
AwsAli05 merged 1 commit from upstream-pr/603 into main 2026-11-25 00:20:27 +00:00
AwsAli05 commented 2026-11-24 05:24:49 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by AwsAli05 on 2026-11-24T05:24:49Z.


Texture uploads convert console micro-tiles to linear rows before the host GPU can sample them. The existing row walk finds contiguous runs, but passes a runtime length to every copy. This change checks the repeated run length once per subresource. It dispatches 8-, 16- and 32-byte runs once per row, which lets the compiler inline the individual copies. The final run and irregular rows still use their recorded lengths.

Detile timings

Single-threaded Layout::detile on a Ryzen 7 7700 with Rust 1.98.1, x86_64-pc-windows-gnu, optimized library linked from a separate binary. Times are milliseconds per complete texture. Each process measured seven batches of 16 copies after warm-up. The table gives the median across three process medians for each revision, with run order reversed for the middle pair.

Synthetic input Swizzle main at d2a4bae This change
1920×1080 RGBA8 64KB_D 1.015 0.507
4096×4096 BC7 64KB_D 2.497 1.875
4096×4096 BC1 64KB_S 0.956 0.536
1919×1079 R8 4KB_D 0.458 0.235
1920×1080 RGBA8 Linear 0.122 0.122

All 20 active victory-formats tests pass, including byte-for-byte comparisons against per-element swizzled offsets, round trips, mip tails and padding checks. Three reference-data tests were ignored. These timings measure conversion on the CPU. Gameplay frame time is unmeasured. The full diagnostics workspace run on this GNU target also reported two failures outside the changed crate. The loader fixture passes /DELAYLOAD to the GNU linker, and the PE test expects a TLS directory in its own test binary.

Reproduce the benchmark

Save the Rust source below as bench.rs outside the checkout. From that directory, run the following on each revision, with $repo set to its checkout path.

rustc --edition 2024 -O --crate-name victory_formats --crate-type rlib "$repo/crates/victory-formats/src/lib.rs" -o libvictory_formats.rlib
rustc --edition 2024 -O bench.rs --extern victory_formats=libvictory_formats.rlib -o detile-bench.exe
.\detile-bench.exe
use std::{hint::black_box, time::Instant};
use texture::{Desc, Dimension, Layout, Swizzle};
use victory_formats::texture;
fn main() {
    for (name, width, height, block, elem, swizzle) in [
        ("rgba8", 1920, 1080, 1, 4, Swizzle::SW_64KB_D),
        ("bc7", 4096, 4096, 4, 16, Swizzle::SW_64KB_D),
        ("bc1", 4096, 4096, 4, 8, Swizzle::SW_64KB_S),
        ("r8-odd", 1919, 1079, 1, 1, Swizzle::SW_4KB_D),
        ("linear", 1920, 1080, 1, 4, Swizzle::LINEAR),
    ] {
        let l = Layout::new(&Desc {
            dimension: Dimension::Tex2d,
            width,
            height,
            depth: 1,
            mips: 1,
            element_bytes: elem,
            block,
            samples: 1,
            swizzle,
        })
        .unwrap();
        let tiled: Vec<_> = (0..l.size).map(|i| (i * 117 >> 7) as u8).collect();
        let row = (width.div_ceil(block) * elem) as usize;
        let len = row * height.div_ceil(block) as usize;
        let mut out = vec![0; len];
        let mut times = Vec::new();
        for batch in 0..8 {
            let start = Instant::now();
            for _ in 0..16 {
                l.detile(black_box(&tiled), 0, 0, black_box(&mut out), row, len)
                    .unwrap();
                black_box(&out);
            }
            if batch != 0 {
                times.push(start.elapsed().as_secs_f64() * 1000. / 16.);
            }
        }
        times.sort_by(f64::total_cmp);
        println!(
            "{name} {:.3} ms {}",
            times[3],
            out.iter().map(|&b| b as u64).sum::<u64>()
        );
    }
}
<!-- greyfinch-sync:Marvisak/VIctory:issue:6575275030 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/603). Originally posted by [AwsAli05](https://github.com/AwsAli05) on 2026-11-24T05:24:49Z. --- Texture uploads convert console micro-tiles to linear rows before the host GPU can sample them. The existing row walk finds contiguous runs, but passes a runtime length to every copy. This change checks the repeated run length once per subresource. It dispatches 8-, 16- and 32-byte runs once per row, which lets the compiler inline the individual copies. The final run and irregular rows still use their recorded lengths. ### Detile timings Single-threaded `Layout::detile` on a Ryzen 7 7700 with Rust 1.98.1, x86_64-pc-windows-gnu, optimized library linked from a separate binary. Times are milliseconds per complete texture. Each process measured seven batches of 16 copies after warm-up. The table gives the median across three process medians for each revision, with run order reversed for the middle pair. | Synthetic input | Swizzle | main at d2a4bae | This change | |---|---|---:|---:| | 1920×1080 RGBA8 | 64KB_D | 1.015 | 0.507 | | 4096×4096 BC7 | 64KB_D | 2.497 | 1.875 | | 4096×4096 BC1 | 64KB_S | 0.956 | 0.536 | | 1919×1079 R8 | 4KB_D | 0.458 | 0.235 | | 1920×1080 RGBA8 | Linear | 0.122 | 0.122 | All 20 active `victory-formats` tests pass, including byte-for-byte comparisons against per-element swizzled offsets, round trips, mip tails and padding checks. Three reference-data tests were ignored. These timings measure conversion on the CPU. Gameplay frame time is unmeasured. The full diagnostics workspace run on this GNU target also reported two failures outside the changed crate. The loader fixture passes /DELAYLOAD to the GNU linker, and the PE test expects a TLS directory in its own test binary. <details> <summary>Reproduce the benchmark</summary> Save the Rust source below as `bench.rs` outside the checkout. From that directory, run the following on each revision, with `$repo` set to its checkout path. ```powershell rustc --edition 2024 -O --crate-name victory_formats --crate-type rlib "$repo/crates/victory-formats/src/lib.rs" -o libvictory_formats.rlib rustc --edition 2024 -O bench.rs --extern victory_formats=libvictory_formats.rlib -o detile-bench.exe .\detile-bench.exe ``` ```rust use std::{hint::black_box, time::Instant}; use texture::{Desc, Dimension, Layout, Swizzle}; use victory_formats::texture; fn main() { for (name, width, height, block, elem, swizzle) in [ ("rgba8", 1920, 1080, 1, 4, Swizzle::SW_64KB_D), ("bc7", 4096, 4096, 4, 16, Swizzle::SW_64KB_D), ("bc1", 4096, 4096, 4, 8, Swizzle::SW_64KB_S), ("r8-odd", 1919, 1079, 1, 1, Swizzle::SW_4KB_D), ("linear", 1920, 1080, 1, 4, Swizzle::LINEAR), ] { let l = Layout::new(&Desc { dimension: Dimension::Tex2d, width, height, depth: 1, mips: 1, element_bytes: elem, block, samples: 1, swizzle, }) .unwrap(); let tiled: Vec<_> = (0..l.size).map(|i| (i * 117 >> 7) as u8).collect(); let row = (width.div_ceil(block) * elem) as usize; let len = row * height.div_ceil(block) as usize; let mut out = vec![0; len]; let mut times = Vec::new(); for batch in 0..8 { let start = Instant::now(); for _ in 0..16 { l.detile(black_box(&tiled), 0, 0, black_box(&mut out), row, len) .unwrap(); black_box(&out); } if batch != 0 { times.push(start.elapsed().as_secs_f64() * 1000. / 16.); } } times.sort_by(f64::total_cmp); println!( "{name} {:.3} ms {}", times[3], out.iter().map(|&b| b as u64).sum::<u64>() ); } } ``` </details>
mercuryVM commented 2026-11-24 09:05:46 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by mercuryVM on 2026-11-24T08:13:17Z.

Review: APPROVED


Tested 705a2f6 on Windows 11, RTX 5070, MSVC: cargo test --workspace --no-fail-fast passes (264 passed, 0 failed), including the byte-for-byte detile comparisons in victory-formats.

  • Behaviour is unchanged. run_len is Some(n) only when every run but the last has length n. Then copy_runs::<N> passes the constant, otherwise each run's own length, and the last run (possibly short at a mip edge) always uses its recorded length. Same calls, same arguments, same order.
  • Speed comes only from the compiler seeing a constant length in copy. I didn't re-run your timings, but the change can't make results differ.

No issues found.

AI-assisted (Claude Code).

<!-- greyfinch-sync:Marvisak/VIctory:review:6035736875 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/603#pullrequestreview-6035736875). Originally posted by [mercuryVM](https://github.com/mercuryVM) on 2026-11-24T08:13:17Z. **Review:** APPROVED --- Tested 705a2f6 on Windows 11, RTX 5070, MSVC: `cargo test --workspace --no-fail-fast` passes (264 passed, 0 failed), including the byte-for-byte detile comparisons in `victory-formats`. - Behaviour is unchanged. `run_len` is `Some(n)` only when every run but the last has length n. Then `copy_runs::<N>` passes the constant, otherwise each run's own length, and the last run (possibly short at a mip edge) always uses its recorded length. Same calls, same arguments, same order. - Speed comes only from the compiler seeing a constant length in `copy`. I didn't re-run your timings, but the change can't make results differ. No issues found. AI-assisted (Claude Code).
fromthemoonx commented 2026-11-24 09:06:07 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by fromthemoonx on 2026-11-24T08:12:16Z.


Tested 705a2f6 merged onto current main (f67c50c, merges cleanly) on another CPU and the MSVC target.

Environment: Windows 11 Pro build 26300, AMD Ryzen 7 5700X (Zen 3), 16 GB, Rust 1.98.1 x86_64-pc-windows-msvc.

Same output as main. A throwaway in-crate test (not pushed) detiles every subresource, then tiles it back, and hashes everything (FNV-1a), across:

  • 16 swizzle modes: LINEAR, the 256B/4KB/64KB S and D modes, the _T and the _X ones
  • 1D, 2D, 2D arrays of 3, 3D depth 5
  • element sizes 1/2/4/8/16 and BC 8/16
  • widths 1–1919 and heights 1–1079 (odd sizes included), 4 mips
revision subresources bytes digest
main f67c50c 37,080 3,233,909,767 f393252946004ca1
main + this PR 37,080 3,233,909,767 f393252946004ca1

So detile and tile are byte-identical, including the error results for invalid combinations.

Timing (single-threaded Layout::detile, release test binary, 16 copies per batch, 10 measured batches, medians of three alternating runs per revision):

synthetic input swizzle main this PR
1920×1080 RGBA8 64KB_D 1.500 ms 0.640 ms
4096×4096 BC7 64KB_D 2.457 ms 1.470 ms
4096×4096 BC1 64KB_S 1.529 ms 0.672 ms
1919×1079 R8 4KB_D 0.969 ms 0.317 ms

Every run of the PR was faster than every run of main on all four inputs. The gains here (about 1.7–3×) are larger than on your Zen 4 numbers, mostly because main is slower on this CPU.

Other checks (on the merge):

  • cargo test --locked -p victory-formats: 20 passed, 3 ignored
  • cargo test --locked --workspace: 291 passed, 0 failed, 5 ignored
  • cargo clippy -p victory-formats --all-targets: no warnings
  • cargo xtask policy: 152 files ok; git diff --check: clean
  • cargo fmt --check lists the same 35 places in texture.rs on main, d2a4bae and this PR: none are new

Not tested: real title textures or frame time (no game data).

AI-assisted (Claude Code) ran the checks and drafted this comment.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7125850121 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/603#issuecomment-7125850121). Originally posted by [fromthemoonx](https://github.com/fromthemoonx) on 2026-11-24T08:12:16Z. --- Tested `705a2f6` merged onto current `main` (`f67c50c`, merges cleanly) on another CPU and the MSVC target. **Environment:** Windows 11 Pro build 26300, AMD Ryzen 7 5700X (Zen 3), 16 GB, Rust 1.98.1 `x86_64-pc-windows-msvc`. **Same output as `main`.** A throwaway in-crate test (not pushed) detiles every subresource, then tiles it back, and hashes everything (FNV-1a), across: - 16 swizzle modes: `LINEAR`, the 256B/4KB/64KB S and D modes, the `_T` and the `_X` ones - 1D, 2D, 2D arrays of 3, 3D depth 5 - element sizes 1/2/4/8/16 and BC 8/16 - widths 1–1919 and heights 1–1079 (odd sizes included), 4 mips | revision | subresources | bytes | digest | |---|---|---|---| | `main` `f67c50c` | 37,080 | 3,233,909,767 | `f393252946004ca1` | | `main` + this PR | 37,080 | 3,233,909,767 | `f393252946004ca1` | So `detile` and `tile` are byte-identical, including the error results for invalid combinations. **Timing** (single-threaded `Layout::detile`, release test binary, 16 copies per batch, 10 measured batches, medians of three alternating runs per revision): | synthetic input | swizzle | `main` | this PR | |---|---|---:|---:| | 1920×1080 RGBA8 | 64KB_D | 1.500 ms | 0.640 ms | | 4096×4096 BC7 | 64KB_D | 2.457 ms | 1.470 ms | | 4096×4096 BC1 | 64KB_S | 1.529 ms | 0.672 ms | | 1919×1079 R8 | 4KB_D | 0.969 ms | 0.317 ms | Every run of the PR was faster than every run of `main` on all four inputs. The gains here (about 1.7–3×) are larger than on your Zen 4 numbers, mostly because `main` is slower on this CPU. **Other checks** (on the merge): - `cargo test --locked -p victory-formats`: 20 passed, 3 ignored - `cargo test --locked --workspace`: 291 passed, 0 failed, 5 ignored - `cargo clippy -p victory-formats --all-targets`: no warnings - `cargo xtask policy`: 152 files ok; `git diff --check`: clean - `cargo fmt --check` lists the same 35 places in `texture.rs` on `main`, `d2a4bae` and this PR: none are new **Not tested:** real title textures or frame time (no game data). AI-assisted (Claude Code) ran the checks and drafted this comment.
catminou4 commented 2026-11-24 12:04:02 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by catminou4 on 2026-11-24T11:07:08Z.

Review: APPROVED


Clean optimization, semantics preserved. Splitting runs into body+last is correct: run_len is Some only when every body run has the same length (checked via body.iter().all), and the const-generic copy_runs::<N> is only selected for 8/16/32 — anything else falls back to copy_runs::<0>, which uses each run's own length, exactly the old behavior. The last run always uses N=0 since a mip can end partway through it. Edge cases check out: single-run (runs.len()==1) gives empty body + run_len=None → no-op body, last copied with real length; empty runs can't happen (guarded upstream by the loop that pushes runs).

Verified locally: test-merge with current main (ffe310e) is clean; cargo test -p victory-formats --locked on the merged tree (macOS arm64, rustc 1.98.1) → 23 passed / 0 failed / 4 ignored. No new tests, but this is a pure copy-loop refactor covered by the existing detiling tests.

<!-- greyfinch-sync:Marvisak/VIctory:review:6038085794 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/603#pullrequestreview-6038085794). Originally posted by [catminou4](https://github.com/catminou4) on 2026-11-24T11:07:08Z. **Review:** APPROVED --- Clean optimization, semantics preserved. Splitting `runs` into body+last is correct: `run_len` is `Some` only when every body run has the same length (checked via `body.iter().all`), and the const-generic `copy_runs::<N>` is only selected for 8/16/32 — anything else falls back to `copy_runs::<0>`, which uses each run's own length, exactly the old behavior. The last run always uses N=0 since a mip can end partway through it. Edge cases check out: single-run (`runs.len()==1`) gives empty body + `run_len=None` → no-op body, last copied with real length; empty `runs` can't happen (guarded upstream by the loop that pushes runs). Verified locally: test-merge with current main (`ffe310e`) is clean; `cargo test -p victory-formats --locked` on the merged tree (macOS arm64, rustc 1.98.1) → **23 passed / 0 failed / 4 ignored**. No new tests, but this is a pure copy-loop refactor covered by the existing detiling tests.
upstream-sync closed this pull request 2026-11-25 01:04:26 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Marvisak/VIctory!603
No description provided.