//! 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, event: HANDLE, rtvs: ID3D12DescriptorHeap, rtv_size: u32, /// With `VICTORY_D3D12_DEBUG` set: the debug layer's messages. messages: Option, next_rtv: AtomicU32, presenter: Mutex>, } // 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> = 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 { // 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 = 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 = 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::().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, /// 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, } impl Host { /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result { // 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> = 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::(); 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 = 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 { 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::(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 { 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::()?; 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 { 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) = Some(hwnd); return false.into(); } } true.into() } let mut found: Option = 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 { 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 { 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::() 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); } } }