diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs b/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs index 8a212c6..c8a7c92 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs @@ -262,6 +262,7 @@ public readonly record struct AquariumFieldTubeSplineLowering( float Alpha, float Feather, string RampTexturePath, + string RampResourceKey, float EmissionScale, int CatmullRomSubdivisions) { @@ -314,7 +315,8 @@ public readonly record struct AquariumFieldResourceDeclaration( long ValidUntilNs, ulong Version, IntPtr NativeHandle, - string NativeHandleKind) + string NativeHandleKind, + string SourceUri = "") { public bool HasIdentity => !string.IsNullOrWhiteSpace(ResourceKey); @@ -322,7 +324,9 @@ public readonly record struct AquariumFieldResourceDeclaration( Kind != AquariumFieldResourceKind.Unknown && Residency != AquariumFieldResourceResidency.Unknown && Access != AquariumFieldShaderAccess.Unknown && - (Width > 0 || DepthOrCount > 0 || StrideBytes > 0); + (Width > 0 || DepthOrCount > 0 || StrideBytes > 0 || HasSourceAsset); + + public bool HasSourceAsset => !string.IsNullOrWhiteSpace(SourceUri); public bool IsGpuVisible => Residency is AquariumFieldResourceResidency.GpuResident or AquariumFieldResourceResidency.SharedGpu; @@ -331,6 +335,32 @@ public readonly record struct AquariumFieldResourceDeclaration( timestampNs <= 0 || ((ValidFromNs <= 0 || timestampNs >= ValidFromNs) && (ValidUntilNs <= 0 || timestampNs <= ValidUntilNs)); + + public static AquariumFieldResourceDeclaration LocalTexture2D( + string resourceKey, + string sourceUri, + string format = "Rgba8Unorm", + ulong version = 0, + int width = 0, + int height = 0, + long validFromNs = 0, + long validUntilNs = 0) => + new( + ResourceKey: resourceKey, + Kind: AquariumFieldResourceKind.Texture2D, + Residency: AquariumFieldResourceResidency.GpuResident, + Access: AquariumFieldShaderAccess.ShaderResource, + Format: format, + Width: width, + Height: height, + DepthOrCount: 1, + StrideBytes: 4, + ValidFromNs: validFromNs, + ValidUntilNs: validUntilNs, + Version: version, + NativeHandle: IntPtr.Zero, + NativeHandleKind: "local-asset", + SourceUri: sourceUri); } public sealed class AquariumFieldEvidenceFrame @@ -574,6 +604,12 @@ public static class AquariumFieldEvidenceValidator { issues.Add(Error(lowering.LoweringKey, $"Tube spline lowering references unknown resource '{lowering.ResourceKey}'.")); } + + if (!string.IsNullOrWhiteSpace(lowering.RampResourceKey) && + !resourceKeys.Contains(lowering.RampResourceKey)) + { + issues.Add(Error(lowering.LoweringKey, $"Tube spline lowering references unknown ramp resource '{lowering.RampResourceKey}'.")); + } } return issues.Count == 0 diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs b/src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs index 0a24943..2e699b1 100644 --- a/src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs +++ b/src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs @@ -36,6 +36,9 @@ public static class AquariumFieldScriptCompiler case "resource": BindResource(args, resourceBindings, resourceAliases, resources, lineIndex); break; + case "texture2d": + BindTexture2D(args, resourceAliases, resources, lineIndex); + break; case "domain": var domain = ParseFieldDomain(args, lineIndex); if (domainKeys.Add(domain.DomainKey)) @@ -73,6 +76,31 @@ public static class AquariumFieldScriptCompiler return frame; } + private static void BindTexture2D( + IReadOnlyDictionary args, + IDictionary resourceAliases, + ICollection resources, + int lineIndex) + { + var id = Required(args, "id", lineIndex); + var key = StringValue(args, "key", $"aquarium:resource:texture2d:{id}"); + var path = Required(args, "path", lineIndex); + var resource = AquariumFieldResourceDeclaration.LocalTexture2D( + key, + path, + StringValue(args, "format", "Rgba8Unorm"), + UInt64(args, "version", 0, lineIndex), + Int(args, "width", 0, lineIndex), + Int(args, "height", 0, lineIndex)); + + resourceAliases[id] = resource; + resourceAliases[key] = resource; + if (resources.All(existing => !string.Equals(existing.ResourceKey, resource.ResourceKey, StringComparison.Ordinal))) + { + resources.Add(resource); + } + } + public static AquariumBufferFieldFrame Compile( string source, IReadOnlyDictionary textureBindings, @@ -262,6 +290,13 @@ public static class AquariumFieldScriptCompiler var claimKey = $"dsl:tube:{id}"; var resourceId = Required(args, "resource", lineIndex); var resource = resourceAliases[resourceId]; + var ramp = StringValue(args, "ramp", ""); + var rampResourceKey = resourceAliases.TryGetValue(ramp, out var rampResource) + ? rampResource.ResourceKey + : ""; + var rampTexturePath = rampResourceKey.Length > 0 + ? rampResource.SourceUri + : ramp; var lowering = new AquariumFieldTubeSplineLowering( LoweringKey: $"dsl:tube-spline:{id}", ClaimKey: claimKey, @@ -285,7 +320,8 @@ public static class AquariumFieldScriptCompiler RadiusScale: Float(args, "radiusScale", 0.030f, lineIndex), Alpha: Float(args, "alpha", 0.92f, lineIndex), Feather: Float(args, "feather", 0.20f, lineIndex), - RampTexturePath: StringValue(args, "ramp", ""), + RampTexturePath: rampTexturePath, + RampResourceKey: rampResourceKey, EmissionScale: Float(args, "emissionScale", 10.0f, lineIndex), CatmullRomSubdivisions: Int(args, "subdivisions", 4, lineIndex)).Normalized(); lowerings.Add(lowering); @@ -422,6 +458,9 @@ public static class AquariumFieldScriptCompiler private static uint UInt(IReadOnlyDictionary args, string key, uint fallback, int lineIndex) => args.TryGetValue(key, out var value) ? uint.Parse(value, CultureInfo.InvariantCulture) : fallback; + private static ulong UInt64(IReadOnlyDictionary args, string key, ulong fallback, int lineIndex) => + args.TryGetValue(key, out var value) ? ulong.Parse(value, CultureInfo.InvariantCulture) : fallback; + private static float Float(IReadOnlyDictionary args, string key, float fallback, int lineIndex) => args.TryGetValue(key, out var value) ? float.Parse(value, CultureInfo.InvariantCulture) : fallback; diff --git a/src/Aquarium.Engine/Aquarium.Engine.csproj b/src/Aquarium.Engine/Aquarium.Engine.csproj index 305d312..a52a185 100644 --- a/src/Aquarium.Engine/Aquarium.Engine.csproj +++ b/src/Aquarium.Engine/Aquarium.Engine.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs b/src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs index 558da05..9f3050b 100644 --- a/src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs +++ b/src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs @@ -7,10 +7,11 @@ internal readonly record struct D3D12FieldResourceStats( int Declared, int Resolved, int StructuredBuffers, + int Texture2D, int Unsupported, int StaleRemoved) { - public static D3D12FieldResourceStats Empty { get; } = new(0, 0, 0, 0, 0); + public static D3D12FieldResourceStats Empty { get; } = new(0, 0, 0, 0, 0, 0); } internal sealed class D3D12FieldResourceRegistry : IDisposable @@ -18,6 +19,7 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable private const string RegistryPrefix = "field-resource:"; private readonly Dictionary structuredBuffers = new(StringComparer.Ordinal); + private readonly Dictionary textures = new(StringComparer.Ordinal); private readonly HashSet liveKeys = new(StringComparer.Ordinal); public D3D12FieldResourceStats Resolve( @@ -33,6 +35,7 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable var resolved = 0; var structuredBufferCount = 0; + var textureCount = 0; var unsupported = 0; foreach (var declaration in declarations) { @@ -63,14 +66,22 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable continue; } + if (declaration.Kind == AquariumFieldResourceKind.Texture2D) + { + textureCount++; + continue; + } + unsupported++; } var staleRemoved = RemoveStaleStructuredBuffers(resourceRegistry, liveKeys); + staleRemoved += RemoveStaleTextures(liveKeys); return new D3D12FieldResourceStats( Declared: declarations.Count, Resolved: resolved, StructuredBuffers: structuredBufferCount, + Texture2D: textureCount, Unsupported: unsupported, StaleRemoved: staleRemoved); } @@ -82,7 +93,13 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable slot.Buffer.Dispose(); } + foreach (var slot in textures.Values) + { + slot.Texture.Dispose(); + } + structuredBuffers.Clear(); + textures.Clear(); liveKeys.Clear(); } @@ -98,6 +115,80 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable return false; } + public bool TryGetTexture2D(string resourceKey, out D3D12FieldTexture2D texture) + { + if (textures.TryGetValue(resourceKey, out var slot)) + { + texture = slot.Texture; + return true; + } + + texture = null!; + return false; + } + + public bool TryResolveTexture2D( + ID3D12Device device, + ID3D12GraphicsCommandList commandList, + AquariumFieldResourceDeclaration declaration, + out D3D12FieldTexture2D texture) + { + texture = null!; + if (declaration.Kind != AquariumFieldResourceKind.Texture2D || + declaration.Residency != AquariumFieldResourceResidency.GpuResident || + declaration.Access != AquariumFieldShaderAccess.ShaderResource || + !declaration.HasSourceAsset) + { + return false; + } + + if (textures.TryGetValue(declaration.ResourceKey, out var existing) && + existing.Version == declaration.Version && + string.Equals(existing.SourceUri, declaration.SourceUri, StringComparison.Ordinal)) + { + texture = existing.Texture; + return true; + } + + if (existing is not null) + { + existing.Texture.Dispose(); + textures.Remove(declaration.ResourceKey); + } + + try + { + texture = D3D12FieldTexture2D.LoadLocalAsset(device, commandList, declaration); + textures[declaration.ResourceKey] = new Texture2DSlot(texture, declaration.SourceUri, declaration.Version); + return true; + } + catch (IOException) + { + texture = null!; + return false; + } + catch (InvalidOperationException) + { + texture = null!; + return false; + } + catch (UnauthorizedAccessException) + { + texture = null!; + return false; + } + catch (ArgumentException) + { + texture = null!; + return false; + } + catch (SharpGenException) + { + texture = null!; + return false; + } + } + private bool ResolveStructuredBuffer( ID3D12Device device, D3D12ResourceRegistry resourceRegistry, @@ -167,6 +258,24 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable return removed; } + private int RemoveStaleTextures(HashSet currentKeys) + { + var removed = 0; + foreach (var key in textures.Keys.ToArray()) + { + if (currentKeys.Contains(key)) + { + continue; + } + + textures[key].Texture.Dispose(); + textures.Remove(key); + removed++; + } + + return removed; + } + private static string RegistryKey(string resourceKey) => RegistryPrefix + resourceKey; private static D3D12StructuredBuffer? OpenSharedStructuredBuffer( @@ -206,4 +315,9 @@ internal sealed class D3D12FieldResourceRegistry : IDisposable int StrideBytes, bool AllowUnorderedAccess, ulong Version); + + private sealed record Texture2DSlot( + D3D12FieldTexture2D Texture, + string SourceUri, + ulong Version); } diff --git a/src/Aquarium.Engine/Render/D3D12FieldTexture2D.cs b/src/Aquarium.Engine/Render/D3D12FieldTexture2D.cs new file mode 100644 index 0000000..7069c22 --- /dev/null +++ b/src/Aquarium.Engine/Render/D3D12FieldTexture2D.cs @@ -0,0 +1,222 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using Vortice.Direct3D12; +using Vortice.DXGI; + +namespace Aquarium.Engine.Render; + +internal sealed unsafe class D3D12FieldTexture2D : IDisposable +{ + public ID3D12Resource Resource { get; } + + public int Width { get; } + + public int Height { get; } + + public Format Format { get; } + + public ResourceStates State { get; private set; } = ResourceStates.CopyDest; + + private readonly ID3D12Resource? uploadResource; + + private D3D12FieldTexture2D( + ID3D12Resource resource, + ID3D12Resource? uploadResource, + int width, + int height, + Format format, + string name) + { + Resource = resource; + this.uploadResource = uploadResource; + Width = width; + Height = height; + Format = format; + Resource.Name = name; + } + + public static D3D12FieldTexture2D CreateFallbackRamp( + ID3D12Device device, + ID3D12GraphicsCommandList commandList, + string name) + { + const int width = 256; + var rgba = new byte[width * 4]; + for (var x = 0; x < width; x++) + { + var value = (byte)x; + var offset = x * 4; + rgba[offset + 0] = value; + rgba[offset + 1] = value; + rgba[offset + 2] = value; + rgba[offset + 3] = 255; + } + + return CreateRgba8(device, commandList, rgba, width, 1, name); + } + + public static D3D12FieldTexture2D LoadLocalAsset( + ID3D12Device device, + ID3D12GraphicsCommandList commandList, + AquariumFieldResourceDeclaration declaration) + { + if (string.IsNullOrWhiteSpace(declaration.SourceUri)) + { + throw new InvalidOperationException($"Texture2D field resource `{declaration.ResourceKey}` is missing SourceUri."); + } + + var path = declaration.SourceUri; + if (!File.Exists(path)) + { + throw new FileNotFoundException($"Texture2D field resource `{declaration.ResourceKey}` local asset does not exist.", path); + } + + var rgba = LoadRgba8(path, out var width, out var height); + return CreateRgba8( + device, + commandList, + rgba, + width, + height, + $"Aquarium D3D12 Field Texture2D {declaration.ResourceKey}"); + } + + public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot descriptor) + { + device.CreateShaderResourceView( + Resource, + new ShaderResourceViewDescription + { + Format = Format, + ViewDimension = ShaderResourceViewDimension.Texture2D, + Shader4ComponentMapping = ShaderComponentMapping.Default, + Texture2D = new Texture2DShaderResourceView { MipLevels = 1 }, + }, + descriptor.Cpu); + } + + public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) + { + if (State == nextState) + { + return; + } + + commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState)); + State = nextState; + } + + public void Dispose() + { + uploadResource?.Dispose(); + Resource.Dispose(); + } + + private static D3D12FieldTexture2D CreateRgba8( + ID3D12Device device, + ID3D12GraphicsCommandList commandList, + byte[] rgba, + int width, + int height, + string name) + { + var texture = device.CreateCommittedResource( + HeapType.Default, + ResourceDescription.Texture2D( + Format.R8G8B8A8_UNorm, + (uint)width, + (uint)height, + 1, + 1, + 1, + 0, + ResourceFlags.None), + ResourceStates.CopyDest, + null); + + var rowBytes = checked(width * 4); + var rowPitch = (int)Align(rowBytes, D3D12.TextureDataPitchAlignment); + var uploadBytes = checked(rowPitch * height); + var upload = device.CreateCommittedResource( + HeapType.Upload, + ResourceDescription.Buffer((ulong)uploadBytes), + ResourceStates.GenericRead, + null); + upload.Name = $"{name} Upload"; + + var mapped = upload.Map(0); + try + { + for (var row = 0; row < height; row++) + { + rgba.AsSpan(row * rowBytes, rowBytes).CopyTo(new Span(mapped + (row * rowPitch), rowBytes)); + } + } + finally + { + upload.Unmap(0, null); + } + + var source = new TextureCopyLocation( + upload, + new PlacedSubresourceFootPrint + { + Offset = 0, + Footprint = new SubresourceFootPrint(Format.R8G8B8A8_UNorm, (uint)width, (uint)height, 1, (uint)rowPitch), + }); + var destination = new TextureCopyLocation(texture, 0); + commandList.CopyTextureRegion(destination, 0, 0, 0, source, null); + var fieldTexture = new D3D12FieldTexture2D(texture, upload, width, height, Format.R8G8B8A8_UNorm, name); + fieldTexture.Transition(commandList, ResourceStates.PixelShaderResource); + return fieldTexture; + } + + private static byte[] LoadRgba8(string path, out int width, out int height) + { +#pragma warning disable CA1416 + using var source = new Bitmap(path); + width = source.Width; + height = source.Height; + using var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.DrawImage(source, 0, 0, width, height); + } + + var data = bitmap.LockBits( + new Rectangle(0, 0, width, height), + ImageLockMode.ReadOnly, + PixelFormat.Format32bppArgb); + try + { + var rgba = new byte[checked(width * height * 4)]; + for (var y = 0; y < height; y++) + { + var sourceRow = (byte*)data.Scan0 + y * data.Stride; + var targetRow = y * width * 4; + for (var x = 0; x < width; x++) + { + var sourceOffset = x * 4; + var targetOffset = targetRow + sourceOffset; + rgba[targetOffset + 0] = sourceRow[sourceOffset + 2]; + rgba[targetOffset + 1] = sourceRow[sourceOffset + 1]; + rgba[targetOffset + 2] = sourceRow[sourceOffset + 0]; + rgba[targetOffset + 3] = sourceRow[sourceOffset + 3]; + } + } + + return rgba; + } + finally + { + bitmap.UnlockBits(data); + } +#pragma warning restore CA1416 + } + + private static long Align(long value, long alignment) + { + return (value + alignment - 1) & ~(alignment - 1); + } +} diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs index 2523d10..027f6e3 100644 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ b/src/Aquarium.Engine/Render/D3D12Renderer.cs @@ -92,6 +92,10 @@ public sealed class D3D12Renderer : IAquariumRenderer private const int RootTubeFieldVertices = 2; private const int RootTubeFieldIndices = 3; private const int RootTubeFieldStats = 4; + private const int RootTubeFieldRenderFrameConstants = 0; + private const int RootTubeFieldRenderConstants = 1; + private const int RootTubeFieldRenderSource = 2; + private const int RootTubeFieldRenderRamp = 3; private static readonly DebugUi.DebugUiOption[] RenderDebugOptions = [ new(0, "Final"), @@ -136,6 +140,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly ID3D12RootSignature tubeFieldRootSignature; private readonly ID3D12RootSignature tubeFieldRenderRootSignature; private readonly D3D12BlueNoiseTexture blueNoiseTexture; + private D3D12FieldTexture2D? tubeFieldFallbackRampTexture; private ID3D12PipelineState? heightFieldBasePipelineState; private ID3D12PipelineState? heightFieldBrushPipelineState; private ID3D12PipelineState? scenePipelineState; @@ -969,6 +974,7 @@ public sealed class D3D12Renderer : IAquariumRenderer tubeFieldRootSignature.Dispose(); tubeFieldRenderRootSignature.Dispose(); blueNoiseTexture.Dispose(); + tubeFieldFallbackRampTexture?.Dispose(); studioIrradianceTexture.Dispose(); studioPmremTexture.Dispose(); fieldResourceRegistry.Dispose(); @@ -1836,19 +1842,61 @@ public sealed class D3D12Renderer : IAquariumRenderer Format.R32_UInt); activeCommandList.SetPipelineState(tubeFieldRenderPipelineState); activeCommandList.SetGraphicsRootSignature(tubeFieldRenderRootSignature); - activeCommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu); + activeCommandList.SetGraphicsRootDescriptorTable(RootTubeFieldRenderFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); activeCommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); activeCommandList.IASetVertexBuffers(0, [vertexView]); activeCommandList.IASetIndexBuffer(indexView); foreach (var batch in tubeFieldDrawBatches) { batch.Source.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - activeCommandList.SetGraphicsRootConstantBufferView(1, batch.ConstantsGpuVirtualAddress); - activeCommandList.SetGraphicsRootShaderResourceView(2, batch.Source.Resource.GPUVirtualAddress); + var ramp = ResolveTubeFieldRamp(activeCommandList, batch.RampResourceKey); + ramp.Transition(activeCommandList, ResourceStates.PixelShaderResource); + var rampDescriptor = frameResources.TransientShaderDescriptors.Allocate(); + ramp.CreateShaderResourceView(device, rampDescriptor); + activeCommandList.SetGraphicsRootConstantBufferView(RootTubeFieldRenderConstants, batch.ConstantsGpuVirtualAddress); + activeCommandList.SetGraphicsRootShaderResourceView(RootTubeFieldRenderSource, batch.Source.Resource.GPUVirtualAddress); + activeCommandList.SetGraphicsRootDescriptorTable(RootTubeFieldRenderRamp, rampDescriptor.Gpu); activeCommandList.DrawIndexedInstanced((uint)batch.IndexCount, 1, (uint)batch.StartIndex, 0, 0); } } + private D3D12FieldTexture2D ResolveTubeFieldRamp(ID3D12GraphicsCommandList activeCommandList, string rampResourceKey) + { + if (!string.IsNullOrWhiteSpace(rampResourceKey) && + fieldResourceRegistry.TryGetTexture2D(rampResourceKey, out var resolvedRamp)) + { + return resolvedRamp; + } + + if (!string.IsNullOrWhiteSpace(rampResourceKey) && + TryFindActiveFieldResource(rampResourceKey, out var declaration) && + fieldResourceRegistry.TryResolveTexture2D(device, activeCommandList, declaration, out var loadedRamp)) + { + return loadedRamp; + } + + tubeFieldFallbackRampTexture ??= D3D12FieldTexture2D.CreateFallbackRamp( + device, + activeCommandList, + "Aquarium D3D12 TubeField Fallback Ramp"); + return tubeFieldFallbackRampTexture; + } + + private bool TryFindActiveFieldResource(string resourceKey, out AquariumFieldResourceDeclaration declaration) + { + foreach (var resource in activeFieldEvidenceFrame.Resources) + { + if (string.Equals(resource.ResourceKey, resourceKey, StringComparison.Ordinal)) + { + declaration = resource; + return true; + } + } + + declaration = default; + return false; + } + private static void AppendSplineSurfaceEnvelopeGeometry(List output, AquariumSpline3D spline) { var style = spline.Style.Normalized(); @@ -2314,6 +2362,7 @@ public sealed class D3D12Renderer : IAquariumRenderer tubeFieldDrawBatches.Add(new D3D12TubeFieldDrawBatch( sourceBuffer, constantsUpload.GpuVirtualAddress, + normalized.RampResourceKey, startIndex, dispatchSegments * 6)); } @@ -2947,6 +2996,7 @@ public sealed class D3D12Renderer : IAquariumRenderer $"resources {activeFieldEvidenceFrame.Resources.Count:N0}; " + $"resolved resources {activeFieldResourceStats.Resolved:N0}; " + $"structured buffers {activeFieldResourceStats.StructuredBuffers:N0}; " + + $"texture2d {activeFieldResourceStats.Texture2D:N0}; " + $"unsupported resources {activeFieldResourceStats.Unsupported:N0}; " + $"claims {activeFieldEvidenceFrame.Claims.Count:N0}; " + $"candidates {activeFieldEvidenceFrame.Candidates.Count:N0}; " + @@ -3540,16 +3590,40 @@ public sealed class D3D12Renderer : IAquariumRenderer 0, 0, D3D12.DescriptorRangeOffsetAppend); + var rampTexture = new DescriptorRange( + DescriptorRangeType.ShaderResourceView, + 1, + 43, + 0, + D3D12.DescriptorRangeOffsetAppend); var rootParameters = new[] { new RootParameter(new RootDescriptorTable([frameConstants]), ShaderVisibility.All), new RootParameter(RootParameterType.ConstantBufferView, new RootDescriptor(3, 0), ShaderVisibility.All), new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(42, 0), ShaderVisibility.Pixel), + new RootParameter(new RootDescriptorTable([rampTexture]), ShaderVisibility.Pixel), + }; + var staticSamplers = new[] + { + new StaticSamplerDescription( + 0, + Filter.MinMagMipLinear, + TextureAddressMode.Clamp, + TextureAddressMode.Clamp, + TextureAddressMode.Clamp, + 0.0f, + 1, + ComparisonFunction.Never, + StaticBorderColor.TransparentBlack, + 0.0f, + float.MaxValue, + ShaderVisibility.Pixel, + 0), }; var description = new RootSignatureDescription( RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters, - []); + staticSamplers); return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); } @@ -3996,6 +4070,7 @@ public sealed class D3D12Renderer : IAquariumRenderer private readonly record struct D3D12TubeFieldDrawBatch( D3D12StructuredBuffer Source, ulong ConstantsGpuVirtualAddress, + string RampResourceKey, int StartIndex, int IndexCount); diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl index 4f8f1f5..e32f9a1 100644 --- a/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl +++ b/src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl @@ -57,6 +57,8 @@ cbuffer TubeFieldConstants : register(b3) }; ByteAddressBuffer TubeFieldSamples : register(t42); +Texture2D TubeFieldRamp : register(t43); +SamplerState TubeFieldRampSampler : register(s0); RWStructuredBuffer TubeFieldVertices : register(u10); RWStructuredBuffer TubeFieldIndices : register(u11); RWStructuredBuffer TubeFieldStats : register(u12); @@ -146,7 +148,7 @@ TubeFieldVertex MakeTubeVertex(float3 position, float3 previous, float3 start, f { TubeFieldVertex vertex; float radius = max(tubeMaterial.x + value * tubeMaterial.y, 0.0001); - float3 rampColor = lerp(float3(0.0, 0.0, 0.0), float3(1.0, 0.62, 0.18), value); + float3 rampColor = value.xxx; vertex.position = position; vertex.segmentStart = start; vertex.segmentEnd = end; @@ -440,7 +442,7 @@ SceneOut D3D12TubeFieldPS(TubeFieldVertexOut input) float coverage = 1.0 - smoothstep(0.0, aa, sdf); float sampleX = lerp(input.tubeData.y, input.tubeData.z, closestT); float value = SampleCurve((uint)round(input.tubeData.x), sampleX); - float3 rampColor = lerp(float3(0.0, 0.0, 0.0), float3(1.0, 0.62, 0.18), value); + float3 rampColor = TubeFieldRamp.SampleLevel(TubeFieldRampSampler, float2(saturate(value), 0.5), 0.0).rgb; float3 ray = rayDirectionForPixel(samplePx, jitterPixels, cameraPosition, cameraTarget); float3 forward; float3 right; diff --git a/state/evidence.jsonl b/state/evidence.jsonl index e2632ea..4e4e831 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -237,3 +237,4 @@ {"lesson":"Rendering-relevant field buffers must be GPU-resident early and stay GPU-resident. The TubeField contract now has an explicit AquariumFieldTubeSplineLowering/DSL command for interpreting a 2D rolling Float32 buffer as Catmull-Rom XY tubes with modulo column addressing, amplitude power/normalization, radius scaling, ramp texture path, and emission scale. D3D12FieldResourceRegistry no longer creates duplicate empty buffers for SharedGpu declarations: shared structured/curve resources must import by GPU handle or remain unsupported; allocation is only for Fensalir-owned GPU-resident producer slots. Visible TubeField rendering remains blocked on shader-side expansion/binding over the GPU slot, not CPU spline tessellation. Fensalir.sln builds cleanly; Aquarium.Engine.Tests passed with 17 tests.","timestamp":"2026-05-26T18:50:34+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs","state/map.yaml"],"source":"user clarified GPU-resident no-copy rendering buffer invariant","topic":"gpu-resident-tubefield-dsl"} {"lesson":"D3D12 TubeField now has a first GPU-only rendering path: resolved resource-backed 2D rolling float buffers bind as read-only GPU memory, a compute shader expands endpoint-clamped Catmull-Rom tube envelopes into fixed-budget vertex/index UAVs, byte-address sample loads honor declared stride, the existing spline SDF pipeline draws opaque tube field geometry, and capacity logs report requested/dispatched/truncated segment counts. This proves shader-side expansion/binding without CPU tessellation; per-pixel source-row material sampling, ramp texture binding, and indirect draw remain the next cuts.","timestamp":"2026-05-26T20:11:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","state/map.yaml"],"source":"continued GPU-resident TubeField implementation","topic":"d3d12-tubefield-compute-expansion"} {"lesson":"TubeField rendering now has a dedicated D3D12 render pipeline rather than reusing generic spline material. Compute expansion records one draw batch per lowering, and the TubeField pixel shader binds the matching source buffer/constants and resamples the rolling buffer per pixel by column+spline coordinate with the cheap 5-tap path. The initial material is opaque field geometry with fallback black-to-warm ramp, squared normalized emission, and fake Fresnel center-bright/edge-dark shaping. Real ramp texture binding, indirect draw packets, and non-buffer resolvers remain open. Headless dev reload, Aquarium.Engine.Tests, Mimir build, and both Mimir Fensalir field smokes passed.","timestamp":"2026-05-26T20:22:00+01:00","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","state/map.yaml"],"source":"continued GPU-resident TubeField material implementation","topic":"d3d12-tubefield-pixel-material"} +{"lesson":"Texture2D local assets are now first-class field resources. AquariumFieldResourceDeclaration carries SourceUri and has a LocalTexture2D factory; the field DSL accepts `texture2d id=... key=... path=...` and TubeField `ramp=...` resolves aliases into RampResourceKey. D3D12FieldResourceRegistry lazily uploads local Rgba8 assets into GPU-resident textures, TubeField rendering binds the ramp SRV plus linear clamp sampler, and unresolved ramps use a Fensalir-owned 0-1 fallback texture. This replaces raw ramp paths as live authority while keeping them as compatibility metadata. Fensalir build/tests/headless reload and Mimir build/field smokes passed.","timestamp":"2026-05-26T20:40:00+01:00","files":["src/Aquarium.Engine.Contracts/Render/AquariumFieldEvidence.cs","src/Aquarium.Engine.Contracts/Render/AquariumFieldScriptCompiler.cs","src/Aquarium.Engine/Render/D3D12FieldTexture2D.cs","src/Aquarium.Engine/Render/D3D12FieldResourceRegistry.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12TubeField.hlsl","tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs","state/map.yaml"],"source":"user requested Texture2D local asset resource declaration and automatic DSL binding","topic":"field-texture2d-resource-binding"} diff --git a/state/map.yaml b/state/map.yaml index 5270e24..d09adcf 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -88,11 +88,14 @@ next_actions: envelopes, honors declared sample stride with byte-address loads, and records one draw batch per lowering so the TubeField pixel shader can bind the right source row/column and resample material per pixel with the cheap - 5-tap approximation. The first material is opaque field geometry with a - black-to-warm fallback ramp, squared normalized emission, fake Fresnel + 5-tap approximation. Texture2D local assets are now declared as first-class + field resources with source URI metadata, DSL aliases, lazy D3D12 upload, + SRV binding, and TubeField ramp lookup by resource key; missing/unresolved + ramps bind a Fensalir-owned linear fallback ramp. The first material is + opaque field geometry with squared normalized emission, fake Fresnel center-bright/edge-dark shaping, and requested/dispatched/truncated segment - reporting. Remaining cuts are real ramp texture binding, indirect draw - packets, and texture/mesh/surface-page/volume resolvers. + reporting. Remaining cuts are indirect draw packets plus mesh/surface-page/ + volume 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. diff --git a/tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs b/tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs index dfcda82..ae37c23 100644 --- a/tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs +++ b/tests/Aquarium.Engine.Tests/FieldEvidenceContractTests.cs @@ -463,6 +463,7 @@ tubeclaim id=spectrum-trail resource=spectrum domain=mimir:spectrum:asio-ch0 con Alpha: 1.0f, Feather: 0.2f, RampTexturePath: @"D:\WIP4\Projects\Aetheria\Assets\Resources\Ramps\blackbody.png", + RampResourceKey: "", EmissionScale: 10.0f, CatmullRomSubdivisions: 4) ], diff --git a/tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs b/tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs index 4536a0a..2d89d07 100644 --- a/tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs +++ b/tests/Aquarium.Engine.Tests/FieldScriptCompilerTests.cs @@ -84,5 +84,47 @@ public sealed class FieldScriptCompilerTests Assert.Equal(2.0f, lowering.AmplitudePower); Assert.Equal(10.0f, lowering.EmissionScale); Assert.Equal(@"D:\WIP4\Projects\Aetheria\Assets\Resources\Ramps\blackbody.png", lowering.RampTexturePath); + Assert.Equal("", lowering.RampResourceKey); + } + + [Fact] + public void CompileEvidenceBindsLocalTexture2DResourcesAsTubeRamps() + { + var resource = new AquariumFieldResourceDeclaration( + "mimir:resource:log-mel", + AquariumFieldResourceKind.StructuredBuffer, + AquariumFieldResourceResidency.SharedGpu, + AquariumFieldShaderAccess.ShaderResource, + "Float32", + Width: 64, + Height: 32, + DepthOrCount: 2048, + StrideBytes: 4, + ValidFromNs: 0, + ValidUntilNs: 10_000, + Version: 7, + NativeHandle: IntPtr.Zero, + NativeHandleKind: "fensalir-buffer"); + + var frame = AquariumFieldScriptCompiler.CompileEvidence( + """ + resource id=mel key=mimir:resource:log-mel + texture2d id=blackbody key=aquarium:resource:ramp:blackbody path=D:\WIP4\Projects\Aetheria\Assets\Resources\Ramps\blackbody.png format=Rgba8Unorm version=11 + tubespline id=mel-field resource=mel domain=mimir:log-mel width=64 height=32 stride=4 columns=8 ramp=blackbody + """, + new Dictionary(StringComparer.Ordinal) + { + [resource.ResourceKey] = resource, + }); + + Assert.Equal(2, frame.Resources.Count); + var ramp = frame.Resources.Single(resource => resource.Kind == AquariumFieldResourceKind.Texture2D); + Assert.Equal("aquarium:resource:ramp:blackbody", ramp.ResourceKey); + Assert.Equal("local-asset", ramp.NativeHandleKind); + Assert.Equal(@"D:\WIP4\Projects\Aetheria\Assets\Resources\Ramps\blackbody.png", ramp.SourceUri); + + var lowering = Assert.Single(frame.TubeSplineLowerings); + Assert.Equal(ramp.ResourceKey, lowering.RampResourceKey); + Assert.Equal(ramp.SourceUri, lowering.RampTexturePath); } }