graphics: bind GPU-indexed T# tables as sampled image arrays #1257
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1257
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/1257/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@TheCruZ on GitHub · 2026-10-08 20:49 UTC · original
pr/bindless-image-tables→main· +979 −117 · 27 files · 1 commits · closed without mergingSummary
Makes the ray-hit shading compute shader of Grand Theft Auto V (PPSA04263) in Fidelity mode (ray tracing) supported:
cs 0xc6c91cf1882cdc3bsamples material textures whose T#s it reads from a 65536-entry descriptor heap at an index taken from GPU-written material records. With the current image-table lookup it fails withsampled image descriptor 9813 uses unsupported format 60, and the ray-traced reflections and shadows cannot be shaded.Problem
Indirect images could only probe host-readable material keys and bind at most 64 candidates through a switch. Upstream
cd066010replaced that probing with a direct image-table lookup that makes every distinct T# of a bounded table its own specialized image. On GTA V's ray tracing heaps that lookup took ~9800 table words as candidate T#s, some of which are not images the root's view can read, and failed.Change
Resource tracking. When the key is not a probeable material word, the table itself is kept (also through a masked table offset, and when several image instructions share one T# load). Scalar 32-byte T# tables that are not indexed by the workgroup, including those whose key is a plain material word (the four roots of c6c9 that used to probe their keys), take this table path; the direct lookup keeps the other tables.
Materialization. The table is read, its valid T#s are deduplicated into slots (reused while the table is unchanged), and an entry-to-slot mapping is appended to the flattened SRT. The slots follow the resources of the root's image binding, sized to a power-of-two capacity.
Shader. The shader computes
entry = key & mask, loads its slot and samples the element of a sampled image array withNonUniformindexing (shaderSampledImageArrayNonUniformIndexingandshaderSampledImageArrayDynamicIndexingare enabled when available).Host binding. Each slot is resolved through the texture cache; T#s the root's view cannot read, or whose guest memory is gone, bind null images. Slot resolution runs under a new
Common::SoftExitScope, which turns a fatal error of the current thread into aCommon::SoftExitError, so a T# the texture cache cannot use binds a null image instead of terminating (WriteBackingis no longernoexcept, so its failure reaches the scope too). A pipeline whose sampled images exceed the device's per-set or per-stage limits or the descriptor pool's budget exits with a message instead of creating an invalid layout. Table elements resolve throughTextureCache::FindImageSpeculative, which declines depth/color recreations (a few heap T#s alias depth buffers the frame renders to, and converting them cost two recreations per frame). Elements whose image an earlier rebind replaced are rediscovered before their views are acquired.Cost. The shader binds five roots of 4096 elements each; resolving all of them on every dispatch took 17% of the GPU thread.
RenderExecutorkeeps each element's resolution by T#, shared by roots with the same view, and resolves it again only when an image overlapping its memory was registered or unregistered (a per-page epoch in the texture cache, plus a global image-set epoch that skips the per-range check while no image changed), when the guest backing changed (new kernelBackingEpoch), or always when it has DCC metadata. Elements declined by the texture cache are revalidated against the guest range the lookup examined. A table element whose memory is not readable on the guest side is still accepted when a GPU-written image covers it (TextureCache::IsRegionGpuModified).Relation to #811, #852 and #1118
Those PRs generalize the indirect image planner (address-backed tables, bounded and mixed candidates, more table shapes) while keeping one specialized image per candidate T#. This PR adds a different binding for large GPU-indexed T# tables (a sampled image array indexed per lane), so it touches the same planner code in
ResourceTracking.cppand will likely conflict textually with them; I can rebase on whichever lands first.Testing
cs 0xc6c91cf1882cdc3bruns and ray-traced reflections are shaded; played in my fork with this change (together with my other Fidelity fixes, e.g. #931).resource_tracking_tests: newTestBindlessImageTablecase; passes.shader_recompiler_compute_tests:CheckImageSamplerSpecializationnow expects GPU-selected material T#s to bind the T# table (one image table whose mapping covers every entry) and compiles and validates the resulting SPIR-V. The default run and--indirect-image-onlypass.resource_materialization_tests,memory_tracker_tests,page_manager_tests,shader_cfg_testsandvirtual_memory_allocation_testspass.AI usage
AI (Claude Opus 5.5) was used to investigate the issue and to implement the change. I reviewed the code, understand it, tested it as described above, and wrote this description myself, in general fully tested the game while doing few missions and playing in-game with my GTA V fork, i will be bringing PRs here after test them enough.
@coderabbitai[bot] on GitHub · 2026-10-08 20:55 UTC · original · edited 2026-10-08 21:41 UTC
📝 Walkthrough
Walkthrough
The change adds bindless image-table tracking and materialization, then uses table mappings to select sampled-image descriptors at runtime. The renderer resolves and caches table images, with image and backing epochs used for refresh checks. Speculative texture lookup can reject depth-overlap candidates. The change also adds soft-exit exceptions, backing-readability checks, and supported Vulkan sampled-image array indexing features.
Suggested reviewers:
nmzik,senaxx,claxten10Priority: ➖ Normal
Change: Feature
Merge Risk: 🟡 Moderate · up to
1d3a5The new bindless texture-table path can fail pipeline creation on GPUs with lower sampled-image limits. A failed lookup can also leave the texture cache in an inconsistent state. Both should be fixed or explicitly accepted before merging.
🚥 Pre-merge checks | ✅ 4 | ❓ 1
❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 12.64% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 87 functions across 22 files. (3 skipped: 2 unsupported, 1 too large.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@ -14,0 +29,4 @@if (g_soft_exit_depth > 0) {throw SoftExitError(fmt::format("{} ({}:{})", text, file, line));}}@coderabbitai[bot] on GitHub · 2026-10-08 20:55 UTC · original · edited 2026-10-08 21:14 UTC
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 11022
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 11022
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 42590
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 43585
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 14534
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 34699
Keep
SoftExitErrorout of mutating texture-cache code.ResolveTableTexturekeepsSoftExitScopeactive for the fullResolveTexturecall.FindImageSpeculativecan then enterResolveOverlapwhile holdingm_lock. Non-depth overlap branches callExpandImage, which inserts an image before initialization, copying, and freeing. Those later operations containEXITpaths.MaterializeColorClearalso mutates image metadata before validation checks that can exit.A soft failure can therefore unwind to
ResolveTableTextureafter partial cache updates. Complete failure-prone validation before cache mutation, or make speculative lookup and materialization rollback-safe before catchingSoftExitError. Do not keep the current soft-exit scope across mutating cache work.@ -457,0 +473,4 @@uint32_t ImageTableCapacity(size_t slots) {return std::bit_ceil(std::max<uint32_t>(static_cast<uint32_t>(slots), 256u));}@coderabbitai[bot] on GitHub · 2026-10-08 20:55 UTC · original · edited 2026-10-08 21:41 UTC
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 9905
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 17667
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 21400
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 41490
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 19528
Guard bindless table descriptors against device limits.
ImageTableCapacitycan select capacities above a device'smaxPerStageDescriptorSampledImages.NativeDescriptorCountpasses the resulting table count to the sampled-image descriptor layout, andCreateDescriptorLayoutdoes not check that limit before callingcreateDescriptorSetLayout. A device with a lower limit can therefore fail pipeline creation. Also check the aggregate sampled-image count against the 65,536-descriptor pool budget when a layout contains multiple table ranges. Use the existing non-table path or return a controlled failure when either limit is exceeded.✅ Confirmed as addressed by @TheCruZ
@coderabbitai[bot] on GitHub · 2026-10-08 20:55 UTC · original · reviewed
Actionable comments posted: 2
🧹 Nitpick comments (1)
ℹ️ Review info
⚙️ Run configuration
7e7fba2b-ac24-4c54-9d9b-5bbdad8876b6📥 Commits
Reviewing files that changed from the base of the PR and between
2f4b8a335dand 1d3a50e7eeb1ad55a57bff3600b944228b8e6ce8.📒 Files selected for processing (25)
CMakeLists.txtsrc/common/assert.cppsrc/common/assert.hsrc/graphics/host_gpu/renderer/cache/textureCache.cppsrc/graphics/host_gpu/renderer/cache/textureCache.hsrc/graphics/host_gpu/renderer/pipeline/descriptorHeap.cppsrc/graphics/host_gpu/renderer/pipeline/descriptors.cppsrc/graphics/host_gpu/renderer/pipeline/descriptors.hsrc/graphics/host_gpu/renderer/render.hsrc/graphics/presentation/window/vulkanWindow.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterAnalysis.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterImage.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterInternal.hsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterModule.cppsrc/graphics/shader/recompiler/ir/ResourceSnapshot.hsrc/graphics/shader/recompiler/ir/ShaderIR.hsrc/graphics/shader/recompiler/ir/passes/BindingLayout.cppsrc/graphics/shader/recompiler/ir/passes/ResourceMaterialization.cppsrc/graphics/shader/recompiler/ir/passes/ResourceMaterialization.hsrc/graphics/shader/recompiler/ir/passes/ResourceTracking.cppsrc/kernel/memory.cppsrc/kernel/memory.hsrc/kernel/memoryAddressSpace.inctests/ResourceTrackingTests.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.
@ -457,0 +473,4 @@uint32_t ImageTableCapacity(size_t slots) {return std::bit_ceil(std::max<uint32_t>(static_cast<uint32_t>(slots), 256u));}@TheCruZ on GitHub · 2026-10-08 21:14 UTC · original
Fixed in f78d0ab:
CreateDescriptorLayoutnow counts the sampled images of the layout (in total and per stage) and exits with a message naming the counts when they exceedmaxDescriptorSetSampledImages,maxPerStageDescriptorSampledImagesor the descriptor pool's sampled-image budget (nowDescriptorHeap::MaxSampledImages, the same constant the pool uses), instead of creating an invalid layout. There is no non-table path that can run these shaders (that is what this PR adds), so a clear failure is the fallback.@ -14,0 +29,4 @@if (g_soft_exit_depth > 0) {throw SoftExitError(fmt::format("{} ({}:{})", text, file, line));}}@TheCruZ on GitHub · 2026-10-08 21:14 UTC · original
I'm keeping the scope as it is. Everything that can be rejected from the T# and the backing alone (
ImageTableSlotCompatible, readable backing, format and dimension checks inResolveTexture) happens before the texture cache is touched, so the common rejections never reach mutating code. The scope only matters for errors further down, inside the cache, and those were fatal before this PR: without it the same failure terminates the emulator. Making every cache mutation that has anEXITafter it transactional (ExpandImage, overlap merging, clear materialization) is a large change to the texture cache that is outside this PR; in the worst case a failed element leaves an extra image registered over memory the shader does not read through that slot, which the cache already handles like any other overlap.@TheCruZ on GitHub · 2026-10-08 21:15 UTC · original
@coderabbitai About the nitpick on the mapping assertion in
ShaderRecompilerComputeTests: I'm leaving it as is in this PR. The slot mapping that materialization produces is checked entry by entry inResourceTrackingTests(duplicates share a slot, null and invalid T#s map to the null slot), and the GPU case covers the shader side of the same layout; wiring the produced mapping into a GPU sample test would mostly duplicate those two.@ -457,0 +473,4 @@uint32_t ImageTableCapacity(size_t slots) {return std::bit_ceil(std::max<uint32_t>(static_cast<uint32_t>(slots), 256u));}@coderabbitai[bot] on GitHub · 2026-10-08 21:15 UTC · original
@TheCruZ, thanks for the fix and clarification. The checks you describe cover the per-stage limit, descriptor-set limit, and sampled-image pool budget. UsingDescriptorHeap::MaxSampledImagesfor both the check and the pool keeps the budget consistent.A clear failure is appropriate because these GPU-indexed shaders have no working non-table path.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@ -14,0 +29,4 @@if (g_soft_exit_depth > 0) {throw SoftExitError(fmt::format("{} ({}:{})", text, file, line));}}@coderabbitai[bot] on GitHub · 2026-10-08 21:15 UTC · original
@TheCruZ, thanks for the clarification. Ordinary T# and backing rejections occur before texture-cache access. The remaining concern is recovery after a cache-internal failure, not those early rejections.I understand your decision to retain
SoftExitScopeand keep transactional cache changes outside this PR. I will not press for that change here.Would you like a follow-up issue for exception safety in speculative texture-cache lookup?
✏️ Learnings added
You are interacting with an AI system.
@coderabbitai[bot] on GitHub · 2026-10-08 21:15 UTC · original
🧩 Analysis chain
🏁 Script executed:
Length of output: 201110
@TheCruZThanks for clarifying.TestBindlessImageTablechecks the exact slot mapping and its refresh after descriptor changes. That supports keeping the mapping-size assertion inShaderRecompilerComputeTests.cppas is. I withdraw the nitpick.✏️ Learnings added
You are interacting with an AI system.
@ -457,0 +473,4 @@uint32_t ImageTableCapacity(size_t slots) {return std::bit_ceil(std::max<uint32_t>(static_cast<uint32_t>(slots), 256u));}@TheCruZ on GitHub · 2026-10-08 21:41 UTC · original
Follow-up in
4d0b7f2a: GTA V's ray tracing table needs ~82000 sampled images in one set, more than the 65536 a pool held, so the pool now holds 262144 sampled images and the layout check still fails clearly above that.@ -457,0 +473,4 @@uint32_t ImageTableCapacity(size_t slots) {return std::bit_ceil(std::max<uint32_t>(static_cast<uint32_t>(slots), 256u));}@coderabbitai[bot] on GitHub · 2026-10-08 21:42 UTC · original
@TheCruZ, thanks for the update. The new 262,144 sampled-image pool budget covers GTA V’s reported requirement of about 82,000 sampled images in one set. Keeping the device-limit checks and the sharedDescriptorHeap::MaxSampledImagescheck preserves clear failure when a layout exceeds either limit.✏️ Learnings added
🧠 Learnings used
✅ Review thread resolved.
You are interacting with an AI system.
@overlordxrz-source on GitHub · 2026-10-09 01:32 UTC · original
Thanks for this, it's a clean way to handle large GPU-indexed heaps. I went through the diff at
4d0b7f2a. The SPIR-V side looks right to me: sized array,NonUniformon the index, pointer, image and sampled image, and the index can't leave the array becausecapacity >= slotsand the entry is clamped. A few things I think are worth fixing before it lands:1. Linux/macOS: a soft exit inside the texture cache leaves
m_lockheld.On GCC/Clang everything except
common,descriptors.cppandpipelineCache.cppis built with-fno-exceptions(src/utils.cmake:99/104).ResolveTableTexture→FindImageSpeculative→FindImageImpltakesstd::scoped_lock lock {m_lock}(textureCache.cpp ~1322) and canEXITunder it, for example "unresolvable equal-address image overlap" (~895) or image creation. When that throwsSoftExitError, it unwinds through-fno-exceptionsframes that have no cleanup pads. So the lock's destructor never runs, thecatchin descriptors.cpp succeeds, and the next texture-cache call spins forever. Main prints a fatal error at that point instead. Windows is fine because clang-cl keeps/EHsc. I checked the mechanism with a 3-TU model (RAII guard in a-fno-exceptionsTU between thrower and catcher): the guard is not released. Smallest fix is addingtextureCache.cppto the-fexceptionslist:Another option is to suspend the soft scope around the
FindImage*call, so cache-internal errors stay fatal like on main.2. Non-update-after-bind limits on MoltenVK and some drivers.
The new layout check correctly uses
maxPerStageDescriptorSampledImages/maxDescriptorSetSampledImages. But MoltenVK reports those as 128 or 256 per stage (5× that per set), and raises only the update-after-bind limits to 1e6 with Tier-2 argument buffers (MVKDevice.mm). gpuinfo also has ~200 Windows reports at 200. SinceImageTableCapacityhas a floor of 256, every table pipeline exits on those devices. Andtable_arraynow replaces the direct-lookup and key-probe paths for scalar stride-32 tables of any size, so shaders that worked there before would start exiting. Could table bindings useUPDATE_AFTER_BIND | PARTIALLY_BOUND(with an update-after-bind pool, checked against the UAB limits)? If not, could the old paths stay as the fallback when the device limit is too small?3. Pool budget for every game.
DescriptorPoolSizesnow gives every pool 262144 sampled images (was 8192), and several pools are alive while ticks retire. On drivers that allocate pool memory up front frompPoolSizes, that is a lot of memory per pool for games that never use tables. With an ~82k-descriptor layout, a pool also holds only 3 sets. So it switches every 3 dispatches,m_sets.clear()drops the other layouts' batches, andAllocatere-tries 32→16→8→4 before 2 succeed. A separate heap for table layouts, sized from the layout, would keep the general pool at 8192 and avoid the churn.4. Small:
vulkanWindow.cpp.shaderSampledImageArrayNonUniformIndexingis already required byRequiredVulkan12Features()(checked at device selection), so that assignment and half the warning are no-ops.shaderSampledImageArrayDynamicIndexingis only enabled if supported, while the module always declaresSampledImageArrayDynamicIndexingfor table bindings. It's probably simplest to make it required too.Also a heads-up: main gained Nmzik's SPIR-V emitter refactor today.
git merge-treeshows conflicts in descriptors.cpp, render.h, spirvEmitterImage.cpp, spirvEmitterModule.cpp, ShaderIR.h, andBindingLayout.cppwas deleted on main (e1ac893a), so the table-range allocation needs a new home. #1258 will need the same rebase.I compile-checked the changed files with an x86_64 Clang cross build. I couldn't run the test suites in my environment.
Written with AI assistance.
Pull request closed