Bind studio PMREM reflections

This commit is contained in:
Meta Vens 2026-05-11 06:26:08 +01:00
commit e0d04d6f23
7 changed files with 337 additions and 6 deletions

View file

@ -0,0 +1,244 @@
using Vortice.Direct3D12;
using Vortice.DXGI;
namespace Aquarium.Engine.Render;
internal sealed unsafe class D3D12CubeTexture : IDisposable
{
private const uint DdsMagic = 0x20534444;
private const uint DdsHeaderSize = 124;
private const uint DdsPixelFormatSize = 32;
private const uint DdsFourCcDx10 = 0x30315844;
private const int DxgiFormatR16G16B16A16Float = 10;
private const int D3D10ResourceDimensionTexture2D = 3;
private const int D3D11ResourceMiscTextureCube = 0x4;
private const int BytesPerPixel = 8;
private const int FaceCount = 6;
private const int DdsDx10PayloadOffset = 148;
private D3D12CubeTexture(ID3D12Resource resource, int size, int mipCount, string name)
{
Resource = resource;
Size = size;
MipCount = mipCount;
Resource.Name = name;
}
public ID3D12Resource Resource { get; }
public int Size { get; }
public int MipCount { get; }
public ResourceStates State { get; private set; } = ResourceStates.CopyDest;
public static D3D12CubeTexture LoadRgba16FloatDds(
ID3D12Device device,
ID3D12GraphicsCommandList commandList,
string path,
string name,
out ID3D12Resource uploadResource)
{
var bytes = File.ReadAllBytes(path);
var dds = ParseDds(bytes, path);
var texture = device.CreateCommittedResource(
HeapType.Default,
ResourceDescription.Texture2D(
Format.R16G16B16A16_Float,
(uint)dds.Width,
(uint)dds.Height,
FaceCount,
(ushort)dds.MipCount,
1,
0,
ResourceFlags.None),
ResourceStates.CopyDest,
null);
var cubeTexture = new D3D12CubeTexture(texture, dds.Width, dds.MipCount, name);
uploadResource = CreateUploadResource(device, dds, bytes);
CopySubresources(commandList, cubeTexture.Resource, uploadResource, dds);
cubeTexture.Transition(commandList, ResourceStates.PixelShaderResource);
return cubeTexture;
}
public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot descriptor)
{
device.CreateShaderResourceView(
Resource,
new ShaderResourceViewDescription
{
Format = Format.R16G16B16A16_Float,
ViewDimension = ShaderResourceViewDimension.TextureCube,
Shader4ComponentMapping = ShaderComponentMapping.Default,
TextureCube = new TextureCubeShaderResourceView
{
MostDetailedMip = 0,
MipLevels = (uint)MipCount,
ResourceMinLODClamp = 0.0f,
},
},
descriptor.Cpu);
}
public void Dispose()
{
Resource.Dispose();
}
private void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState)
{
if (State == nextState)
{
return;
}
commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState));
State = nextState;
}
private static DdsLayout ParseDds(ReadOnlySpan<byte> bytes, string path)
{
if (bytes.Length < DdsDx10PayloadOffset)
{
throw new InvalidDataException($"DDS file '{path}' is too small.");
}
if (ReadUInt32(bytes, 0) != DdsMagic || ReadUInt32(bytes, 4) != DdsHeaderSize)
{
throw new InvalidDataException($"DDS file '{path}' is not a supported DDS texture.");
}
var height = checked((int)ReadUInt32(bytes, 12));
var width = checked((int)ReadUInt32(bytes, 16));
var mipCount = checked((int)ReadUInt32(bytes, 28));
var pixelFormatSize = ReadUInt32(bytes, 76);
var fourCc = ReadUInt32(bytes, 84);
var dxgiFormat = checked((int)ReadUInt32(bytes, 128));
var resourceDimension = checked((int)ReadUInt32(bytes, 132));
var miscFlags = checked((int)ReadUInt32(bytes, 136));
var arraySize = checked((int)ReadUInt32(bytes, 140));
if (width <= 0 || height != width || mipCount <= 0)
{
throw new InvalidDataException($"DDS file '{path}' must be a square cubemap with mips.");
}
if (pixelFormatSize != DdsPixelFormatSize
|| fourCc != DdsFourCcDx10
|| dxgiFormat != DxgiFormatR16G16B16A16Float
|| resourceDimension != D3D10ResourceDimensionTexture2D
|| (miscFlags & D3D11ResourceMiscTextureCube) == 0
|| arraySize != 1)
{
throw new InvalidDataException($"DDS file '{path}' must be a DX10 R16G16B16A16_FLOAT cubemap.");
}
var subresources = new DdsSubresource[FaceCount * mipCount];
var sourceOffset = DdsDx10PayloadOffset;
for (var face = 0; face < FaceCount; face++)
{
for (var mip = 0; mip < mipCount; mip++)
{
var mipWidth = Math.Max(1, width >> mip);
var mipHeight = Math.Max(1, height >> mip);
var rowBytes = mipWidth * BytesPerPixel;
var dataBytes = rowBytes * mipHeight;
if (sourceOffset + dataBytes > bytes.Length)
{
throw new InvalidDataException($"DDS file '{path}' ended before face {face}, mip {mip}.");
}
subresources[(face * mipCount) + mip] = new DdsSubresource(sourceOffset, mipWidth, mipHeight, rowBytes);
sourceOffset += dataBytes;
}
}
if (sourceOffset != bytes.Length)
{
throw new InvalidDataException($"DDS file '{path}' has {bytes.Length - sourceOffset} unexpected trailing bytes.");
}
return new DdsLayout(width, height, mipCount, subresources);
}
private static ID3D12Resource CreateUploadResource(ID3D12Device device, DdsLayout dds, ReadOnlySpan<byte> source)
{
var uploadBytes = 0L;
foreach (var subresource in dds.Subresources)
{
uploadBytes = Align(uploadBytes, D3D12.TextureDataPlacementAlignment);
subresource.UploadOffset = uploadBytes;
subresource.UploadRowPitch = checked((int)Align(subresource.RowBytes, D3D12.TextureDataPitchAlignment));
uploadBytes += (long)subresource.UploadRowPitch * subresource.Height;
}
var upload = device.CreateCommittedResource(
HeapType.Upload,
ResourceDescription.Buffer((ulong)uploadBytes),
ResourceStates.GenericRead,
null);
upload.Name = "Aquarium D3D12 Studio PMREM Upload";
var mapped = (byte*)upload.Map<byte>(0);
try
{
foreach (var subresource in dds.Subresources)
{
for (var row = 0; row < subresource.Height; row++)
{
var sourceStart = subresource.SourceOffset + (row * subresource.RowBytes);
var destinationStart = subresource.UploadOffset + ((long)row * subresource.UploadRowPitch);
source.Slice(sourceStart, subresource.RowBytes).CopyTo(new Span<byte>(mapped + destinationStart, subresource.RowBytes));
}
}
}
finally
{
upload.Unmap(0, null);
}
return upload;
}
private static void CopySubresources(ID3D12GraphicsCommandList commandList, ID3D12Resource texture, ID3D12Resource upload, DdsLayout dds)
{
for (var subresourceIndex = 0; subresourceIndex < dds.Subresources.Length; subresourceIndex++)
{
var subresource = dds.Subresources[subresourceIndex];
var source = new TextureCopyLocation(
upload,
new PlacedSubresourceFootPrint
{
Offset = (ulong)subresource.UploadOffset,
Footprint = new SubresourceFootPrint(
Format.R16G16B16A16_Float,
(uint)subresource.Width,
(uint)subresource.Height,
1,
(uint)subresource.UploadRowPitch),
});
var destination = new TextureCopyLocation(texture, (uint)subresourceIndex);
commandList.CopyTextureRegion(destination, 0, 0, 0, source, null);
}
}
private static uint ReadUInt32(ReadOnlySpan<byte> bytes, int offset)
{
return BitConverter.ToUInt32(bytes.Slice(offset, sizeof(uint)));
}
private static long Align(long value, long alignment)
{
return (value + alignment - 1) & ~(alignment - 1);
}
private sealed record DdsLayout(int Width, int Height, int MipCount, DdsSubresource[] Subresources);
private sealed record DdsSubresource(int SourceOffset, int Width, int Height, int RowBytes)
{
public long UploadOffset { get; set; }
public int UploadRowPitch { get; set; }
}
}

View file

@ -38,6 +38,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
private const string GridShaderRelativePath = "Render/Shaders/D3D12Grid.hlsl";
private const string SceneShaderRelativePath = "Render/Shaders/D3D12Scene.hlsl";
private const string PostShaderRelativePath = "Render/Shaders/D3D12Post.hlsl";
private const string StudioPmremRelativePath = "Assets/Textures/studio3_pmrem.dds";
private static readonly DebugUi.DebugUiOption[] RenderDebugOptions =
[
new(0, "Final"),
@ -91,6 +92,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
private readonly D3D12RenderTarget[] bloomRenderTargets = new D3D12RenderTarget[BloomLevelCount];
private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount];
private readonly D3D12StructuredBuffer bodyLightBuffer;
private readonly D3D12CubeTexture studioPmremTexture;
private readonly BodyLightGpu[] bodyLights = new BodyLightGpu[BodyLightCount];
private readonly GridHeightBrushCpu[] gridHeightBrushes = new GridHeightBrushCpu[GridHeightBrushCount];
private Viewport viewport;
@ -188,6 +190,9 @@ public sealed class D3D12Renderer : IAquariumRenderer
fence.Name = "Aquarium D3D12 Frame Fence";
commandQueue.ExecuteCommandList(commandList);
WaitForGpu();
ReportStartupProgress(startupProgress, "Loading studio PMREM cubemap");
studioPmremTexture = LoadStudioPmremTexture();
resourceRegistry.Add("studio-pmrem-cubemap", studioPmremTexture);
ReportStartupProgress(startupProgress, "Creating D3D12 render pipelines");
fullscreenRootSignature = CreateFullscreenRootSignature();
fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature";
@ -307,6 +312,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
frameResources.BodyLightDescriptor = frameResources.TransientShaderDescriptors.Allocate();
bodyLightBuffer.CreateShaderResourceView(device, frameResources.BodyLightDescriptor);
frameResources.StudioPmremDescriptor = frameResources.TransientShaderDescriptors.Allocate();
studioPmremTexture.CreateShaderResourceView(device, frameResources.StudioPmremDescriptor);
frameResources.GridHeightDescriptor = frameResources.TransientShaderDescriptors.Allocate();
gridHeightRenderTarget.CreateShaderResourceView(device, frameResources.GridHeightDescriptor);
frameResources.SceneDescriptor = frameResources.TransientShaderDescriptors.Allocate();
@ -423,6 +430,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
overlayDevice.Dispose();
DisposePipelineStates();
fullscreenRootSignature.Dispose();
studioPmremTexture.Dispose();
bodyLightBuffer.Dispose();
DisposeBloomRenderTargets();
DisposeHistoryRenderTargets();
@ -457,6 +465,25 @@ public sealed class D3D12Renderer : IAquariumRenderer
}
}
private D3D12CubeTexture LoadStudioPmremTexture()
{
var path = Path.Combine(AppContext.BaseDirectory, StudioPmremRelativePath);
if (!File.Exists(path))
{
throw new FileNotFoundException("Studio PMREM cubemap asset was not copied to the runtime asset directory.", path);
}
var frameResources = frames[frameIndex];
frameResources.CommandAllocator.Reset();
commandList.Reset(frameResources.CommandAllocator, null);
var texture = D3D12CubeTexture.LoadRgba16FloatDds(device, commandList, path, "Aquarium D3D12 Studio PMREM Cubemap", out var uploadResource);
commandList.Close();
commandQueue.ExecuteCommandList(commandList);
WaitForGpu();
uploadResource.Dispose();
return texture;
}
private void CreateOverlayDevice(out ID3D11Device createdDevice, out ID3D11DeviceContext createdContext, out ID3D11On12Device createdOn12Device)
{
var featureLevels = new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 };
@ -763,6 +790,7 @@ public sealed class D3D12Renderer : IAquariumRenderer
context.CommandList.SetGraphicsRootDescriptorTable(0, frameResources.FrameConstantsDescriptor.Gpu);
context.CommandList.SetGraphicsRootDescriptorTable(1, frameResources.GridHeightDescriptor.Gpu);
context.CommandList.SetGraphicsRootDescriptorTable(3, frameResources.BodyLightDescriptor.Gpu);
context.CommandList.SetGraphicsRootDescriptorTable(14, frameResources.StudioPmremDescriptor.Gpu);
context.CommandList.RSSetViewports(viewport);
context.CommandList.RSSetScissorRects(scissorRect);
context.CommandList.OMSetRenderTargets(
@ -1410,6 +1438,12 @@ public sealed class D3D12Renderer : IAquariumRenderer
21,
0,
D3D12.DescriptorRangeOffsetAppend);
var studioPmremRange = new DescriptorRange(
DescriptorRangeType.ShaderResourceView,
1,
22,
0,
D3D12.DescriptorRangeOffsetAppend);
var rootParameters = new[]
{
new RootParameter(new RootDescriptorTable([constantBufferRange]), ShaderVisibility.All),
@ -1426,10 +1460,24 @@ public sealed class D3D12Renderer : IAquariumRenderer
new RootParameter(new RootDescriptorTable([currentEventMetadataRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([historyEventColorRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([historyEventMetadataRange]), ShaderVisibility.Pixel),
new RootParameter(new RootDescriptorTable([studioPmremRange]), ShaderVisibility.Pixel),
};
var staticSamplers = new[]
{
new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0),
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,
@ -1751,6 +1799,8 @@ public sealed class D3D12Renderer : IAquariumRenderer
public D3D12DescriptorSlot BodyLightDescriptor { get; set; }
public D3D12DescriptorSlot StudioPmremDescriptor { get; set; }
public D3D12DescriptorSlot GridHeightDescriptor { get; set; }
public D3D12DescriptorSlot SceneDescriptor { get; set; }

View file

@ -7,6 +7,7 @@ internal sealed class D3D12ResourceRegistry
private readonly Dictionary<string, D3D12TrackedResource> trackedResources = new(StringComparer.Ordinal);
private readonly Dictionary<string, D3D12RenderTarget> renderTargets = new(StringComparer.Ordinal);
private readonly Dictionary<string, D3D12StructuredBuffer> structuredBuffers = new(StringComparer.Ordinal);
private readonly Dictionary<string, D3D12CubeTexture> cubeTextures = new(StringComparer.Ordinal);
public void Add(string name, D3D12TrackedResource resource)
{
@ -32,6 +33,14 @@ internal sealed class D3D12ResourceRegistry
}
}
public void Add(string name, D3D12CubeTexture cubeTexture)
{
if (!cubeTextures.TryAdd(name, cubeTexture))
{
throw new InvalidOperationException($"D3D12 cube texture already registered: {name}");
}
}
public D3D12TrackedResource GetResource(string name)
{
return trackedResources.TryGetValue(name, out var resource)
@ -63,6 +72,6 @@ internal sealed class D3D12ResourceRegistry
public string Describe()
{
return $"resources={trackedResources.Count}, renderTargets={renderTargets.Count}, structuredBuffers={structuredBuffers.Count}";
return $"resources={trackedResources.Count}, renderTargets={renderTargets.Count}, structuredBuffers={structuredBuffers.Count}, cubeTextures={cubeTextures.Count}";
}
}

View file

@ -21,6 +21,7 @@ cbuffer AquariumFrame : register(b0)
};
Texture2D<float4> gridHeightTexture : register(t0);
TextureCube<float4> studioPmremTexture : register(t22);
SamplerState gridSampler : register(s0);
struct BodyLight
@ -53,6 +54,8 @@ static const float TERRAIN_FIELD_LINE_PIXEL_WIDTH = 0.38;
static const float3 GRID_COLOR = float3(0.30, 0.90, 0.82);
static const float GRID_ALPHA_SCALE = 0.56;
static const int BODY_LIGHT_COUNT = 8;
static const float STUDIO_PMREM_MAX_LOD = 8.0;
static const float STUDIO_PMREM_SPECULAR_INTENSITY = 0.34;
struct VertexOut
{
@ -624,6 +627,22 @@ float3 cursorSpecularBodyLightRadiance(float3 p, float3 normal)
return result;
}
float3 fresnelSchlickRoughness(float cosine, float3 f0, float roughness)
{
return f0 + (max(1.0 - roughness, f0) - f0) * pow(1.0 - cosine, 5.0);
}
float3 studioPmremSpecularRadiance(float3 p, float3 normal, float roughness, float3 f0)
{
float3 viewDirection = normalize(cameraPosition - p);
float ndv = saturate(dot(normal, viewDirection));
float3 reflectionDirection = reflect(-viewDirection, normal);
float lod = saturate(roughness) * STUDIO_PMREM_MAX_LOD;
float3 radiance = studioPmremTexture.SampleLevel(gridSampler, reflectionDirection, lod).rgb;
float3 fresnel = fresnelSchlickRoughness(ndv, f0, roughness);
return radiance * fresnel * STUDIO_PMREM_SPECULAR_INTENSITY;
}
float3 shadeBody(float2 uv, float travel, float3 p, float3 normal, int primitiveId)
{
float fieldId = primitiveFieldId(primitiveId);
@ -635,12 +654,20 @@ float3 shadeBody(float2 uv, float travel, float3 p, float3 normal, int primitive
if (primitiveId == CURSOR_PRIMITIVE_ID)
{
return emission + cursorSpecularBodyLightRadiance(p, normal);
static const float CursorRoughness = 0.16;
float3 cursorF0 = float3(0.95, 0.62, 0.26);
return emission
+ cursorSpecularBodyLightRadiance(p, normal)
+ studioPmremSpecularRadiance(p, normal, CursorRoughness, cursorF0);
}
float hue = hash21(float2(primitiveId, 6.3));
float3 albedo = lerp(float3(0.34, 0.42, 0.18), float3(0.70, 0.76, 0.42), hue);
return emission + albedo * bodyLightIrradianceAt(p, normal) / PI;
float roughness = lerp(0.46, 0.72, hash21(float2(primitiveId, 11.9)));
float3 dielectricF0 = 0.04;
return emission
+ albedo * bodyLightIrradianceAt(p, normal) / PI
+ studioPmremSpecularRadiance(p, normal, roughness, dielectricF0);
}
SceneOut D3D12ScenePS(VertexOut input)

View file

@ -5,3 +5,4 @@
{"timestamp":"2026-05-11T04:20:00+01:00","topic":"medium-froxel-purge","lesson":"Medium/froxel render targets, structured buffers, shader bindings, scene outputs, post history lanes, and medium debug paths were removed from the live D3D12 renderer. Future atmospheric or field transport work needs a new explicit pass contract rather than reviving shelved scaffolding.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/map.yaml","state/memory.json"]}
{"timestamp":"2026-05-11T05:32:00+01:00","topic":"body-light-lane","lesson":"Blue-noise assets are retained for future dithering. Self and future other Selves emit through an explicit body light buffer; generic field instances are not the lighting authority.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"]}
{"timestamp":"2026-05-11T06:18:00+01:00","topic":"pmrem-cubemap-bake","lesson":"Studio HDR reflection lighting is baked as a PMREM DDS cubemap: roughness selects higher mips, and the bake samples the source latlong by output direction so cubemap faces are generated from one continuous domain instead of filtered as isolated square images.","files":["scripts/bake-pmrem-cubemap.py","src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\EpiphanyAquarium\\public\\textures\\studio3.hdr"}
{"timestamp":"2026-05-11T06:28:00+01:00","topic":"pmrem-scene-binding","lesson":"The Studio3 PMREM asset is live in the scene as a D3D12 TextureCube bound at t22. The renderer owns a narrow RGBA16F DX10 DDS cubemap loader, keeps upload resources alive until the copy fence completes, and the scene shader uses roughness-scaled SampleLevel for specular material reflections only.","files":["src/Aquarium.Engine/Render/D3D12CubeTexture.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"]}

View file

@ -55,7 +55,7 @@ renderer_state:
- Direct-traced Grid linework as a non-terminating stochastic event lane before the nearest solid.
- SDF/analytic solids for Self, planets, and the cursor locator.
- Body light buffer feeds Self emission and direct body lighting; future other Selves should join this light lane, not a generic field-instance table.
- Studio3 PMREM DDS cubemap is baked from the Epiphany HDR latlong for future roughness-mip PBR reflections.
- Studio3 PMREM DDS cubemap is loaded as a D3D12 TextureCube and sampled for roughness-mip PBR specular reflections.
- DirectWrite/Direct2D debug UI panel with code-first controls bound to renderer state.
- Global GraphicsSettings document feeding render debug, exposure, bloom intensity, and bloom veil.
- Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them.

View file

@ -35,7 +35,7 @@
"Heavy/specialized SDF evaluators should not live inside generic packed-id helpers when those helpers are called repeatedly; avoid shader compiler path cloning.",
"Lighting is diegetic. Self is the initial emitter; later other Selves should emit through an explicit body light lane, not generic field instances or ambient convenience fill.",
"Keep bundled blue-noise texture assets available for future dithering/noise work even when no current pass samples them.",
"Specular IBL should use PMREM cubemaps: bake HDR latlong radiance into roughness-indexed cubemap mips, sampling the latlong by direction during prefilter instead of downsampling each face in isolation.",
"Specular IBL uses the Studio3 PMREM cubemap: bake HDR latlong radiance into roughness-indexed cubemap mips, load it as a D3D12 TextureCube, and sample it by reflection direction plus roughness LOD. Keep this as material reflection response, not a replacement for diegetic body light authority.",
"HDR/PBR presentation follows research/rendering/hdr-pbr-presentation.md: scene-linear lighting, explicit exposure, pre-tonemap bloom/veil, then display transform.",
"Current temporal diagnostics are for inspection. With projection jitter disabled, final presentation should not blindly trust temporal color history until a real temporal contract earns authority."
],