diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index c96ff17e04..83b013b90f 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -456,12 +456,16 @@ pub(crate) enum View { impl View { /// Whether the view reads buffer memory (constant buffers, buffer views - /// of resources or of memory) or memory the title placed a texture in: - /// such views get host slots only for draws. + /// of resources or of memory) or memory the title placed a texture in + /// to sample: such views get host slots only for draws. Placed + /// unordered texture views live on the host alone, as texture objects' + /// unordered views do, so shader-visible heap writes mirror them. #[cfg(windows)] fn is_buffer(&self) -> bool { + const BUFFER: u32 = 1; match self { - View::Constant(..) | View::Placed(..) => true, + View::Constant(..) | View::Placed(false, ..) => true, + View::Placed(true, resource, _) => resource[0] == BUFFER, View::Shader(r, _) | View::Unordered(r, _, _) => { crate::resource::buffer_bytes(*r as This).is_some() } diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index 7970fc5f0c..4f4189edac 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -2877,10 +2877,6 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { } const BUFFER: u32 = 1; if resource[0] != BUFFER { - // shortcut: unordered access to a texture the title placed - // itself is not mirrored; give it a resource as shader - // views of such textures get when a dispatch writes one. - once!(dimension = resource[0], "placed unordered texture view not mirrored"); return None; } // The resource description's width, after the alignment. @@ -2925,19 +2921,32 @@ fn same_placed_texture(a: &View, b: &View) -> bool { } } -/// A shader view of a texture the title placed in memory itself, as a view -/// of the resource made for that memory (on first use). +/// A shader or unordered access view of a texture the title placed in +/// memory itself, as a view of the resource made for that memory (on first +/// use). pub(crate) fn placed_texture(view: &View) -> Option { const BUFFER: u32 = 1; - let View::Placed(false, resource, desc) = view else { + const TARGET_DEPTH_UNORDERED: u32 = 0x7; + let &View::Placed(unordered, mut resource, ref desc) = view else { return None; }; if resource[0] == BUFFER { return None; } let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; - let texture = crate::resource::texture_at(address, resource)?; - Some(View::Shader(texture as usize, desc[..10].try_into().ok())) + let words = desc[..10].try_into().ok(); + if unordered { + let texture = crate::resource::uav_texture_at(address, &resource, desc[0])?; + Some(View::Unordered(texture as usize, 0, words)) + } else { + // Shader views placed in memory take their texels either from title + // memory or from `TARGETS_AT` (`resource::alias_of`): clear target + // flags the title left on the resource description so this view + // never replaces that target in `TARGETS_AT`. + resource[12] &= !TARGET_DEPTH_UNORDERED; + let texture = crate::resource::texture_at(address, &resource)?; + Some(View::Shader(texture as usize, words)) + } } /// A null view of the kind `view` is, for a slot whose view the host @@ -3586,6 +3595,202 @@ mod tests { assert_eq!(heap.dynamic(50), Some(4)); assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40)); } + + /// Placed unordered texture views (2D and 3D) mirror onto host unordered + /// access textures when written into a shader-visible heap, reuse an + /// existing target at the same address, and feed shader views placed at + /// that address in another format through `texture::alias`. + #[test] + fn placed_unordered_texture_view_mirrors_and_aliases_to_shader_view() { + let Some(host) = host() else { + return; // no host GPU + }; + let Some(heap) = HostHeap::new(false, 8) else { + return; + }; + + // 1. 3D volume UAV (4x4x4 R32_UINT, resource flags = 0) mirrored via + // `HostHeap::mirror(..., for_draw = false)` as a shader-visible heap + // copy does. + let vol_at = 0x7fed_1000_0000u64; + let vol_res = [4, 0, 0, 0, 4, 0, 4, 0x1_0004, 42, 1, 0, 0, 0, 0]; + let mut vol_uav = [0u32; 16]; + (vol_uav[0], vol_uav[1], vol_uav[4]) = (42, 8, 4); + (vol_uav[10], vol_uav[11]) = (vol_at as u32, (vol_at >> 32) as u32); + let slot_mem = [0u64; 4]; + let slot_handle = slot_mem.as_ptr() as u64; + super::super::create_placed_uav(std::ptr::null(), &vol_res, &vol_uav, slot_handle); + assert!(heap.mirror(0, slot_handle, false).is_some()); + { + let kept = heap.kept.lock().unwrap(); + let tex = kept[0].as_ref().expect("3D placed UAV must mirror immediately"); + // SAFETY: live D3D12 resource. + let d = unsafe { tex.GetDesc() }; + assert_eq!(d.Dimension, D3D12_RESOURCE_DIMENSION_TEXTURE3D); + assert_ne!(d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0, 0); + } + // SAFETY: plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + + // Another placed UAV at the same address with compatible format reuses + // the resource already recorded in `TARGETS_AT`. + let Some(View::Unordered(first_vol, _, _)) = + placed_texture(&View::Placed(true, vol_res, vol_uav)) + else { + panic!("expected View::Unordered"); + }; + let mut explicit_flags = vol_res; + explicit_flags[12] = 0x4; + let Some(View::Unordered(second_vol, _, _)) = + placed_texture(&View::Placed(true, explicit_flags, vol_uav)) + else { + panic!("expected View::Unordered"); + }; + assert_eq!(first_vol, second_vol, "must reuse existing UAV texture at address"); + + // 2. Cross-format aliasing: a 4x4 R9G9B9E5_SHAREDEXP (67) description + // written through an R32_UINT (42) placed UAV and then read through an + // R9G9B9E5_SHAREDEXP placed SRV (even if `ALLOW_UNORDERED_ACCESS` was + // left on the SRV's resource description) copies the GPU texels across. + let alias_at = 0x7fed_2000_0000u64; + let rgb9e5_res = [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 67, 1, 0, 0, 0x4, 0]; + let mut uav_desc = [0u32; 16]; + (uav_desc[0], uav_desc[1]) = (42, 4); + (uav_desc[10], uav_desc[11]) = (alias_at as u32, (alias_at >> 32) as u32); + let uav_placed = View::Placed(true, rgb9e5_res, uav_desc); + let Some(View::Unordered(uav_obj, _, _)) = placed_texture(&uav_placed) else { + panic!("expected placed UAV texture"); + }; + assert!(make(&uav_placed, heap.cpu(1)).flatten().is_some()); + + let mut srv_words = [0u32; 16]; + (srv_words[0], srv_words[1], srv_words[2], srv_words[5]) = + (67, 4, D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, 1); + (srv_words[10], srv_words[11]) = (alias_at as u32, (alias_at >> 32) as u32); + let srv_placed = View::Placed(false, rgb9e5_res, srv_words); + let Some(View::Shader(srv_obj, _)) = placed_texture(&srv_placed) else { + panic!("expected placed SRV texture"); + }; + assert!(make(&srv_placed, heap.cpu(2)).flatten().is_some()); + assert_eq!( + crate::resource::alias_of(srv_obj as crate::object::This), + Some(uav_obj as crate::object::This), + "placed SRV must find the placed UAV texture in TARGETS_AT" + ); + + // Upload a known R32_UINT pattern into `uav_obj` on the GPU, run + // `texture::alias` into `srv_obj`, and read `srv_obj` back. + let uav_tex = crate::resource::host_resource(uav_obj as crate::object::This).unwrap(); + let srv_tex = crate::resource::host_resource(srv_obj as crate::object::This).unwrap(); + let pattern = 0x7c40_8210u32; + let make_buf = |heap_type, state| { + let hp = D3D12_HEAP_PROPERTIES { + Type: heap_type, + ..Default::default() + }; + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut out: Option = None; + // SAFETY: valid buffer description. + unsafe { + host.device + .CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &rd, state, None, &mut out) + .unwrap(); + } + out.unwrap() + }; + let upload = make_buf(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let readback = make_buf(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + // SAFETY: 1024-byte upload buffer mapped on CPU. + unsafe { + let mut ptr = std::ptr::null_mut(); + upload.Map(0, None, Some(&mut ptr)).unwrap(); + std::slice::from_raw_parts_mut(ptr.cast::(), 256).fill(pattern); + upload.Unmap(0, None); + } + + let list = host.new_list().unwrap(); + crate::list::ensure_state(&list, uav_obj as crate::object::This, 0x400); // COPY_DEST + let buf_loc = |buf: &ID3D12Resource, format| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: borrowed pointer not released by the copy location. + pResource: unsafe { std::mem::transmute_copy(buf) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: format, + Width: 4, + Height: 4, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let tex_loc = |tex: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: borrowed pointer not released by the copy location. + pResource: unsafe { std::mem::transmute_copy(tex) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + // SAFETY: open list and live resources in matching copy states. + unsafe { + list.list.CopyTextureRegion( + &tex_loc(uav_tex), + 0, + 0, + 0, + &buf_loc(&upload, DXGI_FORMAT_R32_UINT), + None, + ); + } + crate::list::ensure_state(&list, uav_obj as crate::object::This, 0x8); // UNORDERED_ACCESS + assert!(crate::texture::alias( + &list, + srv_obj as crate::object::This, + uav_obj as crate::object::This + )); + crate::list::ensure_state(&list, srv_obj as crate::object::This, 0x800); // COPY_SOURCE + // SAFETY: open list and `srv_tex` transitioned to `COPY_SOURCE`. + unsafe { + list.list.CopyTextureRegion( + &buf_loc(&readback, DXGI_FORMAT_R9G9B9E5_SHAREDEXP), + 0, + 0, + 0, + &tex_loc(srv_tex), + None, + ); + } + list.close(); + host.execute(&[&list]); + + // SAFETY: GPU execution finished; readback holds 1024 bytes. + let got = unsafe { + let mut ptr = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut ptr)).unwrap(); + let word = *ptr.cast::(); + readback.Unmap(0, None); + word + }; + assert_eq!(got, pattern); + // SAFETY: plain device query. + assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok()); + } } #[cfg(test)] diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 244a76ccc0..58933fe60f 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -2645,6 +2645,106 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { Some(out) } +/// The resource for an unordered access view of a texture placed at +/// `address` with resource description `desc` and view format `view_format` +/// (0: the resource's own): an existing unordered-access texture at that +/// address when its format allows the view, else a placed unordered-access +/// resource made on first use (starting in `UNORDERED_ACCESS` and recorded +/// in [`TARGETS_AT`] so shader views placed at `address` find its texels +/// through [`alias_of`]). +#[cfg(windows)] +pub(crate) fn uav_texture_at(address: u64, desc: &[u32; 14], view_format: u32) -> Option { + const DEPTH: u32 = 0x2; + const UNORDERED: u32 = 0x4; + const UNORDERED_ACCESS: u32 = 0x8; + const DEFAULT: HeapProperties = HeapProperties { + kind: 1, + cpu_pages: 0, + pool: 0, + creation_nodes: 1, + visible_nodes: 1, + }; + if address == 0 { + return None; + } + // SAFETY: 56 bytes in the description's layout. + let d = unsafe { desc.as_ptr().cast::().read_unaligned() }; + if d.dimension == BUFFER { + return None; + } + let own = pc_format(d.format); + let wanted = if view_format == 0 { + own + } else { + pc_format(view_format) + }; + { + let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&other) = targets.get(&address) { + let o = resource(other as This); + let o_fmt = target_format(pc_format(o.desc.format)); + let w_fmt = target_format(wanted); + let typeless = family(o_fmt) == o_fmt && family(o_fmt + 1) == o_fmt; + let srgb = SRGB.iter().any(|&(s, _)| s == o_fmt); + let compatible = o_fmt == w_fmt || ((typeless || srgb) && family(w_fmt) == family(o_fmt)); + if o.desc.dimension == d.dimension + && o.desc.width == d.width + && o.desc.height == d.height + && o.desc.mip_levels == d.mip_levels + && o.desc.depth_or_array_size == d.depth_or_array_size + && o.desc.sample_count <= 1 + && d.sample_count <= 1 + && o.desc.flags & (DEPTH | UNORDERED) == UNORDERED + && compatible + { + return Some(other as This); + } + } + } + let mut r = *desc; + r[12] = (r[12] & !DEPTH) | UNORDERED; + if view_format != 0 && target_format(own) != target_format(wanted) { + if family(own) == family(wanted) { + r[8] = family(wanted); + } else if element(own) == element(wanted) { + r[8] = wanted; + } + } + let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(&existing) = map.get(&(address, r)) { + // A temporary target at this address may have replaced this texture + // and since been released. Restore the alias only if the slot is vacant. + TARGETS_AT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(address) + .or_insert(existing); + return Some(existing as This); + } + // SAFETY: 56 bytes in the description's layout. + let uav_desc = unsafe { r.as_ptr().cast::().read_unaligned() }; + let mut out = std::ptr::null(); + let made = hand_out_resource( + uav_desc, + DEFAULT, + 0, + Backing::Address(address as *mut u8), + UNORDERED_ACCESS, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut out, + ); + if made != S_OK { + return None; + } + map.insert((address, r), out as usize); + resource(out) + .host + .placed + .store(true, std::sync::atomic::Ordering::Relaxed); + Some(out) +} + pub(crate) extern "system" fn create_placed( _: This, heap: This, @@ -2834,6 +2934,48 @@ mod tests { visible_nodes: 0, }; + #[cfg(windows)] + #[test] + fn cached_placed_uav_is_visible_after_releasing_a_temporary_target() { + static TITLE_BYTES: [u8; 4096] = [0; 4096]; + let address = TITLE_BYTES.as_ptr() as u64; + let srv = [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 67, 1, 0, 0, 0, 0]; + let uav = uav_texture_at(address, &srv, 42).unwrap(); + let view = texture_at(address, &srv).unwrap(); + assert_eq!(alias_of(view), Some(uav)); + + // The title uses the storage temporarily for a different shape. + let mut other = texture(8, 4, 42, 1); + other.flags = 4; + let mut target = std::ptr::null(); + assert_eq!( + create_at_address( + std::ptr::null(), + address, + &other, + 0, + std::ptr::null(), + &RESOURCE_IIDS[0], + &mut target, + ), + S_OK + ); + let mut temporary_srv = srv; + temporary_srv[4] = 8; + let temporary_view = texture_at(address, &temporary_srv).unwrap(); + assert_eq!(uav_texture_at(address, &srv, 42), Some(uav)); + assert_eq!( + alias_of(temporary_view), + Some(target), + "keep the active target" + ); + assert_eq!(resource_release(target), 0); + + // Mirror the original placed UAV again, then resolve its paired SRV. + assert_eq!(uav_texture_at(address, &srv, 42), Some(uav)); + assert_eq!(alias_of(view), Some(uav), "restore the cached target"); + } + fn buffer(width: u64) -> ResourceDesc { ResourceDesc { dimension: BUFFER,