diff --git a/AGENTS.md b/AGENTS.md index c60428c..02b2f97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ clients. It owns the window, D3D12 renderer, input loop, live-reload boundary, audio host, debug chrome, render contracts, and reusable field/fractal machinery. Client-specific meaning belongs to client repos. Epiphany Aquarium lives at -`E:\Projects\Aquarium-Engine`. +`..\Aquarium`. ## Operating Doctrine diff --git a/docs/papers/fensalir-native-domain-reservoirs.pdf b/docs/papers/fensalir-native-domain-reservoirs.pdf deleted file mode 100644 index a06d2ca..0000000 Binary files a/docs/papers/fensalir-native-domain-reservoirs.pdf and /dev/null differ diff --git a/docs/papers/fensalir-pipeline.pdf b/docs/papers/fensalir-pipeline.pdf deleted file mode 100644 index e2482aa..0000000 Binary files a/docs/papers/fensalir-pipeline.pdf and /dev/null differ diff --git a/scripts/dev-reload.ps1 b/scripts/dev-reload.ps1 index 92e7bc0..574f364 100644 --- a/scripts/dev-reload.ps1 +++ b/scripts/dev-reload.ps1 @@ -18,11 +18,8 @@ $liveProjectPath = if ([System.IO.Path]::IsPathRooted($ClientProject)) { $Client $liveProjectPath = (Resolve-Path $liveProjectPath).Path $liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) $devRoot = Join-Path $repoRoot "artifacts\dev-reload" -# Everything the host may load as client code lives under $assemblyRoot (slots here, live-slots from dev-watch); -# it is the host's trusted root, so state, cache and logs in $devRoot are not part of it. -$assemblyRoot = Join-Path $devRoot "assemblies" -$slotRoot = Join-Path $assemblyRoot "slots" -$liveSlotRoot = Join-Path $assemblyRoot "live-slots" +$slotRoot = Join-Path $devRoot "slots" +$liveSlotRoot = Join-Path $devRoot "live-slots" $visibleStatePath = Join-Path $devRoot "state.clixml" $headlessStatePath = Join-Path $devRoot "headless-state.clixml" $statePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath } @@ -83,7 +80,6 @@ function Remove-OldSlots { return } - # Both roots hold client code the host may load; dev-watch adds a live slot per change and never prunes. $slots = foreach ($root in @($slotRoot, $liveSlotRoot)) { Get-ChildItem -Path $root -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTimeUtc -Descending | @@ -202,8 +198,7 @@ function Start-AquariumProcess { "--cache", $cultCachePath, "--shader-source", (Join-Path $SlotPath "Render\Shaders\D3D12HeightField.hlsl"), "--client-assembly", $LiveAssemblyPath, - "--client-reload-pointer", $liveReloadPointerPath, - "--client-trusted-root", $assemblyRoot + "--client-reload-pointer", $liveReloadPointerPath ) if ($RunHeadless) { $arguments += "--headless" @@ -249,13 +244,6 @@ function Reopen-VisibleProcess { $liveAssemblyPath = [string]$state.liveAssembly } - # Stale state fails here, in words, instead of as a refused load inside the host. - $assemblyRootPrefix = [System.IO.Path]::GetFullPath($assemblyRoot).TrimEnd('\') + '\' - foreach ($recorded in @($slotPath, $liveAssemblyPath)) { - if (-not [System.IO.Path]::GetFullPath($recorded).StartsWith($assemblyRootPrefix, [System.StringComparison]::OrdinalIgnoreCase)) { - throw "Visible dev-reload state names '$recorded', outside the assemblies root '$assemblyRoot' (state from before the trusted-root layout, or the root moved). Run dev-reload without -Reopen to rebuild." - } - } if (-not (Test-Path -LiteralPath $liveAssemblyPath)) { throw "Visible dev-reload state names '$liveAssemblyPath', which no longer exists (pruned slot). Run dev-reload without -Reopen to rebuild." } diff --git a/scripts/dev-watch.ps1 b/scripts/dev-watch.ps1 index 0b9c9cb..cc9ef3c 100644 --- a/scripts/dev-watch.ps1 +++ b/scripts/dev-watch.ps1 @@ -20,7 +20,7 @@ $liveProjectPath = (Resolve-Path $liveProjectPath).Path $liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) $clientSourceRoot = Split-Path $liveProjectPath $watchLogPath = Join-Path $repoRoot "artifacts\dev-reload\watch.log" -$liveSlotRoot = Join-Path $repoRoot "artifacts\dev-reload\assemblies\live-slots" +$liveSlotRoot = Join-Path $repoRoot "artifacts\dev-reload\live-slots" $liveReloadPointerPath = Join-Path $repoRoot "artifacts\dev-reload\live-current.txt" $shaderPath = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders\Aquarium.hlsl" $engineShaderRoot = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders" @@ -455,15 +455,12 @@ function Wait-LiveReloadAcknowledged { $stderrLog = if ($state.stderrLog) { [string]$state.stderrLog } else { $null } $timeoutSeconds = [Math]::Max(1, $LiveReloadAckTimeoutSeconds) $deadline = (Get-Date).AddSeconds($timeoutSeconds) - # The host logs the resolved path with backslashes doubled, which can differ from the path built here when the - # repo sits under a link. The slot directory name is unique, so match its leaf and the assembly name. - $slotLeaf = Split-Path -Leaf (Split-Path -Parent $liveAssemblyPath) - $appliedSuffix = ("$slotLeaf\" + (Split-Path -Leaf $liveAssemblyPath)).Replace("\", "\\") + $appliedLine = "Client runtime reload applied: $liveAssemblyPath" while ((Get-Date) -lt $deadline) { if (Test-Path $stdoutLog) { $stdoutTail = (Get-Content -Path $stdoutLog -Tail 120 -ErrorAction SilentlyContinue) -join "`n" - if ($stdoutTail -match ("(?m)^Client runtime reload applied: .*" + [regex]::Escape($appliedSuffix) + "\s*$")) { + if ($stdoutTail.Contains($appliedLine)) { Write-WatchLog "Live reload acknowledged by host: $liveAssemblyPath" return } diff --git a/src/Aquarium.Engine/Aquarium.Engine.csproj b/src/Aquarium.Engine/Aquarium.Engine.csproj index add87e4..8bf3795 100644 --- a/src/Aquarium.Engine/Aquarium.Engine.csproj +++ b/src/Aquarium.Engine/Aquarium.Engine.csproj @@ -30,7 +30,6 @@ - diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs index f3c1864..1966946 100644 --- a/src/Aquarium.Engine/AquariumHost.cs +++ b/src/Aquarium.Engine/AquariumHost.cs @@ -22,13 +22,12 @@ public static class AquariumHost IAquariumRuntime runtime; try { - loader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args), ParseClientTrustedRoot(args)); + loader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); runtime = loader.Load(); } catch (Exception error) { - // Startup refusals carry raw, attacker-writable paths; the console gets them escaped, once, here. - Console.Error.WriteLine($"Client runtime failed to start ({ClientRuntimeLoader.Printable(error.GetType().FullName ?? error.GetType().Name)}). {ClientRuntimeLoader.Printable(error.Message)}"); + Console.Error.WriteLine($"Client runtime failed to start ({error.GetType().FullName ?? error.GetType().Name}). {error.Message}"); loader?.Dispose(); return 1; } @@ -272,10 +271,6 @@ public static class AquariumHost ?? Environment.GetEnvironmentVariable("AQUARIUM_LIVE_ASSEMBLY"); } - private static readonly TrustedRootSetting TrustedRoot = TrustedRootSetting.FromProcessEnvironment(); - - private static string? ParseClientTrustedRoot(IReadOnlyCollection args) => TrustedRoot.Resolve(args); - private static string? ParseClientReloadPointerPath(IReadOnlyCollection args) { var values = args.ToArray(); diff --git a/src/Aquarium.Engine/Assets/Fensalir-Splash.png b/src/Aquarium.Engine/Assets/Fensalir-Splash.png deleted file mode 100644 index a2b1afc..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Splash.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png deleted file mode 100644 index e7d9173..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 deleted file mode 100644 index bcf3b09..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds b/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds deleted file mode 100644 index a3246b1..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds b/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds deleted file mode 100644 index c8487bf..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 6cdb517..2eb9192 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -237,9 +237,9 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12StructuredBuffer sdfObjectBuffer; private readonly D3D12StructuredBuffer gpuSensorCameraBuffer; private readonly D3D12StructuredBuffer acousticConstraintBuffer; - private readonly D3D12StructuredBuffer gpuFusionSeedBuffer; - private readonly D3D12StructuredBuffer gpuFusionPointBuffer; - private readonly D3D12StructuredBuffer temporalGaussianBuffer; + private D3D12StructuredBuffer? gpuFusionSeedBuffer; + private D3D12StructuredBuffer? gpuFusionPointBuffer; + private D3D12StructuredBuffer? temporalGaussianBuffer; private D3D12StructuredBuffer? fractalSplatBuffer; private D3D12StructuredBuffer? fractalSdfReservoirBuffer; private D3D12StructuredBuffer? fractalPbrReservoirBuffer; @@ -248,11 +248,11 @@ public sealed class D3D12Renderer : IAquariumRenderer private D3D12StructuredBuffer? fractalProgramTransformBuffer; private D3D12StructuredBuffer? bufferFieldTextureSplineProgramBuffer; private D3D12StructuredBuffer? bufferFieldTextureSampleBuffer; - private readonly D3D12StructuredBuffer tubeFieldVertexBuffer; - private readonly D3D12StructuredBuffer tubeFieldIndexBuffer; - private readonly D3D12StructuredBuffer tubeFieldSegmentBuffer; - private readonly D3D12StructuredBuffer tubeFieldStatsBuffer; - private readonly D3D12StructuredBuffer tubeFieldDrawArgumentBuffer; + private D3D12StructuredBuffer? tubeFieldVertexBuffer; + private D3D12StructuredBuffer? tubeFieldIndexBuffer; + private D3D12StructuredBuffer? tubeFieldSegmentBuffer; + private D3D12StructuredBuffer? tubeFieldStatsBuffer; + private D3D12StructuredBuffer? tubeFieldDrawArgumentBuffer; private readonly D3D12StructuredBuffer tubeFieldReplayManifestBuffer; private D3D12StructuredBuffer fieldReservoirCandidateBuffer = null!; private D3D12StructuredBuffer fieldReservoirLockBuffer = null!; @@ -280,8 +280,8 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly AquariumSdfObject[] sdfObjects = new AquariumSdfObject[MaxSdfObjectCount]; private readonly D3D12GpuSensorCameraPacket[] gpuSensorCameras = new D3D12GpuSensorCameraPacket[MaxGpuSensorCameraCount]; private readonly D3D12AcousticConstraintPacket[] acousticConstraints = new D3D12AcousticConstraintPacket[MaxAcousticConstraintCount]; - private readonly D3D12GpuFusionSeedPacket[] gpuFusionSeeds = new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; - private readonly D3D12TemporalGaussianPacket[] temporalGaussians = new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; + private D3D12GpuFusionSeedPacket[]? gpuFusionSeeds; + private D3D12TemporalGaussianPacket[]? temporalGaussians; private AquariumGpuFusionPointBuffer gpuFusionPointSource; private int temporalGaussianCount; private int gpuSensorCameraCount; @@ -444,28 +444,12 @@ public sealed class D3D12Renderer : IAquariumRenderer sdfObjectBuffer = new D3D12StructuredBuffer(device, MaxSdfObjectCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Object Buffer"); gpuSensorCameraBuffer = new D3D12StructuredBuffer(device, MaxGpuSensorCameraCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Camera Buffer"); acousticConstraintBuffer = new D3D12StructuredBuffer(device, MaxAcousticConstraintCount, Marshal.SizeOf(), "Aquarium D3D12 Acoustic Constraint Buffer"); - gpuFusionSeedBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Seed Buffer"); - gpuFusionPointBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Fusion Native Point Buffer"); - temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer", allowUnorderedAccess: true); - tubeFieldVertexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldVertices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Vertex Buffer", allowUnorderedAccess: true); - tubeFieldIndexBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldIndices, Marshal.SizeOf(), "Aquarium D3D12 TubeField Index Buffer", allowUnorderedAccess: true); - tubeFieldSegmentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldSegments, Marshal.SizeOf(), "Aquarium D3D12 TubeField Segment Buffer", allowUnorderedAccess: true); - tubeFieldStatsBuffer = new D3D12StructuredBuffer(device, 4, Marshal.SizeOf(), "Aquarium D3D12 TubeField Stats Buffer", allowUnorderedAccess: true); - tubeFieldDrawArgumentBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldDrawBatches * GeneratedMeshDrawArgumentUIntCount, Marshal.SizeOf(), "Aquarium D3D12 TubeField Indirect Draw Arguments", allowUnorderedAccess: true); tubeFieldReplayManifestBuffer = new D3D12StructuredBuffer(device, MaxTubeFieldReplaySources, Marshal.SizeOf(), "Aquarium D3D12 TubeField Replay Manifest"); CreateFieldReservoirBuffers(); resourceRegistry.Add("sdf-light-buffer", sdfLightBuffer); resourceRegistry.Add("sdf-object-buffer", sdfObjectBuffer); resourceRegistry.Add("gpu-sensor-camera-buffer", gpuSensorCameraBuffer); resourceRegistry.Add("acoustic-constraint-buffer", acousticConstraintBuffer); - resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); - resourceRegistry.Add("gpu-fusion-point-buffer", gpuFusionPointBuffer); - resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); - resourceRegistry.Add("tube-field-vertex-buffer", tubeFieldVertexBuffer); - resourceRegistry.Add("tube-field-index-buffer", tubeFieldIndexBuffer); - resourceRegistry.Add("tube-field-segment-buffer", tubeFieldSegmentBuffer); - resourceRegistry.Add("tube-field-stats-buffer", tubeFieldStatsBuffer); - resourceRegistry.Add("tube-field-indirect-draw-arguments", tubeFieldDrawArgumentBuffer); resourceRegistry.Add("tube-field-replay-manifest", tubeFieldReplayManifestBuffer); commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); commandList.Name = "Aquarium D3D12 Graphics Command List"; @@ -882,6 +866,8 @@ public sealed class D3D12Renderer : IAquariumRenderer EnsureFractalReservoirBuffers(activeFractalReservoirField); EnsureFractalProgramTransformBuffer(); EnsureBufferFieldProgramBuffers(); + EnsureTemporalGaussianResources(); + EnsureGpuSensorFusionResources(); var activeGpuSensorInput = frame.Scene.GpuSensorFrame.HasInput; var activeAccumulationWindow = activeGpuSensorInput ? frame.Scene.GpuSensorFrame.AccumulationWindowSeconds @@ -962,14 +948,40 @@ public sealed class D3D12Renderer : IAquariumRenderer CreateGpuSensorTextureViews(frame.Scene.GpuSensorFrame, frameResources.GpuSensorTextureDescriptor); frameResources.AcousticConstraintDescriptor = frameResources.TransientShaderDescriptors.Allocate(); acousticConstraintBuffer.CreateShaderResourceView(device, frameResources.AcousticConstraintDescriptor); - frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); - frameResources.GpuFusionPointDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionPointBuffer.CreateShaderResourceView(device, frameResources.GpuFusionPointDescriptor); + if (temporalGaussiansGpuGenerated && temporalGaussianCount > 0) + { + frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + if (gpuFusionSeedBuffer is not null) + { + gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.GpuFusionSeedDescriptor, Marshal.SizeOf()); + } + + frameResources.GpuFusionPointDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + if (gpuFusionPointBuffer is not null) + { + gpuFusionPointBuffer.CreateShaderResourceView(device, frameResources.GpuFusionPointDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.GpuFusionPointDescriptor, Marshal.SizeOf()); + } + } + frameResources.TemporalGaussianDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); - frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); + if (temporalGaussianBuffer is not null) + { + temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); + frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); + } + else + { + CreateNullStructuredBufferView(frameResources.TemporalGaussianDescriptor, Marshal.SizeOf()); + } frameResources.BlueNoiseDescriptor = frameResources.TransientShaderDescriptors.Allocate(); blueNoiseTexture.CreateShaderResourceView(device, frameResources.BlueNoiseDescriptor); frameResources.StudioPmremDescriptor = frameResources.TransientShaderDescriptors.Allocate(); @@ -1158,16 +1170,12 @@ public sealed class D3D12Renderer : IAquariumRenderer && heightFieldBrushPipelineState is not null && scenePipelineState is not null && splinePipelineState is not null - && temporalGaussianPipelineState is not null - && gpuSensorFusionPipelineState is not null && fractalSurfaceSplatRenderPipelineState is not null && fractalTransparentSplatRenderPipelineState is not null && fractalSplatPipelineState is not null && fractalSdfReservoirPipelineState is not null && fractalPbrReservoirPipelineState is not null && fractalRadiosityReservoirPipelineState is not null - && tubeFieldComputePipelineState is not null - && tubeFieldRenderPipelineState is not null && fieldReservoirResolvePipelineState is not null && sdfProxyPipelineStates.All(pipeline => pipeline is not null) && bloomPrefilterPipelineState is not null @@ -1221,18 +1229,18 @@ public sealed class D3D12Renderer : IAquariumRenderer DisposeFractalReservoirBuffers(); bufferFieldTextureSplineProgramBuffer?.Dispose(); bufferFieldTextureSampleBuffer?.Dispose(); - tubeFieldStatsBuffer.Dispose(); - tubeFieldDrawArgumentBuffer.Dispose(); + tubeFieldStatsBuffer?.Dispose(); + tubeFieldDrawArgumentBuffer?.Dispose(); tubeFieldReplayManifestBuffer.Dispose(); - tubeFieldSegmentBuffer.Dispose(); - tubeFieldIndexBuffer.Dispose(); - tubeFieldVertexBuffer.Dispose(); + tubeFieldSegmentBuffer?.Dispose(); + tubeFieldIndexBuffer?.Dispose(); + tubeFieldVertexBuffer?.Dispose(); fieldReservoirLockBuffer.Dispose(); fieldReservoirCandidateBuffer.Dispose(); DisposeFieldReservoirHistoryBuffers(); - temporalGaussianBuffer.Dispose(); - gpuFusionPointBuffer.Dispose(); - gpuFusionSeedBuffer.Dispose(); + temporalGaussianBuffer?.Dispose(); + gpuFusionPointBuffer?.Dispose(); + gpuFusionSeedBuffer?.Dispose(); acousticConstraintBuffer.Dispose(); gpuSensorCameraBuffer.Dispose(); foreach (var texture in externalSensorTextures.Values) @@ -1824,7 +1832,11 @@ public sealed class D3D12Renderer : IAquariumRenderer overlayWrappedBackBuffers = []; } - private D3D12PipelineSet CreatePipelineSet(D3D12ShaderPaths paths) + private D3D12PipelineSet CreatePipelineSet( + D3D12ShaderPaths paths, + bool includeTemporalGaussian, + bool includeGpuSensorFusion, + bool includeTubeField) { var heightFieldBase = CreateHeightFieldBasePipelineState(paths.HeightField); heightFieldBase.Name = "Aquarium D3D12 Height Field Base Pipeline"; @@ -1834,10 +1846,18 @@ public sealed class D3D12Renderer : IAquariumRenderer scene.Name = "Aquarium D3D12 Scene Pipeline"; var spline = CreateSplinePipelineState(paths.Spline); spline.Name = "Aquarium D3D12 Spline Surface Claim Pipeline"; - var temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); - temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; - var gpuSensorFusion = CreateGpuSensorFusionPipelineState(paths.GpuSensorFusion); - gpuSensorFusion.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + ID3D12PipelineState? temporalGaussian = null; + if (includeTemporalGaussian) + { + temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); + temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; + } + ID3D12PipelineState? gpuSensorFusion = null; + if (includeGpuSensorFusion) + { + gpuSensorFusion = CreateGpuSensorFusionPipelineState(paths.GpuSensorFusion); + gpuSensorFusion.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + } var fractalSurfaceSplatRender = CreateFractalSurfaceSplatRenderPipelineState(paths.FractalSplatRender); fractalSurfaceSplatRender.Name = "Aquarium D3D12 Fractal Surface Splat Render Pipeline"; var fractalTransparentSplatRender = CreateFractalTransparentSplatRenderPipelineState(paths.FractalSplatRender); @@ -1850,10 +1870,15 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalPbrReservoir.Name = "Aquarium D3D12 Fractal PBR Reservoir Compute Pipeline"; var fractalRadiosityReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12RadiosityReservoirCS"); fractalRadiosityReservoir.Name = "Aquarium D3D12 Fractal Radiosity Reservoir Compute Pipeline"; - var tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); - tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; - var tubeFieldRender = CreateTubeFieldRenderPipelineState(paths.TubeField); - tubeFieldRender.Name = "Aquarium D3D12 TubeField Render Pipeline"; + ID3D12PipelineState? tubeFieldCompute = null; + ID3D12PipelineState? tubeFieldRender = null; + if (includeTubeField) + { + tubeFieldCompute = CreateTubeFieldComputePipelineState(paths.TubeField); + tubeFieldCompute.Name = "Aquarium D3D12 TubeField Compute Pipeline"; + tubeFieldRender = CreateTubeFieldRenderPipelineState(paths.TubeField); + tubeFieldRender.Name = "Aquarium D3D12 TubeField Render Pipeline"; + } var fieldReservoirResolve = CreateFieldReservoirResolvePipelineState(paths.Post); fieldReservoirResolve.Name = "Aquarium D3D12 Field Reservoir Resolve Pipeline"; var sdfProxies = new ID3D12PipelineState[paths.SdfShaders.Count]; @@ -2406,6 +2431,135 @@ public sealed class D3D12Renderer : IAquariumRenderer } } + private void EnsureTemporalGaussianResources() + { + if (temporalGaussianCount <= 0) + { + return; + } + + if (temporalGaussianBuffer is null) + { + temporalGaussianBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 Temporal Gaussian Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); + } + + if (temporalGaussianPipelineState is null) + { + temporalGaussianPipelineState = CreateTemporalGaussianPipelineState(shaderPaths.TemporalGaussian); + temporalGaussianPipelineState.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; + } + } + + private void EnsureGpuSensorFusionResources() + { + if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) + { + return; + } + + if (gpuFusionPointCount > 0 && gpuFusionPointBuffer is null) + { + gpuFusionPointBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 GPU Sensor Fusion Native Point Buffer"); + resourceRegistry.Add("gpu-fusion-point-buffer", gpuFusionPointBuffer); + } + + if (gpuFusionSeedCount > 0 && gpuFusionSeedBuffer is null) + { + gpuFusionSeedBuffer = new D3D12StructuredBuffer( + device, + MaxTemporalGaussianCount, + Marshal.SizeOf(), + "Aquarium D3D12 GPU Sensor Fusion Seed Buffer"); + resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); + } + + if (gpuSensorFusionPipelineState is null) + { + gpuSensorFusionPipelineState = CreateGpuSensorFusionPipelineState(shaderPaths.GpuSensorFusion); + gpuSensorFusionPipelineState.Name = "Aquarium D3D12 GPU Sensor Fusion Compute Pipeline"; + } + } + + private void EnsureTubeFieldResources() + { + if (tubeFieldVertexBuffer is null) + { + tubeFieldVertexBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldVertices, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Vertex Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-vertex-buffer", tubeFieldVertexBuffer); + } + + if (tubeFieldIndexBuffer is null) + { + tubeFieldIndexBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldIndices, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Index Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-index-buffer", tubeFieldIndexBuffer); + } + + if (tubeFieldSegmentBuffer is null) + { + tubeFieldSegmentBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldSegments, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Segment Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-segment-buffer", tubeFieldSegmentBuffer); + } + + if (tubeFieldStatsBuffer is null) + { + tubeFieldStatsBuffer = new D3D12StructuredBuffer( + device, + 4, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Stats Buffer", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-stats-buffer", tubeFieldStatsBuffer); + } + + if (tubeFieldDrawArgumentBuffer is null) + { + tubeFieldDrawArgumentBuffer = new D3D12StructuredBuffer( + device, + MaxTubeFieldDrawBatches * GeneratedMeshDrawArgumentUIntCount, + Marshal.SizeOf(), + "Aquarium D3D12 TubeField Indirect Draw Arguments", + allowUnorderedAccess: true); + resourceRegistry.Add("tube-field-indirect-draw-arguments", tubeFieldDrawArgumentBuffer); + } + + if (tubeFieldComputePipelineState is null) + { + tubeFieldComputePipelineState = CreateTubeFieldComputePipelineState(shaderPaths.TubeField); + tubeFieldComputePipelineState.Name = "Aquarium D3D12 TubeField Compute Pipeline"; + } + + if (tubeFieldRenderPipelineState is null) + { + tubeFieldRenderPipelineState = CreateTubeFieldRenderPipelineState(shaderPaths.TubeField); + tubeFieldRenderPipelineState.Name = "Aquarium D3D12 TubeField Render Pipeline"; + } + } + private void DisposeFractalReservoirBuffers() { resourceRegistry.RemoveStructuredBuffer("buffer-field-texture-sample-buffer"); @@ -2516,9 +2670,9 @@ public sealed class D3D12Renderer : IAquariumRenderer context.CommandList.DrawInstanced(6, 1, 0, 0); } - if (temporalGaussianCount > 0) + if (temporalGaussianCount > 0 && temporalGaussianPipelineState is not null) { - context.CommandList.SetPipelineState(temporalGaussianPipelineState!); + context.CommandList.SetPipelineState(temporalGaussianPipelineState); context.CommandList.DrawInstanced(6, (uint)temporalGaussianCount, 0, 0); } @@ -2686,7 +2840,7 @@ public sealed class D3D12Renderer : IAquariumRenderer batch.Source.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); } - tubeFieldStatsBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + tubeFieldStatsBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); tubeFieldReplayManifestBuffer.Upload(activeCommandList, frameResources.UploadRing, replayManifest); activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); @@ -2694,8 +2848,18 @@ public sealed class D3D12Renderer : IAquariumRenderer for (var index = 0; index < MaxTubeFieldReplaySources; index++) { var descriptor = frameResources.TransientShaderDescriptors.Offset(replaySourceDescriptors, index); - var source = index < replaySourceCount ? tubeFieldDrawBatches[index].Source : tubeFieldStatsBuffer; - source.CreateRawShaderResourceView(device, descriptor); + if (index < replaySourceCount) + { + tubeFieldDrawBatches[index].Source.CreateRawShaderResourceView(device, descriptor); + } + else if (tubeFieldStatsBuffer is not null) + { + tubeFieldStatsBuffer.CreateRawShaderResourceView(device, descriptor); + } + else + { + CreateNullRawBufferView(descriptor); + } } activeCommandList.SetPipelineState(reservoirHistoryUpdatePipelineState); @@ -2723,7 +2887,12 @@ public sealed class D3D12Renderer : IAquariumRenderer private void RenderTubeFields(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (activeTubeFieldDrawIndexCount <= 0 || tubeFieldRenderPipelineState is null || tubeFieldDrawBatches.Count == 0) + if (activeTubeFieldDrawIndexCount <= 0 + || tubeFieldRenderPipelineState is null + || tubeFieldDrawBatches.Count == 0 + || tubeFieldVertexBuffer is null + || tubeFieldIndexBuffer is null + || tubeFieldDrawArgumentBuffer is null) { return; } @@ -3076,21 +3245,21 @@ public sealed class D3D12Renderer : IAquariumRenderer { if (gpuFusionPointCount > 0) { - gpuFusionPointBuffer.UploadPartialBytes( + gpuFusionPointBuffer!.UploadPartialBytes( activeCommandList, frameResources.UploadRing, gpuFusionPointSource.Buffer, gpuFusionPointCount, gpuFusionPointSource.StrideBytes); } - else + else if (gpuFusionSeedCount > 0) { - gpuFusionSeedBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds.AsSpan(0, gpuFusionSeedCount)); + gpuFusionSeedBuffer!.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds!.AsSpan(0, gpuFusionSeedCount)); } } - else + else if (temporalGaussianCount > 0) { - temporalGaussianBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians.AsSpan(0, temporalGaussianCount)); + temporalGaussianBuffer!.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians!.AsSpan(0, temporalGaussianCount)); } } finally @@ -3101,7 +3270,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DispatchGpuSensorFusion(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { - if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) + if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0 || temporalGaussianBuffer is null || gpuSensorFusionPipelineState is null) { return; } @@ -3109,12 +3278,12 @@ public sealed class D3D12Renderer : IAquariumRenderer activeCommandList.BeginEvent("GPU Sensor Fusion"); try { - gpuFusionSeedBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - gpuFusionPointBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + gpuFusionSeedBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); + gpuFusionPointBuffer?.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); activeCommandList.SetComputeRootSignature(gpuSensorFusionRootSignature); - activeCommandList.SetPipelineState(gpuSensorFusionPipelineState!); + activeCommandList.SetPipelineState(gpuSensorFusionPipelineState); activeCommandList.SetComputeRootDescriptorTable(RootFusionFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); activeCommandList.SetComputeRootDescriptorTable(RootFusionSeeds, frameResources.GpuFusionSeedDescriptor.Gpu); activeCommandList.SetComputeRootDescriptorTable(RootFusionSensorCameras, frameResources.GpuSensorCameraDescriptor.Gpu); @@ -3216,7 +3385,7 @@ public sealed class D3D12Renderer : IAquariumRenderer activeFieldResourceUploadCount = 0; activeFieldResourceUploadSkippedCount = 0; tubeFieldDrawBatches.Clear(); - if (tubeFieldComputePipelineState is null || activeFieldEvidenceFrame.TubeSplineLowerings.Count == 0) + if (activeFieldEvidenceFrame.TubeSplineLowerings.Count == 0) { return; } @@ -3277,6 +3446,8 @@ public sealed class D3D12Renderer : IAquariumRenderer continue; } + EnsureTubeFieldResources(); + activeTubeFieldTruncatedSegments += requestedSegments - dispatchSegments; var startIndex = segmentBase * 6; var fieldId = StableFieldId(lowering.ClaimKey, 5100.0f, 4096); @@ -3299,19 +3470,19 @@ public sealed class D3D12Renderer : IAquariumRenderer var constantsUpload = frameResources.UploadRing.WriteConstant(constants); sourceBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - tubeFieldVertexBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldIndexBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldStatsBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - tubeFieldDrawArgumentBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldVertexBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldIndexBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldStatsBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldDrawArgumentBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetComputeRootSignature(tubeFieldRootSignature); - activeCommandList.SetPipelineState(tubeFieldComputePipelineState); + activeCommandList.SetPipelineState(tubeFieldComputePipelineState!); activeCommandList.SetComputeRootConstantBufferView(RootTubeFieldConstants, constantsUpload.GpuVirtualAddress); activeCommandList.SetComputeRootShaderResourceView(RootTubeFieldSource, sourceBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldVertices, tubeFieldVertexBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldIndices, tubeFieldIndexBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldStats, tubeFieldStatsBuffer.Resource.GPUVirtualAddress); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldDrawArguments, tubeFieldDrawArgumentBuffer.Resource.GPUVirtualAddress); - tubeFieldSegmentBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); + tubeFieldSegmentBuffer!.Transition(activeCommandList, ResourceStates.UnorderedAccess); activeCommandList.SetComputeRootUnorderedAccessView(RootTubeFieldSegments, tubeFieldSegmentBuffer.Resource.GPUVirtualAddress); var ramp = ResolveTubeFieldRamp(activeCommandList, normalized.RampResourceKey); ramp.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); @@ -3506,6 +3677,46 @@ public sealed class D3D12Renderer : IAquariumRenderer descriptor.Cpu); } + private void CreateNullStructuredBufferView(D3D12DescriptorSlot descriptor, int strideBytes) + { + device.CreateShaderResourceView( + null, + new ShaderResourceViewDescription + { + Format = Format.Unknown, + ViewDimension = Vortice.Direct3D12.ShaderResourceViewDimension.Buffer, + Shader4ComponentMapping = ShaderComponentMapping.Default, + Buffer = new BufferShaderResourceView + { + FirstElement = 0, + NumElements = 1, + StructureByteStride = (uint)strideBytes, + Flags = BufferShaderResourceViewFlags.None, + }, + }, + descriptor.Cpu); + } + + private void CreateNullRawBufferView(D3D12DescriptorSlot descriptor) + { + device.CreateShaderResourceView( + null, + new ShaderResourceViewDescription + { + Format = Format.R32_Typeless, + ViewDimension = Vortice.Direct3D12.ShaderResourceViewDimension.Buffer, + Shader4ComponentMapping = ShaderComponentMapping.Default, + Buffer = new BufferShaderResourceView + { + FirstElement = 0, + NumElements = 1, + StructureByteStride = 0, + Flags = BufferShaderResourceViewFlags.Raw, + }, + }, + descriptor.Cpu); + } + private void RenderHeightField(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) { var viewport = new Viewport(0.0f, 0.0f, HeightFieldTextureSize, HeightFieldTextureSize); @@ -3629,6 +3840,7 @@ public sealed class D3D12Renderer : IAquariumRenderer temporalGaussianCount = seedCount; gpuFusionSeedCount = seedCount; temporalGaussiansGpuGenerated = true; + gpuFusionSeeds ??= new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; for (var index = 0; index < seedCount; index++) { gpuFusionSeeds[index] = ToGpuFusionSeedPacket(scene.GpuFusionField.Seeds[index]); @@ -3646,9 +3858,13 @@ public sealed class D3D12Renderer : IAquariumRenderer var gaussianCount = Math.Min(scene.TemporalGaussianField.Gaussians.Count, MaxTemporalGaussianCount); temporalGaussianCount = gaussianCount; - for (var index = 0; index < gaussianCount; index++) + if (gaussianCount > 0) { - temporalGaussians[index] = ToTemporalGaussianPacket(scene.TemporalGaussianField.Gaussians[index]); + temporalGaussians ??= new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; + for (var index = 0; index < gaussianCount; index++) + { + temporalGaussians[index] = ToTemporalGaussianPacket(scene.TemporalGaussianField.Gaussians[index]); + } } } @@ -4256,9 +4472,12 @@ public sealed class D3D12Renderer : IAquariumRenderer } var paths = shaderPaths; + var includeTemporalGaussian = temporalGaussianPipelineState is not null || temporalGaussianCount > 0; + var includeGpuSensorFusion = gpuSensorFusionPipelineState is not null || (temporalGaussiansGpuGenerated && temporalGaussianCount > 0); + var includeTubeField = tubeFieldComputePipelineState is not null || tubeFieldRenderPipelineState is not null || activeFieldEvidenceFrame.TubeSplineLowerings.Count > 0; LatestShaderWriteTimeUtc(); pipelineBuildInProgressReported = false; - pipelineBuildTask = Task.Run(() => CreatePipelineSet(paths)); + pipelineBuildTask = Task.Run(() => CreatePipelineSet(paths, includeTemporalGaussian, includeGpuSensorFusion, includeTubeField)); Console.WriteLine($"D3D12 shader pipeline build started ({reason}): {shaderSourceRoot}"); } @@ -4294,7 +4513,11 @@ public sealed class D3D12Renderer : IAquariumRenderer } var replacement = task.Result; - var oldPipelines = CapturePipelineSetOrNull(); + var oldPipelines = CapturePipelineSetOrNull( + includeTemporalGaussian: replacement.TemporalGaussian is not null, + includeGpuSensorFusion: replacement.GpuSensorFusion is not null, + includeTubeFieldCompute: replacement.TubeFieldCompute is not null, + includeTubeFieldRender: replacement.TubeFieldRender is not null); if (oldPipelines is not null) { WaitForGpu(); @@ -4316,7 +4539,11 @@ public sealed class D3D12Renderer : IAquariumRenderer } } - private D3D12PipelineSet? CapturePipelineSetOrNull() + private D3D12PipelineSet? CapturePipelineSetOrNull( + bool includeTemporalGaussian = true, + bool includeGpuSensorFusion = true, + bool includeTubeFieldCompute = true, + bool includeTubeFieldRender = true) { return PipelinesReady ? new D3D12PipelineSet( @@ -4324,16 +4551,16 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState!, scenePipelineState!, splinePipelineState!, - temporalGaussianPipelineState!, - gpuSensorFusionPipelineState!, + includeTemporalGaussian ? temporalGaussianPipelineState : null, + includeGpuSensorFusion ? gpuSensorFusionPipelineState : null, fractalSurfaceSplatRenderPipelineState!, fractalTransparentSplatRenderPipelineState!, fractalSplatPipelineState!, fractalSdfReservoirPipelineState!, fractalPbrReservoirPipelineState!, fractalRadiosityReservoirPipelineState!, - tubeFieldComputePipelineState!, - tubeFieldRenderPipelineState!, + includeTubeFieldCompute ? tubeFieldComputePipelineState : null, + includeTubeFieldRender ? tubeFieldRenderPipelineState : null, fieldReservoirResolvePipelineState!, sdfProxyPipelineStates.Select(pipeline => pipeline!).ToArray(), bloomPrefilterPipelineState!, @@ -4351,16 +4578,28 @@ public sealed class D3D12Renderer : IAquariumRenderer heightFieldBrushPipelineState = pipelines.HeightFieldBrush; scenePipelineState = pipelines.Scene; splinePipelineState = pipelines.Spline; - temporalGaussianPipelineState = pipelines.TemporalGaussian; - gpuSensorFusionPipelineState = pipelines.GpuSensorFusion; + if (pipelines.TemporalGaussian is not null) + { + temporalGaussianPipelineState = pipelines.TemporalGaussian; + } + if (pipelines.GpuSensorFusion is not null) + { + gpuSensorFusionPipelineState = pipelines.GpuSensorFusion; + } fractalSurfaceSplatRenderPipelineState = pipelines.FractalSurfaceSplatRender; fractalTransparentSplatRenderPipelineState = pipelines.FractalTransparentSplatRender; fractalSplatPipelineState = pipelines.FractalSplat; fractalSdfReservoirPipelineState = pipelines.FractalSdfReservoir; fractalPbrReservoirPipelineState = pipelines.FractalPbrReservoir; fractalRadiosityReservoirPipelineState = pipelines.FractalRadiosityReservoir; - tubeFieldComputePipelineState = pipelines.TubeFieldCompute; - tubeFieldRenderPipelineState = pipelines.TubeFieldRender; + if (pipelines.TubeFieldCompute is not null) + { + tubeFieldComputePipelineState = pipelines.TubeFieldCompute; + } + if (pipelines.TubeFieldRender is not null) + { + tubeFieldRenderPipelineState = pipelines.TubeFieldRender; + } fieldReservoirResolvePipelineState = pipelines.FieldReservoirResolve; for (var index = 0; index < sdfProxyPipelineStates.Length; index++) { @@ -4376,10 +4615,36 @@ public sealed class D3D12Renderer : IAquariumRenderer private void DisposePipelineStates() { - CapturePipelineSetOrNull()?.Dispose(); + resolvePipelineState?.Dispose(); + reservoirHistoryUpdatePipelineState?.Dispose(); + bloomBlurVerticalPipelineState?.Dispose(); + bloomBlurHorizontalPipelineState?.Dispose(); + bloomDownsamplePipelineState?.Dispose(); + bloomPrefilterPipelineState?.Dispose(); + fieldReservoirResolvePipelineState?.Dispose(); + foreach (var sdfProxy in sdfProxyPipelineStates) + { + sdfProxy?.Dispose(); + } + tubeFieldRenderPipelineState?.Dispose(); + tubeFieldComputePipelineState?.Dispose(); + fractalRadiosityReservoirPipelineState?.Dispose(); + fractalPbrReservoirPipelineState?.Dispose(); + fractalSdfReservoirPipelineState?.Dispose(); + fractalSplatPipelineState?.Dispose(); + fractalTransparentSplatRenderPipelineState?.Dispose(); + fractalSurfaceSplatRenderPipelineState?.Dispose(); + gpuSensorFusionPipelineState?.Dispose(); + temporalGaussianPipelineState?.Dispose(); + splinePipelineState?.Dispose(); + scenePipelineState?.Dispose(); + heightFieldBrushPipelineState?.Dispose(); + heightFieldBasePipelineState?.Dispose(); + heightFieldBasePipelineState = null; heightFieldBrushPipelineState = null; scenePipelineState = null; + splinePipelineState = null; temporalGaussianPipelineState = null; gpuSensorFusionPipelineState = null; fractalSurfaceSplatRenderPipelineState = null; @@ -4390,6 +4655,7 @@ public sealed class D3D12Renderer : IAquariumRenderer fractalRadiosityReservoirPipelineState = null; tubeFieldComputePipelineState = null; tubeFieldRenderPipelineState = null; + fieldReservoirResolvePipelineState = null; Array.Clear(sdfProxyPipelineStates); bloomPrefilterPipelineState = null; bloomDownsamplePipelineState = null; @@ -5419,16 +5685,16 @@ public sealed class D3D12Renderer : IAquariumRenderer ID3D12PipelineState HeightFieldBrush, ID3D12PipelineState Scene, ID3D12PipelineState Spline, - ID3D12PipelineState TemporalGaussian, - ID3D12PipelineState GpuSensorFusion, + ID3D12PipelineState? TemporalGaussian, + ID3D12PipelineState? GpuSensorFusion, ID3D12PipelineState FractalSurfaceSplatRender, ID3D12PipelineState FractalTransparentSplatRender, ID3D12PipelineState FractalSplat, ID3D12PipelineState FractalSdfReservoir, ID3D12PipelineState FractalPbrReservoir, ID3D12PipelineState FractalRadiosityReservoir, - ID3D12PipelineState TubeFieldCompute, - ID3D12PipelineState TubeFieldRender, + ID3D12PipelineState? TubeFieldCompute, + ID3D12PipelineState? TubeFieldRender, ID3D12PipelineState FieldReservoirResolve, IReadOnlyList SdfProxies, ID3D12PipelineState BloomPrefilter, @@ -5448,15 +5714,15 @@ public sealed class D3D12Renderer : IAquariumRenderer BloomPrefilter.Dispose(); FieldReservoirResolve.Dispose(); FractalRadiosityReservoir.Dispose(); - TubeFieldRender.Dispose(); - TubeFieldCompute.Dispose(); + TubeFieldRender?.Dispose(); + TubeFieldCompute?.Dispose(); FractalPbrReservoir.Dispose(); FractalSdfReservoir.Dispose(); FractalSplat.Dispose(); FractalTransparentSplatRender.Dispose(); FractalSurfaceSplatRender.Dispose(); - GpuSensorFusion.Dispose(); - TemporalGaussian.Dispose(); + GpuSensorFusion?.Dispose(); + TemporalGaussian?.Dispose(); Spline.Dispose(); foreach (var sdfProxy in SdfProxies) { diff --git a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs b/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs index d1734a8..185177c 100644 --- a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs +++ b/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs @@ -1,6 +1,6 @@ +using System.Diagnostics; using System.Reflection; using System.Runtime.Loader; -using System.Diagnostics; namespace Aquarium.Engine.Runtime; @@ -8,49 +8,24 @@ public sealed class ClientRuntimeLoader : IDisposable { private readonly string? clientAssemblyPath; private readonly string? clientReloadPointerPath; - private readonly string? trustedRoot; - private readonly string? trustedRootAsGiven; + private readonly TimeSpan reloadPollInterval; private readonly Stopwatch reloadClock = Stopwatch.StartNew(); private readonly AquariumRuntimeOptions options; private ReloadedRuntime? current; private TimeSpan lastReloadCheck; private string? currentAssemblyPath; - /// - /// Every assembly this loader runs, and every dependency or native library it resolves, must lie, links followed, - /// under (default: the directory of the initial assembly). The root is resolved once - /// here and pinned; a volume root is refused. A relative initial path is taken against the working directory; - /// a relative or UNC reload target is refused. The boundary this enforces is the root directory's own ACLs. - /// public ClientRuntimeLoader( AquariumRuntimeOptions options, string? clientAssemblyPath = null, string? clientReloadPointerPath = null, - string? trustedRoot = null) + TimeSpan? reloadPollInterval = null) { this.clientAssemblyPath = string.IsNullOrWhiteSpace(clientAssemblyPath) ? null : Path.GetFullPath(clientAssemblyPath); - this.clientReloadPointerPath = clientReloadPointerPath; + this.clientReloadPointerPath = string.IsNullOrWhiteSpace(clientReloadPointerPath) ? null : clientReloadPointerPath; + this.reloadPollInterval = reloadPollInterval ?? TimeSpan.FromMilliseconds(500); this.options = options; - - var root = string.IsNullOrWhiteSpace(trustedRoot) - ? this.clientAssemblyPath is null ? null : Path.GetDirectoryName(this.clientAssemblyPath) - : Path.GetFullPath(trustedRoot); - this.trustedRootAsGiven = root; - if (root is not null) - { - root = ResolveLinks(root); - if (string.Equals( - Path.TrimEndingDirectorySeparator(root), - Path.TrimEndingDirectorySeparator(Path.GetPathRoot(root) ?? root), - PathComparison)) - { - throw new ArgumentException($"A drive or volume root cannot be the client runtime trusted root: {root}", nameof(trustedRoot)); - } - - Console.WriteLine($"Client runtime trusted root: {Printable(root)}"); - } - - this.trustedRoot = root; + lastReloadCheck = -this.reloadPollInterval; } public IAquariumRuntime Runtime @@ -72,18 +47,26 @@ public sealed class ClientRuntimeLoader : IDisposable return Runtime; } - public void Reload(string assemblyPath, AquariumRuntimeOptions options) => - LoadResolved(ResolveTrusted(assemblyPath), options); - - private void LoadResolved(string assemblyPath, AquariumRuntimeOptions options) + public void Reload(string assemblyPath, AquariumRuntimeOptions options) { + if (string.IsNullOrWhiteSpace(assemblyPath)) + { + throw new ArgumentException("Client runtime assembly path cannot be blank.", nameof(assemblyPath)); + } + + var fullPath = Path.GetFullPath(assemblyPath); + if (!IsExistingDll(fullPath)) + { + throw new FileNotFoundException($"Client runtime assembly must resolve to an existing .dll: {fullPath}", fullPath); + } + var previous = current; - var loadContext = new ClientAssemblyLoadContext(assemblyPath, trustedRoot!); + var loadContext = new ClientAssemblyLoadContext(fullPath); IAquariumRuntime? nextRuntime = null; try { - var assembly = loadContext.LoadFromAssemblyPath(assemblyPath); + var assembly = loadContext.LoadFromAssemblyPath(fullPath); var factoryTypes = assembly.GetTypes() .Where(type => typeof(IAquariumRuntimeFactory).IsAssignableFrom(type) && type is { IsAbstract: false, IsInterface: false }) @@ -109,7 +92,7 @@ public sealed class ClientRuntimeLoader : IDisposable } current = new ReloadedRuntime(loadContext, nextRuntime); - currentAssemblyPath = assemblyPath; + currentAssemblyPath = fullPath; previous?.Runtime.Dispose(); previous?.Unload(); } @@ -122,7 +105,7 @@ public sealed class ClientRuntimeLoader : IDisposable private void TryReloadFromPointer() { - if (string.IsNullOrWhiteSpace(clientReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < TimeSpan.FromMilliseconds(500)) + if (string.IsNullOrWhiteSpace(clientReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < reloadPollInterval) { return; } @@ -143,159 +126,40 @@ public sealed class ClientRuntimeLoader : IDisposable return; } + string fullPath; try { - RequireLocalFullyQualified(candidatePath); // string rules first: no filesystem or network probe of a UNC path - RequireLexicallyUnderRoot(candidatePath); // and no probe of anything outside the root, whatever a link there points at - if (!File.Exists(candidatePath)) - { - return; - } + fullPath = Path.GetFullPath(candidatePath); + } + catch + { + return; + } - var resolved = ResolveTrusted(candidatePath); - if (string.Equals(resolved, currentAssemblyPath, PathComparison)) - { - return; - } + if (!IsExistingDll(fullPath) || string.Equals(fullPath, currentAssemblyPath, PathComparison)) + { + return; + } + try + { current?.Runtime.FlushState(); - LoadResolved(resolved, options); - Console.WriteLine($"Client runtime reload applied: {Printable(resolved)}"); + Reload(fullPath, options); + Console.WriteLine($"Client runtime reload applied: {fullPath}"); } catch (Exception error) { - Console.Error.WriteLine($"Client runtime reload failed; keeping previous runtime. {Printable(error.Message)}"); + Console.Error.WriteLine($"Client runtime reload failed; keeping previous runtime. {error.Message}"); } } + private static bool IsExistingDll(string path) => + string.Equals(Path.GetExtension(path), ".dll", StringComparison.OrdinalIgnoreCase) + && File.Exists(path); + private static StringComparison PathComparison => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - private string ResolveTrusted(string assemblyPath) => - trustedRoot is null - ? throw new InvalidOperationException("No trusted root for client runtime assemblies is set.") - : ResolveTrusted(trustedRoot, assemblyPath, trustedRootAsGiven); - - private void RequireLexicallyUnderRoot(string path) => - RequireLexicallyUnder(Path.GetFullPath(path), trustedRoot, trustedRootAsGiven); - - // Pure string comparison against the root as resolved and as given: a path outside both is refused before any - // filesystem access, so a link there (to a UNC share, a mapped drive) is never followed or probed. - private static void RequireLexicallyUnder(string fullPath, params string?[] roots) - { - if (!roots.Any(root => root is not null && IsUnder(root, fullPath))) - { - throw new InvalidOperationException($"Client runtime path is outside the trusted root '{roots[0]}': {fullPath}"); - } - } - - private static bool IsUnder(string root, string path) - { - var relative = Path.GetRelativePath(root, path); - return !(relative == ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) || Path.IsPathRooted(relative)); - } - - // The final path of a local, fully qualified file under the already-resolved root; throws otherwise. - internal static string ResolveTrusted(string resolvedRoot, string path, string? rootAsGiven = null) - { - RequireLocalFullyQualified(path); - RequireLexicallyUnder(Path.GetFullPath(path), resolvedRoot, rootAsGiven); - var resolved = ResolveLinks(Path.GetFullPath(path)); - if (!IsUnder(resolvedRoot, resolved)) - { - throw new InvalidOperationException($"Client runtime path is outside the trusted root '{resolvedRoot}': {path}"); - } - - return resolved; - } - - internal static void RequireLocalFullyQualified(string path) - { - if (!Path.IsPathFullyQualified(path) || (path.Length >= 2 && IsSeparator(path[0]) && IsSeparator(path[1]))) - { - throw new InvalidOperationException($"Client runtime path must be local and fully qualified: {path}"); - } - } - - // Paths come from files other people can write. Exception messages carry them raw; every console write escapes - // them here, once: backslashes, control, format (bidi, zero-width, tag characters) and line/paragraph separator - // characters, by code point, and lone surrogates. - internal static string Printable(string text) - { - var builder = new System.Text.StringBuilder(text.Length); - for (var index = 0; index < text.Length;) - { - if (!System.Text.Rune.TryGetRuneAt(text, index, out var rune)) - { - builder.Append($"\\u{(int)text[index]:x4}"); // a lone surrogate - index++; - continue; - } - - index += rune.Utf16SequenceLength; - var category = System.Text.Rune.GetUnicodeCategory(rune); - if (rune.Value == '\\') - { - builder.Append("\\\\"); - } - else if (category is System.Globalization.UnicodeCategory.Control or System.Globalization.UnicodeCategory.Format - or System.Globalization.UnicodeCategory.LineSeparator or System.Globalization.UnicodeCategory.ParagraphSeparator) - { - builder.Append(rune.Value switch - { - '\n' => "\\n", - '\r' => "\\r", - '\t' => "\\t", - <= 0xFFFF => $"\\u{rune.Value:x4}", - _ => $"\\U{rune.Value:x8}", - }); - } - else - { - builder.Append(rune.ToString()); - } - } - - return builder.ToString(); - } - - private static bool IsSeparator(char c) => c is '/' or '\\'; - - // The path with every symlink or junction on it replaced by its final target. - internal static string ResolveLinks(string path, int depth = 0) - { - if (depth > 32) - { - throw new InvalidOperationException($"Too many links resolving {path}."); - } - - for (var probe = path; probe is not null; probe = Path.GetDirectoryName(probe)) - { - FileSystemInfo info = Directory.Exists(probe) ? new DirectoryInfo(probe) : new FileInfo(probe); - if (info.LinkTarget is null) - { - continue; - } - - string target; - try - { - target = info.ResolveLinkTarget(returnFinalTarget: true)?.FullName - ?? throw new InvalidOperationException($"Link does not resolve: {probe}"); - } - catch (IOException error) - { - // Windows refuses to traverse a mount point made by a non-administrator ("untrusted mount point"): - // that is a refusal like any other, not a crash with a different type. - throw new InvalidOperationException($"Link cannot be resolved: {probe} ({error.GetType().Name})", error); - } - var rest = Path.GetRelativePath(probe, path); - return ResolveLinks(rest == "." ? target : Path.GetFullPath(Path.Combine(target, rest)), depth + 1); - } - - return path; - } - private string RequireClientAssemblyPath() { if (!string.IsNullOrWhiteSpace(clientAssemblyPath)) @@ -324,7 +188,7 @@ public sealed class ClientRuntimeLoader : IDisposable } } - private sealed class ClientAssemblyLoadContext(string assemblyPath, string trustedRoot) : AssemblyLoadContext(isCollectible: true) + private sealed class ClientAssemblyLoadContext(string assemblyPath) : AssemblyLoadContext(isCollectible: true) { private readonly AssemblyDependencyResolver resolver = new(assemblyPath); @@ -336,13 +200,13 @@ public sealed class ClientRuntimeLoader : IDisposable } var path = resolver.ResolveAssemblyToPath(assemblyName); - return path == null ? null : LoadFromAssemblyPath(ResolveTrusted(trustedRoot, path)); + return path == null ? null : LoadFromAssemblyPath(path); } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { var path = resolver.ResolveUnmanagedDllToPath(unmanagedDllName); - return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(ResolveTrusted(trustedRoot, path)); + return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path); } } } diff --git a/src/Aquarium.Engine/Runtime/TrustedRootSetting.cs b/src/Aquarium.Engine/Runtime/TrustedRootSetting.cs deleted file mode 100644 index f99bd2e..0000000 --- a/src/Aquarium.Engine/Runtime/TrustedRootSetting.cs +++ /dev/null @@ -1,48 +0,0 @@ -namespace Aquarium.Engine.Runtime; - -/// -/// The client runtime trusted root as given on the command line or in AQUARIUM_CLIENT_TRUSTED_ROOT. The environment -/// value is taken (read and cleared) the first time anything is resolved, on every path, and cached: children do not -/// inherit it and a second resolution does not silently fall back to the default root. A blank flag value, a flag with -/// no value or a blank environment value is refused. -/// -internal sealed class TrustedRootSetting(Func takeEnvironment) -{ - private const string Flag = "--client-trusted-root"; - private const string Variable = "AQUARIUM_CLIENT_TRUSTED_ROOT"; - private readonly Lazy fromEnvironment = new(takeEnvironment); - - public static TrustedRootSetting FromProcessEnvironment() => new(() => - { - var value = Environment.GetEnvironmentVariable(Variable); - Environment.SetEnvironmentVariable(Variable, null); - return value; - }); - - public string? Resolve(IReadOnlyCollection args) - { - var environment = fromEnvironment.Value; - if (environment is not null && string.IsNullOrWhiteSpace(environment)) - { - throw new ArgumentException($"{Variable} is set but empty; an empty value would fall back to the default root."); - } - - var values = args.ToArray(); - for (var index = 0; index < values.Length; index++) - { - if (!string.Equals(values[index], Flag, StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - if (index + 1 >= values.Length || string.IsNullOrWhiteSpace(values[index + 1])) - { - throw new ArgumentException($"{Flag} needs a directory; an empty value would fall back to the default root."); - } - - return values[index + 1]; - } - - return environment; - } -} diff --git a/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs b/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs new file mode 100644 index 0000000..e8ccc2c --- /dev/null +++ b/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTests.cs @@ -0,0 +1,173 @@ +using Aquarium.Engine; +using Aquarium.Engine.Input; +using Aquarium.Engine.Runtime; + +namespace Aquarium.Engine.Tests; + +public sealed class ClientRuntimeLoaderTests : IDisposable +{ + private static readonly AquariumRuntimeOptions Options = new(true, null); + private readonly string work = Directory.CreateDirectory( + Path.Combine(Path.GetTempPath(), "aquarium-loader-" + Guid.NewGuid().ToString("N"))).FullName; + + public void Dispose() + { + for (var attempt = 0; attempt < 5; attempt++) + { + try + { + if (Directory.Exists(work)) + { + Directory.Delete(work, recursive: true); + } + + return; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + Thread.Sleep(50); + } + } + } + + private string CopyValidRuntime(string directoryName, string fileName = "client.dll") + { + var directory = Directory.CreateDirectory(Path.Combine(work, directoryName)).FullName; + var path = Path.Combine(directory, fileName); + File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, path); + return path; + } + + [Fact] + public void ValidDllLoadsAndExposesItsOwnLocation() + { + var first = CopyValidRuntime("slot1"); + using var loader = new ClientRuntimeLoader(Options, first); + + var runtime = loader.Load(); + + Assert.Equal(first, runtime.GetType().Assembly.Location); + } + + [Fact] + public void PointerReloadAppliesNewDllOnceAndLogsPlainPath() + { + var first = CopyValidRuntime("slot1"); + var second = CopyValidRuntime("slot2"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + File.WriteAllText(pointer, second); + var stdout = CaptureOut(() => loader.Update(0.01f, new InputState())); + var reloaded = loader.Runtime; + + Assert.NotSame(initial, reloaded); + Assert.Equal(second, reloaded.GetType().Assembly.Location); + Assert.Contains($"Client runtime reload applied: {second}", stdout); + if (OperatingSystem.IsWindows()) + { + Assert.DoesNotContain(second.Replace("\\", "\\\\"), stdout); + } + + // Duplicate pointer update is ignored. + loader.Update(0.01f, new InputState()); + Assert.Same(reloaded, loader.Runtime); + } + + [Fact] + public void BlankMissingAndNonDllPointerTargetsAreIgnored() + { + var first = CopyValidRuntime("slot1"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + // Missing pointer file + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Blank pointer file + File.WriteAllText(pointer, " \r\n"); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Non-existent target + File.WriteAllText(pointer, Path.Combine(work, "missing", "client.dll")); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + + // Existing non-.dll file + var notADll = Path.Combine(work, "notes.txt"); + File.WriteAllText(notADll, "not a dll"); + File.WriteAllText(pointer, notADll); + loader.Update(0.01f, new InputState()); + Assert.Same(initial, loader.Runtime); + } + + [Fact] + public void BadDllInPointerKeepsPreviousRuntimeAlive() + { + var first = CopyValidRuntime("slot1"); + var badDll = Path.Combine(work, "bad.dll"); + File.WriteAllText(badDll, "not a valid assembly"); + var pointer = Path.Combine(work, "current.txt"); + using var loader = new ClientRuntimeLoader(Options, first, pointer, TimeSpan.Zero); + loader.Load(); + var initial = loader.Runtime; + + File.WriteAllText(pointer, badDll); + var stderr = CaptureError(() => loader.Update(0.01f, new InputState())); + + Assert.Same(initial, loader.Runtime); + Assert.Contains("Client runtime reload failed; keeping previous runtime.", stderr); + } + + [Fact] + public void MissingClientAssemblyOnHostStartupExitsNonZero() + { + var exitCode = 0; + var stderr = CaptureError(() => exitCode = AquariumHost.Run(["--headless"])); + + Assert.Equal(1, exitCode); + Assert.Contains("Client runtime failed to start", stderr); + } + + private static string CaptureOut(Action action) + { + var original = Console.Out; + using var captured = new StringWriter(); + Console.SetOut(captured); + try + { + action(); + } + finally + { + Console.SetOut(original); + } + + return captured.ToString(); + } + + private static string CaptureError(Action action) + { + var original = Console.Error; + using var captured = new StringWriter(); + Console.SetError(captured); + try + { + action(); + } + finally + { + Console.SetError(original); + } + + return captured.ToString(); + } +} diff --git a/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTrustTests.cs b/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTrustTests.cs deleted file mode 100644 index 6ab1693..0000000 --- a/tests/Aquarium.Engine.Tests/ClientRuntimeLoaderTrustTests.cs +++ /dev/null @@ -1,485 +0,0 @@ -using System.Diagnostics; -using Aquarium.Engine; -using Aquarium.Engine.Input; -using Aquarium.Engine.Runtime; - -namespace Aquarium.Engine.Tests; - -/// Runs only where this process can create symbolic links; otherwise reported as skipped with the reason. -public sealed class SymlinkFactAttribute : FactAttribute -{ - public SymlinkFactAttribute() - { - var probe = Path.Combine(Path.GetTempPath(), "aquarium-symlink-probe-" + Guid.NewGuid().ToString("N")); - try - { - File.CreateSymbolicLink(probe, Path.GetTempPath()); - File.Delete(probe); - } - catch (Exception error) when (error is IOException or UnauthorizedAccessException) - { - Skip = "This account cannot create symbolic links: " + error.Message; - } - } -} - -/// Junctions exist only on Windows. -public sealed class JunctionFactAttribute : FactAttribute -{ - public JunctionFactAttribute() - { - if (!OperatingSystem.IsWindows()) - { - Skip = "NTFS junctions exist only on Windows; run this test there."; - } - } -} - -/// Windows file names cannot contain a newline, so this setup cannot be built there. -public sealed class NewlineInFileNameFactAttribute : FactAttribute -{ - public NewlineInFileNameFactAttribute() - { - if (OperatingSystem.IsWindows()) - { - Skip = "Windows file names cannot contain a newline; the escaping is covered by the Printable tests."; - } - } -} - -public sealed class ClientRuntimeLoaderTrustTests : IDisposable -{ - private static readonly AquariumRuntimeOptions Options = new(true, null); - private readonly string work = Path.Combine(Path.GetTempPath(), "aquarium-trust-" + Guid.NewGuid().ToString("N")); - private readonly string trusted; - private readonly string outside; - - public ClientRuntimeLoaderTrustTests() - { - trusted = Directory.CreateDirectory(Path.Combine(work, "trusted")).FullName; - outside = Directory.CreateDirectory(Path.Combine(work, "outside")).FullName; - } - - // A loaded assembly stays locked on Windows until its unloaded context is collected: tolerate that here. - public void Dispose() - { - for (var attempt = 0; attempt < 5; attempt++) - { - try - { - Directory.Delete(work, recursive: true); - return; - } - catch (Exception error) when (error is IOException or UnauthorizedAccessException) - { - GC.Collect(); - GC.WaitForPendingFinalizers(); - Thread.Sleep(100); - } - } - - Console.Error.WriteLine($"Warning: test cleanup could not delete (locked loaded assembly?): {ClientRuntimeLoader.Printable(work)}"); - } - - // A real client assembly: the minimal sample, copied so its location is ours to choose. - private static string Copy(string directory, string name = "client.dll") - { - var path = Path.Combine(directory, name); - File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, path); - return path; - } - - [Fact] - public void AssemblyInsideTheTrustedRootLoadsAndReloads() - { - var first = Copy(trusted, "a.dll"); - var second = Copy(Directory.CreateDirectory(Path.Combine(trusted, "slot2")).FullName); - using var loader = new ClientRuntimeLoader(Options, first); - loader.Load(); - var before = loader.Runtime; - loader.Reload(second, Options); - Assert.NotSame(before, loader.Runtime); - } - - [Fact] - public void SiblingDirectoryOfTheInitialAssemblyLoadsOnlyInsideTheExplicitRoot() - { - // dev-watch reloads from live-slots, a sibling of the slot the host started in. - var slot = Directory.CreateDirectory(Path.Combine(trusted, "slots", "s1")).FullName; - var live = Directory.CreateDirectory(Path.Combine(trusted, "live-slots", "s2")).FullName; - var sibling = Copy(live); - using var loader = new ClientRuntimeLoader(Options, Copy(slot), trustedRoot: trusted); - loader.Load(); - loader.Reload(sibling, Options); - - using var narrow = new ClientRuntimeLoader(Options, Path.Combine(slot, "client.dll")); - narrow.Load(); - Assert.Throws(() => narrow.Reload(sibling, Options)); // default root is the initial directory - } - - [Fact] - public void InitialAssemblyOutsideTheExplicitRootIsRefused() - { - using var loader = new ClientRuntimeLoader(Options, Copy(outside), trustedRoot: trusted); - Assert.Throws(() => loader.Load()); - } - - [Fact] - public void ReloadOutsideTheRootViaDotDotOrRelativePathIsRefused() - { - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll")); - loader.Load(); - var escaped = Copy(outside); - Assert.Throws(() => loader.Reload(escaped, Options)); - Assert.Throws(() => loader.Reload(Path.Combine(trusted, "..", "outside", "client.dll"), Options)); - Assert.Throws(() => loader.Reload("a.dll", Options)); - } - - [Theory] - [InlineData("//host/share/client.dll")] - [InlineData(@"\\host\share\client.dll")] - [InlineData(@"\/host/share\client.dll")] - [InlineData(@"/\host\share/client.dll")] - public void UncPathsInAnySeparatorMixAreRefused(string path) - { - Assert.Throws(() => ClientRuntimeLoader.ResolveTrusted(trusted, path)); - } - - [Fact] - public void AVolumeRootCannotBeTheTrustedRoot() - { - Assert.Throws(() => new ClientRuntimeLoader(Options, Copy(trusted), trustedRoot: Path.GetPathRoot(trusted))); - } - - [Fact] - public void ADependencyOrNativeLibraryOutsideTheRootIsRefused() - { - // The load context resolves dependencies through the same check; assert the check it calls. - var dependency = Path.Combine(outside, "dep.dll"); - File.WriteAllText(dependency, ""); - Assert.Throws(() => ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), dependency)); - var inside = Path.Combine(trusted, "dep.so"); - File.WriteAllText(inside, ""); - Assert.Equal(inside, ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), inside)); - } - - [SymlinkFact] - public void SymlinkedFileOrDirectoryPointingOutsideTheRootIsRefused() - { - var fileLink = Path.Combine(trusted, "link.dll"); - var dirLink = Path.Combine(trusted, "dirlink"); - File.CreateSymbolicLink(fileLink, Copy(outside)); - Directory.CreateSymbolicLink(dirLink, outside); - - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll")); - loader.Load(); - Assert.Throws(() => loader.Reload(fileLink, Options)); - Assert.Throws(() => loader.Reload(Path.Combine(dirLink, "client.dll"), Options)); - } - - [JunctionFact] - public void JunctionPointingOutsideTheRootIsRefused() - { - var junction = Path.Combine(trusted, "junction"); - Copy(outside); - var mklink = Process.Start(new ProcessStartInfo("cmd.exe", $"/c mklink /J \"{junction}\" \"{outside}\"") { UseShellExecute = false, CreateNoWindow = true })!; - mklink.WaitForExit(); - Assert.Equal(0, mklink.ExitCode); - - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll")); - loader.Load(); - // Windows refuses an untrusted (non-administrator) mount point itself; the loader reports it as a refusal too. - Assert.ThrowsAny(() => loader.Reload(Path.Combine(junction, "client.dll"), Options)); - } - - [SymlinkFact] - public void ALoadedLinkIsStoredByItsResolvedPathSoThePointerDoesNotReloadItEveryPoll() - { - var real = Copy(Directory.CreateDirectory(Path.Combine(trusted, "real")).FullName); - var link = Path.Combine(trusted, "link.dll"); - File.CreateSymbolicLink(link, real); - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, link); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - - Thread.Sleep(600); // the loader polls the pointer at most every 500 ms - loader.Update(0.01f, new InputState()); - var afterFirst = loader.Runtime; // the link was loaded once, by its resolved path - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - - Assert.Same(afterFirst, loader.Runtime); - } - - [SymlinkFact] - public void TheTrustedRootIsPinnedAtConstructionAndNotReResolved() - { - var first = Directory.CreateDirectory(Path.Combine(work, "first")).FullName; - var second = Directory.CreateDirectory(Path.Combine(work, "second")).FullName; - var rootLink = Path.Combine(work, "root"); - Directory.CreateSymbolicLink(rootLink, first); - using var loader = new ClientRuntimeLoader(Options, Copy(first), trustedRoot: rootLink); - loader.Load(); - - Directory.Delete(rootLink); - Directory.CreateSymbolicLink(rootLink, second); // the root now names another directory - var elsewhere = Copy(second, "other.dll"); - - Assert.Throws(() => loader.Reload(Path.Combine(rootLink, "other.dll"), Options)); - Assert.Throws(() => loader.Reload(elsewhere, Options)); - } - - [Fact] - public void PointerNamingAnAssemblyOutsideTheRootKeepsThePreviousRuntime() - { - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, Copy(outside)); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - var before = loader.Runtime; - - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - - Assert.Same(before, loader.Runtime); - } - - [Fact] - public void AnUncPointerIsRefusedAndReportedBeforeAnyFilesystemProbe() - { - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, "//no-such-host.invalid/share/client.dll"); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - - var errors = CaptureError(() => - { - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - }); - - // File.Exists on this path would return false silently; the string rule must speak first. - Assert.Contains("local and fully qualified", errors); - } - - [NewlineInFileNameFact] - public void ControlCharactersInAPointerTargetAreEscapedInTheLog() - { - var hostile = Path.Combine(outside, "a\nClient runtime reload applied: forged.dll"); - File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, hostile); - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, hostile); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - - var errors = CaptureError(() => - { - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - }); - - Assert.Contains("outside the trusted root", errors); - Assert.DoesNotContain("\nClient runtime reload applied", errors); - Assert.Contains("\\nClient runtime reload applied", errors); - Assert.Equal("a\\u0007b", ClientRuntimeLoader.Printable("a\u0007b")); - } - - [Fact] - public void TheTrustedRootEnvironmentVariableIsTakenOnceOnEveryPathAndCached() - { - const string Name = "AQUARIUM_CLIENT_TRUSTED_ROOT"; - Environment.SetEnvironmentVariable(Name, "/from/env"); - var setting = TrustedRootSetting.FromProcessEnvironment(); - Assert.Equal("/from/flag", setting.Resolve(["--client-trusted-root", "/from/flag"])); - Assert.Null(Environment.GetEnvironmentVariable(Name)); // cleared although the flag won - Assert.Equal("/from/env", setting.Resolve([])); // cached: a second resolution does not fall to the default root - } - - [Theory] - [InlineData("")] - [InlineData(" ")] - public void ABlankEnvironmentValueIsRefusedLikeABlankFlag(string value) - { - Assert.Throws(() => new TrustedRootSetting(() => value).Resolve([])); - Assert.Throws(() => new TrustedRootSetting(() => null).Resolve(["--client-trusted-root", value])); - Assert.Throws(() => new TrustedRootSetting(() => null).Resolve(["--client-trusted-root"])); - } - - [Fact] - public void APathOutsideTheRootIsRefusedBeforeAnyLinkOnItIsFollowed() - { - // A link loop outside the root: following it would throw "Too many links"; the string check must refuse first. - var a = Path.Combine(outside, "a"); - var b = Path.Combine(outside, "b"); - try - { - Directory.CreateSymbolicLink(a, b); - Directory.CreateSymbolicLink(b, a); - } - catch (Exception error) when (error is IOException or UnauthorizedAccessException) - { - // No links here: the check is still exercised by the nonexistent outside path below. - } - - var error2 = Assert.Throws( - () => ClientRuntimeLoader.ResolveTrusted(ClientRuntimeLoader.ResolveLinks(trusted), Path.Combine(a, "client.dll"))); - Assert.Contains("outside the trusted root", error2.Message); - } - - [Fact] - public void ANonexistentPointerTargetOutsideTheRootIsRefusedAndReportedNotSilentlyIgnored() - { - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, Path.Combine(outside, "not-there.dll")); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - - var errors = CaptureError(() => - { - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - }); - - Assert.Contains("outside the trusted root", errors); - } - - [SymlinkFact] - public void ARootReachedThroughALinkAsGivenStillAcceptsPathsUnderIt() - { - var real = Directory.CreateDirectory(Path.Combine(work, "real")).FullName; - var rootLink = Path.Combine(work, "rootlink"); - Directory.CreateSymbolicLink(rootLink, real); - Copy(real, "a.dll"); - var viaLink = Path.Combine(rootLink, "b.dll"); - File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, viaLink); - using var loader = new ClientRuntimeLoader(Options, Path.Combine(rootLink, "a.dll"), trustedRoot: rootLink); - loader.Load(); - loader.Reload(viaLink, Options); - } - - [Fact] - public void ABackslashInAPointerTargetIsEscapedExactlyOnceInTheLog() - { - if (OperatingSystem.IsWindows()) - { - return; // a backslash is a separator in a Windows file name; the escaping itself is covered by the Printable tests - } - - var hostile = Path.Combine(outside, "x\\y.dll"); - File.Copy(typeof(Aquarium.Sample.Minimal.MinimalRuntime).Assembly.Location, hostile); - var pointer = Path.Combine(work, "pointer.txt"); - File.WriteAllText(pointer, hostile); - using var loader = new ClientRuntimeLoader(Options, Copy(trusted, "a.dll"), pointer); - loader.Load(); - - var errors = CaptureError(() => - { - Thread.Sleep(600); - loader.Update(0.01f, new InputState()); - }); - - Assert.Contains("x\\\\y.dll", errors); // one literal backslash is shown as two characters - Assert.DoesNotContain("x\\\\\\\\y.dll", errors); // not four: the message is not escaped a second time - } - - [Fact] - public void AStartupRefusalIsLoggedByTheHostAndExitsNonzero() - { - var volumeRoot = Path.GetPathRoot(Path.GetFullPath(work))!; - var exit = 0; - var errors = CaptureError(() => exit = AquariumHost.Run(["--headless", "--client-trusted-root", volumeRoot])); - - Assert.Equal(1, exit); - Assert.Contains("Client runtime failed to start (System.ArgumentException).", errors); - Assert.Contains("cannot be the client runtime trusted root", errors); - } - - [Fact] - public void ALoadedClientSeesItsOwnFilePathAsAssemblyLocation() - { - var path = Copy(trusted, "a.dll"); - using var loader = new ClientRuntimeLoader(Options, path); - loader.Load(); - - Assert.Equal(ClientRuntimeLoader.ResolveLinks(path), loader.Runtime.GetType().Assembly.Location); - } - - [Fact] - public void LoggedPathsEscapeAstralFormatCharactersAndLoneSurrogatesByCodePoint() - { - Assert.Equal("a\\U000e0001b", ClientRuntimeLoader.Printable("a\U000E0001b")); // language tag - Assert.Equal("a\\U000e0041b", ClientRuntimeLoader.Printable("a\U000E0041b")); // tag letter - Assert.Equal("a\\U0001d173b", ClientRuntimeLoader.Printable("a\U0001D173b")); // musical begin beam - Assert.Equal("a\\ud800b", ClientRuntimeLoader.Printable("a\ud800b")); // lone high surrogate - Assert.Equal("a\\udc00b", ClientRuntimeLoader.Printable("a\udc00b")); // lone low surrogate - Assert.Equal("a\\ud800\\ud800b", ClientRuntimeLoader.Printable("a\ud800\ud800b")); // two highs in a row - Assert.Equal("a\U0001F600b", ClientRuntimeLoader.Printable("a\U0001F600b")); // an ordinary astral character is kept - } - - [Fact] - public void LoggedPathsEscapeBackslashesLineSeparatorsAndBidiAndZeroWidthControls() - { - Assert.Equal("a\\\\b", ClientRuntimeLoader.Printable("a\\b")); - Assert.Equal("a\\u2028b", ClientRuntimeLoader.Printable("a\u2028b")); - Assert.Equal("a\\u2029b", ClientRuntimeLoader.Printable("a\u2029b")); - Assert.Equal("a\\u202eb", ClientRuntimeLoader.Printable("a\u202eb")); - Assert.Equal("a\\u200bb", ClientRuntimeLoader.Printable("a\u200bb")); - Assert.Equal("plain-name.dll", ClientRuntimeLoader.Printable("plain-name.dll")); - } - - [Fact] - public void DevScriptsKeepEverythingLoadableUnderOneAssembliesRootThatIsNotTheWholeDevRoot() - { - var scripts = Path.Combine(RepositoryRoot(), "scripts"); - var reload = File.ReadAllText(Path.Combine(scripts, "dev-reload.ps1")); - var watch = File.ReadAllText(Path.Combine(scripts, "dev-watch.ps1")); - - Assert.Contains("\"--client-trusted-root\", $assemblyRoot", reload); - Assert.DoesNotContain("\"--client-trusted-root\", $devRoot", reload); - Assert.Contains("$slotRoot = Join-Path $assemblyRoot \"slots\"", reload); - Assert.Contains("artifacts\\dev-reload\\assemblies\\live-slots", watch); - } - - [Fact] - public void DevScriptsMatchTheHostAckByItsUniqueSlotLeafPruneLiveSlotsAndRejectStaleReopenState() - { - var scripts = Path.Combine(RepositoryRoot(), "scripts"); - var reload = File.ReadAllText(Path.Combine(scripts, "dev-reload.ps1")); - var watch = File.ReadAllText(Path.Combine(scripts, "dev-watch.ps1")); - - Assert.Contains(".Replace(\"\\\", \"\\\\\")", watch); // the host logs backslashes doubled - Assert.DoesNotContain("Contains($appliedLine)", watch); - Assert.Contains("@($slotRoot, $liveSlotRoot)", reload); - Assert.Contains("outside the assemblies root", reload); - Assert.Contains("no longer exists (pruned slot)", reload); - } - - private static string CaptureError(Action action) - { - var original = Console.Error; - using var captured = new StringWriter(); - Console.SetError(captured); - try - { - action(); - } - finally - { - Console.SetError(original); - } - - return captured.ToString(); - } - - private static string RepositoryRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Fensalir.sln"))) - { - directory = directory.Parent; - } - - return directory?.FullName ?? throw new InvalidOperationException("Fensalir.sln not found above the test binaries."); - } -}