mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
XDefiant title screen: shared descriptor heap, quad lane reads, audio processor, GameInput
- Console view descriptors are values: titles create them in a CPU-only heap and copy them into the shader-visible one as memory (the header's inline CopyDescriptorsSimple). T# word 0 was an index into each heap's own PC heap, so every copied T# named an empty descriptor (all frames black). All console view heaps now share one shader-visible PC heap (T# word 0 indexes it, lists bind it, the title's own heap is a CPU-only mirror). - Write-watch scans cover only what the GPU sees (textures kept in step, sparse tiles with video memory) instead of 16+ GiB per submit: ~2 -> ~40 fps. - Pixel shaders read lanes of their own quad with QuadReadLaneAt (helper lanes included): derivatives taken across a quad were wrong along triangle edges (seams on large quads); test with the console compiler. - acphal / xapu: APU memory, the processor's channel (commands acknowledged, audio frames ticking), SHAPE context arrays, the decoder answering with silence - the title's audio setup no longer aborts (still silent: SHAPE is not run). - GameInput: the GDK v0 interfaces with one gamepad (XInput controller, keyboard), ordinal #1; XCL_PRESS_A_AT for tests. The title screen takes A. - Diagnostics under XCL_TRACE_FRAME (heap census, descriptor copies, full-screen dispatch arguments), sparse upload timing; HANDOFF updated.
This commit is contained in:
+51
-7
@@ -1109,12 +1109,54 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76
|
||||
`note_alias`). GPU-owned textures (render target / depth / UAV flags) now go to *arenas*: default heaps standing for
|
||||
ranges of title addresses (from the 32 MiB below, at least 128 MiB), placed at their address's offset, so resources
|
||||
at one address share memory. ~16 arenas in XDefiant's first 25 s. Other textures stay committed and mirrored.
|
||||
- **XDefiant now (2026-11-22)**: runs 90 s without a GPU hang and ends itself (`XCL_RUN_SECONDS`); ~1 500 console
|
||||
shaders translated, thousands of draws and dispatches, nothing skipped. The presented 3840x2160 buffer is still
|
||||
black: it is written by a compute pass through a UAV (never a render target); the scene / UI render targets are
|
||||
(almost) black too – the title may be at its online-login gate (another implementer: it retries RTA / Ubisoft
|
||||
services), or something in the frame is still wrong. ~2.3 frames per second: the sparse-window uploads cost ~30 ms
|
||||
a submit (126 s in 4 096 submits) – next to optimise (no wait for idle per upload, cheaper dirty scan).
|
||||
- **XDefiant now (2026-11-22, later)**: its title screen is on screen – logo, "Welcome, Player1#0001", "press A to
|
||||
start / change account" (in the system's language), ~40–50 frames per second there (release build). After a
|
||||
change to the translated pixel shaders' HLSL the DXIL cache misses: ~1 500 pixel shaders compile in the
|
||||
background over two or three runs, and until a pipeline is built it draws nothing (black or half-drawn frames –
|
||||
check "new dxil" before blaming a change).
|
||||
- **Seams along triangle edges (fixed)**: dotted lines on the diagonal of the logo's quads. The console takes
|
||||
derivatives across a quad's lanes by hand (DPP quad_perm, ds_swizzle) and reads the helper pixels of quads a
|
||||
primitive's edge splits; `rla` read lanes with WaveReadLaneAt, which leaves helper lanes out before SM 6.7. Pixel
|
||||
shaders now read lanes of their own quad with QuadReadLaneAt (quad operations include helper lanes) – `XCL_PIXEL`
|
||||
in the prelude; `console_compiled_derivatives_hold_on_triangle_edges` (two triangles, ddx_fine / ddy_fine: 48 of
|
||||
1 024 pixels wrong before, 0 after). Do NOT use `[WaveOpsIncludeHelperLanes]` (ps_6_7): tried, the device hung
|
||||
~9 s in – with it the entry `ballot(true)` (the live mask the console code returns to after `s_wqm`) includes the
|
||||
helper lanes, so they never stop. Ballots (v_cmp) still leave helper lanes out (matters for branches inside
|
||||
whole-quad sections). The console sets IASetPrimitiveTopology 17 (rectangle lists) for these quads; the AMD driver
|
||||
draws them as two triangles here – rectangle lists are not modelled otherwise.
|
||||
- **Why every frame was black: descriptors are values.** XDefiant makes its views in a CPU-only heap (131 072
|
||||
slots) and copies them into its shader-visible heap (442 368 slots) as memory – the console header's inline
|
||||
CopyDescriptorsSimple; only sampler copies reach the device. T# word 0 was an index into each heap's own PC heap,
|
||||
so every copied T# named a descriptor of the wrong heap (empty): shaders read zeros, UAV writes went nowhere – the
|
||||
presented buffers stayed 0 including alpha. Now all console view heaps share one shader-visible PC heap
|
||||
(`console_heap`, `Global`: up to 2^21 descriptors, OPTIONS19 says this GPU takes 32 M): each heap gets a range,
|
||||
T# word 0 is an index into the shared heap (a copied T# still names its PC descriptor), lists bind the shared
|
||||
heap whatever the title names (`list_x::pc_heaps`: console #32 and the console-list replay), the title's own PC
|
||||
heap is a CPU-only mirror (views are made there and copied over – `publish`; copies come from it; UAV clears take
|
||||
its CPU handle). A heap that finds no room keeps its own PC heap (the old way). Copies follow the source PC
|
||||
descriptor: a source slot rewritten later changes earlier copies too (not seen).
|
||||
- **Speed**: the per-submit write-watch scan covered every watched region (4 GiB of window 0, 12 GiB of sparse
|
||||
windows, graphics reservations): ~10 ms a submit, more than half of all time. It now covers only where a CPU write
|
||||
matters – the textures kept in step and the sparse tiles with video memory (`title_textures::watch_ranges`,
|
||||
`sparse::mapped_ranges`). Use the release build for game runs: the debug build hashes the dirty chunks ~10×
|
||||
slower (and the queues then wait on each other for the sparse lock). The log has
|
||||
"sparse windows timing: write-watch / lock wait / chunk scan / upload" lines.
|
||||
- **Controllers** (`hle::gameinput`): GameInput.dll was Windows' own (other interfaces, reads only for its own
|
||||
foreground app) – the title never saw a button. Now XCL's: the GDK's v0 interfaces (IGameInput, IGameInputDevice,
|
||||
IGameInputReading in the public header's order), one gamepad always connected, read from the PC's first XInput
|
||||
controller plus the keyboard while a window of the process has the focus (Enter / Space A, Escape / Backspace B,
|
||||
arrows D-pad, Tab View, P Menu); device callbacks (blocking / asynchronous enumeration), reading callbacks
|
||||
(polled at 250 Hz), UI navigation state, rumble through XInputSetState. XDefiant imports GameInputCreate by
|
||||
ordinal #1 (`stubdb.toml`). `XCL_PRESS_A_AT=s1,s2…` presses A for 200 ms at those seconds (tests). With it the
|
||||
title screen takes A and goes to a loading screen (spinner) – it then waits, most likely for Ubisoft's services
|
||||
(the network gate, next).
|
||||
- **Audio processor** (`hle::acphal`, routes acphal.dll and xapu.dll; chad.dll / XDsp stays E_NOTIMPL): APU memory
|
||||
(32-bit APU addresses for ApuAlloc / ApuMapVirtualAddress), AcpHalCreate's channel (commands acknowledged at once,
|
||||
an audio frame message every 2.667 ms), SHAPE context arrays, the xapu decoder answering with silence. Before,
|
||||
`ApuCreateHeap` got E_NOTIMPL and XDefiant dropped its whole audio setup (+0x7639ef). Now it creates a 350 MB APU
|
||||
heap, connects the decoder (320 streams), SHAPE contexts [512, 0, 0, 1024, 512] and the channel (commands 2 and
|
||||
8). Its audio is still silent: it mixes through SHAPE (not XAudio2 – only bink2scarlett.dll imports XAudio2),
|
||||
and SHAPE contexts are not run; that is the next step for sound (context layouts unknown).
|
||||
- **What made the GPU hang** (four PC reboots – the AMD driver did not always recover from the TDR): vertex buffers.
|
||||
Console #48 IASetVertexBuffers gave the title's addresses to the PC as GPU addresses – the index buffer was
|
||||
translated, the vertex buffers were not (NaN in every render target, then device hangs). `ia_set_vertex_buffers_x`.
|
||||
@@ -1145,7 +1187,9 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76
|
||||
as CJK characters); `hle::user` makes them Unicode calls. The window stays white (console titles never paint it).
|
||||
- Diagnostics: `XCL_TRACE_FRAME=1` (what console code does with each presented resource; render-target binds, UAV
|
||||
views of large render targets, clear colours; with `XCL_FRAME_DUMP` also the busiest render target and raw texel
|
||||
histograms), `XCL_TRACE_ADDRESSES=1` (root descriptor addresses in / outside unified memory), `XCL_DRED=1` (DRED
|
||||
histograms; the console descriptor heaps made, the device's descriptor copies, a census of what each view heap's
|
||||
slots hold – T# with their own index / another (copied as memory) / buffers – and, for full-screen dispatches, the
|
||||
root arguments and constant-buffer words with the resources their small values index in the dispatch's tables), `XCL_TRACE_ADDRESSES=1` (root descriptor addresses in / outside unified memory), `XCL_DRED=1` (DRED
|
||||
page fault + breadcrumbs on a device removal – opt-in: twice the title stalled with it), `XCL_LIST_TRACE=1`.
|
||||
- **Notes from another implementer** (user-provided): XDefiant also calls XGCreateTextureComputerFromDescriptor, then
|
||||
libHttpClient / XCurl (XUserGetTokenAndSignature*, XNetworking) and retries wss://rta.xboxlive.com/connect every
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
"d3d12_x.dll" = "E_NOTIMPL"
|
||||
"xg_xs.dll" = "E_NOTIMPL"
|
||||
"acphal.dll" = "E_NOTIMPL"
|
||||
# the console's audio decoder and DSP: what XCL does not answer is not there
|
||||
"xapu.dll" = "E_NOTIMPL"
|
||||
"chad.dll" = "E_NOTIMPL"
|
||||
# console DirectStorage (DStorageGetFactory) and the Xbox One texture layout library: a fake S_OK
|
||||
# would leave the title's output pointer as it was
|
||||
"xcrdapi.dll" = "E_NOTIMPL"
|
||||
@@ -30,6 +33,10 @@
|
||||
"*!XGameUiShowAchievementsAsync" = "E_ABORT"
|
||||
"*!XGameUiShowPlayerProfileCardAsync" = "E_ABORT"
|
||||
|
||||
[ordinals."gameinput.dll"]
|
||||
# the console's GameInput.dll exports GameInputCreate as #1 (XDefiant imports it by ordinal)
|
||||
1 = "GameInputCreate"
|
||||
|
||||
[ordinals."xaudio2_9.dll"]
|
||||
# Export ordinals of Windows' xaudio2_9.dll (Bink2Scarlett.dll imports #1); assumed the same on the console.
|
||||
1 = "XAudio2Create"
|
||||
|
||||
@@ -3420,6 +3420,10 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}"
|
||||
pub fn finish(&self, body: &str) -> String {
|
||||
let mut h = String::new();
|
||||
h.push_str("// generated by XCL (RDNA2 -> HLSL), do not edit\n");
|
||||
if matches!(self.opt.mode, Mode::Pixel(_)) {
|
||||
// lane reads within a quad see helper lanes (`rla`)
|
||||
h.push_str("#define XCL_PIXEL 1\n");
|
||||
}
|
||||
h.push_str("RWByteAddressBuffer io : register(u0);\nRWByteAddressBuffer res : register(u1);\n");
|
||||
// compute work across workgroups (bottom-up BVH builds: atomics, then reading what
|
||||
// other groups wrote) relies on GLC / cache invalidation on the console: keep the flat
|
||||
@@ -4383,8 +4387,18 @@ uint2 ballot(bool b) {
|
||||
return uint2(select(and(xcl_w32, xcl_half != 0u), m.y, m.x), select(xcl_w32, 0u, m.y));
|
||||
}
|
||||
uint rla(uint v, uint l) {
|
||||
if (xcl_logical_wave64) return (l >> 5) == xcl_half ? WaveReadLaneAt(v, l & 31u) : 0u;
|
||||
return WaveReadLaneAt(v, l + 32u * xcl_half);
|
||||
uint w;
|
||||
if (xcl_logical_wave64) w = (l >> 5) == xcl_half ? WaveReadLaneAt(v, l & 31u) : 0u;
|
||||
else w = WaveReadLaneAt(v, l + 32u * xcl_half);
|
||||
#ifdef XCL_PIXEL
|
||||
// A lane of the reader's own quad through a quad read: those see helper lanes (wave reads
|
||||
// do not before SM 6.7), and the console's derivatives (DPP quad_perm, ds_swizzle) read the
|
||||
// helper pixels of a quad a primitive's edge splits.
|
||||
uint q0 = QuadReadLaneAt(v, 0u), q1 = QuadReadLaneAt(v, 1u), q2 = QuadReadLaneAt(v, 2u), q3 = QuadReadLaneAt(v, 3u);
|
||||
uint q = (l & 2u) != 0u ? ((l & 1u) != 0u ? q3 : q2) : ((l & 1u) != 0u ? q1 : q0);
|
||||
if ((l >> 2) == (lane_id >> 2)) w = q;
|
||||
#endif
|
||||
return w;
|
||||
}
|
||||
bool lanebit_at(uint lo, uint hi, uint l) { return ((select(l < 32u, lo, hi) >> (l & 31u)) & 1u) != 0u; }
|
||||
uint sdwa_sel(uint x, uint sel, bool sext) {
|
||||
|
||||
@@ -0,0 +1,649 @@
|
||||
//! The console's audio processor (`acphal.dll`, `xapu.dll`): memory the audio hardware
|
||||
//! addresses, the processor's command / message channel, SHAPE contexts and the decoder queue.
|
||||
//!
|
||||
//! Nothing is decoded or mixed here – the processor answers as hardware with no work to do:
|
||||
//! commands are acknowledged, audio frames tick (one every 128 samples at 48 kHz), SHAPE
|
||||
//! context arrays exist, and the decoder returns silence of the length asked for. A title's
|
||||
//! audio engine then starts and runs (XDefiant: `ApuCreateHeap` failing made it drop its whole
|
||||
//! audio setup), sounds decoded in software go wherever the engine sends them, and nothing
|
||||
//! waits forever on the processor. Audio through the console's mixer (SHAPE) stays silent.
|
||||
//!
|
||||
//! Interfaces as titles call them (observed on retail titles; another project's notes on
|
||||
//! the same titles agree): `ApuAlloc(&va, &apu, size, alignment, flags)`,
|
||||
//! `ApuMapVirtualAddress(&apu, va, size)`, `ApuMapApuAddress(apu) -> va`,
|
||||
//! `AcpHalCreate(&hal)` – an object whose vtable is Connect(commands, messages), Disconnect,
|
||||
//! SubmitCommand(type, id, frame, data, size), PopMessage(&message) -> bool,
|
||||
//! GetNumMessages, Release; messages {u32 type, u32, u64 value, u64 id}: 2 audio frame,
|
||||
//! 0x10 command done (id), 0x80 disconnected. `chad.dll` (XDsp) is left to the stub database:
|
||||
//! E_NOTIMPL, the processor's DSP is not there.
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::util::{HRESULT, S_OK};
|
||||
|
||||
const E_INVALIDARG: HRESULT = 0x8007_0057_u32 as i32;
|
||||
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
|
||||
const E_UNEXPECTED: HRESULT = 0x8000_FFFF_u32 as i32;
|
||||
/// XApuDequeueResult: no result waiting
|
||||
const XAPU_NO_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
|
||||
|
||||
/// one audio frame: 128 samples at 48 kHz
|
||||
const FRAME: Duration = Duration::from_micros(2667);
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// memory the audio processor addresses (32-bit APU addresses)
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
struct Region {
|
||||
va: usize,
|
||||
size: u32,
|
||||
apu: u32,
|
||||
/// allocated here (ApuAlloc), released by ApuFree
|
||||
owned: bool,
|
||||
}
|
||||
|
||||
struct Apu {
|
||||
regions: Vec<Region>,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
static APU: Mutex<Apu> = Mutex::new(Apu { regions: Vec::new(), next: 0x1000_0000 });
|
||||
|
||||
impl Apu {
|
||||
/// The APU address of `va` – in a known region, or a new region of `size` bytes there.
|
||||
fn address(&mut self, va: usize, size: u32, owned: bool) -> u32 {
|
||||
if let Some(r) = self.regions.iter().find(|r| va >= r.va && va - r.va < r.size.max(1) as usize) {
|
||||
return r.apu + (va - r.va) as u32;
|
||||
}
|
||||
let apu = self.next;
|
||||
self.next = self.next.wrapping_add((size.max(1) + 0xFFF) & !0xFFF);
|
||||
self.regions.push(Region { va, size, apu, owned });
|
||||
apu
|
||||
}
|
||||
}
|
||||
|
||||
/// `size` bytes aligned to `align` (zeroed; the allocation's base is `va` rounded down to
|
||||
/// 64 KiB – VirtualAlloc's granularity – so MEM_RELEASE of it frees all)
|
||||
unsafe fn alloc_aligned(size: usize, align: usize) -> Option<usize> {
|
||||
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
|
||||
let align = align.max(1).next_power_of_two();
|
||||
if align <= 0x1_0000 {
|
||||
let p = VirtualAlloc(std::ptr::null(), size.max(1), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as usize;
|
||||
return (p != 0).then_some(p);
|
||||
}
|
||||
// reserve enough to find an aligned start, then reserve exactly there
|
||||
for _ in 0..8 {
|
||||
let p = VirtualAlloc(std::ptr::null(), size + align, MEM_RESERVE, PAGE_READWRITE) as usize;
|
||||
if p == 0 {
|
||||
return None;
|
||||
}
|
||||
VirtualFree(p as *mut c_void, 0, MEM_RELEASE);
|
||||
let a = (p + align - 1) & !(align - 1);
|
||||
let q = VirtualAlloc(a as *const c_void, size.max(1), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as usize;
|
||||
if q == a {
|
||||
return Some(q);
|
||||
}
|
||||
if q != 0 {
|
||||
VirtualFree(q as *mut c_void, 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// ApuCreateHeap(size, flags): the heap ApuAlloc takes from – the process's memory here.
|
||||
pub unsafe extern "system" fn ApuCreateHeap(size: u32, flags: u32) -> HRESULT {
|
||||
crate::xlog_info!("acphal: ApuCreateHeap({size:#x}, {flags:#x}) – the audio processor's memory is the process's");
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// ApuAlloc(&va, &apu, size, alignment, flags)
|
||||
pub unsafe extern "system" fn ApuAlloc(va: *mut *mut c_void, apu: *mut u32, size: u32, alignment: u32, _flags: u32) -> HRESULT {
|
||||
if va.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let Some(p) = alloc_aligned(size as usize, alignment as usize) else {
|
||||
*va = std::ptr::null_mut();
|
||||
return E_OUTOFMEMORY;
|
||||
};
|
||||
*va = p as *mut c_void;
|
||||
let a = APU.lock().unwrap().address(p, size, true);
|
||||
if !apu.is_null() {
|
||||
*apu = a;
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// ApuFree(va)
|
||||
pub unsafe extern "system" fn ApuFree(va: *mut c_void) -> HRESULT {
|
||||
use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE};
|
||||
if va.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let owned = {
|
||||
let mut g = APU.lock().unwrap();
|
||||
let i = g.regions.iter().position(|r| r.va == va as usize);
|
||||
i.map(|i| g.regions.swap_remove(i).owned).unwrap_or(false)
|
||||
};
|
||||
if owned {
|
||||
VirtualFree(va, 0, MEM_RELEASE);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// ApuMapVirtualAddress(&apu, va, size): an APU address for the title's own memory
|
||||
pub unsafe extern "system" fn ApuMapVirtualAddress(apu: *mut u32, va: *mut c_void, size: u32) -> HRESULT {
|
||||
if apu.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
*apu = APU.lock().unwrap().address(va as usize, size, false);
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// ApuMapApuAddress(apu) -> the memory an APU address stands for (null: none)
|
||||
pub unsafe extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void {
|
||||
let g = APU.lock().unwrap();
|
||||
g.regions
|
||||
.iter()
|
||||
.find(|r| apu >= r.apu && apu - r.apu < r.size.max(1))
|
||||
.map_or(std::ptr::null_mut(), |r| (r.va + (apu - r.apu) as usize) as *mut c_void)
|
||||
}
|
||||
|
||||
/// ApuIsVirtualAddressValid: all of the process's memory is the processor's here
|
||||
pub unsafe extern "system" fn ApuIsVirtualAddressValid(_va: *const c_void, _size: u32) -> i32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// ApuHeapGetState(&state, flags): free bytes, bytes in use, bytes lost, the largest free
|
||||
/// block, blocks – there is always room
|
||||
pub unsafe extern "system" fn ApuHeapGetState(state: *mut u32, _flags: u32) -> HRESULT {
|
||||
if state.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let g = APU.lock().unwrap();
|
||||
let used: u32 = g.regions.iter().filter(|r| r.owned).map(|r| r.size).fold(0, u32::wrapping_add);
|
||||
let s = std::slice::from_raw_parts_mut(state, 5);
|
||||
s.copy_from_slice(&[256 << 20, used, 0, 64 << 20, g.regions.len() as u32]);
|
||||
S_OK
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// SHAPE contexts
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
/// AcpHalAllocateShapeContexts' argument: counts of the five kinds, then an array of each
|
||||
#[repr(C)]
|
||||
pub struct ShapeContexts {
|
||||
counts: [u32; 5],
|
||||
reserved: u32,
|
||||
contexts: [*mut c_void; 5],
|
||||
}
|
||||
|
||||
/// bytes of a context entry (the largest seen)
|
||||
const CONTEXT_BYTES: u32 = 64;
|
||||
static SHAPE: Mutex<[usize; 5]> = Mutex::new([0; 5]);
|
||||
|
||||
/// AcpHalAllocateShapeContexts(&contexts): an array of each kind in APU memory (none run)
|
||||
pub unsafe extern "system" fn AcpHalAllocateShapeContexts(c: *mut ShapeContexts) -> HRESULT {
|
||||
if c.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let c = &mut *c;
|
||||
let mut arrays = SHAPE.lock().unwrap();
|
||||
for i in 0..5 {
|
||||
c.contexts[i] = std::ptr::null_mut();
|
||||
if c.counts[i] == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut va = std::ptr::null_mut();
|
||||
let hr = ApuAlloc(&mut va, std::ptr::null_mut(), c.counts[i].saturating_mul(CONTEXT_BYTES), 256, 0);
|
||||
if hr < 0 {
|
||||
return hr;
|
||||
}
|
||||
arrays[i] = va as usize;
|
||||
c.contexts[i] = va;
|
||||
}
|
||||
crate::xlog_info!("acphal: SHAPE contexts {:?} (they do not run: no audio from the console's mixer)", c.counts);
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// AcpHalReleaseShapeContexts()
|
||||
pub unsafe extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
|
||||
let arrays = std::mem::take(&mut *SHAPE.lock().unwrap());
|
||||
for a in arrays.into_iter().filter(|&a| a != 0) {
|
||||
ApuFree(a as *mut c_void);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// the processor's command / message channel (AcpHalCreate)
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
|
||||
pub struct Message {
|
||||
pub kind: u32,
|
||||
pub reserved: u32,
|
||||
pub value: u64,
|
||||
pub id: u64,
|
||||
}
|
||||
|
||||
pub const MSG_AUDIO_FRAME: u32 = 2;
|
||||
pub const MSG_COMMAND_DONE: u32 = 0x10;
|
||||
pub const MSG_DISCONNECTED: u32 = 0x80;
|
||||
|
||||
/// What the channel holds: queued messages and when the next audio frame is due.
|
||||
#[derive(Default)]
|
||||
pub struct Channel {
|
||||
messages: VecDeque<Message>,
|
||||
connected: bool,
|
||||
next_frame: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub fn connect(&mut self, now: Instant) {
|
||||
self.connected = true;
|
||||
self.next_frame = Some(now + FRAME);
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self) {
|
||||
self.connected = false;
|
||||
self.messages.push_back(Message { kind: MSG_DISCONNECTED, ..Default::default() });
|
||||
}
|
||||
|
||||
/// A command: done at once (a message for it unless its id is 0 – nobody waits).
|
||||
pub fn submit(&mut self, id: u64) -> bool {
|
||||
if !self.connected {
|
||||
return false;
|
||||
}
|
||||
if id != 0 {
|
||||
self.messages.push_back(Message { kind: MSG_COMMAND_DONE, id, ..Default::default() });
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn frame_due(&self, now: Instant) -> bool {
|
||||
self.connected && self.next_frame.is_some_and(|t| now >= t)
|
||||
}
|
||||
|
||||
/// The next message: queued ones first, else an audio frame when one is due (a frame
|
||||
/// late by more than 8 is not made up for).
|
||||
pub fn pop(&mut self, now: Instant) -> Option<Message> {
|
||||
if let Some(m) = self.messages.pop_front() {
|
||||
return Some(m);
|
||||
}
|
||||
if self.frame_due(now) {
|
||||
let t = self.next_frame.unwrap_or(now) + FRAME;
|
||||
self.next_frame = Some(t.max(now - FRAME * 8));
|
||||
return Some(Message { kind: MSG_AUDIO_FRAME, ..Default::default() });
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn count(&self, now: Instant) -> u32 {
|
||||
self.messages.len() as u32 + self.frame_due(now) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct Hal {
|
||||
vtable: *const usize,
|
||||
channel: Mutex<Channel>,
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_connect(h: *mut Hal, commands: u32, messages: u32) -> HRESULT {
|
||||
(*h).channel.lock().unwrap().connect(Instant::now());
|
||||
crate::xlog_info!("acphal: audio processor connected ({commands} commands, {messages} messages) – commands are acknowledged, nothing runs");
|
||||
S_OK
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_disconnect(h: *mut Hal) -> HRESULT {
|
||||
(*h).channel.lock().unwrap().disconnect();
|
||||
S_OK
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_submit(h: *mut Hal, kind: u32, id: u64, _frame: u32, _data: *const c_void, _size: u32) -> HRESULT {
|
||||
static SEEN: Mutex<Vec<u32>> = Mutex::new(Vec::new());
|
||||
{
|
||||
let mut s = SEEN.lock().unwrap();
|
||||
if !s.contains(&kind) && s.len() < 64 {
|
||||
s.push(kind);
|
||||
crate::xlog_info!("acphal: audio processor command {kind:#x} first seen");
|
||||
}
|
||||
}
|
||||
if (*h).channel.lock().unwrap().submit(id) {
|
||||
S_OK
|
||||
} else {
|
||||
E_UNEXPECTED
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_pop(h: *mut Hal, m: *mut Message) -> bool {
|
||||
if m.is_null() {
|
||||
return false;
|
||||
}
|
||||
match (*h).channel.lock().unwrap().pop(Instant::now()) {
|
||||
Some(x) => {
|
||||
*m = x;
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_count(h: *mut Hal) -> u32 {
|
||||
(*h).channel.lock().unwrap().count(Instant::now())
|
||||
}
|
||||
|
||||
unsafe extern "system" fn hal_release(h: *mut Hal) {
|
||||
drop(Box::from_raw(h));
|
||||
}
|
||||
|
||||
/// the channel object's vtable (made once; function addresses are not constants)
|
||||
fn hal_vtable() -> *const usize {
|
||||
static V: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
*V.get_or_init(|| {
|
||||
let v: Box<[usize; 6]> = Box::new([hal_connect as usize, hal_disconnect as usize, hal_submit as usize, hal_pop as usize, hal_count as usize, hal_release as usize]);
|
||||
Box::leak(v).as_ptr() as usize
|
||||
}) as *const usize
|
||||
}
|
||||
|
||||
/// AcpHalCreate(&hal)
|
||||
pub unsafe extern "system" fn AcpHalCreate(out: *mut *mut c_void) -> HRESULT {
|
||||
if out.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let h = Box::new(Hal { vtable: hal_vtable(), channel: Mutex::new(Channel::default()) });
|
||||
*out = Box::into_raw(h) as *mut c_void;
|
||||
S_OK
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// xapu.dll: the decoder's command queue
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct XApuCommand {
|
||||
pub kind: u32,
|
||||
pub stream: u32,
|
||||
pub sequence: u32,
|
||||
pub options: u32,
|
||||
pub context: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
struct XApuActivate {
|
||||
id: XApuCommand,
|
||||
channels: u32,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
struct XApuProcess {
|
||||
id: XApuCommand,
|
||||
ramp: f32,
|
||||
pitch: f32,
|
||||
first_frame: u32,
|
||||
frames: u32,
|
||||
input_bytes: u32,
|
||||
input: *mut c_void,
|
||||
output_bytes: u32,
|
||||
output: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct XApuResult {
|
||||
pub id: XApuCommand,
|
||||
pub state: u32,
|
||||
pub state_data: u64,
|
||||
pub time: u64,
|
||||
pub error: HRESULT,
|
||||
pub frames: u32,
|
||||
pub output_bytes: u32,
|
||||
pub output: *mut c_void,
|
||||
pub pitch: f32,
|
||||
pub input_bytes: u32,
|
||||
pub input: *mut c_void,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
pub struct XApuConnectInput {
|
||||
process: u32,
|
||||
streams: u32,
|
||||
commands_per_stream: u32,
|
||||
data_bytes: u32,
|
||||
frames_per_output: u32,
|
||||
options: u32,
|
||||
}
|
||||
|
||||
#[repr(C, packed)]
|
||||
pub struct XApuConnectOutput {
|
||||
data: *mut c_void,
|
||||
ready: *mut c_void,
|
||||
}
|
||||
|
||||
const XAPU_ACTIVATE: u32 = 1;
|
||||
const XAPU_PROCESS: u32 = 3;
|
||||
|
||||
struct XApu {
|
||||
results: Mutex<VecDeque<XApuResult>>,
|
||||
channels: Mutex<Vec<u32>>,
|
||||
data: usize,
|
||||
ready: usize,
|
||||
frames_per_output: u32,
|
||||
}
|
||||
|
||||
/// XApuConnect(&input, &output, &handle)
|
||||
pub unsafe extern "system" fn XApuConnect(input: *const XApuConnectInput, output: *mut XApuConnectOutput, handle: *mut *mut c_void) -> HRESULT {
|
||||
use windows_sys::Win32::System::Threading::CreateEventW;
|
||||
if input.is_null() || output.is_null() || handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let i = std::ptr::read_unaligned(input);
|
||||
let data = if i.data_bytes != 0 { alloc_aligned(i.data_bytes as usize, 0x1_0000).unwrap_or(0) } else { 0 };
|
||||
let ready = if i.options & 8 != 0 { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize } else { 0 };
|
||||
let x = Box::new(XApu { results: Mutex::new(VecDeque::new()), channels: Mutex::new(vec![2; i.streams.max(1) as usize]), data, ready, frames_per_output: i.frames_per_output });
|
||||
std::ptr::write_unaligned(output, XApuConnectOutput { data: data as *mut c_void, ready: ready as *mut c_void });
|
||||
*handle = Box::into_raw(x) as *mut c_void;
|
||||
let (process, streams) = (i.process, i.streams);
|
||||
crate::xlog_info!("xapu: decoder connected (process {process}, {streams} streams) – it answers with silence");
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// XApuDisconnect(handle)
|
||||
pub unsafe extern "system" fn XApuDisconnect(handle: *mut c_void) -> HRESULT {
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE};
|
||||
if handle.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let x = Box::from_raw(handle as *mut XApu);
|
||||
if x.data != 0 {
|
||||
VirtualFree(x.data as *mut c_void, 0, MEM_RELEASE);
|
||||
}
|
||||
if x.ready != 0 {
|
||||
CloseHandle(x.ready as _);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// XApuEnqueueCommand(handle, &command, &results waiting): done at once – a Process command
|
||||
/// with silence of the length asked for
|
||||
pub unsafe extern "system" fn XApuEnqueueCommand(handle: *mut c_void, command: *const XApuCommand, count: *mut u32) -> HRESULT {
|
||||
use windows_sys::Win32::System::Threading::SetEvent;
|
||||
if handle.is_null() || command.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
let x = &*(handle as *const XApu);
|
||||
let c = std::ptr::read_unaligned(command);
|
||||
let mut r = XApuResult { id: c, state: 0, state_data: 0, time: 0, error: S_OK, frames: 0, output_bytes: 0, output: std::ptr::null_mut(), pitch: 1.0, input_bytes: 0, input: std::ptr::null_mut() };
|
||||
{
|
||||
let mut ch = x.channels.lock().unwrap();
|
||||
let s = if (c.stream as usize) < ch.len() { c.stream as usize } else { 0 };
|
||||
if c.kind == XAPU_ACTIVATE {
|
||||
let n = std::ptr::read_unaligned(command as *const XApuActivate).channels;
|
||||
ch[s] = if n == 1 { 1 } else { 2 };
|
||||
} else if c.kind == XAPU_PROCESS {
|
||||
let p = std::ptr::read_unaligned(command as *const XApuProcess);
|
||||
let frame_bytes = ch[s] * 4;
|
||||
let asked = if p.frames != 0 { p.frames } else { x.frames_per_output };
|
||||
let frames = (if asked != 0 { asked } else { 960 }).min(p.output_bytes / frame_bytes);
|
||||
if !p.output.is_null() && frames != 0 {
|
||||
std::ptr::write_bytes(p.output as *mut u8, 0, (frames * frame_bytes) as usize);
|
||||
}
|
||||
// output ready, more input wanted
|
||||
r.state = 1 | 2;
|
||||
r.frames = frames;
|
||||
r.output_bytes = frames * frame_bytes;
|
||||
r.output = p.output;
|
||||
r.pitch = p.pitch;
|
||||
r.input_bytes = p.input_bytes;
|
||||
r.input = p.input;
|
||||
}
|
||||
}
|
||||
let n = {
|
||||
let mut q = x.results.lock().unwrap();
|
||||
q.push_back(r);
|
||||
q.len() as u32
|
||||
};
|
||||
if !count.is_null() {
|
||||
*count = n;
|
||||
}
|
||||
if x.ready != 0 && c.options & 1 != 0 {
|
||||
SetEvent(x.ready as _);
|
||||
}
|
||||
S_OK
|
||||
}
|
||||
|
||||
/// XApuDequeueResult(handle, &result)
|
||||
pub unsafe extern "system" fn XApuDequeueResult(handle: *mut c_void, result: *mut XApuResult) -> HRESULT {
|
||||
if handle.is_null() || result.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
match (*(handle as *const XApu)).results.lock().unwrap().pop_front() {
|
||||
Some(r) => {
|
||||
std::ptr::write_unaligned(result, r);
|
||||
S_OK
|
||||
}
|
||||
None => XAPU_NO_RESULTS,
|
||||
}
|
||||
}
|
||||
|
||||
/// XApuGetResultCount(handle, &count) -> count
|
||||
pub unsafe extern "system" fn XApuGetResultCount(handle: *mut c_void, total: *mut u32) -> u32 {
|
||||
if handle.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let n = (*(handle as *const XApu)).results.lock().unwrap().len() as u32;
|
||||
if !total.is_null() {
|
||||
*total = n;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// XApuGetUtilization(…, &utilization): streams available and the most there can be
|
||||
pub unsafe extern "system" fn XApuGetUtilization(_a: u32, _b: u32, u: *mut u32) -> HRESULT {
|
||||
if u.is_null() {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
*u = 256;
|
||||
*u.add(1) = 256;
|
||||
S_OK
|
||||
}
|
||||
|
||||
pub fn exports() -> Vec<(&'static str, usize)> {
|
||||
crate::hle_exports![
|
||||
ApuCreateHeap,
|
||||
ApuAlloc,
|
||||
ApuFree,
|
||||
ApuMapVirtualAddress,
|
||||
ApuMapApuAddress,
|
||||
ApuIsVirtualAddressValid,
|
||||
ApuHeapGetState,
|
||||
AcpHalCreate,
|
||||
AcpHalAllocateShapeContexts,
|
||||
AcpHalReleaseShapeContexts,
|
||||
XApuConnect,
|
||||
XApuDisconnect,
|
||||
XApuEnqueueCommand,
|
||||
XApuDequeueResult,
|
||||
XApuGetResultCount,
|
||||
XApuGetUtilization,
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn apu_memory_maps_both_ways() {
|
||||
unsafe {
|
||||
let (mut va, mut apu) = (std::ptr::null_mut(), 0u32);
|
||||
assert_eq!(ApuAlloc(&mut va, &mut apu, 0x3000, 0x2_0000, 0), S_OK);
|
||||
assert_eq!(va as usize % 0x2_0000, 0, "alignment above 64 KiB");
|
||||
assert_eq!(ApuMapApuAddress(apu + 0x10) as usize, va as usize + 0x10);
|
||||
let mut again = 0u32;
|
||||
assert_eq!(ApuMapVirtualAddress(&mut again, (va as usize + 0x20) as *mut c_void, 4), S_OK);
|
||||
assert_eq!(again, apu + 0x20);
|
||||
assert_eq!(ApuFree(va), S_OK);
|
||||
assert!(ApuMapApuAddress(apu).is_null());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_acknowledges_and_ticks() {
|
||||
let t0 = Instant::now();
|
||||
let mut c = Channel::default();
|
||||
assert!(!c.submit(7), "not connected yet");
|
||||
c.connect(t0);
|
||||
assert!(c.submit(7));
|
||||
assert!(c.submit(0), "id 0: no message");
|
||||
assert_eq!(c.count(t0), 1);
|
||||
assert_eq!(c.pop(t0), Some(Message { kind: MSG_COMMAND_DONE, id: 7, ..Default::default() }));
|
||||
assert_eq!(c.pop(t0), None, "no frame due yet");
|
||||
let later = t0 + FRAME * 3;
|
||||
assert_eq!(c.pop(later).map(|m| m.kind), Some(MSG_AUDIO_FRAME));
|
||||
c.disconnect();
|
||||
assert_eq!(c.pop(later).map(|m| m.kind), Some(MSG_DISCONNECTED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_returns_silence() {
|
||||
unsafe {
|
||||
let input = XApuConnectInput { process: 1, streams: 2, commands_per_stream: 4, data_bytes: 0, frames_per_output: 256, options: 0 };
|
||||
let mut out = XApuConnectOutput { data: std::ptr::null_mut(), ready: std::ptr::null_mut() };
|
||||
let mut h = std::ptr::null_mut();
|
||||
assert_eq!(XApuConnect(&input, &mut out, &mut h), S_OK);
|
||||
let mut buf = vec![0xAAu8; 4096];
|
||||
let p = XApuProcess {
|
||||
id: XApuCommand { kind: XAPU_PROCESS, stream: 1, sequence: 1, options: 0, context: std::ptr::null_mut() },
|
||||
ramp: 0.0,
|
||||
pitch: 1.0,
|
||||
first_frame: 0,
|
||||
frames: 0,
|
||||
input_bytes: 0,
|
||||
input: std::ptr::null_mut(),
|
||||
output_bytes: buf.len() as u32,
|
||||
output: buf.as_mut_ptr() as *mut c_void,
|
||||
};
|
||||
let mut n = 0;
|
||||
assert_eq!(XApuEnqueueCommand(h, &p as *const _ as *const XApuCommand, &mut n), S_OK);
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(XApuGetResultCount(h, std::ptr::null_mut()), 1);
|
||||
let mut r: XApuResult = std::mem::zeroed();
|
||||
assert_eq!(XApuDequeueResult(h, &mut r), S_OK);
|
||||
let frames = r.frames;
|
||||
assert_eq!(frames, 256, "frames_per_output, stereo floats");
|
||||
assert!(buf[..256 * 8].iter().all(|&b| b == 0) && buf[256 * 8] == 0xAA);
|
||||
assert_eq!(XApuDequeueResult(h, &mut r), XAPU_NO_RESULTS);
|
||||
assert_eq!(XApuDisconnect(h), S_OK);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,7 +289,86 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// `XCL_TRACE_FRAME`: a full-screen dispatch (enough groups to cover a 4K target in tiles of up
|
||||
/// to 128 pixels) – what its root arguments say. A bindless title passes the indices of its
|
||||
/// descriptors in root constants and constant buffers: every small value there is looked up
|
||||
/// in the dispatch's descriptor tables, and the resources found (the pass's inputs and
|
||||
/// outputs) are logged.
|
||||
unsafe fn trace_fullscreen(this: *mut c_void, pso: usize, groups: [u32; 3]) {
|
||||
if groups[0] < 30 || groups[1] < 17 {
|
||||
return;
|
||||
}
|
||||
let Some(u) = crate::gpu::uma::get() else { return };
|
||||
let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone()));
|
||||
let Some(layout) = layout else { return };
|
||||
static SEEN: Mutex<Vec<usize>> = Mutex::new(Vec::new());
|
||||
{
|
||||
let mut g = SEEN.lock().unwrap();
|
||||
if g.contains(&pso) || g.len() >= 12 {
|
||||
return;
|
||||
}
|
||||
g.push(pso);
|
||||
}
|
||||
let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap()));
|
||||
let mut tables: Vec<u32> = Vec::new();
|
||||
let mut values: Vec<u32> = Vec::new();
|
||||
let mut what: Vec<String> = Vec::new();
|
||||
for (i, p) in layout.params.iter().enumerate() {
|
||||
match *p {
|
||||
Param::Constants { at, count } => {
|
||||
let w: Vec<u32> = (0..count as usize).filter_map(|k| word(at as usize + 4 * k)).collect();
|
||||
what.push(format!("p{i} constants {w:x?}"));
|
||||
values.extend(&w);
|
||||
}
|
||||
Param::Descriptor { at } => {
|
||||
let lo = word(at as usize).unwrap_or(0) as u64;
|
||||
let hi = word(at as usize + 4).unwrap_or(0) as u64;
|
||||
let va = (lo | hi << 32) as usize;
|
||||
let n = 64usize;
|
||||
if va != 0 && crate::gpu::shader::readable(va, 4 * n) {
|
||||
let w: Vec<u32> = (0..n).map(|k| ((va + 4 * k) as *const u32).read_unaligned()).collect();
|
||||
what.push(format!("p{i} buffer {va:#x}: {w:x?}"));
|
||||
values.extend(&w);
|
||||
} else {
|
||||
what.push(format!("p{i} buffer {va:#x} (not readable)"));
|
||||
}
|
||||
}
|
||||
Param::Table { at } => {
|
||||
let v = word(at as usize).unwrap_or(0);
|
||||
what.push(format!("p{i} table {v:#x}"));
|
||||
tables.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found: Vec<(u32, usize)> = Vec::new();
|
||||
for &v in &values {
|
||||
if v >= 1 << 20 {
|
||||
continue;
|
||||
}
|
||||
for &t in &tables {
|
||||
let slot = u.base() + t as usize + 32 * v as usize;
|
||||
if let Some(r) = super::console_heap::resource_at(slot) {
|
||||
if !found.iter().any(|x| x.1 == r) {
|
||||
found.push((v, r));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let res: Vec<String> = found
|
||||
.iter()
|
||||
.map(|&(v, r)| {
|
||||
let d = ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| x.GetDesc());
|
||||
format!("[{v}] {r:#x} {:?}{}", d.map(|d| (d.Dimension.0, d.Width, d.Height, d.Format.0)), if super::present::is_presented(r) { " PRESENTED" } else { "" })
|
||||
})
|
||||
.collect();
|
||||
crate::xlog_info!("frame trace: full-screen dispatch {groups:?}, pipeline {pso:#x}: {}", what.join("; "));
|
||||
crate::xlog_info!("frame trace: … its indices name: {}", if res.is_empty() { "nothing".to_string() } else { res.join("; ") });
|
||||
}
|
||||
|
||||
unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> {
|
||||
if super::present::trace_frame() {
|
||||
trace_fullscreen(this, pso, [x, y, z]);
|
||||
}
|
||||
bind_abi(this, list, pso, false)?;
|
||||
list.Dispatch(x, y, z);
|
||||
Ok(())
|
||||
|
||||
@@ -5,13 +5,25 @@
|
||||
//! (shaders load it with the high half 0 – amd_fidelityfx_upscaler_xbox.dll, HANDOFF "FSR4").
|
||||
//! XCL gives console code heaps whose slots live in unified memory (so the table addresses
|
||||
//! console code computes from the heap start work as they are in the recompiler's `mem`
|
||||
//! model) and keeps a PC heap beside each: view slot k → PC SRV at 2k, PC UAV at 2k + 1;
|
||||
//! model) and keeps PC descriptors beside each: view slot k → an SRV and, next to it, a UAV;
|
||||
//! sampler slot k → PC sampler k. A slot holds the descriptor in the XCL shader ABI
|
||||
//! (`desc::xcl_image_words`: T# word 0 = 2k; `desc::xcl_sampler_words`: S# word 3 [11:0] = k;
|
||||
//! V# with its unified-memory address).
|
||||
//! (`desc::xcl_image_words`: T# word 0 = the SRV's index in the shader-visible PC heap;
|
||||
//! `desc::xcl_sampler_words`: S# word 3 [11:0] = k; V# with its unified-memory address).
|
||||
//!
|
||||
//! View descriptors are values on the console: titles create them in a CPU-only heap and copy
|
||||
//! them into the shader-visible one as memory (the console header's inline
|
||||
//! CopyDescriptorsSimple; XDefiant copies every texture that way), and a descriptor table may
|
||||
//! be in any heap. So all console view heaps share one shader-visible PC heap (`Global`):
|
||||
//! each gets a range there, T# word 0 is an index into it – a T# copied anywhere still names
|
||||
//! its PC descriptor – and that heap is what lists bind. The title's own PC heap stays as a
|
||||
//! CPU-only mirror (where views are made, copies come from and UAV clears take their CPU
|
||||
//! handle). Without the shared heap (no room, not made) a heap keeps its own PC heap: SRV at
|
||||
//! 2k, UAV at 2k + 1.
|
||||
|
||||
use std::sync::Mutex;
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
/// bytes of a CBV/SRV/UAV slot (T# / V#) and of a sampler slot (S#)
|
||||
pub const SLOT: u32 = 32;
|
||||
pub const SAMPLER_SLOT: u32 = 16;
|
||||
@@ -25,6 +37,10 @@ struct Heap {
|
||||
pc_gpu: u64,
|
||||
inc: u32,
|
||||
sampler: bool,
|
||||
/// views in the shared heap: index of slot 0's SRV there, and its CPU / GPU handles
|
||||
first: Option<(u32, u64, u64)>,
|
||||
/// shader visible as the title made it
|
||||
visible: bool,
|
||||
}
|
||||
|
||||
impl Heap {
|
||||
@@ -39,16 +55,139 @@ impl Heap {
|
||||
|
||||
static HEAPS: Mutex<Vec<Heap>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The shader-visible PC heap of all console view heaps.
|
||||
struct Global {
|
||||
dev: ID3D12Device,
|
||||
heap: ID3D12DescriptorHeap,
|
||||
cpu: u64,
|
||||
gpu: u64,
|
||||
inc: u32,
|
||||
cap: u32,
|
||||
next: u32,
|
||||
/// released ranges (first, count)
|
||||
free: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
// D3D12 descriptor heaps and devices are free-threaded
|
||||
unsafe impl Send for Global {}
|
||||
|
||||
static GLOBAL: Mutex<Option<Global>> = Mutex::new(None);
|
||||
static GLOBAL_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
/// descriptors of the shared heap at most (the GPU may take more: OPTIONS19)
|
||||
const GLOBAL_MAX: u32 = 1 << 21;
|
||||
|
||||
/// A first-fit range of `count` in `free` (released ranges), else at `next` below `cap`.
|
||||
fn take_range(free: &mut Vec<(u32, u32)>, next: &mut u32, cap: u32, count: u32) -> Option<u32> {
|
||||
if let Some(i) = free.iter().position(|&(_, n)| n >= count) {
|
||||
let (f, n) = free[i];
|
||||
if n == count {
|
||||
free.swap_remove(i);
|
||||
} else {
|
||||
free[i] = (f + count, n - count);
|
||||
}
|
||||
return Some(f);
|
||||
}
|
||||
if cap - *next < count {
|
||||
return None;
|
||||
}
|
||||
*next += count;
|
||||
Some(*next - count)
|
||||
}
|
||||
|
||||
/// `count` descriptors of the shared shader-visible heap (made on first use): the index of
|
||||
/// the first. None: no shared heap, or no room left in it.
|
||||
pub unsafe fn reserve_global(dev: &ID3D12Device, count: u32) -> Option<u32> {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let mut g = GLOBAL.lock().unwrap();
|
||||
if g.is_none() {
|
||||
if GLOBAL_FAILED.load(Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default();
|
||||
let max = if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS19, &mut o as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.MaxViewDescriptorHeapSize > 0 {
|
||||
o.MaxViewDescriptorHeapSize
|
||||
} else {
|
||||
1_000_000
|
||||
};
|
||||
let cap = max.min(GLOBAL_MAX);
|
||||
let d = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, NumDescriptors: cap, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0 };
|
||||
let heap: ID3D12DescriptorHeap = match dev.CreateDescriptorHeap(&d) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
GLOBAL_FAILED.store(true, Relaxed);
|
||||
crate::xlog_warn!("console descriptor heaps: no shared shader-visible heap of {cap} ({e}) – each keeps its own");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them");
|
||||
*g = Some(Global {
|
||||
dev: dev.clone(),
|
||||
cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64,
|
||||
gpu: heap.GetGPUDescriptorHandleForHeapStart().ptr,
|
||||
inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV),
|
||||
heap,
|
||||
cap,
|
||||
next: 0,
|
||||
free: Vec::new(),
|
||||
});
|
||||
}
|
||||
let s = g.as_mut()?;
|
||||
let (cap, mut next) = (s.cap, s.next);
|
||||
let r = take_range(&mut s.free, &mut next, cap, count);
|
||||
s.next = next;
|
||||
if r.is_none() {
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if N.fetch_add(1, Relaxed) == 0 {
|
||||
crate::xlog_warn!("console descriptor heaps: the shared heap ({cap}) has no room for {count} more – that heap keeps its own");
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// The shared range starting at `first` (`count` descriptors) is free again.
|
||||
pub fn release_global(first: u32, count: u32) {
|
||||
if let Some(s) = GLOBAL.lock().unwrap().as_mut() {
|
||||
s.free.push((first, count));
|
||||
}
|
||||
}
|
||||
|
||||
/// The shader-visible PC heap lists bind for view descriptors (None: none shared).
|
||||
pub fn global_heap() -> Option<ID3D12DescriptorHeap> {
|
||||
GLOBAL.lock().unwrap().as_ref().map(|s| s.heap.clone())
|
||||
}
|
||||
|
||||
/// Whether `obj` (a title's view heap) has its descriptors in the shared heap.
|
||||
pub fn in_global(obj: usize) -> bool {
|
||||
HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && h.first.is_some())
|
||||
}
|
||||
|
||||
/// `obj` is a PC heap from `pc_cpu` / `pc_gpu` (increment `inc`; `pc_gpu` 0 when not shader
|
||||
/// visible) with 2·`n` view descriptors or `n` samplers: give it `n` console slots in
|
||||
/// unified memory.
|
||||
pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: bool) -> bool {
|
||||
/// unified memory. `first`: its range in the shared heap (`reserve_global`); `visible`: what
|
||||
/// the title asked for.
|
||||
pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: bool, first: Option<u32>, visible: bool) -> bool {
|
||||
let Some(u) = crate::gpu::uma::get() else { return false };
|
||||
let bytes = n.max(1) * if sampler { SAMPLER_SLOT } else { SLOT };
|
||||
// descriptor tables are 32-bit console addresses: window 0
|
||||
let Some(p) = u.alloc_in(0, bytes as usize, 256) else { return false };
|
||||
unsafe { std::ptr::write_bytes(p, 0, bytes as usize) };
|
||||
HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler });
|
||||
{
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 {
|
||||
crate::xlog_info!(
|
||||
"console descriptor heap {obj:#x}: {n} {} slots at UMA {:#x}, {}",
|
||||
if sampler { "sampler" } else { "view" },
|
||||
p as usize - u.base(),
|
||||
if visible { "shader visible" } else { "CPU only" }
|
||||
);
|
||||
}
|
||||
}
|
||||
let first = first.and_then(|f| {
|
||||
let g = GLOBAL.lock().unwrap();
|
||||
g.as_ref().map(|s| (f, s.cpu + f as u64 * s.inc as u64, s.gpu + f as u64 * s.inc as u64))
|
||||
});
|
||||
HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, first, visible });
|
||||
true
|
||||
}
|
||||
|
||||
@@ -58,8 +197,13 @@ pub fn unregister(obj: usize) {
|
||||
let mut heaps = HEAPS.lock().unwrap();
|
||||
heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i))
|
||||
};
|
||||
if let (Some(h), Some(u)) = (gone, crate::gpu::uma::get()) {
|
||||
u.free(h.shadow);
|
||||
if let Some(h) = gone {
|
||||
if let Some((f, _, _)) = h.first {
|
||||
release_global(f, 2 * h.n);
|
||||
}
|
||||
if let Some(u) = crate::gpu::uma::get() {
|
||||
u.free(h.shadow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,11 +218,14 @@ pub struct Slot {
|
||||
pub at: usize,
|
||||
/// views: PC heap index of the SRV (the UAV is at + 1); samplers: of the sampler
|
||||
pub index: u32,
|
||||
/// PC CPU handles of the SRV / UAV where views are made (the title's heap)
|
||||
pub pc_srv: u64,
|
||||
pub pc_uav: u64,
|
||||
/// PC GPU handle of the UAV (0: heap not shader visible)
|
||||
pub pc_gpu_uav: u64,
|
||||
pub sampler: bool,
|
||||
/// CPU handle of the SRV in the shared heap (0: the heap is not in it)
|
||||
pub shared_srv: u64,
|
||||
}
|
||||
|
||||
/// The slot behind a console CPU handle (None: not one of XCL's console heaps).
|
||||
@@ -87,17 +234,57 @@ pub fn slot(cpu: u64) -> Option<Slot> {
|
||||
let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?;
|
||||
let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32;
|
||||
if h.sampler {
|
||||
return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index: k, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true });
|
||||
return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index: k, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv: 0 });
|
||||
}
|
||||
let uav = ((2 * k + 1) * h.inc) as u64;
|
||||
Some(Slot {
|
||||
at: h.shadow + (k * SLOT) as usize,
|
||||
index: 2 * k,
|
||||
pc_srv: h.pc_cpu + (2 * k * h.inc) as u64,
|
||||
pc_uav: h.pc_cpu + uav,
|
||||
pc_gpu_uav: if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav },
|
||||
sampler: false,
|
||||
})
|
||||
let (index, pc_gpu_uav, shared_srv) = match h.first {
|
||||
Some((f, cpu, gpu)) => (f + 2 * k, gpu + uav, cpu + (2 * k * h.inc) as u64),
|
||||
None => (2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0),
|
||||
};
|
||||
Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv })
|
||||
}
|
||||
|
||||
/// The view just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap.
|
||||
pub unsafe fn publish(s: &Slot, uav: bool) {
|
||||
if s.shared_srv == 0 {
|
||||
return;
|
||||
}
|
||||
if let Some(g) = GLOBAL.lock().unwrap().as_ref() {
|
||||
let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) };
|
||||
g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` view slots from `first` were copied (in the title's heap): they go to the shared heap.
|
||||
pub unsafe fn publish_range(first: &Slot, n: u32) {
|
||||
if first.shared_srv == 0 || n == 0 {
|
||||
return;
|
||||
}
|
||||
if let Some(g) = GLOBAL.lock().unwrap().as_ref() {
|
||||
g.dev.CopyDescriptorsSimple(2 * n, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: first.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: first.pc_srv as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
}
|
||||
}
|
||||
|
||||
/// view slot address → the resource its view names (`XCL_TRACE_FRAME` diagnostics)
|
||||
static RES: Mutex<Option<std::collections::HashMap<usize, usize>>> = Mutex::new(None);
|
||||
|
||||
/// The view in slot `s` names `res` (0: none).
|
||||
pub fn note_resource(s: &Slot, res: usize) {
|
||||
if s.sampler || !super::present::trace_frame() {
|
||||
return;
|
||||
}
|
||||
let mut g = RES.lock().unwrap();
|
||||
let m = g.get_or_insert_with(Default::default);
|
||||
if res == 0 {
|
||||
m.remove(&s.at);
|
||||
} else {
|
||||
m.insert(s.at, res);
|
||||
}
|
||||
}
|
||||
|
||||
/// The resource of the view slot at UMA address `at`.
|
||||
pub fn resource_at(at: usize) -> Option<usize> {
|
||||
RES.lock().unwrap().as_ref()?.get(&at).copied()
|
||||
}
|
||||
|
||||
pub fn write(s: &Slot, words: &[u32]) {
|
||||
@@ -118,6 +305,44 @@ pub fn copy_words(src: &Slot, dst: &Slot) {
|
||||
w[0] = dst.index;
|
||||
}
|
||||
write(dst, &w[..n]);
|
||||
if !src.sampler {
|
||||
note_resource(dst, resource_at(src.at).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
|
||||
/// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose
|
||||
/// PC index is the slot's own (made or copied through the device) or another (copied by the
|
||||
/// title itself, as memory), buffers, empty.
|
||||
pub fn census() {
|
||||
let heaps = HEAPS.lock().unwrap();
|
||||
for h in heaps.iter().filter(|h| !h.sampler) {
|
||||
let (mut empty, mut own, mut other, mut buffers) = (0u32, 0u32, 0u32, 0u32);
|
||||
let mut examples: Vec<(u32, u32)> = Vec::new();
|
||||
let base = h.first.map_or(0, |f| f.0);
|
||||
for k in 0..h.n {
|
||||
let w = unsafe { std::slice::from_raw_parts((h.shadow + (k * SLOT) as usize) as *const u32, 8) };
|
||||
if w.iter().all(|&x| x == 0) {
|
||||
empty += 1;
|
||||
} else if w[3] >> 28 >= 8 {
|
||||
if w[0] == base + 2 * k {
|
||||
own += 1;
|
||||
} else {
|
||||
other += 1;
|
||||
if examples.len() < 8 {
|
||||
examples.push((k, w[0]));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
buffers += 1;
|
||||
}
|
||||
}
|
||||
crate::xlog_info!(
|
||||
"frame trace: view heap {:#x} ({} slots, {}): {own} images with their own PC index, {other} with another (slot, index: {examples:?}), {buffers} buffers, {empty} empty",
|
||||
h.obj,
|
||||
h.n,
|
||||
if h.visible { "shader visible" } else { "CPU only" }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The descriptor at a console GPU address (low 32 bits, as in a descriptor table), if it
|
||||
@@ -134,13 +359,29 @@ pub fn words_at(addr32: u32) -> Option<[u32; 8]> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Ranges of the shared heap: released ones first (first fit, split), then new ones, and
|
||||
/// none past its size.
|
||||
#[test]
|
||||
fn shared_heap_ranges() {
|
||||
let (mut free, mut next) = (Vec::new(), 0u32);
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 40), Some(0));
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 40), Some(40));
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 40), None, "20 left");
|
||||
free.push((0, 40));
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 30), Some(0));
|
||||
assert_eq!(free, vec![(30, 10)]);
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 20), Some(80));
|
||||
assert_eq!(take_range(&mut free, &mut next, 100, 10), Some(30));
|
||||
assert!(free.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_copy_and_release() {
|
||||
let Some(u) = crate::gpu::uma::get() else { return };
|
||||
let rel = |p: u64| (p as usize - u.base()) as u32;
|
||||
// views: 4 slots over a PC heap at 0x1000 (increment 32, GPU 0x5000); samplers: 2 at 0x9000
|
||||
assert!(register(0xA1, 4, 0x1000, 0x5000, 32, false));
|
||||
assert!(register(0xA2, 2, 0x9000, 0, 16, true));
|
||||
assert!(register(0xA1, 4, 0x1000, 0x5000, 32, false, None, true));
|
||||
assert!(register(0xA2, 2, 0x9000, 0, 16, true, None, true));
|
||||
let (v, sm) = (start(0xA1).unwrap(), start(0xA2).unwrap());
|
||||
let s1 = slot(v + 32).unwrap();
|
||||
assert_eq!((s1.index, s1.pc_srv, s1.pc_uav, s1.pc_gpu_uav), (2, 0x1040, 0x1060, 0x5060));
|
||||
|
||||
@@ -652,12 +652,14 @@ pub unsafe fn close(obj: *mut c_void) -> Result<Translation, String> {
|
||||
at += 4;
|
||||
} else if w0 == HEAPS_MARKER {
|
||||
let n = get(1) as usize;
|
||||
let heaps: Vec<Option<ID3D12DescriptorHeap>> = (0..n)
|
||||
.map(|k| {
|
||||
let p = (get(2 + 2 * k) as usize | (get(3 + 2 * k) as usize) << 32) as *mut c_void;
|
||||
ID3D12DescriptorHeap::from_raw_borrowed(&p).cloned()
|
||||
})
|
||||
.collect();
|
||||
let named: Vec<usize> = (0..n).map(|k| get(2 + 2 * k) as usize | (get(3 + 2 * k) as usize) << 32).collect();
|
||||
let heaps = super::list_x::pc_heaps(n as u32, named.as_ptr());
|
||||
if super::present::trace_frame() {
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 {
|
||||
crate::xlog_info!("frame trace: SetDescriptorHeaps {:x?}", (0..n).map(|k| get(2 + 2 * k) as usize | (get(3 + 2 * k) as usize) << 32).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
list.SetDescriptorHeaps(&heaps);
|
||||
at += 2 + 2 * n;
|
||||
} else if w0 == TRANSITIONS_MARKER {
|
||||
|
||||
@@ -344,6 +344,38 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V
|
||||
f(list, view.map_or(std::ptr::null(), |v| v as *const _));
|
||||
}
|
||||
|
||||
/// The heaps a list binds for console code: a view heap in the shared shader-visible heap
|
||||
/// is that one (`console_heap`), which is bound whatever the title names (a console
|
||||
/// descriptor table may be in any heap); sampler heaps as they are.
|
||||
pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec<Option<ID3D12DescriptorHeap>> {
|
||||
let shared = super::console_heap::global_heap();
|
||||
let mut out: Vec<Option<ID3D12DescriptorHeap>> = shared.iter().cloned().map(Some).collect();
|
||||
for k in 0..n as usize {
|
||||
let p = *heaps.add(k) as *mut c_void;
|
||||
if p.is_null() || (shared.is_some() && super::console_heap::in_global(p as usize)) {
|
||||
continue;
|
||||
}
|
||||
let Some(h) = ID3D12DescriptorHeap::from_raw_borrowed(&p) else { continue };
|
||||
if shared.is_some() && h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV {
|
||||
continue;
|
||||
}
|
||||
out.push(Some(h.clone()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// console #32 SetDescriptorHeaps (PC #28)
|
||||
pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) {
|
||||
const PC_SET_DESCRIPTOR_HEAPS: usize = 28;
|
||||
let f = pc::<unsafe extern "system" fn(*mut c_void, u32, *const usize)>(this, PC_SET_DESCRIPTOR_HEAPS);
|
||||
if heaps.is_null() || super::console_heap::global_heap().is_none() {
|
||||
return f(this, n, heaps);
|
||||
}
|
||||
let h = pc_heaps(n, heaps);
|
||||
let raw: Vec<usize> = h.iter().map(|x| x.as_ref().map_or(0, |x| x.as_raw() as usize)).collect();
|
||||
f(this, raw.len() as u32, raw.as_ptr())
|
||||
}
|
||||
|
||||
const PC_IA_SET_VERTEX_BUFFERS: usize = 44;
|
||||
|
||||
/// command list #48 IASetVertexBuffers(start slot, count, views) (PC #44): the addresses are
|
||||
|
||||
@@ -63,6 +63,19 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl
|
||||
if res == 0 {
|
||||
return 0;
|
||||
}
|
||||
{
|
||||
let mut p = PRESENTED.lock().unwrap();
|
||||
if !p.contains(&res) {
|
||||
p.push(res);
|
||||
}
|
||||
}
|
||||
if trace_frame() {
|
||||
static K: AtomicU64 = AtomicU64::new(0);
|
||||
let k = K.fetch_add(1, Ordering::Relaxed);
|
||||
if k == 2 || k == 300 {
|
||||
super::console_heap::census();
|
||||
}
|
||||
}
|
||||
if trace_frame() {
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -155,6 +168,13 @@ pub fn note_use(res: usize, what: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// resources the title presented
|
||||
static PRESENTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
|
||||
|
||||
pub fn is_presented(res: usize) -> bool {
|
||||
PRESENTED.lock().unwrap().contains(&res)
|
||||
}
|
||||
|
||||
/// the resource an RTV handle names (render-target binds)
|
||||
pub fn rtv_resource(handle: usize) -> Option<usize> {
|
||||
RTVS.lock().unwrap().as_ref()?.get(&handle).copied()
|
||||
|
||||
@@ -703,6 +703,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> {
|
||||
(13, b::draw_indexed_instanced as usize),
|
||||
(14, b::dispatch as usize),
|
||||
(48, l::ia_set_vertex_buffers_x as usize),
|
||||
(32, l::set_descriptor_heaps_x as usize),
|
||||
(59, b::execute_indirect as usize),
|
||||
(83, l::copy_texture_region_flags_x as usize),
|
||||
(34, b::set_graphics_root_signature as usize),
|
||||
@@ -779,19 +780,32 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc:
|
||||
if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && !sampler {
|
||||
return dev_create_descriptor_heap(this, desc as usize, riid, ppv);
|
||||
}
|
||||
// views: an SRV / UAV pair per console slot; samplers: one per slot
|
||||
let pc = [d[0], if sampler { d[1] } else { d[1].saturating_mul(2) }, d[2], d[3]];
|
||||
// views: an SRV / UAV pair per console slot (in the shared shader-visible heap, the
|
||||
// title's own a CPU-only mirror – `console_heap`); samplers: one per slot
|
||||
let pc_n = if sampler { d[1] } else { d[1].saturating_mul(2) };
|
||||
let visible = d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0;
|
||||
let first = match ID3D12Device::from_raw_borrowed(&this) {
|
||||
Some(dev) if !sampler && !desc.is_null() => super::console_heap::reserve_global(dev, pc_n),
|
||||
_ => None,
|
||||
};
|
||||
let flags = if first.is_some() { d[2] & !(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32) } else { d[2] };
|
||||
let pc = [d[0], pc_n, flags, d[3]];
|
||||
let hr = dev_create_descriptor_heap(this, pc.as_ptr() as usize, riid, ppv);
|
||||
if hr >= 0 {
|
||||
let raw = *ppv;
|
||||
let heap = ID3D12DescriptorHeap::from_raw_borrowed(&raw).unwrap();
|
||||
let dev = ID3D12Device::from_raw_borrowed(&this).unwrap();
|
||||
let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64;
|
||||
let gpu = if d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0 { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 };
|
||||
let gpu = if flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0 { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 };
|
||||
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE(d[0] as i32));
|
||||
if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc, sampler) {
|
||||
if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc, sampler, first, visible) {
|
||||
crate::xlog_warn!("console descriptor heap: no room in UMA for {} slots", d[1]);
|
||||
if let Some(f) = first {
|
||||
super::console_heap::release_global(f, pc_n);
|
||||
}
|
||||
}
|
||||
} else if let Some(f) = first {
|
||||
super::console_heap::release_global(f, pc_n);
|
||||
}
|
||||
hr
|
||||
}
|
||||
@@ -1192,6 +1206,9 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty:
|
||||
}
|
||||
let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24));
|
||||
f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty);
|
||||
if !d0.sampler {
|
||||
super::console_heap::publish_range(&d0, n);
|
||||
}
|
||||
let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64;
|
||||
for k in 0..n as u64 {
|
||||
if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) {
|
||||
@@ -1201,6 +1218,15 @@ unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty:
|
||||
true
|
||||
}
|
||||
|
||||
/// `XCL_TRACE_FRAME`: the device's descriptor copies (first few, and a count)
|
||||
fn note_copy_call(what: &str, n: u32, dst: u64, src: u64) {
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
let k = N.fetch_add(1, Ordering::Relaxed);
|
||||
if super::present::trace_frame() && (k < 4 || k.is_power_of_two()) {
|
||||
crate::xlog_info!("frame trace: {what} #{k}: {n} from {src:#x} to {dst:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
static MIXED_COPIES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn note_mixed_copy() {
|
||||
@@ -1211,6 +1237,7 @@ fn note_mixed_copy() {
|
||||
|
||||
/// #24 CopyDescriptorsSimple(n, dst, src, type)
|
||||
unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) {
|
||||
note_copy_call("CopyDescriptorsSimple", n, dst, src);
|
||||
if copy_console_slots(this, n, dst, src, ty) {
|
||||
return;
|
||||
}
|
||||
@@ -1225,6 +1252,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3
|
||||
/// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) {
|
||||
note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs });
|
||||
use super::console_heap::{slot, SAMPLER_SLOT, SLOT};
|
||||
let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some();
|
||||
if !console {
|
||||
@@ -1267,6 +1295,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void,
|
||||
let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18));
|
||||
let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) };
|
||||
f(this, res, desc, slot.pc_srv);
|
||||
super::console_heap::publish(&slot, false);
|
||||
super::console_heap::note_resource(&slot, res as usize);
|
||||
let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else {
|
||||
return super::console_heap::write(&slot, &[0; 8]);
|
||||
};
|
||||
@@ -1316,6 +1346,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void,
|
||||
}
|
||||
let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, counter, desc, cpu) };
|
||||
f(this, res, counter, desc, slot.pc_uav);
|
||||
super::console_heap::publish(&slot, true);
|
||||
super::console_heap::note_resource(&slot, res as usize);
|
||||
let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else {
|
||||
return super::console_heap::write(&slot, &[0; 8]);
|
||||
};
|
||||
@@ -1355,6 +1387,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void,
|
||||
};
|
||||
let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18));
|
||||
g(this, res, &srv, slot.pc_srv);
|
||||
super::console_heap::publish(&slot, false);
|
||||
}
|
||||
let (w, h) = ((w >> mip).max(1), (h >> mip).max(1));
|
||||
super::console_heap::write(&slot, &crate::gpu::desc::xcl_image_for_view(slot.index, fmt, ty, w, h, d, 1));
|
||||
|
||||
@@ -54,6 +54,8 @@ struct State {
|
||||
waited: HashMap<usize, u64>,
|
||||
/// 4 KiB page → hash of each 64-byte chunk the GPU got from the CPU (absent: all zero)
|
||||
sent: HashMap<usize, Box<[u64; CHUNKS]>>,
|
||||
/// `mapped` as sorted (start, end) runs (None: to be made again)
|
||||
runs: Option<Vec<(usize, usize)>>,
|
||||
}
|
||||
|
||||
const PAGE: usize = 0x1000;
|
||||
@@ -152,6 +154,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, u64)> {
|
||||
list,
|
||||
waited: HashMap::new(),
|
||||
sent: HashMap::new(),
|
||||
runs: None,
|
||||
})
|
||||
})();
|
||||
match made {
|
||||
@@ -224,6 +227,7 @@ impl State {
|
||||
if !self.mapped.contains_key(&t) && self.window(t).is_some() {
|
||||
let Some((tile, reused)) = self.take_tile() else { break };
|
||||
self.mapped.insert(t, tile);
|
||||
self.runs = None;
|
||||
if reused {
|
||||
self.to_zero.push((t, TILE));
|
||||
}
|
||||
@@ -363,6 +367,7 @@ pub unsafe fn decommitted(a: usize, n: usize) {
|
||||
}
|
||||
for t in tiles {
|
||||
if let Some(tile) = s.mapped.remove(&t) {
|
||||
s.runs = None;
|
||||
if !s.pinned.contains_key(&tile) {
|
||||
s.free.push(tile);
|
||||
}
|
||||
@@ -380,13 +385,47 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write
|
||||
/// has to reach the GPU.
|
||||
pub fn mapped_ranges() -> Vec<(usize, usize)> {
|
||||
let mut g = STATE.lock().unwrap();
|
||||
let Some(s) = g.as_mut() else { return Vec::new() };
|
||||
if s.runs.is_none() {
|
||||
let mut tiles: Vec<usize> = s.mapped.keys().copied().collect();
|
||||
tiles.sort_unstable();
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
for t in tiles {
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.1 == t => last.1 = t + TILE,
|
||||
_ => runs.push((t, t + TILE)),
|
||||
}
|
||||
}
|
||||
s.runs = Some(runs);
|
||||
}
|
||||
s.runs.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line
|
||||
static WATCH: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
|
||||
/// [lock wait, chunk scan, upload] in µs, runs uploaded
|
||||
static PHASES: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
|
||||
|
||||
pub fn note_watch(t: std::time::Duration, pages: usize) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
WATCH[0].fetch_add(t.as_micros() as u64, Relaxed);
|
||||
WATCH[1].fetch_add(pages as u64, Relaxed);
|
||||
}
|
||||
|
||||
/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB
|
||||
/// pages from the write-watch, sorted) and the reused tiles are copied into video memory, and
|
||||
/// `queue` waits for that and for new tile mappings.
|
||||
pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let t0 = std::time::Instant::now();
|
||||
let mut g = STATE.lock().unwrap();
|
||||
let Some(s) = g.as_mut() else { return };
|
||||
let t_locked = std::time::Instant::now();
|
||||
PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Relaxed);
|
||||
let zeroed = std::mem::take(&mut s.to_zero);
|
||||
for &(a, n) in &zeroed {
|
||||
for pg in (a..a + n).step_by(PAGE) {
|
||||
@@ -428,9 +467,13 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page:
|
||||
}
|
||||
}
|
||||
}
|
||||
let t_scanned = std::time::Instant::now();
|
||||
PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Relaxed);
|
||||
PHASES[3].fetch_add(runs.len() as u64, Relaxed);
|
||||
if !runs.is_empty() {
|
||||
s.upload(&runs);
|
||||
}
|
||||
PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Relaxed);
|
||||
{
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
static CALLS: AtomicU64 = AtomicU64::new(0);
|
||||
@@ -442,6 +485,16 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page:
|
||||
let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Relaxed) + t0.elapsed().as_micros() as u64;
|
||||
if n.is_power_of_two() && n >= 16 {
|
||||
crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len());
|
||||
let ms = |x: &std::sync::atomic::AtomicU64| x.load(Relaxed) / 1000;
|
||||
crate::xlog_info!(
|
||||
"sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)",
|
||||
ms(&WATCH[0]),
|
||||
WATCH[1].load(Relaxed),
|
||||
ms(&PHASES[0]),
|
||||
ms(&PHASES[1]),
|
||||
ms(&PHASES[2]),
|
||||
PHASES[3].load(Relaxed)
|
||||
);
|
||||
}
|
||||
}
|
||||
let q = queue.as_raw() as usize;
|
||||
|
||||
@@ -102,11 +102,18 @@ unsafe fn refresh_once(queue: *mut c_void) {
|
||||
if TEXTURES.lock().unwrap().is_empty() && !sparse {
|
||||
return;
|
||||
}
|
||||
let watch_t0 = std::time::Instant::now();
|
||||
let mut dirty: Vec<usize> = Vec::new();
|
||||
let mut page = 0x1000u32;
|
||||
// the committed windows, the sparse ones (the title's reservations) and other reservations
|
||||
// the write-watched regions (the committed windows, the sparse ones – the title's
|
||||
// reservations – and other graphics reservations) …
|
||||
let regions: Vec<(usize, usize)> = (0..u.shader_windows()).map(|k| u.window(k)).chain(crate::hle::kernelx::graphics_reservations()).collect();
|
||||
for (base, size) in regions {
|
||||
// … where a CPU write matters: the textures kept in step and the sparse windows' tiles
|
||||
// with video memory. A scan costs with the size it covers (GetWriteWatch walks the page
|
||||
// tables), and the whole regions are 16 GiB and more – looked at before every submit.
|
||||
let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().values().map(|e| (e.va & !0xFFF, (e.va + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect();
|
||||
wanted.extend(super::sparse::mapped_ranges());
|
||||
for (base, size) in watch_ranges(®ions, wanted) {
|
||||
loop {
|
||||
let mut buf = vec![std::ptr::null_mut::<c_void>(); 16384];
|
||||
let mut n = buf.len();
|
||||
@@ -120,6 +127,7 @@ unsafe fn refresh_once(queue: *mut c_void) {
|
||||
}
|
||||
}
|
||||
dirty.sort_unstable();
|
||||
super::sparse::note_watch(watch_t0.elapsed(), dirty.len());
|
||||
// the title's own memory: what the CPU wrote goes to its video memory first
|
||||
if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) {
|
||||
super::sparse::before_execute(q, &dirty, page as usize);
|
||||
@@ -151,6 +159,30 @@ unsafe fn refresh_once(queue: *mut c_void) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The parts of `wanted` (start, end) inside `regions` (base, size), merged and sorted, as
|
||||
/// (base, size) – each within one region (a write-watch call covers one allocation).
|
||||
fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
|
||||
wanted.sort_unstable();
|
||||
let mut merged: Vec<(usize, usize)> = Vec::new();
|
||||
for (a, b) in wanted {
|
||||
match merged.last_mut() {
|
||||
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
||||
_ => merged.push((a, b)),
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (a, b) in merged {
|
||||
for &(base, size) in regions {
|
||||
let (lo, hi) = (a.max(base), b.min(base + size));
|
||||
if lo < hi {
|
||||
out.push((lo, hi - lo));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_unstable();
|
||||
out
|
||||
}
|
||||
|
||||
/// `len` bytes at `at`: the committed, readable pages copied, the rest zero (a streaming pool
|
||||
/// has only some of its pages mapped).
|
||||
unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> {
|
||||
@@ -205,3 +237,16 @@ unsafe fn run_upload((device, va, tex, state): Upload, res: &ID3D12Resource) ->
|
||||
UPLOADS.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Only the wanted parts of the watched regions are scanned, merged, one region each.
|
||||
#[test]
|
||||
fn watch_ranges_clip_and_merge() {
|
||||
let regions = [(0x10000, 0x10000), (0x40000, 0x10000)];
|
||||
let wanted = vec![(0x12000, 0x13000), (0x11000, 0x12800), (0x1F000, 0x41000), (0x60000, 0x61000)];
|
||||
assert_eq!(watch_ranges(®ions, wanted), vec![(0x11000, 0x2000), (0x1F000, 0x1000), (0x40000, 0x1000)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,687 @@
|
||||
//! GameInput.dll: how a GDK title reads its controllers.
|
||||
//!
|
||||
//! The title gets the console's GameInput interfaces (the public GameInput.h of the GDK, v0:
|
||||
//! IGameInput, IGameInputDevice, IGameInputReading as COM objects with the methods in that
|
||||
//! header's order) with one device: a gamepad that is always connected. A reading is the
|
||||
//! state at the moment it is asked for – the PC's first XInput controller, and the keyboard
|
||||
//! while a window of this process has the focus (Enter / Space A, Escape / Backspace B,
|
||||
//! arrows the D-pad, Tab View, P Menu). Windows' own GameInput.dll is not used: its
|
||||
//! interfaces are not the console's and it reads only for a foreground app of its own.
|
||||
//! Device callbacks report the gamepad (at once for a blocking enumeration, from another
|
||||
//! thread for an asynchronous one); reading callbacks get a reading when the state changes
|
||||
//! (polled at 250 Hz). Methods not listed log their slot once and fail.
|
||||
//!
|
||||
//! `XCL_PRESS_A_AT=s1,s2…`: press A for 200 ms at those seconds after start (tests).
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::util::{HRESULT, S_OK};
|
||||
|
||||
const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
|
||||
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
|
||||
const GAMEINPUT_E_DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32;
|
||||
const GAMEINPUT_E_READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32;
|
||||
|
||||
// GameInputKind
|
||||
const KIND_CONTROLLER: u32 = 0xE;
|
||||
const KIND_GAMEPAD: u32 = 0x4_0000;
|
||||
const KIND_UI_NAVIGATION: u32 = 0x100_0000;
|
||||
const KINDS: u32 = KIND_CONTROLLER | KIND_GAMEPAD | KIND_UI_NAVIGATION;
|
||||
// GameInputDeviceStatus: connected, input enabled, output enabled, synchronized
|
||||
const STATUS: u32 = 0x1 | 0x2 | 0x4 | 0x40;
|
||||
// GameInputEnumerationKind
|
||||
const ENUM_BLOCKING: u32 = 2;
|
||||
|
||||
/// GameInputGamepadState
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq)]
|
||||
pub struct GamepadState {
|
||||
pub buttons: u32,
|
||||
pub left_trigger: f32,
|
||||
pub right_trigger: f32,
|
||||
pub left_x: f32,
|
||||
pub left_y: f32,
|
||||
pub right_x: f32,
|
||||
pub right_y: f32,
|
||||
}
|
||||
|
||||
// GameInputGamepadButtons
|
||||
pub const MENU: u32 = 0x1;
|
||||
pub const VIEW: u32 = 0x2;
|
||||
pub const A: u32 = 0x4;
|
||||
pub const B: u32 = 0x8;
|
||||
pub const X: u32 = 0x10;
|
||||
pub const Y: u32 = 0x20;
|
||||
pub const DPAD_UP: u32 = 0x40;
|
||||
pub const DPAD_DOWN: u32 = 0x80;
|
||||
pub const DPAD_LEFT: u32 = 0x100;
|
||||
pub const DPAD_RIGHT: u32 = 0x200;
|
||||
pub const LEFT_SHOULDER: u32 = 0x400;
|
||||
pub const RIGHT_SHOULDER: u32 = 0x800;
|
||||
pub const LEFT_STICK: u32 = 0x1000;
|
||||
pub const RIGHT_STICK: u32 = 0x2000;
|
||||
|
||||
/// XINPUT_GAMEPAD button bits → GameInputGamepadButtons
|
||||
pub fn buttons_from_xinput(w: u16) -> u32 {
|
||||
const MAP: [(u16, u32); 14] = [
|
||||
(0x0001, DPAD_UP),
|
||||
(0x0002, DPAD_DOWN),
|
||||
(0x0004, DPAD_LEFT),
|
||||
(0x0008, DPAD_RIGHT),
|
||||
(0x0010, MENU),
|
||||
(0x0020, VIEW),
|
||||
(0x0040, LEFT_STICK),
|
||||
(0x0080, RIGHT_STICK),
|
||||
(0x0100, LEFT_SHOULDER),
|
||||
(0x0200, RIGHT_SHOULDER),
|
||||
(0x1000, A),
|
||||
(0x2000, B),
|
||||
(0x4000, X),
|
||||
(0x8000, Y),
|
||||
];
|
||||
MAP.iter().filter(|(x, _)| w & x != 0).fold(0, |b, (_, g)| b | g)
|
||||
}
|
||||
|
||||
/// GameInputUiNavigationButtons from gamepad buttons
|
||||
pub fn ui_navigation(b: u32) -> u32 {
|
||||
const MAP: [(u32, u32); 12] = [
|
||||
(MENU, 0x1),
|
||||
(VIEW, 0x2),
|
||||
(A, 0x4),
|
||||
(B, 0x8),
|
||||
(DPAD_UP, 0x10),
|
||||
(DPAD_DOWN, 0x20),
|
||||
(DPAD_LEFT, 0x40),
|
||||
(DPAD_RIGHT, 0x80),
|
||||
(X, 0x100),
|
||||
(Y, 0x200),
|
||||
(LEFT_SHOULDER, 0x4000),
|
||||
(RIGHT_SHOULDER, 0x8000),
|
||||
];
|
||||
MAP.iter().filter(|(g, _)| b & g != 0).fold(0, |u, (_, n)| u | n)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// the state: XInput controller 0..3 (the first connected), the keyboard, scripted presses
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct XInputState {
|
||||
packet: u32,
|
||||
buttons: u16,
|
||||
left_trigger: u8,
|
||||
right_trigger: u8,
|
||||
lx: i16,
|
||||
ly: i16,
|
||||
rx: i16,
|
||||
ry: i16,
|
||||
}
|
||||
|
||||
type GetState = unsafe extern "system" fn(u32, *mut XInputState) -> u32;
|
||||
type SetState = unsafe extern "system" fn(u32, *const [u16; 2]) -> u32;
|
||||
|
||||
fn xinput() -> Option<(GetState, SetState)> {
|
||||
static F: OnceLock<Option<(usize, usize)>> = OnceLock::new();
|
||||
let f = *F.get_or_init(|| unsafe {
|
||||
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
|
||||
let h = LoadLibraryA(b"xinput1_4.dll\0".as_ptr());
|
||||
if h.is_null() {
|
||||
crate::xlog_warn!("GameInput: xinput1_4.dll not loaded – controllers of the PC are not read");
|
||||
return None;
|
||||
}
|
||||
let g = GetProcAddress(h, b"XInputGetState\0".as_ptr())? as usize;
|
||||
let s = GetProcAddress(h, b"XInputSetState\0".as_ptr())? as usize;
|
||||
Some((g, s))
|
||||
});
|
||||
f.map(|(g, s)| unsafe { (std::mem::transmute::<usize, GetState>(g), std::mem::transmute::<usize, SetState>(s)) })
|
||||
}
|
||||
|
||||
/// the XInput user index that answered last
|
||||
static PAD: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
fn start() -> Instant {
|
||||
static T: OnceLock<Instant> = OnceLock::new();
|
||||
*T.get_or_init(Instant::now)
|
||||
}
|
||||
|
||||
/// `XCL_PRESS_A_AT`: seconds after start at which A is held for 200 ms
|
||||
fn scripted_a() -> bool {
|
||||
static AT: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
let at = AT.get_or_init(|| std::env::var("XCL_PRESS_A_AT").ok().map(|v| v.split(',').filter_map(|s| s.trim().parse().ok()).collect()).unwrap_or_default());
|
||||
let t = start().elapsed().as_secs_f64();
|
||||
at.iter().any(|&s| t >= s && t < s + 0.2)
|
||||
}
|
||||
|
||||
#[link(name = "user32")]
|
||||
extern "system" {
|
||||
fn GetAsyncKeyState(key: i32) -> i16;
|
||||
fn GetForegroundWindow() -> *mut c_void;
|
||||
fn GetWindowThreadProcessId(window: *mut c_void, pid: *mut u32) -> u32;
|
||||
}
|
||||
|
||||
unsafe fn keyboard() -> u32 {
|
||||
let w = GetForegroundWindow();
|
||||
if w.is_null() {
|
||||
return 0;
|
||||
}
|
||||
let mut pid = 0u32;
|
||||
GetWindowThreadProcessId(w, &mut pid);
|
||||
if pid != std::process::id() {
|
||||
return 0;
|
||||
}
|
||||
const KEYS: [(i32, u32); 10] = [(0x0D, A), (0x20, A), (0x1B, B), (0x08, B), (0x26, DPAD_UP), (0x28, DPAD_DOWN), (0x25, DPAD_LEFT), (0x27, DPAD_RIGHT), (0x09, VIEW), (0x50, MENU)];
|
||||
KEYS.iter().filter(|(k, _)| GetAsyncKeyState(*k) as u16 & 0x8000 != 0).fold(0, |b, (_, g)| b | g)
|
||||
}
|
||||
|
||||
/// the gamepad now
|
||||
pub fn poll() -> GamepadState {
|
||||
let mut s = GamepadState::default();
|
||||
if let Some((get, _)) = xinput() {
|
||||
let first = PAD.load(Ordering::Relaxed);
|
||||
for k in (0..4).map(|i| (first + i) % 4) {
|
||||
let mut x = XInputState::default();
|
||||
if unsafe { get(k, &mut x) } == 0 {
|
||||
PAD.store(k, Ordering::Relaxed);
|
||||
let axis = |v: i16| (v as f32 / 32767.0).max(-1.0);
|
||||
s = GamepadState {
|
||||
buttons: buttons_from_xinput(x.buttons),
|
||||
left_trigger: x.left_trigger as f32 / 255.0,
|
||||
right_trigger: x.right_trigger as f32 / 255.0,
|
||||
left_x: axis(x.lx),
|
||||
left_y: axis(x.ly),
|
||||
right_x: axis(x.rx),
|
||||
right_y: axis(x.ry),
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
s.buttons |= unsafe { keyboard() };
|
||||
if scripted_a() {
|
||||
s.buttons |= A;
|
||||
}
|
||||
{
|
||||
// the first presses of each button: worth a line (is input arriving at all?)
|
||||
static SEEN: AtomicU32 = AtomicU32::new(0);
|
||||
let new = s.buttons & !SEEN.fetch_or(s.buttons, Ordering::Relaxed);
|
||||
if new != 0 {
|
||||
crate::xlog_info!("GameInput: gamepad buttons {new:#x} pressed for the first time");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn now_us() -> u64 {
|
||||
start().elapsed().as_micros() as u64 + 1
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------
|
||||
// objects
|
||||
// ---------------------------------------------------------------------------------------
|
||||
|
||||
#[repr(C)]
|
||||
struct Object {
|
||||
vtable: *const usize,
|
||||
}
|
||||
|
||||
// static objects: their vtables are leaked tables
|
||||
unsafe impl Sync for Object {}
|
||||
unsafe impl Send for Object {}
|
||||
|
||||
#[repr(C)]
|
||||
struct Reading {
|
||||
vtable: *const usize,
|
||||
refs: AtomicU32,
|
||||
state: GamepadState,
|
||||
sequence: u64,
|
||||
timestamp: u64,
|
||||
}
|
||||
|
||||
/// GameInputDeviceInfo, as far as a title looks to tell a gamepad: an Xbox controller that
|
||||
/// reads as a gamepad (and controller, UI navigation) with the four rumble motors
|
||||
#[repr(C)]
|
||||
struct DeviceInfo {
|
||||
size: u32,
|
||||
vendor: u16,
|
||||
product: u16,
|
||||
revision: u16,
|
||||
interface: u8,
|
||||
collection: u8,
|
||||
usage_page: u16,
|
||||
usage_id: u16,
|
||||
hardware_version: [u16; 4],
|
||||
firmware_version: [u16; 4],
|
||||
device_id: [u8; 32],
|
||||
root_id: [u8; 32],
|
||||
family: i32,
|
||||
capabilities: u32,
|
||||
supported_input: u32,
|
||||
rumble_motors: u32,
|
||||
rest: [u8; 896],
|
||||
}
|
||||
|
||||
const DEVICE_ID: [u8; 32] = *b"XCL gamepad 0 | ||||