Skip to content

Zero-fill per-object slots that a batch's object data leaves unwritten - #182

Draft
kristux wants to merge 1 commit into
carbonengine:mainfrom
kristux:fix/gdr-zero-fill-unwritten-per-object-data
Draft

kristux wants to merge 1 commit into
carbonengine:mainfrom
kristux:fix/gdr-zero-fill-unwritten-per-object-data

Conversation

@kristux

@kristux kristux commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Summary

On Metal, the GPU-driven batch path (RenderGdprBatches with g_gdrEnabled) crashes when an effect reads pixel-shader per-object data that the object's C++ per-object data does not provide. The crash is in ConstantBufferAllocator::GetPage, called from Tr2IndirectDrawBuffer::Submit, with a garbage page index.

RenderGdprBatches already zero-fills the per-object slots when a batch has no object data at all. It does not do so when the object data writes some stages but not the one the effect reads. This PR closes that gap:

  • Writer tracking: Tr2IndirectDrawBufferWriter records which per-object stages the current command wrote.
  • Zero-fill: RenderGdprBatches zero-fills every per-object stage the layout declares but the batch left unwritten, and logs the effect as before.
  • Bounds check: ConstantBufferAllocator::GetPage now asserts on an out-of-range page and returns nil, instead of reading past its page table.

Minimal repro (by construction)

  1. Take an effect whose pixel shader declares the per-object constant buffer (register Tr2Renderer::GetPerObjectPSStartRegister()).
  2. Draw it through the GPU-driven batch path on Metal, for an object whose Tr2PerObjectData::ApplyConstantBuffers writes only VERTEX_SHADER.
  3. The indirect draw's perObject[1] is never written for that command, and Submit binds whatever value was already there.

Mechanism

All line numbers are at bf116baa.

  • The layout declares the pixel-shader slot. Tr2IndirectDrawBufferLayout sets m_hasPerObjectData[1] from the pixel-shader program's constant-buffer mask (trinity/Tr2IndirectDrawBuffer.cpp:52).
  • The object data writes only some stages. SetPerObjectData( stage, ... ) writes m_buffer->perObject[stage] (Tr2IndirectDrawBuffer.cpp:97, :112). Several Tr2PerObjectData::ApplyConstantBuffers overrides write only the vertex-shader slot, or vertex and geometry.
  • The zero-fill covers only "no object data at all". In RenderGdprBatches (trinity/Tr2RenderContext.cpp:693-709), the zero-fill branch is an else of if( batch.m_objectData ). A batch that has object data, but not for the pixel-shader stage, skips it.
  • Indirect args are never cleared. On Metal they are DP structs allocated with new DP[m_pageSize], which default-initialises them (Tr2IndirectDrawBuffer.cpp:256). SetFrameNumbers reuses them from offset 0 every frame (:382-383). An unwritten slot therefore holds an earlier draw's value or indeterminate memory.
  • Submit trusts the slot. When layout.m_hasPerObjectData[1] is set, Submit unpacks dp.perObject[1] as (page << 32) | offset (Tr2IndirectDrawBuffer.cpp:458). It passes page to ConstantBufferAllocator::GetPage (trinityal/metal/MetalUtils.mm:424-427), which indexes m_pages[page] unchecked.
  • The crash we see. Dumps show EXC_BAD_ACCESS in GetPage with page indices such as 0x55e4b002, or in the ARC retain of the pointer read from past the table.

On DX12 the same unwritten slot holds a stale root CBV address. The existing comment there says that hangs the GPU, so the fix is in the shared draw path rather than in the Metal backend.

Fix

  • Tr2IndirectDrawBuffer.h/.cpp:
    • The writer gets a m_writtenPerObjectData stage bitmask. Both SetPerObjectData overloads set it, and Next() clears it.
    • A new IsPerObjectDataWritten( stage ) method reads it.
  • Tr2RenderContext.cpp: after ApplyConstantBuffers, RenderGdprBatches checks VERTEX_SHADER and PIXEL_SHADER. Any stage that HasPerObjectData but was not written gets the existing 4 KB zero block.
    • This replaces the old else branch. A batch with no object data takes the same path, with the same result as before.
    • The capped error log now names the shader stage, and keeps its old wording otherwise.
  • MetalUtils.mm: GetPage does CCP_ASSERT( page < MAX_PAGE_COUNT ) and returns nil when out of range. Metal accepts a nil buffer binding, and nil.gpuAddress is 0. Any future slot bug becomes a wrong draw instead of a crash.

Cost: one 4 KB zero upload per offending batch and stage, per frame. That is what the existing no-object-data path already pays. Well-formed batches pay one bit-or per SetPerObjectData.

Why not clear the indirect args instead? Zeroing a slot means page 0, offset 0 on Metal (someone else's constants) and a null GPU address on DX12. Writing a real zero block gives defined data on both backends, and it reuses the existing zero-fill.

Linked issue (optional)

Testing

Run on an Apple Silicon Mac, Apple clang 21.0.0, macOS SDK 27.2.

  • Not built: trinity and the game. Trinity's vcpkg dependencies are not set up on this machine. The trinity/ translation units (Tr2IndirectDrawBuffer.cpp, Tr2RenderContext.cpp) need Python, Blue, granny and cmf headers, so they were not compiled at all. The writer tracking and the zero-fill loop are reviewed by reading only, and need a real build to confirm.
  • Compiled: trinityal/metal/MetalUtils.mm, with -fobjc-arc -std=c++17 -DTRINITY_PLATFORM=TRINITY_METAL, against carbon-core and imageio headers that may not match the versions vcpkg pins.
  • GetPage red/green, out-of-repo harness: the real MetalUtils.mm is linked to a small driver on a real MTLDevice. The driver allocates once, checks GetPage of that page is non-nil, then calls GetPage( 0x55e4b002 ).
    • Before (base): segfault, exit 139.
    • After: returns nil, exit 0, with asserts disabled and enabled. With asserts enabled, the assert fires once.
  • Not verified: that the zero-fill stops the crash in a running client. We will confirm that in our client once this is built.
  • There is no in-repo test, because trinityal/tests has no Metal test target. Happy to add one if you want it.

Questions for the Trinity team

  1. Should a per-object data type that writes only some stages be considered a content error (log, as now), or should each ApplyConstantBuffers override write every stage the layout declares?
  2. On Metal, Tr2IndirectDrawBufferLayout::m_hasMaterialData / m_hasPerObjectData and DP::material / DP::perObject have 2 entries. ShaderType has 6. Tr2Material::ApplyConstantBuffers loops over all 6 stages and calls HasMaterialConstants( i ), and some per-object types call SetPerObjectData( GEOMETRY_SHADER, ... ). On Metal those index past the 2-entry arrays. Should the Metal side clamp to vertex and pixel? Not changed here.
  3. Separate follow-up, not part of this PR: ConstantBufferAllocator::Allocate (MetalUtils.mm:390-422) moves to the next page without checking MAX_PAGE_COUNT. Past 32 pages (64 MB before a reset) it writes through m_pageContents[32], which aliases m_pages[0], and corrupts that MTLBuffer object. We did not hit it here (about 0.3 to 0.6 MB per frame), but an out-of-repo harness corrupts the heap at 96 MB. Is 64 MB per frame a deliberate cap? Would you like a separate PR that guards it?
  4. Also from reading only, not observed: MetalWorkQueue::BlitToDrawableAndPresent waits on m_frameSemaphore (count 2, MetalWorkQueue.mm:97 / :557). It returns false at :585 (no drawable) and :617 (pipeline creation failed) without signalling it. The only signal is in the completion handler at :666. If nothing else rebalances it, two failed presents would block the next present forever. Is that right?

🤖 Generated with Claude Code

RenderGdprBatches zero-filled the per-object constant slots of an
indirect draw only when a batch had no object data at all. A batch whose
object data writes some stages but not others (for example vertex-shader
data only, drawn with an effect that also reads pixel-shader per-object
data) left the other slot holding whatever an earlier draw wrote there:
indirect draw arguments are reused between draws without being cleared.
On Metal, Tr2IndirectDrawBuffer::Submit then passed that stale value to
ConstantBufferAllocator::GetPage as a page index and crashed.

The indirect draw writer now records which per-object stages the current
command wrote, and RenderGdprBatches zero-fills every stage the layout
declares but the batch left unwritten, logging the effect as before.
ConstantBufferAllocator::GetPage asserts and returns nil for an
out-of-range page instead of reading past its page table.
@ccpgames-carbon

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants