Skip to content
Closed
Show file tree
Hide file tree
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
133 changes: 125 additions & 8 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use std::sync::atomic::{AtomicU64, Ordering};

use victory_shader::emit::{AddressView, UserData};
use victory_shader::{ResourceType, RootType, UsedResource};

use crate::descriptor::View;
Expand Down Expand Up @@ -149,6 +150,23 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
Some(gpu)
}

/// Addresses below this are taken as unset (null, or no buffer): a root SRV
/// at an address in root constants is not bound there and its draw is
/// dropped.
const MIN_ADDRESS: u64 = 0x1_0000;

/// The address a root SRV at an address in root constants starts at: the
/// two constants' current values, low half first. `None` when the title has
/// not set either or the address is below [`MIN_ADDRESS`].
fn pair_address(roots: &[Root], view: &AddressView) -> Option<u64> {
let half = |u: &UserData| match roots.get(usize::from(u.slot))? {
Root::Constants(c) => c.get(u.dword as usize).copied(),
_ => None,
};
let address = u64::from(half(&view.lo)?) | u64::from(half(&view.hi)?) << 32;
(address >= MIN_ADDRESS).then_some(address)
}

macro_rules! once {
($($arg:tt)*) => {{
static ONCE: std::sync::Once = std::sync::Once::new();
Expand Down Expand Up @@ -344,7 +362,9 @@ impl State {
once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
return false;
}
self.bind(list, p, false);
if !self.bind(list, p, false) {
return false;
}
let l = &list.list;
// Vertex buffers the input layout reads.
let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
Expand Down Expand Up @@ -402,8 +422,10 @@ impl State {
/// it changed, constant data copied, textures made readable.
/// What draws and dispatches share: heaps, our root signature, the
/// pipeline, and per stage the user data, root views and the
/// descriptors its tables hold.
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) {
/// descriptors its tables hold. False if a root SRV at an address in
/// root constants has no address to bind: the draw cannot run.
fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
let mut bound = true;
let l = &list.list;
// Heaps first: a root signature with directly indexed heaps must be
// set after them.
Expand Down Expand Up @@ -488,7 +510,29 @@ impl State {
}
}
}
for &(view, param) in &stage.address_srvs {
let gpu = pair_address(self.roots_ref(compute), &view)
.and_then(|address| root_view(list, address, true));
let Some(gpu) = gpu else {
once!(
slot = view.lo.slot,
dword = view.lo.dword,
"a shader reads through an address in root constants that is unset; draw dropped"
);
bound = false;
continue;
};
// SAFETY: an open list; the address is in live memory.
unsafe {
if compute {
l.SetComputeRootShaderResourceView(param, gpu);
} else {
l.SetGraphicsRootShaderResourceView(param, gpu);
}
}
}
}
bound
}

/// Runs a dispatch on the host.
Expand All @@ -513,7 +557,12 @@ impl State {
once!("a dispatch with a graphics pipeline");
return;
}
self.bind(list, p, true);
if !self.bind(list, p, true) {
DROPPED.fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
crate::pipeline::note_drop(self.pipeline as This);
return;
}
#[cfg(feature = "diagnostics")]
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
// SAFETY: an open list with everything set.
Expand Down Expand Up @@ -553,6 +602,16 @@ impl State {
let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
}
}
for (view, _) in &stage.address_srvs {
let address = pair_address(self.roots_ref(compute), view);
let host =
address.and_then(|a| crate::shadow::find(a, 1).map(|s| (s.gpu(a), s.left(a))));
let _ = write!(
text,
" u{}:u{}={address:#x?} host {host:#x?}",
view.lo.index, view.hi.index
);
}
}
let _ = write!(text, " tables {:?}", self.reads(compute));
text
Expand Down Expand Up @@ -988,10 +1047,7 @@ impl State {
DRAW | INDEXED => self.topology != RECTANGLES && self.prepare(list, kind == INDEXED),
MESH => self.prepare_for(list, false, true),
DISPATCH => match crate::pipeline::host_pipeline(self.pipeline as This) {
Some(p) if p.compute => {
self.bind(list, p, true);
true
}
Some(p) if p.compute => self.bind(list, p, true),
_ => false,
},
_ => false,
Expand Down Expand Up @@ -1180,3 +1236,64 @@ pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
// SAFETY: an open list.
unsafe { list.list.OMSetStencilRef(reference) };
}

#[cfg(test)]
mod tests {
use super::*;

fn half(slot: u8, dword: u32) -> UserData {
UserData {
index: 0,
slot,
root: RootType::Constants,
dword,
}
}

/// The low half at dword 1 of root parameter 0, the high half at dword 0
/// of parameter 2.
fn view() -> AddressView {
AddressView {
lo: half(0, 1),
hi: half(2, 0),
}
}

fn roots(lo: u32, hi: u32) -> Vec<Root> {
vec![
Root::Constants(vec![7, lo]),
Root::None,
Root::Constants(vec![hi]),
]
}

#[test]
fn addresses_in_root_constants_are_composed_from_both_halves() {
assert_eq!(
pair_address(&roots(0x2345_0000, 1), &view()),
Some(0x1_2345_0000)
);
assert_eq!(pair_address(&roots(0x1_0000, 0), &view()), Some(0x1_0000));
}

#[test]
fn an_address_with_a_missing_half_is_unset() {
let set = roots(0x2345_0000, 1);
assert_eq!(pair_address(&set[..2], &view()), None);
let mut no_high = set.clone();
no_high[2] = Root::Constants(Vec::new());
assert_eq!(pair_address(&no_high, &view()), None);
let mut not_constants = set.clone();
not_constants[0] = Root::View(0x1_0000_0000);
assert_eq!(pair_address(&not_constants, &view()), None);
let mut short = set;
short[0] = Root::Constants(vec![7]);
assert_eq!(pair_address(&short, &view()), None);
}

#[test]
fn null_and_low_addresses_are_unset() {
assert_eq!(pair_address(&roots(0, 0), &view()), None);
assert_eq!(pair_address(&roots(0xFFFF, 0), &view()), None);
}
}
28 changes: 25 additions & 3 deletions crates/victory-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
//! title's graphics state with the translated shaders, under a root
//! signature of our own that the translated shaders' bindings define
//! (`victory_shader::emit`): per stage one block of root constants for the
//! user data, root views for the title's root views, static samplers for
//! the immediate samplers, and directly indexed heaps.
//! user data, root views for the title's root views and for addresses the
//! title passes in root constants, static samplers for the immediate
//! samplers, and directly indexed heaps.

use std::ffi::{CStr, CString};
use std::sync::Arc;

use victory_shader::emit::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
use victory_shader::emit::{
AddressView, ROOT_ADDRESS_SPACE, ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE,
};
use windows::Win32::Graphics::Direct3D::ID3DBlob;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
Expand Down Expand Up @@ -251,6 +254,10 @@ pub(crate) struct Stage {
/// Root parameters of its root views: (title root parameter, ours).
pub(crate) root_cbvs: Vec<(u8, u32)>,
pub(crate) root_srvs: Vec<(u8, u32)>,
/// Root parameters of its root SRVs at addresses in root constants:
/// (the two constants, ours), `t<n>` in [`ROOT_ADDRESS_SPACE`] for the
/// one at position n.
pub(crate) address_srvs: Vec<(AddressView, u32)>,
}

impl Stage {
Expand Down Expand Up @@ -339,6 +346,7 @@ impl HostPipeline {
user_data: None,
root_cbvs: Vec::new(),
root_srvs: Vec::new(),
address_srvs: Vec::new(),
};
let dwords = t.user_data_dwords();
if dwords > 0 {
Expand Down Expand Up @@ -382,6 +390,20 @@ impl HostPipeline {
});
}
}
for (n, &view) in t.address_srvs.iter().enumerate() {
stage.address_srvs.push((view, params.len() as u32));
params.push(D3D12_ROOT_PARAMETER1 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check D3D12's limit of 64.

Count the u32s you're pushing. Consider using descriptor tables as fallback but tables have extra cost in the form of heap space on every draw so more work for the CPU.

Make sure to log the fallback i.e "root signature over 64 DWORDs" in the code for debugging

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the limit is never reached maybe a hard cap and error instead

ParameterType: D3D12_ROOT_PARAMETER_TYPE_SRV,
Anonymous: D3D12_ROOT_PARAMETER1_0 {
Descriptor: D3D12_ROOT_DESCRIPTOR1 {
ShaderRegister: n as u32,
RegisterSpace: ROOT_ADDRESS_SPACE,
Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE,
},
},
ShaderVisibility: visibility,
});
}
for (n, s) in t.static_samplers.iter().enumerate() {
samplers.push(D3D12_STATIC_SAMPLER_DESC {
Filter: D3D12_FILTER(s.filter as i32),
Expand Down
54 changes: 44 additions & 10 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

use victory_pipeline::{Cache, Converter};
use victory_shader::emit::{HostShader, StaticSampler, UserData};
use victory_shader::emit::{AddressView, HostShader, StaticSampler, UserData};
use victory_shader::{HwStage, RootType};

static CACHE: OnceLock<Cache> = OnceLock::new();
Expand Down Expand Up @@ -175,11 +175,14 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, stage);
word(&mut out, s.dxil.len() as u32);
out.extend(&s.dxil);
word(&mut out, s.user_data.len() as u32);
for u in &s.user_data {
let user = |out: &mut Vec<u8>, u: &UserData| {
for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] {
word(&mut out, v);
word(out, v);
}
};
word(&mut out, s.user_data.len() as u32);
for u in &s.user_data {
user(&mut out, u);
}
word(&mut out, s.samplers.len() as u32);
for sampler in &s.samplers {
Expand Down Expand Up @@ -210,6 +213,11 @@ fn encode(s: &HostShader) -> Vec<u8> {
word(&mut out, slots.len() as u32);
out.extend(slots);
}
word(&mut out, s.address_srvs.len() as u32);
for view in &s.address_srvs {
user(&mut out, &view.lo);
user(&mut out, &view.hi);
}
out
}

Expand All @@ -228,6 +236,14 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
let n = self.word()? as usize;
Some(self.take(n)?.to_vec())
}
fn user(&mut self) -> Option<UserData> {
Some(UserData {
index: self.word()?,
slot: u8::try_from(self.word()?).ok()?,
root: root_type(self.word()?),
dword: self.word()?,
})
}
}
let mut r = Reader(bytes);
if r.take(4)? != MAGIC {
Expand All @@ -238,12 +254,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
let n = r.word()? as usize;
let mut user_data = Vec::with_capacity(n.min(256));
for _ in 0..n {
user_data.push(UserData {
index: r.word()?,
slot: u8::try_from(r.word()?).ok()?,
root: root_type(r.word()?),
dword: r.word()?,
});
user_data.push(r.user()?);
}
let n = r.word()? as usize;
let mut samplers = Vec::with_capacity(n.min(256));
Expand All @@ -266,6 +277,14 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
}
let root_cbvs = r.list()?;
let root_srvs = r.list()?;
let n = r.word()? as usize;
let mut address_srvs = Vec::with_capacity(n.min(256));
for _ in 0..n {
address_srvs.push(AddressView {
lo: r.user()?,
hi: r.user()?,
});
}
r.0.is_empty().then_some(HostShader {
stage,
dxil,
Expand All @@ -274,6 +293,7 @@ fn decode(bytes: &[u8]) -> Option<HostShader> {
static_samplers,
root_cbvs,
root_srvs,
address_srvs,
})
}

Expand All @@ -300,6 +320,20 @@ mod tests {
])],
root_cbvs: vec![2],
root_srvs: vec![0, 3],
address_srvs: vec![AddressView {
lo: UserData {
index: 3,
slot: 0,
root: RootType::Constants,
dword: 3,
},
hi: UserData {
index: 4,
slot: 4,
root: RootType::Constants,
dword: 0,
},
}],
}
}

Expand Down
Loading