Skip to content

runtime: native BCPack decoder, a C++ port of tools/bcpack.py (RT-186) - #4921

Open
rhtnxe wants to merge 3 commits into
ItsNotRexed:mainfrom
rhtnxe:rt-186-native-bcpack
Open

rhtnxe wants to merge 3 commits into
ItsNotRexed:mainfrom
rhtnxe:rt-186-native-bcpack

Conversation

@rhtnxe

@rhtnxe rhtnxe commented Nov 23, 2026 •

Copy link
Copy Markdown

Claimed in the coordination issue as: RT-186 (claim)

What and why

The runtime had no native BCPack decoder, only tools/bcpack.py. This adds one:

  • runtime/src/bcpack.{h,cpp}: a dependency-free C++20 port of tools/bcpack.py, the interleaved rANS lane array and the BC1/BC3/BC4/BC5/BC6H/BC7 block rebuilders. leonida::bcpack::decode(raw, codec, out, allow_provisional) gives the same bytes, the same refusals (error / provisional / unsupported, with the same messages) and the same provisional labels as bcpack.decode_with_info(raw, codec, len(out), allow_provisional=...) with history=None. No Windows or Vulkan code.
  • tools/gen_bcpack_tables.py → runtime/src/bcpack_tables.inc: the codec tables are generated from bcpack_tables.py, bcpack_tables_bptc.py and the BC6H header plans of bcpack._bc6h_plan, so the two decoders can't drift apart.
  • tests/test_bcpack_native.py: encodes random lanes for all six codecs with the test encoder of tests/test_bcpack.py (single and multi-fragment lanes, narrowed widths, every q), corrupts some chunks (bit flips, truncation, trailing bytes, wrong sizes, unsupported codecs), and checks that both decoders agree on status, message, labels and bytes in strict and provisional mode. Six fixed BC7 chunks, one per mode 4/5 × rotation 1–3 pair, are added whatever the seed, so the rotation channel swap is always covered. It also fails when bcpack_tables.inc is stale. Without a built bcpack_test it only runs the table check, which is what the CI Python job does.
  • ctest: bcpack (the decoder's own checks) and bcpack_native_vs_python (the comparison, with --bin $<TARGET_FILE:bcpack_test>; run_wine_tests.py skips it as a Python-driven test). On Windows bcpack_test --batch takes wide paths (wmain), and the comparison runs it from its temp folder with relative names, so a non-ASCII temp path works.
  • docs/textures.md §6 describes it.

Not ported yet: --history loading (BC6H/BC7 initial history and the BC1–BC5 overrides). Without it the native decoder, like tools/bcpack.py without --history, refuses BC6H/BC7 chunks that reference built-in history. On the corpus in docs/textures.md that's every BC6H chunk and most BC7 chunks, so that's the next step for real textures (posted as a finding: in #4933). The internal history structs are already shaped like load_bc6h / load_bc7's output, so a loader only has to fill them.

Tested

macOS 27.2.1 arm64 (Apple M4), Apple clang 21.0.0, CMake 4.3.3, CPython 3.15.2. No GPU or game files needed.

  • python -I tests/test_bcpack_native.py --bin runtime/build/linux/bcpack_test (default seed 186): 498 decodes, all identical. ok / error / provisional per codec: BC1 45/34/1, BC3 24/30/26, BC4 31/26/23, BC5 47/24/9, BC6H 5/57/18, BC7 27/52/13, plus unsupported codecs. (486 and BC7 15/52/13 before the fixed rotation chunks of 86ab1905.) 17 provisional-mode successes carry labels (e.g. BC3 unknown history [72, 203] (2 blocks), BC6H anchor index inconsistent in 2 pixels, BC7 signature 252).
  • 8 more seeds × 30 chunks per codec (~4,800 decodes) against a -fsanitize=address,undefined -Wall -Wextra -Wshadow -Wconversion build: no mismatches, no warnings, no sanitizer reports.
  • ctest -R bcpack: 2/2 pass. Seeds 186 and 1–7 pass at 86ab1905.
  • Control: with the BC7 rotation swap (if (rot) w[rot - 1] = ab, w[3] = cb;) removed from bc7_rebuild, each of the six rotation chunks fails on its own, and so does every seed.
  • Non-ASCII paths: the comparison passes with a 測試 temp folder, and bcpack_test --batch accepts absolute 測試 paths.
  • Unchanged: tests/test_bcpack.py, test_bcpack_tables.py, test_bcpack_tables_bptc.py, test_bcpack_tool.py, test_docs_links.py, test_text_write_line_endings.py all OK.
  • Not built with MSVC here. Reviewers built it with MSVC 19.38–19.52 on Windows 11, with no warnings in these files (also at /W4 /permissive-); see the comments.

AI-assisted: yes (Claude Code)

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

runtime/src/bcpack.{h,cpp} decodes one BCPack chunk (the interleaved rANS lane
array, then the BC1/BC3/BC4/BC5/BC6H/BC7 block rebuilders) with the same bytes,
refusals and provisional labels as bcpack.decode_with_info(..., history=None).
Dependency-free C++20, no Windows or Vulkan code.

The codec tables are generated from tools/bcpack_tables.py and
tools/bcpack_tables_bptc.py (and the BC6H header plans from bcpack.py) by
tools/gen_bcpack_tables.py into runtime/src/bcpack_tables.inc.

tests/test_bcpack_native.py encodes random lanes for all six codecs with the
test encoder of tests/test_bcpack.py, corrupts some, and checks that both
decoders agree on status, message, labels and bytes in strict and provisional
mode; it also fails when the generated tables are stale. ctest runs it as
bcpack_native_vs_python, next to bcpack_test's own checks.

Not ported yet: --history loading for BC6H/BC7 (and BC1-BC5 overrides).
@Kev-Ball

Copy link
Copy Markdown

Tested 0f03de95 on CachyOS x86-64 with GCC 16.2.1. I compared the C++ decoder with the Python reference on retail 1.0.2.1 texture chunks, with external history omitted as specified by the PR.

I indexed all 57 pools and their 108,605 BCPack chunks, sorted each of the six codecs by compressed size, and selected the smallest, median and largest chunk per codec. The two decoders agreed on 36/36 comparisons (18 distinct chunks × strict and provisional modes). I compared status, exact diagnostic text, provisional labels and decoded bytes. The 16 successful calls produced 18,116,608 bytes in total, all byte-identical.

Mode Successful decodes Provisional refusals
Strict 4 14
Allow provisional 12 6

The six refusals with provisional mode enabled were the three BC6H and three BC7 selections. This sample verifies their refusal parity. Successful retail byte comparisons covered BC1, BC3, BC4 and BC5. Both CTests (bcpack and bcpack_native_vs_python) passed. Counts only. AI-assisted.

@whattheflop whattheflop left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent Windows CPU verification, AI-assisted. bcpack_test compiled and linked without diagnostics using MSVC 19.38.33145 x64, Windows SDK 10.0.26100.0, CMake 4.4.4 and Ninja 1.13.2. The generated table check passed with uv CPython 3.12.13. On 102 hand-built valid chunks (17 per codec across BC1/3/4/5/6H/7), all 204 strict and provisional native/Python comparisons matched the expected bytes, with empty provisional labels. This covers all 16 q values and a split-fragment case per codec.

One Windows test-driver issue: the same valid BC1 batch succeeds with ASCII paths and exits 2 on code page 1252 if either the input or output filename independently contains 測試. The narrow main arguments/file streams make the Python comparison dependent on its temp path. Wide filesystem paths on Windows, or running the batch from its temporary directory with ASCII relative filenames, would keep the comparison usable there.

Synthetic positive cases only, no GPU or game inputs.

@tupacfan04

Copy link
Copy Markdown
Contributor

Independent Windows CPU check at 0f03de95, AI-assisted.

Built bcpack_test with MSVC 19.51.36260.0 x64, Windows 11, CMake/Ninja, RelWithDebInfo, -DBUILD_TESTING=ON. No compiler warnings.

  • bcpack_test: bcpack_test: ok.
  • ctest -R "^(bcpack|bcpack_native_vs_python)$": 2/2 passed (7.1 s).
  • tests/test_bcpack_native.py: the default seed 186 run checked 486 decodes. I also ran seeds 1–4 with --chunks 100: 2,010 decodes each, 8,040 total, 0 mismatches. Status, exact messages, provisional labels and bytes matched Python in both strict and provisional modes, covering all six codecs.
  • A separate 2,000-record random differential run (codecs 0–9/255, random raw bytes, sizes 0–256, both modes) also had 0 mismatches.
  • The generated-table check passed; runtime/src/bcpack_tables.inc is current.

One test-driver portability issue reproduced on Windows, matching the earlier review: bcpack_test --batch uses narrow main arguments and narrow file streams. A batch file whose absolute path contains 測試 fails with cannot read ...\??4921\in.bin, exit 2; a non-ASCII output path also exits 2. Running from that directory with ASCII relative filenames (--batch in.bin out-relative.bin) succeeds. This only affects the test helper, not leonida::bcpack::decode; wide paths or a UTF-8 std::filesystem::path would make the batch mode usable with non-ASCII temp paths.

Synthetic data only; no GPU or game files used.

@theswiss24

Copy link
Copy Markdown

Tested 0f03de95 on Linux Mint 22.3 (x86_64, GCC, Ninja, Release), PR merged onto main 3faac557 and built in its own folder.

Result: pass.

  • The runtime builds with the native decoder.
  • python -I tests/test_bcpack_native.py: 2 tests, OK.
  • ctest -R "vk_pipeline_check|shader_library|bench": 5/5 passed, the same as main at the same commit.

No game files were used (the test's own inputs only).

Tested and written by Claude (Claude Code), posting from @theswiss24's account.

The --batch helper took narrow argv and opened files by char*, so a temp
folder outside the ANSI code page (reported with a non-ASCII directory on
Windows) made it exit 2. Use wmain + std::filesystem::path on Windows, and
have test_bcpack_native.py run it from the temp folder with relative names.
@rhtnxe

rhtnxe commented Nov 23, 2026

Copy link
Copy Markdown
Author

Thanks for testing, everyone. 5a5b7378 fixes the non-ASCII path failure that tupacfan04 and whattheflop both hit in bcpack_test --batch:

  • On Windows the helper now uses wmain and opens its files through std::filesystem::path, so wide paths reach it intact. Other platforms still use main.
  • tests/test_bcpack_native.py runs the helper from inside its temp folder with the relative names in.bin and out.bin, so the comparison no longer depends on the temp path.
  • The helper now also reports when it can't write its output file.

Tested on macOS arm64 with Apple clang. bcpack_test reports ok, test_bcpack_native.py is OK at the default seed, and ctest -R bcpack passes 2/2. I also ran the comparison with a 測試 temp folder (seed 7) and gave the helper an absolute 測試 path; both worked. I couldn't build the Windows wmain branch here, so it gets its first MSVC compile in CI or from a Windows tester.

@memorypressure

Copy link
Copy Markdown

Verified merged with main 3faac55: gen_bcpack_tables.py reproduces runtime/src/bcpack_tables.inc byte-for-byte (the freshness check passes under python -I), so the table blob is provenance-clean generated data, and test_bcpack stays fully green. The native-vs-python differential test correctly skips without a built bcpack_test binary — so the C++ port's equivalence rests on the CI ctest run, and GitHub reports no checks scheduled on this branch. Please trigger CI before merge; the build itself is also outside this verifier's scope (no cmake builds). AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

@daemosofchaos

Copy link
Copy Markdown
Contributor

Independent Windows/MSVC check of 5a5b7378, including the updated Windows wmain test helper. Built with MSVC 19.52 on Windows 11; both bcpack and bcpack_native_vs_python CTests passed.

The previously reported Unicode-path case now works: four combinations of absolute Unicode input/output paths passed; a directory used as the output was rejected. With a Unicode TEMP directory, the PR's differential suite passed with seed 7 (486 decodes).

Additional synthetic parity checks matched the Python reference on 33 captured lane vectors and 20 reconstruction vectors, plus 575 truncated/boundary lane cases and 1,150 strict/provisional decoder cases. For lane successes I compared symbols and bytes consumed; for reconstruction I compared statuses, labels, bytes and the project's diagnostic-message comparator. The two synthetic BC6H/BC7 custom-history examples were tested in Python only: the native API does not support custom histories yet; its default-history refusals matched.

CPU-only synthetic inputs; no game files or GPU. This checks reference parity, not real-texture or runtime integration correctness. AI-assisted review.

— LocalFirst-AI

@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Tested 5a5b737 (on its base main d974c88a) on Windows 11 26300 with MSVC VS 2022 (Ninja RelWithDebInfo), Python 3.13.7: pass. Full ctest is 179/179, and the default seed gives the same 486 decodes and per-codec counts as the description. A relative --bin path works now; at 0f03de9 it failed for me with FileNotFoundError from subprocess, which the cwd=tmp + abspath change fixes. The ctest build compiles bcpack_test at MSVC's default warning level. So I also compiled bcpack.cpp and bcpack_test.cpp with /W4 /permissive- /std:c++20 (the flags gta6rt uses): no warnings.

What I can add to the runs above is controls. One change at a time in bcpack.cpp, rebuilt, then restored; bcpack.cpp is the same at both heads. bcpack_test's own checks pass in every row, so the comparison is what catches them:

Change test_bcpack_native.py
Model::advance: drop the c == 0 adjustment fails, 408 of 486 decodes differ (fragment did not end at its home state)
BC7 rebuild: drop the rotation channel swap (if (rot) w[rot - 1] = ab, w[3] = cb;) fails at seed 186, but on one chunk only: 2 mismatches, the same 528-byte BC7 chunk in strict and provisional mode. Seeds 2 and 3 (--chunks 30) catch it too (6 and 4 mismatches); seed 1 passes
the same swap in bc7_field_bits (history-coverage check) passes at seeds 186 and 1–3. Expected: without --history, any reference to built-in history is unknown whatever its bit widths

The second row is the only thin spot I found. BC7 rotation (modes 4/5 with rot != 0) is covered by chance, by a single clean chunk at the default seed. A clean BC7 chunk that always uses rotated mode 4 and mode 5 signatures, or a few fixed BC7 cases per rotation, would make it deterministic. The third row will matter once the --history loader lands, and the comparison will need history-bearing cases then.

AI-assisted (Claude Code).

The seeded chunks reached BC7 modes 4/5 with rotation != 0 by chance only
(one chunk at the default seed; seed 1 missed a dropped channel swap).
Add one decodable chunk per (mode, rotation) pair, independent of --seed,
with full-range endpoint deltas so the swapped channels always differ.
@rhtnxe

rhtnxe commented Nov 23, 2026

Copy link
Copy Markdown
Author

Thanks Parakeet-Wheat, those controls were useful. 86ab1905 makes the BC7 rotation coverage deterministic:

  • test_bcpack_native.py now always adds six fixed BC7 chunks, one for each mode 4/5 × rotation 1–3 pair, whatever --seed is. Every block in a chunk uses that pair, and each chunk is checked to decode in Python.
  • The endpoint lanes (R, G, B, A) get full-range deltas in these chunks. The first try zeroed the red lane the way other clean chunks do, and then a missing swap left 3 of the 6 chunks unchanged. Modes 4 and 5 have no p-bits, so the chunks still decode.

I repeated your control on macOS arm64 by dropping if (rot) w[rot - 1] = ab, w[3] = cb; from bc7_rebuild. Each of the six chunks now catches it on its own, and seeds 1 and 186 fail with 13 and 14 mismatches (seed 1 passed before). With the code restored, seeds 186 and 1–7 pass (498 decodes each at the default chunk count), and ctest -R bcpack passes 2/2. Generating the six chunks takes about 0.1 s.

I agree about bc7_field_bits: without --history it can't be tested here, so it should get history-bearing cases when the loader lands.

@DenRakEiw

Copy link
Copy Markdown
Contributor

Tested 86ab1905 on Windows 11 (MSVC 19.44 / Ninja / Windows SDK 10.0.26100, Python 3.12.10, synthetic inputs, no game files): pass.

  • Trial-merged onto origin/main (3faac557): clean; bcpack_test built cleanly.
  • ctest -R "^bcpack$" -V: 1/1 passed (bcpack_test: ok, 0.03s).
  • python -I tests/test_bcpack_native.py: 2/2 OK (498 decodes, seed 186, 5.17s).

AI-assisted (Gemini 4 Neon).

@XFlawless1

Copy link
Copy Markdown
Contributor

Tested the current head 86ab1905 merged onto main 3faac557 (clean merge), Windows 11 Pro 26300, MSVC 19.44 (VS 2022 Build Tools), full scripts/build_runtime.ps1 build (Ninja, RelWithDebInfo), Python 3.12: pass.

  • Build: all 516 steps complete; none of the build's 7 compiler warnings is in bcpack.cpp, bcpack.h or bcpack_test.
  • ctest: ctest -R "^(bcpack|bcpack_native_vs_python)$": 2/2 passed.
  • Native vs Python: python -I tests/test_bcpack_native.py --bin <build>/bcpack_test.exe, all OK (identical results):
seed decodes BC7 ok / error / provisional
186 (default) 498 27 / 52 / 13
4921 498 28 / 54 / 10
7 498 19 / 52 / 21

Seed 186 now gives 498 decodes, against 486 in the description. The other codecs' counts are the description's exactly, and the 12 extra are all BC7 ok (27 vs 15), which matches the fixed mode-4/5 × rotation chunks 86ab1905 adds.

  • Unicode path: a copy of bcpack_test.exe under a folder named with Greek, accented and Japanese characters (outside the ANSI code page) passes the same test, so the wmain fix from 5a5b7378 holds with MSVC.

Synthetic chunks only, no game files. AI-assisted (Claude Code).

@whattheflop

Copy link
Copy Markdown
Contributor

Follow-up to my Unicode-path review at 86ab1905, AI-assisted. MSVC 19.38 and uv CPython 3.12.13 on Windows, code page 1252. I confirmed the path issue is resolved on the current head. The direct helper now passes all four absolute ASCII/Unicode input and output combinations. The same 13-record batch (BC1 control plus six fixed BC7 fixtures in both decoder modes) matched Python under both ASCII and Unicode TEMP. I also inspected all 77 reference BC7 blocks. For rotations 1/2/3, mode 4 has 4/16/4 blocks and mode 5 has 4/33/16 blocks. All six fixtures vary all four endpoint channels, with 56/77 blocks exercising the extra alpha bit. The fixed suffix is byte-identical across four seed/count settings. Synthetic inputs only.

@tunczzz

tunczzz commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 86ab1905 (merge base d974c88a) on Windows 11 10.0.26300 with an NVIDIA GeForce RTX 5070 Ti (Blackwell, subgroup 32..32), driver 616.56. Result: pass.

  • Runtime built from this head: MSVC 19.44 (BuildTools 2022), Ninja, RelWithDebInfo, -DLEONIDA_VULKAN_HEADERS_FETCH=ON (no Vulkan SDK; the loader comes from the NVIDIA driver). glslangValidator and llvm-mc 21 came from WSL Ubuntu. Build exit 0.
  • ctest -j 3: 179/179 passed.
  • scripts/run_gpu_tests.py --build <this build>: 170/217 passed, 47 skipped, 0 failed.
  • New here: bcpack PASS and bcpack_native_vs_python PASS (5.9 s).
  • The merge base d974c88a is older than main 3faac557. Apart from the two new tests, the list matches main, and every test gives the same result as on main 3faac557 (ctest 177/177, GPU 170/217).
  • As on main, run_gpu_tests.py records cs_fmt_d16_xyz twice and skips cs_tbuffer_store. That's main's runner bug, fixed by run_gpu_tests: record cs_tbuffer_store's result; fail a run that records a test twice #4784, not this PR.

Not run: other GPUs/vendors, Linux, the Vulkan validation layer (not installed). No game files.

AI-assisted (Claude Code).

@Atomic258

Copy link
Copy Markdown
Contributor

Tested 86ab190 on Windows Server 2022, CPython 3.13.12: pass

  • python -I tests/test_bcpack_native.py -> OK (skipped=1 - native build step skipped)
  • Generated tables import and self-check cleanly.

git diff --check clean; python -m compileall -q exit 0. No game files, no GPU. AI-assisted (Devin).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.