mirror of
https://github.com/GiovannaSGuerrera/Victory-RTX2080.git
synced 2026-12-06 06:28:40 +00:00
- Rewrote README.md with complete RTX 2080 documentation - Redesigned ENGINE_PRESETS in core.py with 5 RTX 2080 presets: * v21 8GB SEGURO (default), v21 NÍTIDO, v21 MAX FPS, v21 + DLSS FG 2x, v21 ORIGINAL - Updated LauncherConfig defaults for RTX 2080 8GB - Added VICTORY_DYNAMIC_SLOTS and VICTORY_L0_MAX_MB to Motor tab in app.py - Updated tab_image descriptions for RTX 2080 - Added GitHub repo GiovannaSGuerrera/Victory-RTX2080 as default Co-Authored-By: Claude Code <noreply@anthropic.com>
915 lines
36 KiB
Diff
915 lines
36 KiB
Diff
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
|
|
index 04738c80cd752a64f93715658c3610ebaa1de097..728306c920462f00b543a684d21964e8acb4b9ba 100644
|
|
--- a/crates/victory-gpu/src/host.rs
|
|
+++ b/crates/victory-gpu/src/host.rs
|
|
@@ -194,42 +194,70 @@ fn create() -> windows::core::Result<Host> {
|
|
let messages = debug
|
|
.then(|| device.cast::<ID3D12InfoQueue>().ok())
|
|
.flatten();
|
|
- let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
|
- Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
|
|
- ..Default::default()
|
|
- })?;
|
|
- let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
|
|
- let event = CreateEventW(None, false, false, None)?;
|
|
- let rtvs: ID3D12DescriptorHeap =
|
|
- device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
|
- Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
|
|
- NumDescriptors: RTV_RING,
|
|
- ..Default::default()
|
|
- })?;
|
|
- let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
|
|
- let dsvs: ID3D12DescriptorHeap =
|
|
- device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
|
- Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
|
|
- NumDescriptors: RTV_RING,
|
|
+ let host = Host::from_device(device, messages)?;
|
|
+ tracing::info!("host D3D12 device ready");
|
|
+ Ok(host)
|
|
+ }
|
|
+}
|
|
+
|
|
+impl Host {
|
|
+ fn from_device(
|
|
+ device: ID3D12Device,
|
|
+ messages: Option<ID3D12InfoQueue>,
|
|
+ ) -> windows::core::Result<Host> {
|
|
+ // SAFETY: plain D3D12 queue, fence, event and descriptor heap creation.
|
|
+ unsafe {
|
|
+ let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
|
|
+ Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
|
|
..Default::default()
|
|
})?;
|
|
- let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
|
|
- tracing::info!("host D3D12 device ready");
|
|
- Ok(Host {
|
|
- device,
|
|
- queue,
|
|
- fence,
|
|
- submitted: Mutex::new(0),
|
|
- event,
|
|
- rtvs,
|
|
- rtv_size,
|
|
- dsvs,
|
|
- dsv_size,
|
|
- next_dsv: AtomicU32::new(0),
|
|
- messages,
|
|
- next_rtv: AtomicU32::new(0),
|
|
- presenter: Mutex::new(None),
|
|
- })
|
|
+ let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
|
|
+ let event = CreateEventW(None, false, false, None)?;
|
|
+ let rtvs: ID3D12DescriptorHeap =
|
|
+ device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
|
+ Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
|
|
+ NumDescriptors: RTV_RING,
|
|
+ ..Default::default()
|
|
+ })?;
|
|
+ let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
|
|
+ let dsvs: ID3D12DescriptorHeap =
|
|
+ device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
|
|
+ Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
|
|
+ NumDescriptors: RTV_RING,
|
|
+ ..Default::default()
|
|
+ })?;
|
|
+ let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
|
|
+ Ok(Host {
|
|
+ device,
|
|
+ queue,
|
|
+ fence,
|
|
+ submitted: Mutex::new(0),
|
|
+ event,
|
|
+ rtvs,
|
|
+ rtv_size,
|
|
+ dsvs,
|
|
+ dsv_size,
|
|
+ next_dsv: AtomicU32::new(0),
|
|
+ messages,
|
|
+ next_rtv: AtomicU32::new(0),
|
|
+ presenter: Mutex::new(None),
|
|
+ })
|
|
+ }
|
|
+ }
|
|
+
|
|
+ /// Creates an isolated WARP-backed `Host` for unit tests without touching
|
|
+ /// the process-global host singleton.
|
|
+ #[cfg(test)]
|
|
+ pub(crate) fn new_warp() -> Option<Host> {
|
|
+ // SAFETY: creates an isolated DXGI factory and requests its software adapter.
|
|
+ let adapter: IDXGIAdapter = unsafe {
|
|
+ let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?;
|
|
+ factory.EnumWarpAdapter().ok()?
|
|
+ };
|
|
+ let mut device: Option<ID3D12Device> = None;
|
|
+ // SAFETY: `adapter` is a verified software WARP adapter.
|
|
+ unsafe { D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).ok()? };
|
|
+ Host::from_device(device?, None).ok()
|
|
}
|
|
}
|
|
|
|
@@ -323,9 +351,15 @@ enum Step {
|
|
Run(Box<dyn Fn() + Send>),
|
|
/// Work that writes host memory only.
|
|
Host(Box<dyn Fn() + Send>),
|
|
- Texture(std::sync::Arc<crate::texture::Staging>),
|
|
/// Shaders write a range (address, bytes) of a buffer's host copy.
|
|
GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
|
|
+ /// Brings a texture's staging buffer up to date and, when dirty, copies
|
|
+ /// it into the host texture on the list's prelude: once per submission,
|
|
+ /// whichever lists sample it, until a `Copy` or `Run` intervenes.
|
|
+ Texture(
|
|
+ std::sync::Arc<crate::texture::Staging>,
|
|
+ std::sync::Arc<crate::resource::HostTexture>,
|
|
+ ),
|
|
}
|
|
|
|
/// What a list does on the CPU when it is submitted: copies between host
|
|
@@ -490,8 +524,8 @@ impl Host {
|
|
let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
|
|
let mut batch = Batch::default();
|
|
for list in runs {
|
|
- list.run_deferred(&mut batch);
|
|
- if let Some(prelude) = list.prelude() {
|
|
+ let uploads = list.run_deferred(&mut batch);
|
|
+ if let Some(prelude) = list.prelude(&uploads) {
|
|
lists.push(Some(prelude));
|
|
}
|
|
lists.push(list.list.cast().ok());
|
|
@@ -813,12 +847,50 @@ impl HostList {
|
|
}
|
|
}
|
|
|
|
- /// At submission: the list that moves each texture this list uses from
|
|
- /// its real state to the one the list starts with; the textures' real
|
|
- /// states become those the list ends with.
|
|
- fn prelude(&self) -> Option<ID3D12CommandList> {
|
|
+ /// Records that this list starts and ends with `copy` in `wanted` state
|
|
+ /// (test helper matching `transition`'s first-use tracking).
|
|
+ #[cfg(test)]
|
|
+ pub(crate) fn expect_texture_state(
|
|
+ &self,
|
|
+ copy: &std::sync::Arc<crate::resource::HostTexture>,
|
|
+ wanted: u32,
|
|
+ ) {
|
|
+ let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
|
|
+ states
|
|
+ .entry(std::sync::Arc::as_ptr(copy) as usize)
|
|
+ .or_insert_with(|| (wanted, wanted, copy.clone()));
|
|
+ }
|
|
+
|
|
+ #[cfg(test)]
|
|
+ pub(crate) fn has_deferred_work(&self) -> bool {
|
|
+ !self.deferred().copies.is_empty()
|
|
+ }
|
|
+
|
|
+ /// At submission: the list that copies any newly dirtied textures from
|
|
+ /// their staging buffers into their host textures and moves each texture
|
|
+ /// this list uses from its real state to the one the list starts with;
|
|
+ /// the textures' real states become those the list ends with.
|
|
+ fn prelude(
|
|
+ &self,
|
|
+ uploads: &[(
|
|
+ std::sync::Arc<crate::texture::Staging>,
|
|
+ std::sync::Arc<crate::resource::HostTexture>,
|
|
+ )],
|
|
+ ) -> Option<ID3D12CommandList> {
|
|
+ const COPY_DEST: u32 = D3D12_RESOURCE_STATE_COPY_DEST.0 as u32;
|
|
+ let mut pre_barriers = Vec::new();
|
|
+ for (_, copy) in uploads {
|
|
+ let real = copy.state.swap(COPY_DEST, Ordering::Relaxed);
|
|
+ if real != COPY_DEST {
|
|
+ pre_barriers.push(transition(
|
|
+ ©.texture,
|
|
+ D3D12_RESOURCE_STATES(real as i32),
|
|
+ D3D12_RESOURCE_STATE_COPY_DEST,
|
|
+ ));
|
|
+ }
|
|
+ }
|
|
let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
|
|
- let barriers: Vec<D3D12_RESOURCE_BARRIER> = states
|
|
+ let post_barriers: Vec<D3D12_RESOURCE_BARRIER> = states
|
|
.values()
|
|
.filter_map(|(first, last, copy)| {
|
|
let real = copy.state.swap(*last, Ordering::Relaxed);
|
|
@@ -831,16 +903,24 @@ impl HostList {
|
|
})
|
|
})
|
|
.collect();
|
|
- if barriers.is_empty() {
|
|
+ if uploads.is_empty() && post_barriers.is_empty() {
|
|
return None;
|
|
}
|
|
let (allocator, list) = &self.prelude;
|
|
// SAFETY: the prelude is not executing (every submission is waited
|
|
- // for); the textures are live.
|
|
+ // for); the textures and staging buffers are live.
|
|
let recorded = unsafe {
|
|
allocator.Reset().and_then(|()| {
|
|
list.Reset(allocator, None)?;
|
|
- list.ResourceBarrier(&barriers);
|
|
+ if !pre_barriers.is_empty() {
|
|
+ list.ResourceBarrier(&pre_barriers);
|
|
+ }
|
|
+ for (staging, copy) in uploads {
|
|
+ staging.record_copies(list, ©.texture);
|
|
+ }
|
|
+ if !post_barriers.is_empty() {
|
|
+ list.ResourceBarrier(&post_barriers);
|
|
+ }
|
|
list.Close()
|
|
})
|
|
};
|
|
@@ -1064,8 +1144,17 @@ impl HostList {
|
|
self.deferred().copies.push(Step::Host(Box::new(work)));
|
|
}
|
|
|
|
- pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
|
|
- self.deferred().copies.push(Step::Texture(staging));
|
|
+ /// Brings a texture's staging buffer up to date when the list is
|
|
+ /// submitted (and copies it to `texture` on the prelude only if dirty),
|
|
+ /// keeping both alive until the list is reset.
|
|
+ pub(crate) fn defer_texture(
|
|
+ &self,
|
|
+ staging: std::sync::Arc<crate::texture::Staging>,
|
|
+ texture: std::sync::Arc<crate::resource::HostTexture>,
|
|
+ ) {
|
|
+ self.deferred()
|
|
+ .copies
|
|
+ .push(Step::Texture(staging, texture));
|
|
}
|
|
|
|
pub(crate) fn defer_readback(&self, readback: crate::readback::Readback) {
|
|
@@ -1074,10 +1163,18 @@ impl HostList {
|
|
|
|
/// Runs the list's submission-time steps; refreshes go into `batch`
|
|
/// (the title's big buffers, a 174 MB one among them, are read by most
|
|
- /// lists of a submission, through many ranges).
|
|
- fn run_deferred(&self, batch: &mut Batch) {
|
|
+ /// lists of a submission, through many ranges). Returns the textures
|
|
+ /// whose staging buffers changed and must be copied onto the prelude.
|
|
+ fn run_deferred(
|
|
+ &self,
|
|
+ batch: &mut Batch,
|
|
+ ) -> Vec<(
|
|
+ std::sync::Arc<crate::texture::Staging>,
|
|
+ std::sync::Arc<crate::resource::HostTexture>,
|
|
+ )> {
|
|
#[cfg(feature = "diagnostics")]
|
|
use crate::copystat::{C, add};
|
|
+ let mut uploads = Vec::new();
|
|
let deferred = self.deferred();
|
|
for (heap, writes) in &deferred.bindless {
|
|
batch.bindless(heap, *writes);
|
|
@@ -1113,12 +1210,6 @@ impl HostList {
|
|
batch.add(shadow, *address, *len);
|
|
continue;
|
|
}
|
|
- Step::Texture(staging) => {
|
|
- if batch.texture_due(staging) {
|
|
- staging.refresh();
|
|
- }
|
|
- continue;
|
|
- }
|
|
Step::Run(work) | Step::Host(work) => {
|
|
if matches!(step, Step::Run(_)) {
|
|
batch.title_written();
|
|
@@ -1137,10 +1228,17 @@ impl HostList {
|
|
shadow.writing(*address, *len);
|
|
continue;
|
|
}
|
|
+ Step::Texture(staging, copy) => {
|
|
+ if batch.texture_due(staging) && staging.refresh() {
|
|
+ uploads.push((staging.clone(), copy.clone()));
|
|
+ }
|
|
+ continue;
|
|
+ }
|
|
};
|
|
PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
|
|
PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
|
|
}
|
|
+ uploads
|
|
}
|
|
}
|
|
|
|
diff --git a/crates/victory-gpu/src/texture.rs b/crates/victory-gpu/src/texture.rs
|
|
index e6d2c2bcfa5e33f3b5da733dda897b19af41ab8a..8914e94833df2a2f80170407fa5a77efe462caaf 100644
|
|
--- a/crates/victory-gpu/src/texture.rs
|
|
+++ b/crates/victory-gpu/src/texture.rs
|
|
@@ -34,9 +34,6 @@ macro_rules! once {
|
|
/// texture's subresources, and what was last detiled.
|
|
pub(crate) struct Staging {
|
|
buffer: ID3D12Resource,
|
|
- /// Its bytes.
|
|
- #[cfg(feature = "diagnostics")]
|
|
- size: u64,
|
|
data: *mut u8,
|
|
footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
|
|
rows: Vec<u32>,
|
|
@@ -45,6 +42,8 @@ pub(crate) struct Staging {
|
|
mips: u32,
|
|
memory: *const u8,
|
|
last: Mutex<Last>,
|
|
+ #[cfg(test)]
|
|
+ gpu_uploads: std::sync::atomic::AtomicU64,
|
|
}
|
|
|
|
/// What a texture's staging buffer holds: the hash of the memory detiled
|
|
@@ -96,10 +95,10 @@ pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
|
|
unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0
|
|
}
|
|
|
|
-/// Records, once per list, the copy of `resource`'s staging buffer into
|
|
-/// its host copy, and the detiling that refreshes the staging buffer at
|
|
-/// submission if the memory changed. Leaves the texture in the copy
|
|
-/// destination state.
|
|
+/// Registers a title-written texture with `list` (once per list) so that at
|
|
+/// submission time its staging buffer is checked for CPU modifications and,
|
|
+/// only when its contents changed (including first upload), copied into its
|
|
+/// host texture on the list's prelude command list.
|
|
pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
|
|
#[cfg(feature = "diagnostics")]
|
|
if crate::resource::expanded_scene_hdr(resource) {
|
|
@@ -116,84 +115,43 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
|
|
if host_written || !list.first_use(resource as usize) {
|
|
return;
|
|
}
|
|
+ let Some(copy) = crate::resource::host_copy(resource) else {
|
|
+ return;
|
|
+ };
|
|
let Some(staging) = staging(resource, texture) else {
|
|
return;
|
|
};
|
|
- const COPY_DEST: u32 = 0x400;
|
|
- crate::list::ensure_state(list, resource, COPY_DEST);
|
|
- // The staging buffer lives as long as `staging`, which the deferred
|
|
- // refresh below holds until the list is reset.
|
|
- for (i, footprint) in staging.footprints.iter().enumerate() {
|
|
- #[cfg(feature = "diagnostics")]
|
|
- {
|
|
- let f = footprint.Footprint;
|
|
- // SAFETY: live resources.
|
|
- let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
|
|
- let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
|
|
- list.note_read(
|
|
- || {
|
|
- format!(
|
|
- "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
|
|
- d.Width,
|
|
- d.Height,
|
|
- d.DepthOrArraySize,
|
|
- d.Format.0,
|
|
- d.MipLevels,
|
|
- staging.footprints.len(),
|
|
- staging.size,
|
|
- footprint.Offset,
|
|
- f.Width,
|
|
- f.Height,
|
|
- f.Depth,
|
|
- f.RowPitch
|
|
- )
|
|
- },
|
|
- (gpu + footprint.Offset, len),
|
|
- );
|
|
- }
|
|
- let to = D3D12_TEXTURE_COPY_LOCATION {
|
|
- // SAFETY: a borrowed pointer the location never releases.
|
|
- pResource: unsafe { std::mem::transmute_copy(texture) },
|
|
- Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
|
- Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
- SubresourceIndex: i as u32,
|
|
- },
|
|
- };
|
|
- let from = D3D12_TEXTURE_COPY_LOCATION {
|
|
- // SAFETY: as above.
|
|
- pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
|
|
- Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
|
- Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
- PlacedFootprint: *footprint,
|
|
- },
|
|
- };
|
|
- // SAFETY: an open list; both locations name live resources.
|
|
- unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
|
- }
|
|
- list.defer_texture(staging);
|
|
+ // Once per submission however many of its lists sample the texture;
|
|
+ // `copy` keeps the host texture alive even if the title releases it
|
|
+ // before submission, and `CopyTextureRegion` is only recorded onto the
|
|
+ // prelude when `staging.refresh()` reports dirty contents.
|
|
+ list.defer_texture(staging, copy);
|
|
}
|
|
|
|
impl Staging {
|
|
/// Detiles the texture memory into the staging buffer if it changed
|
|
- /// since the last time (and is mapped at all).
|
|
- pub(crate) fn refresh(&self) {
|
|
+ /// since the last time (and is mapped at all). Returns `true` when the
|
|
+ /// staging buffer received new contents that must be copied to the host
|
|
+ /// texture (including initial upload).
|
|
+ pub(crate) fn refresh(&self) -> bool {
|
|
use std::sync::atomic::Ordering::Relaxed;
|
|
let started = std::time::Instant::now();
|
|
- let read = self.refresh_now();
|
|
+ let (read, dirty) = self.refresh_now();
|
|
let preparing = &crate::host::PREPARING;
|
|
preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
|
|
preparing[3].fetch_add(read as u64, Relaxed);
|
|
+ dirty
|
|
}
|
|
|
|
- /// Returns the bytes of title memory read.
|
|
- fn refresh_now(&self) -> usize {
|
|
+ /// Returns `(bytes_read, dirty)`.
|
|
+ fn refresh_now(&self) -> (usize, bool) {
|
|
let size = self.layout.size as usize;
|
|
let start = self.memory as usize;
|
|
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
|
|
let last = &mut *last;
|
|
if let Some((now, written)) = crate::watch::writes(start, start + size, false) {
|
|
if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
|
|
- return 0;
|
|
+ return (0, false);
|
|
}
|
|
last.asked = now;
|
|
// Read through the copy, which stands unmapped pages: memory of
|
|
@@ -203,7 +161,7 @@ impl Staging {
|
|
self.detile(&last.read);
|
|
#[cfg(feature = "diagnostics")]
|
|
crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
|
|
- return size;
|
|
+ return (size, true);
|
|
}
|
|
if !committed(self.memory, size) {
|
|
#[cfg(feature = "diagnostics")]
|
|
@@ -213,7 +171,7 @@ impl Staging {
|
|
desc = ?self.layout.desc,
|
|
"a sampled texture's memory is not committed"
|
|
);
|
|
- return 0;
|
|
+ return (0, false);
|
|
}
|
|
// SAFETY: committed memory of the texture's layout size.
|
|
let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
|
|
@@ -221,13 +179,46 @@ impl Staging {
|
|
#[cfg(feature = "diagnostics")]
|
|
crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
|
|
if last.hash == Some(hash) {
|
|
- return size;
|
|
+ return (size, false);
|
|
}
|
|
last.hash = Some(hash);
|
|
self.detile(tiled);
|
|
#[cfg(feature = "diagnostics")]
|
|
crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
|
|
- size
|
|
+ (size, true)
|
|
+ }
|
|
+
|
|
+ /// Records `CopyTextureRegion` for every subresource from this staging
|
|
+ /// buffer into `texture` (which must already be in `COPY_DEST`).
|
|
+ pub(crate) fn record_copies(&self, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) {
|
|
+ for (i, footprint) in self.footprints.iter().enumerate() {
|
|
+ let to = D3D12_TEXTURE_COPY_LOCATION {
|
|
+ // SAFETY: a borrowed pointer the location never releases.
|
|
+ pResource: unsafe { std::mem::transmute_copy(texture) },
|
|
+ Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
|
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
+ SubresourceIndex: i as u32,
|
|
+ },
|
|
+ };
|
|
+ let from = D3D12_TEXTURE_COPY_LOCATION {
|
|
+ // SAFETY: as above.
|
|
+ pResource: unsafe { std::mem::transmute_copy(&self.buffer) },
|
|
+ Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
|
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
+ PlacedFootprint: *footprint,
|
|
+ },
|
|
+ };
|
|
+ // SAFETY: an open list; both locations name live resources.
|
|
+ unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
|
|
+ #[cfg(test)]
|
|
+ self.gpu_uploads
|
|
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
+ }
|
|
+ }
|
|
+
|
|
+ #[cfg(test)]
|
|
+ fn gpu_uploads(&self) -> u64 {
|
|
+ self.gpu_uploads.load(std::sync::atomic::Ordering::Relaxed)
|
|
}
|
|
|
|
/// Detiles `tiled` (the texture's memory) into the staging buffer.
|
|
@@ -300,6 +291,19 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
|
return None;
|
|
}
|
|
let host = host()?;
|
|
+ let s = create_staging(host, resource, texture, layout, memory)?;
|
|
+ tracing::debug!(?desc, "texture contents queued for staging upload");
|
|
+ map.insert(resource as usize, s.clone());
|
|
+ Some(s)
|
|
+}
|
|
+
|
|
+fn create_staging(
|
|
+ host: &crate::host::Host,
|
|
+ resource: This,
|
|
+ texture: &ID3D12Resource,
|
|
+ layout: victory_formats::texture::Layout,
|
|
+ memory: *const u8,
|
|
+) -> Option<Arc<Staging>> {
|
|
// SAFETY: a live resource.
|
|
let d = unsafe { texture.GetDesc() };
|
|
let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
|
|
@@ -330,11 +334,8 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
|
d.Width, d.Height, d.DepthOrArraySize, d.Format.0
|
|
)
|
|
});
|
|
- tracing::debug!(?desc, total, "texture contents uploaded from title memory");
|
|
- let s = Arc::new(Staging {
|
|
+ Some(Arc::new(Staging {
|
|
buffer,
|
|
- #[cfg(feature = "diagnostics")]
|
|
- size: total,
|
|
data,
|
|
footprints,
|
|
rows,
|
|
@@ -342,7 +343,377 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
|
|
mips: u32::from(d.MipLevels),
|
|
memory,
|
|
last: Mutex::default(),
|
|
- });
|
|
- map.insert(resource as usize, s.clone());
|
|
- Some(s)
|
|
+ #[cfg(test)]
|
|
+ gpu_uploads: std::sync::atomic::AtomicU64::new(0),
|
|
+ }))
|
|
+}
|
|
+
|
|
+#[cfg(test)]
|
|
+mod tests {
|
|
+ use super::*;
|
|
+ use crate::host::Host;
|
|
+ use crate::resource::HostTexture;
|
|
+ use std::sync::atomic::{AtomicU32, Ordering};
|
|
+ use victory_formats::texture::{Dimension, Swizzle, Texture, TextureDesc};
|
|
+ use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC};
|
|
+
|
|
+ const SHADER_RESOURCE: u32 = (D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0
|
|
+ | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0) as u32;
|
|
+
|
|
+ fn make_rgba_texture(host: &Host, width: u32, height: u32) -> (Arc<HostTexture>, Texture) {
|
|
+ let layout_tex = Texture::new(&TextureDesc {
|
|
+ dimension: Dimension::Tex2d,
|
|
+ format: DXGI_FORMAT_R8G8B8A8_UNORM.0 as u32,
|
|
+ width,
|
|
+ height,
|
|
+ depth_or_array: 1,
|
|
+ mips: 1,
|
|
+ samples: 1,
|
|
+ swizzle: Swizzle::LINEAR,
|
|
+ })
|
|
+ .expect("linear RGBA layout");
|
|
+ let heap = D3D12_HEAP_PROPERTIES {
|
|
+ Type: D3D12_HEAP_TYPE_DEFAULT,
|
|
+ ..Default::default()
|
|
+ };
|
|
+ let desc = D3D12_RESOURCE_DESC {
|
|
+ Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
|
+ Width: u64::from(width),
|
|
+ Height: height,
|
|
+ DepthOrArraySize: 1,
|
|
+ MipLevels: 1,
|
|
+ Format: DXGI_FORMAT_R8G8B8A8_UNORM,
|
|
+ SampleDesc: DXGI_SAMPLE_DESC {
|
|
+ Count: 1,
|
|
+ Quality: 0,
|
|
+ },
|
|
+ Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN,
|
|
+ ..Default::default()
|
|
+ };
|
|
+ let mut resource: Option<ID3D12Resource> = None;
|
|
+ // SAFETY: plain default-heap 2D texture creation on our test device.
|
|
+ unsafe {
|
|
+ host.device
|
|
+ .CreateCommittedResource(
|
|
+ &heap,
|
|
+ D3D12_HEAP_FLAG_NONE,
|
|
+ &desc,
|
|
+ D3D12_RESOURCE_STATE_COMMON,
|
|
+ None,
|
|
+ &mut resource,
|
|
+ )
|
|
+ .expect("create host texture");
|
|
+ }
|
|
+ let copy = Arc::new(HostTexture {
|
|
+ texture: resource.unwrap(),
|
|
+ state: AtomicU32::new(D3D12_RESOURCE_STATE_COMMON.0 as u32),
|
|
+ });
|
|
+ (copy, layout_tex)
|
|
+ }
|
|
+
|
|
+ /// Reads a 2D RGBA8 texture back from `host` into a tightly packed row buffer.
|
|
+ fn read_back_rgba(host: &Host, copy: &Arc<HostTexture>, width: u32, height: u32) -> Vec<u8> {
|
|
+ let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
|
|
+ let mut rows = 0u32;
|
|
+ let mut total = 0u64;
|
|
+ // SAFETY: querying footprint of a live texture.
|
|
+ let desc = unsafe { copy.texture.GetDesc() };
|
|
+ // SAFETY: single-subresource footprint query.
|
|
+ unsafe {
|
|
+ host.device.GetCopyableFootprints(
|
|
+ &desc,
|
|
+ 0,
|
|
+ 1,
|
|
+ 0,
|
|
+ Some(&mut footprint),
|
|
+ Some(&mut rows),
|
|
+ None,
|
|
+ Some(&mut total),
|
|
+ );
|
|
+ }
|
|
+ let readback_heap = D3D12_HEAP_PROPERTIES {
|
|
+ Type: D3D12_HEAP_TYPE_READBACK,
|
|
+ ..Default::default()
|
|
+ };
|
|
+ let readback_desc = D3D12_RESOURCE_DESC {
|
|
+ Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
|
+ Width: total,
|
|
+ Height: 1,
|
|
+ DepthOrArraySize: 1,
|
|
+ MipLevels: 1,
|
|
+ SampleDesc: DXGI_SAMPLE_DESC {
|
|
+ Count: 1,
|
|
+ Quality: 0,
|
|
+ },
|
|
+ Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
|
+ ..Default::default()
|
|
+ };
|
|
+ let mut readback: Option<ID3D12Resource> = None;
|
|
+ // SAFETY: plain readback buffer creation.
|
|
+ unsafe {
|
|
+ host.device
|
|
+ .CreateCommittedResource(
|
|
+ &readback_heap,
|
|
+ D3D12_HEAP_FLAG_NONE,
|
|
+ &readback_desc,
|
|
+ D3D12_RESOURCE_STATE_COPY_DEST,
|
|
+ None,
|
|
+ &mut readback,
|
|
+ )
|
|
+ .expect("create readback buffer");
|
|
+ }
|
|
+ let readback = readback.unwrap();
|
|
+ let list = host.new_list().expect("readback list");
|
|
+ let before = copy.state.load(Ordering::Relaxed);
|
|
+ let to = D3D12_TEXTURE_COPY_LOCATION {
|
|
+ // SAFETY: borrowed COM pointer for the copy call.
|
|
+ pResource: unsafe { std::mem::transmute_copy(&readback) },
|
|
+ Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
|
|
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
+ PlacedFootprint: footprint,
|
|
+ },
|
|
+ };
|
|
+ let from = D3D12_TEXTURE_COPY_LOCATION {
|
|
+ // SAFETY: borrowed COM pointer for the copy call.
|
|
+ pResource: unsafe { std::mem::transmute_copy(©.texture) },
|
|
+ Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
|
|
+ Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
|
|
+ SubresourceIndex: 0,
|
|
+ },
|
|
+ };
|
|
+ // SAFETY: recording a valid readback copy on an open list.
|
|
+ unsafe {
|
|
+ if before != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 {
|
|
+ list.list.ResourceBarrier(&[crate::host::transition(
|
|
+ ©.texture,
|
|
+ D3D12_RESOURCE_STATES(before as i32),
|
|
+ D3D12_RESOURCE_STATE_COPY_SOURCE,
|
|
+ )]);
|
|
+ }
|
|
+ list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
|
|
+ if before != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 {
|
|
+ list.list.ResourceBarrier(&[crate::host::transition(
|
|
+ ©.texture,
|
|
+ D3D12_RESOURCE_STATE_COPY_SOURCE,
|
|
+ D3D12_RESOURCE_STATES(before as i32),
|
|
+ )]);
|
|
+ }
|
|
+ }
|
|
+ list.close();
|
|
+ host.execute(&[&list]);
|
|
+
|
|
+ let mut ptr = std::ptr::null_mut();
|
|
+ // SAFETY: GPU finished writing `readback`; map for CPU read.
|
|
+ unsafe {
|
|
+ readback.Map(0, None, Some(&mut ptr)).expect("map readback");
|
|
+ let pitch = footprint.Footprint.RowPitch as usize;
|
|
+ let row_bytes = width as usize * 4;
|
|
+ let src = std::slice::from_raw_parts(ptr.cast::<u8>(), total as usize);
|
|
+ let mut out = Vec::with_capacity(row_bytes * height as usize);
|
|
+ for y in 0..height as usize {
|
|
+ let start = footprint.Offset as usize + y * pitch;
|
|
+ out.extend_from_slice(&src[start..start + row_bytes]);
|
|
+ }
|
|
+ readback.Unmap(0, None);
|
|
+ out
|
|
+ }
|
|
+ }
|
|
+
|
|
+ fn fill_linear_rgba(layout: &victory_formats::texture::Layout, mem: &mut [u8], pixel: [u8; 4]) {
|
|
+ let mut linear = vec![0u8; layout.desc.width as usize * layout.desc.height as usize * 4];
|
|
+ for chunk in linear.as_chunks_mut::<4>().0 {
|
|
+ *chunk = pixel;
|
|
+ }
|
|
+ let pitch = layout.desc.width as usize * 4;
|
|
+ layout
|
|
+ .tile(mem, 0, 0, &linear, pitch, linear.len())
|
|
+ .expect("tile pixels");
|
|
+ }
|
|
+
|
|
+ fn all_pixels_eq(bytes: &[u8], expected: [u8; 4]) -> bool {
|
|
+ let (chunks, rem) = bytes.as_chunks::<4>();
|
|
+ rem.is_empty() && !chunks.is_empty() && chunks.iter().all(|&px| px == expected)
|
|
+ }
|
|
+
|
|
+ /// Exercises the real D3D12 WARP prelude upload path end to end:
|
|
+ /// (a) initial use uploads title memory to GPU,
|
|
+ /// (b) subsequent frames with unchanged title memory record zero GPU copies,
|
|
+ /// (c) multi-list submissions after a modification upload only once,
|
|
+ /// (d) modifying title memory triggers a fresh GPU upload with new pixels.
|
|
+ #[test]
|
|
+ fn warp_skips_clean_texture_uploads_and_reuploads_on_change() {
|
|
+ let Some(host) = Host::new_warp() else {
|
|
+ return; // WARP software adapter unavailable here
|
|
+ };
|
|
+ let (width, height) = (4, 4);
|
|
+ let (copy, tex) = make_rgba_texture(&host, width, height);
|
|
+ let layout = tex.planes[0].layout.clone();
|
|
+ let mut title_mem = vec![0u8; layout.size as usize];
|
|
+ let v1 = [0x11, 0x22, 0x33, 0xff];
|
|
+ fill_linear_rgba(&layout, &mut title_mem, v1);
|
|
+
|
|
+ let staging = create_staging(
|
|
+ &host,
|
|
+ std::ptr::null(),
|
|
+ ©.texture,
|
|
+ layout.clone(),
|
|
+ title_mem.as_ptr(),
|
|
+ )
|
|
+ .expect("create staging");
|
|
+ assert_eq!(staging.gpu_uploads(), 0);
|
|
+
|
|
+ let make_sampling_list = || {
|
|
+ let list = host.new_list().expect("new list");
|
|
+ list.defer_texture(staging.clone(), copy.clone());
|
|
+ list.expect_texture_state(©, SHADER_RESOURCE);
|
|
+ list.close();
|
|
+ list
|
|
+ };
|
|
+
|
|
+ // (a) Submission 1: first use must upload onto the prelude and land on GPU.
|
|
+ let list1 = make_sampling_list();
|
|
+ host.execute(&[&list1]);
|
|
+ assert_eq!(staging.gpu_uploads(), 1, "initial use must record 1 copy");
|
|
+ assert_eq!(copy.state.load(Ordering::Relaxed), SHADER_RESOURCE);
|
|
+ assert!(all_pixels_eq(
|
|
+ &read_back_rgba(&host, ©, width, height),
|
|
+ v1
|
|
+ ));
|
|
+
|
|
+ // (b) Submission 2: unchanged title memory across two lists records ZERO copies.
|
|
+ let list2a = make_sampling_list();
|
|
+ let list2b = make_sampling_list();
|
|
+ host.execute(&[&list2a, &list2b]);
|
|
+ assert_eq!(
|
|
+ staging.gpu_uploads(),
|
|
+ 1,
|
|
+ "unchanged texture must record zero CopyTextureRegion uploads"
|
|
+ );
|
|
+ // Re-submitting the same closed list with unchanged memory also records zero copies.
|
|
+ host.execute(&[&list2a]);
|
|
+ assert_eq!(staging.gpu_uploads(), 1);
|
|
+ assert!(all_pixels_eq(
|
|
+ &read_back_rgba(&host, ©, width, height),
|
|
+ v1
|
|
+ ));
|
|
+
|
|
+ // (c) Submission 3: CPU modifies title memory; two lists sample it -> exactly 1 upload.
|
|
+ let v2 = [0xaa, 0xbb, 0xcc, 0xff];
|
|
+ fill_linear_rgba(&layout, &mut title_mem, v2);
|
|
+ let list3a = make_sampling_list();
|
|
+ let list3b = make_sampling_list();
|
|
+ host.execute(&[&list3a, &list3b]);
|
|
+ assert_eq!(
|
|
+ staging.gpu_uploads(),
|
|
+ 2,
|
|
+ "modified texture across two lists must upload exactly once"
|
|
+ );
|
|
+ assert_eq!(copy.state.load(Ordering::Relaxed), SHADER_RESOURCE);
|
|
+ assert!(all_pixels_eq(
|
|
+ &read_back_rgba(&host, ©, width, height),
|
|
+ v2
|
|
+ ));
|
|
+
|
|
+ // (d) Submission 4: unchanged again -> zero additional uploads.
|
|
+ let list4 = make_sampling_list();
|
|
+ host.execute(&[&list4]);
|
|
+ assert_eq!(staging.gpu_uploads(), 2);
|
|
+ }
|
|
+
|
|
+ /// Verifies the write-watched (`MEM_WRITE_WATCH`) dirty-tracking path on
|
|
+ /// real D3D12 WARP: first use uploads, clean frames skip, and a CPU page
|
|
+ /// write triggers a single fresh upload.
|
|
+ #[test]
|
|
+ fn warp_write_watched_texture_uploads_only_when_written() {
|
|
+ use windows_sys::Win32::System::Memory::{
|
|
+ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, VirtualFree,
|
|
+ };
|
|
+ const MEM_WRITE_WATCH: u32 = 0x20_0000;
|
|
+
|
|
+ let Some(host) = Host::new_warp() else {
|
|
+ return;
|
|
+ };
|
|
+ let (width, height) = (4, 4);
|
|
+ let (copy, tex) = make_rgba_texture(&host, width, height);
|
|
+ let layout = tex.planes[0].layout.clone();
|
|
+ let alloc_size = (layout.size as usize).max(crate::watch::PAGE);
|
|
+ // SAFETY: allocating a private write-watched page buffer freed before returning.
|
|
+ let raw = unsafe {
|
|
+ VirtualAlloc(
|
|
+ std::ptr::null(),
|
|
+ alloc_size,
|
|
+ MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
|
|
+ PAGE_READWRITE,
|
|
+ )
|
|
+ } as *mut u8;
|
|
+ assert!(!raw.is_null());
|
|
+
|
|
+ let v1 = [0x33, 0x44, 0x55, 0xff];
|
|
+ // SAFETY: `raw` is committed read-write memory of `alloc_size` bytes.
|
|
+ unsafe {
|
|
+ let mem = std::slice::from_raw_parts_mut(raw, layout.size as usize);
|
|
+ fill_linear_rgba(&layout, mem, v1);
|
|
+ }
|
|
+
|
|
+ let staging = create_staging(&host, std::ptr::null(), ©.texture, layout.clone(), raw)
|
|
+ .expect("create staging");
|
|
+
|
|
+ let run_once = || {
|
|
+ let list = host.new_list().expect("new list");
|
|
+ list.defer_texture(staging.clone(), copy.clone());
|
|
+ list.expect_texture_state(©, SHADER_RESOURCE);
|
|
+ list.close();
|
|
+ host.execute(&[&list]);
|
|
+ };
|
|
+
|
|
+ // Initial submission uploads.
|
|
+ run_once();
|
|
+ assert_eq!(staging.gpu_uploads(), 1);
|
|
+ assert!(all_pixels_eq(
|
|
+ &read_back_rgba(&host, ©, width, height),
|
|
+ v1
|
|
+ ));
|
|
+
|
|
+ // Unchanged write-watched memory skips GPU upload.
|
|
+ run_once();
|
|
+ assert_eq!(staging.gpu_uploads(), 1);
|
|
+
|
|
+ // CPU write dirties the watched page -> next submission uploads.
|
|
+ let v2 = [0xde, 0xad, 0xbe, 0xff];
|
|
+ // SAFETY: `raw` is still committed read-write memory.
|
|
+ unsafe {
|
|
+ let mem = std::slice::from_raw_parts_mut(raw, layout.size as usize);
|
|
+ fill_linear_rgba(&layout, mem, v2);
|
|
+ }
|
|
+ run_once();
|
|
+ assert_eq!(staging.gpu_uploads(), 2);
|
|
+ assert!(all_pixels_eq(
|
|
+ &read_back_rgba(&host, ©, width, height),
|
|
+ v2
|
|
+ ));
|
|
+
|
|
+ // Clean again -> zero upload.
|
|
+ run_once();
|
|
+ assert_eq!(staging.gpu_uploads(), 2);
|
|
+
|
|
+ // SAFETY: freeing our own allocation.
|
|
+ unsafe { VirtualFree(raw.cast(), 0, MEM_RELEASE) };
|
|
+ }
|
|
+
|
|
+ #[test]
|
|
+ fn host_written_texture_never_queues_cpu_upload() {
|
|
+ let Some(host) = Host::new_warp() else {
|
|
+ return;
|
|
+ };
|
|
+ let (copy, _) = make_rgba_texture(&host, 4, 4);
|
|
+ let fake_resource = 0x1234_5678usize as This;
|
|
+ host_written(fake_resource);
|
|
+ let list = host.new_list().expect("new list");
|
|
+ upload(&list, fake_resource, ©.texture);
|
|
+ assert!(
|
|
+ !list.has_deferred_work(),
|
|
+ "host-written textures must not queue CPU-to-GPU uploads"
|
|
+ );
|
|
+ forget(fake_resource as usize);
|
|
+ }
|
|
}
|