intersect_tests.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //! The ray-tracing node test end to end: a synthetic compute program that
  2. //! runs `image_bvh64_intersect_ray` (or the 32-bit form) once per thread,
  3. //! lowered to DXIL, validated by `dxil.dll` when present, run on the host
  4. //! GPU and WARP, and compared dword for dword with the CPU reference
  5. //! ([`crate::bvh`]).
  6. //!
  7. //! The nodes are in a raw buffer. Two ways to name it are run: the
  8. //! buffer's descriptor from the program's table (a resource of the host,
  9. //! [`crate::resource::BvhNodes::Resource`]), and the title's way, a
  10. //! descriptor of numbers over title memory with the structure's address in
  11. //! the node pointer or in the descriptor. These tests have no host that
  12. //! keeps copies of title memory and their directory, so for the second
  13. //! they put a stand-in under the node reader
  14. //! (`lower::intersect::TEST_MEMORY`); without it the same program reads
  15. //! through the directory, which is only checked to lower and validate.
  16. use super::host::{Dispatch, Host, Root, Stride, View};
  17. use super::lower::intersect::TEST_MEMORY;
  18. use super::{HostShader, lower, validator};
  19. use crate::bvh::{self, Ray, tests as nodes};
  20. use crate::native::{
  21. ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
  22. };
  23. use crate::resource::BvhNodes;
  24. use crate::{ShaderError, io, ir, resource, structure};
  25. /// Threads of one group, each with its own record.
  26. const THREADS: u32 = 32;
  27. /// Bytes of a thread's record: the node pointer (two dwords), the ray's
  28. /// extent, origin, direction and inverse direction, and whether the
  29. /// thread runs the instruction.
  30. const RECORD: u32 = 64;
  31. /// Where the nodes start in the buffer.
  32. const NODES: u32 = THREADS * RECORD;
  33. /// What the result registers hold before the instruction.
  34. const BEFORE: [u32; 4] = [1, 2, 3, 4];
  35. /// How the program names the nodes' memory.
  36. #[derive(Clone, Copy, PartialEq)]
  37. enum Descriptor {
  38. /// The buffer's descriptor from the table.
  39. Table,
  40. /// Numbers, as the title builds it: dwords 0 and 1 (the base address
  41. /// in 256-byte units and the box sorting bit); the size and the rest of
  42. /// the flags as the title sets them.
  43. Numbers(u32, u32),
  44. }
  45. /// The descriptor the title builds for the 64-bit form: the whole address
  46. /// space, sorted boxes, barycentrics returned.
  47. const WHOLE: Descriptor = Descriptor::Numbers(0, bvh::BOX_SORT);
  48. /// The program: per thread, the record's twelve operand dwords in v1-v12,
  49. /// the instruction's result in v13-v16 (under a lane mask of the threads
  50. /// whose record says so), stored to the UAV at 16 bytes a thread.
  51. fn program(wide: bool, descriptor: Descriptor) -> Vec<u32> {
  52. let mut w = vec![
  53. 0xBE85_0380, // s_mov_b32 s5, 0
  54. 0xF408_0202,
  55. 0xFA00_0000, // s_load_dwordx4 s[8:11], s[4:5], 0x0
  56. 0xF408_0302,
  57. 0xFA00_0020, // s_load_dwordx4 s[12:15], s[4:5], 0x20
  58. 0x3428_0086, // v_lshlrev_b32 v20, 6, v0
  59. 0xE038_1000,
  60. 0x8002_0114, // buffer_load_dwordx4 v[1:4], v20, s[8:11], 0 offen
  61. 0xE038_1010,
  62. 0x8002_0514, // buffer_load_dwordx4 v[5:8], v20, s[8:11], 0 offen offset:16
  63. 0xE038_1020,
  64. 0x8002_0914, // buffer_load_dwordx4 v[9:12], v20, s[8:11], 0 offen offset:32
  65. 0xE030_1030,
  66. 0x8002_1114, // buffer_load_dword v17, v20, s[8:11], 0 offen offset:48
  67. ];
  68. for k in 0..4u32 {
  69. // v_mov_b32 v13+k, 1+k
  70. w.push(0x7E00_0200 | (13 + k) << 17 | (0x81 + k));
  71. }
  72. let rsrc = match descriptor {
  73. Descriptor::Table => 8,
  74. Descriptor::Numbers(word0, word1) => {
  75. // s_mov_b32 s24, word0
  76. w.extend([0xBE98_03FF, word0]);
  77. if word1 == bvh::BOX_SORT {
  78. // As the title makes it.
  79. w.push(0xBE99_0B81); // s_brev_b32 s25, 1
  80. } else {
  81. w.extend([0xBE99_03FF, word1]); // s_mov_b32 s25, word1
  82. }
  83. w.extend([
  84. 0xBE9A_03C1, // s_mov_b32 s26, -1
  85. 0xBE9B_03FF,
  86. 0x8900_03FF, // s_mov_b32 s27, 0x890003ff
  87. ]);
  88. 24
  89. }
  90. };
  91. w.extend([
  92. 0xBE94_037E, // s_mov_b32 s20, exec_lo
  93. 0x7DAA_2280, // v_cmpx_ne_u32 exec_lo, 0, v17
  94. ]);
  95. let first = 0x0000_0D01 | (rsrc >> 2) << 16;
  96. if wide {
  97. // image_bvh64_intersect_ray v[13:16], [v1 .. v12], s[rsrc:rsrc+3]
  98. w.extend([0xF19C_9F07, first, 0x0504_0302, 0x0908_0706, 0x000C_0B0A]);
  99. } else {
  100. // image_bvh_intersect_ray v[13:16], [v1, v3 .. v12], s[rsrc:rsrc+3]
  101. w.extend([0xF198_9F07, first, 0x0605_0403, 0x0A09_0807, 0x0000_0C0B]);
  102. }
  103. w.extend([
  104. 0xBEFE_0314, // s_mov_b32 exec_lo, s20
  105. 0x342A_0084, // v_lshlrev_b32 v21, 4, v0
  106. 0xE078_1000,
  107. 0x8003_0D15, // buffer_store_dwordx4 v[13:16], v21, s[12:15], 0 offen
  108. 0xBF81_0000, // s_endpgm
  109. ]);
  110. w
  111. }
  112. fn native(words: &[u32]) -> NativeProgram {
  113. let table = |kind, at| UsedResource {
  114. kind,
  115. root: RootType::Table,
  116. table_offset_dwords: at,
  117. lower_bound: 0,
  118. stride: 4,
  119. dwords: 4,
  120. user_data: 4,
  121. slot: 1,
  122. };
  123. NativeProgram {
  124. stage: HwStage::Cs,
  125. wave64: false,
  126. vgprs: 22,
  127. layout: vec![
  128. RootParam {
  129. root: RootType::Constants,
  130. table_offset_dwords: 0,
  131. sgprs: 4,
  132. base_register: 0,
  133. user_data: 0,
  134. slot: 0,
  135. },
  136. RootParam {
  137. root: RootType::Table,
  138. table_offset_dwords: 0,
  139. sgprs: 1,
  140. base_register: 0,
  141. user_data: 4,
  142. slot: 1,
  143. },
  144. ],
  145. used: vec![table(ResourceType::Srv, 0), table(ResourceType::Uav, 8)],
  146. io: StageIo::Cs(ComputeIo {
  147. rsrc2: 5 << 1,
  148. threads: [THREADS, 1, 1],
  149. }),
  150. code: words.iter().flat_map(|w| w.to_le_bytes()).collect(),
  151. }
  152. }
  153. /// Lowers the program; the DXIL is validated when the validator is there.
  154. fn build(
  155. wide: bool,
  156. descriptor: Descriptor,
  157. ) -> Result<(HostShader, resource::Resources), ShaderError> {
  158. let native = native(&program(wide, descriptor));
  159. let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
  160. let st = structure::structure(&p).expect("structure");
  161. let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
  162. let io = io::raise(&p, &native).expect("io::raise");
  163. let lowered = lower::lower(&lower::Parts {
  164. native: &native,
  165. p: &p,
  166. st: &st,
  167. io: &io,
  168. res: &res,
  169. inputs: Vec::new(),
  170. outputs: Vec::new(),
  171. prims: Vec::new(),
  172. mesh_stride: 0,
  173. })?;
  174. let shader = HostShader {
  175. stage: HwStage::Cs,
  176. dxil: lowered.dxil,
  177. user_data: lowered.user_data,
  178. samplers: lowered.samplers,
  179. static_samplers: Vec::new(),
  180. root_cbvs: lowered.root_cbvs,
  181. root_srvs: lowered.root_srvs,
  182. root_uavs: lowered.root_uavs,
  183. root_indexed_views: res.root_indexed_views.clone(),
  184. };
  185. if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) {
  186. let mut copy = shader.dxil.clone();
  187. v.validate(&mut copy).expect("DXIL validation failed");
  188. }
  189. Ok((shader, res))
  190. }
  191. /// One thread's test: a node (by its index in the node list), the kind its
  192. /// pointer carries, and the ray; `None` leaves the thread masked out.
  193. type Case = Option<(usize, u32, Ray)>;
  194. /// The scene: node dwords (a 32-bit box node takes 32, the others 16) and
  195. /// where each node starts, in dwords from the first node.
  196. struct Scene {
  197. words: Vec<u32>,
  198. starts: Vec<usize>,
  199. }
  200. impl Scene {
  201. fn new() -> Self {
  202. Self {
  203. words: Vec::new(),
  204. starts: Vec::new(),
  205. }
  206. }
  207. /// Adds a node of `dwords` (16 or 32) and returns its index.
  208. fn add(&mut self, node: [u32; 28], dwords: usize) -> usize {
  209. self.starts.push(self.words.len());
  210. let mut padded = [0u32; 32];
  211. padded[..28].copy_from_slice(&node);
  212. // Bytes the instruction must not read as part of the node: what
  213. // follows a 64-byte node, and a box node's last 16 bytes.
  214. for w in padded.iter_mut().skip(if dwords == 16 { 16 } else { 28 }) {
  215. *w = 0x7fc0_dead;
  216. }
  217. self.words.extend(&padded[..dwords]);
  218. self.starts.len() - 1
  219. }
  220. /// The pointer of node `n` with `kind`, counted from the first node.
  221. fn pointer(&self, n: usize, kind: u32) -> u32 {
  222. (4 * self.starts[n] as u32) >> 3 | kind
  223. }
  224. /// What the instruction reads of node `n`.
  225. fn node(&self, n: usize) -> [u32; 28] {
  226. std::array::from_fn(|k| self.words.get(self.starts[n] + k).copied().unwrap_or(0))
  227. }
  228. }
  229. /// A small generator of repeatable numbers.
  230. struct Numbers(u64);
  231. impl Numbers {
  232. fn next(&mut self) -> u32 {
  233. self.0 = self
  234. .0
  235. .wrapping_mul(6364136223846793005)
  236. .wrapping_add(1442695040888963407);
  237. (self.0 >> 33) as u32
  238. }
  239. /// A float in -1..1 in steps of 1/4096 (exactly representable).
  240. fn unit(&mut self) -> f32 {
  241. (self.next() % 8193) as f32 / 4096.0 - 1.0
  242. }
  243. fn vector(&mut self, scale: f32) -> [f32; 3] {
  244. [
  245. self.unit() * scale,
  246. self.unit() * scale,
  247. self.unit() * scale,
  248. ]
  249. }
  250. }
  251. /// The scene and batches of cases over it.
  252. fn scene() -> (Scene, Vec<Vec<Case>>) {
  253. let mut s = Scene::new();
  254. let mut g = Numbers(0x5eed);
  255. const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
  256. let moved =
  257. |b: [f32; 6], by: [f32; 3]| -> [f32; 6] { std::array::from_fn(|k| b[k] + by[k % 3]) };
  258. let off = [f32::NAN; 6];
  259. let mut box_nodes = Vec::new();
  260. // The boxes of the reference's own tests, in both widths.
  261. let lined = [
  262. moved(UNIT, [30.0, 0.0, 0.0]),
  263. moved(UNIT, [10.0, 0.0, 0.0]),
  264. moved(UNIT, [10.0, 5.0, 0.0]),
  265. moved(UNIT, [20.0, 0.0, 0.0]),
  266. ];
  267. let ids = [0x105, 0x20c, 0x304, 0x400];
  268. box_nodes.push((s.add(nodes::box32(ids, lined), 32), 5));
  269. box_nodes.push((s.add(nodes::box16(ids, lined), 16), 4));
  270. // Boxes around the origin, one switched off, one child missing.
  271. let around = [
  272. UNIT,
  273. moved(UNIT, [0.5, 0.5, 0.5]),
  274. off,
  275. [-4.0, -0.25, -0.25, 4.0, 0.25, 0.25],
  276. ];
  277. let ids2 = [8, bvh::NONE, 24, 0x1fff_fffc];
  278. box_nodes.push((s.add(nodes::box32(ids2, around), 32), 5));
  279. box_nodes.push((s.add(nodes::box16(ids2, around), 16), 4));
  280. // Random boxes.
  281. for n in 0..6 {
  282. let boxes: [[f32; 6]; 4] = std::array::from_fn(|_| {
  283. let (c, h) = (g.vector(8.0), g.vector(2.0).map(f32::abs));
  284. std::array::from_fn(|k| c[k % 3] + if k < 3 { -h[k] } else { h[k - 3] })
  285. });
  286. let ids: [u32; 4] = std::array::from_fn(|k| 0x1000 * (n + 1) + 8 * k as u32 + 5);
  287. if n % 2 == 0 {
  288. box_nodes.push((s.add(nodes::box32(ids, boxes), 32), 5));
  289. } else {
  290. box_nodes.push((s.add(nodes::box16(ids, boxes), 16), 4));
  291. }
  292. }
  293. // Triangles: one of the reference's tests, a pair as the title's
  294. // builder stores it, all four triangles of a full node with turned
  295. // ids, random ones.
  296. let mut triangle_nodes = Vec::new();
  297. let front = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
  298. triangle_nodes.push((s.add(nodes::triangles(&front, 9), 16), 0));
  299. let pair = s.add(
  300. nodes::triangles(
  301. &[front[0], front[1], front[2], [2.0, 2.0, 5.0]],
  302. 9 | 0x80 | 6 << 8,
  303. ),
  304. 16,
  305. );
  306. triangle_nodes.extend([(pair, 0), (pair, 1)]);
  307. let five = [
  308. [-3.0, -1.0, 6.0],
  309. [-1.0, 2.0, 6.5],
  310. [1.0, -1.0, 6.0],
  311. [3.0, 2.0, 6.5],
  312. [5.0, -1.0, 7.0],
  313. ];
  314. // I and J per triangle: (1, 2), (2, 0), (0, 1), (1, 2).
  315. let full = s.add(nodes::triangles(&five, 9 | 2 << 8 | 4 << 16 | 9 << 24), 16);
  316. triangle_nodes.extend((0..4).map(|k| (full, k)));
  317. for _ in 0..5 {
  318. let c = g.vector(6.0);
  319. let v: [[f32; 3]; 3] = std::array::from_fn(|_| {
  320. let d = g.vector(3.0);
  321. [c[0] + d[0], c[1] + d[1], c[2] + d[2]]
  322. });
  323. triangle_nodes.push((s.add(nodes::triangles(&v, 9), 16), 0));
  324. }
  325. let mut cases: Vec<Case> = Vec::new();
  326. // Rays of the reference's tests against the lined-up boxes.
  327. for &(n, kind) in &box_nodes[..2] {
  328. for (origin, direction, extent) in [
  329. ([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
  330. ([0.0; 3], [1.0, 0.0, 0.0], 19.5),
  331. ([0.0; 3], [1.0, 0.0, 0.0], 19.0),
  332. ([0.0; 3], [-1.0, 0.0, 0.0], 1000.0),
  333. ([40.0, 0.0, 0.0], [-2.0, 0.0, 0.0], 1000.0),
  334. ([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
  335. ([0.0, 1.0, 0.0], [1.0, 0.0, 0.0], 1000.0),
  336. ([0.0, 0.5, 0.25], [1.0, -0.0, 0.0], 1000.0),
  337. ([0.0; 3], [0.0; 3], 1000.0),
  338. ] {
  339. cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
  340. }
  341. }
  342. // Random rays at every box node, half of them aimed at a box.
  343. for &(n, kind) in &box_nodes {
  344. let words = s.node(n);
  345. let boxes = if kind == 5 {
  346. bvh::boxes32(&words)
  347. } else {
  348. bvh::boxes16(&words)
  349. };
  350. for k in 0..12 {
  351. let origin = g.vector(12.0);
  352. let direction = if k % 2 == 0 {
  353. let b = boxes[(k / 2) % 4];
  354. if b[0].is_nan() {
  355. g.vector(1.0)
  356. } else {
  357. std::array::from_fn(|a| (b[a] + b[3 + a]) / 2.0 - origin[a] + g.unit() / 2.0)
  358. }
  359. } else {
  360. g.vector(1.0)
  361. };
  362. let extent = if k % 3 == 0 { 6.0 } else { 100.0 };
  363. cases.push(Some((n, kind, Ray::new(origin, direction, extent))));
  364. }
  365. }
  366. // Rays at every triangle: aimed inside, at an edge, at a vertex, past
  367. // it, from both sides, along each axis.
  368. for &(n, kind) in &triangle_nodes {
  369. let p = bvh::triangle_vertices(&s.node(n), kind);
  370. let at = |w: [f32; 3]| -> [f32; 3] {
  371. std::array::from_fn(|a| w[0] * p[0][a] + w[1] * p[1][a] + w[2] * p[2][a])
  372. };
  373. for (k, w) in [
  374. [0.5, 0.25, 0.25],
  375. [0.125, 0.75, 0.125],
  376. [0.5, 0.5, 0.0],
  377. [0.0, 0.5, 0.5],
  378. [1.0, 0.0, 0.0],
  379. [0.75, 0.75, -0.5],
  380. [-0.25, 0.5, 0.75],
  381. [0.25, 0.25, 0.5],
  382. ]
  383. .into_iter()
  384. .enumerate()
  385. {
  386. let target = at(w);
  387. let origin = if k % 2 == 0 { [0.0; 3] } else { g.vector(16.0) };
  388. let mut direction: [f32; 3] = std::array::from_fn(|a| target[a] - origin[a]);
  389. if k == 7 {
  390. // The triangle lies behind.
  391. direction = direction.map(|d| -d);
  392. }
  393. cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
  394. }
  395. for axis in 0..3 {
  396. for sign in [1.0f32, -1.0] {
  397. let target = at([0.25, 0.5, 0.25]);
  398. let mut origin = target;
  399. origin[axis] -= 8.0 * sign;
  400. let mut direction = [0.0; 3];
  401. direction[axis] = sign;
  402. cases.push(Some((n, kind, Ray::new(origin, direction, 100.0))));
  403. }
  404. }
  405. }
  406. // Kinds the instruction does not read, and threads masked out.
  407. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  408. cases.extend([
  409. Some((triangle_nodes[0].0, 6, ray)),
  410. Some((triangle_nodes[0].0, 7, ray)),
  411. None,
  412. Some((
  413. box_nodes[0].0,
  414. 5,
  415. Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0),
  416. )),
  417. None,
  418. ]);
  419. let batches = cases
  420. .chunks(THREADS as usize)
  421. .map(<[Case]>::to_vec)
  422. .collect();
  423. (s, batches)
  424. }
  425. /// The buffer for one batch: the threads' records, then the nodes. Node
  426. /// pointers count from `base` before the first node, in bytes.
  427. fn buffer(scene: &Scene, batch: &[Case], base: u64) -> Vec<u32> {
  428. let mut data = vec![0u32; (NODES / 4) as usize];
  429. for (t, case) in batch.iter().enumerate() {
  430. let Some((n, kind, ray)) = case else { continue };
  431. let r = &mut data[t * (RECORD / 4) as usize..][..13];
  432. let pointer = (base >> 3) + u64::from(scene.pointer(*n, *kind));
  433. (r[0], r[1]) = (pointer as u32, (pointer >> 32) as u32);
  434. r[2] = ray.extent.to_bits();
  435. for a in 0..3 {
  436. r[3 + a] = ray.origin[a].to_bits();
  437. r[6 + a] = ray.direction[a].to_bits();
  438. r[9 + a] = ray.inverse[a].to_bits();
  439. }
  440. r[12] = 1;
  441. }
  442. data.extend(&scene.words);
  443. data
  444. }
  445. fn expected(scene: &Scene, case: &Case, sort: bool) -> [u32; 4] {
  446. match case {
  447. Some((n, kind, ray)) => bvh::intersect(&scene.node(*n), *kind, ray, sort),
  448. None => BEFORE,
  449. }
  450. }
  451. /// Sets the tests' title memory for this thread until dropped.
  452. struct Memory;
  453. impl Memory {
  454. fn at(base: u64) -> Self {
  455. // Heap slot 0: the buffer of records and nodes.
  456. TEST_MEMORY.set(Some((0, base)));
  457. Self
  458. }
  459. }
  460. impl Drop for Memory {
  461. fn drop(&mut self) {
  462. TEST_MEMORY.set(None);
  463. }
  464. }
  465. /// Runs every batch on the hardware adapter and WARP and compares with
  466. /// the reference. `pointers` is what node pointers count from, in bytes
  467. /// before the first node.
  468. fn run(wide: bool, descriptor: Descriptor, pointers: u64, sort: bool) {
  469. let (shader, res) = build(wide, descriptor).expect("the program lowers");
  470. assert_eq!(res.bvh.len(), 1);
  471. let (scene, batches) = scene();
  472. // The reference must see a bit of everything, or the comparison
  473. // proves little.
  474. let all: Vec<&Case> = batches.iter().flatten().collect();
  475. let results: Vec<[u32; 4]> = all.iter().map(|c| expected(&scene, c, sort)).collect();
  476. let boxes = |hits: usize| {
  477. all.iter()
  478. .zip(&results)
  479. .filter(|(c, r)| {
  480. matches!(c, Some((_, 4 | 5, _)))
  481. && r.iter().filter(|&&x| x != bvh::NONE).count() == hits
  482. })
  483. .count()
  484. };
  485. let triangles = |hit: bool| {
  486. all.iter()
  487. .zip(&results)
  488. .filter(|(c, r)| {
  489. matches!(c, Some((_, 0..=3, _))) && (r[0] != f32::INFINITY.to_bits()) == hit
  490. })
  491. .count()
  492. };
  493. assert!(
  494. boxes(0) > 5 && boxes(1) > 5 && boxes(2) > 5 && boxes(3) > 0,
  495. "box cases"
  496. );
  497. assert!(
  498. triangles(true) > 30 && triangles(false) > 30,
  499. "triangle cases"
  500. );
  501. // Sorting must matter to some case, or the unsorted run proves nothing.
  502. assert!(
  503. all.iter()
  504. .any(|c| expected(&scene, c, true) != expected(&scene, c, false)),
  505. "no case tells sorted from unsorted"
  506. );
  507. let _one = super::valu_tests::ONE_AT_A_TIME
  508. .lock()
  509. .unwrap_or_else(|e| e.into_inner());
  510. let mut ran = 0;
  511. for (label, warp) in [("hardware", false), ("warp", true)] {
  512. let Ok(host) = Host::new(warp) else {
  513. eprintln!("no SM 6.6 {label} device; skipped");
  514. continue;
  515. };
  516. let (root, pso) = host
  517. .compute_pipeline(&shader)
  518. .unwrap_or_else(|e| panic!("{label}: compute_pipeline failed: {e}"));
  519. for (b, batch) in batches.iter().enumerate() {
  520. let data = buffer(&scene, batch, pointers);
  521. let out = host
  522. .dispatch(
  523. &root,
  524. &pso,
  525. &Dispatch {
  526. roots: vec![(0, Root::Constants(vec![0; 5]))],
  527. views: &[
  528. View::Buffer {
  529. data: &data,
  530. stride: Stride::Raw,
  531. },
  532. View::RawUav(4 * THREADS),
  533. ],
  534. samplers: &[],
  535. groups: [1, 1, 1],
  536. },
  537. )
  538. .unwrap_or_else(|e| panic!("{label}: dispatch failed: {e}"));
  539. for t in 0..THREADS as usize {
  540. let case = batch.get(t).copied().flatten();
  541. let want = match batch.get(t) {
  542. Some(c) => expected(&scene, c, sort),
  543. // A thread past the batch: its record is zeros, so it
  544. // is masked out.
  545. None => BEFORE,
  546. };
  547. let got = &out[0][4 * t..4 * t + 4];
  548. assert_eq!(
  549. got,
  550. want,
  551. "{label}, batch {b} thread {t}: {case:x?}\n got {:x?} = {:?}\nwant {:x?} = {:?}",
  552. got,
  553. got.iter().map(|&x| f32::from_bits(x)).collect::<Vec<_>>(),
  554. want,
  555. want.map(f32::from_bits),
  556. );
  557. }
  558. }
  559. ran += 1;
  560. }
  561. assert!(ran > 0, "no SM 6.6 device available");
  562. }
  563. #[test]
  564. fn the_64_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
  565. // Pointers count from the buffer's start.
  566. run(true, Descriptor::Table, u64::from(NODES), true);
  567. assert_eq!(
  568. build(true, Descriptor::Table).unwrap().1.bvh[0].1,
  569. BvhNodes::Resource
  570. );
  571. }
  572. #[test]
  573. fn the_32_bit_node_test_in_a_host_buffer_matches_the_reference_on_the_card() {
  574. run(false, Descriptor::Table, u64::from(NODES), true);
  575. }
  576. /// Where the tests' title memory puts the buffer: past 4 GiB, on 256 bytes.
  577. const BASE: u64 = 0x12_3456_7800;
  578. #[test]
  579. fn the_64_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
  580. // The title's way: one descriptor for all of memory, the structure's
  581. // address folded into a 64-bit pointer.
  582. let _memory = Memory::at(BASE);
  583. run(true, WHOLE, BASE + u64::from(NODES), true);
  584. }
  585. #[test]
  586. fn the_32_bit_node_test_over_title_memory_matches_the_reference_on_the_card() {
  587. // The title's other way: the structure's address in the descriptor
  588. // (in 256-byte units, 40 bits), a 32-bit pointer from there. Here with
  589. // an address past 2^40 bytes, and without box sorting.
  590. let base = 0x312_3456_7800u64;
  591. let structure = base + u64::from(NODES);
  592. let _memory = Memory::at(base);
  593. let descriptor = Descriptor::Numbers((structure >> 8) as u32, (structure >> 40) as u32);
  594. run(false, descriptor, 0, false);
  595. // And sorted.
  596. let descriptor = Descriptor::Numbers(
  597. (structure >> 8) as u32,
  598. (structure >> 40) as u32 | bvh::BOX_SORT,
  599. );
  600. run(false, descriptor, 0, true);
  601. }
  602. #[test]
  603. fn a_descriptor_of_numbers_is_title_memory_read_through_the_directory() {
  604. for wide in [true, false] {
  605. let native = native(&program(wide, WHOLE));
  606. let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
  607. let st = structure::structure(&p).expect("structure");
  608. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
  609. // The flags the title sets: sorted boxes, barycentrics, a
  610. // ray-tracing structure. No resource is taken for it: the buffer
  611. // loads' and the store's descriptors are all there is.
  612. assert_eq!(res.bvh.len(), 1);
  613. assert_eq!(
  614. res.bvh[0].1,
  615. BvhNodes::Memory {
  616. word1: 0x8000_0000,
  617. word3: 0x8900_03ff
  618. }
  619. );
  620. assert_eq!(res.descriptors.len(), 5);
  621. // Without the tests' stand-in the nodes are read as the title's
  622. // programs will read them: through the host's directory of title
  623. // memory. The program lowers and validates, and asks the host for
  624. // the directory and for the list of pages it found no copy of.
  625. let (shader, _) = build(wide, WHOLE).expect("lowers through the directory");
  626. assert!(shader.root_srvs.contains(&super::SLOT_MEMORY));
  627. assert!(shader.root_uavs.contains(&super::SLOT_FAULTS));
  628. }
  629. }
  630. #[test]
  631. fn a_structure_that_returns_triangle_ids_is_refused_by_name() {
  632. // Triangle return mode 0 (bit 24 of dword 3 clear): the last two
  633. // result dwords would be a triangle id and a hit status.
  634. let mut words = program(true, WHOLE);
  635. let flags = words.iter().position(|&w| w == 0x8900_03FF).unwrap();
  636. words[flags] = 0x8800_03FF;
  637. let native = native(&words);
  638. let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
  639. let st = structure::structure(&p).expect("structure");
  640. let res = resource::track(&p, &native.layout, native.stage, Some(&st)).expect("tracked");
  641. let io = io::raise(&p, &native).expect("io::raise");
  642. let r = lower::lower(&lower::Parts {
  643. native: &native,
  644. p: &p,
  645. st: &st,
  646. io: &io,
  647. res: &res,
  648. inputs: Vec::new(),
  649. outputs: Vec::new(),
  650. prims: Vec::new(),
  651. mesh_stride: 0,
  652. });
  653. match r {
  654. Err(ShaderError::Unsupported { what, .. }) => {
  655. assert_eq!(what, "a ray-tracing structure that returns triangle ids");
  656. }
  657. other => panic!("{:?}", other.map(|_| ())),
  658. }
  659. }