thin.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. //! List calls that only write down their arguments (`VICTORY_THIN=1`); what
  2. //! they mean is worked out by threads of ours, beside the title's.
  3. //!
  4. //! Why: the title makes 45,000 to 60,000 list calls a frame. Each was
  5. //! translated inside the call, 3.5 us of it, 160 to 190 ms of processor time a
  6. //! frame on the title's five recording threads; its own code between the calls
  7. //! is a tenth of that. Nothing else of the title's frame could go on
  8. //! meanwhile: recording took 55 of 65 ms, and behind it the card stood idle
  9. //! for half the frame (timeline waits-3). On the console such a call writes a
  10. //! few words into the list's memory and the card reads them when the list
  11. //! runs. So it is here now: a call appends its arguments (and copies of what
  12. //! they point at) to a stream of words; threads of ours run the stream, call
  13. //! by call and in order, through the list methods there were before, on a list
  14. //! of ours ([`Recording::back`]) that the title never sees. They begin while
  15. //! the title still records (every [`CHUNK`] words are handed over), several
  16. //! lists at a time. A submission goes into the line of submissions
  17. //! (`crate::queue::behind`) as it was made, by the recordings' names; the
  18. //! thread that serves the line goes on with it when they are translated.
  19. //!
  20. //! What may be looked at later than before, and why that is all right: all
  21. //! that the card of the console looks at when the list runs (descriptor heaps,
  22. //! constants, upload memory, indirect arguments): it must stay as it is until
  23. //! the list has run, and no fence behind the list is set before. What D3D12
  24. //! reads at the call is copied at the call: the arrays and structures passed,
  25. //! and the render target and depth views, whose slots may be written again
  26. //! right after. Objects named (pipelines, resources) must live until the list
  27. //! has run; a recording the title resets or releases without submitting it is
  28. //! not run any further.
  29. use super::*;
  30. use std::collections::VecDeque;
  31. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::*};
  32. use std::sync::{Arc, Condvar, Mutex, OnceLock};
  33. use crate::descriptor::RtvRecord;
  34. use crate::draw::{IndexView, VertexView};
  35. use windows::Win32::Foundation::RECT;
  36. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  37. /// Words after which a stream is handed to the translating threads.
  38. const CHUNK: usize = 1024;
  39. /// Whether list calls are only written down (`VICTORY_THIN=1`; needs the line
  40. /// of submissions, which it turns on).
  41. pub(crate) fn on() -> bool {
  42. static ON: OnceLock<bool> = OnceLock::new();
  43. *ON.get_or_init(|| {
  44. wanted() && crate::host::host().is_some() && crate::queue::line_on() && {
  45. start();
  46. true
  47. }
  48. })
  49. }
  50. /// Whether it is asked for.
  51. pub(crate) fn wanted() -> bool {
  52. static ON: OnceLock<bool> = OnceLock::new();
  53. *ON.get_or_init(|| std::env::var_os("VICTORY_THIN").is_some_and(|v| v == "1"))
  54. }
  55. /// What a title list keeps: the recording being written and the words of it
  56. /// not handed over yet.
  57. #[derive(Default)]
  58. pub(super) struct Front {
  59. recording: Option<Arc<Recording>>,
  60. words: Vec<u64>,
  61. closed: bool,
  62. submitted: bool,
  63. }
  64. impl Drop for Front {
  65. fn drop(&mut self) {
  66. self.leave();
  67. }
  68. }
  69. impl Front {
  70. /// Lets go of the recording there is: one never submitted is not run any
  71. /// further.
  72. fn leave(&mut self) {
  73. if let Some(recording) = self.recording.take()
  74. && !self.submitted
  75. {
  76. recording.abandoned.store(true, Release);
  77. }
  78. self.words.clear();
  79. }
  80. /// Begins a recording, with `pipeline` bound.
  81. pub(super) fn begin(&mut self, kind: u32, pipeline: This) {
  82. self.leave();
  83. self.recording = Some(Arc::new(Recording::new(kind)));
  84. self.closed = false;
  85. self.submitted = false;
  86. self.put(RESET, &[pipeline as u64]);
  87. }
  88. #[inline]
  89. fn put(&mut self, op: u64, args: &[u64]) {
  90. if self.closed || self.recording.is_none() {
  91. return;
  92. }
  93. self.words.push(op | (args.len() as u64) << 16);
  94. self.words.extend_from_slice(args);
  95. if self.words.len() >= CHUNK {
  96. self.hand_over();
  97. }
  98. }
  99. /// [`Self::put`] of some words and then the bytes of some things.
  100. fn put_with(&mut self, op: u64, args: &[u64], blobs: &[&[u8]]) {
  101. if self.closed || self.recording.is_none() {
  102. return;
  103. }
  104. let at = self.words.len();
  105. self.words.push(0);
  106. self.words.extend_from_slice(args);
  107. for blob in blobs {
  108. let from = self.words.len();
  109. self.words.resize(from + blob.len().div_ceil(8), 0);
  110. // SAFETY: the words just made hold the bytes; plain data.
  111. unsafe {
  112. std::ptr::copy_nonoverlapping(blob.as_ptr(), self.words.as_mut_ptr().add(from).cast(), blob.len())
  113. };
  114. }
  115. let len = (self.words.len() - at - 1) as u64;
  116. self.words[at] = op | len << 16;
  117. if self.words.len() >= CHUNK {
  118. self.hand_over();
  119. }
  120. }
  121. fn hand_over(&mut self) {
  122. let Some(recording) = &self.recording else { return };
  123. if self.words.is_empty() {
  124. return;
  125. }
  126. let fresh = held(&WORDS).pop().unwrap_or_else(|| Vec::with_capacity(CHUNK + 256));
  127. let words = std::mem::replace(&mut self.words, fresh);
  128. CHUNKS.fetch_add(1, Relaxed);
  129. let schedule = {
  130. let mut inner = held(&recording.inner);
  131. inner.chunks.push_back(words);
  132. !std::mem::replace(&mut inner.scheduled, true)
  133. };
  134. if schedule {
  135. held(&READY).push_back(recording.clone());
  136. WORK.notify_one();
  137. }
  138. }
  139. fn close(&mut self) {
  140. if self.closed {
  141. return;
  142. }
  143. self.put(CLOSE, &[]);
  144. self.closed = true;
  145. self.hand_over();
  146. }
  147. }
  148. /// Streams' memory to use again.
  149. static WORDS: Mutex<Vec<Vec<u64>>> = Mutex::new(Vec::new());
  150. /// Recordings with words to translate.
  151. static READY: Mutex<VecDeque<Arc<Recording>>> = Mutex::new(VecDeque::new());
  152. static WORK: Condvar = Condvar::new();
  153. /// Lists of ours nobody uses, closed.
  154. static BACKS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
  155. /// Since the last line of the log: streams handed over; calls translated and
  156. /// the microseconds that took (all threads), recordings translated, and
  157. /// recordings let go of in the middle.
  158. static CHUNKS: AtomicU64 = AtomicU64::new(0);
  159. static STATS: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
  160. fn held<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
  161. m.lock().unwrap_or_else(|e| e.into_inner())
  162. }
  163. /// One recording of a title list: what was written of it and not translated
  164. /// yet, and the list of ours it goes to.
  165. pub(crate) struct Recording {
  166. kind: u32,
  167. inner: Mutex<Inner>,
  168. /// Translated to its end.
  169. done: AtomicBool,
  170. moved: Condvar,
  171. abandoned: AtomicBool,
  172. }
  173. #[derive(Default)]
  174. struct Inner {
  175. chunks: VecDeque<Vec<u64>>,
  176. /// Streams translated (commands may name places in them until the end).
  177. kept: Vec<Vec<u64>>,
  178. /// It is among [`READY`] or being translated.
  179. scheduled: bool,
  180. /// The list of ours (0: none yet).
  181. back: usize,
  182. /// That list was closed by the stream.
  183. closed: bool,
  184. }
  185. impl Recording {
  186. fn new(kind: u32) -> Self {
  187. Recording {
  188. kind,
  189. inner: Mutex::default(),
  190. done: AtomicBool::new(false),
  191. moved: Condvar::new(),
  192. abandoned: AtomicBool::new(false),
  193. }
  194. }
  195. pub(crate) fn done(&self) -> bool {
  196. self.done.load(Acquire)
  197. }
  198. /// Waits until it is translated.
  199. pub(crate) fn wait(&self) {
  200. let mut inner = held(&self.inner);
  201. while !self.done() {
  202. inner = self.moved.wait(inner).unwrap_or_else(|e| e.into_inner());
  203. }
  204. }
  205. /// The list of ours it went to (null: it was never begun).
  206. pub(crate) fn back(&self) -> This {
  207. held(&self.inner).back as This
  208. }
  209. /// Translates what there is.
  210. fn run(&self) {
  211. loop {
  212. let (chunk, back) = {
  213. let mut inner = held(&self.inner);
  214. let Some(chunk) = inner.chunks.pop_front() else {
  215. inner.scheduled = false;
  216. return;
  217. };
  218. if inner.back == 0 {
  219. inner.back = back_list(self.kind) as usize;
  220. }
  221. (chunk, inner.back as This)
  222. };
  223. let began = std::time::Instant::now();
  224. let (calls, closed) = translate(back, &chunk, || self.abandoned.load(Acquire));
  225. STATS[0].fetch_add(calls, Relaxed);
  226. STATS[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
  227. let mut inner = held(&self.inner);
  228. inner.kept.push(chunk);
  229. if closed {
  230. inner.closed = true;
  231. let kept = std::mem::take(&mut inner.kept);
  232. self.done.store(true, Release);
  233. self.moved.notify_all();
  234. drop(inner);
  235. give_back(kept);
  236. STATS[2].fetch_add(1, Relaxed);
  237. crate::queue::line_moved();
  238. }
  239. }
  240. }
  241. }
  242. impl Drop for Recording {
  243. fn drop(&mut self) {
  244. let inner = self.inner.get_mut().unwrap_or_else(|e| e.into_inner());
  245. give_back(inner.chunks.drain(..).chain(std::mem::take(&mut inner.kept)).collect());
  246. if inner.back != 0 {
  247. if !inner.closed {
  248. // Left in the middle.
  249. STATS[3].fetch_add(1, Relaxed);
  250. super::close(inner.back as This);
  251. }
  252. held(&BACKS).push(inner.back);
  253. }
  254. }
  255. }
  256. fn give_back(streams: Vec<Vec<u64>>) {
  257. let mut words = held(&WORDS);
  258. for mut s in streams {
  259. if words.len() < 1024 && s.capacity() <= 16 * CHUNK {
  260. s.clear();
  261. words.push(s);
  262. }
  263. }
  264. }
  265. /// A list of ours, closed.
  266. fn back_list(kind: u32) -> This {
  267. if let Some(back) = held(&BACKS).pop() {
  268. // SAFETY: a list of ours nobody uses.
  269. unsafe { (*(back as *mut List)).kind = kind };
  270. return back as This;
  271. }
  272. let list: This = Box::into_raw(super::boxed(kind, std::ptr::null(), false)).cast_const().cast();
  273. super::close(list);
  274. list
  275. }
  276. fn start() {
  277. let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32);
  278. for i in 0..threads {
  279. let worker = move || {
  280. crate::cores::keep_many_on_fast_cores("victory-list");
  281. crate::queue::no_drain_here();
  282. loop {
  283. let recording = {
  284. let mut ready = held(&READY);
  285. loop {
  286. match ready.pop_front() {
  287. Some(r) => break r,
  288. None => ready = WORK.wait(ready).unwrap_or_else(|e| e.into_inner()),
  289. }
  290. }
  291. };
  292. if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| recording.run())).is_err() {
  293. crate::host::fail(format_args!("a thread that translates lists panicked"));
  294. }
  295. }
  296. };
  297. if let Err(e) = std::thread::Builder::new().name(format!("victory-list-{i}")).spawn(worker) {
  298. tracing::warn!(error = %e, "a thread less to translate lists");
  299. }
  300. }
  301. tracing::info!(threads, "list calls are written down and translated by threads of ours (VICTORY_THIN=1)");
  302. }
  303. /// The recordings of submitted lists, in order (one that was not begun is left
  304. /// out).
  305. pub(crate) fn submitted(lists: &[This]) -> Arc<[Arc<Recording>]> {
  306. lists
  307. .iter()
  308. .filter(|l| !l.is_null())
  309. .filter_map(|&l| {
  310. // SAFETY: the title passes its lists, which nobody records into now.
  311. let front = unsafe { &mut (*l.cast_mut().cast::<List>()).thin };
  312. front.close();
  313. front.submitted = true;
  314. front.recording.clone()
  315. })
  316. .collect()
  317. }
  318. /// For the frame-rate line.
  319. pub(crate) fn line(frames: f64) {
  320. if !wanted() || !on() {
  321. return;
  322. }
  323. let s: Vec<f64> = STATS.iter().map(|s| s.swap(0, Relaxed) as f64 / frames).collect();
  324. tracing::info!(
  325. "list calls translated by threads of ours per frame (VICTORY_THIN): {:.0} in {:.1} ms (all threads), {:.1} lists, {:.1} pieces; left in the middle {:.2}",
  326. s[0],
  327. s[1] / 1000.0,
  328. s[2],
  329. CHUNKS.swap(0, Relaxed) as f64 / frames,
  330. s[3]
  331. );
  332. }
  333. #[inline]
  334. fn front<'a>(this: This) -> &'a mut Front {
  335. // SAFETY: the title passes one of our lists; a list is recorded by one
  336. // thread at a time.
  337. unsafe { &mut (*this.cast_mut().cast::<List>()).thin }
  338. }
  339. /// An argument as a word.
  340. trait Word: Copy {
  341. fn word(self) -> u64;
  342. fn unword(w: u64) -> Self;
  343. }
  344. macro_rules! words {
  345. ($($t:ty),*) => { $(impl Word for $t {
  346. #[inline]
  347. fn word(self) -> u64 { self as u64 }
  348. #[inline]
  349. fn unword(w: u64) -> Self { w as $t }
  350. })* };
  351. }
  352. words!(u8, u32, i32, u64, This);
  353. impl Word for f32 {
  354. #[inline]
  355. fn word(self) -> u64 {
  356. u64::from(self.to_bits())
  357. }
  358. #[inline]
  359. fn unword(w: u64) -> Self {
  360. f32::from_bits(w as u32)
  361. }
  362. }
  363. /// The methods whose arguments are all plain values: the one the title calls,
  364. /// and the call made of it later.
  365. macro_rules! plain {
  366. ($($op:ident $name:ident = $was:path, ($($a:ident: $t:ty),*);)*) => {
  367. #[allow(clippy::upper_case_acronyms, non_camel_case_types)]
  368. #[repr(u64)]
  369. enum Plain { $($op),* , END }
  370. $(extern "system" fn $name(this: This $(, $a: $t)*) {
  371. front(this).put(Plain::$op as u64, &[$(Word::word($a)),*]);
  372. })*
  373. /// Whether `op` was one of them; done on `list`.
  374. #[inline]
  375. fn run_plain(op: u64, list: This, w: &[u64]) -> bool {
  376. match op {
  377. $(n if n == Plain::$op as u64 => {
  378. let mut words = w.iter();
  379. $(let $a: $t = Word::unword(words.next().copied().unwrap_or(0));)*
  380. let _ = words;
  381. $was(list $(, $a)*);
  382. })*
  383. _ => return false,
  384. }
  385. true
  386. }
  387. };
  388. }
  389. plain! {
  390. TOPOLOGY topology = state::topology, (v: u32);
  391. STENCIL_REF stencil_ref = state::stencil_ref, (v: u32);
  392. DEPTH_BOUNDS depth_bounds = state::depth_bounds, (min: f32, max: f32);
  393. COMPUTE_TABLE compute_table = state::compute_table, (slot: u32, handle: u64);
  394. GRAPHICS_TABLE graphics_table = state::graphics_table, (slot: u32, handle: u64);
  395. COMPUTE_CONSTANT compute_constant = state::compute_constant, (slot: u32, value: u32, offset: u32);
  396. GRAPHICS_CONSTANT graphics_constant = state::graphics_constant, (slot: u32, value: u32, offset: u32);
  397. COMPUTE_VIEW compute_view = state::compute_view, (slot: u32, address: u64);
  398. GRAPHICS_VIEW graphics_view = state::graphics_view, (slot: u32, address: u64);
  399. SET_PIPELINE set_pipeline = super::set_pipeline, (pipeline: This);
  400. DRAW draw = state::draw, (vertices: u32, instances: u32, first: u32, first_instance: u32);
  401. DRAW_INDEXED draw_indexed = state::draw_indexed, (indices: u32, instances: u32, first: u32, base: i32, first_instance: u32);
  402. DISPATCH dispatch = state::dispatch, (x: u32, y: u32, z: u32);
  403. DISPATCH_X dispatch_x = super::dispatch_x, (x: u32, y: u32, z: u32, flags: u32);
  404. DISPATCH_MESH dispatch_mesh = state::dispatch_mesh, (x: u32, y: u32, z: u32);
  405. DISPATCH_MESH_X dispatch_mesh_x = state::dispatch_mesh_x, (x: u32, flags: u64, indirect: u64, payload: u64);
  406. COPY_BUFFER copy_buffer_region = super::copy_buffer_region, (dst: This, dst_offset: u64, src: This, src_offset: u64, len: u64);
  407. COPY_RESOURCE copy_resource = super::copy_resource, (dst: This, src: This);
  408. COPY_RESOURCE_X copy_resource_x = super::copy_resource_x, (dst: This, src: This, flags: u32);
  409. COPY_MEMORY copy_memory = super::copy_memory, (dst: u64, src: u64, len: u64, flags: u32);
  410. RESOLVE resolve = super::resolve, (dst: This, dst_sub: u32, src: This, src_sub: u32, format: u32);
  411. RESOLVE_QUERIES resolve_queries = super::resolve_queries, (heap: This, kind: u32, first: u32, count: u32, buffer: This, offset: u64);
  412. EXECUTE_INDIRECT execute_indirect = super::execute_indirect, (signature: This, max: u32, arguments: This, offset: u64, count: This, count_offset: u64);
  413. WRITE32 write32 = super::write32, (address: u64, value: u32, flush: u32, flags: u32);
  414. WRITE64 write64 = super::write64, (address: u64, value: u64, flush: u32, flags: u32);
  415. WAIT_VALUE wait_value = super::wait_value, (address: u64, comparison: u32, reference: u64);
  416. WAIT_VALUE64 wait_value64 = super::wait_value64, (address: u64, comparison: u32, reference: u64);
  417. SYNC sync = super::sync, (flags: u32, control: u32, address: u64, size: u64);
  418. }
  419. const fn after(n: u64) -> u64 {
  420. Plain::END as u64 + n
  421. }
  422. const RESET: u64 = after(0);
  423. const CLOSE: u64 = after(1);
  424. const UPLOAD: u64 = after(2);
  425. const BARRIER: u64 = after(3);
  426. const BARRIER_GROUPS: u64 = after(4);
  427. const VIEWPORTS: u64 = after(5);
  428. const SCISSORS: u64 = after(6);
  429. const BLEND_FACTOR: u64 = after(7);
  430. const HEAPS: u64 = after(8);
  431. const COMPUTE_CONSTANTS: u64 = after(9);
  432. const GRAPHICS_CONSTANTS: u64 = after(10);
  433. const INDEX_BUFFER: u64 = after(11);
  434. const VERTEX_BUFFERS: u64 = after(12);
  435. const TARGETS: u64 = after(13);
  436. const CLEAR_RTV: u64 = after(14);
  437. const CLEAR_DSV: u64 = after(15);
  438. const COPY_TEXTURE: u64 = after(16);
  439. /// The bytes of `count` things at `items` (none if null).
  440. fn bytes_of<'a, T>(items: *const T, count: usize) -> &'a [u8] {
  441. if items.is_null() || count == 0 {
  442. return &[];
  443. }
  444. // SAFETY: the title passes `count` items.
  445. unsafe { std::slice::from_raw_parts(items.cast(), count * size_of::<T>()) }
  446. }
  447. /// Where the things are in a stream (null for none).
  448. fn at<T>(w: &[u64], from: usize, count: usize) -> *const T {
  449. if count == 0 || from >= w.len() { std::ptr::null() } else { w[from..].as_ptr().cast() }
  450. }
  451. /// [`at`] where an empty array is not null.
  452. fn at_or<T>(w: &[u64], from: usize) -> *const T {
  453. // SAFETY: at most one past the end.
  454. unsafe { w.as_ptr().add(from.min(w.len())).cast() }
  455. }
  456. /// A view's record as it is now (zeros for no view), so that its slot may be
  457. /// written again: the copy stands for the handle.
  458. fn record(handle: u64) -> [u64; RECORD] {
  459. let mut words = [0u64; RECORD];
  460. if handle != 0 {
  461. // SAFETY: a descriptor slot the title passes (they are larger).
  462. unsafe {
  463. std::ptr::copy_nonoverlapping(handle as *const u8, words.as_mut_ptr().cast(), size_of::<RtvRecord>())
  464. };
  465. }
  466. words
  467. }
  468. const RECORD: usize = size_of::<RtvRecord>().div_ceil(8);
  469. extern "system" fn list_close(this: This) -> HRESULT {
  470. front(this).close();
  471. S_OK
  472. }
  473. extern "system" fn list_reset(this: This, allocator: This, pipeline: This) -> HRESULT {
  474. if allocator.is_null() {
  475. return E_INVALIDARG;
  476. }
  477. // SAFETY: the title passes one of our lists.
  478. let kind = unsafe { (*this.cast::<List>()).kind };
  479. front(this).begin(kind, pipeline);
  480. S_OK
  481. }
  482. extern "system" fn list_reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  483. list_reset(this, allocator, pipeline)
  484. }
  485. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  486. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  487. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  488. return std::ptr::null_mut();
  489. };
  490. if this.is_null() || !align.is_power_of_two() {
  491. return std::ptr::null_mut();
  492. }
  493. let front = front(this);
  494. if front.closed || front.recording.is_none() {
  495. return std::ptr::null_mut();
  496. }
  497. let Some(mut block) = Upload::new(len) else {
  498. return std::ptr::null_mut();
  499. };
  500. let start = block.start();
  501. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  502. let place = unsafe { start.add(start.align_offset(align)) };
  503. front.put(UPLOAD, &[Box::into_raw(Box::new(block)) as u64]);
  504. place
  505. }
  506. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  507. if !barriers.is_null() {
  508. front(this).put_with(BARRIER, &[u64::from(count)], &[bytes_of(barriers, count as usize)]);
  509. }
  510. 0
  511. }
  512. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  513. front(this).put(BARRIER_GROUPS, &[u64::from(count)]);
  514. }
  515. extern "system" fn viewports(this: This, count: u32, items: *const D3D12_VIEWPORT) {
  516. let count = if items.is_null() { 0 } else { count };
  517. front(this).put_with(VIEWPORTS, &[u64::from(count)], &[bytes_of(items, count as usize)]);
  518. }
  519. extern "system" fn scissors(this: This, count: u32, items: *const RECT) {
  520. let count = if items.is_null() { 0 } else { count };
  521. front(this).put_with(SCISSORS, &[u64::from(count)], &[bytes_of(items, count as usize)]);
  522. }
  523. extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  524. let given = !factor.is_null();
  525. front(this).put_with(BLEND_FACTOR, &[u64::from(given)], &[bytes_of(factor, usize::from(given))]);
  526. }
  527. extern "system" fn heaps(this: This, count: u32, items: *const This) {
  528. let count = if items.is_null() { 0 } else { count };
  529. front(this).put_with(HEAPS, &[u64::from(count)], &[bytes_of(items, count as usize)]);
  530. }
  531. fn constants(this: This, op: u64, slot: u32, count: u32, values: *const u32, offset: u32) {
  532. let count = if values.is_null() { 0 } else { count };
  533. front(this).put_with(
  534. op,
  535. &[u64::from(slot) | u64::from(offset) << 32, u64::from(count)],
  536. &[bytes_of(values, count as usize)],
  537. );
  538. }
  539. extern "system" fn compute_constants(this: This, slot: u32, count: u32, values: *const u32, offset: u32) {
  540. constants(this, COMPUTE_CONSTANTS, slot, count, values, offset);
  541. }
  542. extern "system" fn graphics_constants(this: This, slot: u32, count: u32, values: *const u32, offset: u32) {
  543. constants(this, GRAPHICS_CONSTANTS, slot, count, values, offset);
  544. }
  545. extern "system" fn index_buffer(this: This, view: *const IndexView) {
  546. let given = !view.is_null();
  547. front(this).put_with(INDEX_BUFFER, &[u64::from(given)], &[bytes_of(view, usize::from(given))]);
  548. }
  549. extern "system" fn vertex_buffers(this: This, start: u32, count: u32, views: *const VertexView) {
  550. let given = !views.is_null();
  551. front(this).put_with(
  552. VERTEX_BUFFERS,
  553. &[u64::from(start) | u64::from(count) << 32, u64::from(given)],
  554. &[bytes_of(views, count as usize)],
  555. );
  556. }
  557. extern "system" fn targets(this: This, count: u32, handles: *const u64, one_range: i32, depth: *const u64) {
  558. let count = if handles.is_null() { 0 } else { (count as usize).min(8) };
  559. // SAFETY: the title passes a handle or null.
  560. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  561. let mut records = [0u64; RECORD * 9];
  562. let mut present = 0u64;
  563. for i in 0..count {
  564. // SAFETY: the title passes `count` handles, or the first of a range
  565. // of views of 128 bytes.
  566. let handle = unsafe { if one_range != 0 { *handles + 128 * i as u64 } else { *handles.add(i) } };
  567. present |= u64::from(handle != 0) << i;
  568. records[i * RECORD..(i + 1) * RECORD].copy_from_slice(&record(handle));
  569. }
  570. records[count * RECORD..(count + 1) * RECORD].copy_from_slice(&record(depth));
  571. let records = &records[..(count + 1) * RECORD];
  572. front(this).put_with(
  573. TARGETS,
  574. &[count as u64, present, u64::from(depth != 0)],
  575. &[bytes_of(records.as_ptr(), records.len())],
  576. );
  577. }
  578. extern "system" fn clear_rtv(this: This, handle: u64, color: *const [f32; 4], count: u32, rects: *const Rect) {
  579. if handle == 0 || color.is_null() {
  580. return;
  581. }
  582. let count = if rects.is_null() { 0 } else { count };
  583. let view = record(handle);
  584. front(this).put_with(
  585. CLEAR_RTV,
  586. &[u64::from(count)],
  587. &[bytes_of(view.as_ptr(), RECORD), bytes_of(color, 1), bytes_of(rects, count as usize)],
  588. );
  589. }
  590. extern "system" fn clear_dsv(
  591. this: This,
  592. handle: u64,
  593. flags: u32,
  594. depth: f32,
  595. stencil: u8,
  596. count: u32,
  597. rects: *const Rect,
  598. ) {
  599. if handle == 0 {
  600. return;
  601. }
  602. let count = if rects.is_null() { 0 } else { count };
  603. let view = record(handle);
  604. front(this).put_with(
  605. CLEAR_DSV,
  606. &[u64::from(count), u64::from(flags) | u64::from(stencil) << 32, Word::word(depth)],
  607. &[bytes_of(view.as_ptr(), RECORD), bytes_of(rects, count as usize)],
  608. );
  609. }
  610. extern "system" fn copy_texture_region(
  611. this: This,
  612. dst: *const CopyLocation,
  613. x: u32,
  614. y: u32,
  615. z: u32,
  616. src: *const CopyLocation,
  617. source_box: *const [u32; 6],
  618. ) {
  619. if dst.is_null() || src.is_null() {
  620. return;
  621. }
  622. let boxed = !source_box.is_null();
  623. front(this).put_with(
  624. COPY_TEXTURE,
  625. &[u64::from(x) | u64::from(y) << 32, u64::from(z) | u64::from(boxed) << 32],
  626. &[bytes_of(dst, 1), bytes_of(src, 1), bytes_of(source_box, usize::from(boxed))],
  627. );
  628. }
  629. #[allow(clippy::too_many_arguments)] // the method's own arguments
  630. extern "system" fn copy_texture_region_x(
  631. this: This,
  632. dst: *const CopyLocation,
  633. x: u32,
  634. y: u32,
  635. z: u32,
  636. src: *const CopyLocation,
  637. source_box: *const [u32; 6],
  638. _flags: u32,
  639. ) {
  640. copy_texture_region(this, dst, x, y, z, src, source_box);
  641. }
  642. /// Makes the calls of a stream on `list`: how many, and whether the last one
  643. /// closed it. Once `left` says so only what must not be lost is done.
  644. fn translate(list: This, stream: &[u64], left: impl Fn() -> bool) -> (u64, bool) {
  645. let (mut i, mut calls, mut closed) = (0, 0, false);
  646. let mut skip = left();
  647. while i < stream.len() {
  648. let (op, len) = (stream[i] & 0xffff, (stream[i] >> 16) as usize);
  649. let w = &stream[i + 1..i + 1 + len];
  650. i += 1 + len;
  651. calls += 1;
  652. if calls % 64 == 0 {
  653. skip = left();
  654. }
  655. if op == UPLOAD {
  656. // SAFETY: made by `allocate_upload`, named once.
  657. let block = *unsafe { Box::from_raw(w[0] as *mut Upload) };
  658. // SAFETY: a list of ours.
  659. let uploads = unsafe { &(*list.cast::<List>()).uploads };
  660. held(uploads).push(block);
  661. continue;
  662. }
  663. if skip && op != CLOSE && op != RESET {
  664. continue;
  665. }
  666. if run_plain(op, list, w) {
  667. continue;
  668. }
  669. let n = w.first().map_or(0, |&n| n as usize);
  670. match op {
  671. RESET => {
  672. // (Only whether there is an allocator is looked at.)
  673. let allocator: This = std::ptr::NonNull::<u64>::dangling().as_ptr().cast_const().cast();
  674. super::reset(list, allocator, w[0] as This);
  675. }
  676. CLOSE => {
  677. super::close(list);
  678. closed = true;
  679. }
  680. BARRIER => {
  681. super::barrier(list, n as u32, at_or(w, 1));
  682. }
  683. BARRIER_GROUPS => super::barrier_groups(list, n as u32, std::ptr::null()),
  684. VIEWPORTS => state::viewports(list, n as u32, at(w, 1, n)),
  685. SCISSORS => state::scissors(list, n as u32, at(w, 1, n)),
  686. BLEND_FACTOR => state::blend_factor(list, at(w, 1, n)),
  687. HEAPS => state::heaps(list, n as u32, at(w, 1, n)),
  688. COMPUTE_CONSTANTS => {
  689. state::compute_constants(list, w[0] as u32, w[1] as u32, at(w, 2, w[1] as usize), (w[0] >> 32) as u32)
  690. }
  691. GRAPHICS_CONSTANTS => {
  692. state::graphics_constants(list, w[0] as u32, w[1] as u32, at(w, 2, w[1] as usize), (w[0] >> 32) as u32)
  693. }
  694. INDEX_BUFFER => state::index_buffer(list, at(w, 1, n)),
  695. VERTEX_BUFFERS => {
  696. let views = if w[1] != 0 { at_or(w, 2) } else { std::ptr::null() };
  697. state::vertex_buffers(list, w[0] as u32, (w[0] >> 32) as u32, views);
  698. }
  699. TARGETS => {
  700. let mut handles = [0u64; 8];
  701. let place = |k: usize| w[3 + k * RECORD..].as_ptr() as u64;
  702. for (k, h) in handles.iter_mut().enumerate().take(n) {
  703. if w[1] >> k & 1 != 0 {
  704. *h = place(k);
  705. }
  706. }
  707. let depth = if w[2] != 0 { place(n) } else { 0 };
  708. state::targets(list, n as u32, handles.as_ptr(), 0, &depth);
  709. }
  710. CLEAR_RTV => {
  711. super::clear_rtv(
  712. list,
  713. w[1..].as_ptr() as u64,
  714. at_or(w, 1 + RECORD),
  715. n as u32,
  716. at(w, 1 + RECORD + 2, n),
  717. );
  718. }
  719. CLEAR_DSV => {
  720. super::clear_dsv(
  721. list,
  722. w[3..].as_ptr() as u64,
  723. w[1] as u32,
  724. Word::unword(w[2]),
  725. (w[1] >> 32) as u8,
  726. n as u32,
  727. at(w, 3 + RECORD, n),
  728. );
  729. }
  730. COPY_TEXTURE => {
  731. let step = size_of::<CopyLocation>().div_ceil(8);
  732. let boxed = (w[1] >> 32) as usize;
  733. super::copy_texture_region(
  734. list,
  735. at_or(w, 2),
  736. w[0] as u32,
  737. (w[0] >> 32) as u32,
  738. w[1] as u32,
  739. at_or(w, 2 + step),
  740. at(w, 2 + 2 * step, boxed),
  741. );
  742. }
  743. _ => {}
  744. }
  745. }
  746. (calls, closed)
  747. }
  748. /// The table of a list whose calls are written down: that of the others with
  749. /// the methods that record replaced (slots as in [`super::METHODS`]).
  750. pub(super) const fn table(newer: bool) -> [*const (); 160] {
  751. let mut f = super::list_table(newer);
  752. let mut i = 0;
  753. while i < MINE.len() {
  754. let (slot, method) = MINE[i];
  755. f[if newer { newer_slot(slot) } else { slot }] = method;
  756. i += 1;
  757. }
  758. if newer {
  759. f[146] = barrier_groups as *const ();
  760. f[148] = allocate_upload as *const ();
  761. }
  762. f
  763. }
  764. const MINE: [(usize, *const ()); 50] = [
  765. (9, list_close as *const ()),
  766. (10, list_reset as *const ()),
  767. (12, draw as *const ()),
  768. (13, draw_indexed as *const ()),
  769. (14, dispatch as *const ()),
  770. (15, copy_buffer_region as *const ()),
  771. (16, copy_texture_region as *const ()),
  772. (17, copy_resource as *const ()),
  773. (19, resolve as *const ()),
  774. (20, topology as *const ()),
  775. (21, viewports as *const ()),
  776. (22, scissors as *const ()),
  777. (23, blend_factor as *const ()),
  778. (24, stencil_ref as *const ()),
  779. (25, set_pipeline as *const ()),
  780. (26, barrier as *const ()),
  781. (30, resolve_queries as *const ()),
  782. (32, heaps as *const ()),
  783. (35, compute_table as *const ()),
  784. (36, graphics_table as *const ()),
  785. (37, compute_constant as *const ()),
  786. (38, graphics_constant as *const ()),
  787. (39, compute_constants as *const ()),
  788. (40, graphics_constants as *const ()),
  789. (41, compute_view as *const ()),
  790. (42, graphics_view as *const ()),
  791. (43, compute_view as *const ()),
  792. (44, graphics_view as *const ()),
  793. (45, compute_view as *const ()),
  794. (46, graphics_view as *const ()),
  795. (47, index_buffer as *const ()),
  796. (48, vertex_buffers as *const ()),
  797. (50, targets as *const ()),
  798. (51, clear_dsv as *const ()),
  799. (52, clear_rtv as *const ()),
  800. (59, execute_indirect as *const ()),
  801. (60, copy_memory as *const ()),
  802. (68, depth_bounds as *const ()),
  803. (69, write32 as *const ()),
  804. (70, write64 as *const ()),
  805. (71, wait_value as *const ()),
  806. (72, wait_value64 as *const ()),
  807. (78, dispatch_x as *const ()),
  808. (83, copy_texture_region_x as *const ()),
  809. (84, copy_resource_x as *const ()),
  810. (98, dispatch_mesh_x as *const ()),
  811. (127, dispatch_mesh as *const ()),
  812. (129, sync as *const ()),
  813. (130, sync as *const ()),
  814. (137, list_reset_x as *const ()),
  815. ];
  816. #[cfg(test)]
  817. mod tests {
  818. use super::*;
  819. /// Every method of the tables that records is written down too: what is
  820. /// left in both tables alike records nothing.
  821. #[test]
  822. fn every_recording_method_is_written_down() {
  823. const NOTHING: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 28, 29, 33, 34, 73, 99, 124];
  824. let mine: Vec<usize> = MINE.iter().map(|m| m.0).collect();
  825. for (slot, _) in METHODS.iter().chain(MORE_METHODS.iter()) {
  826. assert!(mine.contains(slot) != NOTHING.contains(slot), "slot {slot}");
  827. }
  828. for &slot in &mine {
  829. assert!(
  830. METHODS.iter().chain(MORE_METHODS.iter()).any(|m| m.0 == slot),
  831. "slot {slot} is written down and not there"
  832. );
  833. }
  834. }
  835. /// Arguments come out of a stream as they went in.
  836. #[test]
  837. fn a_stream_gives_back_what_was_written() {
  838. let mut f = Front::default();
  839. f.recording = Some(Arc::new(Recording::new(0)));
  840. f.put(Plain::DRAW_INDEXED as u64, &[3, 1, 0, Word::word(-7i32), 5]);
  841. let viewport = [1.0f32, 2.0, 3.0, 4.0, 0.0, 1.0];
  842. f.put_with(VIEWPORTS, &[1], &[bytes_of(viewport.as_ptr(), 6)]);
  843. f.put_with(COMPUTE_CONSTANTS, &[4 | 2 << 32, 3], &[bytes_of([7u32, 8, 9].as_ptr(), 3)]);
  844. let s = std::mem::take(&mut f.words);
  845. assert_eq!((s[0] & 0xffff, s[0] >> 16), (Plain::DRAW_INDEXED as u64, 5));
  846. assert_eq!(<i32 as Word>::unword(s[4]), -7);
  847. let w = &s[6..];
  848. assert_eq!((w[0] & 0xffff, w[0] >> 16, w[1]), (VIEWPORTS, 4, 1));
  849. // SAFETY: what was written just now.
  850. assert_eq!(unsafe { *at::<[f32; 6]>(&w[1..], 1, 1) }, viewport);
  851. let w = &w[5..];
  852. assert_eq!((w[0] & 0xffff, w[0] >> 16), (COMPUTE_CONSTANTS, 4));
  853. // SAFETY: as above.
  854. assert_eq!(unsafe { *at::<[u32; 3]>(&w[1..], 2, 3) }, [7, 8, 9]);
  855. assert!(at::<u32>(&w[1..], 2, 0).is_null());
  856. }
  857. /// A view's record is the one at the call, also if its slot is written
  858. /// again right after.
  859. #[test]
  860. fn a_target_is_the_one_at_the_call() {
  861. let mut slot = [0x5256_5476u64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
  862. let kept = record(slot.as_ptr() as u64);
  863. slot[1] = 99;
  864. assert_eq!(kept[1], 2);
  865. assert_eq!(record(0), [0; RECORD]);
  866. }
  867. }