diff --git a/docs/d3d12-migration.md b/docs/d3d12-migration.md index 5eb0503..18a6499 100644 --- a/docs/d3d12-migration.md +++ b/docs/d3d12-migration.md @@ -8,9 +8,12 @@ has feature parity. - `--renderer d3d11` is the default renderer and owns the live scene. - `--renderer d3d12` creates a D3D12 device, command queue, flip-discard - swapchain, RTV heap, command allocator/list, and fence-backed present loop. -- The D3D12 path currently clears and presents only. It exists to prove the - backend lifecycle before shader, resource, and pass migration starts. + swapchain, RTV heap, per-backbuffer command allocators, command list, + fence-backed present loop, 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, PSO + creation, render target binding, 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. @@ -18,7 +21,7 @@ has feature parity. 1. Keep D3D11 as the visual reference. 2. Move shared renderer contracts behind explicit backend-neutral types. -3. Port root signatures, descriptor heaps, upload/ring buffers, and pass +3. Port descriptor heaps, upload/ring buffers, and pass resource lifetime. 4. Port the existing passes in visible order: grid height, froxel volume, scene, bloom, resolve, overlay/debug. diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 05b5a7e..f4fe60e 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -1,5 +1,7 @@ using Aquarium.Engine.Input; using SharpGen.Runtime; +using Vortice; +using Vortice.D3DCompiler; using Vortice.Direct3D; using Vortice.Direct3D12; using Vortice.DXGI; @@ -10,18 +12,22 @@ namespace Aquarium.Engine.Render; public sealed class D3D12Renderer : IAquariumRenderer { private const int BackBufferCount = 2; + private const string SmokeShaderRelativePath = "Render/Shaders/D3D12Smoke.hlsl"; private readonly IDXGIFactory4 factory; private readonly ID3D12Device device; private readonly ID3D12CommandQueue commandQueue; private readonly IDXGISwapChain3 swapChain; private readonly ID3D12DescriptorHeap renderTargetViewHeap; - private readonly ID3D12Resource[] renderTargets = new ID3D12Resource[BackBufferCount]; - private readonly ID3D12CommandAllocator commandAllocator; + 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; private int frameIndex; private GraphicsSettings settings = GraphicsSettings.Default; @@ -60,11 +66,19 @@ public sealed class D3D12Renderer : IAquariumRenderer renderTargetViewHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription(DescriptorHeapType.RenderTargetView, BackBufferCount)); renderTargetViewDescriptorSize = (int)device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); - CreateRenderTargetViews(); + for (var index = 0; index < frames.Length; index++) + { + frames[index] = new FrameResources(device.CreateCommandAllocator(CommandListType.Direct)); + } - commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); - commandList = device.CreateCommandList(0, CommandListType.Direct, commandAllocator, null); + CreateRenderTargetViews(); + commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Close(); + ReportStartupProgress(startupProgress, "Creating D3D12 fullscreen smoke pipeline"); + fullscreenRootSignature = CreateFullscreenRootSignature(); + smokePipelineState = CreateSmokePipelineState(shaderPath ?? Path.Combine(AppContext.BaseDirectory, SmokeShaderRelativePath)); + viewport = new Viewport(0.0f, 0.0f, width, height); + scissorRect = new RawRect(0, 0, width, height); fence = device.CreateFence(0); Console.WriteLine("D3D12 device and swapchain created."); } @@ -103,25 +117,18 @@ public sealed class D3D12Renderer : IAquariumRenderer public void Render(AquariumFrame frame) { - var clearColor = new Color4( - 0.006f + settings.SceneExposure * 0.02f, - 0.014f + settings.BloomIntensity * 0.2f, - 0.022f + settings.BloomVeilIntensity * 0.8f, - 1.0f); + var frameResources = frames[frameIndex]; + WaitForFrame(frameResources); + frameResources.CommandAllocator.Reset(); + commandList.Reset(frameResources.CommandAllocator, null); - commandAllocator.Reset(); - commandList.Reset(commandAllocator, null); - - var renderTarget = renderTargets[frameIndex]; - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(renderTarget, ResourceStates.Present, ResourceStates.RenderTarget)); - var renderTargetView = GetRenderTargetViewHandle(frameIndex); - commandList.ClearRenderTargetView(renderTargetView, clearColor); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(renderTarget, ResourceStates.RenderTarget, ResourceStates.Present)); + ClearBackBuffer(new D3D12PassContext(commandList, frameResources.BackBuffer, GetRenderTargetViewHandle(frameIndex)), frame); commandList.Close(); commandQueue.ExecuteCommandList(commandList); swapChain.Present(1, PresentFlags.None); - MoveToNextFrame(); + SignalFrame(frameResources); + frameIndex = (int)swapChain.CurrentBackBufferIndex; } public void Dispose() @@ -130,10 +137,9 @@ public sealed class D3D12Renderer : IAquariumRenderer fenceEvent.Dispose(); fence.Dispose(); commandList.Dispose(); - commandAllocator.Dispose(); - for (var index = 0; index < renderTargets.Length; index++) + for (var index = 0; index < frames.Length; index++) { - renderTargets[index].Dispose(); + frames[index].Dispose(); } renderTargetViewHeap.Dispose(); swapChain.Dispose(); @@ -144,27 +150,51 @@ public sealed class D3D12Renderer : IAquariumRenderer private void CreateRenderTargetViews() { - for (var index = 0; index < renderTargets.Length; index++) + for (var index = 0; index < frames.Length; index++) { - renderTargets[index] = swapChain.GetBuffer((uint)index); - device.CreateRenderTargetView(renderTargets[index], null, GetRenderTargetViewHandle(index)); + frames[index].BackBuffer = swapChain.GetBuffer((uint)index); + device.CreateRenderTargetView(frames[index].BackBuffer, null, GetRenderTargetViewHandle(index)); } } + private void ClearBackBuffer(D3D12PassContext context, AquariumFrame frame) + { + _ = frame; + var clearColor = new Color4( + 0.006f + settings.SceneExposure * 0.02f, + 0.014f + settings.BloomIntensity * 0.2f, + 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); + context.CommandList.SetPipelineState(smokePipelineState); + context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); + context.CommandList.RSSetViewports(viewport); + context.CommandList.RSSetScissorRects(scissorRect); + context.CommandList.OMSetRenderTargets(context.RenderTargetView, 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); } - private void MoveToNextFrame() + private void SignalFrame(FrameResources frameResources) { var signalValue = ++fenceValue; commandQueue.Signal(fence, signalValue).CheckError(); - frameIndex = (int)swapChain.CurrentBackBufferIndex; + frameResources.FenceValue = signalValue; + } - if (fence.CompletedValue < signalValue) + private void WaitForFrame(FrameResources frameResources) + { + if (frameResources.FenceValue != 0 && fence.CompletedValue < frameResources.FenceValue) { - fence.SetEventOnCompletion(signalValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()).CheckError(); + fence.SetEventOnCompletion(frameResources.FenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()).CheckError(); fenceEvent.WaitOne(); } } @@ -182,4 +212,64 @@ public sealed class D3D12Renderer : IAquariumRenderer startupProgress?.Invoke(message); Console.WriteLine(message); } + + private ID3D12RootSignature CreateFullscreenRootSignature() + { + var description = new RootSignatureDescription( + RootSignatureFlags.AllowInputAssemblerInputLayout, + [], + []); + return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); + } + + private ID3D12PipelineState CreateSmokePipelineState(string path) + { + var vertexShader = CompileShader(path, "FullscreenTriangleVS", "vs_5_0"); + var pixelShader = CompileShader(path, "D3D12SmokePS", "ps_5_0"); + var description = new GraphicsPipelineStateDescription + { + RootSignature = fullscreenRootSignature, + VertexShader = vertexShader, + PixelShader = pixelShader, + BlendState = BlendDescription.Opaque, + RasterizerState = RasterizerDescription.CullNone, + DepthStencilState = DepthStencilDescription.None, + SampleMask = uint.MaxValue, + PrimitiveTopologyType = PrimitiveTopologyType.Triangle, + RenderTargetFormats = [Format.B8G8R8A8_UNorm], + SampleDescription = new SampleDescription(1, 0), + }; + + return device.CreateGraphicsPipelineState(description); + } + + private static ReadOnlyMemory CompileShader(string path, string entryPoint, string profile) + { + var shaderFlags = ShaderFlags.EnableStrictness; +#if DEBUG + shaderFlags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization; +#endif + + return Compiler.CompileFromFile(path, entryPoint, profile, shaderFlags, EffectFlags.None); + } + + private readonly record struct D3D12PassContext( + ID3D12GraphicsCommandList CommandList, + ID3D12Resource BackBuffer, + CpuDescriptorHandle RenderTargetView); + + private sealed class FrameResources(ID3D12CommandAllocator commandAllocator) : IDisposable + { + public ID3D12CommandAllocator CommandAllocator { get; } = commandAllocator; + + public ID3D12Resource BackBuffer { get; set; } = null!; + + public ulong FenceValue { get; set; } + + public void Dispose() + { + BackBuffer.Dispose(); + CommandAllocator.Dispose(); + } + } } diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl new file mode 100644 index 0000000..f27a626 --- /dev/null +++ b/src/Aquarium.Engine/Render/Shaders/D3D12Smoke.hlsl @@ -0,0 +1,21 @@ +struct VertexOut +{ + float4 position : SV_Position; + float2 uv : TEXCOORD0; +}; + +VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) +{ + float2 uv = float2((vertexId << 1) & 2, vertexId & 2); + VertexOut output; + output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); + output.uv = uv; + return output; +} + +float4 D3D12SmokePS(VertexOut input) : SV_Target0 +{ + float3 baseColor = lerp(float3(0.012, 0.022, 0.032), float3(0.018, 0.040, 0.058), input.uv.y); + float vignette = smoothstep(0.86, 0.18, length(input.uv - 0.5)); + return float4(baseColor * (0.72 + 0.28 * vignette), 1.0); +} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index f14168c..f22c37d 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -61,3 +61,4 @@ {"area":"renderer/volumetrics","lesson":"The Grid is a transparent schematic overlay, not a participating-medium occluder. Keep Grid travel/field id for temporal stability, but do not clamp fog integration to Grid travel; only solid fields such as Self and planets terminate the froxel composite ray.","files":["src/Aquarium.Engine/Render/Shaders/Aquarium.hlsl","state/scratch.md"],"verification":["Aquarium.Engine project build succeeded","Full solution/headless verification blocked by dirty external CultLib changes on E:\\Projects\\CultLib codex/cultcache-attribute-first: CultCache.cs currently fails GameCult.Caching build with System.Text.Json/IsExternalInit errors"],"ts":"2026-05-09"} {"area":"renderer/d3d12","lesson":"Before building the transparent stochastic surface pipe, keep D3D11 as the reference backend and add D3D12 beside it behind IAquariumRenderer. The first D3D12 pass should prove device, command queue, swapchain, RTV heap, command list, fence, clear, and present lifecycle with headless execution before porting scene passes.","files":["src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Render/IAquariumRenderer.cs","src/Aquarium.Engine/Render/D3D11Renderer.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 with latest known-good live assembly exited 0","Aquarium.Engine.exe --headless --renderer d3d11 with latest known-good live assembly exited 0"],"ts":"2026-05-09"} {"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"} diff --git a/state/scratch.md b/state/scratch.md index 576afc2..7ac4dcb 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -3,9 +3,10 @@ ## Current Slice D3D12 migration foothold. D3D11 remains the visual reference renderer; the host -now talks through `IAquariumRenderer`, and `--renderer d3d12` selects a new -D3D12 shell that creates device/queue/swapchain/RTV heap/command list/fence and -clears/presents headlessly. Next renderer work should port pass/resource +now talks through `IAquariumRenderer`, and `--renderer d3d12` selects a D3D12 +backend with device/queue/swapchain/RTV heap/per-frame command allocators/fence, +plus a fullscreen root signature and smoke-test PSO that draws a diagnostic +fullscreen triangle. Next renderer work should port descriptor/upload/resource ownership into D3D12 before building the stochastic transparent surface pipe. ## Hot Context @@ -213,3 +214,9 @@ ownership into D3D12 before building the stochastic transparent surface pipe. graphics command list, fence wait, clear, and present. Do not build the transparent candidate pipe on D3D11 debt; port explicit D3D12 resource/pass ownership first. +- D3D12 pass spine pass: the backend now uses one command allocator per + swapchain buffer instead of stalling a single allocator each frame. It also + compiles `D3D12Smoke.hlsl`, creates a fullscreen root signature and graphics + PSO, binds viewport/scissor/RTV, and draws a fullscreen triangle. This proves + shader, root signature, PSO, and draw submission before real Aquarium passes + migrate.