From 3e03ebdaecebb920e75fd3c78ce04a386a8d063d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 27 May 2026 14:11:48 +0100 Subject: [PATCH] Upload raw frames into leased textures --- .../AquariumRuntimeServices.cs | 2 + .../Render/AquariumFieldEvidence.cs | 4 + .../Render/AquariumFieldResourceBroker.cs | 20 +++ .../Render/D3D12FieldTextureFormat.cs | 4 +- src/Aquarium.Engine/Render/D3D12Renderer.cs | 123 ++++++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 8 +- .../D3D12FieldTextureFormatTests.cs | 3 +- 8 files changed, 160 insertions(+), 5 deletions(-) diff --git a/src/Aquarium.Engine.Contracts/AquariumRuntimeServices.cs b/src/Aquarium.Engine.Contracts/AquariumRuntimeServices.cs index 965856f..1bd9240 100644 --- a/src/Aquarium.Engine.Contracts/AquariumRuntimeServices.cs +++ b/src/Aquarium.Engine.Contracts/AquariumRuntimeServices.cs @@ -25,4 +25,6 @@ internal sealed class AquariumNullFieldResourceBroker : IAquariumFieldResourceBr public AquariumFieldResourceLease LeaseTexture2D(AquariumTexture2DLeaseRequest request) => AquariumFieldResourceLease.Invalid; public bool CommitLeaseVersion(string resourceKey, ulong version, ulong producerFenceValue) => false; + + public bool UploadTexture2D(AquariumTexture2DUpload upload) => false; } diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs b/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs index d9cf82b..8808ee4 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs @@ -525,7 +525,11 @@ public readonly record struct AquariumFieldResourceDeclaration( "R8Unorm" or "R8_UNorm" or "R8_UNORM" => 1, "R16Float" or "R16_Float" or "R16_FLOAT" => 2, "R32Float" or "R32_Float" or "R32_FLOAT" or "Float32" => 4, + "Rg8" or "Rg8Unorm" or "R8G8_UNorm" or "R8G8_UNORM" or "Yuy2" or "YUY2" or "LeapStereoIr" or "LeapPackedMap" => 2, + "Bayer8" or "Gray8" or "R8" => 1, + "Bgra8" or "Bgra8Unorm" or "B8G8R8A8_UNorm" or "B8G8R8A8_UNORM" or "Rgba8Unorm" or "R8G8B8A8_UNorm" or "R8G8B8A8_UNORM" => 4, "Rgba16Float" or "R16G16B16A16_Float" or "R16G16B16A16_FLOAT" => 8, + "Nv12" or "NV12" => 1, _ => 4, }; } diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs b/src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs index 58ef585..46e8dc5 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs @@ -5,6 +5,8 @@ public interface IAquariumFieldResourceBroker AquariumFieldResourceLease LeaseTexture2D(AquariumTexture2DLeaseRequest request); bool CommitLeaseVersion(string resourceKey, ulong version, ulong producerFenceValue); + + bool UploadTexture2D(AquariumTexture2DUpload upload); } public readonly record struct AquariumTexture2DLeaseRequest( @@ -41,3 +43,21 @@ public readonly record struct AquariumFieldResourceLease( 0, false); } + +public readonly record struct AquariumTexture2DUpload( + string ResourceKey, + int Width, + int Height, + string Format, + int SourceStrideBytes, + ReadOnlyMemory Data, + ulong Version = 0) +{ + public bool IsValid => + !string.IsNullOrWhiteSpace(ResourceKey) && + Width > 0 && + Height > 0 && + SourceStrideBytes > 0 && + !string.IsNullOrWhiteSpace(Format) && + Data.Length >= checked(SourceStrideBytes * Height); +} diff --git a/src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs b/src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs index b62588e..1c3cf12 100644 --- a/src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs +++ b/src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs @@ -11,12 +11,12 @@ internal static class D3D12FieldTextureFormat "Gray8" or "R8" or "R8Unorm" or "R8_UNorm" or "R8_UNORM" => Format.R8_UNorm, "R16Float" or "R16_Float" or "R16_FLOAT" => Format.R16_Float, "R32Float" or "R32_Float" or "R32_FLOAT" or "Float32" => Format.R32_Float, - "Rg8" or "Rg8Unorm" or "R8G8_UNorm" or "R8G8_UNORM" => Format.R8G8_UNorm, + "Rg8" or "Rg8Unorm" or "R8G8_UNorm" or "R8G8_UNORM" or "LeapStereoIr" or "LeapPackedMap" => Format.R8G8_UNorm, "Bgra8" or "Bgra8Unorm" or "B8G8R8A8_UNorm" or "B8G8R8A8_UNORM" => Format.B8G8R8A8_UNorm, "Rgba8Unorm" or "R8G8B8A8_UNorm" or "R8G8B8A8_UNORM" => Format.R8G8B8A8_UNorm, "Rgba16Float" or "R16G16B16A16_Float" or "R16G16B16A16_FLOAT" => Format.R16G16B16A16_Float, + "Yuy2" or "YUY2" => Format.YUY2, "Nv12" or "NV12" => Format.NV12, - "LeapStereoIr" or "LeapPackedMap" => Format.B8G8R8A8_UNorm, _ => Format.Unknown, }; return format != Format.Unknown; diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 8cfd263..69d7059 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -198,6 +198,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly D3D12RenderTarget[] bloomRenderTargets = new D3D12RenderTarget[BloomLevelCount]; private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount]; private readonly Dictionary sharedTextureLeases = new(StringComparer.Ordinal); + private readonly object sharedTextureUploadLock = new(); private readonly D3D12StructuredBuffer sdfLightBuffer; private readonly D3D12StructuredBuffer sdfObjectBuffer; private readonly D3D12StructuredBuffer gpuSensorCameraBuffer; @@ -730,6 +731,24 @@ public sealed class D3D12Renderer : IAquariumRenderer return true; } + public bool UploadTexture2D(AquariumTexture2DUpload upload) + { + if (!upload.IsValid || + !sharedTextureLeases.TryGetValue(upload.ResourceKey, out var slot) || + slot.Width != upload.Width || + slot.Height != upload.Height || + !D3D12FieldTextureFormat.TryFormat(upload.Format, out var format) || + slot.Format != format) + { + return false; + } + + lock (sharedTextureUploadLock) + { + return UploadTexture2DLocked(upload, slot); + } + } + public void Render(AquariumFrame frame, int width, int height) { var frameCpuStart = Stopwatch.GetTimestamp(); @@ -1176,6 +1195,110 @@ public sealed class D3D12Renderer : IAquariumRenderer true); } + private bool UploadTexture2DLocked(AquariumTexture2DUpload upload, SharedTextureLeaseSlot slot) + { + ID3D12CommandAllocator? uploadAllocator = null; + ID3D12GraphicsCommandList? uploadList = null; + ID3D12Resource? uploadResource = null; + try + { + if (string.Equals(upload.Format.Trim(), "NV12", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var rowBytes = RowBytes(upload.Format, upload.Width); + if (rowBytes <= 0 || upload.SourceStrideBytes < rowBytes) + { + return false; + } + + var rowPitch = AlignTo(rowBytes, D3D12.TextureDataPitchAlignment); + var uploadBytes = checked(rowPitch * upload.Height); + uploadResource = device.CreateCommittedResource( + HeapType.Upload, + ResourceDescription.Buffer((ulong)uploadBytes), + ResourceStates.GenericRead, + null); + uploadResource.Name = $"Aquarium D3D12 Texture2D Lease Upload {upload.ResourceKey}"; + + unsafe + { + var mapped = uploadResource.Map(0); + try + { + var sourceBytes = upload.Data.Span; + for (var row = 0; row < upload.Height; row++) + { + sourceBytes.Slice(row * upload.SourceStrideBytes, rowBytes) + .CopyTo(new Span(mapped + (row * rowPitch), rowBytes)); + } + } + finally + { + uploadResource.Unmap(0, null); + } + } + + uploadAllocator = device.CreateCommandAllocator(CommandListType.Direct); + uploadList = device.CreateCommandList(0, CommandListType.Direct, uploadAllocator, null); + var source = new TextureCopyLocation( + uploadResource, + new PlacedSubresourceFootPrint + { + Offset = 0, + Footprint = new SubresourceFootPrint(slot.Format, (uint)upload.Width, (uint)upload.Height, 1, (uint)rowPitch), + }); + var destination = new TextureCopyLocation(slot.Resource, 0); + uploadList.ResourceBarrier(ResourceBarrier.BarrierTransition( + slot.Resource, + ResourceStates.PixelShaderResource, + ResourceStates.CopyDest)); + uploadList.CopyTextureRegion(destination, 0, 0, 0, source, null); + uploadList.ResourceBarrier(ResourceBarrier.BarrierTransition( + slot.Resource, + ResourceStates.CopyDest, + ResourceStates.PixelShaderResource)); + uploadList.Close(); + commandQueue.ExecuteCommandList(uploadList); + var signalValue = ++fenceValue; + commandQueue.Signal(fence, signalValue).CheckError(); + if (fence.CompletedValue < signalValue) + { + fence.SetEventOnCompletion(signalValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()).CheckError(); + fenceEvent.WaitOne(); + } + + slot.CommittedProducerFenceValue = 0; + slot.WaitedProducerFenceValue = 0; + return true; + } + catch (SharpGenException) + { + return false; + } + catch (InvalidOperationException) + { + return false; + } + finally + { + uploadList?.Dispose(); + uploadAllocator?.Dispose(); + uploadResource?.Dispose(); + } + } + + private static int RowBytes(string format, int width) + { + var stride = AquariumFieldResourceDeclaration.FormatStrideBytes(format); + return format.Trim().ToUpperInvariant() switch + { + "NV12" => width, + _ => checked(Math.Max(1, width) * Math.Max(1, stride)), + }; + } + private void WaitForCommittedFieldResourceLeases(AquariumFieldEvidenceFrame fieldEvidenceFrame) { if (!fieldEvidenceFrame.HasInput || sharedTextureLeases.Count == 0) diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 6bb855e..9a6ee8d 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -257,3 +257,4 @@ {"lesson":"TubeField metadata now carries stable claim-derived field identity instead of one flat 5100 family constant for every generated tube. D3D12Renderer hashes the planned claim key into the TubeField family range, passes it through compute constants and generated vertex tubeData, and D3D12TubeField writes it to metadata.x while keeping travel in colorTravel.a and coverage/confidence in control/reservoir lanes. Fensalir build/tests and headless Mimir render passed; renderer reported 4 lowerings, 6016 requested/dispatched segments, 0 truncated, 0 invalid columns, and 1 resource upload.","timestamp":"2026-05-27T12:31:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml"],"source":"spectrum TubeField temporal metadata tightening","topic":"tubefield-stable-field-id"} {"lesson":"Shared Texture2D field resources now resolve through the D3D12 field resource registry, not only local PNG assets. D3D12FieldTexture2D can open native shared handles as shader-readable Texture2D resources, and the texture format parser accepts Mimir video descriptor names including Bgra8, Gray8/R8, Rg8, Nv12, and LeapStereoIr. This lets camera FieldEvidence resources become real GPU resources before any selected camera/feature lowering exists. Fensalir build and Aquarium.Engine.Tests passed.","timestamp":"2026-05-27T12:55:00+01:00","files":["src/Aquarium.Engine/Render/D3D12FieldTexture2D.cs","src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs","state/map.yaml"],"source":"Mimir camera observation bridge follow-up","topic":"shared-texture2d-field-resource-resolver"} {"lesson":"Fensalir now exposes engine-owned Texture2D leases through AquariumRuntimeServices. Client runtimes that implement IAquariumRuntimeServicesReceiver receive a field resource broker, can request keyed D3D12 Texture2D leases with shared texture and producer-fence handles, and can commit producer fence values. D3D12Renderer waits on committed producer fences before FieldEvidence resource resolution and shader sampling. This makes Fensalir-owned camera image buffers the preferred hot path while imported shared handles remain an edge case. Fensalir build and Aquarium.Engine.Tests passed; Mimir's fensalir-texture-lease smoke passed.","timestamp":"2026-05-27T13:45:00+01:00","files":["src/Aquarium.Engine.Contracts/AquariumRuntimeServices.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Render/IAquariumRenderer.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/map.yaml"],"source":"Mimir/Fensalir camera buffer ownership correction","topic":"fensalir-owned-texture2d-leases"} +{"lesson":"Fensalir's field resource broker now has an explicit Texture2D upload lane for raw single-plane CPU-origin camera frames. D3D12Renderer copies row-aligned upload data into the leased texture on the direct queue, supports corrected Mimir raw formats including LeapStereoIr as R8G8 and YUY2, rejects CPU NV12 until a real planar copy path exists, and leaves copy accounting to the client producer. This is the fallback for KS/WinUSB-style raw frame paths; GPU/direct producers should write shared texture leases directly. Fensalir build and Aquarium.Engine.Tests passed; Mimir's fensalir-texture-lease smoke passed with copies=1 for the CPU-origin fake driver.","timestamp":"2026-05-27T14:35:00+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldResourceBroker.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","src/Aquarium.Engine/Render/D3D12FieldTextureFormat.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs","state/map.yaml"],"source":"device-direct camera ingestion follow-up","topic":"texture2d-raw-frame-upload-fallback"} diff --git a/state/map.yaml b/state/map.yaml index b9b7a47..f541503 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -98,8 +98,12 @@ next_actions: `AquariumRuntimeServices`: client runtimes can request keyed D3D12 Texture2D leases, receive shared texture and producer-fence handles, then commit producer fence values so the renderer waits before shader sampling. - This makes imported handles an edge case, not the primary live camera - authority. Missing or unresolved TubeField ramps bind a Fensalir-owned linear fallback ramp. + Raw CPU-origin single-plane frames can use the explicit broker upload lane, + which copies rows into the leased texture on the D3D12 queue and leaves copy + accounting to the client producer. Multi-plane NV12 CPU upload is rejected + until a real planar copy path exists; GPU producers can still write NV12 + leases directly. This makes imported handles an edge case, not the primary + live camera authority. Missing or unresolved TubeField ramps bind a Fensalir-owned linear fallback ramp. Camera texture claims can therefore resolve resources before a selected visual-fusion lowering exists. TubeField compute now emits one GPU-resident D3D12 DrawIndexed indirect argument packet per diff --git a/tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs b/tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs index 801534f..10cea19 100644 --- a/tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs +++ b/tests/Aquarium.Engine.Tests/D3D12FieldTextureFormatTests.cs @@ -10,7 +10,8 @@ public sealed class D3D12FieldTextureFormatTests [InlineData("Gray8", Format.R8_UNorm)] [InlineData("R8", Format.R8_UNorm)] [InlineData("Rg8", Format.R8G8_UNorm)] - [InlineData("LeapStereoIr", Format.B8G8R8A8_UNorm)] + [InlineData("LeapStereoIr", Format.R8G8_UNorm)] + [InlineData("Yuy2", Format.YUY2)] [InlineData("Nv12", Format.NV12)] public void FormatParserAcceptsMimirVideoResourceFormats(string sourceFormat, Format expected) {