Speed up tiled texture copies with fixed-size chunks #186

Open
github-bot wants to merge 1 commit from github-bot/gh-186 into main AGit
Owner

@⁠venglov on GitHub · 2026-11-24 22:19 UTC · original
venglov:perf/tiled-texture-copy-chunks → main · +118 −29 · 1 files · 1 commits · open

Summary

The GPU upload path calls Layout::detile on the submitting thread when a sampled texture changes. The existing implementation specializes the width of 8-, 16-, and 32-byte copies, but still builds checked byte ranges for both sides of each copy.

For aligned, equal-sized runs, slice the linear row once and copy through fixed-size byte arrays. Each copy then only needs to index the tiled side. Both copy directions use the same traversal and validation. Short final runs, irregular layouts, and linear copies use byte ranges.

The fixed-width copies already present in this fork specialize the copy length. This PR also removes the per-run linear slice checks. The related proposals split larger subresources into row bands (#92) and reduce time waiting for remaps (#175). The fixed-width changes in VIctory #603 and VIctory #1097 use byte slices for individual copies.

Measurements

Single-threaded, synthetic uploads on an Apple M1 Pro. The Windows x64 build used Rust 1.98.1 targeting x86_64-pc-windows-gnu and ran under Wine 11.21 with Rosetta. Baseline is 2119b0e. The before and after routines run in the same process, alternate batch order, and compare the entire output against each other before timing.

Detile input Swizzle Before After Time saved
4096×4096 RGBA8 64KB_D 11.666 ms 7.194 ms 38%
2560×1440 RGBA8 64KB_D 2.364 ms 1.500 ms 37%
3840×2160 RGBA8 4KB_S 4.149 ms 3.004 ms 28%
4096×4096 BC7 64KB_D 2.248 ms 1.489 ms 34%
1919×1079 R8 4KB_D 0.341 ms 0.261 ms 24%
1920×1080 RGBA8 Linear 0.260 ms 0.260 ms <1%

A second Wine run reproduced the tiled detile savings within one percentage point. The reverse copy took 10–34% less time across the same tiled cases. The native arm64 macOS build took 9–34% less time across the ten tiled detile cases.

Windows x64 with MSVC

The same benchmark ran twice on a GitHub-hosted Windows VM (AMD EPYC 9V45, Rust 1.98.1, x86_64-pc-windows-msvc). The ranges report the two process medians. Each run checked the full output byte-for-byte before timing. Benchmark log

Detile input Swizzle Change in elapsed time
1919×1079 R8 4KB_D 12–15% less
256×256 RGBA8 64KB_D 7–8% less
2560×1440 RGBA8 64KB_D 4–16% less
4096×4096 RGBA8 64KB_D 0.9–1.2% more
3840×2160 RGBA16 64KB_S 0.4–4.1% more
1920×1080 RGBA8 Linear 0.1–0.6% less

On this runner the gains were concentrated in the smaller tiled cases. The larger cases generally moved by a few percent or less. Gameplay frame time remains unmeasured.

Validation

  • cargo test -p victory-formats --locked passed on macOS and for Windows x64 under Wine (25 passed, four ignored on each).
  • The regression test checks output bytes against per-element offsets for all six addressable tiled 2D modes, all five element sizes, odd row pitches, mip chains, and two array slices.
  • Workspace Clippy passed for the Windows GNU target with all targets and features. The Windows MSVC cross-check also passed with blake3/pure to avoid needing MASM on macOS.
  • cargo xtask policy and git diff --check passed.
  • A local differential check matched both copy directions on 720 addressable layouts (8,980 subresources), including block compression, 1D and 2D arrays, and thick 3D volumes.
  • In the fork's Windows x64 MSVC run, workspace tests passed (497 passed, seven ignored), along with Clippy in both default and all-features configurations. Release-mode formats tests also passed (25 passed, four ignored). Windows run

AI-assisted implementation and verification.

Reproduce the synthetic detile benchmark

From the checkout, extract crates/victory-formats/src/texture.rs from 2119b0e into base.rs and copy the changed file to patch.rs in a temporary directory. Save the program below beside them and compile with rustc +1.98.1 --edition 2024 -O -A dead_code bench.rs. For the Wine timings, add --target x86_64-pc-windows-gnu -C linker=x86_64-w64-mingw32-gcc and run the resulting executable with Wine.

#[path = "base.rs"]
mod base;
#[path = "patch.rs"]
mod patch;

use std::{hint::black_box, time::Instant};

macro_rules! bench_fn {
    ($mod:ident, $width:ident, $height:ident, $bpe:ident, $block:ident, $mode:ident) => {{
        let layout = $mod::Layout::new(&$mod::Desc {
            dimension: $mod::Dimension::Tex2d,
            width: $width,
            height: $height,
            depth: 1,
            mips: 1,
            element_bytes: $bpe,
            block: $block,
            samples: 1,
            swizzle: $mod::Swizzle($mode),
        }).unwrap();
        (layout.size, move |src: &[u8], dst: &mut [u8], row: usize, len: usize| {
            layout.detile(black_box(src), 0, 0, black_box(dst), row, len).unwrap();
        })
    }};
}

fn run(name: &str, width: u32, height: u32, bpe: u32, block: u32, mode: u32) {
    let (asize, a) = bench_fn!(base, width, height, bpe, block, mode);
    let (bsize, b) = bench_fn!(patch, width, height, bpe, block, mode);
    assert_eq!(asize, bsize);
    let mut seed = 1u64;
    let src: Vec<_> = (0..asize).map(|_| {
        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
        (seed >> 32) as u8
    }).collect();
    let row = ((width.div_ceil(block) * bpe).next_multiple_of(256)) as usize;
    let len = row * height.div_ceil(block) as usize;
    let mut out = vec![0xcc; len];
    let mut expected = out.clone();
    a(&src, &mut expected, row, len);
    b(&src, &mut out, row, len);
    assert_eq!(out, expected);
    let mut times = [vec![], vec![]];
    let iter = (320_000_000 / len).clamp(6, 1024);
    for batch in 0..10 {
        for i in [batch % 2, 1 - batch % 2] {
            let t = Instant::now();
            for _ in 0..iter {
                if i == 0 { a(&src, &mut out, row, len); } else { b(&src, &mut out, row, len); }
                black_box(&out);
            }
            if batch >= 3 {
                times[i].push(t.elapsed().as_secs_f64() * 1000. / iter as f64);
            }
        }
    }
    times.iter_mut().for_each(|s| s.sort_by(f64::total_cmp));
    let (a, b) = (times[0][3], times[1][3]);
    println!("{name:16} {a:8.4} {b:8.4} {:7.1}%", 100. * (b / a - 1.));
}

fn main() {
    for (name, w, h, n, b, m) in [
        ("rgba8 4K-D", 4096, 4096, 4, 1, 10),
        ("rgba8 1440p-D", 2560, 1440, 4, 1, 10),
        ("rgba8 4K-S", 3840, 2160, 4, 1, 5),
        ("rgba8 1080p-S", 1920, 1080, 4, 1, 9),
        ("rgba16 4K-S", 3840, 2160, 8, 1, 9),
        ("bc7 4K-D", 4096, 4096, 16, 4, 10),
        ("bc1 4K-S", 4096, 4096, 8, 4, 9),
        ("r8 odd-D", 1919, 1079, 1, 1, 6),
        ("rgba8 512-D", 512, 512, 4, 1, 10),
        ("rgba8 256-D", 256, 256, 4, 1, 10),
        ("rgba8 linear", 1920, 1080, 4, 1, 0),
    ] {
        run(name, w, h, n, b, m);
    }
}
**@⁠venglov** on GitHub · 2026-11-24 22:19 UTC · [original](https://github.com/fxceless/victory-fork/pull/186) `venglov:perf/tiled-texture-copy-chunks` → `main` · +118 −29 · 1 files · 1 commits · open ## Summary The GPU upload path calls `Layout::detile` on the submitting thread when a sampled texture changes. The existing implementation specializes the width of 8-, 16-, and 32-byte copies, but still builds checked byte ranges for both sides of each copy. For aligned, equal-sized runs, slice the linear row once and copy through fixed-size byte arrays. Each copy then only needs to index the tiled side. Both copy directions use the same traversal and validation. Short final runs, irregular layouts, and linear copies use byte ranges. The fixed-width copies already present in this fork specialize the copy length. This PR also removes the per-run linear slice checks. The related proposals split larger subresources into row bands (#92) and reduce time waiting for remaps (#175). The fixed-width changes in [VIctory #603](https://github.com/Marvisak/VIctory/pull/603) and [VIctory #1097](https://github.com/Marvisak/VIctory/pull/1097) use byte slices for individual copies. ## Measurements Single-threaded, synthetic uploads on an Apple M1 Pro. The Windows x64 build used Rust 1.98.1 targeting `x86_64-pc-windows-gnu` and ran under Wine 11.21 with Rosetta. Baseline is `2119b0e`. The before and after routines run in the same process, alternate batch order, and compare the entire output against each other before timing. | Detile input | Swizzle | Before | After | Time saved | | --- | --- | ---: | ---: | ---: | | 4096×4096 RGBA8 | 64KB_D | 11.666 ms | 7.194 ms | 38% | | 2560×1440 RGBA8 | 64KB_D | 2.364 ms | 1.500 ms | 37% | | 3840×2160 RGBA8 | 4KB_S | 4.149 ms | 3.004 ms | 28% | | 4096×4096 BC7 | 64KB_D | 2.248 ms | 1.489 ms | 34% | | 1919×1079 R8 | 4KB_D | 0.341 ms | 0.261 ms | 24% | | 1920×1080 RGBA8 | Linear | 0.260 ms | 0.260 ms | <1% | A second Wine run reproduced the tiled detile savings within one percentage point. The reverse copy took 10–34% less time across the same tiled cases. The native arm64 macOS build took 9–34% less time across the ten tiled detile cases. ### Windows x64 with MSVC The same benchmark ran twice on a GitHub-hosted Windows VM (AMD EPYC 9V45, Rust 1.98.1, `x86_64-pc-windows-msvc`). The ranges report the two process medians. Each run checked the full output byte-for-byte before timing. [Benchmark log](https://github.com/venglov/victory-fork/actions/runs/45501217177/job/138824710357) | Detile input | Swizzle | Change in elapsed time | | --- | --- | ---: | | 1919×1079 R8 | 4KB_D | 12–15% less | | 256×256 RGBA8 | 64KB_D | 7–8% less | | 2560×1440 RGBA8 | 64KB_D | 4–16% less | | 4096×4096 RGBA8 | 64KB_D | 0.9–1.2% more | | 3840×2160 RGBA16 | 64KB_S | 0.4–4.1% more | | 1920×1080 RGBA8 | Linear | 0.1–0.6% less | On this runner the gains were concentrated in the smaller tiled cases. The larger cases generally moved by a few percent or less. Gameplay frame time remains unmeasured. ## Validation - `cargo test -p victory-formats --locked` passed on macOS and for Windows x64 under Wine (25 passed, four ignored on each). - The regression test checks output bytes against per-element offsets for all six addressable tiled 2D modes, all five element sizes, odd row pitches, mip chains, and two array slices. - Workspace Clippy passed for the Windows GNU target with all targets and features. The Windows MSVC cross-check also passed with `blake3/pure` to avoid needing MASM on macOS. - `cargo xtask policy` and `git diff --check` passed. - A local differential check matched both copy directions on 720 addressable layouts (8,980 subresources), including block compression, 1D and 2D arrays, and thick 3D volumes. - In the fork's Windows x64 MSVC run, workspace tests passed (497 passed, seven ignored), along with Clippy in both default and all-features configurations. Release-mode formats tests also passed (25 passed, four ignored). [Windows run](https://github.com/venglov/victory-fork/actions/runs/45501217177) AI-assisted implementation and verification. <details> <summary>Reproduce the synthetic detile benchmark</summary> From the checkout, extract `crates/victory-formats/src/texture.rs` from `2119b0e` into `base.rs` and copy the changed file to `patch.rs` in a temporary directory. Save the program below beside them and compile with `rustc +1.98.1 --edition 2024 -O -A dead_code bench.rs`. For the Wine timings, add `--target x86_64-pc-windows-gnu -C linker=x86_64-w64-mingw32-gcc` and run the resulting executable with Wine. ```rust #[path = "base.rs"] mod base; #[path = "patch.rs"] mod patch; use std::{hint::black_box, time::Instant}; macro_rules! bench_fn { ($mod:ident, $width:ident, $height:ident, $bpe:ident, $block:ident, $mode:ident) => {{ let layout = $mod::Layout::new(&$mod::Desc { dimension: $mod::Dimension::Tex2d, width: $width, height: $height, depth: 1, mips: 1, element_bytes: $bpe, block: $block, samples: 1, swizzle: $mod::Swizzle($mode), }).unwrap(); (layout.size, move |src: &[u8], dst: &mut [u8], row: usize, len: usize| { layout.detile(black_box(src), 0, 0, black_box(dst), row, len).unwrap(); }) }}; } fn run(name: &str, width: u32, height: u32, bpe: u32, block: u32, mode: u32) { let (asize, a) = bench_fn!(base, width, height, bpe, block, mode); let (bsize, b) = bench_fn!(patch, width, height, bpe, block, mode); assert_eq!(asize, bsize); let mut seed = 1u64; let src: Vec<_> = (0..asize).map(|_| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); (seed >> 32) as u8 }).collect(); let row = ((width.div_ceil(block) * bpe).next_multiple_of(256)) as usize; let len = row * height.div_ceil(block) as usize; let mut out = vec![0xcc; len]; let mut expected = out.clone(); a(&src, &mut expected, row, len); b(&src, &mut out, row, len); assert_eq!(out, expected); let mut times = [vec![], vec![]]; let iter = (320_000_000 / len).clamp(6, 1024); for batch in 0..10 { for i in [batch % 2, 1 - batch % 2] { let t = Instant::now(); for _ in 0..iter { if i == 0 { a(&src, &mut out, row, len); } else { b(&src, &mut out, row, len); } black_box(&out); } if batch >= 3 { times[i].push(t.elapsed().as_secs_f64() * 1000. / iter as f64); } } } times.iter_mut().for_each(|s| s.sort_by(f64::total_cmp)); let (a, b) = (times[0][3], times[1][3]); println!("{name:16} {a:8.4} {b:8.4} {:7.1}%", 100. * (b / a - 1.)); } fn main() { for (name, w, h, n, b, m) in [ ("rgba8 4K-D", 4096, 4096, 4, 1, 10), ("rgba8 1440p-D", 2560, 1440, 4, 1, 10), ("rgba8 4K-S", 3840, 2160, 4, 1, 5), ("rgba8 1080p-S", 1920, 1080, 4, 1, 9), ("rgba16 4K-S", 3840, 2160, 8, 1, 9), ("bc7 4K-D", 4096, 4096, 16, 4, 10), ("bc1 4K-S", 4096, 4096, 8, 4, 9), ("r8 odd-D", 1919, 1079, 1, 1, 6), ("rgba8 512-D", 512, 512, 4, 1, 10), ("rgba8 256-D", 256, 256, 4, 1, 10), ("rgba8 linear", 1920, 1080, 4, 1, 0), ] { run(name, w, h, n, b, m); } } ``` </details>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:37:47 +00:00
Author
Owner

@⁠chatgpt-codex-connector[bot] on GitHub · 2026-11-24 22:19 UTC · original · edited 2026-11-24 22:21 UTC

Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T22:21:52.907318Z 07259b3 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@⁠codex review" or "@⁠codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

**@⁠chatgpt-codex-connector[bot]** on GitHub · 2026-11-24 22:19 UTC · [original](https://github.com/fxceless/victory-fork/pull/186#issuecomment-7146091616) · edited 2026-11-24 22:21 UTC <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"07259b30cb61b0fd04b2499f22488a840c354eb4","has_any_findings":false,"has_unresolved_findings":false,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-24T22:21:52.907318Z">2026-11-24T22:21:52.907318Z</relative-time> | `07259b3` | PR opened | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@⁠codex review" or "@⁠codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Author
Owner

@⁠LeonardoS11 on GitHub · 2026-11-25 03:07 UTC · original

Tested on another NVIDIA card, picture checked against main.

  • Windows 11, RTX 3080 Ti 12 GB, 64 GB RAM, diag build with diagnostics.
  • Build: main at c96b4f2 with only this PR's commit cherry-picked (no conflict), no environment switches.
  • One run from a checkpoint in the prologue (the room with the window onto the yard), the window's contents saved at 275 s and compared with the same moment of a run of plain c96b4f2: walls, the mesh in the window, the characters and the posters on the wall are the same or better; nothing missing that main shows. No device loss in 330 s.
  • Not measured alone for speed: in the earlier runs it was part of a stack of several PRs, so I have no frame-time number that is this PR's own.

One run only; the "walls missing in some launches" of main did not show in it.

(Runs and screenshots by me on the hardware above; comparison and this note written with Claude Code.)

**@⁠LeonardoS11** on GitHub · 2026-11-25 03:07 UTC · [original](https://github.com/fxceless/victory-fork/pull/186#issuecomment-7151608576) Tested on another NVIDIA card, picture checked against `main`. - Windows 11, RTX 3080 Ti 12 GB, 64 GB RAM, `diag` build with `diagnostics`. - Build: `main` at c96b4f2 with only this PR's commit cherry-picked (no conflict), no environment switches. - One run from a checkpoint in the prologue (the room with the window onto the yard), the window's contents saved at 275 s and compared with the same moment of a run of plain c96b4f2: walls, the mesh in the window, the characters and the posters on the wall are the same or better; nothing missing that `main` shows. No device loss in 330 s. - Not measured alone for speed: in the earlier runs it was part of a stack of several PRs, so I have no frame-time number that is this PR's own. One run only; the "walls missing in some launches" of `main` did not show in it. (Runs and screenshots by me on the hardware above; comparison and this note written with Claude Code.)
This pull request can be merged automatically.
This branch is out-of-date with the base branch
The changes on this branch are already on the target branch. This will be an empty commit.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/186/head:github-bot/gh-186'
git switch 'github-bot/gh-186'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-186'
git switch 'github-bot/gh-186'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-186'
git switch 'github-bot/gh-186'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-186'
git switch 'main'
git merge --squash 'github-bot/gh-186'
git switch 'main'
git merge --ff-only 'github-bot/gh-186'
git switch 'main'
git merge 'github-bot/gh-186'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.