Renderer

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

Renderer: one renderer for both backends (#3)

Written 2026-11-21 for issue #3 (unify the D3D12 and Vulkan backends), together with #52 step 6 (geometry and lights as components, render preparation reading them) and #4 group B (RAII for GPU objects, std::span, the naming macros). The threading model is Docs/RendererThreading.md (from #1); this note decides how the code is split and in which order the work goes. Section 7 holds the user's decisions (2026-11-21), section 6 the plan. Nothing here is implemented yet.

1. What is there today

Both backends were ported module by module, so they have the same files, names and structure. Measured 2026-11-21 (Engine/Graphics/{Direct3D12,Vulkan}, lines of code without blank lines, comments and lone braces; backend names normalized, d3d12::/vulkan::, D3D12/Vulkan prefixes, then a line diff):

Module D3D12 Vulkan Identical Share of D3D12
Camera (.cpp + .h) 275 275 273 99%
Light 681 687 642 94%
Shaders 52 55 47 90%
Interface 56 65 41 73%
Content 755 734 406 54%
Resources 544 608 258 47%
Light culling 240 240 106 44%
Upload 141 182 65 46%
Core 674 1,002 188 28%
Surface 131 295 32 24%
GPass 619 409 104 17%
Post-process 97 111 18 19%
Helpers 626 522 12 2%
All 4,943 5,249 2,207 45%

("All" includes the backends' CommonHeaders.h, 52/64 lines, 15 identical.)

What the numbers say:

  • Camera, the light sets and shader loading are API-free code written twice. LightSet (about 600 lines: light storage, dirty tracking, cullable/non-cullable split, cone bounding spheres) touches the API only through its GPU buffer class (D3D12LightBuffer/VulkanLightBuffer).
  • Content is half bookkeeping (render items, materials, LOD selection, the pipeline cache by shader hashes) and half GPU objects (buffers, textures, pipelines).
  • The frame is the same sequence on both: render_surface() waits for the frame's fence, resets the per-thread command pools/allocators, clears the constant buffer, collects the render items, builds the backend frame info, then depth prepass → light buffers + light culling → gpass → post-process, with the same barriers spelled in each API, and submits and presents. The real differences: the command list type, barrier states (D3D12 states vs Vulkan stage/access/layout), swapchain acquire and resize, root signatures vs pipeline layouts with push descriptors.
  • Helpers (2%) are honestly per API: pipeline state streams vs pipeline create infos, barrier helpers.

The renderer's objects duplicate the ECS since #59. The scene is ECS components now (render::MeshRenderer, the four light components, render::Camera in EngineAPI/RenderComponents.h). graphics::scene::sync() (SceneSync.cpp, 511 lines) diffs them each frame into the renderer's own objects through the platform interface: render items (add_render_item), lights in light sets (create/set_parameter), cameras (create/set_parameter). Those objects then follow their entity's transform. Outside the sync, the object API is used only by:

  • Engine/Components/Geometry.cpp (geometry::create(), the old plain-entity path: editor viewports and game.bin);
  • EngineDLL/EngineAPI.cpp (the editor viewport's camera);
  • EngineTest/Lights.cpp and GraphicsTests/SceneTests.cpp, TestSession.cpp (tests).

2. The options

A. Shared CPU-side modules, two backends. The API-free code moves to Engine/Graphics/ once (camera math, light sets, content bookkeeping, render preparation and the frame packet, batching, the frame/surface contexts as data). Each backend keeps its own pass recording, resources, swapchain and submission, behind a narrow internal interface fed by the frame packet. Expected: about 1,500 of the 2,200 identical lines go (camera, lights, shaders, interface, content bookkeeping, the gpass cache); the rest is the parallel structure of Core/Resources/Surface, which stays written twice but small.

B. A thin RHI (buffers, textures, pipelines, barriers, command recording) with the renderer's passes written once on top. Removes the parallel frame code too, and makes a third backend (Metal, WebGPU: the reason Slang was kept as an option in #45) cheaper. Costs: an abstraction design for barriers and bindings that fits D3D12 root signatures and Vulkan push descriptors + the mutable descriptor heap, an indirection on every command, and a rewrite of every pass at once. For one forward+ renderer with four passes, the RHI would be larger than the code it removes.

C. A render graph that declares each pass's reads and writes and derives the barriers and transitions (hand-coded in both backends today, add_transitions_for_*). Sits on top of A or B. Pays off with many passes (shadows, SSAO, TAA, post chains); with four it mostly moves the barriers into declarations.

Decided (user, 2026-11-21): A now; B and C are follow-up tickets (#67 thin RHI, #66 render graph). The frame packet is the boundary: everything up to the packet is shared, each backend records from the packet. C is taken up when the renderer gets its first new pass (shadows, SSAO, TAA, a post chain); B when a third backend is planned or when, after #3, the per-backend frame code is still mostly parallel (the section 1 diff, measured again at the last step). A graph or an RHI sits on top of A later without undoing it. C's design sketch from the discussion is in #66.

3. The renderer reads the components (#52 step 6)

With the scene in the ECS, the renderer's own objects are a second copy of the same data. Render preparation reads the components directly and writes the frame packet:

  • Render items: a query over render::MeshRenderer + the world matrix (transform:: components, current after transform::update_matrices()); per chunk: visibility (math::Frustum), LOD, pipeline and material lookups, the per-object data in the frame's constant memory. ECS chunks are the natural batches for parallel_for.
  • Lights: queries over the light components, grouped by light_set; the LightSet class becomes the packet's light lists (cullable/non-cullable, bounding spheres) built per frame. Change detection per chunk (the ECS's versions) keeps the light buffer uploads to what changed, if measuring shows rebuilding everything costs too much.
  • Cameras: render::Camera + the entity's transform → view/projection matrices in the packet; a surface renders from a camera entity (FrameInfo names the entity, as scene::frame_info() already does).
  • What goes: SceneSync.*, the light/camera/render-item halves of PlatformInterface, graphics::Light, graphics::Camera as renderer objects, light set creation by key, and the backends' Camera and Light modules (their GPU buffer part moves to the packet's upload). Content (meshes, textures, materials, shader groups) stays a backend API: it is GPU data loaded from assets.
  • Converted: geometry::create() writes a render::MeshRenderer (the old plain-entity path), the editor viewport's camera is an entity with render::Camera, EngineTest/Lights.cpp and the graphics tests make light entities.

4. Threading and frames

As Docs/RendererThreading.md sections 3-5, built into A's shared modules from the start:

  • a frame context per engine frame in flight (fence, constant memory, deferred releases, per-thread command pools/allocators), one fence wait, one submission and one present call per engine frame for all surfaces;
  • a surface context per surface (its gpass cache, render targets, barrier tracker, light culler, frame packet);
  • resizing before recording, then one parallel recording pass per surface (both backends record in batches of 512 already);
  • the packet built in parallel (per ECS chunk), surfaces prepared and recorded in parallel;
  • later steps of the same note: asynchronous uploads on a copy/transfer queue, jobs::attach_thread() for the editor's render thread, worker spinning.

5. #4 group B, as the code is touched

  • RAII for GPU objects: D3D12 holds 33 raw COM pointers (9 ComPtr), Vulkan 15 raw handle members with hand-written deferred release. One owning handle type per backend whose destructor queues a deferred release (Vulkan: vkx::Owned<VkBuffer> with its allocation; D3D12: ComPtr plus the same queue), in new and rewritten code.
  • std::span/std::string_view at the graphics API's boundaries (about 40 pointer + count parameters).
  • NAME_D3D12_OBJECT/NAME_VK_OBJECT (78 uses) → functions (set_name(object, "...")) that compile to nothing in Release, with debug markers per pass for RenderDoc/PIX.

6. Order of work

Each step leaves both backends building and running: the renderer test on both, GraphicsTests on Vulkan (validation and sync validation clean), D3D12 in the VM, UnitTests. Every step is checked on clang, GCC, MSVC and tidy before the next starts.

  1. Shared modules, no behavior change. Camera math, LightSet with a backend buffer hook, engine shader loading, the interface glue move to Engine/Graphics/. Done when the section 1 diff shows them gone from both backends.
  2. Render preparation from the components (#52 step 6). The frame packet (FramePacket.h): render items, lights and cameras from ECS queries; SceneSync and the object halves of PlatformInterface removed; geometry::create(), the editor viewport camera, EngineTest/Lights.cpp and the graphics tests converted to components. The light buffers are rebuilt from the packet each frame (decision 8); measure the renderer test.
  3. Frame context per engine frame, surface contexts. One fence wait, submission and present call per engine frame for every surface; each surface with its own render targets and barrier tracker (decision 4). Measure four windows.
  4. Resizing out of recording; one parallel recording pass. Everything that may recreate a resource (gpass targets in gpass::set_size(), the light culling buffers in cull_lights(), light buffers) runs during preparation on the frame thread; then all passes of a surface record in parallel on both backends. The D3D12 ExecuteIndirect path goes (decision 3). RenderDoc on Vulkan (Linux) and PIX/RenderDoc on D3D12 (desktop) for parity.
  5. Preparation in parallel per ECS chunk; surfaces prepared and recorded in parallel; content reads under a shared lock (decision 5). Measure the 6,400-item benchmark, preparation alone and the whole frame.
  6. Cleanup: #4 group B in what steps 1-5 touched; the section 1 diff measured again and recorded here (input for #67); desktop checks (real GPU, both backends, the editor).
  7. Separate tickets afterwards: asynchronous uploads on a copy/transfer queue, jobs::attach_thread() for the editor's render thread, worker spinning (Docs/RendererThreading.md steps 5-7); #28 (GraphicsTests on D3D12) right after #3.

Steps 1-2 remove the most code; 3-5 are where the frame time changes. A step that needs a user decision not listed here stops and asks.

7. Decisions (user, 2026-11-21)

  1. A: shared CPU-side modules, two backends, the frame packet as the boundary. B (thin RHI) is #67, C (render graph) is #66, each with the condition for taking it up.
  2. The renderer reads the components; its object API goes (lights, cameras, render items, light sets by key, SceneSync). Content stays an API.
  3. D3D12's ExecuteIndirect gpass is removed (2.5-4x slower on the GPU than direct draws, #11).
  4. Render targets per surface; a pool later if memory calls for it.
  5. Content is read under a shared (reader) lock during preparation, measured in step 5.
  6. Vulkan keeps secondary command buffers; suspend/resume primaries revisited on an NVIDIA machine.
  7. The shared code is headers + .cpp in Engine/Graphics/, not a named module (the backends' headers need the packet types; headers can't import).
  8. Lights are rebuilt from the components each frame; change tracking only if the renderer test shows a cost.

8. Step 1 done: shared modules (2026-11-21, committed in 54bfffe)

What moved to Engine/Graphics/ (both backends use it; no behavior change):

  • Camera.h/.cpp (was D3D12Camera.*, Arash's, moved; VulkanCamera.* deleted): graphics::camera::RenderCamera and the camera API. The backends' frame infos point to a camera::RenderCamera.
  • Lights.h/.cpp (from D3D12Light.cpp, Arash's): the light sets and the light API (graphics::light), and LightBuffers, the base class of each backend's per-frame light buffer: update() holds the copy algorithm (what changed per frame index, the 150% growth), and the backend implements size(), resize() and cpu_address(). The ambient light's texture descriptor indices come from the backend's content::texture::get_descriptor_indices, passed to light::initialize(). D3D12Light.*/VulkanLight.* keep only their buffer class, update_light_buffers() and the buffer accessors; the three shared queries are re-exported there with using-declarations, so calls in the backends didn't change.
  • EngineShaderFile.h/.cpp (from D3D12Shaders.cpp, Arash's): loading and reloading shaders.bin (graphics::engine_shaders); D3D12Shaders.cpp/VulkanShaders.cpp turn a shader into their byte code type. The Vulkan check that SPIR-V is 4-byte aligned now runs when a shader is handed out instead of after loading.
  • FramesInFlight.h: graphics::frame_buffer_count (3), instead of one constant per backend.
  • The interface glue: Renderer.cpp's set_shared_interface() fills the camera and light entries of PlatformInterface after the backend's (also after the PRIMAL_PLUS one), so the backends' Interface.cpp no longer do.

Measured (the section 1 diff): D3D12 4,943 → 4,024 lines, Vulkan 5,249 → 4,326, identical lines 2,207 (45%) → 1,308 (33%), with 976 shared lines in the new files. Left in the pairs: the light/shader/interface wrappers (each a few dozen lines), and the larger parallel structure of Core, Content, Resources and light culling, for steps 2-5.

Checked: Linux clang Debug + Release and GCC Debug (0 warnings, UnitTests 239/241, GraphicsTests 22 with validation and sync validation, the test game, header_check), ci.sh tidy 0, the source checks, the renderer test 10 s on RADV (validation clean). Windows VM: all four configurations with 0 C++ warnings, UnitTests 238 Debug / 240 Release, the renderer test on D3D12 (WARP, 60 s) and on Vulkan (lavapipe, 180 s, validation clean), exit 0. clang-tidy over the Windows databases (engine-debug, -release, -editor) for the touched files: 0.

Found on the way:

  • Tools/WindowsCompileDb/gen_windb.py had no path to the reflection generator's headers (X.generated.h, since #41), so every file including a reflected header was parsed with errors and clang-tidy reported findings that weren't there (7 in the touched files). It now takes them from build/linux-debug/<target>/reflection/ (README updated).
  • The VM's Release UnitTests link crashed MSVC (C1001 in vectortests.cpp, LNK1000) with a stale incremental LTCG database; deleting x64\Release\UnitTests.iobj/.ipdb fixed it (plan doc B16).
  • A clang build after ci.sh build linux-gcc-debug relinks only what changed into the same x64/Debug/, leaving GCC-built programs next to a clang-built engine library: every engine type is then registered twice and the unit tests fail. Build with --clean-first after switching compilers.

Desktop: plan doc A48.

9. Step 2: render preparation from the components (done 2026-11-22, committed in 54bfffe)

What step 2 found beyond section 3: the editor's viewports keep their own camera objects (and the editor never passes another camera), the old plain-entity geometry component (Components/Geometry.*) is no longer used (mesh parts write render::MeshRenderer, the editor sends an empty geometry list, game.bin stores no geometry), mesh parts draw LOD 0 (the sync passes thresholds of 0), and each backend's render item caches the pipelines of a mesh's submeshes.

Decided (user, 2026-11-22; every recommendation):

  1. The old geometry component goes (Components/Geometry.*, EntityInfo::geometry, EngineDLL's entity geometry descriptor, SetGeometryIds, the editor's leftover calls). render::MeshRenderer is the only way to draw a mesh.
  2. LOD by distance: preparation computes each mesh's distance to the surface's camera and picks its LOD (what the old editor path did). Meshes with several LODs now switch with distance.
  3. A backend render item per entity, kept by the shared preparation: made when an entity gets a MeshRenderer or its geometry/materials change, released when it goes. Destroying content still needs a flush first.
  4. graphics::Camera and graphics::Light leave the game API (EngineAPI/Camera.h, Light.h): cameras and lights are components only (CameraPart, the light parts, or the render:: components on plain entities).

Slices (each checked before the next): cameras from render::Camera each frame; light sets from the light components each frame; mesh render items from MeshRenderer with distance LOD; then the old API and SceneSync removed and their users converted (EngineDLL's viewports, the graphics tests, EngineTest, the editor's C#).

Done (2026-11-22):

  • Cameras: camera::RenderCamera (Graphics/Camera.h) is made each frame from an entity's render::Camera and world transform (camera::camera_of()); FrameInfo::camera_entity names the entity. Gone: graphics::Camera (EngineAPI/Camera.h), CameraInitInfo, CameraParameter, create_camera()/remove_camera(), the camera half of PlatformInterface. D3D12 renders with a default camera and nothing to draw when the entity has none (Vulkan skips the scene passes as before).
  • Lights: light::rebuild() (Graphics/Lights.cpp) builds every light set from the four light components each frame (enabled lights only; the first enabled ambient light of a set); LightBuffers::update(key) copies a set into the frame's buffers (no dirty tracking: decision 8). A light set is the lights that name its key: nothing creates or removes one. Gone: graphics::Light (EngineAPI/Light.h), LightInitInfo, LightParameter, the light API and the light half of PlatformInterface, the editor's add_light_set(0); CreateLightSet only hashes the name now.
  • Meshes: graphics::scene (Graphics/Scene.h/.cpp, was SceneSync.*): prepare() once a frame keeps one backend render item per entity with a MeshRenderer (decision 3) and rebuilds the lights; Surface::render() fills FrameInfo's render items and LOD thresholds, the distance from the camera to each mesh (decision 2). FrameInfo lists what the caller sets first (light set, camera entity, frame times); add_render_item()/remove_render_item() are internal (GraphicsPlatformInterface.h). scene::stats() counts render items, visible ones, enabled lights and light sets with lights.
  • The old geometry component is gone (decision 1): Components/Geometry.*, EngineAPI/GeometryComponent.h, EntityInfo::geometry, Entity::geometry(), game_entity::update_component() and ComponentType, EngineDLL's UpdateComponent/GetComponentId/SetGeometryIds exports and the descriptor's geometry, and the editor's matching C# (GeometryComponent, Geometry.GetComponentId(), SetComponentIds()). The layer table lost Components -> Graphics (one of #3's known tangles).
  • Converted: EngineDLL's viewport cameras (editor-owned entities with a render::Camera; resize, field of view and range write the component), EngineTest (scene::prepare()), the graphics tests (the scene's meshes and lights are entities with components; the LOD test moves the cameras; the 6,400-item benchmark is now 400 entities of 16 boxes, a MeshRenderer holds at most 16 materials).

Checked: Linux clang Debug + Release and GCC Debug (0 warnings; UnitTests 239/241, GraphicsTests 22 with validation and sync validation, the test game), the source checks, ci.sh tidy 0, the renderer test 12 s on RADV with no errors. Windows VM: four configurations with 0 C++ warnings (the editor's C# builds), UnitTests 238/240, the renderer test on D3D12 (WARP) and Vulkan (lavapipe, 180 s, validation on), exit 0 without errors; the editor opens ScriptTest, renders its viewports, builds and loads its game code, exits 0. clang-tidy over the Windows databases (engine, EngineDLL) 0. Desktop: plan doc A49 (the picture, LOD switching, the editor with mesh actors and lights).

Measured: steps 1 and 2 together: 2,644 lines added, 5,081 removed in the code; the backends' identical lines stay at 33% (step 2 removed the object API, not duplication).

10. Step 3: one frame for every surface (2026-11-23, uncommitted)

Decided (user, 2026-11-23): one call per frame, graphics::render_frame(std::span<const SurfaceFrame>) with SurfaceFrame{Surface, FrameInfo}; Surface::render() is gone (no shorthand: one window is a one-element frame). The other shapes (a begin_frame()/end_frame() bracket, or both APIs) were turned down: a bracket keeps hidden state between calls and hands the renderer surfaces one at a time, which steps 4 and 5 need to see together.

Done:

  • Frame context per engine frame (both backends): render_frame() waits once for the frame index's fence, resets the command pools/allocators and the per-thread ones, processes the deferred releases, collects every surface's render items and reserves the constant buffer once for all of them (other_constant_bytes per surface), records the surfaces one after another into the frame's command buffer/lists, and submits once. Vulkan presents every acquired swapchain with one vkQueuePresentKHR (pResults per swapchain); D3D12 calls Present() per swapchain after its one ExecuteCommandLists. The frame index now advances once per engine frame, not per surface.
  • Surface context per surface: gpass render targets (main and depth buffer, sized to the surface and grown with it, decision 4), the barrier tracker (VulkanSurface::barriers(), D3D12Surface::barriers()), the gpass cache (D3D12 had one global cache; it and its ExecuteIndirect command buffers are per surface now), and the light buffers (one copy per surface and frame index: surfaces of a frame may show different light sets). Vulkan's image-acquired semaphores moved from the command frames to the surfaces (one per surface and frame index). remove_surface() releases a surface's gpass and light buffers.
  • Vulkan resizes every out-of-date swapchain before the frame with one flush. A surface whose image can't be acquired (minimized) sits the frame out; the frame is still submitted.
  • scene::fill_frame_info() keeps LOD thresholds per place in the frame.
  • Callers: EngineTest (renderer and surfaces tests), the graphics tests, and the editor: EngineDLL's RenderFrame export is now RenderFrames(count, surface_ids, camera_ids, light_sets), and the editor's render thread (RenderSurfaceHost.cs) gathers every viewport and calls it once per loop.
  • New benchmark: benchmark: 1500 objects in one and in four windows (GraphicsTests).

Measured (RADV, RX 6800 XT, clang Release, vsync off, 1,526 render items, four 640 x 360 windows; median of 5 runs):

one window four windows
before (one frame per surface) 0.52 ms 1.92 ms
after (one frame for all) 0.55 ms 1.84 ms

Within the run-to-run noise (four windows: 1.83-2.39 ms before, 1.53-1.98 ms after). RADV didn't wait much between the windows before either; the CPU work (four times preparation and recording) dominates, which steps 4 and 5 parallelize. The GPU overlap on a slower GPU or with vsync remains for the desktop check.

Costs to watch: render target memory grows with the number of surfaces (a pool if it matters, decision 4); the editor's lock is held for all viewports of a frame instead of one; presenting all swapchains together ties their pacing together with vsync on monitors of different refresh rates.

Checked: Linux clang Debug + Release and GCC Debug (0 warnings; UnitTests 239, GraphicsTests 22 with validation and sync validation on both compilers), clang-tidy 0 on the changed files. Windows VM: four configurations with 0 C++ warnings (the editor's C# builds), UnitTests Debug 238 + Release 240, the renderer test with four windows on D3D12 (WARP) and Vulkan (lavapipe, validation on), exit 0 without errors, matching pictures; the editor opens ScriptTest and its four viewports render through RenderFrames (65 Hz each), exit 0. Desktop: plan doc A50.

11. Step 4: resizing out of recording, one parallel recording pass (2026-11-23, committed in 5b936e6)

What was done. A surface is recorded in three phases on both backends (record_surface() in VulkanCore.cpp and D3D12Core.cpp):

  1. Preparation, on the rendering thread: gpass::set_size() (render targets), gpass::prepare() (per-object and material data in the frame's constant buffer, was in depth_prepass()), light::update_light_buffers() (was between the depth prepass and the gpass) and the new delight::prepare(), which resizes the light culling buffers when the surface's size or field of view changed (was inside cull_lights(), during recording). cull_lights() only records, and computes the grid frustums again after a resize (frustums_changed).
  2. The batches: gpass::record_batches() records the depth prepass's and the gpass's draws in one jobs::parallel_for over both passes' batches (512 items each; up to 512 items, nothing is batched and the passes record into the frame's list/buffer as before). Vulkan: secondary command buffers; D3D12: thread command lists that set their own render targets. Before, each pass ran its own parallel_for, so the gpass's batches waited for the depth prepass's.
  3. The frame's command list/buffer: barriers, the depth prepass (executes its batches), light culling, the gpass (executes its batches), post-process.

Nothing that the batches bind can be recreated once they record, which is what step 5 needs to prepare and record surfaces in parallel. Light culling and post-process stay in the frame's list (a few commands each).

The D3D12 ExecuteIndirect path is gone (decision 3): depth_prepass_indirect()/render_indirect(), the indirect command buffers per surface, group_by_pso(), DrawIndexedIndirectCommand, the material command signatures in D3D12Content.cpp and PRIMAL_D3D12_DRAW_INDIRECT. The generic helpers (d3dx::create_command_signature(), D3D12CommandSignatureDesc) stay for later GPU-driven work. Also fixed: two clang-tidy findings of step 3 in the Windows databases (SurfaceGpass's redundant initializers, the surface_light_buffers alias name in both backends).

Measured (RADV, clang Release, GraphicsTests benchmarks, median of 5, same session):

Benchmark Before After
6,400 items, one window 0.78 ms 0.70 ms
1,526 objects, one window 0.53 ms 0.45 ms
1,526 objects in one window (four-window benchmark) 0.50 ms 0.42 ms
the same in four 640x360 windows 1.60 ms 1.28 ms

The gain is the two passes' batches running together (one wait instead of two). The four-window "before" is lower than step 3's 1.84 ms: that was another session (the machine's load differs), so compare within a table only.

Checked: plan doc A51. Not done here: PIX/RenderDoc parity (desktop, A51).

12. Step 5: surfaces collected, prepared and recorded together (2026-11-23, committed in aa9c480)

Where the time went before this step (temporary timers in vulkan::core::render_frame(), Release, RADV, ms per frame): with 6,400 items, collecting the render items' content 0.19, preparation 0.07, the batches 0.30, the primary command buffer 0.02, and everything outside render_frame() (scene::prepare(), the matrices) about 0.04. With four windows, each surface paid its collection, preparation and batches one after the other.

What was done (both backends; render_frame() in VulkanCore.cpp and D3D12Core.cpp):

  1. Collect in parallel. The surfaces collect their render items in jobs (jobs::parallel_for over the surfaces), and each surface's content reads are split into jobs of 1,024 items (collect_render_items()). The content locks (meshes, materials, render items, pipelines, and the geometry lock in ContentToEngine.cpp) are std::shared_mutex: readers share them, writers (adding and removing content) are exclusive (decision 5). The LOD scratch lists are per thread. gpass::add_surface() makes each surface's cache first, on the rendering thread.
  2. Preparation stays serial, but only allocates. gpass::prepare() allocates the per-object and material data in the constant buffer and sets every item's addresses; light buffers and delight::prepare() as in step 4. The data itself is written by jobs (below): the addresses are known before the data, so the draws can be recorded at the same time.
  3. One job pass for every surface. gpass::plan_jobs() returns a surface's jobs (its object data in jobs of 512 objects, its material data in jobs of 2,048 items, then the depth prepass's and the gpass's batches of 512); render_frame() runs every surface's jobs in one parallel_for (gpass::run_job()). D3D12's thread command lists take the surface's size (core::begin_thread_command_list(width, height)), since several surfaces record at once.
  4. The frame's command list/buffer is recorded per surface afterwards (about 0.007 ms each).

The batch size was measured again with both passes and several surfaces in one pass: 512 stays (256 and 1,024 were slower: four windows 0.88-0.93 and 0.87 ms against 0.82-0.84 ms).

Not done, on purpose: scene::prepare() per ECS chunk. It costs about 0.04 ms with 6,400 items, less than the wake-up of the workers (step 5 of #1 measured 37-48 us); it is worth it with far more entities. Preparing the surfaces in parallel (light buffers, culling buffers, allocation) needs a thread-safe constant buffer allocator and resource creation from jobs; it costs about 0.03 ms per surface now.

Measured (RADV, clang Release, GraphicsTests benchmarks, median of 5, same session as step 4's "after"):

Benchmark Step 4 Step 5
6,400 items, one window 0.70 ms 0.60 ms
1,526 objects, one window 0.45 ms 0.43 ms
1,526 objects in one window (four-window benchmark) 0.42 ms 0.41 ms
the same in four 640x360 windows 1.28 ms 0.84 ms

Since step 3 (1.60 ms in that session's measurement), four windows take about half the time. The one-window frame gains less: its preparation and batches were already in jobs, and what is left serial is the constant buffer allocation and addresses (about 0.03-0.07 ms), the frame's command buffer and the submission.

Checked: plan doc A52.

13. Step 6: cleanup and the duplication measured again (2026-11-23, uncommitted)

The duplication, measured again with Tools/measure_backend_duplication.py (new; same method as section 1, which it reproduces within 0.2% on commit 8f333d9: 4,938 D3D12 lines against 4,943):

Module D3D12 Vulkan Identical Share of D3D12
Interface 44 53 39 88%
Shaders 21 23 16 76%
Light 106 108 65 61%
Content 724 736 408 56%
Resources 544 608 258 47%
Upload 141 182 65 46%
Light culling 242 237 109 45%
Core 753 1,141 230 30%
Surface 135 311 35 25%
GPass 489 471 100 20%
Post-process 97 111 18 18%
CommonHeaders 62 52 11 17%
Helpers 626 522 14 2%
All 3,984 4,555 1,368 34%

Before #3 (section 1): D3D12 4,943, Vulkan 5,249, 2,207 identical (44%). After steps 1-6: 3,984 and 4,555, 1,368 identical (34%): 959 and 694 fewer lines, and the 839 identical lines that went are the API-free code now written once in Engine/Graphics/ (734 lines: camera, light sets, scene, engine shader loading, the frame). What is still alike is mostly Content (408 lines: render item, material and pipeline bookkeeping next to the GPU objects), Resources and Upload (the same classes over different APIs), and the Core frame sequence. That is the input for #67 (a thin RHI would write the frame sequence and the passes once) and for a later step moving content bookkeeping to Engine/Graphics/.

#4 group B in what steps 1-5 touched:

  • Object names are functions: vkx::set_name(handle, "name") / set_name(handle, "name", index) (the VkObjectType comes from the handle's type) and d3dx::set_name(object, L"name") / with an index, compiled to nothing in Release. The NAME_VK_OBJECT*/NAME_D3D12_OBJECT* macros are gone (68 uses converted).
  • Debug markers per pass for RenderDoc and PIX: vkx::ScopedMarker (vkCmdBeginDebugUtilsLabelEXT, when VK_EXT_debug_utils is loaded) and d3dx::ScopedMarker (BeginEvent, in every build): "Depth prepass", "Light culling", "GPass", "Post-process". D3D12's batches run in their own command lists, so each batch has its own marker ("Depth prepass batch", "GPass batch"); a marker can't span lists.
  • std::span at the content reads steps 1 and 5 rewrote: render_item::get_items(), submesh::get_views(), material::get_materials(), texture::get_descriptor_indices() and the light sets' texture-index callback, on both backends. The other pointer + count parameters (add_mesh(), set_option(), root signature creation) weren't touched by #3 and stay for #4.
  • RAII for GPU objects: not done here. Steps 1-5 added no owning GPU member except the Vulkan surface's image-acquired semaphores, which VulkanSurface::release() destroys with the surface's other objects. An owning handle type with one user isn't worth it; it comes with code that creates GPU objects anew (#67 or #71).

Step 7's tickets: #71 (asynchronous uploads on a copy/transfer queue), #72 (jobs::attach_thread() for the editor's render thread), #73 (worker spinning, measured); #28 (GraphicsTests on D3D12) right after #3.

Checked: plan doc A53. #3 stays open until the desktop checks (A48-A53) pass.

Pages 19

View all

Clone this repository