RendererThreading

Chuck Smith edited this page 2026-11-25 01:11:23 +00:00 · 1 commit

Renderer threading: design note for #3

Written 2026-11-12 as step 8 of issue #1 (Docs/Multithreading.md, section 9), from what steps 5 to 7 measured on Linux. It is input for #3 (unifying the D3D12 and Vulkan backends): the shared renderer that #3 produces should be built around the frame and threading model below, so that the threading isn't added afterwards a second time. Nothing here is implemented except where it says so.

1. What the measurements showed

All numbers: clang Release, 24 hardware threads, RADV (AMD RX 6800 XT), Vulkan. Details in Docs/Multithreading.md section 9 and in issue #1.

Work Size One thread Job system Notes
World matrices (transform::update_matrices()) 100,000 transforms 1.6 ms 0.36-0.47 ms Memory bound after ~8 threads.
Per-object data (fill_per_object_data()) 1,526 objects 34 us 37-48 us ~22 ns an object: cheaper than waking the workers.
Recording, depth prepass + gpass (prototype) 6,400 render items ~1.8 ms ~0.42 ms Batches of 512 per secondary command buffer.
prepare_render_frame() 6,400 render items 1.5 ms 1.5-1.6 ms Serial: now the largest cost.
Whole frame (one view) 6,400 render items 3.2-3.4 ms 2.23-2.27 ms
Test content loading 14 assets 170-185 ms ~100 ms Same as a thread per asset.

What follows from it:

  • Parallelism pays off only per batch of real work. Waking a sleeping worker costs tens of microseconds. Work of less than ~50 us (a few thousand cheap items) should stay on the calling thread; parallel_for batch sizes are set from measurements (1024 transforms, 1024 objects, 512 draws), and anything up to one batch never leaves the caller.
  • Recording parallelizes well (4x with 24 threads). The draw loop is cheap per item but long.
  • Render preparation is the next bottleneck: ~240 ns a render item, serial, and it scales with items, not entities. It is also where a frame packet (section 4) would be built.
  • Many small jobs per frame need workers that are awake. Today every parallel_for in a frame wakes the workers again. Letting a worker spin briefly (a few microseconds) before it sleeps, or giving a frame one wake-up for all its phases, is worth measuring before the batch sizes are revisited.

2. The renderer's frame today

Both backends have the same structure (Vulkan was ported module by module from D3D12).

  • A "frame" is one surface. Surface::render() is one frame of the graphics command queue: it waits for the frame index's fence, resets its command allocator/pool, records, submits and presents. The frame index advances per surface, so with 4 windows the 3 frames in flight cover less than one engine frame, and each window's frame waits for the GPU work of the windows before it.
  • Resources per frame index are shared by all surfaces in turn: the constant buffer (1 MB, cleared at the start of each surface's frame), the light buffers (light_buffers[frame_index]), deferred releases.
  • Resources shared by all surfaces outright: the gpass render targets (one main buffer and one depth buffer, sized to the largest surface), the resource barrier tracker (resource_barriers), the gpass frame cache (per surface since step 7 on Vulkan; one global in D3D12).
  • Per surface already: the swapchain, the light culler (light_cullers[light_culling_id], per frame index), the camera.
  • Uploads are synchronous: UploadContext::end_upload() submits the copy on the graphics queue and waits for it on the calling thread (4 upload frames, so 4 uploads can be in flight from 4 threads). Loading runs as background jobs (step 5), which hides the wait from the frame but holds a worker.
  • Light culling may recreate buffers while it records (cull_lights() resizes the light grid when the surface size changed), and the gpass binds them. That is why the recording prototype records depth and gpass in two parallel passes.
  • The editor renders on its own thread (RenderFrame(), RenderSurfaceHost.cs), outside the job system: its jobs run on the workers while it waits without helping.

3. The model to build in #3

Two kinds of context

  • Frame context, one per frame in flight (frame_buffer_count), indexed by the engine frame (frame::index() % frame_buffer_count), not by surface:
    • the fence value of that frame;
    • the per-frame upload/constant memory: a linear allocator large enough for all surfaces of the frame (or one block per surface taken from it);
    • deferred releases;
    • per thread (jobs::worker_index(), plus one slot for a thread outside the pool): Vulkan command pools for secondary command buffers (the step 7 prototype, ThreadCommandPools), D3D12 command allocators and command lists.
  • Surface context, one per surface, in its own frame-in-flight copies where the GPU reads it:
    • the gpass cache (render items, pipelines, per-object and material data references);
    • its render targets (gpass main and depth buffers), or targets taken from a pool keyed by size and format;
    • the barrier tracker for its resources;
    • the light culler (already per surface) and its own light buffer copy;
    • the frame packet (below).

A frame then is: wait for the frame context's fence once, reset it, prepare and record every surface (in parallel when there is enough work), submit all surfaces' command buffers in one submission, and present all swapchains together (vkQueuePresentKHR takes several; D3D12 presents per swapchain after one ExecuteCommandLists).

Frame packet (stage 2 of Docs/Multithreading.md section 3)

Render preparation becomes the only code that reads component data (transforms, geometry, lights). It writes an immutable packet per surface: camera matrices, the visible render items with their pipeline and buffer references, per-object data and material data in the frame's constant memory, light data. Recording reads only the packet. That allows, later, the game update of frame N+1 to run while frame N is recorded (one frame of latency); whether to do that is decided when it is needed. The packet is built in parallel:

  • The content queries (get_vulkan_render_item_ids, get_items, get_views, get_materials and their D3D12 counterparts) take one lock per call and loop over items. Split them into batches that read under a shared (reader) lock, or snapshot the content tables at the sync point, when content changes are applied.
  • Material data: offsets by a prefix sum over the items, then filled in parallel.
  • (Done 2026-11-13: range()/gpu_address() take no lock any more, allocate() is lock-free, and the buffer grows with the item count.) Was: ConstantBuffer::range() / gpu_address() take a mutex for each item; they only compute an offset from a pointer and should be lock-free. Allocation stays a bump of an atomic offset.
  • LOD selection and visibility (frustum culling, not done today) per item, in parallel.

Recording

  • What the step 7 prototype does stays: batches of items, each into a secondary command buffer (Vulkan, dynamic rendering with VK_RENDERING_CONTENTS_SECONDARY_COMMAND_BUFFERS_BIT) or a command list (D3D12, executed in order), recorded by jobs, with the bindings each batch needs at its start. Recorded serially up to one batch.
  • Resize before recording. Everything that may recreate a resource (gpass targets, light culling buffers, light buffers) is done in preparation, on the frame thread, so that all passes of all surfaces can be recorded in one parallel pass.
  • Vulkan alternative to evaluate: several primary command buffers with suspend/resume rendering (VK_RENDERING_SUSPENDING_BIT / RESUMING_BIT) instead of secondaries; same parallelism, no inheritance info, but the dynamic state isn't inherited either. Measure on RADV and NVIDIA before choosing.
  • D3D12: one command list per batch from the thread's allocator, executed in order with the frame's primary lists in one ExecuteCommandLists. Root signature, descriptor heaps, viewport and render targets are set at the start of each list (D3D12 lists inherit nothing). Bundles aren't needed. The ExecuteIndirect path (#11) records one command per pass and doesn't need splitting.
  • Barriers stay on the thread that builds the surface's command buffer, from the surface's own tracker (or a render graph, #3 option C, which would derive them).

Asynchronous uploads

  • A transfer queue where the device has a separate one (Vulkan: a queue family with transfer but no graphics; D3D12: a copy queue, always available), with its own timeline semaphore/fence. Without one (lavapipe), the graphics queue as today.
  • An upload returns at once. The resource records the fence value at which its data is complete; end_upload() doesn't wait. The upload memory of a context is reused when its fence value has passed.
  • Render preparation skips what isn't ready (a render item whose mesh, textures or material aren't uploaded yet isn't drawn this frame), or the frame waits for the fence value at the sync point when a load must be complete before the game starts using it. Content IDs exist from the call on, so game code doesn't change.
  • Vulkan ownership: buffers and images uploaded on a transfer queue need a queue family ownership transfer (release barrier on the transfer queue, acquire on the graphics queue, at the first frame that uses them), or VK_SHARING_MODE_CONCURRENT for the two families. Measure which; concurrent is simpler and usually free for buffers.
  • D3D12: a copy queue leaves resources in COMMON; they are promoted on first use on the graphics queue (buffers always, textures for read states), so no explicit transition is needed for the usual cases.
  • Background pipeline creation (#10) follows the same pattern: a pipeline is ready at some point, and items whose pipeline isn't ready are skipped.

Threads and the editor

  • The frame thread prepares and submits; the workers record and build packets; loading and pipeline creation run on the background lane. No dedicated render thread in the engine; a later "game update of N+1 while N records" is a scheduling change on top of the frame packet, not a new thread.
  • The editor's render thread should join the job system. Today it waits without helping and uses the extra command pool slot. A jobs::attach_thread()/detach_thread() pair (giving a foreign thread a worker index and letting its waits help) would make it a full frame thread; the UI thread, which calls InitializeEngine(), would then not need to be the pool's frame thread.

4. What is shared and what is per backend

Fits #3 option A (shared CPU-side modules) and B (thin RHI) alike:

  • Shared: frame and surface contexts (as data), frame packet building (render item queries, LOD, visibility, per-object and material data), batching and the job orchestration, the upload "ready at fence value" bookkeeping.
  • Per backend: command pools/allocators and command buffers/lists per thread, beginning a batch (the bindings it needs), executing batches inside a pass, submission and presentation, queues and their fences, ownership transfers.

5. Suggested order within #3

  1. Frame context per engine frame, one submission and one fence wait per frame for all surfaces. Surface contexts with their own render targets and barrier trackers. (Measure: 4 windows, frame time and GPU overlap.)
  2. Resizing moved out of recording; one parallel recording pass for all passes of a surface (both backends).
  3. Frame packet; render preparation in parallel; lock-free ConstantBuffer::range(). (Measure: the 6,400-item benchmark, prepare_render_frame() alone.)
  4. Surfaces prepared and recorded in parallel.
  5. Asynchronous uploads with a transfer/copy queue.
  6. jobs::attach_thread() for the editor's render thread.
  7. Worker spinning before sleeping, measured against batch sizes.

6. Open questions

  • Vulkan: secondary command buffers or suspend/resume primaries (measure on two vendors).
  • Render targets per surface or from a pool (memory with several large windows).
  • Queue ownership transfers or concurrent sharing for uploaded resources.
  • Whether render preparation snapshots content at the sync point (no locks while preparing) or reads under a shared lock (simpler, some contention).
  • When to pipeline the game update of frame N+1 with the recording of frame N (one frame of latency).

Pages 19

View all

Clone this repository