Hot reload Aquarium shaders in process

This commit is contained in:
Meta Vens 2026-05-08 15:31:38 +01:00
commit 4c6cb24f4c
5 changed files with 122 additions and 16 deletions

View file

@ -72,6 +72,12 @@ slot, and only replaces the running Aquarium after the new build succeeds. If a
build fails, the previous good process keeps running and that same broken source
fingerprint is not retried until files change again.
Shader edits do not restart the process. The dev reload runner passes the
source `Aquarium.hlsl` path into the live app, and the renderer polls that file,
compiles changed shaders in the running process, then swaps the D3D shader
objects only after compilation succeeds. A bad shader edit leaves the previous
working shaders bound and writes the compiler failure to stderr.
Runtime live state is a typed CultCache document, not a loose sidecar file. The
first document is `epiphany.aquarium.live_state`, currently banking camera
target, yaw, pitch, distance, time, and save generation every few frames so a

View file

@ -16,6 +16,7 @@ $slotRoot = Join-Path $devRoot "slots"
$statePath = Join-Path $devRoot "state.clixml"
$buildStatePath = Join-Path $devRoot "last-build.clixml"
$cultCachePath = Join-Path $devRoot "cultcache\aquarium-client.msgpack"
$shaderSourcePath = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders\Aquarium.hlsl"
$stdoutLogPath = Join-Path $devRoot "latest.out.log"
$stderrLogPath = Join-Path $devRoot "latest.err.log"
@ -156,7 +157,7 @@ if (-not (Test-Path $exePath)) {
throw "Expected apphost was not produced: $exePath"
}
$arguments = @("--cache", $cultCachePath)
$arguments = @("--cache", $cultCachePath, "--shader-source", $shaderSourcePath)
if ($Headless) {
$arguments += "--headless"
}

View file

@ -44,7 +44,7 @@ function Get-WatchedFiles {
Where-Object {
$_.FullName -notmatch "\\bin\\" -and
$_.FullName -notmatch "\\obj\\" -and
$_.Extension -in @(".cs", ".csproj", ".hlsl", ".json", ".slnx")
$_.Extension -in @(".cs", ".csproj", ".json", ".slnx")
}
}
}

View file

@ -16,7 +16,7 @@ public static class AquariumHost
var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Aquarium-Engine-Icon.ico");
using var window = Win32Window.Create("Epiphany Aquarium Engine", width, height, input, iconPath);
window.PaintSplash();
using var renderer = new D3D11Renderer(window.Handle, window.ClientWidth, window.ClientHeight);
using var renderer = new D3D11Renderer(window.Handle, window.ClientWidth, window.ClientHeight, ParseShaderPath(args));
runtime.Start();
@ -66,4 +66,18 @@ public static class AquariumHost
return Environment.GetEnvironmentVariable("AQUARIUM_CULTCACHE_PATH");
}
private static string? ParseShaderPath(IReadOnlyCollection<string> args)
{
var values = args.ToArray();
for (var index = 0; index < values.Length - 1; index++)
{
if (string.Equals(values[index], "--shader-source", StringComparison.OrdinalIgnoreCase))
{
return values[index + 1];
}
}
return Environment.GetEnvironmentVariable("AQUARIUM_SHADER_SOURCE");
}
}

View file

@ -4,6 +4,7 @@ using Vortice.Direct3D11;
using Vortice.DXGI;
using Vortice.Mathematics;
using CultMath;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
@ -12,6 +13,8 @@ namespace Aquarium.Engine.Render;
public sealed class D3D11Renderer : IDisposable
{
private const string ShaderRelativePath = "Render/Shaders/Aquarium.hlsl";
private static readonly TimeSpan ShaderReloadPollInterval = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan ShaderReloadWriteSettleTime = TimeSpan.FromMilliseconds(150);
private const int GridHeightTextureSize = 128;
private const int FroxelCountX = 8;
private const int FroxelCountY = 8;
@ -31,20 +34,26 @@ public sealed class D3D11Renderer : IDisposable
private readonly ID3D11RenderTargetView gridHeightRenderTargetView;
private readonly ID3D11ShaderResourceView gridHeightShaderResourceView;
private readonly ID3D11SamplerState gridSampler;
private readonly ID3D11VertexShader vertexShader;
private readonly ID3D11PixelShader gridHeightPixelShader;
private readonly ID3D11PixelShader pixelShader;
private readonly ID3D11Buffer frameConstantBuffer;
private readonly ID3D11Buffer froxelPrimitiveBuffer;
private readonly ID3D11ShaderResourceView froxelPrimitiveShaderResourceView;
private readonly Int4[] froxelPrimitiveIds = new Int4[FroxelBufferElementCount];
private readonly int width;
private readonly int height;
private readonly string shaderPath;
private readonly Stopwatch shaderReloadClock = Stopwatch.StartNew();
private ID3D11VertexShader vertexShader;
private ID3D11PixelShader gridHeightPixelShader;
private ID3D11PixelShader pixelShader;
private DateTime lastShaderWriteUtc;
private TimeSpan lastShaderReloadCheck;
private bool shaderReloadFailureReported;
public D3D11Renderer(IntPtr windowHandle, int width, int height)
public D3D11Renderer(IntPtr windowHandle, int width, int height, string? shaderPath = null)
{
this.width = width;
this.height = height;
this.shaderPath = shaderPath ?? Path.Combine(AppContext.BaseDirectory, ShaderRelativePath);
var featureLevels = new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 };
var swapChainDescription = new SwapChainDescription
@ -78,14 +87,11 @@ public sealed class D3D11Renderer : IDisposable
using var backBuffer = swapChain.GetBuffer<ID3D11Texture2D>(0);
renderTargetView = device.CreateRenderTargetView(backBuffer);
var shaderPath = Path.Combine(AppContext.BaseDirectory, ShaderRelativePath);
var vertexShaderBytecode = CompileShader(shaderPath, "FullscreenTriangleVS", "vs_5_0");
var gridHeightShaderBytecode = CompileShader(shaderPath, "GridHeightPS", "ps_5_0");
var pixelShaderBytecode = CompileShader(shaderPath, "AquariumPS", "ps_5_0");
vertexShader = device.CreateVertexShader(vertexShaderBytecode.Span, null);
gridHeightPixelShader = device.CreatePixelShader(gridHeightShaderBytecode.Span, null);
pixelShader = device.CreatePixelShader(pixelShaderBytecode.Span, null);
var initialShaders = CompileShaderSet(this.shaderPath);
vertexShader = initialShaders.VertexShader;
gridHeightPixelShader = initialShaders.GridHeightPixelShader;
pixelShader = initialShaders.AquariumPixelShader;
lastShaderWriteUtc = File.GetLastWriteTimeUtc(this.shaderPath);
gridHeightTexture = CreateGridHeightTexture();
gridHeightRenderTargetView = device.CreateRenderTargetView(gridHeightTexture);
gridHeightShaderResourceView = device.CreateShaderResourceView(gridHeightTexture);
@ -121,6 +127,8 @@ public sealed class D3D11Renderer : IDisposable
public void Render(AquariumFrame frame)
{
TryHotReloadShaders();
var constants = new FrameConstants(
new float2(width, height),
frame.TimeSeconds,
@ -206,6 +214,66 @@ public sealed class D3D11Renderer : IDisposable
context.Draw(3, 0);
}
private void TryHotReloadShaders()
{
var now = shaderReloadClock.Elapsed;
if (now - lastShaderReloadCheck < ShaderReloadPollInterval)
{
return;
}
lastShaderReloadCheck = now;
DateTime writeTimeUtc;
try
{
writeTimeUtc = File.GetLastWriteTimeUtc(shaderPath);
}
catch (Exception error)
{
if (!shaderReloadFailureReported)
{
Console.Error.WriteLine($"Shader hot reload cannot stat {shaderPath}: {error.Message}");
shaderReloadFailureReported = true;
}
return;
}
if (writeTimeUtc <= lastShaderWriteUtc || DateTime.UtcNow - writeTimeUtc < ShaderReloadWriteSettleTime)
{
return;
}
shaderReloadFailureReported = false;
try
{
var replacement = CompileShaderSet(shaderPath);
var oldVertexShader = vertexShader;
var oldGridHeightPixelShader = gridHeightPixelShader;
var oldPixelShader = pixelShader;
vertexShader = replacement.VertexShader;
gridHeightPixelShader = replacement.GridHeightPixelShader;
pixelShader = replacement.AquariumPixelShader;
oldPixelShader.Dispose();
oldGridHeightPixelShader.Dispose();
oldVertexShader.Dispose();
lastShaderWriteUtc = writeTimeUtc;
Console.WriteLine($"Shader hot reload applied: {shaderPath}");
}
catch (Exception error)
{
lastShaderWriteUtc = writeTimeUtc;
if (!shaderReloadFailureReported)
{
Console.Error.WriteLine($"Shader hot reload failed; keeping previous shaders. {error.Message}");
shaderReloadFailureReported = true;
}
}
}
private void BuildFroxelPrimitiveTable(AquariumFrame frame)
{
for (var i = 0; i < froxelPrimitiveIds.Length; i++)
@ -350,6 +418,18 @@ public sealed class D3D11Renderer : IDisposable
return Compiler.CompileFromFile(path, entryPoint, profile, shaderFlags, EffectFlags.None);
}
private ShaderSet CompileShaderSet(string path)
{
var vertexShaderBytecode = CompileShader(path, "FullscreenTriangleVS", "vs_5_0");
var gridHeightShaderBytecode = CompileShader(path, "GridHeightPS", "ps_5_0");
var pixelShaderBytecode = CompileShader(path, "AquariumPS", "ps_5_0");
return new ShaderSet(
device.CreateVertexShader(vertexShaderBytecode.Span, null),
device.CreatePixelShader(gridHeightShaderBytecode.Span, null),
device.CreatePixelShader(pixelShaderBytecode.Span, null));
}
private readonly record struct FrameConstants(
float2 Resolution,
float TimeSeconds,
@ -363,4 +443,9 @@ public sealed class D3D11Renderer : IDisposable
[StructLayout(LayoutKind.Sequential)]
private readonly record struct Int4(int X, int Y, int Z, int W);
private readonly record struct ShaderSet(
ID3D11VertexShader VertexShader,
ID3D11PixelShader GridHeightPixelShader,
ID3D11PixelShader AquariumPixelShader);
}