Resolve field resources into D3D12 slots

This commit is contained in:
Meta Vens 2026-05-26 17:31:07 +01:00
commit b6967e8351
6 changed files with 194 additions and 7 deletions

View file

@ -402,7 +402,10 @@ public static class AquariumFieldEvidenceValidator
issues.Add(Warning(resource.ResourceKey, "Field resource is not GPU-visible; shader lowering must import or upload before use."));
}
resourceKeys.Add(resource.ResourceKey);
if (!resourceKeys.Add(resource.ResourceKey))
{
issues.Add(Error(resource.ResourceKey, "Field resource declarations must have unique keys."));
}
}
foreach (var claim in frame.Claims)

View file

@ -0,0 +1,150 @@
using Vortice.Direct3D12;
namespace Aquarium.Engine.Render;
internal readonly record struct D3D12FieldResourceStats(
int Declared,
int Resolved,
int StructuredBuffers,
int Unsupported,
int StaleRemoved)
{
public static D3D12FieldResourceStats Empty { get; } = new(0, 0, 0, 0, 0);
}
internal sealed class D3D12FieldResourceRegistry : IDisposable
{
private const string RegistryPrefix = "field-resource:";
private readonly Dictionary<string, StructuredBufferSlot> structuredBuffers = new(StringComparer.Ordinal);
private readonly HashSet<string> liveKeys = new(StringComparer.Ordinal);
public D3D12FieldResourceStats Resolve(
ID3D12Device device,
D3D12ResourceRegistry resourceRegistry,
IReadOnlyList<AquariumFieldResourceDeclaration> declarations)
{
ArgumentNullException.ThrowIfNull(device);
ArgumentNullException.ThrowIfNull(resourceRegistry);
ArgumentNullException.ThrowIfNull(declarations);
liveKeys.Clear();
var resolved = 0;
var structuredBufferCount = 0;
var unsupported = 0;
foreach (var declaration in declarations)
{
if (!declaration.HasIdentity || !declaration.HasShape || !declaration.IsGpuVisible)
{
unsupported++;
continue;
}
if (!liveKeys.Add(declaration.ResourceKey))
{
unsupported++;
continue;
}
if (declaration.Kind is AquariumFieldResourceKind.StructuredBuffer or AquariumFieldResourceKind.CurvePointBuffer)
{
ResolveStructuredBuffer(device, resourceRegistry, declaration);
resolved++;
structuredBufferCount++;
continue;
}
unsupported++;
}
var staleRemoved = RemoveStaleStructuredBuffers(resourceRegistry, liveKeys);
return new D3D12FieldResourceStats(
Declared: declarations.Count,
Resolved: resolved,
StructuredBuffers: structuredBufferCount,
Unsupported: unsupported,
StaleRemoved: staleRemoved);
}
public void Dispose()
{
foreach (var slot in structuredBuffers.Values)
{
slot.Buffer.Dispose();
}
structuredBuffers.Clear();
liveKeys.Clear();
}
private void ResolveStructuredBuffer(
ID3D12Device device,
D3D12ResourceRegistry resourceRegistry,
AquariumFieldResourceDeclaration declaration)
{
var elementCount = Math.Max(1, declaration.DepthOrCount > 0 ? declaration.DepthOrCount : declaration.Width);
var strideBytes = Math.Max(1, declaration.StrideBytes);
var allowUnorderedAccess = declaration.Access == AquariumFieldShaderAccess.UnorderedAccess;
var hasExisting = structuredBuffers.TryGetValue(declaration.ResourceKey, out var existing);
if (hasExisting && existing is not null &&
existing.ElementCount == elementCount &&
existing.StrideBytes == strideBytes &&
existing.AllowUnorderedAccess == allowUnorderedAccess &&
existing.Version == declaration.Version)
{
return;
}
var registryKey = RegistryKey(declaration.ResourceKey);
if (hasExisting && existing is not null)
{
resourceRegistry.RemoveStructuredBuffer(registryKey);
existing.Buffer.Dispose();
}
var buffer = new D3D12StructuredBuffer(
device,
elementCount,
strideBytes,
$"Aquarium D3D12 Field Resource {declaration.ResourceKey}",
allowUnorderedAccess);
resourceRegistry.Add(registryKey, buffer);
structuredBuffers[declaration.ResourceKey] = new StructuredBufferSlot(
buffer,
elementCount,
strideBytes,
allowUnorderedAccess,
declaration.Version);
}
private int RemoveStaleStructuredBuffers(D3D12ResourceRegistry resourceRegistry, HashSet<string> currentKeys)
{
var removed = 0;
foreach (var key in structuredBuffers.Keys.ToArray())
{
if (currentKeys.Contains(key))
{
continue;
}
resourceRegistry.RemoveStructuredBuffer(RegistryKey(key));
structuredBuffers[key].Buffer.Dispose();
structuredBuffers.Remove(key);
removed++;
}
return removed;
}
private static string RegistryKey(string resourceKey) => RegistryPrefix + resourceKey;
private sealed record StructuredBufferSlot(
D3D12StructuredBuffer Buffer,
int ElementCount,
int StrideBytes,
bool AllowUnorderedAccess,
ulong Version);
}

View file

@ -116,6 +116,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
private readonly ID3D11On12Device overlayOn12Device;
private readonly IDXGISwapChain3 swapChain;
private readonly D3D12ResourceRegistry resourceRegistry = new();
private readonly D3D12FieldResourceRegistry fieldResourceRegistry = new();
private D3D12DescriptorArena renderTargetViewArena;
private D3D12DescriptorArena depthStencilViewArena;
private D3D12DescriptorArena staticShaderDescriptorArena;
@ -220,6 +221,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
private AquariumFieldEvidenceFrame activeFieldEvidenceFrame = AquariumFieldEvidenceFrame.Empty;
private AquariumFieldEvidenceValidationReport activeFieldEvidenceValidation = AquariumFieldEvidenceValidationReport.Empty;
private AquariumFieldLoweringPlan activeFieldLoweringPlan = AquariumFieldLoweringPlan.Empty;
private D3D12FieldResourceStats activeFieldResourceStats = D3D12FieldResourceStats.Empty;
private Viewport viewport;
private RawRect scissorRect;
private int width;
@ -497,7 +499,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
var errorCount = activeFieldEvidenceValidation.Issues.Count(issue => issue.Severity == AquariumFieldEvidenceIssueSeverity.Error);
return
$"domains {activeFieldEvidenceFrame.Domains.Count} / claims {activeFieldEvidenceFrame.Claims.Count} / " +
$"resources {activeFieldEvidenceFrame.Resources.Count} / " +
$"resources {activeFieldEvidenceFrame.Resources.Count} resolved {activeFieldResourceStats.Resolved} unsupported {activeFieldResourceStats.Unsupported} / " +
$"candidates {activeFieldEvidenceFrame.Candidates.Count} / packets {activeFieldEvidenceFrame.BackendPackets.Count} / " +
$"planned {activeFieldLoweringPlan.Packets.Count} / deferred {activeFieldLoweringPlan.DeferredRequests.Count} / errors {errorCount}";
}
@ -934,6 +936,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
blueNoiseTexture.Dispose();
studioIrradianceTexture.Dispose();
studioPmremTexture.Dispose();
fieldResourceRegistry.Dispose();
DisposeFractalReservoirBuffers();
bufferFieldTextureSplineProgramBuffer?.Dispose();
bufferFieldTextureSampleBuffer?.Dispose();
@ -2295,6 +2298,9 @@ public sealed class D3D12Renderer : IAquariumRenderer
? scene.FieldEvidenceFrame
: AquariumFieldEvidenceFrame.Empty;
activeFieldEvidenceValidation = AquariumFieldEvidenceValidator.Validate(activeFieldEvidenceFrame);
activeFieldResourceStats = activeFieldEvidenceValidation.HasErrors
? fieldResourceRegistry.Resolve(device, resourceRegistry, [])
: fieldResourceRegistry.Resolve(device, resourceRegistry, activeFieldEvidenceFrame.Resources);
activeFieldLoweringPlan = activeFieldEvidenceValidation.HasErrors
? AquariumFieldLoweringPlan.Empty
: AquariumFieldLoweringPlanner.Plan(activeFieldEvidenceFrame);
@ -2781,6 +2787,9 @@ public sealed class D3D12Renderer : IAquariumRenderer
Console.WriteLine(
$"D3D12 field evidence: domains {activeFieldEvidenceFrame.Domains.Count:N0}; " +
$"resources {activeFieldEvidenceFrame.Resources.Count:N0}; " +
$"resolved resources {activeFieldResourceStats.Resolved:N0}; " +
$"structured buffers {activeFieldResourceStats.StructuredBuffers:N0}; " +
$"unsupported resources {activeFieldResourceStats.Unsupported:N0}; " +
$"claims {activeFieldEvidenceFrame.Claims.Count:N0}; " +
$"candidates {activeFieldEvidenceFrame.Candidates.Count:N0}; " +
$"producer packets {activeFieldEvidenceFrame.BackendPackets.Count:N0}; " +

View file

@ -233,3 +233,4 @@
{"lesson":"AquariumFieldLoweringPlanner now converts pending lowering requests into backend packets only for unambiguous encodings: height/SDF2D to surface pages, SDF3D to direct SDF, density/extinction to volume splats, tube to tube field, and mesh to mesh. Ambiguous feature/confidence/material-style evidence is deferred instead of guessed. This keeps backend selection in Fensalir while avoiding new hidden policy. Engine tests passed with 14 tests; Fensalir.sln built cleanly, and Mimir.slnx still builds against the contract.","timestamp":"2026-05-26T14:42:00+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs"],"source":"continued rendering rebuild Phase 1","topic":"field-evidence-lowering-planner"}
{"lesson":"D3D12Renderer now consumes AquariumSceneState.FieldEvidenceFrame at the renderer boundary as planning telemetry. Each frame validates field evidence, builds the conservative backend-lowering plan, and exposes counts for domains, claims, candidates, producer packets, planned packets, deferred requests, and validation issues in debug/console. It does not render these packets yet, preserving the migration order. Fensalir.sln builds cleanly and Mimir.slnx builds against the integrated path.","timestamp":"2026-05-26T15:02:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs"],"source":"continued rendering rebuild Phase 1","topic":"renderer-field-evidence-ingest"}
{"lesson":"Field packet payload handles are now demoted behind typed resource declarations. AquariumFieldEvidenceFrame carries AquariumFieldResourceDeclaration rows; validation rejects unknown resource references; the lowering planner defers resource-backed encodings without declared GPU-visible compatible resources; AquariumFieldScriptCompiler.CompileEvidence can bind declared resources and produce planned TubeField packets. D3D12Renderer debug/console summaries now show resource counts. Visible rendering remains blocked on the D3D12 packet/resource resolver that imports or aliases structured buffers, textures, meshes, surface pages, and volumes and binds them to selected shader lowerings.","timestamp":"2026-05-26T16:42:47+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/map.yaml"],"source":"continued Mimir/Fensalir field resource boundary implementation","topic":"field-resource-declarations"}
{"lesson":"The corrected Mimir/Fensalir resource boundary is in-process engine ownership, not a cross-process payload authority. D3D12Renderer now owns a D3D12FieldResourceRegistry that resolves valid AquariumFieldResourceDeclaration rows into Fensalir-owned structured/curve buffer slots, reuses unchanged slots, recreates changed shape/access/version, and retires stale slots from the renderer resource registry. Duplicate resource keys are validation errors. Visible rendering is no longer blocked on ownership resolution for structured TubeField payloads; it is blocked on shader binding selected TubeField packets to the resolved slots, with texture, mesh, surface-page, and volume resolvers still future cuts. dotnet build Fensalir.sln --no-restore passed with 0 warnings; dotnet test tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj --no-restore passed with 16 tests.","timestamp":"2026-05-26T17:29:30+01:00","files":["src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs","state/map.yaml"],"source":"continued Mimir/Fensalir field resource boundary implementation","topic":"d3d12-field-resource-registry"}

View file

@ -71,11 +71,13 @@ next_actions:
- Keep `dotnet build Fensalir.sln` green after the split.
- Cut the rendering rebuild through explicit field-domain/field-claim
contracts before adding another backend-specific visual path.
- Add the D3D12 field packet/resource resolver: import or alias declared
GPU-resident structured buffers, textures, meshes, surface pages, and
volumes, then bind them to selected shader lowerings. Current contracts and
DSL can plan resource-backed TubeField packets, but visible rendering is
blocked until this engine-owned resolver exists.
- Extend the D3D12 field packet/resource resolver beyond its first
Fensalir-owned structured-buffer slot cut. Current contracts, DSL, and
renderer registry can validate, plan, allocate, reuse, and retire
GPU-visible structured/curve buffer resources for resource-backed
TubeField packets. Visible rendering is now blocked on binding those
resolved slots into a concrete shader lowering, then adding honest
texture, mesh, surface-page, and volume resource resolvers.
- Move any remaining client-only Epiphany state found here back to `E:\Projects\Aquarium-Engine`.
- Keep Mimir app/adapters out of this repo; Fensalir may expose generic sensor-fusion contracts only.
- Package contracts/host deliberately before replacing sibling source references in client repos.

View file

@ -172,6 +172,28 @@ public sealed class FieldEvidenceContractTests
Assert.Contains(report.Issues, issue => issue.Key == "packet:debug");
}
[Fact]
public void ValidatorRejectsDuplicateFieldResourceKeys()
{
var frame = BuildValidTubeEvidenceFrame();
var duplicate = frame.Resources[0] with { Version = 43 };
frame = new AquariumFieldEvidenceFrame
{
Resources = [frame.Resources[0], duplicate],
Domains = frame.Domains,
Claims = frame.Claims,
Candidates = frame.Candidates,
BackendPackets = frame.BackendPackets,
AccumulationWindowSeconds = frame.AccumulationWindowSeconds,
PresentationDelaySeconds = frame.PresentationDelaySeconds,
};
var report = AquariumFieldEvidenceValidator.Validate(frame);
Assert.True(report.HasErrors);
Assert.Contains(report.Issues, issue => issue.Key == "mimir:resource:native-ring:asio-ch0");
}
[Fact]
public void NormalizerBuildsPendingLoweringRequestsWithoutChoosingBackend()
{