Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 143 additions & 26 deletions d3d12/crates/leonida-gpu/src/ambient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,28 +439,43 @@ void place(uint3 at : SV_DispatchThreadID) {
#endif

#ifdef GATHER
groupshared float4 tile_pos[64];
groupshared float3 tile_light[64];
[RootSignature(RS)]
[numthreads(8, 2, 1)]
void gather(uint3 at : SV_DispatchThreadID) {
float2 size = float2(width, height);
float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size);
float r2 = 0.25 + 0.0025 * p.z * p.z;
[numthreads(8, 8, 1)]
void gather(uint3 at : SV_DispatchThreadID, uint lid : SV_GroupIndex) {
bool active = at.x < PX && at.y < PY;
float3 p = 0;
float r2 = 0;
if (active) {
float2 size = float2(width, height);
p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size);
r2 = 0.25 + 0.0025 * p.z * p.z;
}
float whole = 0;
float3 toward = 0, light = 0, red = 0, green = 0, blue = 0;
for (uint i = 0; i < CELLS; i++) {
float4 c = cells[CELLS + 1 + i];
float3 L = cells[i].rgb;
float3 d = c.xyz - p;
float dd = dot(d, d);
float w = c.w / (dd + r2);
float3 dir = d / sqrt(dd + 0.25 * r2);
whole += w;
toward += w * dir;
light += w * L;
red += w * L.r * dir;
green += w * L.g * dir;
blue += w * L.b * dir;
for (uint base = 0; base < CELLS; base += 64) {
uint idx = base + lid;
tile_pos[lid] = cells[CELLS + 1 + idx];
tile_light[lid] = cells[idx].rgb;
GroupMemoryBarrierWithGroupSync();
if (active) for (uint j = 0; j < 64; j++) {
float4 c = tile_pos[j];
float3 L = tile_light[j];
float3 d = c.xyz - p;
float dd = dot(d, d);
float w = c.w / (dd + r2);
float3 dir = d / sqrt(dd + 0.25 * r2);
whole += w;
toward += w * dir;
light += w * L;
red += w * L.r * dir;
green += w * L.g * dir;
blue += w * L.b * dir;
}
GroupMemoryBarrierWithGroupSync();
}
if (!active) return;
whole = max(whole, 1e-6);
light /= whole;
toward /= whole;
Expand Down Expand Up @@ -715,9 +730,20 @@ fn pass() -> Option<&'static Pass> {
.as_ref()
}

fn uav_barrier(list: &ID3D12GraphicsCommandList) {
let barrier = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() };
// SAFETY: an open list; the barrier names no resource.
fn uav_barrier(list: &ID3D12GraphicsCommandList, resource: Option<&ID3D12Resource>) {
let barrier = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
// SAFETY: borrowed until ResourceBarrier returns; never released by the barrier.
pResource: resource.map_or(std::mem::ManuallyDrop::new(None), |r| unsafe {
std::mem::transmute_copy(r)
}),
}),
},
..Default::default()
};
// SAFETY: an open list; any named resource remains live through the call.
unsafe { list.ResourceBarrier(&[barrier]) };
}

Expand Down Expand Up @@ -797,7 +823,9 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool {
// program has just used both views, so their textures are in the states
// these views need; buffers the list keeps.
unsafe {
uav_barrier(l);
if role != Role::Resolve {
uav_barrier(l, None);
}
// The depth is bound only where it is read: a table nobody sets is
// undefined on some drivers.
l.SetComputeRootSignature(if views.depth.is_some() { &pass.resolve_root } else { &pass.root });
Expand All @@ -811,24 +839,33 @@ pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool {
let run = |pso: &ID3D12PipelineState, x, y, z| {
l.SetPipelineState(pso);
l.Dispatch(x, y, z);
uav_barrier(l);
};
match role {
Role::Radiance => {
run(&pass.keep, 8, 9, 1);
uav_barrier(l, Some(&pass.cells));
run(&pass.mean, 1, 1, 1);
uav_barrier(l, Some(&pass.cells));
KEPT.store(true, Ordering::Relaxed);
}
Role::Air | Role::Alpha => {
run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2))
run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2));
uav_barrier(l, None);
}
Role::Reflect => {
run(&pass.reflect, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1);
uav_barrier(l, None);
}
Role::Reflect => run(&pass.reflect, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1),
Role::Resolve => {
if constant == 0.0 {
run(&pass.place, 8, 9, 1);
run(&pass.gather, 20, 45, 1);
uav_barrier(l, Some(&pass.cells));
run(&pass.gather, 20, 12, 1);
}
// Synchronizes both `pass.points` (from `gather`) and the title's `views.image` UAV write before `raise`.
uav_barrier(l, None);
run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1);
uav_barrier(l, None);
}
}
}
Expand Down Expand Up @@ -868,4 +905,84 @@ mod tests {
};
make(&host.device, |bytes| host.uav_buffer(bytes)).expect("the passes");
}

/// A single lit cell in the final tile reaches every point, including the
/// two live rows in the last group (`90 % 8 == 2`). Unwritten points retain NaNs.
#[test]
fn gather_dispatches_the_partial_group() {
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT;

let Some(host) = host() else { return };
let pass = make(&host.device, |bytes| host.uav_buffer(bytes)).expect("the passes");
let (upload, data) = host.upload_buffer(CELL_BYTES + POINT_BYTES).expect("upload");
let back = host.read_back_buffer(POINT_BYTES).expect("readback");
let list = host.new_list().expect("list");
// SAFETY: the upload mapping has CELL_BYTES + POINT_BYTES bytes.
unsafe {
std::ptr::write_bytes(data, 0, CELL_BYTES as usize);
std::ptr::write_bytes(data.add(CELL_BYTES as usize), 0xff, POINT_BYTES as usize);
let light = data.add(((CELLS - 1) * 16) as usize).cast::<f32>();
light.write_unaligned(0.25);
light.add(1).write_unaligned(0.5);
light.add(2).write_unaligned(1.0);
data.add(((2 * CELLS) * 16 + 12) as usize).cast::<f32>().write_unaligned(4096.0);

let heap: ID3D12DescriptorHeap = host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: 1,
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
NodeMask: 0,
}).expect("descriptor heap");
let srv = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT_R32_FLOAT,
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() },
},
};
// A null texture SRV supplies zero depth at every sample.
host.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&srv), heap.GetCPUDescriptorHandleForHeapStart());
let l = &list.list;
l.ResourceBarrier(&[
crate::host::transition(&pass.cells, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST),
crate::host::transition(&pass.points, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST),
]);
l.CopyBufferRegion(&pass.cells, 0, &upload, 0, CELL_BYTES);
l.CopyBufferRegion(&pass.points, 0, &upload, CELL_BYTES, POINT_BYTES);
l.ResourceBarrier(&[
crate::host::transition(&pass.cells, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
crate::host::transition(&pass.points, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
]);
l.SetDescriptorHeaps(&[Some(heap.clone())]);
l.SetComputeRootSignature(&pass.resolve_root);
let mut words = [0u32; 16];
words[4] = 0.1f32.to_bits();
words[5] = 0.45f32.to_bits();
words[6] = 160;
words[7] = 90;
l.SetComputeRoot32BitConstants(0, 16, words.as_ptr().cast(), 0);
l.SetComputeRootUnorderedAccessView(2, pass.cells.GetGPUVirtualAddress());
l.SetComputeRootUnorderedAccessView(3, pass.points.GetGPUVirtualAddress());
l.SetComputeRootDescriptorTable(4, heap.GetGPUDescriptorHandleForHeapStart());
l.SetPipelineState(&pass.gather);
l.Dispatch(20, 12, 1);
l.ResourceBarrier(&[crate::host::transition(&pass.points, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
l.CopyBufferRegion(&back, 0, &pass.points, 0, POINT_BYTES);
list.close();
host.execute(&[&list]);
host.device.GetDeviceRemovedReason().expect("gather execution");
let mut mapped = std::ptr::null_mut();
back.Map(0, None, Some(&mut mapped)).expect("map points");
let points = std::slice::from_raw_parts(mapped.cast::<f32>(), (POINT_BYTES / 4) as usize);
for (point, values) in points.chunks_exact(12).enumerate() {
for (channel, expected) in [0.25f32, 0.5, 1.0].into_iter().enumerate() {
let value = &values[channel * 4..channel * 4 + 4];
assert!(value[..3].iter().all(|v| v.is_finite() && v.abs() < 1e-5), "point {point}, channel {channel}: {value:?}");
assert!((value[3] - expected).abs() < 1e-5, "point {point}, channel {channel}: {value:?}");
}
}
back.Unmap(0, None);
}
}
}
Loading