Extract D3D12 resource helpers

This commit is contained in:
Meta Vens 2026-05-09 12:45:14 +01:00
commit bed74180b1
8 changed files with 210 additions and 78 deletions

View file

@ -10,11 +10,13 @@ has feature parity.
- `--renderer d3d12` creates a D3D12 device, command queue, flip-discard
swapchain, RTV heap, per-backbuffer command allocators, command list,
fence-backed present loop, shader-visible CBV/SRV/UAV descriptor arena,
per-frame upload buffers, fullscreen root signature, and a smoke-test PSO.
per-frame upload buffers, renderer-owned offscreen render target, fullscreen
root signature, and a smoke-test PSO.
- The D3D12 path currently draws a diagnostic fullscreen pass. It exists to
prove backend lifecycle, shader compilation, root signature creation,
descriptor-table binding, per-frame constant upload, PSO creation, render
target binding, and draw submission before real scene passes migrate.
target binding, resource state transitions, render-target-to-swapchain copy,
and draw submission before real scene passes migrate.
- `IAquariumRenderer` is the host boundary. The host should not learn backend
internals as the D3D12 renderer grows teeth.
@ -22,8 +24,8 @@ has feature parity.
1. Keep D3D11 as the visual reference.
2. Move shared renderer contracts behind explicit backend-neutral types.
3. Replace the smoke-only descriptor/upload code with general ring-buffer and
resource lifetime helpers.
3. Replace the smoke-only resource code with general render-target, SRV/UAV,
and upload ring helpers.
4. Port the existing passes in visible order: grid height, froxel volume, scene,
bloom, resolve, overlay/debug.
5. Build the transparent stochastic surface pipe in D3D12 once descriptor and

View file

@ -5,6 +5,7 @@
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Aquarium-Engine-Icon.ico</ApplicationIcon>
</PropertyGroup>

View file

@ -0,0 +1,43 @@
using Vortice.Direct3D12;
namespace Aquarium.Engine.Render;
internal sealed class D3D12DescriptorArena : IDisposable
{
private readonly int descriptorSize;
private int used;
public D3D12DescriptorArena(ID3D12Device device, DescriptorHeapType type, int capacity, DescriptorHeapFlags flags)
{
Type = type;
Capacity = capacity;
Heap = device.CreateDescriptorHeap(new DescriptorHeapDescription(type, (uint)capacity, flags));
descriptorSize = (int)device.GetDescriptorHandleIncrementSize(type);
}
public ID3D12DescriptorHeap Heap { get; }
public DescriptorHeapType Type { get; }
public int Capacity { get; }
public D3D12DescriptorSlot Allocate()
{
if (used >= Capacity)
{
throw new InvalidOperationException($"D3D12 {Type} descriptor arena exhausted ({Capacity} descriptors).");
}
var index = used++;
return new D3D12DescriptorSlot(
Heap.GetCPUDescriptorHandleForHeapStart() + (index * descriptorSize),
Heap.GetGPUDescriptorHandleForHeapStart() + (index * descriptorSize));
}
public void Dispose()
{
Heap.Dispose();
}
}
internal readonly record struct D3D12DescriptorSlot(CpuDescriptorHandle Cpu, GpuDescriptorHandle Gpu);

View file

@ -0,0 +1,65 @@
using Vortice.Direct3D12;
using Vortice.DXGI;
using Vortice.Mathematics;
namespace Aquarium.Engine.Render;
internal sealed class D3D12RenderTarget : IDisposable
{
public D3D12RenderTarget(
ID3D12Device device,
int width,
int height,
Format format,
D3D12DescriptorSlot renderTargetView,
Color4 clearColor)
{
Width = width;
Height = height;
Format = format;
RenderTargetView = renderTargetView;
var optimizedClear = new ClearValue(format, in clearColor);
Resource = device.CreateCommittedResource(
HeapType.Default,
ResourceDescription.Texture2D(
format,
(uint)width,
(uint)height,
1,
1,
1,
0,
ResourceFlags.AllowRenderTarget),
ResourceStates.PixelShaderResource,
optimizedClear);
device.CreateRenderTargetView(Resource, null, renderTargetView.Cpu);
}
public ID3D12Resource Resource { get; }
public int Width { get; }
public int Height { get; }
public Format Format { get; }
public D3D12DescriptorSlot RenderTargetView { get; }
public ResourceStates State { get; private set; } = ResourceStates.PixelShaderResource;
public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState)
{
if (State == nextState)
{
return;
}
commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState));
State = nextState;
}
public void Dispose()
{
Resource.Dispose();
}
}

View file

@ -7,7 +7,6 @@ using Vortice.Direct3D12;
using Vortice.DXGI;
using Vortice.Mathematics;
using System.Numerics;
using System.Runtime.InteropServices;
namespace Aquarium.Engine.Render;
@ -20,15 +19,15 @@ public sealed class D3D12Renderer : IAquariumRenderer
private readonly ID3D12Device device;
private readonly ID3D12CommandQueue commandQueue;
private readonly IDXGISwapChain3 swapChain;
private readonly ID3D12DescriptorHeap renderTargetViewHeap;
private readonly DescriptorArena shaderDescriptorArena;
private readonly D3D12DescriptorArena renderTargetViewArena;
private readonly D3D12DescriptorArena shaderDescriptorArena;
private readonly D3D12RenderTarget smokeRenderTarget;
private readonly FrameResources[] frames = new FrameResources[BackBufferCount];
private readonly ID3D12GraphicsCommandList commandList;
private readonly ID3D12RootSignature fullscreenRootSignature;
private readonly ID3D12PipelineState smokePipelineState;
private readonly ID3D12Fence fence;
private readonly AutoResetEvent fenceEvent = new(false);
private readonly int renderTargetViewDescriptorSize;
private readonly Viewport viewport;
private readonly RawRect scissorRect;
private ulong fenceValue;
@ -67,15 +66,21 @@ public sealed class D3D12Renderer : IAquariumRenderer
swapChain = swapChain1.QueryInterface<IDXGISwapChain3>();
frameIndex = (int)swapChain.CurrentBackBufferIndex;
renderTargetViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription(DescriptorHeapType.RenderTargetView, BackBufferCount));
renderTargetViewDescriptorSize = (int)device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
shaderDescriptorArena = new DescriptorArena(device, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, BackBufferCount, DescriptorHeapFlags.ShaderVisible);
renderTargetViewArena = new D3D12DescriptorArena(device, DescriptorHeapType.RenderTargetView, BackBufferCount + 1, DescriptorHeapFlags.None);
shaderDescriptorArena = new D3D12DescriptorArena(device, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, BackBufferCount, DescriptorHeapFlags.ShaderVisible);
for (var index = 0; index < frames.Length; index++)
{
frames[index] = CreateFrameResources(index);
}
CreateRenderTargetViews();
smokeRenderTarget = new D3D12RenderTarget(
device,
width,
height,
Format.B8G8R8A8_UNorm,
renderTargetViewArena.Allocate(),
new Color4(0.006f, 0.014f, 0.022f, 1.0f));
commandList = device.CreateCommandList<ID3D12GraphicsCommandList>(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null);
commandList.Close();
ReportStartupProgress(startupProgress, "Creating D3D12 fullscreen smoke pipeline");
@ -133,7 +138,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
frameResources.CommandAllocator.Reset();
commandList.Reset(frameResources.CommandAllocator, null);
ClearBackBuffer(new D3D12PassContext(commandList, frameResources.BackBuffer, GetRenderTargetViewHandle(frameIndex)), frame);
ClearBackBuffer(new D3D12PassContext(commandList, frameResources.BackBuffer, frameResources.BackBufferRenderTargetView.Cpu), frame);
commandList.Close();
commandQueue.ExecuteCommandList(commandList);
@ -150,12 +155,13 @@ public sealed class D3D12Renderer : IAquariumRenderer
commandList.Dispose();
smokePipelineState.Dispose();
fullscreenRootSignature.Dispose();
smokeRenderTarget.Dispose();
for (var index = 0; index < frames.Length; index++)
{
frames[index].Dispose();
}
shaderDescriptorArena.Dispose();
renderTargetViewHeap.Dispose();
renderTargetViewArena.Dispose();
swapChain.Dispose();
commandQueue.Dispose();
device.Dispose();
@ -167,7 +173,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
for (var index = 0; index < frames.Length; index++)
{
frames[index].BackBuffer = swapChain.GetBuffer<ID3D12Resource>((uint)index);
device.CreateRenderTargetView(frames[index].BackBuffer, null, GetRenderTargetViewHandle(index));
frames[index].BackBufferRenderTargetView = renderTargetViewArena.Allocate();
device.CreateRenderTargetView(frames[index].BackBuffer, null, frames[index].BackBufferRenderTargetView.Cpu);
}
}
@ -180,23 +187,21 @@ public sealed class D3D12Renderer : IAquariumRenderer
0.022f + settings.BloomVeilIntensity * 0.8f,
1.0f);
context.CommandList.ResourceBarrier(ResourceBarrier.BarrierTransition(context.BackBuffer, ResourceStates.Present, ResourceStates.RenderTarget));
context.CommandList.ClearRenderTargetView(context.RenderTargetView, clearColor);
smokeRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget);
context.CommandList.ClearRenderTargetView(smokeRenderTarget.RenderTargetView.Cpu, clearColor);
context.CommandList.SetDescriptorHeaps(shaderDescriptorArena.Heap);
context.CommandList.SetPipelineState(smokePipelineState);
context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature);
context.CommandList.SetGraphicsRootDescriptorTable(0, frames[frameIndex].SmokeConstantsGpuDescriptor);
context.CommandList.RSSetViewports(viewport);
context.CommandList.RSSetScissorRects(scissorRect);
context.CommandList.OMSetRenderTargets(context.RenderTargetView, null);
context.CommandList.OMSetRenderTargets(smokeRenderTarget.RenderTargetView.Cpu, null);
context.CommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList);
context.CommandList.DrawInstanced(3, 1, 0, 0);
context.CommandList.ResourceBarrier(ResourceBarrier.BarrierTransition(context.BackBuffer, ResourceStates.RenderTarget, ResourceStates.Present));
}
private CpuDescriptorHandle GetRenderTargetViewHandle(int index)
{
return renderTargetViewHeap.GetCPUDescriptorHandleForHeapStart() + (index * renderTargetViewDescriptorSize);
smokeRenderTarget.Transition(context.CommandList, ResourceStates.CopySource);
context.CommandList.ResourceBarrier(ResourceBarrier.BarrierTransition(context.BackBuffer, ResourceStates.Present, ResourceStates.CopyDest));
context.CommandList.CopyResource(context.BackBuffer, smokeRenderTarget.Resource);
context.CommandList.ResourceBarrier(ResourceBarrier.BarrierTransition(context.BackBuffer, ResourceStates.CopyDest, ResourceStates.Present));
}
private void SignalFrame(FrameResources frameResources)
@ -251,16 +256,12 @@ public sealed class D3D12Renderer : IAquariumRenderer
private FrameResources CreateFrameResources(int index)
{
var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct);
var uploadBuffer = device.CreateCommittedResource(
HeapType.Upload,
ResourceDescription.Buffer(D3D12.ConstantBufferDataPlacementAlignment),
ResourceStates.GenericRead,
null);
var uploadBuffer = new D3D12UploadBuffer<SmokeConstants>(device, 1);
var constantBufferSlot = shaderDescriptorArena.Allocate();
device.CreateConstantBufferView(
new ConstantBufferViewDescription(
uploadBuffer.GPUVirtualAddress,
D3D12.ConstantBufferDataPlacementAlignment),
uploadBuffer.GpuVirtualAddress,
(uint)uploadBuffer.ElementStride),
constantBufferSlot.Cpu);
return new FrameResources(commandAllocator, uploadBuffer, constantBufferSlot.Gpu);
@ -302,27 +303,28 @@ public sealed class D3D12Renderer : IAquariumRenderer
ID3D12Resource BackBuffer,
CpuDescriptorHandle RenderTargetView);
[StructLayout(LayoutKind.Sequential)]
private readonly record struct SmokeConstants(Vector4 Tint, Vector4 Params);
private sealed class FrameResources(
ID3D12CommandAllocator commandAllocator,
ID3D12Resource smokeConstantBuffer,
D3D12UploadBuffer<SmokeConstants> smokeConstantBuffer,
GpuDescriptorHandle smokeConstantsGpuDescriptor) : IDisposable
{
public ID3D12CommandAllocator CommandAllocator { get; } = commandAllocator;
public ID3D12Resource SmokeConstantBuffer { get; } = smokeConstantBuffer;
public D3D12UploadBuffer<SmokeConstants> SmokeConstantBuffer { get; } = smokeConstantBuffer;
public GpuDescriptorHandle SmokeConstantsGpuDescriptor { get; } = smokeConstantsGpuDescriptor;
public ID3D12Resource BackBuffer { get; set; } = null!;
public D3D12DescriptorSlot BackBufferRenderTargetView { get; set; }
public ulong FenceValue { get; set; }
public void WriteSmokeConstants(SmokeConstants constants)
{
SmokeConstantBuffer.Map<SmokeConstants>(0, 1)[0] = constants;
SmokeConstantBuffer.Write(0, constants);
}
public void Dispose()
@ -332,44 +334,4 @@ public sealed class D3D12Renderer : IAquariumRenderer
CommandAllocator.Dispose();
}
}
private sealed class DescriptorArena : IDisposable
{
private readonly int descriptorSize;
private int used;
public DescriptorArena(ID3D12Device device, DescriptorHeapType type, int capacity, DescriptorHeapFlags flags)
{
Type = type;
Capacity = capacity;
Heap = device.CreateDescriptorHeap(new DescriptorHeapDescription(type, (uint)capacity, flags));
descriptorSize = (int)device.GetDescriptorHandleIncrementSize(type);
}
public ID3D12DescriptorHeap Heap { get; }
public DescriptorHeapType Type { get; }
public int Capacity { get; }
public DescriptorSlot Allocate()
{
if (used >= Capacity)
{
throw new InvalidOperationException($"D3D12 {Type} descriptor arena exhausted ({Capacity} descriptors).");
}
var index = used++;
return new DescriptorSlot(
Heap.GetCPUDescriptorHandleForHeapStart() + (index * descriptorSize),
Heap.GetGPUDescriptorHandleForHeapStart() + (index * descriptorSize));
}
public void Dispose()
{
Heap.Dispose();
}
}
private readonly record struct DescriptorSlot(CpuDescriptorHandle Cpu, GpuDescriptorHandle Gpu);
}

View file

@ -0,0 +1,52 @@
using System.Runtime.CompilerServices;
using Vortice.Direct3D12;
namespace Aquarium.Engine.Render;
internal sealed unsafe class D3D12UploadBuffer<T> : IDisposable
where T : unmanaged
{
private readonly ID3D12Resource resource;
private readonly T* mapped;
public D3D12UploadBuffer(ID3D12Device device, int elementCount)
{
ElementCount = elementCount;
ElementStride = Align256(Unsafe.SizeOf<T>());
resource = device.CreateCommittedResource(
HeapType.Upload,
ResourceDescription.Buffer((ulong)(ElementStride * elementCount)),
ResourceStates.GenericRead,
null);
mapped = resource.Map<T>(0);
}
public int ElementCount { get; }
public int ElementStride { get; }
public ID3D12Resource Resource => resource;
public ulong GpuVirtualAddress => resource.GPUVirtualAddress;
public void Write(int index, in T value)
{
if ((uint)index >= (uint)ElementCount)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
Unsafe.Write((byte*)mapped + (index * ElementStride), value);
}
public void Dispose()
{
resource.Unmap(0, null);
resource.Dispose();
}
private static int Align256(int value)
{
return (value + 255) & ~255;
}
}

View file

@ -63,3 +63,4 @@
{"area":"renderer/backend-selection","lesson":"Backend-neutral startup logging matters once D3D12 exists beside D3D11. Live runtime messages should describe Aquarium host invariants, not claim a specific graphics API that may be false for the selected renderer.","files":["src/Aquarium.Engine.Live/AquariumRuntime.cs"],"verification":["dotnet build Aquarium.Engine.slnx",".\\scripts\\dev-reload.ps1 -Headless -RetainSlots 4 -HeadlessTimeoutSeconds 60","Latest slot Aquarium.Engine.exe --headless --renderer d3d12 exited 0 and logged D3D12 device/swapchain creation"],"ts":"2026-05-09"}
{"area":"renderer/d3d12","lesson":"A useful D3D12 foothold must exercise shader and PSO machinery, not just ClearRenderTargetView. The D3D12 backend now uses per-swapchain-buffer command allocators, a pass context, fullscreen root signature, compiled smoke shader, PSO, viewport/scissor/RTV binding, and DrawInstanced fullscreen triangle submission.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 and logged fullscreen smoke pipeline creation"],"ts":"2026-05-09"}
{"area":"renderer/d3d12","lesson":"D3D12 descriptor/upload ownership is now represented in the backend instead of hiding inside a draw call. The smoke pass uses a shader-visible CBV/SRV/UAV descriptor arena, one upload constant buffer per swapchain frame, a CBV descriptor table at b0, and per-frame writes before command recording. Generalize this foothold into renderer-wide descriptor and upload ring helpers before porting Aquarium scene resources.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 with CBV descriptor table smoke pass"],"ts":"2026-05-09"}
{"area":"renderer/d3d12","lesson":"D3D12 now has reusable renderer-side primitives instead of smoke-pass-local plumbing: a descriptor arena, persistent mapped upload buffer, and default-heap render target with explicit state tracking. The smoke pass renders into the offscreen target and copies to the swapchain, proving render target lifetime and copy barriers before porting Aquarium scene/history/froxel textures.","files":["src/Aquarium.Engine/Aquarium.Engine.csproj","src/Aquarium.Engine/Render/D3D12DescriptorArena.cs","src/Aquarium.Engine/Render/D3D12UploadBuffer.cs","src/Aquarium.Engine/Render/D3D12RenderTarget.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/d3d12-migration.md","state/scratch.md"],"verification":["dotnet build src\\Aquarium.Engine\\Aquarium.Engine.csproj","Aquarium.Engine.exe --headless --renderer d3d12 exited 0 with offscreen render target copy path"],"ts":"2026-05-09"}

View file

@ -6,10 +6,11 @@ D3D12 migration foothold. D3D11 remains the visual reference renderer; the host
now talks through `IAquariumRenderer`, and `--renderer d3d12` selects a D3D12
backend with device/queue/swapchain/RTV heap/per-frame command allocators/fence,
plus a shader-visible descriptor arena, per-frame upload constant buffers,
fullscreen root signature, and smoke-test PSO that draws a diagnostic fullscreen
triangle. Next renderer work should generalize this into renderer-owned
descriptor/upload/resource helpers before building the stochastic transparent
surface pipe.
renderer-owned offscreen render target, fullscreen root signature, and
smoke-test PSO that draws a diagnostic fullscreen triangle into the offscreen
target before copying to the swapchain. Next renderer work should generalize
this into renderer-owned SRV/UAV/upload-ring helpers before building the
stochastic transparent surface pipe.
## Hot Context
@ -228,3 +229,8 @@ surface pipe.
constants before drawing. This is still diagnostic, but it proves descriptor
heap visibility, root descriptor table binding, and per-frame CPU-to-GPU
upload ownership.
- D3D12 render-target foothold: the smoke pass now renders into a renderer-owned
default-heap offscreen render target with explicit RTV descriptor ownership and
tracked state transitions, then copies that texture into the swapchain
backbuffer. This proves render-target resource lifetime and copy barriers
before Aquarium scene/history/froxel targets are ported.