Register the Switch update and the 425 shaders read by the DrinkBox container parser. Record the depth mode selected by the guest so the pipeline prebuild uses the same vertex entry as live rendering. Verify the Mac opening, stereo PCM, both DLC licenses and the bundled pipeline archive. Build and integrity-check the unsigned IPA. Movement, combat, co-op, DLC gameplay and an iPhone run remain open.
896 KiB
Shaders
Finding, keying and translating shaders (dm/gfx/tools/shader_split.py, dmsh_build.py, dmsh_xlate, Program.cs) and their pipelines. Each entry: symptom, cause, fix, the games it was found on. The symptom index lists every symptom.
Containers by engine
EA BIG4, EASF and NXSHADER archives
- Symptom: the shader splitter cannot reach an EA title's shader programs inside its BIG4 archives. A reader that imports PyCryptodome only on encountering EASF instead fails late in a clean tool environment.
- Cause: these archives wrap NXSHADER programs in chunkzip raw-deflate blocks and EASF AES-CBC encryption. Existing Frostbite readers use different layouts. EASF's eight-byte ID identifies an
id[8], key[16]registry entry in the matching main NSO; the header verifies the first 32 plaintext bytes. - Fix:
easfreads members by signature, validates ranges and decoded sizes, finds and verifies the registry key, and passes control/code records to normal package, fact and pairing generation. Archive jobs use their version's main, with the newest main for DLC, and the normal worker/unreadable-file path. CBC decryption sharesdm/tools/aes.pywith the existing Unreal and RPF6 ECB readers, so no extra Python crypto dependency is introduced. - Check: synthetic fixtures cover key discovery, bad candidates, compressed NSOs, archive bounds, compute offsets, version separation, DLC, directory/image IO and package export while PyCryptodome is unavailable. Independent AES known-answer vectors and existing encrypted Unreal/RPF6 fixtures check the shared helper. The current-main split of FIFA 23 reproduces all 386 expected shader keys and its full Mac shader build succeeds.
- Found on: FIFA 23 Legacy Edition, PR #1696.
Telltale effect packs in ttarch2 archives
- Symptom:
[RED] the shader split found no shaders in main or the RomFS, withshaders: 0, on a Telltale Tool game whose RomFS is.ttarch2archives and whosemainnames*.t3fxpack. No BNSH, BAHS or control-section magic appears in the compressed files. - Cause: the archives use
NCTTorZCTTwrappers. AZCTTblock has version0x10000, a chunk count andcount + 164-bit offsets, followed by raw-deflate chunks. The effect packs contain unaligned records: a code area, a 32-bit control length, then the control section. Compute code areas can be headerless. Existing BNSH and whole-GLSLC readers cannot reach these records. - Fix:
ttarch2_shadersdetects the wrapper by magic, checks compressed-block ranges and inflates shader archives identified by.t3fxpackin their initial directory data. It takes the code area immediately before each control-length word and retains only pairs accepted byglslc_stageandcheck(). No title, build or profile switch selects the reader. - Check:
test_ttarch2.pycovers deflate chunks, both wrappers, unaligned and headerless compute records, inconsistent control lengths, non-shader archives and file-scanner dispatch with the original shader bytes preserved. A real-archive A/B check against the pre-integration splitter finds zero keys without the reader and 24,243 with it; the keys exactly match PR #1965. - Found on: Sam & Max: The Devil's Playhouse 1.8.0, a provisional Mac profile with a successful user playtest; episode completion and save/reload remain unvalidated.
RenderDragon material shaders
- Symptom: the packer finds no loose SPIR-V files, although the game creates its modules from assets it ships.
- Cause: RenderDragon places bgfx vertex and fragment v5 and compute v3 shader records in
renderer/materials/*.material.bin. Its built-in graphics shader records are in the main NSO. Each record has a uniform table and a length-prefixed SPIR-V payload. - Fix:
vk_shaders.pychecks the material and bgfx headers, bounds-checks the uniform records and shader length, and requires the SPIR-V instruction stream to occupy that length exactly. It deduplicates by the same hash of the payload that the runtime uses. Compute rows include their workgroup size. Fragment shaders with three or more color outputs keep their normal MRT layout, which Metal cannot compile as dual-source blending. - Found on: Minecraft for Nintendo Switch 1.26.62, with 1,784 unique graphics and 44 compute modules, including 11 built-in modules in
main.
L.A. Noire WAD and VFP shader arrays
- Symptom: the split finds only a few dozen shaders. The notebook pages render black, and game scenes have missing materials.
- Cause:
out.wad.nxhas a span table and a name table. Its.vfp.nxmembers store the GLSLC headers, control sections and code in separate arrays. - Fix: the splitter maps
out.wad.nxwith theWAD\x01signature and reads its.vfp.nxmembers. It checks the name table and shader member ranges, requires non-empty code and complete coverage of the VFP arrays, then passes the original control and code bytes to the existing shader checks. The VFP arrays give individual stages. Their vertex and pixel pairing is unknown. - Check:
dm/gfx/tests/test_noire_shader.pychecks keys and bytes in both RomFS forms, the signature and basename gate, and rejection of truncated directories, invalid names and malformed spans. On M4 Pro/macOS 27.2.1, the WAD yielded zero shaders witha6aaf66dand 8,933 with the reader. A full split with the reader and the startup captures found 8,968 shaders, all of which compiled for the Mac. - Found on: L.A. Noire 1.2 (NX2Apple issue #1386).
Firaxis CIVBSF shader libraries
- Symptom: the shader split stops with no shaders in
mainor RomFS, and the host reports missing programs while presenting a black picture. - Cause: Firaxis's
CIVBSFlibrary is neither BNSH nor a whole GLSLC output, so the loose-file prefilter discarded it. Its shader table points to descriptors of separate code/control payloads; the first pointer in a table entry can instead name platform metadata. - Fix:
shader_split.pyselects the entry size from the container revision:0x1218uses 0x50-byte entries with separate code/control payloads;0x1118uses 0x48-byte entries with four platform descriptors, of which platform 3 holds anNVBCheader and a complete GLSLC output followed by reflection. It validates the table, descriptor ranges, platform tags and payload lengths, ignores saved runtime pointers, and applies the existing control/code checks only to the declared GLSLC body. The original bytes and keys are preserved. Detection follows the container magic, with no title, build or filename gate. The stages use the existing pixel-input cover for vertex padding; the effect table's program-pair relation has not been established, so it supplies no guessed pairs. - Check:
test_split_civbsf.pycovers vertex, pixel and compute stages, trailing control bytes, nested archives, padding, malformed ranges and payloads, and the file scanner's rejection contract. - Found on: Sid Meier's Civilization VII (
0x1218) and Sid Meier's Civilization VI (0x1118).
Larian LSPK packages and BSHD programs
- Symptom: the split finds only the GLSLC outputs in the executable, while the game presents a black picture and reports missing vertex, pixel and compute shaders.
- Cause: Larian's version 13 packages have their
LSPKsignature and header at the end. Their LZ4-compressed index names individually stored, zlib or LZ4 members, possibly in numbered archive parts. BSHD members have a big-endian decoded length (the top bit selects zlib), followed by a stage/range table; the NX stages are complete GLSLC outputs. The same archives also carry other platforms' programs. - Fix:
dm/gfx/tools/lspk.pyreads the footer and index, validates member ranges and bounds decompression.shader_split.pyscans the indexed BSHD members and preserves each program's vertex/pixel pair. Other assets and sound/video continuation parts need no whole-file scan. Detection follows the archive signature and compiled-stage format, with no title ID, build or archive-name gate. - Check: synthetic parser tests cover compressed and stored members, numbered parts, stage pairing and corrupt ranges/streams. The live shader census and startup capture comparison are in the game's note.
- Found on: Divinity: Original Sin 2.
SHN resources and embedded shader objects
- Symptom: the split finds only a loose upscaler pack, while a game's
.shdrfiles and scene resources produce no shaders; the host reports missing vertex and pixel shaders and draws a blank picture. - Cause: Shin'en's
SHN!wrapper compresses its metadata, relocations and GPU data independently as LZ4 blocks (equal stored and decoded lengths mean raw data). The metadata holdsSHDROUNCobjects, both in loose shader files and embedded inSCENOUNCscene resources. Control offsets are absolute within decoded metadata; code offsets point into the separate GPU-data block. Scanning only the loose shaders misses the materials embedded in scenes. - Fix:
shader_split.py'sshn_shadersreads the blocks and each object's variant/stage table, validates every range and control/code pair, and preserves program variants for shader pairing. It decodes GPU data only when the metadata holds shader objects: textures and other resources use the same wrapper. Detection uses the file and object signatures, with no title, path or build gate. - Check:
test_shn.py: raw and LZ4 blocks, embedded objects, several variants, separate code offsets, shader pairs, compute stages, non-shader resources, damaged lengths and offsets. The startup capture comparison and shader counts are in the game's note. - Found on: Fast Fusion.
One scrambled archive indexed by the NRO
- Symptom: the split finds no shaders, and the RomFS is one huge file with a short name (
42) whose bytes look random past a table at its start (magicCRA.). Or the split stops with[RED] /42: a CRA archive, and no NRO in DM_NRO_DIR (…) holds its file table: the NRO reads a layoutcra.pydoes not know. - Cause: Mario Tennis Fever's engine keeps its 8,671 files in that archive, listed only in the game's code: a file table in read-only data, which an NRO the game decodes at run time holds (A game that decodes its code at run time). Each file is scrambled in 16-byte blocks with a key from its name, and most are NARC containers (the DS's format) whose members are packed by their first byte (LZ4, zstd, deflate, an LZ of the game's own, or chunks of these). The shaders are BNSH in the FSHA, VFXB and SARC members, one FSHA per model, and 40 more in the NRO's own data.
- Fix:
dm/gfx/tools/cra.pyfinds the table from the code that reads it, in any build, and reads a file as the game does; the game's checksum of each file catches a wrong key.cra.indextakes the layout the NRO's code reads: Mario Tennis Fever's, else the older one of Mario Golf: Super Rush (Index2021: an i32 per file, records behind the table with the size, a CRC-32 checksum and the offset under other masks, bit-reversed path characters, files xored in 16-byte blocks with two keys from the last path element and each byte bit-reversed;cra.pydocuments both). Each file's entry names its layout, whichreadandheadtake it in.shader_split.py(cra_jobs) reads the NRO fromDM_NRO_DIR, scans each file but sound and movies (by their magics), and expands NARC members inscan_blob. The whole archive unscrambles in 30 s with numpy; the split, in pure Python with 12 workers and a warm file cache, takes under a minute. - Check:
dm/gfx/tests/test_cra.py. All 8,671 files of Mario Tennis Fever 1.1.1 pass the game's checksums; all 5,101 of Mario Golf: Super Rush 4.0.0 (4.1 GB) do too, read in 37 s. - Found on: Mario Tennis Fever: 35,045 shaders. Mario Golf: Super Rush (4.0.0, issue #814), the older layout, decoded by the author of PR #2216 from the game's reader at
nro0+0x54b6d4: 25,270 shaders in 18 s.
Packed shader banks in loose NARC files
- Symptom: the split finds only a small part of a game's shaders, with no
[RED]line, and its RomFS holds files that startNARC(.narc,.nptl,.ntexon Mario Tennis Aces). - Cause: the split reads a whole file only when it sees a shader magic in the file's bytes. A NARC's members are packed by their first byte (
cra.undo), which hides those magics, so the file was left out before the reader ever saw it. Mario Tennis Fever did not show this: its files come throughcra_jobs, past that check. - Fix:
scan_file_inpasses every file with theNARCmagic toscan_blob, whatever its name. The members go through the samecra.narc_membersandcra.undoas Fever's. - Check:
dm/tools/tests/test_split_narc.py: synthetic files with every packing and BNSH hidden in the file's bytes give the same keys and pairs as plain ones. - Found on: Mario Tennis Aces, no profile yet (issue #1131, diagnosed by PikaMan80, who counted 1,388 shaders from the loose
.nsbfiles and 21,703 with the archives read). Not run on the game's files here. Open: that report says kind0x50wraps a zlib stream, andcra.undodoes not unwrap one, so such members would give no shaders and no red line.
Malformed NARC archives fail outside the reader's rejection contract
- Symptom: the shader-split fuzz harness fails with
cra.Error: /fuzz: no BTAF or GMIF, orstruct.erroron a truncated NARC header or member table. - Cause:
scan_blobdid not translatecra.Errorinto its declared[RED]rejection.cra.narc_membersalso read the header and BTAF table before checking their bounds, and bounded members by the whole file rather than their GMIF section. - Fix: the NARC reader validates its header, section sizes, member count and GMIF ranges before reading them. The scanner preserves its layout diagnosis, including a member's path for decompression errors, through
red(). - Check:
test_split_narc.pychecks malformed headers, sections, tables and members, alongside the valid packed shader banks.test_fuzz_corpus.pyreplays the minimized synthetic CI input and its truncated header. - Found on: the nightly fuzz run of November 14, 2026; no game files.
Sumo Ninty_NX shaders and MuxFDMR streams
- Symptom: the split finds no shaders in
mainor RomFS, while reporting control sections inmainwith no code area. The game has.sp4resources and loose.nvnbinfiles rather than BNSH archives or whole GLSLC outputs. - Cause: Sumo's
Ninty_NXdescriptors store control/code offsets relative to their container, whose start is recovered from the descriptor's own relative offset. The code is not necessarily adjacent to its control section.MuxFDMRversion 2 resources wrap these containers in one or two zlib streams; their header holds both the stored and decoded lengths. LooseNVNshversion 1 records instead name one stage and its control/code ranges directly. - Fix:
shader_split.pyreads the bounded descriptor ranges and loose records, checks each stage through the existing control/code validation, and scans decoded Mux members recursively. It validates container versions, non-overlapping ranges, complete zlib frames and exact decoded lengths before accepting their shaders. As with Needle, a magic whose container does not fit the data is a literal in executable code and is passed over; the split readsmainwhole, where a stop would end it. Detection follows the format bytes, not a filename or title ID. Original control/code bytes and shader keys are preserved; single-stage vertex programs use the existing pixel-input cover.test_sumo.pycovers embedded containers, loose records, compressed members, malformed input and file-scanner integration. - Found on: Team Sonic Racing 1.0.3: 337
.sp4resources contain 28,258 descriptors,mainholds 586, and two.nvnbinfiles hold four stages. The split finds 4,516 unique shaders (2,116 vertex, 2,399 pixel, one compute), against zero before.
Phyre NVN effects in Virtuos VBF archives
- Symptom: the shader split finds no game programs despite loose
.fx.phyreeffects and multi-GB.vbfarchives. - Cause: Phyre stores GPU code immediately before its control section, often at unaligned offsets inside
RYHPeffect containers. VirtuosSRYKarchives keep the effects in 64 KB zlib or raw blocks. These are neither BNSH nor whole GLSLC outputs. - Fix:
vbf.pyreads the Switch archive's two hash tables, file records, names and block lengths through the RomFS adapter. The split reads compiled effects and shader members without extracting textures or audio.phyre_shadersverifies the adjacent code header, the control's code length and stage, and preserves the original bytes and keys. Single-stage vertex programs use a pixel-input cover for padding. - Found on: FINAL FANTASY X/X-2 HD Remaster; base and both supplied DLC packs yield 5,752 unique shaders.
- Check:
test_vbf.pycovers raw and zlib blocks, shared/missing members, truncation, unaligned effects, loose shader keys and inconsistent lengths. All 5,752 programs translate on the Mac.
LZ4 blocks in FFXII's VBF archives and Phyre programs in main
- Symptom: every frame black after the logos, the title screen included, while music plays and the game takes input; the split logs
[RED] FFXII_TZA.vbf: error: Error -3 while decompressing data: incorrect header check (its shaders are left out)(the same forFFXII_TZA_PATCH.vbf) and 7[RED] main control section @… : no code arealines, and the run[RED] shader … is not in the shader map(27 keys in the first minute) andprogram has no vertex shader. - Cause: FFXII TZA's
SRYKarchives keep the same layout as FFX/X-2's, but their compressed blocks are raw LZ4 blocks (no frame, no size prefix:gamedata/nxgamesetting.ini's block opens with the tokenf6 90and thenLanguage=), not zlib streams, so the first compressed block stopped the whole archive and none of its 3,331 shader members were read. Separately,mainholds 23 of PhyreEngine's built-in programs in Phyre's own form, the code area right before its control section, unaligned, 9 bytes between pairs and with noRYHPcontainer around them; nothing points at them in a formraw_shadersfollows (no data record, no adrp + add), so the aligned ones were left out with a red line and the unaligned ones were never looked at. Among them are the passes that draw the UI and composite the cutscenes. - Fix:
vbf.readtakes a block that is one whole zlib stream of the block's size as before and any other compressed block as a raw LZ4 block of exactly that size (vbf.block), a block that is neither stopping the member with an error.raw_shaders, which reads the control sections inmainthat no other reader took, now gives one that nothing references the code area that ends right at it, when that area has a header and exactly the length the control section gives (+0x704), Phyre's own form, labelled#PHYRE@asphyre_shaderslabels it in effects; an unaligned control section is taken in this form only. Data records and adrp + add references still decide first, so a neighbour that only looks right (Advance Wars 1+2's) is not taken. It holds for every game'smain, not only Phyre's: on 20 other mains on hand (none of them has a control section left forraw_shaders) the tables and red lines are the same as before. A SHAD record nothing points at (test_split_casc.py) is now taken in this form instead of left out with a red line. - Found on: FINAL FANTASY XII THE ZODIAC AGE: 3,100 shaders before (3,028 from
main's GLSLC outputs, 72 loosegamedata/nvn/branch_shaderfiles), 6,454 after (3,051 frommain, 3,403 from the archives and loose files); all 32 programsDM_NVN_SHDUMPsaved up to the first cutscene are among them (25 in the archives, 7 inmain). - Check:
test_vbf.pyadds LZ4 blocks beside zlib ones, a block that is neither, and Phyre pairs in a main-like blob, unaligned and referenced by nothing, whichraw_shaderstakes, leaves out when another reader took them, and does not take without a header or with a code area that would start beforemain.
Phyre effects in split KIT archives
- Symptom: the shader split finds no shaders in
mainor RomFS, which holds a.kitindex and numbered.kit.Nparts. Reading the effects alone still misses their compute programs. - Cause: the
kit!index names members by hash and places their data in separate parts. Compressed members use 64 KiB LZ4 blocks whose matches can reach the previous block. TheirRYHPeffects contain both ordinary graphics programs and compute programs without the graphics code header thatphyre_shadersrequired. - Fix:
dm/gfx/tools/kit.pyreads the format:entrieschecks the index and part ranges;readcarries the previous 64 KiB into each block and verifies decoded lengths, complete input consumption and the member's SHA1, raisingValueErrornaming the archive or member. Raw members use their decoded length.kit_jobsin the split scans the members in ranges throughscan_bloband excludes the index's parts from the loose-file scan; a damaged member leaves its range out with a red line, as any file no reader reads.phyre_shadersuses the existing control/code stage reader; a headerless compute program must be inside aRYHPeffect, fit its bounds and not overlap a control section. Graphics programs keep their existing acceptance rules.scan_blobtakes Phyre effects and FFX/X-2's loose programs wherever it meets them, and a loose file in either form goes to it (one rule for both). Nonzero high offset words remain unsupported and are rejected. - Found on: Unravel TWO (
0100E5D00CC0C000) 1.0.1, with a provisional profile: 22,268 archive members yield 2,629 unique shaders (438 vertex, 1,793 pixel, 398 compute), against zero before. The Mac shader build completes with all 2,629. - Check:
test_kit.pyconstructs KIT parts and Phyre effects without game data. It covers a block that cannot decode without the preceding dictionary, raw members, missing or truncated parts, invalid lengths and hashes, stable game rows when a DLC repeats a KIT effect, parts inside a RomFS image, and the split's red line for a damaged member.test_vbf.pycovers the Phyre rules: compute bounds, the parent archive's scan budget and graphics code containing the control magic as a literal.test_pg_shader.pychecks that a minimal binding-table record still reaches the existing reader. Format reference: Luigi Auriemma's Unravel KIT reader.
Falcom .pkg / .pka archives and Phyre RYHP GLSLC effects
- Symptom: the shader split finds no shaders (or only the few offline outputs in
main) and stalls reading an 8 GB.pkaarchive as a plain file; the RomFS holds headerless.pkgpackages (u32 0,u32 count,count × 0x50-byte entries) and/or a PH3.pkaarchive (0x7ff7cf0d). - Cause: Falcom's Switch releases store assets and shaders in compressed
.pkgentries (flags1= raw LZ4 block carrying BNSH in CLE ports; flags0x10= zstd in PH3/NISA ports) and deduplicated.pkaarchives indexing virtual.pkgfiles by SHA-256. In PH3's PhyreEngine Switch port, each.fx.phyre/.fx#*.phyre(RYHP) effect carries whole single-stage GLSLC outputs (0x19866891) rather than FFX/FFXII's adjacent code+control layout, sophyre_shadersreturned none. - Fix:
shader_split.pyaddsfalcom_decompress(flags0stored,1LZ4 block with a255:1pre-allocation check,0x10bounded zstd; unknown flags skipped with one[WARN]per archive),falcom_pkg/falcom_pkg_shaders(validatingfirst_off == 8 + 0x50 * nbefore walking any table and falling back to plain scanning on mismatch), andfalcom_pka_jobs/falcom_pka_shaders(validating bounds, deduplicating by SHA-256, skipping.dds.phyre/.dae.phyre/.xml, and sharding across workers).scan_blobfalls back toglslc_shaders(..., need=False)insideRYHPcontainers whenphyre_shadersfinds nothing andGLSLC_MAGICis present. Single-stage vertex programs useseparable_pairs. - Found on: The Legend of Heroes: Trails into Reverie (NISA v1.0.4 /
v262144): 8.09 GBdata/asset/nx/assets.pka(14,915 virtual.pkgs, 83,768 unique zstd blobs, 5,710.fx*.phyre) and 213 loose.pkgfiles yield 58,567 unique shaders (44,189 pixel, 14,378 vertex, 14,378 variation pairs, 0[RED]/[WARN]) in 9.5 s on Mac, against a stall/0 before. - Check:
dm/tools/tests/test_split_falcom.pytests stored/LZ4/zstd.pkgentries,RYHPGLSLC fallback,.pkaSHA-256 deduplication inside aRomFS.img, non-pkg fallback, O(1) rejection on large bogus counts, LZ4 bomb pre-check, unknown-flag[WARN], and corrupt.pkg/.pkared lines.
Cornfox VFS2 archives
- Symptom: the shader split finds no shaders (
[RED] the shader split found no shaders in main or the RomFS) when the RomFS stores its assets inVFS2containers (data.vfs). - Cause: Cornfox & Bros.
VFS2archives open with'VFS2',u32 ndir(7in Oceanhorn'sdata.vfs),ndir × 20-byte directory records,u32 nfile,nfile × 24-byte file records ({hash, index, flags, dir_index, offset, stored_size}), an optionalu32 names_offtail table (nfilefile names +ndirdirectory names), and payload data from immediately afternames_off. Per-file encoding (flags & 7, confirmed inExeFS/main0x327658/0x3283a8) is0raw,1bitwise-NOT (^ 0xff), or2u32inflated length + zlib stream; Oceanhorn packs its 362 GLSLC shader files (181.vs+ 181.psineffects/) with mode2, so the generic prefilter saw no known shader magic and skippeddata.vfs. - Fix:
shader_split.pydispatches'VFS2'files (mapped viaromfs.mmapinscan_file_in, and bytes inscan_blob) tovfs2_shaders. It validates the directory, file, and optional name tables, checks every entry's data range and encoding mode, peeks 4 bytes (raw, inverted, or zlib) to skip non-shader assets without inflating them, and inflates/parses every entry starting withGLSLC_MAGICthroughglslc_shaders(..., need=True)with exact-EOF and length checks (failing loudly viared()on malformed containers or damaged entries). - Found on: Oceanhorn: Monster of Uncharted Seas (
01007D7001D0E0001.0.1; originally reported in PR #2906):data.vfs(172.6 MB, 1,041 indexed entries) yields 362 GLSLC records (172 unique shaders: 57 vertex, 115 pixel) in ~180 ms viammap, matching a full-file zlib scan with zero[RED]lines. - Check:
dm/tools/tests/test_split_vfs2.pycovers mode 0 (raw), mode 1 (bitwise-inverted), and mode 2 (zlib) entries, nested directory paths, nameless (names_off = 0) containers viascan_file(mmap), and fail-loud[RED]rejection on truncated headers, oversized counts, out-of-range offsets, corrupt zlib, length mismatches, inflated-size bombs, unsupported modes, and parent cycles; fuzz seedvfs2indm/tools/fuzz/fuzz_shader_split.py.
Diablo III's console packages
- Symptom: the split finds no shaders (
[RED] the shader split found no shaders in main or the RomFS), the RomFS holds only.cpkfiles, andcpk.pyrefuses them (not a CPK); the run prints[RED] shader … is not in the shader mapfor every program. - Cause: Diablo III: Eternal Collection's
.cpkfiles are Blizzard's console packages, not CRI's: they start with the u320xa1b2c3d4and a version (7), then bit-packed tables and the data in 64 KiB sectors. Each file is stored or one zlib stream behind a 6-byte record{u32 decoded length, u16 stored length}; the game's SNO assets (0xdeadbeefheaders) are such streams, and its shader assets hold each program as a control section directly followed by its code area. No reader looked inside the streams. - Fix:
dm/gfx/tools/d3cpk.pyfinds each stream by its record and keeps it only when it inflates to exactly its decoded length and ends at its stored length, so a false start in stored data is left out; it does not read the archive's tables (no stream crosses a sector: inClientCommon.cpkall 57,942 store at most 0xffff bytes).shader_split.pyreads the packages in byte ranges (d3cpk_jobs) and takes every control section of 0x760 to 0x880 bytes followed by its code area in the same stream (d3cpk_shaders), each a program of one stage; one that is not is named in a red line, never dropped silently. - Found on: Diablo III: Eternal Collection 2.7.7: 1,324 shaders (562 vertex, 762 pixel) from 16 GB in 26 s, against none before; every program the game asked for up to its menus is among them.
- Check:
dm/tools/tests/test_split_d3cpk.py: shaders in streams among stored data with a false zlib header, any cut of the byte ranges giving the same keys, a control section whose code area is cut short named, a record whose decoded length is wrong not taken.
Blizzard's CASC storage and SHAD containers
- Symptom: the split finds no shaders (
[RED] the shader split found no shaders in main or the RomFS) and names control sections inmainwithno code area: no data record points at one; the RomFS is adatafolder of archives named00-00000001.data…17-00000002.databeside.psvmanifests andbuild_key.txt; the run prints[RED] shader … is not in the shader mapfor every program and draws black. - Cause: Diablo II: Resurrected keeps its files in Blizzard's CASC storage (
build-playbuild-installer = ngdptool_casc2indata/.build.config): the archives hold each file stored, as one zlib stream, or as a BLTE container, and only text manifests (pipe-separated, one line per file with its archive and encoded key, whose last five bytes are the file's offset) say where. Its shaders areSHADSHADcontainers in it (data/hd/shaders/*.bin, one stage per file, its permutations asBTCDchunks underPRM[), each record{u32 5, control length, code length + 0xc, code length, u32 4}+ code area + control section.mainholds 10 more records of the same form (9 distinct shaders), and its code points at the record's start, not at either section, soraw_shadersfound no code area for them. - Fix:
dm/gfx/tools/casc.pyreads the manifest whose config keybuild_key.txtnames (the current build's) and decodes a file by its encoding (z,n,b:BLTE withN/Zchunks), checking its decoded length.shader_split.pyreads every current file by archive in ranges (casc_jobs,casc_shaders) and scans it like a loose file;scan_blobreads aSHADSHADfile's chunk tree (shad_shaders), each record's lengths checked against its chunk, the stage from the code area;raw_shaderstakes the code area before a control section when a record header there gives exactly that section andmainpoints at the record (a relocated pointer or adrp + add).'#SHAD@'keys are single-stage programs. - Found on: Diablo II: Resurrected 1.0.34.0: 6,931 shaders (2,344 vertex, 4,559 pixel, 26 compute, 1 hull, 1 domain) from 132,413 files in 12 s, against none before; all 38 programs the game asked for up to its title are among them.
- Check:
dm/tools/tests/test_split_casc.py: shaders inz,nand BLTE files of a synthetic storage, another config key and a key naming another archive refused with a red line, a record whose lengths do not add up named, BLTE lengths checked, and main's records found through a relocation and an adrp + add while one nothing points at is named.
DrinkBox's SHADERS container
- Symptom: the split finds no shaders (
[RED] the shader split found no shaders in main or the RomFS) although the RomFS holds ashaders.dat.nxof 733 KiB (Guacamelee! STCE) or 2.8 MB (Guacamelee! 2), starting withSHADERS\0. - Cause: DrinkBox Studios' shader container (verified in Guacamelee! 2
main+0x62ba0and+0x673f0):'SHADERS\0',u8endianness (1= little-endian),u32string table length + NUL-terminated.vsh/.pshsource and entry names,u32uniform count +127-byte uniform descriptors (char name[124]+ 3 binding bytes),u32shader data length + 16-byte-aligned shader blobs, andu32shader count +29-byte index entries (<6IBI:name_off,entry_off,u_start,u_cnt,data_off,data_len,kind0=vertex/1=pixel,id) ending at EOF. Each blob in the data section is a20-byte header ({u32 code_len, u32 ctl_len, u32 n_uniforms, u32 cbuf_size, u32 flags}),n_uniforms × 127uniform descriptors, the GPU code area, and the NVN control section (0x838bytes here). The generic prefilter saw none of the known magics and dropped the file. - Fix:
shader_split.pydispatchesSHADERS\0files (scan_file_inandscan_blob) todbx_shaders: it parses the container structurally end-to-end, validates UTF-8 shader/entry names, uniform ranges, non-overlapping blob spans, exact blob sizes (20 + 127 * n_uniforms + code_len + ctl_len),GFX_MAGICwith at least0x80bytes (header + SPH), entry-vs-SPH stage agreement, andcheck(), rejecting NVN2 controls and trailing/truncated data with a red line. Because DrinkBox caches pipelines in avs_count × ps_counttable (main+0x63300),#SHDR#programs are paired as single-stage programs (separable_pairs). - Found on: Guacamelee! 2 (
01007E100456C000, v0 and v1.0.4): all 444 entries (133 vertex, 311 pixel; 425 unique shaders, 0 unclaimed bytes) read with full.vsh/.pshnames; also reported on Guacamelee! Super Turbo Championship Edition (0100BAE00B470000, 165 blocks / 163 unique) in PR #2810. - Check:
dm/tools/tests/test_split_dbx.pytests named entry parsing, uniform descriptors, separable-stage pairing, empty containers,scan_blob/scan_filedispatch, and 19 malformed-container rejection cases; fuzz seeddbxindm/tools/fuzz/fuzz_shader_split.py.
NXSD single-stage shader containers
- Symptom: the shader split finds no shaders while loose RomFS files start with
NXSD; a build stops with[RED] the shader split found no shaders in main or the RomFS. - Cause: NXSD version
0x100stores a table of 24-byte descriptors, then fixed0x880-byte NVN control sections and variable-sized code areas in separate regions. The splitter did not recognize the container. Each descriptor names one control and code section; control+0x704gives its code length. - Fix:
shader_split.pyrecognizes the magic independently of the filename. Before copying shader code, it checks the header and makes sure the descriptors cover both regions without duplicate controls, overlapping code or unclaimed bytes. It reads the stages from the code headers, checks each control/code pair through the shared NVN validator, and uses the existing separable-program input cover. - Found on: TETRIS THE GRAND MASTER 4 -ABSOLUTE EYE- (no profile), reported by ralph303 in issue #743, with the layout and original reader in their source commit. Other NXSD versions and layouts remain unsupported; recognizing its shaders does not establish gameplay support.
Media.Vision wide MVGL archives and NXVS / NXFS / NXCS shader containers
- Symptom: the shader split finds no RomFS shaders in a Media.Vision NVN title whose files live in
MDB1.mvglarchives, andraw_shadersmisses embedded post-processing/present shaders inmainwhose control sections are followed by compiler options before the code area ([RED] main control section @…: no code area). - Cause: newer Media.Vision titles use a wider 64-bit
MDB1layout (0x20-byte header withu32counts andu64data start/size, 16-byte tree entries with0xffffffffempty sentinel,0x80-byte name entries, 16-byte data entries withu64offsets, and raw LZ4 blocks instead of doboz), whereasmvgl.pypreviously only read Cyber Sleuth's 32-bit/doboz layout andshader_split.pydid not openMDB1archives or parse Media.Vision'sNXVS/NXFS/NXCScontainers (u32total size at+4,u32control offset/length and code offset/length at+0xc). - Fix:
dm/gfx/tools/mvgl.pyrecognizes both legacy and wideMDB1layouts structurally from header table-end equality and archive size, decoding doboz or raw LZ4 blocks accordingly.shader_split.pydispatchesMDB1archives by magic (mvgl_jobs/mvgl_shaders, reading.shadentries without decompressing unrelated assets), validates standalone and embeddedNXVS/NXFS/NXCScontainers (nxsh_shader/nxsh_embedded, covering both RomFS.shadfiles andmain's embedded shaders), and adds#NXSH@toSINGLE_STAGEfor separable-program pairing. - Found on: Digimon Story Time Stranger (issue #872): v1.2.2 (
135c83cdea06aec2) extracts 19,078 unique RomFS shaders (37,885NXVS+37,885NXFSacross 51 wideMDB1archives), 202 unique shaders frommain(28NXVS,172NXFS,2NXCS, zero missed controls), and 3,657 additional DLC shaders (22,937 total). LegacyMDB1reading was re-verified on Digimon Story Cyber Sleuth: Complete Edition. - Check:
dm/tools/tests/test_split_mvgl.pyanddm/tools/fuzz/fuzz_shader_split.py(nxvs/nxfsseeds).
A file no reader reads
- Symptom: the shader split stops on one archive with a Python traceback (an
IndexErrororstruct.errornaming no file), or a reader's[RED]line about a format it does not know, and nothing is written; the NSP script loses the build at the split. - Cause: a worker's exception (and
red(), aSystemExit) ended the whole split through the process pool, so one archive of a format revision a reader does not know stopped every other file's shaders too.nlg_dictread its index without checking the layout, so an index of another revision gave anIndexErrorinstead of a line naming the archive. - Fix:
scan_fileleaves out a file whose reader fails, with[RED] <file>: <why> (its shaders are left out), and the split goes on; at the end it prints[RED] <n> file(s) could not be read, their shaders are left out (first: …)and writes its tables. The NSP script shows that line and packs a provisional profile's IPA without those shaders; for a registered profile it stops there, since the profile's tables were split from every file.nlg_dictchecks that the records and chunks fit the index and every chunk index is in range before reading it. The format itself still needs a reader: the line names the archive and, for NLG, its header bytes. - Found on: Mario Strikers: Battle League (no profile; seedds/nxnative#282): one of its 879 Next Level Games archives, a revision
nlg_dictdoes not read. That revision is read now: Next Level Games archives of revision 4.
A large NXCX texture archive stalls the shader split
- Symptom: the split stays at 99% for many minutes and the remaining worker consumes nearly all memory on a 16 GB Mac.
- Cause: the generic loose-file scanner reads the entire 15.6 GiB
w_allpac.mrginto a Python bytes object and searches it repeatedly for embedded formats. Byte sequences that happen to match shader magics occur inside compressed textures and trigger extra searches. - Fix: for an
NXCXtexture archive, look for embedded signatures in overlapping 16 MiB chunks. Pass GLSLC candidate offsets to the existing validator through a read-only mapping. If a signature indicates another supported embedded format, use the ordinary loose-file scanner. - Found on: TSUKIHIME A piece of blue glass moon 1.0.2. The full split finished in 77–80 seconds on a 16 GB Apple M6 Mac mini with the files on S790. The original run was stopped after 19 minutes 55 seconds and its worker peaked at a 15.6 GiB physical footprint. The original reader, run against the large archive using a mapping for comparison, also found zero shaders there.
- Check:
dm/tools/tests/test_split_nxcx.pycompares both paths for a valid GLSLC record whose magic crosses the chunk boundary, and checks that a BNSH signature takes the ordinary path.
Next Level Games archives of revision 4
- Symptom: a black screen after the loading text; the split prints
[RED] /init.dict: the index (… header 04 04 03 00 …) is not in the layout of Luigi's Mansion 3's archivesfor 878 of 879 archives and keeps only the 40 shaders ofmain, and the run prints[RED] shader … is not in the shader mapfor the programs the game draws with. - Cause: Mario Strikers: Battle League's archives are a later revision of Luigi's Mansion 3's (
nlg_dict): after the magicu8 4, u8 4, u8 3(zstd), 0x20 bytes, the stored length of the index and six more words, then the index as one zstd frame at +0x40. The.databeside it is a stream of zstd frames (2 MB each, some padded to 8 bytes) whose concatenation is the archive's sections. The index's shader table has four 12-byte entries per program{u8 kind (1 code area, 2 control section), u16 type (0x0db4), u8 number 1 to 4, u32 length, u32 offset in its section}: numbers 1 and 2 are the program's code area and control section, 3 and 4 the same kinds in the.debug/.nxpcfiles, which are not shipped. All shaders are ininit: in 1.0.0 the control sections back to back (0x880 bytes each) and the code areas back to back in the same order. An update'sinit.patch(u8 4, u8 5, u8 3, the inflated body length, the entry count of its table, then the body as one zstd frame at +0x18) starts with the new table and the new shader table; an offset below the old section's length reads the base archive, the rest the body's new data counted from that length, as in Luigi's Mansion 3's patches. - Fix:
nlg4_shaders(shader_split.py) reads that table from the base index and, when there is one, from the patch body. Where each section starts in the stream (and in the body) is not read from the index yet: it is the one start for which every offset of its kind lands on a control section or a code area header, and every program is then checked bycheck(), so a wrong start cannot pass. Other archives have no shader table, but NintendoWare Ui2d / Font keep BNSH containers in their data (19 inFrontEnd/Persistent, 5 inglobal, 2 in each tutorial archive): every archive's data and patch body is searched for them and read withscan_blob, as BNSH is everywhere else. zstd frames are measured from their block headers (zstd_frame_len) and decompressed with thezstdcommand, asunzsdoes. - Found on: Mario Strikers: Battle League (no profile): 2,648 programs in 1.0.0, 3,149 in update 1.3.2 (the count of
nvnProgramSetShaderscalls at boot), all of them checked, and 41 more from the BNSH containers; 3,230 shaders in the map withmain's 40, against 40 before. With the table alone, eight programs were still missing when the menus came up (captured withDM_NVN_SHDUMP, then found by their bytes in those archives' data) and the quick-match menu showed its bars without text. The intro movie, the menus, the tutorials and a whole match draw on the Mac with no program missing from the map. - Check:
dm/tools/tests/test_nlg4.py: padded frames with and without checksums as one stream, a byte that is neither a frame nor padding named, a base archive and its patch (one program unchanged, one replaced past the old lengths), an index without a shader table read as no shaders, and BNSH containers looked for in the data and in the patch body.
A Yaz0 member that expands is not overlap
- Symptom: the split leaves out archives whose members do not overlap:
[RED] <file>/<member>.szs/#7: the archive members add up to more than 16 times the file (members that overlap), then[RED] <n> file(s) could not be read, and a registered profile's build stops there. - Cause:
scan_blobbounds archives in archives (SARC, PlatinumGames' DAT) so that a damaged or crafted file cannot make its work grow with each level: they nest at mostNEST(16) deep, and the members a file's archives open add up to at most 16 times the file. It counted a Yaz0 member by what it expands to, then counted that member's members again, so the same decoded bytes were paid twice. A 204 KB SARC holding one layout archive that expands 9 times added up to 18 times the file. - Fix: two budgets, each 16 times the file. The first counts each member by what it takes up in its archive, so it still stops members that overlap. The second counts what Yaz0 members expand to, charged from the Yaz0 header before the member is decoded. Each bound stays what it was, so the work is still within a small multiple of 16 times the file. Charging only the stored size, with no second budget, would have let the work grow by the Yaz0 ratio (about 90 at most) as well.
test_split_nesting.pycovers the layout archive's shape, the fan-out corpus input, a compressed fan-out (stopped after 19 scans; 8^6 without the bounds) and a Yaz0 member that expands 87 times, stopped before it is decoded. - Found on: Mario Kart 8 Deluxe (GitHub issue #640): its race and result layout archives (
UI/<lang>/race.sarc,tv.sarc,UI/cmn/tv_result.sarc), 14 files in 4.0.0 and 28 with 4.0.1.
BNSH in NintendoWare archives and in main
- BNSH (
BNSH\0\0\0\0+grscblock at +0x60) is found insidebfsha, particle effects (esetb, VFXB), UI layouts (blarc), andmainitself. - Variation table at +0x80 (count at +0x7c); binary program at variation +0x10; six stage pointers from program +0x08 (vs, hs, ds, gs, ps, cs).
- Stage code descriptor: control ptr +0x08, code ptr +0x10, code size +0x18, control size +0x1c. All pointers are relative to the BNSH start.
Nintendo EPD (sead / agl / gsys): BNSH, agl sharcb and resource packs
- Super Mario 3D World + Bowser's Fury: bfsha (BNSH) and agl sharcb (BAHS version 9, next entry) in
ShaderData/*.szs, particle effects (BNSH, including 25 compute shaders) inEffectData, six layouts andSystemData/AglResource.szs(BAHS), and two BNSH inmain: 11,080 shaders. All bind with Mario's texture handle layout (0x20 + 8 × slot); the one failure is a geometry shader (fur fins,RenderFinFur), which Metal cannot express (Geometry shaders with no Metal stage). - The Legend of Zelda: Breath of the Wild: 19,592 shaders:
Shader/*.sbfsha(BNSH) and the gsys / ksys / terrain resource packs insidePack/Bootup_Graphics.packandPack/TitleBG.pack, the particle effects inEffect/*.sesetlist(11,373 shaders, 101 compute), layouts (.sblarc) and 37 inmain. All bind with Mario's texture handle layout; the full build had no failure and no unresolved binding.
BAHS in agl sharcb
- How it is stored: agl
sharcb, the engine utility shaders: code region at header +0x1c (size +0x18). Binary entries in the table area are 16 bytes{code offset, 0, control size (0x880/0x88c; 0x848 in BAHS version 9, Super Mario 3D World), signed offset from this entry to the control section}. - Pairing: control sections are shared between programs, so pair by entry, never by searching for code near a control.
- Found on: Super Mario 3D World + Bowser's Fury (BAHS version 9).
A control section's words read as a BAHS entry
- Symptom: the shader build fails one agl or terrain shader no run ever asks for, with
Ampere instruction 481 at 0x0 (000000000000000000000000020c0481) is not implemented(a vertex shader's SPH read as an instruction); in the map, a shader whose control stage disagrees with its code (a compute control with a vertex SPH, a pixel control with a vertex SPH) and whose stored control section is longer than the file's real ones (0x200, 0x1100, 0x1400 against 0xe0). Also: nopso_pairs.tsvrows from a file whose lowest such entry hides its binary array. - Cause:
bahs_shadersfinds the entries by scanning the table area 4 bytes at a time. An NVN2 control section's +0x38..+0x47 (instruction length, c1 start and end, code length:L, 0, L, L) reads as an entry{code offset L, 0, control size L, control L bytes on}. When L is a multiple of 0x100 and a later program's control section lies L bytes on, every check passes: the shader pairs that control with whatever code lies at L in the code region.bahs_variationsfinds the binary array at the lowest entry taken minus 0x18, so such an entry below the real ones also hid that file's variation pairs. - Fix: an entry that lies inside a control section another entry names, measured by that section's own length (
ctl_len, 0x48 key bytes for NVN2) rather than the length an entry claims, is dropped. Whether a false entry's section is genuine does not matter, as its first 0x48 bytes are a real control section. - Found on: The Legend of Zelda: Ocarina of Time: six such shaders in
agl_common,agl_technique,agl_technique_pfxandtera_common, none of them ever loaded; one failed the build.tera_commongave 175 variation pairs once its false entry was gone. Splatoon Raiders: the same three agl keys (68bbe98b3bfd9876,18be578dfdaaffa0,7a4936fccf82094e), dropped when its tables were split again (issue #1613). Donkey Kong Bananza was split again too and holds no such entry: its tables did not change. Mario Kart World: one compute shader inagl_common(797e77c2ec4341c5), dropped from its tables (issue #1592). - Payload outside the control section: descriptor-shaped words can also lie after a control section, beyond the control-span exclusion. A nonempty binary record array that fits before the code region and agrees with the scan supplies the entry offsets for both shader selection and variation pairing. The split drops candidates outside those record entry slots. An unrecognized or inconsistent array leaves the scan candidates unchanged.
- Also found on: Mario Kart World 1.8.0, Donkey Kong Bananza, The Legend of Zelda: Ocarina of Time and Splatoon Raiders.
- Check:
dm/tools/tests/test_split_bahs_entries.pyuses synthetic fixtures for control words, payload outside entry slots, and scan fallback for inconsistent arrays, including empty arrays and arrays overlapping code.
Zstd files recognised by their magic
- Symptom:
shader_split.pyfinds 0 shaders in a RomFS of zstd files named.zst. - Cause: the split decompressed only
.zsfiles. - Fix: it now goes by the zstd magic (
28 b5 2f fd) whatever the name. - Found on: Paper Mario: The Thousand-Year Door (8,726 of the RomFS's 9,959 files, the shader archives among them). Of the other 21 games' RomFS on hand only Super Mario Galaxy's
GDDR3.zst(a Vulkan game, no NVN split) has such a file.
HAL's .cmp containers: a size-prefixed frame
- Symptom: the game asks for shaders the map does not have (
[RED] shader ... is not in the shader map, hundreds of lines), and the split finds far fewer shaders than the game uses (121 against 27,288 on Kirby and the Forgotten Land). - Cause: HAL keeps its assets in
.cmpcontainers: a 4-byte little-endian uncompressed size, then a frame (zstd, or LZ4 in theubin/map data). The split decompressed a zstd file by its magic at offset 0, so a frame that starts at offset 4 was read raw, and the shaders inside the BFRES archives of those containers were never seen. - Fix: the split opens a size-prefixed frame as well (
unsized: zstd, with a dictionary as for a plain zstd file, or LZ4) when the file's bytes 4 to 8 are a frame magic and bytes 0 to 4 are not the zstd magic. A frame whose header records a size other than the prefix is not such a container, and the file is read as it is: Tears of the Kingdom's 1,202Cave/…/C.crbin.<hash>/*.quadfiles are a 4-byte hash (the one in their folder name) and a zstd frame, the only files with a frame at +4 in the RomFS of 39 other games on hand. A frame that records no size must decompress to exactly the prefix's size; otherwise (it does not decompress, it holds more or less, or it names a dictionaryPack/ZsDic.pack.zsdoes not have) the split prints a[RED]line and reads the file as it is. - Found on: Kirby and the Forgotten Land: 7,201
.cmpfiles, 5,121 of them zstd frames with 19,364 BNSH inside (11.2 GB decompressed) and 2,080 LZ4 frames, all of the latter inubin/(0.3 GB, and no BNSH); the same layout is in 430.cmpbinfiles (76 zstd inlyt/, 354 LZ4 insnd/). Every zstd frame records its size, the same as its prefix; no LZ4 frame does, and each decompresses to its prefix's size. The split now finds 27,288 shaders in the base game (18,476 ingfx/, 8,313 inptcl/, 378 inlyt/, 67 in the looseshaderfiles, 54 inmain), against 121 before, and 27,302 with update 1.1.0 (v65536: 14 more inlyt/).
BNSH in Bezel Engine archives
- How it is stored: the shaders are BNSH in the
.bfshaentries of the.beaarchives (zstd entries, 01), most of them the engine's own inSystem.nx.bea(_BezelSystemResources/<system>/shader/*.bfsha: PBR shadow maps 846, post effects 770, …), the rest in the layouts'__ArchiveShader.bnshand the per-archive shader packs (.bnbshpk), plus one BNSH inmain. - Reader:
shader_split.pyscans each archive entry as a file of its own (bea_members). - Found on: Big Brain Academy: Brain vs. Brain (NintendoWare Bezel Engine 1.56): 2,125 shaders in about 90 s.
Bezel Engine 2.9 archives keep their entries inline
- Symptom: the split finds almost no shaders and reports
[RED] /Archive/<name>.bea: entry 0 @0x4854535341 is not an ASST entry (its shaders are left out)for every archive (… file(s) could not be read); the "offset" is the bytesASSTH. - Cause: the 1.56 form (version 0x10100 at +8) has at +0x28 the offset of an array of entry offsets; the 2.9 form (version 0x60000) has the entries themselves there, back to back, each 0x48 bytes (its size the u32 at
ASST+4), with an 8-byte type tag (_G3DSHA,_TEXDATA, …) at +0x1c and a 16-byte hash before the data and name offsets, which are the last two u64 of an entry in both forms. - Fix:
bea_membersreads the entries in place when the array starts withASST. - Found on: Super Mario Party Jamboree (Bezel Engine 2.9, 949 archives, 127,203 entries): 25,693 shaders, against 246 (those in
main) before, most of them in the 13,839.fshb(_G3DSHA) entries; the split takes about 10 minutes.
BNSH entries of GFPAK archives
- Symptom: a provisional split finds only a fraction of the shaders (3,126 of Pokémon Sword's 41,516).
- Fix:
shader_split.pygfpak_membersreads the BNSH entries of GFPAK archives (LZ4 entries, 01). - Found on: Pokémon Sword: 41,516 shaders, nearly all BNSH entries of the 7,699 GFPAK archives under
bin/archive(the models' and effects' shader archives), beside loose BNSH files (bin/battle/waza/model/**/*.bnsh_vsh/_fsh,bin/graphics,system_resource/shader) and two inmain. The YEBIS shaders it also draws are inmain(Shaders in a zlib stream in main).
Oodle entries of GFPAK archives
- Symptom: the split counts hundreds of files as unreadable (678 on Pokémon Legends: Arceus), each with
[RED] <file>.gfpak: entry 0 has compression 3 (Oodle), which this reader does not decode, and leaves their shaders out. - Cause: every entry of Arceus's GFPAKs is compression 3, Oodle Kraken, where every entry of Sword's is LZ4 (BNSH entries of GFPAK archives).
- Fix:
shader_split.pygfpak_membersdecodes compression 3 with the game's own decoder, as it decodes Trinity packs (oodle,DM_OODLE_HOST/DM_OODLE_MODULES).profile_guess.pybuild_sourcescounts the GFPAKs that hold an Oodle entry, so the NSP script sets that decoder up for the split (oodle_packs).dm/gfx/tests/test_gfpak.pycovers each compression. The Mac path was checked without Arceus's files: a GFPAK of 300 Kraken streams from Pokémon Scarlet's packs (28 MB raw), read bygfpak_membersthrough the Mac host, decodes the same with Scarlet's and Z-A'sOodleLZ_Decompress, andbuild_sourcessetsoodle_packsfor it but not for an LZ4-only GFPAK. - Found on: Pokémon Legends: Arceus 1.0.2 (
01001F5010DFA000, no profile yet;mainhasOodleLZ_Decompress): all 678 GFPAKs underbin/archive, Oodle in every entry. The provisional split finds 12,851 shaders with them, 69 more than without. 73 shader map rows first appear in a GFPAK:field/resident_release.gfpak40,appli/battle_resident.gfpak26,appli/system_resident.gfpak5,appli/poke_dex.gfpak2.
BNSH in Trinity packs
- How it is stored: every shader is a BNSH inside the Oodle-compressed files of
arc/data.trpfs(01). - Reader: for any game with Trinity packs (
ONEPACKfiles),trpfs_jobs/trinity_shadersinshader_split.pyname the packs fromdata.trpfd, decode every file with the game's own Oodle in the Mac host (DM_OODLE_HOST/DM_OODLE_MODULES, set by the NSP script) and scan it like a loose file. - Copies that differ: the layout archives' control sections are 104 KB long, and their stage descriptors run 456 bytes past the control's own length (control +0x20), with bytes that differ between copies of one shader;
same_shadercompares copies only up to the control's own length. - Found on: Pokémon Legends: Z-A (Game Freak's engine): 28,603 shaders (11,633 vertex, 16,845 pixel, 125 compute) and 26,051 variation pairs: the material shaders in
system_resource/gfx2/shader/NX64/env_ikkaku(material/standard.bnsh,material/transparent.bnsh,system/light.bnsh, and thespecial/imgui.trshapack with the engine's system shaders), particle effects (.ptcl/.trtmlinik_effectdata, 19,842 of the shaders), UI layouts (__ArchiveShader.bnshin the.truivpacks ofuidata) and the 40 BNSH inmain.
GLSLC outputs in main and in loose files
- How it is stored: 13 Sentinels (Vanillaware's engine) has no shader file in RomFS, whose six CRI CPK archives hold textures, scripts, CRI audio and USM movies: 838 GLSLC compiler outputs sit in
main's read-only segment, each referenced from a{pointer, size, 0}table in.data. Other engines keep whole outputs in loose RomFS files of their own formats (below). - Layout: an output starts with the magic
0x19866891, its total size is at +0x44, and it holds exactly one control section with the code area right after it (control +0x20 = control length); a debug section with the NV assembly and the GLSL source follows. The stage comes from SPH word 0, as for BAHS. Outputs that hold several stages, and SDK 4's outputs, are read through their section headers (GLSLC outputs holding several stages, GLSLC outputs read through their section headers). - Reader:
shader_split.pyreads them in every game'smain, accepting only outputs that pass the control / code / length check. Loose RomFS files are searched the same way: it reads GLSLC outputs in any RomFS file no other reader takes. When the reader was written, of the other profiles' files only Metroid Dread's MSHD files held any, whichmshd_shadersreads (MSHD in MercurySteam's bshdat files). - Found on:
- 13 Sentinels: Aegis Rim: 838 in
main. - Fire Emblem Engage: 11 in
main, Unity's own. - FINAL FANTASY TACTICS - The Ivalice Chronicles: 257 whole GLSLC outputs in the engine's technique files (
*.tec:resources_nx/release/master/shader/*.tec, magicTEC\0, each output whole after a table of parameter names) beside 49 inmain. - Absolum: 163 GLSLC outputs in
shaders.nx.bin(rom:/shaders.nx.bin: a u32 count, then per entry a u32 hash, a u32 size and one whole output): 162 unique shaders, 83 pixel and 79 vertex, every vertex shader paired with the single-stage cover (Single-stage programs paired with a cover). Its.xnbeffects are XNA's D3D9 effects, MOJOSHADER linked in, which the GPU does not run. - Catherine: Full Body: 3,050 loose files in
data/shaders_binary(*.vs/*.ps, one stage each, one output per file), read like FINAL FANTASY TACTICS' technique files; its vertex shaders are in two parts (VertexA and VertexB parts merged into one vertex shader).
- 13 Sentinels: Aegis Rim: 838 in
SHARC archives in GIANTS Engine
- Symptom: the shader split finds no shaders in main or the RomFS, which keeps them in
shared/shader_switch.sharc. - Cause: SHARC v11 (
RAHS) puts three entry tables after its0x2c-byte header, then the metadata and shader payloads. Each shader member contains one GLSLC output compressed with raw LZMA1, preceded by a five-byte property and dictionary header. - Fix:
shader_split.py(sharc_shaders) checks the table and member spans, including the side records and length-prefixed names. The LZMA members omit end markers, so the reader checks each decoded GLSLC output against its declared length and requires it to pass the GLSLC parser. A short member fails the archive read even if earlier members decoded. - Found on: Farming Simulator 26: Nintendo Switch Edition, update 1.0.1.0. Removing one to eight bytes from the final compressed member left its GLSLC output short even when the compressed size was adjusted to match.
GLSLC outputs holding several stages
- Symptom: the split found no shader in the game (0 shaders).
- Cause: an output may hold several stages compiled together as one program (Baba Is You: the 120 outputs in
Assets.dat, each a pixel and a vertex shader, then a reflection section), which the single-stage reader does not take. - Fix: such an output is read by its section headers (+0x4c section count, section i's header at +0x90 + 0x90 i, type 0 = GPU code;
glslc_program; the same headers SDK 4's outputs are read through, GLSLC outputs read through their section headers), and its stages are paired with each other, not as single-stage programs. The NSP script now stops at the split when it finds none. - Found on: Baba Is You.
GLSLC outputs in a zip archive, and those NROs compile at run time
- Symptom: an NVN game's split finds none of its shipped shaders, and the ones it compiles at run time were not captured: the game's renderer is in NROs that call
glslcCompile, and its whole RomFS is one zip. - Cause: Portal keeps all its files in
game.zip(41,416 members, Deflate or stored). The Source engine's D3D9 layer (materialsystem.nro) links each vertex and pixel shader combination into one program; the programs of the game's precache list (portal/glbaseshaders.cfg, 219 entries) ship compiled asnxcontent/nvsb/<hash>.nvsb(NVSB, version 0x65, the file's length at +8, a 0x60-byte header, then one GLSLC output holding a vertex and a pixel shader). A deflated member hides the GLSLC magic from the loose-file scan. The game compiles the rest withglslcCompile(its movie shaders and its own blits: 10 outputs within 30 s of boot), and the capture rule looked only formainholding GLSL sources and importingglslcCompile. - Fix:
shader_split.pyreads zip archives member by member in parallel ranges (zip_jobs/zip_shaders;zipfile), each member scanned like a loose file, whole GLSLC outputs included.profile_guess.pyshader_sourcesasks for the run-time GLSLC capture when an NRO the game loads importsglslcCompileand a subsdk defines it (glslc_capture). Portal's map: 242 keys from the.nvsbfiles and 13 from the capture, 229 vertex and pixel pairs. - Found on: Portal. No other profile's RomFS has a zip archive holding shaders.
PMAP records in phx's PDAT archives
- Symptom: a Switch 2 game whose split finds no shader: the RomFS holds
Asset/assets_a000.dat(magicPDAT, 16.6 GB) andAsset/assets.cat(magicPARC, a table of 64-bit ID hashes), and the first boot stops oncannot read the shader map. - Cause: the engine's namespace is
phx, its platform layerAurora. Its records are flatbuffers with a four-letter tag at +4 (PMAP,PMTR,PANM,PMSH,PSHD, ...), nearly all of them one zstd frame each, unencrypted. APMAPrecord is one program: its control sections (NVN2, 0xe0 to 0x128 bytes, their length at +0x30) lie 8-aligned, each directly followed by its code area (control +0x44 bytes). 19,143 are vertex + pixel, 85 add a geometry shader and 8,071 are one compute shader. A record too small to shrink is stored as it is (one, a compute shader). - Fix:
pdat_jobsandpdat_shadersinshader_split.py: a byte range of the archive per job, every zstd frame whose decoded tag isPMAP, and control sections outside any frame. The catalog is not read. A frame's first block can be 128 KB, and zstd gives no output before it has the whole block, so the tag check feeds it that much: fed 4 KB, 21,962 of 27,540 shaders were silently left out. A loose.ndsrfile also never reachedndsr_shaders(the prefilter for loose files did not know its magic); it does now:Bin/Nvn2-upper_left.ndsr, 28 shaders, in Star Fox's and Bananza's record layout from +0x10. - Found on: Kirby Air Riders: 27,568 shaders, 13,078 pixel, 8,092 compute, 6,322 vertex and 76 geometry.
LZ4-chained zip members behind a VZIP preamble, and shader binaries of one stage
- Symptom: a Switch 2 game's RomFS is one
data.zipthat does not start with a zip's local header, zipfile reads a member of it only to stop onBad CRC-32, and the split finds no shader: every member is listed as stored, yet most are smaller on disk than their file size. - Cause: Star Fox's engine keeps the whole game in a zip of its own making (
vfs.zip.c): an 18 MBVZIPindex before the first member, and members the central directory calls stored (method 0) that are chains of 64 KB chunks, each a u32 length and an LZ4 block of that length compressed against the previous chunk as its dictionary (a chunk that would not shrink is stored raw); the CRC is the decoded data's. Its shaders are 2,828 members of a wrapper the engine calls_vrender_shader_binary_t: the GLSLC output magic, u32 code length, u32 control length, u32 0, a 64-bit hash, then the Ampere code area and the NVN2 control section, one stage each;glslc_shadersfinds no section headers in it. - Fix:
zip_jobstakes aVZIPfile as a zip too,zip_memberdecodes a stored member whose size on disk differs from its file size through the LZ4 chain (viper_zip_member, with the CRC checked), andscan_blobreads the wrapper as a single-stage program (viper_shader, keys#VIPER, paired at draw time as GLSLC outputs are). The engine'sVIPRresource containers are scanned for an embedded NDSR file (two of them wrapounce-nvn2-upper_left_ndsr.bin, the upscaler networks, 40 shaders each):ndsr_shadersreads it from the magic on.dm/tools/tests/test_split_viper.pycovers the zip and the wrapper with synthetic bytes. - Found on: Star Fox: 2,856 shaders, 1,483 vertex, 1,305 pixel and 68 compute, all in
data.zip.
GLSLC outputs in Criterion's Bundle 2 resources
- Symptom: an NVN game's split finds a few dozen shaders (
main's and a loose file's) and the screen stays black but for the loading indicator, with[RED] shader … is not in the shader mapandprogram has no vertex shader; the RomFS holds.BNDLfiles that start withbnd2. Burnout Paradise Remastered's shader split reports resources with no stored bytes or data starting inside the resource table; the world and vehicles are invisible. - Cause: Criterion's Bundle 2 keeps each resource zlib-compressed. Its version sets the number of blocks a resource has, B: 3 in version 2 (Burnout Paradise Remastered), 4 in version 3 (Need for Speed: Hot Pursuit Remastered). The header gives the entry count and table offset (+0x10, +0x14), B block data offsets (+0x18) and then the flags (bit 0: compressed; +0x24 in v2, +0x28 in v3); an entry (0x40 bytes in v2, 0x50 in v3) gives the resource ID, B uncompressed sizes (+0x10), B sizes on disk (alignment in the top nibble), B offsets and then the import offset and the type (+0x38 in v2, +0x44 in v3). Hot Pursuit Remastered's
SHADERS.BNDLholds 2,112 whole GLSLC outputs in block 1 of its type 0x8 resources, and Burnout's bundles hold its model and material shaders, none of which a raw scan of the files can see. - Version 2: read with version 3's layout, a version 2 bundle's other fields pass for sizes and offsets: Burnout's split read 2,882 of its files as damaged (
declares N bytes and has none stored,its data … starts inside the resource table) and kept onlymain's 138 shaders.bnd2_resourcestakes B and the entry size from the version (BND2_LAYOUTS) and every other offset from B;test_split_bnd2.pychecks a synthetic compressed v2 bundle beside the v3 tests. - Fix:
shader_split.pyreads a file that starts withbnd2resource by resource (bnd2_resources) and scans each inflated block for GLSLC outputs (bnd2_shaders), by the outputs' magic rather than the resource type, whose numbering is per game. Hot Pursuit Remastered: 89 → 2,154 shaders, the 10 its first frames asked for among them; Burnout Paradise Remastered (v0): 138 → 376, none missing from the map from the title to the first drive. - Resource validation: the reader believes no size in the file. The header and the entry table must lie inside the file, each block's data after the table and inside the file, and each block's declared size (alignment bits masked) must match what is stored; a block that declares a size and stores nothing is an error too. Inflation stops one byte past the declared size and needs a complete stream, so a size that lies cannot grow without bound. A bundle that fails is named in a red line and its shaders are left out, like any file no reader can read (
scan_file). The platform field (+0x08) is not checked: nothing here reads it, and a big-endian bundle already fails on its version. Measured on the game: What it needs. - Found on: Need for Speed: Hot Pursuit Remastered; Burnout Paradise Remastered (version 2).
GLSLC outputs in UbiArt IPK archives
- Symptom: an NVN game's split finds a handful of shaders (
shaders: 8 (pixel 5, vertex 3)) and the screen stays black after boot, with[RED] shader … is not in the shader map(27 programs on the title screen); the RomFS holds.ipkfiles that start with50 EC 12 BA. - Cause: Ubisoft's UbiArt keeps its files in big-endian IPK archives (
50 EC 12 BA, version, platform, data start at+0xc, file count at+0x10). Version 7 has a0x38-byte header and stores directory then name in each entry. Version 5 has a0x30-byte header and stores name then directory, followed by the path ID and cooked flags. Each entry starts with the offset count, size, compressed size (0when stored), timestamp, and offsets from the data start. The engine's.fx.fxbeffect files hold whole GLSLC outputs. A raw scan misses them because they are zlib-compressed inside the archive. - Fix:
ipk_shadersinshader_split.pyuses the archive version to read the entry table and checks that each entry fits before reading its payload. It reads only.fxbentries outsideshaders_dev/, inflates compressed entries, and scans them for GLSLC outputs. A malformed table or stream is reported in a red line.dm/tools/tests/test_split_ipk.pychecks both versions on synthetic archives. - Found on: Version 7 in Rayman Legends: Definitive Edition and version 5 in Just Dance 2022 and Just Dance 2019.
G2S containers in KTGL RDB archives
- How it is stored: each material's shaders are a G2S container (
_S2G3000, type KTID0x7bcd279f; 23,108 entries inasset/system.rdb.bin*, 2.3 GB inflated) of GLSLC outputs, as in 13 Sentinels'main, inside zlib-chunked IDRK entries (01). One_DOK0000container (type0x20a6a0bb, the engine's system resources) holds 151 more bare GLSLC outputs, 21 of them drawn in the first battle. - Reader:
shader_split.pymaps the RDB files and inflates only entries that start with those two magics (idrk_shaders), and the 117 outputs inmainas in every game. Many outputs carry 0x850-byte control sections and the compute ones have no code header, soglslc_shadersaccepts controls from 0x760 bytes and takes the stage of headerless code from the thread group size at control +0x748. Pairs come from the single-stage cover (separable_pairs). - Found on: Hyrule Warriors: Age of Calamity (Koei Tecmo's KTGL): 40,726 shaders (37,043 pixel, 3,440 vertex, 241 compute, 2 geometry), Mario's texture handle layout (
0x20 + 8 × slot). ROMANCE OF THE THREE KINGDOMS 8 REMAKE's newer KTGL keeps them (_S2G5000/6000/7000, and_DOK0000) in.fdatafiles whose IDRK entries are LZ4 or zlib in chunks of another form (01): 59,214 outputs there and 149 inmain, all of them built. - Note: the older KTGL of Three Houses packs the same G2S containers differently (SPKG packages in KTGL LINKDATA).
SPKG packages in KTGL LINKDATA
- How it is stored: shader packages (
SPKG:patch*/nx/shader/*.spkgand 132 entries ofDATA1.bin) of G2S containers as in the RDB entry, one_SPK4100package without G2S (the post effects,DATA1.binentry 549), and map and model archives carrying packages of their own. - Reader:
kt_shadersinflates every LINKDATA entry and loose*.gz/*.spkgfile (01), takes every GLSLC output that passes the triple check, and scans its SARCs for BNSH;DATA1.binis split into 64 scan jobs by entry range (linkdata_jobs). - Symptom: 24 shaders before the control-length fix, 1,355 after.
- Cause: its GLSLC (output version 0x1d.2) writes the 0x848 / 0x850-byte controls and headerless compute code described in the RDB entry, which
glslc_shadersused to drop. A few outputs of version 0x1d.0 keep something else at control +0x20 (odd values such as 0x136b), so a control length must be a multiple of 4; the section-header reading now takes 8 of them (GLSLC outputs read through their section headers). - Index names: the archive and its index are
DATA1.bin+DATA0.bin(Three Houses),LD_<name>.BIN+LI_<name>.IDX(KTGL on NVN2) orLINKDATA.BIN+LINKDATA.IDX(DRAGON QUEST BUILDERS 2: 1.1 GB, 59,193 entries).linkdata_indexnames each. With a name it does not know, the archive is scanned as one plain file and nothing inside its compressed entries is found: the split reported 130 shaders against 2,107 with the index, and the host printedis not in the shader maponce the 3D scenes began. - Found on: Fire Emblem: Three Houses (the older KTGL), DRAGON QUEST BUILDERS 2.
KTGL on NVN2: Switch 2 GLSLC outputs and LD_ / LI_ LINKDATA
- Symptom: the split finds almost none of a KTGL Switch 2 game's shaders: the G2S containers in its RDB entries yield nothing, and its programs name no packaged shader.
- Cause: the Switch 2's GLSLC writes a longer output header (the output's length at +0x5c, the section count at +0x64, section headers from +0xa8, 0x98 apart; GPU code version 0xc9 at +0x30), its NVN2 control sections are too short for the Switch 1 rule, and the game keeps more outputs in a LINKDATA pair named
LD_<name>.BIN/LI_<name>.IDX, whose larger entries use zlib chunks above 0x10000 bytes. - Fix:
glslc_layoutreads either header,linkdata_indexnames the index of either pair, andkt_gztakes any power of two from 0x10000 as its chunk size (shader_split.py). - Found on: Pokémon Pokopia: 131,426 shaders on update v655360.
- Note: nine more shaders exist only at run time (Built-in shaders compiled with the game's own GLSLC).
GLSLC outputs in base64 in Heaps' shader cache
- Symptom: the NSP script stops at
the shader split found no shaders in main or the RomFSon a game whosemainimportsglslcCompileand whose RomFS is one or two.pakfiles. - Cause: Heaps keeps its files in a PAK archive (
PAK, a version byte, i32 header size, i32 data size; version 1 adds a 64-character hash; then a tree of named entries,DATA, and the file data, which starts at the header size). Itshxsl.CacheFilefor the Switch,shaders.cache.nx, holds a table of programs (!<signature>\t<vertex hash>\t<pixel hash>), then each stage's GLSL; the GLSL of each program's pixel stage ends with the program's GLSLC output in base64,//BIN=<base64>#. The output's magic is hidden by the base64, and GLSL strings are not inmain, so neither the loose-file scan nor the GLSLC capture rule sees it. - Fix:
shader_split.pylists a file that starts withPAKby its own header (heaps_pak_files; a file that does not parse as one, ending inDATA, goes on to the other readers), reads only itsshaders.cache.nx, and decodes each comment (heaps_shaders). Each output holds both stages, so they pair with each other (GLSLC outputs holding several stages). - Found on: Dead Cells:
res1.pak, 1,222 outputs, 1,262 unique shaders and 1,222 pairs.
Gzip-wrapped shader archives
- Symptom: only movies render, while the 3D scene reports missing shaders and programs without a vertex stage; the shader split finds loose programs but misses those in
Shaders/Shaders.arc.gz. - Cause: the archive is standard gzip around a Wii U8 archive containing GLSLC outputs. Its shader signatures are hidden by compression, so the loose-file scan discards it before the existing GLSLC reader can discover its programs.
- Fix:
shader_split.pyrecognizes gzip by its magic, regardless of the filename, and decodes it before the shader scan.ungzipvalidates the stream's CRC and end, including concatenated members, and bounds the total decoded bytes to the greater of 1 GiB andNESTtimes the compressed size. Deflate reaches about 1000x on repetitive data, and an unreadable file stops a registered game's build, so the floor lets a small, highly compressible file without shaders through and still caps a gzip bomb. A damaged or oversized source is named as unreadable and contributes no partial shader output. The existing reader retains each program's vertex/pixel pairing; Gust's differently encoded.gzfiles keep their own reader below. - Found on: The Legend of Zelda: Skyward Sword HD 1.0.1, issue #497, reported with a source-only patch by zatteogit. Measured on that build's own file: 4.9 MB of gzip decode to a 22.8 MB U8 archive with 2,096 GLSLC programs in
cache/(one a byte-identical copy of another) and 2,096 fixed 632-byte records indesccache/that hold no shaders. The split takes 2,412 unique shaders (384 vertex, 2,028 pixel) and 2,095 pairs from it, and 2,470 shaders for the whole game withmain. The game now boots and plays with them: its note. - Check:
test_split_gzip.pyuses an authored U8/GLSLC fixture: raw and gzip inputs produce byte-identical package/table files through the full CLI, with two shader stages and one pair. It also covers magic-based discovery, timestamp bytes resembling other compression headers, concatenated members, corrupt CRCs, truncated footers, trailing garbage and the decoded-byte budget.
Encrypted .vert and .frag files are no run-time GLSL
- Symptom: the NSP script stops at its GLSLC capture with
captured only 0 run-time shaders, after the game ran the whole capture normally, on a game whosemainimportsglslcCompile, with a.vertor.fragfile in its RomFS. - Cause:
build_sourcescounted such files by their extension as GLSL the game compiles itself (Turrican Anthology Vol. I), soshader_sourcesasked for a capture. Skyward Sword HD'sShaders/Dummy.vertandDummy.fragare AES-256-CTR ciphertext (7.99 bits per byte). Itsmaindecrypts them on first need (main+0x1053bac) and hashes the sources into a name inShaders/cache/; it callsglslcCompile(main+0x1053a38) only when the archive lacks that program, which every shipped program avoids, so nothing is compiled and nothing can be captured. - Fix:
romfs_glsl_filescounts a.vertor.fragfile only when its first 4 KiB are text (glsl_text: not empty, no control byte). The capture's own failure stays strict for a game that does capture. A game that compiles encrypted sources for shaders it does not ship would get no capture and showis not in the shader mapwhen it draws them; none has been met. - Found on: The Legend of Zelda: Skyward Sword HD, reported in GitHub issue #928.
Gust's chunked zlib .gz files
- Symptom: every frame black, the title screen included, while the game runs at full rate and draws (about 19,000 NVN calls a frame), with
[RED] shader … is not in the shader map(26 keys in the first minute) andprogram has no vertex shader; the dumped shaders (DM_NVN_SHDUMP) match no file byte for byte, and some differ from a split shader only in the control section's compile information (+0x7d0), which is a sign of another GLSLC compile of the same source, not of a shared section. - Cause: Gust's
*.elixir.gzfiles come in two forms: most areCRAEarchives stored as they are, which the split reads like any loose file, and the rest are chunked zlib, each chunk a u32 stored length and one zlib stream (16 KB inflated, the last shorter), ended by a zero length. The post effects' archiveData/NX/PostEffect/pe_pack.elixir.gzis one of them, with 162 GLSLC outputs (128 keys found nowhere else, among them the frame composite and the copy passes), which a raw scan cannot see. - Fix:
shader_split.pyinflates a.gzfile in that form (gust_gz: every chunk must be one whole zlib stream and the zero length must end the file, so another format is left alone) and scans it as a loose file. Atelier Ryza DX: 921 → 1,049 shaders, every key of the opening, title, story and field runs. - Found on: Atelier Ryza: Ever Darkness & the Secret Hideout DX (Gust's engine on KTGL): 156 of its 4,112
.gzfiles are chunked zlib.
GLSLC outputs in FromSoftware's BND3 and dvdbnd archives
- How it is stored: RomFS is two archives,
dvdbnd0.bdtanddvdbnd1.bdt(3.6 GB), each indexed by the.bhd5beside it:BHD5, 0xff (little-endian), u32 1, u32 file size, u32 bucket count, u32 0, u64 bucket table offset; each 16-byte bucket{u32 count, u32, u64 offset}points at 16-byte entries{u32 path hash, u32 size, u64 offset}(paths only hashed). 5,184 entries are DCX containers (DCX\0, big-endian header,DFLT= a zlib stream at +0x4c), most of them BND3 archives (28-byte entries{u8 flags, i32 size, u64 offset, i32 ID, u32 name offset, i32 unpacked size}in formats 0x5c / 0x7c). Six BND3 archives indvdbnd0.bdthold the shaders, one GLSLC output per entry (.vpovertex,.fpopixel, namedShader/FRPG_Sfx/NVNShaderBinary/ps/…or by base name in the two FLVER material archives, 2,602 + 486 entries). - Reader:
bhd5_entries,undcx,bnd3_members,bdt_shadersinshader_split.py, in 64 jobs by entry range, about 10 s. Only archives that contain a GLSLC magic are parsed (the others use format 0x78). - Note: SDK 4's GLSLC needs its section headers read (GLSLC outputs read through their section headers).
- Found on: DARK SOULS: REMASTERED.
MSHD in MercurySteam's bshdat files
- How it is stored:
system/shd/*.bshdat, the only place the game's shaders live (nothing inmainor the.pkgpacks). Each stage is a control section, whose length is at control +0x20, sometimes followed by a small compiler-option table (fastmath true), then the code area at the next code header. Every file holds vertex / pixel stages in alternating order (1, 2 or 4 programs) and is paired two by two. - The control section carries NV assembly text after its first 0x880 bytes, and the SASS disassembly follows each code area, so the binding layout can be read straight from the files (
TEX/TEXShandle immediates). - Reader:
mshd_shaders. - Found on: Metroid Dread (MercurySteam's engine): 478 files, 1,342 stages, 1,010 unique keys (359 vertex, 651 pixel), 659 pairs.
SDF definitions in RE Engine PAKs
- How it is stored: shader definitions (
SDF\0, 2,685 files in the PAK view, 01): u16 version 1, u16 entry count, u64, then 0x108-byte entries from +0x10. Entry +0x10 holds six u64 offsets (vertex, hull, domain, geometry, pixel, compute; 0 = none), each to{u32 control length, u32 code length}followed by the control section (0x880 bytes) and the code area; compute code has no header. An entry's stages are one program, so its vertex / pixel stages are a pair. Empty definitions are 16 bytes of version 0. - PRAGMATA's form (KPKA 4.2, Switch 2): the PAK header's feature bit 0x20 adds a block table after the entries (u32 block length 0x80000, u32 count, a u64 per block: offset in bits 0–41, stored length from bit 42; a block whose stored length is the block length is stored, any other is one zstd frame of a padded block). An entry with attribute 0x1000000 starts at a block index, not an offset, and its data runs on through the following blocks. The SDF files hold two u64s, then 0x110-byte entries from +0x18 (entry +0: the offset of its name); each stage record is a 0x58-byte header (a u64 hash, the two lengths at +8), then the NVN2 control section and the code area. Mesh shaders sit in the hull slot (1,407 of them).
- Resident Evil 4's form (KPKA 4.2, Switch 2): PRAGMATA's entries, but each stage record's header is 0x60 bytes (the two lengths still at +8), so the control section is at +0x60: every one of its 20,311 records (in the 23 of its 821 SDF files that hold entries). Without the third layout no file fit and the split stopped with
the SDF entries fit 0 of the 2 known layoutsandthe shader split found no shaders. Its one OCIO file has the same 0x60-byte headers, packed to 1 byte (control sections at0x3712f3,0x37173b, ...). - OCIO files: RE Engine's OpenColorIO colour pipelines (
OCIO) hold the shaders of the frame's tonemap and display transform as the same stage records, among tables of their own. The control sections there have other hashes at +0x10 and +0x20 than the SDF copies of the same code, so their keys are different shaders. Without them, PRAGMATA's last composite before the window had no shaders and its draw was skipped: the picture came out cyan-saturated, every subtitle drawn over the ones before. The larger OCIO files (3.9 MB,8ae6c7ee83bc0563and three more) pack their records to 4 bytes, not 8: a reader that took only 8-byte aligned control sections read 2 of their 65, and left out the compute shaders that bake the colour pipeline's tables (2ceb3ec288321a37, dispatched every frame:[RED] the dispatched program has no compute shader). - Reader:
kpka_jobsmaps the PAKs, takes the newest copy of each path, peeks at 4 decompressed bytes and inflates only SDF and OCIO entries (kpka_datajoins block-table entries;sdf_shaderstakes the SDF layout the file's offsets fit, of three;ocio_shaderstakes each NVN2 control section, at any offset, whose record header (0x58 or 0x60 bytes) names its length and whose +0x44 names the code area after it). - Found on: Monster Hunter Rise: 63,111 shaders (30,233 vertex, 21,475 pixel, 11,271 compute, 53 geometry, 33 hull, 46 domain) and 102,345 pairs, in 5 s with 12 jobs. PRAGMATA: 759 SDF files, 36,465 shaders, and OCIO files. Resident Evil 4: 23 SDF files with entries, 20,311 stage records, and one OCIO file.
- Check:
python3 dm/gfx/tests/test_kpka.py.
Shader records in Snowdrop SDF data slices
- Symptom: the split finds no shaders in a RomFS made of
.sdfdata,.sdftocand.sdfverfiles. - Cause: Snowdrop stores the shaders in individually compressed records inside its
BERGdata slices. A cache record can itself be wrapped in an SDF zstd chunk. These SDF archives are a different format from RE Engine's shader definitions above. A shader record has a 20-byte header{u32 codec, flags, 0, raw length, stored length}:0xabcd00c5precedes zlib data,0xabcd00c6a zstd frame; reflection data precedes the NVN sections inside it. Both supplied games use SDF version 22, so that version does not select the codec. - Fix:
shader_split.pyrecognizesBERGby magic and reads the length-delimited compressed records (snowdrop_shaders). Every control section is followed immediately by its code, with lengths from control +0x20 and +0x704; they are byte-packed, so a control need not be aligned. A single record can hold more than one shader. Each section must pass the control / code / stage checks. Programs hold one stage, and the vertex shaders take the single-stage cover. The reader also peeks at each zstd frame's decoded header and finishes only frames beginning with a cache record. This finds nested records without treating a coincidental frame magic or a bare frame containing control-like bytes as a shader asset. - DLC: additional shader records ship in the DLC's data slices. The NSP script includes each extracted DLC RomFS as an extra shader root, without an ExeFS module, and fingerprints its index and extraction timestamps for split reuse. Vulkan and OpenGL builds include the DLC roots too. When installing or removing optional DLC changes an NVN shader union, the script uses an external profile with new shader tables only after every non-DLC shader row and fact matches the registered tables; package indices may change. The registered module builds, settings and build-gated cuts are preserved. A cached proof of this comparison permits repeat builds to reuse the split.
- Bare zlib cache files: an older SDF layout stores each shader cache file (
*.mcache) as a bare zlib stream, without the 20-byte record header, at the offset its table of contents gives; a file over 64 KB is a run of 64 KB streams. Its decoded head is a0xabcd00d4record{magic, kind, 0, length, length}(the length counts what follows the 20 bytes), and the shader sections inside have the same layout.snowdrop_zlibfinds each stream by its zlib header and a peek at the decoded head, decodes the 64 KB streams one after another up to that length, and skips bytes inside a decoded record. - Found on: Mario + Rabbids Sparks of Hope (zstd); Mario + Rabbids Kingdom Battle (zlib records, some wrapped in zstd chunks; shorter control sections and headerless compute code); South Park: The Fractured But Whole (bare zlib cache files).
CompiledBytecode resources in Frostbite superbundles
- Symptom: the survey finds no shader container in a RomFS of
.tocand.casfiles (Data/NX,Patch/NX,Data/layout.toc,Data/initfs_NX); the split reads every file loosely and finds nothing. - Cause: Frostbite keeps its data in bundles that superbundle tables (
.toc, magic00 D1 CE 01) list, the bundles' manifests and items in the install chunks' cas files, each item in blocks of at most 256 KB compressed with Oodle Leviathan (8C 0C). A toc entry gives each item's cas file by an 8-byte cas id (Data or Patch, the install chunk'spersistentIndexfromlayout.toc, the cas number), its offset and stored size; items of one bundle need not lie together. The NVN shaders are the bundles'CompiledBytecoderesources (shaders/bytecode/<GUID>, res type0x0e2b02f7, the type name's hash): a 0x20-byte header, then aVNVNrecord (fb::NvnCustomShaderDataof the renderer NRO) with one control section and code area at offsets its trailer gives.ShaderBlockDepotresources hold parameter blocks only. - Fix:
dm/gfx/tools/frostbite.pyreadslayout.toc's install chunks (a DbObject), every toc's bundle entries, the manifests and the blocks;shader_split.py(frostbite_jobs,frostbite_shaders) decodes eachCompiledBytecoderesource with the game's own Oodle in the Mac host's tool mode, as for Trinity packs, and leaves the.tocand.casfiles out of the loose scan.profile_guess.pyturns the Oodle decoder on for a RomFS withData/layout.toc. Data and Patch are read alike: keys are content hashes, so a base copy the update replaced only adds an unused shader. The resources name no vertex / pixel pairs (Frostbite pairs them in its pipeline data), so the tables have none. - Found on: EA SPORTS FC 27 (Frostbite 2025.1.2): 83,325 bundles, 10,401 resources, 10,342 shaders (3,738 vertex, 3,306 pixel, 3,298 compute), 35 MB stored; the split takes about 6 s.
Control sections and code areas in Scimitar / Anvil forge archives
- Symptom:
[RED] ... forge version 31, only version 28 ... is knownorthe shader split found no shaders in main or the RomFSon a RomFS of.forgefiles (scimitar\0at +0, e.g.AC2/DataNX*.forge); ormain's unaligned control sections are left out and title screen / menus draw nothing. - Cause: Ubisoft's Scimitar / Anvil engine stores its assets in
.forgearchives (scimitar\0, u32 version, 64-bit data header offset) with compressed block containers (33 AA FB 57 99 FA 04 10) holding Oodle chunks (stored as-is when raw and stored sizes match):- Version 28 (Immortals Fenyx Rising): data header +0x24 points at chained index headers of 20-byte rows
{u64 offset, u64 file ID, u32 size}; each entry is sequential v0 containers (u32 chunk sizes), whose decoded resources (and the looseShaderDataNVN.bin) holdGPUCODEONLY\0shader records (code area, then control section). - Versions 25 and 31 (Assassin's Creed: The Ezio Collection): data header +0x20 points at chained tables of 16-byte index rows
{i64 offset, u32 id, u32 size}(excluding each entry's 0x1b8-byteFILEDATAheader) and 0xbc-byte name records (NUL-terminated name at +0x2c); entries hold v1 blocks (u16 chunk sizes; block type 6 Leviathan in v31 AC II, type 4 Mermaid in v25 Brotherhood). Decoded material templates contain NVN control sections (0x880 bytes) each followed directly by its code area. In addition,mainholds 232 unreferenced control+code pairs packed byte by byte (164 starting off a 4-byte boundary, 8 headerless compute).
- Version 28 (Immortals Fenyx Rising): data header +0x24 points at chained index headers of 20-byte rows
- Fix:
dm/gfx/tools/forge.pyreads.forgeheaders, validates known versions (25, 28, 31) and bounds, and decodes v28 containers and v25/v31 blocks through the game's ownOodleLZ_Decompressin the Mac host's tool mode (dm/host/hle_oodle.c, enabled byprofile_guess.py'sanvil_forgescheck).shader_split.py(forge_jobs,forge_shaders) handles all known.forgeversions in one pass, reports unknown-version or damaged forges through the unreadable-file path without falling through to the loose scan, labels v25/v31 shaders#SCIMITAR:(listed inSINGLE_STAGEfor single-stage cover pairing without affecting v28's#GPUCODEONLY@records), and letsraw_shadersadmit unaligned control sections throughadjacent_shaderwith a moving lower bound so back-to-back packed shaders do not collide.test_forge.py,test_anvil_forge.pyandtest_split_adjacent.pycover v25/v28/v31 tables, stored and decoded chunks, unknown-version rejection, single-stage covers and unalignedraw_shaders. - Found on: Immortals Fenyx Rising (
010010A00B228000, v28, no profile yet); Assassin's Creed: The Ezio Collection 1.3 (0100670014482000, no profile yet): AC II's 27 v31 forges hold 20,417 distinct shaders (1,514 vertex, 18,903 pixel) besidemain's 232, and Brotherhood's 29 v25 forges (ACB/) hold 26,123 distinct shaders.
SPK shader package in an MT Framework ARC
- How it is stored: The Great Ace Attorney Chronicles keeps its one shader package,
sc\NX_64\root(SPK\0, type hash0x02358e1a) innativeNXx64/sa/NX_64/root.arc(01). After the package's tables every shader is a code area followed directly by its control section, back to back to the end of the file: 230 vertex shaders, then 230 pixel shaders. - Reader: ARC v7 directory entries use 128-byte paths in Ace Attorney and 64-byte paths in ULTRA STREET FIGHTER II.
mtarc_memberschecks each member's offset and stored length against the directory and file bounds. USF II also stores each SPK control section before its code. The first control's code length (+0x704) locates the adjacent graphics header;mtspk_shadersfollows that order through the entire package, checking every boundary. The tables that say which vertex and pixel shaders the engine combines are not read: the vertex shaders are paired with the single-stage cover (one pixel shader reads every input any of them reads). - Note: in Ace Attorney,
CustomShaderPackage.mfx(MFX\0, the effect descriptions) holds no shader code, and neithermainnor any other ARC entry does. - ARC version 9 and headed SPK records (Resident Evil HD Remaster, Ultra Street Fighter II): a version 9 directory entry is 0x54 bytes: a 64-byte path, the type hash, the stored length, the length, a u32 (2 in every entry) and the offset; the first member starts at 0x8000, and every member is a zlib stream, even when the stream is longer than or equal to the data.
mtarc_membersenforces directory and archive bounds on both v7 and v9 and bounds zlib inflation to each entry's declared length. Headed SPK packages (Resident Evil'ssc\NX_64\root,Title,Game, and Ultra Street Fighter II's 6 packages) are not back to back: each shader record is binding data of its own length, a 0x20-byte header {the package hash (SPK +4), control + code length, two u32, 0, control length, code length, control length}, the control section, then the code area.mtspk_headed_shaderstakes a control section only with a non-overlapping header in front of it, and every control magic in the package must belong to one. - Found on: The Great Ace Attorney Chronicles (Capcom's MT Framework): all 460 build, with Mario's binding layout; every binding decodes. Resident Evil (HD Remaster): 19,104 shaders, all build.
PKZ version 1 archives
- Symptom:
[RED] ... PKZ version 0x10000: only 0x20000 is knownstops the shader split. - Cause: the PKZ reader accepted only the version first found on Bayonetta 3. Version
0x10000uses the same 0x20-byte header, 0x20-byte entries and relative name offsets; the last header word is zero rather than a v2 alignment. The named compression method still determines how each entry is decoded. - Fix:
shader_split.pyaccepts both0x10000and0x20000, retaining rejection of unknown versions. The existing Zstandard decoder and DAT/shader scanners handle the contents. Synthetic directory fixtures cover both versions indm/gfx/tests/test_pkz.py. - Found on: ASTRAL CHAIN.
PlatinumGames' shader objects
- PlatinumGames' shader objects:
VSO\0/PSO\0/CSO\0/HSO\0/DSO\0(the stage), u32 compiler version, u32 control length, u32 control offset (0x18), u32 code length, u32 code offset, and nothing else. The engine makes a program of each and binds them per stage at draw time, so they are single-stage programs, paired with a cover pixel shader (shader_split.pypg_shader; the archives: 01). It finds its built-in ones by name (hwfillcolor.vso, …) and checks each object's GPU code version against the driver's (the NVN layer reports the translator's supported GPU-code range: Newest GPU code version reported by the driver, SDK 13.3.2). - Found on: Bayonetta 3: 8,024 objects in
root_000.pkz(shader.dat,shader2.dat,shadereff*.dat,autoshadereff.dat); 6,424 distinct keys (4,288 pixel, 2,047 vertex, 78 compute, 6 domain, 5 hull).
Size-delimited PlatinumGames shader objects
- Symptom: the split finds zero shaders and refuses the shader build, although the CPK's DAT archives contain the objects passed to NVN at boot.
- Cause: another PlatinumGames wrapper stores a binding table before the code and control sections, rather than the stage-tagged object above or a BNSH file: u32 prefix length (including that word), binding bytes, u32 code length, code, u32 control length, control. The observed prefix is
0x88bytes and the control section0x880bytes. - Fix:
shader_split.pypg_sized_shaderrecognizes the self-described section boundaries and NVN magics (0x12345678for graphics code,0x12345679for compute,0x98761234for control). The prefix must be aligned and in bounds, both sections must fit, the record must end with its control section, and the control's code length at+0x704must agree. Graphics stages come from SPH; the compute magic identifies compute. The reader emits#PGSOrecords so the existing single-stage cover pairing applies. Recognition needs no title or filename rule, and the shader translation chain is unchanged. - Found on: NieR:Automata The End of YoRHa Edition: the objects in five DAT shader archives inside
data000.cpk; the game note records the census and the runtime-key checks.
BNSH files in PlatinumGames DAT archives inside CRI CPK archives
- PlatinumGames' engine in its Wii U form keeps its shaders as BNSH files of one stage each, the
.vso/.psomembers of PlatinumGames DAT archives (shader.dat,shader2.dat,shadereff.dat) inside a CRI CPK archive, all CRILAYLA-compressed (01 has the CPK layout).dm/gfx/tools/cpk.pyreads the @UTF tables (and the masked ones of Unicorn Overlord's CPKs, the same tables as before once unmasked), the TOC and CRILAYLA (a decoder over a bit string, about 29 MB/s);shader_split.pycpk_jobssplits the CPKs into jobs and scans each entry (a CPK it cannot read is scanned as one file, with a[RED]line). - Each file is one variation with one stage, so the split pairs nothing; as in Hades II, the vertex shaders write every output their pixel shaders read and no pipeline failed to link.
- Found on: Bayonetta 2: 1,856 distinct keys (1,547 pixel, 309 vertex) in
shader.dat,shader2.datandshadereff.datofdata000.cpk(the split about 2.5 minutes); Bayonetta: 458 distinct keys (236 pixel, 222 vertex), the members ofshader.datindata00.cpk(about 1.7 minutes). All build for both. - Not checked: 13 Sentinels and Catherine: Full Body's CPKs (no files on the drives).
CRI CPK archives with the table of contents at the end
- Symptom:
[RED] the shader split found no shaders in main or the RomFSon a game whose RomFS is CRI CPK archives, with many[RED] /<archive>.cpk/<file>: not CRILAYLA; not scannedlines; entries the TOC lists as stored start with another file's bytes (CRILAYLA,DXBC, path or name text). - Cause: a file's FileOffset counts from the smaller of ContentOffset and TocOffset, with TocOffset counted as at most 0x800 (CRI's rule, as CriPakTools reads it).
cpk.pytookmin(TocOffset, ContentOffset), which is the same when the TOC follows the header (TocOffset 0x800) but is ContentOffset when the TOC is at the end of the file, so every file was read that far past its start: compressed entries no longer began withCRILAYLAand stored ones were the middles of their neighbours. - Fix:
cpk.filescaps TocOffset at 0x800 before taking the smaller of the two. - Found on: LUNAR Remastered Collection (0100DCD01E9EE000, a launcher and two game programs):
data.cpk(ContentOffset 0x16000, TocOffset 0x42b06800) was read 0x15800 bytes too far in andmovie.cpk0x1000; with the fix program 1's split takes 18 shaders and program 2's 20, from the.bnshfiles undersysbin/nx/shader/. - Check:
dm/tools/tests/test_cpk_offsets.py: a synthetic CPK with its TOC after the header and one with its TOC at the end give each file its own bytes.
Monolith ARH1, XBC1 and HCPS/SLCT shader containers
- Symptom: archive or loose asset shaders are absent from the map; only boot shaders in
mainare found, sometimes reported as raw controls with no identified code area. Mixed-architecture assets reportHCPS: truncated controland leave out their Maxwell shaders too. - Cause: Monolith uses ARH1/ARH2 indexes, ARD archives and XBC1 streams. HCPS shader containers live inside models, map streams and standalone shader files; a standalone SLCT in
mainomits the HCPS header. - Fix:
shader_split.pyreconstructs paths from the ARH1 XOR trie, reads bounded archive entries in parallel, and decodes stored/zlib/zstd XBC1 streams recursively. The ARH stored size excludes an XBC1 wrapper's 48 bytes. Decoded members are searched for both HCPS and complete GLSLC outputs (effect asset packs); compressed literals are visited only after decoding. HCPS's SLCT/NVSD descriptors locate each variant's control and code ranges; a vertex bundle can include geometry, so stages are split by each control's own lengths. Text-bearing controls advance at eight-byte alignment. Standalone SLCT sections use offsets relative to their own start. Source-only HCPS containers with empty code/control ranges hold no NVN binaries. Pairs stay within their program variant. Synthetic fixtures cover wrapper bounds, embedded geometry, variants, standalone offsets and compressed streams containing literal container magics. - Nested effect compression: Firehawk WIPAC resources can wrap their
BlShaderArchiveGLSLC programs incmp\0zlib: an eight-byte signature, little-endian stored/raw u32 lengths, then zlib. This layer lives inside the decoded XBC1 entry. The recursive reader checks both lengths and the end of the stream; it excludes these compressed ranges from raw container scans too. The four initially missing geometry/pixel keys and two additional vertex/pixel keys from Xenoblade Chronicles 3's opening match/effect/fld/ma01a.wipacafter this decoding. Synthetic tests cover nested literal streams and incorrect sizes. - Loose containers: HCPS programs, XBC1 streams, DRSM model streams and compressed effect resources also occur outside ARH/ARD archives. Both the file scanner and nested-container scanner dispatch their headers to the same recursive decoder, before the generic shader-magic filter. Otherwise even a complete loose HCPS program is discarded. Synthetic file scans cover direct programs, compressed programs and several embedded streams, independent of filename suffix.
DMPAmodel packages (.wimdo) are among these headers: 18 of Xenoblade Chronicles: Definitive Edition's (/chr/obj/oj*.wimdo, the same files in the Switch 1 program and the Switch 2 Edition's add-on) keep uncompressed HCPS programs beside the model. BeforeDMPAwas dispatched, the Switch 2 Edition (0400FF500E34A001)'s prologue logged[RED] shader … is not in the shader mapfor 14 keys andprogram has no vertex shaderas New Game started; all 14 were inoj300001.wimdoandoj300021.wimdo, and the split found 465 more shaders with it (16,506 → 16,971). An archive member or XBC1 payload that is an NDSR pack (the upscaler's networks,/monolib/shader/ndsr.pck) goes to the NDSR reader (ndsr_shaders) frommonolith_shaders: Xenoblade Chronicles 2's Switch 2 Edition (0400E95004038001) keeps it as an XBC1 member ofbf2.ard, which only the HCPS and GLSLC scans saw, and its title screen drew no scene, with 9[RED] shader … is not in the shader mapkeys andthe dispatched program has no compute shader; the split finds 28 more shaders with it (22,533 → 22,561), the same 9 keys Xenoblade DE's Switch 2 Edition takes from its loose copy. - ARH2 and mixed shader architectures: an
arh2index holds hashed members, with offsets accumulated from aligned disk sizes (including XBC1 wrappers), rather than ARH1's path trie and explicit offsets. The reader validates the index, alignment and every member's ARD bounds, then uses the same recursive shader decoder. One asset can contain both Maxwell and NVN2 HCPS programs: each control's version chooses its own length fields and stage decoder. Assuming Maxwell controls makes the shorter NVN2 sections reportHCPS: truncated controland discards the archive job's Maxwell shaders too. Synthetic tests cover aligned members, wrappers with no expanded-size hint, invalid bounds, and an asset containing both architectures. Found on Xenoblade Chronicles X: Definitive Edition; format checked against XbxDeTool's ARH2 reader and the supplied archive. - Found on: Xenoblade Chronicles 3, whose note records the census and runtime key checks; Xenoblade Chronicles 2, with the same archive and standalone SLCT layouts on SDK 3.5.0; Xenoblade Chronicles: Definitive Edition, with loose containers.
- Format references: ARH1 layout, xc3_lib shader structures. The reader's lengths and keys were checked against the supplied game files.
Needle shader containers in main and GFD archives
- Symptom: the split finds no shaders, although
maincontains NVN control sections; it reports that no data record or code-address pair identifies their code areas. - Cause: Needle keeps independent shader programs in
HNSHV002containers, embedded inmainand in GFD's GSC files inside CRI CPK archives. These are neither GLSLC outputs nor BNSH files. A container can hold many variants separated by reflection metadata. - Fix:
shader_split.pyneedle_shadersuses the container's big-endian whole length at +8, then the little-endian NVN section descriptors: 0x90 bytes immediately before each control section, with control offset, code offset, code length and control length at +0x30. Both regions must fit within that container, and the control/code headers and lengths must agree. Graphics stages come from SPH; headerless compute stages from the control's thread-group dimensions. Each program is paired with the single-stage cover, since its draw-time partner is not recorded by this wrapper. Synthetic fixtures check embedded variants, compute, length mismatches and container boundaries. - Found on: Persona 5 Royal, with 0x850-byte control sections. The game note records counts and runtime coverage.
Needle containers with NVN2 records
- Symptom:
[RED] main NEEDLE @<addr>: invalid control offset or control length at <addr>, and the split stops onmain. - Cause: a Switch 2 game's Needle records hold NVN2 control sections (version 0xc9 at +4, their own length 0xd8 at +0x30). The descriptor has the same fields at +0x30 (control offset, code offset, code length, control length), but it is 0x98 bytes long, not 0x90, and the code follows the control section. The reader took every record for the NVN layout.
- Fix:
needle_shaderstells a record's kind by its control section (nvn2_ctl) and takes that kind's layout (NEEDLE_RECORD): an NVN2 one has a 0x98-byte descriptor, a control section of at least 0x48 bytes and its own length at +0x30; an NVN one is read as before. A container too small for the kind of record it holds is still not one, so a container of one NVN2 record is read. - Found on: Sonic Frontiers Definitive Edition
main: 1,586 records in 233 containers, every one with this layout, the code right after the control section and its length equal to the control's +0x44. - Check:
test_needle.py: NVN2 records of the three stages, a container of one record, and a control length that disagrees with the descriptor; the NVN fixtures pass unchanged.
Shaders in Hedgehog Engine 2's PACx 403 archives
- Symptom:
[RED] 1 file(s) could not be read, their shaders are left out (first: /raw/NeedleShader.pac NEEDLE @<addr>: incomplete NVN section at <addr>)oncemainis read; without that file's shaders a stage draws its geometry black, with[RED] shader <key> is not in the shader maplines. - Cause: a PACx 403 archive is LZ4 chunks. A Needle container's magic stood among the literals of the compressed bytes, and the split read the bytes after it as a container.
- Fix:
pacx4_partsreads the archive. The header's +0x10 / +0x14 / +0x18 are the root's offset, stored length and length, +0x20 the length of the dependency table at +0x30 and +0x24 that of the root's chunk table after it (a count, then stored length and length of each chunk; equal lengths mean a stored chunk). The root is a PACx 402 archive: +0x10 the length of its trees, +0x14 that of the block table after them, 0 when the root holds the resources itself. Each 0x20-byte block entry names its name, stored length, length, offset in the file and chunks, and the table's length must equal 0x10 + 0x20 per block + 8 per chunk. A block, decompressed, is a PACx 402 archive with its resources as they are, andscan_blobfinds its Needle containers; the root is scanned too. Only an archive whose root names a shader type is decompressed.scan_blobcharges the decoded bytes to its nesting budget, and the split's pre-filter lets PACx 403 archives through. - Found on: Sonic Frontiers Definitive Edition:
raw/NeedleShader.pac(24 MB, two blocks of 30 MB, 3,626 Needle records). The game's other 1,434 archives (1,068 with a dependency table, 688 without blocks) name no shader type; decompressed whole, all 1,435 give 15.6 GB, and none butNeedleShader.pacholds a Needle container or a control section. - Check:
test_needle.pycovers multichunk blocks with and without a dependency table, resources in the root, and a root without a shader type. A nightly fuzz run found a root chunk count that fit the declared table length even though the last entry ran past the end of the file. The reader checks the table entries against the file length before unpacking them. Tests also cover truncated outer and root headers and a truncated chunk payload.
Shaders in a zlib stream in main (YEBIS .tfxo)
- Symptom: shaders the game draws are missing from the map (
DM_NVN_SHDUMP), in no RomFS file and no module, stored or LZ4, and not compiled at run time. - Cause: Silicon Studio's YEBIS post-effect library (bloom, glare, depth of field, vignette;
C:/workspace/YEBIS_draft/src/GPU/…inmain) keeps its shaders in a zlib stream inmain: YEBIS's.tfxo file, a text header (the shader count,hlsl,TexUtil_NVN_NX, the technique list) and the shaders, each a control section (its own length 0x850 on SDK 7) directly followed by its code area. - Fix:
shader_split.pyinflates it and reads the shaders as single-stage programs (tfxo_streams,tfxo_shaders). - Found on: Pokémon Sword: after the GFPAK reader, 38 shaders the opening drew were still missing; none was a patched copy of a split shader (the nearest ones of the same length differ in hundreds of bytes).
mainimportsglslcCompilefromsubsdk1but never calls it and holds no GLSL source. The only zlib stream inmainthat inflates (main+0x1c98ed9, 39.5 MB) holds 3,155 shaders (3,015 distinct, 3,112 pixel and 43 vertex); they covered all 38. - Check: a temporary trace in
nvnProgramSetShaders(the key's code and control addresses, a backtrace and the heap around them) showed control sections packed back to back with technique names such asps_BrightPassT1_THRESHOLD_LUMINANCE_S1beside them; the names are inmain, and so is the data.
Loose control sections and code areas in main (Bink 2)
- Symptom: two
[RED] shader … is not in the shader maplines andprogram has no vertex shaderas the opening movie starts; every movie drew white. - Cause: the movie player (Bink 2's Unity plugin) builds its programs from 32 control sections and code areas in
main's read-only segment that are in no GLSLC output and no BNSH file. 26 are 0x20-byte records in two tables in.data({code area pointer, control section pointer, u32 code length, u32 control length}, both pointers relative relocations); the code takes the other 6 by address (adrp+addto the control section and, a few instructions away, to the code area it copies withmemcpy), the code area right after the control section's own length (+0x20, 16-byte aligned) or right before it, and two control sections share one code area. The 8 compute shaders' code areas have no header (SDK 10). - Fix: the reader (
raw_shaders) takes them. Both neighbours can pass the header and length checks, so it takes only a code area the code builds the address of, the nearest one to the control section's. - Found on: Advance Wars 1+2: Re-Boot Camp (Unity 2020.2 with Bink 2's Unity plugin). Of 25
mains on hand no other has such control sections.
SNVN program records in Retro Studios' RFRM forms
- Symptom: the provisional split finds only
main's 294 GLSLC outputs; the 3D scene and the title logo are magenta, with[RED] shader … is not in the shader maplines; or the NSP script stops at the shader split withADIR of 13 entries in 0x30c bytes, neither 36 nor 52 bytes eachfor every pack andthe shader split found no shaders in main or the RomFS(Metroid Prime 4: Beyond); or[RED] the split shader tables differ from game profile 0100C1F0051B6000'son supported Tropical Freeze 1.0.2 after the reader began accepting previously skipped records. - How it is stored: Retro's files are RFRM forms (
RFRM, big-endian u64 data length, u64, then the form type and two u32 versions; chunks inside are a fourcc, u64 length, two u32 versions, then the data).MaterialArchive.arcis oneMTRLform holding anSDXchunk (the same materials' D3D bytecode, 3,468 DXBC programs) and anSNVNchunk (the NVN ones). The.pakfiles arePACKforms whoseADIRchunk lists the resources (u32 count, then 36-byte entries: fourcc type, 16-byte GUID, big-endian u64 offset and length); eachMTRLresource is an RFRM form whose data is one zlib stream holding anotherMTRLform with anSNVNchunk. An SNVN program record is a big-endian u32 code length, u32 control length, a byte, u32 stream length, then a zlib stream that inflates to the program's code areas back to back followed by their control sections in the same order (0x840 or 0x848 bytes each on SDK 4). The chunk's tables differ between files, so the reader finds the records by their own lengths: a stream whose header ends where it says and that inflates to exactly code + control bytes. - Startup archive in
main: the first programs the game builds (theCGraphicsUtilCachequads that draw the title logo) come from a startup material archive compressed intomain(NMaterialStartup::get_startup_archive_compressed_buffer, 5,870 bytes;NMaterialArchive::ImportStartupArchiveinflates it at boot). ItsCBufferedCompressionheader is a type byte (1: LZSS on 8-bit units,CLZSSDecompressor::DecompressBuffer8) and three zero bytes; the data inflates to anMTRLform likeMaterialArchive.arc's. Its programs share code areas withMaterialArchive.arc's but differ in control +0x7d0 (a per-program value), so their keys are their own. - Little-endian forms (Metroid Prime Remastered): the same forms with every length, count and record header little-endian (
rfrm_ordertells the order from the u64 length: the reading that is a length is the small one). A pack's first chunk is aTOCCform holding theADIRchunk, whose entries are 52 bytes: fourcc type, GUID, two u32 versions, u64 offset, u64 length and u64 stored length (shorter for a compressed resource; none of the 778MTRLresources is). AnMTRLresource's zlib stream inflates to anEXPTchunk and then theMTRLform. Control sections are SDK 12's 0x880 bytes, and four vertex stages ofMaterialArchive.arccarry 0xc0 bytes more than their own length (+0x20) says: GLSLC's extra data at +0x7e8 (offset 0x880) / +0x7ec (length) / +0x7f0 (16 entries of 12 bytes), which the reader steps over to reach the next stage's section. - zstd records and 60-byte entries (Metroid Prime 4: Beyond): the split stops with
ADIR of 13 entries in 0x30c bytes, neither 36 nor 52 bytes eachfor every pack and finds no shaders. TheADIRentries are 60 bytes, the 52 and a u64 0; a resource stored compressed (stored length shorter) has theCBufferedCompressionheader of the startup archive (none of theMTRLresources is). AnMTRLresource's data, and each program record's stream, is zstd where the older games have zlib: the record keeps its 13 bytes (code length, control length, a byte, stream length), the stream is the program's frame and then an empty one, and 44 bytes the lengths do not count follow it.MaterialArchive.arc'sSNVNchunk starts with a table of (offset, length) per record and a directory of the materials by name. Control sections are still 0x880 bytes, most with the 12-byte entries of +0x7e8 after them, and the next section starts on 16 bytes (0x890 after a stage with one entry), so the control length is only a multiple of 4. The archive has anNVN2chunk of the same layout besideSNVN, which the reader leaves. The packs reach 3.9 GB, so the reader maps them. - Records the reader skipped (found on Metroid Prime 4: Beyond, wrong since Tropical Freeze): the reader took a record only when its control length was a multiple of 0x40 and stepped from one control section straight to the next. A stage's 12-byte entries (+0x7e8) make the length 0x88c for one stage with one entry, and the next section starts on 16 bytes (0x890), so two stages give 0x1110 or 0x11d0. Such records were passed over silently, as if they were other data: 16 of the 583 programs of Metroid Prime Remastered's
MaterialArchive.arc(control lengths 0x1110, 0x11d0, 0x88c) and 28,479 of its 68,962 shaders in all, which its map lacked from its bring-up until this fix. SDK 4's two declared 0x848-byte sections also give a valid 0x1090-byte total without appended entries. The length test is a multiple of 4 now and the step rounds up to 16 bytes when no section follows directly; every key of the old maps is in the new ones. A supported profile's generated tables must be refreshed with the reader: otherwise the packing script correctly rejects their difference, as in Tropical Freeze's profile refresh. - Reader:
rfrm_shaders,snvn_records,retro_main_formsandretro_lzss8inshader_split.py; each record is one program, so its stages pair with each other. - Found on: Donkey Kong Country: Tropical Freeze (SDK 4.4.0): 24,258 shaders (11,724 vertex, 11,814 pixel, 720 geometry, which run as compute kernels): 3,460 first seen in
MaterialArchive.arc(its 3,468 stages), the rest in the 795MTRLresources of the packs, 8 in the startup archive and 294 GLSLC outputs inmain. - Also found on: Metroid Prime Remastered (SDK 12.3.1, little-endian): 68,962 shaders (34,472 vertex, 34,472 pixel, 12 geometry, 6 compute; 40,483 before the skipped records were read): 1,156 first seen in
MaterialArchive.arc, the rest in the 778MTRLresources of the world, preload and UI packs, and 8 in the startup archive (main+0x1d0e7a4, the sameCBufferedCompressiontype 1);mainholds no GLSLC output. Before the skipped-record fix, the byte-order-aware reader preserved Tropical Freeze's 80,212 stages from its 76 RFRM files. - Also found on: Metroid Prime 4: Beyond (SDK 19.3.15): 259,989 shaders (129,992 vertex, 129,972 pixel, 19 geometry, 6 compute) from
MaterialArchive.arc(3,473 stages in 1,740 programs) and theMTRLresources of 444 packs, none inmain; 2 minutes 19 s. Metroid Prime Remastered's split with the changed reader keeps every key it had and adds the skipped records' (above).
MGFX effects in MonoGame XNB files
- How it is stored: the 13 XNB files in
Content/Effects(XNB platformS, uncompressed, read byEffectReader) each hold one MGFX effect, andmainholds SpriteBatch's built-in one; no other file and no GLSLC output. A compressed XNB (MonoGame's LZX flag 0x80 or LZ4 flag 0x40, as in Stardew Valley) is decompressed first (xnb_decompress). Tribute Games' ParisEngine wraps XNB assets in raw DEFLATE as.zxnbfiles;zxnb_effectpeeks the first 0x200 decompressed bytes to skip non-effect assets (includingSoundEffectReader) and inflates only.EffectReaderstreams. - Layout: MGFX version 8 is MonoGame's own layout:
MGFX, u8 version, u8 profile, u32 effect key, the constant buffers, then each shader as u8 vertex (1) / pixel (0), u32 length, the bytecode (u32 control length, the control section, u32 code length, the code area: GLSLC's output without its header), the samplers, the constant buffer indices and an attribute list (as MonoGame's OpenGL backend writes it), then the parameters and the techniques with their passes (mgfx_effect). MGFX version 10 (MonoGame 3.8+) keeps the same header and per-shader layout, widens effect-level counts and indices (constant buffers, parameter bindings, shaders, parameters, annotations, techniques, passes and pass shader indices, with −1 for none) from u8 to i32, and appends a trailingMGFXsignature. - Reader: the reader parses every effect to its end, which checks the layout; in
main, four bytesMGFXcount only when version 5, 8 or 10 and a control section (or GLSLC output for v5) follow. - Pairing: a pass names its vertex and pixel shader by index, 255 for none (v5/v8) or −1 for none (v10), and 10 of Celeste's 13 effects have no vertex shader: SpriteBatch binds its own and the effect's pass only replaces the pixel shader. Vertex and pixel shaders therefore combine across effects, and they are paired as single-stage programs.
- Found on: Celeste (MonoGame for the Switch, its C# compiled to C++ by Sickhead's BRUTE): 26 shaders (20 pixel, 6 vertex), all with Mario's binding layout; every binding decodes. Stardew Valley (compressed XNB). Teenage Mutant Ninja Turtles: Shredder's Revenge (update 1.0.9): MGFX version 10 in 6 built-in effects in
mainand 13.zxnbeffects inContent/Shaders/.
MGFX version 5 effects (MonoGame 3.0)
- Symptom: the NSP script's split stops with
[RED] 24 file(s) could not be read, eachan XNB effect without an MGFX version 8 effect of NVN shaders. - Cause: MonoGame 3.0's EffectReader (
MonoGame.Framework, Version=3.0.0.0in the XNB) writes MGFX version 5:MGFX, u8 version, u8 profile and no effect key; constant buffers without names (i16 size, u8 count, {u8 parameter, u16 offset}); each shader's bytecode is a whole GLSLC output of one stage (magic 0x19866891, its +0x44 length equal to the shader's), not a control section and a code area; and the shaders are in MonoGame's DirectX layout: samplers without names and no attribute list. The parameters and techniques are version 8's. The length in front ofMGFXin the XNB runs about 0xff0 bytes past the effect, all zeros. - Fix:
mgfx_effectreads version 5 too, taking each shader throughglslc_shaders; an XNB effect may end in zeros. The 7.dx11.mgfxofiles inResources(MonoGame's stock effects) are version 5 as well: 5 hold GLSLC outputs and are read the same way,EnvironmentMapEffectandSkinnedEffecthold only DirectX bytecode and give no shader. - Found on: Bastion: 72 shaders, 24 pixel shaders in
Content/Effects(no vertex shader: SpriteBatch's own pairs with them) and 48 inResources.
Unity 2020.3 Shader objects in UnityFS bundles
- How it is stored: Unity 2020.3 keeps each shader's compiled programs in its
Shaderobject (class 48), in UnityFS bundles (StreamingAssets/aa) and in the player's own serialized files (data.unity3d,Resources/unity default resources). - Reader:
dm/gfx/tools/unityfs.pyreads them: UnityFS blocks (LZ4 / LZMA), the serialized file, the object through its type tree, thencompressedBlobper platform (LZ4 segments; each segment starts with a u32 count and 12-byte{offset, length, segment}entries). - Type trees: the player's files have no type trees; they borrow the bundles'
Shadertree with the same type hash (same Unity build, same layout). Type-tree strings with the high bit set index Unity's common string table, whichunityfs.common_stringsreads from the game's ownmain(AABB\0AnimationClip\0…). - Program code: on Switch every subprogram is one whole NVN program. Its code is a 0x60-byte header of four
i32 ×6arrays indexed by NVN stage (0 vertex, 1 fragment, 2 geometry, 3 tess control, 4 tess evaluation, 5 compute): an unused / scratch size, the block offset from +0x60 (−1 = no stage), the control size and the code size. Each block is the control section followed by the code area. The vertex and fragment stages of one program form a pair. - Found on: Fire Emblem Engage: 209
Shaderobjects in 188 bundles plus the engine files, 9,269 stage shaders (4,634 vertex / pixel pairs and one geometry shader), no compute shaders.
Unity compute kernels with no code
- Symptom:
[RED] 1 file(s) could not be read, their shaders are left out (first: Data/resources.assets: error: unpack_from requires a buffer of at least 96 bytes for unpacking 96 bytes at offset 0 (actual buffer size is 0))from the shader split, and the game's built-in shaders in that file missing at run time. - Cause: a
ComputeShaderkernel can have an emptycode, with no buffers and no constants, so nothing to translate.unity_computeread it as a program, and the exception cost the split every shader in the file, not only that kernel. - Fix:
unity_computeinshader_split.pyskips a kernel with no code and reads the rest (dm/gfx/tests/test_unity_compute.py). - Found on: DAVE THE DIVER (Unity 6000.0.52f1): 11 of the 142 kernels in
Data/resources.assets, such asParticleGrid'sBuildContactListandClothRendering'sUpdateClothMesh. The file holds 1,815 programs, of which 1,669 shaders occur nowhere else.
Legacy Unity stages lose their pass partners
- Symptom:
failed to create render pipelinewith a fragmentuser(locn1)input missing from the vertex output, while the split found all shaders but almost no vertex / pixel pairs. - Cause: before Unity 2019.3 each blob entry contains one stage. The vertex and pixel variants of a parsed pass have different blob indices, so pairing by the source's
#var<platform>.<index>connects none of them. Without its pixel partner, output padding does not know which unwritten vertex attributes the fragment shader reads. Return of the Obra Dinn'sOneBit/Ropehas vertex blob 0 with pixel blob 8 and vertex blob 28 with pixel blob 35; both fragment stages read generic locations 0–4. - Fix:
unity_pass_pairsinshader_split.pyreads the stages listed by each parsed pass, separately per platform, and pairs its vertex stages with a deterministic pixel-input cover in the supplementalpso_pairs.tsv. This covers every input used by the pass's pixel variants without depending on equal stage keyword lists or generating every combination. Existing evidence-pair tables, combined-stage Unity programs and source labels stay unchanged; profiles without a stored supplemental table take the generated one beside the shader package. - Found on: Return of the Obra Dinn (Unity 2017.4.28f1, 1.0.1): the two
OneBit/Ropepipeline failures reported in PR #427.
Unity 2022 Shader objects with parameter blobs
- How it is stored: the program code keeps the 0x60-byte stage header (Unity 2020.3 Shader objects in UnityFS bundles), but two things changed. From Unity 2022 the blob also holds each program's parameter tables as entries of their own (the parsed form's
m_ParameterBlobIndices; their bytes startPGlobals), and the player's programs are listed inm_PlayerSubPrograms[tier][].m_BlobIndex(m_SubProgramsis empty). - Reader:
unity_code_blobskeeps only those player programs. UnityPy's type trees for 2020.3 (Engage) and 2021.3 have neither field, so those read every entry as before. Subprogram version 202012090 (from Unity 2021.2) also has no local keyword list, sounityfs.subprogramreads no second keyword array (with one it read the code length as a keyword count). - Type trees: the player's serialized files have no type trees and the Addressables bundles hold no
Shader, except theunitybuiltinshadersbundle, whose tree has the same hash and is borrowed in the second pass. - Found on: Ace Attorney Investigations Collection (Unity 2022.3.17f1): 4,951 stage shaders: 2,475 vertex / pixel pairs (4,294 in the player's files, 517 built-ins, 140 in bundles) and one geometry shader, which Metal cannot express (its build fails).
- Note: armyja's issue #17 proposed UnityPy and a reader of its own; neither was needed.
Unity Shader layouts written out for players without bundles
- Symptom: the split stopped with
no bundle has a Shader type tree of the same hash to borrow. - Cause: a Unity player with no bundle to borrow a tree from: its serialized files have no type trees, and no bundle carries a
Shadertree of the same hash. - Fix:
unityfs.pycarries the layouts written out (KNOWN_TREES;tree_from_layoutbuilds the tree a file with type trees would have), and the split's second pass gives one to the stripped files when no bundle lent a tree of that hash. Only there: taken in the first pass, Ace Attorney Investigations Collection's player files came before itsunitybuiltinshadersbundle and the built-ins' source column and package indices moved, while with the second pass its tables come out byte-identical. The structs both the 2020.3 and 2022.3 layouts share are written once (_SHADER_COMMON), and the 2022.3 layout comes out byte-identical. - Found on:
- Brain Memory Training Academy (Unity 2022.3.5f1: only
Data/*.assets,level*and the two engine files inData/Resources, none with type trees). TheShadertype hash there (ea424a5f…) is the one in Ace Attorney Investigations Collection's bundles (2022.3.17f1): the same layout, about 30 structs. Checked against Ace Attorney's own tree: the same 2,324 nodes with the same alignment flags, and its 40 bundleShaderobjects decode identically with either. 496 stage shaders: 439 engine built-ins, 46 of the game's, 11 of the player's inmain, and the built-in VR blit's geometry shader, which does not build. - Patrick's Parabox (Unity 2020.3.30f1, built-in shaders only, no bundles) stopped there with hash
a30e3dcf…, which one 18 KB shader bundle of Fire Emblem Engage (2020.3.18f1) carries; its tree is now in the table too (SHADER_2020_3: per subprogram global and local keyword indices, every subprogram inm_SubPrograms, no parameter blobs, keyword names or stage counts), equal to Engage's node for node (2,179 nodes, the alignment flags included), and each of the game's 48Shaderobjects reads to its exact end. - Raging Loop (Unity 2018.3.10f1, no bundles: 48
Shaderobjects inData/*.assetsandData/Resources) stopped there with hash8db76007…, and no game of that Unity version with a bundle was at hand, soSHADER_2018_3is written from AssetRipper's TypeTreeDumps (StructsDump/release/2018.3.10f1.dump), checked node for node against the dump (1,325 nodes, the alignment flags included). It is a layout of its own, older than the common structs: no conservative raster state,BufferBindingwithoutm_ArraySize,ConstantBufferwithoutm_IsPartialCB, the parameters in each subprogram and nom_CommonParameters, one segment per platform (the pre-2019.3 form Cuphead's trees gaveshader_programs). Each of the 48 objects reads to its exact end: 450 subprograms of version 201802150 (older than the local keyword list, which starts at 201806140). - Return of the Obra Dinn (Unity 2017.4.28f1): hash
266d5311….SHADER_2017_4derives from the 2018.3 layout by removingm_HasProceduralInstancingVariantandm_NonModifiableTextures, with the instancing flag retaining the alignment. It matches all 1,313 nodes and alignment flags in AssetRipper's release type tree; the game note records the object census and exact-end checks. - Donkey Kong Country Returns HD (Unity 6000.0.28f1, no bundles): hash
2ec7223d…matches BALL x PIT's Unity 6000.0.62f1 bundles.SHADER_6000_0derives from the 2022.3 layout by removing each pass'sm_EditorDataHashandm_Platformsarrays and appending the shader'sm_AssetGUID. The generated tree equals the bundle tree in types, field order and alignment flags; the game note records the object census and build results. - LEGO Builder's Journey (Unity 2021.2.13f1, provisional profile: every serialized file is stripped and no bundle carries a
Shadertree): hashd8236c9b….SHADER_2021_2is written from AssetRipper's 2021.2.13f1 release tree and matches it node for node (2,174 nodes, the alignment flags included): its subprograms drop the local keyword list (as Unity 2022 does), keep their parameters and use signed 64-bit requirements; each pass appendsm_SerializedKeywordStateMask, and the parsed form adds keyword names and flags. All 195Shaderobjects read to their exact ends, and the split finds 9,410 stage shaders (3,567 vertex, 3,571 pixel, 2,271 compute, one geometry) in the player's files andmain. - Dynablaster (Unity 2021.3.25f1, no bundles, provisional profile; seedds/nxnative#1147): hash
f0c18427….SHADER_2021_3derives from the 2021.2 layout by adding each program'sm_PlayerSubProgramsandm_ParameterBlobIndicesand the shader'sstageCounts; the keyword state mask stays in the pass. It matches all 2,304 nodes and alignment flags of AssetRipper's 2021.3.25f1 release tree, and it read all 50 Shader objects of the three small stripped files on the reporter's Mac (1,771 shaders split). - Castlevania: Belmont's Curse's Digital Sound & Art Gallery (
01005F4027E94000, on the Midnight Edition cartridge; Unity 6000.3.6f1,mainbuild ID79efa8c369b16c2a8b7993675b1f6ee3; not the game itself, whose files are 2022.3): hash57f0dd2d….SHADER_6000_3is the 6000.0 layout withSInt64 m_AssetLocalIdentifierInFileafterm_AssetGUID(Shaderversion 4, from 6000.3.0f1 on; the 6000.3.0b4 dump still has version 3, which hashes like 6000.0). It matches all 2,306 nodes and alignment flags of AssetRipper's 6000.3.0f1, 6000.3.11f1 and 6000.3.20f1 release trees, and all 97 of the Gallery's strippedShaderobjects read to their exact ends. The Gallery has not been run. - Dodgeball Academia (Unity 2019.4.21f1, provisional profile: every serialized file is stripped and no bundle carries a
Shadertree): hashed2a06ce….SHADER_2019_4derives from the 2018.3 layout, checked node for node against AssetRipper's 2019.4.21f1 release tree (1,481 nodes, the alignment flags included) and equal to the tree Subnautica's Unity 2019.4.36f1 bundles carry under the same hash: global and local keyword indices in each subprogram, a ray tracing program in each pass, and 2019.3's segments (oneoffsets/compressedLengths/decompressedLengthslist per platform); the parameters stay in each subprogram, withoutm_CommonParameters. All 62Shaderobjects read to their exact ends, and the split finds 7,996 stage shaders (4,162 vertex, 3,778 pixel, 55 compute, one geometry) where 11 came frommainalone. - Lovers in a Dangerous Spacetime 1.0.4 (provisional profile, Unity 5.5.0p1): hash
4496e93f2179252104401c8dda0a1751.SHADER_5_5matches all 1,222 nodes (types, names, order and alignment) of AssetRipper's 5.5.0f3 release tree. All 69 Shader objects read to their exact ends; the split succeeds with 548 stage shaders (284 vertex, 264 pixel; 544 from assets, four from main). Older arrays mostly do not align, but the channel vector aligns on its parent. No shader requirements, procedural instancing or nonmodifiable textures. Extraction validated only: translation and gameplay remain unchecked.
- Brain Memory Training Academy (Unity 2022.3.5f1: only
- Note: a Unity version whose
Shaderhash is not in the table still stops with the same message; read its tree from any bundle of that Unity version, or from AssetRipper's TypeTreeDumps for that exact version (compared node for node, the alignment flags included), and add it with its hash toKNOWN_TREESand todm/gfx/tests/test_unity_known_trees.py. To take one file out of an NSP without extracting the RomFS, filternx_extract'sCopyby path.
Unity 6 Shader objects
- Read with no change: Hollow Knight: Silksong's 2,068 Addressables bundles carry their type trees (they report the engine version
0.0.0, Unity's stripped version string), so no layout had to be written out. - BALL x PIT keeps most of its shaders in the player's loose serialized files (
resources.assets,sharedassets1.assets, the built-in resources), which have no type trees; they borrow theShadertree its 10 shader bundles carry (shader_split.pydefers a file that raisesNoTreeto a second pass), so it needed no layout either. - Found on: Hollow Knight: Silksong (Unity 6000.0.50f1): 2,450 stage shaders: 1,189 vertex, 1,193 pixel, 67 compute and one geometry shader, which does not build; 11 of them are the player's own in
main. BALL x PIT (6000.0.62f1): 38,099 shaders, most of them in the loose files. Silver Pines (6000.3.15f1): 56,386 stage shaders in its Addressables bundles, read with no change.
Unity ComputeShader objects
- Symptom: the 3D battle scene was black behind a correct UI, with
[RED] shader 854a8afc9d07f88d is not in the shader mapandthe dispatched program has no compute shader. - Cause:
DM_NVN_SHDUMPsaved the program; its code bytes were inData/sharedassets2.assets, uncompressed, inside aComputeShader(class 72): the post-processing stack's colour grading LUT baker (Lut3DBaker#KGenLut3D_AcesTonemap), so the LUT the scene is graded through stayed black. The split read onlyShaderobjects. AComputeShaderholds per platform variant a list of kernels, each with its unique variants; a variant'scodeis the program code of aShadersubprogram (the 0x60-byte stage header, only the compute block present) and itsthreadGroupSizematches control +0x748. - Fix:
unity_computeinshader_split.pyreads them beside theShaderobjects of every serialized file. The game has no bundle with a class 72 tree, sounityfs.pycarries Unity 2022.3.54f1's layout (COMPUTE_2022_3, written from AssetRipper's TypeTreeDumps for that version; all 12 objects decode,resourcesResolvedtrue at each end). 85 compute shaders came in (86 with the player's own). - Found on: Monster Train 2 (Unity 2022.3.54f1).
- Older layouts: Unity 2019.4 stores each kernel's code directly, without
uniqueVariantsorvariantMap.unity_computeaccepts that form too, andCOMPUTE_2019_4supplies the stripped-file layout. Found on Pokémon Brilliant Diamond (2019.4.27f1); its missing runtime shader is the built-in GPU skinning kernel. The layout matches the release dump's 116 nodes and alignment flags, and both built-in compute objects decode to their exact ends. - Unity 2021.3:
COMPUTE_2021_3covers stripped class 72 hashabd9135b8ce83d043fef4e9ec7f53366, matching all 144 nodes and alignment flags in AssetRipper's 2021.3.18f1 release tree. Kernel parents usevariantMap, global and local keywords; each kernel holds byte-vector code, astaticvectorthread group size and signed 64-bit requirements. Unlike 2022.3 there are nouniqueVariants,variantIndicesor dynamic keywords; both versions store code as bytes.resourcesResolvedaligns after every platform variant, including when another platform follows. The synthetic tests cover two platforms, multiple keyword variants, byte-code padding, exact object consumption and shader provenance. Found on Shin chan: Shiro and the Coal Town (Unity 2021.3.18f1): PR #440 reports recovered GPU skinning kernels and correctly rendered characters on the iPhone; that gameplay result has not been independently repeated here. - Unity 2020.3:
COMPUTE_2020_3covers stripped class 72 hashd0171b849bb064b2424893e7d4809be5. It is the 2021.3 layout without the kernel's trailingSInt64 requirements: kernel parents usevariantMap(not aligned) with global and local keywords, code is a byte vector andthreadGroupSizea staticvector (not aligned). All 143 nodes and alignment flags match AssetRipper's 2020.3.27f1 release tree; the synthetic tests cover the 2021.3 fixture withoutrequirements. Found on MADiSON (0100C3F0181C8000, 1.1, Unity 2020.3.27f1, SDK 13, provisional profile):unity default resourcesandsharedassets0.assetsskipped their ComputeShader objects, the split had 1 compute shader, and the run logged 6shader … is not in the shader mapand onethe dispatched program has no compute shader. The 3D scene was black on an iPhone 16 while the crosshair, menus and sound worked. With the layout the split takes 91 compute shaders (8,795 in all), the Mac run logs no red line and the scene draws; those results are the author's, and the fixed build has not run on the iPhone. The hash is not MADiSON's alone: Unity's type hash (MD4 over each node's type, name, byte size, array flag, version and align flag) recomputed from the release trees of 2020.3.0f1, 18f1, 27f1, 30f1 and 48f1 gives it each time, and the same formula gives 2021.3.18f1'sabd9135b…. So the layout can also reach the registered 2020.3 games. AI: THE SOMNIUM FILES - nirvanA Initiative already has its compute kernels, since its bundles carry type trees. The tables of Fire Emblem Engage and Patrick's Parabox have no Unity compute kernels: if their stripped files hold ComputeShader objects, their next NSP pack adds them through the shader-only derived profile (below). Neither game's files were available to check this. - Unity 2017.4: Return of the Obra Dinn needs hash
20291e02…for strippedinternalskinningobjects.COMPUTE_2017_4restores the nested buffer-counter fields; all 120 nodes and alignment flags match the release dump. The game note records the object census and exact-end checks. - Unity 6000.3:
COMPUTE_6000_3covers stripped class 72 hash43a0948a3f403068c0b31bff90ba0c9a: the 2022.3 layout with anint resTypeafter each resource'stexDimensionandthreadGroupSizeastaticvectoragain. All 159 nodes and alignment flags match AssetRipper's 6000.3.11f1 release tree and its 6000.3.0b4, 6000.3.0f1 and 6000.3.20f1 trees; a synthetic test reads a fixture to its exact end and into the split. Found on Hello Kitty Party Land (Unity 6000.3.11f1, provisional profile): its characters drew as huge stretched triangles, with[RED] … unity default resources: ComputeShader objects that no bundle lends a type tree to and unityfs.py has no layout forin the split andthe dispatched program has no compute shaderin the run, since the built-inInternal-Skinningkernels were left out. PR #857 reports that all 11 objects read to their exact ends (Internal-Skinning40 kernels,Internal-BlendShape9), the split finds 92 compute shaders instead of 1, and the Mac app draws the characters right; PR #791 reports the same hash on another game. Neither result has been repeated here, since no game with this hash is available. Silver Pines (6000.3.15f1) already has these kernels in its table without this layout. - Registered tables after a reader update: a newly supported layout can add kernels to an existing game's shader map. For registered module builds, the NSP script permits a shader-only derived profile only when every original shader's package, stage and source, every original fact and every evidence pair remain unchanged (package indices may move), and every added shader is compute with matching key/source evidence from
unity_compute. Each added kernel must also have its fact row. Registered settings, build rows and cuts are retained; the repository tables are not edited. A cached comparison pins the registered tables, split inputs and comparison code. Deleted or changed original rows, graphics additions and additions without reader evidence still stop the build. The incremental-build tests cover acceptance, rejection and cache invalidation. - Note: a file whose
ComputeShaderhas no tree still goes to the second pass; if it has none there either, the split prints a[RED]line and leaves its kernels out instead of stopping. The original bring-up omitted stripped objects in Cuphead (2), Fire Emblem Engage (4) and Raging Loop (2 built-ins; no compute dispatched). Their type hashes were not recorded, so their compatibility with the newer layouts remains unchecked. Unity 2017.4.9f1, 2017.4.17f1 and 2017.4.28f1's published class 72 release dumps are identical, but that does not establish the hashes in Cuphead or AI: THE SOMNIUM FILES.
GLSLC outputs in a Unity TextAsset
- Symptom: black, jagged holes in the ground of a map (whole tiles of the terrain mesh missing while others draw), with about 25 distinct
[RED] shader … is not in the shader mapkeys andprogram has no vertex shader, on a Unity game whoseShaderobjects all split cleanly. - Cause: the game draws its maps and effects with programs of its own, not Unity's:
DM_NVN_SHDUMPsaved 24 of them, and none was in anyShadersubprogram of the 1,606Shaderobjects in the RomFS (all of them decoded); their code areas were inData/resources.assets, uncompressed, inside theTextAsset(class 49)shader.switch.vfxsb(11 MB, first word 0x20160817): 1,160 whole GLSLC outputs of a vertex and a pixel stage each. Their control sections carry GLSLC's full header (control +0x20 = 0xa10 and more), unlike the 0x850-byte sections Unity 2018 stores in its subprograms. The split read onlyShaderandComputeShaderobjects, and the fallback for loose GLSLC outputs skips Unity files. - Fix:
unity_text_glslcinshader_split.pyreads theTextAssets of a serialized file that holds the GLSLC magic (unityfs.text_assets: name and bytes, the two leading fields every Unity version shares, so no type tree is needed) throughglslc_shaders, which keeps only outputs that pass its checks. A file without the magic is not decoded, so other games' tables do not change. This one TextAsset added 1,207 distinct shaders (the game has 31,635 in all), with 1,156 vertex / pixel pairs; they covered all 57 keys the runs had reported missing. - Found on: FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition (Unity 2018.4.2f1): the intro's overworld shot.
Unreal Engine 5 shader code archives (Oodle)
- How it is stored:
ShaderArchive-Global-SF_GLSL_SWITCH_MOBILE-SP_GLSL_SWITCH_MOBILE.ushaderbytecode(1,219 shaders) andShaderArchive-Octopath_Traveler0_Chunk0-…(9,377), both stored in the pak (01). Version 2 archives of shader map hashes, shader hashes, shader map entries, shader entries{u64 offset, u32 size, u32 raw size, u8 frequency}(17 bytes packed; frequency 0 vertex, 3 pixel, 5 compute), preload entries and shader indices, then the code. - Compression: every shader is Oodle-compressed (Mermaid, block header
8C 0A). There is no Oodle decoder in this repository, so the game's ownOodleLZ_Decompress(statically linked intomain; the host finds it as the one function that takes the address of the library's own name string "OodleLZ_Decompress", its profiler scope: Octopath Traveler 0main+0x4f77e10, Pokemon Legends: Z-Amain+0x1a9c9e0) decodes them in the Mac host:DM_OODLE_JOB(dm/host/hle_oodle.c), the NSP script'sdecode_ue_shadersfor any game with Unreal paks. - Record: a decoded shader is an
LSLGrecord:LSLG, a stage tag (SV,SP,SC), a header with the source name (/Engine/Private/…usf:MainPS), thenu32code length, the code area,u32control length (0x880), the control section and a 24- or 29-byte tail, all at unaligned offsets (uepak.lslg). - Check: the host keys came out exactly: 37 of 37 shaders a first run reported missing were in the two archives.
- Found on: Octopath Traveler 0: 10,324 unique shaders (1,457 vertex, 6,346 pixel, 2,521 compute); vertex and pixel shaders combine per draw, so every vertex shader is paired with the single-stage cover. Bindings: separate textures and samplers, as Engage's (
0x168/0x568); 61 vertex shaders pick a texture slot at run time (profile keytex_dyn_slots, Texture slots picked at run time), 2,084 shaders do atomics on buffer images (Image atomics). - Note: 16 compute shaders do atomics on a 3D
r32uiimage, all Unreal's paged global distance field (GlobalDistanceFieldCompositeObjects.usf:CompositeObjectsIntoPagesCS), which the mobile renderer does not dispatch (none in any run). They build since image atomics are native (Image atomics).
Unreal Engine 4.27 shader code archives (LZ4)
- How it is stored: the desktop renderer's
ShaderArchive-Global-SF_GLSL_SWITCH.ushaderbytecode(1,764 shaders) andShaderArchive-DOLL_Chunk0-SF_GLSL_SWITCH.ushaderbytecode(63,185), stored in the pak: the same version 2 archives and the sameLSLGrecords as Unreal Engine 5's, but every shader is an LZ4 block (the first bytes are LZ4 tokens followed byLSLG; LZ4 is Unreal's default shader compression since 4.26). - Reader:
uepak.pydecodes them itself (lz4_shaders): every compressed shader must decode to its raw size as anLSLGrecord, else the archive goes to the Oodle job as before. - Found on: DRAGON QUEST VII Reimagined (Unreal Engine 4.27): 62,901 unique shaders (10,114 vertex, 50,756 pixel, 1,968 compute, 63 geometry).
- Note: its fragment shaders carry no output types either: one global shader writes integers bit-cast into a float output to an
R8Uinttarget, listed in the profile'sshader_facts_manual.tsvuntil 2026-11-16, when the typed-output entry point took its place (Integer fragment outputs declared by hand).
Unreal Engine 5.6 IoStore shader libraries
- Symptom:
[RED] the shader split found no shaders in main or the RomFS, the split's log ending inshaders: 0, and noUE shader decodestep, on a game whose container holds shader libraries and whose pak namesGlobalShaderCache-: from 2026-11-04 until issue #1277 was fixed, such a pak counted as inline. - How it is stored: the desktop renderer (
SF_GLSL_SWITCH) with the sameLSLGrecords, but no archive in the pak: the two libraries are IoStore shader libraries inFFRS-Switch.ucas, whose shader groups are Oodle-compressed as a whole (01). Each shader entry packs its frequency (bits 0–3), group (4–33) and offset in the group's decoded bytes (from bit 34), and a shader runs to the next one's offset. - Reader:
uepak.pywrites them out as version 2 archives, so the split reads them as any other. The pak beside them can name the global shader cache as an inline game's does, so that name alone does not tell the two apart:inline_in_containersdoes, by the shader libraries. - Found on: FINAL FANTASY RESONANCE (Unreal Engine 5.6.1): 73,496 unique shaders (9,253 vertex, 61,305 pixel, 2,934 compute, 4 geometry). The symptom on its Asian release.
Unreal Engine 5.6 IoStore shader libraries for the Switch 2
- Symptom: the NSP script's
UE shader decodefinds both libraries (ShaderArchive-Global-SF_GLSL_SWITCH2-SP_GLSL_SWITCH2.ushaderbytecodeand the game's), then the split stops at once:[RED] /ue_shaders/ShaderArchive-Global-…: shader 0 is not an LSLG record. - How it is stored: as the Switch's 5.6 libraries, but each decoded shader is the NVN2 record of Unreal Engine 5.4 for the Switch 2 (
uepak.sage_record: header, source name, code area, NVN2 control section), with noLSLGtag to give the stage. The frequency byte is in Unreal Engine 5's numbering (0 vertex, 1 mesh, 2 amplification, 3 pixel, 4 geometry, 5 compute), where Unreal Engine 4 had hull and domain at 1 and 2. - Fix:
shader_split.pyue_shaderstakes such a record when it is notLSLG, its stage from the record itself (nvn2_stage: the control section's stage byte, else the SPH), and checks the stage against the frequency in that numbering. Covered bydm/tools/tests/test_uepak_iostore.py(a synthetic decoded archive). - Found on: Orbitals (Unreal Engine 5.6.1): 40,995 shaders in the two libraries (4,515 + 36,480), 23,432 unique (3,556 vertex, 16,459 pixel, 3,415 compute, 2 geometry), split in 57 s.
IoStore patch containers keep their shader groups in the base container
- Symptom:
ValueError: …/Glow-Switch_0_P.utoc: shader group 0 has no chunkfromuepak.py io_archivewhile the NSP script decodes the shaders (decode_ue_shaders, after[4/8] UE shader decode). - Cause: an update's IoStore container is a patch: its shader libraries have the base game's chunk IDs (so they replace their tables), and an unchanged shader group is listed with the base container's chunk ID.
io_archivelooked every group up in the container the library chunk came from. - Fix:
uepak.pyreads every.utocunder the RomFS (io_tocs, in mount order: the base game's containers, then_Ppatches and numbered_0_P,_1_P, … patches,mount_order, case-insensitive_Pmarker) and resolves a group's chunk ID in any of them; a library chunk ID two containers share is taken from the later (patch) one, whose tables are the current set. TOC metadata is read without a key;Toc.readrefuses encrypted data without a key only when the selected library or group needs it, so an encrypted group-only container is refused and a fully superseded encrypted library is never read. - Found on: LEGO Horizon Adventures (update v262144, Unreal Engine 5; provisional profile): the update's
Glow/Content/Paks/Glow-Switch_0_P.utocover the base'sGlow-Switch.utoc; 20,889 shaders in its two libraries, 20,880 unique after the split.
An Unreal pak key split into two 16-byte literals
- Symptom:
[RED] …/Nicola-Switch_0_P.pak: the index is encrypted and no window of main decrypts itfrom the NSP script before[5/8] UE shader decode(the message now readsno key in main (a 32-byte window or two 16-byte literals its code stores together) decrypts it). - Cause:
uepak.py find_keytried every 32-byte window ofmain's read-only and data segments. The engine gets the key from a callback that copies a 32-byte array into its argument (UE_REGISTER_ENCRYPTION_KEY), and clang compiled the copy as two 16-byte constants loaded from separate places:adrp,adrp,ldr q0,ldr q1,stp q0, q1, [x0],ret, so the key's halves are not side by side and no window holds it. - Fix:
find_keyfirst tries the keys the code builds that way (code_keys: eachstp qA, qB, [x0]with both registers loaded byldr qfrom anadrppage within the 8 instructions before it, a register written by anything else in between dropped), then the windows as before. The right key is the one that decrypts the index start to a short mount point, as for a window. Covered bydm/tools/tests/test_uepak_key.py(a syntheticmainand pak, no game files). - Found on: DRAGON QUEST III HD-2D Remake (Unreal Engine 4.27): 8 candidate pairs in
main, the key found in about 2 s.
Unreal Engine 4.18 shaders inline in cooked packages
- How it is stored: legacy version 4 paks with LZ5-compressed blocks (01) and no shader code archive. Each material's shader map is serialized in its
.uexp(38 to 87 shaders in the ones looked at) and the engine's global shaders inEngine/GlobalShaderCache-GLSL_SWITCH.bin(945: 597 pixel, 104 vertex, 241 compute, 3 geometry). Each shader's code is a byte array (i32length, then the bytes) holding one zlib stream that inflates to the sameLSLGrecord as Unreal Engine 5's. - Reader:
shader_split.py(ue_legacy_jobs,ue_inline_shaders) decodes every file of the newest copy of each path with the game's own LZ5 and takes each zlib stream that inflates whole from exactly the length in front of it and starts withLSLG(every such stream in the files looked at). Records stored uncompressed are taken too, but none were seen. - Found on: DRAGON QUEST XI S: 38,892 unique shaders (4,654 vertex, 33,981 pixel, 234 compute, 23 geometry) from 1,740 files; vertex and pixel shaders are paired as single-stage programs, as for Octopath Traveler 0.
Unreal Engine 4.27 shaders inline in cooked packages (LZ4)
- Symptom:
the RomFS has Unreal paks, but none … holds a shader code archive, thenthe shader split found no shaders in main or the RomFS. - How it is stored: a version 11 pak (Zlib blocks, index not encrypted) with no
.ushaderbytecode: the project turnedbShareMaterialShaderCodeoff, so each material keeps its shaders in its own.uexpand the engine's global shaders are inEngine/GlobalShaderCache-SF_GLSL_SWITCH.bin, as in Unreal Engine 4.18. Unreal 4.27 serializes each one as an entry ofFShaderMapResourceCode: the code (i32length, then an LZ4 block, the engine's shader compression since 4.26), the raw size (i32) and the frequency (u8). - Reader:
uepak.pyinline_shaderstells such a pak from one with archives by its directory index (cooked packages and no.ushaderbytecode; an encrypted index is read withmain's key, Unreal Engine 5.1 shaders inline in encrypted IoStore containers), andshader_split.pyue_legacy_jobsreads it file by file, Zlib and LZ4 blocks decoded in Python (Pak.read), so no host runs.ue_inline_shadersfinds each LZ4 block by its first literals, the record'sLSLG, with the token and literal length bytes in front of it, and takes it when it decodes to exactly the raw size after the block. - Found on: OCTOPATH TRAVELER II: 13,980 unique shaders (1,910 vertex, 11,346 pixel, 694 compute, 30 geometry) from the 3.3 GB pak in 13 s.
Unreal Engine 4.27 shaders inline in IoStore export bundles
- Symptom:
the RomFS has Unreal paks, but none … holds a shader code archivefrom the NSP script, on a game with a.pakbeside a.utocand.ucas. - How it is stored: the same inline records as the paks'
.uexpfiles,bShareMaterialShaderCodebeing off, with IoStore on as well: the cooked packages are the container's export bundles (chunk type 2 in Unreal 4.27's numbering, TOC version 3), Oodle-compressed block by block, and the pak beside it keeps everything else, the global shader cache (Engine/GlobalShaderCache-SF_GLSL_SWITCH.bin) too. The pak's directory has neither.ushaderbytecodenor.uexp, so it was taken for one with archives. - Reader:
uepak.pyinline_shadersalso takes the global shader cache with no.ushaderbytecodeas inline when the containers in the pak's folder hold export bundles and no shader libraries (inline_in_containers; with neither a.uexpnor such a container the NSP script stops rather than read the global shaders alone), andshader_split.pyue_legacy_jobsthen also reads the export bundles of the containers beside such a pak, the newest copy of each chunk ID (mount_order), through the game's own Oodle in the host's tool mode. Bulk data chunks are skipped.Toc.namesreads the container's directory index, so a shader's label names its package, as for a pak, andshader_groupsworks the same way. - Found on: Mario & Luigi: Brothership: 45,824 unique shaders from 8.8 GB of export bundles in 39 s.
An entry of a package's export list read as an Oodle shader table
- Symptom: the shader split reports
the game's decoder in the Mac host failed on a 8 → 30650 byte stream, the host's output saysasked to decode Legacy compressor; not supported!, and a run of the NSP script stops withfile(s) could not be read(a provisional profile goes on without those shaders). - Cause:
uepak.shader_map_entriesscans every Unreal file for a stream's two first bytes and holds a table by its two counts and its walk. An export of a split package's summary can pass all of that as a one-entry table: name number 1 is the count, flags 8 the stream's length, the 8-byte size0xb8c(8C 0B, then zeros) the stream, the offset 30650 the raw size.ue_inline_shadersthen took the decoder's refusal as fatal, where its zlib and LZ4 scans take it as no stream, and the failure cost the whole job, about 1/64 of the pak's bytes, not the one file. - Fix: the decode is the proof.
ue_inline_shaderspassesshader_map_entriesa check of each table's first entry: a stream the decoder refuses, a stored one that is no record, or a game whosemainhas no decoder at all makes it no table, and it hides nothing inside its span. A stream that decodes to exactly its raw size is a real one, so a record of another layout stays red, as do a later entry that fails and a host that dies.ue_packagesreads each package of a job on its own, so one that does not read costs itself. Nothing depends on the summary's layout, so this holds for every package version and for.uexpfiles and export bundles too. - Found on: OCTOPATH TRAVELER II, update 1.1.1, by PR #1333: six summary files matched, four jobs were lost, 11,832 of 13,980 shaders were left (the PR's measurement). The scan came with Unreal Engine 5.4's tables, so every game with inline Unreal shaders was exposed.
Unreal Engine 5.4 shaders for the Switch 2
- Symptom:
shaders: 0from the split, with no red line, on a game whose pak holdsEngine/GlobalShaderCache-SP_GLSL_SAGE.bin(Sageis the engine's name for the platform). - How it is stored: inline as in the 4.27 export bundles,
bShareMaterialShaderCodebeing off, in the TOC version 6 container's export bundles, which are chunk type 1 in Unreal Engine 5's numbering. Two things differ. The code of eachFShaderMapResourceCodeentry is one Oodle stream, not LZ4. And the record is NVN2's, with noLSLG: a 0x3e-byte header,u32name length, the name (Global/<type>/0:/Engine/Private/<file>.usf|<entry>),u32code length, the code area,u32control length, the control section (version 0xc9), a 12-byte tail. The frequency byte after each entry names the stage as in Unreal'sEShaderFrequency. - Reader:
uepak.shader_map_entriesfinds a table by its first entry's stream (8C 0Ais Mermaid) and takes it only when the count before the first entry, the same count before the 20-byte hashes, and a walk over all its entries agree: those two bytes also turn up inside other data, and decoding such a false start aborts the decoder (85 of 5,341 candidates in the global cache).uepak.sage_recordsplits each decoded stream by its lengths and the control section's own.Toc.export_bundlesnow takes UE5's chunk type as well; a container is read only beside a pakinline_shadersaccepts, so FINAL FANTASY RESONANCE and Octopath Traveler 0 are unaffected. - Found on: Yoshi and the Mysterious Book: 133,154 unique shaders (45,614 vertex, 60,840 pixel, 21,654 compute, 5,041 mesh, 5 geometry) from 19 GB of container in 76 s.
Unreal Engine 4.22 to 4.25 paks (version 8)
- Symptom:
[RED] the shader split found no shaders in main or the RomFS; the survey counts the game's Unreal paks, but noUE shader decodestep runs and the split reads none of them. - Cause: the paks are version 8, which
uepak.pydid not read (only 4 and 11):footerraised, andunreal_paksskipped both paks as no Unreal paks. Version 8 keeps version 4's per-file index, but its footer is version 11's (key GUID, encrypted flag, magic 0xcc from the end, five 32-byte compression method names after the SHA-1), and an FPakEntry's compression method is an index (from 1) into those names instead of version 4's flags. - Fix:
uepak.pyreads version 8 as a legacy pak: its footer as version 11's, its index as version 4's, each file's method named from the footer (Zlib, decoded in Python byPak.read). The shaders are inline in the cooked packages andEngine/GlobalShaderCache-GLSL_SWITCH.bin, as in Unreal Engine 4.18, soshader_split.pyue_legacy_jobsreads them unchanged.dm/tools/tests/test_uepak_v8.pybuilds a version 8 pak with a Zlib file and a stored one. - Found on: DRAGON BALL Z: KAKAROT + A NEW POWER AWAKENS SET (1.00, SDK 9.3.1): 43,113 shaders from 3,776 files in 38 s. The base build played from the title through the opening fight.
Shared shader archives in five-slot Unreal version 8 paks
- Symptom: the shader split reports
shaders: 0on a version 8 Unreal pak whose directory lists.ushaderbytecodefiles. - Cause:
pak_shader_sourcessent five-slot v8 paks to the inline scan based on the number of compression-method slots. That count describes the entry header layout. The pak directory describes which shader sources it holds. - Fix: use the same directory-based selection for both v8 footer layouts. Send the shared archives to the existing archive decoder. Keep scanning for inline shaders when the pak lists cooked packages or a global shader cache, or when an adjacent IoStore container holds inline export bundles.
- Found on: Oceanhorn 2: Knights of the Lost Realm. The two version 1 archives contain 4,496 records, all decoded by the existing version 1 reader.
Unreal Engine short version 8 paks and version 1 shader archives
- Symptom: the shader split finds no Unreal shaders on a game whose paks hold shared shader archives. The footer reader skips these version 8 paks with
no pak footer. - Cause: the short version 8 footer has four compression method slots, putting its magic
0xacbytes from the end. Each entry uses one byte for the method and has a 50-byte stored header. The version 1 shader archive stores a flat table of SHA-1 hashes, offsets, sizes and frequencies followed by stored or Zlib-compressed LSLG records. - Fix:
uepak.pyselects the entry layout from the footer and routes shared archives to the decode step. A pak can also supply inline shaders, soshader_split.pyscans its inline files and takes the shared shaders from the decode step. The version 1 reader bounds each record and normalizes it to a decoded version 2 archive with no shader maps. - Found on: Minecraft Dungeons (
01006C100EC08000). All 5 base pak indexes and all 46 update pak indexes parse to their declared end. The base game's two archives contain 8,398 records and the full split writes 7,853 unique shaders. For v1769472 the two archives contain 15,596 records and the full split with local DLC writes 14,903 unique shaders. Bloodstained: Ritual of the Night (0100BF500207C000, 1.60, v851968 with five DLC) has seven short v8 pak indexes that parse to their declared end. Its two archives contain 33,767 records, and the full split writes 33,401 unique shaders with zero unreadable files. Minecraft Dungeons PR #1270 · Bloodstained PR #2652
Unreal Engine frozen pak indices (version 9)
- Symptom: the shader split finds no shaders although the RomFS contains Unreal
.pak,.utocand.ucasfiles;uepak.footerreportsno pak footeron paks whose footer version is 9. - Cause: version 9 adds a
FrozenIndexbyte before the footer's compression-method names, moving its magic to 0xcd bytes from the end. When that flag is set, the index is a frozen memory image, not version 8's serialized entries: relative pointers, UTF-16 strings, 80-byteFPakEntryrecords and nested sparse directory maps. Merely accepting the version still misreads the index. - Fix:
uepak.pyreads the flag, bounds the frozen pointers and arrays, enumerates allocated map slots and resolves each filename's entry index. The compressed blocks retain entry-relative offsets and the data files retain their serialized headers. A clear flag uses the existing version 8 index reader. Encrypted-index key discovery validates the pointed-to UTF-16 mount, including non-ASCII names. Shader discovery routes shared archives to extraction and inline packages and global shader caches to the split, including when both are in the same pak. The split finds adjacent inline IoStore export bundles from their TOC metadata, even when the pak names no global cache. - Check:
dm/tools/tests/test_uepak_v9.pyexercises both index layouts, sparse-map holes, backward pointers, UTF-16 names, malformed ranges and references, deleted entries, and stored and multi-block Zlib data. Synthetic packing checks cover a mixed pak, a v2 IoStore TOC beside an empty pak, and key discovery for a non-ASCII mount. - Found on: Demon Slayer -Kimetsu no Yaiba- The Hinokami Chronicles (issue #2134, PR #2476), Crash Bandicoot 4: It's About Time (issue #1577), and DRAGON QUEST TREASURES (PR #1260).
An encrypted legacy Unreal pak with the shaders inline
- Symptom: the shader split says
[RED] /<pak>: the pak cannot be read (<path>: the index is encrypted and no key was given); its shaders are left out, then[RED] the shader split found no shaders in main or the RomFSwhen that pak holds all of them. - Cause: the pak's index and its entries are AES-encrypted.
shader_split.pyue_legacy_jobsopened legacy paks without a key, so the index did not parse and the pak was left out. The paks with archives already took their key frommain(An Unreal pak key split into two 16-byte literals); the inline path did not. - Fix:
ue_legacy_jobstakes each pak's key fromuepak.Keys, the key finder the shader code archives use too (uepak.job): for a pak whose footer says the index is encrypted it tries eachmainit is given (base game and update) withuepak.find_key, a key found once first. Each job carries the key, soue_legacy_shadersdecrypts the entries too. With no key in any main the pak is reported in red and skipped. Covered bydm/tools/tests/test_uepak_legacy_key.py(a synthetic encrypted version 4 pak andmain, no game files). - Found on: Little Nightmares II (
010097100EDD6000, 1.4, v262144; one version 8 pak): 20,170 shaders from 57 files in 9:38; it reaches the title screen and plays on the Mac.
Zstandard-compressed Unreal pak entries sent to Oodle
- Symptom: shader splitting reports no shaders after every Zstd-compressed pak entry fails with
main has no "OodleLZ_Decompress" name and no streaming decoder to find. - Cause: the pak footer names
Zstd, butPak.readdelegated every method except Zlib and LZ4 to the game's decoder. A game with Zstandard packages need not contain Oodle at all. - Fix: decode Zstd blocks directly in
uepak.pywith Python'scompression.zstdorbackports.zstd. Reject negative block sizes, limit output to the block's declared raw size plus one byte, and require a complete frame, no trailing bytes and the exact raw size. Keep genuine decompression failures visible. - Found on: BRAVELY DEFAULT Ⅱ 1.0.0. Its version 8 pak has 155,207 Zstd entries. The fixed split found 33,335 shaders. One monster texture block in the copy used for the original bring-up failed two independent Zstandard decoders. PR #3193
- Check:
test_uepak_v8.pycovers synthetic Zstd paks (with and without frame content sizes) without calling the guest decoder, wrong or negative raw sizes, empty frames, truncated frames, trailing bytes, andPak.readerror reporting.
Single-block Unreal pak entries truncated by their 6-bit block size
- Symptom:
[RED] <N> file(s) could not be read, their shaders are left out (first: ...#Engine/Config/BaseCompat.ini: ValueError: ...: Engine/Config/BaseCompat.ini block 0 does not decode (the stream does not end within its 0x3800 raw bytes)), followed at run time by[RED] shader <key> is not in the shader mapand missing 3D gameplay geometry while menus and 2D HUD render. - Cause: in version 11 encoded entries (
uepak.pyPak.entry), Unreal Engine 4.26 writes(raw >> 11) & 0x3finto the 6-bit block-size field for single-block compressed files without taking the0x3fexplicit-u32escape, becauseFPakFile::DecodePakEntryalways usesUncompressedSize(raw) whenCompressionBlocksCount == 1.Pak.entryonly substitutedrawwhen the decoded 6-bit field was0(< 2 KBor UE 5.6), so any single-block file at or above 2 KB whose raw size is not a multiple of 2 KB decoded a smallerblock_size(raw & ~0x7ff, e.g.0x3800for ~15 KBBaseCompat.ini), cappingzlib_blockbefore end-of-stream. - Fix: set
bsz = rawfor every single-block encoded entry (nblk == 1) inPak.entry, userawfor single-block reads inPak.readacross all pak versions, and reject negative raw sizes, non-positive multi-block sizes, or entries whose blocks leave unconsumedrawbytes. - Found on: Grand Theft Auto: The Trilogy – The Definitive Edition 1.0.8 (GTA III
0100C3C012718000, Vice City0100182014022000, San Andreas010065A014024000; Unreal Engine 4.26, version 11 Zlib paks, issue #3012). Pending reporter retest on all three titles. - Check:
dm/tools/tests/test_uepak_v11.pycovers synthetic version 11 single-block entries with truncated 6-bit block sizes (plain and encrypted), zero and0x3f-escaped block sizes, multi-block entries, legacy single-block entries, and damaged block-coverage rejection.
Unreal Engine 5.1 shaders inline in encrypted IoStore containers
- Symptom: the NSP script stops at
[8/11] UE shader decodewith[RED] …/pakchunk1-Switch.pak: the index is encrypted and no key in main (a 32-byte window or two 16-byte literals its code stores together) decrypts it, althoughpakchunk0-Switch.pakopened withmain's key. Past that:the RomFS has Unreal paks, but none … holds a shader code archive, thenthe shader record at … (frequency 5) is not a record of the known layoutfor every package. - How it is stored: inline as in the 4.27 export bundles (
bShareMaterialShaderCodeoff), with four differences. Every pak's index is AES-encrypted, with the key of GUID zero thatmainholds. Beside each container (pakchunk0-17-Switch.utoc, TOC version 5, flags compressed, encrypted and indexed) is a pak, and all butpakchunk0's are empty: 365 bytes, no file, mount point/. The containers are encrypted with the same key, data blocks and directory index alike. And eachFShaderMapResourceCodeentry is one Oodle stream, as in Unreal Engine 5.4 for the Switch 2, but it decodes to the Switch'sLSLGrecord (SP_GLSL_SWITCH). - Cause:
find_keytook a key only when the index decrypted to../, so it refused the right key on the empty paks.inline_shadersfiled every encrypted index under "archives" without reading it (Octopath Traveler 0's case), so the NSP script ran the archive decode, which found nothing.ue_legacy_jobsskipped encrypted containers, andTocdropped an encrypted directory index. Finally, the Oodle table path ofue_inline_shaderstook only NVN2 records. - Fix: all in
uepak.pyandshader_split.py, for every game:find_keyaccepts any short mount point that is a path (it starts with.or/, printable up to its NUL).inline_shadersreads an encrypted index with the key thatunreal_paks(…, mains=)gets fromuepak.Keys. Every caller passes the ExeFSmain:profile_guess.build_sources,uepak.joband the split. A pak that names no file is neither kind (None).ue_legacy_jobsreads an encrypted container with the key of the pak beside it, else the first key found, and its jobs carry that key toue_io_shaders.Tocdecrypts the directory index with the key, so shaders are labelled by their packages.- The Oodle table path takes an
LSLGrecord through the sametakeas the zlib and LZ4 scans. A stored record is left to the plainLSLGscan, so it is not taken twice. - Covered by
test_uepak_key.py(test_root_mount_point) andtest_uepak_iostore.py(test_an_encrypted_index_is_read_with_mains_key,test_split_reads_an_encrypted_container_with_the_key_of_the_pak_beside_it,test_lslg_records_in_an_oodle_table). None needs game files.
- Found on: DRAGON BALL Sparking! ZERO: 14,842 unique shaders (9,927 pixel, 3,698 vertex, 1,215 compute, 2 geometry) from 18 containers in 31 s. All 2,125 entries of its global shader cache are
LSLGrecords.
Unreal Engine 3 shader caches (Oodle packages)
- Symptom:
the shader split found no shaders in main or the RomFS,no compressed chunk at … (the chunks do not run to the end of the package)for zero-padded.xxxpackages,chunk at … has block size 0on 64-bit chunk headers, or Oodle failing withRequested Fuzz Safety, saw a compressor that can't decode Safeon small-window zlib blocks (0x28 0x15). - How it is stored: the engine's global shaders are in
GlobalShaderCache-Switch.bin(magicBMSG, not compressed), the materials' inCombinedShaderCache-Switch.xxx, an Unreal Engine 3 package (tag0x9E2A83C1, a positive file version after it: 864; Unreal Engine 4's is a negative legacy version). After the package summary come compressed chunks, each {tag, block size, compressed and raw size of the chunk, then each block's two sizes} and the blocks: 0x20000 bytes of Oodle Mermaid each (8C 0A), a block stored whole having its two sizes equal. Each shader is a record {u32length,u32code area length,u32control length (0x880), in the global cache one moreu32}, then its code area and right after it its control section. 64-bit UE3 packages (Mortal Kombat 11 v1703936) serialize the chunk tag, sizes and block table asu64(so the tag's high 32-bit word is zero), and store control-first shader records{u32 stored control size, u32 code size, u32 zero, u32 stored control size}, the control bytes (which may include compiler text and reflection beyond+0x20), then the code area (compute code may omit the magic header, with the thread group at control+0x748identifying it). - Reader:
shader_split.pyue3_package/ue3_bodyselect 32-bit or 64-bit chunk field width from the tag's high word, validate the block table, per-block decoded lengths and chunk totals, and decode each block (stored raw whenc == u, full RFC 1950 DEFLATE header check for zlib windows up to 32 KiB in Python, and Oodle with the game's own decoder through the Mac host's tool mode,DM_OODLE_SERVE). The chunk walk accepts an all-zero tail as package padding; any nonzero byte in a tail that cannot form a chunk is still an error.ue3_shadersreads both control-first records (checked by the repeated control size,+0x20,+0x704andglslc_stage) and code-first records (checked by control magic,+0x704back to code magic, and the two lengths in front).profile_guess.py(ue3_oodle_package) uses the same chunk field width when counting Oodle packages so the NSP script gives the split the host. - Found on: Batman: Arkham Knight has 1,847 records in the global cache and 22,874 in the combined one, with 21,923 keys after the profile's
shader_key_skip. Its 4,058 packages decoded in about a minute. None of 68 sampled packages outside the combined cache holds a shader. Borderlands: Game of the Year Edition pads packages to 32 KiB, which caused all 922 compressed packages to fail the walk. Mortal Kombat 11 v1703936 (main build4f7ab1a3eefc7eb20413936e8e37c2e9, draft profile #2799) uses 64-bit chunks, control-first records (76,865 keys in its split), and a small-window zlib stream (28 15) inAsset/Tweakvars.xxx(762 decoded bytes, zero shader records).
Task and mesh shaders in BNSH, and indirect mesh draws
- Symptom:
[RED] shader <key> is not in the shader mapfor shaders whose code is in a.bfshathe split reads,[RED] NVN unimplemented function called: nvnCommandBufferDrawMeshTasksIndirect, and grass and ferns missing. - Cause: a BNSH program's stage pointers went only to compute (+0x30). NVN2's task and mesh stages follow at +0x40 and +0x48, so the split saw only the pixel shaders of such a program. The draw takes a GPU address, whose record the game's culling writes earlier in the frame: zeros when it is recorded.
- Fix:
bnsh_shadersreads the two pointers, taking only one that leads to a control section of that stage, as an older BNSH's program ends before them. Metal's indirect mesh draw takes{x, y, z}, not{count, first}, somdx_runcopies the count on the GPU into{count, 1, 1}before the render pass, and the task or object function reads{count, first}from the record (Mesh draws with no task shader above 1024 workgroups). Reading the record on the CPU took 73 % of the submit thread in Kokiri Forest, waiting for the GPU. - Found on: The Legend of Zelda: Ocarina of Time: 491 mesh and 17 task shaders in
Foliage*.bfshaandModel*.bfsha.
Float atomics in storage memory
- Symptom: a Switch 2 game's picture is far too bright and warm wherever the view opens out: lifted blacks, yellow skin, a pale veil. The build log has
Invalid reduction type: F32FtzRn, easy to miss among thousands of lines. - Cause: RED.F32.FTZ.RN (0x98e, type 3) adds a float to a word of memory, and the translator dropped it with that log line. agl's scene analysis sums luminance this way (
probe_analyze,shadow_analyze,sky_analyze,cube_map_probe_analyze,inner_mask_analyze, and Foliage and TerrainGround variants). The CPU reads those buffers back into exposure: the sums stayed 0, so it applied its full negative correction. The tone map itself was right. - Fix:
InstEmitMemory.csEmitAtomicAddF32: a compare-and-swap loop on the word, inEmitAtomicOp, so ATOM's float form gets it too. A chain change. F16x2FtzRn stayed a log line until a game used it (Half-float pair atomics in storage memory). The shader build then turns the loop of an add whose result nothing reads into oneatomic_fetch_add_expliciton adevice atomic_float(MSL 3.0;dmsh_rewrite.pyfloat_add_msl, only the exact loop spirv-cross writes): agl's analysis adds every thread's value into the same few words, so the loops retried for each other. The translator cannot write the native add itself: its storage buffers areuintarrays, a float pointer to one is anOpBitcastthat SPIR-V's logical addressing forbids, and spirv-cross writes that as areinterpret_castof the loaded value, not of its address. An add traced to no storage buffer (through the memory pool table), a bounded buffer's guarded swap, shared memory and an ATOM whose result is used stay loops: correct, only slower. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py FloatRed(the translator's loop, and thatfloat_add_mslstill finds it);test_dmsh_float_add.py(the rewrite, and on the GPU the loop and the native add reach the same sums). - Found on: The Legend of Zelda: Ocarina of Time: 28 of its seen shaders; the frame's mean brightness at Navi's close-up went from 0.71 to 0.38. With the native add, on a MacBook Air M4,
6e28359aa3558f61(one workgroup of 256 threads, four words) went from 0.25 ms a frame to under 0.13 ms and1bba09ec4bc8ff67from 0.40 ms, the exposure the same (mean luminance 116-117 of 255 both ways); the Hyrule Field view's frame p50 went from 23.42 to 22.39 ms, between two builds (PR #1930).
Half-float pair atomics in storage memory
- Symptom: black blots with a white bloom halo on a Switch 2 game's mesh that is built on the GPU (Donkey Kong Bananza: the muck that salt melts). The scene's HDR target holds NaN there, the tone map makes it black and bloom spreads it. The build log has
Invalid reduction type: F16x2FtzRn. - Cause: RED.E.ADD.F16x2.FTZ.RN (0x98e, type 4) adds two halves to the two halves of a word of memory, and
EmitAtomicOpdropped it with that log line (Float atomics in storage memory added only the float32 form). Bananza's muck mesh pass writes each vertex's half4 normal as zero (STG.E.64 [R8], RZ), then its normal pass adds every face normal into its three vertices this way. The normals stayed zero, and the vertex shader's normalize gave 0 × ∞ = NaN, which the pixel shader's light loop carried to its colour. The console does the same arithmetic on the summed normal, so nothing there differs. - Fix:
InstEmitMemory.csEmitAtomicAddF16x2: a compare-and-swap loop on the word, asEmitAtomicAddF32, that unpacks both halves of the word and of the value, adds each pair in float32 and packs the sums. float32 has at least 2 × 11 + 2 bits, so rounding its sum to half once gives the half sum rounded to nearest even, as .RN does. Half denormals are not flushed (.FTZ). A chain change. The loop stays a loop: Metal has no atomic add on halves. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py HalfRed: the translator no longer logs the type, and its own kernel on the Mac's GPU, 1,024 threads adding (1.0, 0.5) into one storage word, ends exactly at (1024.0, 512.0), and one thread adding (3.0, 1.5) to (2048.0, 2048.0) gives (2052.0, 2050.0), which rounding toward zero would make (2050.0, 2048.0); with the translator before the fix the word does not change. - Found on: Donkey Kong Bananza:
be71d8f78b52e62fande5f7ed151822e560, 24 adds each (48 log lines in the build). Layer 1400: the blots on melting muck are gone on the Mac.
A float atomic add's retry flag survives the rewrite
- Symptom: a shader that reads a float-add loop's retry flag after the loop has an undeclared identifier after the native-atomic rewrite.
- Cause:
float_add_mslremoved the flag with the loop, although the flag is declared before the do-block and remains in scope after it. Only the word, sum and CAS temporaries are local to the block. - Fix: retain the flag as
bool <flag> = falseafter the native add. The original loop exits only when that flag is false, so later reads keep their value. An unused flag is left for the compiler to eliminate; the matcher and atomic operation are unchanged. - Check:
test_dmsh_float_add.pyconsumes the flag after both ordinary and exact adds; its GPU sum test and iPhone compile also consume the flags. - Found on: no game: reproduced with a synthetic shader while reviewing the existing matcher.
textureGatherOffsets and a loop over its offsets
- Symptom: dotted horizontal rows in blocks of the picture, in smooth and blurred areas, from a Switch 2 game's upscaler: the frame before it is clean and the frame after it is not. The same input gives a different picture each run. Bright scenes show more of them.
- Cause: spirv-cross's
spvGatherConstOffsetscallsgather()in a loop withcoffsets[i]. Metal takes that offset only as a constant expression. At the chain's-O1the loop stays, the compiler accepts it without a word, and the gathers read texels at offsets that differ between lanes and between runs. agl's NDSR network builds its 28x28 input tile with these gathers, so some of its lanes read zeros for a channel (at Ocarina of Time's first shared-memory barrier, a word's high half was the luma without its green term), and the network drew that as rows. - Fix:
dmsh_rewrite.pygather_offsets: each call ofspvGatherConstOffsetsandspvGatherCompareConstOffsetsbecomes its four gathers with the offsets written out, from the constant array the call names. A call whose array is not such a constant stops the shader. A chain change. - Squares: when the four offsets form a 2x2 square (b, b+(1,0), b+(0,1), b+(1,1), in any order), the call is one gather at b with a swizzle (
gather_quad). Each offset's texel is the (i0, j0) corner of its own footprint. With integer offsets, those corners are the four texels of b's footprint, each wrapped on its own either way, so the result is the same bits. The test compares the one gather with the four on the GPU at 49 positions per lane, from four texels before the texture to four past it, clamped and repeating. Ocarina of Time: 27 of its 32 shaders with gather offsets have squares, all of them compute (the NDSR networks), with 3 to 15 squares each. On an M6, standing on the Kokiri Forest deck, the frame's 4-dispatch compute encoder that holds the network went from 959–961 µs to 935.5 µs (two runs each, same session; the frame's GPU time shows no difference at that size). A contributor measured the network's largest dispatch on an M4 Pro at 845 → 779 µs (discussion #1789). - Check:
python3 dm/gfx/tests/test_dmsh_gather_offsets.py. Offline, one captured dispatch ofb106afba1a18faa9: about 40 % of the pixels differed between three runs of the old shader; the rewritten one gave the same bytes each time, equal to a version that reads the texels explicitly, and took 3.85 ms against 4.16 ms. - Found on: The Legend of Zelda: Ocarina of Time: 28 NDSR compute shaders of its seen shaders. Every game with agl's upscaler builds it the same way. Not yet checked: whether this is the open cause of Mario Kart World's isolated bright dots.
Runtime per-texel gathers wrap wide offsets on Metal
- Symptom: a per-texel gather with a runtime offset of +8 reads as if the offset were -8. A ramp texture makes the wrong texel visible in the shader result.
- Cause: the SPIR-V generator passes each tap's
Offsetthrough SPIRV-Cross to Metal'sgather. Metal's offset range is -8 to +7. On an M4 Pro running macOS 27.2.1, the runtime argument uses only the low four bits. Ampere's six-bit decode preserves the offsets used by the affected compute shaders. - Fix:
dmsh_xlatetellsTexturePassto lower runtime per-texel offsets into normalized coordinate shifts using the base texture size. Each tap gathers at its own coordinate and returns the same corner of the footprint. The sampler still applies its addressing modes. Constant offset arrays continue throughgather_offsets. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py GatherOffsets. On the M4 Pro, the coordinate shift matched explicit texel reads in all 1,788,750 samples per addressing mode on a 257×127 texture. The direct runtime offsets mismatched 1,325,760 samples with clamp and 1,341,888 with repeat. - Found on: The Legend of Zelda: Ocarina of Time and Donkey Kong Bananza while reviewing PR #2831.
F2IP
- Symptom:
Ampere instruction 243 at 0x… is not implemented, orISBERD mode b8 in a task or mesh shader, in the build. - Cause: 0x243 converts two floats to saturated bytes and packs them, a in byte 1 and b in byte 0, the layout of F2FP's halves; bits 78..79 are the rounding, as in F2I. A task shader can read its own payload back with ISBERD's mode 0xb8, the mode of its 0x927 store.
- Fix:
InstEmitAmpereAlu.csAF2ip,InstEmitAmpereMem.csAIsberd. The packing order comes from code that uses the result, not from documentation: the RZ form's byte is shifted to bytes 2 and 3, so b is byte 0. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py F2ip. - Found on: The Legend of Zelda: Ocarina of Time:
FoliageShader.sharcband 8 foliage mesh shaders.
nn::ndve's movie enhancement file
- Symptom: when an AV1 movie starts,
[RED] shader <key> is not in the shader mapfor 11 compute shaders and[RED] the dispatched program has no compute shader (or it is not mapped). - Cause:
Movie/Ndve/Ndve-Nvn2-vid_seq5.dat.zsholds the compute networks (roulibr) that upscale the game's movies, in a wrapper the split did not read:NDVE, a header, an NDSR pack, then the networks, each control section with its code area right behind it. The pack's entries are 8 bytes, a shader taking two, so a data entry moves the next shader by 8. The walk went by 16 bytes and lost it. - Fix:
shader_split.pyreads the wrapper (ndve_shaders) and walks the pack by entry. On Ocarina of Time the walk also finds 3 more compute shaders inagl_ndsr.pck, whose records are the same; a profile gets them at its next split. - Check:
dm/tools/tests/test_split_ndve.py. - Found on: The Legend of Zelda: Ocarina of Time.
The NDSR pack's record start
- Symptom:
draw skipped: no render pipeline (vertex - fragment -)in a game's final passes; shaders "not in the shader map", all fromagl_ndsr.pck. A short synthetic pack found by fuzzing raisedstruct.error: iterative unpacking requires a buffer of a multiple of 16 byteswhile choosing the record start. - Cause: the pack's records start at +0x10 in one SDK's version and +0x14 in another's, by the words in its header (Donkey Kong Bananza 0x300, 0x6efeff, 0xc0000; Splatoon Raiders 0x40100, 0x80300, 0x90, 0x20c00).
- Fix:
ndsr_shadersinshader_split.pyscores up to 16 complete records at each start and takes the start with more pointers to NVN2 control sections. The two starts can leave different numbers of trailing bytes in a short pack; those partial records are excluded from the score, as from the subsequent record walk. - Found on: Splatoon Raiders.
RAGE RPF6 archives and rgxd effects
- Symptom: the NSP script's split finds no shaders in a RomFS made of
.rpffiles; after a first reader,[RED]lines name groups of files that could not be read. - How it is stored: Rockstar's RPF6 (big-endian, as on the PS3 and Xbox 360): a 16-byte header {
RPF6, entry count, name table offset / 8, tag0xfffffffd= encrypted}, 20-byte entries, then a name table. The entry and name tables are AES-256 ECB decrypted 16 times over, with a key inmain's data segment. Entry 0 is the root directory; a directory's children are consecutive entries; a name hash is Jenkins one-at-a-time of the lower-case name, found by hashing every string in the name table. A plain file's data is raw, one zstd frame, a zlib stream, or raw deflate (audio_switch.rpf's config files). A resource (flags bit 31) keeps its type in the offset word's low byte, so its offset is(word & 0x7fffff00) × 8, and its data starts with anRSC\x05header (12 bytes) or, when the flags are bit 31 alone, anRSC\x85header (16 bytes);.wscscripts are AES encrypted like the tables as well. The shaders are RAGE effects (.nvninshaders.rpf, and effects inmain):rgxd, the parameter names, then one record per shader {u32, GLSLC's magic 0x19866891, u32 code length, u32 control length}, the code area, then the control section. A control section may carry bytes past its own length (+0x20), so it is compared at that length. - Fix:
dm/gfx/tools/rpf6.pyreads the archives:find_keytriesmain's 4-aligned 32-byte windows with at least 24 distinct bytes on an archive's first entry until it decrypts to the root directory (the key is never printed or written). Update 1.0.4 has the same key but not in one piece: its key setup loads the eight key words, each a big-endian u32 zero-extended to 64 bits, from four 16-byte constants, sokey_from_setupfollows the setup's loads and stores (it startscmp w1, #0; mov w8, #-3; csel w8, w8, w1, eq; cmn w8, #3in both builds).shader_split.pyreads every archive's files in parallel ranges (rpf_jobs,rpf_shaders), andrgxd_shadersreads effects in files and inmain. Reading resources as plain files gave 145 groups of unreadable files; with the resource offsets, both headers, zlib, raw deflate and the scripts' encryption, none. - Found on: Red Dead Redemption: 134 archives (11 GB), 3,413 shaders from 131 effects in
shaders.rpfand 168 frommain. - Check:
rpf6.py <main NSO> <file.rpf>lists an archive; the fuzz harness has anrgxdseed (dm/tools/fuzz/fuzz_shader_split.py).
Double Eleven .pkdswitch packs
- Symptom: after the RPF6 archives are read, the first screen's two shaders are still
[RED] shader … is not in the shader map. - How it is stored: Double Eleven's resource pack: the members one after another in
.pkdswitch, and an index.pkiswitchbeside it: u32 version 3, u32 0, u32 member count, then 16-byte entries {length, stored length, offset in the data file, name hash}; a member whose stored length differs from its length is one zlib stream. The shaders are whole GLSLC outputs (langselect: members 4 and 5, the screen's pixel and vertex shader); the other members are textures (DFvN) and fonts (BMF). - Fix:
d11_pack_shadersinshader_split.pyreads a.pkdswitchthrough its index and scans each member for shaders. - Found on: Red Dead Redemption:
d11extra/langselect.pkdswitch, the language selection shown before the game.
REDengine 3 shader caches
- Symptom: the split finds only the 563 shaders in
mainand the loose.binfiles (vertex 158, pixel 405, no hull, domain, geometry or compute); every material and the lighting and post-processing passes are[RED] shader … is not in the shader map. - How it is stored: two REDengine 3 containers.
shadernx.cache(incontent/content0,content/patch0and each DLC'scontent/: the material shaders) is a run of records {u64 hash, u8 1, u32 raw length, u32 stored length, one zstd frame}, each frame one whole GLSLC output, then an index of material and technique names; a 16-byte footer {u64 index offset,RDHS, u32 version 3} ends the file, and the records end exactly at the index.staticshadernx.cache(incontent/content0: the engine's own shaders, lighting, post-processing and every compute shader) is a header {FZLC, u32 chunk count, u32 first chunk's offset}, a table of {u32 stored length, u32 raw length, u32 next chunk's offset}, then the chunks, zstd frames of at most 1 MiB, or stored as they are when the two lengths are equal (the DLCs' 804-byte stubs); the GLSLC outputs run across chunk boundaries. - Fix:
rdhs_shadersreads the material records in order. TheRDHSfooter identifies the format, checked when the first record flag is set or the file is namedshadernx.cache.fzlc_shadersjoins the static cache chunks before scanning for GLSLC outputs. Both readers report a damaged record or chunk by number and offset and leave out the file's shaders. - Found on: The Witcher 3: Wild Hunt — Complete Edition (v458752): 29,673 shaders (vertex 24,617, pixel 4,968, compute 46, geometry 22, domain 13, hull 7; 21,233 from
content, 7,877 from the DLCs) in 80 s on an M1 Max, against 563 before. - Check:
dm/tools/tests/test_split_redengine.pycovers material records, static shader programs spanning chunks, an uncompressed DLC stub, wrong lengths, a damaged record flag, and zstd errors in both formats. A flag at +8 without the footer still goes through the plain reader.
Control sections and code
Code area and control section layout
- Code area: graphics = 0x30-byte header (magic
0x12345678) + 0x50 SPH + instructions (at +0x80); compute = 0x30-byte header (magic0x12345679) + zero padding, instructions at +0x100 (all 71 of Mario's). - Control section: magic
0x98761234; +0x700 = c1 offset in the code area, +0x704 = code size, +0x748 = compute thread-group size (u32 ×3), +0x754 = compute shared memory bytes. - Found on: Super Mario Bros. Wonder.
Control sections shorter than 0x880 bytes
- Cause: the control section stores its own length at +0x20. Mario's, Engage's, Dread's and 13 Sentinels' are all at least 0x880 bytes; 3D World has 2,888 of 0x850 bytes (its ShaderData bfsha and six layouts) and 0x848 in BAHS version 9, each followed directly by other data.
- Fix: the key hashes the first
min(0x880, control +0x20)bytes (ctl_leninshader_split.py,keys_hashinhle_nvn.c); the other games' tables came out byte-identical. - Found on: Super Mario 3D World + Bowser's Fury (SDK 10).
Optional stage byte in short NVN2 control sections
- Symptom: the offline shader build raises
IndexError: index out of rangeinjob_forwhile readingrec[ci + 0x56], after the shader split succeeds. - Cause: NVN2 identification needs only the 0x48-byte base control header. A valid short graphics control section can omit the optional stage byte at +0x56; the ordinary-job RT rejection read it without checking the section's length. The package's stored code length and control marker agree, so this is not a misplaced control boundary.
- Fix: check that +0x56 exists before testing it for stage 8. Short graphics records retain their ordinary translation path; records with an explicit RT stage still fail there and must use the RT build path. Synthetic job tests cover control lengths 0x48, 0x50, 0x56, 0x57 and 0xe0, retained code/constants, and explicit RT rejection.
- Found on: Splatoon Raiders, issue #2916: vertex key
22fff9012db5acaa,vs_other.binindex 81,agl_common.sharcb#BAHS@0x27ea4, pointed to a 0x50-byte NVN2 control section. Resolved, 2026-11-17. The later BAHS record check identified the entry as a stray descriptor. The v65536 refresh removed it. Issue #3089
Program keys computed inside nvnProgramSetShaders
-
Symptom: shaders reported missing at random, and their dumped control sections are garbage (Unity). Also: about 130
[RED] shader … is not in the shader mapkeys a boot, nearly all different from run to run, all single-stage programs, withprogram has no vertex shader, and every frame the same picture of grey noise; withDM_NVN_SHDUMPset the game draws correctly. -
Cause: NVN lets the caller free a program's control section once
nvnProgramSetShadersreturns; Unity does, and the host used to hash it at the first draw, so keys computed later hashed freed memory. The keys were then computed inSetShadersbut kept by the NVNprogram's address, and Unity 2018.4 copies an NVNprogram afterSetShadersand draws with the copy: the copy had no keys at its address, so its stages were hashed at the first draw again, from the freed section.DM_NVN_SHDUMPhid it, as it points every stage at a host copy of its section. -
Fix: the keys are computed inside
SetShaders(hle_nvn.cprog_key) and are found by the program's serial, which a copy carries, as the Metal side finds the program's translation. A serial's record stays as long as the process (a copy can outlive the program it was made from; 64 bytes aSetShaders). Mario callsSetShadersfor some programs with a code address that is not mapped yet, so a stage whose code is not in a registered memory pool at that moment is hashed at its first draw, from a host copy of its control section thatSetShaderskeeps. -
Found on: Fire Emblem Engage and Unity games in general (the source names no other); Super Mario Bros. Wonder (the unmapped code addresses); Ori and the Will of the Wisps (
01008DD013200000, Unity 2018.4.24f1, 1.2.1: the program copies, 135 stages a boot; no profile yet). -
Missing control sections (resolved, found by clang-tidy):
prog_keymust return the hash failure without marking a cached key valid. Previously a serial-less stage returned success with uninitialized output, and a serial-backed stage cached a zero key. Resolution and prefetch now stop with a fatal diagnostic rather than reading an invalid key;t_nvnchecks both forms and a successful retry after supplying a control section. No game failure was observed.
Control sections shared among shaders that differ only in their compile information
- Symptom:
[RED] shader … is not in the shader mapfor shaders whose control section and code area are both in the game files, but in different records: dumped (DM_NVN_SHDUMP), the control section is one record's and the code area another's. - Cause: the engine shares one control section among shaders whose sections differ only in GLSLC's compile information (+0x778..+0x791 and +0x7d0..+0x7e7):
DM_NVN_PROGTRACEshowed the same control pointer set first with its own code area and later with another shader's. The GPU does not read those bytes, so on hardware it makes no difference; the host's key hashes them. Masked, Batman: Arkham Knight's 24,721 control sections are 5,615; the tools read nothing there (dmsh_build.pyreads up to +0x75f). - Fix: the profile key
shader_key_skip <offset>+<length>(0x770+0x78): the key hashes that range as zeros, inshader_split.py(key_ctl, andsame_shaderignores it) and in the host (hle_nvn.ckeys_hash). Without the key, every game's keys are as before. It is a profile input of the shader chain, so the libraries follow it. - Found on: Batman: Arkham Knight: 40 shaders missing in the first 45 s before the key. With
0x7d0+0x18alone the opening cutscene still met one whose section differed at +0x778, as pull request #340 had found, so the range starts at +0x770. - Also found on: EA SPORTS FC 27 (
0x7d0+0x18): Frostbite's NVN renderer keeps one copy of each control section in a cache keyed by a hash that leaves out the compile information (fb::ShaderPlatformDataNvn,s_controlBlockCacheMutexinEngine.Render.Core2.PlatformNvn.nro); 10 programs were missing in the first menus, and the 10,342 keys are 7,873 shaders with the key. Its sections differed only at +0x7d0..+0x7e7 (+0x778 is zero in all of them).
Compute code with and without a header
- Cause: compute code areas have a header in Mario (
0x12345679), not in D2R. 3D World's particle compute shaders (SDK 10) start their instructions at code +0 (like D2R), not after a0x12345679header. - Fix:
shader_split.pyaccepts both;dmsh_build.pystrips only a header that is there. - Found on: Super Mario Bros. Wonder (header); Super Mario 3D World + Bowser's Fury (no header, SDK 10).
Exact program start for the decoder
- Symptom: 12 compute shaders (particles, post effects) translated into an endless loop that hung the GPU at the first gameplay scene; SPIRV-Cross failed on 7 shaders instead of 2 (SPIRV-Cross parse failures).
- Cause: Ryujinx's decoder treats every 32-byte boundary relative to the start as a scheduling word. Mario's compute code was first fed from +0x30: the groups were misaligned by 0x10, and instructions were dropped or misread.
- Fix: the program start must be exact (compute instructions at +0x100).
dmsh_build.pynow refuses compute code whose padding is not zero. - Check: for a new title, the first non-zero word after the header must be a control word, and the trailing
EXIT(e30000000007000f) /BRA-to-self (e2400fffff87000f) must sit in instruction slots of 32-byte groups counted from your chosen start. - Found on: Super Mario Bros. Wonder.
GLSLC outputs read through their section headers
- Symptom: GLSLC outputs fail the reader's check and are dropped (44 of DARK SOULS: REMASTERED's
main's 72 outputs and most of its archives' pixel shaders). Or an output is kept under a key the game never uses:[RED] shader ae4027f44fae34ef is not in the shader mapand[RED] the dispatched program has no compute shaderas Trails in the Sky 2nd Chapter's prologue reaches the garden terrace, with the output that holds that control section in the map as61b2373911028f85(main#GLSLC@0x7774a8). - Cause: the single-stage rule takes the code area right after the control section's own length (+0x20). SDK 4's GLSLC outputs (version 0x20.4): pixel shaders' control sections store at +0x20 a value 12 bytes short of their length. SDK 21's GLSLC (Trails in the Sky 2nd Chapter 1.0.4, a compute shader in
main): the control section (+0x20 = 0x1c6c8) holds GLSLC's NVcp5.0 assembly listing from +0x878 (0x1be48 bytes, the length at +0x18), and the code area starts 0x180 bytes past that length, at the section header's code offset (0x1c848). The rule read a code area 0x180 bytes early that still passed the check, so the key was wrong. - Fix: an output's own section headers say where everything is: the output's +0x4c is the section count, section i's header is at +0x90 + 0x90 i (
{size, data offset from the output, type}, type 0 = GPU code), and a GPU code header adds +0x30 control offset, +0x34 code offset (both from the section's data), +0x38 code length, +0x3c control length.glslc_shadersreads an output of one GPU code section by them first (glslc_section), and uses the +0x20 rule only for an output whose headers give no usable section. The key takes the control section's first 0x880 bytes, so the listing after them does not change it. - Found on: DARK SOULS: REMASTERED (SDK 4.5.0); Trails in the Sky 2nd Chapter (SDK 21.4.4).
- Check: on every output the old rule keeps (1,073 in 13 Sentinels, Three Houses, FINAL FANTASY TACTICS, Engage and Age of Calamity) both give the same key; the new reading also takes 8 outputs of Fire Emblem: Three Houses and 3 of Hyrule Warriors: Age of Calamity (GLSLC version 0x1d.0, whose control +0x20 holds odd values) that used to be dropped, so those two profiles' tables gained them. Reading the headers first changed one key in the 595 outputs of the 28 extracted modules on hand that hold GLSLC outputs (26 games'
mains, among them Three Houses, Age of Calamity, Hyrule Warriors: Definitive Edition, ROMANCE OF THE THREE KINGDOMS XIV, Smash and the Unity players): Trails in the Sky 2nd Chapter's compute shader,61b2373911028f85→ae4027f44fae34ef, the key the game dispatches.
VertexA and VertexB parts merged into one vertex shader
- Symptom:
no GLSLC output, a black screen with sound, a missing scope reticle, orvertex shader of shader type 0 without a VertexB part in the expected place. - Cause: Maxwell's first vertex slot (type 0, VERTEX_CULL_BEFORE_FETCH) can run before a type-1 VertexB. Running A alone left the generic varyings at (0, 0, 0, 1), so full-screen passes sampled their sources at (0, 0) and 2D draws sampled the first atlas texel. Reading
c1from after B for every pair also lost the constants in layouts that store them between A and B. - Fix:
sph_stageaccepts type 0 as a vertex shader.vertex_abreads the two SPH offsets and sizes from control +0x748. It redirects A'sEXITinstructions with CC T to B's first instruction and merges the SPHs as in Ryujinx'sTranslatorContext.Translate(VertexA). When control +0x700 points to B's 0x30-byte header,c1follows B. Otherwisec1starts at the offset and ends at B's SPH. The latter layout requires a zero tail after B because the merged program has one constant bank. A type-0 program with no B is translated as it is. - Found on: Catherine: Full Body has 1,244 VertexA/B shaders with B's header at +0x700's offset and zero padding after B. A writes no generic outputs, ends in an
EXITpredicated on CC FCSM_TR, an unconditionalEXITand aBRAto itself. Neither part uses absolute or table jumps. Borderlands: Game of the Year Edition has both layouts, including the reticle shader whose billboard-axis guard reads an embedded constant before B.
Translation
Optimized shader calls and memory snapshots
- Symptom: with shader job
debug = false, SPIR-V generation throwsGetLocalPointer/KeyNotFoundExceptionor casts anAstOperationto anAstOperand. Other inputs compile but read a call's output before calling it, lose an unused-return call's side effects, or read local memory after an intervening store instead of preserving its earlier value. - Cause: AST expression propagation treated every single-use assignment as a movable value. SPIR-V call arguments require local storage passed by reference; propagating their temporaries destroyed those lvalues. Moving call results or memory loads changed evaluation order, and dead-assignment removal could discard a call or atomic whose result was unused. A snapshot of an output argument could also move past another call that overwrote it.
- Fix: mark address-taken call locals and retain their storage. Propagate only pure expression trees with immutable leaves; keep memory reads and call/atomic effects at their original evaluation points, and retain unused assignments with side effects. This is shared translator behavior, without shader, game or build gates. Default shader builds use
DebugModeand already skip this AST optimizer; their generated source is expected to remain unchanged. - Found on: Nintendo Switch 2 Welcome Tour, while testing original RT bodies in an isolated callable-region prototype. The pointer and effect failures also reproduce in ordinary compute IR without that prototype mode. This does not establish playable RT graphics.
- Check: ordinary compute GPU fixtures cover nested calls, constant/expression/formal arguments, output lvalues, return ordering, storage side effects and memory snapshots. An independent aliased Ampere carry fixture fails 7 of 736 state words before the fix and zero afterward; plain register-SSA and debug-mode controls pass both before and after.
A jump enters a condition whose definition it bypassed
- Symptom: Metal warns that a boolean is used uninitialized on a path through a translated shader. A generated
if (!bypass) predicate = ...; if (predicate || bypass)readspredicatebefore testing the bypass flag; the analogous AND form has the same defect. - Cause: goto elimination widened an existing IF/ELSE condition with the jump flag. The jump can bypass the original condition's definition. Combining those operands does not preserve their original evaluation paths, even when the flag alone determines the combined result.
- Fix: materialize the entry condition in a registered boolean temporary, initialized from the jump flag. Evaluate the original condition only on its original entry path. Place that initialization after the enclosure that skips the bypassed statements, so the jump cannot skip the temporary's initialization too. This is shared structured-control-flow lowering, in both debug and optimized translation; it does not initialize arbitrary shader locals.
- Found on: Nintendo Switch 2 Welcome Tour, six native RT condition sites. Ordinary compute CFGs independently reproduce the same error.
- Check: 64 synthetic twelve-block CFGs, including conditional and unconditional jumps, exhaust 2,048 input patterns in debug and optimized modes: 3,145,728 path/output checks, with an eager AST interpreter rejecting every undefined read. The old lowering fails that interpreter and emits 103 conditional-uninitialized warnings per mode; current SPIR-V validates and Metal compiles with
-Werror=sometimes-uninitialized. The full build's early warnings come from rechecking the previous library for cache prefill: shader009135d86e77a09e_breproduces those exact old diagnostics, while its current source passes the strict compile.
Tested tools and compiler-specific shader caches
- Symptom: a shader build accepts tools that differ from
dmsh_chain.lock; after an override build, returning to the tested Metal compiler can still restore the override's libraries. - Cause:
own_compilers.pypreviously accepted any present Metal compiler or SPIRV-Cross. The shader and fetch-variant caches hashed the recorded Metal version and flags, without the actual compiler or SDK. Prefill checked only a sample's compiled bytes, so a mixed folder's other libraries could be attributed to the wrong compiler. The NSP stage key recorded Xcode's version, which can stay unchanged when its separately downloaded Metal toolchain changes, and did not followSPIRV_CROSSoverrides. - Fix: ship a universal SPIRV-Cross built from a pinned commit and require its fingerprint for NVN builds. Require both tested Metal compilers before an NVN game's shader steps;
--allow-other-metal(DM_ALLOW_OTHER_METAL=1forown_compilers.py) explicitly permits another present Metal compiler. Shader and fetch-variant keys include the actual Metal compiler and SDK identities. Earlier-library prefill requires that identity on every library's reflection (chain_compiler); matching a few sample compiles cannot establish the unsampled libraries' compiler. Unmarked legacy libraries are not imported, and the Metal cache format is bumped to discard entries prefill might have misclassified. NSP and regression keys hash the selected converter's bytes, including overrides; NSP keys also include both SDKs and Metal tools. - Found on: Breath of the Wild, issue #242. The report used an untested compiler, but whether that caused the corrupted picture remains open. The cache failures were reproduced with stand-in libraries; this does not establish the rendering cause.
- Check:
test_own_compilers.pychecks enforcement and the explicit Metal override.test_shader_toolchain_cache.pyfirst restored an untested library after switching compiler identities, for both main shaders and fetch variants, and now rejects it. It also checks stage invalidation on actual Metal, SDK and selected converter changes.test_spirv_cross_pin.pychecks the shipped binary, pin, lock, architectures and licences.
Metal compiler of a newer Xcode
- Symptom: after an Xcode update the build stops with
[RED] this Mac's Metal compiler is not the one the shaders were tested with (dm/gfx/tools/dmsh_chain.lock): metal_macosx Apple metal version 32023.922 …;xcodebuild -downloadComponent MetalToolchain, as the message said, downloads the same untested compiler again. - Cause: since Xcode 26 the Metal toolchain is a system asset that each Xcode downloads in its own build and
xcruntakes for the selected Xcode (xcodebuild -showComponent MetalToolchainnames it), whatever the macOS version. When #717 was reported, macOS 27.2 with Xcode 27.1 selected gave the then-pinned 32023.921, with Xcode 27.2 selected 32023.922. The message named the Xcode to install but not that it must be the selected one, and README linked the App Store, which offers only the newest Xcode. - Fix: the stop message names the selected Xcode and its folder, and says to install the tested Xcode from Apple's download page (beside a newer one as
Xcode-<version>.app), select it (xcode-select -sorDEVELOPER_DIR), then download its Metal toolchain; README says the same. The lock stays at the one tested compiler: another one needs a regression run before it is recorded, and the lock is part of the chain version. Whether two installed toolchain assets each follow their own Xcode is inferred from-showComponent, not yet tried with both installed (open). - Found on: no game: GitHub issue #717, on macOS 27.2 with Xcode 27.2 (Metal Toolchain 27B47).
- Check:
test_own_compilers.py(the selection step before the download),test_ci_toolchain.py(the message's and README's Xcode are CI's).
Idle MSBuild workers block regression measurements
- Symptom:
regress.pywaits for other jobs to end while the only reported jobs are sleepingMSBuild.dll /nodemode:1 /nodeReuse:trueworkers using 0% CPU. - Cause: the busy-machine check treated every
dotnetprocess as an active build. Reusable MSBuild workers can remain asleep after their build exits, and later builds can recreate them after a build-server shutdown. - Fix: exclude only sleeping, zero-CPU MSBuild reuse workers whose parent has exited. Active workers, I/O-blocked workers, workers still attached to a parent, and build commands remain busy jobs.
- Check:
test_regress.pysupplies the process census that blocked the measurement, with active, I/O-blocked and parented controls. - Found on: no game: Xcode 27.2 toolchain validation on an M4 Pro.
SPIRV-Cross parse failures
- Symptom: SPIRV-Cross can't parse the SPIR-V (
nullptrexception). - Cause: 2 agl post-effect compute shaders still produce such SPIR-V. Before the compute start-offset fix (Exact program start for the decoder) it was 7: misdecoded code produced the bad SPIR-V.
- Found on: Super Mario Bros. Wonder.
Pixel shader inputs the vertex shader does not write
- Symptom:
Fragment input(s) user(locnN) mismatching vertex shader output type(s) or not written by vertex shaderand the draw is skipped; the host reports[RED] failed to create render pipeline (vertex … fragment …). Offline packing fails withpso_offline: metal-tt failedfor the same reason. - Cause: every pixel shader input must be a vertex shader output. Maxwell attributes are untyped slots: a pixel shader that reads a slot the vertex shader never wrote gets a default, but Metal refuses to build the pipeline. Translating one shader at a time cannot know what the partner reads. The offline archive exposed a second omission: prebuild reads both
shader_pairs.tsvand BAHS program variations inpso_pairs.tsv, but padding read only the first table. - Fix:
dmsh_build.pyreads both pair tables and gives each vertex shader the outputs its partners read but it doesn't write, asfloat4(0, 0, 0, 1) (vs_pad). A profile withoutpso_pairs.tsvtakes the split's copy beside the package, as the archive builder does. The union controls pixel-before-vertex build order and shader cache dependencies (Shader cache key covering the pairs); the profile input stamp includes itspso_pairs.tsv, and the NSP script's shader reuse key includes the generated fallback. Padding precedes the depth, shadow-input, pulling and geometry-capture variants. Rebuild shaders and the host for the new chain. The host caches failed pipelines and reports each once with its vertex / fragment keys; before that, every draw retried the failing compile. - Found on: Super Mario Bros. Wonder: 331 of 9,043 pairs failed; the opening course used none of them, later levels did (about 11,500 failed builds in one 11-minute session). The missing BAHS table was reproduced on Tears of the Kingdom (#283) and Super Mario Odyssey (#276); their notes keep the pair counts and validation.
- Check:
dm/gfx/tests/test_dmsh_pairs.pycovers both table locations, union/deduplication, defaults and cache dependencies; Metal compiles the generated sources for Mac and iOS and builds an archive with regular and pulling vertex entries in both depth modes.test_nsp_mac.pychecks fallback invalidation and progress ordering;test_nsp_incremental.pyregenerates a missing fallback. Check all pairs offline after a game build (recipe in 05).
Pixel shader inputs the mesh shader does not write
- Symptom:
[RED] task / mesh pipeline: task - mesh … fragment …: … is not found in the output from the previous stage, and the mesh draws of that program are skipped. Ocarina of Time's foliage: the point meshes3a6340a04bf09797anda203347bb7bdbd03write only a point size and a position, while their pixel shaders (2a7c48d595feaaeb,cd609edc78b467d8) read generic attribute 5 (pull request #1590). - Cause: the same as for a vertex shader: a pixel shader input no stage wrote reads a default on the console, and Metal refuses the pipeline. Mesh shaders were left out of that rule twice:
shader_split.pyvar_pairspaired only vertex keys with pixel keys, so no table held a mesh shader's partners, anddmsh_meshstage.to_stagemade only the outputs its SPHs enable. It is not point sprite coordinate replacement: the pixel shaders' SPH input maps read generic attribute 5 (not a fixed-function texture coordinate, the only kind the hardware's point sprite select replaces, nor the point coordinate at attribute0x2e0), NVN has no point sprite function (onlynvnCommandBufferSetPointSize), and the same foliage file's triangle meshes leave locations 2, 8 and 9 unwritten that their pixel shaders read. - Fix:
var_pairspairs a mesh key with its variation's pixel key as it pairs a vertex key, anddmsh_build.pypassesto_stagewhat the partners read (partner_inputs, whichvs_paduses too): the locations neither the vertex nor the per-primitive SPH enables become vertex outputs of (0, 0, 0, 1). A mesh shader's pairs feed its build order and cache key as a vertex shader's do.pso_offline.pyplanand the host's prebuild (nvn_mtl.mpre_desc) leave mesh pairs out: mesh pipelines are built at the draw (nvn_geometry.incmtk_pso), not from archive bases. Ocarina'sshader_pairs.tsvwas split again. Of Ocarina's 1,284 mesh pairs (491 mesh shaders), 31 read a location their mesh shader does not write (19 mesh shaders, in the foliage and model files); with the padding Metal built the mesh pipeline of every pair but one. - Found on: Ocarina of Time: the foliage files' variations; pull request #1590 found the failing pipelines and padded at run time on Metal's error text, which this replaces.
- Then: one pair padded past Metal's mesh size: Mesh outputs as wide as their pixel shaders read.
- Check:
test_dmsh_meshstage.py(test_pad_unwritten_pixel_inputs, and a padded point mesh compiled by Metal),test_dmsh_pairs.py(VariationPairs, withDM_GAMEset),test_pso_offline.py.
Mesh outputs as wide as their pixel shaders read
- Symptom:
[RED] task / mesh pipeline: … Total mesh size (35840) exceeds the maximum mesh size allowed (32768), and the program's mesh draws are skipped: Ocarina of Time's foliage mesh626fbf48041cb82bwith pixel shaderc5eb985e769e317f(Foliage.Product.110,#BNSH@0x1b1000#var3), once padded. - Cause: what Metal counts against a mesh's 32 KB is its declared outputs, the largest vertex count times the vertex struct (35,840 = 160 × 14
float4).to_stagedeclared afloat4for every attribute an SPH names: the mesh writes 26 components a vertex, x alone in four attributes and x, y, z in six, but declared 11float4beside its position, and 3 more padded. The hardware's attribute area holds only the written words. - Fix: with its pixel partners known,
to_stagedeclares each output as wide as they can see (_width): the components the shader writes, and a w they read but it does not write, which must hold 1. A Metal fragment input wider than the mesh output it links to reads 0 in the missing components (checked on the GPU:float,float2,float3intofloat4read 0 in the rest,wtoo), the hardware's default for x, y and z.dmsh_build.pypartner_readstakes what each partner reads from its SPH input map (dmsh_meshstage.pixel_reads, byte 0x18 on, two bits a component); a location its MSL declares that the map does not name counts as all four. Without pairs every output stays afloat4. The mesh above comes to 160 × (16 + 4 × 4 + 6 × 16 + 3 × 16) = 28,160 bytes, the 3 padded locations keptfloat4as its pixel shader reads their w. - Found on: Ocarina of Time: all 1,284 of its mesh pairs build their Metal mesh pipelines.
- Check:
test_dmsh_meshstage.py(test_outputs_as_wide_as_read,test_pixel_reads, and Metal compiling narrowed outputs).
Single-stage programs paired with a cover
- Cause: a game that builds one NVN program per GLSLC output and combines vertex and pixel programs per draw with
BindProgramstage bits has its real pairs only at draw time, so the offline build cannot know which pixel shaders a vertex shader must feed. - Fix: the composite-program path (Programs bound per stage) does all the pairing at replay. When every pixel shader input is a plain
float4at fixed locations,shader_split.pypairs every vertex shader with a cover: the fewest pixel shaders whose inputs together are every input any pixel shader reads.vs_padthen gives each vertex shader all of them, and any vertex / pixel combination links. - Found on: 13 Sentinels: Aegis Rim: 838
ProgramSetShadersat startup; every pixel shader input is a plainfloat4at locations 1–9 (the SPH input map, words 6–13, matches the translated MSL inputs for all 375 pixel shaders), so the cover is one shader. - Also found on: Assassin's Creed: The Ezio Collection's AC2: its Scimitar material templates (
.forge) bind vertex and pixel programs apart, so its#SCIMITAR:sources are single-stage too. Before, 8 pairs failed to link (Fragment input(s) user(locn2),user(locn3) … not written by vertex shader), among them the Ubisoft logo movie's draw (7136662acd210955with main'sfb9bddefd9b309ba): a black screen with the logo's sound.
Unwritten components of a written output start as (0, 0, 0, 1)
- Symptom: outdoors dim and nothing casts a sun shadow (every shadow-map lookup fails).
- Cause: a vertex shader may write only part of an output (Link's Awakening writes a world position's x, y and z) while the pixel shader reads the rest (it divides by w). On the hardware the unwritten components read as (0, 0, 0, 1); Ryujinx gets the same by initializing the components the next stage reads when it links stages. The translator's MSL starts every vertex shader with
main0_out out = {};, all zeros, so w was 0, and a fragment shader dividing by it got infinite compare values. - Fix: general:
dmsh_build.py(vs_init) sets everyfloat4output to (0, 0, 0, 1) right after it, and the translated body overwrites what it writes. - Found on: The Legend of Zelda: Link's Awakening (Mac and iPhone): 12,281 of 18,410 vertex outputs never write w. The sun's shadow map (2048×2048, depth 32-bit float) was correct; the surface shaders compute the lookup from a world position the vertex shader passes in
locn24, divided by its w. Found withDM_NVN_TEXRAWon the shadow map, the light matrices fromDM_NVN_CBDUMP, and a hand-edited copy of one surface shader that wrote the compare value and the stored depth as its colour. Compared with forcing the compare to pass (compareFunctionalways): the same brightness, plus shadows from the fences, the house and the trees.
Early fragment tests from the control section
- Symptom: rows of dark dots along contour lines of alpha-tested surfaces drawn after a depth pre-pass (Tears of the Kingdom: the stone lattice in front of the Great Sky Island start, as reported by MacNativeGames ae8f4f4; not reproduced here). On Switch 2, GPU time: every covered pixel of a shader that writes memory was shaded (PRAGMATA's cabin on an M4 Pro: GPU 19.0 ms a frame, p95 frame 64 ms, a quarter of the frames over 33 ms).
- Cause: byte +0x718 of a pixel shader's NVN control section is its early fragment tests flag: the NVN driver's getter is
ldrb w0, [x8, #0x718]in thesdkof all 21 games on hand, and Ryujinx receives it as the 3D engine's EarlyZForce. The translator always passedearlyZForcefalse. Without the attribute, Metal tests depth after a fragment shader that writes memory. In the lattice's G-buffer pass (EQUAL, no depth write, after a LESS pre-pass) that late depth differed by an ulp from the pre-pass along contour lines, the test failed there and the G-buffer kept its clear value. A Switch 2 (NVN2) control section keeps the flag at byte +0x5b: the NVN2 driver reads the pixel shader's flags one byte each at +0x58..+0x62 (ldr x8, [x0, #8]; ldrb w0, [x8, #0x5b]; ret, at the same slot of thesdk's seven vtables, one per control section version), and Ampere's SPH has no such bit (NVK sends it as the 3D methodSET_API_MANDATED_EARLY_Z). Over 70,763 NVN2 pixel shaders of four games, +0x58 is set exactly when the SPH writes depth (word 19 bit 1), and +0x5b on none of those.job_forread the flag in its NVN1 branch only, so no NVN2 shader got the attribute. - Fix: general:
dmsh_build.py(early_fragment_tests) setsearly_fragment_testsin the translation job of every pixel shader whose control byte +0x718 is set.dmsh_xlatepasses it to Ryujinx asearlyZForce, and the MSL entry point is declared[[ early_fragment_tests ]]. A shader whose SPH writes depth (word 19 bit 1) is left as it is, since a test made early would not use the depth it computes. For an NVN2 section the flag is +0x5b (dmsh_ampere.early_fragment_tests), with the same depth-writer rule. - Found on: Tears of the Kingdom: 1,677 of its pixel shaders set the flag, and none of them writes depth. Rebuilding the chain changed exactly those 1,677 shaders' MSL, by the attribute alone. Elsewhere the attribute alone changed 699 of Wonder's 16,268 shaders and 51 of Scarlet's 30,142. Breath of the Wild and ANIMAL WELL set the flag in no shader. Switch 2: Ocarina of Time 746 of 22,352 pixel shaders, Donkey Kong Bananza 2,855 of 13,546, Orbitals 38 of 16,459 and PRAGMATA 6,175 of 18,406 (the last two have no profile here). On PRAGMATA's cabin route the flag is set on all 81 pixel shaders whose only reason to test late is their own store (the streaming feedback's
atomic_fetch_min), on 11 of 84 that discard, and on none of its 75 without side effects or its 5 depth writers; with the attribute GPU time fell to 16.6 ms, p95 to 26 ms and frames over 33 ms to 0.2 %, with no flicker and no coarser textures (PR #1846). - Check:
dm/gfx/tests/test_early_fragment_tests.py(NVN1 and NVN2). - Open: with the attribute, a fragment shader that writes memory gives a picture that varies from run to run on Apple's GPU: Tears of the Kingdom's
8f470f5ce5864df7, a per-fragment visibility flag (2026-10-30; the frame's replays: one digest without the attribute, 3 to 7 in 8 with it).
Dead-code removal dropped the inputs of atomics
- Cause: Ryujinx's
Optimizer.RemoveNoderemoves a dead node, then follows each source whose last use went away into the node that produced it. It did so even when that producer has side effects, such as an atomic or a call whose result is unused. Such a producer stays in the block, but its sources lost their uses, so the next dead-code pass deleted the chain that feeds it, and the atomic read undefined values. - Fix: general:
RemoveNodefollows only into producers without side effects (HasSideEffects). This follows MacNativeGames' translator patch 0002. - Found on: no game on hand so far. Rebuilding the chain changed no shader for this reason in Tears of the Kingdom, Breath of the Wild, Wonder, Scarlet or ANIMAL WELL (94,717 shaders); every MSL change was the early fragment tests attribute.
Dead-code removal dropped a coordinate of a multi-output instruction
- Symptom: a simulation or filter that reads neighbouring texels misbehaves though every constant is right. In the translated MSL a variable is declared with no value and read at once (
int _139; int _141 = _139;), used as a coordinate. On Ocarina of Time: grass whose blades shift at 10 Hz, with a 6-frame cycle in the depth buffer and a wind velocity texture of strong stripes. - Cause: the same walk as the entry above.
RemoveNodealso followed a producer with another destination still in use. An image read with a dead.xand a live.ystays in the block, but its coordinates lost their use, and the next pass deleted the chain computing them. So the read took an undefined coordinate. Ocarina of Time's divergence step04942f42cae10d0fread itsy - 1neighbour at a garbage row, so the wind's pressure solve never settled. - Fix: general:
Optimizer.csRemoveNodefollows only a producer all of whose destinations are unused (DestHasNoUses). A chain change. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py DeadChannel. - Found on: The Legend of Zelda: Ocarina of Time: 8 of its 42,845 shaders, among them the wind solver and two NDSR upscaler variants. Mario Kart World: 3 compute shaders, noted open earlier.
Position invariance across shaders
- Symptom: the ground kept stale 32×32 blocks where the G-buffer draw failed the depth test: blocks of a stale image where a depth pre-pass and a later pass with other vertex shaders meet (Odyssey: 32×32 blocks on every fourth frame). With mesh shaders: white shapes on plants for single frames, at other places each frame while the leaves move (Ocarina of Time).
- Cause: a game may draw the same geometry with two programs and rely on identical depth, for example a depth pre-pass and then a less-or-equal G-buffer pass. Maxwell evaluates identical position math identically; Metal only does for outputs marked
[[invariant]](the translation marksgl_Position) when compiled with-fpreserve-invariance. Without it, Metal compiled two vertex shaders' identical position math to slightly different depths, so fragments of the second pass failed a less-or-equal depth test against the pre-pass and those pixels kept the previous content. - Fix:
dmsh_build.py(Mac) andios_metal.py(iOS) pass-fpreserve-invarianceto every compile. A mesh shader's position is marked too: the mesh stage wrapper (dmsh_meshstage.to_stage) declares[[position, invariant]], as the translation does forgl_Position. - Found on: Super Mario Odyssey (Mac): the Cap Kingdom ground. Presents 4k were brighter and blocky, 4k+1 and 4k+2 clean, 4k+3 partly blocked, repeating to the decimal across runs. The blocks were already in the HDR target when the G-buffer pass ended, and only with the ground's material (
b6384a85afd3ef94) drawn. In some frames the game first draws a depth pre-pass (alRenderDepthOnly) for objects its occlusion queries report visible (the queries rotate through three slots, hence the cycle), then draws the G-buffer with other vertex shaders and depth test less-or-equal, without clearing the colour targets. The Legend of Zelda: Ocarina of Time (Mac): the foliage in Kokiri Forest is drawn twice by two different mesh shaders, a depth pre-pass (depth LESS, no colour) and a colour pass with depth EQUAL and no depth write. Pixels where the colour pass missed EQUAL showed white for one frame; how the white reaches the picture was not traced (the scene target's clear value, alpha 0, is the likely source). Without the mark the wrapper's position was a plain[[position]]. With it: no flashes in five 121-frame windows on an M4 Max (14 on main), none in 240 frames at a flashing flower on an M4 Pro. - Note: ruled out on the way: the TBDR optimizations, same-pass feedback, the present path. Evaluating the game's conditional rendering on the CPU from earlier frames' results made it worse (the condition belongs to the same frame on the GPU), so the host still ignores the condition there and draws.
A NaN colour under a zero blend weight
- Symptom: white clouds over the ground, coming and going (Ocarina of Time: over the ground mist between Kokiri Forest and Hyrule Field, and over the ferns at the camera in Kokiri Forest while they sway). The scene target holds NaN pixels after a fog or lighting pass and bloom spreads each into a white blot; dropping that pass removes them.
- Cause: NVIDIA's float blender has an option, "zero times anything is zero" (
SET_BLEND_FLOAT_OPTION, method 0x670 of the 3D engine, bitZERO_TIMES_ANYTHING_IS_ZEROin NVIDIA's published class headers), and NVN's driver switches it on in its start-up command list: the word0x80010670(an immediate write of 1 to that method) is in thesdkmodule of Ocarina of Time (sdk+0xbb81ac, among other immediate writes) and of 12 of 14 other games looked at. A blend term whose weight is 0 is then 0 whatever the colour, so a pixel shader may write a NaN colour with alpha 0 under SRC_ALPHA / ONE_MINUS_SRC_ALPHA blending, its way of adding nothing to that pixel, and the target keeps its value. Apple's blender multiplies as IEEE does and stores NaN (measured on an M6: NaN, +Inf and -Inf at alpha 0 all store NaN; only a factor of ZERO itself leaves its term out), which every later pass reading the target carries on. It is not Direct3D's rule: Direct3D 11.3's specification (17.5) wants NaN kept through blending, 0.0 weights included. The NaN itself is the game's arithmetic, translated exactly: Ocarina of Time's mist shader averages hit positions over a layer whose density is 0 there, a positive hit count with a weight sum of 0 (1/0 × 0), and its FMULs carry no.FMZ. - Fix: the rule is the blender's, so it follows the draw's blend state.
dmsh_rewrite.pyblend_zerogives every pixel shader with afloat4colour output a guard before each return ofmain0and a word from the host at fragment bufferDMSH_BLEND_BUFFER, two bits per colour output; the build runs it before it makes the other entry points, which callmain0's body and take its parameters, so all of them have it. The host (nvn_mtl.mbz_word,bz_bind) sets an output's bits for a floating-point target that blends by a sum or difference with a source colour factor of SRC_ALPHA (zero where alpha is 0) or ONE_MINUS_SRC_ALPHA (zero where alpha is 1), and whose destination factor does not read the source colour. There the guard returns a non-finite rgb as 0, what the zero weight makes of it. With blending off, MIN / MAX, another factor or another target format the bits are 0 and the colour is returned as it is: NVIDIA stores that NaN or Inf too. A finite colour and the alpha are never changed.DM_NVN_BLEND_ZERO=0gives 0 for every draw. A draw whose pipeline maps its outputs to other attachments (a pass that reads its targets from the tile: physical target i holds outputlmap[i]) takes both words under that map, as its pipeline's blending does:draw_clearsg_pso_lmaponce it has the pipeline, so it keeps a copy and binds the fragment state itself (alpha test, both words, logic operation) after the shader's arguments, passingbz_bindthat copy. Until thenbz_bindran insideencode_args, after the clear, and read the words as for an unmerged pass, and an output drawn into a float target at another attachment number got 0 and kept its NaN; no draw on main maps an output to another number today (fb_tile_planmaps each to itself), so no game's picture changed. - Check:
python3 dm/gfx/tests/test_dmsh_blend_zero.py(the guard and the word in every entry point throughdmsh_side.unitanddmsh_fetch.fold, whatdmsh_entry.fs_uintreads of a shader unchanged, the rule, each text compiled by Metal's compiler);make -C dm/gfx/tests GAME=<id> check_t_blend_zerodraws NaN, ±Inf and 2 at alpha 0 and 1 through the replay into an RGBA16F target under seven blend states and reads it back, with the rule and withDM_NVN_BLEND_ZERO=0(Apple's blender as it is). It also draws a merged pass (output 0 to attachment 1, an RGBA16F target beside an RGBA8 one) and reads back that the NaN and Inf of alpha 0 are zeroed, with the wordsbz_bindbound (g_bz_last). - Found on: The Legend of Zelda: Ocarina of Time (Mac, issue #1839, PR #2030): the half-resolution mist shader
5ad65c0eefd09c7fwrote NaN into its RGBA16F target (about 15,000 to 229,000 pixels a frame in three reports), the mist composite888c1068ac8f7043carried it into the R11G11B10F scene and bloom made the clouds. Not reproduced on the Mac this was written on (an M6): the village route from the reference save and two passes over the village floor with the camera low and high gave 0 non-finite pixels withDM_NVN_BLEND_ZERO=0too (DM_NVN_MAGSCAN), so the fix is checked there by the replay test, in the mist's blend state and target format, and by the word being set in play (output 0, on more than 131,000 passes or states of one run). Its cost, standing on the village deck with the resolution fixed (DM_NVN_GPU_TS=submission), three runs a side: GPU p50 10.86 ms on main's libraries, 10.95 ms with the guard in every pixel shader (10.91 ms with the word 0 for every draw), submit and present 5.67 against 5.73 ms, 60 fps both; the difference is about the spread between runs (0.06 and 0.11 ms). - Open: a NaN or Inf already in the target under a zero destination weight, and a non-finite weight on a colour of 0, which a shader cannot see; the alpha channel's own weights; the Vulkan and OpenGL shader paths (whether those drivers set the option is not known).
- Note: found with
DM_NVN_SNAPRAWandDM_NVN_TEXSNAP(raw floats of every colour target after chosen passes of one frame) andDM_NVN_MAGSCAN, then the one shader instrumented beside the library (DM_MSL_DIR): the first NaN at1/w × vwithw = 0, every NaN texel stored with alpha 1 (source alpha 0). Ruled out on the way: the fog volumes (finite), FMZ handling (none in the code), stale uniforms (DM_NVN_UB_DEFER=0,DM_NVN_UBP_CHECK), the depth test,-fmetal-math-mode=relaxed. The driver's command word was found by scanning the modules for writes to method 0x670; the code that sends the list was not disassembled, and no console was measured.
The blend helper's output reference on iOS
- Symptom: pixel shader compilation fails with
reference type must have explicit address space qualifieratdm_blend0(main0_out& dm_o, ...): every iOS build, and a Mac build made on macOS 26. A Mac build made on macOS 27 compiled, so the fault passed where it was written. - Cause:
blend_zerogenerated a reference without an address space (the output is a local variable of the fragment function). Metal's language version follows the deployment target: the iOS build names iOS 18, whose language requires the qualifier, and the Mac compile named none, so it took the build Mac's system. Measured with Metal front end 32023.922 on macOS 27.2, a shader with that signature: it compiles with no minimum and with iOS 27.0, and fails with-mmacosx-version-min=26.0,15.0and-mios-version-min=18.0. One chain version therefore gave different results on two Macs. - Fix:
dmsh_rewrite.pydeclares the helper's output parameterthread main0_out&; the helper's behavior is unchanged. Every Mac compile of a game's shaders now names the Mac host's minimum macOS (MACOS_MINindm/mac/min_os.mk, read asdmsh_chain.MAC_MIN):MAC_METAL(then indmsh_build.py, now indmsh_chain.py: Tests compiled with copies of the Mac compile),vk_shaders.pyandgl_shaders.py, as the host's own libraries already did (The host's own shaders compiled from source at run time). The file is part of the chain version and the flag is in each shader's cache key.test_dmsh_blend_zero.pycompiles the plain, integer-output, side and readable-tile variants with both targets' flags, so the Mac case fails on any Mac. - Found on: The Binding of Isaac: Rebirth: all 10 pixel shaders failed on iOS, while its 9 vertex shaders and all 19 Mac shaders compiled (macOS 27). Ocarina of Time: 22,296 of 42,848 Mac shaders failed on two Macs with macOS 26 (GitHub issue #2272); 42,848 built there with the qualifier (a reporter's run).
Tests compiled with copies of the Mac compile
- Symptom: three translator tests (
test_dmsh_gather_offsets.py,test_dmsh_wrapv.py,test_dmsh_raw_last.py) failed with aNameErroror a non-literal value once the Mac compile named its deployment target, and three others compiled with flags the build does not use:test_dmsh_tg_fence.pywithout-fwrapvand the deployment target,test_image_atomic_bounds.pywithout-O1,-fwrapvand the deployment target,test_shader_pch.pywith a hand copy that would not follow a change. - Cause: the Mac compile command,
MAC_METAL, was a line ofdmsh_build.py, a script that reads its arguments and starts a build when imported, so tests took the line out of its source and evaluated it (which broke when the line nameddmsh_chain.MAC_MIN_FLAG) or copied its flags. - Fix:
MAC_METALis defined indmsh_chain.py, beside the deployment target it names, with each flag's reason; that module imports without side effects beyond readingdm/mac/min_os.mk, and both files are in the chain version.dmsh_build.py(its record and its direct run) and every test takedmsh_chain.MAC_METAL, andtest_image_atomic_bounds.pytakesios_metal.METALfor the iPhone. The command is unchanged, word for word: a full build of Bastion on both chains gave byte-identical Metal sources and libraries for the Mac (170) and the iPhone (170), the reflection files differing only in the chain name.test_mac_metal.pychecks the command, its deployment target and thatdmsh_build.pykeeps no copy. Since the step 15 audit, an import ofdmsh_chain.pyreads nothing:MAC_MIN,MAC_MIN_FLAGandMAC_METALare its module attributes (__getattr__, PEP 562), read frommin_os.mkwhen used, sopr_areas.pyimports main's file for its list (FILES) instead of running it, and its test no longer copiesmin_os.mkinto its fixture (test_mac_metal.pyimports the file alone, with nomin_os.mk: the list is there, the flags raise). The iPhone's deployment target and math mode areios_metal.py'sIOS_FLAGS, whichvk_shaders.py,gl_shaders.pyand two tests take instead of their own copies; the commands are unchanged. - Found on: no game; found when
f75ac06echanged the line and in a review of the shader tools.
gl_FragCoord.z against the depth stored for its own surface
- Symptom: dark specks flickering in a ground mist, a few pixels each, at different places every frame (Ocarina of Time in Kokiri Forest; the console shows none). Dropping the mist removes them, as does dropping its depth-only pass.
- Cause: a pixel shader tests its fragment against a depth image of the same surface, which an earlier pass stored. The mist's fragment shader
5ad65c0eefd09c7fdiscards whengl_FragCoord.zis above the depth its depth-only pass (fragment4757b5b373a5406e, the same geometry) stored, so a fragment should never reject its own surface. NVIDIA stores exactly the z a pixel shader reads. Apple's GPU stores a value at or below the fragment's[[position]].z, with any vertex or mesh shader and-fpreserve-invariance. On an M4 Pro the stored value is lower at 0.2–3.8% of a triangle's pixels and never higher. An M6 stores exactly the fragment's z, as NVIDIA does (check_t_zsnap: 0 of 718,400 pixels, 2026-11-09), so the gap belongs to the GPU generation; other generations are not measured. The gap is at most one ulp of z plus 2^-23 of the depth's step across a pixel (fwidth(z)). It happens even for triangles of constant depth. With the stored depth one ulp under, the mist discarded its own surface there. The specks went when the depth-only pass wrote[[position]].zas its depth, and the mist's own test was the failing one (a raw dump of its 768x432 target held 41,226 zero pixels). - Fix: general, in the chain:
dmsh_rewrite.pyfrag_z_snap. Where agl_FragCoord.zread inmain0meets a value read from a texture in one comparison, through any arithmetic on either side, the read becomesdm_zsnap(gl_FragCoord.z, value, fwidth(gl_FragCoord.z)). That returns the texture value when it lies in[z - ulp(z) - 2^-20 fwidth(z), z)and z otherwise. A comparison of a fragment with its own surface's stored depth then sees equality, as on NVIDIA, whatever its operator or the scale on each side. A surface outside that window, constants, uniforms, and z read in other functions are unchanged. Not chosen: making the depth-only pass write[[position]].zas depth. That moves its depth test after the shader, and a stored depth that differs from the rasterizer's fails anEQUALpass on the same geometry (Metroid Dread's G-buffer after its prepass). - Check:
python3 dm/gfx/tests/test_dmsh_zsnap.py(the rewrite on the translator's shapes) andmake -C dm/gfx/tests GAME=<id> check_t_zsnap. The GPU test draws 2,000 triangles depth-only, then reads the stored depth back in a second draw of the same triangles. Five sets: perspective, w = 1, constant depth, depth < 0.001, depth > 0.999. Throughdm_zsnapno pixel is above its own stored depth (plain z: 9,511 of 718,400 pixels on an M4 Pro, 0 on an M6, where the rewrite changes no result), and a copy 4e-6 farther stays farther at every pixel. - Found on: The Legend of Zelda: Ocarina of Time: 39 of its pixel shaders compare z with a texture value, all rewritten. They are the mist's 4 and its foliage's
z * c[188].w > d * c[188].w. Elsewhere the rewrite changes 158 of OCTOPATH TRAVELER 0's shaders and 122 of Minecraft Dungeons II's, bothz < d, which the gap left as NVIDIA's. It changes none of OCTOPATH TRAVELER II's 7,005 shaders that read z, nor Three Houses'.
iOS math mode (relaxed)
- Cause: the translated shaders reproduce Maxwell's NaN behaviour with
isnanselects (8,337 of 12,809 use them), and the default fast mode allows the GPU compiler to assume there is no NaN. - Fix: the iOS libraries are compiled with
-fmetal-math-mode=relaxed(dm/ios/tools/ios_metal.py; the Vulkan and GL libraries invk_shaders.pyandgl_shaders.pytoo). Relaxed keeps fast math's reassociation but not that assumption. - Found on: listed among the mechanisms first met in Super Mario Bros. Wonder; the source gives the 8,337 of 12,809 count without naming the game.
Mac math mode (relaxed)
- Symptom: the Mac draws the menus, but every 3D object is black. The colour target before tonemapping shows the full scene. The tonemap pass writes zeros.
- Cause: the tonemap's dither term multiplies by
as_type<float>(0x7f800000u), the infinity constant from the Maxwell code, and uses anisnanselect. Metal's default fast mode lets the compiler assume inputs and results are finite. It folded the select and the tonemap wrote zeros. - Fix:
mac_metal()indm/gfx/tools/dmsh_chain.pypasses-fmetal-math-mode=relaxedfor every Mac NVN shader, matching the iOS compile. - Found on: Godzilla: Destroy All Monsters Melee Remastered (
0100A00026D70000, update 131072). PR #3024 records the gameplay checks.
Front end at -O1: Apple's control-flow lowering
- Symptom: making a pipeline archive prints
Max Unstruct ID 758 in function agc.main in shader 13941 exceeds supported limit, and one pipeline takes many minutes, inmetal-ttoffline or in the host's prebuild on the device (Preparing pipelinesholding one count for minutes). The line is a note, not an error:metal-ttgoes on, exits 0 and writes that pipeline into the archive. - Cause: at the front end's default
-O2,CorrelatedValuePropagationand theSimplifyCFGafter it fold a translated shader's repeated tests of one value into switches whose cases jump past their own join, so nestedifs become an unstructured graph. Apple's GPU backend lowers unstructured control flow with per-function IDs; past its budget (255 onapplegpu_g13s, the check inlibapplegpu-nt.dylibof AIR-TT 32023.921 picks 255 or 65,535 by a capability not yet characterized), it prints the note and lowers the function another way that is far slower and larger. At-O1those two passes do not run; the backend still optimizes the AIR itself, so ordinary shaders come out the same. - Fix:
dmsh_build.py(Mac) andios_metal.py(iOS) compile with-O1. - Found on: Super Mario Odyssey, issue #276: the float body of
alRenderMaterialUber(fragment007d7e411ef14ebd, 16,227ifs in one function) took 24.6 minutes and 17.3 MB ofg13scode at-O2, 31 s and 1.3 MB at-O1. Its-O1graph still goes past the budget (642), at that small cost. - Check: random samples of archive bases from seven games (Odyssey, Tears of the Kingdom, Breath of the Wild, Kirby, Luigi's Mansion 3, Wonder, Pikmin 4; 22 to 400 each) compile at
-O1to vertex and fragment code within a few percent of-O2(Odyssey 400 bases: −0.9% / +0.01%; TotK: +0.1% / −1.0%; Kirby: −3.1% / +0.07%), with noMax Unstruct IDnote at either level, and the front end is faster. Odyssey's fullg13sarchive of 32,864 bases builds in 15.6 minutes (exit 0); its Cap Kingdom frames 4,200 to 6,600 match-O2except for scattered differences of at most 3 of 255 in three of nine frames, and their GPU time per frame (DM_NVN_GPUPROF=every:150, three runs each on an M-seriesg18g) has medians of 4.76 to 5.05 ms at-O1and 4.75 to 4.83 ms at-O2, within run-to-run noise.
Specialized second functions in the offline pipeline archive
- Symptom: the Mac app's (or the iPhone build's) pipeline archive step stops in its first group with
[RED] pso_offline: metal-tt failed for applegpu_<arch> (exit 1): applegpu-nt: error: cannot find private metadata at offset '8' in '…/<key>_bp.metallib', and the app is packed without an archive, compute pipelines included. The host's prebuild then makes every base on the first start. Only a game with the near = 0 depth mode (depth_mode zero) whose vertex shaders declare the border corrections' constant. - Cause:
pso_offline.pyspecializes a function that declares the border corrections' constantdm_border_offas the host's prebuild does (HOST_CONSTANTS,pre_fninnvn_mtl.m).metal-tt32023.922 specializes only a library's first function: it does not find a later function's private metadata (offset 8 is the second function's entry), also in a library linked by Apple's ownmetallib. The same function with the library's two functions swapped compiles, and the then-secondmain0fails, so it is the position, not the entry. A near = 0 game asks formain0_z, the second function of each pulling library<key>_bp; Ocarina of Time, where the specialization was first checked, usesmain0, and a pixel library's base is its first function. One failing pipeline fails its group, and a failed group ends the step. - Fix: a workaround for Apple's compiler: a specialized function that is not its library's first is specialized from a library of its own (
needs_cut,cut_entries).real_librarieswrites<library>@<entry>.metallibwith that function alone (dmsh_side.cut, the bytesmetallib --function-namegives) beside links to the group's other libraries. The archive serves the host's lookup through the whole library, as a base is found by its function, not by its library file. The script and the archive key do not change for a game whose specialized functions all come first. - Found on: Bayonetta Origins: Cereza and the Lost Demon (
0100CF5010FEC000, no profile yet; issue #2337,applegpu_g14s: 492 of 4,772 bases); Pokémon Legends: Z-A and Castlevania: Belmont's Curse (applegpu_g16s); Nintendo Switch Sports Resort (04008E001F098000; PR #2371: 2,401 of 11,075 bases, from 124 such libraries); reproduced on an Apple M6, macOS 27.2, compiling a two-function library built by Xcode forapplegpu_g17p. With the fix, Switch Sports Resort's 2,401 bases compiled in 96 s, and 11 sampled bases were found through the whole libraries. - Check:
test_pso_offline.py(test_a_specialized_function_after_the_first_has_a_library_of_its_own, and with Xcodetest_the_cut_library_holds_the_function_alone);t_pso_bundle(a pulling library whosemain0andmain0_zdeclare the constant, archived for near = 0:pre_descfinds itsmain0_zbase and nomain0base; without the fixpso_offline.pyfails).
Tests of one uniform word folded into switches
- Symptom: the Mac app's (or the iPhone build's) pipeline archive step runs for many hours: a group of 1,000 bases runs past its time limit, and
compile_splitleaves out single pipelines that each ran past theirs ([RED] pso_offline: applegpu_<gpu>: left out of the archive, the device builds it), whileair-ntgrows past the Mac's memory and swap fills. Alone, such a pipeline does not finish in 10 minutes and takes 10 to 13 GB, where the build before took seconds. On the device, the same pipelines would holdPreparing pipelinesfor as long. - Cause: a game's material shader chooses a branch by a uniform word, and the translator writes the GLSL switch as Ryujinx's structurizer gives it: one test of the word for each case, with flags for the fall-throughs and each case nested in the next (
bool _6240 = as_type<int>((*spvDescriptorSet0.fp_c5)._m0[16].w) != 102; if (!_6240) { … }). The Metal front end's SimplifyCFG (which runs at -O1 too) folds a chain of blocks that each hold only such a test of one value into aswitch, whose cases jump into the nested blocks past their joins, and Apple's GPU compiler (applegpu-nt, AIR-TT 32023.922) takes that graph for hours. Turning the switches back into compares (metal-opt -passes=lowerswitch) does not help: the graph is the cost, not the instruction. Before the host bounded reads at fixed offsets (chainb7249b1c2b66), each read's bounds test sat in the test's own block, so no chain was folded; with the reads plain, Nintendo Switch Sports Resort's pixel shader692008b305ce264fhas 42 switches in its IR (none before) and7c2becb054a5376566 (6 before). - Fix: every game, a chain change.
dmsh_rewrite.uniform_tests, called bydmsh_build.pyafter the other rewrites (and on the geometry stage and its reader), reads a word of a game uniform slot (c3and up; the driver's banks are left as written) that the shader tests for equality with an integer constant more than once throughdm_uword, a volatile load of that word for each test (as_type<int>(dm_uword((*spvDescriptorSet0.fp_c5)._m0[16], 3)) != 102). The front end can neither merge one test's load with the next nor move it out of its block, so it folds no chain. A uniform load per test is less than the bounds test each read had before. A word tested once, a test against a variable, and an ordering test are left as they are. - Found on: Nintendo Switch Sports Resort (
04008E001F098000): with chainb7249b1c2b66the Mac app's archive ran 15 hours in its first group (vertex1f0649e274faa626,1552eae0ea641bcdand24ce8042ec8edfffwith pixel7c2becb054a53765, vertex2265ca4db20439bfwith pixel692008b305ce264f, each left out after about 30 minutes alone), where chain592225da745bhad built 1,000 bases in about 3 minutes. Measured alone withmetal-tt32023.922 (applegpu_g14s, macOS 27.2, M2 Max with 32 GB),2265ca4db20439bf+692008b305ce264f: chain592225da745b7.4 s and 0.25 GB; chainb7249b1c2b66stopped at 10 minutes and 13.4 GB; that chain's vertex library with the old pixel library 4.2 s, the old vertex library with the new pixel library stopped at 5 minutes and 10 GB; the old MSL with the fixed-offset bounds tests taken out stopped at 5 minutes; the same with the tests kept only on the 910 reads that feed an equality test, 3.1 s; withuniform_tests, 6.3 s and 0.21 GB.1f0649e274faa626+7c2becb054a53765withuniform_tests: 11.5 s and 0.45 GB. - Check:
python3 dm/gfx/tests/test_dmsh_uniform_tests.py(the forms it rewrites and leaves; with Xcode, the plain shader's IR has a switch withdmsh_build.py's andios_metal.py's commands and the rewritten one none).
Bracket nesting past the front end's 256
- Symptom: the shader build prints
fatal error: bracket nesting level exceeded maximum of 256and<key>.metal: does not compile, and the shader is left out. - Cause: a translated expression nests deeper than the Metal front end's default limit of 256 brackets. Ocarina of Time's compute shaders
1f78730053feb036ande172bd7ec218ab8e(3.5 MB of MSL each) reach 259. - Fix: every library compile passes
-fbracket-depth=1024(dmsh_build.pyMETAL_DEPTH,ios_metal.pyDEPTH). A source within the old limit compiles to the same bytes with the flag, on macOS and iOS. Like the precompiled header, the flag is not in the compile records, so the Metal cache keeps every library already compiled. - Found on: Ocarina of Time (Switch 2,
0400486024DEC000, PR #1299); both shaders now compile. - Check:
test_shader_pch.py(BracketDepth: 300 nested brackets fail without the flag and compile with it, the test shaders' bytes are unchanged, and both builds take the same depth).
min, max and clamp with a NaN operand
- Symptom: the half of Mario facing the camera's left was white (GitHub issue 72, on an iPhone).
- Cause: spirv-cross writes
FMin/FMax/FClampasfast::min/max/clamp, which leave a NaN operand's result to the GPU. Maxwell'sFMNMXreturns the other operand and its saturation gives 0, as Metal'sprecise::functions (IEEEfmin/fmax) do. Plainmax/min/clampcompile to thefast_intrinsics in every Metal math mode, relaxed included (iOS math mode (relaxed)). Galaxy's GX lighting normalizes light directions the game leaves at (0, 0, 0) (the key and fill lights of its characters) and takesmax(0, dot(ldir, NaN))as the spot term: 0 on the M4 Pro with either function, so the attenuation is 1. The fill light sits at the camera's left in view space, so its terminator runs down the middle of a character facing the camera. - Fix:
dmsh_build.py(precise),vk_shaders.pyandgl_shaders.pywrite theprecise::functions instead (every game). - Found on: Super Mario Galaxy 2 (GitHub issue 72). The NVN chain had about 124,000
fast::max, 98,000fast::clampand 41,000fast::minin Paper Mario: The Thousand-Year Door, none guarded by itsisnanselects.
Integer fragment outputs declared by hand
- Superseded (2026-11-16): every pixel shader has the typed-output entry point (Typed outputs for every pixel shader), and the six profiles' rows below were removed; the pipeline red line prints a row only for a shader whose
main0has a shapefs_uintdoes not know, where the root-cause fix is teachingfs_uintthat shape. The text below is how it was. - Symptom: a pipeline red line for a float output meeting an integer attachment (the red line prints the row to add); a BC encoder's pipeline fails.
- Cause: with no PC version the translator has no output types and declares every output float, and Metal refuses a pipeline whose float output meets an integer attachment. A scan for outputs built from integer operations was not trusted: the translated code keeps float bits in integer variables (register reuse), so such a scan cannot tell an integer output from raw float bits stored into a float target.
- Fix: the profile's
shader_facts_manual.tsvdeclares such outputsuint. When another one fails, the pipeline red line prints the row to add. Shaders that write an output from integer bits now also get integer entry points (Integer entry points for integer colour outputs). - Found on: The Legend of Zelda: Breath of the Wild (agl's BC4 encoder
8e2cc2671cae6020and its twin for a 2D source93aa5e22a8202409, whose failure showed up in an iPhone run); The Legend of Zelda: Tears of the Kingdom (the BC4 encoder0544282c162305dband the Ultrahand maske3fb0bb58a691e10, R8Uint, found by PR #11; the Mac route does not reach it); Pokémon Legends: Z-A (two system pixel shaders write an ID into anR8_UItarget on the character creation screen); DRAGON QUEST VII Reimagined (one global shader writing anR8Uinttarget, Unreal Engine 4.27 shader code archives). - Note: the compressed render target side is in Compressed textures as render targets through an uncompressed shadow.
A pixel shader's depth after a partly written target
- Symptom: a pixel shader that writes depth and only some components of a colour target writes the wrong depth: in the translated MSL,
gl_FragDepthtakes a value the shader computes a step before its last one, or a colour. - Cause: the colours are read four registers per render target with any component enabled (component c of the n-th such target in R(4n + c)), then comes the sample mask register, then the depth.
TranslatorContext.GetDepthRegistercounted enabled components instead, which agrees only when each enabled target has all four. With OmapTargets 0x10f (RT0 RGBA, RT2 R) the shader computes its depth into R9,R6 = 1 / -(z * a + b)then two constant adds, and R6 was read. - Fix:
GetDepthRegisterreturns 4 × the enabled targets + 1. A chain change. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py DepthRegister(R6 0.25, R9 0.75: the old translator writes 0.25). - Found on: The Legend of Zelda: Ocarina of Time: 46 of the 126 depth-writing pixel shaders in its shader package (mask 0x10f ×24, 0x100 ×16, 0x3f ×4, 0x30 ×2), 16 of them in its seen shaders, among them agl_common's depth pass
3a4a0270fc35b848, whose depth now takes the step after R6 too,(R6 * c3[32].z + 1) * c3[32].w. Its effect on the picture has not been compared. No other local game has such a shader: the 1,105 depth-writing pixel shaders of seven Switch 1 games enable whole targets. Found by the flaviopz fork.
Integer entry points for integer colour outputs
- Symptom:
failed to create render pipeline … output of type float4 is not compatible with a MTLPixelFormatR32Uint color attachment(orMTLPixelFormatRGBA16Uint); every draw into the target skipped. - Cause: with no PC version the translator types every fragment output float, and the shaders write bit-packed integers through
as_type<float>. A hand-written row per shader (shader_facts_manual.tsv, Breath of the Wild's way, Integer fragment outputs declared by hand) does not scale. - Fix:
dmsh_entry.pyfs_uintgives a pixel shader a second entry point,main0_u(since 2026-11-16 every pixel shader, with signed members too: Typed outputs for every pixel shader; the text below is how it began). It was given when the shader writes an output from integer bits (directly or through a float local that holds them), nothing but constants (a clear drawn into an R32Uint target) or nothing but flat inputs passed through. Its output struct holds two members on each float colourn, the float and the unsigned integer vector of the same bits, each present by a bool function constant (DMSH_UINT_FC + n,dm_ui<n>), and it returns each colour as whichever is present: the hardware writes the output's bits to an integer target whatever the shader computed, so the copy is exact. The host specializes it with the pipeline's integer targets (pso_uint_mask,uint_fn: one function per set, kept), whether all of them are integer or some, and the alpha test and logic operation entry pointsmain0_u_aandmain0_u_lthe same way (at_fn,lo_fn). A shader withoutmain0_ukeepsmain0and the red line. - Found on: Luigi's Mansion 3: about 1,400 pixel shaders writing its G-buffer of two integer targets (R32Uint, RGBA8Uint), so every scene draw was skipped. Pokémon Sword: 10 pipelines as the opening's stadium loads; the scene shaders write colour 0 and 2 as floats and colour 1 from integer bits into an RGBA16Uint target (colour 1 in all 336 of Sword's). Silver Pines: URP's rendering-layers mask, an R8Uint target beside float outputs (colour 1 forward, 4 and 5 deferred), in 9,720 pixel shaders; without it only the fog drew. Trails in the Sky 2nd Chapter: its G-buffer float at colour 0 and integer at colours 1 to 3.
Integer outputs told by the pipeline's targets
- Symptom: a deferred scene with part of its materials unlit or black: grass, ground and trees dark while wood and characters look right, whole areas of a map black. There may be no red line. A texture dump shows an integer G-buffer target (
fmt=73, RGBA8Uint) holding only zeros, and the lighting pass reads it. Or[RED] shader … writes colour target …, an integer format, as a float. - Cause: a G-buffer of float and integer targets needs a pixel shader to return some outputs as floats and others as integers. Until 2026-11-13 the build chose which from the shader's code and gave such a shader fixed mixed entry points (
main0_m, thenmain0_n), and the host took one only when the pipeline's integer targets were exactly its set. The translator keeps registers in integer locals, so a plain float colour reaches its output as integer bits too, and the code says less than the pipeline does. A shader with no entry point for its pipeline keptmain0, whose float output met the integer attachment: a pipeline built on its own is refused for that, but one specialized from a Metal 4 base is not, and the target stayed zero with no error. Kirby Star Allies' G-buffer is RGBA16F, RGBA8 sRGB, RGBA8Uint, RG11B10F: 283 of its pixel shaders got the mask 0b111, 8 got 0b101 and 396 none. Following each write back through the locals (int_outputs) fixed Kirby, and Trails in the Sky 2nd Chapter then needed four more rules in turn, each found by its red line in play: a uniform word written straight into an output, outputs of nothing but zeros, a register value every branch overwrites, a texel read withread(). Each was beside integer outputs into integer targets, and each rule moved other games' masks. - Fix: the pipeline's formats say which outputs are integers, as they do on the hardware:
main0_ureturns each colour as a float or as integer bits by a function constant, and the host specializes it per pipeline (Integer entry points for integer colour outputs). No rule reads which outputs hold integers any more; the build only decides whether a shader getsmain0_uat all. Over five of the local games' libraries that givesmain0_uto the shaders that had it before and a few more (PRAGMATA 403 of 15,877 pixel shaders, Pikmin 4 119, Luigi's Mansion 3 5, Fire Emblem Engage 8, none in OCTOPATH TRAVELER II, Diablo II: Resurrected, Hollow Knight: Silksong or Bastion), and withmain0_mandmain0_ngone, fewer entry points in all (PRAGMATA's 8,578main0_uand 3,212main0_mbecame 8,981). - Found on: Kirby Star Allies: 687 pixel shaders whose integer target stayed zero. Trails in the Sky 2nd Chapter: the red line from five shaders in turn (
10cd95a2a310ea8c,979fd4d4d4bd7615,b09f3ac96129e558,96ec090803707686,aa682f8e32981529). - What made a shader an integer writer (until 2026-11-16, when every pixel shader got
main0_u: Typed outputs for every pixel shader): a float local that holds a register's bits counts: PRAGMATA's visibility pass writesfloat _439 = as_type<float>(int(gl_PrimitiveID))and the depth to an RG32Uint target, and without it no shader gotmain0_u([RED] task / mesh pipeline failed: … output of type float4 is not compatible with a MTLPixelFormatRG32Uint color attachment). So do writes after an early return: four of those shaders (a9c1f9ea0c76a54c,1282ed0df15021c7,a88532b3a2bbc36f,bfce48e3c0debea2) return zeros early, after a discard, and write the primitive id and depth after that; read only up to the firstreturn out;, they got none, and the whole 3D scene was black behind the UI.
Integer entry points for flat inputs passed through beside constants
- Symptom: an Unreal landscape drawn from a runtime virtual texture is one flat lit colour on the Mac (green grass with no texture) and a grid of repeating tiles on an iPhone; rocks, characters and everything else right; no red line. A texture dump shows the virtual texture's BC tile caches full and varied, and its page table (R16Uint,
fmt=23, 512x512 with 10 mips, the texture the landscape's pixel shader reads atreg130) holding 255 in every entry: level 15, page address 15, so the sample lands on one texel of the cache. Since this entry,[RED] shader … writes colour target …, an integer format, as a float, and has no integer entry point. - Cause:
fs_uintgave a pixel shader its integer entry point when its outputs were all written from integer bits, all constants, or all flat inputs passed through. Unreal's page table update (global shader17eda07e4bac39f8; its vertex shader478292f0f6d79ae4reads the update records from a texture buffer and packs the page's level and address into a flat varying) writes the flat input's x and the constant 0 to y, z and w: neither rule held,main0kept itsfloat4output, a pipeline specialized from a Metal 4 base was built without an error (Integer outputs told by the pipeline's targets), and the R16Uint target took 255 at every pixel drawn. That entry's red line fires only for a shader that has an integer entry point, so nothing named the shader. - Fix:
fs_uinttakes any mix of constants and flat inputs passed through. The reflection now records which colour outputsmain0declares float (raster.float_colors,raster_facts), and the pipeline path (pso_desc) prints the red line above, with theshader_facts_manual.tsvrow (pso_fout_hint), when such an output meets an unsigned integer attachment and no integer entry point fits, whether the shader has one or none. A chain change. - Check:
python3 -m unittest dm/tools/tests/test_shader_rewrites.py(TypedOutputs: since Typed outputs for every pixel shader every shader gets the entry point, whatever it writes). - Found on: DRAGON BALL: Sparking! ZERO: the landscape of the story battles' stage on an M1 (base v0), and #1889 (an iPhone 17). Rebuilt with the change, the floor shows its dirt, grass and tracks, with no new red line; the iPhone is still to be checked.
Typed outputs for every pixel shader
- Symptom: on the
MTLDevicepath (the iPhone's default)[RED] failed to create render pipeline … output of type float4 is not compatible with a MTLPixelFormatR8Uint color attachmentfor many fragment shaders, and most of the scene missing (black sky, no characters). WithDM_PSO_MTL4=1the same pipelines build from Metal 4 bases and the picture looks right, but[RED] shader … writes colour target 5, an integer format, as a float, and has no integer entry pointstays: the target takes undefined values. A signed integer target (R32Sint, …) is refused the same way, by every shader. - Cause: the class of a colour output (float, unsigned, signed) is its target's: Maxwell writes the register's bits whatever the shader computed.
fs_uintgave a pixel shader its integer entry pointmain0_uonly when its code looked like an integer writer (integer bits, constants, flat inputs passed through), rules each found by a red line in play and each missing the next game: Kirby and the Forgotten Land's 76 shaders writing its R8Uint colour 5 matched none.main0_uhad no signed members, so a signed target had no entry point at all, and the host's red line fired only for unsigned targets. - Fix: every pixel shader of a known shape gets
main0_u, whatever its code writes. Its output struct holds three members on each colourndeclaredfloat,uintorint(scalar or vector): the float, unsigned and signed vector of the same width, each present by a bool function constant (DMSH_UINT_FC + n,DMSH_SINT_FC + n; the float where neither is set), and returns the colour's bits as whichever is present (as_type, nothing converted); a colour of another type (half) or shape stays asmain0has it.main0_ualso holds the fixed-function work Metal lacks, each switched by a constant with its arguments present only then: the alpha test (DMSH_TYPED_ALPHA_FC, on colour 0's alpha before the outputs are typed,dmsh_alpha.test), the logic operation (DMSH_TYPED_LOGIC_FC, on the typed outputs, reading the attachmentsDMSH_LOGIC_FC + nnames,dmsh_logic.parts), and dual-source blending (DMSH_TYPED_DUAL_FC, returning colour 1 as[[color(0), index(1)]]with colours 1..7 absent when colours 0 and 1 share a width and every colour >= 1 is typed, replacingmain0_danddual_want.tsv: A written secondary blend source), so it replacesmain0_u_a,main0_u_l,main0_l,main0_dandmain0_d_a, and one function serves every variant a pipeline asks for.main0_astays, with no constant, so an alpha-tested pipeline of the declared classes needs no specialization at run time. The build cutsmain0_uinto the side library<key>_bx(ps_libraries,entry_u_side,entry_u_alpha,entry_u_logic,entry_u_dualin the reflection), so the base library every shader loads, and the pipeline archive compiles, keepsmain0alone with no function constant. A side library that does not build leavesmain0_uin<key>_b, and one that does not build with it is built without it (entries_lost), as before. The reflection records which coloursmain0declares float, unsigned and signed (raster.float_colors,uint_colors,sint_colors); the host (pso_cls,pso_reads_src1,typed_fn, one function per set of classes and switches, kept) takesmain0_uwhen a target's class is not the declared one, in either direction (afoutfact that declares an output unsigned meeting a float target too), when the pipeline has a logic operation, or when target 0 blends with aSRC1factor, with the alpha test on when the pipeline has one; the side library is loaded once per shader on first need (bx_lib). An alpha test with a logic operation, which no library combined, now draws throughmain0_u(lop_key). The red line now names a shader whose pipeline needs a class it cannot give: one whosemain0has a shapefs_uintdoes not know, with theshader_facts_manual.tsvrow (pso_fout_hint, also on a refused pipeline, only for such a shader). The hand-writtenfoutrows of six profiles went with it (Breath of the Wild's and Tears of the Kingdom's BC4 encoders and Ultrahand mask, Pokémon Legends: Z-A's, DRAGON QUEST VII Reimagined's and FINAL FANTASY RESONANCE's): their shaders takemain0_ulike any other. The BC encoders write bits no float keeps (NaN payloads, denormals) throughmain0's float output, andmain0_ugives them to an integer target unchanged (t_typed_outputs' colour 3). Replaces PR #2807's second entry pointmain0_tfor the same problem. A chain change. - Cost: measured on 200 of Cuphead's pixel shaders with a cold compile cache (M4 Pro): the iOS libraries 13.55 → 13.92 MB (+2.8%), the Mac's 17.54 → 18.62 MB (+6.1%), build time within noise (13–14 s both once warm). A first version with
main0_u_aandmain0_u_las entry points of their own took +47% and +38%: each is a whole copy of the shader's body. The base library, the pipeline archive, frame time and the draws of pipelines of the declared classes do not change. The first pipeline of a shader with a target of another class or a logic operation loads its side library and specializesmain0_u(a synchronousnewFunctionWithName:constantValues:), asmain0_uandmain0_lalways did. - Check:
python3 -m unittest dm/tools/tests/test_shader_rewrites.py(TypedOutputs),python3 dm/gfx/tests/test_dmsh_typed.py(the unit, the cut and the reflection's classes),make -C dm/gfx/tests GAME=<id> check_t_typed_outputs(every mix of float, unsigned and signed targets on colours 0 to 2, and the alpha test of a float colour 0 beside integer targets, throughpso_descon the Metal 4 path and theMTLDevice's, the bits read back),check_t_logic(the logic operation throughmain0_u) andcheck_t_alpha. - Found on: Kirby and the Forgotten Land on an iPhone (#2760): 76 shaders in Waddle Dee Town writing an R8Uint colour 5. Mortal Kombat 11's signed and unsigned material outputs (PR #2807).
Integer textures and images through float declarations keep their bits
- These accesses kept their integer bits on the Apple GPU used in the original check. Metal leaves a mismatch between texture format and shader type undefined. The host adapts supported 32-bit integer buffer image formats to matching float views. See Float views for integer buffer images.
- Found on: DRAGON QUEST VII Reimagined (the volumetric lightmap's indirection texture, the light grid buffers).
Integer-typed vertex inputs fed normalized formats
- Symptom:
failed to create render pipeline … Cannot convert attribute …; draws missing (a pipeline that fails to build). - Cause: the translation declares a vertex input
uint4when the shader only moves its bits (x bit-cast to an integer, y copied as a float; Integer vertex inputs), and a game that feeds it a 16-bit normalized format gets a pipeline Metal will not build (no integer input pairs with a normalized format). - Fix: the profile's
shader_facts_manual.tsvdeclares such inputs float (the bits Maxwell would see), which changes only that profile's chain version. The guess is not wrong in general, so overrides are added only for shaders seen failing with float formats. The general replay-side answers are the CPU conversion and the shadow vertex inputs (CPU conversion of vertex attributes the input type cannot take, Shadow vertex inputs). - Found on: The Legend of Zelda: Link's Awakening: missing palm tree and flowers (the pipeline
147c829e79fb322f+0ebba5ff6a44aa52,shadowmap_pbr.bfshavariant 641, vertex inputs 1–5): the foliage's shadow-map and depth pre-pass draws; the main pass shades with depth test EQUAL, so without the pre-pass the plants never appeared. Four outdoor shaders with the same loop (03c43da3e3f46da8,079700f3577e311f,15c02683a10f8e9d,2344874045b1e758) failed the same way on the iPhone in Mabe Village (Half2, RG8 / RG16 normalized) and are listed too. 1,437 of the game's vertex shaders have integer-typed inputs, many of them bone indices the shader multiplies as integers.
Depth mode near = 0 needs the per-mode entry points
- Symptom: outdoors the whole screen blurred (depth of field out of focus everywhere).
- Cause: a game that sets depth mode near = 0 had every vertex shader translated for GL, so all depths sat in 0.5..1.
- Fix: the per-mode entry points of 04, section 5.
- Found on: The Legend of Zelda: Link's Awakening (Mac and iPhone): the depth-of-field composite (
52fcbb4ca2a78907,postprocess.bfsha) blends the sharp frame with two blurred levels by a blur amount computed from the half-size depth copy:pow(clamp((c5[2].y / (depth + c5[2].x) − c5[3].x) · c5[3].y), c5[3].z)above a screen line, by screen position below it. Found with a save file from the iPhone (Mabe Village outside the house),DM_NVN_PASSDUMP/DM_NVN_TEXDUMPof that frame, and LASRecomp, which rewrites z only for the GL mode.
Open: the window Y-direction register SR_Y_DIRECTION
- The register is −1 under a lower-left origin. The Ryujinx recompiler answers a constant +1 (a TODO in
InstEmitMove.cs; LASRecomp, a static recompilation of Link's Awakening, answers −1). Answering it per profile means a translator change, i.e. every game's chain. - Found on: The Legend of Zelda: Link's Awakening: 2,487 of its pixel shaders read it; in the room shader the value only scales a depth slope under
abs(); other shaders may use its sign (dFdy-based effects).
Subgroup operations rewritten for a one-lane subgroup
- Symptom:
SPIRV-Cross threw an exception: Subgroup builtins are not available in this type of function. - Cause: Metal has no SIMD-group functions in vertex functions, and SPIRV-Cross's own subgroup emulation covers only
Elect. RE Engine scalarizes uniform loads: ballot the active lanes, shuffle the first lane's value to all and take a fast path when all agree. - Fix: with a one-lane subgroup that is exact, so
dmsh_build.pyrewrites the vertex and domain shaders' SPIR-V that way before SPIRV-Cross (spv_single_lane: the ballot is the lane's own bit, shuffles and broadcasts return its own value, all / any are the predicate, all-equal and elect are true, lane ID 0, size 1). A mask component read throughOpAccessChain/OpInBoundsAccessChainbecomes an extraction from the constant mask, preserving the index. - Found on: Monster Hunter Rise (about 4 % of its vertex shaders); Xenoblade Chronicles 3 (vertex
4b98320a0f512efe, a prefix ballot that readsSubgroupLtMaskthrough a component pointer). - Types the module lacks: the rewrite's constants need
booland auint4-vector; a module without one (a shader that reads only the lane ID) was left as it was, and now gets the type declared with the constants. - Note: domain shaders take the rewrite too: SPIRV-Cross writes them as post-tessellation vertex functions, with the same limit (PRAGMATA's
859225c91a5fe2b2andf1ad8f78c6c1551edid not build; two of Bayonetta 3's failed this way, not rebuilt since). The tessellated draw replays them as plain vertex functions (Tessellation stages drawn without a Metal tessellator).
Geometry shaders that only pick the layer
- Symptom: the tone mapper read an empty LUT and the screen came out a flat blue.
- Cause: Unreal Engine 4.18 builds its 32×32×32 colour-grading LUT with
WriteToSliceMainVS+FWriteToSliceGS, one slice per instance. Metal has no geometry stage. - Fix:
dmsh_build.pyrecognises such a shader in its SPIR-V (gs_slice: triangles in, at most 3 vertices out, positions and other inputs copied,gl_Layertaking the bits of one input component). It builds no library for it and records the component in its reflection. Each vertex shader that writes integer bits from the instance index into an output component gets two more entry points (vs_layer_entry:main0_l/main0_lzwrite that component as[[render_target_array_index]]). At bind timeprog_fold_gs(nvn_mtl.m) swaps the vertex shader for its layer variant and drops the geometry stage when the components match. The pass and pipeline side of layer-writing vertex shaders: Layered passes for vertex shaders that write the layer, Layer-writing vertex shaders get the triangle class. - Note: Unreal binds each stage from a program of its own, so a vertex shader is often paired for a moment with the previous draw's geometry shader. A stub that does not fit stays in the program, and only a draw that uses it prints a red line (
draw_gs_check). The other 22 geometry shaders in DQ11 (one-pass cube shadows that emit transformed triangles) still do not build (Geometry shaders with no Metal stage). - Found on: DRAGON QUEST XI S.
NVN2 task and mesh shaders
- Symptom:
[RED] NVN unimplemented function called: nvnCommandBufferDrawMeshTasks, and a build that fails withAmpere instruction 927 ... is not implementedin shaders the map calls vertex or domain; what they draw is missing. - Cause: NVN2 has NVIDIA's task and mesh shaders, stages 6 and 7. The control section says so (+0x56), while the SPH reads as vertex or domain (type 1 or 3), so the split filed them there. Their stage memory has instructions of its own: ISBERD reads a workgroup's number (mode 0x78) or a payload word (0x38), and 0x927 writes a task's payload word (0xb8), a mesh attribute word (0xf8), the primitive count byte (0x88, at +3) or a primitive index byte (0x80, from +4). Control +0x58 is the workgroup's threads, +0x5a the payload's bytes, +0x5e whether a mesh shader has a task, +0x5f a primitive's vertices (1 point, 2 line, 3 triangle), +0x60 and +0x62 a mesh shader's most vertices and primitives, and +0x64 the code area offset of its per-primitive SPH where +0x68 bit 7 is set. Attributes come in all the blocks of 32 vertices, then all the blocks of 32 primitives (Mesh attributes: every vertex block before the primitive blocks), each component 0x80 bytes: a vertex block the components the SPH's OMAP enables (byte 0x35 bit 3 the point size, bits 4..7 the position, bytes 0x36 on a nibble a generic attribute), a primitive block the per-primitive SPH's. A task writes its launch count at payload +4 and its records from +0x10; the hardware puts a mesh workgroup's number among its task's launches at payload +0.
- Fix:
shader_split.pynames the stagestsandms, astaskandmeshin the shader map.dmsh_build.pytranslates one as compute, its SPH taken off, with its stage memory in shared memory at the offsetsdmsh_meshstage.memorygives (jobstage_memory,AIsberdandAStageOutinInstEmitAmpereMem.cs). A byte store goes through the shared memory's byte store, which the build makes one Metal byte store, as neighbouring threads write neighbouring bytes (Stage memory byte stores through a compare-and-swap loop).- On the console a workgroup of 32 threads is one warp, so the zero count each thread writes first cannot pass the count one thread writes later. Metal's threads run in no such step, and a late zero would erase the count: that store is left out, and the wrapper starts the stage memory at zero.
dmsh_meshstage.to_stagewraps the kernel as a Metal[[object]]or[[mesh]]function: it fills the inputs, calls the kernel's body (whose early returns come back to it) and hands the outputs over. A mesh shader hasmain0andmain0_zfor the two depth conventions, as a vertex shader does.- The host keeps these stages in the tessellation stages' places, 3 and 4 (
hle_nvn.cst_host,nvn_mtl.mgfx_stage_bits): a program has mesh shaders or tessellation, never both.nvn_geometry.incmesh_tasks_drawdraws throughdraw_with the pixel stage alone, on a mesh pipeline built in the background; the mesh stage shares the vertex stage's argument table, as a geometry mesh draw does, and a task shader has the object stage's. Their storage buffer tables inc0are at 0x670 and 0x770: Task and mesh draws reading the dummy buffer.
- Not done:
DrawMeshTasks3Dand the multi-draw forms have no game yet to show their arguments, so they stay red. A task or mesh shader with shared memory of its own (LDS, STS, ATOMS) is refused at build time: it would lie over the stage memory and the control section does not give its size. No game's does. - Found on: Mario Kart World: 7 task and 18 mesh shaders, which draw its bushes and grass. All 11 pipelines its first race makes build, and the race holds 60 fps with them. The facts of pull request #983 were checked against the game's code and hold, except its storage buffer table offsets.
- Check:
python3 dm/gfx/tests/test_dmsh_meshstage.py(the stages compile for macOS and iOS where the Metal compiler is installed),DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(StageMemory).
Task and mesh draws reading the dummy buffer
- Symptom: large flat panels in front of the sky, the clouds behind them blinking at times, in some places and not others. In a
DM_NVN_PASSDUMP_ALLdump every task and mesh shader's storage buffer shows asst3/st4 sbufp reg6orreg7dummy addr=0 size=0, though the game binds buffers for those stages. - Cause: the task and mesh storage buffer tables in
c0start at 0x670 and 0x770, and the host took them to start at 0x610 and 0x710, 0x100 apart as the other stages' are. Task shaders readc00x670 and 0x680 and mesh shaders 0x770 to 0x7b0, so the build gave them slots 6 and up, while the game binds slots from 0. Each read the shared dummy buffer. Three of those shaders write their storage, so that buffer probably held their data when the others read it (not observed directly): shapes drawn into a 128x128x5 array got values past 1,000 where the rest stay under 1, and the vertex shader that moves its vertices by that array lifted them into the sky. - Fix:
DMSH_C0_SSBO_TSandDMSH_C0_SSBO_MSindmsh_abi.hare 0x670 and 0x770. The tables no longer lie over the graphics stages' single words at 0x610 to 0x647, so the host writes the largest point size for every graphics stage again. - Found on: Mario Kart World, issue #1186.
- Check:
python3 -m unittest dm/tools/tests/test_dmsh_abi.py.
Stage memory byte stores through a compare-and-swap loop
- Symptom: a game with task and mesh shaders runs at a lower internal resolution than it could, or below its frame rate, and the GPU time sits in the pass that draws its mesh work (a render pass's start stamp is written after its vertex stage, where Metal runs the object and mesh stages, so in a
DM_NVN_GPUPROFprofile the mesh work shows as the gap before that pass or as its length).DM_NVN_SKIP_MESH=1(diagnostic: every task and mesh draw dropped, the picture wrong) takes most of that time away. - Cause: the translator stores a byte or half-word of shared memory (
SharedStore8,SharedStore16: STS.U8 / .U16, and a mesh shader's primitive count and index bytes, 0x927 modes 0x88 and 0x80) through a helper from upstream Ryujinx, a compare-and-swap loop on the word, because SPIR-V's shared memory is an array of words. A mesh workgroup's threads write neighbouring index bytes, so four threads contend for each word and each store retries, divergently, about four times. Metal's threadgroup memory takes byte and half-word stores, and C++'s memory model, which MSL follows, makes each byte its own memory location: neighbouring stores need no atomics. - Fix: the helper is named
dmsh_shared_store8_<n>/dmsh_shared_store16_<n>(HelperFunctionManager.cs), anddmsh_rewrite.pyshared_store_mslreplaces its body in the Metal source with one store through aucharpointer, or an alignedushortone markedmay_alias, over the array (threadgroup, or device wheretg_spillmoved it). Character types andmay_aliaskeep the compiler's type-based alias analysis from reordering the store against the word loads around it. Two threads storing the same byte at once leave one of the two values, as the loop did. A helper of another form stops that shader's build (shared store rewrite failed). - Not taken: an atomic AND to clear the field and an atomic OR to set it (pull request #1503) need no retries either, but two threads writing the same byte leave the OR of both values, a value neither wrote; on the GPU that is what 64 threads writing different bits to one byte give.
- Found on: The Legend of Zelda: Ocarina of Time: 515 of 42,848 shaders (500 mesh shaders, the foliage among them, and 15 compute kernels with half-word stores). Pull request #1503 measured the atomic AND / OR form on an M3 Pro in Kokiri Forest: the foliage pass from 8.3-8.6 ms to 3.5-4.0 ms, and the game's internal resolution from 854x480 to 1120x630 (the frame from 25-28 ms to about 21 ms). On an M6 (12 GPU cores), standing on the forest deck, the three forms measure the same: GPU p50 14.0-14.6 ms with each, the two depth passes that hold the mesh work 3.1-3.3 and 2.2-2.4 ms, against 10.3 ms with the mesh draws dropped (three runs of each form, one of them with no pipeline archive). The store has not been measured on an M3. Mario Kart World: its 18 mesh shaders with a byte store build with the store for the Mac and iOS (not run).
- Check:
python3 dm/gfx/tests/test_dmsh_shared_store.py(the rewrite, a spilled kernel, and on the GPU 64 threads storing neighbouring bytes and half-words over 64 dispatches);DMSH_TEST_XLATE=<translator>adds the translated index byte store.
Mesh stage memory of 6 KB and more in a device slice
- Symptom: a mesh shader whose stage array is 6-16 KB runs slower than its instruction count suggests, and the foliage mesh pass of Ocarina of Time takes a large share of a Kokiri Forest frame on an M3 Pro. Shrinking the array (timing only) made the same code faster.
- Cause: each 32-thread mesh group declares its whole stage array (
dmsh_meshstage.pymemory(): the input, the vertex and primitive attribute blocks, the primitive bytes) as threadgroup memory, 5-16 KB in the foliage meshes. Apple GPUs hold fewer groups at once the more threadgroup memory each takes, and the mesh bodies were occupancy-limited: about 0.09 ms per KB per 16,384 groups. - Fix:
to_stagetakes the array from a device scratch buffer for a mesh shader (kindms) of 32 threads and 6000 to 16384 bytes of stage memory. The stage body, the byte store helpers and the wrapper's barriers (nowmem_device | mem_threadgroup) use thedeviceaddress space; the mesh function takesdevice uchar* dm_scr [[buffer(DMSH_MESH_SCRATCH_SLOT)]], slot 7 of the table the mesh stage shares with the vertex stage (a mesh draw binds only slot 0, the arguments, and this one; vertex draws rebind whatever slot they read, asenc_r_vbuftracks every write). The reflection recordsmesh_spill: 1(nvn_refl.mintorf.mesh_spill).- The pool. One buffer in shared storage (
nvn_geometry.incmesh_scratch), made on first use: a head of 32-bit words, a flag word a slice, then a power of two of 16 KiB slices. The slices must outnumber the groups the GPU runs at once. With the array out of threadgroup memory an Apple GPU core holds at most 3072 threads, 96 groups of 32, and the pool is twice that so that a claim takes about two tickets at worst: the Mac reads its GPU'sgpu-core-countfrom the I/O Registry (an M4 Pro's 20 cores: 4096 slices, 64 MiB), iOS takes 2048 (32 MiB; at most 10 cores), and 16384 is the most. The GPU test measured at most 161 groups running at once on an M4 Pro, far below the bound. - Claiming a slice. Lane 0 takes a ticket with a relaxed atomic add, and claims slice
ticket & maskwhen its flag is 0 or holds a tag no newer than the head'sDONEword, by compare-and-swap to its own tag; up toDMSH_MESH_SCRATCH_TRIES(64) tickets. The group broadcasts the slice (32 threads are one SIMD-group), passes a device-scope fence, and zeroes the slice withuint4stores, as the threadgroup array started (the count byte relies on it). After its last read of the slice (a barrier after the index loop) and another device-scope fence, lane 0 clears the flag. A slice is handed out again only after its group finished, however long that group ran (GitHub pull request #2308: a first version took the slice at the ticket modulo the count, and a group that 8192 later groups overtook had its slice zeroed under it). - Tags. Before each draw of a spilled mesh shader the host writes the head's
TAGword: the fence of the submission being encoded, so at least the fence of any submission whose groups read it (the commit follows the store, and the tag only grows).post_completewritesDONEasg_doneadvances, failed submissions included. A flag with a tag no newer thanDONEbelongs to a submission that is over, so its group runs no more: groups that a failed command buffer cut off leave their flags set, and the next claims reclaim them, with no wait on the GPU and no clearing pass. Tags compare by their signed 32-bit difference. - No free slice. A group that claims none in 64 tickets adds 1 to the head's
OVERword, sets a primitive count of 0 and returns: it draws nothing and touches no slice it does not own. The host prints a red line once (mesh scratch: … mesh groups found none of the … slices free and drew nothing), which would mean the GPU ran more groups at once than the pool was sized for. An earlier version used its last ticket's slice without owning it after 8192 tickets.
- The pool. One buffer in shared storage (
- Not taken: below about 5.3 KB the device form gained nothing in the harness, so those shaders keep threadgroup memory. A group of more than 32 threads would broadcast its slice through a threadgroup word instead; no such mesh shader was measured, so they keep threadgroup memory.
- Found on: The Legend of Zelda: Ocarina of Time: the real translated foliage mesh bodies in a standalone harness on an M3 Pro: 20-46 % faster for stage arrays of 6.5 KB and more (73dc0b90, 10.3 KB: 0.568 ms to 0.332 ms with a ticketed slice). In the game, Kokiri Forest on an M3 Pro (pull request #2308, the ticket-and-flag version against main, six alternating rounds): frame p50 24.70 to 23.65 ms standing and 24.95 to 23.87 ms on a replayed route, GPU p50 22.89 to 21.83 ms standing. The lease version on an M4 Pro (20 GPU cores, 2026-11-15,
scripts/bench.pyroutekokiri-deck, three runs a side, no prebuild, the first run of each warming its own pipeline archive): 4096 slices, no group without one, no red line, the shots alike; in the two warm runs GPU p50 14.58 / 14.60 ms against 13.87 / 15.10 ms and p95 16.64 / 16.68 against 15.82 / 16.32, so the main side's frame step held two vsyncs (40 fps) and the slices' side mostly one (43.1 and 58.6 fps). Two runs are too few to call the GPU time different on that Mac. - Check:
python3 dm/gfx/tests/test_dmsh_meshstage.py(the wrapper's structure, and both depth conventions compiled for macOS and iOS).DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_meshstage.py OnGpudraws a spilled mesh stage on the GPU, 24,576 groups a draw, with the head's words set as the host sets them: (1) a long group among short ones, 8 submissions, where group 0 keeps reading its slice until 5,120 more tickets were taken from a pool of 4096: no lane may read a stamp another group wrote or zeroed, and every flag must be clear afterwards; (2) every flag holding a tag no newer thanDONE, across the 32-bit wrap: all groups run; (3) every flag holding a newer tag: every group draws nothing and no byte of a slice changes; (4) a pool of 32 slices: the groups that run own their slices and the rest are counted. It skips when the GPU never let the pool's count of groups pass a running one. On an M3 Pro the ticket-modulo rule failed in the first draw (32 lanes). The host binding has no test of its own; it needs rebuilt shaders (the chain stamp changed withdmsh_abi.h).
A task shader's payload past Metal's 16 KB
- Symptom: the shader build refuses a task shader and the mesh shaders it launches:
mesh stage failed: shared memory of its own, or stage memory past Metal's limitindmsh_build.log, and the game's draws with them are skipped. - Cause: Metal holds an object function's payload to 16 KB (
DMSH_MESH_PAYLOAD_MAX) and a function's threadgroup memory to 32 KB. Nintendo Switch Sports Resort's sea task shaders (AnnaSea) hand their mesh shaders 21–28 KB. The payload went through Metal's payload, and the mesh shader copied it into its stage memory (the input area, ISBERD modes 0x30 / 0x34 / 0x38) on top of its attributes and primitives, reaching 33.7–34.6 KB (and two 21 KB mesh shaders built with an invalid >16 KB Metal payload). A task shader's stage memory also reserved an unused input area as large as its payload, making 42.5–56.1 KB. - Fix: a payload past
DMSH_MESH_PAYLOAD_MAXgoes through a transient device buffer the host binds atDMSH_MESH_SPILL_SLOT(11) of the object table and the mesh table (viaenc_r_vbuf, keepingg_vtslot tracking intact;nvn_geometry.incmtk_encode): word 0 holds the slice count, followed by one 16-byte-aligned slice per task workgroup. Direct draws allocate the exact workgroup count; indirect draws wait for the GPU (mdi_wait) to read{count, first}and draw directly (astg_spilldoes for compute). The task stores its payload in its workgroup's slice behind a device-scope fence and passes the slice's 64-bit word offset in Metal's 16-byte payload (dmsh_meshstage.to_stage). The mesh shader's stage input is kept in a shared memory of its own (stage_input_words,InstEmitAmpereMem.csAIsberd,InstEmitMemory.csEmitLoad,ResourceManager.GetStageInputMemoryId, covering U8/U16/B32), which the wrapper backs withdm_in_tover the device slice behind a device-scope fence so it leaves the mesh shader's stage memory. A task shader's stage memory no longer reserves an input area. Payloads up to 16 KB keep Metal's payload unchanged. - Found on: Nintendo Switch Sports Resort: task shaders
4d57f62a663c4cc9,3c8eaa19f720a02f,07abb052a670b8ba,8c49b3da7fd802dfand mesh shaders56d019ebc580bac3,b5b8595847c61aa3,d60092d7424cb5b4,a68f2301bbaceb8c(issue #1753, PR #2264). All 50 task/mesh shaders (and their 49 paired pixel shaders) build for macOS and iOS with 0 failures (11,057 shaders in the profile). No play session has logged a draw through the buffer yet, so the path has been verified by the standalone GPU test rather than in-game. - Check:
python3 dm/gfx/tests/test_dmsh_ampere_mem.py(dm_stage_infor B32/U16/U8),python3 dm/gfx/tests/test_dmsh_meshstage.py(layouts, wrapper, coexistence withmesh_spill, macOS/iOS Metal compiles) andDMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_meshstage.py OnGpu.test_spilled_payload_object_to_mesh_on_gpu(64 object groups passing 27,904-byte payloads to 256 mesh groups on the GPU, plus cap clipping).
Geometry shaders with no Metal stage
- Symptom: a geometry shader fails to compile with
unknown main0_out: SPIRV-Cross writesunknown main0_out main0()for the geometry stage, and the shader does not build. - Cause: Metal has no geometry stage, so a geometry shader that does more than pick the layer has nothing to translate to. A geometry shader that only picks the layer is folded into the vertex shader instead (Geometry shaders that only pick the layer:
gs_slice,prog_fold_gs; DRAGON QUEST XI S). - Found on: Fire Emblem Engage (one geometry shader, in
unity_builtin_extra; nothing in the opening scenes uses it); Super Mario 3D World + Bowser's Fury (fur fins,RenderFinFur, its one failing shader); Captain Toad: Treasure Tracker (the fin fur geometry shader, as in Super Mario 3D World, is the one shader of its 7,258 that does not build); Monster Hunter Rise (53 geometry shaders); FINAL FANTASY TACTICS - The Ivalice Chronicles (one,bahamuteffect.tec); Big Brain Academy: Brain vs. Brain (Bezel's line renderer, below); Luigi's Mansion 3 (10 geometry shaders, one expands a box from two corners; no draw used one from the title through the opening cutscene to the lobby). The Unity games' built-in geometry shaders do not build either (the container entries above). - Note: a program whose geometry shader has no library used to draw silently without that stage, with the vertex shader's positions taken as clip coordinates;
draw with geometry shader … which has no librarynow names it (Luigi's Mansion 3). - Note: Big Brain Academy's 12 geometry shaders (
_BezelSystemResources/line/shader/line.bfsha) do not build (unknown main0_out) and their draws are skipped ([RED] primitive type 11 not implemented). They take a line strip with adjacency (primitive type 11) and emit up to 12 vertices per segment as triangle strips: thick lines with joins and caps (28 emit sites). From the main menu on, every frame draws one such line (width 10 in its uniform block) into the top-left 512x512 of the frame and copies that region into a texture, so the menu's chart loses its outlines. Not done. - Note: geometry shaders that do more than pick the layer are now built as compute kernels from the vendored translator's geometry-to-compute transforms (geometry shaders on Metal, Passthrough geometry shaders).
Passthrough geometry shaders
- Symptom: the models a passthrough geometry shader draws are missing: its own draw (a depth prepass) shows nothing, and so do the draws that test against that depth for equality. Before the shader loaded at all, the same models showed as black silhouettes.
- Cause: bit 24 of the shader header's first word marks a Maxwell passthrough geometry shader (NV_geometry_shader_passthrough): the input primitive goes on to the rasterizer unchanged, and the shader only writes per-primitive outputs and memory. A viewport mask (
a[0x3a0]) of 0 sends the primitive to no viewport, which drops it. Ryujinx emits the primitive itself only when the host reports no passthrough support. The translator's accessor kept the default answer, "supported", so the compute kernel emitted no vertex and nothing was rasterized. - Fix:
Program.csanswersQueryHostSupportsGeometryShaderPassthroughwith false for the compute geometry jobs;- the vendored translator then emits the input primitive at each return of the shader (
EmitterContext.PrepareForReturn) with every attribute the shader does not write: it is translated without the next stage, against the fixed 144-word input map. It skips the primitive when the shader wrote a viewport mask of 0, and the mask starts at all viewports (Translator.EmitOutputsInitialization); geometry_finishindmsh_build.pytakes the output vertex count and primitive class of such a shader from the input topology (the header declares one vertex of a triangle strip).
- Found on: NieR:Automata The End of YoRHa Edition:
IndexBuildIndependent_{b,x}{cw,ccw}.gsoare the depth prepass, one draw per mesh, and each also writes the mesh's culled index list and its count for the shading pass's indexed indirect draws.
The topology table passed to a helper function
- Symptom:
[geometry failed] missing geometry topology bufferin the build, then[RED] shader … (geometry) failed to loadand those draws skipped. - Cause: when a block is reached from several places, SPIRV-Cross makes it a function and passes the table
trb_dataas a parameter.topology_pointerexpected the one declaration in the argument buffer and only reads through it. - Fix: it rewrites every declaration, the parameter too, and reads with or without the descriptor set in front.
- Found on: Kirby Air Riders: 26 of its 76 geometry shaders.
- Check:
test_dmsh_geometry.py(TopologyPointer).
A captured draw's vertex IDs far apart
- Symptom: the host's memory watchdog closes the game (at 28.3 GB on Kirby Air Riders, whose Switch 2 has 9 GB), with the Metal heap full of frame arena blocks of 36 or 72 MB; it comes on quickly in a scene full of ribbons.
- Cause: a geometry capture sized its vertex space by the range of the draw's vertex IDs. Kirby Air Riders draws ribbons with 144 instances and vertex IDs spread over 65,537 or 131,073, so a draw of few real vertices asked 36 or 72 MB of scratch, per draw, every frame.
- Fix:
geo_prep(nvn_geometry.inc) compacts a sparse draw when that saves at leastGEO_COMPACT_MIN(1 MB): the vertices actually used are captured in contiguous runs (nvn_geo_capture_runs), one capture per run, and the geometry stage reads through a map from the original ID to the compact one (nvn_geo_compact_map). Up toGEO_COMPACT_RUNSruns; a kernel that keeps its original addressing has the original map. - Check:
t_geometrychecks the runs, the map and a draw through both. - Found on: Kirby Air Riders: resident from 28.3 GB (and closed) to about 10 GB through a race.
Viewport indices in geometry compute records
- Symptom: Metal rejects a translated geometry shader with
invalid return type 'main0_out' for kernel function: the compute entry writesout.gl_ViewportIndexinstead of placing that output in its emitted vertex records. - Cause:
ResourceReservations.FillIoOffsetMap(in the vendored translator, as in Ryujinx) reserved the slot for a stage that writes the viewport index underVertexIndex. The geometry-to-compute transform found no viewport-index slot, left that store as a raster output on the compute kernel, and the raster reader read the wrong builtin. - Fix: the slot is reserved as
ViewportIndex, so the geometry store and the raster reader use the same field of the emitted vertex, a dynamic index included. Shaders that do not write the viewport index translate as before. - Check:
test_dmsh_geometry.py(PassthroughCompiler.test_viewport_index_survives_geometry_compute_conversion, withDMSH_TEST_XLATE): a geometry shader that writes the viewport index from the primitive ID, for all five input topologies, compiled as kernel and reader for macOS and iOS. - Found on: Alien: Isolation (SDK 8.2.0): both of its geometry shaders.
Geometry passthrough and viewport masks in compute
- Symptom: geometry reader compilation fails with undeclared
gl_BuiltIn_5253and a scalar.elementsaccess. Compiling only the compute kernel also leaves native passthrough geometry without emitted vertices. - Cause: the accessor advertises NV geometry passthrough, but Metal needs explicit compute emission. The reader tries to expose the unsupported NV viewport-mask array, and the raw SPH output bound can be one even though passthrough emits a complete input primitive. Geometry storage buffers also need their own driver-table base, and
BufferUsageFlags.Writeis bit 0. - Fix: compute jobs report native geometry passthrough unsupported, activating the translator's explicit passthrough emission.
geometry_verticesrecords the translated bound per input topology.GeometryToComputeapplies viewport-zero mask visibility to emitted indices before strip compaction; the vertex reader skips the mask output. This covers the current replay's viewport-zero path, not replication across multiple viewports. Geometry storage-buffer slots decode fromc0 + 0x410in reflection and replay, and writable reflection follows the translator's actual flag definition. - Found on: NieR:Automata US 1.0.3 (four index-building passthrough shaders; all 1,225 compile; visible/rejected primitive GPU fixtures pass).
Geometry capture indices deduplicated with a bounded bitset
- Symptom: sorting repeated mesh indices consumes much of the render thread's CPU time.
- Cause: every indexed geometry draw copied and comparison-sorted its full input index list to construct sorted unique vertex capture IDs, even for static meshes rendered every frame.
- Fix: mark indices relative to the validated minimum in a bitset, then enumerate set bits in ascending order. The existing vertex-capture bound limits the bitset to about 57 KiB; primitive assembly retains the original index order and restart boundaries. Non-indexed captures need no unique index list. No cross-frame cache or new hazard assumptions are involved.
- Found on: NieR:Automata: a Mac CPU sample attributes 316 of 687 replay samples to
qsort. The geometry tests cover repeated indices, a sparse range spanning multiple bitset words, restart, base vertex and instancing (121 GPU checks, also passing with forced conservative waits).
Geometry runs retain external buffer dependencies
- Symptom: later geometry uses stale shader-written data or appears in the earlier draw's position when draws are combined into a geometry run.
- Cause: a run captures all vertex inputs, dispatches all geometry shaders, then rasterizes all draws. That reorders a later capture before an earlier geometry write. Shader writes can also communicate with other geometry or fragment work in the run. Separate scratch outputs do not prove independence of the game's own buffers.
- Fix: record external vertex-buffer, uniform and storage-buffer access ranges for each job, including write access and read-only storage metadata. A read/write or write/write overlap stops the run before the next capture; read-only sharing and disjoint writes can still batch. Unknown sizes, range overflow, indirect storage pointers, image accesses and typed buffers conservatively stop batching. Existing encoder barriers then order the separate jobs.
t_geometry_hazardsexercises an actual geometry write followed by vertex capture through a storage binding and through a uniform alias, checking both the counter and literal covered pixels. All 14 checks pass with early submission enabled or disabled. Removing the dependency guard causes six failures: both counters are stale and both dependent triangles disappear from their expected positions. - Found on: investigation of NieR:Automata US shadow jitter. This is a reproduced general replay bug; its contribution to that game's reported shadow motion is not yet established.
Geometry dependency checks skip read-only pairs
- Symptom: the CPU spends substantial replay time checking dependencies among geometry jobs that share many read-only buffers.
- Cause: the original dependency predicate compares every pair of access ranges, including read/read pairs that cannot communicate. Repeating that quadratic scan across a run can dominate the check even when each job has only one write. Even without read/read pairs, checking each new job against every earlier job of the run stays quadratic in the run's length: in Donkey Kong Bananza (runs of about 56 jobs, 19 ranges and 2 writes a job, hundreds of geometry draws a frame) that loop alone was about 8 % of the submitting thread's samples.
- Fix: maintain a 64-bit write mask as ranges are added or promoted from read to write. A run keeps two sorted sets of merged half-open intervals (
geo_run_access,nvn_geometry.inc): the union of its jobs' writes and of their reads. A new job conflicts with some earlier job exactly when one of its ranges meets the write union or one of its writes meets the read union. Overlap with a union is overlap with one of its members, so merging touching and overlapping intervals loses nothing. Each check is a branch-free binary search, and a range already covered is not inserted again. Unknown access, overflow, half-open bounds and the 64-range limit retain their conservative behavior; the run's ordering policy is unchanged. - Check:
t_geometry_hazardscompares 4,096 generated runs of 1 to 63 jobs with the exhaustive scalar pairwise oracle (both outcomes occur), and covers bit 63, duplicate promotion, adjacent bounds, reads across two merged writes and overflow on either side. All 26 checks, including the existing real-GPU storage/uniform dependency cases, pass with early submission on and off. On the same scripted Donkey Kong Bananza route (sample, 25 s), the submitting thread'sgeo_draw_self time fell from 562 to 81 samples, plus 42 in the new set code, and the game's 60/30 interval switches fell from 30 to 12. In an isolated CPU benchmark of a 64-job run with 32 shared reads and one private write each, the run check takes 13 us against 54 us for the pairwise check. - Found on: NieR:Automata iPhone CPU capture (the read/read pairs); Donkey Kong Bananza (the quadratic run).
An empty vertex stream kept every geometry draw out of a run
- Symptom: a game whose frames are mostly geometry-shader draws stays GPU-bound by attachment traffic: a
DM_NVN_GPUPROFframe shows hundreds of two-draw render passes (each geometry draw, then the reopened pass of its raster) and gigabytes of attachment loads and stores, and nogeometry hoistline ever appears in the log. - Cause: the game leaves a vertex stream bound at address 1 with size 0. Three checks looked at every one of the 16 streams, used or not: the lookahead's alignment test in
geo_prep(a run may not prepare an unaligned stream ahead of intervening draws) returned -1 for it;geo_access_ofadded it as a zero-length range, whichgeo_access_addmarks unknown, so every pair of geometry draws counted as a dependency; andcsh_draw_readscould not list the draw's reads, which stopped compute dispatches from moving out of the pass.vbuf_prepareandbind_vbufsalso sent it tovbuf_unaligned, which logged a[RED]that it could not be copied although there were no bytes to copy. - Fix: all of them skip a stream of size 0. It holds no guest memory that a draw could depend on: a draw that reads past it gets zeros, from a copy filled on the CPU with no ordering to keep (
vbuf_unaligned), so neither the ordering nor the dependency proof changes for a stream that holds data. Geometry captures do not bound their streams (geo_capture_oneclearsg_vbuf_need), so a vertex shader that really reads an empty stream there still reads the memory at its address, or a stale binding if that address is not aligned, instead of zeros, with or without a run. That is open. - Check:
t_geometry_hazardsforms a run across an empty stream at address 1, keeps a stream with data at an unaligned address out of one, and checks the lists ofgeo_access_ofandcsh_draw_reads;t_vbufchecks that an empty stream logs no red line and still reads zeros when a draw reads it. The frame rate below is the reporter's measurement, not reproduced here. - Found on: FINAL FANTASY XII THE ZODIAC AGE (
0100EB100AB42000, no profile yet): about 180 geometry draws a frame from two triangle-in, three-vertex-out shaders. On an M1 in handheld mode, gameplay went from 264 render passes and 2.9 GB load + 2.3 GB store a frame (GPU 52–68 ms, 12–17 fps) to 6,053 draws prepared in 153 runs by frame 1,500, GPU about 15 ms and a steady 30 fps, the game's own rate there.
Parallel geometry index compaction
- Symptom: geometry-heavy rendering spends substantial GPU time compacting the geometry shader's emitted indices.
- Cause: the original
geo_pack_indiceskernel walks every invocation group in a single GPU thread. - Fix: use upstream commit
16f4889's ordered count, offset-scan and write dispatches. The count kernel computes exclusive offsets within each 64-group block using SIMD scans and a threadgroup barrier; the middle kernel scans block totals, and the write kernel adds local and block offsets. Scratch holds one word per group plus one per block. The middle scan now uses 128 GPU lanes, each walking a contiguous chunk before scanning lane totals across SIMD groups. Draws with at most 1,024 invocation groups instead compact in one 128-thread workgroup, without global scratch or two extra dispatches. Both paths preserve exact invocation order, strip winding, restart boundaries and whole-primitive clipping at the output capacity.DM_NVN_GEOMETRY_PACK=legacyrestores the earlier three-dispatch policy with its single-thread block scan. - Found on: upstream OCTOPATH TRAVELER II; the blocked scan was measured on NieR:Automata. On an M4 Pro, a 65,536-group compaction benchmark with alternating warmed runs measured 3,918 us median for the upstream scan and 81 us for the blocked scan, with identical output. Production geometry checks pass 157 checks, including 257-group partial blocks, empty groups, restart boundaries, output capacity and pending index writes. Both normal and forced-wait policies pass. Full-game timing remains scene-dependent.
- Further check: the newer fused/parallel paths pass 914 geometry checks in normal, legacy and split-compute modes, including 0–1,024-group boundaries, points/lines/triangles, partial chunks and a 16,387-block prefix stress case. An alternating warmed 256-draw query workload improves 2.998 to 2.832 ms GPU median with identical query results; the large block-scan stress benchmark improves 1,221 to 45.8 us with byte-identical prefixes and indirect counts. The latter is an isolated stress workload, not a measured game frame. Game FPS with these additional changes remains to be measured.
Geometry reader viewport masks
- Symptom: the geometry kernel compiles, but its
_bgv.metalvertex reader fails withuse of undeclared identifier 'gl_BuiltIn_5253'andmember reference base type 'int' is not a structure or union. - Cause:
ResourceReservationspacksViewportMaskinto one output word;GenerateVertexPassthroughForComputestores that word as a scalar although SPIR-VIoMapdeclares builtin 5253 (ViewportMaskNV) asint[1]. SPIRV-Cross emits an invalid array-copy expression for it, and Metal has no viewport-mask output. The mask still matters: zero discards a primitive, while bit zero selects viewport zero (NV_viewport_array2). - Fix:
dmsh_geometry.readerrecognizes that generated scalar-array store, retains the mask's integer bits and moves vertices beyond the X clip plane when bit zero is clear. This runs beforevs_depthmakes both depth entries. Using the X plane preserves culling with depth clamp too; moving vertices beyond the far depth plane allowed masked points to render when depth clamp was enabled. Unknown mask expressions fail the build instead of silently losing culling. No pinned translator change is required. - Found on: NieR:Automata The End of YoRHa Edition: its four geometry shaders' readers.
- Check:
dm/gfx/tests/test_dmsh_geometry.pyuses synthetic generated-reader MSL. Both Mac and iOS compiler checks reproduce the original error before the fix. Mac GPU readback covers six masks, points and triangles, depth clip and clamp, and both production depth entries (48 cases); zero-mask points under depth clamp fail with the earlier depth-plane cull. All four original readers also pass both platform syntax checks. - Limits: replay binds viewport zero only. Multi-viewport fanout is not implemented, and per-vertex-disagreeing masks are not validated; the tested primitives use one mask for every vertex. These tests establish compilation and viewport-zero culling, not the appearance of those effects in gameplay.
Vertex viewport masks apply only at rasterization
- Symptom: an ordinary vertex shader that stores
gl_BuiltIn_5253[0]fails Metal compilation withuse of undeclared identifier 'gl_BuiltIn_5253'; applying the geometry reader's cull before making capture entries would also change the positions a later stage receives. - Cause: SPIR-V declares
ViewportMaskNVasint[1], but Metal has no corresponding output. The ordinary vertex finishing path left its indexed accesses untranslated. NV_viewport_array2 takes the mask only from the last active vertex/tessellation/geometry stage and applies it after transform feedback; a previous stage's mask is ignored even if the last stage writes no mask. - Fix: one unconditional element-zero store before every return is lowered only when its value is provably uniform for the draw: an integer literal, a declared constant scalar parameter, or a fixed component of a declared constant-buffer array. The check verifies the address-space and type declarations; varying indexes, vertex inputs, device pointers, multiple or conditional stores, and other unproven expressions retain an explicit unsupported diagnostic. The accepted store becomes a signed local value. Only the final raster entries move the position beyond the X clip plane when bit zero is clear, including both depth conventions and pulling inputs. Geometry capture, transform feedback, rasterizer discard and folded layer-writing geometry entries use the original positions and outputs. A mask-writing vertex shader uses the full geometry capture/kernel/reader path: lean replay would rerun the earlier vertex stage as a raster entry and incorrectly apply its ignored mask. The fixed capture record remains unchanged because the viewport mask is not an input to the next shader stage. Rebuild shader libraries and the host together.
- Found on: PikaMan80's Mario Tennis Aces report, part 3, which supplies indexed stores in its cube-shadow vertex shaders and describes masks
1and63. There is no registered game profile or local gameplay validation for that title here. - Limits: this implements the existing viewport-zero raster contract for primitive-uniform masks. Multi-viewport broadcast, viewport swizzles and the reported six-face cube-shadow result remain unsupported or unverified. The specification selects one implementation-dependent vertex's mask; it does not permit clipping each vertex independently. Per-vertex-dependent masks are therefore refused, not approximated. This does not close the whole game-support report.
Passthrough geometry output bounds follow input topology
- Symptom: a passthrough geometry kernel writes beyond its vertex and raw-index scratch regions, and compaction reads the wrong groups; corruption can reach the following primitive-map buffers without a red diagnostic.
- Cause: the builder used the SPH's raw maximum output count for every topology. Ryujinx's
ShaderDefinitionsoverrides that count forGpPassthrough(SPH word 0 bit 24) with the input primitive's vertex count excluding adjacency. A header can declare one vertex while the triangle variant writes three vertices and six raw index words per group. Allocating two index words per group then overlaps later scratch regions. - Fix:
dmsh_geometry.output_layoutmirrors the translator's override for each input variant: points, lines, lines with adjacency, triangles, triangles with adjacency use vertex bounds1, 2, 2, 3, 3and index strides2, 4, 4, 6, 6. Passthrough also inherits the input primitive: native GLSL omits the SPH's output primitive declaration, soShaderDefinitionsand metadata use point, line strip or triangle strip accordingly.geometry_finishwrites those bounds and topology into each variant's metadata, which replay uses for allocation and compaction. Ordinary geometry shaders retain their declared bound and topology. Rebuild shaders and the host for the new chain. - Found on: NieR:Automata The End of YoRHa Edition: its passthrough index-building geometry shaders; the triangle kernel's six-word stores disagreed with its two-word metadata while rendering flight. The game note tracks the visual result after correction.
- Check:
test_dmsh_geometry.pycovers all five variants, ordinary bounds and malformed headers. WithDM_TEST_GEOMETRYpointing att_geometry, it passes production-generated layouts to a native emitter with independent topology bounds. GPU canaries protect the nominal vertex and raw-index allocations, and compaction must preserve the emitted count and order. The old rule produced 34 failures; the corrected metadata passes all 170 native checks with Metal validation.
Passthrough geometry kernels lose raster vertices
- Symptom: a geometry kernel compiles and runs its storage-buffer side effects, but contains no
geometry_vb_outputbinding and fills its index stream with restart markers; its following raster pass draws no geometry. - Cause: the offline accessor inherited native geometry-passthrough support. Native NV passthrough forwards input vertices without an explicit emit, but Metal's compute stage must emit them. Disabling native support alone still loses generic attributes: independently compiled stages have no linked next-stage usage to populate
PassthroughAttributes. - Fix: fixed-input compute jobs report no native geometry-passthrough support.
EmitterContextexplicitly emits input positions and every captured generic attribute the GS did not replace, removing adjacency vertices as the input topology requires. This uses the complete Maxwell capture map; ordinary linked translation retains its existing usage mask. Copying all 128 generic components also exposes a Metal backend compiler failure at normal optimization (Internal compiler errorwhen creating the pipeline, despite successful offline compilation).dmsh_geometry.capture_inputkeeps capture reads volatile, preserving their values and normal kernel optimization while preventing that failure. No game IDs or shader keys participate. - Found on: NieR:Automata The End of YoRHa Edition: its passthrough index-building shaders run before depth-writing raster passes during flight. The game note tracks rendering after rebuilding.
- Check:
PassthroughCompilertranslates a synthetic EXIT-only Maxwell passthrough shader for all five input topologies, deliberately declaring triangle output in every raw header. Both Mac and iOS compile checks run. WithDM_TEST_GEOMETRY, production reflection and the argument encoder dispatch the actual kernels; readback checks positions, all 32 generic attributes, adjacency selection, two instances, raw indices, restart padding, primitive compaction and allocation canaries (9,066 native checks). The original pinned translator fails all five variants because raster output is absent. Removing volatile capture reads makes the 128-component synthetic pipeline fail to compile on the M4 Pro; reducing to 96 components or compiling at-O0independently removes that failure.
Geometry capture waits for every indexed draw
- Symptom: geometry-heavy frames have a large submission wall/CPU gap despite short GPU execution; stack samples spend most of the main thread in
geo_draw→mdi_wait→ shared-event wait, with index sorting another substantial cost. - Cause: every indexed geometry draw unconditionally committed and drained the GPU before assembling its primitives on the CPU. It also waited for vertex streams consumed only by native GPU capture. The capture list sorted every index reference to remove duplicates, even though the scratch bound already limits the vertex span.
- Fix:
nvn_geometry.incchecks each actual CPU-read range against pending copies/updates/fills, current shader writes and previous live submission writes. Unknown or overflowing write sets retain the wait. Indirect records are checked before decoding; their selected index ranges are checked afterwards. CPU-converted vertex bindings retain the same hazard checks, while native capture follows GPU encoder ordering. A successful drain covers the remaining reads of that draw. Capture uniqueness uses a bounded vertex-span bitset and ascending set-bit enumeration; allocation failure or a wider span retains an in-place sort fallback. Non-indexed captures need no unique index list. The primitive map, restart handling, base vertex and instance semantics are unchanged. - Found on: NieR:Automata The End of YoRHa Edition: its flight geometry path. The game note records matched frame-time and visual validation.
- Check:
t_geometryfirst reproduced five unnecessary drains for clean static and indirect inputs. Its 226 native checks cover clean versus pending/current/prior GPU-written ranges, unknown write sets, GPU-only and converted streams, indirect arguments selecting a different dirty index range, 8/16/32-bit indices, restart, base vertex and instances. Actual copy/compute writes and raster readback validate synchronization; converted data must see the new GPU-written value. Sparse duplicates, ascending output, short destinations, fallback and allocation canaries cover the capture list. These checks establish behavior; throughput is measured separately in gameplay.
Geometry compaction serial prefix scan
- Symptom: geometry-heavy frames remain GPU-bound after CPU readback waits are removed; encoder timestamps attribute most compaction time to the offset scan rather than the geometry shader or index writes.
- Cause: count and write dispatches ran in parallel, but one GPU thread walked all group counts to compute ordered offsets. Geometry replay also created a separate compute encoder for each of the geometry, count, scan and write dispatches, with full queue barriers at every boundary.
- Fix:
geo_pack_scandivides the groups into contiguous chunks across at most 256 threads. Each thread sums its chunk; a threadgroup prefix scan gives its starting offset; a second chunk pass writes the ordered offsets. The group count does not need to fit in the threadgroup. Totals use 64 bits; unrepresentable 32-bit offsets saturate, output writes use subtraction-based capacity checks, and indirect counts retain complete-primitive truncation.geo_pack_encodekeeps the geometry and three compaction dispatches in one encoder, with explicit dispatch-to-dispatch device-memory barriers. Full barriers remain at its boundaries. The primitive order and large-draw algorithm are preserved; no shader-library chain change is required. - Found on: NieR:Automata The End of YoRHa Edition: its flight geometry passes. The game note records the baseline encoder timings and matched result.
- Check:
t_geometrypasses 1,066 checks with Metal validation. A GPU producer and the production compaction stages share one encoder; readback compares every offset and ordered index with an independent CPU result, including 129,032 groups. Cases cover points, lines and triangle strips, empty groups, zero/odd/thread-boundary group counts, 1/32/192/256-thread scans, short capacities, integer overflow and allocation canaries. The actual translated passthrough integration also passes all five input topologies through the same encoder path. Performance is checked separately with matched gameplay.
Geometry draws above the capture scratch bound
- Symptom:
[RED] geometry draw needs 261 MiB of scratch, above the 256 MiB bound(orexceeds the capture or invocation bound); the draw is skipped. - Cause: the geometry path captures the vertex shader's outputs for every vertex between the draw's lowest and highest index, for every instance, and the geometry kernel's outputs take room per primitive (
nvn_geometry.incgeo_draw). Unreal's one-pass point light shadow draws a whole level mesh through its geometry shader. - Fix: such a draw is drawn in runs in the hardware's order (
geo_split): one instance at a time, then runs of at most 4,096 primitives of a list topology whose index range fits 64 MB of capture. The index list is read once and the runs skip the GPU wait the outer draw took (a first version halved the draw recursively, each part reading the indices again and waiting: that frame took 805 ms). The index compaction after the geometry kernel was one thread walking every group; it is a count, an offset scan and a write dispatch now (nvn_geometry.h,t_geometry). Scratch arenas above 32 MB are kept while such draws go on and released after 600 idle submissions (nvn_mtl.marena_begin), andarena_newtakes the smallest free arena that fits. - Found on: OCTOPATH TRAVELER II: 129,032 triangles of one mesh (vertex
9214254d203a4e45, geometrycb17a9453d4789d0, both from the default material) at the start of the first battle and in the scene after it; with the one-thread compaction each such frame took about 300 ms, now only the first is long (395 ms on the Mac, with two new pipelines and the scratch allocation). - Note: strips, fans and primitive restart are not split. Guest primitive numbering retains the original draw's offset across supported splits: Split geometry primitive IDs.
Split geometry primitive IDs
- Symptom: a geometry shader that reads
PrimitiveIDrepeats its visibility decisions or storage addresses after a large draw is split into compute dispatches. - Cause: fixed-input
GeometryToComputelowered the guest ID to dispatch-localGlobalId.x. Each child dispatch starts at zero. That local index is correct for capture, topology remapping and scratch output addresses, but loses the guest draw's primitive offset. - Fix: replay passes an explicit primitive base through recursive splits, keeping it unchanged when splitting instances and adding each primitive run's start when splitting the range. The counter resets between instances, as specified for geometry primitive IDs.
vb_info.geometry_counts.ycarries it to the shader. Only the guestPrimitiveIDload adds that base; helper addressing remains local, and ordinary draws start at zero. The rebuilt translator and shared chain stamp prevent older libraries from using the new ABI. - Found on: review of OCTOPATH TRAVELER II's large-draw splitter following the NieR integration. The primitive-ID failure is reproduced with a synthetic Maxwell shader; no new Octopath visual failure is attributed to it.
- Check:
test_geometry_split.pychecks 160 nested range/ID cases over all five supported list topologies, all index widths, non-indexed draws, two instance counts and nonzero ancestor bases.ComputeSplitPrimitiveIdintest_dmsh_geometry.pycompiles a real MaxwellALD PrimitiveIDshader for both Metal targets. Its nativet_geometry_primitive_idreplay checks every emitted ID and captured vertex/instance attribute in 40 GPU cases, with 1/8,199 primitives, five topologies, 1/2 instances and 1/3 shader invocations. The old translator repeats ID zero at primitive 4,096; the corrected translator preserves it. A GPU-independent ABI assertion catches stale translator binaries too. Feedback counts and an output canary also check that the offset never leaks into local scratch addresses.
Recursive geometry splits retain their original draw range
- Symptom: a large geometry draw crashes in
geo_split/memcpywhile reading indices, sometimes preceded bygeometry draw exceeds the capture or invocation boundfor an unexpectedly small child draw. - Cause:
geo_preppasses a draw descriptor stored in the reusableg_geo_runjob to the splitter. A child draw prepares its own job in the same slot, overwriting the parent's borrowed descriptor. Later chunks add their offsets to the previous child's index address or first vertex instead of the original draw's range. The job-based geometry integration exposed this lifetime error; the earlier splitter received a local descriptor. - Fix:
geo_splitsnapshots the input descriptors before issuing any child draw. Every chunk and recursive instance split derives its range from that immutable copy. This repairs ownership for indexed and non-indexed draws without changing split limits or skipping geometry. - Found on: OCTOPATH TRAVELER II, the 129,032-triangle shadow draw after Hikari's first attack, during the NieR geometry integration's cross-game review.
- Check:
test_geometry_split.pycompiles the production splitter with a callback that reuses the caller's descriptor exactly asgeo_prepdoes. The expanded 160-case test checks each chunk's range, instance and primitive base for 8/16/32-bit indices and non-indexed draws, including 129,032 primitives and nested splits. Removing the snapshot reproduces the range drift.
Geometry jobs preserve transform-feedback replay
- Symptom: geometry draws with transform feedback report
geometry draw cannot capture this pipelineand write no feedback records after the geometry-job integration. - Cause: the new preparation path rejected active feedback and omitted main's gather of the geometry shader's emitted vertices. Replaying a geometry reader through the ordinary vertex-feedback branch would also capture its synthetic draw a second time.
- Fix: full geometry jobs gather their packed output into feedback before rasterization or raster discard. Active feedback remains in draw order, and feedback state/buffer commands end lookahead. The subsequent synthetic raster draw does not capture vertex feedback again. Lean and mesh eligibility still exclude active feedback.
- Found on: final review of the NieR geometry integration, against main's existing geometry-feedback implementation; no game-specific condition is involved.
- Check:
t_geometry_feedbackreplays actual capture, geometry, compaction, feedback pause/resume and rasterization with GPU readback. Its oracle checks every emitted vertex and saved count, excludes the draw made while paused, and runs with raster discard both enabled and disabled.
Passthrough geometry shaders drawn by the vertex shader
- Symptom: geometry-heavy frames are GPU-bound on the emulation itself. A
DM_NVN_GPUPROFframe shows, for every geometry draw, a capture pass (0x0 0c), a compute encoder and a one-draw reopening of the game's pass, with most of the frame's GPU time in the first two. - Cause: a passthrough geometry shader (SPH word 0 bit 24, NV_geometry_shader_passthrough) cannot change the vertices it passes on; it only decides per primitive (the viewport mask) and may write storage. The emulation still captured all 144 words of every vertex, ran a kernel that copied 134 words per output vertex (volatile loads of the whole capture map, Passthrough geometry kernels lose raster vertices), and drew the copies through the reader.
- Fix: for point, line and triangle input (no adjacency),
dmsh_build.pyadds a lean kernel<key>_bl<topology>(dmsh_geometry.lean): every output store but the viewport mask's word goes, the mask is written one word per output vertex, what only fed the removed stores is dropped (a worklist over the generated straight-line code), and the capture reads that remain (literal words of the record) are renumbered into a record of just those words (capture_reads). The capture writes each word once through a slot table and a record stride the host passes (dm_geometry_capture; the full kernel gets every word in order). At replay (nvn_geometry.inc)geo_lean_cullturns the vertices of masked primitives into restarts before the usual compaction,geo_lean_indexmaps the packed output vertices to the draw's own vertex indices (output vertexg × n + kis input vertexkof primitiveg, the primitive map's word) and sets the base instance, and the program's own vertex and fragment stages draw them indexed and indirect. Instanced or multi-invocation draws, vertex shaders with storage writes (they would run twice), transform feedback and adjacency input keep the full path; so doesDM_NVN_GEO_LEAN=0. The CPU side reads indices with typed loops and copies list topologies without restart directly into the primitive map; amemcpyper index was most of the translation time of such frames. - Found on: NieR:Automata The End of YoRHa Edition: its four
IndexBuildIndependent_*shaders, about 80 draws a frame in the opening flight, most of which keep no primitive (they build culled index lists for later passes). The lean kernels read 4 of the 144 capture words and are about 970 lines instead of 10,500. On an M1 Mac at 720p: GPU work per frame 33–43 ms → about 10 ms, translation 75 M → 42 M instructions per frame, frame time 50 → 27 ms where the Mac was otherwise idle. - Check:
test_dmsh_geometry.pycovers capture slots, lean rewriting, both Metal targets and mesh composition. The native geometry suite covers capture, compaction and dependency ordering. All M1 measurements in this entry were reported for the original implementation in PR #416; they are not measurements of the reconciled host. - Fix: the shared geometry run (
geo_run_walk,nvn_geometry.inc) batches independent captures, geometry kernels and rasters, retaining #336's buffer dependency proof, exact-byte index cache, query positions and parallel compaction. A storage write that could affect another capture or raster ends the run. Lean triangle output uses fixed triangle slots and skips compaction; point and line output retains ordered compaction, then maps output vertices back to the draw's own indices.DM_NVN_GEO_HOIST=0disables batching for comparison. No game identity participates in these decisions. - Found on: the same scene, M1 at 720p: render passes a frame 205 → 39, encoders 290 → 45, attachment traffic 860 → 190 MB, GPU busy 7.6 ms, translation 4.6 ms, frame time p50 / p95 16.66 / 17.26 ms: 60 fps held through four minutes of the flight, factory and ocean combat (frame time 16.6–16.8 ms in every 300-frame window), where it was 50 ms at first.
- Fix: the compute path still costs the CPU a capture, a kernel and a compaction per draw, and the GPU the vertex shader twice. A pair the game drew gets a mesh library
<vertex key>_<geometry key>_m3at the end ofdmsh_build.py(dmsh_mesh.py). Which pairs (dmsh_chain.mesh_pairs): a lean pair with no mesh library takes the compute path, and the host writes it once to the pipeline record as aGrow (geo_mesh_fn), so the prewarm list a recording makes (pso_manifest.tsv) names the pairs to build, as many as the game really draws; a profile's hand-writtengeo_mesh.tsvadds pairs no recording has reached yet. Where the game's shader archives pair the stages (BNSH variations; not yet agl BAHS programs, whose variationsbahs_variationsbuilds from vertex and pixel binaries only), the shader split writes every vertex / geometry pair togeo_pairs.tsv(shader_split.pyvar_pairs), and every pair whose geometry shader has a lean kernel gets its library before the game draws it; the others are skipped (no lean geometry kernelin the build'smesh librariesline). A variation pair whose library cannot be composed or compiled is counted (variation pairs not composed,variation pairs failed to compile) rather than printed as[RED]: no one has drawn it, and the host still draws it through the compute path; a pair from aGrow orgeo_mesh.tsvstays a red line. Until then a game's later areas met pairs no recording had reached, and drew them through the compute path (Donkey Kong Bananza's Sublayer 1200). Separate programs (NieR:Automata's.vso/.gso) name no pairing, so they still depend onGrows andgeo_mesh.tsv. TheGrows are in the profile's input digest (dmsh_chain.inputs, only when there are any), so a new one asks for a full build, which takes every shader from the cache. The library holds the vertex shader's pulling entry (vertex pulling) and the lean triangle kernel, each in its own namespace, under one mesh entry per depth convention (dm_mesh,dm_mesh_z). A threadgroup takes 32 triangles of a list: 96 threads run the vertex shader once per index, write the vertex, and keep the words the kernel reads in threadgroup memory; the first 32 run the kernel body (capture reads from that memory, the topology map as the identity, the mask store into a variable, index stores dropped) and cull their triangle when viewport 0's bit is clear ([[primitive_culled]]). The kernel's storage writes and the subgroup operations that order them run as before, one triangle per thread, 32 consecutive triangles per SIMD group. The host (geo_mesh_draw,DM_NVN_GEO_MESH=0off) takes it for a non-instanced, non-indirect triangle list without restart whose vertex shader has a pulling entry and no storage writes: the draw stays in the open pass, with the pulling layout, the vertex and fragment arguments as for any draw, the kernel's arguments and the draw's index source in two free slots of the vertex table (which the mesh stage shares), anddrawMeshThreadgroups. The mesh pipeline (the draw's colour state, aspso_descgives it) is built in the background; until it is ready, the draw takes the compute path. The vertex shader runs per index instead of per vertex. - Found on: the same game: its 24 shadow-map vertex shaders (
zmap_vs_*.vso) with the four kernels, 96 pairs. In the Resistance Camp on an M1 at 720p, every geometry draw became a mesh draw: translation 184 M → 122 M instructions (16.3 → 12.0 ms) a frame, GPU 12.3 → 11.3 ms, attachment traffic 463 → 415 MB a frame, frame time 21.2 → 16.6–17.4 ms. - Which draws still take the compute path: the log's
[nvn] geometry compute path up to frame Nline counts them per window by the first condition that kept each off the mesh path (geo_mesh_fn,geo_mesh_draw: not a triangle list, instanced, indirect, restart or index type, rasterizer discard or transform feedback, a vertex shader without a pulling entry, tessellation or mesh stages, no lean kernel, no mesh library, an index buffer outside a Metal buffer, a mesh pipeline being built, a depth split) and names the three pairs that drew most (vertex+geometry (reason) count). A pair withno mesh libraryis in the pipeline record as aGrow, and the next recording intopso_manifest.tsvand build give it one (a pair of a shader variation should not appear here:geo_pairs.tsvnames it); the other reasons need host work. It came from Donkey Kong Bananza, whose slow windows each drew 1,600-3,400 geometry draws a frame through the compute path (thegeometry hoistline) and the 60 fps ones none, with nothing in the log to say why.make check_t_geometry_meshchecks the line: the draws made while the test's mesh pipelines are built, under that reason and the test's pair.
A passthrough geometry shader that writes the layer
- Symptom: a pale blue wash over every 3D scene with atmosphere; the HUD is clean, and the albedo and normal targets are right. A 3D table (
texraw) has data in plane 0 only, and the pass that fills it has noL … layered passline and draws withgs=-. - Cause: a passthrough geometry shader cannot change the vertices it passes on, but it may pick the layer. The lean path draws with the program's own vertex shader, which has no layer output, so every plane went to plane 0 and the rest of the table stayed zero. The output reader the full path uses (
<key>_bgv) does write it. - Fix:
geo_lean_pickkeeps the full kernel and its reader when the reader writes the layer (nvn_geometry.inc). No chain change. Those draws cost the full path's capture. - Found on: Mario Tennis Fever: the atmosphere's table (
d9c3a99828b4f39f, one 8x8 plane of 64 per draw, which the atmosphere pass1cdcda78119d2e8dreads) and the shadow map'sf4c2c8feea0727e9. 6 of its 7 lean-capable geometry shaders write the layer.
Mesh geometry primitive IDs restart per group
- Symptom: a passthrough geometry shader that uses
PrimitiveIDmakes different visibility decisions or storage writes after the first 32 triangles when composed into a mesh shader. - Cause:
GeometryToComputeusesGlobalId.xfor both the guest primitive ID and capture-buffer addressing. The mesh composer supplied a group-local lane as that ID to address local capture records, repeating guest IDs in every mesh group. - Fix:
dmsh_mesh.composesupplies the draw-wide primitive ID and rebases only capture loads to the mesh group's first record. Guest calculations and storage writes retain the original ID. A translated Maxwell fixture readsPrimitiveID, shifts it by five and combines it with a captured attribute to control viewport zero. Its GPU test covers 1–97 primitives, both depth conventions and non-indexed, 16-bit and 32-bit indexed draws with a negative base vertex. The original mapping fails at 33 triangles; the corrected mapping passes all 48 cases. - Found on: review of NieR:Automata and PR #416. Its four actual
IndexBuildIndependent_*shaders load generic attributes only, with noPrimitiveIDor physical attribute loads. This is a general mesh-composition defect exposed by the synthetic shader, not an observed NieR rendering failure.
Mesh geometry groups sized to the vertex output
- Symptom: after a pair is added to
geo_mesh.tsv,[RED] geometry mesh pipeline: ... Total mesh size (37248) exceeds the maximum mesh size allowed (32768), and the frames that draw the pair get much slower than on the compute path (Donkey Kong Bananza: translation from about 10 to 22–31 ms a frame). - Cause: a mesh threadgroup took 32 triangles, 96 vertices, whatever the vertex shader outputs. Metal limits a mesh threadgroup's output to 32 KB, and 96 vertices of 388 bytes (24
float4varyings, the position and the point size) are 37,248 bytes. The pipeline failed in the background, but the pair kept its mesh function, sogeo_run_walkkept ending its runs at each of the pair's draws, and every draw went through the compute path alone. - Fix:
dmsh_mesh.prims_fortakes the most triangles of 32, 16, 8, ... whose vertices and primitives fit 32 KB, from the size ofmain0_out(out_bytes, Metal's packed count). Any count other than 32 is in the entry's name (dm_mesh_p16,dm_mesh_z_p16), so libraries of 32 keep their names and the host reads the count from the name (geo_mesh_prims). A triangle's kernel invocations then share a SIMD group with fewer active lanes, which the guest's subgroup operations already allow. A mesh pipeline that fails sends its pair back to the compute path for good (geo_mesh_pso). A mesh draw's storage writes are noted as its arguments are encoded, so it keeps a drain's list of later writes (CPU reads after a drain wait only for later writes). With every geometry draw a mesh draw, two per-draw lookups showed: the pair's mesh function (a key string and a dictionary lookup) and whether the pass's colour attachments can be left out (geo_color_omit, resolving each attachment's Metal texture). Both now keep the last answer, the second keyed by the targets with their serials, views, clears and colour mask: translation 7.20 → 6.64 ms a frame on the same route. - Check:
test_dmsh_geometry.pychecks the sizes (388 bytes takes 16 triangles, the test shader 32, arrays and half types, an unknown member type and a vertex too large for one triangle refused) and composes and compiles a 16-triangle mesh shader. On Donkey Kong Bananza's scripted route, its one geometry pair as mesh draws against the compute path (DM_NVN_GEO_MESH=0), each run alone: translation 7.20 against 9.94 ms a frame, GPU p50 9.0 against 11.8 ms, no red lines. Frames through gameplay show the terrain, rocks, vines and props. - Found on: Donkey Kong Bananza: a
SilverStarMaterialpair (then in itsgeo_mesh.tsv, now from the split'sgeo_pairs.tsv), about 600 geometry draws a frame.
Guarded helpers in a composed mesh library
- Symptom: the shader build prints
[RED] mesh <vertex> <geometry>: does not compile (…)witherror: use of undeclared identifier 'dm_uword'; did you mean 'dm_v::dm_uword'?, and the pair has no mesh library: its draws take the compute path. - Cause: a helper the translator adds under an include guard (
#ifndef DM_UWORD/#define DM_UWORD,dmsh_rewrite.UWORD) is written once into each translated shader.dmsh_mesh.composeputs the vertex shader and the geometry kernel into one file, in the namespacesdm_vanddm_g. The preprocessor does not see namespaces: the vertex part's copy defined the macro, the kernel's copy was skipped, and the kernel's calls named a helper onlydm_vheld. - Fix:
composeundefines every include-guard macro the vertex part defines (dmsh_mesh.guards) before the kernel's namespace, so each part keeps its own copy. - Check:
test_dmsh_geometry.pycomposes a vertex shader and a kernel that both carry the guarded helper, the kernel calling it, and compiles the result with Metal; it fails without the fix. - Found on: Donkey Kong Bananza: 20 of its 31 variation pairs, with kernels
2c8dd0644ddf30d5andb3c54c3b1bf31e7c, when the split's pairs first asked for their libraries (2026-11-22). No earlier pair used the helper in its kernel.
Mesh geometry draws gathered into one dispatch
- Symptom: a depth prepass of many small geometry-shader draws, drawn as mesh draws, leaves the GPU nearly idle: the per-pass profile (
DM_NVN_GPUPROF) shows an idle gap before the pass that grows with its draw count (about 2.3 µs a draw), and the GPU counters show vertex-only time at about 4 % occupancy. - Cause: a Metal mesh draw has a fixed cost on the GPU, whatever it draws. On an M1, 480 one-triangle mesh draws of Donkey Kong Bananza's pair took 1.24–1.32 ms (about 2.7 µs each), and 480 draws of the prepass's sizes (15–350 triangles) 1.5–1.7 ms, where one draw of the same 67,000 triangles took 0.5–0.6 ms.
- Fix:
dmsh_mesh.composegives each mesh entry a run twin (dm_mesh_run,dm_mesh_run_z,..._p16). It takes a table at the draw slot (buffer 12) ofdm_mesh_rec: each draw's arguments, the running total of its threadgroups and the addresses bound at the vertex table's slots for it. A threadgroup finds its draw by halving, takes the vertex set, the pulling layout and the kernel's arguments through those addresses, and runs the same body with the draw's own threadgroup and primitive numbers. A pair whose vertex resources are not all constant references gets no twin.- The host (
nvn_geometry.inc,geo_mesh_take) lets a mesh draw that fits wait instead of dispatching: its record copiesg_vt_addr, the shadow of the vertex table the mesh stage shares, after its arguments are bound. The run is one dispatch of the twin, drawn before any operation other than bindings, a program bind and draws (geo_mesh_keeps, frommtl_exec), before a draw of another pair, pass or kind (geo_mesh_draw,draw_), and before its pass ends (rp_end,defer_fallback). Bindings only change the replay state and dirty flags, so nothing else reaches the encoder between the draws of a run. - The GPU may rasterize the threadgroups of one dispatch in any order, so a run takes only draws whose result does not depend on their order: no colour writes to an attached target, no stencil writes, depth written only with a test that keeps the nearest or the farthest (NEVER, LESS, LEQUAL, GREATER, GEQUAL), and a fragment shader that writes no memory (no writable storage buffer or image, no image atomics, no global-memory write log). The fragment table is not in the record, so the run is drawn with the table as it is then: a change of a fragment table address while a run waits draws the run first (
enc_r_args→geo_mesh_ft_change; the log'sa fragment binding change), and every draw of a run read the same fragment bindings. The first version took only fragment shaders with no resources at all. Donkey Kong Bananza's alpha-tested prepass draws (fragment7f7781d3621f0ce6: two uniform buffers, the support buffer and a discard) then drew 1,700-2,800 mesh draws a frame one by one, at 22,000 instructions a draw against 11,000 and 14-23 fps in those areas. The mesh draw also marked every stage's arguments dirty after it (geo_mesh_draw), so the next draw re-encoded its fragment block at a new arena address with the same bindings, which would have split every run again; it keeps the fragment stage's block now, as the raster program's fragment shader encodes it from the same bindings. Occlusion query counting may be on: a report ends the run and a pass keeps one query slot, so each query's interval holds whole runs, and whether any of its samples passed is the same in any order (the nearest fragment of each pixel passes); only the exact count can differ. The first version refused runs while counting was on, and counting stays on for the rest of the game after the first samples-passed reset: in Donkey Kong Bananza no draw ever joined a run (the log's0 of them in 0 runs). A refused draw's reason is logged once (geometry mesh run: a draw of vertex … draws alone). The kernel's storage writes are unordered between separate mesh draws of a pass already (NVN orders them only with a barrier, which ends the run). - The twin's pipeline is built in the background like the pair's own; until it is ready, and when it fails, the draws are single.
DM_NVN_GEO_MESH_RUN=0turns runs off. Thegeometry mesh drawsline of the log counts the draws drawn in runs, the runs, and what ended them.
- Check:
test_dmsh_geometry.pychecks the twins' text (the table, the halving, the resources from the record, the same body in all four entries) and that a non-constant vertex resource leaves the twin out. WithDMSH_TEST_XLATEandDMSH_TEST_GPU=1,mesh_primitive_id.malso draws 97 translated triangles as four draws (31, 1, 33, 32) in one run dispatch for both depth modes and all three index types, each draw numbering its own primitives.make check_t_geometry_meshreplays six geometry draws throughmtl_exec, each with its own uniform (its depth) and its own storage counter, a scissor change between the fourth and the fifth, in runs, withDM_NVN_GEO_MESH_RUN=0, and in runs on the encoding thread: the same depth in every pixel column, every counter equal to its draw's triangles, two runs, under Metal validation. Then again with a fragment shader that reads a uniform buffer and discards when it says so, bound for the third draw alone: that draw's columns stay clear, the rest keep their depth, four runs.- A benchmark on an M1 with Donkey Kong Bananza's pair (
f9c807930abd1234/5d537f7630ec3671): 480 draws of the prepass's sizes 1.50 → 0.67–0.72 ms, 480 one-triangle draws 1.24–1.32 → 0.28 ms, 2,100 draws of 32 triangles 4.37 → 0.66 ms.
- Found on: Donkey Kong Bananza: the 960x540 depth prepass of its heavy areas in handheld mode, 420–550 geometry draws a frame, 1.0–2.0 ms of idle GPU before the pass.
Mesh stage memory reserves the primitive index bytes for every primitive block
- Symptom: white blotches over Kokiri Forest's foliage, walkway and ground in Ocarina of Time, which are the house light tiles. The light-tile pass of task
a5288d0a6c4971fdwith meshese8c667282ba7bd9bandd4171cf9adf0504bwrites constant white through fragmentea1bf96b72e72476, and its triangles were corrupt. - Cause: the guest writes the U8 index bytes of primitive
t = min(count - 1, lane + 32k)for each of its primitive blocks,ceil(max_p / 32)of them. A meshlet count of 0 wrapscount - 1, so all 128 lanes of amax_p126 mesh write. Withmax_p126 the index area was4 + 378bytes, so lanes 126 and 127 wrote bytes 2,702 to 2,707: word 676, past the 676-word threadgroup array, into neighbouring workgroups' memory. Meshes whosemax_pis a multiple of 32 were never affected. - Fix:
dmsh_meshstage.memoryreserves4 + 3 * ceil(max_p / 32) * 32bytes (rounded to a word) for the index bytes: whole primitive blocks, not the vertex blocks a mesh with more vertices than primitives has as well. Meshes of 128 vertices and 64 primitives did not write past4 + 3 * 64before the fix, so the guest's loop goes by primitive blocks. All 500 of Ocarina's mesh shaders were run standalone on zeroed inputs, each with a guard band past its stage array (Metal shader validation does not check static threadgroup arrays): 387 meshes wrote past the array before the fix, everymax_p126 mesh, and none after (pull request #1575, measured with every vertex and primitive block reserved; the primitive-block size was not run through the guard band). In the game on an M2 Pro the blotches are gone and the house doorways and windows glow as intended. This does not fix the intermittent GPU hangs seen in buffers with these meshes; those are a separate open issue. - Found on: Ocarina of Time. The other mesh-shader games in the games table (Yoshi and the Mysterious Book, Mario Kart World, Splatoon Raiders) rebuild their shaders with the chain change; none was checked in the game.
Mesh attributes: every vertex block before the primitive blocks
- Symptom: a mesh shader's per-primitive outputs read as other values once it has more than 32 vertices: Ocarina of Time's Poe Sisters and Phantom Ganon paintings (mesh shaders
ee4ef51a4fddc28eand83c0dbc51c5481e3, 128 vertices, 64 primitives, a per-primitive colour) came out solid green or magenta (pull request #1590). A mesh shader that draws points with a point size takes the size as its position's x. - Cause: the wrapper read the attribute area as blocks of 32 vertices and 32 primitives side by side, each block holding the vertex components and then the primitive components. The guest lays out all its vertex blocks first, then all its primitive blocks, each block only its own SPH's components:
ee4ef51a4fddc28e(6 vertex components, 4 primitive components) writes vertexvat(v / 32) * 768 + (v % 32) * 4and primitivepat3072 + (p / 32) * 512 + (p % 32) * 4past the attribute area's start. The SPH's point size (byte 0x35 bit 3) takes the vertex block's first component, ahead of the position: Ocarina's point mesh3a6340a04bf09797writes the size at component 0 and the position at 1 to 4. A primitive's index bytes are control +0x5f of them (1 point, 2 line, 3 triangle); Ocarina's 5 mesh shaders with +0x5f 1 are the 5 with the point size, the other 495 have 3. - Fix:
dmsh_meshstage.memoryandto_stagetake the vertex blocks (ceil(max_v / 32), the vertex components each) and then the primitive blocks (ceil(max_p / 32), the primitive components each); the point size goes to[[point_size]], the topology and the index bytes a primitive follow +0x5f, and any other value stops the shader's build. The primitive index bytes stay reserved for every primitive block (Mesh stage memory reserves the primitive index bytes for every primitive block),+0x5fbytes a primitive. - Found on: Ocarina of Time: the layout and the point size checked against the guest's address arithmetic in the translated shaders; the paintings not seen in the game since. Pull request #1590 found the layout and the point size.
- Check:
python3 dm/gfx/tests/test_dmsh_meshstage.py.
Mesh shader per-primitive system values: the primitive count overwritten, the primitive id lost
- Symptom: a mesh-shaded draw shows nothing, though its workgroups run: every workgroup ends with a primitive count of 0. Once that is mended, a visibility buffer written from
[[primitive_id]]holds only the index within the meshlet, and each pixel is shaded from the wrong cluster. - Cause: a mesh shader's per-primitive SPH can enable system-value outputs besides generic attributes: OMAP byte 0x34 and byte 0x35 bits 0..3, attribute 0x40 + 4 × bit (0x35 bit 0 is the primitive id; bit 1 the layer, bit 2 the viewport).
dmsh_meshstage.infodropped them, somemoryleft them no room, and the primitive count and index bytes began where the guest keeps the per-primitive blocks: its store of primitive 0's id landed on the count byte. The wrapper also gave Metal no per-primitive id, so the fragment stage's[[primitive_id]]was Metal's own index, not the value NVN'sgl_PrimitiveIDreads (here(cluster << 7) | primitive). - Fix:
infolists the per-primitive system values (primitive_system,primitive_builtins); a primitive block holds them first, then the generic attributes, and the primitive bytes follow every block. The primitive id goes to Metal as the mesh primitive's[[primitive_id]](PRIMITIVE_BUILTINS), which the fragment stage then reads; the same fragment function in a vertex pipeline still reads Metal's index. The layer and the viewport get room but no Metal output: no mesh shader is known to write them. Ported from uncraftablexd's PRAGMATA bring-up (PR #1802); its other part, a storage buffer table atc0+ 0x210 for mesh shaders in the hull slot, is not taken, sincec[26]there is the mesh stage's buffer bank, its push block 2 (NVN2 graphics stages' buffer banks). - Found on: PRAGMATA: 494 of its 539 mesh shaders enable the primitive id, among them the title's lunar terrain (
5aab38bb5ba67ef7,28ef097c07ceb429) and the visibility pass (765e6d9d2588ce70,bc8b4e0fcbb79159). - Check:
python3 dm/gfx/tests/test_dmsh_meshstage.py.
Mesh shaders that also address their vertices as records
- Symptom: thin streaks or stray triangles from a mesh shader over parts of the picture its geometry does not cover (PRAGMATA: white vertical streaks over the cockpit window in the opening).
- Cause: besides the SoA blocks (
ISBEWR.O.ATTR.SKEW.32, mode 0xf8), a mesh shader may write its vertices as records (ISBEWR.O.ATTR.32, mode 0xb8): vertexv'sncomponents ataos + 4n * v + 4c,aosbeing the end of its SoA area, with the same values as their SoA words. The translator took mode 0xb8 as a word at the outputs' base, so the records ran over the primitive count and the index bytes. - Fix:
dmsh_meshstage.memorypassesstage_memory[4..6](the records' start,n, their size); in a mesh shaderAStageOutandAIsberd(InstEmitAmpereMem.csAosToSoa) send a mode 0xb8 address inside the records to the SoA word of the same vertex and component, so both writes coincide.v = w / nis a reciprocal multiply where that is exact for every word of the records (AosVertexchecks it), a division otherwise. Ported from PR #1802. - Found on: PRAGMATA:
6adf14e9a4100082,4fcffc73d65dc1ed,c0e44513c35d209a. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(test_vertex_records_go_to_their_soa_word).
Mesh shaders that read their own outputs back
- Symptom:
NotSupportedException: Ampere 923 …: ISBERD mode f8 in a task or mesh shaderin the shader build; those mesh shaders are left out and their draws skipped ([RED] DrawMeshTasks without its task and mesh shaders). - Cause: ISBERD's mode bits as nvdisasm names them: 0x80 .O (the output area), 0x40 .SKEW, 0x30 .ATTR, 0x08 .32. Modes 0xf8 and 0xb8 read back a word the shader's own ISBEWR of the same mode wrote; the translator took only 0xb8, as a task's payload.
- Fix:
AIsberdreads both from the stage memory's outputs, 0xb8 through the vertex records (previous entry). From uncraftablexd's PRAGMATA bring-up (PR #1407). - Found on: PRAGMATA:
5aab38bb5ba67ef7and28ef097c07ceb429, the title's lunar terrain, read back each triangle's positions to swap two indices of a mirrored instance's triangles.
Subword task and mesh payload accesses
- Symptom: task and mesh shaders fail translation with
ISBERD mode 34 in a task or mesh shaderorstage output store mode b4 outside a task or mesh shader; the host cannot load their libraries when the race uses them. - Cause: the stage-memory emitters accepted only 32-bit attributes and payload words. Bits 74–75 of ISBERD/ISBEWR select unsigned 8-bit, unsigned 16-bit or 32-bit access, independently of the attribute, skew and output bits (Mesa NAK's encoder,
OpIsberd/OpIsbewr). Mode 0x34 reads a 16-bit task-payload entry; 0xb4 writes one. Treating it as a whole word would overwrite the adjacent entry. - Fix:
AIsberdandAStageOutdecode width separately from the stage-memory area and use the existing byte/halfword load and store lowering. Subword vertex-record accesses preserve the byte offset within the remapped SoA word. The existing 32-bit paths are unchanged; there is no shader-key or build gate. - Check:
test_dmsh_ampere_mem.pychecks unsigned input extraction, the high half of a word, subword vertex records and correctly sized store helpers.test_dmsh_shared_store.pyfollows a translated halfword store through the Metal rewrite and tests neighboring byte/halfword writes on the GPU. - Found on: Fast Fusion.
Indexed texture handles in NVN2 compute c0
- Symptom: a shader library builds but cannot load:
reflection conversion failed: B binding cp_t2d_cb196608_10568000 has no resolved slot number, followed bythe dispatched program has no compute shader. The first race's sky is black. - Cause: NVN2 compute places texture handles in a per-shader c0 layout. Fixed reads already pass through
AMapC0into the canonical c2 driver tables, but an indexed LDC keeps its native bank and byte offset.BindlessToArrayturned that read into an array of a game's uniform-buffer handles instead; native c0 has no such uniform slot. - Fix: when the texture-array pass finds an indexed native compute c0 sampled-texture handle, it uses the control section's existing
QueryAmpereComputeC0Layoutmetadata to map the recovered index into the canonical c2 combined or separate-texture table. A fixed separate sampler keeps its own c2 word. Reflection and replay then use their existing driver-table array path. Storage images, other constant-buffer banks and shaders without an NVN2 compute layout retain their previous lowering. - Check:
test_dmsh_nvn2_buffers.pycovers indexed combined handles and separate textures ORed with a fixed sampler; both declare c2 resources and retain no c0 read. The before/after shader-source comparison and rendered result are in the game's note. - Found on: Fast Fusion.
Threadgroup stores in warp-synchronous code
- Symptom: a small scan or sort in a compute shader gives wrong results every frame, with no barrier in its loop (Orbitals: Niagara's sorted particle indices).
- Cause: Ampere compilers rely on lockstep warps and leave the barrier out of small scans: a thread stores its word to shared memory, then loads its neighbour's. For one thread the load and its own earlier store do not alias, so Metal may move the load above the store and read the neighbour's old value.
- Fix: the translator's
SharedMemoryFencepass (Translation/Transforms/SharedMemoryFence.cs, after the lowering passes) calls the helperdmsh_tg_fence()before each shared memory load that some path reaches from a shared memory store with no barrier or fence in between. It is a forward pass over the function's blocks to a fixed point, so a store at the bottom of a loop reaches the load at its top, and a store on one branch reaches a load after the join. One fence orders every store before it, so a run of stores takes one fence. Stores at the end of the shader take none: a compute kernel reads nothing after them, and a task or mesh shader's wrapper puts a barrier after its body. Stage memory, which lies in shared memory, is treated as shared memory.tg_fenceindmsh_rewrite.pymakes the helper's body a simdgroup-scope memory fence (atomic_thread_fence(mem_flags::mem_threadgroup, …, thread_scope_simdgroup)). That is not an execution barrier, so it is safe in divergent code. A kernel whose arrays spill to device memory gets the device scope too (tg_spill). From uncraftablexd's Orbitals bring-up (PR #1775). Its first form, a fence after every threadgroup store in the Metal source, gave Ocarina of Time 25,108 fences in 699 shaders and crashed Apple's compiler on an M2 (next entry). - Found on: Orbitals (no profile here), by PR #1775; taken for PRAGMATA's GPU-driven passes.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_tg_fence.py(placement through the translator; the rewrite alone without it).
A fence after every shared memory store crashes Apple's compiler
- Symptom:
[RED] task / mesh pipeline prewarm failed: task … mesh … fragment …: … XPC_ERROR_CONNECTION_INTERRUPTEDonce per run, at the prewarm before the first frame;MTLCompilerServicecrashes withEXC_BAD_ACCESSinllvm::MachineOperand::setRegunderAGCModule<AGX::Impl::MeshProgramKey>::compileLLVMObject. Runs with the fences also hung on the GPU more often (7 of 9 long runs against 0 of 3), which is suggestive, not proven. - Cause: the first form of the previous entry's fix put a simdgroup fence after every store to a threadgroup array: 17,641 in Ocarina of Time's 500 mesh shaders (most after the stage output writes, which nothing reads before the wrapper's barrier), 85 in its 20 task shaders and 7,382 in 179 compute shaders. Apple's GPU compiler on an M2 (macOS 27.0, compiler 32023.922) crashed on one foliage mesh pipeline in every run; the same Metal source with only those fences removed compiled. An M4 Pro on macOS 27.2, and
metal-tt -arch applegpu_g14g, compiled main's fenced pipeline, so the crash is in the M2's system compiler. - Fix: fences only where a load follows a store with no barrier between, decided in the translator (previous entry). Ocarina of Time's 699 shaders went from 25,108 fences to 1,566: none in its 500 mesh shaders (the foliage mesh shader
f85bb2e8d78b864camong them), 1 in its task shaders, 1,565 in its compute shaders, 1,030 of them in two particle shaders (agl_technique_pfx) that store and load the same array in a chain of branches. Before that the pass counted each call of the HMMA helper as a store, and Ocarina's movie networks took a fence before every HMMA of a chain (15,536). - Found on: Ocarina of Time: task
a7f22b4a795ff4d1, meshf85bb2e8d78b864c, fragment72fba2ec8558f6d4(Foliage.Product.110, var0), reported on an M2 MacBook Air in GitHub issue #2481. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_tg_fence.py; on an M2, the prewarm log has no such line.
Tessellation stages drawn without a Metal tessellator
-
Symptom:
primitive type 14 not implemented; patch draws skipped. -
Cause: SPIRV-Cross already writes the hull shaders as kernels and the domain shaders as post-tessellation vertex functions, but Metal 4's render encoder and pipelines have no tessellation (no
drawPatches, no factor buffer). The hull kernels writeMTLQuadTessellationFactorsHalffor either domain (a triangle domain's in edges 0..2 and inside 0). -
Fix: a patch draw is replayed in four steps (
nvn_tess.inc), for every game:- the vertex shader's capture entry writes each control point as a 144-word record, in an attachment-less pass, as for geometry shaders (
nvn_geometry.inc); - the hull shader runs as an ordinary compute kernel (
dmsh_tess.pyhull), one threadgroup per patch: its control points come from the records through an index list, its per-control-point and per-patch outputs go to location slots (33 and 32float4), its factors stayMTLQuadTessellationFactorsHalf. The kernel's threadgroup memory goes through the deferred encoder's recording (nvn_rec.h), so it also runs withDM_NVN_ENC_THREAD=1(the iOS default); - an expansion kernel in the same compute encoder reads each patch's factors, skips culled patches (an outer factor <= 0 or NaN), counts the patch's triangles in the domain's mode and appends one entry (
patch << 12 | entry) per two triangles to a list whose length feeds one indirect draw; - the domain shader is the vertex function of that draw (
dmsh_tess.pydomain), with the game's fragment shader and render state: vertexvis cornerv % 6of entryv / 6, anddm_tvertgives its domain point.
The subdivision is a hardware tessellator's, in OpenGL's terms (4.6, 11.2.2): quad and triangle domains;
equal,fractional_oddandfractional_evenspacing, each level clamped and rounded as its spacing does (up toDM_NVN_TESS_MAX, default 64), the two short segments of a fractional level placed symmetrically so a shared edge evaluated from either side gives the same points; an inside level of one taken as 1 + epsilon (placed as two or three equal segments, since the short ones of 1 + epsilon would be empty and fold) unless every level is one, when the patch is not subdivided. The layout has an inner part on the inside levels (a quad's grid; a triangle's concentric rings, where the perpendiculars through the inside level's points meet, and its middle triangle or point) and an outer ring of strips that stitch each edge's own points to it, so an edge shared by two patches is cut at the same points from either side and nothing folds or overlaps, also when the inside level is below an edge level. A vertex two strips share is computed by one expression. The layout is one text,dmsh_tess.TESS_MSL, which the host's expansion kernel and the domain prologue both use; the domain's mode is compiled into it from its control section (+0x738 mode, +0x73c spacing, +0x744 winding; the translator answers a fixed default) and given to the expansion kernel from the shader's facts (md). A draw may expand toDM_NVN_TESS_BUDGETentries (default 2M); patches past it are dropped whole and counted in thetessellation:statistics line.DM_NVN_TESS_LEVEL=Ngives every patch level N instead of its hull's, for A/B comparisons;DM_NVN_TESS_ONLYandDM_NVN_TESS_STAGESisolate draws and stages. The first draws logtessellation (frame F): vertex … hull … domain … fragment …with the mode.An indirect patch draw's arguments are read on the CPU once the GPU work that may write them is done (
geo_indirect_args, shared with the geometry path, which reads its draws' vertices on the CPU too); a multi-draw's live draws likewise. The state's patch size starts at NVN's default, 3 control points. Not covered: isoline domains (dmsh_tess.pyleaves those shaders as they were) are skipped with a[RED] tessellated draw not replayedline that gives the reason. The hull kernel's pipeline is built from its specialized function (fn_dev), as the geometry kernels are: a hull that samples a texture carries the border corrections' function constant, and Metal aborts on the unspecialized one (function main0 cannot be used to build a pipeline state; Mario Golf's grass hull).A geometry shader after the domain takes the domain's triangles through the geometry path, whose count only the GPU knows (
nvn_geometry.incgeo_prep_gpu, issue #1423). The domain shader has a capture entry as a vertex shader has (dmsh_geometry.capture,main0_gs), run as an indirect point draw over the list's vertex count, one full record per listed vertex; the job's scratch is sized for an upper bound (the patch list's budget is lowered so that two triangles an entry fit the geometry path's 256 MiB), and a one-thread kernel after the expansion (dm_tess_geo) writes the geometry kernel's primitive count (the info block'sGeometryCounts.x, which bounds its threads), the compaction's group count and both dispatches' threadgroup counts from the list's vertex count. The geometry kernel reads triangle t from records 3t .. 3t + 2 through an identity map, the compaction and the draw are the geometry path's, and no CPU waits for the count. The first draws logtessellation (frame F) into geometry …with the list's bound. A degenerate second triangle of an entry reaches the geometry shader as a triangle of one point, and the geometry shader's primitive ID is the triangle's number in the list. Open: Vulkan gives a geometry shader after tessellation the patch's index ("the same value as the tessellation shaders would read"), and a fragment shader with no geometry shader the value a geometry shader would have read, so also the patch's; the replay gives the triangle's number in the list, and a fragment shader after tessellation Metal's primitive ID of the indirect draw (a triangle number). The patch is in each list entry (patch << 12), so a fix would read it there: in the translator's geometry-as-compute kernel (its primitive ID now comes from the thread index) and, for the fragment stage, through a flat output of the domain prologue. No shader of the games with tessellation reads the primitive ID (2026-11-13: the fragment and geometry shaders of Mario Golf: Super Rush, Luigi's Mansion 3, SUPER ROBOT WARS Y, Super Mario Party Jamboree and Paper Mario: The Thousand-Year Door, about 62,000, checked for IPA / ALD of a[0x60]; the check finds the reads of Mario + Rabbids Sparks of Hope'sdd82a2b07d3cd61band two of Nintendo Switch Sports Resort's; and Hyrule Warriors: Age of Imprisonment's 46,593 fragment and 7 geometry shaders, translated and checked for an input decoratedBuiltIn PrimitiveId, about 23 not translated by that check), so nothing differs yet. PRAGMATA (33 hull, 62 domain shaders) is not checked. - the vertex shader's capture entry writes each control point as a 144-word record, in an attachment-less pass, as for geometry shaders (
-
Found on: The Witcher 3: Wild Hunt — Complete Edition (issue #1423, PR #2426's quad /
fractional_evenpath): its terrain draws on an M1 Max with no cracks or GPU faults, with about 1 ms less GPU time a frame than a fixed 8 x 8 grid and 26% fewer triangles. Luigi's Mansion 3: its two tessellated programs (vertex28a39709d0adfcfa/ hull51d2d156bb12c260/ domain0b95742e863bec50, andd4d89931b5a9a514/8aa6feeb7d33e9f6/f254b4dce2d6c012; triangles,equal) replay with no red line, 60 patches each, on the first two frames of a new game's opening scene (the G-buffer pass and a later colour pass, under the loading screen, so nothing of them reaches the screen). Domain shaders rewritten in their own mode and compiled for macOS: Luigi's Mansion 3 (18, trianglesequal), SUPER ROBOT WARS Y (25, trianglesfractional_odd), Super Mario Party Jamboree (4, trianglesequal), Paper Mario: The Thousand-Year Door (4, trianglesfractional_odd), Mario Golf: Super Rush (3, quads: the grassequal, lava and seafractional_evenclockwise); the hull shaders of Luigi's Mansion 3 (15), SUPER ROBOT WARS Y (25), Ori and the Will of the Wisps (6, whose domains are trianglesfractional_odd), Super Mario Party Jamboree (1) and Mario Golf (3) likewise. Mario Golf: Super Rush's grass (vertexb34da03583527fee/ hull6c095f74c7d35822/ domain3fa8664b1e261629, quadsequal/ geometry87303af8a75b208a, one triangle in, at most one out): the blades are drawn on the rough, about 267 patches and 6,300 triangles a draw, 60% of the patches culled by the game's hull, levels up to 10, none dropped over the budget (64,111 entries a draw); frame time stays 16.7 ms on an M6 (Bonny Greens' first hole). Bayonetta 3: two domain shaders do not build (DS_Vanish05_*.dso:SPIRV-Cross threw an exception: Subgroup builtins are not available in this type of function); the one-lane rewrite (spv_single_lane, Subgroup operations rewritten for a one-lane subgroup) now covers domain shaders too; not rebuilt since. -
Check:
make -C dm/gfx/tests GAME=<id> check_t_tess:test_dmsh_tess.pychecks that the expansion kernel and the domain prologue shareTESS_MSL, andt_tessruns the layout and the expansion kernel on the GPU from that text in all 12 modes (2 domains, 3 spacings, 2 windings): about 36,700 patches of curated and random factors against an independent reference (entry counts, each side's points for its spacing, winding, area 1 or 1/2, no fold or overlap), 72 meshes (10 x 10 quads in all 8 orientations and 10 x 10 squares of two triangles in all 6, every spacing; no crack), the expansion kernel's counts, culling, budget and fixed level, game-like factor patterns in every mode, anddm_tess_geo's counts and dispatches. -
Hull shaders that write into the circular buffer: some games' hull shaders write their control points with global stores instead of attributes, which the translator turns into outputs (A hull shader's control points written into the stage's circular buffer).
-
Note: the vertex shaders that feed a hull or geometry shader can be found from the shader headers (SPH): the generic attribute map at +0x18 of the consumer's header (inputs) equals the one at +0x36 of the vertex shader's (outputs). In Luigi's Mansion 3, 40 vertex shaders match a hull shader and 49 a geometry shader.
A hull shader's control points written into the stage's circular buffer
-
Symptom: a hull shader translates with no per-control-point outputs: its MSL kernel's
main0_outis empty (or lacks the attributes the domain shader reads), and the translator's notes listGlobal memory operation "Store" traced to no storage bufferonce for each output word and copy. The tessellated draw replays such a hull with no control points for the domain shader (Tessellation stages drawn without a Metal tessellator). -
Cause: NVIDIA's compiler can have a tessellation control shader write its control points with global stores (STG.E) into the circular buffer the tessellator and the next stage read, instead of storing them as attributes (AST). The code around the shader's body is the same in every such shader:
- the buffer's address comes from system registers 21 and 22 (
S2RDirectCbeWriteAddressLow/High), the count N of per-patch words and the stride S between output words from the shader's own outputs (ISBERDwith O at 0x7e and 0x7f); - output word k of the control point in lane L goes to
address + 0x80 * (1 + ceil(N / 4) + p) + 4 * L + 4 * S * k, p being 1 when the shader writes a primitive ID; k counts the words of the header's output map (240 bits at +0x32, one per attribute word from 0x000 to 0x3bc: position, then the generic words, in attribute order); - after the body, the shader copies into the buffer what it already wrote with AST (the per-patch words: tessellation factors, patch outputs), a header word and the primitive ID, read back with
ISBERDwith O.
The translator answered 0 for both registers and passed ISBERD's offset through, so the stores went to small addresses through the memory pool table and the outputs were lost.
- the buffer's address comes from system registers 21 and 22 (
-
Fix: in a hull shader that reads register 21 or 22 (the decoder sets
FeatureFlags.DirectCbeand marks the header's generic output words used, as an AST of each would), both registers and ISBERD with O are marker loads in the IR.Optimizations/DirectCbeWrites.csanswers N with the header's per-patch count and S with 0x2000 words, so that once the optimizer has folded the addresses, k is the constant part of the address shifted down by 15 (4 * S * k lies above the rows and the lane term). A store into the buffer whose value was read with ISBERD with O is a copy and goes; any other becomes a store of output word k (ShaderHeader.OutputWords) of control pointgl_InvocationID(AttributeMap.CreateOutputStore). An address that is not the base, a lane term4 * Land constants, or a k past the header's output words, is not guessed: the store goes with a note. The translator notesHull shader writes its control points to the stage's circular buffer: n stores became outputs (w of the header's m output words), c copies of its outputs dropped.Other shaders translate as before (byte-identical SPIR-V). -
Found on: Mario Golf: Super Rush: the grass hull
6c095f74c7d35822(position, 4 words), one of its 3 hull shaders. The same form in every hull shader of SUPER ROBOT WARS Y (25, 20 words each), Ori and the Will of the Wisps (6, 11 words) and Super Mario Party Jamboree (1, 71 words); none in Luigi's Mansion 3's 15 or Diablo II: Resurrected's one. All 33 now write every word of their output map, and their MSL compiles for macOS. -
Check:
DMSH_TEST_XLATE=dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate python3 dm/gfx/tests/test_dmsh_hull_cbe.py: a hull assembled in this form, with a predicated row and a copy of a header word, gets its six output words from the right inputs and keeps no store to an address; an address with another term is refused with its note.
Ampere shader code (Switch 2)
- Symptom: a Switch 2 game's shaders do not translate (the translator reads Maxwell: 64-bit instructions behind scheduling words, a 0x50-byte SPH), or, rewritten as Maxwell code, UI text draws as solid boxes or not at all.
- Cause: NVN2 ships Ampere (sm_86) code: 128-bit instructions, a 0x80-byte SPH (version 4; its first 0x50 bytes keep version 3's layout), uniform registers UR0–UR62 and uniform predicates, convergence barriers (BSSY / BSYNC) instead of the SSY / SYNC stack, CALL / RET with the return offset in a register, and scoreboards: a variable-latency instruction (one that sets a write barrier, control bits 110..113) writes its registers when its result arrives, and an instruction that does not wait on that barrier (wait mask, bits 116..122) reads the old values. A rewrite into Maxwell code got several meanings wrong: IPA (0x326, 0x526) is IPA.PASS and the shader multiplies by 1 / a[0x7c] itself; IPA's indexed form takes its index from a uniform register; TEX's bit 79 (
.F16) packs the results as half pairs; anLDG.128 R0, [R0.64]must read its address once. - Fix: the translator decodes Ampere natively (
TranslationFlags.Ampere, jobarch: sm86;Decoders/DecoderAmpere.cs,Instructions/InstEmitAmpere*.cs) into the shared IR. Uniform registers and predicates are register types of their own; a CALL into code with no reachable RET is a jump; BRX targets come from the c1 jump table its LDC reads (BRXU's from the uniform LDC of its uniform register), up to the next table another BRX of the program reads: the compiler puts a shader's switch tables back to back in c1, and read on to the end, Donkey Kong Bananza'sSilverStarMaterialvertex shaders took every later switch's targets, 400 and more nested comparisons, past the Metal compiler's 256 nested brackets (11 shaders). An instruction with a write barrier writes into shadow registers that are copied to its destinations before the first instruction that waits on the barrier, at DEPBAR and at the end of the block (Translator.EmitOpsAmpere). Field positions follow Mesa NAK's SM70 encoder, CuAssembler's sm_86 tables and the facts of other projects (Eglantine). Maxwell code takes the old path, unchanged (byte-identical SPIR-V on 7,168 shaders).- Semantics that differ from Maxwell:
MUFU.SIN/COStake the angle in turns (the compiler multiplies by 1 / 2π first; Maxwell's came through RRO), of which they use the fraction (MUFU.SIN and MUFU.COS of a large number of turns); bit 76 of FMUL / FFMA is .FMZ (a product with a zero factor is zero). - Warp-cooperative instructions (
InstEmitAmpereTensor.cs): HMMA (m16n8k8 / m16n8k16, F16 sources, F16 or F32 accumulator; in a compute shader, m16n8k16 with an F16 accumulator goes through Apple's matrix hardware instead: Ampere HMMA through simdgroup_matrix), LDSM (1, 2 or 4 8×8 matrices, plain or transposed) and MOVM run per thread: each lane gathers the fragments it needs from the lanes that hold them with subgroup shuffles (Metal's SIMD-groups are 32 wide, as the warp), in the layouts NVIDIA documents for PTXmma.m16n8k16,ldmatrixandmovmatrix. HSETP2, HSET2 and HMNMX2 are the packed-half compares; MATCH (.ANY / .ALL, 32- or 64-bit) compares a value across the warp with a ballot of the active lanes and 32 shuffles, and REDUX reduces one into a uniform register the same way. - UP2UR takes any mask: bit k of the result is UPk where bit k of the mask is set, as P2R does (Mario Kart World's pixel shaders save UP3 or UP6 with masks 8 and 0x40 and test the register against URZ later). SURED (0x59f) is SUATOM's layout with no result; only SURED.ADD.U32 has been seen (Mario Kart World's
ab77eaee44cfef88, adding 1 at a 2D coordinate), and another form is refused. - Geometry stage: OUT (0x124, emit / cut; none is OUTFINAL) and ISBERD (the vertex index passes through, as on Maxwell). A geometry shader that ends through an exit stub sets it up with LEPC and 0x357, and the stub runs OUTFINAL and 0x957 before its EXIT; per thread there is nothing to finish, so LEPC writes its own address and 0x357 / 0x957 do nothing.
- NVN2 compute lays out
c[0]per shader, from the control section: from 0x10 its push constants (+0xa9, in words), then its uniform buffer entries (+0xb1 of them) and storage buffer entries (+0xb2), 0x10 bytes each, then its texture handles (+0xb3), separate texture and sampler handles and image handles, 8 bytes each; the u16 at +0xba is the total (checked on all 205 of Donkey Kong Bananza's compute shaders).dmsh_build.pypasses the counts (jobnvn2_cs) and the frontend maps each range onto the tables the host already fills (AMapC0): push constants toc[24](DMSH_PUSH_BANK), uniform entries to the compute uniform table, storage entries to the compute storage table, handles toc[2]. Graphics stages keep NVN's fixed tables. The push constants themselves come fromnvnCommandBufferPushGraphicsConstants/PushComputeConstants(OP_PUSH_CONST, aDMSH_PUSH_SIZEblock a stage group). - A storage address added from two constant buffer values (a
c[0]entry plus an offset fromc[1], by UIMAD.WIDE) put thec[1]term second, andGlobalToStoragetook the second operand as the base; it now prefers the driver segment's operand when only one is from it (Maxwell output unchanged, 28,669 shaders).
- Semantics that differ from Maxwell:
- Found on: Donkey Kong Bananza: 22,751 of 22,822 shaders translate; its menu renders, and its gameplay, including agl's upscaler network (
agl_ndsr.pck, 24 compute shaders with HMMA). - Resolved: 0x593 is SUATOM, an image atomic through a handle (
ASuatom,InstEmitAmpereMem.cs): SUST's handle (40..59) and dimension (61..64), ATOMG's operation (87..91), size (73..76) and predicate result (81..83, PT here). Its two shaders, agl'sagl_technique_pfxcompute shaders, take an append counter with it (SUATOM.ADD.U32 on a 1D image, the old value shuffled to the warp, then their SUST), and now translate: all 22,852 of the package's shaders do. Neither has been met in play so far, so the picture is not checked;test_dmsh_ampere_mem.pytranslates the encoding. A handle in another bank or a predicate result is refused. - Open: loads and stores through addresses read from memory, which had no storage buffer to become, go through the memory pools now (Global memory at an address loaded from memory).
Storage words read one by one
- Symptom: a lit pass far slower on an M1 than the M4 Pro's figures suggest, the time spread over every material that loops over the scene's lights; dropping one material's draws (
DM_NVN_UB) saved only its share. - Cause: Ampere reads a storage buffer 64 or 128 bits at a time (LDG.E.64 / .128). The translator splits each read into 32-bit LoadGlobal operations, and spirv-cross writes each word with an index of its own,
uint(int(uint(base + 4) >> uint(2))). Metal's front end cannot tell such words are neighbours (each index is the shift of its own sum, then widened to 64 bits), so every word stays a load of its own with its own address arithmetic: about 240 in Splatoon Raiders' Hoian_UBER, most of them in its light loop (80 bytes a light). - Fix:
wide_loads(dm/gfx/tools/dmsh_wide.py, a step ofdmsh_build.pyafterpool_arrays): the words of one read-only (const device) buffer at byte offsets k, k+4, … from one value, with no brace between them, become one read of apacked_uint2/3/4at the first word, each word taking its lane. In the AIR that read is still one load per word, but each at a constant offset from one address, so the words share the address arithmetic they each had; computing the index once in the translator ((base >> 2) + i, unsigned or signed) leaves every word its own widened index and gains nothing. A packed vector needs 4-byte alignment only, and the shader does not write the buffer through that binding. A run ends at any line that may write memory or change a value (a store through a subscript or a pointer, an atomic, a barrier, an image write, an assignment to an existing variable), so a write through another binding to the same memory cannot fall between its words; the values are the same. In TotK's 28,669 and Wonder's 16,266 built shaders that rule left every run as it was. A run starts on a 16-byte step of the common value and holds at most four words, as the original reads did. - Found on: Splatoon Raiders: 4,558 of its 27,155 shaders change. On an M1 in the opening dialogue scene, the lit pass's median GPU time went from 70.2 to 15.6 ms and the frame's from 91.5 to 30.1 ms (
DM_NVN_GPUPROF=every:60, 15 and 35 profiled frames in the scene); the 40 shaders that did not build before are the only ones that fail. - Check:
python3 dm/gfx/tests/test_dmsh_wide.py.
Device loads from read-only storage buffers
- Symptom: fragment shaders spend GPU time on device loads from storage buffers whose addresses are uniform across the draw.
- Cause: SPIRV-Cross emits
const devicestorage pointers for shaders without writes through buffers. Metal can use constant registers for uniform addresses when the pointer has theconstantaddress space. - Fix:
constant_readsruns afterwide_loads. It requires read-only storage metadata from the translator and accepts direct word reads and the packed loadswide_loadsemits. A buffer or element pointer passed to another operation keeps its original address space, as does a shader with a device reference. The argument ID and the host binding are the same. Fragment stages are the default.DMSH_SCONST=0disables the pass for comparison andDMSH_SCONST=allenables the other eligible stage prefixes. The option is part of the chain and shader cache keys. - Found on: Ocarina of Time on an M2 Air. In the PR author's paired run against the same cut9p test build, GPU encoder time fell from 20.43 to 19.82 ms per frame. The hottest fragment shader was 17.1% faster in isolation with bit-identical output. Game note, PR #2889
- Check:
test_dmsh_wide.pycovers write metadata, stage selection, escaped pointers and references, and Metal compilation of promoted packed loads with and without bounds checks.
Bindings and handles
- Note: the layout of NVN's driver segments
c0andc2(the handle tables, the storage and uniform buffer tables, the words the host fills) and the binding kinds of the reflection JSON have one definition,dm/gfx/nvn/dmsh_abi.h. The host includes it (nvn_mtl.m,nvn_refl.m,nvn_obj.h);dmsh_build.pyreads it throughdm/gfx/tools/dmsh_abi.py, which stops on any line it cannot read. Both files are part of the chain version.dm/tools/tests/test_dmsh_abi.pychecks that the tables fit together, that the host converts every kind the build may write, that the translator's own copy of thec2layout (Program.cs) agrees, and that the values do not come back as literals in the host or the build. The entries below cite the offsets.
Images and buffer textures with their handle in a uniform buffer
- Symptom:
reflection conversion failed: B binding cp_i_cb3_0_ has no resolved slot numberat load, thenthe dispatched program has no compute shader; in the build,SUATOM handle in bank 3orSURED handle in bank 3, and bindings of an unrecognized kind for a typed buffer. Compute passes are skipped. - Cause: the compiler reads a texture handle from wherever the game put it, and bindless textures in uniform buffers were already read at bind time. Images and buffer textures were not, as no game had done it: Unreal Engine 5.4 for the Switch 2 keeps every one in
c[3], uniform slot 0 (about 87,000 SURED, 15,000 SULD and 121,000 SUST in one game's shaders, none of them in another bank). - Fix: binding kinds
img_uboandtbuf_ubo(dmsh_abi.h),NVN_RB_IMGUandNVN_RB_TBUFUin the host, which read the handle asNVN_RB_TEXUdoes and otherwise bind as an image slot or a typed buffer: usage upgrades for written images (image_prepare), the uniform shadow check, and the pass logic that treats any bindless shader cautiously. In the translator SUATOM and SURED pass their bank on. With no descriptor to ask at build time, an atomic takes its format from the instruction's size (UniformHandleAtomicFormat). - Found on: Yoshi and the Mysterious Book.
Texture and sampler words in either order
- Symptom: a scene lit black with correct geometry. In
DM_NVN_PASSDUMP, the lighting shader's bindings showtex … tid=0 dummywhere the G-buffer should be, and a sampler bound where a texture is expected. - Cause: a handle from two words (
fp_t_cb262147_10020016: words 0x16 and 8, handle type 1) is the OR of a texture and a sampler word, and the GPU does not care which comes first. The build took the first as the texture and the second as the sampler. Unreal Engine 5.4's lighting shaders read a shared sampler's word first, so each G-buffer texture came out as ID 0. - Fix: each half of such a binding carries the other word (
soff,sreg), and the host ORs the two as the GPU does (ubo_bind_handle). A shader whose order was as assumed gets the same handle. - Found on: Yoshi and the Mysterious Book: its lighting, with this as the last step from a black scene to a lit one.
Compute texture handles loaded through uniform addresses
- Symptom:
Failed to find handle source for bindless access of type "textureBuffer".in compute shaders; the build reports deleted reads whose results become zero. - Cause: compute code can load its handle words through the uniform addresses in the canonical c0 table (
DMSH_C0_CS_UBO), instead of direct constant-buffer instructions.GlobalToStoragelowers these loads to storage-buffer operations beforeBindlessElimination, which recognized only direct constant-buffer handle words. A two-word handle then lost its known uniform origin and its buffer fetch was deleted. - Fix:
ResourceManager.TryGetComputeUniformSlotrecovers the uniform slot from the storage binding's descriptor origin.BindlessElimination.UniformHandleWordresolves a fixed word in a representable game-uniform slot to the existing constant-buffer binding metadata, retaining both words of an ORed handle. It changes no ordinary load. Other stages, unrelated storage descriptors, reserved slots and dynamic word offsets keep their existing paths. This is bound to the NVN compute driver layout, with no game/build gate or pool-array workaround. - Found on: Sid Meier's Civilization VI: all 382 deleted accesses in four compute shaders restored. Their later gameplay use has not been exercised.
- Check:
DMSH_TEST_XLATE=<translator> DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_compute_uniform_handles.py; synthetic Maxwell checks both handle orders and descriptor/offset boundaries, and executes a translated fetch on Metal.t_tbuf_handlechecks production binding of both uniform words.
A store only a dispatch's first invocation makes
- Symptom: objects from a compute-built list flicker: each is in one of two states, on and off irregularly and independently of the others, while the draws are the same frame to frame and the camera is still. Whole groups may vanish or appear in one frame and stay that way until the list's next rebuild. Shots of consecutive frames show the change per frame jumping between two levels.
- Cause: a compute shader's preamble
if (-local.x == workgroup.x << log2(local size)) buffer[k] = 0resets an append counter on the dispatch's first invocation, while the others add to it hundreds of instructions later. Nothing orders them in the API; it works where the first workgroup starts ahead of the rest. Apple's GPUs start workgroups in no order, so a workgroup that appended before the reset lost its entries to the next one's. - Fix:
first_storeindmsh_build.pyrecognises exactly that condition, for a flat local size or one with rows (the same test on y and x, with workgroup z zero), and takes the stores out of the shader; the reflection'sfirst_storehas the host make them in order before the dispatch (nvn_mtl.m). The stores may be one guarded block each, and a value may be a constant or a local set to one under the same guard. A guarded store it does not understand leaves the whole shader as it is: a first invocation that does more than plain stores (Mario Kart World's649e36162cad9e79, whose setup loops over a uniform's count) keeps the race. - Found on: Splatoon Raiders:
029d9c3ec1fcb39f(Hoian_Proc), the plants' instance lists, the only one of the game's 9 compute shaders with atomics that has it. The change per frame over the plants: 1.1, 2.4 or 4.5 at random, to a flat 1.0-1.3; pixels that jumped and returned the next frame: up to 88 % of them, to at most 21 %. The buffers the shader reads alternate frame by frame, which turned out unrelated. Mario Kart World:2ce9071c2f22d74fand5fea9b7ddb30e8a8(the scenery lists, four guarded blocks) and0823b08c2027a38d(local size 8x8), which the first form of the recogniser missed. Trees and bushes vanished in blocks with a still camera; over a title run a rebuild of the list lost 50 % of its entries on average, some well inside their draw range (406, 202, 797, 104 entries in turn), and 4 % after the fix, with no entry lost inside its range among those logged.DM_NVN_PASSDUMPof one frame shows no writer, as the list is rebuilt only every few frames: look over many. - Check:
python3 dm/gfx/tests/test_dmsh_first_store.py.
Goto elimination forcing loops around a whole program
- Symptom:
metalruns for hours on a shader of about 100 MB of MSL, mostly indentation, stuck in LICM (hoistRegion→ScalarEvolution::forgetValue), then the GPU compiler's connection breaks; even-O0and finished libraries crash it. Hundreds of forced one-pass loops nest around the program. - Cause:
MoveOutwardinGotoElimination.csencloses what follows an if in an else when it moves a goto out. When another goto jumps into that range, it needs a loop of its own, and each one encloses the others. - Fix: the else is skipped when a goto would have to jump into it (
HasGotoInto, the goto's own label included). Only shaders that got a forced loop change. - Found on: Splatoon Raiders: 26 such loops around the whole program in its uber shaders: the mid-size shader went from 176 loops to 0, the largest from 364 to 5, and 8 workers stalled for 5 h 40 before that. Three test shaders then compile in 89 s.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_control_flow.py.
A loop exit's subgroup block run by the lanes of every iteration together
- Symptom: a warp-aggregated atomic in a loop lands for one leader only: PRAGMATA's compute shader
607ceeefb9478700elects a leader, the lanes with its key leave the loop and reduce with oneSURED.MIN, and the others go round again; translated, the lanes that left in different iterations voted together, the ballot mixed keys, and the other keys' minimums were lost. Found by an offline differential check of the shader against the instruction stream; no picture traced to it yet. - Cause:
GotoEliminationturns a conditional branch out of a loop intof = X; if (f) break;in the loop andif (false || f) { B }after it. For one thread that is the same program, but when B has subgroup operations, the lanes that left in different iterations now run it together, where the GPU runs each iteration's lanes as their own group before they reconverge (BSYNC). - Fix:
StructuredIr/LoopExitCohort.cs, after goto elimination, moves B into the loop,if (f) { B; break; }, leaving the resetf = falsewhere B was. Only for a B with subgroup operations (directly or in a function it calls), and only in the exact shape where every thread runs the same statements in the same order: nothing butif (!f)blocks between the loop and B, no else, no other mention of f in B, no break or continue in B, and f otherwise only ever set to false. A B that ends the program (returnordiscard) keeps no break after it: the code generators take a block's last statement as its only terminator, andreturn; break;was SPIR-V with a branch outside any block, which SPIRV-Cross refused (Trying to end a non-existing block; Sonic Frontiers'0e6f8156033ae07e). Builds translate in debug mode, so the AST optimizer does not carry a ballot from B to a use elsewhere. - Entry guards: a constant condition needs no guard against an undefined value.
GotoElimination.GuardEntryConditionkeeps its direct logical condition; wrapping a constantfalselabel condition in a temporary hid the shape above fromLoopExitCohortand moved its subgroup block out of the loop again (caught by the control-flow tests in CI). Conditions whose definitions a jump may bypass still use the guarded evaluation. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_control_flow.py:test_loop_exit_target_with_subgroup_ops_stays_in_the_iterationfails without the pass;test_loop_exit_target_without_subgroup_ops_stays_after_the_loopchecks that a block without subgroup operations stays where it was;test_loop_exit_target_that_exits_has_no_break_after_it, a B that ends inEXIT. A translator A/B over a game's shader packages shows the reach: the changed shaders loseif (false || f)blocks and keep their subgroup calls. - Found on: PRAGMATA (12 of its 6,856 compute shaders,
607ceeefb9478700among them); Sonic Frontiers (80 of its 352 compute shaders, none of its pixel or vertex shaders; one B ends the program); Resident Evil 4 (6 of its 7,568 compute shaders). None in Nintendo Switch Sports Resort's compute, mesh and task shaders, Pokémon Sword's or Kirby Star Allies' compute shaders.
Ampere carries, PLOP3's second result, POPC / FLO immediates, LEA.SX32 and LEA's negated B
- Symptom: none met in a game yet: found by differential testing (single instructions with nvdisasm-checked encodings, run on an Apple GPU and compared with an interpreter on Mesa NAK's hardware-checked folds). A 64-bit three-operand add off by 2^32,
POPC R, 0x800000ffgiving 23, a predicate pair fromPLOP3that reads its own first result, a negative 32-bit index added to a 64-bit address as if positive. - Cause: IADD3 set its two carry predicates to the bits of the carry count, where the first is sum >= 2^32 and the second sum >= 2 * 2^32 (the high word's IADD3.X adds both); PLOP3 wrote its first destination before computing the second; POPC and FLO applied bit 63 as a bitwise not in every form, where in the immediate form (4) it is the immediate's top bit; LEA ignored
.SX32(bit 73: the high word is the sign extension of a); LEA negated B arithmetically with.X(the bitwise not there) and without it left the+ 1of~B + 1out of the carry. - Fix:
AIadd3,APlop3,APopc,AFloandALeainInstEmitAmpereAlu.csfollow those meanings. - Found on: no game; encodings from the CuAssembler sm_86 corpus, nvdisasm-guided fuzzing and variants.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(CarriesAndModifiers).
FSETP / ISETP pairs on their own accumulator, and IMAD's B
- Symptom: a predicate pair that disagrees with itself (
FSETP.LT.AND P0, P1, R2, R3, P0: P1 combined with the new P0, not the old); a multiply-add off by2 * a * b(IMAD read asa * -b + c). - Cause: FSETP and ISETP wrote their first predicate before computing the second, which reads the accumulator again, as PLOP3 did (previous entry). The decoder read bit 63 (bit 75 in the register-B forms) of IMAD, IMAD.WIDE and IMAD.HI as B's negation; IMAD has none there (nvdisasm prints no
-on B for either bit), only C's negation. - Fix:
ASetPredPaircomputes both results before writing either (FSETP, ISETP);AImadSrcsgives B without modifiers to the three IMAD forms (InstEmitAmpereAlu.cs). Ported from uncraftablexd's PRAGMATA bring-up (PR #1800). - Found on: PRAGMATA, from PR #1800; no picture or hang here has been traced to either alone.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(SingleInstructionSemantics: the four fail on the translator before).
Ampere jump tables read past their end
- Symptom:
BRX with no target, or code about 20 % larger than it should be. - Cause: a BRX's table in c1 stores no length. The decoder read entries until one failed, so a table ran on into the next one; a target of 0 counted as a jump to the start of the program; and it looked only on one path for the
LDCthat loads the table's base, so a base loaded before an if / else join was not found. - Fix:
FindBrxTargetsAmperereads a table one new target per pass, so the next table is known before this one overruns it, and stops at the next known base; an entry of 0 is filler for unused cases.FindBrxTableAmperewalks every predecessor and takes the base only when all paths reach the sameLDC. - Found on: Splatoon Raiders: 18
Hoian_UBERvertex shaders, 5 of them used at boot. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_control_flow.py.
An Ampere jump table loaded in a block split later
- Symptom:
BRX with no target found in the c1 jump table, although the shader'sLDCof the table's base is on the only path to the BRX. - Cause:
Block.Splitgives the right half the left half's successors but leaves their predecessor lists naming the left half.FindBrxTableAmperewalks those lists back to theLDC, so when the block holding theLDCwas split after its successors were linked (a later branch lands inside it), the walk from the BRX started in the left half, before the load, and met another write of the register or the program's start. - Fix:
Block.Splitpoints the moved successors' predecessor entries at the right half, for both decoders: the Maxwell decoder's walk from a BRX (FindBrxTargetRange) reads the same lists. No other code reads them except for their count. - Found on: Pokémon Pokopia: 16 pixel shaders (an
LDC c[0x1][R20+0x790], then a conditional BRA to the BRX). - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_control_flow.py(test_table_loaded_in_a_block_split_later).
MUFU.F16
- Symptom:
Ampere instruction 308refused; a neural upscaler's programs missing, so the frame never reaches the window (a black 3D scene). - Cause: MUFU has an F16 form (bit 73): the source is the half that bits 60..61 select (bit 62 its abs, as in every B slot), and the result goes back as the low half of the register, the high half zero. MUFU is the multi-function unit (op 2 EXP2, 3 LOG2, …), not a multiply.
- Fix:
AMufuinInstEmitAmpereAlu.cs. - Found on: Splatoon Raiders: 10 compute shaders of
agl_ndsr.pck. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
MUFU.SIN and MUFU.COS of a large number of turns
- Symptom: part of the picture without ambient occlusion, bounded by an arc whose centre is off the screen (the top-left corner), the rest correct; on Donkey Kong Bananza a wedge in the lower right of the SSAO's half-size target when dynamic resolution is at its top (1152x648 for a 2304x1296 scene, docked), a fifth of the picture with the effects at full size (1676x943).
- Cause: Ampere's
MUFU.SIN/COStake turns and use only their fraction, which is exact for any float. The translator multiplied the turns by 2π in float and took Metal'ssin/cosof that: the product rounds the fraction away (at 2^20 turns a step of 0.4 rad), and Metal's fastsin/cosreturn 0 from about 2^20 turns (6.6e6 rad) on, both of them. Bananza's SSAO (a6f04605183d9915) turns its kernel per pixel by (10 (3 (x mod y) + x y) + 5.652) / 2π turns; past x y ≈ 659,000 the rotation (cos, sin) was (0, 0), every sample landed on the pixel itself and nothing occluded it. The SSAO runs at half the scene's size, which dynamic resolution moves: at 838x471 (a 1676x943 scene) the product stays below 395,000, no hole, but angles up to 0.23 rad from the hardware's; at 1152x648 (the docked scene's top, 2304x1296) 5,425 pixels of the lower-right corner (0.7%) have no occlusion; at 1676x943 (the effects at full size) 346,009 (22%). - Fix:
AMufulowers both assin/cos((t − rint(t)) · 2π)(InstEmitAmpereAlu.csATurnsToRadians).t − rint(t)is exact and lies in [−0.5, 0.5], where fastsin/cosare accurate, and a small angle stays itself. The angles are the hardware's (within 2e-7), at every size; past 2^21 turns the fraction itself has only 4 values, as on the Switch. Maxwell code is unchanged (itsMUFUfollowsRROand takes radians; a huge angle there is open). Any Ampere shader that passessin/cosan angle that large, such as a per-pixel rotation built from pixel coordinates, had the same fault; only Bananza was checked. Every Switch 2 game's shaders that usesin/coschange (8,258 of Bananza's 23,638 shaders inregress.py check): a chain change. - Found on: Donkey Kong Bananza, its SSAO: a corner wedge at the top of dynamic resolution (1152x648), and a fifth of the picture with the effects at full size (1676x943, a local code patch of its effects-resolution levels, 0.5 to 1.0).
- Check:
make -C dm/gfx/tests GAME=<id> t_mufu_turns && dm/gfx/tests/t_mufu_turns(the lowering on the GPU againstcos/sin(2π · fract(t))in double over the SSAO's angles at 838x471, 1152x648, 1676x943 and 2560x1440: the earlier lowering collapses 0, 5,425, 345,255 and 1,893,254 rotations);DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(MufuTurns: the lowered MSL).
Scaled shared memory addresses
- Symptom: a compute shader's results in shared memory land in the wrong elements, or only part of its memory is cleared. An exposure histogram came back with its bins at about four times their index, the scene several stops too dark.
- Cause: LDS and STS with a register carry a stride at 78..79, so the register counts elements of 4, 8 or 16 bytes (stride 1, 2, 3), not bytes. The decoder ignored it. The field is a scale, not the access size: stride 3 occurs on 4, 8 and 16-byte accesses alike.
- Fix:
AStrideinInstEmitAmpereMem.cs, for LDL, LDS, STL, STS and ATOMS. LDSM keeps its mode at those bits (1 is a transposed read, MT88), so it takes its address unscaled (stride: false): scaled by that mode, Donkey Kong Bananza's upscaler (7629d857a0a93833, 12 of its 27 LDSM) read four times too far along, and the picture came out as an 8x8 lattice of garbage for as long as the upscaler ran, with nothing in the log. - Found on: Fire Emblem Fortune's Weave: 2 LDS and 2 STS with a register in its 16,888 shaders, all in the Lighting compute shaders;
d5bc99ffd183fa20bounds its register by the element count (0x20) before[R2 * 8]. Pokémon Pokopia: 921 accesses with stride 1, 68 with 2 and 3,312 with 3, among its 131,426 shaders;2118ab534fac88c6's histogram increments[R3 * 4]. Mario Kart World: its froxel shaders (03923de3c507135eand 35 variants) keep a float4 a thread at[R * 16 + 0x500]; unscaled, pull request #1151 reports the race picture in rainbow bands by depth slice. The stride is not the access size there:f94552a2a2bff505stores 8 bytes at[R9 * 16]and 4 at[R9 * 16 + 8]. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(Shared: each stride, on 4, 8 and 16-byte stores in the games' encodings).
Compute shared memory past 32 KB
- Symptom:
[RED] failed to create compute pipeline: Threadgroup memory size (49152) exceeds the maximum threadgroup memory allowed (32768), thousands a run; the dispatch is skipped. Once moved to device memory: with more than 512 workgroups in a dispatch, or an indirect one, workgroups found other workgroups' data in their shared memory (no game seen doing so). - Cause: Ampere gives a workgroup up to 100 KB of shared memory, and an Apple GPU 32 KB (
maxThreadgroupMemoryLength). SPIRV-Cross declares the shader's shared memory asthreadgrouparrays of its full size. - Fix:
dmsh_rewrite.pytg_spill: a kernel whose threadgroup arrays exceedDMSH_TG_MAXtakes them from a device buffer at compute buffer indexDMSH_TG_SLOT(dmsh_abi.h), one slice of their total per workgroup, at the workgroup's index in the whole grid (in 64 bits). Its threadgroup barriers order device memory too (mem_device | mem_threadgroup), and the reflection'stg_spillgives the bytes per workgroup.nvn_mtl.mdispatchbinds a slice of the submission's arena for every workgroup of the dispatch. An indirect dispatch's grid is in GPU memory: the replay waits for the GPU, as an indirect-count multi-draw does (mdi_wait), and reads it first, logging the first such dispatch. - Measurement: before, the slice was the workgroup's index modulo 512, on the assumption that workgroups 512 apart are not on the GPU together, and an indirect dispatch always got 512. Apple's GPUs start workgroups in no order. On an M6 (12 GPU cores), 64-thread workgroups ran up to 537 at once, and groups 512 apart overlapped from 1,024 workgroups on: 2 to 5 of 1,024 and 187 to 427 of 16,384 found their slice taken by another. The 48 KB kernel of the check, rewritten that way, got 126,988 of 262,144 sums wrong over 1,024 workgroups. Pull request #1242 found it, without a game's symptom; Mario Kart World never dispatched more than 3 workgroups of these shaders (below).
- Found on: Mario Kart World: 168 compute shaders of
DrivePassShaderDefaultdeclare 48 KB (spvUnsafeArray<uint, 12288>), 84 of them with barriers and none with shared atomics; all 168 compile rewritten. From the title to the first race all their dispatches are direct, of 1 to 3 workgroups, 6 a frame in the race. - Check:
python3 dm/gfx/tests/test_dmsh_tg_spill.py(the rewritten kernel compiles where the Metal compiler is installed, and with Xcode runs over 1,024 workgroups on this Mac's GPU, each summing data its workgroup wrote to its shared memory);make -C dm/gfx/tests check_t_tg_spillrunsdispatchover 1,024 such workgroups, direct and indirect, the indirect counts written by the GPU after the CPU's copy named one workgroup.
Compute dispatches past the pipeline's thread limit
- Symptom: on an M1 or M2 only,
[RED] compute pipeline for <key> allows 384 threads a threadgroup, its local size 8x8x8 needs 512 (its dispatches are skipped); before the host checked, the pass wrote nothing with no red line and no GPU error: its output kept its old contents (zeros for a volume the pass alone fills). Ocarina of Time loses Kokiri Forest's and Hyrule Field's haze and light shafts (the scene's upper half about 3.7 times darker); the same library is right on an M3 or M4, and the same MSL is right at-O0. - Cause: a Metal compute pipeline's
maxTotalThreadsPerThreadgroupis not always 1,024. On GPUs without Dynamic Caching (applegpu_g13*,applegpu_g14*: the M1 and M2, and the iPhone GPUs of their generation) it falls with the registers the kernel takes: 1,024 threads at up to 52 32-bit registers, 768 at 68, 640 at 80, 512 at 104, down to 384 at the most a thread can take, 128. The GPU compiler picks the registers without knowing the size the host will dispatch, and the host dispatches the Switch shader's local size (nvn_mtl.m), so a kernel compiled past that size's budget gets a dispatch larger than its pipeline allows, and no invocation runs. Ocarina of Time's froxel light injection9ed48d1011f1b48b(local size 8x8x8) takes 104 registers onapplegpu_g14gwith plain uniform reads, exactly the 512-thread budget, and 128 once its 195 reads at computed offsets are bounded as selects (918e9f34), so its six 128x72x96 volumes stayed zero; seven more froxel kernels of the game (8x8x8) are in the same state. Any change that adds registers to such a kernel can tip it over. Onapplegpu_g15*andapplegpu_g16*every size up to 1,024 fits (96 registers at most, spilling past them). - Fix: every game, a chain change.
dmsh_rewrite.max_threads, called bydmsh_build.pyfor every compute kernel after the other rewrites, puts the local size on the kernel as[[max_total_threads_per_threadgroup(N)]]when it is above 384. The front end passes it to the GPU compiler (air.max_work_group_size), which then fits the kernel's registers to N and spills what does not fit, as it does for a pipeline descriptor'smaxTotalThreadsPerThreadgroup. Sizes up to 384 are left as they are: no register count can refuse them, and onapplegpu_g13*/applegpu_g14*the attribute changes the code of most kernels that already fit. Onapplegpu_g15*/applegpu_g16*the GPU code is the same byte for byte. The host compares each guest compute pipeline'smaxTotalThreadsPerThreadgroupwith the shader's local size when it builds the pipeline (nvn_mtl.m), and skips that shader's dispatches with the red line above when the pipeline is too small, so a kernel the rewrite misses is named in the log instead of drawing nothing. - Found on: Ocarina of Time (issue #2425, M2 and M2 Pro). Measured offline with
applegpu-nt(Metal toolchain 32023.922,-arch applegpu_g14g) on9ed48d1011f1b48b's MSL: 128 registers as built, 104 with the attribute; the plain-read and branch forms (which worked on the M2) 104 and 100; at-O048. Withapplegpu_g16s(M4 Pro) the code with and without the attribute is identical. Across the games built here, on chain 2b9f460cf42c (metal-tt32023.922, the registers from the GPU binary's metadata, the limit taken as 53,248 registers in steps of 128 threads): kernels above 384 threads past their size's budget without the attribute onapplegpu_g13sandapplegpu_g14galike, Ocarina of Time 8 of 20 (the same eight an M1 Pro measured at 384 threads), PRAGMATA 73 of 255 (69 of them 1,024-thread kernels at 56 to 128 registers), Minecraft Dungeons II 1 of 39 (ce4e9fdf514d0196, 8x8x8, 124 registers), OCTOPATH TRAVELER II 0 of 19 and Fire Emblem: Three Houses 0 of 8; with it none, every kernel at its budget or under (52 registers at 1,024 threads, 104 at 512), and theapplegpu_g16scode of all 341 the same byte for byte. - Check:
python3 dm/gfx/tests/test_dmsh_max_threads.py(the sizes it marks and leaves; with Xcode, the rewritten kernel's IR names its size withdmsh_build.py's andios_metal.py's commands, and the plain one none).
Uniform references past the first kilobyte
- Symptom:
[RED] shader <key>_b reflection conversion failed: fetch call 0: frag_pos uniform reference out of range; the shader does not load and its draws are skipped. - Cause: the reflection keeps a uniform it reads on the host (a pixel-position sample's scale, an interpolated output's affine terms) as slot, vector and component in 16 bits, which held vectors up to 63, the first kilobyte of a uniform buffer; a uniform buffer is 64 KB.
- Fix: such references are 32 bits (
nvn_refl.m): slot << 16 | vector << 2 | component, vectors 0 to 4095. - Found on: Mario Kart World: pixel-position samples whose scale is at c[6] vector 989; 611 load failures in a run of its title.
- Check:
make -C dm/gfx/tests GAME=<id> check_t_refl check_t_feedback.
HADD2 and HMUL2 with an immediate
- Symptom: the GPU hangs (
kIOGPUCommandBufferCallbackErrorHang) from the first 3D scene on, or frames of about 88 ms, in a shader with a half-float loop. - Cause: the two-source half-pair operations took their second source from the operand order HFMA2 needs: in forms 2, 3 and 7 that is the unused register field at bit 64, not the immediate, constant or uniform register. A blur stepping its loop with
HADD2 Rd, Rd, immstepped by whatever R0 held. An immediate also took modifiers from its own bits 62 and 63, flipping the sign of a negative constant. - Fix:
AHalfSecondinInstEmitAmpereAlu.csfor HADD2, HMUL2, HSETP2, HSET2 and HMNMX2;AHalfSrcsleaves an immediate's bits alone. - Found on: Pokémon Pokopia: 25,726 of its shaders use those forms;
85446a6753300fc8is the blur. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(Pokopia: constants, a negative immediate's sign) andDMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(HalfImmediate: on a live register).
HFMA2 .H0_NH1
- Symptom: wrong shading where a shader needs a cross product or a 2D rotation of half pairs; on Eden-NS2, which first read the mode as a plain negation of the high lane, sun and cloud shadows were lost.
- Cause: bit 86 of HFMA2 rotates B: the name gives the lanes high first, so the high lane reads B's low half and the low lane B's high half negated. The decoder ignored the bit.
- Fix:
AHfma2inInstEmitAmpereAlu.cs. The lane order comes from Eden-NS2's fix (checked there against Switch 2 footage), not from a shader that proves it here. - Found on: Pokémon Pokopia: 10,177 instructions in 7,590 programs. The fix made no visible difference in its tutorial area.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
Global memory: descriptors, ATOMG.CAS, INC / DEC
- Symptom: a global load, store or atomic at the wrong address in code that uses
desc[URb][Ra.64](the descriptor's value added to the address); a shader withATOMG.CASrefused (Ampere instruction 3a9 ... is not implemented); anATOMG.INC/ATOMG.DEC/RED.INC/RED.DECwith no effect. - Cause:
AGlobalAddressadded the uniform register in every uniform form. nvdisasm (sm_86) names two forms:[Ra.64+URb], where URb is part of the address, anddesc[URb][Ra.64](bit 76 of LDG / STG, bit 71 of ATOMG / RED), where it is a memory descriptor (the compiler's cache policy) and the address is Ra.64 alone. Unreal Engine 5.4's bounded read (LDG.!P0 R5, [R5 + UR4],GuardedWrites) is the first form and is unchanged. Opcode 0x3a9 was not registered; INC and DEC have no case inEmitAtomicOp. - Fix:
AGlobalAddresstakes the form's descriptor bit;AAtomgCas(0x3a9, 32 bits: Rb expected, Rc at 64 the new value, the old value returned);AGlobalIncDec, a compare-and-swap loop as ATOMS's, for ATOMG and RED. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(GlobalMemory: the three fail onmain). A GPU cross-check of 300 LDG / STG / ATOMG / RED from an nvdisasm-validated corpus (sm_86 and sm_80 compiled code), as one-thread compute shaders through a gmem_map the harness builds as the host does (dmsh_abi.hDMSH_GMEM_MAP_*), production options: 135 identical to 300. Which forms NVN's compiler emits for games is not known here: the descriptor form is CUDA's usual one, and no game note in this repository shows it. - Found on: cross-checking the translator against nvdisasm and a reference interpreter; no game run.
Maxwell PRMT byte permutation
- Symptom: the translator reports
Shader instruction PrmtI is not implemented.(orPrmtR,PrmtC,PrmtRc), and leaves the destination unchanged. A shader may still compile despite the missing operation. - Cause: the Maxwell decoder recognized the register, immediate-selector and two constant-buffer forms, but all four emitters only logged a note. Ampere's separate PRMT emitter did not cover these encodings.
- Fix: Maxwell PRMT selects four bytes from its two data operands. In generic mode each selector nibble names one of eight bytes and may replicate that byte's sign; F4E, B4E, RC8, ECL, ECR and RC16 use the selector's low two bits and copy bytes without sign replication, as specified by NVIDIA's PTX PRMT table. The
Rcencoding takes its selector from the register field and its upper data word from the constant buffer. Reserved mode values fail translation. The shader chain changes, so existing shader libraries must be rebuilt. - Found on: EA SPORTS FC 27 and Farming Simulator 26 recorded
PrmtIin their shader builds. The game notes record rebuild and runtime status. #2040 identified the missing Maxwell implementation separately from the Ampere series.
Maxwell ATOM.CAS
- Symptom: the shader build counts
Shader instruction AtomCas is not implemented.among the translator's messages, and the shader still loads: its global compare-and-swap does nothing and its result register keeps its old contents (a hash-table insertion or a lock-free update that never lands). - Cause: Ryujinx's Maxwell
AtomCasonly logged. Its fields, from envytools'gm107.c(the 0xeef0 row:atommem0_imm,tabeef0sz) and nvdisasm's sm_61 records in CuAssembler: Rd at 0, Ra at 8, Rb at 20, a signed byte displacement at 28..47,.Eat 48,.64at 49.ATOM.E.CAS R3, [R2], R10, R11compares the word with Rb, swaps in Rb + 1 and returns the old word (CUDA atomicCAS); the second source is implied. Every recorded form has an even Rb and bits 50..51 (Ryujinx'sBcRz) clear. - Fix: a chain change (
InstEmitMemory.csAtomCas): a global compare-and-swap on the 40-bit address, Rd the old word, through the same storage buffer or pool table lowering asATOM. The 64-bit form (Metal has no 64-bit compare-and-swap), set bits 50..51 and an odd or RZ Rb fail translation (ATOM.CAS at 0x…: only the 32-bit form …), as unsupported image atomic forms do; no compiled code has them. - Check:
DMSH_TEST_XLATE=<translator> DMSH_TEST_METAL=1 DMSH_TEST_GPU=1 python3 -m unittest -v dm/tools/tests/test_global_memory.py: the old word, the swap, a mismatch, both displacement signs, predication, a 32-bit address, Rd equal to Ra, Rb or Rb + 1, Rd = RZ, and the pool table route, all 1,024 words of the buffer checked on the GPU (dm/gfx/tests/t_global_memory.m); the rejected forms fail. EachATOM.CAScase fails on the translator before the fix. - Found on: EA SPORTS FC 27: compute shader
90ce32c070f208a5(ATOM.E.CAS R6, [R6], R8, R9), the onlyATOM.CASin the Maxwell games' shaders on this Mac's drives; not met in the menus or a match, so no change on screen is known. Retranslating the game's 3,222 compute shaders changed that one alone. Also reported in LOLLIPOP CHAINSAW RePOP (pull request #684, whose profile is not in this repository), in a feedback-compaction compute shader on its prologue route, with no measured change on screen.
A negative displacement on a 40-bit global address
- Symptom: a load through a pointer the shader read from memory gives 0, and a store or atomic through one does nothing, when the instruction has
.Eand a negative displacement (LDG.E R4, [R2+-0x4]); aREDwith a negative displacement does nothing on either route. - Cause: two errors in Ryujinx's Maxwell global addresses.
Get40BitsAddressadded the displacement to the low word and the carry out of it to the high word, but no sign: a negative displacement is 2^32 − k unsigned, whose add carries unless the low word borrows, so the high word came out one too high, 4 GB up. Accesses the translator turns into a descriptor's storage buffer take their offset from the low words and were right; the memory pool table's lookup takes the whole address (Global memory at an address loaded from memory), finds no pool there and drops the access. AndRedpassed its 20-bit displacement unsigned (atommem0_immis signed, asATOM's), 1 MB on instead of back. - Fix: a chain change (
InstEmitMemory.cs): a negative displacement adds −1 to the high word with the carry;Redsign-extends its displacement. - Check:
dm/tools/tests/test_global_memory.py(above): itspointer_*cases with negative displacements, among them one whose low word borrows (0x2_00000004 − 8), fail without the high-word change, and itsred_*cases without the sign. - Found on: reviewing the
ATOM.CASwork of pull request #684. Among the Maxwell games' shaders on this Mac's drives, only Sid Meier's Civilization VII has.Eaccesses with negative displacements (oneATOMshader, fiveLDG/STGin another), and none goes through the pool table, so no game picture is known to change.
ATOMS.INC / ATOMS.DEC, and ATOMS.CAS's result
- Symptom: a shared-memory counter that never moves (
ATOMS.INC,ATOMS.DEC: CUDA's atomicInc / atomicDec, the old value read as 0); a lock-free update on shared memory that loops or takes a wrong branch afterATOMS.CAS(its result 0 or 1 instead of the old value). - Cause:
AAtomshands operations 3 and 4 toEmitAtomicOp, which has no case for them: it logs "Invalid atomic operation" and gives the constant 0, with no access.AAtomsCasgave every compare-and-swap CAST.SPIN's result; nvdisasm names three forms by bit 87 (CAS clear, CAST set, CAST.SPIN with bit 88 too), and a plain CAS gives the old value (PTXatom.cas). - Fix: INC (
old >= b ? 0 : old + 1) and DEC (old == 0 || old > b ? b : old - 1) are a compare-and-swap loop inAAtoms;AAtomsCasgives the old value when bit 87 is clear, 1 / 0 for CAST and CAST.SPIN as before (Fire Emblem Fortune's Weave's retry loop). - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(SharedAtomics: the three fail onmain). A GPU cross-check of 400 LDS / STS / ATOMS from an nvdisasm-validated sm_86 corpus, run as one-thread compute shaders with the production options (debug and reduced on, MSL 2.3), against a reference: 84 mismatches (all INC, DEC and CAS) to none; the same on encodings from real compiled code. - Found on: cross-checking the translator against nvdisasm and a reference interpreter; no game run. Also seen with
debug: false(the AST optimizer, off by default): a shared store of 8 or 16 bits makes the translator throw, and an ATOMS whose result goes to RZ is dropped.
FRND of a half (FRND.F16)
- Symptom:
[translation failed] NotSupportedException: Ampere 307 at …: FRND of a float that is not 32-bit. - Cause: the emitter took 32-bit floats only.
FRND.F16rounds a half to an integer value: both sizes are 1 (bits 84..86 and 75..77), the rounding at 78..80 as for a float. - Fix: a chain change (
AFrndin the vendoredInstEmitAmpereAlu.cs). The half bits 60..62 select (as F2F's) is unpacked, rounded in 32 bits and packed into the low 16 bits. The pack is exact: every half from 2^10 up is an integer already, and an integer below 2^11 has at most 11 significant bits. That the half is selected as F2F's is taken from F2F, not from a disassembly of a high-half case (all of PRAGMATA's read the low half). A source and result of different sizes still fail. - Found on: PRAGMATA: 65 shaders (47 compute, 11 vertex, 7 pixel), nearest and floor.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py -k Frnd.
Ampere forms met on PRAGMATA: TLD through a uniform register, I2F of an immediate, SUATOM.CAS
- Symptom:
[translation failed] NotSupportedException: Ampere instruction f66 … is not implemented,Ampere instruction 595 … is not implemented, orAmpere 906 …: I2F byte select of a 32-bit source. - Cause: three forms the emitters did not take. 0xf66 is TLD with its handle in a uniform register (40..46), the fetch beside 0xf60 (TEX), 0xf63 (TLD4), 0xf69 (TMML) and 0xf6c (TXD): its other fields are 0xb66's. That reading is the family's pattern (0xf60 + 3n beside 0xb60 + 3n), not a disassembly. 0x595 is SUATOM's compare-and-swap through a bound handle: Mesa's NAK encodes the bindless ones as 0x394 (atomic) and 0x396 (compare-and-swap, its data the pair compare value, new value), and 0x593 is 0x394 with the handle bound. I2F in its immediate form (0x906) has the value in 32..63, so 60..62 select no byte there; an immediate of -2 read as select 7.
- Fix: a chain change (vendored
InstEmitAmpereMem.cs:ATextakes 0xf66,ASuatomCas;InstEmitAmpereAlu.cs:AI2freads no select from an immediate). - Found on: PRAGMATA: 17 shaders with 0xf66 (11 vertex, 6 pixel), compute shader
50fece0d891feba4with 0x595, 3 compute shaders with the I2F. All build; none has been watched drawing. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py -k I2fImmediate; the other two forms are checked by PRAGMATA's build only.
Indexed Ampere patch outputs
- Symptom:
[translation failed] NotSupportedException: Ampere 322 at 0x6d0: AST with an offset register and an addressfor a hull shader. - Cause:
AST.Pcan select a patch word with a register plus its immediate byte offset. The emitter rejected every such non-physical attribute store, and usage tracking treated its outputs as per-control-point attributes instead of patch attributes. Welcome Tour's hull sets the register toInvocationId * 4, writes an outer tessellation factor there, then writes its inner factor at 0x10. The instruction fields are independently described by Mesa NAK's SM70 encoder. - Fix:
InstEmitAmpereMem.csemits each component at register + immediate + 4 times its component index. Patch words 0–3 select the outer factors, 4–5 the inner factors, and the rest select the patch's user location and component. Locations are dispatched as constants for the SPIR-V interface; components remain indexed.DecoderAmpere.csrecords patch output usage without enabling indexing of per-control-point outputs. Scalar and vector stores, immediate offsets, the end of the patch map and 32-bit address wrap are checked numerically on Metal. Ordinary non-physical indexedASTwithout.Premains unsupported. - Found on: Nintendo Switch 2 Welcome Tour, Bezel PBR hull shader
0b9e5d475e9afd21, in_SystemBuiltinRenderer.ounce.bea(bezel_pbr.bfsha). Its repaired hull compiles through the production tessellation lowering; no draw using it was observed in Area A. - Check:
DMSH_TEST_XLATE=<translator> DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_ampere_patch.py: every valid patch word, out-of-range and wrapping addresses, and four-component stores crossing factor and user-output boundaries. A translation-chain change, with no game or build binding.
IPA at an offset, and the barycentric coordinates
- Symptom:
[translation failed] NotSupportedException: Ampere 326 at …: IPA at an offset; before the offset is reached, the build's log hasAttribute offset 0x3B4 is not validand the read gives 0. - Cause: two things the attribute emitters did not have. IPA's sample location 2 (bits 76..78) interpolates at an offset from the pixel centre, the offset word in the second source register (32..40): x in bits 8..11 and y in bits 24..27, signed, in 1/16 pixel (Mesa NAK's
load_barycentric_offsetbuilds a signed 12-bit value in 1/4096 per half and clamps it to -0.5..0.4375, so only those four bits vary; GLSLC's code masks them with0xf00and0x0f000000). Anda[0x3a8..0x3b0]anda[0x3b4..0x3bc]are the pixel's barycentric coordinates, screen-linear and perspective, three words each, Mesa'sNAK_ATTR_BARY_COORD_NO_PERSP_X..ZandNAK_ATTR_BARY_COORD_X..Z(this entry first read the perspective group as two words with a third of 1 - x - y; Resident Evil 4's shaders reada[0x3bc], and Mesa'snak_private.hhas it there); the perspective pair is read like any perspective attribute, divided by w, and the shader multiplies by 1 /a[0x7c]read at the same place. - Fix: a chain change.
AttributeMap.csmaps both groups to new inputs (IoVariable.BaryCoord,BaryCoordNoPersp: SPIR-VBaryCoordKHR/BaryCoordNoPerspKHRwithSPV_KHR_fragment_shader_barycentric, MSL[[barycentric_coord]]), andEmitIpamultiplies the perspective pair bygl_FragCoord.w. For the offset (AIpapasses the register,EmitIpa), what IPA.PASS reads (an attribute over w, 1 / w, a screen-linear attribute, the position) is linear over the screen within the primitive, so its value at the offset is the centre's plus the offset times its screen derivatives, which are exact for a linear function:v + dFdx(v) * ox + dFdy(v) * oy. That needs nointerpolateAtOffset, which SPIRV-Cross can give a user attribute only (aninterpolant<>member), not the built-ins this shader reads. A constant (flat) read and the integer attributes take no offset. Maxwell's IPA has the same location field, not met and not changed. - Found on: PRAGMATA: pixel shader
4a9d4507eea6c837reads 1 / w and the perspective barycentric pair at the position of the sample it runs for (the table byte atc0 + 0x620, shifted into the offset word); it builds; no draw with it has been watched. No other of its 36,779 shaders has either. - Open: on a multisampled target SPIRV-Cross moves
gl_FragCoord.xyto the sample, while IPA ofa[0x70]/a[0x74]at the default location is the pixel centre: a shader that adds the sample offset itself (PRAGMATA's 154 sample position readers) would add it twice. Not met: the game's per-sample shaders have been seen on single-sample targets only. Derivatives are taken where the IPA stands; one inside non-uniform control flow has not been met. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py -k IpaAtOffset.
LDTRAM: an attribute at each vertex of the triangle
- Symptom:
[translation failed]for Ampere opcode3adin thousands of pixel shaders (Resident Evil 4: 7,246 of its 42,313 shaders did not build). - Cause: 0x3ad is LDTRAM, which reads a user attribute as the triangle's vertices hold it, not interpolated: Mesa NAK's
OpLdTram, which lowersload_input_vertex(fragment shader barycentrics). The attribute address in words is in bits 64..71; with bit 72 clear (.AB) Rd gets vertex 0's word and Rd + 1 vertex 1's, with it set (.C) Rd gets vertex 2's. The shader weighs the three itself with the barycentric coordinates (a[0x3b8],a[0x3bc], above). The translator had no emitter for it, and SPIRV-Cross has no MSL form of SPIR-V'sPerVertexKHR. - Fix: a chain change.
InstEmitAmpereMem.csALdTramloads a new input,IoVariable.UserDefinedPerVertex(location = attribute × 3 + vertex, component = the word), whichDeclarations.csdeclares as a flatvec4nameddm_pv<attribute>_<vertex>at location 64 + that, past every attribute's own.dmsh_rewrite.per_vertexthen makes the reads of attribute L one MSL 4.0vertex_value<float4>atuser(locn<L>), fed by the vertex shader's output there (whichvs_padpads when the vertex shader does not write it), and each read that vertex'sget(vertex_index::first / second / third), the vertices[[barycentric_coord]]weighs. The Mac's deployment target is already MSL 4.0;ios_metal.compilecompiles such a source with-std=metal4.0, which iOS 26 loads, and every other source as before. A shader that also interpolates the attribute is refused (per-vertex input rewrite failed); none is known. - Found on: Resident Evil 4: 7,225 of its 18,248 pixel shaders read generic attribute 1, 2 or 3 this way, never one they also interpolate; most leave it out of their SPH input map.
- Open: an iPhone on iOS 18 to 25 cannot load those libraries. Vertex order is taken to match between NVN and Metal; not yet checked against a frame.
- Check:
DMSH_TEST_METAL=1 python3 dm/gfx/tests/test_dmsh_per_vertex.py.
The shared compare-and-swap loop retries with the value it got
- Symptom: a shared-memory atomic built from a compare-and-swap loop (INC, DEC, the 64-bit and float operations) spins longer than it should or stores a value computed from stale data when other threads write the word.
- Cause: the loop
GenerateSharedAtomicCasLoop(HelperFunctionManager.cs) writes reloaded the word at the head of every iteration instead of taking the value the failed exchange returned, which is the word's current value. The reload is a plain load between atomics, with no ordering against them. - Fix: the old value is loaded once before the loop; each iteration computes from it, and a failed exchange's result becomes the next iteration's old value. Ported from uncraftablexd's PRAGMATA bring-up (PR #1796).
- Found on: PRAGMATA, from PR #1796; not traced to a symptom here.
Half-pair swizzle on a constant, and .F32
- Symptom: wrong values in the high lane of half-pair math that scales by one half of a uniform (
HMUL2 R37, R37.H0_H0, c[0x0] [0x168].H0_H0), or a garbage operand where a half-pair operation reads a 32-bit float (R20.F32). - Cause:
AHalfLanestook a constant operand as is, ignoring its swizzle (bits 60..61 in the 32 slot, where a constant lives), so.H0_H0/.H1_H1on a constant gave the high lane the constant's other half. Swizzle value 1 was read as.H1_H1; nvdisasm (sm_86) names it.F32in all three slots (A 74..75, the 32 slot 60..61, the 64 slot 81..82), the operand's own 32-bit float. Only an immediate has no swizzle: those bits are its own. - Fix:
AHalfLanesinInstEmitAmpereAlu.csapplies the swizzle to constants and takes.F32as the float itself in both lanes (the lanes are computed in 32 bits already). MUFU.F16, whose bits 60..61 pick one half (.H0/.H1), keeps its own reading..F32's exact rounding on NVIDIA (whether the float is rounded to a half first) is not known; the float itself is the closer reading than its top 16 bits. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(HalfSwizzle: the three fail onmain), andtest_dmsh_ampere_mem.py'sMufuF16. A GPU cross-check of 900 HADD2 / HMUL2 / HFMA2 from an nvdisasm-validated sm_86 corpus against an exact binary16 reference (one rounding, FMA included) went from 86 mismatches on constant swizzles to none; what is left is.FMZ(0 times infinity). The half .RELU NaN correction is shared by ordinary HFMA2 and HMUL2. - Found on: cross-checking the translator against nvdisasm and a reference interpreter; no game run.
HSETP2 / HSET2 .FTZ
- Symptom: a half comparison with
.FTZon a subnormal operand passes where NVIDIA's fails (or the reverse):HSET2.BF.GT.FTZ R6, R19, RZgives 1.0 for a positive subnormal half, 0 on NVIDIA. - Cause: bit 80 of HSETP2 and HSET2 was dropped.
AFtz(FSETP / FSET) does not fit: the half lanes are unpacked to 32-bit floats, where a half's subnormals are normal, soFlushDenormal's bound never flushes them. - Fix:
AHalfFtzinInstEmitAmpereAlu.csflushes each lane under the half's own bound (2^-14) before the comparison. The arithmetic shares the signed flush described in Half-pair .FTZ flushes f16 subnormals. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(HalfCompareFtz: two fail before the comparison fix). The GPU cross-check with subnormal and zero inputs: 4 HSETP2 / HSET2 mismatches in 400, none with the fix. HMNMX2.FTZ now shares the source flush and has synthetic boundary coverage. - Found on: cross-checking the translator against nvdisasm and a reference interpreter (NAK's
OpHSetP2gives the.H_ANDreading the translator already has); no game run.
I2F and F2F directed rounding
- Symptom: integer division results one off for some operands (the compiler's 32-bit division takes its reciprocal from
I2F.U32.RP), or a half one ulp off (an overflow giving infinity instead of the largest finite value) afterF2F.F16.F32.RM/.RP/.RZ. - Cause: the rounding field (78..79:
.RM1,.RP2,.RZ3) was decoded but not applied: I2F and the pack of F2F round to nearest. For a 32-bit integer above 2^24, I2F rounded to nearest is one ulp off the directed result about half the time. A first fix of F2F also met the optimizer'sPropagatePack, which takes an unpack of a pack for the packed float itself (dropping the half's rounding). - Fix:
AI2f(32-bit source, 32-bit float) andAF2f(F32 to F16) inInstEmitAmpereAlu.cscompare the rounded result with the exact value (the integer converted back, exact below 2^31 / 2^32; the half read back through a mask) and step its bits to the neighbourADirectedpicks. Narrow integer sources are exact; I2F to a half keeps rounding to nearest. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(DirectedRounding: two fail onmain). A GPU cross-check against an exact reference (one rounding, IEEE directed modes; NAK's hardware test for F2F.F16.F32.RZ's overflow): I2F 45 mismatches in 300, none with the fix; F2F 25-31 in 300, 6 left, all with results at or below 0x050d (half subnormals and the smallest normals, where the GPU's own conversion differs). Also left: FRND / F2I of a 32-bit subnormal (FLOOR of a tiny negative is -1 on NVIDIA; the GPU flushes it to zero). - Found on: cross-checking the translator against nvdisasm and a reference interpreter; no game run.
I2F from a 64-bit integer rounds once
- Symptom:
I2Ffrom a signed or unsigned 64-bit register pair to f32 can give the wrong float. A negative integer close to zero can lose its entire value during cancellation. - Cause:
AI2f64rounded the high and low words separately as floats before adding them, and discarded the rounding mode. The division sequence that introduced the emitter used a zero high word, where the old nearest-rounding calculation is exact. - Fix: form the magnitude as two integer words, normalize to recover the 24 retained bits and the round and sticky bits, and round once in the encoded mode. Set the low bit of the leading-bit search operand to keep the shift counts valid for zero. Return positive zero for a zero input. This applies to the Ampere register-pair form with an f32 destination.
- Check:
test_dmsh_ampere_orin.pyon M4 Pro, macOS 27.2.1, Metal 32023.922. Signed nearest-even changes from 16 differences to zero across 1,024 recorded Jetson Orin lanes. All 112 synthetic boundary lanes and a separate 36,244-lane exact-reference comparison match on the Mac for signed and unsigned inputs in RN, RM, RP and RZ. All eight synthetic shaders validate as SPIR-V and compile offline for iOS. The directed modes and unsigned conversion are covered by synthetic references. No games or iOS device ran. - Found on: the Jetson Orin sm_87 probes from PR #2045. The opcode appears in the Fire Emblem Fortune's Weave lighting path.
F2FP packs BF16 and applies RELU and RZ
- Symptom:
F2FP.BF16.PACK_ABreturns a pair of F16 values, andF2FP.RELU.PACK_ABkeeps negative values. A toward-zero pack can round away from zero or turn a finite value into infinity. - Cause:
AF2fpused the same nearest-even F16 pack for allPACK_ABinstructions. It ignored the format, clamp and rounding bits. - Fix: clamp negative inputs, including -0 and -infinity, to +0 for
.RELU. Preserve NaNs through the clamp and emit canonical0x7fffin.RELUlanes. BF16 uses the upper 16 input bits, with a nearest-even bias when requested, and canonicalizes NaNs. F16.RZwidens the rounded half's magnitude and steps it back one code when a finite input rounded away from zero. Plain F16.RNand Pokopia's plain.MERGE_Ckeep their existing conversion. - Check:
test_dmsh_ampere_orin.pyon M4 Pro, macOS 27.2.1, Metal 32023.922. Recorded differences fall from 1,880 to zero for BF16 and from 913 to zero for F16.RELU, each across 2,048 halves. Plain F16.RNhas the same 44 NaN-bit differences (Orin0x7fff, Metal0x7e00). Six synthetic forms cover BF16 ties, combined BF16.RELUand F16 truncation. All 64 exact boundary halves pass with default and relaxed Mac math, and a separate sweep of 2,072,574 halves also matches its exact reference. Eight shaders compile offline for iOS. Plain F16.RNand both plain Pokopia.MERGE_Cexamples emit identical MSL on main and the fix. - Found on: the Jetson Orin sm_87 probes from PR #2046. The new combinations and
.RZare checked against synthetic references. No game or iOS device ran.
IDP integer dot products
- Symptom: an Ampere shader using
dp4aordp2afails translation withAmpere instruction 226 ... is not implementedfor the register form. - Cause: the Ampere decoder had no IDP entry for opcode
0x026in the low nine bits. - Fix: register
InstName.Idpand use the shared ALU operand reader.AIdpextracts the four bytes of each source for DP4A or extracts two halfwords of A and B's low or high pair of bytes for DP2A. Signedness is independent for each source. Integer multiplies and adds accumulate the products into C with 32-bit wraparound. Before optimization the lowering emits 16 IR operations for DP4A and eight for DP2A. - Check:
test_dmsh_ampere_orin.pyon M4 Pro, macOS 27.2.1, Metal 32023.922. All five recorded register programs were refused on main and now match all 5,120 Orin lanes. Four synthetic shaders cover the B and C constant-buffer slots for DP4A and DP2A, with all 16 lanes matching using a nonzero Metal argument-buffer word atc[3][5]. Another 144 synthetic lanes cover independent signedness, DP2A low and high pairs, wraparound, immediate and uniform-register inputs. All 27 IDP shaders validate as SPIR-V and compile offline for iOS. - Found on: the Jetson Orin sm_87 probes from PR #2052. Only register forms have recorded Orin outputs in this fixture. No affected game is documented. No games or iOS device ran.
VABSDIFF, the absolute difference with an add
- Symptom: an Ampere shader using
sad.u32fails translation withAmpere instruction 214 ... is not implementedfor the register form. - Cause: the GPU compiler emits
VABSDIFF.U32, and the Ampere decoder had no entry for opcode0x014in the low nine bits. - Fix:
AVabsdiffuses the shared ALU operand reader and emitsmax(a, b) - min(a, b) + cwith 32-bit wraparound. Bit 73 selects signed ordering. Bits 81–83 are thePupredicate field. The recorded form usesPT, so otherPuvalues and unrecognized modifiers are rejected. The lowering emits four integer IR operations before optimization. - Check:
test_dmsh_ampere_orin.pyon M4 Pro, macOS 27.2.1, Metal 32023.922. The previously refused unsigned register program now matches all 1,024 recorded lanes, including 416 wrapping additions. All 64 synthetic lanes match, including signed extrema, immediate and uniform-register sources, and 16 lanes using nonzero constants atc[3][5]in slots B and C. Separate probes confirm that a non-PTPuand an unrecognized modifier fail translation. Nine supported shaders validate as SPIR-V and compile and link offline for iOS. - Found on: the Jetson Orin sm_87 probes from PR #2053. Signed and non-register cases use synthetic references. No affected game is documented. No games or iOS device ran.
A guarded load whose destination is its address
- Symptom: none in the log: everything drawn with an engine's scene data lands on the first instance's transform, or at nothing. In the MSL, a bounds-checked read has a constant index (
vp_s2._m0[0]) just after a comparison of the register it should use. - Cause: a uniform-form LDG (
0x981) with a predicate is zero where the predicate is false, so the translator zeroed the destination first and then read the address. WithLDG.P R5, [R5 + UR4]the address was already gone. - Fix:
ALdgreads the address into locals before anything is written. - Found on: Yoshi and the Mysterious Book: Unreal Engine 5.4's GPU scene reads, every one of them; the first step away from a black scene.
A deferred write under a false guard
- Symptom: the scene goes white with a yellow fringe: a few objects hold the largest value their target can, and bloom spreads it over the picture. Clamping a shader's terms one by one finds a value that is a register's stale contents. Or characters lit from an environment cube turn bright white in certain places only, and the cube's mean is far above its value elsewhere.
- Cause: an instruction with a write barrier writes through a shadow register, which starts as the register's value and is copied back at the first instruction that waits on the barrier. A guarded one whose guard is false writes nothing on hardware, but the copy still ran, and overwrote whatever had been written meanwhile. Here:
EXP2 R17under P4,R17 = R29 * R29under !P4, then the wait; under !P4, R17 got back a squared distance from long before, and the light's falloff with it. - Fix:
EmitOpsAmperekeeps the guard as it was at issue in a shadow register of its own and commits only where it held. A predicated last instruction of a block no longer branches straight to the next block when writes are pending, which skipped their commits. A later guarded write no longer discards an earlier pending one, which may still be the one that lands. - Found on: Yoshi and the Mysterious Book: the first light's falloff, 65,000 in R11G11B10 on leaves and eggs. Donkey Kong Bananza (GitHub issue 1100): DK and Pauline white between Hilltop's rocks. The terrain capture shader
7612419c02d496b9picks its material with@P0 IPA R8then@!P0 MOV R8as a block's last instruction, and always got material 0, a placeholder with an emissive scale of 30, so the environment cube's red mean reached 53 against about 1.2 elsewhere. A hand patch of that one selection, on the old chain, brought it to 0.45 at the spot with DK normal. On chain 3dd02e581c0c the shader's MSL has the right selection; the spot itself was not revisited on that chain.
Ampere forms with a handle in a register, and SURED's other operations
- Symptom:
Ampere instruction f63(orf6c,364,367,394)is not implemented, orSURED form 0310e000, in the build. - Cause: 0xf60 and 0x361 were known for TEX. The same pairs exist for the others: 0xf63 and 0xf6c are TLD4 and TXD through a uniform register at 40..46, 0x364 and 0x367 are TLD4 and TLD through a register, the first of the second source block, each otherwise laid out as its bound form. 0x364's meaning was inferred from these siblings, and its use agrees: Yoshi's single-layer water converts each of its four results as a device Z (
c4[66]), which only a gather of a depth texture gives. SURED takes SUATOM's operation field (87..91): MAX, OR and MIN on 32 bits turn up. - Fix:
ATexmaps them to the bound forms,ASuredtakes the operation. TMML has the same pair, 0xf69 and 0x36a (Kirby Air Riders' cube map LOD, 4,776 pixel shaders), with a binding of its own only when the handle is bound by its slot. SURED.MAX.U64 (33,550 uses, Nanite's visibility buffer) is now a 64-bit texture atomic on Apple GPU family 9; this game has not been rebuilt with it. - TXQ: 0xf6f is TXQ (0xb6f) through a uniform register at 40..46, Ra the LOD (
ATxq; PRAGMATA: 12 shaders); the size query reads the pools like any handle no slot holds. Check:GuardedWrites.test_size_query_through_a_uniform_register_translates. - Surfaces:
Ampere instruction 394 … is not implemented(00321e00001ee014…7394). Each surface instruction has a form with the handle in a register at 64..72 (Rc), 0x1ff below its bound form, which names a constant buffer word at 40..59: SULD 0x998 / 0x99a, SUST 0x99c / 0x99e, SUATOM 0x394, SUATOM.CAS 0x396 and SURED 0x3a0, the opcodes Mesa NAK encodes (itssm70_encode.rsOpSuLd,OpSuSt,OpSuAtom), with the other fields where the bound forms have them.ASurfaceHandlegives the register forms a bindless handle from Rc, and bindless elimination finds the constant buffer word the register was loaded from, as for TEX through a register. Orbitals's global compute shaders take Unreal's ShaderPrint counter with SUATOM.ADD.U32 on a 1D buffer image whose handle a MOV reads fromc[3][0](45389d82b79dbf0c+0x1850:MOV R12, c[3][0]; MOV R20, R12; SUATOM R12, [R12], R24, R20): 5 compute shaders stopped there. Only 0x394 is met in a game; the others follow from the same pairing (chain change). Check:Suatom.test_handle_in_a_register,Suatom.test_reduction_with_its_handle_in_a_register. - Found on: Kirby Air Riders (TMML); Orbitals (SUATOM through a register); Yoshi and the Mysterious Book. Its shaders' jump tables also ran past their code on two compute shaders (
ArgumentOutOfRangeException, inGetCode): an address past the code is now no code, which ends the table as the decoder expected.
Ampere BMSK and the read of a covered pixel
- Symptom:
Ampere instruction 21b at … is not implemented(…0405721b) orAmpere instruction 925 at 0x0 is not implemented(040e0200000e4000 …7925) in the build. - Cause: 0x21b, beside SGXT's 0x21a, is BMSK: a mask of b bits from bit a. Star Fox's
58046f286de779e1takes it from two bytes of a word, ANDs it with the value shifted by the same a and hands the result to an atomic, a bit field written into a word. 0x925 has no name in the tables at hand (the part of CuAssembler's sm_80 table read so far; Mesa's NAK encoder could not be fetched); what it reads comes from its two shaders, quad efficiency views. They rebuild its value at the quad's three other pixels through SHFL and FSWZADD and add the four: one indexes a 4-entry palette with the sum minus 1, so a shaded pixel's sum is at least 1, and the other draws 0.03125 + 0.15625 sum in red. So it is 1 for a covered pixel and 0 for a helper invocation. - Fix:
ABmskfollows PTX'sbmskdefinition, its.Wat bit 75 as SGXT's (only the clamping form has been seen).APixelCoveredloads a newIoVariable.HelperInvocation, Metal'ssimd_is_helper_thread(), as an integer; any other form of 0x925 stays refused (chain change).test_dmsh_ampere_mem.pycovers both. - Found on: Star Fox: 1 compute and 2 pixel shaders, none asked for in play so far, so neither instruction has run. Neither opcode is in the shaders of Donkey Kong Bananza, Splatoon Raiders, Mario Tennis Fever or Pokopia.
- Form 3, the sample index:
[RED] … 0x925 form 3 outside a covered pixel's readfor 154 of PRAGMATA's pixel shaders, at their first instruction. The register indexes the driver's sample position table (LDC c[0][R + 0x620], a byte of x and y nibbles), which is what GLSLC's Maxwell code does with PIXLD.MY_INDEX (numbered 5 there), so form 3 is the index of the sample the fragment runs for:IoVariable.SampleId, Metal's[[sample_id]]. Check:PixelCovered.test_form_3_reads_the_sample_index.
The fragment's shading-rate size reads 1 x 1
- Symptom: a Switch 2 game's water or another full-screen surface draws black (or as a flat dark colour under the fog) while its normals and depth are right; a texture dump of the target shows the colour channel at 0 where the surface is, and building the shader without fast maths changes nothing.
- Cause: S2UR of system register 0x84 (Mesa NAK's
NAK_SV_VARIABLE_RATE): the fragment's size in pixels, X in bits 8..15 and Y in bits 16..23, which variable rate shading makes 2 or 4. The translator did not know the register and gave 0, the default for an unknown one. Nintendo Switch Sports Resort's sea shaders divide a blend weight by the fragment's area: 0, an infinite weight, and the colour came out NaN, whichblend_zero(dm_az) writes as 0. - Fix:
SReg.VariableRate(132,Decoders/InstDecoders.cs) reads0x10100inEmitSReg(Instructions/InstEmitMove.cs): the host shades every pixel, so 1 x 1 (chain change). - Found on: Nintendo Switch Sports Resort (
04008E001F098000, v65536): 612 of its 11,059 shaders, all pixel shaders, read the register; its title screen's sea was black and draws blue with the change, on the Mac. - Check:
test_dmsh_ampere_mem.py(ShadingRate, withDMSH_TEST_XLATE).
VOTEU writes the uniform predicate
- Symptom: no wrong picture seen so far. In the MSL, a shader with a 0x886 vote has
if (false)andfalse ? a : bwhere a uniform predicate guards a value or a branch, and a lane guard on the same number readssimd_allorsimd_anyof its own predicate. - Cause: the destination at bits 81..84 of 0x886 is the uniform predicate UPd: nvdisasm prints
@!P1 VOTEU.ANY UP2, P2for0x000000000104010000000000003f9886(CuAssembler's sm_86 records), and NAK encodesOpVotewith a uniform destination as 0x886 and a lane one as 0x806, with its source and guard always lane predicates. The translator wrote the lane predicate of that number for both. An unwritten predicate reads false, so a uniform guard on the vote never held, and the lane predicate of that number became the subgroup's vote. Across Yoshi and the Mysterious Book, Pokémon Pokopia and The Legend of Zelda: Ocarina of Time, 14,960 of the 17,889 votes that name a destination are next read as a uniform predicate, through a uniform guard, UPLOP3, USEL or PLOP3's uniform source (bit 67), and the 2,929 next read as a lane predicate all have an earlier lane writer. 0x806's next readers are all lane reads. - Fix:
AVotewrites UPd for 0x886 (dm/gfx/tests/test_dmsh_ampere_alu.py, classVote). No other instruction in CuAssembler's sm_86 tables has a uniform predicate destination without already being registered as uniform. - Reach: every shader with such a vote changes: 7,560 translated of 9,231 in Yoshi (the rest stop at SURED, both ways), all 471 in Pokopia, 321 translated of 329 in Ocarina of Time; none in Mario Kart World, Fire Emblem: Fortune's Weave or Donkey Kong Bananza's 5,219 surveyed. Before, 1,815, 454 and 284 of them had a guard folded to a constant. In the shaders read, the vote is on a value that is one per draw, such as
c3[87].z != 11, so the old code goes wrong only where that vote is true. Open: no played scene has shown such a vote. In Pokopia's first area the one changed pixel shader drawn, the full-screen075fd7285c64b798, has all 7 votes false and no mixed subgroup (a build that turns the frame red where one fires stayed untinted over a walk, and its control, forced on, was red all over), so the picture is unchanged there. In Yoshi's 1,124 keys asked in play, the one changed shader,cbd80cb96ad38a61, votes on a uniform buffer value and the uniform registers it guards are unused. - Found on: Yoshi and the Mysterious Book, Pokémon Pokopia.
TXD through a uniform register kept no handle
- Symptom:
[RED] <key>: the translator deleted N bindless accessesin the build (Losses a shader build reports;Failed to find handle source for bindless accessin its reflection's notes), for a shader with TXD through a uniform register (0xf6c). The MSL has no gradient sample, and what it read comes back 0. - Cause: a bindless read takes its handle as source 0.
ATexadds it in every other form, but TXD has a branch of its own, which left it out. BindlessElimination then took the first coordinate for the handle, found no source for it and deleted the read. - Fix: the TXD branch adds the handle first, as the others do.
- Found on: Yoshi and the Mysterious Book: in 14,079 of its 133,154 shaders, none of them among the 1,519 the playtests asked for, so no route has shown it in a picture. Found by PR 1261.; Star Fox (281 pixel shaders, the characters' fur shells among them)
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
Handles built under a guard the read's guard cannot be tied to
- Symptom:
Failed to find handle source for bindless accessin the build's translator notes, for a read whose handle is two words of the game's own uniform buffer, and what it read comes back 0. Or nothing in the log: the read bindsfp_t_cb3_<word>orfp_t_cb2_<word>, a texture word with no sampler word, so its sampler issamp_tex's guess, where the shader's other reads of that word bind both. - Cause: the compiler builds a handle in a register under a guard (
R = word;R |= sampler word) and reads through it under a guard of its own. The register's phi then merges the handle, its first word and what the register held before.Utils.FindLastOperationpicks the phi's input only when both guards are the same operand in the same branch form, which misses!UP0with UP0 the vote ofP0against a read under!P0,P4against a read underP5 = P4 && !P1, andP6against a read pastBRA.!P6.TryTableHandlethen took only c2 words, so a handle in another bank was deleted. In a register with no earlier value the first word's phi is (undefined, word):FindLastOperation's rule that the one defined source of such a phi is its value was also applied to that phi inside the outer phi, so the first word came back as the whole handle. - Fix: in the vendored translator.
TryTableHandlealso takes a texture word ORed with a sampler word of the same bank or a constant sampler from any constant buffer, including when only the OR's source is a phi and the handle is not. A word of a game's uniform buffer alone is no candidate, as it may be other data, so the first word and a float left in the register drop out without a look at the guards. A c2 word alone that an ORed candidate also takes is that handle on its way, not a second candidate, which also saves a read chosen at run time.FindLastOperationapplies the undefined rule only to the phi it was asked about. Proving the guards equal instead would take a boolean prover over predicate logic and the vote's meaning. A chain change. - Found on: Yoshi and the Mysterious Book: of 128,113 translated shaders, 130 reads in 78 were deleted (the pool's water surface on Chapter 1's page) and 189 reads in 152 bound the texture word alone. SPIR-V of every shader against the translator before: those 230 change there; 364 of 22,072 in DAVE THE DIVER and 2,633 of 69,924 in DRAGON QUEST I & II HD-2D Remake, of which 319 and 1,780 bound the texture word alone and the others lose a second read; 16 of 13,980 in OCTOPATH TRAVELER II, a second read. None of Fire Emblem Fortune's Weave's 16,888, nor of Blasphemous, NieR:Automata, Return of the Obra Dinn, Catherine: Full Body and FINAL FANTASY X/X-2. Only Yoshi's water was compared in a picture. FINAL FANTASY RESONANCE's 26 reads with no c2 word may be this form, not checked: its shaders are not split on disk.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(the three guard forms, an unguarded OR, and a c2 handle read once).
Layer entry points with the point size passed by reference
- Symptom:
no member named 'gl_PointSize' in 'main0l_out'anddoes not compilein the build, which still exits 0, then[RED] <key>: its library builds only without its layer entry points(Losses a shader build reports). A slice-writing geometry shader on it logshas no layer entry points. - Cause: Metal builds no pipeline for a vertex function that writes both the layer and a point size, so the layer's entry points lose the output.
dmsh_build.pyremoved it with a regex overout.gl_PointSize = …;, but Unreal Engine 5.4's bodies are functions of their own, called as_88(out.gl_Position, out.gl_PointSize), which that left behind. - Fix:
drop_point_sizeremoves the writes as before, and gives a vertex function that still passes the output by reference a local float instead (the same forvs_layerandvs_layer_entry). - Found on: Yoshi and the Mysterious Book: 38 of the vertex shaders of the 1,519 its playtests asked for lacked layer entries. The first habitat's picture does not change, and it logged no
has no layer entry pointsbefore or after. Found by PR 1261. - Check:
python3 dm/gfx/tests/test_dmsh_geometry.py PointSize.
Losses a shader build reports
- Symptom: in the build's log,
[RED] <key>: the translator deleted N bindless accesses (<type> N): their results read 0or[RED] <key>: its library builds only without its layer, integer output, dual source entry points, and[RED] lost without failing: …with the counts per kind (the NSP script repeats that one line). Inregress.py,NEW-FAIL: N shaders with more … than in the baseline. - Cause: both leave a shader that builds, so the build's status said ok and it exited 0. BindlessElimination deletes an access whose handle it cannot trace and writes 0 to its results (
Failed to find handle source, kept in the reflection's notes).finishindmsh_build.pyrebuilds a library that does not compile with its extra entry points without any of them. Nothing compared these between builds, which is how 14,079 of Yoshi's shaders and 38 of its vertex shaders lost something unnoticed. - Fix: the reflection holds both (
notes,entries_lost), so a build that restores a shader from its cache reports it too.dm/gfx/tools/shader_regressions.pyholds what counts as a loss (losses) and prints the lines (report_losses).regress.pycompares each shader with the baseline (loss_diff): more accesses of a type or a new entry point lost in any shader isNEW-FAIL, however the totals move, and a shader new in the candidate starts from none. What the baseline has too is listed as known, and the game's note says what is known about it. - The build still exits 0: the NSP script runs it for players, and one shader the game may never reach must not stop a pack.
regress.pyis the check for a change, so there is no stricter exit code. On a baseline from beforeentries_lostexisted, every lost entry point counts as new. - Not counted yet: the translator's other messages that lose something:
Shader instruction … is not implementedandFailed to find targets for BRX instruction, which the build summary still counts among its translator lines. - Found on: the 79 games with a library on the Mac (2026-11-05, those shaders rebuilt on the current chain): 1,984 deleted accesses in 964 shaders of 13 games, the most in Ghost Trick (1,030 in 616) and Super Monkey Ball Banana Rumble (490 in 245), and FINAL FANTASY RESONANCE has 26 by its note. No shader built without its extra entry points when rebuilt (65 of Sparks of Hope's, which look as if they did, could not be: its package is not on the Mac): the 25 compiles that failed in the logs were all Yoshi and the Mysterious Book's, before the point size fix. Each game's note lists its own. A listed loss is not proved harmless: none has been traced to a picture.
- Check:
python3 dm/tools/tests/test_shader_regressions.py Losses,python3 dm/tools/tests/test_regress.py Regress.
A guard band cull in every vertex shader (0x80d)
- Symptom:
Ampere instruction 80d ... (000fc80003fe0000c43211110000780d) is not implementedfor every vertex shader of the game, so nothing draws. - Cause: the compiler ends the position's computation with a test of its own. FSETP sets P0..P5 where x, y or z lies beyond +/- w times the system registers 30 and 31, which nothing else reads: a guard band. Two 0x80d follow, immediate 0xc4321111 with no predicate result, then immediate 0x80000000 with a result, and that predicate guards an EXIT before the shader writes its position and outputs. All 6,319 vertex shaders hold this once; no other game's do. What the instruction reads is not known: it is inferred from what surrounds it, and no other instruction reads its result.
- Fix:
AGuardCullinInstEmitAmpereAlu.cs: the result is false, so no vertex leaves early. Every vertex writes its outputs and clipping does the rest, as for a shader without this; only the optimization is lost. A form with no predicate result at all (PT, as the first of the two) writes nothing and is skipped in any stage (PRAGMATA's mesh and pixel shaders hold it). Any other form of 0x80d stops the shader. - Found on: Kirby Air Riders.
- Open: the instruction's real meaning. A vertex output at
a[0x5c], written by 4,771 vertex shaders (Attribute offset 0x5C is not valid), is dropped; it has no known meaning either. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
Ampere instructions new in Pokémon Pokopia
- Symptom:
Ampere instruction <op> at 0x… is not implemented,F2FP.MERGE_CorF2I from a float that is not 32-bitin the shader build; those shaders are left out and their draws and dispatches skipped. - Fix:
- F2FP.MERGE_C (bit 78): b converted into the low half, c's low half into the high one.
- F2I from a half (source size 1): the half that bits 60..61 select.
- ATOMS.POPC.INC (0xf8c): an add of 1 with no source register, also counted as using shared memory. The game's one encoding is accepted; any other stops the shader.
- UP2UR (0x883):
URd = UP0 ? 1 : 0. The game's one encoding (URZ, mask 1) is accepted; any other stops the shader.
- Found on: Pokémon Pokopia.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
Ordered not-equal becomes unordered in MSL
- Symptom: an ordered not-equal comparison is true with a NaN operand, so a NaN guard lets it through. An inverted result is wrong too; NVIDIA's compiler can implement unordered equal by inverting ordered not-equal. No game symptom has been identified.
- Cause: the ISA translator emits the correct SPIR-V
OpFOrdNotEqual, but SPIRV-Cross's MSL emitter maps it to!=, which is unordered in MSL. The pinned upstream emitter has a TODO at that case. Writing(a < b) || (a > b)is insufficient under Metal fast math: the compiler can fold it back to!=. - Fix:
spirv_cross_bin/ordered-ne.patch, applied by its pinnedbuild.sh, makes the MSL emitter write!isunordered(a, b) && a != band preserve both operands' expression dependencies. The ISA translator remains unchanged. Logical and integer not-equal and unordered floating-point not-equal keep their existing lowering. This fixes the shared converter used by NVN, Vulkan and OpenGL. - Check:
DMSH_TEST_GPU=1 DMSH_TEST_METAL=1 python3 dm/gfx/tests/test_spirv_ordered_ne.py: synthetic scalar and two-, three- and four-component f32/f16 modules, assembled and validated as SPIR-V, compiled with the chain's Mac flags and checked by GPU readback; the iOS compiler checks the same modules offline. Ordered, unordered, inverted, integer and Boolean results cover signed zeros, finite values, infinities and signed quiet/signaling NaNs. The old converter fails every width and type; changing only its emitter passes. PR #2042's five targeted Orin-fixture operations also pass outside the fixture's separate denormal allowance (M4 Pro, macOS 27.2.1, Metal 32023.922). - Found on: synthetic SPIR-V and a Jetson Orin's recorded instruction results (PR #2042); no game symptom identified. The Cuphead Mac route supplies regression coverage.
Comparisons with .FTZ
- Symptom: single bright dots at thin far geometry (railings, track edges), changing frame to frame as the camera moves, already in the lit picture before anti-aliasing. Most of them come from another cause (below).
- Cause: a float comparison has an .FTZ flag (Ampere: FSET and FSETP bit 80, after the comparison at 76..80; Maxwell: FSETP bit 47, FSET bit 55, FCMP bit 47): on NVIDIA a denormal operand compares as zero. The translator decoded it and dropped it, and Apple's GPUs keep fp32 denormals. A guard like
sum != 0before1 / sumthen lets a denormal sum through: its reciprocal overflows, the products give NaN, and amin(x, 1.0)(precise::, see min, max and clamp with a NaN operand) turns it into 1.0, a fully lit pixel. - Fix: a comparison flushes each operand where the flag is set:
|x| < FLT_MIN ? 0 : x(FlushDenormal,InstEmitAluHelper.cs, fromAFset/AFsetpand from Maxwell'sEmitFset,EmitFsetpandEmitFcmp, which flushes only the source it compares). An immediate or RZ needs no code. - Limit: only the comparisons. The compilers set .FTZ on nearly every float instruction of every shader, so it is in effect a mode of the whole shader, and Metal has none (
MTLCompileOptionshas math modes, no denormal control). Flushing the arithmetic would be about 3.3 million more sites in Mario Kart World, so its FADD, FMUL and FFMA keep denormals. Four denormal weights can still add up to a normal sum, which NVIDIA sees as zero; it stays finite, so it makes no NaN. - Found on: Mario Kart World: its deferred lighting
635061c90d75a8d1normalises four depth-weighted half-resolution samples by1 / sumonly whereFSETP.NEU.FTZsays the sum is not zero. No Switch 1 game has shown the symptom; Maxwell's comparisons follow for the same semantics (the flag is on all of them in the 8 Switch 1 games counted). - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_alu.py(CompareFtz, on the game's encoding) andtest_dmsh_maxwell_ftz.py.
Compute threads that return before a barrier
- Symptom: none on the Mac. Suspected as a cause of GPU hangs (
kIOGPUCommandBufferCallbackErrorHang) in compute, task and mesh shaders that return before athreadgroup_barrier. - Cause (checked, not a bug): on NVIDIA's GPUs a thread that has exited counts as arrived at a barrier, and Switch compute shaders rely on it (
if (lid * 4 >= count) return;, then a barrier). Metal's specification wants every thread of the threadgroup at each barrier, and the translator keeps the return in the MSL. On an Apple M6 a returned thread counts as arrived too. Seven shapes all complete with every remaining thread's value right: whole simdgroups returning, all but the last simdgroup returning, half the lanes of every simdgroup, returns between two barriers, a barrier loop after the returns, threads leaving a barrier loop at different iterations, half the lanes before asimdgroup_barrier. Each ran with 4,096 threadgroups of 1,024 threads, 280 dispatches in all with no hang. - Fix: none: the translator keeps the return. A pass that kept a returned thread arriving at every later barrier (
BarrierExits.cs, PR #1774) was not taken. It fixes nothing measured: PRAGMATA's hang went away only together with a cap on every shader loop. That hang was its cloth solver's loop, which never ends when the iteration count it reads is 0, and the cap hid it. - Limit: measured on an M6 only. M1 to M5 have not run it. A failure of
t_barrier_exiton one of them would bring the pass back for those GPUs. - Found on: PRAGMATA (no profile; 156 of its compute shaders return before a barrier) and Orbitals (PR #1783), as PR #1774 reports; neither game's files were run here. Not Ocarina of Time's GPU hang: none of its 520 task and mesh shaders has a barrier in its body. Only 12 of its compute kernels return before a barrier, none of them in the pass that hangs.
- Check:
make -C dm/gfx/tests GAME=<id> t_barrier_exit && dm/gfx/tests/t_barrier_exit.
MEMBAR is a fence, not a barrier
- Symptom: a GPU hang (
kIOGPUCommandBufferCallbackErrorHang,[RED] the host has waited 10 s for GPU work) in a compute shader whose threads poll a flag in a loop with no BAR.SYNC: a persistent work queue. - Cause: MEMBAR (and the ERRBAR after it) orders memory and does not wait for other threads. The translator emits it as SPIR-V's
OpMemoryBarrier, which SPIRV-Cross writes asthreadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup | mem_flags::mem_texture): an execution barrier every thread of the threadgroup must reach. A thread that leaves the polling loop early never reaches it again, and the threads still in the loop wait for it for ever. - Fix: SPIRV-Cross writes the chain's MSL at version 3.2 (
dmsh_chain.CROSS_MSL), whereOpMemoryBarrierbecomes the fence it is,atomic_thread_fence(…, memory_order_seq_cst, thread_scope_threadgroup)for MEMBAR.CTA andthread_scope_devicefor MEMBAR.GL / .SYS and Ampere's MEMBAR, with no execution barrier. BAR.SYNC'sthreadgroup_barrier(mem_flags::mem_threadgroup)stays a barrier. First fixed by a text rewrite of that line (membar_fence, ported from uncraftablexd's PRAGMATA bring-up, PR #1407), which made every MEMBAR a device fence and lost the BAR.SYNC after one (next entry). - Found on: PRAGMATA: its culling queue
12a52b683eec95c1polls a done flag withMEMBAR.SC.GPU; ERRBARat the end of the loop body. - Check:
python3 dm/gfx/tests/test_dmsh_membar_fence.py(withDMSH_TEST_METAL=1the shaders also compile for the Mac and the iPhone; withDMSH_TEST_XLATEa Maxwell MEMBAR and BAR.SYNC go through the translator).
Compute loops that outlive the process
- Symptom: the game exits but compute work keeps the Mac GPU busy,
kill -9does not reclaim it, and WindowServer can stop until a reboot. PRAGMATA's reporters needed seven reboots, including after a game abort on main9ccbd6b1(issue #2664). Kirby Air Riders' particle submission hung twice in two races; the loop guard's author reports none in sixteen later sessions, whose builds also carried other changes (PR #2254). - Cause: a loop whose exit condition never arrives in the translated execution. PRAGMATA's persistent queue kernels poll shared counters; why those counters disagree is open, as is Kirby's failing loop/input. Existing memory and fence fixes may affect the trigger, so a reproduction on current main is still needed. The platform failure is that committed GPU work is not reliably reclaimed at process exit. A CPU-raised abort was retracted: only 2 of 24 lone-kernel trials observed the store; the 876 ms bounded trial is evidence against that CPU approach, not a timing of the GPU approach below.
- Fix: declared host/chain containment, not the root fix.
dmsh_rewrite.compute_loops, based on PRs #2254 and #2709, adds a budget of 2^18 loop-condition checks per function invocation to compute shaders and their reachable helpers. Nested and consecutive non-barrier loops spend the same function budget. Fragment, vertex, geometry, task and mesh shaders are unchanged. The first capped thread raises a GPU-written abort word shared by the submission; other non-barrier loops check it every 1,024 checks. Helpers receive the state through their callers. A loop containing an execution barrier, directly or through helpers, gets a separate counter reset on each entry and never reads the abort word. Unequal work in earlier or nested non-barrier loops therefore cannot consume its barrier budget, and an asynchronous abort cannot split its threads. Every submission gets a fresh abort word. - Diagnostics: each kernel in a submission has its own hit record, separate from the abort word. On completion the host reads it before recycling the arena and logs
[RED] loop cap hit: submission N, kernel <hash>, loop site N, once per loaded kernel. Only reaching the kernel's own budget records a hit; observing another kernel's abort does not. The site indexesloop_sitesin<hash>_b.json, with its function, source line before containment and barrier status; the emitted MSL also marks each site. If multiple sites hit, the record names the lowest numbered one. This identifies capped work, not proof of the original runaway's cause. - Limits: this changes the result of capped or canceled work, including persistent state used in later frames. A legitimate long function can exhaust the budget: a 512 × 512 nested count produces 261,632 increments instead of 262,144 and reports its cap hit; a 256 × 256 count completes unchanged. No absence of hits on a smoke route proves all workloads fit. Helpers have independent budgets; barrier loops can still run to the full budget, and each queued submission must raise its own abort. Large grids, non-compute work and time spent before the first cap are not bounded in milliseconds. This is safer reproduction, not a guarantee against another reboot. #2664 stays open for the bad loop/input and its loosest correct binding.
- Check:
DMSH_TEST_GPU=1 python3 -m unittest dm/gfx/tests/test_dmsh_compute_loops.py. Bounded GPU inputs exercise actual host dispatches and completion readback, a capped helper through a loop-free wrapper, propagation to later ordered dispatches, attribution without blaming canceled kernels, helper barriers following unequal per-thread work, once-per-kernel logging, next-submission isolation and valid/exhausted cumulative budgets in both encoding modes. Original inputs remain bounded if containment is broken. Checked on an Apple M6 with Metal compiler 32023.922; the authors' M4 Pro synthetic GPU measurements at a smaller 2^14 test cap were 59.8 → 8.6 ms for eight dispatches and 809.3 → 118.8 ms for one large dispatch, compared with the cap alone. Isolated containment overhead is unmeasured. - Validation: Fast Fusion's race and Sports Resort's title route exercise guarded kernels. Static inspection accounts for every loop in both rebuilt compute libraries, including helpers. Such checks qualify those workloads, not every legitimate loop or a maximum completion time. The game comparisons used chain
968f7d1ea898against19d159c0b938, before the landing rebase onto current main. The rebased chain7d5d6482def7passes all nine containment tests, including the GPU host fixtures in both encoding modes, and 63 documentation/chain/reflection checks. An additional game comparison after rebase was not run: an interactive PRAGMATA root-cause investigation held the shared GPU measurement lock. - Found on: PRAGMATA and Kirby Air Riders. Current-main trigger and gameplay retests on those titles remain open.
A BAR.SYNC right after a MEMBAR lost
- Symptom: a GPU hang on the iPhone (
Caused GPU Hang Error,kIOGPUCommandBufferCallbackErrorHang, thenFATAL GPU access revoked) in a scene that ran before chain d24f05cf9d78 (ccd834e0); the failed command buffer lists a compute shader with shared memory. Shared memory read before the other threads of the group wrote it can also give wrong values without a hang. - Cause: below MSL 3.2 SPIRV-Cross writes
OpMemoryBarrieras athreadgroup_barrieron every memory, an execution barrier, and so leaves out anOpControlBarrierthat directly follows one as redundant (spirv_msl.cpp,OpControlBarrier). The translator emits MEMBAR then BAR.SYNC exactly so:MEMBAR.CTA; BAR.SYNCis how NVIDIA's compiler writes GLSL'smemoryBarrierShared(); barrier();. Themembar_fencerewrite then made that one line a fence (two such lines in a row one fence), so the group had no barrier left: its simdgroups (two in a 64-thread group) raced on shared memory. Both MEMBAR scopes printed the same line, so MEMBAR.CTA also became a device-scope fence, about 6 times the cost of a threadgroup-scope one in a kernel with one per iteration on an M6 (1.9 ms against 0.25 to 0.3 ms). - Fix: MSL 3.2 for every shader of the chain (previous entry): SPIRV-Cross writes each barrier and each fence with its own scope, and
membar_fenceis gone. The per-shader MSL 3.1 for image atomics (dmsh_atomic.cross_args) went with it. - Found on: Fire Emblem: Three Houses on an iPhone 15 Pro (A17 Pro), compute shader
b0a3586f7a5ead00(64 threads, 512 bytes of shared memory) in the failed command buffer (issue #2786); the hang has not been run again on the fixed chain. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_membar_fence.py(test_maxwell_membar_then_bar_sync: a fence and a barrier for each pair).
Barrier moves around warp shuffles
- Symptom:
Ampere instruction f55 at 0x… (000fe20000000000000000001a0f7f55) is not implementedin the shader build; those shaders are left out. - Cause:
0xf55and0xf56(BMOV) save convergence barrier B15 into R26 before a block of warp shuffles (SHFL) and restore it after. The translator had no entry for either. - Fix: both are no-ops, as the barriers they save are (BSSY, BSYNC, BREAK, WARPSYNC): per thread they do nothing. In the shaders found, no other instruction reads R26 after them, and the register beside the barrier field (R15) is read live by an FMUL, so neither writes a general register (
InstEmitAmpere.cs). - Found on: Hyrule Warriors: Age of Imprisonment: pixel shaders
02e49c189b769074and49241cf469c76830, 16 pairs each (chain 95ba69b5403e). - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(BarrierMoves: the game's encodings leave the translated shader unchanged; it fails on the translator before).
YIELD
- Symptom:
Ampere instruction 946 at 0x… (000fde00038000000000000000007946) is not implementedin the shader build; those shaders are left out. - Cause: 0x946 is YIELD (CuAssembler's sm_86 records disassemble
…7946asYIELD ;), which only lets the warp scheduler run another of the warp's paths. The translator had no entry for it. - Fix: a no-op, beside the convergence barriers and ERRBAR in
InstEmitAmpere.cs: per thread it does nothing. - Found on: Resident Evil 4: 21 compute shaders (
68e3f47c80022855,b86773bfdc9f50e5, ...), each with one YIELD afterMEMBAR; ERRBAR, before a branch. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py Yield(the translated shader is unchanged by it; it fails on the translator before).
LDC with the bank in its address register (.IS)
- Symptom:
Ampere b82 at 0x…: LDC with a bindless bank or an address mode (…00008a00…7b82)in the shader build; those shaders are left out. - Cause: LDC's address mode 2 (
.IS, bits 78..79; 3 is.ISL) takes the bank as the instruction's plus Ra's upper 16 bits, and the offset from Ra's lower 16 bits plus the instruction's, as Maxwell's LDC does. The compiler uses it for an indexed read of c1 with the bank folded into the address ((index * stride) + 0x10000). The Ampere path refused the mode, and the shared load picks a run-time bank only among the banks the accessor reports, none here, so even the Maxwell path reads 0 for it. - Fix:
ALdclowers.IS/.ISLto that bank and offset, and the load selects among the banks the shader can reach: its own constant segment c1, the instruction's bank and every bank its other constant reads name, but not c0 (ARuntimeBanks, from a scan of the decoded program;InstEmitAmpereAlu.cs). The host fills the driver segment only at offsets known when the shader is built and does not load a shader that indexes it at run time (dmsh_reflect.pyunfillable): with c0 among the candidates, the pixel shader below, which reads c0 elsewhere, translated but was not loaded. Maxwell shaders are unchanged. A run-time bank 0 in a compute shader is not remapped as a constant one is (AMapC0). - Found on: Hyrule Warriors: Age of Imprisonment: vertex shader
cc679c7b4d3e703creads its quad corners (−1,1), (1,1), (0,0), (−1,−1), (1,−1) from c1 by vertex index % 5, and pixel shader059a0a910ff87a26reads c1 from 0x60 (chain 316fb82e2f22). The vertex shader is also Pokémon Pokopia's. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py(LdcIndexedBank; it fails on the translator before).
LDC's 16-bit immediate: signed beside a register, the address alone
- Symptom:
reflection conversion failed: B binding fp_c15: 536839244 bytes read at fixed offsetsat load, and the draw is skipped; the shader's MSL readsfp_c15._m0[33552452], a slot the game binds with a few words. - Cause: Maxwell's LDC (
c[bank][Ra + imm], the immediate at bits 20..35) took the immediate as signed in every form (InstEmitMemory.Ldc,Imm16ToSInt). Added to a register that is right, and the sum is 32 bits: nvdisasm prints0xef94003fffc7050basLDC R11, c[0x3][R5+-0x4]; Xenoblade Chronicles 2's pixel shaders read c6 at R − 8 to R − 128 (858 LDCs in 76 shaders); and to reach past 32 KiB the compiler adds 0x10000 to the register first, which a 16-bit wrap would make pointless (Yoshi and the Mysterious Book's pixel shader461579dbf57658b4:IADD3 R40, R26, 0x10000andLDC.64 R24, c[6][R40 + 0xaa88], 438 shaders there and 290 in Orbitals, all on Ampere). Alone (Ra = RZ) the immediate is the address as it is: the compiler reads c[14][0x8448] withLDC.U16 R49, c[14][0x8448]beside a plain read of c14[0x844C]. Sign-extended, that read's byte address was 0xFFFF8448 and its word 0x3FFFE112, whose high bits ran into the operand's 5-bit slot field (Operand.PackCbufInfo): a read of c14 became c15 at word 33,552,452, which stretched c15's fixed extent (NoteUniformRead) to 512 MB. - Fix: a lone immediate (Ra = RZ) is unsigned; added to a register it stays signed (
InstEmitMemory.Ldc). Ampere's fixed forms, ULDC (0xab9) and LDC with RZ (0xb82, mode 0), take the immediate unsigned the same way (InstEmitAmpereAlu.cs); no Switch 2 shader in the local builds has one at 0x8000 or above. A constant word past the 64 KiB bank reads 0, as a read past the size the game bound does, instead of being packed into the operand (ConstantFolding, the Load case), andPackCbufInfothrows for an offset or slot that does not fit rather than change the slot. Reading every immediate unsigned (the first proposal) moves XC2's reads 64 KiB away; wrapping everyRa + immat 64 KiB agrees on all the shaders above but is not what the compiler assumes, and would put an AND in every indexed constant load whose(Ra + imm) >> 2shapeBindlessToArrayand the uniform handle matchers read. - Found on: Mortal Kombat 11 (
0100F2200C984000, v1703936, draft profile in seedds/nxnative#2799; diagnosed in seedds/nxnative#2800): 27 rejected shader loads, 11 distinct keys, each with oneLDC.U16 c[14][0x8448]. The signed form beside a register: Xenoblade Chronicles 2 (pixel shader09030ba6b1d1283e,LDC.64 R4, c[6][R59 - 0x40]), which the unsigned reading proposed first would have moved 64 KiB away. Corpus: the shader packages of 13 Switch 1 and 9 Switch 2 builds (chain 53cf95b181aa). - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ldc_offset.py(the games' own encodings; 4 of 5 fail on the translator before, the signed register cases pass on both).
IMAD.HI adds a register pair, and IMAD.X its carry
- Symptom: 64-bit arithmetic in a shader gives wild results: the 64-bit division behind an exposure average returned 893011 for 218, so the exposure stayed at the end of its range. With only the pair fixed it still gave 2 for 340 / 1.
- Cause: IMAD.HI is the high word of
a * b + {c + 1:c}, the same 64-bit addition as IMAD.WIDE, with the carry out on the predicate at 81..84. The decoder took the high word ofa * band addedcalone, losing the upper word of the pair and the low word's carry. The compiler's 64-bit multiply chains the two:R9:R8 = R6 * R13 + {R9:R8}, thenR8 = high(R7 * R11 + {R9:R8}). Separately, all three IMAD forms have .X (bit 74, the carry predicate at 87..90), which the decoder dropped; as with IADD3.X, a negated addend is then its bitwise not. - Fix:
AImadHiandAImadCarryIninInstEmitAmpereAlu.cs. - Found on: Fire Emblem Fortune's Weave: the Lighting compute shaders' division, run line by line from its translated MSL on 208 known inputs, with dividends up to 2^44: 26 wrong with only the pair fixed, none with both. Other Switch 2 games share the decoder and have not been rebuilt with this.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
NVN2 compute reads its workgroup counts at c0 + 4
- Symptom: a scene lit by many small lights comes out too dark, with its clustered light lists empty for most clusters.
- Cause: a light culling shader computes its cluster as
(z * c0[8] + y) * c0[4] + x. NVN2 compute keeps the dispatch's workgroup counts at the start of its driver segment, below the per-shader layout at 0x10, and the host wrote them only at c0 + 0x200, Maxwell's place. At zero, every cluster of a column wrote the same entry. - Fix: with a Switch 2
sdk(dm_sdk_ounce),encode_args_also writes them atDMSH_C0_DISPATCH_NVN2, and an indirect dispatch copies its GPU-written counts there too. x and y are read by the shader; z at c0 + 12 follows their order and has not been seen read. - Found on: Fire Emblem Fortune's Weave:
35d12d6f98fa05e2, read from its translated MSL. The picture's change has not been measured on its own.
Texture handles of SDK 22's Ampere code
- Symptom:
Ampere instruction 361(orf60,370,38dand others) refused, or hundreds ofFailed to find handle source for bindless access of type "textureCube"when the handle was taken from the wrong register: units drawn white, the rest of the scene right. - Cause: the bindless form of a texture instruction is the bound opcode + 1 with 0x300: 0xb60 becomes 0x361 and 0xb6f becomes 0x370. 0x361 takes its handle first in the second source block (bit 59), 0xf60 in a uniform register at 40..46, and 0x370 (TXQ) in Ra with the level in Ra + 1. A census of all the game's instructions gave the position.
- Fix:
ATexandATxqinInstEmitAmpereMem.cs. The same bring-up adds, from their encodings in the game: 0x301 BREV and 0x2be its uniform form, 0x311 F2I.U64, 0x312 I2F of a 64-bit pair, 0x38c ATOMS, 0x38d ATOMS.CAS (Rd is 1 when it swapped, not the old value: the game's only use is a retry loop until Rd == 1), 0x992 MEMBAR, 0x9ab ERRBAR, and the carry out of IMAD.WIDE. - Found on: Fire Emblem Fortune's Weave: 902 shaders had the wrong register at first; all 16,888 translate now. Splatoon Raiders lists 0x2be, 0x301 and 0x38c among its refused instructions; it has not been rebuilt with this.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py.
NVN2 compute's separate handles in c[0]
- Symptom:
reflection conversion failed: B binding cp_t_cb196610_10280074Smplr has no resolved slot numberat load, thenthe dispatched program has no compute shader; the shader's image has no slot either (cp_i_tcb_AA_). - Cause: after the uniform and storage entries, NVN2 compute keeps four runs of 8-byte handles in
c[0]: textures (control +0xb3), separate textures (+0xb4), separate samplers (+0xb5) and images (+0xb6).AMapC0knew textures and images, so everything past the textures landed in the image table and beyond. Star Fox's1002069a331cededshows the order: 13 uniform entries, 4 textures, 32 separate textures, 13 separate samplers and 5 images make its 0x290 bytes (+0xba) exactly, and its handles fall on separate textures 22, 24 and 31, samplers 11 and 12 and image 4. - Fix:
dmsh_build.pypasses the two counts (jobnvn2_cs) andAMapC0maps them to NVN's fixed tables, separate texture r toc[2]0x168 + 8 r and separate sampler r to 0x568 + 8 r (chain change). A shader with neither maps as before.test_dmsh_ampere_mem.pycovers the image past both. - Found on: Star Fox: one compute shader, dispatched in the prologue. Any NVN2 compute shader with separate handles reads them this way.
NVN2 compute's second push block holds buffer entries
- Symptom: the GPU never finishes the first 3D frame:
[RED] the host has waited 10 s for GPU work, with persistent compute shaders (a loop on a work counter,threadgroup_barrierinside) among the failed command buffer's shaders. - Cause:
nvnCommandBufferPushComputeConstants(cmd, block, offset, size, data)writes block 0 or block 1. NVN2 compute'sc[0]lays out, after its 0x10-byte header, push block 0 (control +0xa9 words, rounded to 16 bytes), then push block 1 (+0xaa words), then the uniform entries (+0xb1), the storage entries and the handle tables of the entry above (the SDK's accessor atsdk+0x5e6f20reads byte +0xa9 + block). PRAGMATA pushes 16-byte{address, size}entries, 1 to 3 of them, into block 1 before its dispatches, and its shaders read buffers through those addresses (ubo_ptr-style global loads). The host kept one block, so block 1 overwrote block 0, and the translator placed block 1 after the uniform entries: the persistent shaders spun on a counter in the wrong buffer. - Fix: the host keeps
DMSH_PUSH_BLOCKS(2) blocks, block b atb * DMSH_PUSH_SIZEofc[24](push_constinhle_nvn.c; a block past them is a red line). The translator mapsc[0]reads in push block 1's range toc[24] + 0x100(AMapC0,nvn2_csfield 7 from +0xaa), andGlobalToStoragetakesc[24]as an address bank likec[0]. A storage buffer whose address the game pushed binds through the bytes the replay holds (sbuf_push,NVN_RB_SBUFQ). Chain change. - Found on: PRAGMATA: with it, the hang at frame ~1,300 is gone.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py.
NVN2 graphics stages' buffer banks (c[25] to c[29]) are push blocks
- Symptom:
Ampere … bank 25(to 29) refused, orstage N cbN has no uniform buffer boundfor graphics shaders that read buffers through an address. Then, with those banks taken for the uniform slots:[RED] graphics push constants into block 5 (0 + 0x10): the host keeps 2, dropped,sbufp reg3 dummy(to reg5) for a mesh shader in the pass dump, and everything a visibility buffer draws comes out black while the rest of the frame is lit. - Cause: NVN2 graphics stage i (vertex 0, hull or mesh 1, domain 2, geometry 3, pixel 4) reads buffer entries from a bank of its own,
c[25 + i]: 16-byte{address, size}entries, or 8-byte handles. They are not the uniform slots the game binds. They are what the game pushes withnvnCommandBufferPushGraphicsConstantsinto push block 1 + i, as compute reads its own entries from push block 1 (block 0 holds the constants). The translator mapped the banks onto the uniform slots, and the host kept two push blocks and dropped the rest. PRAGMATA pushes its mesh stage's six entries into block 2 and its pixel stage's five into block 5 before its visibility and material passes. Its mesh shader5aab38bb5ba67ef7binds uniform slots 0 to 2 only and read its rows 3 to 5 (the visible-cluster tables) from unbound slots, so the primitive IDs it writes into the visibility buffer were garbage. The material depth pass93590d7bd6125d1ctook its cluster table from uniform slot 3, a 16-byte buffer, and every raw load it made missed. No material strip passed its depth test, and the G-buffer stayed black. - Fix: a chain change, general to NVN2.
- Translator:
InstEmitAmpere.csAStageBlockmaps the stage's bank to its block ofc[24], at(1 + i) * 0x100(AMapC0,AIndexedBank). The addresses read there becomesbuf_pushbindings, which the host reads from its push blocks (NVN_RB_SBUFQ, handles decoded). - ABI:
DMSH_PUSH_BLOCKSis 6. - Host:
push_constkeeps graphics blocks 0 to 5, and compute's 0 and 1. - Removed: the per-stage fill of
c[0] + 0x210for graphics stages; only compute reads that table. - Check:
Nvn2Buffers.test_a_graphics_stage_bank_is_its_push_blockfails on the old translator.
- Translator:
- Found on: PRAGMATA:
c[25]in 9,944 vertex shaders,c[26]in 538 mesh and 3 hull shaders,c[27]in 37 domain shaders,c[28]in 1 geometry shader,c[29]in 12,195 pixel shaders. In one intro frame it pushes block 1 157 times, block 2 51 times and block 5 92 times. A host-only test (each stage's rows filled from its block) brought back the ship's engines and the tower's lights at the moon base.
Uniform words read through a buffer address (cx)
- Symptom:
Ampere … is not implementedfor ALU forms, ULDC (0xab9) or LDC (0x582) with bit 91 set. - Cause: bit 91 makes a constant operand bindless:
cx[UR][offset]reads a word of the buffer whose 64-bit GPU address is in the uniform register pair UR, UR + 1 (ALU forms: UR at bits 32–37, offset at 38–54; ULDC: UR at 24–29; 0x582 LDC adds Rb at 64–71). The address is a plain GPU address, not a handle: decoding it as one read through wrong pools and page-faulted the GPU. - Fix:
ABindlessConstantreads it as a global load at UR + offset, through the memory pool table the shader walks for raw global memory (gmem_map) (AUldc,ALdcBindless,AGet). Chain change. - Found on: PRAGMATA: RE Engine's materials read their constants this way; its 0x36d (TXD with the handle leading the first block) and the plain form of 0x80d came up in the same shaders.
A handle pair ORed sampler word first
- Symptom:
reflection conversion failed: B binding fp_t_cb2_170 has no resolved slot numberat load (the draw is skipped), the build summary counting the binding under slot was not decoded; or, once the read's other inputs are known,Failed to find handle source for bindless access of type "texture2D"and the read answers 0.DMSH_BINDLESS_TRACE=1on admsh_xlatejob prints what a refused handle is made of. - Cause: the compiler ORs the separate texture word and the separate sampler word of c[2] in either order. The bindless elimination took the OR's first operand as the texture: with the sampler word first (
c[2][0x5c0] | c[2][0x248], word 0x170 of the separate sampler table at 0x568), the sampler's word was named as the texture, a slot the host cannot decode. Through a phi (the OR predicated, the bare sampler word on the other path) the bare word was a candidate too, so the read was refused. - Fix:
BindlessElimination.csorders a pair of c[2] words by the table they lie in: a word of the separate sampler table (dmsh_abi.hDMSH_C2_SAMP, 128 slots) is the sampler, the other the texture, in the plain OR and among a phi's candidates; a bare sampler word is no texture candidate (chain change). - Found on: Star Fox (62 pixel shaders, 5 of them loaded at the prologue cinematic).
A buffer texture with a two-word handle
- Symptom: menu labels and other text disappear while their backgrounds and icons render.
- Cause: a type-1 bindless handle ORs two uniform words, which may hold the sampler and texture in either order. Buffer-texture reflection discarded the second word, and the host bound the dummy buffer when the first word held only a sampler. Glyph vertices read zeros and collapsed.
- Fix:
dmsh_reflect.pypreservessregandsofffortbuf_ubo,nvn_refl.mretains them, andencode_argsresolves both words withubo_bind_handle, as for ordinary textures. This is a chain change, bound to the handle representation rather than a game or build. - Check: Python reflection fixtures and
t_refl;t_tbuf_handlereads distinct buffers on the GPU with both word orders, a second word at byte zero, a one-word control, a nonzero pool base and inline updates to either texture word. - Found on: Sid Meier's Civilization VI, its glyph vertex fetches.
Ampere HMMA through simdgroup_matrix
- Symptom: a Switch 2 game's frame rate swings between 60 and 30 fps (Donkey Kong Bananza's own controller,
main+0x204a18, drops to 30 after two frames of 20 ms from their start to the GPU's end, and comes back after six), and the GPU profile (DM_NVN_GPUPROF) shows one compute dispatch of 2-6.5 ms a frame: agl's upscaler network (agl_ndsr.pck, shader7629d857a0a93833). - Cause: its 144 HMMA.16816 a thread (F16 sources and accumulator) were emulated lane by lane: 32 subgroup shuffles and 64 FMAs a lane for each, 4,922 shuffles in the shader. Without its shuffles (each returning its own value; a wrong picture, measured only) the dispatch took 0.24-0.40 ms. On this GPU shuffles cost more than threadgroup memory: one HMMA a SIMD-group took 5.42 ns emulated, 1.08 ns through threadgroup memory and
simdgroup_matrix, 0.65 ns with the tiles loaded straight from where LDSM reads them, and 2.73 ns moving the register fragments intosimdgroup_matrixelements with shuffles (Apple's 8×8 layout gives each lane a pair of columns of one row too, but in another order). Metal's matrix types have no SPIR-V form spirv-cross converts (its cooperative matrix support is GLSL only). - Fix: in a compute shader, HMMA.16816 with an F16 accumulator becomes
MatrixMultiplyAdd(AHmma), then a call of the helperdmsh_hmma16816_f16(TensorPass,HelperFunctionManager.GenerateHmma16816F16), named in the SPIR-V. Each SIMD-group has 256 words of a shared memory of its own (hmma_scratch, 1 KB a SIMD-group): the lanes store their fragment words as they are, A row-major, B transposed and C row-major, and after a SIMD-group barrier (the new IR instructionSubgroupBarrier, Metalsimdgroup_barrier) the helper's body computes D from them lane by lane.dmsh_build.py(hmma_msl) replaces that body in the Metal source withsimdgroup_load(B with its transpose flag), foursimdgroup_multiply_accumulateand asimdgroup_storeinto the same block; the name, the arguments and the block are the contract, and the translator's body stays correct where the rewrite does not apply. Other HMMA forms (m16n8k8, an F32 accumulator) keep the per-lane emulation. A chain change. - Check:
dm/gfx/tests/test_dmsh_hmma.py: the rewrite of the helper as spirv-cross writes it, and on the Mac's GPU the rewritten body against a CPU reference of PTXmma.m16n8k16on random fragments (4 SIMD-groups a threadgroup; largest error 0.009 against a reference that rounds once: the matrix hardware rounds the F16 accumulator as it goes, as Ampere's does). The translator's body agreed with the same reference to 0.002. - Found on: Donkey Kong Bananza: its 24 NDSR compute shaders. On one save and route, the upscaler took 1.1-1.6 ms a frame instead of 0.1-5.1 ms (2.5-4.5 typically), a frame's GPU span 8.9-19.4 ms instead of 13.8-23.3, and the game's 60 ↔ 30 switches fell from 87 to 68 in the same run length; the picture is unchanged.
- Note: three of four of these HMMAs start an output tile, with C = 0. A variant for those calls that neither stores nor loads C (
simdgroup_multiplyfirst) was measured and not kept: 0.767 against 0.820 ns a warp-HMMA (6 %) in an isolated loop of the build's two bodies on an M4 Pro, about 0.04 ms of the upscaler's 1.6-1.9 ms a frame, and no measurable change in the game. - Open: LDSM and MOVM (27 and 72 a shader) are still emulated with shuffles (314 left in the upscaler, whose floor without them is about 0.3 ms); loading A and B straight from LDSM's source and keeping D as matrices between HMMAs (0.65 ns an HMMA) needs the translator to follow LDSM → MOVM → HMMA → HMMA chains. Done for accumulator chains and for A read by an LDSM: HMMA chains keep their matrices in the SIMD-group; B and MOVM remain.
HMMA chains keep their matrices in the SIMD-group
- Symptom: a Switch 2 game's movie or upscaler network runs slow on the Mac and iPhone, and the GPU profile (
DM_NVN_GPUPROFwith each dispatch in an encoder of its own, thenDM_NVN_DISPATCH_OWN=1, since removed) shows its compute dispatches, small grids of one to four SIMD-groups a threadgroup that loop over tiles, at 1-3 ms each; the dispatches' shaders calldmsh_hmma16816_f16hundreds of times (Ampere HMMA through simdgroup_matrix). - Cause: each call took every operand through the SIMD-group's scratch block: the lanes stored A (4 words), B (2) and C (2), the matrix hardware loaded them, and D went back to the registers through the block, three SIMD-group barriers a call. In these networks almost every HMMA continues an accumulation (C is the D of the call before it, which nothing else reads: chains of 9 to 36), four calls in a row share A, and A comes straight from an LDSM whose rows are a strided tile in shared memory. That LDSM's emulation cost four shuffles a lane on top of the round trip. Measured on an M4 (8 GPU cores) in Ocarina of Time's movie networks (14 dispatches a frame): without the helper's body the frame's compute fell from 26.9 to 15.4 ms; without the shuffles as well, to 11.0 (wrong pictures, measured only, over four frames).
- Fix:
TensorPass.Preparegives each HMMA flags, a constant argument after C, from the optimised IR of its block: an accumulator slot (8 a function) for a chain, whose D stays there as the next call's C (FlagCSlot,FlagDSlot); A that is the previous call's (FlagAReuse); C = 0 (FlagCZero); and A that is four matrices of one LDSM of the block with no shared memory write or barrier between (FlagADirect,FlagATransfor .MT88), with the LDSM's row address, each matrix's offset from lane 0's row and the row stride. That needs the address to be U + f(lane) with U the same in every lane and f known: a divergence analysis of the function (the lane and the thread index components a subgroup spans are divergent, a loop header's phis are not when every exit branches on a uniform condition and, for a loop with several back edges, every other branch in it too, phis where paths meet are) and an evaluation of f for the 32 lanes, whose rows must be 16-byte aligned and strided. An LDSM in a compute shader is now aMatrixLoada matrix, lowered to its per-lane code after that. The translator's own body reads only the registers, so every flag is a promise about values it computes anyway.dmsh_rewrite.pyhmma_msldeclares the slots and A's matrices in each function that calls the helper and passes them by reference, so the inlined helper keeps them in registers, and passes the caller's shared memory array (the one threadgroup array besides the scratch; with none or several, A goes through the block): A loads withsimdgroup_loadat lane 0's row (simd_broadcast) plus its offset, which leaves the LDSM's per-lane code unused. A chain's middle call stores only B. A chain change. - Check:
dm/gfx/tests/test_dmsh_hmma.py: the rewrite's arguments and callers, and on the GPU a run of four calls with those flags (A from shared memory plain and transposed, A kept, C = 0, accumulators in two slots), each given the registers the translator's body would read (a stale A where A comes from shared memory), against a CPU reference (64 SIMD-groups, largest error 0.014 for two HMMAs with an f16 accumulator between them). WithDMSH_TEST_XLATE, the flags the translator gives two chained HMMAs on an LDSM's matrices.DMSH_TENSOR_TRACE=1on admsh_xlatejob prints why an HMMA's A is not loaded where its LDSM read it. - Found on: The Legend of Zelda: Ocarina of Time: its title and opening movies run eleven NDVE network shaders with 2,217 HMMAs, 1,890 of them continuing a chain. Measured on the title screen, the median over 321 profiled frames of the frame's compute: 26.65 ms before, 18.85 after on an M4 with 8 GPU cores (quartiles within 0.1 ms); on an M6 with 12, 14.78 before and 11.41 after (frames from 3,000 on, 1,057 and 851 profiled, quartiles within 0.6 ms), the GPU span 15.63 and 11.87 ms; the title and the opening movie unchanged to the eye. 1,789 of the HMMAs take no A through the scratch (540 load it where its LDSM read it, 1,249 keep the previous call's); of the other 428, 427 (most of
d15370a382630d4e's) have a shared memory store between their LDSM and the HMMA. agl's NDSR upscaler, in this game and in Donkey Kong Bananza (24 compute shaders, 5,328 calls: 2,664 keep A, 1,325 continue a chain, 3,996 start from C = 0), loads none of its A where its LDSM read it: its LDSM rows are addresses read from a table in shared memory, which the analysis cannot prove strided, so A goes through the scratch there. Bananza's opening and first play render as before. - Note: what is left is B's trip through the block: with B loaded from shared memory too (a fake address, measured only), the frame took 12.6 ms. In these networks B is the weights, read by LDSM.MT88 before the tile loop and kept in registers (72 pairs in two of the shaders), while the shared memory is reused for activations, so it cannot be loaded where it was read. Turning B into matrices once where it is defined and keeping them in registers took 18.9 to 17.4 ms but slowed one shader (
0a56002cdc7e1fce, four SIMD-groups a threadgroup, 144 matrices) by 13 %; not kept. Removing the barrier at the end of a chain's middle call changed nothing (18.84 against 18.88 ms). - B kept where it repeats (
hmma_bslots): two calls have the same B when their B arguments come, through copies (x,as_type<T>(x),int(x)), from the same variables, each written once in the function and declared at its top level. Out arguments, a non-const reference or a taken address count as writes. The first such call at the function's top level keeps B's two matrices in a slot (dm_bm), and the calls of that B after it take them, with no store, load or barrier for B. It is a literal argument at each call, so the branches fold away when the helper is inlined. Ocarina of Time: 10,293 of 16,620 HMMAs in 56 of its 71 HMMA shaders take B;fa3033d05c0a41d6takes it in 118 of 176. Its largest shaders hold up to 168 slots, and they still gain: on an M6, a latency-bound chain (24 threadgroups of 4 SIMD-groups) with 10 to 160 weight pairs ran 16–28 % faster, with the same bits. In the game, standing on the Kokiri Forest deck, the 4-dispatch compute encoder that holds the upscaler's network went from 984 / 979 µs to 951 / 946 µs (two runs each in one session, pictures the same within noise). A contributor measured that network's largest dispatch on an M4 Pro at 779 → 655 µs (discussion #1789). - Ruled out: building the matrices from the lanes' registers. Apple's matrix hardware fills a matrix quickly only through
simdgroup_load. The 8x8 lane layout is fixed: on an M6 lane l holds row (l/16)·4 + (l/2)%4 and columns c, c+1 with c = 4·((l/8)%2) + 2·(l%2), the layout published for the M1. With it, each lane can set its elements throughthread_elements()from SIMD shuffles, which gives the same bits. On a 64-call chain this took 1.716 ms with B built that way, against 1.448 through the block, and 8.9 ms with every operand built that way. So B's trip cannot get cheaper per call, and the slots leave it out where B repeats. With no trip at all the same chain took 1.147 ms. The exact Ampere rounding (f32 blocks, two conversions a lane) is the larger cost of a chain: 1.448 ms against 0.734 with f16 accumulation, which gives different bits.
LDSM reads rows other lanes stored
- Symptom: a Switch 2 game's movie or upscaler network output has dotted streaks, every other pixel of a few rows wrong, in other places each run, while its input is clean. Through agl's NDSR upscaler a few such pixels a frame grow into white blotches over the whole picture: Ocarina of Time's Kokiri Forest on an M4 Pro on chain 844bf1a5ea8f, with the game's own upscaler (the default); with
DM_UPSCALER=metalfxin its place, no blotches. - Cause: a warp stores tiles to shared memory (STS) and reads them back with LDSM, often with no BAR between them. The Switch runs a warp's shared memory accesses in order. Metal orders another lane's threadgroup store and this lane's load only through a barrier, and its compiler moves them past each other. Since HMMA chains keep their matrices in the SIMD-group, a compute shader's LDSM is a
MatrixLoadthatTensorPasslowers late to its per-lane code, and NDSR's LDSMs all go that way: its picture went bad on that chain. - Fix:
InstEmitAmpereTensor.ALdsmputs a subgroup barrier (simdgroup_barrier(mem_flags::mem_threadgroup)) before an LDSM's reads and one after them, so the stores have landed and no lane's next store reaches the rows before every lane has read them; in a compute shader they bracket theMatrixLoads and so the code that replaces them. LDSM is warp-collective, so the whole SIMD-group reaches both.TensorPassdoes not count a subgroup barrier as a shared memory write, so an HMMA still loads its A where its LDSM read it. A chain change. - Check:
test_dmsh_ampere_mem.pyShared.test_ldsm_reads_between_subgroup_barriers(fails on the translator before). Ocarina of Time on an M4 Pro, Kokiri Forest autosave, the game's upscaler: white blotches over the forest on chain 844bf1a5ea8f, none on fbd67412d49d at the bridge and on the village floor. GPU time through the title movie unchanged (median 12.7 and 13.6 ms a 300-frame window, both chains). - Found on: The Legend of Zelda: Ocarina of Time: the movie library's NDVE networks first (five of them have no BAR between STS and LDSM; MetaIX, GitHub pull request #1376), then agl's NDSR in play. Not the cause of the dotted horizontal rows that remained in the scene with either upscaler (GitHub issue #1537): An HMMA outside a chain overwrote the chain's accumulator.
An HMMA outside a chain overwrote the chain's accumulator
- Symptom: dotted horizontal rows across the picture at a regular spacing, in fog and light, with the game's upscaler and with
DM_UPSCALER=metalfxalike (MetalFX then replaced onlyagl_ndsr.pck's shaders): Ocarina of Time in Kokiri Forest, Hyrule Field and the castle town since chain 23a1ea1db092. The rows are the tiles of agl'sagl_ndsr_vr.pck/agl_ndsr_vr_light.pcknetworks (about 28.8 pixels of the 1536-wide input). - Cause: HMMA chains keep their matrices in the SIMD-group gives a chain an accumulator slot,
acc[k..k+1]with k from the flags. The helper did all its work inacc[k], and a call outside every chain has no slot bits, so it worked in slot 0: an unchained call between the two calls of a chain held in slot 0 overwrote that chain's accumulator. Each of those 30 networks has such calls (2,515 in all, of 7,558); their outputs came out wrong where the overwritten chains land in each tile. - Fix:
dmsh_rewrite.pyHMMA_BODYcomputes C and D in matrices of its own; a slot is read only for a chain's C (FlagCSlot) and written only for its D (FlagDSlot). The flags are constants at each inlined call, so the copies cost nothing. A chain change. - Check:
test_dmsh_hmma.pyHmmaOnGpu.test_calls_outside_a_chain_leave_its_slot_alone(a chain in slot 0 around two calls outside it, on the GPU against a CPU reference): 8,090 outputs over tolerance (largest error 9.6) with the helper before, none after. Ocarina of Time on an M4 Pro, the same Kokiri Forest view: rows on chain 23a1ea1db092 and later; none on 0f510fd5's chain, with the helper's rewrite left out, or with this fix. - Found on: The Legend of Zelda: Ocarina of Time (GitHub issue #1537). Counted in the translated MSL (calls outside a chain while slot 0 is held): Ocarina of Time 3,700 in 52 of its 62 HMMA shaders (its NDSR upscaler and movie networks too); Donkey Kong Bananza's NDSR 7 in 5 of its 24, so a few of its outputs were wrong as well (not looked at in the game).
HMMA rounds its f16 accumulator once per 8 products
- Symptom: a Switch 2 game's movie or upscaler network gives values a few f16 steps off the console's, in about half the outputs of each HMMA. Nothing looks broken; it is the network's arithmetic, compounded layer by layer.
- Cause:
HMMA_BODYaccumulated onsimdgroup_half8x8, whose multiply-accumulate rounds the f16 accumulator after every product. Ampere's HMMA with an f16 accumulator adds 8 products to C and rounds once (Khattak and Mikaitis's A100 model, N_FMA 8; MATLAB-tensor-core): an HMMA.16816 is k 0-7 rounded to f16, then k 8-15 on top, rounded again. Against the toolbox's 5,000 recorded A100 fp16 cases (C as f16), per-product rounding matches 2,420; summing the 8 products in f32 and rounding once matches all 5,000. On a Jetson Orin (sm_87,mma.sync.aligned.m16n8k16through PTX, 3 x 4,096 warps of random halves in [-1, 1]), per-product rounding matched 34.9 % of the outputs and the once-per-8 sum 99.97 % (fxd0h, PR #1897). - Fix:
HMMA_BODYaccumulates each block of 8 into asimdgroup_float8x8(half operands and a half C, whichsimdgroup_multiply_accumulatetakes) and rounds it to f16 per lane throughthread_elements(). A multiply-accumulate with zero A and B into a half result rounds the same, but took NDSR's network twice as long. The host's NDVE network (ndve_engine.metalhmma()) rounds the same way, into a new matrix: written into its accumulator arrays' ownthread_elements(), its layers ran 15 to 50 times slower on an M6. A chain change. - Check:
test_dmsh_hmma.py's GPU runs compare every output bit for bit with the two-block reference: main's body differs in 21,461 of them on an M5 Max and on an M6, the new one in none;test_ndve_engine.pykeeps the host's network bit for bit with the helper. Isolated on an M5 Max, NDSR'sfa3033d05c0a41d6takes 0.316 ms against 0.276 andd99fbeeb53d388470.446 against 0.393; their outputs change in 1.5 % and 0.8 % of halves. On an M6, a chain of 258 calls takes 2.56 ms against 1.69 for 2,048 threadgroups of 4 SIMD-groups, and the host network's seven layer kernels at the movie's sizes 2.94 ms against 2.85 (best of 100 each, summed). Not measured in a game. - Found on: The Legend of Zelda: Ocarina of Time: its NDVE movie network and agl's NDSR upscaler (PR #1897).
SHFL takes its lane from the low 5 bits
- Symptom: a warp shuffle whose lane comes from a register with bits above bit 4 set returns the thread's own value instead of the requested lane's. Orin probes found 207 wrong IDX results, 196 BFLY results and 179 segmented IDX results, each out of 1,024 rows (PR #2044).
- Cause: SHFL uses only b[4:0] as its lane or offset in every mode (PTX ISA). The translator's
HelperFunctionManager.csGenerateShuffle*helpers consumed the whole register, so the high bits affected the source lane and validity predicate. Both Maxwell'sInstEmitWarp.Shfland Ampere'sAShfllower to these helpers; the c operand's clamp and segment mask were already decoded correctly. - Fix: mask the lane argument to
& 31in all four shared helpers (IDX, UP, DOWN, BFLY). General shader ISA semantics, with no game or build gate; at most one additional integer AND per shuffle. Rebuild the native translator and regenerate its lock and chain header. - Check: on an M4 Pro, macOS 27.2.1 (26B131), Metal 32023.922, the PR's recorded Orin SHFL programs through current main's chain reproduce 207/196/179 differences with the baseline native translator and zero with the rebuilt one. UP, DOWN and immediate BFLY still match.
DMSH_TEST_XLATE=dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_shfl.pychecks synthetic Maxwell and Ampere shaders on Metal: all four modes, raw high-bit operands, immediate lanes, result and predicate, and clamp/segment boundaries. UP uses clamp zero; its separate nonzero-clamp issue is unchanged. No game or iOS device run. - Found on: no game; the Jetson Orin's sm_87 results (CUDA driver 12.6, PR #2044). The Orin fixture now runs in
test_dmsh_ampere_orin.py; IDX, BFLY and segmented IDX are no longer expected failures.
Ampere instructions checked against an Ampere GPU
- Symptom: none that shows on its own: a translated instruction gives other bits than the console's GPU for some inputs (a NaN operand, a lane index past 31, a directed rounding), and the picture is off only where a shader depends on them. The translator tests check the MSL a few encodings give, not the values the shader computes.
- Cause: nothing compared the translated instructions' values with an Ampere GPU's, so a meaning read wrong from the encoding, or lost on the way through spirv-cross and Metal, went unseen until a game showed it.
- Fix:
test_dmsh_ampere_orin.pyruns about 190 operations, each the GPU compiler's own machine code for one PTX operation, through the whole chain: the translator with the build's options, spirv-cross with the chain's arguments, every MSL rewritedmsh_build.py'sfinish()makes (read from its source, so a new rewrite is included), and the chain's Metal flags. On this Mac's GPU each takes the 1,024 input rows of its fixture, and every output word is compared bit for bit with what a Jetson Orin (sm_87, CUDA 12.6 driver) computed from the same rows. The inputs mix special values (signed zeros, denormals, infinities, NaNs with several payloads, the limits of each integer type, ties for the roundings), random bits and ordinary values; warp operations run 32 threads to a group on both sides, so a lane's neighbours are the same.dm/gfx/tools/ampere_orin/capture.pyrecords the fixture on any Linux machine with an Ampere GPU and NVIDIA's driver: the driver compiles each op's PTX itself (no CUDA toolkit, no compiler on either side), runs it, and the same machine code is rewritten for the translator, its global loads and stores becoming shared memory ones and the CUDA parameter reads and the addressing they feed becoming NOPs (prog.py), which the device'snvdisasmchecks.ampere_orin/ampere_orin.sasslists each program as the translator gets it.- Allowed on every op: what Metal's f32 arithmetic itself gives, NaN bits (Ampere writes the canonical NaN, 0x7fffffff) and flushed f32 denormals (
compare.PLATFORM). KNOWNlists the ops that still differ, each with its reason (the tracking issue);APPROXthe ones that run Metal's own approximation (MUFU, and the divisions built on it), which are reported and never fail. An op outside both lists that differs fails the test, and so does aKNOWNop that matches, so a fix takes its entry out.
- Allowed on every op: what Metal's f32 arithmetic itself gives, NaN bits (Ampere writes the canonical NaN, 0x7fffffff) and flushed f32 denormals (
- Check:
DMSH_TEST_XLATE=dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate python3 dm/gfx/tests/test_dmsh_ampere_orin.py(about 5 s on an M5 Max); it prints every op's differing lanes by cause.AMPERE_ORIN_ONLY=<ops or families>runs some,AMPERE_ORIN_REPORT=<file>writes the results as JSON. To record again:python3 dm/gfx/tools/ampere_orin/capture.py --host <user@machine> [--arch sm_86], with NVIDIA'snvdisasm(thecuda_nvdisasmredistributable) in~/ampere_orinon that machine. - Found on: no game; a Jetson Orin's results. The HMMA comparison it extends is PR #1897's.
Directed rounding in FADD, FMUL and FFMA
- Symptom: FADD, FMUL and FFMA with
.RM,.RPor.RZcan return the round-to-nearest result, one ULP away from the result requested by the shader. - Cause: the Ampere and Maxwell emitters discarded the directed modes. Metal's floating-point operations round to nearest, so these modes need a correction in the translator.
- Fix: the shared helpers use the sign of the rounding error to step the nearest result by one ULP when required. FADD orders the addends by magnitude before recovering the error, which prevents an intermediate overflow when the sum is finite. FMUL recovers the product error from the significands and scales the operand that keeps the intermediate in range. FFMA computes the error on scaled terms so a finite fused result survives an overflowing separate product. Directed
.FTZflushes inputs and results with their signs. The same FMUL rule applies to the1/(2π)literal used before MUFU. - Check: the nine directed programs in
test_dmsh_ampere_orin.pycover 9,216 recorded Orin lanes. On M4 Pro, macOS 27.2.1 and Metal 32023.922, rounding differences fall from 2,857 to zero. The remaining differences are 486 NaN encodings (Orin0x7fffffff, Metal0x7fc00000), 179 with denormal inputs and 14 with denormal outputs. Another 48 synthetic lanes compare exact bits for finite overflow boundaries, signed FTZ, scaling, the trig literal and fused cancellation. - Coverage: those 48 synthetic Ampere lanes and 45 synthetic Maxwell lanes pass with default and relaxed Mac math modes. Their 33 shaders validate as SPIR-V and compile offline for iOS. At the normal/subnormal boundary
FMUL.RP.FTZon0x00800000 * 0x3f7fffffstill gives +0 on Metal, where exact arithmetic with round-up before flushing gives0x00800000. That case has no NVIDIA hardware readback. The approximateMUFU.SINandMUFU.COSprograms differ in 746 and 581 of 1,024 lanes, down from 780 and 606. No iOS device ran the shaders. - Found on: the Jetson Orin sm_87 probes from PR #2051. Mac regression runs cover Fast Fusion's menus and Cuphead's map.
FMNMX and HMNMX2 signed-zero ordering
- Symptom: minimum or maximum returns the wrong sign for a zero result. On the recorded Orin inputs,
max(+0, -0)returns +0 while the translation can return -0. A subsequent reciprocal or sign test can distinguish the results. - Cause: NVIDIA orders -0 below +0 for min/max in either operand order. Metal's min/max can choose either zero, including after the chain's rewrite to precise functions.
- Fix: the shared
FPMinMaxinstruction helper checks for two zeros using their integer bits. For that case it selects the operands' bitwise OR for minimum and AND for maximum. Ampere FMNMX and HMNMX2 and Maxwell FMNMX use the helper after operand modifiers and half-input FTZ. The usual constant predicate adds four integer operations for minimum and five for maximum, per lane. Double min/max uses its existing path. - Check:
test_dmsh_ampere_orin.pyruns recorded Orin cases and separate synthetic contracts. On an M4 Pro, macOS 27.2.1, Metal 32023.922, recorded fmax changes from one zero-sign error and one f32 denormal difference to only the denormal difference. Recorded hmin2 and hmax2 have 8 and 7 NaN-bit differences in 2,048 lanes each (Orin0x7fff, Metal0x7e00). Synthetic zero, numeric and NaN cases cover both directions, half FTZ, and Maxwell constant/register predicates. All pass in default and relaxed Mac math modes, and their nine shaders compile with the iOS Metal target. Maxwell results are synthetic contracts against the documented NVIDIA semantics. No Maxwell hardware or iOS device was used. - Found on: the Jetson Orin sm_87 probes from PR #2047. Fast Fusion's validation records the shader build and Mac menu-route comparison.
Half-pair .FTZ flushes f16 subnormals
- Symptom: HADD2.FTZ, HMUL2.FTZ and HFMA2.FTZ keep half subnormals instead of flushing them. A subnormal times infinity consequently gives infinity instead of NaN.
- Cause: the translator dropped bit 80, as for f32 arithmetic, but Metal keeps half subnormals. The Orin reference shows that both inputs and the rounded half result flush to signed zero. Flushing only inputs or only results leaves 57 or 60 HMUL2.FTZ lanes wrong; dropping the zero's sign leaves at least 125.
- Fix:
AHalfFlushinInstEmitAmpereAlu.csflushes unpacked inputs below 2^-14 while preserving their sign.AHalfResultclears a packed result lane's mantissa when its exponent is zero, after rounding to half. A.F32result bypasses half-result flushing. HSETP2/HSET2 share the source helper; HMNMX2.FTZ uses it too. No game or build gate is needed. Non-FTZ forms emit the same code; FTZ forms add source comparisons/selects and integer result masking. - Check:
DMSH_TEST_XLATE=dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate AMPERE_ORIN_ONLY=f16x2 python3 dm/gfx/tests/test_dmsh_ampere_orin.py. On M4 Pro, macOS 27.2.1, Metal 32023.922 (metalfe-32023.922.4), the rebuilt native translator through current-main rewrites changes differing halves as follows: HADD2.FTZ 246 → 215; HMUL2.FTZ 449 → 234; ordinary HFMA2.FTZ 418 → 332. Every remaining difference is Orin0x7fffversus Metal0x7e00, both NaNs; differences beyond NaN bits fall from 31, 221 and 93 respectively to zero. These are not bit-exact matches. The JSON report records NaN patterns separately, and a classifier test keeps NaN-versus-infinity failures distinct from NaN-bit differences. - Coverage: the hardware fixture uses HFMA2.MMA, translated by the shared HFMA2 emitter; derived
hfma2_alu/hfma2_alu_ftzcopies change only opcode bit 2 to exercise ordinary HFMA2 with the recorded inputs/reference. Synthetic min/max FTZ cases cover both inputs, signed zeros and the smallest normal half (64 halves each); a synthetic.F32result case preserves ±2^-15 (32 floats). These synthetic checks are not new NVIDIA recordings..F32source swizzles and HSETP2/HSET2.FTZ lack hardware-reference coverage. No game frame-time benefit or cost is established. - Found on: no game symptom; the Orin comparison. PR #2048 reports about 7,700 FTZ half instructions in Ocarina of Time, a static census rather than a timing measurement.
HFMA2.MMA, the half-pair FMA on the tensor pipe
- Symptom:
NotSupportedException: Ampere instruction 235or435prevents a shader from translating. Half.RELUarithmetic also turns NaN into zero instead of retaining NaN. - Cause: the translator registered ordinary HFMA2 (low-nine-bit opcode 0x031) but omitted its tensor-pipe form 0x035. NVIDIA's compiler emits the latter for
fma.rn.f16x2and for constant loads such as-RZ * RZ + imm. The result emitter used a plain maximum with zero for.RELU; unlike.SAT, .RELU preserves a NaN result. - Fix: register 0x035 with
AHfma2andInstName.Hfma2, preserving the same operand forms, predicates, constant-bank discovery and result modifiers.AHalfResultselects a NaN through before taking the maximum with zero on HFMA2, HFMA2.MMA and HMUL2.RELUforms. The existing input/result.FTZhandling remains shared. This is general Ampere ISA behavior, with no game or build gate; ordinary non-RELU HFMA2/HMUL2 output is unchanged. - Check:
DMSH_TEST_XLATE=dm/gfx/tools/dmsh_xlate_bin/dmsh_xlate python3 dm/gfx/tests/test_dmsh_ampere_orin.py: all 200 recorded/derived/synthetic operations pass on M4 Pro, macOS 27.2.1 (26B131), Metal 32023.922 (metalfe-32023.922.4). Main rejects 17 programs at HFMA2.MMA; 13 now run, while four reach their separate FCHK, F2I.S64, DADD or DMUL refusal. Eight constant-loading conversion/integer programs are bit-exact. HFMA2, HFMA2.FTZ and HFMA2.RELU differ in 317, 332 and 314 of 2,048 halves respectively, all Orin0x7fffversus Metal0x7e00NaNs; saturation is bit-exact. Reciprocal remains a Metal approximation, not a bit-exact result. - Coverage: derived ordinary-HFMA2.RELU changes only opcode bit 2 and retains the Orin inputs/reference: main has 314 NaN-versus-zero errors, the fix none beyond NaN bits. Synthetic HMUL2.RELU checks NaN inputs, zero times infinity, infinities, negative clamping and positive subnormals: main has 24 NaN-versus-zero errors in 64 halves, the fix 24 NaN-bit differences and no numerical errors.
HalfFmaAliasintest_dmsh_ampere_alu.pychecks identical emitted MSL and resource metadata across all seven operand forms, each plain or with SAT/F32/RELU/FTZ (35 comparisons). These translation checks do not provide new NVIDIA recordings for constant-bank/uniform forms. The #2049 fixtures have no triple that triggers the independent half-FMA double-rounding error. - Found on: synthetic Jetson Orin sm_87 programs (CUDA driver 12.6); the existing RELU path is present in PRAGMATA. No game symptom is attributed to it.
HFMA2 single rounding to half
- Symptom: a packed HFMA2 result is one half ULP off near a rounding midpoint. For example,
-3136 × -8.125 + 0.000124693produces 25488 on Orin and 25472 with the old translation. - Cause: rounding the fused result to f32 can turn a value just beyond a half midpoint into a tie. Packing that f32 value then rounds the tie to the wrong half.
- Fix: the Ampere emitter selects a typed half FMA for HFMA2 and HFMA2.MMA when the sources and result are halves. SPIR-V widens the already rounded result exactly for the shared result handling, so even a later unpack sees the half-rounded value. Operand FTZ runs before FMA and result FTZ after half rounding. The shared .RELU still retains NaNs and clamps negative values, and .SAT still saturates. .F32 sources, .F32 destinations and FFMA use the f32 path.
- Check:
test_dmsh_ampere_orin.pyruns the 4,570 input triples recorded for PR #1902 through the actual translator. On an M4 Pro with macOS 27.2.1 and Metal 32023.922, 70 numeric differences in 9,140 lanes fall to zero. The 1,160 NaN encodings still differ (Orin0x7fff, Metal0x7e00). Separate cases check .RELU and .FTZ together, packed results read back as floats, .F32 operands and results, and float FMA followed by an explicit pack. - Found on: Jetson Orin sm_87 probes. The issue was found in arithmetic comparisons.
The NDVE movie network by the host
- Symptom: a Switch 2 game's movies and the title behind them run below 60 fps on a Mac with a smaller GPU, and the GPU profile (
DM_NVN_GPUPROF) shows almost all of the frame in a dozen compute dispatches ofnn::ndve's movie network: Ocarina of Time's title at about 24 fps and 38 ms of GPU a frame on an M1 Pro with 16 GPU cores, 24.8 ms on an M1 Max (issue 1375), 18.9 ms of compute on an M4 with 8 (HMMA chains keep their matrices in the SIMD-group); 11-14 ms of the 16.7 on an M6, an M4 Pro or an M5 Max. - Cause:
nn::ndve(a Nintendo library linked into the game'smain:nn::ndve::RouleauArchiveIO) runs the first network of its model,Movie/Ndve/Ndve-Nvn2-vid_seq5.dat(nn::ndve's movie enhancement file): a Rouleau archive (footerRLA1: four entries, two networks and two small shaders) whose networks hold a table of their 9 compute shaders,0x3c320bytes of weights and the shaders, compiled for a 1920x1080 picture. The graph is in the library's code, not in the archive: a U-Net over the picture packed 2x2 at 960x540 (16, 32 and 64 channels), eleven HMMA.16816 convolution dispatches, the last convolution added to the picture (5a7d69b0), then a 4/3 resampler with a small network of its own (4f41ccf2, from the archive's NDSR pack). Its code is written for NVIDIA's register file: each convolution loads its weights before the tile loop (LDG.128, STS.128, LDSM.MT88.4) and keeps them in registers through it, up to 72 B pairs (144 registers a thread), each used once a row. Translated, that is register pressure and a trip through the SIMD-group's scratch for every HMMA's B. No general lowering found does better on an M4 Pro (best ms of the five heaviest dispatches standalone, chaindedc9391c30b:e6be82d81.34,0a56002c1.69,5a7d69b00.97,d15370a30.80,a8b4fb480.54): B assimdgroup_matrixregisters once before the loop gave 1.18 / 2.29 / - / - / 0.49 (worse where four SIMD-groups a threadgroup each hold their own 72 pairs); B loaded at every HMMA from its storage buffer, whereTensorPassproved it came from (built and bit-exact), 1.75 fore6be82d8and 0.94 for5a7d69b0; B in threadgroup slots of their own, 2.16 fore6be82d8(the memory costs occupancy). A variant that read every B from one fixed place looked 35 % faster, but only because those 256 bytes were always in the cache. - Fix:
nvn_mtl.m's dispatch hands the network tonvn_ndve.inc, which runs it as kernels of the host (dm/gfx/msl/ndve_engine.metal, built with the host's other shaders): 8x8simdgroup_matrixtiles straight from the tensors, weights loaded once a tap, 3x3 inputs staged per threadgroup, the network's tensors in buffers of the host's with a zero border, one encoder for the 13 kernels. On by default;DM_NDVE_ENGINE=0runs the game's dispatches,abalternates withDM_AB. It is bound to the library's model, not to a game: the keys are the hashes of the model's shaders and the weights' offsets follow from its layers (each layer's weights, then its biases, each padded to 256 bytes, to the archive's0x3c320), so any game that ships this model runs it. Recognition: the 14 keys in order, each dispatch's weights and biases at the offsets the layers give from the first's, the picture the last convolution adds being the one the first read, the sizes and formats, the resampler's constants. Anything else (another model, the archive's second network, other sizes) leaves the game's dispatches running, logged once; a mismatch after some dispatches were skipped turns the host's network off for the rest of the run. The colour conversion49dff010stays the game's. The kernels compute what the translated shaders compute, in their order: each HMMA asHMMA_BODYdoes it (twosimdgroup_multiply_accumulateonsimdgroup_half8x8, input channels 0-7 then 8-15,simdgroup_multiplyfor a chain's first call), a chain over the taps and then the 16-channel blocks, the epilogue's D + bias in f32, ReLU and one rounding; the picture's sum in the game's order under safe math. - Check:
dm/gfx/tests/test_ndve_engine.py: every kernel on random inputs and weights at the network's sizes, bit for bit against references that calldmsh_hmma16816_f16ashmma_mslrewrites it, in PTX's fragment layout with TensorPass's chain flags (all 10 identical on an M1 Pro, an M5 Max and an M4 Pro; with an f32 accumulator per HMMA instead, the 9 with HMMAs differ in 6-25 % of their outputs), and the weight offsets the layer table gives against those Ocarina of Time binds. Standalone on one title-movie frame on the M1 Pro (16 GPU cores): main's 13 translated dispatches 36.3 ms of GPU, the host's 13 kernels 10.8 ms (PR #1894). In the game, on an M4 Pro with 20 GPU cores (Ocarina of Time'stitle-movieroute,scripts/bench.py, three runs each, the window kept in focus): the frame's GPU time 12.78 ms withDM_NDVE_ENGINE=0, 6.77 with the host's network (p50), both at 60 fps.DM_NDVE_ENGINE=checkruns the game's dispatches and the host's network and resampler beside them into images of its own and compares them texel by texel (logged every 300 frames): over 1,500 title frames, the resampler identical in every frame, the network in all but 10 texels, each 1/1023 off, the same 10 withDM_NVN_ENC_THREAD=1. The translated shaders are built with Metal's fast math, which may contract and reorder those sums:5a7d69b0built with-fno-fast-mathinstead gives other bits in a few texels of random inputs; the host's kernels keep the game's order. - Note: run standalone on fixed inputs, 4 times each, the 10 translated dispatches gave the same output every time on an M4 Pro, on chain
dedc9391c30band on39417042cfe8(issue 1893 reported outputs that change from run to run on an M1 Pro, measured by another harness; not reproduced). - Note: the host's network rounds each HMMA's f16 accumulator once per 8 products, as the translated helper does since HMMA rounds its f16 accumulator once per 8 products (resolved; before that both rounded after every product, as
simdgroup_half8x8does, and differed from the Switch in the low bits of most HMMAs). The host's network follows the helper, andtest_ndve_engine.pyfails when the two differ. - Found on: The Legend of Zelda: Ocarina of Time: its title and opening movies (issue 1375, PR #1894).
An interrupted compute compile broke the NDVE sequence
- Symptom: green and grey striped blocks over the opening movie after
XPC_ERROR_CONNECTION_INTERRUPTED. The host logs[RED] NDVE engine: a dispatch out of the network's orderand disables the engine for the rest of the run. - Cause: when Apple's
MTLCompilerServicedied, NVN dispatch cached the interrupted compute compile as a permanent failure. The dispatch returned before the NDVE engine saw the layer, so the next layer looked out of order. The game's fallback then ran with the same dispatch missing. - Fix: recognized NDVE dispatches reach the engine after resource preparation and before the translated pipeline lookup. If the engine falls back, the host leaves interrupted compiles retryable on a later dispatch and caches permanent refusals.
- Check:
t_dispatch_pipelineinjects the Metal error through the real dispatch path, checks that the next fallback dispatch writes its result, and checks that NDVE advances through the two reported layers without asking Metal for the first layer's fallback. - Found on: The Legend of Zelda: Ocarina of Time, on an M2 MacBook Air on macOS 27.0 (issue #2920).
Driver-segment reads outside fragment shaders
- Symptom: a vertex or compute shader reads zeros from NVN's driver segment
c0. - Cause:
dmsh_reflect.py'sdrv_readsscan matches only fragment-shader names (fp_c0/fp_c2), so vertex and compute shaders that readc0were never marked, and the host passed them an all-zeroc0; these reads are not listed in the JSON. - Fix: the host treats a declared driver-segment binding as read (
nvn_refl.m). The words the host fills are in the entries below. - Found on: The Legend of Zelda: Link's Awakening, Super Mario Odyssey, Pokémon Legends: Z-A.
Compute c0: dispatch size and uniform buffer table
- Symptom: flickering hard-edged white tiles (tiled lighting with every tile row getting row 0's or other rows' lights).
- Cause: a compute shader that computes its tile index as workgroup y ×
c0[0x200]+ workgroup x reads the dispatch's workgroup count from the driver segment, which the host left zero. - Fix: for compute,
c0carries the dispatch size at 0x200 (x, y, z) and the uniform buffer table at 0x210 + 16 r (address, size) in front of the storage buffer table at 0x310 (encode_args_). - Found on: The Legend of Zelda: Link's Awakening (Mac and iPhone): the step of Marin and Tarin's doorway. The room shaders use tiled forward lighting: the fragment position picks a 64×64-pixel tile (
trunc(y / 64) × ceil(width / 64) + trunc(x / 64)), whose light count and light indices come from two storage buffers that a compute shader (light_culling_compute.bfsha, one thread per workgroup, one workgroup per tile) fills every frame. Every row's workgroups wrote row 0's entries, the last writer won (a different one each frame), and the bottom tile row, where the step is, got the lights of other rows; a dump of the tile lists showed only the first of 17 rows filled. After the fix every tile row has its lights and the doorway shows the game's soft light from outside. - Check: Breath of the Wild (101 compute and 4 vertex shaders read
c0) and Super Mario 3D World (11 and 1) render the same as before on the Mac.
Geometry-stage storage buffer table
- Symptom:
[RED] shader ... reflection conversion failed: B binding gp_s0 has no resolved slot number; a geometry shader reading driver segmentc0reports that its storage-buffer table base was never measured. - Cause: geometry shaders access their storage buffers through
c0 + 0x410 + 0x10 r, but the builder'sSSBOmap and replay'sc0_ssbo_basecovered only vertex, pixel and compute. Running the lowered geometry shader as a Metal kernel does not change its logical NVN stage or driver table. - Fix: geometry uses base
0x410in both reflection and driver-buffer population.encode_argskeeps NVN stage 2 for these kernels, so storage slots and driver-table rows come from the geometry bindings. Hull and domain bases remain unmeasured and unresolved. - Found on: NieR:Automata The End of YoRHa Edition: the original shader's constant-buffer operands and the pinned translator's metadata agree on addresses in rows 0 and 2.
- Check:
dm/gfx/tests/test_dmsh_reflect.pyresolves synthetic geometry descriptors to slots 0 and 2 and rejects unknown or unaligned table addresses.t_geometrypasses synthetic metadata through native reflection and the production argument encoder; GPU readback checks both rows' guest addresses and sizes with different compute-stage bindings, plus a write through the geometry storage pointer.
Storage-buffer write flag in translation metadata
- Symptom: a storage buffer the shader stores to or uses atomically has
rw: falsein its generated reflection; replay does not record its GPU writes for dependent buffer reads. - Cause: Ryujinx's
BufferUsageFlags.Writeis bit 0 (1), andProgram.csserializes that enum unchanged. The builder tested bit 1 (2), incorrectly marking every such descriptor read-only. Native reflection honors the explicitrwfield, so its older fallback to the MSL pointer qualifier could not correct it. - Fix:
reflecttests bit 0 for both driver-table storage buffers and addresses carried in guest uniform buffers. Replay then uses its existing write-access and pending-write tracking paths. Rebuild shaders to replace the old metadata. - Found on: NieR:Automata The End of YoRHa Edition: its geometry counter atomic and output stream both emitted translator flag
1but reached reflection as read-only. - Check:
test_dmsh_reflect.pyexercises writable and read-only translator descriptors, including an address in a guest uniform.t_geometryverifies that native reflection preserves explicit true and false flags and that the writable geometry output enters the GPU-write tracker before its dispatch.
Graphics c0 + 0x610: the largest point size
- Symptom: point sprites of size 0 (Odyssey's Cap Kingdom fog never parted around Mario).
- Cause: a vertex shader that writes
gl_PointSize = min(size, c0[0x610])read 0, because the host had nothing at that offset of the driver segment. - Fix:
c0 + 0x610holds the largest point size, and the host writes 2047 there for the graphics stages. Writing theSetPointSizevalue instead (always 1 in Odyssey) left one-pixel splats whose disc weight came out 0 (the fields held-0.0). - Found on: Super Mario Odyssey (reported on an iPhone; fix checked on the Mac): on the Switch the ground fog opens around Mario as he walks through it. The fog's shading reads velocity fields that a small fluid simulation updates every frame: two 256×256 and two 128×128 RG16F targets, with a two-pass blur and a blended composite. Its only input is a point-sprite splat per mover, drawn with
alPointSpriteShader: one vertex per mover, its size in the vertex data (Mario's main splat asks for about 18 px, others 3–5 px) and a soft disc in the fragment shader (clamp(1 - 4r², 0, 1)× velocity). The simulation fields stayed exactly zero (raw dumps withDM_NVN_TEXDUMP+DM_NVN_SNAPRAW; the 8-bit dump shows velocities as black either way). After the fix the fields hold velocities up to ±44, and the fog clears around Mario.
Graphics c0 + 0x644: the draw's base instance
- Symptom: occlusion queries that always return 0 samples (Z-A: characters' legs folded back from the hips once they walked); every instanced draw's transform taken for instance 0.
- Cause: a shader that picks its transform with (instance index − base instance) +
c0[0x644]: Maxwell's instance ID leaves the base instance out, and the NVN driver keeps it in its constant segment, where GLSLC reads it forgl_InstanceID + gl_BaseInstance. The host left0x644at 0. - Fix:
encode_argswrites the draw's base instance there for graphics stages and does not reuse a stage's argument block across draws with different base instances. The word before it,0x640, is added to the vertex ID by 58 of Z-A's shaders and stays 0 until what the driver puts there is known. - Found on: Pokémon Legends: Z-A: from the first step on, the player's legs stuck straight out behind her at hip height, and the rival's forward in a later cutscene; standing still beforehand looked right. The bone palette the game computes on the CPU was already bent. The cause was six occlusion queries a frame, one 36-vertex box each (
a793f436dcabd350, base instance 61, 62, …), drawn against mip level 2 of the depth pyramid: every box was box 0, every query came back with 0 samples, and the game took its characters for hidden and posed their legs that way. Forcing every result to visible fixed the legs, and depth testing with ALWAYS did not. 793 of the game's vertex shaders read the word. - Note: how it was found: the raycasts were logged with scratch observation gates (all correct), then
DM_HLECOUNTshowed nothing walking-specific, then the counter reports.
The base instance of indirect draws comes from Metal
- Symptom: flat grey or background-coloured triangles with straight edges across part of the scene, changing shape from frame to frame while the camera stands still; dropping the colour pass's fragment shaders in groups (
DM_NVN_SKIP_FS) did not remove them, as the instances are misplaced in the depth pre-pass too, whose depth the colour pass tests for equality. - Cause: for an indirect draw (
DrawElementsIndirect/DrawArraysIndirect) the base instance is in the argument record, which the game's GPU culling writes earlier in the same submission;encode_argscould only write the command's base instance intoc0 + 0x644, 0 for an indirect draw. A vertex shader whose instance is (instance index − base instance) +c0[0x644]then read its transforms from the first records for every indirect draw. - Fix: the translation reads the word from Metal's
[[base_instance]], which holds every draw's base instance, direct, indirect or masked (dmsh_entry.pyvs_base_instance: in vertex functionsc0[100].ybecomes the base instance's bits, andmain0gets the parameter when it lacks it).encode_argsstill writes the word for the other stages. - Found on: Super Mario Party Jamboree: every board. Its culling (
2b5485a2a731a231, 62 points with rasterization off) writes 80-byte transforms per visible instance into a 30 KB buffer and counts them,276504dc5c987ecfwrites nine indirect records from the count, and the instanced draws (5a805bbb08421b86in the depth pre-pass,4b05556737e9535fandeaa3a44ba28f0744in the colour pass) draws them, both reading record = instance +c0[0x644]. 5,249 of its vertex shaders read the word.
Pixel c0 + 0x620: the sample index and GLSLC's sample position table
- Symptom:
[RED] shader … reflection conversion failed: reads driver-bank locations at run time that the replay layer cannot fill: c0 dynamic index c0+0x630(orc0 dynamic indexalone), and that shader's draws are missing ([RED] shader … (pixel) failed to load); the build notesShader instruction Pixld is not implementedfor pixel shaders;[RED] NVN unimplemented function called: nvnProgramSetSampleShading. - Cause: GLSLC reads the sample index with
PIXLD.MYINDEX(RZ, offset 0; nouveau readsgl_SampleIDthe same way), which Ryujinx's translator left unwritten, so the register read as 0. Forgl_SamplePosition(or interpolation at a sample) it then indexes a byte table the NVN driver keeps atc0 + 0x620: index = ((((y & w) << z) + (x & z)) << log2 samples) + (sample & mask), with {mask, log2 samples, z, w} atc0 + 0x630and x, y the pixel (gl_FragCoordover the render scale); each byte holds the sample's x (low nibble) and y in 1/16 pixel. The replay filled neither row, and the build refused any computed index intoc0. - Fix: the translator writes the sample index for
PIXLD.MYINDEX(IoVariable.SampleId, SPIR-VSampleIdwithSampleRateShading; MSL[[sample_id]], so the fragment function runs per sample on a multisampled target, and SPIRV-Cross movesgl_FragCoordto the sample); the other modes still log.encode_argsfills both rows for the pixel stage from the pass's sample count (c0_sample_rows: Metal's default positions, the same for every pixel, so the grid masks are 0; one sample is 0x88, the pixel centre), anddmsh_build.pycounts them as filled for pixel shaders (SAMPLE_ROWS), with a computedc0index accepted when the shader reads the 0x630 row, or when its range is proven (index_range: an integer expression of literals and the sample index, below 16, through single-assignment temporaries) to lie in the filled rows.nvnProgramSetSampleShadingreturns true: Metal has no switch to force per-sample shading, which a shader gets by reading the sample index. - Found on: Metroid Prime Remastered: 438 of the 562 pixel shaders of
MaterialArchive.arcread the sample index; in 30 the translated shader keeps it, and there it reaches the table, whose byte the G-buffer shaders pack into an integer target (04023899305e93e1). Its targets are single-sample (1600×900), so sample 0 was right and only the table mattered: 0 there put every sample in the pixel's corner. No other game here reads either row (58 games' libraries checked). The nibble order for several samples is the hardware's, not seen in a game. NVN2's table is signed from the pixel centre: PRAGMATA's 154 readers compute(byte ^ 0x88)nibbles / 16 - 0.5 and add it to the pixel centre, and4a9d4507eea6c837passes the nibbles unchanged to IPA's offset, which is signed from the centre (IPA at an offset): both are right only when the byte holds each coordinate minus 8, so one sample at the centre is 0x00 there, not 0x88. With the corner form every sample position read half a pixel up and left.c0_sample_rowsnow writes that form when the sdk is the Switch 2's (dm_sdk_ounce). Whether NVN1's table is the same was not checked (this game only stores the byte, and its files are not at hand): open. PRAGMATA: 156 pixel shaders read the byte at0x620 + samplewithout the grid and without the 0x630 row (a689530d00090ebf:_m0[(sample + 1568) >> 4], row 98), and were refused (c0 dynamic index) until the build bounded the index; all 156 load, the other 6,753 of its shaders that readc0orc2keep their result. Check:DriverReads.test_sample_byte_by_the_sample_index_is_filled_in_a_pixel_shader.
Texture and sampler pools with overlapping IDs
- Symptom: a menu's labels drawn as plain bars, other menus empty except for the cursor (one pool's textures overwritten by another's); a black screen when IDs past a fixed table read as empty slots.
- Cause: a game that binds two texture pools and two sampler pools whose IDs overlap; the replay had one ID table.
- Fix: each pool has a base in the table, in creation order;
RegisterTexture/RegisterSampleradd it, and binds recorded on a command buffer add the base of the pool that command buffer last set (bind_handlesinhle_nvn.c, the base kept incmd_t, next entry; log linepool #2 (…): numbered from N). Handles read from uniform buffers take the base of the pool bound at replay (DARK SOULS: REMASTERED,ubo_tex_id/ubo_samp_id, Handles from uniform buffers take the bound pools' bases). Deferred binds are not remapped (red line; Deferred texture binds read at execution). The table's capacity is the sum of the pools. - Found on: Fire Emblem: Three Houses: the scene binds a 12,544-entry texture pool and a 3,856-entry sampler pool, the 2D UI's command buffer binds 4,096-entry ones, and both fill IDs from 256. The scene's default 8×8 white texture overwrote the UI's textures (the title menu's labels drew as plain bars). The scene registers each draw's textures into fresh IDs of a ring (8,729 and up a few seconds in), which used to read as empty slots and left the screen black.
Bases of bound handles kept in the command buffer
- Symptom: red lines from the list of command buffers that bound a non-first pool (6,734 in one DARK SOULS: REMASTERED run).
- Cause: that list had 64 entries and was never cleared, and the game binds a non-first pool in more than 64.
- Fix: originally the bases lived in each command buffer, removing the fixed-size lookup. That was incomplete for inherited pools; execution-relative descriptor handles now keep pool selection only in queue execution state.
- Found on: DARK SOULS: REMASTERED.
Descriptor handles use the execution pools
- Symptom: terrain is magenta, trees are white and colour conversion reads uninitialized data; the compute pass dump shows
W ... tid=360 dummydespite a registered writable 3D texture. - Cause: explicit binds added host descriptor-table bases at recording, using the pools that particular command buffer had bound. Civilization VI records its colour-LUT dispatch in a list that inherits a different pool at execution: relative image index 360 should resolve to host ID 30824, not 360. The dispatch wrote a dummy image, leaving the sampled 32³ LUT unwritten. A pool change after a bind had the same error, and deferred binds did not apply any base.
- Fix: all recorded handles and binding state remain the hardware's relative 32-bit words.
bound_handle,bound_texandbound_imgresolve them against the queue's active texture and sampler pools when consumed: sampled textures, buffer textures, images, separate and constant samplers, driver-table arrays, feedback/dependency checks andDrawTexture. Uniform-memory handles already follow that rule. Pool changes invalidate argument blocks. A single bind still puts its patchable handle 16 bytes into the command, always in the short record. The capture record layout changes to version 2; captures with the old absolute IDs must be recorded again. - Check:
t_descriptor_poolsrecords real NVN binds without a pool, inherits a non-first pool, changes pools without rebinding, changes deferred handles after recording and writes two distinct 3D images through the same image slot. Both this test andt_tbuf_handlerun under Metal validation.t_nvnchecks compact/canonical records and patchable single binds;t_capturerejects the old record layout. Binding of Isaac and Xenoblade Chronicles 2 quick regressions pass. - Found on: Sid Meier's Civilization VI, colour-LUT compute
06932ac941e93119and final colour conversion65381f87fa4f1382.
Handles from uniform buffers take the bound pools' bases
- Symptom: distant walls and floors smeared sideways (DARK SOULS: REMASTERED): tiling textures took a clamp-to-edge sampler and repeated their edge column.
- Cause: the map materials read their combined texture / sampler handles from a uniform buffer (
fp_t_cb13_*, resolved at replay byubo_handle), and the game keeps several sampler pools, each with its own samplers under the same IDs, one per command buffer that records the scene. The replay resolved uniform-buffer handles in the first pool. - Fix: the replay keeps the texture and sampler pools bound (
OP_SET_TEX_POOL/OP_SET_SAMP_POOL, which it used to skip; a command buffer that binds none keeps the queue's, as on the GPU) and adds their bases to handles read from uniform buffers (ubo_tex_id/ubo_samp_idinnvn_mtl.m). - Found on: DARK SOULS: REMASTERED: the map materials
FRPG_Phn_*Lit*; 12 sampler pools of 2,304 entries (ID 261 is clamp-to-edge with LOD 0..0 in one pool, repeat with mips in others); the walls' tiling base textures (u ≈ −3.45). - Check: found by highlighting the six most common fragment shaders of the scene pass (
DM_NVN_HILITE), then the next six, and reading the wall draw's binding lines (DM_NVN_PASSDUMP_ALL).
Deferred texture binds read at execution
- Symptom: the 3D scene black, only particles and the HUD drawn; pass dump
Blines alltid=0 dummy. - Cause:
nvnCommandBufferBindTexturesDeferredpasses a pointer to the handle, and "deferred" means the GPU reads the handle from that address when the command executes. A game that records its command blocks once, submits them every frame and writes the handles afterwards got the handles the host copied at recording, mostly zeros, so draws read the dummy texture 0. - Fix: the bind record keeps the source address (
p_bind_handles.defer / src) and every replay-time reader refreshes the handles first (bh_freshinnvn_mtl.m). - Found on: The Legend of Zelda: Breath of the Wild: the engine binds almost every texture this way (
main+0xec2e64, one handle, the pointer being the handle field inside the texture-sampler object); the deferred-lighting composite (one full-screen triangle per material class, blending into the HDR target) read texture 0 for all of its inputs. - Note: how it was found: a frame data-flow table built from
DM_NVN_PASSDUMP_ALL(per pass: attachments, shader keys, sampled serials) showed the half-resolution lighting outputs never being read, and the composite pass'sBlines were alltid=0 dummy. Without_ALLthe dump lists only the first draw of each pass, which hid the composite. Deferred binds are not remapped by pool base (Texture and sampler pools with overlapping IDs).
Handles in uniform buffers written earlier in the same submission
- Symptom: bindless handles read from a uniform buffer name the wrong texture when the game writes them earlier in the same submission.
- Cause: the replay reads handles on the CPU, and a write queued earlier in the submission has not landed yet.
- Fix: inline uniform updates keep where their data sits, so the handle is read from the newest one covering it (
pend_read). The queued writes are indexed by granule in one hash, newest first in each chain: a write goes in at the finest granule size (4 KB, then each eight times the last:pend_shift) over which it spans at most 8 granules, and a lookup walks the chains of the granules it touches at each size the submission used (g_pend_lv). Nothing caps the count: the old limit of 256 writes per submission went first (Monster Hunter Rise), then writes over more than 8 pages, which had a list of their own that stopped at 256 and that every lookup scanned. Past it the submission counted as a write anywhere (g_pend_over), and every handle in it was read from memory, under updates still queued (RED 47,more writes than the host tracks). Merely growing that list would have made each lookup cost about 0.25 µs per thousand such writes (a CPU-only benchmark of the tracker, Apple M4 Pro); with the index a lookup takes 7–19 ns from 256 to 20,000 of them. - Found on: Monster Hunter Rise (it queues more than 256 writes per submission); Mortal Kombat 11 (
0100F2200C984000, not yet in the games table: GitHub PR #2801), whose fragment shaders read handles from slot 3 after more than 256 large writes in a submission. - Check:
make -C dm/gfx/tests GAME=<id> check_t_pend_index(CPU only, with AddressSanitizer: 9,000 large writes, 10,002 over one handle, writes from 16 bytes to 1 GB at their edges, and 20,000 mixed writes and lookups against a scan of every entry; 8 of its checks fail with the old list).
Storage buffer addresses in the game's own uniform buffer
- Symptom: a storage buffer reported with
cb_slot3, which had no NVN slot. - Cause: the shader reads a storage buffer's address from the game's own uniform buffer (c3 + 0x38), which Ryujinx reports with
cb_slot3. - Fix: the build marks it
sbuf_ubo(uniform slotcb_slot - 3, byte offset), and the replay reads the 64-bit address there at bind time, as it reads bindless handles. - Found on: Monster Hunter Rise (about 30 compute shaders).
Global memory at an address loaded from memory
- Symptom: whatever a shader writes through a pointer it read from memory never happens. The build summary counted
Failed to find storage buffer for global memory operation "Store", and the shader's MSL had a store function with an empty body. In Donkey Kong Bananza the tunnel's walls and floor were black and only the loose rocks drew. - Cause: Ryujinx turns a global memory access into a storage buffer access by tracing its address back to a constant buffer entry (
GlobalToStorage). An address the shader loaded from memory traces to none, and Ryujinx dropped the access: a store did nothing, a load read 0. Donkey Kong Bananza's gsys vertex shaderc9a56f796ea4a4cddraws 96 points every frame. Each point loads one indirect draw record's 64-bit address from its storage buffer and writes {0, 1, 0, 0, 0} there (count 0, one instance) before the terrain's culling geometry shader adds its triangles to the count. Without those stores the records kept instance count 0, and their counts grew frame after frame. NVN2 draws instance count 0 as nothing. Its indirect draw (sdk+0x6049b0) calls macro 27 (driver constants at 0x640) and macro 40 with the record's five words. Macro 40, decoded with Mesa's MME decoder after running the driver's macro upload (sdk+0x60fd40) in an emulator, skips its draw loop when the instance count is 0 and never writes the record. - Fix: general, in the chain. Accesses traced to one or more storage buffers translate as before; only those traced to none change:
- Translator (
GlobalToStorage.TryGenerateRawStorageOp): reserves the host's pool table as a storage buffer under a sentinel constant buffer slot (DMSH_KIND_GMEM_MAP,dmsh_abi.hDMSH_GMEM_MAP_*). It finds the pool holding the address by the entry it chose last (Raw global memory lookups that start from their last entry), else a tagged hint for its 2 MiB chunk, else a branchless binary search over the table's starts, adds that pool's delta and accesses the result through a physical storage buffer pointer. In MSL that isreinterpret_cast<device uint*>(ulong). - Why a delta: a no-copy Metal buffer's
gpuAddressis not its CPU address, so the guest address has to move by the pool's delta (GPU address minus guest address). - Host table (
nvn_mtl.mgmem_map): built from the memory pools whenever they change, 8,191 ranges at most (a pool past that is not reached, with a red line). It lists only the pools something gave a GPU address in, and those are made resident while such a shader is in use (Memory pools nothing gave an address to stay out of the raw pool table). Each 2 MiB chunk wholly inside an entry gets a hint in entry (chunk & 8191): the chunk as a tag, and the index of the entry holding it. A colliding chunk or a smaller pool searches. - Write log: where a store through a loaded pointer lands is known only once the GPU has run it. Counting it as a write anywhere refused every uniform shadow of the submission: Donkey Kong Bananza's tunnel ran at about 70 ms a frame, with 4,533 passes ended to land deferred updates. So each store or atomic also sets the bit of its table entry in a write log the host hands each draw (
DMSH_KIND_GMEM_LOG,gml_take), and the completion handler reads the bits against the same table. The word is read first: a bit is set once, so nearly every store costs a load, not an atomic (A shader that writes a whole frame through raw global memory). A bitmap cannot run out of slots, as the hash set of pages it replaced did. - Learned pools: the host takes each logged entry's range. The stores count as a write anywhere until the learned pools have stayed the same over 8 logs, then as writes over those pools. A later log that shows another range adds it, without going back to a write anywhere: a write anywhere makes every later geometry draw of the submission wait for the GPU (
geo_cpu_hazard), and going back for 8 logs after each miss gave Donkey Kong Bananza streaks of 300-2,000 ms frames (38 such frames in 5,400, 6 after the change, the geometry wait in one 25 s sample 3,490 → 264 ms). The host then checks whether the miss could have mattered: every uniform shadow taken from that submission on (its own and those of the later submissions encoded while it ran, each recorded with its fence) is compared with the ranges the stores wrote outside the prediction, whole pools now, so this check can report a shadow elsewhere in the pool. Only an overlap, or a record that has wrapped before the check, prints a[RED]line; a miss no shadow saw is logged with the pools' ages. - Why pools, not pages: the game allocates new records as the level streams in, in the same pools. Learned page by page, the tunnel still met a new page 213 logs in.
- Result in Donkey Kong Bananza: 4 pools learned over 9 logs at first, 60 fps (p50 16.64 ms), and no pass ended to land deferred updates. Further into the level the stores keep reaching pools the set does not hold yet: 12 in a 17,700-frame session, 10 in a scripted 13,500-frame run. Those pools are not new: they were added 3.5 to 294 s before the miss (the game streams records into pools it made earlier), so a new pool would not have announced them. None of the 7 misses checked had a page under a shadow (3 to 5 shadows each).
- Still dropped: an address in no pool. Atomics on 8- and 16-bit values are not implemented.
- Translator (
- A full table loses geometry silently: a pool past the table's end is not reached, so a load from it reads 0. Ocarina of Time holds about 4,170 ranges, and at the former 4,095 entries its foliage and moss were missing: black shapes where moss should cover them, and the sky through the ground (restored at 8,191 entries, and back again with the host capped at 4,095). The only sign was one red line (
raw global memory: N more memory pools than the … entries), so treat that line as a picture fault. - Open: the prediction is checked, not proven: a miss that does reach a shadow is reported (
[RED]) after the frame, not prevented. The records' pointers come from memory, so the pools they will reach are not known ahead of the draw. - Found on: Donkey Kong Bananza: its terrain, and agl's compute shader
49bc2268925e25b6(one load); rebuilding the chain changed only these two of Donkey Kong Bananza's shaders. Vertex shader588e242a52f5f7aa(five stores) has one too, the same shader in The Legend of Zelda: Tears of the Kingdom and Super Mario Bros. Wonder, so likely one the SDK ships; neither drew it in its regression route.
Global memory at a storage buffer's address on some paths only
- Symptom: GPU-driven geometry never draws: its indirect draw records keep count 0 and its visibility buffer stays clear, although the culling compute runs every frame. A persistent culling kernel takes its work items (its work counter passes the item count) and writes nothing. Its build notes do not say
traced to no storage buffer: the loads are traced, to a storage buffer the address is in on only some paths. In PRAGMATA the title's Earth and Moon and the intro's ship and cockpit were black. - Cause: for an address that is a phi,
GlobalToStorage.TryGenerateMultiTargetStorageOpcollects the storage buffers its sources trace to and makes a helper that range-checks each one. A source it cannot trace (an address the shader loaded from memory) was skipped without a word, and the helper returned 0 when the address was in none of the buffers. That case is exactly the untraced source. PRAGMATA's cluster culling251426e9d44fd558reads each instance's mesh header at an offset of its push+0x170 buffer on one path and at an address from its table at push+0x110 on the other, in other pools. Every header read gave 0, every instance 0 clusters, so the chain after it (3c5dde027a045df7,1b16be7a9ee2c490, which fills the mesh draws' records) had nothing to count. Found with counters added to the kernel's MSL (a copy laid over the library from a folder beside its image): 59,000 items reached the header test, 0 reached the header read, 0 reached either output store. - Fix: general, in the chain (
GlobalToStorage.cs). A source that is neither traced nor another phi marks the access. Its helper keeps the range checks, and on a miss calls the pool table helper (TryGenerateRawStorageOp, Global memory at an address loaded from memory) instead of returning 0. A tag after the buffers keeps it apart from a helper whose sources are all traced. An access the table cannot serve (an atomic on an 8- or 16-bit value) keeps the 0. The build notes saytraced to a storage buffer on some paths only. - Found on: PRAGMATA (
0400C76024710000): the title's 3D and the intro's mesh-shader geometry.
Bindless constant buffer handles in the hardware's layout
- Symptom: an NVN2 shader that reads a constant buffer through a bindless handle (
cx[UR][offset]) gets a dummy buffer or zeros, with[RED] shader <key>: the buffer address the game pushed at c[24] + 0x… is 0x1800830776a28, in no memory pool: bound to a dummy buffer(an "address" of 49 bits, with a small number in its top bits). - Cause: the handle is not an address. Its layout is the hardware's (as NVK's
nvk_bindless_cbuf): bits 0..44 hold the address >> 4 and bits 45..63 the size >> 4. The translator (InstEmitAmpere.csABindlessConstant) used the handle as the address, and that worked only for the handles the host writes itself (compute's uniform entries in c[0]), because the host wrote plain addresses there. A game that builds its own handles reached no pool. PRAGMATA pushes them: its SDF compute shaderb12078fe3bce1273takes three at push block 1,0x5a0083055d124= 32 bytes at0x83055d1240, the other two 192 bytes each. Its pixel shaders also load such handles withLDG.64from the game's own buffers. An earlier attempt to decode the handle in the shader alone met the host's plain addresses: wild reads, a GPU timeout and page faults at the first 3D frame. - Fix: general, in the chain and the host.
- Translator:
ABindlessConstantdecodes the handle: the address is(handle & (2^45 - 1)) << 4. - Storage pass (
GlobalToStorage.csTryUnwrapHandle): traces that address (handle << 4) back to the handle's constant buffer words as it traces an address, and marks the target (SearchResult.Handle, bit 15 of a packed target). A multi-target helper compares the decoded address and size. - Host (
nvn_mtl.m): writes NVN2's uniform entries in the hardware's layout (ucb_handle; NVN1 shaders read the plain address there, Link's Awakening'sc0[0x280]). The readers of a pushed or a uniform-buffer word (NVN_RB_SBUFQ,NVN_RB_SBUFU) decode a handle (ucb_handle_addr): a handle of any size has a bit at 45 or above, which no guest address has, so a word with a plain address is read as before. - Traces unchanged: a 312-shader sample of PRAGMATA's library (every stage, with uniform, pushed and raw bindings) built with the same bindings and raw-access notes as before.
- Translator:
- Open: a read past the handle's size returns what lies there; the hardware returns 0.
- Found on: PRAGMATA (
0400C76024710000).
A uniform word << 4 taken for a bindless handle where it is the offset
- Symptom: skinned meshes lose parts or explode: players without heads in the lineup cutscene, and with the uniform test rewrite on, giant triangles over the pitch at pauses and in cutscenes. No red line; the shaders build. In a shader's Metal source, a storage buffer read's word index is
c[x][y] >> 2where the previous chain had(c[x][y] << 4) >> 2. - Cause:
GlobalToStorage.FindUniqueBaseAddressCb, for an address that adds two sources, replaced each source thatTryUnwrapHandlematched (a constant buffer word << 4, the address of a bindless handle) by the word itself, before choosing which source is the base. When the other source was a buffer's address (c[0], or a pushed entry in c[24]), the shifted word was the offset, and the access went to the unshifted word: element y / 16 of a 16-byte array instead of element y. The match also ran on Maxwell code, which has no bindless constant buffers, so on NVN1 it was always wrong. Ampere code meets the same offset throughLEA(index << 4 plus an address). - Fix: general, in the chain (
GlobalToStorage.cs).TryUnwrapHandlematches only in Ampere code (TranslationFlags.Ampere, throughTransformContext.Ampere), and there the handle's words stand for a source only as the base; the source chosen as the offset keeps its shifted value. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_storage_offset.py: a Maxwell compute shader (c[0] + 0x110 plus c[3][4] << 4) and an Ampere one (a pushed entry plus c[3][0x10] << 4 byLEA); both fail on chain ff7c2e3ba2b4. On the PR author's build (PR #1129), 23 vertex and 8 compute shaders of EA SPORTS FC 27's 7,875 had lost the shift, and all 31 matched chain 2afd39090b76 (before the handle pass) again with the base-only rule. - Found on: EA SPORTS FC 27 (
0100C49025D3E000): its skinning vertex shaders (0a82d49f3c969ed1among them) and compute shaders.
Raw global memory through a pointer read when the draw is bound
- Symptom: a raw load reads 0 when its pointer names a pool omitted from the raw table. Ocarina of Time's eight culling task shaders then compute
(min(end - start, 256) - 1) >> 5from two zero range ends: 134,217,727 iterations and an isolated GPU hang. - Cause: the address filter lists pools whose GPU addresses NVN handed out. A pointer derived by the game can reach another pool. Refreshing the table at commit handles pools created after encoding, but does not discover these existing, unaddressed targets.
- Fix: general, in the translator, reflection and host.
GlobalToStorage.FindPointerSitetraces fixed storage-buffer words contributing a raw load's address, including across mixed traced/loaded pointer paths.dmsh_reflect.gptr_sitesrecords up to 64 supported[NVN storage slot, byte offset]sources on the existinggmem_mapbinding. Before argument-block reuse as well as a fresh encode,gmem_discoverreads each complete pointer word, including a covering queued inline update. It checks the binding's size, the source pool and sparse mapping before a CPU read. A valid target admits its logical pool or mapped run throughmtl_pool_addressed; the existing commit-time table refresh and write-log pairing then apply. Texture-only pools with no discovered pointer remain excluded. There is no extra GPU binding, site check, or change to scalar/vector raw helpers. - Limits: a pointer generated later by the GPU, a dynamically indexed source, or an unsupported source descriptor still relies on the addressed pool table. Discovery does not establish a fix for the separate whole-mesh GPU hang. The memory line reports pointer words read and newly addressed logical ranges; those bytes are not a measurement of additional wired memory.
- Checks:
test_dmsh_raw_pointers.pytranslates scalar, 64-bit, 128-bit and mixed-path loads;test_dmsh_reflect.pyandt_reflcheck metadata.t_gmem_wordschecks an omitted target, commit refresh, changed pointer data without rebinding, bounds and queued inline updates;t_vpool_first_mapexercises an unmapped sparse source and a word crossing a mapped run's end. The existing raw-helper GPU tests cover scalar/vector reads and misses. PR #1585 supplies the original diagnosis: on an M3 each of the eight task shaders hung with its pool omitted (about 22 ms GPU time) and completed with its target supplied; its original site-table implementation filled 1,091,044 sites over 2,700 frames on an M2 Pro 16 GB. Those are contributor results for that implementation, not measurements of this table-population revision. - Found on: The Legend of Zelda: Ocarina of Time.
Raw global memory lookups that start from their last entry
- Symptom: a pass whose shaders read memory through loaded addresses takes several milliseconds on the GPU for little work.
[gpuprof]names the pass, and its shaders' build notes sayGlobal memory operation "Load" traced to no storage buffer. Ocarina of Time's foliage mesh shader73dc0b90c4082e43(Foliage.Product.110, 135 such reads) took 10.9 ms of a 683x384 frame; 2,241 of the game's shaders (vertex, compute, fragment and mesh) have such a lookup, some hundreds of them. - Cause: each 32-bit word found its pool on its own (Global memory at an address loaded from memory): the hint of its 2 MiB chunk, and on a miss the 13-step search of the pool table. A shader reads a structure word after word from one pool, so all but the first lookup of a run chose the entry the first one chose.
- Fix: general, in the translator (
GlobalToStorage.TryGenerateRawStorageOp). Each helper keeps the entry it chose last in a private word of the invocation (ResourceManager.AddRawLastEntryMemory, zero at the start through a SPIR-V null initializer,MemoryDefinition.ZeroInit; spirv-cross declares ituint _N = 0u;inmain0and passes it to the helper). An address inside that entry's range takes it without the hint or the search; a hint or a search records its choice. Loads, stores and atomics all do it, and a store's write log bit is the chosen entry's. It holds because the table's ranges are disjoint (nvn_mtl.mgmem_map) and the host binds one table for a whole draw or dispatch; entry 0 is empty, so an invocation's first lookup searches.dmsh_meshstage.pykeeps thread variables declared ahead of the stage memory indm_stage_body: until then Ocarina of Time's 98 mesh and 11 task shaders with such a lookup failed the mesh stage (no kernel main0 starting with its stage memory). - Shorter load check: the host stores a 32-bit byte span in the pool entry when the range fits within one 4 GiB address window and its length fits in 32 bits. A load can reuse the last entry by comparing the high address word and checking the unsigned offset against that span. A zero span sends loads through the full lookup, including for ranges that straddle a 4 GiB boundary. Stores and atomics use exact ranges and the submission's write log. Guest-visible NVN addresses stay CPU-compatible.
- Check:
dm/gfx/tests/test_dmsh_raw_last.py: the translated helper's shape, and on the GPU its reads over runs of addresses that stay in, leave and come back to pools (adjacent pools, a gap, a hinted chunk above 4 GiB); the scalar and vector checks also cover a range straddling a 4 GiB boundary and a miss with the same low word in another window.test_dmsh_meshstage.pyfor the thread variables. Ocarina of Time on an M6 Mac (macOS 27.2), main's host, the 2,241 shaders of the new chain laid over main's libraries (the other 2,592 shaders built with them came out with the same MSL), the same scripted walk fromsave_refwith warmed pipeline archives, two runs a side: at the spawn point right after loading (the same view, about 2,500 draws a frame) the GPU span p50 went 16.53 / 16.41 → 14.11 / 14.57 ms, and over the walk 15.7 → 14.0 ms. Screenshots at the spawn point match, and so do the red lines. - Open: over the walk the frame time p95 went 19 → 26 ms. The runs ended in different places (the route is timed and the game moves at its frame rate), the new side's render target loads were higher (the game's dynamic resolution taking the headroom), and the Mac had 8 GB of swap in use, so this is not settled. Keeping the range itself in registers (PR #1464's form, no table reads on a hit), tried on an M4 Pro (2026-11-08) as an overlay of Ocarina's eleven hot task and mesh shaders, changed nothing (GPU p50 16.45 → 16.61 ms, two runs each): the table reads hit the cache. The time went to the words of each 128-bit load being read one by one (128-bit raw global loads read one word at a time).
- Found on: The Legend of Zelda: Ocarina of Time; the diagnosis, the cache and the first measurements in PR 1464 and PR 1405.
Raw global lookups built once for every call
- Symptom: a pipeline whose shader reads memory through loaded addresses takes seconds to compile on a cold Metal cache, and the GPU waits at its first draw (Native mesh pipelines compiled at their first draw); its library is large for its MSL. Ocarina of Time's foliage mesh shader
3439aaa071d868aemakes 141 raw accesses; its pipeline took 1.9 s on an M2 Air, and the route's 54 task / mesh pipelines 25 s at the first start. - Cause: the pool table lookup of a raw access (Raw global memory lookups that start from their last entry) is a helper function, and spirv-cross marks every function
static inline __attribute__((always_inline))(it ignores SPIR-V'sDontInline). Metal's compiler built a copy of the last-entry check, the chunk hint, the binary search and the physical-pointer access at each access. - Fix: general, in the chain. The translator puts the chunk hint and the binary search in one function per shader,
int dmsh_raw_find(address low, address high), which returns the entry (GlobalToStorage.csGetRawFindFunction;SpirvGeneratorkeepsdmsh_names), and the access helpers call it past the last entry's check. The build (dmsh_rewrite.pyraw_noinline, called fromdmsh_build.pyfinishfor every stage) writes that functionstatic __attribute__((noinline))outside final mesh stages: one copy the misses branch to. Mesh stages retain the inline search as a compiler workaround. The last entry's check, the entry's end, the delta and the access stay inline at each access, so a hit runs as before. Writing the whole access helpernoinline(PR 2769's first form) compiled faster still but put the last entry and the vector words behind a call at every access: on an M4 Pro, Ocarina's still Kokiri Forest scene took 17.4 / 17.7 ms of GPU time a frame against 15.0 / 15.2 on main, in every pass with raw accesses. - Found on: The Legend of Zelda: Ocarina of Time, on main
74181da8(2026-11-16). Offline Metal 4 pipeline compiles (metal-tt, 5 runs each in turn, on an M4 Pro), main → this fix:3439aaa071d868ae's mesh pipeline with pixel shaderbd09ab5fc4fd76801.67 → 0.66 s for the M2 (applegpu_g14g; whole helpernoinline: 0.48 s), 1.81 → 0.70 s for the M4 Pro (applegpu_g16s), its archive 874 → 425 KB; the vertex pipeline offfc2a130a97593c3(216 accesses) with pixel shader9ef3ef25d67ef099, 1.38 → 0.73 s for the M2, 828 → 449 KB; the compute kerneld15370a382630d4e(384 accesses) 132 → 109 s (median of 3; most of its time is elsewhere), 3.2 → 1.6 MB. The 938 playtested shaders with raw accesses have main libraries of 233 → 109 MB; the playtested build compiled in 14 instead of 19 minutes. GPU time on the M4 Pro, the still Kokiri Forest route (kokiri-still, 1920x1080, warm pipelines, steady frames): 15.2 / 15.2 / 15.3 ms a frame on main, 14.8 / 15.0 with the fix. Earlier, with the whole helpernoinlineon an older chain (c39ed5ebd458) and a 16 GB M2 Air, the pipeline compiled cold in 1.92 → 0.46 s and the Kokiri Forest walk's frame time stayed within its runs' noise at 683x384. - Check:
dm/gfx/tests/test_dmsh_raw_noinline.py:dmsh_raw_findmarked, the access helpers and a function of the same shape without the name left inline, the pass idempotent, and the result compiles withxcrun metal.test_dmsh_raw_last.py(withDMSH_TEST_XLATE) runs the translator's scalar and 128-bit lookups on the GPU with the search inline andnoinline.
A noinline raw lookup crashes the M1 and M2 mesh compiler
- Symptom: Ocarina of Time logs
task / mesh pipeline prewarm failedwithXPC_ERROR_CONNECTION_INTERRUPTED; the compiler backend dies with SIGBUS inllvm::MachineOperand::setRegwhile compiling a mesh program. Other compiles interrupted by the same service death can fail too. The isolated pipeline can compile on an M4 Pro even when an offline compile for an older GPU fails. - Cause:
43e816d8introduced the separatedmsh_raw_findsearch and marked itnoinline(Raw global lookups built once for every call). This call shape triggers an external mesh-compiler defect: changing only the search's attribute back toalways_inlineremoves it without changing the lookup. The controlled inputs, exact targets and compiler identity are recorded in the linked game's validation. Offline evidence and a successful local-device compile do not establish the affected system compiler's runtime result. - Fix: a general chain workaround:
raw_noinlinekeeps the search inline in final Metal mesh code, and retains one search in other stages. Native task/mesh shaders reach the pass as compute shaders, sodmsh_build.pypasses theirmesh_stage.kind. Geometry-generated mesh libraries also restore the inline attribute inherited from their vertex/geometry inputs. No title, build or GPU-family branch is added; the library preserves the same lookup semantics on every target. Apple's compiler defect remains open. - Cost: estimate: mesh pipelines with raw accesses can take longer to compile and have larger binaries because the search is duplicated again. Earlier measurements in the linked entry concern one different foliage pipeline and the optimization across all stages; they do not measure this workaround's aggregate startup or mesh-only GPU cost.
- Check:
test_dmsh_raw_noinline.pycovers inline mesh code, already-rewritten inputs used by composed mesh libraries, unchanged non-mesh stages, idempotence and a real Metal compile. Offline verification exports every full manifest row through the production host, retaining differing descriptors even when rows share a shader triple; the linked game note records its coverage and results. - Found on: The Legend of Zelda: Ocarina of Time, the later M1/M2 reports in #2825 and #2911.
- Remaining: affected-device retests are recorded in the game note. Recovery of archives poisoned before the host fix remains separate; this workaround changes no host recovery or serialization.
Inlining mesh helpers with subgroup inputs can crash the Metal compiler
- Symptom: a native mesh pipeline fails to compile with
XPC_ERROR_CONNECTION_INTERRUPTED. The compiler report shows SIGBUS atllvm::MachineOperand::setRegunder the mesh backend. In-flight compiles in the same service can also fail. - Cause: SPIRV-Cross's translated helpers and the generated stage body are forced into the mesh entry points at
-O1. Relaxing that policy cleared the failure on an M2 Pro with macOS 27.0.1. Ordinary inlining still reproduced it offline at the 26.6 minimum. Forcing only the stage body out of line cleared the isolated row, with failures elsewhere in the batch. Forcing only the helpers that take subgroup inputs out of line cleared the entire batch. The earlier raw-search failure shares a backend stack signature. The relationship between the internal defects is unknown. - Fix:
mesh_subgroup_noinlinemarks SPIRV-Cross's multiline helpers withgl_Subgroup*parametersnoinlinein final native mesh stages. The generated stage body and raw search keep their inlining attributes. This is a workaround for Apple's backend. The same pass also rewritesthreadreferences togl_Subgroup*parameters by value throughout the final mesh source (Subgroup inputs passed by reference to out-of-line helpers read one lane's value). - Check:
test_dmsh_raw_noinline.pychecks that the rewrite selects the subgroup helper and preserves the raw search, stage body and other helpers. The isolated foliage pipeline reproduces the original SIGBUS in the offline backend ong14sat minimum 26.6. The subgroup helper rewrite clears the isolated pipeline and all 164 rows on the five checked targets. - Found on: The Legend of Zelda: Ocarina of Time, from d4kine's isolation in PR #3069.
Subgroup inputs passed by reference to out-of-line helpers read one lane's value
- Symptom: after a save loads, the game logs
kIOGPUCommandBufferCallbackErrorHangor a GPU page fault (ErrorPageFault), and thenGPU access revoked. Mesh groups write vertices and primitives outside their own output ranges. On Ocarina of Time this appeared once the subgroup helpers were made out of line (Inlining mesh helpers with subgroup inputs can crash the Metal compiler). - Cause: a defect in Apple's Metal compiler. SPIRV-Cross passes builtins such as
gl_SubgroupInvocationIDto helpers by reference (thread uint&). Onenoinlinehelper can pass that reference on to another, as Ocarina's exclusive-scan helper does with its shuffle step. Apple's compiler then reads the builtin as one value for the whole SIMD group. Every lane got the same prefix sum, so each mesh group's output bases were wrong. This reproduces at-O1,-O2and-O3, at minimum 26.6 and 27.0, in compute and mesh kernels. It does not reproduce at-O0, inlined, or by value. A by-valuegl_SubgroupInvocationIDis enough to correct the scan. A by-valuegl_SubgroupLtMaskalone does not correct it. Smaller helpers of the same shape did not reproduce it. - Fix:
dmsh_rewrite.mesh_subgroup_noinlinepasses thegl_Subgroup*parameters of final mesh code by value. They are SPIR-VInputbuiltins and are never written, so a copy has the same meaning. The helpers staynoinline, which avoids the SIGBUS. This changes our generated source to avoid Apple's compiler defect; the defect itself remains open. - Check:
test_dmsh_raw_noinline.pyuses synthetic nested helpers to check the by-value rewrite, the out-of-line attributes and idempotence. The game note records the local GPU reproducer, offline compiler checks and device results. - Found on: The Legend of Zelda: Ocarina of Time.
128-bit raw global loads read one word at a time
- Symptom: a pass of mesh, vertex or compute shaders whose build notes say
Global memory operation "Load" traced to no storage buffertakes milliseconds of its stage's time for little drawing, at any resolution. Metal System Trace's Shader Timeline shows no samples for task and mesh shaders, so such a pass looks idle there; the encoder's vertex-stage time and an overlay A/B tell. Ocarina of Time's foliage mesh pass took 4.6 ms of vertex-stage time a frame at 683x384, 0.2 ms of fragment. - Cause: the emitters split an
LDG.64/LDG.128into 32-bit loads (InstEmitAmpereMem.ALdg, Maxwell'sInstEmitMemory.EmitLdg), each with its own 64-bit address. Traced to no storage buffer, each word then went through the pool table on its own (Raw global memory lookups that start from their last entry) and was read through a pointer of its own, built from two 32-bit halves. Metal's compiler cannot see that four such pointers are consecutive, so one 128-bit read became four word loads, each waiting on its own address. Ocarina's foliage mesh shadereed1add7c89f5d34read 464 of its 506 raw words as pieces of 116 such loads. Measured on an M4 Pro: the lookups' table reads cost nothing (kept in registers, no change), and the reads were the time (replaced by a value made from the address, the frame's GPU time fell 16.8 → 13.0 ms). - Fix: general, in the translator. The emitters mark the words of one access (
Operation.GlobalVectorCount,GlobalVectorWord). For such an access whose address goes through the pool table,GlobalToStorage(ReplaceGlobalMemoryWithStorage,GenerateRawVectorLoad) calls a vector helper once (…RawV2/…RawV4,TryGenerateRawStorageOp): the first word's lookup, then one 64- or 128-bit load through a physical pointer (StorageKind.GlobalMemoryVector, the SPIR-V backend'sGenerateRawVectorLoad, aligned as a word like the scalar loads). Word 0 is returned and the others go to the shader'sgmem_veclocal memory, which the loads of those words read right after the call (they become copies, so the pass does not take them for global accesses again). The first word's entry holds the whole access: anLDG.64/LDG.128is aligned to its size on the GPU, and every pool table entry starts and ends on a pool's 4 KiB boundary (nvn_mtl.m gmem_map). Ocarina'seed1add7c89f5d34makes 122 vector calls and 22 word calls instead of 506 word calls, and its MSL shrinks from 7,949 to 5,656 lines. - Found on: The Legend of Zelda: Ocarina of Time: the Kokiri Forest route (
bench.tsvkokiri-deck, its partial shader set rebuilt, with occlusion conditions read once landed) on a 20-core M4 Pro went from GPU p50 16.3 / p95 18.6 ms at 34.7 fps (a 30 fps frame step) to 12.6 / 13.6 ms at 51.8 fps, frame p50 16.69 ms (60 fps most of the time), two runs each, picture unchanged. - Check:
dm/gfx/tests/test_dmsh_raw_last.pyRawVector(withDMSH_TEST_XLATE): anLDG.E.128through an untraced address translates to one call of a helper with oneuint4load and no word call, and on this Mac's GPU each of its four words is the pool's.
A 64- or 128-bit raw global load in no pool reads undefined upper words
- Symptom: a 64- or 128-bit load through an address in no pool (a null or stale pointer, a gap between pools) reads 0 in its first word and whatever the invocation's
gmem_vecheld in the others: the words of the previous vector load, or undefined data on the first. Before the change in 128-bit raw global loads read one word at a time, every word of such a load read 0. A shader that tests a loaded record's first word for 0 is unaffected; one that uses the other words (a bounding box, a count, a second pointer) gets garbage. - Cause: the vector helper (
…RawV2/…RawV4,GlobalToStorage.TryGenerateRawStorageOp) returned 0 on a miss but wrote nothing togmem_vec, which spirv-cross declares in the entry point without a value and the caller reads right after the call. - Fix: general, in the translator: before its miss return, the vector helper stores 0 to each of the other words, as the word loads it replaced read on a miss.
- Check:
dm/gfx/tests/test_dmsh_raw_last.pyRawVector.test_a_miss_zeroes_the_other_wordsandtest_a_64_bit_miss_zeroes_its_other_word(the 128- and 64-bit helpers' miss paths store 0 togmem_vec[0..2]/gmem_vec[0]) andtest_reads_on_gpu, whose kernel now sets the three words to0xdeadbefore each call: a read in no pool must leave all four 0. All three fail with the previous translator (on the GPU, 256 of its 1,024 reads: every miss). - Found on: found by reading the translated vector helper; no game's wrong picture is traced to it yet.
A word of one 128-bit load read from another's vector
- Symptom: wrong data, no error: of two
LDG.64/LDG.128in one block, a word of the second reads a word of the first load's memory, and the second load's own memory is never read. - Cause:
GenerateRawVectorLoad's follower scan took any later load with the same word count and a word above 0 as a word of its call. When the first load's later words are unused (so the scan does not end at its last word) and the second load's word 0 is unused too (so it has no call of its own), a used later word of the second load became a read of the first call'sgmem_vec. - Fix: general, in the translator: the emitters give each access's words a group of their own (
Operation.GlobalVectorGroup, counted byEmitterContext.GlobalVectorGroups), and the scan ends at a word of another group. That word then takes a lookup of its own. - Check:
dm/gfx/tests/test_dmsh_raw_last.pyRawVectorPair(two adjacent unpredicatedLDG.128, the first using word 0, the second word 2): one vector call, nogmem_vecread, one scalar lookup for the second load. It fails with the previous translator, which readgmem_vec[1]. - Found on: reported by lunks on PR #1813 from reading the code; none of Ocarina of Time's 2,055 shaders that call a vector helper has the pattern.
Bindless handles through a loop phi
- Symptom:
no resolved slot number, the shader does not load; the translation has a 32-entry texture-pool array (fp_t2d_cb0_40000000, handle type Direct). - Cause: the handle is
c2[0x1A0] | 0x10500000(separate texture slot 7, constant sampler 0x105), kept in a loop variable. Ryujinx's bindless elimination compared only the phi's direct inputs, gave up, and turned the access into an index into a 32-entry texture-pool array, which the replay cannot bind. - Fix: the vendored translator now follows the phis that feed a phi, and treats two
constant buffer | constanthandles as the same value (third_party/ryujinx/README.md). Those accesses become ordinary type-3 handles. - Found on: Monster Hunter Rise (218 pixel shaders).
Bindless reads whose handle phi also carries other values
- Symptom: none in the log: texture reads come back 0. Particle meshes collapse to a point (their scale reads 0), so effects are missing or show as dark patches. The translator's own message (
Failed to find handle source for bindless access of type "textureBuffer") used to be dropped, becausedmsh_xlate's accessor had noLog; its messages now go into the shader's notes, markedtranslator:, and the build summary counts them apart from unanswered queries. - Cause: the handle reaches the read through a phi. Some inputs are c2 handle words, the others are not handles: undefined, or a value the compiler kept in the same register on a path where the predicated read does not run (float arithmetic, a texture result, the absolute value of a uniform word). Some phis merge two or more different c2 handles too (a float and a half-precision buffer).
TryConvertBindlesscannot trace one handle, andGenerateBindlessAccessrefuses a phi with such an input, so bindless elimination deleted the read and wrote 0 to its results. - Fix: only for a phi
GenerateBindlessAccessrefuses (TryTableHandlein the vendoredBindlessElimination.cs, markednxnative:), the read takes the c2 handles among the phi's inputs (a word, or a texture word ORed with a sampler word or a constant sampler). With one handle, it takes the phi's place. With several, one read is made per handle and the result is the read whose handle equals the phi's value at run time: the host fills c2 with the bound handles, or with slot indices fortex_dyn_slots. A candidate that other reads of the shader use as a texture of another shape is left out, so those reads are converted in a second sweep once every other read has registered its texture (ResourceManager.GetTextureTypes). An image store or atomic with several candidates is left alone, since one per candidate would write each of them. A phi made only of handle words keepsGenerateBindlessAccess(the dynamic arrays of Texture slots picked at run time), so no other shader changes: in FINAL FANTASY RESONANCE, the SPIR-V of the 69,449 other shaders is byte for byte what it was. A chain change. - Found on: FINAL FANTASY RESONANCE: 58,122 reads removed (57,861 of them texture-buffer reads, mostly in Unreal's Niagara particle vertex factories), of which 58,096 in 3,197 shaders are now resolved: 21,380 with one handle, the rest choosing among 2 to 5 at run time. 26 reads in 14 shaders, whose handle comes from no c2 word, are still removed. Reported in GitHub issue #168.
Texture slots picked at run time
- Symptom: the shaders' bindless arrays have no slot and used not to load; the translator falls back to a 32-entry array such as
array<texture_buffer<float>, 32> vp_tb_cb0_40000000. - Cause: the shader reads one of several c2 texture-table words, chosen by branches. With separate textures (Octopath Traveler 0) it ORs the word with a sampler-table word; with combined ones (Paper Mario) the handle is read from the combined texture table (c2
0x20 + 8 × slot, constant offsets only). The translator cannot trace that to one slot and falls back to Ryujinx's bindless arrays,array<texture_buffer<float>, 32> vp_tb_cb0_40000000andarray<sampler, 32> vp_s_cb0_40000000, indexed by the handle's texture ID (low 20 bits) and sampler ID (high 12), capped at 31; the build leaves them without a slot. - Fix: for sampled buffer textures. Every other sampled texture indexes the whole texture pool (Texture handles from game memory index the pools), which took over Paper Mario's cube and 2D arrays, and every dynamic non-atomic image indexes the image pool (Image handles picked at run time index the image pool). With the profile key
tex_dyn_slotsthe reflection reads them asNVN_RB_TEXD/NVN_RB_SAMPDarrays (nvn_refl.m), the replay writes slot indices into that shader's c2 tables (texture slot r → r, sampler slot r → r << 20; in the combined tabler | r << 20in slot r) and binds slot k at element k, so the shader's own arithmetic lands on the binding: the handle names element r, which holds the texture bound in slot r. The array's other elements hold whatever the other slots do, mostly 2D textures where the array is of cubes; an array element bound to a 2D texture gets the zero cube without a type mismatch report (tex_fit_elem), since the shader does not pick it there. The host logs each such shader's first encode with the slots that held textures. Host only: the chain version does not change. - Check: check first that the handles come only from c2's tables: in Octopath Traveler 0 every integer read of c2 in those shaders is a table slot (texture slots 0-10, samplers 0-4).
- Found on: Octopath Traveler 0: 61 Unreal vertex shaders, particles reading their data from buffer textures (separate textures and samplers). FINAL FANTASY RESONANCE: 2,077 particle vertex shaders. Paper Mario: The Thousand-Year Door: 2,386 pixel shaders (5,476 cube samples, 487 2D), slots 0, 7, 8, 13 and 28 (combined table), until the pools took them over.
A texture chosen at run time between two uniform-buffer handles
- Symptom: Ryujinx's fallback arrays (
fp_t2d_cb0_40000000) in pixel shaders whose handle comes from the game's own uniform buffers; the shaders do not load and their draws are skipped. - Cause: the handle is one of two words of the game's own uniform buffers, chosen by a flag, packed as texture ID | sampler ID << 20.
tex_dyn_slotscovers only handles from the driver's c2 tables (Texture slots picked at run time). - Fix: the pools: whichever word the flag picks, its texture ID indexes the texture pool (Texture handles from game memory index the pools). Not checked on Big Brain Academy, whose files are not on the Mac the change was made on.
- Found on: Big Brain Academy: Brain vs. Brain: ten pixel shaders (six in
03GamePerception.bnbshpk, two PBR, two inmain); ine10f24835bbaa5f6the handle is c3 +0x130 or c12 +0x1d0, chosen by a flag in c12. None of the activities checked uses them; a long run of activities met one once.
Texture handles from game memory index the pools
- Symptom:
[RED] shader … reflection conversion failed: a texture handle the translator could not trace to one slot (profile key tex_dyn_slots off), thenfailed to load, and the draws are skipped: in Mario Party Superstars every character and NPC in a lit scene is a flat grey silhouette (the depth pre-pass draws, the colour pass does not), and the opening scene's pipe is grey. - Cause: a lit pixel shader loops over the lights, reading each light's shadow map, cube map and sampler handles from the game's storage buffer (
fp_s1) at a computed offset. Ryujinx cannot trace such a handle to a slot and falls back to arrays indexed by the handle's IDs (array<texturecube<float>, n> fp_tcube_cb0_40000000,array<sampler, n> fp_s_cb0_40000000, texture ID in bits 0–19, sampler ID from bit 20), clamped ton − 1. The translator's accessor gaven= 32 and the replay had no pool to bind there: onlytex_dyn_slotsarrays, whose handles must come from c2. - Fix: a chain change. The accessor sizes these arrays to the whole ID ranges (
Program.csQueryTextureArrayLengthFromPool2²⁰,QuerySamplerArrayLengthFromPool2¹²) for sampled textures other than buffer textures; buffer textures and images keep 32-entry slot arrays (vendoredBindlessElimination.cs,NvnSlotArrayLength).dmsh_reflect.pypool_arraysturns each such array into a pointer tostruct spvPool_<name> { uint n; array<element, 1> e; }, read as(&e[0])[min(index, n)], and renumbers the argument IDs (a pointer takes one). The struct declares one element because Metal's argument encoder walks every element of a declared array (AGX::IndirectArgumentLayoutGen2::parseArray): with 2²⁰ textures each pool shader's encoder took 57 ms and 66 MB, and the prewarm of 733 pipelines left the Mac host at 12.5 GB resident (9.7 GB of large mallocs); the elements are 8-byte resource IDs, so the pointer reaches the others (checked on the GPU with a test kernel); the reflection names themtex_pool(with the element type) andsamp_pool. The host keeps one buffer per element type and pool base (nvn_mtl.mpool_gpu): the bound n, then fromDMSH_POOL_HEADthe resource ID of each texture (sampler) ID of the pool bound at the draw, the dummy where an ID holds nothing or a texture of another type and at n. It is rebuilt when a registration or a texture's storage changes (g_reg_gen,g_ser_gen), the old buffer released after its submissions, and an argument block holding a pool address is not reused past a rebuild. Handles read from game memory are the bound pool's IDs, so the pool takes that pool's base (asubo_tex_id), and a pool shader's c2 holds the relative bound handles as the game wrote them; ordinary slot consumers resolve them through the execution pools. Every texture is already in the residency set. A walk over every ID also reaches IDs no draw binds, which a game leaves registered after it is done with them: the first walk once crashed innvn_sparse_protectmaking such a texture (a garbagepool->vp; the ID was not caught). So a texture no draw has made is made only while its storage exists (tex_storage_live: the memory pool object still holds its magic, and an ordinary pool's storage is in a pool the host maps), and an ID whose memory pool the game finalized is skipped until it is registered again (treg_t.gone, set intreg_drop_pool_views). Every other route is covered too: A texture read after its memory pool object was freed. - Found on: Mario Party Superstars: 6,370 of its 82,790 shaders, every character and NPC material (
_chara/pc/*.bnbshpk,_chara/npc/*.bnbshpk) and some board variants (hsmn_bg.bnbshpk); a 2,304-entry texture pool (1,286–1,314 2D textures, 65 cubes) and a 512-entry sampler pool, about 0.1 ms per rebuild once the textures exist.
Image handles picked at run time index the image pool
- Symptom:
reflection conversion failed: B binding cp_i3d_cb0_40000000_ has no resolved slot number(orcp_ib_cb0_40000000_, or deleted bindless image accesses): compute shaders that pick an image handle fromc2, a uniform buffer, or a storage buffer fail to load or never write their image (in The Duskbloods network test,GXFogVolume_*reads its 3D image handle from storage buffer 0 and the world drew black behind the HUD; in Persona 3 Reload, 150 compute shaders pick images fromc2and 59 write 1D buffer images dynamically). - Cause:
BindlessEliminationexcluded storage images from the pools, falling back to 32-entry slot arrays (<stage>_i<dim>_cb0_40000000_<fmt>) or deleting non-table image accesses, anddmsh_reflect.pypool_arrays/nvn_refl.mhad no image-pool binding kind (img_pool). - Fix: a chain change (
hostbinding, no profile key). Every dynamic non-atomic storage image (2D, 3D, array, cube, 1D and buffer images, whatever made its handle) sizes its fallback array to the texture pool length (BindlessElimination.csIsPooled/GenerateBindlessAccess).dmsh_reflect.pypool_arraysturns<stage>_i…_cb0_40000000…arrays into unmarkedspvPool_pointers reflected asimg_pool(DMSH_KIND_IMG_POOL), wrapping buffer-image.read,.writeand.get_widthintodm_buffer_read/dm_buffer_write/dm_buffer_widthwithp->bias.nvn_refl.mmapsimg_pooltoNVN_RB_IMGP(rwfromelemaccess qualifiers,pool = 1,bindless = 1), andnvn_mtl.mimg_pool_gpubuilds a cached per-(dtt, dpf, rw, base)table of live target-compatibleIMAGE-flagged textures (andleadsfor buffer images, plus anyRegisterTexture-only ID bound toS.img), silently placing the type-matched write sink (dummy_img) everywhere else and bumpingg_psnap_genon rebuild;image_prepare_shaderprepares only matching liveIMAGEtextures in the active pool. - Check:
test_dmsh_pool_arrays.py,test_dmsh_ampere_mem.py(DynamicImages),t_reflandcheck_t_img_pool(t_img_pool.m, Metal GPU test covering 3D SSBO handles,c2-picked 2D images includingRegisterTextureupgrade, unaligned buffer-imagedm_buffer_write/read/width, andg_psnap_gen). - Found on: The Duskbloods network test (PR #2616 / #2617,
GXFogVolume_*and dynamicc2compute images) and Persona 3 Reload (PR #2654, dynamicc2and buffer-image compute shaders).
Handles a shader computes index the pools
- Symptom:
[RED] <key>: the translator deleted N bindless accesses (<type> N): their results read 0for thousands of shaders, andlost without failing: …in the build; textures read as black (PRAGMATA: 65,241 reads in 8,630 shaders, its intro a saturated cyan). - Cause: the handle is no word of any buffer but a value the shader computes: RE Engine's materials read a heap index from game memory (
cx[UR][off]) or from a uniform buffer at a computed offset, clamp it to the heap (0x100–0x7fff), and OR it with a sampler ID (| 0x10800000, or with a separate sampler word of c2).GenerateBindlessAccessread such a handle through the pools only when it was loaded straight from a constant buffer, an input or a storage buffer (Ryujinx'sIsBindlessAccessAllowed, kept there to spare its pool walks), so every other read was deleted. - Fix: a chain change. A sampled texture other than a buffer texture indexes the pools whatever made its handle (vendored
BindlessElimination.cs): its texture ID indexes the texture pool and its sampler ID the sampler pool, as on the GPU. Images and buffer textures keep the old rule, since their slot arrays are bound only for handles from c2's tables. - Found on: PRAGMATA: no access is deleted after the change. Any game with deleted sampled reads in its build log (Losses a shader build reports) changes with it.
- Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py GuardedWrites.test_a_computed_handle_reads_the_pools.
A handle loaded from memory on one path only
- Symptom:
reflection conversion failed: B binding … has no resolved slot numberat load, thenthe dispatched program has no compute shadereach time the game dispatches it; the build log hasBindless handle taken from the one constant buffer handle among its phi inputsfor the shader. - Cause: the handle is a texture ID ORed with a constant sampler, and the ID's register holds a word loaded from memory on the path that reads the texture and something else on the other (a pushed buffer address's high word,
c[24] + 0x114).TryTableHandlewalks the OR's phi inputs for words of a uniform buffer, did not count the loaded word (a global loadGlobalToStorageserved is a copy of its helper's result, not aLoad), and took the stray word alone as the handle: a binding the host has no slot for. - Fix: a chain change (vendored
BindlessElimination.cs). For a read that indexes the pools, a handle with a loaded word among its phi inputs (IsLoaded: a load, a call, or a copy that keeps a storage kind), alone or as a source of the OR, is left toGenerateBindlessAccess: the read takes the texture its ID names, whatever path made it. Images and buffer textures keep their candidates. - Found on: PRAGMATA: compute shader
02e1292114121308, which reads a material's texture by an ID from a material record. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py -k test_a_texture_id_loaded_on_one_path_indexes_the_pools.
One handle read as a texture and as an array
- Symptom:
[metal failed]in the build, the compiler's messagevector component access exceeds type 'float2'on a line that samples atexture2d_arraywith a two-component coordinate anduint(rint(coord.z))as its layer; the shader and its alpha test entry points do not build. - Cause: a handle has one binding, declared with one type, but Ryujinx gave the declaration the type of the last instruction that read it and the descriptor the first accurate one, while each instruction built its coordinates for its own type. A 2D read (
TEX2D at level 0) of a binding another instruction read asARRAY_2D(TXD) gave no layer, which is invalid SPIR-V that SPIRV-Cross wrote out as it was. - Fix: a chain change (
ResourceManager.UnifyArrayTypes, run once every function is translated). A 1D or 2D binding that some instructions read as an array is an array for all of them, in the declaration and in the descriptor the host binds by; an instruction that gives no layer reads layer 0, which is what the GPU reads through a non-array instruction. Level-of-detail queries take no layer either way. Cube and 3D bindings and arrays of handles are left as they were. - Found on: PRAGMATA: 24 pixel shaders (
21ba8fea5a5eb03cis one), each readingcb65542handle0x3041000Eboth ways. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_nvn2_buffers.py -k test_a_handle_read_as_2d_and_as_a_2d_array_is_an_array.
An array of handles in a uniform buffer
- Symptom: the host stops at the shader's first load:
unexpected argument buffer layout: encodedLength=640 maxAid=48. - Cause: a loop reads one handle per light from the game's uniform buffer at a computed offset; Ryujinx's texture array from a buffer indexes it by the handle's byte offset ÷ 8 (an NVN handle is 64-bit, the shader computes
(word >> 2) << 1 | (word & 3) >> 1). The build reads the name as one bindless texture (tex_ubo, offset 0), so the argument buffer was 32 entries longer than the reflection said. - Fix: the host's reflection reader takes the array length from the MSL type, and the replay fills element k from the handle at byte 8k of that uniform slot (
NVN_RB_TEXU/SAMPUwithn); elements whose bytes are not a registered texture or sampler ID read the dummy, silently. No chain change: the build already wrote the array type. Sampled textures have since moved to a table the replay builds; this form remains for images and buffer textures. - Found on: Paper Mario: The Thousand-Year Door: the reflection shaders (
reflection.bfsha:array<texture2d<float>, 32> fp_t2d_cb14_0and its samplers), c14 (uniform slot 11). The first run showed elements 0–3, 6 and 8–12 holding textures, among them the shader's fixed handles at +8, +16 and +24 and the lights' from +64.
A table of handles longer than the array
- Symptom: characters and other moving objects have almost no ambient light: lit only from where the sun reaches, black underneath, while the scenery around them is right. Nothing is red. On Kirby Air Riders a dark red Kirby on a bright course, where the game's own tutorial movie shows him bright pink.
- Cause: an array of handles in a uniform buffer was declared with 32 elements and its index clamped to the last, but the game's table is longer. Kirby Air Riders' compute shader
f59db619b5c0be33traces each object's eight light probe values from atlases named in c[4], and its index was 390 for the player's objects: clamped to element 31, which held nothing, so the eight values were black and the vertex shaders that read them lit the character with nothing. Objects whose probes happened to sit under element 32 were lit. The table has 197 handles up to element 392, in a buffer of 4,096, and nothing in the shader tells how long it is. - Fix: a chain change.
Program.csQueryTextureArrayLengthFromBuffergives a game's uniform buffer 8,192 elements (64 KB of 8-byte handles),dmsh_reflect.pypool_arraysturns such an array and its samplers into pointers with a run-time bound, and the replay builds the table from the buffer (nvn_mtl.mhtab_gpu), as long as the last handle, looking again in each pass and keeping the buffer when the elements are the same. Images and buffer textures stay arrays of 32, bound element by element. Reading these handles through the pools instead gave the same picture and cost too much: the walk over 65,824 IDs made all 34,000 of the game's registered textures, 16 GB resident against 9.7, and 9 to 25 fps against 60. - Check:
test_dmsh_pool_arrays.pychecks the rewrite and the reflection. - Found on: Kirby Air Riders: most of its lit materials and light probes.
Reads of a handle table marked through a null address
- Symptom: a pass that samples through a table of a uniform buffer's handles takes hundreds of milliseconds on the GPU; nothing is red and the picture is right. In Fire Emblem Fortune's Weave on an M1 Pro, the lighting pass at Alcineus Bridge took 196.7 ms and the scene ran at 4 fps.
- Cause:
dmsh_reflect.pypool_arraysgave the table's texture reads the same mark as the pool's (dm_pool_mark, an atomic load, and an OR when the bit is clear, at the bitmap address in the buffer's header).htab_gpunever set that address, so every read went to address 0. The mark had no use there anyway: a table's index is its element, not a texture ID, and the replay has made every texture the table names before the draw. - Fix: a chain change.
pool_arraysmarks only reads of the texture pool (_cb0_40000000); a table is read plainly, and a fragment shader with no other mark keeps its depth test where Metal puts it. The header keeps its layout, with the address 0 in a table. PR #1738 (HammerChain), which found the null address, pointed it at a premarked bitmap in the host instead; with that the bridge ran at 56.1 fps and the lighting pass took 2.35 ms (M1 Pro, 1080p output from 960x540). The chain change takes the mark away as well, which leaves every table read a plain load. - Check:
test_dmsh_pool_arrays.py(test_table_of_uniform_handles). - Found on: Fire Emblem Fortune's Weave at Alcineus Bridge.
A handle table kept past a write to its handles
- Symptom: a draw or dispatch that reads a table of a uniform buffer's handles samples the texture or sampler of an earlier draw: the one before an inline uniform update (
nvnCommandBufferUpdateUniformBuffer) in the same pass, or, in a submission with compute work only, the one the previous submission read. Nothing is red. - Cause:
nvn_mtl.mhtab_gpukept a table without reading its handles again while the pass serial, the registrations and the size were the same. Neither covers a write queued in the submission over the handles (an inline update an open pass defers, a copy or a fill), and a compute-only submission keeps the last render pass's serial, so the guest memory read in the submission before was taken for this one's. - Fix: a table is kept only in the same pass and submission and when no write queued since its last look lands on its bytes (
htab_written:pend_sincescans the writes queued since then, or any when the host lost count). Otherwise its handles are read again as the GPU will see them (ubo_readwith the queued inline updates); changed handles go into a new buffer, as commands already encoded hold the old one, and the same handles keep it. A write elsewhere keeps the table without reading it, as games update other uniform blocks before nearly every draw; the table log line counts the reads. Handles written by a buffer copy, a fill or a shader are still read as the CPU sees them (see Handles in uniform buffers written earlier in the same submission). - Check:
dm/gfx/tests/t_htab_update.mencodes real draws and dispatches throughencode_argswith red and green textures and clamp and repeat samplers: full and partial inline updates between two draws in an open pass (the first draw's pixels unchanged), a write beside the table (kept without a read), two dispatches around an update, and a new compute-only submission. Main before the fix failed 8 of its checks. - Found on: source review in PR #2228 (akratch); no game's symptom is attributed to it yet. It reaches the games that read handle tables: Kirby Air Riders, Fire Emblem Fortune's Weave and Paper Mario: The Thousand-Year Door.
An array of uniform-buffer handles with its sampler word in c2
- Symptom:
reflection conversion failed: B binding fp_t2ds_cb196614_10570000 has no resolved slot number, thenfailed to load; those draws are skipped, and the scene is dark or black where it is lit by them. - Cause: handle type 1 on an array of handles in a uniform buffer: the texture words in the game's c[6], one separate sampler word in the driver table (slots 0x30006: the high half is bank + 1, so bank 2; word 0x15c, c2 byte 0x570).
decode_ubo_textook only a uniform buffer for that word. - Fix:
decode_ubo_texanswers ('c2', byte), the reflection gives the samplersregDMSH_SREG_C2, and the replay takes every element's sampler from that c2 word (sampu_id), whose IDs are moved already, as those ofNVN_RB_SAMPA. - Found on: Kirby Air Riders: about 5,700 pixel and compute shaders, its shadows and lights.
- Check:
test_dmsh_reflect.py(UniformArraysWithDriverSampler).
A separate sampler ID in a uniform buffer (handle type 2)
- Symptom:
reflection conversion failed: B binding fp_t_cb720898_2000005ASmplr has no resolved slot number, thenfailed to load; those draws are skipped. In The Witcher 3 245 of 602 shaders failed this way, its domain shaders among them, and the screen stayed black. - Cause: handle type 2, Ryujinx's
SeparateSamplerId: the texture word is in the driver table c2 (the low half of the slots, 2), and the second word is a sampler ID itself, not a handle with the ID in its high 12 bits, in one of the game's uniform buffers (the high half less one: slots 0xb0002, bank 10;(handle >> 14) & 0x3fffits word).decode_ubo_texdecodes a uniform buffer only for the texture half, so the sampler had no slot.decode_texalso tried both words for the texture, so a sampler word at a byte offset that is a combined texture slot's in c2 (0x20 to 0x11f) would be named as the texture. - Fix: a chain change.
dmsh_reflect.pydecode_ubo_samp_idgives a single sampler of this formsamp_ubowith the uniform slot and the word's byte offset andraw_id, anddecode_textakes only the first word as the texture for type 2, as for type 3. The replay reads the word and shifts it into the handle's sampler field before the pool lookup (nvn_refl.hraw_id,nvn_mtl.msampu_id). Arrays of such samplers are not covered; none is known. - Found on: The Witcher 3: Wild Hunt — Complete Edition:
fp_t_cb720898_2000005ASmplrin 181 of its shaders,fp_t_cb720898_2000405CSmplrin 34. - Check:
test_dmsh_reflect.py(SeparateSamplerIds) andt_refl(theraw_idkey).
A table of handles past the array's length
- Symptom: characters shaded black; a shader indexes a table of cube maps, and every element it reads clamps to the array's last one, which holds no handle.
- Cause: the shader reads
c[14][8 * i + 0x340].BindlessToArraystarts an array of handles at the buffer's start, so with a base past the array's length (32) each index ran off its end. - Fix:
TryArrayBasefinds an index plus a constant base; when the base is past the length, the array starts at the base and the index is the handle's place in the table.nvn_mtl.mfills element k from the array's offset + 8k (NVN_RB_TEXU,NVN_RB_SAMPU). A base inside the array keeps the array at 0, as before. - Found on: Fire Emblem Fortune's Weave:
e496014da6497fadand the character shaders.
An array of handles from the driver table c2
- Symptom:
shaders with a binding whose slot was not decoded 588; shadow cascades read througharray<texture2d_array<float>, 32> fp_t2das_cb2_0. - Cause: Ryujinx's texture array from a buffer, as Paper Mario's uniform-buffer arrays (An array of handles in a uniform buffer), but over the driver table c2, indexed by (0x80 + a cascade offset) ÷ 8.
- Fix:
dmsh_reflect.pyc2_arraynames ittex_c2a/samp_c2awith the c2 byte offset of element 0; the replay fills element k from the slot whose c2 word is at that offset + 8k (combined, else separate), and the dummy elsewhere (NVN_RB_TEXA/NVN_RB_SAMPA,c2_handle). - Found on: Luigi's Mansion 3 (586 pixel shaders, the shadow cascades).
Arrays of c2 handles cover the whole table, with a separate sampler word
- Symptom:
[RED] shader … reflection conversion failed: B binding fp_t2d_cb196610_10570000 has no resolved slot number, then, with that resolved,… reads driver-bank locations at run time that the replay layer cannot fill: c2 dynamic index; the shader does not load and its draws are skipped. - Cause: two gaps in An array of handles from the driver table c2. The translator sized every texture array from a buffer at 32 elements (
Program.csQueryTextureArrayLengthFromBuffer) and clamps the index to the last one, but over c2 the index is any handle word's byte offset ÷ 8: EA SPORTS FC 27's pixel shaderdc446d7f52c14ea6loops over separate texture slots i = 1, 2, …, reads each handle word at c2 byte 0x168 + 8i and samples element 45 + i, so every element it picked was clamped to 31 (a combined slot). And the handle is type 1:BindlessToArrayORs one fixed separate sampler word (c2 byte 0x570, separate sampler slot 1) into every element's handle, whichc2_arraydid not decode (it took only_cb2_with type 0), so the texture array had no slot and its sampler array took that one slot. - Fix: a chain change.
Program.csgives an array over c2 one element per handle word up to the end of the separate sampler table (C2HandleWords, 301; other buffers keep 32),c2_arraydecodes type 1 with the sampler word in c2 too (soffin the reflection), and the replay ORs that word into each element's handle for the samplers (NVN_RB_SAMPA;c2_handlenow also answers the separate sampler table).nvn_rbind.nis 16 bits andNVN_REFL_MAXARG768 (such a pair takes 602 argument entries). The same loop reads each handle word itself at a computed c2 index (fp_c2._m0[int(_237)], to test the light's handle), whichunfillablerefused for any bank; the replay fills c2's handle tables whole (DRV2inencode_args), so a computed index into c2 is accepted, and one into c0, filled only in its tables, still refused. Luigi's Mansion 3's cascade arrays become 301 long as well; the host fills the elements past the handles with the dummy. - Found on: EA SPORTS FC 27 (its lights in a match).
- Check:
test_dmsh_reflect.py(DriverTableArrays,DriverReads) andtest_dmsh_abi.py(the translator's table length agrees with the header).
A texture slot that shares its c2 word with an image slot
- Symptom: characters and props glowing white, about 10⁴ too bright, in DRAGON QUEST VII Reimagined's opening cutscene only, while walls and gameplay look right.
- Cause: a size query (
GetDimensionson aRWTexture3D) is a TXQ on the image's handle, c20x120(image slot 0): the build numbers it combined texture slot 32, the slot that shares that word, and with no type in the facts table the translator read it as 2D. The host bound the empty texture slot 32, and the 1×1 dummy's size passed only thread (0, 0, 0). - Fix: two general fixes: a texture binding of slot 32–39 reads the image bound in slot 0–7 when there is one, as c2 holds it (
nvn_mtl.mtex_slot_h; Hades II's texture slot 34 without an image still reads the texture), and a query on an image handle the facts do not type is translated again with the type of that image from the first translation (dmsh_xlateImageTypesOf). - Found on: DRAGON QUEST VII Reimagined: the per-pixel volumetric lightmap read brick (0, 0, 0) of the brick atlas for almost every cell. Unreal merges each streamed level's lightmap into one atlas on the GPU: brick copies (
0a7ff4171bd1a82a), then a patch of the shared 16³RGBA8_UINTindirection texture (7b958a7b21e72801) whose bounds come fromGetDimensionson the veryRWTexture3Dit writes. Only cell (0, 0, 0) was written, every other cell kept size 0, and the shader fell back to the atlas origin: the first daytime level's bricks, baked about 2¹⁵ brighter (the same bricks in gameplay hold 0.5–1.4). Monster Hunter Rise has four such size queries (cp_t_tcb_48/_4A). - Check: how it was found: the raw scene colour (
texraw) put the characters at 1,000–2,000 and the walls at 0.05; a debug build of one character shader that wrote its terms in alternating 8-pixel columns isolated the volumetric lightmap ambient term; dumps of the atlas (texlist/texraw), of the uploaded level bricks (the 3D upload dump) and of the indirection texture, with the cell computed from the primitive's origin and ViewVolumetricLightmapWorldToUVScale / Add(View 220 / 221), gave the rest.
A size query on a 3D texture gets a 2D slot
- Symptom:
[RED] texture type mismatch: shader … declares slot 128 as Metal type 2, texture ID … is type 7 (NVN target 2, …); bound as is, for a shader whose MSL has atexture3dand atexture2don the same register and only callsget_width/get_heighton thetexture2d. - Cause: a size query (TXQ) carries no texture type, and a table built without the game's PC shaders does not answer one, so
QuerySamplerTypedefaults to 2D. A handle ORs a texture word and a sampler word, and the query's has another sampler word than the sample's, so Ryujinx's merge by handle (MergeTextureMeta) keeps them apart. The shader then has a second binding of the slot, typed 2D, beside the sample's owntexture3d, and the host has no 2D view of a 3D texture (tex_fit). In Princess Peach: Showtime!, 1,490 slots in 1,463 of 56,594 shaders had that pair. The same pair with a cube (27 slots,get_num_mip_levels) or a 2D array raises no red line, since those have a 2D view. - Fix: general, in the translator: when a query's guess meets another type on its texture slot,
dmsh_xlatetranslates again with that type (TextureTypesOf), asImageTypesOfdoes for images. Types go by slot, as the answer table does; the table comes first, a query with nothing else on its slot stays 2D, and a slot two instructions give different shapes keeps the guess. The values these shaders read do not change: every query of the 1,490 3D slots reads only the width, or the mip count on the 27 cube slots, and an Apple M6 returned the right width through the old binding for all six sizes tried. What changes is that Metal now defines the binding. - Check:
dm/tools/tests/test_txq_type.py(synthetic shaders; the fix's tests fail on the translator before it). Princess Peach: Showtime! has no such pair left, and its route into the ninja play went from 15 red lines to none, with the same picture at the same spot. Of the 69 local games' shader folders scanned, only two others hold the pattern: Ghost Trick (2 shaders) and EA SPORTS FC 27 (1), each with a 2D array. - Found on: Princess Peach: Showtime!: up to 19 red lines per run, with no visible fault over the first play.
More than 64 bindings in one shader
- Symptom:
[RED] shader … reflection conversion failed: 66 bindings, over the limit 64, thenfailed to load, and the draws with it are dropped (a black map). - Cause: the reflection is converted into fixed arrays of
NVN_REFL_MAXBbindings (nvn_refl.h), which was 64. NVN gives a stage 32 textures and 32 samplers beside its uniform and storage buffers and images, so a shader can have more. - Fix:
NVN_REFL_MAXBis 128; the argument buffer entries keep their own limit (NVN_REFL_MAXARG, 768, see Arrays of c2 handles cover the whole table). It was raised from 96 when every sampled sampler got a twin binding (Border colours Metal has no sampler state for): that shader then has 97 bindings. - Found on: OCTOPATH TRAVELER II: the 3D world map of the traveler selection (
UiMM_WorldMap3D, pixel shaderf7c8373b7323687d: 30 textures, 30 samplers, 3 uniform buffers and the c1 / support / driver segments).
Argument buffer members with attributes after their id
- Symptom: the host stops at a shader's first load:
FATAL shader … has an unexpected argument buffer layout: encodedLength=88 maxAid=8(crash inc1_store/pull_load), with a storage buffer or image missing from its reflection json. - Cause: a pixel shader that writes a storage buffer and images inside a fragment interlock (the translator's FSI,
PixelInterlockOrderedEXT) gets those members as[[id(n), raster_order_group(0)]]from SPIRV-Cross.dmsh_reflect.pyreflectmatched only[[id(n)]], so it left them out, and the host's argument buffer came out longer than the reflection. - Fix:
reflectreads attributes after the id, and a member it still cannot read fails that shader's build (reflection failed) instead of loading with a short reflection. A chain change. - Found on: Mario Party Superstars:
light_primitive_point_cluster.bnsh(56071a5cf62dccc3, the engine's clustered point lights), first drawn on the way into a party.
Image atomics
- Symptom: the replay put a texture resource ID where the shader wanted an address; with the old 64 KB dummy buffer, pointers in the game's objects and in the host's program objects got their upper 4 bytes replaced and the game or the replay crashed, or
kIOGPUCommandBufferCallbackErrorPageFault, after which macOS ignores the process's command buffers (GitHub issue #101). Later,[RED] image atomics on a block-linear texture … not followed, the atomics go to a scratch buffer, and compute shaders with atomics on a 3D image did not build (array subscript is not an integer). - Cause: below MSL 3.1, SPIRV-Cross emulates an image atomic with a raw device pointer beside the texture (
texture_buffer<uint> cp_i_cb2_4C_r32uianddevice atomic_uint* cp_i_cb2_4C_r32ui_atomic), indexed by the bound image's width (spvImage2DAtomicCoord), so the host had to bind memory in that packed layout. A buffer image's pool memory has it. A block-linear image's Metal texture is a deswizzled copy whose pool memory has another layout, so its atomics went to a scratch buffer that nothing read, and a pointer shorter than the image (or an invalid coordinate) wrote over other GPU memory. For a 3D image SPIRV-Cross indexes the pointer with theint3coordinate itself. - Fix: image atomics are Metal's native texture atomics (MSL 3.1:
texture3d<uint, access::read_write>::atomic_fetch_max).dmsh_atomic.pyhas SPIRV-Cross write shaders with image atomics (anOpImageTexelPointer) at MSL 3.1, and every other shader at MSL 2.3 as before, so their MSL is unchanged and their libraries come from the compile cache; a shader whose MSL still has the pointer form fails the build. The atomics act on the texture every other access of the image uses (a buffer image's view of its pool, a linear image's pool memory, a block-linear image's Metal texture), for buffer, 2D, 2D-array and 3D images. Metal runs texture atomics only on an R32Uint / R32Sint texture made withMTLTextureUsageShaderAtomic: NVN images of those formats take that usage when they are made (nvn_mtl.mimg_usage; a view keeps working through its base), the build marks the slots a shader uses atomically ("atomic"in the reflection,nvn_rbind.atom), and the host binds an atomic-capable write sink, logged red, in place of any other texture there (dummy_img_atomic). The translator's coordinate guard stays (Bounds of image atomics). - Found on: Octopath Traveler 0: 2,084 shaders with atomics on buffer images (Unreal's GPU particles; three ran in the first 100 seconds) and 16 on a 3D image. Pokémon Legends: Z-A: an atomic max into a 480x270 r32ui block-linear 2D array (fragment shader
2bd5037003980716, the scene after the story opening's first cutscene), which ran about 1.4 MB past the 64 KB dummy buffer into zero-copy pools over the game's heap and into unmapped addresses (GitHub issue #101), then went to a scratch buffer. FINAL FANTASY RESONANCE (8 shaders) and Ghost Trick (5, one of them a compare-and-swap): atomics on 3D images. - Check:
dm/tools/tests/test_image_atomic_bounds.pywith the rebuilt translator,DMSH_TEST_METAL=1 DMSH_TEST_GPU=1: synthetic Maxwell atomics on buffer, 2D, 2D-array and 3D images, compare-and-swaps among them, run on native atomic textures of a Mac GPU under the Metal validation layer (t_atomic_return.m).t_refl.mchecks the atomic flag of a reflected image.
Buffer image reflection keeps its texture type
- Symptom:
image atomics: unsupported or overflowing IMG extentat the first dispatch, despite a valid four-byte counter buffer. - Cause:
nvn_refl.mclassifiedtexture_buffer<uint>as the default 2D texture. The atomic admission check of the pointer emulation then rejected the actual Metal buffer texture against that 2D descriptor. - Fix: the shared reflection type decoder recognizes
texture_bufferasMTLTextureTypeTextureBuffer, so a buffer image keeps its buffer-image shape.t_refl.mchecks the reflection converter with a buffer image. - Found on: SHIN MEGAMI TENSEI V: Vengeance, compute shader
2d2093c1f1d3a7e0, image slot 2 (one R32Uint texel).
Image atomics on a 32-bit colour texture
- Symptom:
[RED] image atomics on a texture Metal cannot run them on, and whatever the shader computes through them is lost: its writes go to a sink. - Cause: Metal runs texture atomics only on R32Uint and R32Sint textures and views. NVN lets a shader run them through an R32 view of any 32-bit colour texture: agl's anti-aliasing (
d17eefaff4f0bc23) ORs its blend weights into RGBA8 that way, then reads it as RGBA8. - Fix:
nvn_mtl.mtex_upgrade,tex_atomic_alias: at the first such dispatch the texture moves to R32 storage holding the same bytes, and its own format becomes a view of that storage for sampling, rendering and copies. Packaged, multisampled, 3D and buffer-backed textures keep their storage. The design is PR 1312's. - Check:
make -C dm/gfx/tests GAME=0400486024DEC000 check_t_image_alias. - Found on: The Legend of Zelda: Ocarina of Time.
Bounds of image atomics
- Symptom: Metal shader validation reports invalid image-atomic stores even with an image-sized scratch buffer; without validation, GPU page faults can freeze rendering.
- Cause: the translator lost the surface instruction's
IGNbounds mode before lowering an image atomic, so a coordinate outside the image reached memory. Neither a pointer nor a native texture atomic outside its image is defined on Metal. - Fix: the translator (
TranslationFlags.MetalImageAtomics, Metal only; other backends keep their behaviour) keeps the bounds mode and whether the result is used, queries the bound image's size and tests every original coordinate, the layer included, before the atomic. Negative coordinates fail an unsigned comparison; coordinates are not clamped or flattened. Invalid coordinates leave memory unchanged and return zero (ARB_shader_image_load_store, issue 30): a returningIGNatomic joins the old texel from the valid branch and zero from the other with an SPIR-V phi. A compare-and-swap (SUATOM.CAS: compare with Rb, swap in Rb+1) is Metal's texture compare-exchange behind the same guard; SPIRV-Cross loopsatomic_compare_exchange_weakuntil it succeeds or the texel differs. Predicate-returning,TRAPand unknown modes fail translation, as do 64-bit, floating-point and half2 sources (checked before the descriptor format can erase their size), descriptors that are not R32 integers, bindless handles that do not resolve statically, and indexed or multisample images. Source 1D and 1D-array surfaces keep the translator's one-row normalization to 2D. - Found on: Pokémon Legends: Z-A (PR #178); SHIN MEGAMI TENSEI V: Vengeance, whose two buffer-image counter shaders dispatched at boot consume their returned values.
- Check:
dm/tools/tests/test_image_atomic_bounds.py. Portable tests check the MSL version choice and the rejection of the pointer form. WithDMSH_TEST_XLATEset to a rebuilt translator (andspirv-valonPATH; spirv-cross is the in-repo build) the synthetic shaders are translated, the guard's dataflow is checked in the SPIR-V (the size query and comparison dominate the atomic, the phi carries zero on the invalid edge), and the MSL is produced;DMSH_TEST_METAL=1compiles and links it (DMSH_TEST_METAL_SDKS=macosx,iphoneosfor both SDKs) andDMSH_TEST_GPU=1runs the returning fixtures (above). Changing this path changes the chain version: rebuild the translator and update the lock before building shaders.
64-bit image max and min (SURED.MAX.U64)
- Symptom:
NotSupportedException: Ampere 59f at …: SURED form 0110e400in the shader build, then the scene's 3D picture black behind a UI that draws:[RED] shader … (compute) failed to loadand[RED] the dispatched program has no compute shader. A texture dump shows the visibility target (RG32Uint) all zero. - Cause: a visibility buffer written by compute rasterization keeps, per pixel, the nearest primitive as one 64-bit value, depth in the high word and the primitive id in the low word, through SURED.D.2D.MAX.U64 on an RG32UI image. The decoder took only the 32-bit sizes, and Metal's texture atomics were bound only on R32 textures. SPIRV-Cross has no 64-bit atomics at all.
- Fix:
ASuredsends the U64 form toEmitSuatom, which allows only a 2D, 2D-array or 3D max or min with no result (Metal has no 64-bit texture add, fetch or bitwise atomic).GenerateImageAtomicwrites it as two 32-bit atomics of the same operation on the same texel, low word then high word, a marker that never runs.dmsh_atomic.wide_atomicsturns each pair into onetexture2d<ulong, access::read_write>::atomic_max/atomic_min(MSL 3.1) and fails the shader on any other access of that image. The host makes RG32Uint images with the shader-atomic usage on Apple GPU family 9, M3 / A17 Pro and later (pf_atomic), and the reflection marks such a bindingatom2. Older GPUs have no 64-bit texture atomic, and those pipelines do not build there. Ported from uncraftablexd's PRAGMATA bring-up (PR #1801). - Found on: PRAGMATA: 336 compute shaders, among them
26166d37ed56d6bband3bc957e2739551e7, dispatched at the title. - Check:
DMSH_TEST_XLATE=<translator> python3 dm/gfx/tests/test_dmsh_ampere_mem.py Sured64 WideAtomics;test_image_atomic_bounds.py(the source-size gate).
Reads past a uniform binding's size
-
Symptom: the GPU hangs (Metal command-buffer timeouts,
GPU access revoked, exit 70; on the Mac WindowServer can lose its watchdog check-in and the session restarts) or a draw reads garbage, where a shader reads a uniform slot further than the game bound it. No[RED]line. -
Cause: Maxwell bounds every constant buffer read by the size the game bound (
nvnCommandBufferBindUniformBuffer): past it a read gives 0, and games rely on that. The translator declared each slot asfloat4 _m0[4096]behind a plain pointer, and Metal has no bounds of its own, so such a read reached the guest memory after the binding. Paper Mario: The Thousand-Year Door'sforward.bfshavariantf1e0f08cc43e21e3reads its light count at byte 0x900 of uniform slot 11 and loops over that many lights, filling a 19-entry local array and reading c14 at0x440 + 0x30 i; the game binds 2,384 bytes to the slot for some materials and 16 bytes for others (501 of 1,024 bindings sampled in Peach's invisibility-potion scene). On the 16-byte bindings the count was whatever lay past them. -
Fix: in the chain and the host, for every game (
TranslationFlags.MetalUniformBounds, Metal only), in two parts, since a slot's bound size is one value for a draw:- Reads at fixed offsets, in the host, once a binding. The translator leaves such a read as it is and reports how far they go in each game uniform slot (c[3] to c[16]): the bytes from the slot's start to the end of the highest word read so (
ResourceManager.NoteUniformRead,BufferDescriptor.FixedSize,fixedin the translator's report and in the reflection'scbufbinding,nvn_rbind.fixw). When the game binds a slot shorter than that, the argument-buffer encode copies the binding into an arena block with zeros up to there and points the slot at it (ub_paddedinnvn_mtl.m; the bytes are the ones the slot would have pointed at, the deferred updates' or a partly updated block's copy included), and logs the first such shaders with a running count (uniform slot N of shader K (stage S) is bound with B bytes and read up to byte E at fixed offsets). Every other binding costs one comparison on the CPU. The code generator refuses a fixed read past the reported extent, so the two cannot disagree silently. - Reads at computed offsets, in the shader. The word's index is compared with the slot's size in words; out of bounds the read goes to row 0 and gives 0, so it reaches no memory past the binding (
TryGenerateBoundedUniformLoadinCodeGen/Spirv/Instructions.cs). The sizes come from a table in a bank of its own,DMSH_CBSIZE_BANK(25), a u32 for each of the 14 slots in fouruint4(binding kindcbsize,NVN_RB_CBSIZE), which the host fills from the current bindings at each argument-buffer encode, 0 for an unbound slot (whose reads already go to the zero bank), at most 64 KiB. Only a shader with such a read declares the table.
The size that bounds a slot is the bound size rounded up to 256 bytes (
ub_boundinnvn_mtl.m), which is what the console's driver gives the GPU:nvnCommandBufferBindUniformBufferwrites(size + 0xff) & ~0xffin NVN1's driver (method 0x8e0; Sonic Superstars'sdk, 0x467170) and((size + 0xff) >> 8) << 20in NVN2's (method 0xe02; Ocarina of Time'ssdk, 0x67bc80). A read between the bound size and the next multiple of 256 gives the memory there, so the padded copy carries those bytes (where the pool reaches that far) and the size table holds the rounded size. The host used the exact size until GitHub issue #2218; Ocarina of Time binds 16, 64, 144, 192, 464, 976, 16,960 and 41,600 bytes. Open: what an Ampere GPU returns past the rounded size is not measured (Maxwell gives 0), and whether this is what streaked Ocarina's animated models is not shown: the streaks did not appear on an M-series Mac here with the exact size either (the slingshot aimed at Link's house, the ReDeads of Castle Town).The driver segments (c0, c2), the shader's own c1, NVN2's push constants (c[24]) and compute's uniform pointers (
ubo_ptr, global memory on Maxwell too) are not bounded. The host takes a uniform word for its own proofs only from inside the binding (ubo_floatrefuses a word past the size). - Reads at fixed offsets, in the host, once a binding. The translator leaves such a read as it is and reports how far they go in each game uniform slot (c[3] to c[16]): the bytes from the slot's start to the end of the highest word read so (
-
History: the first form (chain
3510ea767778) compared every read in the shader, fixed offsets too ((576u < (sizes[2].w >> 2u)) ? c14[144].x : 0.0). spirv-cross wrote each as a conditional expression, a branch for every read, until they were written as selects (chaineaa843a79149). The branch form cost little where shaders read few uniform words (NieR:Automata's opening flight, GPU p50 +1.6%) and a fifth of the GPU's time in Donkey Kong Bananza, whose material shaders read many: 14.6 → 17.5-18.1 ms a frame on the Freezer Layer on an M4, which took the game from 55 to 30 fps (GitHub issue #2066, the reporter's measurement on their own build). Of the 8.3 million uniform reads in its 23,638 shaders, 95.5% are at fixed offsets, and 73% of the shaders have no other kind. -
Found on: Paper Mario: The Thousand-Year Door (GitHub issue #1860): the reporter found the variant and the short bindings, and padding those bindings with zeros let Peach's scene through on an M3 Ultra Mac and an M4 iPad Pro. Donkey Kong Bananza (GitHub issue #2066): the cost of comparing every read.
-
Check:
dm/tools/tests/test_dmsh_abi.pytest_uniform_bounds_agree(the translator's bank and slots are the header's);dm/gfx/tests/test_dmsh_ampere_mem.pytest_fixed_uniform_reads_are_bare_and_counted(withDMSH_TEST_XLATE: two fixed reads of c[3] give no size table andfixed28). On NieR:Automata's 1,225 shaders built with this change: all 148,022 reads at fixed offsets are bare, all 28,604 at computed offsets are compared (andselect_guardswrites each of them as a select, none refused), 455 shaders declare the size table, and each slot'sfixedends in the highest row its source reads at a constant index. Not run in a game yet (open): the host's padding has met no short binding, the potion scene's retest by the reporter of #1860 is open, and so is Bananza's frame time on the Freezer Layer. The first form's numbers,bench.pyon NieR:Automata's opening flight (M6, two runs each, 60 s window): GPU time p50 6.43 → 6.53 ms (+1.6%), p95 9.12 → 9.70 ms (+6.4%), frame time unchanged at 60 fps. Changing this path changes the chain version: rebuild the translator, update the lock and rebuild the shaders. -
Computed row bounds: the translator compares an unsigned row index to the size table's byte count divided by 16 when it can prove the component is in 0–3. The host's size entries are multiples of 16. Comparing the row directly avoids a left shift that could discard the high bits, and the MSL rewriter keeps the load and select. Fixed-offset reads still use the reflected extent. In the author's Mario Kart World docked race (M3 Max, uncapped), the original row optimization reduced scene pass time from 2.43 to 2.34 ms and 2.42 to 2.23 ms in the two run orders. The translator implementation is common to every profile.
Bounded uniform reads written as select
- Symptom: on an M1 Pro (macOS 26), blue, green and white blocks for one or two frames on trees that dither-fade (OCTOPATH TRAVELER's S'warkii, walking behind a tree); a texture dump shows NaN pixels in the scene colour and holes in the normal G-buffer target, which depth of field spreads into blocks. Not seen on an iPhone or on newer Macs. On every GPU, a branch for each uniform word a shader reads.
- Cause: the translator's bounded read (Reads past a uniform binding's size) is a load and a choice, OpLoad then OpSelect, but spirv-cross writes OpSelect on a scalar as a conditional expression and forwards the load into it:
cond ? read : 0.0, which reads only when the condition holds. Metal's compiler makes a branch, a load inside it and a phi of each (its LLVM IR at -O1 and -O2,xcrun metal -S -emit-llvm), whereselect(0.0, read, cond)is one load and a select with no branch. The M1's compiler gets that form wrong in OCTOPATH TRAVELER's tree material (pixel shader040208cd98c2ac2f): its volumetric lightmap word (G-buffer target 5) comes out wrong although every guard is true (all its bindings are full size, and a size table of 64 KiB for every slot changes nothing), and the lighting turns it into NaN. The same shader at -O0, without the guards, or with them asselectis right;-fno-fast-mathdoes not help; only removing the guards of the whole lightmap block (c3[174..177]) fixes it, not either half. Found by bisecting to26062f9e(5 against 0 of 96 shots), then the shaders, then the guards inside the one shader. Open: which step of Apple's compiler fails is not known, nor whether it is the Metal front end of macOS 26, which built those libraries, or the M1's GPU compiler: a platform fault that the select form avoids and does not fix. - Fix: every game, a chain change.
dmsh_rewrite.select_guards, called bydmsh_build.pyon each spirv-cross output (the shader, the geometry stage and its reader), writes every bounded read asselect(0, read, cond), the translator's own meaning. Since GitHub issue #2066 only reads at computed offsets are bounded in the shader (the fixed-offset reads this was found on are plain loads again, the ones Metal made before reads were bounded; the host bounds them). At a computed offset the index already chooses row 0 when out of bounds (bool _5 = word < size; select(0.0, c14[_5 ? _3 : 0][_4], _5)), so the load stays inside the binding without the branch. A bounded read it cannot write as a select fails the shader (uniform bounds rewrite failed), so a change in what spirv-cross writes cannot bring the branches back unseen. - Found on: OCTOPATH TRAVELER (GitHub PR #2127: the bisection, the shader and the select form, on an M1 Pro).
- Check:
python3 dm/gfx/tests/test_dmsh_fetch.py UniformBounds(the forms spirv-cross writes at a computed offset, the error for an unknown form or a fixed offset compared in the shader). On the M1 Pro, the dog route in S'warkii (walking up and down behind the tree left of the dog by the weapon shop): 5 to 14 of 96 shots with blocks before, 0 of 192 with the fixed-offset reads as selects; not run there with those reads plain (open: the author's retest).
Reads past a storage buffer bound by address
- Symptom: a shader reads another resource's bytes where it indexes a storage buffer past the memory the game mapped there. No
[RED]line. PRAGMATA's R53 hangar (after the tram ride, "Contact Earth from the Comms Tower") washes out in pink, green and white as you enter and on the stairs up to the upper deck, and it fades when the camera stays still; on the console the hangar is dark blue-grey. - Cause: a storage buffer whose address the shader takes from a game uniform slot (
sbuf_ubo,NVN_RB_SBUFU), the push constants (sbuf_push,NVN_RB_SBUFQ), or NVN's ownc[0]table (sbuf,NVN_RB_SBUFP;ubo_ptr,NVN_RB_UBOP) is read through a raw GPU address on hardware. On the console the shader reads the GPU's page table as far as it indexes from the address: the pages mapped there, and 0 for an unmapped page of a sparse pool, where a write is dropped. The host binds the Metal buffer that holds the address (mtl_gpu_addr): a memory pool, a large pool's chunk, or a sparse pool's mapped run. Metal has no bounds of its own, so a read past that buffer reached whatever lay after it in the GPU's address space or faulted on an unmapped page. PRAGMATA's GI voxeliseref4ad01151918469read 0x150000 bytes and more through anSBUFU(cp_s3) at the base of a 1 GB sparse pool with one 0xc0000-byte run mapped there (washing the R53 hangar in hot surfel colours); Immortals Fenyx Rising boundc[0]storage buffers (NVN_RB_SBUFP, e.g. a 512 MB UI table at the start of a 144 MB sparse pool and 16–64 MB compute bindings) whose declared sizes exceeded the mapped run and whose compute shaders read past it into GPU faults. - Fix: in the chain and the host, for every game (
TranslationFlags.MetalStorageBounds, Metal only). Each access to a storage buffer (includingc[0]NVN_RB_SBUFP/NVN_RB_UBOP, excluding the raw global memory pool table) compares its word index with the memory the host bound there,idx + before < totalas one unsigned comparison that bounds both ends (TryGetBoundedStoragePointerinCodeGen/Spirv/Instructions.cs). Out of bounds, a load reads word 0 and gives 0, written as a select (dmsh_rewrite.select_guards, as for uniform reads), and a store or an atomic is skipped (an atomic gives 0). The two words come from a table in a bank of its own,DMSH_SBLEN_BANK(27): two u32 for each storage slot, binding kindsblen(NVN_RB_SBLEN), the slot in the reflection'ssbx. The host fills the table as it encodes each binding (sblen_putinnvn_mtl.m): the words of the buffer before the address, then that plus the words from the address to the buffer's end, or 0 for the dummy; forNVN_RB_SBUFP/NVN_RB_UBOP, whenmtl_gpu_addr(addr, size)fails becausesizeextends past the mapped buffer, it falls back tomtl_gpu_addr(addr, 1)and bounds accesses throughsblen_putrather than falling back to a dummy or widening into arbitrary host memory.wide_loadsreads a run of bounded words whole when its first and last words are inside, and word by word otherwise;first_storeandfloat_add_mslmatch both plain and bounded forms (keeping Ocarina of Time's nativeatomic_fetch_add_explicitonRED.F32and Splatoon Raiders' hoisted first-invocation stores).args_cbuf_onlystill patches shaders withSBUFP+SBLENwhen onlyCBUFbindings change. - Not taken: a tail of zero pages past the last mapped run (PR #2626), and widening
NVN_RB_SBUFPwithmach_vm_regionzero-copyMTLBufferwrappers over arbitrary readable host memory (PR #3126, which leaked up to 64 buffers and returned garbage host memory instead of zeros). - Open: a read past the run that would reach a later mapped run after a hole reads 0 here, where the console reads that run (spans over holes are PR #2509). A read more than 64 MB past the address in a large pool reads 0, past the chunk the lookup makes (
BIG_UNKNOWN). Not run in a game here: the PRAGMATA build folder is gone and there is no save near the hangar, and Immortals Fenyx Rising is not installed locally. The cost is estimated, not measured: one comparison and one select per storage load, and a branch per storage store or atomic. - Found on: PRAGMATA (GitHub issue #2618), extended to
c[0]storage buffers from Immortals Fenyx Rising (PR #3126). - Check:
t_storage_bounds(26 checks, under Metal validation),test_dmsh_storage_bounds.py(withDMSH_TEST_XLATE:SBUFU,SBUFQ, andc[0]SBUFPloads, stores, atomics, and reflection),test_dmsh_first_store.py,test_dmsh_float_add.py,test_dmsh_ampere_alu.pyFloatRed,test_dmsh_fetch.pyUniformBounds, andtest_dmsh_wide.py.
Shaders compiled at run time
A GLSL language preamble is not a complete shader
- Symptom: the NSP script stops with
captured only 0 run-time shadersalthough the game reaches its frame loop with precompiled shaders. - Cause: the detection counted every
#versionoccurrence. Snowdrop carries a GLSL header containing extensions and type macros, without an entry point; importingglslcCompilealongside it does not establish a boot shader compilation. - Fix:
profile_guess.pycounts embedded source strings containing both#versionandvoid main(...)before their terminating NUL. The survey, build and split share that detector. Three Houses still has its nine complete boot sources; NRO imports retain their separate capture rule. - Found on: Mario + Rabbids Kingdom Battle, whose only
#versionstring is the 646-byte language preamble also carried by Sparks of Hope.
Built-in shaders compiled with the game's own GLSLC
- Symptom: shaders missing from the map that no game file holds.
- Cause: a game whose shaders come from its own GLSLC at boot has no file holding their output. KTGL compiles 9 built-in GLSL shaders at boot with the game's own GLSLC (
glslcCompilefrommain+0x9c89f8; the sources are strings inmain). - Fix: they are captured once on the Mac (
DM_GLSLC_CAPTURE):DM_GLSLC_CAPTURE=<dir>saves every compile's output (hle_glslc.c; the compile object's first word points at {status, output}), andshader_split.pyreads<version dir>/glslc_capture(the NSP script makes it for any game whosemainimportsglslcCompileand holds GLSL sources or, with none there, whose RomFS holds.vert/.fragfiles). The outputs are identical on every run.shader_split.pyasks for captured GLSLC outputs only when a module of the profile's definesglslcCompile, asprofile_guess.pydoes. - Found on:
- Fire Emblem: Three Houses (SDK 6.5.0): the 2D primitive, text and loading-feather shaders.
- Catherine: Full Body (SDK 8.2.1): its two built-in programs are captured on the Mac the same way; they compile only once the host reports the GLSLC's GPU code version (next entry).
- The Legend of Zelda: Link's Awakening:
subsdk0is NVN's runtime GLSL compiler andmainimportsglslcCompile*, but up to the house, the beach and the menus every shader the game loaded was in the offline tables. - Captain Toad: Treasure Tracker (the rule that a module must define
glslcCompile):mainimportsglslcCompileand holds agl's GLSL sources, but no module defines it, so nothing is compiled at run time.
A run-time compile that waits for a button press
- Symptom: the NSP script stops with
captured only 0 run-time shaderswhile the capture run reaches the game's frame loop and runs to the end of its 30 s. - Cause: the game compiles its run-time programs only after its title screen has had a button press, and the capture run had no input: 0 outputs in 200 s without a press, both of them 3 s after the first A.
- Fix: the capture run presses A every 4 s from 5 s on (
GLSLC_KEYSinbuild_ipa_from_nsp.py, throughDM_KEYS). The run keeps its own save and temporary storage, so whatever the presses choose is thrown away with them; a game that compiles at boot (Three Houses) is done before the first press. - Found on: Crash Team Racing Nitro-Fueled (
0100F9F00C696000, update 1.0.15, no profile yet): both outputs within the 30 s run.
Shaders compiled after boot
- Symptom: a scene is missing geometry and logs
[RED] shader … is not in the shader mapwhen it first uses a material. - Cause: a miss in the game's own shader cache can make the game compile with
glslcCompilelong after the packer's boot capture ends. The compile produces Switch GPU code. A host with only the packaged Metal libraries skips any stage whose key is absent. - Fix in testing: the Mac host can translate missing NVN1 vertex and pixel stages from the code and control bytes supplied to
nvnProgramSetShaders.--platform mac --nvn-runtimeuses the packer's translator and Xcode tools. The first use waits for translation. Files are cached underDM_TEMP/nvn-shadersby shader, chain, and profile inputs. Translation currently works stage by stage. Linking pairs that need extra vertex outputs remains open. - Mac app in testing:
--platform mac-app --nvn-runtime-python DIRbundles a relocatable Python installation and the shader translators. The Metal API compiles translated source without Xcode. Catherine's Night 2 save passed with an empty shader cache after fixing CPU staging recycled before a texture upload. iOS has no runtime translator yet. - Offline workaround for builds without the runtime compiler: run the game with
DM_GLSLC_CAPTUREset to a separate capture folder. Rebuild the same version with--glslc-play DIR. The splitter adds new keys and their program pairs after the game, boot and DLC sources. The packer uses a shader-only derived profile and keeps the registered module fixes. - Found on: Catherine: Full Body.
Offline coverage after an empty GLSLC capture
- Symptom: The Mac capture boot submits shader programs but writes no GLSLC capture files.
- Cause: The source/import heuristic finds a compiler that the game can call. A cache hit lets the game submit a precompiled output without calling it.
- Fix: If the profile requires no capture files, use an empty shader map for the capture boot to observe submitted shader keys. An empty capture can continue only after the offline split supplies every observed key. A stopped host, failed capture, missing key or no observations fails the check. This verifies coverage of the observed boot.
- Found on: Alien: Isolation (SDK 8.2.0).
GLSLC GPU code version against the driver's range
- Symptom: a null read at
main+0x3316dcinnnMain, right after the window setup (the program object's interface pointers at +0xd0 / +0xd8 both null). - Cause: the game compiles two built-in programs at boot with its own GLSLC (
subsdk0, the same build as Link's Awakening's), and first checks that GLSLC's GPU code version againstnvnDeviceGetIntegeritems 0x2E–0x31 (the driver's supported range,main+0x330dcc). The host reported Super Mario Odyssey's SDK 7 driver range, 1.5–1.14; this GLSLC writes 1.15, so nothing was compiled and the first uniform lookup read the empty program. - Fix: every SDK's driver runs the code of the GLSLC in the same SDK, so the host now reports at least the version the game's own
glslcGetVersionreturns (hle_glslc.cdm_glslc_gpu_code,hle_nvn.c). The host also advertises the translator's supported range for precompiled shaders (Newest GPU code version reported by the driver). - Found on: Catherine: Full Body (SDK 8.2.1, Atlus's GFD engine, CRI middleware; one boot).
GLSL ES 1.00 sources without a #version line
- Symptom:
gl_shaders.pyfailed on the captured sources:ES shaders for SPIR-V require version 310 or higher. - Cause: GameMaker's runner writes each shader variant as GLSL ES 1.00 with the version statement left out (
attribute,varying,texture2D,gl_FragColor,precision mediump float;), and usessampleas a variable name, a reserved word since ES 3.00. - Fix:
gl_shaders.py'ses100()pass, run when the source has no#versionline or says#version 100(that line is dropped): dropprecision <p> <t>;lines (the pattern has to accept\r, the captured files mix CRLF and LF), striplowp/mediump/highp(GameMaker has#define LOWPREC lowp, so a macro would otherwise expand to nothing useful), renameattribute→in,varying→out(vertex) /in(fragment), declareout vec4 gm_FragColor;and renamegl_FragColor, renamesample→gm_sample, then prepend#version 310 eswithprecision highp float; precision highp int;. Texture functions stay with the existingfixups()so the rename happens afterglslangValidator -Eand a macro cannot hide one. - Found on: Well Dweller (93 run-time shaders; see its
gl_capture.tsv).
Struct uniforms become member rows
- Symptom:
uniform LightEnv { … };failed withuniform u_LightEnv: type LightEnv (structs are not implemented), so every program that used one was missing from the library. - Cause: GameMaker declares several uniform blocks as struct uniforms, and the layer's
glGetUniformLocationcompares the name the game asks for (minus a[n]suffix) against the table's rows, whose name field is 48 bytes — the game asks foru_LightEnv.m_dirLights_dirand similar dotted member names. - Fix:
gl_shaders.pygaineduni_members(), which walks a struct type's members and emits one row per member with the dotted name (u:u_LightEnv.m_dirLights_dir[0]), adding each member's offset to its parent's (the reflection gives a nested member's offset relative to its parent); arrays of structs return an error. - Found on: Well Dweller, whose lighting programs were the missing ones.
Pipelines and caches
A compile that does not return stalls every flush and draw
- Symptom: the pipeline prebuild stops at the same line on every start (
pipeline prebuild: 7000 of 20740 pairs, 1987 built, 5013 already archived, 0 left to the draws, 0 failed), behind Preparing pipelines or, withDM_PSO_PREPARE=0, as a black screen while the sound plays on; the NSP script's[7/7] Pipeline prebuilddoes not end (dmhostat 0% CPU,MTLCompilerServiceat 100%), andMTLCompilerServicecrash reports (EXC_CRASH,llvm::report_bad_alloc_error) come every 6 to 10 minutes. The bases built since the last file are never written, so the next start builds them again and stops at the same pair. - Cause: one base Apple's GPU compiler cannot build, and a host lock that let its compile hold everything else. The compiler grows
MTLCompilerServicepast several GB until it aborts inllvm::report_bad_alloc_error, and Metal hands the request to the relaunched service; only after four aborts (33.7 minutes on an M6 with 16 GB, macOS 27.0) doesnewRenderPipelineStateWithDescriptorreturn, withCompilation failed due to an interrupted connection: XPC_ERROR_CONNECTION_INTERRUPTED. This error occurred after multiple retries.Metal's serializer cannot be written while it captures: the write (-[_MTLBinaryArchive airntSerializeToURL:options:error:]) runs on the archive's_serializeQueueand then empties the archive (its entries, AIR objects, library cache and file mapping) on its_queue, while each function a compile captures adds itself from the compile's completion (__122-[MTLCompiler compileFunctionRequestInternal:…]_block_invoke: a newMTLBinaryEntryfrom the request's AIR script and the function's bitcode, mapped bynewArchiverIdWithBinaryKeybefore it takes_queue, then added under it, before the compile reports back). A compile under way across a write came back with both nil and crashed indispatch_data_create_map(seen in lldb at the crash, the write's thread waiting for_serializeQueue). So every compile the archive captured held a read lock (g_arch_rw) and a flush its write lock. The flush at the next 1,000 bases waited behind the compile, and every other compile, draw and the present path waited behind the flush. The prepare step also waited for the last compile to return. - Fix: flush periods (
ArchEpochinnvn_mtl.m). Each period has its own compiler and serializer; a compile the archive captures joins the current period (arch_capture) and leaves it when it returns. A flush (arch_flush) gives the compiles after it a new period and returns at once; the old period's serializer is written (arch_write, on the archive queue) once every compile in it has returned. No compile waits for a flush, and a compile that does not return holds back only its own period's file. The prebuild's flushes every 1,000 bases no longer wait; its last one (arch_flush_wait) waits for every period beforeprebuilt.tsvis written. Specializations go through a compiler without a serializer (g_comp4). The prepare step waits until every pair is handed to a worker; compiles still under way then (at most one per worker) finish in the background, and the log sayspipeline prepare: every shader pair handed out after … s; N compiles still under way finish in the background. The prebuild tool still waits for every compile, since it writes them all. The base itself was made buildable by Front end at -O1 (11.4 s at run time on the same M6). A base that fails no longer keepsprebuilt.tsvfrom being written (every start compiled it again in the background, half an hour at-O2): the pair goes intopso_archive/prebuild_failed.tsvwith the system build and the stamp it failed under (pre_fail_load), and a later start of that system build with that stamp leaves it to the draws without compiling it; another system build (a new GPU compiler) or stamp tries it again. A failure Metal reports has already been retried by Metal itself. The log sayspipeline prebuild: N pairs whose base failed are left to the draws (…prebuild_failed.tsv; M of them failed on an earlier start of this system build, not built again). Open: a compile still under way when the game exits leaves no result, so a base that takes longer than a session to fail is compiled again in the background on the next start. - Found on: Super Mario Odyssey, update 1.4.1, GitHub issue #294: the base of pair 5641,
3c3435a62e05975b+007d7e411ef14ebd(alRenderMaterialUber.bfshavariation 0, 444,013 lines of MSL), found by a reporter's bisect of the pair list withDM_PSO_PREBUILD=tool, with that chain's-O2front end. On an M6 with 16 GB (macOS 27.0), the prebuild tool on the whole list with the-O2library and 8 workers: the old host stopped at 7,000 of 20,740 at 65 s and wrote nothing more in 5 minutes; with flush periods 20,000 pairs were done at 262 s, and 17 files held 18,739 of the other 20,739 bases, only the 2,000 in that compile's period waiting for it (three compiler aborts in 40 minutes). With the-O1library (all 20,740 built): 253 s cold and 227 s with the old host, 213 and 225 s with flush periods; the files written gave all 20,740 back, none compiled. - Check:
t_pso_stall: a compiler that holds one prebuild compile; while it is held, the prebuild hands out every pair and builds the others, a draw's compile returns and a later period's flush writes its file, and a base of a written period still specializes; once released, its period is written and the prebuild stamps. A pair whose compile fails: stamped all the same and listed; not compiled again on a later start of the same system build, also without the stamp; tried again with a list from another system build, and the list removed once it builds. On Odyssey's pair 5641 alone with the-O2library (M6, macOS 27.0): Metal's error after 36.6 minutes, the pair listed and the stamp written; the next start had nothing to do (1 s), and one withoutprebuilt.tsvleft the pair to the draws without compiling it. The Metal behaviour, by a probe outside the tree on an M6 (macOS 27.0), eight threads compiling 1,500 pipelines: one serializer written every 150 ms while they compile crashed 3 runs of 3 innewArchiverIdWithBinaryKey; a write that first waits for the compiles under way but lets new ones start, 6 of 6; one that lets no compile start until it is done, 1 run of 111, during the write itself, with issue #342's signature (dispatch_retain(NULL)inmaterializeAirNTFromOnlineForSlice); a compiler and serializer per period, none of 118, every pipeline found in the files, also with 121 periods in one run (no memory growth), and making a period took about 30 µs.
Shader-pair tables in a Mac app
- Symptom: a self-contained Mac app (
--platform mac-app) logspipeline prebuild: no .../Resources/dm/shader_pairs.tsv, nothing to buildalthough every shader library is there; it draws no hybrid stand-ins, and each pipeline seen for the first time compiles on the submit thread (frames of 100–550 ms). - Cause:
dm/mac/pack_app.pycopied the shader map, the prewarm manifest,c1_full.tsvandcb_extent.tsvbesideDM_NVN_SHMAP, but notshader_pairs.tsvandpso_pairs.tsv, whichbuild_ipa.shcopies into the IPA and the host's pipeline prebuild reads there (pso_prebuild). Without them the app makes no pulling bases. For a profile withoutpso_pairs.tsva Mac run (mac_run) passes the shader split's copy asDM_PSO_PAIRS; the app had neither. A full shader-library build does not build the pipeline bases by itself. - Fix: the packer copies both tables when the profile has them, and the split's
pso_pairs.tsv(--pso-pairs, which the NSP script passes) when the profile has none. They stay optional. An app packed before the fix needs repacking. An NVN game's app also carries its pipeline archive made offline for this Mac's GPU, so the first start builds no base: A Mac app. - Found on: The Legend of Zelda: Echoes of Wisdom, update 1.1.0: a 308.4 ms frame, 283.5 ms of it pipeline acquisition and 5.9 ms GPU work; with the tables the offline prebuild built all 7,495 bases. The Legend of Zelda: Breath of the Wild: frames of 100–546 ms before, none of its bases compiled on the first start after.
- Check:
test_nsp_mac_app:App.test_pipeline_pair_tables,App.test_split_pso_pairsandApp.test_layoutfail without the tables in the packer;Script.test_pack_commandchecks the split's copy is passed only when the profile has nopso_pairs.tsv.
Offline pipeline archive missing for the device GPU
- Symptom:
pipeline archive bundled with the app: none for this GPU (...): the device builds the bases itself although the app carries an offline archive. - Cause: each archive targets one GPU architecture. The iOS packers defaulted to
g18pfor profiles withpso_mtl4 on; another GPU family needed an explicit build override. - Fix: both packers also read the optional profile key
pso_gpubehind the existingpso_mtl4 ongate. It names the families to build for; explicit build overrides still win. Without the new key, opted-in profiles retaing18p; profiles with Metal 4 off retain no archive. See archive target selection. - Found on: Super Mario Bros. Wonder. Its note records the contributor's Mac build probe and the outstanding device checks.
- Check:
dm/tools/tests/test_game_profile.pyvalidates the key;dm/tools/tests/test_pso_offline.pyexercises both packers' selection and override precedence with synthetic profiles.
Offline pipeline archive reuse and fallback
- Symptom: a truncated
.mtl4areachesMTL4ArchiveImpl::loadFromURL; the bundle reports coverage with0 of 0 probed bases found; rebuilt shader libraries reuse an archive of their old binaries; or packing fails withpso_offline: no base to buildwhen every eligible pair has function constants, or when the profile'sshader_pairs.tsvholds only its header (--platform mac-app, GitHub issue #338). - Cause: the archive guard checked only four magic bytes; coverage accepted
found == probedeven when every sampled pair was ineligible; the offline cache key included library paths and profile stamps but omitted library bytes; and a zero-base plan aborted before writing its device remainder list, also when there was no pair at all, somac_pso()never reached its no-archive branch. - Fix:
arch_file_okchecks the GPU Mach-O load commands and payload ranges, universal slice bounds and the serializer's bundled Metal library ranges before opening the archive. It does not validate the compiler's private payload.pso_bundle_coversrequires at least one actual lookup and no misses.pso_offline.pyhashes every consumed library's bytes into the cache key; when all eligible pairs need device specialization, it removes old archives and writesrest_pairs.tsvwithout invokingmetal-tt. A pair list with no pair takes the same path (old archives removed, stamp written, exit 0), and the app is packed without an archive; pairs that the host would leave out entirely (wrong or missing libraries) still fail. - Found on: The Legend of Zelda: Breath of the Wild, during review of its offline archive path with synthetic libraries and pair lists; no new gameplay or iPhone run. The empty pair list on ANIMAL WELL.
- Check:
dm/tools/tests/test_pso_offline.pychanges vertex and fragment library bytes without changing entries or stamps, and exercises the all-constant plan, the header-only pair list and pairs all left out.t_pso_bundlerejects bare headers, truncated archives, malformed load commands and out-of-range universal slices, accepts real offline and serialized archives, and rejects zero-probe coverage.
A bundled pipeline archive read a page at a time when it opens
- Symptom: a gray screen for several seconds at startup, before the pipeline progress screen, on a Mac whose GPU has an archive in the app:
pipeline archive bundled with the app: .../pso/applegpu_g16s.mtl4a, 4405.6 MB, opened in 7978.8 ms. The same app starts fast on a Mac whose GPU has none, although that Mac's ownpso_archivefolder holds twice as much (38 files, 8,880 MB, about 1.4 s on an M1 Pro). - Cause: Metal's open (
MTL4ArchiveImpl::loadFromURL, macOS 27) makes a library of every Metal library in the file and hashes all of it with SHA-256 on the calling thread. It reads the whole__AIR_DATAsegment and__TEXT,__metallibsection of each GPU image, 2.9 GB of Ocarina of Time's 4.4 GB file (mincoreafter the open). It leaves the GPU code (__vertex,__fragment,__compute) for when a pipeline is taken. A file not in memory is mapped and read one page fault at a time, about 230 MB/s. The device's folder is opened file by file in parallel, so its faults overlap. The bundled archive is one file: 12.5 s cold and 1.5 s warm in a probe on an M4 Max. The bytes Metal reads, not an index, are the cost: the device files'.keysindex only speeds up lookups after the open. - Fix:
arch_open(nvn_mtl.m) first asks for the ranges Metal will read, 8 MB at a time on every core, from the load commandsarch_file_okalready checks: each piece is mapped on its own, givenMADV_WILLNEEDand unmapped, so the kernel reads it into the file cache that Metal's mapping shares. Metal then finds it in memory. It is used for every archive file the host opens: the bundled one, the bundle's prewarm files and the device's folder, inside the window that maps them (see A pipeline archive on an external drive is read into memory). The first version read each piece into an 8 MB heap buffer: as fast, butmallockept the freed buffers, +99 MB of footprint on a 12-core M6 after the open, and a warm open copied every byte again. One mapping of the whole file is ruled out because Metal maps the whole file too, and two of a 4.4 GB file do not fit an iPhone's address space;F_RDADVISEwas erratic (0.34–12.9 s cold for the same file). - Found on: Ocarina of Time (v131072), its Mac app on an M4 Max, macOS 27. The host's
pso_bundle_openon the bundled archive, each time a fresh APFS clone (a clone's pages are not in memory): 8.07 / 7.91 s → 1.61 / 1.52 s; warm 1.04–1.15 → 1.09–1.10 s. A device folder of 21 files (1,490 MB) throughpso4_init: 452 → 220 ms cold, 88 → 100 ms warm. In the game, headless boots of hostf4b7e77cwith and without the change (the app's chain), each on fresh clones of the bundle and of a 23-file device folder: the bundled archive 10.57 / 8.07 s → 1.63 / 1.53 s, the device folder 673 / 460 → 258 / 221 ms. Both sides found the same pipelines: 15 of 15 probed bases, 324 compute pipelines from the bundle, 164 mesh pipelines from the archive and 6,061 indexed pipelines. - Measured again on an M6 (macOS 27, 12 cores) after the rebase onto the mapped reader, a harness opening through the host's code inside its window, each cold run on a fresh APFS clone on an external drive: Divinity: Original Sin 2's bundled archive (373 MB, 231 MB read ahead) 0.99–1.58 s → 0.34 s cold, warm 92–97 → 99–103 ms; 16 of Ocarina of Time's device files opened in parallel (1.8 GB, 746 MB read ahead) 0.93–1.26 → 0.64–0.77 s cold, warm 81–82 → 91–98 ms. Footprint after the open the same on both sides (20 and 26–27 MB).
- Check:
t_pso_bundlechecks that the reads of an offline archive and of a serialized one are their records and libraries, less than the file, and that both open througharch_open.
Shader extraction reruns after translation-only updates
- Symptom: an unchanged NSP spends minutes in
shader splitafter a shader-chain update, on both Mac and iOS builds, although the extracted package is identical. - Cause: the split key included all graphics Python tools, every profile file and the whole decoder host executable. Translation tools, profile notes and the host's compiled
DMSH_CHAINlabel therefore invalidated extraction. - Fix: the NSP script follows the extractor's transitive repository Python imports and fingerprints its profile settings, manual facts, checked/generated tables, modules, RomFS/DLC identities and capture directories. A managed decoder host records its build inputs with only the chain label normalized, bound to its executable's bytes; unknown or replaced binaries use their binary identity. All other host build inputs and rewritten module contents still invalidate conservatively. Package and supplemental-pair digests reject damaged cached outputs. The common split serves Mac and iOS, while translation keeps its own target-specific keys. Existing split caches require one warm-up.
- Found on: Pokémon Legends: Z-A.
- Check:
test_nsp_incremental.pycovers translation-only hits, transitive readers, extraction settings, auxiliary modules, explicit captures, decoder changes, corrupt outputs and the existing registered/derived, DLC and damaged-input paths.test_host_msl.pyverifies executable-bound provenance, chain-only reuse and invalidation for decoder/profile/compiler/header changes.test_nsp_mac.pychecks separate Mac/iOS translation outputs.
Offline pipeline archive rebuilt after a chain-only update
- Symptom: rebuilding an unchanged NSP after a shader-chain update runs
metal-ttfor minutes even when all referenced Metal libraries and pipeline settings remain identical. - Cause: the offline archive key included the chain label, profile stamp, whole builder source and absolute library paths inside
b-<chain>. These can change without changing the compiler's inputs. - Fix:
pso_offline.pykeys each archive by the complete generated pipeline configuration with library locations normalized to their labels, every referenced library's name and bytes, GPU architecture, platform, minimum OS and Metal translator version. It still validates reflection against the current chain before planning. After a cache hit it writes the currentprebuilt.tsv, remainder list and archive metadata, so host validation remains current. macOS and iOS use the same builder with separate target keys. Legacy cache keys rebuild once; a changed shader, entry point, pipeline descriptor or compiler target still rebuilds the archive. The cache format has an explicit version for future changes not represented by these inputs. - Found on: Pokémon Legends: Z-A, while measuring repeat Mac app builds. Timings and platform-validation limits are in the game note.
- Check:
dm/tools/tests/test_pso_offline.pyexercises chain relocation and metadata refresh on both platforms, changed shader bytes and pipeline settings, target and compiler changes, missing archives, stale reflection and legacy keys.
Offline pipeline archive and profile depth disagree
- Symptom: the host logs
pipeline archive bundled with the app: made for ... this run needs ..., naming different depths, and pipeline bases compile during play despite a successful archive build. There need not be a[RED]line. - Cause: offline builds use the profile's
depth_mode(glwhen omitted), while runtime vertex entries follownvnDeviceSetDepthMode. An archive built withmain0cannot supply a near-zero base usingmain0_z. The runtime stamp comparison correctly rejects the mismatch; the missing input is in the profile. - Fix: declare the observed mode in the profile and rebuild the archive. Both vertex entries already exist, so this does not require a shader-chain change.
scripts/regress.pyrecords the runtime depth and compares it with the tested revision's profile on every NVN smoke run, including quick runs without an archive. It also records bundled archive stamp rejection for any chain, depth or pair-list mismatch. New mismatches fail the check; unchanged baseline mismatches are reported as known and prevent--recordfrom marking the game validated. An absent depth log is unknown, not evidence for GL. This detects mismatches on exercised routes; it does not infer unobserved games' modes or edit profiles automatically. For a new game the NSP script does: the heap and address region checks of a provisional or derived profile set the key from the game's ownnvnDeviceSetDepthModecall in their boot, before the shader steps (Super Mario RPG before this: a 24 minute prebuild at the default mode, then 0 of 34 archive lookups found). A game with no check boot, or one that stops before the call, keeps the default. - Found on: The Legend of Zelda: Echoes of Wisdom, update 1.1.0, GitHub issue #758: its note already recorded near-zero depth, but its profile omitted the key. The game note records archive validation and its limits; castle-entry performance remains open.
- Also confirmed: missing depth keys on SteamWorld Heist II, NieR:Automata, Portal, DRAGON QUEST III HD-2D Remake, Raging Loop, Subnautica, Subnautica: Below Zero, Batman: Arkham Knight, Blasphemous 2, EA SPORTS FC 27, Paper Mario: The Origami King and Super Smash Bros. Ultimate (13.0.5, a player's Mac app: its 1,316.9 MB archive refused, 31,148 pairs built before the first frame in 397 s). Recorded routes, short isolated boots and the NSP script's check boots select near-zero depth on their registered module builds; their notes record the evidence. The profile corrections have not been measured as rebuilt-archive performance fixes.
- Also found on: Cozy Land: the original profile omitted the key; its note records the corrected prebuild and runtime reuse.
- NX18 reproduced the archive rejection and found the startup probes passed after setting the key. Star Fox · Persona 5 Royal
- Check:
dm/tools/tests/test_pso_offline.pyruns the archive builder with the affected games' real profiles and synthetic libraries, checking the stamp and the vertex entry.dm/tools/tests/test_regress.pyreplays runtime depth and rejection logs through a smoke run, checking failure classification and reporting.
Offline pipeline archive made for another major version
- Symptom:
pipeline archive bundled with the app: this system cannot open …/applegpu_<gpu>.mtl4a (deployment target for architecture … found in archive … is not compatible with current OS …): the bases are built on the device. On macOS 26.6 with Xcode 27.1,t_pso_bundlefailed 10 checks, frombundle: openedon, and a Mac app packed there compiled every base on its first start, as without the archive. - Cause: a Metal 4 pipeline archive opens only on the major system version it was made for. Measured on macOS 27.2 (M4 Pro,
newArchiveWithURL:): archives thatmetal-ttmade with-macos-version-min26.0 or 26.6 were refused, from libraries built for 26.0 or 26.6 alike; those made for 27.0 and 27.2 opened.pso_offline.pytook the SDK's major version for every platform. That suits the iPhone, whose system is the SDK's, but the Mac app is built for the Mac that builds it, and Xcode 27.1's SDK is 27.0 on macOS 26.6. Also, the Mac host had no deployment target, so clang took the SDK's 27.0, andpack_app.pycopied it into the app'sLSMinimumSystemVersion.metal-ttalso refuses libraries built for a later system than the archive's (image AIR version (2.9) is bigger than the one of the target (2.8), macOS 27.0 libraries for a 26.6 archive); the chain's Mac libraries are built for the building Mac's system, so that Mac's major version is never below them. - Fix: for macOS,
pso_offline.py's default--os-minis this Mac's major version (sw_vers); iOS keeps the SDK's. The Mac host's minimum isMACOS_MINindm/mac/min_os.mk(26.6, as the README asks), on the host's compile lines (-mmacosx-version-min, libvpx's too), which the NSP script andpack_app.pyfollow. The host builds with the same warnings at 26.6 as at 27.0 (no unguarded newer API). An archive is still for one major version: an iPhone on iOS 26 cannot open the IPA's 27.0 archive and builds its bases itself (open: one archive per major version would serve both). - Found on: no game: GitHub issue #673,
t_pso_bundleon an M4 Pro with macOS 26.6.2 and Xcode 27.1. - Check:
dm/tools/tests/test_pso_offline.py(test_macos_takes_this_macs_major_version).t_pso_bundlebuilds its archive with the default and opens it on macOS 27.2: 52 checks pass with its libraries built for 27.0 and for 26.6 (MACOSX_DEPLOYMENT_TARGET=26.6), the mirror of the reporter's Mac; the same libraries in an archive made for 26.6 failed the 10 checks. Open: no run on macOS 26.x here.
Pipeline archive files left behind by a major system update
- Symptom: after a major macOS update, every start logs
[RED] pipeline archive file …/pso_archive/p00042.mtl4a not usable (deployment target for architecture … is not compatible with current OS …): its bases are built again, once per file written on the old system, but nopipeline prebuild:line; the game then stalls for one to several seconds whenever a scene shows bases it had before (frames of 1–7 s talking to a character or when bombs go off). The red lines and the missing prebuild come back on every later start; a base a draw built is captured again, so the stalls move on to the scenes not yet played since the update. - Cause: the same rule as the offline archive for the files the host writes: Metal opens a pipeline archive only on the major version it was made for.
pso4_initskipped a file it could not open but left it on disk. The prebuild's files (p*.mtl4a) carry its bases, andprebuilt.tsvstill matched (the stamp does not hold the system version), so the prebuild was skipped as done for good and those bases were left to the draws, each built on the submit thread (about 0.3 s, M1 Pro) the first time a scene needed it. The refused files also stayed on disk for good. - Fix: a file Metal refuses is removed with its index, as old indexes already were; a refused prebuild file also removes
prebuilt.tsv, so the next start runs the prebuild again. The log says… not usable (…): removed, its bases are built again. - Found on: The Legend of Zelda: Ocarina of Time, M1 Pro with 16 GB, after updating macOS 26.6.2 to 27.2.1: 57 refused files (1.68 GB of 3.1 GB), 7 of them prebuild files, and no prebuild in a 24-minute session, which had 53 stalls of 100 ms or more on new pipelines (39 s in all). On a copy of that archive the fixed host removed the 57 files and
prebuilt.tsvand ran the prebuild; on main with an empty archive the whole prebuild took 13.4 minutes for 34,649 pairs (10 workers) and 2.7 more for the prewarm lists, once. - Check:
t_pso_archive(test_unusable_file_removed): a prebuild file Metal will not open, its index andprebuilt.tsvare removed on the next start, and the other files still give every base. It fails without the fix.
Mac prewarm pipelines reused after a packed shader library changes
- Symptom: after a shader input changes, the Mac app build recompiles the affected library but reports
prewarm pipelines: reused (inputs unchanged), retaining pipelines made with the previous shader functions. - Cause: the prewarm cache key read
b-<chain>/inputs.tsvwith a normal filesystem path. A full shader build packs that directory intob-<chain>.img, so the stamp was silently replaced with an empty string in the key. A profile input such asdual_want.tsvchanges functions without changing the chain, shader keys or recorded pipeline list. - Fix:
build_ipa_from_nsp.pyreads the stamp throughshader_lib.view, as other library readers do. Both folder and image stamps invalidate the captured prewarm pipelines when shader inputs change; identical inputs still reuse them. - Check:
test_nsp_mac_app.pyexercises unchanged and changed stamps in both storage forms. Its image case reproduced reuse before the fix. - Found on: Sid Meier's Civilization VII, adding the second dual-source shader during bring-up.
Python memory during offline pipeline archive preparation
- Symptom:
pso_offline.pyholds about 1.8 GB whilemetal-ttbuilds an archive of 140,036 bases, and the system's memory view shows the build far larger than that (180.5 GB) beforemetal-ttfails or is stopped. - Cause: the builder made the pipeline script (503 MB at 140,036 bases) as one JSON string and as bytes, read the previous script whole to compare them, and serialized the whole key input once more; the descriptors stayed referenced while
metal-ttran. That is at most about 1.8 GB: the 180.5 GB weremetal-ttand its compiler processes, not Python. - Fix:
write_scriptstreams the script tobases.mtl4-json.partialand replaces the previous script only when the two differ;archive_keyhashes the same JSON as it is encoded (the keys of earlier builds still match); the descriptors are released beforemetal-ttstarts. Measured with 140,036 synthetic bases: peak 1.83 → 0.45 GB, 1.81 → 0.06 GB held whilemetal-ttruns, about 11 s more encoding (Python 3.15), byte-identical script and key. - Found on: Mario Party Superstars (GitHub issue #1022, PR #1024). Open: why
metal-ttfailed after 76 minutes there, and how its memory grows with the number of bases. - Check:
dm/tools/tests/test_pso_offline.py(test_large_script_memory_and_compatible_archive_key).
Bounded groups for the offline pipeline compiler
- Symptom: the offline archive stops with only
applegpu-nt command failed, sometimes afterMax Unstruct IDlines (a note, not the failure); the macOS kernel log reportsno paging space actionand killsair-ntas the largest compressed process. - Cause: Apple's GPU compiler can exhaust memory while compiling the complete pipeline list. Lowering the Python builder's memory does not bound the compiler's. RSS excludes compressed and swapped allocations: use kernel resource-kill diagnostics and physical-footprint measurements to distinguish this failure from a compiler rejection or a full disk.
- Fix: with more bases than
--batch-size(default 1,000; 0: one compiler invocation),pso_offline.pycompiles sequential groups of at most that many, each script referencing only its libraries, then merges all results withmetal-pack -nthreads 1. The normal single-file output, full-input archive key and runtime stamp stay compatible. Successful groups are cached by their own descriptors, library bytes, GPU, OS and compiler. A failed group or merge publishes neither a new complete archive key nor coverage stamp, and keeps the groups already done. The groups stay in the work folder (batches.<arch>/, 1.2 GB for Odyssey), so a run after a failure or after a change to some libraries compiles only what changed. This bounds input count, not compiler memory; an individual pipeline or the final merge may still exhaust resources. - Found on: Super Mario Odyssey, which records the resource-kill evidence, before/after measurements and complete archive validation. Issue #1022 requests archive partitioning for another game's resource-heavy build; that workload remains unverified.
- Check:
dm/tools/tests/test_pso_offline.pycovers the default, pilot reuse, compatible full-archive reuse, partial final batches, changed-group invalidation, compile failure and merge failure.t_pso_bundlecompiles one base per group, opens the merged result, retrieves a base from each group, rejects an absent depth entry and compares the complete coverage stamp with the ordinary build.
A base the GPU compiler cannot encode cost the whole offline archive
- Symptom:
[RED] pso_offline: metal-tt failed for applegpu_… (exit 1): LLVM ERROR: Failed to encode., and the NSP script's[RED] pipeline archive: pso_offline.py failed …; the app is packed without one and builds its pipeline bases on its first start. On a run from the build folder:[RED] pipeline prebuild: the base of … failed: Compilation failed due to an interrupted connection: XPC_ERROR_CONNECTION_INTERRUPTED, aMTLCompilerServicecrash report whose stack ends in a fatal error underllvm::MCObjectStreamer::emitInstruction(Error message SHA256: 01fbda05…, the hash ofFailed to encode.), and the compiles in flight when the service ends failing with it. - Cause: Apple's GPU compiler (the same code in
MTLCompilerServiceand inmetal-tt'sapplegpu-nt) stops with a fatal error on one function, andmetal-ttends its whole run on it, so one base took the archive of every other base with it:compile_archivestopped the build. What the compiler stops on is in its instruction encoder and is not ours to fix; what is known of the trigger, from PRAGMATA's pixel shaderc4ac3ca598cea32e(macOS 27.2, toolchain 32023.922):- every architecture tried up to
applegpu_g17fails (g15s, g16s, g16g, g17s, g17p, and g18p for iOS), for a macOS 26 or 27 target;applegpu_g18mcompiles it; - the vertex function has no part (a trivial one fails the same way);
- the library compiled with
-O0builds its pipeline. Of the front end's passes (-mllvm -opt-bisect-limit), everything up to SROA is fine and the first EarlyCSE on the shader's body makes it fail; withmetal-opt,sroa,early-cse,sroa,gvnandsroa,newgvnfail whilesroa,instcombine,sroa,simplifycfgandsroa,instcombine,simplifycfg,gvn,instcombinedo not; - it is the merging of repeated loads: with every load marked volatile for the pass (and unmarked again) it compiles, and three loads are enough to bring it back, those of one uniform word tested in two neighbouring blocks (
as_type<int>(c10[2].w) & 1, once as a condition several later branches use, once for a? -1 : 0mask); - (found since: the merged load leaves one compare of bit 0 with two users, the mask and the branches, and how many uniforms come before it decides the failure; see A jump Apple's GPU compiler cannot encode)
- it needs the rest of the function around it: reductions of the source and of the IR that keep the failure stop at about 780 statements and 1,300 instructions with nothing left to name, the same pattern written by hand compiles, and so do synthetic shaders with thousands of statements, uniform reads or an early return.
- every architecture tried up to
- Fix:
pso_offline.pyfinds the pipelinesmetal-ttcannot compile and leaves them out (compile_isolating): when a group fails with room on the volume, it is halved until single pipelines fail alone, those are named in a red line each and written torest_pairs.tsv, which the host already builds on the device beside a bundled archive (and whose pairs its probe of the archive skips), and the rest is compiled. A group in which nothing compiles, a failure that does not repeat on the pipeline alone, or more thanMAX_FAILED(8) failures in one group stop the build as before. A reused archive still names them (failed.<arch>.tsvbeside its key). On the device such a pair fails in the prebuild, is recorded (prebuild_failed.tsv) and left to the draws. - Open: a draw with such a shader still has no pipeline. PRAGMATA's
c4ac3ca598cea32e, the one shader known to hit it, now compiles: its trigger was found and is rewritten (A jump Apple's GPU compiler cannot encode); this entry stays the safety net for any other. The general way out would be for the build to try each library's functions throughapplegpu-nt(about 0.2 s each) and compile the ones that fail again without the front end's optimizer; not written: it adds minutes to every game's build for one shader that no draw has been seen to use. - Found on: PRAGMATA: three of its 48,957 bases, all with
c4ac3ca598cea32e. Measured on 304 of its pairs forapplegpu_g16sin groups of 100: the three named, 290 bases archived, 74 s. - Check:
python3 -m unittest dm/tools/tests/test_pso_offline.py -k failing -k cannot_compile.
A failed pipeline archive stops the whole build
- Symptom:
--platform mac-appor the iPhone build stops at its pipeline archive stage, after every earlier stage has finished:[RED] pso_offline: metal-tt failed for applegpu_<gpu> (exit 1), thenpso_offline.py exit code 1. - Cause: the archive is an optimization (without one the device builds the bases on its first start, as with
--gpu none), but the NSP script andbuild_ipa.shtreated its failure as fatal. Whatever made it fail, such as memory or a full disk, lost the whole build. - Fix: both remove the unfinished archive folder, print a
[RED] pipeline archive: pso_offline.py failedline and pack the app without one. The NSP script ends the stage with a warning (⚠in the console,warn: truein its JSON event).pso_offline.pyrun by itself still exits non-zero. - Found on: Super Mario Odyssey 1.4.1 on an M1 (
applegpu_g13g), LNPANDY/NX2Apple#98, through PR #494. - Check:
dm/tools/tests/test_nsp_mac_app.py(test_pso_archive_failure_is_a_warning,test_ipa_build_says_its_archive_failed),dm/tools/tests/test_pso_offline.py(IpaFallback),dm/tools/tests/test_nsp_progress.py(test_warned_stage_end).
Offline pipeline archive on a full disk
- Symptom:
[RED] pso_offline: metal-tt failed for applegpu_<gpu> (exit 1)with onlyapplegpu-nt command failedinmetal-tt.<arch>.log. - Cause:
metal-ttwrites one.airpper base and itstranslate-*folders inTMPDIR(the work folder), and it does not say when the volume is full. Cruis'n Blast's 33,858 bases failed with 366 MB free. A failed run also left its temporary files inpso/mac-work. - Fix:
pso_offline.pyclears those temporary files and stops beforemetal-ttwhen the work folder's volume has less than about 96 KB per base free (2 GB at least), and names the free space. Whenmetal-ttstill fails, it clears the temporary files and says when the volume is nearly full. - Found on: Cruis'n Blast (0100B41013C82000, version 1.0.7; no profile in this repository), on a Mac with 366 MB free.
- Check:
dm/tools/tests/test_pso_offline.py(test_low_disk_space_stops_before_metal_tt).
Compute pipelines compiled at first use
- Symptom: a game without a recorded prewarm list (a provisional profile) stalls at its first dispatches while Metal compiles their compute pipelines. The Mac app's pipeline archive held render bases only (
archive.tsv:bases), whatever the shader map listed. - Cause: a compute pipeline was only ever built on the device, through the
MTLDevice(newComputePipelineStateWithFunction), at its first dispatch or from the prewarm'sCrows, and a provisional profile'spso_manifest.tsvhas none. Yet such a pipeline depends on nothing but its function: the host passes no threadgroup size or other option (the dispatch gives the threadgroup size), so it can be compiled offline for every compute shader of the shader map. - Fix:
pso_offline.pyadds a compute pipeline descriptor that names the function alone for the<key>_bof every compute shader: the prewarm list'sCrows first, then the map's rows of stagecompute; shaders with function constants are left out (the host specializes them). They compile in groups of their own (batches.<arch>/c<index>/, 16 a group,--jobsgroups at a time), cached by their inputs and merged with the bases. The host looks<key>_bup in the bundled archive first (cps_new) and builds it on a miss; the prewarm's last lines count both. - Found on: Star Fox (v131072, with a provisional profile before this repository had one), chain
ae59da13e481, on an M5 Pro, measured on a fork with other host changes: 233 compute shaders give 233 compute pipelines beside 3 bases, a 35 MB archive. Built in 16 groups, 7 at a time, in 268 s, against 453 s as onemetal-ttrun (842 and 829 s of CPU; both at background priority, with load averages of 19-26 from other jobs); unchanged inputs reuse it in 0.3 s. Two headless boots of 90 s to the title took all 7 of their compute pipelines from it and built none, with no watchdog stop. Also The Legend of Zelda: Ocarina of Time (v131072, chainf9f01e4f9994,applegpu_g18g): 4,125 compute pipelines (480 MB, 204 s), and all 103 compute pipelines of a route to the village came from the bundle with none built; PR #1522 measured what the archive saves with the Metal cache cold, 195 s of submit-thread pipelines (155 s in the title movie's twelve kernels) to 0.9 s. - Check:
dm/tools/tests/test_pso_offline.py(Compute, among themtest_pipelines_from_a_library_imagefor one-file libraries,test_compute_pipelines_are_groups_of_their_own,test_compute_pipelines_alone_make_an_archive);t_pso_bundlebuilds an archive with compute shaders and checks that a map's shaders come from it and that a shader with constants or outside the map is built. - Open: iOS archives get the compute pipelines too (
build_ipa.sh), not measured on a device.
Compute pipelines outside the bundled archive built at every start
- Symptom: a compute pipeline the archive bundled with the app does not hold (no bundle, as in a headless boot or a build without
pso_offline.py; a shader outside the shader map; an OS update the bundle's binaries do not survive) was compiled again at its first dispatch of every start the system's shader cache had dropped it, and the device's own pipeline archive (pso_archive) never held one:compute pipelines so far: 0 from the archive bundled with the app, N builtstart after start. - Cause:
cps_newbuilt such a pipeline through theMTLDevice(newComputePipelineStateWithFunction), which no pipeline serializer sees. Only the render bases went through the flush period's Metal 4 compiler, whose serializer captures what it compiles. - Fix: a compute function with a Metal 4 library descriptor (
fn4_note) is looked up in the bundle, then in the device's own archive files. On a miss it is built through theMTLDeviceas before, for the dispatch, and compiled again through the Metal 4 compiler into the current flush period on a background queue, one at a time at utility QoS (arch_harvest,arch_capture_cs): the serializer captures compute pipelines as it captures bases, and the flush writes them. The dispatch does not wait for the capture, which compiles the pipeline whole where theMTLDevicegets it from the system's shader cache: a first version that built the dispatch's pipeline through the capture took 95 ms for Star Fox's first 5 compute pipelines, against 1.2 ms through theMTLDevice. A period with compute pipelines is a plain file, never ap<seq>one, so the lookups skip the prebuild's files. Compaction captures a compute pipeline the prewarm takes from an old file again, as it does bases. Still built through theMTLDeviceand never looked up: a function with constants and the embedded kernels, which have no descriptor. The log counts them:compute pipelines so far: N from the archive bundled with the app, M from this device's archive, K built (… ms looking up, … ms building), andpipeline archive: … and M compute pipelines written to …. - Measurement: headless boots of 90 s to the title (frame 5,100) without the bundle, each series with an archive and prewarm list of its own. Before: 5 compute pipelines built at the first start (1.2 ms in all, from the system's shader cache) and 9 at the second (2.2 ms), none kept. After: 5 built at the first start (0.6 ms), and the flushes wrote them (
2 new pipeline bases and 1 compute pipelines,50 … and 4 compute pipelines); the second start took 8 from the device's archive (the prewarm'sCrows and the first dispatches; 1.4 ms of lookups in all) and built none. Both reached the same frame with the same five[RED]lines. With a warm system cache the two cost about the same; the archive keeps the pipelines when that cache drops them. - Found on: Star Fox (v131072, with a provisional profile before this repository had one), chain
ae59da13e481, M5 Pro, macOS 27.0, on a fork with other host changes. Also The Legend of Zelda: Ocarina of Time: without the bundle, the first start wrote 88 compute pipelines into the device's archive and the second took 88 from it. - Check:
t_pso_archive(compute_pipelines): a compute pipeline is built, compiled into the flush period in the background, written to a plain file, taken from it again without a build, captured again during a compaction, and a function without a descriptor is built through theMTLDevice, never looked up and not captured;t_pso_bundle: a shader outside the map is captured, one with function constants is not.
A learned mesh pipeline is built again after prewarm
- Symptom: a manifest contains native mesh rows, but the game still logs
task / mesh pipeline: … required at framefor the same pipelines after preparation. - Cause: a shader row could carry NVN2's task/mesh stage numbers (6/7), while the host uses slots 3/4. The prewarm workers cache a shader by name, so the first worker could publish the raw stage even for a later request from a valid mesh row. A draw using that shader could write stage 7 into its own mesh row; the next launch then rejected that row.
- Fix: load standalone shader rows using the stage in the current game's shader map, as the live loader does. Read a stored stage 7 as 4 only in a mesh row; the map, task, fragment and render-state checks still apply. Prepare one library per shader name and one pipeline per normalized mesh state and task shader. The render test exercises raw and host stage numbers together and checks both the first demand and its rendered pixels.
- Found on: Mario Kart World.
Native mesh pipelines compiled at their first draw
- Symptom: the first sight of a scene drawn with task and mesh shaders freezes for seconds on a cold Metal cache, on every start once the system's shader cache has dropped the pipelines, although the prewarm finished:
task / mesh pipeline: task … mesh … fragment …, N ms required at frame F. Beforeea0c98dfthe draw was left out instead, and the foliage stayed missing or white until the pipeline was ready. - Cause: a native task / mesh pipeline (
mtk_psoinnvn_geometry.inc) was built only at its first draw, through theMTLDevice(newRenderPipelineStateWithMeshDescriptor), and nothing kept it. No prewarm row named one, so the shader rows loaded its libraries and built nothing, and no pipeline serializer saw it, so the pipeline archive never held one. Sinceea0c98dfthe draw waits for its pipeline, so each one met in play is a stall on the submit thread. - Fix:
- Rows:
mtk_psorecords each pipeline it builds as anMrow inpso_user.tsvand the record list. The row holds the task shader's key or-, then thepso_skeyhex of the render state with the mesh shader in the vertex place and the pixel shader, if any;pso_mesh_skey_parserefuses a row with a vertex layout, a specialized fragment or the wrong stages. - Prewarm: the prewarm builds each row on its workers (a task of its own,
kind 3), so with the prepare step every listed pipeline is ready before the first frame. - Claim: the submit thread takes the pipeline under the live shader objects when they come from the same library and entry (
warm_mesh_shader_equal). The program prefetch loads its own objects for the same keys, and claiming by object identity alone dropped prewarmed pipelines (native mesh prewarm: live shader variant differs, 0-29 a run on an M2 Pro, reported in PR #1368). A mesh shader loaded with its other entry after a depth mode change (entry_z) is not taken. - Metal 4 mesh bases, offline archive and program-creation prefetch: with the Metal 4 compiler,
mtk_buildcompiles each eligible(task, mesh, pixel)triple as an unspecialized mesh pipeline base (mtk_base, colour attachments open) and specializes it per draw (spec_desc+plain_spec, tens to hundreds of microseconds), sharing one base across every colour format, write mask and blend state. Static(task, mesh, pixel)triples from shader variations are emitted tomesh_pairs.tsv(M <TAB> task <TAB> mesh <TAB> pixel, besideshader_pairs.tsvandgeo_pairs.tsv), compiled offline bypso_offline.pyinto the bundled pair archive (mesh_render_pipeline_descriptors, with depth-only triples inrest_pairs.tsv), and prebuilt bypso_prebuildon the device (pre_desc_mesh,DM_MESH_PAIRS). When a game creates a mesh program (mtl_prog_prefetch),mtk_prefetchalso builds its base in the background (DM_NVN_MESH_PREFETCH=0disables it). Draws whose base was already ready or taken from the archive skip recording anMrow. Mesh shaders with per-primitive outputs (mesh_stage.primin reflection, set bydmsh_meshstage.py) and pixel shaders that read[[primitive_id]](PSO_WHOLE) still build whole pipelines because Metal 4 mesh base specialization non-deterministically zeroes per-primitive outputs and[[primitive_id]](reproduced 6/10–7/10 on macOS 27.2.1 Apple M6 and on macOS 27.2 M5 Pro). - Seed rows: Ocarina of Time's
pso_manifest.tsvcarriesMrows recorded in play; its note has the count, the areas and what each set measured.
- Rows:
- Found on: The Legend of Zelda: Ocarina of Time, v131072. Measured by contributors on hosts that carried the rows and prewarm of PR #1368, not the archive path:
- M5 Max, cold cache: without rows, the Kokiri Forest entry built 63 pipelines one after another on the submit thread, 59.5 s in all, with one frame of 42.9 s. With 88
Mrows and the prepare step, all 88 were built before the first frame (76.6 s on 18 workers), none at a draw, and the longest frame was 281 ms. - M1, cold cache: a 300 s walk built 47 pipelines at their draws, 103.5 s in all, the longest 12.76 s. With the rows and a fork's archive, 58 were prewarmed in 7.3 s on 8 workers.
- iPad Pro (M5): 1.9-5 s per pipeline with a cold cache, 0.1-45 ms cached.
- M4 Pro: with the rows, 0 built in play, against 56 without.
- M5 Max, cold cache: without rows, the Kokiri Forest entry built 63 pipelines one after another on the submit thread, 59.5 s in all, with one frame of 42.9 s. With 88
- Check:
t_pso_skey: mesh keys round-trip, and malformed or incompatible rows are refused.t_pso_warm(native_mesh, on both compiler paths): only the canonical row loads, the warm task publishes a pipeline, duplicate live objects claim it without a build, a different depth entry is not claimed and builds its own, and the warmed and demanded pipelines draw the same pixels.t_pso_archive(mesh_pipelines): a pipeline is built, captured in the background and written to apfile, with or without a task or pixel shader. A later start takes it from that file without a build, a compaction captures it again, and a function without a Metal 4 descriptor is built through theMTLDeviceand not captured.t_mesh_first_use: no first draw is left out.
- Open: the archive path has run only in
t_pso_archive, not on a game route. On iOS the Metal 4 path, and with it the archive, is off for a profile withoutpso_mtl4 on(Ocarina of Time has none), so there the rows and the system's shader cache are what keep a mesh pipeline.pso_offline.pymakes no native mesh pipelines for the archive bundled with the app.
Vertex shaders with layer entry points left out of the prebuild
- Symptom: a frame of 200 ms or more the first time an effect appears, although the bundled pipeline archive was trusted and the prewarm finished. With
DM_PSO_WAITLOG=1the frame shows waits on render pipelines with no pulling entry, 34-74 ms each, for vertex shaders that have no stage inputs. - Cause: whether a vertex shader writes the layer was not in its reflection. Three places guessed it from the library's bytes (
render_target_array_indexanywhere in the file), each in its own way: the shader loader (shader_load) excepted a library with layer entry points of its own (entry_layer,main0_l, which alone write the layer; itsmain0writes none), while the offline archive (pso_offline.py) and the device's prebuild (pre_desc) did not, and left every pair of such a shader out. A shader with no stage inputs has no stand-in pipeline, so each of those pairs was compiled at its first draw while the frame waited. - Fix: the reflection holds the fact:
layer_outwhenmain0(and somain0_z) writes the layer (dmsh_entry.pylayer_out, frommain0's output; the geometry output reader<key>_bgvtoo). The loader, the prebuild andpso_offline.pyread it and nothing else, so they cannot part again, and no library is searched. Layer entry points do not count: the host asks for them by name (entry_layer) and their pipelines are layered by that. A chain change (d403eb0683df): the libraries are rebuilt, and with them the archive. - Found on: The Legend of Zelda: Ocarina of Time, v131072, M6 (macOS 27.2): 2,675 pairs had been left out, so the archive grows from 30,690 bases to 33,365. On the
field-runbench route from a Hyrule Field save (a camera turn at about 105 s), two runs each: the worst frame was 230-234 ms with 4 waits of over 20 ms per run before, and 39 ms with none after. - Check:
dm/tools/tests/test_dmsh_layer_out.py(main0writing the layer sets it, layer entry points do not);dm/tools/tests/test_pso_offline.py(a library that names the layer withoutlayer_outgets itsmain0base, one with it none);t_pso_bundle(the same for the prebuild). - Open: a 39 ms frame at about 117 s on the same route, one pipeline taking 15-20 ms, under the wait log's threshold; not traced.
The device's prewarm list unread without a seed list
- Symptom:
[RED] pipeline prewarm: seed list does not exist: …/pso_manifest.tsvat every start, nopipeline prewarm list …/pso_user.tsvline, and the same compile stalls every session in places already visited, whilepso_user.tsvkeeps growing; the pipeline archive gains files every start and is never compacted (Donkey Kong Bananza: 88 files, 7 s to open them). - Cause:
warm_start(dm/gfx/nvn/nvn_mtl.m) returned as soon as the profile had no seed list, before it added the device list, so neither list was warmed, and the prebuild of every shader pair's pulling base and the archive's compaction, which run after the prewarm, never ran either. Draws then waited for their pipelines on the submit thread with no hybrid stand-in. - Fix: a missing seed list is logged and left out; the device list is still warmed, and the prewarm returns only when neither list exists. Host only.
- Found on: Donkey Kong Bananza: before, a 13,200-frame session had 154 frames over 100 ms (122 mostly compiling, the worst 7.1 s), 87 s of compiling on the submit thread and 95 draws with a hybrid pipeline; after, the start warmed the 2,484-line device list in 7.6 s (1,002 bases from the archive), compacted 98 archive files into one and ran the prebuild once (20,647 pairs, 116 s before the first frame), and a 17,700-frame session had 68 such frames (40 compiling, the worst 1.9 s), 12 s of compiling and 5,320 hybrid draws. The game has a seed list now.
A pipeline a hybrid draw stood in for listed only once built
- Symptom: on an iPhone the next start still waits on, or draws with stand-ins for, the pipelines the last session asked for last. Ocarina of Time on an iPhone 18 Pro Max asked for about 400 pipelines in Castle Town and finished about 60 a minute; whatever was still unbuilt when the run ended was not in
pso_user.tsv, so the next start's prepare step did not build it. HookLink's measurement; we have not reproduced it. - Cause:
pso_user.tsvtook a pipeline's row from the submit thread only once its build finished. While a hybrid draw drew with its shader pair's pulling pipeline, the pipeline it wanted was queued in the background (pso_pend_demand), where a build took 5-50 s with the game running on two performance cores, against about 1 s in the prepare step before the first frame. - Fix:
demand_record(dm/gfx/nvn/nvn_mtl.m) writes the row when the hybrid draw first asks for the pipeline, once per key, including an already pending build or one the full build table could not admit. The later row from the built pipeline is the same line, whichpso_user_recorddrops. Early recording remembers at most 65,536 keys per process; new keys beyond that retain completion-only recording.DM_PSO_DEMAND_RECORD=0records a pipeline only once built, as before. The added rows move work into the next preparation; they do not remove compilation. - Found on: The Legend of Zelda: Ocarina of Time, found by HookLink (engine branch: https://github.com/dsi-hub/nxnative/tree/hooklink, commit 0ad4e1a9) on an iPhone 18 Pro Max.
- Check:
t_pso_demand_recordcalls the realpso_gethybrid path with synthetic Metal functions and cached stand-ins while its production demand queues are suspended. New and independently prequeued demands persist canonical rows before compilation; an exec child reads them throughwarm_parse. After releasing the queues, completed pipelines replace the stand-ins and record identical rows without duplicates. Separate processes check recording disabled and the 65,536-entry early-record cap (completed pipelines still record beyond it). Removing call-site recording, or recording only newly queued demands, fails matched controls. API validation is enabled. This proves pipeline lookup and process-reload visibility, not power-loss durability, a game draw, fresh-process prewarm compilation, or native performance. - Preparation cost: a matched, controlled backlog of recorded game pipelines was measured through the real prepare step on the Mac; NieR:Automata's note records its inputs, repeated timings and limitations. The Castle Town iPhone preparation increase remains unmeasured.
Shader libraries loaded when the program is made
- Symptom: the first frame that draws with new programs loads their shader libraries on the submit thread (
[longframe] ... shader libraries N, X ms): tens of milliseconds with the files cached, seconds when the drive is slow. - Cause: a library was loaded when a draw first resolved its program (
prog_get), or, from the first pipeline miss of a submission, for the whole rest of the submission at once and in parallel (shader_prefetch_rest), but still on the submit thread's time. The game names a program's shaders earlier, when it makes the program (nvnProgramSetShaders), often while it loads a scene. - Fix:
mtl_prog_prefetch(called fromnvnProgramSetShaders) loads each stage's library on a background queue, with a vertex shader's pulling entry as the prewarm does, and the next submission takes it into the shader cache (warm_claim), writing it to the prewarm lists asshader_getwould. A set of the libraries loaded or under way (progpf_first, whichshader_getandshader_prefetch_restalso mark) loads each once. A draw that comes before its library has loaded loads it itself, as before. The shader map is read once from any thread (shmap_read_once); the prewarm still starts on the submit thread, once (shmap_load). A first version put the prewarm inside the samedispatch_once, and the pipeline prebuild's own call ofshmap_loadfrom inside it re-entered it: libdispatch aborted Tears of the Kingdom and Pokémon Scarlet at boot (the regression found it; Donkey Kong Bananza runs no prebuild).DM_NVN_PREFETCH=0turns it off. - Check: Donkey Kong Bananza's scripted route, both runs with the drive idle: the first frame's 4 libraries (22 ms on the submit thread) no longer load there; the level opening's 3 still do (0.5-3.9 ms), its programs made just before their draws.
- Found on: Donkey Kong Bananza: 3 to 7 libraries a new area, which took up to 4 s a frame in a session with the drive slowed by other work.
The prepare step inside the shader map's once
- Symptom: at boot,
CRASH sig=5 … pc=_dispatch_once_wait.cold.1right after thepipeline bases so farline, withbt: pso_prebuild __shmap_load_block_invoke … mtl_prog_prefetch h_nvnProgramSetShaders. - Cause: making
shmap_loadsafe from any thread for the prefetch put its whole body in adispatch_once, and that body ended inwarm_start. With a prepare step (a window,DM_PSO_PREPARE=1, or the regression harness's runs),warm_startruns the prebuild in place, andpso_prebuildcallsshmap_loadagain on the same thread inside the once, which libdispatch traps. The prefetch also moved the start of the prepare step from the first submission to the game's firstnvnProgramSetShaders, on the game's thread. Separately,warm_startcreated the list that finished items go on, so a library the prefetch finished before it, or in a run with no prewarm list, was dropped, and its first draw loaded it again. - Fix:
shmap_read_onceis thedispatch_oncearound reading the map;shmap_loadreads through it and then starts the prewarm once, outside it. The prefetch only reads the map, so the step runs at the first submission again (the prepare step).warm_enqueuemakes its own list. Host only. - Check:
dm/gfx/tests/t_shmap_warm.mneeds no game: the map's read leaves the prewarm unstarted, an item finished earlier is kept, and the first submission gets through the prebuild's second call. Before the fix the same sequence trapped with exit 133. - Found on: general to games that run a prebuild: The Legend of Zelda: Tears of the Kingdom and Pokémon Scarlet at boot, Blasphemous under
regress.py, Hollow Knight with a window. Donkey Kong Bananza, where the prefetch came in, runs no prebuild and never showed it.
A prebuild stamp written without the pulling libraries
- Symptom: after an IPA packed without
_bp.metallibran once withDM_PSO_MTL4=1, an app with those libraries still stalls on new pipelines:pipelines up to framelines showdraws with a hybrid pipeline 0anddraws that waited: pulling base not made yet, and the log has nopipeline prebuild:line. The run before it logged[RED] pulling library of … not usableandpipeline prebuild done: … 19838 left to the draws. - Cause:
build_ipa.shleft the pulling libraries out when the profile did not setpso_mtl4 on(until Pulling vertex inputs kept them in every iOS build;IOS_PULL=0still leaves them out), while the launcher can still turn the Metal 4 path on.pre_descthen returned no descriptor for every pair with a pulling vertex entry, andpso_prebuildwroteprebuilt.tsvas for a finished run. The stamp covers the chain, the depth mode and the pair lists, none of which change when the app gains the libraries, so the next start took the prebuild as done and no pulling base was ever made. - Fix: the device's
prebuilt.tsvnow ends with what the run found (pre_device_stampinnvn_mtl.m):libs all, orlibs missing <file>naming one library file a pair needed and the app lacked (pre_lib_absent): a pulling library<key>_bp.metallib, or a shader's<key>_b.jsonor<key>_b.metallib, which a partial shader build can add later.pre_stamp_donetreats the second as done only while the library still lacks that file, so a package with it builds the pairs. A file counts as there when it is in the library's folder or in its imageb-<chain>.img(msl_has, the lookupmsl_dataandlib_from_filemake): the Mac app and the IPA carry only the image, so a check of the folder alone would find every library absent. A stamp without the line was written before this check and may hide such pairs: it runs once more, taking the bases already archived. The run also logs[RED] pipeline prebuild: N pairs need a library file this app does not carry (first: …). The stamp of the archive made offline, whichpso_bundle_coverscompares, is unchanged. - Check:
make -C dm/gfx/tests GAME=<id> check_t_pso_stallcovers a missing pulling library, a later start of the same app, the library arriving, a stamp without the line, and the same with the library packed as an image: its files found there, an absent shader named by its file, and that shader added in a folder beside the image (the first version of this fix checked the folder only and, against an image, built none of the pulling bases and stamped that as done). No device run with the fix yet: the iPad's recovery below was made by overwriting its stamp by hand. - Found on: The Legend of Zelda: Tears of the Kingdom: iPad Pro 11 (M5), 1.4.3. 20,016 pairs: 178 bases built and 19,838 left to the draws without the libraries; with them and the stamp overwritten, 19,779 built in 718 s, and the archive grew to about 1.9 GB. That build raised the thermal state to serious, so the frame step held 30 fps for the first start after it.
Metal's build folders left by pipeline archive flushes
- Symptom: the user cache folder (
getconf DARWIN_USER_CACHE_DIR) fills withgpuarchiver-*folders, one per pipeline archive flush: incom.apple.gpuarchiver/for a host from a build, inorg.nxnative.<title ID>/com.apple.gpuarchiver/for a built Mac app. Each holds an LMDB store (PersistentState) and captured binaries, 0.3–5 MB at first (456 folders, 2.5 GB after two days), later up to about 127 MB (an M4 Pro, 2026-10-29: 19 GB in 423 folders after a day of Mac runs and regression checks); why they grew is open. A built app's folders were never removed: Ocarina of Time's app had 4,016 of them, about 285 GB, and one Mac's apps 345.8 GiB in all; each start of Ocarina's Castle Town route left 6 more, 560 MB (issue #2680). A later compile can fail withcannot open '…/gpuarchiver-…/PersistentState': No such file or directory. - Cause: the Metal 4 serializer (
MTL4PipelineDataSetSerializer) creates a private working folder for each serializer, and the host makes one serializer per flush period (ep_new). Metal puts them under the main bundle's ID:<user cache folder>/<bundle ID>/com.apple.gpuarchiver, or<user cache folder>/com.apple.gpuarchiverfor a process without one (getCacheMainFolderin Metal; its exportedMTLGetGPUArchiverCachePathreturns the folder, measured on macOS 27.2: a test program without a bundle wrote to the shared folder, with anInfo.plistbeside it toorg.example.gatest/). In an iOS 27 simulator app the folder was<container>/Library/Caches/<bundle ID>/com.apple.gpuarchiver, andconfstr(_CS_DARWIN_USER_CACHE_DIR)returned nothing there. The host took the folder as<user cache folder>/com.apple.gpuarchiverin both cases, so its iOS cold-start cleanup most likely never found a folder, and a built Mac app's were outside both it andscripts/clean_metal_cache.py. A former cleanup inferred ownership from the sole new directory between two snapshots of the shared folder; when another compiler created one during the capture or flush, the foreign folder was claimed and deleted. Serialization success concerns the requested output archive, not the lifetime of Metal's private files; the public API exposes neither a scratch-directory selector nor an ownership token. A later start never reads the folders: with them emptied against kept, a Castle Town start's first frame was 2.22 s against 2.32 s and its prewarm 18.2 s against 19.3 s (n=3 each, issue #2680). - Fix:
nvn_mtl.masks Metal for the folder (ga_dir; the same rule computed when Metal lacks the function). A host with a bundle ID (the Mac app, the iOS app, one rule on both) owns its folder together with the other copies of the same game's app: from before its first serializer to its exit, each holds a sharedflockongpuarchiver.lockbeside the folder (ga_claim). At start it first tries an exclusive one; with it, no other copy runs, so it lists thegpuarchiver-*folders there, takes the shared lock, and removes them in the background (pipeline archive: N of M of Metal's build folders left by earlier runs removed from …). Otherwise it waits for the shared lock, at most a starting copy's listing, and removes nothing (another copy of this app is running). A lock held exclusively for the run would not do: a second copy that could not take it would hold nothing, and a third start after the first's exit would delete the second's live folders. Folders are never removed at a flush or exit, and a host without a bundle ID removes none from the shared folder. A run still keeps its own folders until the next start (Ocarina: about 560 MB a start, more in a long session).scripts/clean_metal_cache.pyremoves the shared folder's and the built apps' (org.nxnative.*) folders from outside, for apps not started again: a folder only when nothing in it changed for an hour (--idle-min) and its last change is older than the start of every runningdmhost, and an app's only while no copy of it holds its lock (listed under the exclusive lock, removed after it).scripts/regress.pyruns it at its start and when the disk falls under its limit. A folder of another program's live compiler that stayed idle for an hour in the shared folder would still go; none is known. - Found on: The Legend of Zelda: Ocarina of Time: a built app's folders, 285 GB (issue #2680). Pokémon Scarlet: the ownership defect is reproduced with an isolated foreign-folder fixture. Its longer house run had 20 missing-
PersistentStatefailures, but the deleting process was not observed, so that run's attribution remains open. Earlier cache-growth report: MacNativeGames (1eff989,110e6c6, Metal 3'sMTLBinaryArchive, 25 GB overnight on Tears of the Kingdom). - Check:
t_pso_archive(make -C dm/gfx/tests GAME=<id> check_t_pso_archive) preserves a foreign compiler fixture created during a compiler call through the subsequent flush, and checks the app folder's lock: a first copy lists the earlier runs' folders, a second lists none, and a third start after the first's exit lists none while the second runs.dm/tools/tests/test_clean_metal_cache.pykeeps folders changed within the idle time or since a running host started, keeps an app's folders while its lock is held, removes the rest, and looks in the shared folder and theorg.nxnative.*folders only. The iOS folder is from a simulator app (Metal's function; the simulator has no Metal 4 serializer); no device run yet.
A compaction flush that crashes, then crashes every start
- Symptom: a previously working game exits with 139 on every start after pipeline preparation;
dispatch_retain(NULL)is called by-[_MTLBinaryArchive materializeAirNTFromOnlineForSlice:entryList:]underairntSerializeToURLandarch_flush(issue #342). - Cause: more than eight run archives enables compaction. The prewarm used
MTL4CompilerTaskOptions.lookupArchivesto recapture their bases into the serializer that also captures newly compiled bases. Metal can crash while materializing that dataset for serialization. It crashes beforearch_compact_finishremoves the old files, so every restart retries it. Framework analysis recorded in issue #342 identifies a nilMTLBinaryEntry.bitcode, read from the captured function's library bybitcodeDataInternalwhen the bytes at its bitcode offset are not an AIR wrapper. Which function lacks AIR and why remain open. A lead, not a cause: a probe that reused one serializer after each write, with no compile during the write, crashed once in 111 runs with this signature, and a compile under way across a write comes back with its entry's AIR script and bitcode nil (A compile that does not return stalls every flush and draw); the host now never uses a serializer again after its write, and a serializer per period crashed in none of 118 runs; simple synthetic recaptures and a replay with no new bases did not reproduce it. A mixed Tears of the Kingdom replay did, with the reported null call and backtrace, on an M4 Pro with macOS 27.0.1 (26A434). - Fix: work around the framework defect by capturing each compacted base from its original shader functions, with no lookup archives. Metal's ordinary compiler cache still applies. The archive threshold, ordinary archive lookups, deferred flush during prewarm and removal of old files only after a successful write remain in place. A compaction start can do more compiler work; normal starts keep their archive hits.
arch_capturepasses no task options, so captured bases cannot accidentally import archive entries. The recovery guard from the earlier workaround remains:pso_archive/compactingrecords the system build and the capture method before a compaction flush, and is removed when the flush returns. A marker for this build and method suppresses another attempt after a crash. Legacy OS-only markers from archive imports are cleared so the safer capture method can run; a later OS or capture-method change also allows another attempt. - Found on: The Legend of Zelda: Tears of the Kingdom, reported on an M5 Max and reproduced with the local shader libraries on an M4 Pro. This is shared NVN archive code, not a game profile rule.
- Check: the same 19-file snapshot, 1,490 archived bases and 44 new bases failed in two of three runs with lookup imports and passed all three when only that option was removed. The implemented fix passed three further compactions and their following restarts: each compacted file supplied all 1,534 bases with zero new base compilations on restart. These are library-only manifest replays using the local
e7245308050dlibraries and a matching diagnostic chain header, not a new gameplay run or an iOS test.t_pso_archiverejects lookup imports at the real compiler seam;test_pso_archive.pyexercises disk-built libraries, concurrent recaptures mixed with a fresh function, function constants, compaction and restart in separate processes (make -C dm/gfx/tests GAME=<id> check_t_pso_archive). The marker tests retain the recovery guard and check migration from the old OS-only marker, including a fresh-process restart with that marker present.
Pipeline keys omit unused colour state
- Symptom: identical render pipelines compile repeatedly under different keys, lengthening startup prewarm and adding pipeline misses during play.
- Cause: NVN blend and channel-mask state persists between draws, including state for colour targets absent from the current pass.
pso_descskips targets without a format and reads blend factors only when blending is enabled, but the old keys retained unused state. Deduplicating manifest lines alone also misses old rows whose unused state differs. - Fix:
pso_key_norminnvn_pso_skey.hclears blend factors when blending is disabled and, for normal passes, the blend-enable bit and write-mask nibble of every target without a format. Merged passes retain their logical blend-enable and mask state becauselmapmaps physical attachments to logical targets; a missing physical format does not imply the same logical target is unused.pso_key_fillnormalizes live keys,pso_skey_parsenormalizes historical prewarm rows, andwarm_workerdeduplicates the parsed keys across all input lists before compiling. Depth and stencil formats remain in the key because theMTLDevicepath needs them, even though Metal 4 bases omit them. - Found on: The Legend of Zelda: Breath of the Wild (disabled blend factors), The Legend of Zelda: Tears of the Kingdom (absent-target state, reported by MacNativeGames).
- Check:
t_pso_skeycovers normalized round trips, historical rows differing only in unused state, and preservation of merged-pass logical masks and blend bits;t_pso_archivechecks disabled blend factors with all targets present.make -C dm/gfx/tests GAME=<id> check_t_pso_warmloads two synthetic manifests throughwarm_worker, checks compilation counts and draw-time cache hits, and compares GPU pixels with the original descriptors through both MTLDevice and Metal 4. It includes a merged pass whose physical attachment 0 uses logical target 7's blend and mask state.
Shader cache key covering the pairs
- Symptom: a vertex shader whose pairs changed was restored unpadded from
cas/. - Cause:
dmsh_build.py's shader cache was keyed without the pairs. - Fix: the per-shader key covers the pairs, and a paired vertex shader's key also covers its pixel shaders' keys (
shader_key,pair_keyed), so a change to a profile's pairs rebuilds what it affects (Pixel shader inputs the vertex shader does not write). - Found on: 13 Sentinels: Aegis Rim.
Shader cache key missing helper modules
- Symptom: an edit to a shader build helper reaches no library:
shader cache: hitfor every shader, and the old MSL is filed under the new chain version. An edit todmsh_meshstage.pydid not change the chain version either. - Cause: a cache hit restores a shader's outputs and skips
job_forandfinish, so everything they run has to be in the shader's key.CODE_FPleft outdmsh_wide.py,dmsh_ampere.py,dmsh_meshstage.pyanddmsh_fetch.screen_varyings(throughraster_facts), anddmsh_chain.py'sFILESleft outdmsh_meshstage.py. - Fix:
FILESandCODE_FPcover them. The modules that stay out ofCODE_FPare made again from the restored MSL on every build (dmsh_vin.py,dmsh_pull.py,dmsh_side.pywithdmsh_alpha.pyanddmsh_logic.py,dmsh_mesh.py, the rest ofdmsh_fetch.py), or are covered otherwise (dmsh_facts.py: its row is in the key;dmsh_mtlcache.pychanges no output). The change bumps the chain with the libraries byte for byte as before (Animal Well's 46), so Metal compiles nothing again. - Found on: no game: found reading the code after Mario Kart World added
dmsh_meshstage.py, then reproduced on ANIMAL WELL (an edit towide_loadsreached 0 of 46 libraries before the fix, all 46 after it). - Check:
test_dmsh_code_fp.pyCoveragefails whendmsh_build.pyimports admsh_*module that neither list accounts for.
Partial vertex builds missing paired pixel sources
- Symptom: a full build reports successful shaders, but
metal-ttrejects its pipeline archive with fragment inputs not written by the vertex shader. Fifteen cached vertices lacked default outputs in DRAGON QUEST I & II. - Cause: a partial build requested only its vertex keys.
vs_padskipped absent paired pixel MSL, then cached the incomplete vertex under a key that already included those pixel shaders' input digests. A later full build restored it before pixel-first finishing and never padded that cache hit again. - Fix: include available paired pixel shaders in partial build keys and output cleanup, then finish pixels before vertices. Do not publish a paired vertex cache entry while any paired pixel MSL is missing. The code fingerprint excludes the old incomplete cache entries; the Metal source cache still reuses unchanged complete libraries.
- Found on: DRAGON QUEST I & II HD-2D Remake, while building its Mac pipeline archive.
- Check:
test_shader_toolchain_cache.pyrequests a vertex alone, exercises dependency cleanup and pixel-first finishing, and checks that padding survives publication and a later full-cache restore. A missing pixel source prevents publication.
Target selection keeps the shader analysis files in the cache
- Symptom: a repeated iOS-only shader build crashes with
FileNotFoundErrorfor<key>_b.jsonin the Mac output directory; requesting only Mac libraries withIOSOUTset still compiles iOS side libraries. - Cause: target selection excluded the Mac directory from the per-shader cache entirely, but cache-hit processing, paired vertex padding and the profile tables still read its MSL and reflection. Side-library paths tested
IOSOUTrather than the selected targets. Prefilling the Metal cache also compiled validation samples for unrequested targets. - Fix: cache and restore the Mac MSL and reflection for every target; require and copy metallibs only for selected targets. A cache entry without its analysis source is a miss. Clear
IOSOUTwhen iOS is not selected and restrict prefill validation to selected targets. The NSP script writes only the requested target's reuse key. - Found on: Celeste, while reviewing PR #275 (resolved).
- Check: real Metal output and cache comparisons are recorded in Celeste's shader note above.
test_shader_toolchain_cache.pycovers geometry analysis files, incomplete entries and prefill selection;test_nsp_mac.pychecks target-specific reuse keys.
An iOS build after a Mac-only build kept no Mac libraries
- Symptom: after
scripts/build_ipa_from_nsp.py <NSP folder> --platform mac, a plain (iOS) run of the script on the same folder succeeds, but the Mac run command the first build printed then logs hundreds of[RED] failed to load shader <key>_b: cannot open …/shader/cache/b-<chain>/<key>_b.metalliblines, until--platform macis run again. - Cause: both builds write the Mac sources and reflection into
<id>_build/shader/cache/b-<chain>/, which also holds the Mac libraries. A fulldmsh_build.pyrun first removes every<key>_b*output there, so that a key that left the map or a shader that no longer builds keeps no old library, and then restores or compiles only the targets inDMSH_TARGETS. Since target selection (Target selection keeps the shader analysis files in the cache) the NSP script asked an iOS build foriosalone, so the Mac.metallibfiles were removed and only their.metaland.jsoncame back. - Fix: the NSP script (
build_shaders) asks an iOS build formac,ioswhen the folder holds the current chain's Mac libraries, and then writes both reuse keys, so a later--platform macrun is reused. The Mac libraries are rebuilt, not kept as they were, so none is stale: the Metal compile cache gives back every one whose MSL was compiled before, and only a changed MSL is compiled. The first such build of a folder may translate again, because the per-shader cache entries an iOS-only build left hold no Mac library. A folder without Mac libraries (only ever packed as an IPA) still compiles only the iPhone's.dmsh_build.py's rule, that a full build leaves only what it built, is unchanged; it is part of the chain version, so the fix stays in its caller. - Found on: Team Sonic Racing (resolved).
- Check:
test_nsp_mac.py(test_ios_after_mac_keeps_mac_libraries,test_ios_after_mac_of_another_chain).
Old shader library folders grew a game's build folder with each chain change
- Symptom: the build folder of a game (
<id>_build/shader/) gains about 2 GB for Breath of the Wild with every upstream update that changes the shader chain: after two updatesshader/cacheheldb-157e1b96c8da(2.1 GB) andb-a78f966a7b38(2.3 GB) besides the current one, and the next build added a third. - Cause: the libraries are written to
b-<chain>/(shader/cachefor the Mac,shader/iosfor iOS, with the reuse keysshader/ios/b-<chain>.keyandshader/mac-b-<chain>.key) and a chain change starts a new folder. Nothing removed the old ones. The host loads only the current chain's folder,dm/mac/pack_app.pyandbuild_ipa.shpack only it, andregress.pyreads the folder of its own run, so an old folder is dead weight.dmsh_build.pytook libraries of older folders into the Metal compile cache (dmsh_mtlcache.py) before it translated, andshader_regressions.pycompared the new build with the newest older folder's_b_build.json. - Fix: the NSP script (
prune_stale_chains, called last inbuild_shaders) removes the folders namedb-<12 hex digits>of other chain versions inshader/cacheandshader/ios, and their keys, once the libraries, their tables and the key of the current chain are in place (a reused build prunes too). It logs one line,removed old shader libraries b-… (N GB). A build that stops or fails earlier keeps the old libraries. The regression check has run by then, and the next chain change compares with the folder this build keeps. The compile cache already holds what the old libraries compiled, sincedmsh_build.pytook them in at the first build of the new chain. The only loss is for a chain that comes back (a checkout of an older commit): its shaders compile again where the cache does not hold their MSL. The compile cache itself (shader/cache/cas/metallib) is keyed by the MSL and the compiler, not by the chain, so entries are shared across chains and it is not pruned. It grows only with MSL that is new, and no code removes an entry. - Found on: Breath of the Wild (resolved).
- Check:
test_nsp_mac.py(test_prune_stale_chains_after_success,test_failed_build_keeps_stale_chains,test_prune_ignores_other_names).
Old per-shader cache entries grew a game's build folder with each chain change
- Symptom:
<id>_build/shader/cache/cas/shader/holds several entries for each shader, and grows by a full set with every upstream update that changes the shader chain. Tears of the Kingdom (seedds/nxnative#1033): 172,014 entries after six builds for 28,669 shaders, 11.85 GB of.metaland.jsonthat no build read; the test Mac's copy held 934,955, of which the prune (dry run) found 906,286 unused: 70.2 GB of sources and reflection, scanned in 18 minutes on an external SSD. - Cause: each shader's cache digest (
dmsh_build.pyshader_key) covers the chain's code and tools, so a chain change misses every entry and publishes a new one. Old shader library folders removed the oldb-<chain>/folders, not these entries.cas/index/<key>.jsoncannot tell which entry is in use: a cache hit does not rewrite it, so after a checkout of an older commit it can name a newer digest than the one the build restores. The digests also cover the iOS compile convention, so a Mac-only and an iOS build of one chain use different entries, andregress.pybuilds other chains into the same cache. - Fix: a full
dmsh_build.pyrun lists the digests it used,b-<chain>/_b_cas.txtbeside the Mac outputs (every full build writes those; the iOS folder goes whole into the IPA). The NSP script (prune_shader_cache, called withprune_stale_chainsafter a successful or reused build) removes theshader/<64 hex digits>entries of the compile cache that the list does not name and that are older than it, and logsremoved old shader cache entries: N (X GB), the space of their sources and reflection (an entry's libraries are clones of the compile cache's). No list (libraries built before it), a failed or stopped build, or a regress run: nothing goes. The Metal compiles are keyed by the MSL; since Old chains' compiles stayed in the one compile cache file each chain has its own file, and the files of other chains go whole, so this prune now covers only the chain's own file, where an edit of the shader map leaves old entries. A partialdmsh_build.pyrun (named keys) does not rewrite the list, so the next prune can remove the entries it published; the next full build translates those shaders again. - Found on: Tears of the Kingdom (resolved).
- Check:
test_nsp_mac.py(test_prune_shader_cache,test_prune_shader_cache_needs_success_and_the_list).
A shader build that keeps its packages in memory runs one worker at a time
- Symptom: the NSP script's Mac or iOS shader step for a game with very large shader packages runs at one or two shaders a second whatever
Jis. Its Python process sits at one full core, mostly system time, while fewmetalcompiles run. Pokémon Pokopia (4.4 GB of packages, 131,426 shaders): players reported ETAs of 20 to 200 hours (seedds/nxnative#1036). - Cause:
dmsh_build.pyread each package whole and kept its records as separate copies for the whole build: 105,118 of them for Pokopia's 4.25 GBps_rdb.bin, leaving the process at 8.7 GB. Every child process (spirv-cross,metal,metallib, several per shader) starts with a fork of the builder, which then took 75 ms instead of 3, and Python forks with the GIL held, so theJworkers queued behind each other. The same bytes in one buffer fork in 3 ms: the cost comes from the many separate allocations. - Fix:
record_indexscans a package for its record markers through a read-only mapping it closes again, and keeps only the offsets;rec_ofreads one record withpreadwhen the build needs it and keeps none. The outputs are byte-identical. - Measurement: a cold build of 1,001 Pokopia shaders on an M4 Pro (
J=10): 528 s before, 240 s after (1.9 to 4.2 shaders a second); the builder's Python went from 100% to about 46% of a core, and 8 to 10 Metal compiles ran at once instead of about 3. At that rate the whole map would take about 9 hours on that Mac (not run). The largest packages of the other local games are 241 MB (Splatoon Raiders) and less, where a fork costs a few milliseconds. - Found on: Pokémon Pokopia (resolved).
- Check:
test_shader_toolchain_cache.py(test_package_records_are_read_from_the_file_at_their_offsets).
Each Metal compile instantiates Metal's texture classes again
- Symptom: the Mac or iOS shader step of a game with a large map still takes many hours with every worker busy, and a
metal -cof a translated shader takes about 0.7 s of CPU, nearly all in the front end. Optimising adds about 0.1 s, and an empty shader takes 0.025 s. Pokémon Pokopia's 131,426 shaders: about 9 hours on an M4 Pro (seedds/nxnative#1036). - Cause: a translated shader's argument buffer names several texture types, and Metal's texture classes are large templates. The compiler's module cache holds the templates but not their instantiations, and each shader is a new
metalprocess, so it instantiates them again, along with amemory_coherence_devicecopy of each it uses: 722 of a typical shader's 902 ms of front end by-ftime-trace, against about 180 ms for the shader's own text. Declaring the argument buffer alone took 0.37 s of that shader's compile. - Fix:
dm/gfx/tools/dmsh_pch.pymakes one precompiled header per compile convention at a process's first compile (dmsh_build.pyasks for them before it forks its workers), holding those instantiations, anddmsh_build.pyandios_metal.pycompile with-include-pch. The header adds only the two includes the sources start with and declares no name, and a class left out of it costs only time. The output is byte-identical, so the compile records and the Metal compile cache's keys stay as they were.makechecks this on a test shader and builds without the header if a compiler differs, and a compile that fails with the header runs again without it, so a failure reports what a plain compile reports.DMSH_PCH=0turns it off. The Vulkan and OpenGL shader tools (vk_shaders.py,gl_shaders.py) do not use it. - Measurement: cold builds of 1,019 Pokopia shaders on an M4 Pro (
J=10, with other jobs on the Mac): Mac child processes 2,343 to 975 s of CPU, wall 253–263 s to 176–182 s; iOS child processes 981–1,077 to 574–605 s, wall 179–233 s to 130–153 s. At that rate the whole Mac map would take about 6.4 hours instead of about 9 (not run). All 37,611 Mac files of 8,157 Pokopia shaders and all 3,675 iOS files of 1,020 came out byte-identical with and without the header, as did 1,600 compiles of eight games' shaders. - Open: wall time fell less than CPU, as the builder's Python took about 0.12 s a shader under the GIL (Rewrites that try every character of a large source lowered that).
- Found on: Pokémon Pokopia.
- Check:
test_shader_pch.py.
Rewrites that try every character of a large source
- Symptom: the shader step of a game with large translated sources has fewer Metal compiles running than
Jasks for, anddmsh_build.py's own process stays busy on one core between them. Pokémon Pokopia's sources average 220 KB, and the builder spent about 0.12 s of Python on each shader, all but its system calls under the GIL, which alone would have come to about 4.2 hours of its full build. - Cause: patterns with no literal start, which
recan only try at every character:_onceindmsh_fetch.pybegan with a lookbehind and ran 24 times a pixel shader at about 4 ms (38% of the Python, on shaders that mostly make no variant), the attribute pattern ran on every shader though only vertex shaders have attributes, and patterns beginning\bor an alternation did the same inreflect,fs_uintandcheck_msl.dmsh_side.py_closelooped in Python over each character of a function body, anduses_image_atomicsover each SPIR-V instruction. - Fix: the same questions, answered from the text:
str.findand a look at the character before it (_once,has_word), one pass over a shader's stores instead of one for each output (fs_uint), the lines that hold attributes (attributes), bracket to bracket (_close), and a test for a word every match must hold before the pattern runs (check_msl,uses_image_atomics). The outputs are byte-identical. - Measurement: cold builds on an M4 Pro, old and new taking turns, never on a quiet Mac. Pokopia's 8,157
shader_seen.tsvshaders, Mac and iOS (J=14, load 9 to 19): wall 1,426 to 607 s, the builder's Python 1,121 to 463 s of CPU. 1,001 of them, Mac only:J=14at load 5 to 8, wall 141 to 68 s, Python 116 to 52 s;J=14at load 26 to 39, wall 194 to 94 s;J=10at load 31 to 64, wall 177 and 173 s to 92 and 93 s, Python 150 to 160 s to about 49 s. The child processes' CPU stayed about the same (4,842 to 4,789 s on the 8,157; 2 to 13% more on the 1,001, with more compiles running at once). At those rates the whole Mac map at the NSP script'sJ=14would take about 2.5 hours instead of about 5 (not run). Identical: all 31,836 Mac and 23,678 iOS files of those 8,157, andregress.py chainon all of Breath of the Wild's 19,592 shaders (0 changed); old against new, step by step, 0 differences on 27,325 sources of seven games, 8,197 of their fetch variants among them. - Open: a pool of worker processes for the finish step gained only 6 to 8% more on top of this here (1,001 shaders,
J=10andJ=14, also with half the compiles modelled) and was not built then; on Macs with more cores it gained much more, and the build now has one (A shader build's Python finishes one shader at a time).posix_spawn(close_fds=False) takesPopenfrom 13 to 3 s, but withoutpipe2on macOS another thread's child can inherit a pipe and hold up its reader, so it would need a lock around every launch. The reflections a full build keeps (about 2.5 GB for Pokopia) raise the cost of each fork (of each child the build launches; its worker processes are forked once, before the first result); a micro-benchmark gives 0.7 ms at 176 MB and 1.8 ms at 2 GB, and no full map has been timed. - Found on: Pokémon Pokopia (resolved).
- Check:
test_shader_rewrites.py, which also holds each replacement to the pattern or loop it replaced on random text. - Further scan reductions:
uniform_testsstarts its pattern withas_type<so the regex engine can skip to casts. The lookbehinds still check the characters before each cast, with the same match spans and captures.select_guardsalways checks for inline guards and scans for leftover choices only when it found size-comparison variables. The gather-offset and threadgroup-fence rewrites skip their patterns when the required helper name is absent. The rewrite tests cover matches, no-ops and errors. - Rewrite CPU (PR #2897): Measured on final MSL from a built library, where most scans find nothing. On an M5 Pro with Python 3.13, the 16 measured passes used 16.97 to 7.76 s for Breath of the Wild's 10,560 pixel shaders, 24.17 to 11.22 s for Pokémon Scarlet's 15,006 and 27.65 to 13.53 s for Tears of the Kingdom's 11,969. The estimated savings were under 1% of total shader-build CPU for those three games. On an i7-10700K, dpadr measured 61.6 to 39.8 s for 2,018 sampled Ocarina of Time shaders. The PR's static chain comparison found identical MSL, reflections and variants for all 19,592 Breath of the Wild, 30,142 Pokémon Scarlet and 28,669 Tears of the Kingdom shaders. Ocarina of Time's 42,848 MSL files were also identical.
select_guardsscans: After those reductionsselect_guardswas the largest of the 16 passes (4.5 of 7.8 s for Breath of the Wild's pixel shaders), and its time went to patterns tried at every character.reskips through text only to a pattern's literal start. The two size comparisons began with\b, the choice pattern is an alternation whose first form begins with a lookbehind, and the leftover-name pattern begins with one, so each ran at every character: about 10 ns a character on a source without bounded reads and 35 ns with them (M5 Pro), at any source size. The comparisons now begin with the textbool, and a lookbehind over that text stands for the\b. Choices and leftover names are tried only where a match can start: at the last_before? (*spvDescriptorSet0.or before?, and at a parenthesis before it. The pattern itself decides there, so the matches, their order and the result are those ofsubandfinditer.GuardScansintest_shader_rewrites.pyholds each scan to its earlier pattern on random text. Measured on final MSL from built libraries (M5 Pro, Python 3.13): 4.66 to 0.32 s for Breath of the Wild's 10,560 pixel shaders, 6.72 to 0.47 s for Pokémon Scarlet's 15,006 and 8.22 to 0.53 s for Tears of the Kingdom's 11,969. Estimated for a whole build (every shader once, cut at its second entry point, each bounded read's select written back as the choice so the rewrite fires): 12.9 to 1.1 s, 19.8 to 1.6 s and 22.0 to 1.7 s, under 1% of shader-build CPU. Old and new gave the same output or error on all 78,403 final sources of the three libraries, on the 19,146 with selects written back (698,877 selects) and on 40,000 random sources. Open: not measured on Ocarina of Time's sources or in a whole build; bounded storage reads are rare in these libraries (249 comparisons, in Tears of the Kingdom's vertex shaders), so the tests hold most of that form.
A shader build's Python finishes one shader at a time
- Symptom: a cold shader step leaves about half the cores idle whatever
Jis, anddmsh_build.py's own process stays at one full core from start to end. Ocarina of Time's whole Mac map, 42,848 shaders: 3,506 s on an M3 Max with 16 cores (J=16, the build at 104% CPU, 4 to 5 cores busy in all), 3,002 s on an M5 Max with 18 cores. - Cause: two. Finishing a shader (the MSL rewrites, its reflection, its outputs and the cache) is Python, about 40 ms a shader on Ocarina of Time, and the threads that did it share one GIL, so one core finished every shader while the Metal compiles the threads waited on left the others idle (Rewrites that try every character of a large source lowered that cost; free-threaded Python 3.14t was slower, not faster). And the shaders went in batches of
4 × J: the next batch started when the slowest shader of this one was done, with every other thread idle. - Fix:
dmsh_build.pyfinishes the shaders inDMSH_PROCSworker processes (defaultJ; 0 finishes them in threads, as before). The workers are forks of the build, made once, after the cache check and before its first thread, so they have every table and fingerprint it read; spawned workers would run the script again, and its start clears the outputs. No worker openscas.db: the build makes their cache calls on its one connection (A forked shader worker dies opening the compile cache; as first written each opened its own). The precompiled Metal headers are made before the fork, or each worker would make its own. The build still translates the batches itself and hands a worker each shader's job; the worker's result and counts come back and are added in batch order, so the summary, the progress file and every output are those of the threads. The next batch is handed out before this one is done (two at most), so no worker waits for a batch's slowest shader; paired vertex shaders still wait for every other shader (vs_padreads their pixel shaders' MSL). A worker that dies stops the build with one[RED]line. The outputs are byte-identical; the change is to the chain's code, so it changes the chain version once. - Measurement: cold builds, empty cache, each against the main it was written on.
- Ocarina of Time's whole Mac map on the M3 Max (
J=16): 3,506 to 1,826 s; with every shader restored from the cache 888 to 191 s. Every 8th key (9,133 shaders): 544 to 292 s, 6.4 to 13.4 cores busy; 417 s in threads with the batch overlap alone; 403, 400 and 388 s with 12, 16 and 20 workers. - An M6 with 12 cores and 16 GB (
J=12, another game running beside it). Red Dead Redemption's 3,628 shaders: Mac 54 to 35 s, Mac and iOS 84 s to 53 and 63 s; with every shader restored from the cache 11 to 13 s (the headers are made though nothing compiles). 1,920 of Metroid Prime 4: Beyond's shaders, whose compiles are much longer: 105 to 72 s, and 89 s withDMSH_PROCS=6. - Memory, the summed resident size of the build and everything it runs, sampled every 0.5 s on the M6 (it counts the pages the forks share once for each): Red Dead Redemption 0.45 to 0.8 GB, the Metroid Prime 4 shaders 1.1 to 3.4 GB, and 2.0 GB with
DMSH_PROCS=6. A worker itself held about 35 MB; the rest isJcompilers running at once, which the threads never reached. With a header made in each worker, as first written, Red Dead Redemption's build peaked at 1.4 GB. - Identical apart from the chain version and
_b_cas.txt: all 173,316 files of Ocarina of Time's map, and Red Dead Redemption's Mac and iOS libraries (15,542 and 11,912 files). - Another design, measured and not taken (PR #2035): the build as
J / 3copies of itself, each with a share of the shaders. Ocarina of Time's map on the M5 Max 3,002 to 1,298 s, and 1.41 times faster on an M3 Pro with 11 cores for 1.3 GB more; on the M6 it gained less than the forked workers (Red Dead Redemption: Mac 75 to 58 s, Mac and iOS 104 to 95 s, against its own older main) and compiled about 9% of the Metal sources twice.
- Ocarina of Time's whole Mac map on the M3 Max (
- Open: not measured on a Mac with 8 GB, where
DMSH_PROCSbelowJtrades the gain for memory, nor a whole large map with iOS libraries. Two workers can compile the same Metal source at once (about 10 of Red Dead Redemption's 2,159 compiles), which costs time only. - Found on: The Legend of Zelda: Ocarina of Time.
- Check:
test_shader_cache.py(test_forked_workers_share_it),test_shader_toolchain_cache.py(the batch loop with a substituted translator).
A forked shader worker dies opening the compile cache
- Symptom: the Mac shader step stops a few seconds after it starts, every time, with
concurrent.futures.process.BrokenProcessPool(since 8b55ebb3; the[RED] a shader build worker process stoppedline once the build prints it), andDMSH_PROCS=0builds. The worker's crash report:SIGSEGVin_os_log_preferences_refresh←os_signpost_enabled←os_signpost_id_make_with_pointer←openDatabase(libsqlite3.dylib) ← Python'ssqlite3. Only with a Python whose_sqlite3module links Apple's/usr/lib/libsqlite3.dylib(otool -Lon_sqlite3.__file__): Xcode's, and by the reports some Python 3.12+ builds; Homebrew's Python has its own SQLite and builds. - Cause: Apple's SQLite calls
os_signpostwhen it opens a database, and Apple's logging does not survive a fork without an exec once the process has used it: the child reads the parent's logging preferences at an address it does not have. The build openscas.dbat its start, and each forked worker opened a connection of its own (Store.forked). The same on macOS 27.0.1, 27.2 and 27.3, any game;OS_ACTIVITY_MODE=disabledoes not prevent it. A fork whose parent had opened no database opens one without harm, but the build needs the cache before its tables are complete, so the fork cannot come first. - Fix: only the process that opened the cache uses it (
shader_cache.Served). Each worker has a pipe to a thread of the build, which makes the worker's calls (get,has,names,put,delete_prefix, a batch) on the one connection under its lock, where the worker's thread stood when shaders were finished in threads; files are read and written by the worker (put_file,to_file). A worker's batch is its thread's transaction: whole or absent, and rolled back when the worker dies inside it. The workers stay forks, which is safe while they call nothing of Apple's frameworks themselves: their compilers and tools are exec'd. - Measurement: Cuphead's 3,118 shaders on an M4 Pro (
J=14, Homebrew's Python, an external drive), against main's workers with a connection each: an empty cache 49.5 and 44.9 s to 50.1, 53.3 and 47.4 s (61.8 s in threads), every shader restored from the cache 18.3 and 18.4 s to 18.8 and 16.7 s; the runs differ by more than the two designs do.regress.py chainon Cuphead: 3,131 of 3,131 shaders the same. - Open: the reporters' Python builds are not confirmed (asked on the issue). Workers that are spawned, which would not depend on what a fork may call, were weighed and not built: each would read the build's tables again, which a fork shares. Up to the fork point the build takes 0.4 s and 58 MB on Cuphead and 3.7 s and 346 MB (peak resident) on Ocarina of Time's map, against about 35 MB for a forked worker, so 16 spawned workers there would hold up to about 5.5 GB instead of 0.6 GB; and
dmsh_build.pywould have to become a module whose start does not run a build (134 statements at its top level, the output clearing and the cache check among them). - Found on: DRAGON BALL: Sparking! ZERO (issue #2354; also Ocarina of Time on macOS 27.3, issue #2362's side note).
- Check:
test_shader_cache.py:test_forked_workers_with_apples_sqliteruns the forked workers under/usr/bin/python3when its SQLite is Apple's (with a connection in each worker, all of them are killed),test_worker_dying_in_a_batch.
A library that depends on its source's file name
- Symptom: two builds of the same shaders give different
_blor_bflibraries for some keys, of the same size, 46 bytes apart, while their MSL is the same. A byte comparison of two library folders reports them, andregress.pycan report them as changed variants. - Cause: clang names a source's static initializer after its file (
_GLOBAL__sub_I_<key>_bl.metal), and any function constant brings one, so the name and the library's stored hash change with the file's base name (its folder does not matter). Sources without function constants do not depend on it. The MSL-keyed Metal cache takes the same text for the same bytes, so shaders that share a source took the library of whichever compiled first, or their own when they compiled at once. In Breath of the Wild 3,936 of 10,560 pixel shaders share their_blsource and 1,710 their_bfsource. - Fix:
dmsh_pch.compile, which every compile of a shader library goes through, passes the source on standard input (-x metal -), so no file name reaches the compiler. Metal's messages then say<stdin>, and a failed compile also prints the source's path. Libraries from an earlier compile keep their bytes in the Metal cache: a cold build differs from them once, in_bland_bf. The compile records and the chain version did not change, as the code the libraries hold did not._checkindmsh_mtlcache.pysamples only_b, and the offline pipeline archive leaves function constants to the device, so neither ever saw the difference. - Measurement: cold builds at
J=4andJ=14of 471 Breath of the Wild shaders chosen from shared sources: 15 of 2,595 Mac files and 13 of 2,123 iOS files differed, all_bl; with the source on standard input none did. Pokopia's 1,001 atJ=6andJ=14: none of 4,581 Mac and 3,579 iOS files. - Found on: Pokémon Pokopia (resolved), The Legend of Zelda: Breath of the Wild (resolved).
- Check:
test_shader_pch.py(test_a_mac_library_does_not_depend_on_the_source_name,test_each_run_reads_the_source_from_its_start).
One compile for a pixel shader's side entry points
- Symptom: the Mac or iOS shader step of a game with many pixel shaders spends most of its Metal compiles on libraries that few draws load: Pokémon Pokopia's whole map took 366,805 compiles, about 57% of them for
_baand_bl, and its runs opened none of the 5,775 of each. - Cause: the alpha test and the logic operations were each a whole copy of a pixel shader in a library of its own, compiled apart. Every pixel shader needs them, since which ones draw with either shows only in play: Xenoblade Chronicles 2, Skyward Sword HD, Dark Souls Remastered. Nothing in a game's files tells: every NVN game's binary names both functions, since the loader lists them all. A list per game would turn a miss into a wrong picture (The alpha test through a library of its own, Logic operations through a library of its own), and compiling at run time has no
-O1: GPU code grew by a median of 12% and up to 59%, Default and Size alike, and-O2took Odyssey'salRenderMaterialUber25 minutes. - Fix:
dm/gfx/tools/dmsh_side.pymakes one compile unit from a pixel shader's source: each entry point's body once, as a static function, and thin entry points around it, the shader's own and<entry>_a(dmsh_alpha.py) and<entry>_l(dmsh_logic.py).metallibgives every entry point a complete module whether or not the body is shared, andmetal-ttcompiles every unspecialized entry point of a library, which made the pipeline archive twice as large (1.85 to 3.84 MB for 25 bases). Socutsplits the library in two,<key>_bwith the shader's own entry points (+0.6% of archive) and<key>_bxwith the others, loaded on first need (at_fn,lo_fn). A cut of one function is byte-identical tometallib --function-name, which takes only one name. The Metal cache keeps both pieces under the unit's digest (compile_split), so outputs stay clones.<key>_b.metalstays the plain source, anddmsh_mtlcache.pyfill leaves out a library with a_bx, which was not compiled from it. A shader whose unit does not build gets its base from the plain source, no side library and a red line, and the host draws it without them. The readable-tile entry is a third piece of that same compile (Cold Mac shader builds compile each pixel shader more than once). - Cost: a shared body changes the inliner's decisions (a helper now has two callers), so
main0is no longer byte-identical: GPU code +2.1% at the median and +3.7% at most, on 125 shaders of six games on an M4 Pro, pipeline builds 62.5 against 60.6 ms. Keeping<key>_bas it was with a second compile for<key>_bxwould cost 66-68% of the three compiles' CPU instead of 34-36%. - Measurement: Metal CPU per pixel shader on 125 shaders of six games, three compiles to one: Pokopia 1.503 to 0.512 s with the Mac's flags and 0.830 to 0.285 s with the iPhone's; the others 0.324 to 0.114 s and 0.245 to 0.087 s. Cold builds of 1,021 Pokopia shaders (
J=10, other jobs on the Mac): Metal compiles 2,444 to 1,095 on the Mac and 2,445 to 1,094 for iOS; the whole build's CPU 1,399 to 670 s and 959 to 451 s; wall 273 to 195 s and 232 to 127 s; libraries 359 to 358 MB. All 1,021_b.metalcame out unchanged, and their reflections but for the chain version and the entry point names. Not measured on a device. - Found on: Pokémon Pokopia.
- Check:
test_dmsh_side.py,test_dmsh_alpha.py,test_dmsh_logic.py,make check_t_alpha,make check_t_logic.
Cold Mac shader builds compile each pixel shader more than once
- Symptom: the first Mac shader build of a title, with an empty output directory and CAS and no keys, takes tens of minutes while
JMetal workers stay busy. On an Apple M2 MacBook Pro atJ=8, Mario Kart 8 Deluxe took 22:46 (1366 s) and Super Mario Odyssey 30:02 (1802 s). - Cause: a pixel shader's code went through the Metal compiler several times. The readable-tile version
<key>_bfwas a source and a compile of its own (fetch_finish): 13,666 of Mario Kart 8 Deluxe's 29,651 shaders and 10,512 of Odyssey's 27,984. The integer entry pointsmain0_u/main0_m(fs_uint) and the dual-sourcemain0_d(fs_dual) were each a copy ofmain0's body, which the compiler built again for each: 4,990 of Pokémon Legends: Arceus's 6,160 pixel shaders havemain0_u. And each compile launchedmetalandmetallibthroughxcrun, which looks the tool up again every time (about 4 ms a launch). - Fix: for every game.
dmsh_side.shared_bodymakesmain0's body onealways_inlinefunction,dm_body_main0, whichmain0,main0_uandmain0_dcall.dmsh_fetch.foldrewrites the rewritable samples in that body alone, as(fx_i == k ? fb_k : sample)withfx_iandfb0–fb7parameters of the body, and addsmain0_f, which passes its function constants and the tile's colours; every other caller passes -1 and zeros, which the inlined body folds back to the plain sample, somain0and the side entry points declare no function constants.ps_librariescuts<key>_b,<key>_bxand<key>_bffrom the one compile (dmsh_side.cutwith groups,dmsh_mtlcache.compile_splitwith a list); the host'sbf_fnloadsmain0_f. What does not build is left out alone: a unit whose readable-tile version does not build is compiled again without it, one that does not build at all gives the base from the plain source, each with a red line. A shader with no rewritable sample getsmain0_fonly when its key is inbf_want.tsv, as before.dmsh_build.pyfindsmetalandmetallibonce (xcrun -f) and passes-isysrootwith the SDK, which gives the same.airand.metallibbytes asxcrun -sdk macosx;MAC_RECORDstill names thexcruncommand. Two consequences: a library cut with a_bfis not taken bydmsh_mtlcache.pyfill (its base was not compiled from its.metal), anddmsh_side.pyis part of the shader cache key (CODE_FP), sincefs_uintandfs_dualcall it when a shader misses the cache. - Measurement: cold builds,
own_compilers,DMSH_TARGETS=mac, no keys,J=8, Apple M2 MacBook Pro, of PR #1520's first form (the same fold, with copies still inmain0_d): Mario Kart 8 Deluxe 22:46 (1366 s) to 14:47 (887 s), 1.54×; Super Mario Odyssey 30:02 (1802 s) to 22:23 (1343 s), 1.34×; every shader built in both. Metal CPU on 60 of Odyssey's pixel shaders (Apple M6): 25.8 to 13.6 s for 40 with a readable-tile version (0.53×), 30.5 to 19.6 s for 20 with integer entry points only (0.64×;007d7e411ef14ebd24.5 to 13.6 s); the fold applied to the same 60 shaders as before;main0's bitcode 5.7% smaller at the median and 0.7% larger at most. Thexcrunlookup was about 4 of a launch's 10 ms with 2 GB resident; launching withposix_spawninstead ofsubprocesssaved another 0.4–1.2 ms, which is not worth code of its own. Partial cold builds of the same pixel shaders on the previous chain and this one (Apple M6, translation included): Pokémon Legends: Arceus 239 in 24 to 18 s, Metroid Prime Remastered 182 in 26 to 19 s, each shader with the same libraries, entry points, side and readable-tile records and reflection, none failing (MPR'sab809a7456f59614has bothmain0_dandmain0_f). GPU code and pipeline build time not measured. - Found on: Mario Kart 8 Deluxe, Super Mario Odyssey.
- Check:
test_dmsh_fetch.py(OtherEntryPoints: amain0_d, a copy of the body and a compile unit besidemain0_f;OutputMappingOnly),test_dmsh_side.py,test_shader_toolchain_cache.py,make -C dm/gfx/tests GAME=<id> check_t_feedback check_t_alpha check_t_logic.
One compile for a vertex shader's libraries
- Symptom: a cold Mac or iOS shader build spends most of its Metal compiles on vertex shaders' copies of one body. Breath of the Wild's 19,592 shaders took 21,552 compiles, 2,405 of the build's 3,692 CPU seconds (240 s of wall on an M5 Pro at
J=18): 839 s of that went to pulling libraries and 109 s to shadow-input libraries, each a second and third compile of a body<key>_balready holds three times. - Cause: a vertex shader's body went through the optimizer nine times in two compiles, twelve in three for a shader with integer inputs.
<key>_bheld it inmain0,main0_z(vs_depth) andmain0_gs(dmsh_geometry.capture); the pulling library<key>_bp(dmsh_pull.py), a source and a compile of its own, inmain0,main0_zand twice in each wide-line entry; the shadow-input library<key>_bv(dmsh_vin.py) in three more. A pixel shader's entry points had the same shape before One compile for a pixel shader's side entry points. - Fix: for every game.
dmsh_side.vs_unitmakes one compile unit of a vertex shader that has a pulling library: the body once, asdm_vs_body,always_inlinein the entry points pipelines are made of (main0,main0_z, the pullingmain0_p/main0_zp, the shadow-inputmain0_v/main0_zv), and one out-of-line copy,dm_vs_body_o, for the entry points few draws take: the wide-line entriesmain0_wl/main0_z_wl, which ran the body twice each, and the capture entrymain0_gs(dmsh_geometry.capture), which calls it and writes its capture epilogue (144 stores) once after the call, where its copy of the body had the epilogue at every return.vs_librariesindmsh_build.pycompiles the unit once a target and cuts<key>_b,<key>_bpand<key>_bvfrom it (dmsh_side.cut,dmsh_mtlcache.compile_split), so each library holds the entry points it held and<key>_b.metalstays the plain source. One unit cannot name its entry points allmain0: the reflection'spullandvinname them, and the host (side_entryinnvn_mtl.m) andpso_offline.py(vertex_entry) read the names. What stays as it was:- The rarer entry points (
main0_discard,main0_tf, the layer ones) are whole copies of the body, as ismain0_gswhenvs_viewport_maskculls the raster entries while capture stays unculled. - A shader without a pulling library (no stage input, or one
dmsh_pull.variantdoes not fit) compiles its plain source. - A shader with layer entry points keeps
<key>_bva compile of its own: that library repeatsmain0_lfor the host (vin_fn), and one unit cannot hold it twice (8 of Pokémon Scarlet's shaders, none of the two Zelda games'). - With
DMSH_IOS_PULL=0the iPhone's unit leaves the pulling entry points out, and with no shadow-input library either its<key>_bis the plain source's compile. - A unit that does not build, or a source of a shape
vs_unitdoes not know, gets the three compiles with a red line (its libraries do not build from one compile). None of the 38,402 shaders tested used this fallback. Amain0_gsthat is not the body with its capture epilogue at every return is such a shape; none of the 25,286 units of Breath of the Wild, Tears of the Kingdom and OCTOPATH TRAVELER II has one.dmsh_mtlcache.pyfills the standalone cache from earlier builds. Each target's reflection recordschain_metal_cutwhen its base came from a unit, so the cache skips that base even after iOS packing removes its pulling library. A synthetic test packs that image with two standalone shaders that pass the cache's sample check and verifies that a later standalone compile produces its own library.
- The rarer entry points (
- Forms measured and not taken:
- The body as a plain
staticfunction that every entry point calls is one optimization of the body for all of them (64% less Metal CPU a vertex shader, against 41%), but the GPU compiler then decides the inlining for each pipeline:main0's bitcode grew 4% at the median and pipeline builds took 1.3 to 3.7% longer. Not without a measurement on a device. - The out-of-line copy is never
noinline. Marked so and shared withmain0_gs, it changed that entry's captured words in 24 of 52 shaders, by up to 12,544 units in the last place.
- The body as a plain
- Cost: every output of the entry points pipelines are made of, and of the wide-line ones, is bit for bit what the three compiles gave (Measurement).
main0_gsis the exception. Its captured words are the plain source's when both are compiled in Metal's safe math mode without contraction (-fmetal-math-mode=safe -ffp-contract=off); in the relaxed mode the Mac and the iPhone build with, a few low bits of a few shaders differ, because the GPU compiler fuses a multiply and an add into onefma(one rounding instead of two) in other places in the call than in the copy. A capture entry returns nothing and has no invariant position, so-fpreserve-invariancedoes not hold it tomain0_zeither. It runs only for draws with a geometry shader or tessellation (geo_prep,nvn_tess.inc) and forDM_NVN_VSDUMP. The libraries are not byte-identical. Entry point by entry point, over the 38,402 shaders of three games:main0_discard,main0_tfand the layer entry points are the same bitcode in every shader;main0_zin 36,250;main0in 7,628, since it applies the depth line once, after the call, where the copy had it before every return (0.3 to 0.4% smaller at the median, between 2.4% smaller and 0.8% larger); the pulling and shadow-input entry points have other names, within 1.2% smaller and 0.5% larger; the wide-line entries, which call the out-of-line copy, between 3.4% smaller and 7.3% larger (0.1 to 0.3% smaller at the median).<key>_bvis half its size (Breath of the Wild's 50.1 to 27.0 MB): it no longer repeatsmain0_gs. Againstmain0_gsas a whole copy, over the 25,607 vertex shaders of Breath of the Wild, Tears of the Kingdom and OCTOPATH TRAVELER II: every other entry point is the same bitcode, andmain0_gs, which now carries the shared copy, is 41 to 51% smaller at the median where the body returns more than once and 1 to 3% larger where it returns only once, which leaves no epilogue to share. Those units still compile 6 to 10% faster (one copy fewer for the optimizer), so one rule serves both shapes.<key>_bis 21% smaller in Breath of the Wild (565.4 to 448.1 MB) and 27% in Tears of the Kingdom (1,134.2 to 830.0 MB); in OCTOPATH TRAVELER II, whose vertex shaders all return once, 0.5% larger (104.0 to 104.5 MB). - Measurement: on an M5 Pro, macOS 26.7.3, GPU
applegpu_g17s.- Metal CPU for a vertex shader's libraries (compile and link, the best of three, 40 shaders evenly spread a game): Breath of the Wild 216.3 to 127.0 ms with the Mac's flags (41.3% less) and 218.4 to 128.1 ms with the iPhone's; Tears of the Kingdom 225.7 to 135.3 ms (40.1% less) and 225.3 to 135.5 ms.
- A cold Mac build of Breath of the Wild (
own_compilers.py,DMSH_TARGETS=mac,J=18, an idle Mac), the commit before against this one: wall 240.4 to 188.8 s, CPU 3,692 to 2,859 s, Metal compiles 21,552 to 13,957 (2,405 to 1,685 s), links 21,550 to 13,955 (413 to 311 s). All 8,888 shaders with a pulling library came from a unit. regress.py chainon Breath of the Wild, Tears of the Kingdom and Pokémon Scarlet: every shader builds on both sides (19,592, 28,669 and 30,142), no MSL changes, and the reflections and side libraries of 8,888, 14,549 and 14,965 vertex shaders change (the names); no pipeline base's interface fails.- On the GPU, 26 vertex shaders of each Zelda game (16 evenly spread, the 4 largest sources, 6 more with integer inputs), 2,000 random triangles each (6,000 vertices; random but valid buffers, uniforms and textures, not the games' own data), 512 × 512: the depth image and every
float4output ofmain0,main0_z,main0_pandmain0_zp(26 of 26 shaders a game) and ofmain0_vandmain0_zv(13 of 13 and 9 of 9) are bit-identical to those of the plain source'smain0/main0_z; so aremain0_wl's images (26 of 26). Controls:xone unit in the last place larger is seen in 49 of the 52 shaders, the depth line's 0.5 one unit larger in all 52. main0_gscalling the body, against the whole copy (upstream806fabe1, each tree's ownvs_unit), Metal CPU for a vertex shader's unit (compile and link, the best of three, 40 shaders evenly spread a game): Breath of the Wild 144.8 to 116.6 ms with the Mac's flags (19.5% less) and 147.1 to 118.7 ms with the iPhone's; Tears of the Kingdom 154.7 to 121.7 ms (21.3% less) and 153.8 to 121.8 ms; OCTOPATH TRAVELER II 144.6 to 130.0 ms (10.1% less) and 144.6 to 129.0 ms.- The same, a cold Mac build of Breath of the Wild: wall 197.5 to 183.2 s, CPU 2,870 to 2,614 s, Metal compiles 1,841 to 1,605 s (13,957 and 13,956), links 327 to 311 s.
- The same,
regress.py chainon Breath of the Wild, Tears of the Kingdom and OCTOPATH TRAVELER II: every shader builds on both sides (19,592, 28,669 and 13,980), no MSL, reflection or side library change, no interface failure; 8,888, 14,549 and 1,849 units, none fell back. - The same program by its text, in every vertex shader of those three games (8,931, 14,766 and 1,910):
main0_gs's parameters aremain0's and the capture's own (dm_vid,dm_iid,dm_gs), its prologue isdmsh_geometry.capture's, its epilogue reads onlyout,dm_gsanddm_p, which the body never names, and the body returns onlyreturn out;. - On the GPU, 200 vertex shaders evenly spread of each Zelda game and
0ef972796032c959, 12 seeds of 6,000 random vertices, every run with a control whosexis one unit in the last place larger after the call (a seed counts where the control is seen; 3 shaders the harness cannot drive, 398 reached): compiled-fmetal-math-mode=safe -ffp-contract=off, every captured word of the 398 is the plain source's. With the relaxed flags 385 are, and 13 differ in low bits: 8 in Breath of the Wild by up to 63 units in the last place, 5 in Tears of the Kingdom. In four of those five, relaxed math alone moves the plain source's words further from its strict compile than the call does (0ef972796032c959: 186 words of 18 of 6,000 vertices, up to 1,778 units in the last place, against 4,888 words, up to 1,865,292). In71beca95388ae452, whose plain source relaxed math leaves as strict, positions of about 10 differ by up to 7.63e-6; its counts in units in the last place come from components near zero. 12 of the 13 bodies return more than once. With-ffp-contract=offalone the words are the plain source's, and writing the source's two contractible multiply-adds (the border lerpdm_bmix) asfmaleaves the differences as they were: the GPU compiler's late contraction (theinvariance-late-contractattribute) fuses other multiplies and adds in the call than in the copy. - OCTOPATH TRAVELER II's route (
regress.py check, one run each, 440 s): both reach the target and draw its 129,032-triangle point light shadow through the geometry compute path (97 such draws up to frame 22,200 on each side), 59.8 fps both, frame p99 17.12 and 17.27 ms, no new red line, screenshots within 1 bit of dHash. - Open measurements include iPhone GPU comparisons, device pipeline build times and production archive sizes, and a game that draws a vertex shader with more than one return through
main0_gs.
- Found on: Breath of the Wild, Tears of the Kingdom, OCTOPATH TRAVELER II (the capture entry in a game's draws).
- Check:
test_dmsh_vsunit.py(the unit's text,main0_gscalling the out-of-line copy, its cut libraries on both compilers, a rarer entry point byte for byte the plain source's, the build step with its fallbacks),test_shader_toolchain_cache.py(the Metal cache's fill),test_pso_offline.py;make -C dm/gfx/tests GAME=<id> check_t_vs_unit(every entry point of a unit against the three compiles on the GPU, with a control;main0_gscompiled strict, word for word the plain source's, with a control whosexis one unit in the last place larger),check_t_pso_bundle(the reflection's names in the host and the offline archive),check_t_pull_inv check_t_wline check_t_vin.
Concurrent warm tasks prepare each shader once
- Symptom: startup tasks can prepare the same shader more than once, even though only one object enters the warm dictionary. A measured Tears of the Kingdom startup avoided 320 duplicate preparations; this is not a steady-frame-rate claim.
- Cause: an
Stask and anRtask, or two shader pairs, can miss the same key before either publishes.shader_loadand the pulling-entry preparation used to run independently for each miss. Discarding the losingNvShaderdoes not undo the strong function-descriptor registrations (fn4_note,fn_spec) or constant-bank reservations (c1_store). These ownership mechanisms are deliberate; source inspection alone does not establish a leak or its size. - Fix:
warm_shaderinstalls a per-keyWarmLoadunder the dictionary lock. The owner prepares the library, reflection, functions, argument encoder, c1 storage and optional pulling entry outside that lock, then publishes before releasing its waiters. A cached lookup allocates nothing. Other keys can prepare concurrently. A failed warm load staysNSNullonly for that prewarm, matching the previous warm-call behavior;warm_finishdrops warm dictionaries after all tasks join, and demand loading retains its existing retry behavior. This does not coalesce demand/prefetch loads racing a background prewarm (DM_PSO_PREPARE=0), nor merge layer variants. - Measurement: a Tears of the Kingdom startup probe observed 1,537 distinct shader keys. The old racing path performed 1,857 preparations and discarded 320 successful duplicates; per-key coalescing performed 1,537 preparations and discarded none. Observed startup times were 6.63 s before and 6.51 s / 7.15 s with coalescing, so these runs establish duplicate avoidance, not a wall-time improvement or a memory leak. A Breath of the Wild 1.9.0 probe on the same Mac and chain went from 844 preparations of 819 keys to 819, at 3.07 s before and 2.78 s / 2.83 s with coalescing: the same limit applies.
- Found on: Tears of the Kingdom, through source review of the shared prewarm lookup/load/publish path and a normal-start Mac probe; Breath of the Wild, the same probe.
- Regression seam:
t_pso_warmparses actualSandRmanifest tasks sharing a vertex key and gates the first realMTLDevicelibrary load. A test-owned dictionary proxy observes the second same-key lookup under the production dictionary lock before the owner is released; a third key must finish independently while the owner is held. Actual device library-load counts check that the shared key is prepared once and cached hits do not reload it; both callers retain one shader identity. It also checks warm negative caching and a later successful demand retry after reflection appears. The existingcheck_t_pso_warmtarget runs both MTLDevice and Metal 4 paths.
A prebuild pool sized from the Super cores
- Symptom: the Mac's pipeline prebuild (
DM_PSO_PREBUILD=tool, the NSP script'spso_prebuild.log) runs on far fewer workers than the Mac has:1 workerson an M6, where Metroid Prime Remastered's 20,233 pairs took 1,725 s and Link's Awakening's 17,742 took 667 s, and 4 on an M5 Pro, where Donkey Kong Bananza's 21,225 took 6.5 to 7.5 minutes. - Cause: each worker waits on one synchronous compile, and the tool's pool was the "performance cores" less one, read from
hw.perflevel0.physicalcpu. On the chips with three core levels, level 0 is only the Super cores: 2 on an M6 (beside 4 Performance and 6 Efficiency), 5 on an M5 Pro (beside 10 others). Metal runs 6 and 14 compiles at once there (maximumConcurrentCompilationTaskCount). - Fix: the tool has
maximumConcurrentCompilationTaskCountworkers (compile_tasks; the active cores where Metal gives less than 2).DM_PSO_PREBUILD_THREADSstill sets them. The prepare step keeps the active cores: extra workers only wait, and no iPhone has reported its count. Open: one rule for both pools needs an iPhone's count and first-start time. The background pools (pp_bg_queue, the prebuild without a prepare step) still take a share of level 0, one queue on an M6; nothing has been reported from that. - Measurement: M5 Pro, macOS 27.0 (26A428), the prebuild tool on Bananza's app libraries (chain
2612ffd16287) with hosts built from that app's commit without and with the change, other jobs' Metal compiles running beside both. All 21,225 pairs: 393 and 452 s on 4 workers, 187 and 272 s on 14 (1.8 times faster on average). M6, macOS 27.2, Skyward Sword's 2,125 pairs from an empty archive, another session's shader build beside them, in the quietest of three rounds: 45.1 s on 1 worker, 28.0 on 3, 19.2 on 6 (Metal's count), 21.3 on 9, 18.8 on 12. The host with this fix, Metroid Prime Remastered's first 2,000 pairs on the M6: 52 s on its default 6 workers from a cold cache, 194 s on 1 worker afterwards.shouldMaximizeConcurrentCompilationis not set: Metal reports the same count with it and without it on both Macs, its effect did not rise above the noise on either (M5 Pro, from a cold cache: 62 pairs/s on 4 workers without it, 53 with it, 98 on 14 without it, 112 with it), and Apple's guide gives it as the Metal 3 setting, while the prebuild compiles throughMTL4Compiler. - Found on: Donkey Kong Bananza.
- Check:
t_pso_warmchecks that the tool's default follows Metal's count.
Function constants specialized at load
- Symptom:
fragmentFunction main0 cannot be used to build a pipeline state(a Metal validation assertion). - Cause: SPIRV-Cross declares an optional function constant,
spvLinearTextureAlignmentOverride, in shaders that read a texel buffer, and Metal refuses any function with function constants until it is specialized. - Fix:
shader_loadspecializes such functions with an empty set of values. On the Metal 4 path the pipeline's descriptor specializes them, not the library: Functions with function constants specialized by the pipeline, not the library. - Found on: Pokémon Legends: Z-A (one imgui pixel shader).
Functions with function constants specialized by the pipeline, not the library
- Symptom: with Metal 4 pipelines on (the Mac; on iOS
pso_mtl4 onorDM_PSO_MTL4=1), Apple's performance HUD saysCompiled 2 shaders. Total compilation time is 102.70ms. Consider adopting MTL4Compiler for more fine grained compilationsduring play, when a shader with function constants loads. - Cause: a function that declares function constants must be specialized before it goes into a pipeline (Function constants specialized at load). The host did that through
MTLLibrary'snewFunctionWithName:constantValues:error:when it loaded the shader (shader_load) and the libraries made from it (the pulling and shadow-input vertex entries,pull_loadandvin_fn; the alpha test,at_fn). That call compiles through the MTLDevice, synchronously, on the thread that loads the shader. A Metal 4 pipeline does not need it:fn4_notealready gives MTL4Compiler anMTL4SpecializedFunctionDescriptorwith the same values. - Fix:
fn_specinnvn_mtl.m. With the Metal 4 compiler (pso4_compiler) theMTLFunctionstays unspecialized and is noted with its constant values, so MTL4Compiler specializes it with the pipeline. Its reflection and argument encoders are the same as the specialized function's. A pipeline the MTLDevice builds after all (pso_build's fallback, when a function has no Metal 4 descriptor, such as theDM_NVN_HILITEoverride) takes the functionfn_devspecializes through the library, once per function. A stable record per function serializes overlapping first uses, so they receive the same specialized function; unrelated functions can specialize concurrently, and registering the entry again preserves its cached result. Unchanged:- Compute shaders are still specialized at load: the MTLDevice builds their pipelines.
- Without the Metal 4 compiler, functions are specialized as before.
- The variants that differ only in their constant values still specialize through the library: the logic operation entries (
lo_fn) and the readable-tile versions (bf_fn). Their pipelines would need one function object per set of values, andnewFunctionWithName:may hand back the same object.
- Found on: Animal Crossing: New Horizons on an iPhone 17 Pro Max with Metal 4 pipelines turned on: the HUD warning when a shader loaded during play. On the Mac, with a probe that logs each MTLDevice compile, the specializations came from
shader_loadduring the prepare step and again when a shader loaded during play. After the fix none were left, and the picture was the same. - Check:
t_pso_archive. A function with a constant stays unspecialized, its descriptor specializes it, and a pipeline is made through the Metal 4 compiler. With a fragment function that has no descriptor, the pipeline goes through the MTLDevice with the vertex function specialized once. A gated library holds the first specialization while a second caller requests it: both receive one shared result, an unrelated function progresses, and registering the same entry again does not specialize it again.
Layer-writing vertex shaders get the triangle class
- Symptom: a pipeline for a vertex shader that writes
render_target_array_indexcannot be built. - Cause: Metal builds such a pipeline only with an input primitive class, and the translator writes a point size in every vertex shader, which needs the point class: no class fits both.
- Fix:
vs_layerdrops the point size from vertex shaders that write the layer, and the host gives their pipelines the triangle class (pso_desc) by the reflection'slayer_out(Vertex shaders with layer entry points left out of the prebuild). Before chain d403eb0683df the host found out when Metal refused the pipeline and named the reason, and built it again. Their passes are layered (Layered passes for vertex shaders that write the layer). - Found on: Pokémon Legends: Z-A: two full-screen vertex shaders (
57246f9a04af8529,b29f08619f379a83: one triangle per instance, layer = instance + offset, 20 pixel shaders read the layer).
The precompile look-ahead restores the scissor
- Symptom: the picture bright green and white from some scene on, in runs with pipelines compiled on demand (prewarm lists off or short) and in none with
DM_NVN_PREDICT=0. - Cause: after a pipeline miss the replay looks ahead through the rest of the submission, replaying state only, to compile the next pipelines in the background (
pso_predict_rest). It restoredS, butstate_opalso sets the scissor, which lives inR: the replay went on with the last scissor of the submission until its nextOP_SCISSOR, so the draws in between were clipped to another pass's rectangle. - Fix: the scissor is saved and restored with
S; the fusion probe (fz_probe_cov2) already restored all ofR. Every game. - Found on: OCTOPATH TRAVELER II: from Castti's opening flashback and the battlefield of Hikari's opening on.
- Check: found by bisecting with four runs started at once on copies of one save:
DM_NVN_PREDICT=0fixed it, a look-ahead that compiled nothing did not, and of its parts only the state ops brought it back; four runs green before the fix, four right after it.
Pipeline look-ahead must leave future attachments unresolved
- Symptom: a crash in
-[AGXG16XFamilyRenderContext_mtlnext setRenderPipelineState:]fromdraw_with direct Metal encoding. The pass dump shows a pipeline miss and an end ingpu_read_waitbefore the draw reaches its pipeline bind. - Cause:
pso_predict_rest_resolved the attachments of futureSetRenderTargetsrecords to get their formats and sample counts. Resolving a sparse texture can read GPU-written storage for a CPU upload. Its wait ends and commits the open pass, so the demanding draw retains an encoder that has ended. Deferred encoding can hide the fault because its replay clears the real encoder when processing the end record. - Fix: use
tex_madefor format and sample-count lookups. Skip predictions for a pass with an unresolved attachment and resume when the scan reaches known targets. Actual replay resolves textures at their first use. This also keeps speculative uploads and GPU waits out of pipeline prediction. - Check:
t_pso_pendingsends the look-ahead through an unresolved target and then an existing one. On the old code it attempts a texture allocation and queues a pipeline for the wrong attachment set. With the fix it queues only the pipeline for the existing target. - Found on: Mario Kart World 1.8.0.
The look-ahead hands every later draw's pipeline to the background
- Symptom: on entering a new area or opening a menu for the first time, with no archive or prewarm list covering it, frames of 0.2–2 s whose
[longframe]line is nearly all pipeline work, anddraws that waited: pulling base not made yetin thepipelines up to framelines. - Cause: after a submission's first pipeline miss, the look-ahead (
pso_predict_rest) handed at most two of the rest to the background (PSO_PREDICT_BUDGET,PSO_PEND_ACTIVE), a bound set without a measurement. It applied to the keys of the draws the look-ahead met, with their attachments as they are, although those draws come later in the same submission. A draw with no stand-in whose pipeline was not admitted compiled it on the submit thread, so a frame with dozens of new pipelines compiled them one after another. - Fix: each of those draws' pipelines is admitted (
pso_pend_kick_next, bounded by the 384-slot table), after the same exclusions as before: a key whose base is made (pso_base_made), one that already drew with a stand-in (g_pso_hy) and one whose pulling stand-in is ready (hybrid_get) take nothing. Only the guesses with other depth / stencil attachments keep the bound of two. The draw's own pipeline is built before the look-ahead runs, and a draw whose build is still queued makes it itself (pso_pend_take), so none waits behind the others; the Metal compiler service builds them side by side. Host only, every game. - Found on: FINAL FANTASY RESONANCE (PR #1344, Apple M5 Max): a save loaded into Grandshelt Castle, then the System Menu and the World Map, with no archive, lists or prebuild and the system's Metal cache off: 2.78–2.81 s of pipeline waits, worst frame 2.19–2.23 s, before; 0.74–0.79 s, worst 0.71–0.74 s, after (two runs each). Bounding all of them by 16 instead gave 1.9–2.0 s. Repeated on OCTOPATH TRAVELER II (Apple M4 Pro,
bench.py, the hosts alternating, two runs each): its smoke route from the settings save through New Game and Hikari's opening, 290 s, cold the same way: draws that waited 200–205 for 5.0–6.0 s before, 120–128 for 3.0–3.3 s after; 64–70 builds admitted against 130–151; the look-ahead's own time 0.03–0.17 s either way; the longest frame in the window 1.32–1.58 s against 0.62–1.07 s (the long frames left are the game's loads, with no pipeline work); median frame time unchanged, no red line. The same builds on a fixed set of workers taking them in the draws' order, the draw making any it reached still queued, waited longer in a three-way A/B of one host (two runs each): 10 workers 2.61–2.64 s, 5 workers 2.78–2.95 s, against 2.50–2.53 s with every build started at once. Even with 5 workers almost no draw reached its build still queued, so the order was not what held the draws up; the Metal compiler service builds more of them side by side. - Check:
dm/gfx/tests/t_pso_pending.m(test_next_draws_pass_the_guess_limit). WithoutMTL_SHADER_CACHE_SIZE=0a second run of the same route finds every pipeline in the system's cache and waits almost nothing either way, so cold comparisons need it, withDM_PSO_ARCHIVE=off,DM_PSO_MANIFEST=offandDM_PSO_PREBUILD=0.
GPU frame captures need pipelines built through the device
- Symptom: a GPU frame capture (
DM_GPU_CAPTURE, or Xcode withMTL_CAPTURE_ENABLED=1) fails withCapturing Render pipeline specialization is not supported, or the capture layer crashes on the pipeline archive; a capture of theMTLDeviceis refused. Before the fix below asked Metal, a run that did not capture but hadMTL_CAPTURE_ENABLED=0orDM_GPU_CAPTURE=0left in its environment loggedhybrid pipelines off, and every pipeline it had not built yet stalled its frame (an M1 Ocarina of Time session: 467 stalls of about 170 ms, one 84 s freeze with 255 pipelines in a submission). - Cause: Metal cannot capture pipelines made from Metal 4 bases (
DM_PSO_MTL4, the default on the Mac), and its Metal 4 to 3 conversion for the capture layer crashed on the pipeline archive. A device the replay drives through Metal 4 cannot be the capture object. - Fix: a run that Metal lets capture builds its render pipelines through the
MTLDevice, without bases or archive (pso4_on). Metal answers that itself, once at start (MTLCaptureManager supportsDestination:a GPU trace document or the developer tools): on the Mac whenMTL_CAPTURE_ENABLEDreads as a non-zero number (1; unset, empty,0,trueorYESdo not), on iOS in a build withMetalCaptureEnabled(DM_METAL_CAPTURE=1, every run of it), and when Xcode starts the run for capture.DM_GPU_CAPTUREdoes not decide it: alone it cannot capture, andDM_CTLcan set it later in a run that can. The log says which path the run took:render pipelines through the MTLDevice: Metal may capture GPU frames in this run (…)orrender pipelines from Metal 4 bases and the pipeline archive.gpu_capture_framegpu_capture_framecaptures the Metal 4 queue (g_q4): work on the old queue (present, some uploads) is not in the trace. Such a run builds pipelines more slowly than a normal one, so its frame times are not the game's. Every game. - Found on: The Legend of Zelda: Breath of the Wild (Mac and iPhone); the leftover-variable stalls on The Legend of Zelda: Ocarina of Time (M1, #2688).
A cold Metal cache looks like a long load
- Symptom: the first boot sat on the loading clock for about a minute, the CPU idle, with every file read done after 12 s.
- Cause: that run compiled its Metal libraries and pipelines on first use (cold cache). With a warm cache the title is up after about 15 s; what looked like a 40-second wait in the read log (
DM_FSLOG) was the title screen itself, which reads nothing. - Check: screenshots every few seconds (
ctl.sh snapfrom a script) told the two apart. - Found on: Bayonetta 3 (SDK 13.3.2).
Native mesh draws omitted while their pipeline compiles
- Symptom: missing geometry or bright patches just after loading, which disappear as background pipeline compilation finishes.
- Cause:
mtk_psostarted an asynchronous native task/mesh pipeline build and returned no pipeline; the draw was omitted until a later frame found the completed pipeline. This copied the geometry-mesh optimization's behavior without its equivalent compute fallback. Native mesh draws have no such replacement. Metal validation also rejected the helper descriptor assigning a mesh function tovertexFunctionbefore copying its raster state. - Fix: compile the demanded native mesh pipeline before issuing its first draw, then reuse the cached pipeline. The shared descriptor helper leaves
vertexFunctionunset for a native mesh shader; the mesh descriptor receives it asmeshFunction. A cold pipeline can delay the first frame but cannot silently remove its draw.t_mesh_first_useexercises real NVN submissions with mesh-only, task/mesh, depth-only and ordinary vertex shaders: the old host failed 10 of 42 pixel/state checks; the fixed host passes all 42 with Metal validation in both encoding modes. - Found on: Ocarina of Time, M4 Pro startup white patches. The synthetic GPU regression verifies the missing-draw mechanism; the corrected game's startup remains to be checked with the queue fix.
Geometry runs across occlusion query boundaries
- Symptom: hundreds of geometry raster passes in combat, despite support for batching consecutive geometry draws.
- Cause: the lookahead stopped at each samples-passed query report/reset. NieR wraps most geometry draws in independent occlusion queries, so each one still captured vertices, ran geometry/compaction and reopened the depth buffer.
- Fix: queries remain in their original raster replay positions while lookahead prepares later geometry draws. The shared raster pass uses a separate visibility-result slot after each report/reset; helper capture and compute stages do not count raster samples. Query-result addresses remain marked as report writes for hazard checks.
DM_NVN_GEOMETRY_QUERY_RUN=0retains the earlier split path for comparison. - Found on: NieR:Automata US 1.0.3: the captured factory combat frame has 697 geometry raster draws with 670 intervening query/event/reset groups. A GPU fixture verifies that the first visible draw reports 216 samples and the second, hidden draw reports zero, with the completion event and later color/depth coverage preserved.
Prepared geometry indices reused after byte comparison
- Symptom: geometry preparation dominates rendering CPU even after geometry passes have been batched; primitive assembly and capture-index deduplication repeat for unchanged meshes.
- Cause: each draw decodes all source indices, assembles its primitive map and rebuilds sorted unique capture IDs, even when its source bytes and topology are identical to the previous frame.
- Fix: a 32 MB / 4,096-entry LRU cache keeps only the CPU primitive map, unique capture IDs and original index bytes. The key includes address, count, index width, topology and restart settings. Every reuse compares all original bytes, after the existing readability and GPU-write wait checks; there is no content-hash collision assumption or dependence on write-protection. CPU edits, GPU copies and reused storage with different contents rebuild preparation. Base vertex, instances, vertex capture, transforms and GPU outputs remain per draw.
DM_NVN_GEOMETRY_INDEX_CACHE=0disables reuse for comparison. - Found on: NieR:Automata US 1.0.3: the outdoor flight-unit encounter has approximately 2,300 draws including 855 geometry draws, 24.9 ms rendering CPU and 12.2 ms GPU time. A controlled CPU-only preparation benchmark (64 draws, 32 meshes, 6,144 indices each), alternating warmed paths, drops median CPU preparation from 2.783 to 0.149 ms; it does not execute the GPU geometry stages or establish a gameplay FPS. Production GPU tests preserve literal pixel coverage on unchanged repeats, CPU index edits and GPU index copies, including forced-wait and disabled-cache paths. Cache budget and topology/restart separation are covered too.
Geometry capture initializes only missing words
- Symptom: geometry vertex-capture passes consume substantial GPU time before geometry compute or depth rasterization.
- Cause: the capture entry first zeroed all 144 words of every output record, then wrote the default W components and finally overwrote the actual shader outputs. Much of the initialization was redundant GPU storage traffic.
- Fix:
dmsh_geometry.captureinitializes only words absent from the captured outputs. The capture slot map stores each selected word once, including defaults for absent outputs. Position W, point size, generic W, clip distances, layer and viewport retain their existing bit values. Full capture selects all 144 words; lean capture selects its consumed words. Shaders and host must be rebuilt together. - Check: the synthetic throughput comparison alternates control/candidate order and verifies all 9,437,184 captured words against both the original buffer and literal expected values. Mac runs vary in timing, so their percentage gain does not establish iPhone gameplay FPS. The optional real-translator capture fixture in
t_geometryalso checks all uncaptured defaults. All 1,225 NieR shaders build for Mac and iPhone; standard geometry replay and dependency checks pass. - Found on: NieR:Automata US 1.0.3, iPhone City Ruins: 14 geometry groups in the captured frame spend 7.485 ms in vertex capture, 6.512 ms in compute and 1.019 ms in depth raster. The accompanying pass dump affects total frame time; its large uncovered GPU interval must not be treated as a clean gameplay hitch measurement.
The host's own shaders compiled from source at run time
- Symptom: Apple's performance HUD (
DM_METAL_HUD=1) saysCompiled 2 shaders. Total compilation time is 102.70ms. Consider adopting MTL4Compiler for more fine grained compilationsduring play, with a dip in the frame-rate graph at that moment, for example when a new room first issues a scissored clear. - Cause: the host compiled the shaders it writes itself from MSL source at run time (
newLibraryWithSource:): built-in kernels, clears, copies,nvnCommandBufferDrawTexture, the RGB565 red / blue exchange, index conversions, geometry packing, transform feedback, the present, the GPU deswizzle and the OpenGL layer's clear quad. The thread that asked waits for the compiler. The clear triangles were one library per colour slot and type (snprintf), up to 24, each compiled when a clear of that kind was first met: about 50 ms each on an iPhone, on the submitting thread.MTL4Compiler'snewLibraryWithDescriptor:with a source is no way around it: it calls the device'snewLibraryWithSource:itself (a check with a swizzled device shows the call), and the HUD counts that too. - Fix: the sources are
.metalfiles indm/gfx/msl(the clears in one library:clr_fs_<slot>_<float|uint|int>).dm/gfx/tools/host_msl.pycompiles them when the host is built:make -C dm/hostfor the Mac, andgen_build.pywithMSL_SDK=iphoneosfor the app's deployment target on iOS. It writesdm/host/gen/msl-<sdk>/host_msl_gen.h, which holds each library's metallib and source.host_msl_lib(dm/gfx/nvn/host_msl.m) loads one by name withnewLibraryWithData:, once per device, so nothing is compiled; the pipelines are made as before. A build without the Metal toolchain carries the sources only: the host then compiles each library once and logs a[RED]line (compiled from its source in … ms). The first load logshost shader libraries: 13, compiled for <sdk> by <metal version>. The diagnostic overrides (DM_NVN_HILITE,DM_NVN_MAGSCAN,DM_NVN_TEXDUMP) still compile theirs from source. - Found on: Animal Crossing: New Horizons, iPhone 17 Pro Max: the HUD's compile warning in play, from clear-triangle libraries compiled when a new room first issued a scissored clear.
- Check:
t_host_mslloads every library, with a swizzlednewLibraryWithSource:that counts 0 calls, and finds all 24 clear functions.t_builtin,t_geometryandt_deswz_gpuuse the built libraries. - Build inputs: Mac libraries use
MACOS_MINfromdm/mac/min_os.mk, matching the host's deployment target; otherwise a newer SDK emits libraries older supported Macs cannot load and the host falls back to runtime compilation. Every build rechecks the compiler, SDK, deployment target and source contents, reusing the header only when all match. Installing the Metal toolchain after a source-only build therefore regenerates the libraries without a clean build. - Build callers: the NSP packer and regression harness generate the Mac header before checking their cached host executables, and include it in the host fingerprint. The standalone iOS compile check generates the iPhone header before its dry run, as the app build does. A dry run alone does not generate either header.
Raw pool table words that predate the pools
- Symptom: a raw global memory read of a memory pool made after the shader's arguments were encoded gets 0, though the pool exists when the GPU runs it; a task shader that reads both ends of a range this way loops
(0 - 1) >> 5times and hangs the GPU. The memory report'sraw pool table words at commitline counts the words that were out of date. - Cause: an argument block holds the address of the pool table that was current when it was encoded (
gmem_map_gpu). A pool made later in the same submission, or on another thread while it is encoded, is not in that table, and the table is rebuilt only for the next block that is encoded. A save load makes more than 4,000 pools in a burst, so many blocks are encoded with a table that lags. - Fix: the words are noted as they are encoded (
gmem_slot_note) and, at each commit of the command buffer, whole, segment or the commit before an indirect-count multi-draw waits for its count (mdi_wait), all of which end it throughcb_commit, pointed at a table of the pools as they are then (gmem_commit_patch). A new table is built when the pools changed, not refilled in place, as earlier segments may be reading the old one; the replaced one goes through the deferred release. The write log of a block is a bitmap of the entries of the table its shader searches, so the log follows its table (NvGmlLog):gml_readdecodes its bits against the table the block holds at the commit, not the one it was encoded with. The idea is #1407's, which rewrites the words at commit in its own stack. - Found on: The Legend of Zelda: Ocarina of Time (
0400486024DEC000, profile in PR #1299): on the author's stack, loading the outdoor save, 5,729 of 154,107 words held an older table than the current one by frame 5,100 and 2,582 held the current one behind the pools. Whether this is what is left of the hang in issue #1326, minutes after a clean table growth, is open. - Check:
t_gmem_words(words noted, a pool made after them, an older table, a table that lags, a commit with no words, the commit before a count wait).
Extended products behind spirv-cross's optnone helper
- Symptom: integer divisions by a constant cost GPU time that the compiler should have folded away. The MSL holds calls such as
(spvMulExtended<_2, uint>(uint(_5), 16u))._m1, and spirv-cross definesspvMulExtendedas[[clang::optnone]], so each product stays a call to an unoptimized function. - Cause: spirv-cross writes
OpUMulExtendedandOpSMulExtendedthrough one template that it keeps unoptimized, because Metal's compiler may fail on an inlinedmulhi(its comment atSPVFuncImplMulExtendedinspirv_msl.cpp). Switch 2 shaders divide by constants through the high word of such a product: Ocarina of Time's MSL has 348,587 of these calls, all scalaruintby a literal and 98% of them by a power of two. Four Switch 1 games checked (Fire Emblem: Three Houses, Minecraft Dungeons II, Octopath Traveler II, Sonic Superstars) have none. - Fix:
mul_extendedindmsh_build.pyadds overloads for scalaruintandintoperands beside spirv-cross's helper. They are always inline and take the halves of the 64-bit product, with nomulhi. Overload resolution prefers them to the template, so every scalar call leaves the barrier and the compiler folds its constant; a power of two becomes a shift. Vector calls keep the template. A helper that is not exactly as spirv-cross writes it leaves the shader unchanged. PR #1741 first took out the calls with a literal other than a power of two (5,679 of them); that left the gameplay route below unchanged. - Found on: The Legend of Zelda: Ocarina of Time. On an M4 Pro, the Kokiri Forest deck route's GPU time fell from 15.55 to 14.76 ms a frame and its frame rate rose from 54.0 to 59.1 fps. The title movie's GPU time fell from 12.96 to 12.44 ms. On an M1 Pro, PR #1741's partial version took the title movie from 26.57 to 28.40 fps.
- Check:
test_dmsh_extended_multiply.py. On the Mac GPU, it compares unsigned and signed products by literals (power of two or not) and by variables, over 65,536 input pairs including the edge values, with 64-bit products on the CPU. It compiles the kernel for macOS and iOS and checks that only the vector call is left calling the template.
Signed integer overflow in translated shaders
- Symptom: integer results in a shader come out wrong where the game's code relies on signed arithmetic wrapping: a packed field unpacked by hand, an overflow test, a sign extension. In Ocarina of Time, one section of an otherwise dark wall in the Deku Tree (Gohma's room) was lit brightly and shimmered while the camera moved. Only models drawn with task / mesh shaders were affected; the vertex-shader models beside them were lit correctly.
- Cause: SPIR-V, GLSL and the Switch's GPUs wrap on signed overflow. spirv-cross writes SPIR-V's
OpIMul/OpIAddon signed values as plainintarithmetic in MSL, where overflow is undefined, so Metal's front end optimizes as if it cannot happen. Ocarina's mesh shader35785cddc971290c(taska5288d0a6c4971fd, pixelf4f7e6955d37f40c) sign-extends the low half of a word for the lightmap / light-probe UV:a = as_type<int>(w) * 65536, then(a >> 31) << 16 | uint(a) >> 16. The compiler, assuming the multiply did not overflow, took the sign bits from bits 15-30 ofw((w << 1) & 0xffff0000) instead of from bit 15. The UV's x then came out far too large (13184 / 18432 / 31744 where y gave 0.20 / 0.28 / 0.48), the probe texture was sampled at the wrong texels, and the pixel shader's spherical-harmonics ambient term read about 8 instead of 0.001. On an older chain the translator wrote the extraction without the sign extension, and the fold did not happen. - Fix: every Metal compile of translated shaders passes
-fwrapv:dmsh_build.py(Mac),ios_metal.py(iOS),vk_shaders.pyandgl_shaders.py. The flag also dropsinboundsfrom pointer arithmetic, because Metal's clang has no separate-fwrapv-pointer. It also makes the compiler keep loop bounds that may wrap (an extrasmaxbefore a loop). In a sample of 1,000 of Ocarina's shaders, compiled to LLVM IR on an older chain, 12 came out identical, 746 differed only in theirnsw/nuw/inboundsflags, and 242 had other changes. None of it shows on the GPU. On Ocarina'skokiri-deckroute (bench.tsv) on an M6 (12-core GPU, 2026-11-09), both sides built from the same main with their own libraries and warmed pipeline archives, the medians of three runs a side were 9.94 / 10.51 ms GPU p50 / p95 and 59.4 fps without the flag, and 9.91 / 10.43 ms and 59.6 fps with it. Runs of one side differ by about 0.1 ms. - Found on: The Legend of Zelda: Ocarina of Time, found by nawangwe (PR #1844) on an M4 Pro.
- Check:
test_dmsh_wrapv.pycompiles the sign extension, an overflow test (x + 0x7fffffff < x) and a doubling and halving withdmsh_build.py's command and checks the results on the Mac's GPU over 65,536 inputs. It also checks that the iPhone command keeps the shift and that all four tools pass the flag. Without-fwrapv, the GPU check and the iPhone check both fail.
A jump Apple's GPU compiler cannot encode (a tested bit 0's mask)
- Symptom: building a render pipeline with one pixel shader ends Apple's compiler service:
[RED] pipeline prebuild: the base of … failed: Compilation failed due to an interrupted connection: XPC_ERROR_CONNECTION_INTERRUPTED. This error occurred after multiple retries., the pair inprebuild_failed.tsv, and aMTLCompilerServicecrash report (EXC_CRASH,SIGABRT) whose stack isfatalErrorHandler←llvm::report_fatal_error←llvm::MCObjectStreamer::emitInstruction←AGCLLVMUserObject::compile←AGCModule<AGX::Impl::FragmentProgramKey>::compileLLVMObject. The shader translates and its library builds; every vertex shader paired with it fails the same way, and the compiles in flight when the service ends fail with it. Offline, the toolchain'sapplegpu-ntsaysLLVM ERROR: Failed to encode.for the same library. - Cause: a compiler bug, in the pixel shader alone (no vertex shader is needed to show it). The translator makes a predicate of bit 0 twice: the compare
bool b = (x & 1) != 0, and where the Switch code keeps the predicate in a register, its integer formb ? -1 : 0. Where the shader also branches onb, the compare has two users in the AIR, a sign extension and a branch. The GPU compiler of the M3 and later (applegpu_g15,g16,g17, andg18pfor the iPhone; the macOS 26 and the macOS 27 back end alike) can then select a jump on the bit taken straight from a uniform register, and its encoder has no form for that instruction. It happens only wherexis a uniform the compiler's per-draw constant program has loaded (it holds about 250 values) and the test itself found no room there, so it depends on how many uniforms the shader reads before the test: a few lines more or fewer and the same shader compiles.-O0compiles, and so doapplegpu_g13andg14. What was ruled out on the way: the warp shuffles of its derivatives, its border colour reads, the discard and the early return by themselves, the size of the shader, its vertex shaders' outputs. - Fix:
bit0_maskindmsh_rewrite.py(run bydmsh_build.pyon every shader, a geometry shader's kernel and its reader too): the mask is written from the bit,-(x & 1), the same value, and the compare is left with its branch. It rewrites only= b ? (-1) : 0;wherebis declared asa != 0andaas… & 1, neither assigned again, within one function; a shader without that comes back unchanged. Other bits and other uses of the compare (a select of two constants, a conversion) did not show the bug in the reduced shader, and are left as the translator wrote them. - Found on: PRAGMATA: pixel shader
c4ac3ca598cea32e(/re_chunk_000.pak#e1487969619ddb7a#SDF#var15) tests bit 0 of a constant buffer word (fp_c10[2].w) after 6 texture reads and a discard, keeps the predicate and branches on it twice. The front end's EarlyCSE, which merges the repeated loads of that word, is what leaves the compare with its two users (A base the GPU compiler cannot encode cost the whole offline archive, which keeps such a pipeline out of the offline archive). Reduced with a line-level delta debugger againstapplegpu-ntto the 100-line shader of the test; the failing instruction was read with a debugger on a copy ofapplegpu-nt(a conditional jump whose operand is a uniform register, emitted once, as the last instruction before the abort). M4 Pro, macOS 26.6.2, Metal toolchain 32023.922. - Check:
python3 dm/gfx/tests/test_dmsh_bit0_mask.py(the rewrite, what it leaves alone, each function by itself). WithDMSH_TEST_METAL=1the reduced shader goes throughmetalwith the chain's flags andapplegpu-nt: as translated it must fail withFailed to encode(the test is skipped where a later toolchain compiles it), rewritten it must compile at-O1and-O2forapplegpu_g15g,g16sandg17g.
Prebuilt pipeline archives not opened during the first run
- Symptom: after a cold or partial prepare-step prebuild compiles thousands of pulling bases into
pso_archive/p*.mtl4abefore frame 0, the same session still suffers hundreds-of-milliseconds to multi-second gameplay stalls withdraws that waited: pulling base not made yetandmisses with no pulling base ready, and recompiles those pulling bases again in the background (hy_base_kick). Only restarting the app makes the prebuilt bases visible. - Cause:
pso4_init()openedg_arch_dironce at startup (when it had no prebuild files yet) and leftg_arch_ix/g_arch4pfrozen for the process.prepare_prebuild()then ranpso_prebuild(), which discarded each compiledMTLRenderPipelineStateinpre_pair()and flushed the bases top*.mtl4aon disk without opening those newly written files intog_arch_ix/g_arch4p. - Fix:
prepare_prebuild()waits briefly (up tog_pre_tail_ms, 10 s, preserving the#294hung-compile bound; unlimited onceg_pre_flushingconfirms every worker has returned and only the final disk flush remains) forpso_prebuild()to finish, then callsarch_adopt_prebuilt()before frame 0.arch_adopt_prebuilt()findsp*.mtl4afiles ing_arch_dirnot already opened ing_arch_opened, checks thearch_vm_room()2 GiB runtime reserve, opens them in parallel insidearch_open_begin()/arch_open_end(), indexes their.keysintog_arch_ix(and retains them ing_arch_ixf/g_arch4p, keeping them out ofg_arch_usesoarch_sweep()never retires them), and clearsg_pbase_miss.g_arch_ix/g_arch4pstay immutable and lock-free once frame 0 starts. - Found on: Resident Evil 4 (GitHub issue #3030): on an M5 Pro (macOS 27.2), a first run whose partial bundle triggered an on-device prebuild of 15,764 pulling bases (
p00000.mtl4a–p00014.mtl4a, 1,099.8 s) still waited 4,364.5 ms across 36pulling base not made yetdraws in frames 1–11,700 (including a 2,154.6 ms stall at frame 1469 and a 967.7 ms stall at frame 6487). - Check:
t_pso_archive --adopt-prebuiltverifies real Metal 4arch_adopt_prebuilt()adoption of a newly writtenp*.mtl4a(clearingg_pbase_miss, servingcompile=0lookups with zero recompiles, staying out ofg_arch_use, and idempotence).t_pso_stallverifies the fullprepare_prebuild()path plus the#294held-compileg_pre_tail_mstimeout (skipping adoption while workers are active).t_pso_admissionverifiesarch_adopt_prebuilt()honors the 2 GiB address-space reserve (exactrefuses a new 0.5 GiBp*.mtl4a;ampleopens it).