Run Minecraft: runtime HLE, D3D12.X device on the host GPU, shader IR
Loader: map title-shipped DLLs, patch static TLS loads to slot 0, crash reporter, title paths for GetModuleFileName*. HLE: task queue and async, XUser (one offline user), system ids, title id, features, invites, game events, persistent local storage, GameInput with no devices, xmem, console audio hardware queues, life cycle (close suspends, then terminates), and a file layer with virtual drives rewritten in path-taking imports. GPU: D3D12.X device, DXGI chain, heaps, resources, fences, queues and command lists translated onto a host D3D12 device; clears, barriers, copies, resolves and PresentX into the title's window. Shaders: SGD5 reader and `victory translate`; SSA IR with node splitting for irreducible flow; structurisation removing EXEC. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
12caefe804
commit
754619f30e
61 files changed
+12775
-88
No files matched your search
@@ -7,5 +7,22 @@ rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tracing.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_LibraryLoader", "Win32_System_Threading"] }
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D12",
|
||||
"Win32_Graphics_Dxgi",
|
||||
"Win32_Graphics_Dxgi_Common",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Security",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Threading",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Descriptor heaps: zeroed memory, with handles that are plain addresses
|
||||
//! (CPU and GPU alike, as on the console).
|
||||
//!
|
||||
//! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's
|
||||
//! image and sampler descriptors, so a title that copies descriptors itself
|
||||
//! moves whole ones. Render target and depth views are ours alone; 128 bytes
|
||||
//! leaves room for whatever stride a title assumes.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
|
||||
use crate::resource::{Memory, PAGEABLE_IIDS};
|
||||
|
||||
const HEAP_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x8efb471d,
|
||||
0x616c,
|
||||
0x4f49,
|
||||
[0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct HeapDesc {
|
||||
kind: u32,
|
||||
count: u32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Heap {
|
||||
object: Object,
|
||||
desc: HeapDesc,
|
||||
memory: Memory,
|
||||
}
|
||||
|
||||
fn heap<'a>(this: This) -> &'a Heap {
|
||||
// SAFETY: called from descriptor heap methods only.
|
||||
unsafe { &*this.cast::<Heap>() }
|
||||
}
|
||||
|
||||
/// Bytes per descriptor, by heap type (views, samplers, render targets,
|
||||
/// depth).
|
||||
fn increment(kind: u32) -> Option<u32> {
|
||||
[32, 16, 128, 128].get(kind as usize).copied()
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 {
|
||||
increment(kind).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What our render target views hold: the resource and the view
|
||||
/// description, turned into a host view when a command uses them.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct RtvRecord {
|
||||
tag: u32,
|
||||
described: u32,
|
||||
pub(crate) resource: This,
|
||||
desc: [u32; 6],
|
||||
}
|
||||
const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV");
|
||||
const _: () = assert!(size_of::<RtvRecord>() <= 112);
|
||||
|
||||
impl RtvRecord {
|
||||
/// The view description in the host's type (the same layout).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn desc(
|
||||
&self,
|
||||
) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
|
||||
// SAFETY: 24 bytes in the host's layout.
|
||||
(self.described != 0).then(|| unsafe {
|
||||
(&raw const self.desc)
|
||||
.cast::<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC>()
|
||||
.read_unaligned()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Device method: records the view at `handle` (descriptor memory).
|
||||
pub(crate) extern "system" fn create_rtv(
|
||||
_: This,
|
||||
resource: This,
|
||||
desc: *const [u32; 6],
|
||||
handle: u64,
|
||||
) {
|
||||
if handle == 0 {
|
||||
return;
|
||||
}
|
||||
// SAFETY: the title passes a description or null.
|
||||
let described = unsafe { desc.as_ref() };
|
||||
let record = RtvRecord {
|
||||
tag: RTV_TAG,
|
||||
described: u32::from(described.is_some()),
|
||||
resource,
|
||||
desc: described.copied().unwrap_or_default(),
|
||||
};
|
||||
// SAFETY: the handle is a descriptor slot, at least 112 bytes.
|
||||
unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
|
||||
}
|
||||
|
||||
/// The view recorded at `handle`, if one is.
|
||||
pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
|
||||
if handle == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the handle is a descriptor slot the title passes back.
|
||||
let record = unsafe { (handle as *const RtvRecord).read_unaligned() };
|
||||
(record.tag == RTV_TAG).then_some(record)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_heap(
|
||||
_: This,
|
||||
desc: *const HeapDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1)))
|
||||
else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "descriptor heap");
|
||||
let memory = match Memory::zeroed(size, 64) {
|
||||
Ok(memory) => memory,
|
||||
Err(hr) => return hr,
|
||||
};
|
||||
let heap = Box::new(Heap {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
desc,
|
||||
memory,
|
||||
});
|
||||
object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &HEAP_IIDS).then_some(this);
|
||||
object::answer(DESCRIPTOR_HEAP, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Heap>(this)
|
||||
}
|
||||
extern "system" fn desc(this: This, out: *mut HeapDesc) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a description.
|
||||
unsafe { out.write(heap(this).desc) };
|
||||
}
|
||||
}
|
||||
/// The same address for the CPU and the GPU start.
|
||||
extern "system" fn start(this: This) -> u64 {
|
||||
heap(this).memory.address()
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, heap 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = desc as *const (); // 0x40
|
||||
f[9] = start as *const (); // 0x48 CPU
|
||||
f[10] = start as *const (); // 0x50 GPU
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
#[test]
|
||||
fn heaps_hold_count_descriptors_from_their_start() {
|
||||
let null = std::ptr::null();
|
||||
let desc = HeapDesc {
|
||||
kind: 0,
|
||||
count: 1000,
|
||||
flags: 1,
|
||||
nodes: 0,
|
||||
};
|
||||
let mut h = null;
|
||||
assert_eq!(create_heap(null, &desc, &HEAP_IIDS[0], &mut h), S_OK);
|
||||
let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
|
||||
assert_eq!(cpu % 64, 0);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
|
||||
assert_eq!(increment_size(null, 0), 32);
|
||||
// SAFETY: the heap holds 1000 descriptors of 32 bytes.
|
||||
unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) };
|
||||
assert_eq!(increment_size(null, 9), 0);
|
||||
let bad = HeapDesc { kind: 9, ..desc };
|
||||
assert_eq!(create_heap(null, &bad, &HEAP_IIDS[0], &mut h), E_INVALIDARG);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! The device titles get from device creation, laid out as their inlined
|
||||
//! code expects: the object header, then device fields. Its table starts
|
||||
//! like the PC device interface (IUnknown, the object methods, then the
|
||||
//! device methods in PC order); console additions follow. Methods we have
|
||||
//! not written log their table offset and fail, so a run shows what to
|
||||
//! write next.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
use crate::object::{
|
||||
self, E_INVALIDARG, E_NOINTERFACE, E_NOTIMPL, HRESULT, Iid, Object, S_FALSE, S_OK, Table, This,
|
||||
guid, guid_text,
|
||||
};
|
||||
use crate::{
|
||||
descriptor, dxgi, fence, frame, list, pipeline, query, queue, resource, root, signature,
|
||||
};
|
||||
|
||||
/// What D3D returns when none of the requested feature levels is supported.
|
||||
const UNSUPPORTED: HRESULT = 0x887A_0004_u32 as i32;
|
||||
|
||||
/// The device interface id (the same as on PC). Titles also import it as
|
||||
/// data.
|
||||
pub static IID: Iid = guid(
|
||||
0x189819f1,
|
||||
0x1db6,
|
||||
0x4b57,
|
||||
[0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
|
||||
);
|
||||
|
||||
/// The interface version these layouts were checked against (2.4, what
|
||||
/// Minecraft passes). Newer titles may lay objects out differently.
|
||||
pub const CHECKED_VERSION: u32 = 0x0002_0004;
|
||||
|
||||
/// Feature level 12_2, what the console hardware supports.
|
||||
const HIGHEST_FEATURE_LEVEL: u32 = 0xc200;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Device {
|
||||
object: Object,
|
||||
/// GPU address of a null constant buffer; none yet.
|
||||
null_constant_buffer: u64,
|
||||
/// Byte 0 non-zero: calls the title would otherwise inline come to the
|
||||
/// table. The rest is reserved.
|
||||
out_of_line: [u32; 16],
|
||||
}
|
||||
const _: () = assert!(size_of::<Device>() == 0x58);
|
||||
|
||||
/// One device per process, as on the console.
|
||||
pub(crate) static DEVICE: Device = Device {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
null_constant_buffer: 0,
|
||||
out_of_line: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
};
|
||||
|
||||
pub(crate) fn device() -> This {
|
||||
(&raw const DEVICE).cast()
|
||||
}
|
||||
|
||||
/// Device creation: `(adapter, parameters, iid, out)`. The parameters start
|
||||
/// with the interface version; the rest (ring and scratch sizes, features
|
||||
/// to leave out) does not matter to us yet.
|
||||
pub extern "system" fn create(
|
||||
_adapter: *const c_void,
|
||||
parameters: *const u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if parameters.is_null() || iid.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null; the title passes its parameters and an id.
|
||||
let (version, iid) = unsafe { (parameters.read(), &*iid) };
|
||||
tracing::info!(version = format_args!("{version:#x}"), "D3D12.X device");
|
||||
if version != CHECKED_VERSION {
|
||||
tracing::warn!(
|
||||
version = format_args!("{version:#x}"),
|
||||
"device layouts were checked against {CHECKED_VERSION:#x} only"
|
||||
);
|
||||
}
|
||||
if *iid != IID {
|
||||
tracing::warn!(iid = %guid_text(iid), "device created as an unknown interface");
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
if out.is_null() {
|
||||
return S_FALSE;
|
||||
}
|
||||
object::answer(object::DEVICE, iid, Some(device()), out)
|
||||
}
|
||||
|
||||
/// The device, or its DXGI side.
|
||||
extern "system" fn query_interface(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = if object::is(iid, &[IID]) {
|
||||
Some(this)
|
||||
} else if object::is(iid, &dxgi::DEVICE_IIDS) {
|
||||
Some(dxgi::device())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
object::answer(object::DEVICE, iid, found, out)
|
||||
}
|
||||
|
||||
extern "system" fn node_count(_: This) -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// Feature query 2: the highest of the requested feature levels we support.
|
||||
#[repr(C)]
|
||||
struct FeatureLevels {
|
||||
count: u32,
|
||||
requested: *const u32,
|
||||
highest: u32,
|
||||
}
|
||||
|
||||
/// Feature query 0, what an RDNA 2 GPU reports. The console's layout has
|
||||
/// one field more than PC's (index 11).
|
||||
const OPTIONS: [u32; 16] = [
|
||||
1, // double-precision shader operations
|
||||
1, // output-merger logic operations
|
||||
2, // minimum precision: 16-bit
|
||||
3, // tiled resources tier
|
||||
3, // resource binding tier
|
||||
1, // stencil reference from pixel shaders
|
||||
1, // typed UAV loads of more formats
|
||||
1, // rasterizer-ordered views
|
||||
3, // conservative rasterization tier
|
||||
40, // GPU address bits per resource
|
||||
0, // 64 KiB standard swizzle
|
||||
0, // console-only field
|
||||
0, // cross-node sharing tier
|
||||
0, // cross-adapter row-major textures
|
||||
1, // viewport and render target index from any stage
|
||||
2, // resource heap tier
|
||||
];
|
||||
|
||||
extern "system" fn check_feature_support(
|
||||
_: This,
|
||||
feature: u32,
|
||||
data: *mut c_void,
|
||||
size: u32,
|
||||
) -> HRESULT {
|
||||
const OPTIONS_QUERY: u32 = 0;
|
||||
const ARCHITECTURE: u32 = 1;
|
||||
const FEATURE_LEVELS: u32 = 2;
|
||||
const FORMAT_SUPPORT: u32 = 3;
|
||||
const MULTISAMPLE: u32 = 4;
|
||||
let expected = match feature {
|
||||
OPTIONS_QUERY => size_of_val(&OPTIONS),
|
||||
ARCHITECTURE => 16,
|
||||
FEATURE_LEVELS => size_of::<FeatureLevels>(),
|
||||
FORMAT_SUPPORT => 12,
|
||||
MULTISAMPLE => 16,
|
||||
_ => {
|
||||
tracing::warn!(feature, size, "device feature query not implemented");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
};
|
||||
if data.is_null() || size as usize != expected {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
match feature {
|
||||
OPTIONS_QUERY => {
|
||||
// SAFETY: checked size and non-null.
|
||||
unsafe { data.cast::<[u32; 16]>().write_unaligned(OPTIONS) };
|
||||
S_OK
|
||||
}
|
||||
ARCHITECTURE => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let a = unsafe { &mut *data.cast::<[u32; 4]>() };
|
||||
if a[0] != 0 {
|
||||
return E_INVALIDARG; // one node only
|
||||
}
|
||||
// Not tile-based; unified, cache-coherent memory.
|
||||
a[1..].copy_from_slice(&[0, 1, 1]);
|
||||
S_OK
|
||||
}
|
||||
FORMAT_SUPPORT => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let q = unsafe { &mut *data.cast::<[u32; 3]>() };
|
||||
// shortcut: every use of every format; answer from the host
|
||||
// device once there is one.
|
||||
q[1] = 0x7fff_ffff;
|
||||
q[2] = 0xffff;
|
||||
S_OK
|
||||
}
|
||||
MULTISAMPLE => {
|
||||
// SAFETY: checked size and non-null.
|
||||
let q = unsafe { &mut *data.cast::<[u32; 4]>() };
|
||||
// Format, sample count, flags in; one quality level out for the
|
||||
// counts the hardware has.
|
||||
q[3] = u32::from(matches!(q[1], 1 | 2 | 4 | 8));
|
||||
S_OK
|
||||
}
|
||||
_ => feature_levels(data),
|
||||
}
|
||||
}
|
||||
|
||||
fn feature_levels(data: *mut c_void) -> HRESULT {
|
||||
// SAFETY: the caller checked size and non-null.
|
||||
let query = unsafe { &mut *data.cast::<FeatureLevels>() };
|
||||
if query.requested.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: the title passes `count` levels.
|
||||
let requested = unsafe { std::slice::from_raw_parts(query.requested, query.count as usize) };
|
||||
match requested
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&l| l <= HIGHEST_FEATURE_LEVEL)
|
||||
.max()
|
||||
{
|
||||
Some(level) => {
|
||||
query.highest = level;
|
||||
S_OK
|
||||
}
|
||||
None => UNSUPPORTED,
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object methods 4, device methods 76.
|
||||
static FUNCTIONS: Table<83> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<{ object::DEVICE }, 83>());
|
||||
f[0] = query_interface as *const (); // 0x00
|
||||
f[7] = node_count as *const (); // 0x38
|
||||
f[8] = queue::create as *const (); // 0x40
|
||||
f[9] = list::create_allocator as *const (); // 0x48
|
||||
f[12] = list::create_list as *const (); // 0x60
|
||||
f[10] = pipeline::create_graphics as *const (); // 0x50
|
||||
f[11] = pipeline::create_compute as *const (); // 0x58
|
||||
f[13] = check_feature_support as *const (); // 0x68
|
||||
f[14] = descriptor::create_heap as *const (); // 0x70
|
||||
f[15] = descriptor::increment_size as *const (); // 0x78
|
||||
f[16] = root::create as *const (); // 0x80
|
||||
f[20] = descriptor::create_rtv as *const (); // 0xa0
|
||||
f[25] = resource::allocation_info as *const (); // 0xc8
|
||||
f[27] = resource::create_committed as *const (); // 0xd8
|
||||
f[28] = resource::create_heap as *const (); // 0xe0
|
||||
f[29] = resource::create_placed as *const (); // 0xe8
|
||||
f[36] = fence::create as *const (); // 0x120
|
||||
f[38] = resource::copyable_footprints as *const (); // 0x130
|
||||
f[39] = query::create as *const (); // 0x138
|
||||
f[41] = signature::create as *const (); // 0x148
|
||||
f[69] = object::ignore as *const (); // 0x228 debug error filter
|
||||
f[73] = list::create_list_x as *const (); // 0x248
|
||||
f[78] = frame::set_interval as *const (); // 0x270
|
||||
f[79] = frame::schedule as *const (); // 0x278
|
||||
f[80] = frame::wait as *const (); // 0x280
|
||||
f[81] = frame::statistics as *const (); // 0x288
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
fn create_as(iid: &Iid) -> (HRESULT, This) {
|
||||
let version = CHECKED_VERSION;
|
||||
let mut device = std::ptr::null();
|
||||
let hr = create(std::ptr::null(), &version, iid, &mut device);
|
||||
(hr, device)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creation_hands_out_the_device() {
|
||||
let (hr, device) = create_as(&IID);
|
||||
assert_eq!(hr, S_OK);
|
||||
assert_eq!(device, super::device());
|
||||
// The title tests byte 0x18 before inlining a device call.
|
||||
// SAFETY: the device is 0x58 bytes.
|
||||
assert_ne!(unsafe { device.cast::<u8>().add(0x18).read() }, 0);
|
||||
assert_eq!(create_as(&[0; 16]).0, E_NOINTERFACE);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> u32>(device, 0x38)(device),
|
||||
1
|
||||
);
|
||||
let missing = slot::<extern "system" fn() -> HRESULT>(device, 0x88);
|
||||
assert_eq!(missing(), E_NOTIMPL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feature_levels_pick_the_highest_supported() {
|
||||
type Check = extern "system" fn(This, u32, *mut c_void, u32) -> HRESULT;
|
||||
let device = device();
|
||||
let check = slot::<Check>(device, 0x68);
|
||||
let query = |levels: &[u32], size| {
|
||||
let mut query = FeatureLevels {
|
||||
count: levels.len() as u32,
|
||||
requested: levels.as_ptr(),
|
||||
highest: 0,
|
||||
};
|
||||
let hr = check(device, 2, (&raw mut query).cast(), size);
|
||||
(hr, query.highest)
|
||||
};
|
||||
let levels = [0xb000, 0xb100, 0xc000, 0xc100, 0xd000];
|
||||
assert_eq!(query(&levels, 0x18), (S_OK, 0xc100));
|
||||
assert_eq!(query(&levels, 0x10).0, E_INVALIDARG);
|
||||
assert_eq!(query(&levels[4..], 0x18).0, UNSUPPORTED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! The DXGI side of the device: one adapter with one output, reached from
|
||||
//! the device by interface query. Tables follow the PC interfaces' order
|
||||
//! (IUnknown, the object methods, then each interface's methods).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{
|
||||
self, ADAPTER, DXGI_DEVICE, E_INVALIDARG, FACTORY, HRESULT, Iid, NOT_FOUND, OUTPUT, Object,
|
||||
S_OK, Table, This, guid,
|
||||
};
|
||||
|
||||
/// The DXGI device interfaces, base first (as on PC).
|
||||
pub(crate) const DEVICE_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x54ec77fa,
|
||||
0x1377,
|
||||
0x44e6,
|
||||
[0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c],
|
||||
),
|
||||
guid(
|
||||
0x77db970f,
|
||||
0x6276,
|
||||
0x48ba,
|
||||
[0xba, 0x28, 0x07, 0x01, 0x43, 0xb4, 0x39, 0x2c],
|
||||
),
|
||||
guid(
|
||||
0x05008617,
|
||||
0xfbfd,
|
||||
0x4051,
|
||||
[0xa7, 0x90, 0x14, 0x48, 0x84, 0xb4, 0xf6, 0xa9],
|
||||
),
|
||||
];
|
||||
const ADAPTER_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x2411e7e1,
|
||||
0x12ac,
|
||||
0x4ccf,
|
||||
[0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0],
|
||||
),
|
||||
guid(
|
||||
0x29038f61,
|
||||
0x3839,
|
||||
0x4626,
|
||||
[0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05],
|
||||
),
|
||||
guid(
|
||||
0x0aa1ae0a,
|
||||
0xfa0e,
|
||||
0x4b84,
|
||||
[0x86, 0x44, 0xe0, 0x5f, 0xf8, 0xe5, 0xac, 0xb5],
|
||||
),
|
||||
];
|
||||
const FACTORY_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0x7b7166ec,
|
||||
0x21c7,
|
||||
0x44ae,
|
||||
[0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69],
|
||||
),
|
||||
guid(
|
||||
0x770aae78,
|
||||
0xf26f,
|
||||
0x4dba,
|
||||
[0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87],
|
||||
),
|
||||
guid(
|
||||
0x50c83a1c,
|
||||
0xe072,
|
||||
0x4c48,
|
||||
[0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0],
|
||||
),
|
||||
];
|
||||
const OUTPUT_IIDS: [Iid; 1] = [guid(
|
||||
0xae02eedb,
|
||||
0xc735,
|
||||
0x4690,
|
||||
[0x8d, 0x52, 0x5a, 0x8d, 0xc2, 0x02, 0x13, 0xaa],
|
||||
)];
|
||||
|
||||
static DEVICE: Object = Object::new(&DEVICE_FUNCTIONS);
|
||||
static ADAPTER_OBJECT: Object = Object::new(&ADAPTER_FUNCTIONS);
|
||||
static FACTORY_OBJECT: Object = Object::new(&FACTORY_FUNCTIONS);
|
||||
static OUTPUT_OBJECT: Object = Object::new(&OUTPUT_FUNCTIONS);
|
||||
|
||||
pub(crate) fn device() -> This {
|
||||
&DEVICE
|
||||
}
|
||||
|
||||
/// `found` if `iid` is one of `known`.
|
||||
fn query(kind: usize, iid: *const Iid, known: &[Iid], found: This, out: *mut This) -> HRESULT {
|
||||
object::answer(kind, iid, object::is(iid, known).then_some(found), out)
|
||||
}
|
||||
|
||||
/// The DXGI device also answers for the D3D12 device.
|
||||
extern "system" fn device_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
if object::is(iid, &[crate::device::IID]) {
|
||||
return object::answer(DXGI_DEVICE, iid, Some(crate::device::device()), out);
|
||||
}
|
||||
query(DXGI_DEVICE, iid, &DEVICE_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn device_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(DXGI_DEVICE, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out)
|
||||
}
|
||||
extern "system" fn device_adapter(_: This, out: *mut This) -> HRESULT {
|
||||
object::answer(DXGI_DEVICE, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out)
|
||||
}
|
||||
|
||||
extern "system" fn adapter_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(ADAPTER, iid, &ADAPTER_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn adapter_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(ADAPTER, iid, &FACTORY_IIDS, &FACTORY_OBJECT, out)
|
||||
}
|
||||
extern "system" fn adapter_outputs(_: This, index: u32, out: *mut This) -> HRESULT {
|
||||
if index != 0 {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
object::answer(ADAPTER, &OUTPUT_IIDS[0], Some(&OUTPUT_OBJECT), out)
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct AdapterDescription {
|
||||
name: [u16; 128],
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
subsystem: u32,
|
||||
revision: u32,
|
||||
dedicated_video_memory: usize,
|
||||
dedicated_system_memory: usize,
|
||||
shared_system_memory: usize,
|
||||
luid: [u32; 2],
|
||||
}
|
||||
const _: () = assert!(size_of::<AdapterDescription>() == 0x130);
|
||||
|
||||
const AMD: u32 = 0x1002;
|
||||
const GIB: usize = 1 << 30;
|
||||
|
||||
extern "system" fn adapter_description(_: This, out: *mut AdapterDescription) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let mut name = [0; 128];
|
||||
for (slot, unit) in name.iter_mut().zip("VIctory console GPU".encode_utf16()) {
|
||||
*slot = unit;
|
||||
}
|
||||
// shortcut: memory sizes are the Series X game split (10 GiB fast,
|
||||
// 3.5 GiB standard), not measured; revisit once memory is emulated.
|
||||
let description = AdapterDescription {
|
||||
name,
|
||||
vendor: AMD,
|
||||
device: 0,
|
||||
subsystem: 0,
|
||||
revision: 0,
|
||||
dedicated_video_memory: 10 * GIB,
|
||||
dedicated_system_memory: 0,
|
||||
shared_system_memory: 7 * GIB / 2,
|
||||
luid: [1, 0],
|
||||
};
|
||||
// SAFETY: checked non-null; the title passes room for the description.
|
||||
unsafe { out.write(description) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn factory_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(FACTORY, iid, &FACTORY_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn factory_adapters(_: This, index: u32, out: *mut This) -> HRESULT {
|
||||
if index != 0 {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
object::answer(FACTORY, &ADAPTER_IIDS[0], Some(&ADAPTER_OBJECT), out)
|
||||
}
|
||||
|
||||
extern "system" fn output_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(OUTPUT, iid, &OUTPUT_IIDS, this, out)
|
||||
}
|
||||
extern "system" fn output_parent(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
query(OUTPUT, iid, &ADAPTER_IIDS, &ADAPTER_OBJECT, out)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device 5 + 2 + 3.
|
||||
static DEVICE_FUNCTIONS: Table<17> = {
|
||||
let mut f = object::missing_table::<DXGI_DEVICE, 17>();
|
||||
f[0] = device_query as *const ();
|
||||
f[6] = device_parent as *const (); // 0x30
|
||||
f[7] = device_adapter as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, adapter 3 + 1 + 1.
|
||||
static ADAPTER_FUNCTIONS: Table<12> = {
|
||||
let mut f = object::missing_table::<ADAPTER, 12>();
|
||||
f[0] = adapter_query as *const ();
|
||||
f[6] = adapter_parent as *const (); // 0x30
|
||||
f[7] = adapter_outputs as *const (); // 0x38
|
||||
f[8] = adapter_description as *const (); // 0x40
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, factory 5 + 2 + 11.
|
||||
static FACTORY_FUNCTIONS: Table<25> = {
|
||||
let mut f = object::missing_table::<FACTORY, 25>();
|
||||
f[0] = factory_query as *const ();
|
||||
f[7] = factory_adapters as *const (); // 0x38
|
||||
f[12] = factory_adapters as *const (); // 0x60, the same for version 1
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, output 15 (12 as on PC, then 3 console ones).
|
||||
static OUTPUT_FUNCTIONS: Table<22> = {
|
||||
let mut f = object::missing_table::<OUTPUT, 22>();
|
||||
f[0] = output_query as *const ();
|
||||
f[6] = output_parent as *const (); // 0x30
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{E_NOINTERFACE, slot};
|
||||
|
||||
type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT;
|
||||
type Get = extern "system" fn(This, *mut This) -> HRESULT;
|
||||
type Indexed = extern "system" fn(This, u32, *mut This) -> HRESULT;
|
||||
type Describe = extern "system" fn(This, *mut AdapterDescription) -> HRESULT;
|
||||
|
||||
/// Minecraft's startup: device → DXGI device (newest first) → adapter →
|
||||
/// description, factory, first output.
|
||||
#[test]
|
||||
fn startup_walks_from_device_to_output() {
|
||||
let d3d = crate::device::device();
|
||||
let newest_pc = guid(
|
||||
0x6007896c,
|
||||
0x3244,
|
||||
0x4afd,
|
||||
[0xbf, 0x18, 0xa6, 0xd3, 0xbe, 0xda, 0x50, 0x23],
|
||||
);
|
||||
let mut dxgi = std::ptr::null();
|
||||
let qi = slot::<Query>(d3d, 0);
|
||||
assert_eq!(qi(d3d, &newest_pc, &mut dxgi), E_NOINTERFACE);
|
||||
assert!(dxgi.is_null());
|
||||
assert_eq!(qi(d3d, &DEVICE_IIDS[2], &mut dxgi), S_OK);
|
||||
assert_eq!(dxgi, device());
|
||||
|
||||
let mut adapter = std::ptr::null();
|
||||
assert_eq!(slot::<Get>(dxgi, 0x38)(dxgi, &mut adapter), S_OK);
|
||||
let mut description = std::mem::MaybeUninit::<AdapterDescription>::uninit();
|
||||
assert_eq!(
|
||||
slot::<Describe>(adapter, 0x40)(adapter, description.as_mut_ptr()),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: written above.
|
||||
assert_eq!(unsafe { description.assume_init() }.vendor, AMD);
|
||||
|
||||
let mut factory = std::ptr::null();
|
||||
let parent = slot::<Query>(adapter, 0x30);
|
||||
assert_eq!(parent(adapter, &FACTORY_IIDS[2], &mut factory), S_OK);
|
||||
let mut again = std::ptr::null();
|
||||
assert_eq!(slot::<Indexed>(factory, 0x38)(factory, 0, &mut again), S_OK);
|
||||
assert_eq!(again, adapter);
|
||||
|
||||
let mut output = std::ptr::null();
|
||||
let outputs = slot::<Indexed>(adapter, 0x38);
|
||||
assert_eq!(outputs(adapter, 0, &mut output), S_OK);
|
||||
assert!(!output.is_null());
|
||||
assert_eq!(outputs(adapter, 1, &mut output), NOT_FOUND);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Fences: a 64-bit value and the events waiting for it. Nothing runs on a
|
||||
//! GPU yet, so only signals (the title's, later our queues') move one.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
pub(crate) const FENCE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0a753dcf,
|
||||
0xc4d8,
|
||||
0x4b91,
|
||||
[0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
struct Fence {
|
||||
object: Object,
|
||||
value: AtomicU64,
|
||||
/// Events to set once the value reaches theirs (handles as integers).
|
||||
waiters: Mutex<Vec<(u64, usize)>>,
|
||||
}
|
||||
|
||||
fn fence<'a>(this: This) -> &'a Fence {
|
||||
// SAFETY: called from fence methods only.
|
||||
unsafe { &*this.cast::<Fence>() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
initial: u64,
|
||||
flags: u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
tracing::debug!(initial, flags, "fence");
|
||||
let fence = Box::new(Fence {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
value: AtomicU64::new(initial),
|
||||
waiters: Mutex::new(Vec::new()),
|
||||
});
|
||||
object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
|
||||
}
|
||||
|
||||
fn set_event(event: usize) {
|
||||
#[cfg(windows)]
|
||||
// SAFETY: the title passed an event handle.
|
||||
unsafe {
|
||||
windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void)
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let _ = event;
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
FENCE,
|
||||
iid,
|
||||
object::is(iid, &FENCE_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Fence>(this)
|
||||
}
|
||||
extern "system" fn completed(this: This) -> u64 {
|
||||
fence(this).value.load(Ordering::Acquire)
|
||||
}
|
||||
extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
|
||||
let fence = fence(this);
|
||||
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if fence.value.load(Ordering::Acquire) >= value {
|
||||
if !event.is_null() {
|
||||
set_event(event as usize);
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
if event.is_null() {
|
||||
// shortcut: a null event means "block until reached"; nothing can
|
||||
// reach it while no GPU work runs, so fail instead of hanging.
|
||||
tracing::warn!(value, "blocking fence wait not implemented");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
waiters.push((value, event as usize));
|
||||
S_OK
|
||||
}
|
||||
pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
|
||||
let fence = fence(this);
|
||||
let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
|
||||
fence.value.store(value, Ordering::Release);
|
||||
waiters.retain(|&(wanted, event)| {
|
||||
let reached = wanted <= value;
|
||||
if reached {
|
||||
set_event(event);
|
||||
}
|
||||
!reached
|
||||
});
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, fence 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<FENCE, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = completed as *const (); // 0x40
|
||||
f[9] = set_event_on_completion as *const (); // 0x48
|
||||
f[10] = signal as *const (); // 0x50
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn signals_set_waiting_events() {
|
||||
use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
|
||||
|
||||
let mut f = std::ptr::null();
|
||||
assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 1);
|
||||
// SAFETY: plain auto-reset event.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
|
||||
assert!(!event.is_null());
|
||||
let wait = slot::<extern "system" fn(This, u64, *mut c_void) -> HRESULT>(f, 0x48);
|
||||
let signal = slot::<extern "system" fn(This, u64) -> HRESULT>(f, 0x50);
|
||||
assert_eq!(wait(f, 5, event), S_OK);
|
||||
// SAFETY: a valid event.
|
||||
assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(signal(f, 5), S_OK);
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(wait(f, 5, event), S_OK, "already reached");
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
|
||||
assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
|
||||
// SAFETY: ours.
|
||||
unsafe { CloseHandle(event) };
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//! Frame pacing: the title sets a frame interval and waits for each frame
|
||||
//! to begin. Ours is a clock started by the first interval set, ticking
|
||||
//! once per interval; the token is the frame number.
|
||||
//!
|
||||
//! shortcut: event offsets and display events are not told apart (all
|
||||
//! waits end on the next tick); tie the clock to presentation once frames
|
||||
//! reach the screen.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::object::{HRESULT, S_OK, This};
|
||||
|
||||
/// `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`.
|
||||
const TIMEOUT: HRESULT = 0x8007_0102_u32 as i32;
|
||||
const SIXTIETH: Duration = Duration::from_micros(16_667);
|
||||
|
||||
struct Clock {
|
||||
start: Instant,
|
||||
interval: Duration,
|
||||
}
|
||||
|
||||
static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
|
||||
static FRAME: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn clock() -> std::sync::MutexGuard<'static, Option<Clock>> {
|
||||
CLOCK.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Device method: `periods` intervals of `length` microseconds per frame.
|
||||
pub(crate) extern "system" fn set_interval(
|
||||
_: This,
|
||||
_output: This,
|
||||
length: u32,
|
||||
periods: u32,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
let interval = match u64::from(length) * u64::from(periods.max(1)) {
|
||||
0 => SIXTIETH,
|
||||
us => Duration::from_micros(us),
|
||||
};
|
||||
tracing::info!(?interval, "frame interval");
|
||||
let mut clock = clock();
|
||||
match clock.as_mut() {
|
||||
Some(c) => c.interval = interval,
|
||||
None => {
|
||||
*clock = Some(Clock {
|
||||
start: Instant::now(),
|
||||
interval,
|
||||
})
|
||||
}
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Device method: events are scheduled at every tick.
|
||||
pub(crate) extern "system" fn schedule(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
_offset: u32,
|
||||
_list: *const u8,
|
||||
_flags: u32,
|
||||
) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// How long until the next tick.
|
||||
fn until_next_tick() -> Duration {
|
||||
let mut clock = clock();
|
||||
let c = clock.get_or_insert_with(|| Clock {
|
||||
start: Instant::now(),
|
||||
interval: SIXTIETH,
|
||||
});
|
||||
let elapsed = c.start.elapsed().as_nanos();
|
||||
let interval = c.interval.as_nanos().max(1);
|
||||
let next = (elapsed / interval + 1) * interval;
|
||||
Duration::from_nanos((next - elapsed) as u64)
|
||||
}
|
||||
|
||||
/// Device method: blocks until the next tick, then hands out the frame's
|
||||
/// token.
|
||||
pub(crate) extern "system" fn wait(
|
||||
_: This,
|
||||
_kind: u32,
|
||||
timeout_ms: u32,
|
||||
_list: *const u8,
|
||||
_flags: u32,
|
||||
token: *mut u64,
|
||||
) -> HRESULT {
|
||||
let wait = until_next_tick();
|
||||
let limit = Duration::from_millis(u64::from(timeout_ms));
|
||||
if wait > limit {
|
||||
std::thread::sleep(limit);
|
||||
return TIMEOUT;
|
||||
}
|
||||
std::thread::sleep(wait);
|
||||
let frame = FRAME.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if !token.is_null() {
|
||||
// SAFETY: checked non-null; the title passes its token.
|
||||
unsafe { token.write(frame) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Device method: no statistics are kept, so none are returned.
|
||||
pub(crate) extern "system" fn statistics(
|
||||
_: This,
|
||||
_token: u64,
|
||||
_kinds: u32,
|
||||
count: *mut u32,
|
||||
_out: *mut u8,
|
||||
) -> HRESULT {
|
||||
if !count.is_null() {
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { count.write(0) };
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn waits_end_on_ticks_and_count_frames() {
|
||||
let null = std::ptr::null();
|
||||
assert_eq!(set_interval(null, null, 2_000, 1, 0), S_OK);
|
||||
let mut first = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut first), S_OK);
|
||||
let before = Instant::now();
|
||||
let mut second = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
|
||||
assert!(second > first);
|
||||
assert!(before.elapsed() <= Duration::from_millis(50));
|
||||
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,603 @@
|
||||
//! The host GPU: one D3D12 device and direct queue (decision 0007), and a
|
||||
//! window to present on.
|
||||
//!
|
||||
//! shortcut: every submission is waited for, so CPU and GPU never overlap;
|
||||
//! overlap them with per-submission fences once more than clears run.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
|
||||
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows::Win32::Graphics::Dxgi::*;
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
|
||||
use windows::Win32::UI::WindowsAndMessaging::*;
|
||||
use windows::core::{Interface, PCWSTR, w};
|
||||
|
||||
/// Resource states without the console's own bits (compression hints from
|
||||
/// bit 25 up), which the host rejects.
|
||||
pub(crate) fn pc_state(state: u32) -> u32 {
|
||||
state & 0x01ff_ffff
|
||||
}
|
||||
|
||||
/// A console state as a host texture state: PC bits only, and none of the
|
||||
/// buffer-only ones the console allows on textures (vertex, constant and
|
||||
/// index buffer, stream out, indirect arguments, as in "generic read").
|
||||
pub(crate) fn texture_state(state: u32) -> u32 {
|
||||
const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
|
||||
pc_state(state) & !BUFFER_ONLY
|
||||
}
|
||||
|
||||
/// Render target views live only until their command is recorded, so a
|
||||
/// ring of host descriptors is enough.
|
||||
const RTV_RING: u32 = 1024;
|
||||
|
||||
pub(crate) struct Host {
|
||||
pub(crate) device: ID3D12Device,
|
||||
queue: ID3D12CommandQueue,
|
||||
fence: ID3D12Fence,
|
||||
/// The last value signalled on `fence`, behind the submission lock.
|
||||
submitted: Mutex<u64>,
|
||||
event: HANDLE,
|
||||
rtvs: ID3D12DescriptorHeap,
|
||||
rtv_size: u32,
|
||||
/// With `VICTORY_D3D12_DEBUG` set: the debug layer's messages.
|
||||
messages: Option<ID3D12InfoQueue>,
|
||||
next_rtv: AtomicU32,
|
||||
presenter: Mutex<Option<Presenter>>,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 devices, queues, fences and descriptor heaps are
|
||||
// free-threaded; the event handle is only waited on under `submitted`.
|
||||
unsafe impl Send for Host {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for Host {}
|
||||
|
||||
/// The host GPU, created on first use; `None` without one (a run then
|
||||
/// behaves as before: nothing executes).
|
||||
pub(crate) fn host() -> Option<&'static Host> {
|
||||
static HOST: OnceLock<Option<Host>> = OnceLock::new();
|
||||
HOST.get_or_init(|| match create() {
|
||||
Ok(host) => Some(host),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
|
||||
None
|
||||
}
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
fn create() -> windows::core::Result<Host> {
|
||||
// SAFETY: plain D3D12 object creation with valid descriptions.
|
||||
unsafe {
|
||||
let debug = std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
|
||||
if debug {
|
||||
let mut layer: Option<ID3D12Debug> = None;
|
||||
match D3D12GetDebugInterface(&mut layer) {
|
||||
Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()),
|
||||
Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
|
||||
}
|
||||
}
|
||||
let mut device: Option<ID3D12Device> = None;
|
||||
D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
|
||||
let device = device.ok_or_else(windows::core::Error::empty)?;
|
||||
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);
|
||||
tracing::info!("host D3D12 device ready");
|
||||
Ok(Host {
|
||||
device,
|
||||
queue,
|
||||
fence,
|
||||
submitted: Mutex::new(0),
|
||||
event,
|
||||
rtvs,
|
||||
rtv_size,
|
||||
messages,
|
||||
next_rtv: AtomicU32::new(0),
|
||||
presenter: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A host command list and its allocator, always used together.
|
||||
pub(crate) struct HostList {
|
||||
allocator: ID3D12CommandAllocator,
|
||||
pub(crate) list: ID3D12GraphicsCommandList,
|
||||
/// Work for submission time, in recorded order.
|
||||
deferred: Mutex<Deferred>,
|
||||
/// Set when closing failed: the list must not run until reset.
|
||||
broken: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
/// What a list does on the CPU when it is submitted: copies between host
|
||||
/// memory regions (title buffers and upload buffers), and the upload
|
||||
/// buffers its GPU copies read, kept until the list is reset.
|
||||
#[derive(Default)]
|
||||
struct Deferred {
|
||||
/// Destination, source, bytes.
|
||||
copies: Vec<(usize, usize, usize)>,
|
||||
uploads: Vec<ID3D12Resource>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// A new list, open for recording.
|
||||
pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
|
||||
// SAFETY: plain object creation.
|
||||
unsafe {
|
||||
let allocator: ID3D12CommandAllocator = self
|
||||
.device
|
||||
.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
|
||||
let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
|
||||
0,
|
||||
D3D12_COMMAND_LIST_TYPE_DIRECT,
|
||||
&allocator,
|
||||
None,
|
||||
)?;
|
||||
Ok(HostList {
|
||||
allocator,
|
||||
list,
|
||||
deferred: Mutex::default(),
|
||||
broken: Default::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs closed lists and waits for them.
|
||||
pub(crate) fn execute(&self, lists: &[&HostList]) {
|
||||
// A list that failed to close would remove the device.
|
||||
let lists: Vec<&HostList> = lists
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|l| !l.broken.load(Ordering::Relaxed))
|
||||
.collect();
|
||||
for list in &lists {
|
||||
list.run_deferred();
|
||||
}
|
||||
let lists: Vec<Option<ID3D12CommandList>> =
|
||||
lists.iter().map(|l| l.list.cast().ok()).collect();
|
||||
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*submitted += 1;
|
||||
// SAFETY: closed lists; the fence and event are ours.
|
||||
unsafe {
|
||||
self.queue.ExecuteCommandLists(&lists);
|
||||
let waited = self
|
||||
.queue
|
||||
.Signal(&self.fence, *submitted)
|
||||
.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
|
||||
match waited {
|
||||
Ok(()) => {
|
||||
WaitForSingleObject(self.event, INFINITE);
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
|
||||
}
|
||||
}
|
||||
self.log_messages();
|
||||
}
|
||||
|
||||
/// Moves the debug layer's messages into our log.
|
||||
pub(crate) fn log_messages(&self) {
|
||||
let Some(queue) = &self.messages else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: each message is read into a buffer of the size the queue
|
||||
// reports, then the queue is emptied.
|
||||
unsafe {
|
||||
for i in 0..queue.GetNumStoredMessages() {
|
||||
let mut size = 0;
|
||||
if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut buffer = vec![0u64; size.div_ceil(8)];
|
||||
let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
|
||||
if queue.GetMessage(i, Some(message), &mut size).is_ok() {
|
||||
let m = &*message;
|
||||
let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
|
||||
let text = String::from_utf8_lossy(text);
|
||||
tracing::warn!(
|
||||
id = m.ID.0,
|
||||
severity = m.Severity.0,
|
||||
"D3D12: {}",
|
||||
text.trim_end_matches('\0')
|
||||
);
|
||||
}
|
||||
}
|
||||
queue.ClearStoredMessages();
|
||||
}
|
||||
}
|
||||
|
||||
/// A host render target view of `resource`, valid until it is recorded.
|
||||
pub(crate) fn rtv(
|
||||
&self,
|
||||
resource: &ID3D12Resource,
|
||||
desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
|
||||
) -> D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
|
||||
// SAFETY: a slot of our heap and a live resource.
|
||||
unsafe {
|
||||
let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
|
||||
handle.ptr += (slot * self.rtv_size) as usize;
|
||||
self.device
|
||||
.CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
|
||||
handle
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HostList {
|
||||
pub(crate) fn close(&self) {
|
||||
// SAFETY: our list.
|
||||
if let Err(e) = unsafe { self.list.Close() } {
|
||||
self.broken.store(true, Ordering::Relaxed);
|
||||
tracing::warn!(error = %e, "host command list did not close");
|
||||
if let Some(host) = host() {
|
||||
host.log_messages();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Only after the list's last submission finished (every one is waited
|
||||
/// for).
|
||||
pub(crate) fn reset(&self) {
|
||||
*self.deferred() = Deferred::default();
|
||||
self.broken.store(false, Ordering::Relaxed);
|
||||
// SAFETY: the list is not executing.
|
||||
let reset = unsafe {
|
||||
self.allocator
|
||||
.Reset()
|
||||
.and_then(|()| self.list.Reset(&self.allocator, None))
|
||||
};
|
||||
if let Err(e) = reset {
|
||||
tracing::warn!(error = %e, "host command list did not reset");
|
||||
}
|
||||
}
|
||||
|
||||
fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
|
||||
self.deferred.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Copies `len` bytes from `src` to `dst` when the list is submitted.
|
||||
pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
|
||||
self.deferred()
|
||||
.copies
|
||||
.push((dst as usize, src as usize, len));
|
||||
}
|
||||
|
||||
/// A mapped upload buffer of `size` bytes, alive until the list is
|
||||
/// reset.
|
||||
///
|
||||
/// shortcut: one buffer per copy; pool them once uploads are frequent.
|
||||
pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let (buffer, data) = host.upload_buffer(size)?;
|
||||
self.deferred().uploads.push(buffer.clone());
|
||||
Some((buffer, data))
|
||||
}
|
||||
|
||||
fn run_deferred(&self) {
|
||||
for &(dst, src, len) in &self.deferred().copies {
|
||||
// SAFETY: both ranges were checked against their resources when
|
||||
// recorded; titles keep resources alive until their work ends.
|
||||
unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// A buffer in the upload heap, mapped for writing.
|
||||
fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_UPLOAD,
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: size.max(1),
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
..Default::default()
|
||||
};
|
||||
let mut buffer: Option<ID3D12Resource> = None;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: plain creation and mapping of an upload buffer.
|
||||
let made = unsafe {
|
||||
self.device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
None,
|
||||
&mut buffer,
|
||||
)
|
||||
.and_then(|()| {
|
||||
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
|
||||
b.Map(0, None, Some(&mut data))
|
||||
})
|
||||
};
|
||||
match made {
|
||||
Ok(()) => Some((buffer?, data.cast())),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, size, "no upload buffer");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The swap chain formats a presented texture can be copied into: its own
|
||||
/// family's.
|
||||
fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
|
||||
Some(match format.0 {
|
||||
27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
const BUFFERS: u32 = 2;
|
||||
|
||||
struct Presenter {
|
||||
swap_chain: IDXGISwapChain3,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: DXGI_FORMAT,
|
||||
copy: HostList,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// Shows `texture`, which is in `state` (a host state) and stays in it.
|
||||
pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32) {
|
||||
// SAFETY: a live resource.
|
||||
let desc = unsafe { texture.GetDesc() };
|
||||
let Some(format) = swap_format(desc.Format) else {
|
||||
tracing::warn!(format = desc.Format.0, "cannot present this format");
|
||||
return;
|
||||
};
|
||||
let (width, height) = (desc.Width as u32, desc.Height);
|
||||
let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if presenter.is_none() {
|
||||
*presenter = match self.presenter(width, height, format) {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no swap chain");
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(p) = presenter.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if (p.width, p.height, p.format) != (width, height, format) {
|
||||
// SAFETY: no back buffer is held; every submission was waited for.
|
||||
let resized = unsafe {
|
||||
p.swap_chain
|
||||
.ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
|
||||
};
|
||||
match resized {
|
||||
Ok(()) => (p.width, p.height, p.format) = (width, height, format),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, width, height, "swap chain not resized");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let state = D3D12_RESOURCE_STATES(state as i32);
|
||||
// SAFETY: our swap chain, list and a live source texture.
|
||||
unsafe {
|
||||
let index = p.swap_chain.GetCurrentBackBufferIndex();
|
||||
let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
|
||||
return;
|
||||
};
|
||||
p.copy.reset();
|
||||
let list = &p.copy.list;
|
||||
list.ResourceBarrier(&[
|
||||
transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
|
||||
transition(
|
||||
&back,
|
||||
D3D12_RESOURCE_STATE_PRESENT,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
),
|
||||
]);
|
||||
list.CopyResource(&back, texture);
|
||||
list.ResourceBarrier(&[
|
||||
transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
|
||||
transition(
|
||||
&back,
|
||||
D3D12_RESOURCE_STATE_COPY_DEST,
|
||||
D3D12_RESOURCE_STATE_PRESENT,
|
||||
),
|
||||
]);
|
||||
p.copy.close();
|
||||
self.execute(&[&p.copy]);
|
||||
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
|
||||
}
|
||||
}
|
||||
|
||||
fn presenter(
|
||||
&self,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: DXGI_FORMAT,
|
||||
) -> windows::core::Result<Presenter> {
|
||||
let hwnd = match title_window() {
|
||||
Some(hwnd) => hwnd,
|
||||
None => window(width, height)?,
|
||||
};
|
||||
// SAFETY: plain object creation for our window.
|
||||
unsafe {
|
||||
let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
|
||||
let desc = DXGI_SWAP_CHAIN_DESC1 {
|
||||
Width: width,
|
||||
Height: height,
|
||||
Format: format,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
|
||||
BufferCount: BUFFERS,
|
||||
SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
|
||||
..Default::default()
|
||||
};
|
||||
let swap_chain = factory
|
||||
.CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
|
||||
.cast::<IDXGISwapChain3>()?;
|
||||
let copy = self.new_list()?;
|
||||
copy.close();
|
||||
tracing::info!(width, height, format = format.0, "presenting to a window");
|
||||
Ok(Presenter {
|
||||
swap_chain,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
copy,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A visible top-level window of this process: the one the title made, if
|
||||
/// it made one.
|
||||
fn title_window() -> Option<HWND> {
|
||||
extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
|
||||
let mut process = 0;
|
||||
// SAFETY: a window handle from the enumeration; `found` is ours.
|
||||
unsafe {
|
||||
GetWindowThreadProcessId(hwnd, Some(&mut process));
|
||||
if process == windows::Win32::System::Threading::GetCurrentProcessId()
|
||||
&& IsWindowVisible(hwnd).as_bool()
|
||||
{
|
||||
*(found.0 as *mut Option<HWND>) = Some(hwnd);
|
||||
return false.into();
|
||||
}
|
||||
}
|
||||
true.into()
|
||||
}
|
||||
let mut found: Option<HWND> = None;
|
||||
// SAFETY: the callback only writes `found`, which outlives the call.
|
||||
let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
|
||||
found
|
||||
}
|
||||
|
||||
pub(crate) fn transition(
|
||||
resource: &ID3D12Resource,
|
||||
before: D3D12_RESOURCE_STATES,
|
||||
after: D3D12_RESOURCE_STATES,
|
||||
) -> D3D12_RESOURCE_BARRIER {
|
||||
D3D12_RESOURCE_BARRIER {
|
||||
Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
|
||||
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
|
||||
Anonymous: D3D12_RESOURCE_BARRIER_0 {
|
||||
Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
|
||||
// SAFETY: a borrowed pointer; the barrier never releases it.
|
||||
pResource: unsafe { std::mem::transmute_copy(resource) },
|
||||
Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
|
||||
StateBefore: before,
|
||||
StateAfter: after,
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// A window of the given client size, owned by its own message thread.
|
||||
fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("victory-window".into())
|
||||
.spawn(move || {
|
||||
let made = make_window(width, height);
|
||||
let ok = made.is_ok();
|
||||
let _ = sender.send(made.map(|h| h.0 as usize));
|
||||
if ok {
|
||||
pump();
|
||||
}
|
||||
})
|
||||
.map_err(|_| windows::core::Error::empty())?;
|
||||
let hwnd = receiver
|
||||
.recv()
|
||||
.map_err(|_| windows::core::Error::empty())??;
|
||||
Ok(HWND(hwnd as *mut _))
|
||||
}
|
||||
|
||||
extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
) -> LRESULT {
|
||||
// SAFETY: the default handling for our window.
|
||||
unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
|
||||
}
|
||||
|
||||
fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
|
||||
const CLASS: PCWSTR = w!("VIctory");
|
||||
// SAFETY: registers our class once and creates a window of it.
|
||||
unsafe {
|
||||
let instance = GetModuleHandleW(None)?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
hCursor: LoadCursorW(None, IDC_ARROW)?,
|
||||
..Default::default()
|
||||
};
|
||||
RegisterClassExW(&class);
|
||||
let mut rect = RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: width as i32,
|
||||
bottom: height as i32,
|
||||
};
|
||||
AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
|
||||
CreateWindowExW(
|
||||
WINDOW_EX_STYLE(0),
|
||||
CLASS,
|
||||
w!("VIctory"),
|
||||
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
|
||||
CW_USEDEFAULT,
|
||||
CW_USEDEFAULT,
|
||||
rect.right - rect.left,
|
||||
rect.bottom - rect.top,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn pump() {
|
||||
let mut message = MSG::default();
|
||||
// SAFETY: the standard message loop of this thread's window.
|
||||
unsafe {
|
||||
while GetMessageW(&mut message, None, 0, 0).as_bool() {
|
||||
let _ = TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,31 @@
|
||||
//! D3D12.X on host D3D12.
|
||||
//!
|
||||
//! D3D12.X records many commands by writing command-processor packets into
|
||||
//! command lists from code inlined into the title itself, so no import-level
|
||||
//! hook sees them. This crate decodes those packet streams at
|
||||
//! `ExecuteCommandLists` time and replays them on host D3D12, and maps the
|
||||
//! title's GPU virtual addresses (console memory is unified) to host
|
||||
//! resources.
|
||||
//! D3D12.X records commands from code inlined into the title, which writes
|
||||
//! packets into the command list while its put pointer is below a limit and
|
||||
//! calls the list's method otherwise. Our lists keep the limits at zero, so
|
||||
//! every command arrives here as a call, to be run on host D3D12. The
|
||||
//! title's GPU addresses are CPU addresses (console memory is unified).
|
||||
//!
|
||||
//! Planned modules: `packets` (stream decoder), `memory` (title GPU
|
||||
//! addresses to host heaps), `pipeline` (PSOs from `victory-shader` output),
|
||||
//! `present` (swap chain, frame pacing).
|
||||
//! [`device`] is the device object titles create, [`dxgi`] its adapter side,
|
||||
//! [`resource`] heaps and resources, [`fence`] fences, [`queue`] command
|
||||
//! queues, [`list`] command allocators and lists, [`descriptor`]
|
||||
//! descriptor heaps, [`root`] root signatures, [`query`] query heaps,
|
||||
//! [`signature`] command signatures, [`pipeline`] pipeline states,
|
||||
//! [`frame`] frame pacing, [`object`] what all console graphics objects
|
||||
//! share. Planned: `present` (swap chain).
|
||||
|
||||
pub mod descriptor;
|
||||
pub mod device;
|
||||
pub mod dxgi;
|
||||
pub mod fence;
|
||||
pub mod frame;
|
||||
#[cfg(windows)]
|
||||
mod host;
|
||||
pub mod list;
|
||||
pub mod object;
|
||||
pub mod pipeline;
|
||||
pub mod query;
|
||||
pub mod queue;
|
||||
pub mod resource;
|
||||
pub mod root;
|
||||
pub mod signature;
|
||||
@@ -0,0 +1,678 @@
|
||||
//! Command allocators and command lists.
|
||||
//!
|
||||
//! The title's inlined code writes packets into a list only while its put
|
||||
//! pointer is below a limit, and calls the list's method otherwise. Our
|
||||
//! lists keep the pointer and every limit at zero, so every command reaches
|
||||
//! the table as a call.
|
||||
//!
|
||||
//! shortcut: the methods record nothing yet; unwritten ones log once, so a
|
||||
//! run lists what to translate. Translate them onto host command lists
|
||||
//! (TODO.md, GPU).
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::mem::offset_of;
|
||||
|
||||
use crate::object::{
|
||||
self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const ALLOCATOR_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x6102dee4,
|
||||
0xaf59,
|
||||
0x4b09,
|
||||
[0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
/// The list interfaces whose ids are the same as on PC, then the device
|
||||
/// child's.
|
||||
const LIST_IIDS: [Iid; 8] = [
|
||||
guid(
|
||||
0x7116d91c,
|
||||
0xe7e4,
|
||||
0x47ce,
|
||||
[0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5],
|
||||
),
|
||||
guid(
|
||||
0x5b160d0f,
|
||||
0xac1b,
|
||||
0x4185,
|
||||
[0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
|
||||
),
|
||||
guid(
|
||||
0x553103fb,
|
||||
0x1fe7,
|
||||
0x4557,
|
||||
[0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7],
|
||||
),
|
||||
guid(
|
||||
0x38c3e585,
|
||||
0xff17,
|
||||
0x412c,
|
||||
[0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28],
|
||||
),
|
||||
guid(
|
||||
0x6fda83a7,
|
||||
0xb84c,
|
||||
0x4e38,
|
||||
[0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d],
|
||||
),
|
||||
guid(
|
||||
0x8754318e,
|
||||
0xd3a9,
|
||||
0x4541,
|
||||
[0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
|
||||
),
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
struct Allocator {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
}
|
||||
|
||||
/// The layout the title's inlined code reads.
|
||||
#[repr(C)]
|
||||
struct List {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
/// The put pointer, then the plain, draw, API and unbiased API limits:
|
||||
/// all zero, so every inline check fails.
|
||||
put: [u64; 5],
|
||||
reserved: [u32; 64],
|
||||
/// State the inline code keeps for building packets; unused by us.
|
||||
graphics_root_headers: [u32; 128],
|
||||
compute_root_headers: [u32; 128],
|
||||
pipeline_shadow: [u32; 8],
|
||||
/// Ours, after the console layout: the host list the calls record
|
||||
/// into (decision 0007).
|
||||
#[cfg(windows)]
|
||||
host: Option<crate::host::HostList>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(List, put) == 0x18);
|
||||
const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
|
||||
|
||||
/// The host list behind a title list, if there is a host GPU.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
|
||||
if this.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the title passes one of our lists.
|
||||
unsafe { (*this.cast::<List>()).host.as_ref() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_allocator(
|
||||
_: This,
|
||||
kind: u32,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
let allocator = Box::new(Allocator {
|
||||
object: Object::new(&ALLOCATOR_FUNCTIONS),
|
||||
kind,
|
||||
});
|
||||
object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out)
|
||||
}
|
||||
|
||||
/// Lists start open, as in D3D12.
|
||||
pub(crate) extern "system" fn create_list(
|
||||
_: This,
|
||||
_nodes: u32,
|
||||
kind: u32,
|
||||
allocator: This,
|
||||
_pipeline: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
new_list(kind, allocator, iid, out)
|
||||
}
|
||||
|
||||
/// The console's list creation: type, flags, node mask and barrier batch
|
||||
/// size in a description.
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ListDesc {
|
||||
kind: u32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
barrier_batch: u32,
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create_list_x(
|
||||
_: This,
|
||||
desc: *const ListDesc,
|
||||
allocator: This,
|
||||
_pipeline: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "console command list");
|
||||
new_list(desc.kind, allocator, iid, out)
|
||||
}
|
||||
|
||||
fn new_list(kind: u32, allocator: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
if allocator.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
tracing::debug!(kind, "command list");
|
||||
let list = Box::new(List {
|
||||
object: Object::new(&LIST_FUNCTIONS),
|
||||
kind,
|
||||
put: [0; 5],
|
||||
reserved: [0; 64],
|
||||
graphics_root_headers: [0; 128],
|
||||
compute_root_headers: [0; 128],
|
||||
pipeline_shadow: [0; 8],
|
||||
#[cfg(windows)]
|
||||
host: crate::host::host().and_then(|h| match h.new_list() {
|
||||
Ok(list) => Some(list),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "no host command list");
|
||||
None
|
||||
}
|
||||
}),
|
||||
});
|
||||
object::hand_out(LIST, list, iid, &LIST_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this);
|
||||
object::answer(ALLOCATOR, iid, found, out)
|
||||
}
|
||||
extern "system" fn allocator_release(this: This) -> u32 {
|
||||
object::release_boxed::<Allocator>(this)
|
||||
}
|
||||
/// Nothing is recorded, so there is nothing to free.
|
||||
extern "system" fn allocator_reset(_: This) -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out)
|
||||
}
|
||||
extern "system" fn list_release(this: This) -> u32 {
|
||||
object::release_boxed::<List>(this)
|
||||
}
|
||||
extern "system" fn list_type(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our lists.
|
||||
unsafe { (*this.cast::<List>()).kind }
|
||||
}
|
||||
extern "system" fn close(this: This) -> HRESULT {
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = host_list(this) {
|
||||
host.close();
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn reset(this: This, allocator: This, _pipeline: This) -> HRESULT {
|
||||
if allocator.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = host_list(this) {
|
||||
host.reset();
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// A resource barrier as titles pass it: type, flags, then a resource and
|
||||
/// either a subresource and two states (transition) or a second resource
|
||||
/// (aliasing). The same layout as the host's.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Barrier {
|
||||
kind: u32,
|
||||
flags: u32,
|
||||
first: This,
|
||||
second: u64,
|
||||
last: u64,
|
||||
}
|
||||
|
||||
/// The barrier on host resources, or `None` if it names a resource the host
|
||||
/// GPU does not have (buffers so far).
|
||||
#[cfg(windows)]
|
||||
fn host_barrier(b: &Barrier) -> Option<Barrier> {
|
||||
use windows::core::Interface;
|
||||
let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
|
||||
match b.kind {
|
||||
0 => {
|
||||
// A split barrier's first half: its second half transitions.
|
||||
const BEGIN_ONLY: u32 = 1;
|
||||
if b.flags & BEGIN_ONLY != 0 {
|
||||
return None;
|
||||
}
|
||||
// shortcut: whole resources, from the state we tracked (see
|
||||
// `host_transition`); subresources are not told apart.
|
||||
let wanted = crate::host::texture_state(b.last as u32);
|
||||
let (resource, before) = crate::resource::host_transition(b.first, wanted)?;
|
||||
Some(Barrier {
|
||||
kind: 0,
|
||||
flags: 0,
|
||||
first: resource.cast_const().cast(),
|
||||
second: 0xffff_ffff | (u64::from(before) << 32),
|
||||
last: u64::from(wanted),
|
||||
})
|
||||
}
|
||||
1 => Some(Barrier {
|
||||
first: if b.first.is_null() {
|
||||
b.first
|
||||
} else {
|
||||
host(b.first)?
|
||||
},
|
||||
second: if b.second == 0 {
|
||||
0
|
||||
} else {
|
||||
host(b.second as This)? as u64
|
||||
},
|
||||
..*b
|
||||
}),
|
||||
2 => Some(Barrier {
|
||||
first: if b.first.is_null() {
|
||||
b.first
|
||||
} else {
|
||||
host(b.first)?
|
||||
},
|
||||
..*b
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the console's barrier "actions" (none).
|
||||
extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& !barriers.is_null()
|
||||
{
|
||||
// SAFETY: the title passes `count` barriers.
|
||||
let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
|
||||
let host: Vec<Barrier> = barriers.iter().filter_map(host_barrier).collect();
|
||||
if !host.is_empty() {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
|
||||
const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
|
||||
// SAFETY: the same layout; borrowed resource pointers, never
|
||||
// released through this slice.
|
||||
let host = unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
|
||||
host.len(),
|
||||
)
|
||||
};
|
||||
// SAFETY: an open list and live resources.
|
||||
unsafe { list.list.ResourceBarrier(host) };
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// Moves a title texture's host copy to `state` in the list, if needed.
|
||||
#[cfg(windows)]
|
||||
fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
if let Some(texture) = crate::resource::host_resource(resource)
|
||||
&& let Some((_, before)) = crate::resource::host_transition(resource, state)
|
||||
{
|
||||
let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
|
||||
// SAFETY: an open list and a live texture.
|
||||
unsafe { list.list.ResourceBarrier(&[barrier]) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const COPY_DEST: u32 = 0x400;
|
||||
#[cfg(windows)]
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
|
||||
/// `len` bytes at `offset` of a title buffer, if they are inside it.
|
||||
#[cfg(windows)]
|
||||
fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
|
||||
let (data, size) = crate::resource::buffer_bytes(buffer)?;
|
||||
let end = offset.checked_add(len)?;
|
||||
if end > size {
|
||||
tracing::warn!(offset, len, size, "copy outside its buffer");
|
||||
return None;
|
||||
}
|
||||
// SAFETY: inside the buffer, checked above.
|
||||
Some(unsafe { data.add(offset as usize) })
|
||||
}
|
||||
|
||||
/// Buffer to buffer: both are host memory, copied at submission.
|
||||
extern "system" fn copy_buffer_region(
|
||||
this: This,
|
||||
dst: This,
|
||||
dst_offset: u64,
|
||||
src: This,
|
||||
src_offset: u64,
|
||||
len: u64,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& let Some(to) = buffer_range(dst, dst_offset, len)
|
||||
&& let Some(from) = buffer_range(src, src_offset, len)
|
||||
{
|
||||
list.defer_copy(to, from, len as usize);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, dst_offset, src, src_offset, len);
|
||||
}
|
||||
|
||||
extern "system" fn copy_resource(this: This, dst: This, src: This) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let Some(list) = host_list(this) else {
|
||||
return;
|
||||
};
|
||||
if let (Some(to), Some(from)) = (
|
||||
crate::resource::host_resource(dst),
|
||||
crate::resource::host_resource(src),
|
||||
) {
|
||||
ensure_state(list, dst, COPY_DEST);
|
||||
ensure_state(list, src, COPY_SOURCE);
|
||||
// SAFETY: an open list and live textures.
|
||||
unsafe { list.list.CopyResource(to, from) };
|
||||
} else if let (Some((to, a)), Some((from, b))) = (
|
||||
crate::resource::buffer_bytes(dst),
|
||||
crate::resource::buffer_bytes(src),
|
||||
) {
|
||||
list.defer_copy(to, from, a.min(b) as usize);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, src);
|
||||
}
|
||||
|
||||
extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
|
||||
copy_resource(this, dst, src);
|
||||
}
|
||||
|
||||
/// A copy location as titles pass it, laid out as the host's: a resource,
|
||||
/// then a subresource index (type 0) or a placed footprint (type 1).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct CopyLocation {
|
||||
resource: This,
|
||||
kind: u32,
|
||||
footprint: crate::resource::PlacedFootprint,
|
||||
}
|
||||
|
||||
/// Texture to texture on the GPU; buffer to texture through an upload
|
||||
/// buffer filled at submission. Texture to buffer (read back) is not done
|
||||
/// yet.
|
||||
extern "system" fn copy_texture_region(
|
||||
this: This,
|
||||
dst: *const CopyLocation,
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
src: *const CopyLocation,
|
||||
source_box: *const [u32; 6],
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
|
||||
use windows::core::Interface;
|
||||
const FOOTPRINT: u32 = 1;
|
||||
// SAFETY: the title passes both locations (null is tolerated).
|
||||
let (Some(list), Some(&dst), Some(&src)) =
|
||||
(host_list(this), unsafe { dst.as_ref() }, unsafe {
|
||||
src.as_ref()
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(to) = crate::resource::host_resource(dst.resource) else {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!("texture to buffer copies not implemented"));
|
||||
return;
|
||||
};
|
||||
let mut from = src;
|
||||
let _upload; // keeps the source alive while this call records it
|
||||
if src.kind == FOOTPRINT {
|
||||
let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
|
||||
return;
|
||||
};
|
||||
let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
|
||||
return;
|
||||
};
|
||||
let Some((buffer, staging)) = list.upload(host, bytes) else {
|
||||
return;
|
||||
};
|
||||
list.defer_copy(staging, data, bytes as usize);
|
||||
from.resource = buffer.as_raw().cast_const().cast();
|
||||
from.footprint.offset = 0;
|
||||
_upload = buffer;
|
||||
} else {
|
||||
let Some(texture) = crate::resource::host_resource(src.resource) else {
|
||||
return;
|
||||
};
|
||||
ensure_state(list, src.resource, COPY_SOURCE);
|
||||
from.resource = texture.as_raw().cast_const().cast();
|
||||
}
|
||||
ensure_state(list, dst.resource, COPY_DEST);
|
||||
let mut to_location = dst;
|
||||
to_location.resource = to.as_raw().cast_const().cast();
|
||||
let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
|
||||
const _: () =
|
||||
assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
|
||||
// SAFETY: an open list; both locations in the host's layout, naming
|
||||
// live resources; the box is the title's (same layout).
|
||||
unsafe {
|
||||
list.list.CopyTextureRegion(
|
||||
(&raw const to_location).cast(),
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
(&raw const from).cast(),
|
||||
host_box,
|
||||
)
|
||||
};
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, x, y, z, src, source_box);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)] // the method's own arguments
|
||||
extern "system" fn copy_texture_region_x(
|
||||
this: This,
|
||||
dst: *const CopyLocation,
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
src: *const CopyLocation,
|
||||
source_box: *const [u32; 6],
|
||||
_flags: u32,
|
||||
) {
|
||||
copy_texture_region(this, dst, x, y, z, src, source_box);
|
||||
}
|
||||
|
||||
extern "system" fn resolve(
|
||||
this: This,
|
||||
dst: This,
|
||||
dst_sub: u32,
|
||||
src: This,
|
||||
src_sub: u32,
|
||||
format: u32,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
if let Some(list) = host_list(this)
|
||||
&& let (Some(to), Some(from)) = (
|
||||
crate::resource::host_resource(dst),
|
||||
crate::resource::host_resource(src),
|
||||
)
|
||||
{
|
||||
use windows::Win32::Foundation::RECT;
|
||||
use windows::Win32::Graphics::Direct3D12::{
|
||||
D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
|
||||
};
|
||||
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
|
||||
use windows::core::Interface;
|
||||
const RESOLVE_DEST: u32 = 0x1000;
|
||||
const RESOLVE_SOURCE: u32 = 0x2000;
|
||||
ensure_state(list, dst, RESOLVE_DEST);
|
||||
ensure_state(list, src, RESOLVE_SOURCE);
|
||||
// SAFETY: an open list and live textures; the region is inside both.
|
||||
unsafe {
|
||||
let (a, b) = (to.GetDesc(), from.GetDesc());
|
||||
let format = DXGI_FORMAT(format as i32);
|
||||
if (a.Width, a.Height) == (b.Width, b.Height) {
|
||||
list.list
|
||||
.ResolveSubresource(to, dst_sub, from, src_sub, format);
|
||||
} else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
|
||||
// The console clips a larger source to the destination.
|
||||
let rect = RECT {
|
||||
left: 0,
|
||||
top: 0,
|
||||
right: a.Width.min(b.Width) as i32,
|
||||
bottom: a.Height.min(b.Height) as i32,
|
||||
};
|
||||
list1.ResolveSubresourceRegion(
|
||||
to,
|
||||
dst_sub,
|
||||
0,
|
||||
0,
|
||||
from,
|
||||
src_sub,
|
||||
Some(&rect),
|
||||
format,
|
||||
D3D12_RESOLVE_MODE_AVERAGE,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, dst, dst_sub, src, src_sub, format);
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Rect {
|
||||
left: i32,
|
||||
top: i32,
|
||||
right: i32,
|
||||
bottom: i32,
|
||||
}
|
||||
|
||||
extern "system" fn clear_rtv(
|
||||
this: This,
|
||||
handle: u64,
|
||||
color: *const [f32; 4],
|
||||
count: u32,
|
||||
rects: *const Rect,
|
||||
) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (Some(texture), Some(host)) = (
|
||||
crate::resource::host_resource(record.resource),
|
||||
crate::host::host(),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: the title passes four floats (null is tolerated).
|
||||
let Some(color) = (unsafe { color.as_ref() }) else {
|
||||
return;
|
||||
};
|
||||
let rects = (count > 0 && !rects.is_null()).then(|| {
|
||||
// SAFETY: the title passes `count` rectangles, laid out as the host's.
|
||||
unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
|
||||
});
|
||||
const RENDER_TARGET: u32 = 0x4;
|
||||
let rtv = host.rtv(texture, record.desc().as_ref());
|
||||
// SAFETY: an open list, a fresh view of a live texture.
|
||||
unsafe {
|
||||
if let Some((_, before)) =
|
||||
crate::resource::host_transition(record.resource, RENDER_TARGET)
|
||||
{
|
||||
use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
|
||||
list.list.ResourceBarrier(&[crate::host::transition(
|
||||
texture,
|
||||
State(before as i32),
|
||||
State(RENDER_TARGET as i32),
|
||||
)]);
|
||||
}
|
||||
list.list.ClearRenderTargetView(rtv, color, rects);
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (this, handle, color, count, rects);
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, allocator 2.
|
||||
static ALLOCATOR_FUNCTIONS: Table<10> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 10>());
|
||||
f[0] = allocator_query as *const ();
|
||||
f[2] = allocator_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = allocator_reset as *const (); // 0x40
|
||||
f[9] = object::ignore as *const (); // 0x48 allocation callback
|
||||
Table(f)
|
||||
};
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, list 1, graphics list 96 (59 as
|
||||
/// on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3 + 13).
|
||||
static LIST_FUNCTIONS: Table<140> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<LIST, 140>());
|
||||
f[0] = list_query as *const ();
|
||||
f[2] = list_release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[8] = list_type as *const (); // 0x40
|
||||
f[9] = close as *const (); // 0x48
|
||||
f[10] = reset as *const (); // 0x50
|
||||
f[15] = copy_buffer_region as *const (); // 0x78
|
||||
f[16] = copy_texture_region as *const (); // 0x80
|
||||
f[17] = copy_resource as *const (); // 0x88
|
||||
f[19] = resolve as *const (); // 0x98
|
||||
f[26] = barrier as *const (); // 0xd0
|
||||
f[83] = copy_texture_region_x as *const (); // 0x298
|
||||
f[84] = copy_resource_x as *const (); // 0x2a0
|
||||
f[52] = clear_rtv as *const (); // 0x1a0
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[test]
|
||||
fn every_inline_command_falls_back_to_the_table() {
|
||||
let null = std::ptr::null();
|
||||
let mut allocator = null;
|
||||
assert_eq!(
|
||||
create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
|
||||
S_OK
|
||||
);
|
||||
let mut list = null;
|
||||
let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
|
||||
assert_eq!(hr, S_OK);
|
||||
// What the title's inline draw checks: put < draw limit.
|
||||
// SAFETY: the list is 0x560 bytes.
|
||||
let (put, draw_limit, api_limit) = unsafe {
|
||||
let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
|
||||
(at(0x18), at(0x28), at(0x30))
|
||||
};
|
||||
assert!(put >= draw_limit && put >= api_limit);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
|
||||
S_OK
|
||||
);
|
||||
let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
|
||||
assert_eq!(release(list), 0);
|
||||
assert_eq!(release(allocator), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
//! What every console graphics object starts with: a function table
|
||||
//! pointer, bookkeeping bits and a reference count. Tables begin with
|
||||
//! IUnknown's three slots. Our objects are static and never destroyed.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
pub type HRESULT = i32;
|
||||
pub const S_OK: HRESULT = 0;
|
||||
pub(crate) const S_FALSE: HRESULT = 1;
|
||||
pub(crate) const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
pub(crate) const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
|
||||
pub(crate) const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
pub(crate) const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
pub(crate) const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
/// What D3D and DXGI return for a missing item (adapter, output, private
|
||||
/// data).
|
||||
pub(crate) const NOT_FOUND: HRESULT = 0x887A_0002_u32 as i32;
|
||||
const MORE_DATA: HRESULT = 0x887A_0003_u32 as i32;
|
||||
|
||||
pub type Iid = [u8; 16];
|
||||
|
||||
/// An interface id from its text form's fields, in memory order.
|
||||
pub const fn guid(a: u32, b: u16, c: u16, d: [u8; 8]) -> Iid {
|
||||
let (a, b, c) = (a.to_le_bytes(), b.to_le_bytes(), c.to_le_bytes());
|
||||
[
|
||||
a[0], a[1], a[2], a[3], b[0], b[1], c[0], c[1], d[0], d[1], d[2], d[3], d[4], d[5], d[6],
|
||||
d[7],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn guid_text(g: &Iid) -> String {
|
||||
let a = u32::from_le_bytes([g[0], g[1], g[2], g[3]]);
|
||||
let b = u16::from_le_bytes([g[4], g[5]]);
|
||||
let c = u16::from_le_bytes([g[6], g[7]]);
|
||||
let d: String = g[8..].iter().map(|x| format!("{x:02x}")).collect();
|
||||
format!("{a:08x}-{b:04x}-{c:04x}-{}-{}", &d[..4], &d[4..])
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Object {
|
||||
functions: *const *const (),
|
||||
/// Device index (bits 0-2) and bookkeeping bits; all zero.
|
||||
bits: u32,
|
||||
refs: AtomicU32,
|
||||
}
|
||||
// SAFETY: the table is static and immutable; the count is atomic.
|
||||
unsafe impl Sync for Object {}
|
||||
|
||||
impl Object {
|
||||
pub(crate) const fn new<const N: usize>(table: &'static Table<N>) -> Self {
|
||||
Object {
|
||||
functions: table.0.as_ptr(),
|
||||
bits: 0,
|
||||
refs: AtomicU32::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type This = *const Object;
|
||||
|
||||
#[repr(transparent)]
|
||||
pub(crate) struct Table<const N: usize>(pub [*const (); N]);
|
||||
// SAFETY: function addresses only.
|
||||
unsafe impl<const N: usize> Sync for Table<N> {}
|
||||
|
||||
pub(crate) extern "system" fn add_ref(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our objects.
|
||||
unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn release(this: This) -> u32 {
|
||||
// SAFETY: `this` is one of our objects.
|
||||
let refs = &unsafe { &*this }.refs;
|
||||
let _ = refs.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
|
||||
refs.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Answers an interface query (or any call handing out an object): a new
|
||||
/// reference to `found`, or null and `E_NOINTERFACE`.
|
||||
pub(crate) fn answer(kind: usize, iid: *const Iid, found: Option<This>, out: *mut This) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_POINTER;
|
||||
}
|
||||
let hr = match found {
|
||||
Some(object) => {
|
||||
add_ref(object);
|
||||
// SAFETY: checked non-null; the title passes room for a pointer.
|
||||
unsafe { out.write(object) };
|
||||
return S_OK;
|
||||
}
|
||||
None => E_NOINTERFACE,
|
||||
};
|
||||
// SAFETY: the title passes an interface id (null is tolerated).
|
||||
let iid = unsafe { iid.as_ref() }.map(guid_text).unwrap_or_default();
|
||||
tracing::warn!(object = KINDS[kind], %iid, "unknown interface");
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(std::ptr::null()) };
|
||||
hr
|
||||
}
|
||||
|
||||
/// Whether `iid` is one of `known`.
|
||||
pub(crate) fn is(iid: *const Iid, known: &[Iid]) -> bool {
|
||||
// SAFETY: the title passes an interface id (null is tolerated).
|
||||
unsafe { iid.as_ref() }.is_some_and(|i| known.contains(i))
|
||||
}
|
||||
|
||||
/// Hands a new object to the title as one of `known`, or drops it. `T`
|
||||
/// starts with its `Object`; its table's release slot is
|
||||
/// [`release_boxed::<T>`].
|
||||
pub(crate) fn hand_out<T>(
|
||||
kind: usize,
|
||||
object: Box<T>,
|
||||
iid: *const Iid,
|
||||
known: &[Iid],
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if !is(iid, known) {
|
||||
return answer(kind, iid, None, out);
|
||||
}
|
||||
if out.is_null() {
|
||||
// Asked only whether creation would succeed.
|
||||
return S_FALSE;
|
||||
}
|
||||
answer(kind, iid, Some(Box::into_raw(object).cast()), out)
|
||||
}
|
||||
|
||||
/// Release for objects made by [`hand_out`]: the last reference frees it.
|
||||
pub(crate) fn release_boxed<T>(this: This) -> u32 {
|
||||
// SAFETY: `this` is the header of a boxed `T`.
|
||||
let refs = &unsafe { &*this }.refs;
|
||||
match refs.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) {
|
||||
Ok(1) => {
|
||||
private_data().retain(|&(object, _), _| object != this as usize);
|
||||
// SAFETY: that was the last reference to a `Box<T>`.
|
||||
drop(unsafe { Box::from_raw(this.cast_mut().cast::<T>()) });
|
||||
0
|
||||
}
|
||||
Ok(n) => n - 1,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Private data of every object, by object address and id.
|
||||
static PRIVATE: Mutex<BTreeMap<(usize, Iid), Vec<u8>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
fn private_data() -> std::sync::MutexGuard<'static, BTreeMap<(usize, Iid), Vec<u8>>> {
|
||||
PRIVATE.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
extern "system" fn get_private_data(
|
||||
this: This,
|
||||
id: *const Iid,
|
||||
size: *mut u32,
|
||||
data: *mut u8,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes an id and its buffer size (null is tolerated).
|
||||
let (Some(id), Some(size)) = (unsafe { (id.as_ref(), size.as_mut()) }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let map = private_data();
|
||||
let Some(value) = map.get(&(this as usize, *id)) else {
|
||||
*size = 0;
|
||||
return NOT_FOUND;
|
||||
};
|
||||
let len = value.len() as u32;
|
||||
let room = std::mem::replace(size, len);
|
||||
if data.is_null() {
|
||||
return S_OK;
|
||||
}
|
||||
if room < len {
|
||||
return MORE_DATA;
|
||||
}
|
||||
// SAFETY: the buffer holds `room` >= `len` bytes.
|
||||
unsafe { data.copy_from_nonoverlapping(value.as_ptr(), value.len()) };
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Null data removes the entry.
|
||||
extern "system" fn set_private_data(
|
||||
this: This,
|
||||
id: *const Iid,
|
||||
size: u32,
|
||||
data: *const u8,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes an id (null is tolerated).
|
||||
let Some(&id) = (unsafe { id.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
let mut map = private_data();
|
||||
if data.is_null() {
|
||||
map.remove(&(this as usize, id));
|
||||
} else {
|
||||
// SAFETY: the title passes `size` bytes.
|
||||
let value = unsafe { std::slice::from_raw_parts(data, size as usize) };
|
||||
map.insert((this as usize, id), value.to_vec());
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// Fills a D3D12 table's object methods: private data and name (setting
|
||||
/// an interface as private data stays unwritten).
|
||||
pub(crate) const fn d3d12_object<const N: usize>(mut f: [*const (); N]) -> [*const (); N] {
|
||||
f[3] = get_private_data as *const (); // 0x18
|
||||
f[4] = set_private_data as *const (); // 0x20
|
||||
f[6] = set_name as *const (); // 0x30
|
||||
f
|
||||
}
|
||||
|
||||
/// The object methods' name setter: names only reach our log.
|
||||
pub(crate) extern "system" fn set_name(this: This, name: *const u16) -> HRESULT {
|
||||
let name = if name.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
// SAFETY: a non-null name is NUL-terminated UTF-16.
|
||||
let len = (0..).take_while(|&i| unsafe { *name.add(i) } != 0).count();
|
||||
// SAFETY: `len` units were just read.
|
||||
String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(name, len) })
|
||||
};
|
||||
tracing::debug!(object = ?this, %name, "named");
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// The device-child method: the device that made the object.
|
||||
pub(crate) extern "system" fn parent_device(_: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let device = crate::device::device();
|
||||
answer(
|
||||
DEVICE,
|
||||
iid,
|
||||
is(iid, &[crate::device::IID]).then_some(device),
|
||||
out,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) const DEVICE: usize = 0;
|
||||
pub(crate) const DXGI_DEVICE: usize = 1;
|
||||
pub(crate) const ADAPTER: usize = 2;
|
||||
pub(crate) const FACTORY: usize = 3;
|
||||
pub(crate) const OUTPUT: usize = 4;
|
||||
pub(crate) const HEAP: usize = 5;
|
||||
pub(crate) const RESOURCE: usize = 6;
|
||||
pub(crate) const FENCE: usize = 7;
|
||||
pub(crate) const QUEUE: usize = 8;
|
||||
pub(crate) const ALLOCATOR: usize = 9;
|
||||
pub(crate) const LIST: usize = 10;
|
||||
pub(crate) const DESCRIPTOR_HEAP: usize = 11;
|
||||
pub(crate) const ROOT_SIGNATURE: usize = 12;
|
||||
pub(crate) const QUERY_HEAP: usize = 13;
|
||||
pub(crate) const COMMAND_SIGNATURE: usize = 14;
|
||||
pub(crate) const PIPELINE: usize = 15;
|
||||
const KINDS: [&str; 16] = [
|
||||
"device",
|
||||
"DXGI device",
|
||||
"adapter",
|
||||
"factory",
|
||||
"output",
|
||||
"heap",
|
||||
"resource",
|
||||
"fence",
|
||||
"command queue",
|
||||
"command allocator",
|
||||
"command list",
|
||||
"descriptor heap",
|
||||
"root signature",
|
||||
"query heap",
|
||||
"command signature",
|
||||
"pipeline state",
|
||||
];
|
||||
|
||||
const MAX_SLOTS: usize = 160;
|
||||
|
||||
/// Which unwritten slots have been reported; each is logged once.
|
||||
static REPORTED: [[AtomicBool; MAX_SLOTS]; KINDS.len()] =
|
||||
[const { [const { AtomicBool::new(false) }; MAX_SLOTS] }; KINDS.len()];
|
||||
|
||||
/// Logged once per slot. Wrong for a slot that returns a value instead of
|
||||
/// an `HRESULT`.
|
||||
extern "system" fn missing<const KIND: usize, const SLOT: usize>() -> HRESULT {
|
||||
if !REPORTED[KIND][SLOT].swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!(
|
||||
object = KINDS[KIND],
|
||||
slot = format_args!("{:#x}", SLOT * 8),
|
||||
"method not implemented"
|
||||
);
|
||||
}
|
||||
E_NOTIMPL
|
||||
}
|
||||
|
||||
/// Accepts and ignores (debug-only settings).
|
||||
pub(crate) extern "system" fn ignore() -> HRESULT {
|
||||
S_OK
|
||||
}
|
||||
|
||||
macro_rules! missing {
|
||||
($kind:ident; $($slot:literal)*) => { [$(missing::<$kind, $slot> as *const ()),*] };
|
||||
}
|
||||
|
||||
/// A table of `N` slots that log and fail; callers fill in what they have.
|
||||
pub(crate) const fn missing_table<const KIND: usize, const N: usize>() -> [*const (); N] {
|
||||
let all = missing!(KIND;
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
||||
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
||||
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
||||
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
||||
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
|
||||
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
|
||||
158 159
|
||||
);
|
||||
assert!(N <= all.len());
|
||||
let mut table = [std::ptr::null(); N];
|
||||
let mut i = 0;
|
||||
while i < N {
|
||||
table[i] = all[i];
|
||||
i += 1;
|
||||
}
|
||||
table[1] = add_ref as *const ();
|
||||
table[2] = release as *const ();
|
||||
table
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn slot<F: Copy>(object: This, offset: usize) -> F {
|
||||
// SAFETY: `object` is ours and its table has the slot.
|
||||
let f = unsafe { *(*object).functions.add(offset / 8) };
|
||||
// SAFETY: the caller names the slot's signature.
|
||||
unsafe { std::mem::transmute_copy(&f) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn guids_round_trip_through_text() {
|
||||
let g = guid(
|
||||
0x189819f1,
|
||||
0x1db6,
|
||||
0x4b57,
|
||||
[0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7],
|
||||
);
|
||||
assert_eq!(g[..4], [0xf1, 0x19, 0x98, 0x18]);
|
||||
assert_eq!(guid_text(&g), "189819f1-1db6-4b57-be54-1821339b85f7");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Pipeline states. Both descriptions start as on PC: the root signature,
|
||||
//! then the shader stages (five for graphics, one for compute); only those
|
||||
//! are read so far.
|
||||
//!
|
||||
//! shortcut: the console shader containers are kept, not translated, and
|
||||
//! the rest of the description is ignored. Translate through the cache
|
||||
//! here (TODO.md, GPU: pipeline creation, decision 0003). The 32-byte
|
||||
//! packet after the header stays zero: titles only copy it inline, which
|
||||
//! our null command-list limits keep from running.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::mem::offset_of;
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const PIPELINE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x765a30f3,
|
||||
0xf624,
|
||||
0x4c6f,
|
||||
[0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Bytecode {
|
||||
code: *const u8,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct GraphicsHead {
|
||||
root: This,
|
||||
/// Vertex, pixel, domain, hull, geometry.
|
||||
stages: [Bytecode; 5],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct ComputeHead {
|
||||
root: This,
|
||||
stage: Bytecode,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Pipeline {
|
||||
object: Object,
|
||||
packet: [u32; 8],
|
||||
/// Each stage's container, empty when the stage is unused.
|
||||
shaders: Vec<Vec<u8>>,
|
||||
}
|
||||
const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
|
||||
|
||||
fn copy(stage: &Bytecode) -> Vec<u8> {
|
||||
if stage.code.is_null() || stage.size == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes of shader code.
|
||||
unsafe { std::slice::from_raw_parts(stage.code, stage.size) }.to_vec()
|
||||
}
|
||||
|
||||
fn hand_out(shaders: Vec<Vec<u8>>, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let sizes: Vec<usize> = shaders.iter().map(Vec::len).collect();
|
||||
tracing::debug!(?sizes, "pipeline state");
|
||||
let pipeline = Box::new(Pipeline {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
packet: [0; 8],
|
||||
shaders,
|
||||
});
|
||||
object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_graphics(
|
||||
_: This,
|
||||
desc: *const GraphicsHead,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(desc.stages.iter().map(copy).collect(), iid, out)
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create_compute(
|
||||
_: This,
|
||||
desc: *const ComputeHead,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
hand_out(vec![copy(&desc.stage)], iid, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &PIPELINE_IIDS).then_some(this);
|
||||
object::answer(PIPELINE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Pipeline>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, pipeline 3.
|
||||
static FUNCTIONS: Table<11> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 11>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
#[test]
|
||||
fn pipelines_keep_their_shaders() {
|
||||
let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
|
||||
let none = || Bytecode {
|
||||
code: std::ptr::null(),
|
||||
size: 0,
|
||||
};
|
||||
let desc = GraphicsHead {
|
||||
root: std::ptr::null(),
|
||||
stages: [
|
||||
Bytecode {
|
||||
code: vs.as_ptr(),
|
||||
size: vs.len(),
|
||||
},
|
||||
Bytecode {
|
||||
code: ps.as_ptr(),
|
||||
size: ps.len(),
|
||||
},
|
||||
none(),
|
||||
none(),
|
||||
none(),
|
||||
],
|
||||
};
|
||||
let mut p = std::ptr::null();
|
||||
assert_eq!(
|
||||
create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
|
||||
S_OK
|
||||
);
|
||||
// SAFETY: one of our pipelines.
|
||||
let shaders = unsafe { &(*p.cast::<Pipeline>()).shaders };
|
||||
assert_eq!(shaders[0], vs);
|
||||
assert_eq!(shaders[1], ps);
|
||||
assert!(shaders[2].is_empty());
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Query heaps. Nothing runs on a GPU yet, so no query ever produces a
|
||||
//! result; the heap only remembers its description.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUERY_HEAP, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const HEAP_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0d9658ae,
|
||||
0xed45,
|
||||
0x469e,
|
||||
[0xa6, 0x1d, 0x97, 0x0e, 0xc5, 0x83, 0xca, 0xb4],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Desc {
|
||||
kind: u32,
|
||||
count: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Heap {
|
||||
object: Object,
|
||||
desc: Desc,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const Desc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "query heap");
|
||||
let heap = Box::new(Heap {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
desc,
|
||||
});
|
||||
object::hand_out(QUERY_HEAP, heap, iid, &HEAP_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
QUERY_HEAP,
|
||||
iid,
|
||||
object::is(iid, &HEAP_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Heap>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUERY_HEAP, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
//! Command queues. Nothing is executed yet: submitted lists are dropped and
|
||||
//! fence signals complete at once, as if the GPU were infinitely fast.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const QUEUE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0x0ec870a6,
|
||||
0x5d7e,
|
||||
0x4c22,
|
||||
[0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct QueueDesc {
|
||||
kind: u32,
|
||||
priority: i32,
|
||||
flags: u32,
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
/// The title reads the list type right after the header.
|
||||
#[repr(C)]
|
||||
struct Queue {
|
||||
object: Object,
|
||||
kind: u32,
|
||||
desc: QueueDesc,
|
||||
}
|
||||
const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
|
||||
|
||||
fn queue<'a>(this: This) -> &'a Queue {
|
||||
// SAFETY: called from queue methods only.
|
||||
unsafe { &*this.cast::<Queue>() }
|
||||
}
|
||||
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const QueueDesc,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
tracing::debug!(?desc, "command queue");
|
||||
let queue = Box::new(Queue {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
kind: desc.kind,
|
||||
desc,
|
||||
});
|
||||
object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
object::answer(
|
||||
QUEUE,
|
||||
iid,
|
||||
object::is(iid, &QUEUE_IIDS).then_some(this),
|
||||
out,
|
||||
)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Queue>(this)
|
||||
}
|
||||
|
||||
/// Runs the lists' host lists and waits for them (decision 0007).
|
||||
extern "system" fn execute(_: This, count: u32, lists: *const This) {
|
||||
if lists.is_null() {
|
||||
return;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if let Some(host) = crate::host::host() {
|
||||
// SAFETY: the title passes `count` lists.
|
||||
let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
|
||||
let host_lists: Vec<_> = lists
|
||||
.iter()
|
||||
.filter_map(|&l| crate::list::host_list(l))
|
||||
.collect();
|
||||
host.execute(&host_lists);
|
||||
return;
|
||||
}
|
||||
static ONCE: AtomicBool = AtomicBool::new(false);
|
||||
if !ONCE.swap(true, Ordering::Relaxed) {
|
||||
tracing::warn!(count, "command lists submitted; no host GPU runs them");
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a present plane: frame token, then the plane's resources.
|
||||
#[repr(C)]
|
||||
pub(crate) struct Plane {
|
||||
token: u64,
|
||||
count: u32,
|
||||
resources: *const This,
|
||||
}
|
||||
/// Markers and events only matter to profilers.
|
||||
extern "system" fn marker(_: This) {}
|
||||
extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
|
||||
if fence.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
crate::fence::signal(fence, value)
|
||||
}
|
||||
/// Nothing runs on the queue, so waiting for a fence never blocks it.
|
||||
extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
|
||||
if fence.is_null() { E_INVALIDARG } else { S_OK }
|
||||
}
|
||||
/// Ticks per second of GPU timestamps; none are written yet.
|
||||
extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: checked non-null.
|
||||
unsafe { out.write(100_000_000) };
|
||||
S_OK
|
||||
}
|
||||
/// Shows the first plane's first resource in our window.
|
||||
///
|
||||
/// shortcut: one plane, no scaling or placement, the source expected in
|
||||
/// the common state.
|
||||
extern "system" fn present(
|
||||
_: This,
|
||||
planes: u32,
|
||||
plane_parameters: *const Plane,
|
||||
_parameters: *const u8,
|
||||
) -> HRESULT {
|
||||
static FRAMES: AtomicU64 = AtomicU64::new(0);
|
||||
let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if frame.is_power_of_two() {
|
||||
tracing::info!(frame, "frame presented");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
if planes > 0
|
||||
// SAFETY: the title passes `planes` plane descriptions.
|
||||
&& let Some(plane) = unsafe { plane_parameters.as_ref() }
|
||||
&& plane.count > 0
|
||||
&& !plane.resources.is_null()
|
||||
// SAFETY: the plane lists `count` resources.
|
||||
&& let resource = unsafe { *plane.resources }
|
||||
&& let Some(texture) = crate::resource::host_resource(resource)
|
||||
&& let Some(host) = crate::host::host()
|
||||
{
|
||||
const COPY_SOURCE: u32 = 0x800;
|
||||
let state = crate::resource::host_transition(resource, COPY_SOURCE)
|
||||
.map_or(COPY_SOURCE, |(_, before)| before);
|
||||
host.present(texture, state);
|
||||
crate::resource::host_transition(resource, state);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = (planes, plane_parameters);
|
||||
S_OK
|
||||
}
|
||||
extern "system" fn desc(this: This, out: *mut QueueDesc) {
|
||||
if !out.is_null() {
|
||||
// SAFETY: checked non-null; the title passes room for a description.
|
||||
unsafe { out.write(queue(this).desc) };
|
||||
}
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1, queue 26 (12 as on PC, then
|
||||
/// console ones).
|
||||
static FUNCTIONS: Table<34> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<QUEUE, 34>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
f[10] = execute as *const (); // 0x50
|
||||
f[11] = marker as *const (); // 0x58 set marker
|
||||
f[12] = marker as *const (); // 0x60 begin event
|
||||
f[13] = marker as *const (); // 0x68 end event
|
||||
f[14] = signal as *const (); // 0x70
|
||||
f[15] = wait as *const (); // 0x78
|
||||
f[16] = timestamp_frequency as *const (); // 0x80
|
||||
f[26] = desc as *const (); // 0xd0
|
||||
f[30] = present as *const (); // 0xf0
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[test]
|
||||
fn queue_signals_complete_at_once() {
|
||||
let null = std::ptr::null();
|
||||
let desc = QueueDesc {
|
||||
kind: 0,
|
||||
priority: 0,
|
||||
flags: 0,
|
||||
nodes: 0,
|
||||
};
|
||||
let mut q = null;
|
||||
assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
|
||||
// SAFETY: the title reads the type at +0x10.
|
||||
assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0);
|
||||
let mut fence = null;
|
||||
let fence_iid = &crate::fence::FENCE_IIDS[0];
|
||||
assert_eq!(
|
||||
crate::fence::create(null, 0, 0, fence_iid, &mut fence),
|
||||
S_OK
|
||||
);
|
||||
let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, 0x70);
|
||||
assert_eq!(signal(q, fence, 7), S_OK);
|
||||
assert_eq!(
|
||||
slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
|
||||
7
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,196 @@
|
||||
//! Root signatures.
|
||||
//!
|
||||
//! Serializing goes to the host's `D3D12SerializeRootSignature`: the
|
||||
//! description is laid out as on PC, and the blob it returns works as the
|
||||
//! console's, whose two methods sit in the same slots. The console's own
|
||||
//! flags (bit 24 and up) are dropped first.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::object::{
|
||||
self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const ROOT_SIGNATURE_IIDS: [Iid; 3] = [
|
||||
guid(
|
||||
0xc54a6b66,
|
||||
0x72df,
|
||||
0x4ee8,
|
||||
[0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14],
|
||||
),
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
const CONSOLE_FLAGS: u32 = 0xff00_0000;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Desc {
|
||||
parameter_count: u32,
|
||||
parameters: *const c_void,
|
||||
sampler_count: u32,
|
||||
samplers: *const c_void,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
type Serialize =
|
||||
unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
|
||||
|
||||
/// The host's serializer, from `d3d12.dll` in System32.
|
||||
fn host_serializer() -> Option<Serialize> {
|
||||
static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
|
||||
let address = *FUNCTION.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
let name: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
|
||||
// SAFETY: a NUL-terminated name; System32 only.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
name.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a loaded module and a NUL-terminated name.
|
||||
unsafe { GetProcAddress(module, c"D3D12SerializeRootSignature".as_ptr().cast()) }
|
||||
.map(|f| f as usize)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
None
|
||||
});
|
||||
// SAFETY: the export has this signature.
|
||||
address.map(|a| unsafe { std::mem::transmute::<usize, Serialize>(a) })
|
||||
}
|
||||
|
||||
/// `d3d12_xs!D3D12SerializeRootSignature`.
|
||||
pub extern "system" fn serialize(
|
||||
desc: *const Desc,
|
||||
version: u32,
|
||||
blob: *mut *mut c_void,
|
||||
error: *mut *mut c_void,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(&desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.flags & CONSOLE_FLAGS != 0 {
|
||||
tracing::debug!(
|
||||
flags = format_args!("{:#x}", desc.flags),
|
||||
"console root signature flags dropped"
|
||||
);
|
||||
}
|
||||
let desc = Desc {
|
||||
flags: desc.flags & !CONSOLE_FLAGS,
|
||||
..desc
|
||||
};
|
||||
let Some(serialize) = host_serializer() else {
|
||||
tracing::warn!("no host d3d12.dll to serialize root signatures");
|
||||
return E_NOTIMPL;
|
||||
};
|
||||
// SAFETY: the host function takes the same arguments the title passed.
|
||||
unsafe { serialize(&desc, version, blob, error) }
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct RootSignature {
|
||||
object: Object,
|
||||
/// The serialized form, kept for translating pipelines later.
|
||||
blob: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
_nodes: u32,
|
||||
blob: *const u8,
|
||||
size: usize,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
if blob.is_null() || size == 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
// SAFETY: the title passes `size` bytes.
|
||||
let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec();
|
||||
tracing::debug!(size, "root signature");
|
||||
let root = Box::new(RootSignature {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
blob,
|
||||
});
|
||||
object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this);
|
||||
object::answer(ROOT_SIGNATURE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<RootSignature>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::object::{S_OK, slot};
|
||||
|
||||
/// One 32-bit constant at b0, serialized by the host, then created.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn host_serialized_blobs_create_root_signatures() {
|
||||
#[repr(C)]
|
||||
struct Constants {
|
||||
kind: u32,
|
||||
register: u32,
|
||||
space: u32,
|
||||
count: u32,
|
||||
visibility: u32,
|
||||
}
|
||||
let parameter = Constants {
|
||||
kind: 1,
|
||||
register: 0,
|
||||
space: 0,
|
||||
count: 1,
|
||||
visibility: 0,
|
||||
};
|
||||
let desc = Desc {
|
||||
parameter_count: 1,
|
||||
parameters: (&raw const parameter).cast(),
|
||||
sampler_count: 0,
|
||||
samplers: std::ptr::null(),
|
||||
flags: 0x0100_0001,
|
||||
};
|
||||
let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
|
||||
assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK);
|
||||
let blob = blob.cast_const().cast::<Object>();
|
||||
let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
|
||||
let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
|
||||
assert!(size > 0);
|
||||
let null = std::ptr::null();
|
||||
let mut root = null;
|
||||
assert_eq!(
|
||||
create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root),
|
||||
S_OK
|
||||
);
|
||||
assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0);
|
||||
slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Command signatures: the record layout of indirect execution. Kept for
|
||||
//! translating it later.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use crate::object::{
|
||||
self, COMMAND_SIGNATURE, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid,
|
||||
};
|
||||
use crate::resource::PAGEABLE_IIDS;
|
||||
|
||||
const SIGNATURE_IIDS: [Iid; 4] = [
|
||||
guid(
|
||||
0xc36a797c,
|
||||
0xec80,
|
||||
0x4f0a,
|
||||
[0x89, 0x85, 0xa7, 0xb2, 0x47, 0x50, 0x82, 0xd1],
|
||||
),
|
||||
PAGEABLE_IIDS[0],
|
||||
PAGEABLE_IIDS[1],
|
||||
PAGEABLE_IIDS[2],
|
||||
];
|
||||
|
||||
#[repr(C)]
|
||||
pub(crate) struct Desc {
|
||||
stride: u32,
|
||||
count: u32,
|
||||
/// Each a type and up to three 32-bit fields.
|
||||
arguments: *const [u32; 4],
|
||||
nodes: u32,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Signature {
|
||||
object: Object,
|
||||
stride: u32,
|
||||
arguments: Vec<[u32; 4]>,
|
||||
}
|
||||
|
||||
/// Device method.
|
||||
pub(crate) extern "system" fn create(
|
||||
_: This,
|
||||
desc: *const Desc,
|
||||
_root: This,
|
||||
iid: *const Iid,
|
||||
out: *mut This,
|
||||
) -> HRESULT {
|
||||
// SAFETY: the title passes a description (null is tolerated).
|
||||
let Some(desc) = (unsafe { desc.as_ref() }) else {
|
||||
return E_INVALIDARG;
|
||||
};
|
||||
if desc.arguments.is_null() && desc.count > 0 {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let arguments = if desc.count == 0 {
|
||||
Vec::new()
|
||||
} else {
|
||||
// SAFETY: the title passes `count` argument descriptions.
|
||||
unsafe { std::slice::from_raw_parts(desc.arguments, desc.count as usize) }.to_vec()
|
||||
};
|
||||
tracing::debug!(stride = desc.stride, ?arguments, "command signature");
|
||||
let signature = Box::new(Signature {
|
||||
object: Object::new(&FUNCTIONS),
|
||||
stride: desc.stride,
|
||||
arguments,
|
||||
});
|
||||
object::hand_out(COMMAND_SIGNATURE, signature, iid, &SIGNATURE_IIDS, out)
|
||||
}
|
||||
|
||||
extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
|
||||
let found = object::is(iid, &SIGNATURE_IIDS).then_some(this);
|
||||
object::answer(COMMAND_SIGNATURE, iid, found, out)
|
||||
}
|
||||
extern "system" fn release(this: This) -> u32 {
|
||||
object::release_boxed::<Signature>(this)
|
||||
}
|
||||
|
||||
/// IUnknown 3, object 4, device child 1.
|
||||
static FUNCTIONS: Table<8> = {
|
||||
let mut f = object::d3d12_object(object::missing_table::<COMMAND_SIGNATURE, 8>());
|
||||
f[0] = query as *const ();
|
||||
f[2] = release as *const ();
|
||||
f[7] = object::parent_device as *const (); // 0x38
|
||||
Table(f)
|
||||
};
|
||||
Reference in new issue
Block a user