mod.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. //! DXIL emission (decision 0003, step 3): a console vertex, pixel, compute
  2. //! or mesh shader as a PC DXIL container (SM 6.6) that host D3D12 accepts.
  3. //! Compute shaders keep the console's thread-group size; one that depends
  4. //! on the lane layout (cross-lane operations) declares the console's wave
  5. //! size (`WaveSize`), so the host device must support it.
  6. //!
  7. //! What the host binds for a translated shader ([`HostShader`]):
  8. //!
  9. //! * **User data** at `b0, space 0` (32-bit root constants or a constant
  10. //! buffer, per stage): dword `index` holds a root parameter's value, as
  11. //! [`UserData`] lists. A root-constant dword is the constant. A
  12. //! descriptor table is the byte offset of its first descriptor in its
  13. //! heap: the descriptor index times 32 for CBV/SRV/UAV tables, times 16
  14. //! for sampler tables (the console's descriptor sizes; the code adds
  15. //! offsets in those units). The heap bases of dynamic resources are 0
  16. //! and not listed.
  17. //! * **Descriptors** through SM 6.6 `ResourceDescriptorHeap[]` and
  18. //! `SamplerDescriptorHeap[]`, at the index the console address gives, so
  19. //! the host heaps keep the title's descriptor order. The root signature
  20. //! needs `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` and
  21. //! `SAMPLER_HEAP_DIRECTLY_INDEXED`.
  22. //! * **Immediate samplers** as static samplers `s<n>, space 0`, `n` the
  23. //! position in [`HostShader::samplers`] (the console sampler words) and
  24. //! [`HostShader::static_samplers`] (the same decoded into a D3D12 static
  25. //! sampler description). Comparison sampling (added 2026-11-23): an
  26. //! immediate sampler it uses has a comparison filter there (bit 0x80);
  27. //! a heap sampler it uses must be a comparison sampler on the host.
  28. //! * **Root CBVs and root SRVs** (raw buffers) as root descriptors
  29. //! `b<i>` / `t<i>` in [`ROOT_CBV_SPACE`], `i` the title's root parameter
  30. //! index ([`HostShader::root_cbvs`], [`HostShader::root_srvs`]); the
  31. //! address the title sets is the buffer's.
  32. //! * **Vertex fetch** (added 2026-11-23). Grand Theft Auto VI's mesh and
  33. //! vertex programs fetch vertices themselves with typed-format loads
  34. //! (`tbuffer_load_format_*`): the format (8_8_8_8 unorm, 16_16 snorm,
  35. //! 2_10_10_10 unorm, 8_8_8_8 and 16_16_16_16 uint...) is in the
  36. //! instruction, so the translation reads raw bytes and converts them
  37. //! itself. Their descriptors are built around a root SRV (stride 1, no
  38. //! record limit): the host binds the root SRV `t<slot>` above with the
  39. //! address the title sets, nothing more. The vertex index, the stride
  40. //! and the attribute offset are the shader's own arithmetic on data in
  41. //! that buffer (per-stream headers), not descriptor fields.
  42. //! * **Buffer views in the heap** are declared by how the shader reads
  43. //! them: raw (ByteAddressBuffer) for dword loads and stores, atomics and
  44. //! typed-format loads without an index; structured with the used-resource
  45. //! entry's stride when indexed; typed with four 32-bit float channels for
  46. //! `buffer_load_format_*` and `buffer_store_format_*`. The host's view at
  47. //! that index must be of that kind and start at the console descriptor's
  48. //! base address (raw: `R32_TYPELESS` with the raw flag), whatever kind the
  49. //! title's view description says. Typed-format loads from heap
  50. //! descriptors (1,024 world compute programs, ray-tracing material
  51. //! resolves) read raw views this way.
  52. //!
  53. //! * **Texture atomics** (added 2026-11-23): a texture UAV the shader uses
  54. //! atomically is declared a 32-bit unsigned single-channel view; the
  55. //! host's view at that index must be an R32 integer view (64-bit atomics
  56. //! stop the translation). Global loads from a root SRV read it raw.
  57. //!
  58. //! Entry points: [`translate`] (container bytes as the title passes them
  59. //! at pipeline creation → [`HostShader`]), [`emit`] (the same with the
  60. //! earlier stages already run). The root constants of each stage must
  61. //! cover [`HostShader::user_data_dwords`]. Stability: these types and the
  62. //! binding scheme are what pipeline creation builds on; changes are
  63. //! announced.
  64. //! * **Signatures** as the console container has them (same semantics,
  65. //! registers and masks), so the input layout and stage linking are the
  66. //! title's; pixel outputs are plain 32-bit values.
  67. //! * **Mesh shaders** ([`HwStage::Ms`], `ms_6_6`): user data and
  68. //! descriptors as above (the root constants visible to the mesh stage);
  69. //! the pipeline is a mesh pipeline (pipeline-state stream, no input
  70. //! layout) with the title's pixel shader. The thread group is the
  71. //! console's in lanes (`[numthreads]` in the DXIL), the vertex and
  72. //! primitive maxima its own, triangles only, no wave size required. The
  73. //! console numbers groups in x only: the draw path passes the title's
  74. //! count as `DispatchMesh(x, 1, 1)`. Per-primitive outputs (`PSG1`) are
  75. //! the console's, without `SV_PrimitiveID` and `SV_CullPrimitive` (the
  76. //! console never exports them).
  77. mod bitcode;
  78. mod container;
  79. #[cfg(all(test, windows))]
  80. mod diff_tests;
  81. #[cfg(all(windows, any(test, feature = "host")))]
  82. pub mod host;
  83. mod lower;
  84. mod sampler;
  85. mod shader;
  86. #[cfg(windows)]
  87. pub mod validator;
  88. mod wave;
  89. use crate::dxbc::{Container, FourCC};
  90. use crate::native::{HwStage, NativeProgram, RootType};
  91. use crate::{ShaderError, io, ir, resource, structure};
  92. pub use sampler::StaticSampler;
  93. pub use shader::{ROOT_CBV_SPACE, SAMPLER_SPACE, USER_DATA_SPACE};
  94. /// The loop limit without an override: 2^20.
  95. pub const DEFAULT_LOOP_LIMIT: u32 = lower::LOOP_LIMIT;
  96. /// The iteration count after which a translated loop is left, per lane and
  97. /// per entry into the loop: [`DEFAULT_LOOP_LIMIT`].
  98. ///
  99. /// With the `diagnostics` feature, `VICTORY_SHADER_LOOP_LIMIT` (decimal or
  100. /// `0x` hex, at least 1) sets it instead. A loop that hits the limit in
  101. /// every lane of a full-screen pass still runs for seconds (2^20 times a
  102. /// 4K screen is about 10^13 iterations); a much lower limit shows whether
  103. /// such loops are what makes a frame slow. The value is part of the
  104. /// translation, so the shader cache must key on it (`victory-gpu`'s does).
  105. pub fn loop_limit() -> u32 {
  106. static LIMIT: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  107. *LIMIT.get_or_init(|| {
  108. if cfg!(feature = "diagnostics") {
  109. parse_loop_limit(std::env::var("VICTORY_SHADER_LOOP_LIMIT").ok().as_deref())
  110. } else {
  111. lower::LOOP_LIMIT
  112. }
  113. })
  114. }
  115. /// `VICTORY_SHADER_LOOP_LIMIT`'s value; the default when it is unset,
  116. /// unreadable or 0. Pure, for testing.
  117. fn parse_loop_limit(value: Option<&str>) -> u32 {
  118. let parsed = value
  119. .map(str::trim)
  120. .and_then(|v| match v.strip_prefix("0x") {
  121. Some(hex) => u32::from_str_radix(hex, 16).ok(),
  122. None => v.parse().ok(),
  123. });
  124. match parsed {
  125. Some(n) if n > 0 => n,
  126. _ => lower::LOOP_LIMIT,
  127. }
  128. }
  129. /// A translated shader and what the host binds for it.
  130. #[derive(Debug, Clone, PartialEq, Eq)]
  131. pub struct HostShader {
  132. pub stage: HwStage,
  133. /// The DXIL container, hashed as D3D12 expects.
  134. pub dxil: Vec<u8>,
  135. /// The user-data dwords the shader reads.
  136. pub user_data: Vec<UserData>,
  137. /// Immediate samplers: the four sampler words of `s<n>`.
  138. pub samplers: Vec<[u32; 4]>,
  139. /// The same samplers decoded, `s<n>` at position n: the static sampler
  140. /// descriptions the host's root signature declares.
  141. pub static_samplers: Vec<StaticSampler>,
  142. /// Root CBVs the shader reads: root parameter indices, each bound as
  143. /// `b<index>` in [`ROOT_CBV_SPACE`].
  144. pub root_cbvs: Vec<u8>,
  145. /// Root SRVs (raw buffers) the shader reads: `t<index>` in
  146. /// [`ROOT_CBV_SPACE`].
  147. pub root_srvs: Vec<u8>,
  148. }
  149. impl HostShader {
  150. /// Size of the user-data buffer the shader declares, in dwords (a
  151. /// multiple of 4; 0 when it reads none). Root constants must cover it.
  152. pub fn user_data_dwords(&self) -> u32 {
  153. let n = self
  154. .user_data
  155. .iter()
  156. .map(|u| u.index + 1)
  157. .max()
  158. .unwrap_or(0);
  159. n.next_multiple_of(4)
  160. }
  161. }
  162. /// One dword of user data and the root parameter that fills it.
  163. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  164. pub struct UserData {
  165. /// Dword in the user-data buffer (the console's user-data index).
  166. pub index: u32,
  167. /// Root parameter index in the title's root signature.
  168. pub slot: u8,
  169. /// `Constants` or `Table` (see the module notes for the value).
  170. pub root: RootType,
  171. /// Dword within the parameter.
  172. pub dword: u32,
  173. }
  174. /// Translates the vertex, pixel, compute or mesh program of a console
  175. /// shader container.
  176. pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
  177. let c = Container::parse(container)?;
  178. let dxil = c
  179. .part(FourCC::DXIL)
  180. .ok_or(ShaderError::Malformed("no DXIL part"))?;
  181. let native = crate::native_programs(dxil.data)?
  182. .into_iter()
  183. .find(|p| {
  184. matches!(
  185. p.stage,
  186. HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms
  187. )
  188. })
  189. .ok_or(ShaderError::Unsupported {
  190. offset: 0,
  191. what: "a container without a vertex, pixel, compute or mesh program",
  192. })?;
  193. let p = ir::build(&native.patched_code(), native.wave64, native.vgprs)?;
  194. let res = resource::track(&p, &native.layout, native.stage)?;
  195. let io = io::raise(&p, &native)?;
  196. let st = structure::structure(&p)?;
  197. emit(&c, &native, &p, &st, &io, &res)
  198. }
  199. /// Emits a program whose earlier stages already ran.
  200. pub fn emit(
  201. c: &Container,
  202. native: &NativeProgram,
  203. p: &ir::Program,
  204. st: &structure::Structured,
  205. io: &io::Io,
  206. res: &resource::Resources,
  207. ) -> Result<HostShader, ShaderError> {
  208. let sig = |fourcc| -> Result<Vec<container::SigElement>, ShaderError> {
  209. match c.part(fourcc) {
  210. Some(part) => signature(part.data),
  211. None => Ok(Vec::new()),
  212. }
  213. };
  214. let pixel = native.stage == HwStage::Ps;
  215. let mut inputs = sig(FourCC::ISG1)?;
  216. let mut outputs = sig(FourCC::OSG1)?;
  217. // Interpolation as DXC declares it by default; pixel inputs that are
  218. // read get the mode their barycentrics say.
  219. let interpolated = if pixel { &mut inputs } else { &mut outputs };
  220. for e in interpolated {
  221. e.interp = match (e.kind, e.comp) {
  222. (3, _) => 4,
  223. // Constant, as DXC declares it (the AMD compiler crashed on a
  224. // front face without a mode).
  225. (13, _) => 1,
  226. (0 | 6 | 7, 9) => 2,
  227. (0, _) => 1,
  228. _ => 0,
  229. };
  230. }
  231. // Per-primitive outputs are constant. The console never exports a
  232. // primitive id or cull flag a mesh shader writes (it culls with the
  233. // primitive export), so those rows are left out.
  234. let mut prims = sig(FourCC::PSG1)?;
  235. prims.retain(|e| !matches!(e.kind, 10 | 30));
  236. for e in &mut prims {
  237. e.interp = 1;
  238. }
  239. // A mesh group's id arrives multiplied by max(threads, vertices,
  240. // primitives) (the code divides by that); the thread count is in PSV0
  241. // from runtime info version 2 on.
  242. // shortcut: older containers fall back to the group's lane count, right
  243. // when the HLSL group fills its waves (Grand Theft Auto VI's do).
  244. let mesh_stride = match &native.io {
  245. crate::native::StageIo::Ms(ms) => {
  246. let psv = c.part(FourCC::PSV0).map(|p| p.data);
  247. let threads = psv
  248. .filter(|d| crate::dxbc::u32_at(d, 0).is_ok_and(|n| n >= 48))
  249. .and_then(|d| crate::dxbc::u32_at(d, 4 + 36).ok());
  250. threads.map_or(ms.threads, |t| {
  251. t.max(ms.max_vertices).max(ms.max_primitives)
  252. })
  253. }
  254. _ => 0,
  255. };
  256. let l = lower::lower(&lower::Parts {
  257. native,
  258. p,
  259. st,
  260. io,
  261. res,
  262. inputs,
  263. outputs,
  264. prims,
  265. mesh_stride,
  266. })?;
  267. Ok(HostShader {
  268. stage: native.stage,
  269. dxil: l.dxil,
  270. user_data: l.user_data,
  271. static_samplers: l
  272. .samplers
  273. .iter()
  274. .enumerate()
  275. .map(|(n, &w)| {
  276. let mut s = StaticSampler::from_words(w);
  277. if l.cmp_samplers >> n & 1 != 0 {
  278. s.filter |= 0x80;
  279. }
  280. s
  281. })
  282. .collect(),
  283. samplers: l.samplers,
  284. root_cbvs: l.root_cbvs,
  285. root_srvs: l.root_srvs,
  286. })
  287. }
  288. /// The rows of an `ISG1`/`OSG1` part.
  289. fn signature(part: &[u8]) -> Result<Vec<container::SigElement>, ShaderError> {
  290. use crate::dxbc::u32_at;
  291. let count = u32_at(part, 0)? as usize;
  292. let base = u32_at(part, 4)? as usize;
  293. let mut out = Vec::with_capacity(count);
  294. for i in 0..count {
  295. let at = base + 32 * i;
  296. let name_at = u32_at(part, at + 4)? as usize;
  297. let name = part
  298. .get(name_at..)
  299. .and_then(|s| s.split(|&b| b == 0).next())
  300. .ok_or(ShaderError::Malformed("signature name out of bounds"))?;
  301. let mask = *part
  302. .get(at + 24)
  303. .ok_or(ShaderError::Malformed("truncated"))?;
  304. if u32_at(part, at + 28)? != 0 {
  305. return Err(ShaderError::Unsupported {
  306. offset: 0,
  307. what: "a minimum-precision signature element",
  308. });
  309. }
  310. if u32_at(part, at)? != 0 {
  311. return Err(ShaderError::Unsupported {
  312. offset: 0,
  313. what: "a signature element of another stream",
  314. });
  315. }
  316. let kind = match u32_at(part, at + 12)? {
  317. 0 => 0,
  318. 1 => 3,
  319. 2 => 6,
  320. 3 => 7,
  321. 4 => 4,
  322. 5 => 5,
  323. 6 => 1,
  324. 7 => 10,
  325. 8 => 2,
  326. 9 => 13,
  327. 10 => 12,
  328. 64 => 16,
  329. 65 => 17,
  330. 66 => 14,
  331. 67 => 19,
  332. 68 => 18,
  333. 69 => 20,
  334. 70 => 15,
  335. 25 => 30, // cull primitive
  336. _ => {
  337. return Err(ShaderError::Unsupported {
  338. offset: 0,
  339. what: "a system value in the signature",
  340. });
  341. }
  342. };
  343. // 16-bit elements are declared 32-bit; reading or writing one
  344. // converts (16-bit values travel packed on the console).
  345. let raw = u32_at(part, at + 16)?;
  346. let comp = match (kind, raw) {
  347. // DXIL declares the front face a uint (the validator insists).
  348. (13, _) => 5,
  349. (_, 1 | 4) => 5,
  350. (_, 2 | 5) => 4,
  351. (_, 3 | 6) => 9,
  352. (_, c) => {
  353. return Err(ShaderError::Unsupported {
  354. offset: 0,
  355. what: match c {
  356. 0 => "a signature element of unknown type",
  357. _ => "a 64-bit signature element",
  358. },
  359. });
  360. }
  361. };
  362. let register = u32_at(part, at + 20)?;
  363. out.push(container::SigElement {
  364. name: String::from_utf8_lossy(name).into_owned(),
  365. index: u32_at(part, at + 8)?,
  366. kind,
  367. comp,
  368. interp: 0,
  369. row: (register != u32::MAX).then_some(register),
  370. col: mask.trailing_zeros().min(3) as u8,
  371. cols: mask.count_ones().max(1) as u8,
  372. usage: 0,
  373. half: (4..=6).contains(&raw),
  374. });
  375. }
  376. Ok(out)
  377. }
  378. #[cfg(test)]
  379. mod tests {
  380. use super::bitcode::Attr;
  381. use super::lower::LOOP_LIMIT;
  382. use super::parse_loop_limit;
  383. #[test]
  384. fn the_loop_limit_switch_parses_or_falls_back() {
  385. assert_eq!(parse_loop_limit(None), LOOP_LIMIT);
  386. assert_eq!(parse_loop_limit(Some("4096")), 4096);
  387. assert_eq!(parse_loop_limit(Some(" 0x1000 ")), 4096);
  388. assert_eq!(parse_loop_limit(Some("1")), 1);
  389. for bad in ["", "0", "-5", "lots", "0x", "4294967296"] {
  390. assert_eq!(parse_loop_limit(Some(bad)), LOOP_LIMIT, "{bad:?}");
  391. }
  392. }
  393. use super::container::SigElement;
  394. use super::shader::Shader;
  395. /// A pixel shader writing a constant colour.
  396. fn constant_color() -> Vec<u8> {
  397. let mut s = Shader::new(true);
  398. s.outputs.push(SigElement {
  399. name: "SV_Target".into(),
  400. index: 0,
  401. kind: 16,
  402. comp: 9,
  403. interp: 0,
  404. row: Some(0),
  405. col: 0,
  406. cols: 4,
  407. usage: 15,
  408. half: false,
  409. });
  410. let b = s.entry;
  411. for (c, v) in [1.0f32, 0.5, 0.25, 1.0].into_iter().enumerate() {
  412. let args = [
  413. s.m.i32(0),
  414. s.m.i32(0),
  415. s.m.i8(c as u8),
  416. s.m.f32(v.to_bits()),
  417. ];
  418. s.op(b, "storeOutput.f32", Attr::NoUnwind, s.t.void, 5, &args);
  419. }
  420. s.m.terminate(b, super::bitcode::Term::Ret);
  421. s.finish()
  422. }
  423. #[test]
  424. #[cfg(windows)]
  425. fn stub_pipeline_is_created() {
  426. let Ok(host) = super::host::Host::new(false) else {
  427. eprintln!("no SM 6.6 device; skipped");
  428. return;
  429. };
  430. let ps = super::HostShader {
  431. stage: crate::HwStage::Ps,
  432. dxil: constant_color(),
  433. user_data: Vec::new(),
  434. samplers: Vec::new(),
  435. static_samplers: Vec::new(),
  436. root_cbvs: Vec::new(),
  437. root_srvs: Vec::new(),
  438. };
  439. let file = |var: &str, stage| {
  440. std::env::var(var).ok().map(|p| super::HostShader {
  441. stage,
  442. dxil: std::fs::read(p).unwrap(),
  443. user_data: Vec::new(),
  444. samplers: Vec::new(),
  445. static_samplers: Vec::new(),
  446. root_cbvs: Vec::new(),
  447. root_srvs: Vec::new(),
  448. })
  449. };
  450. let ps = file("VICTORY_REF_PS", crate::HwStage::Ps).unwrap_or(ps);
  451. let vs = file("VICTORY_REF_VS", crate::HwStage::Vs)
  452. .unwrap_or_else(|| super::host::stub_vs(&ps).unwrap());
  453. if let Ok(mut v) = super::validator::Validator::load(
  454. super::validator::Validator::default_path().as_deref(),
  455. ) {
  456. v.validate(&mut vs.dxil.clone()).unwrap();
  457. }
  458. host.pipeline(&vs, &ps).unwrap();
  459. // The runtime checks the container hash: no hash or a wrong one is
  460. // refused. (Recent runtimes also take sixteen 0x01 bytes, a bypass
  461. // value; ours works with older ones too.)
  462. let mut wrong = ps.dxil[4..20].to_vec();
  463. wrong[0] ^= 1;
  464. for digest in [&[0u8; 16][..], &wrong] {
  465. let mut other = ps.clone();
  466. other.dxil[4..20].copy_from_slice(digest);
  467. assert!(
  468. host.pipeline(&vs, &other).is_err(),
  469. "digest {digest:02x?} accepted"
  470. );
  471. }
  472. }
  473. #[test]
  474. #[cfg(windows)]
  475. fn constant_color_validates() {
  476. let mut c = constant_color();
  477. let path = super::validator::Validator::default_path();
  478. let Ok(mut v) = super::validator::Validator::load(path.as_deref()) else {
  479. eprintln!("no dxil.dll; skipped");
  480. return;
  481. };
  482. let ours = c[4..20].to_vec();
  483. v.validate(&mut c).unwrap();
  484. assert_eq!(c[4..20], ours[..], "our hash differs from the validator's");
  485. }
  486. }