intersect.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. //! The console's ray-tracing node test, `image_bvh_intersect_ray` and
  2. //! `image_bvh64_intersect_ray`, as inline DXIL: the host has no instruction
  3. //! that tests one ray against one node of the title's own structures.
  4. //!
  5. //! [`crate::bvh`] says what the instruction computes and is the reference:
  6. //! the code made here does the same float operations in the same order
  7. //! (DXIL float operations carry no fast-math flags, so the host may not
  8. //! reorder or fuse them), and the tests in `intersect_tests.rs` run it on
  9. //! the card against the reference.
  10. //!
  11. //! The title's nodes are in title memory, named by address: they are read
  12. //! through the host's copies of title memory ([`Lower::memory`]), one look
  13. //! in its directory per node (two for a 128-byte box node).
  14. //!
  15. //! Shape of the code, under the instruction's lane guard:
  16. //!
  17. //! ```text
  18. //! kind = pointer & 7
  19. //! box (4, 5): 4 child pointers; 24 box floats (kind 5) or 24 halves widened (kind 4);
  20. //! four slab tests; the sorting network
  21. //! triangle (0-3): the id dword, three vertices at the bytes it names; the watertight test
  22. //! other (6, 7): a triangle miss
  23. //! ```
  24. //!
  25. //! Each lane reads only the dwords its node's kind needs: 28 for a 32-bit
  26. //! box node, 16 for a 16-bit one, 10 for a triangle.
  27. use super::{Attr, Bin, Fields, Inst, Lower, Operand, Reg, Term, V, Why, flags, pred};
  28. use crate::bvh;
  29. use crate::resource::BvhNodes;
  30. #[cfg(test)]
  31. thread_local! {
  32. /// The tests' stand-in for title memory ([`Lower::bvh_memory`]): a
  33. /// heap slot holding a raw buffer, and the title address of its first
  34. /// byte. (The card tests have no host to keep copies of title memory
  35. /// and their directory.)
  36. pub(in crate::emit) static TEST_MEMORY: std::cell::Cell<Option<(u32, u64)>> =
  37. const { std::cell::Cell::new(None) };
  38. }
  39. /// Where the instruction's node is.
  40. #[derive(Clone, Copy)]
  41. enum NodeAt {
  42. /// At this byte of a raw buffer of the host.
  43. Buffer { handle: V, byte: V },
  44. /// In title memory: the raw view of the host copy holding the node's
  45. /// first 64 bytes and the node's byte in it ([`Lower::bvh_memory`]),
  46. /// and the node's address, for the second half of a 128-byte node.
  47. Memory { handle: V, byte: V, low: V, high: V },
  48. }
  49. /// The ray operands, as floats.
  50. struct Ray {
  51. extent: V,
  52. origin: [V; 3],
  53. direction: [V; 3],
  54. inverse: [V; 3],
  55. }
  56. impl<'a> Lower<'a> {
  57. /// `image_bvh_intersect_ray` and `image_bvh64_intersect_ray`.
  58. pub(super) fn bvh(&mut self, inst: &Inst, b: usize, i: usize) -> Result<(), Why> {
  59. let Fields::Image {
  60. data,
  61. addr,
  62. rsrc,
  63. dmask,
  64. a16,
  65. d16,
  66. tfe,
  67. lwe,
  68. ..
  69. } = &inst.fields
  70. else {
  71. unreachable!()
  72. };
  73. if *a16 || *d16 || *tfe || *lwe || *dmask != 0xf {
  74. return Err("a ray-tracing node test with 16-bit operands or a partial result");
  75. }
  76. let wide = inst.name() == "image_bvh64_intersect_ray";
  77. // Operand VGPRs in order: the node pointer (two dwords in the
  78. // 64-bit form), the ray's extent, origin, direction and inverse
  79. // direction.
  80. let mut regs = Vec::new();
  81. for a in addr {
  82. if let Operand::Vector { reg, dwords } = *a {
  83. regs.extend((0..dwords).map(|k| reg + k));
  84. }
  85. }
  86. if regs.len() != if wide { 12 } else { 11 } {
  87. return Err("a ray-tracing node test's operands");
  88. }
  89. let Operand::Vector { reg: dst, .. } = *data else {
  90. return Err("a ray-tracing node test's result");
  91. };
  92. let site = (b, i);
  93. let nodes = self
  94. .x
  95. .res
  96. .bvh
  97. .iter()
  98. .find(|n| n.0 == site)
  99. .map(|n| n.1)
  100. .ok_or("an untracked ray-tracing structure")?;
  101. let (sort, barycentrics) = match nodes {
  102. BvhNodes::Resource => (true, true),
  103. BvhNodes::Memory { word1, word3 } => (
  104. word1 & bvh::BOX_SORT != 0,
  105. word3 & bvh::RETURN_BARYCENTRICS != 0,
  106. ),
  107. };
  108. if !barycentrics {
  109. // Mode 0 returns a triangle id and a hit status in the last two
  110. // dwords; no program of the title asks for it.
  111. return Err("a ray-tracing structure that returns triangle ids");
  112. }
  113. let guard = self.guard(b, i)?;
  114. let mut x = Vec::with_capacity(regs.len());
  115. for &r in &regs {
  116. let v = inst.read(Reg::V(r)).ok_or("an unread operand")?;
  117. x.push(self.i32_of(v)?);
  118. }
  119. let pointer = x[0];
  120. let pointer_high = wide.then(|| x[1]);
  121. let f: Vec<V> = x[1 + usize::from(wide)..]
  122. .iter()
  123. .map(|&v| self.as_float(v))
  124. .collect();
  125. let ray = Ray {
  126. extent: f[0],
  127. origin: [f[1], f[2], f[3]],
  128. direction: [f[4], f[5], f[6]],
  129. inverse: [f[7], f[8], f[9]],
  130. };
  131. let c = self.cur;
  132. let at = match nodes {
  133. BvhNodes::Resource => {
  134. let src = self
  135. .descriptors
  136. .get(&(site, false))
  137. .copied()
  138. .ok_or("an untracked ray-tracing structure")?;
  139. let handle = self.handle(site, src, false, (11, 0))?;
  140. // (pointer >> 3) << 6 from the buffer's start.
  141. let (kind_bits, k3) = (self.s.m.i32(!7), self.s.m.i32(3));
  142. let byte = self.s.m.bin(c, Bin::And, pointer, kind_bits);
  143. let byte = self.s.m.bin(c, Bin::Shl, byte, k3);
  144. NodeAt::Buffer { handle, byte }
  145. }
  146. BvhNodes::Memory { .. } => {
  147. let Operand::Scalar { code, .. } = *rsrc else {
  148. return Err("a ray-tracing structure descriptor not in SGPRs");
  149. };
  150. let mut words = [pointer; 2];
  151. for (k, w) in words.iter_mut().enumerate() {
  152. let v = inst
  153. .read(Reg::S(code + k as u8))
  154. .ok_or("an unread operand")?;
  155. *w = self.i32_of(v)?;
  156. }
  157. let (low, high) = self.bvh_address(words[0], words[1], pointer, pointer_high);
  158. // One look for the node's copy, before the branches: a
  159. // node is 64 bytes on 64, so its first half lies in one
  160. // 64 KiB page whatever its kind.
  161. let (handle, byte) = self.bvh_memory(low, high, guard);
  162. NodeAt::Memory {
  163. handle,
  164. byte,
  165. low,
  166. high,
  167. }
  168. }
  169. };
  170. let zero = self.s.m.i32(0);
  171. let gate = self.begin_guarded(guard);
  172. let head = self.cur;
  173. let (k4, k6, k7) = (self.s.m.i32(4), self.s.m.i32(6), self.s.m.i32(7));
  174. let kind = self.s.m.bin(head, Bin::And, pointer, k7);
  175. let pair = self.s.m.bin(head, Bin::And, pointer, k6);
  176. let is_box = self.s.m.cmp(head, pred::EQ, pair, k4);
  177. let is_triangle = self.s.m.cmp(head, pred::IULT, kind, k4);
  178. let (box_block, leaf_block) = (self.s.m.new_block(), self.s.m.new_block());
  179. let (triangle_block, join) = (self.s.m.new_block(), self.s.m.new_block());
  180. self.s
  181. .m
  182. .terminate(head, Term::CondBr(is_box, box_block, leaf_block));
  183. self.s
  184. .m
  185. .terminate(leaf_block, Term::CondBr(is_triangle, triangle_block, join));
  186. self.cur = box_block;
  187. let boxes = self.bvh_boxes(at, kind, &ray, sort);
  188. let box_end = self.cur;
  189. self.s.m.terminate(box_end, Term::Br(join));
  190. self.cur = triangle_block;
  191. let triangle = self.bvh_triangle(at, kind, &ray);
  192. let triangle_end = self.cur;
  193. self.s.m.terminate(triangle_end, Term::Br(join));
  194. self.cur = join;
  195. // Kinds 6 and 7 (an instance, a procedural primitive): not known
  196. // what the console returns; the title's programs do not read it.
  197. let other = bvh::MISS.map(|f| self.s.m.i32(f.to_bits()));
  198. let i32t = self.s.t.i32;
  199. let mut results = Vec::with_capacity(4);
  200. for k in 0..4 {
  201. let phi = self.s.m.phi(join, i32t);
  202. self.s.m.set_phi(
  203. phi,
  204. vec![
  205. (boxes[k], box_end),
  206. (triangle[k], triangle_end),
  207. (other[k], leaf_block),
  208. ],
  209. );
  210. results.push((phi, zero));
  211. }
  212. let results = self.end_guarded(gate, &results);
  213. for (k, &r) in results.iter().enumerate() {
  214. self.write(inst, Reg::V(dst + k as u8), r, guard);
  215. }
  216. Ok(())
  217. }
  218. /// Title memory at `low`/`high` for a node's bytes: the raw view of the
  219. /// host copy holding the address and the byte in that view
  220. /// ([`Lower::memory`]: a page the host has no copy of reads zeros and
  221. /// is left for the host to fetch, for lanes that run).
  222. fn bvh_memory(&mut self, low: V, high: V, guard: Option<V>) -> (V, V) {
  223. #[cfg(test)]
  224. if let Some((slot, base)) = TEST_MEMORY.get() {
  225. // The buffer at heap slot `slot` holds the bytes from title
  226. // address `base` on; any other address reads past its end,
  227. // which is zeros.
  228. let c = self.cur;
  229. let slot = self.s.m.i32(slot);
  230. let handle = self.s.heap_handle(c, slot, false, false, (11, 0));
  231. let (base_low, base_high) =
  232. (self.s.m.i32(base as u32), self.s.m.i32((base >> 32) as u32));
  233. let at = self.s.m.bin(c, Bin::Sub, low, base_low);
  234. let in_low = self.s.m.cmp(c, pred::IUGE, low, base_low);
  235. let in_high = self.s.m.cmp(c, pred::EQ, high, base_high);
  236. let inside = self.s.m.bin(c, Bin::And, in_low, in_high);
  237. let outside = self.s.m.i32(0xffff_ff00);
  238. let at = self.s.m.select(c, inside, at, outside);
  239. return (handle, at);
  240. }
  241. self.memory(low, high, guard)
  242. }
  243. /// `count` dwords of the node from its byte `base` + `offset` (`base`
  244. /// computed, `offset` fixed; none of the node's bytes past 127), read
  245. /// four at a time.
  246. fn bvh_node_words(&mut self, at: NodeAt, base: Option<V>, offset: u32, count: u32) -> Vec<V> {
  247. let (undef, align) = (self.s.m.undef(self.s.t.i32), self.s.m.i32(4));
  248. // The second half of a 128-byte node may lie in the next 64 KiB
  249. // page, which may be in another copy: its own look, made once.
  250. let mut second = None;
  251. let mut out = Vec::with_capacity(count as usize);
  252. for start in (0..count).step_by(4) {
  253. let n = (count - start).min(4);
  254. let node_byte = offset + 4 * start;
  255. let (handle, mut byte) = match at {
  256. NodeAt::Buffer { handle, byte } => (handle, byte),
  257. NodeAt::Memory { handle, byte, .. } if node_byte < 64 => (handle, byte),
  258. NodeAt::Memory { low, high, .. } => *second.get_or_insert_with(|| {
  259. let (low, high) = self.address_plus(low, high, 64);
  260. // Every lane in this block runs the instruction.
  261. let (handle, byte) = self.bvh_memory(low, high, None);
  262. let (k64, c) = (self.s.m.i32(64), self.cur);
  263. (handle, self.s.m.bin(c, Bin::Sub, byte, k64))
  264. }),
  265. };
  266. let c = self.cur;
  267. if let Some(b) = base {
  268. byte = self.s.m.bin(c, Bin::Add, byte, b);
  269. }
  270. let k = self.s.m.i32(node_byte);
  271. let byte = self.s.m.bin(c, Bin::Add, byte, k);
  272. let mask = self.s.m.i8((1u8 << n) - 1);
  273. let r = self.s.op(
  274. c,
  275. "rawBufferLoad.f32",
  276. Attr::ReadOnly,
  277. self.s.t.res_ret,
  278. 139,
  279. &[handle, byte, undef, mask, align],
  280. );
  281. for k in 0..n {
  282. let f = self.s.m.extract(c, r, k);
  283. out.push(self.as_int(f));
  284. }
  285. }
  286. out
  287. }
  288. /// The node's title address, [`bvh::node_address`]: the descriptor's
  289. /// base (dword 0 and the low byte of dword 1, in 256-byte units) plus
  290. /// `(pointer >> 3) << 6`.
  291. fn bvh_address(&mut self, word0: V, word1: V, pointer: V, pointer_high: Option<V>) -> (V, V) {
  292. let c = self.cur;
  293. let i64t = self.s.m.int(64);
  294. let (zero, byte) = (self.s.m.i32(0), self.s.m.i32(0xff));
  295. let base_high = self.s.m.bin(c, Bin::And, word1, byte);
  296. let base = self.join64(word0, base_high);
  297. let k8 = self.s.m.int_const(i64t, 8);
  298. let base = self.s.m.bin(c, Bin::Shl, base, k8);
  299. let p = self.join64(pointer, pointer_high.unwrap_or(zero));
  300. let (k3, k6) = (self.s.m.int_const(i64t, 3), self.s.m.int_const(i64t, 6));
  301. let p = self.s.m.bin(c, Bin::LShr, p, k3);
  302. let p = self.s.m.bin(c, Bin::Shl, p, k6);
  303. let a = self.s.m.bin(c, Bin::Add, base, p);
  304. self.s.flags |= flags::INT64;
  305. self.split64(a)
  306. }
  307. /// The box test ([`bvh::boxes`]): four result dwords. Starts in the
  308. /// current block and leaves `self.cur` at the block it ends in.
  309. fn bvh_boxes(&mut self, at: NodeAt, kind: V, ray: &Ray, sort: bool) -> [V; 4] {
  310. let head = self.cur;
  311. let children = self.bvh_node_words(at, None, 0, 4);
  312. let k5 = self.s.m.i32(5);
  313. let wide = self.s.m.cmp(head, pred::EQ, kind, k5);
  314. let (wide_block, half_block) = (self.s.m.new_block(), self.s.m.new_block());
  315. let join = self.s.m.new_block();
  316. self.s
  317. .m
  318. .terminate(head, Term::CondBr(wide, wide_block, half_block));
  319. // 32-bit floats: 24 dwords from byte 16.
  320. self.cur = wide_block;
  321. let k16 = self.s.m.i32(16);
  322. let words = self.bvh_node_words(at, None, 16, 24);
  323. let floats: Vec<V> = words.iter().map(|&w| self.as_float(w)).collect();
  324. // (The look for the second half goes on in another block.)
  325. let wide_block = self.cur;
  326. self.s.m.terminate(wide_block, Term::Br(join));
  327. // 16-bit floats: 24 halves in 12 dwords from byte 16, the low half
  328. // of a dword first.
  329. self.cur = half_block;
  330. let words = self.bvh_node_words(at, None, 16, 12);
  331. let f32t = self.s.t.f32;
  332. let mut halves = Vec::with_capacity(24);
  333. for n in 0..24 {
  334. let mut h = words[n / 2];
  335. if n % 2 == 1 {
  336. h = self.s.m.bin(half_block, Bin::LShr, h, k16);
  337. }
  338. // The conversion reads the low 16 bits.
  339. halves.push(self.s.op(
  340. half_block,
  341. "legacyF16ToF32",
  342. Attr::ReadNone,
  343. f32t,
  344. 131,
  345. &[h],
  346. ));
  347. }
  348. self.s.m.terminate(half_block, Term::Br(join));
  349. self.cur = join;
  350. let mut coords = Vec::with_capacity(24);
  351. for n in 0..24 {
  352. let phi = self.s.m.phi(join, f32t);
  353. self.s
  354. .m
  355. .set_phi(phi, vec![(floats[n], wide_block), (halves[n], half_block)]);
  356. coords.push(phi);
  357. }
  358. // The inverse direction held finite ([`bvh::boxes`]).
  359. let (most, least) = (
  360. self.s.m.f32(f32::MAX.to_bits()),
  361. self.s.m.f32((-f32::MAX).to_bits()),
  362. );
  363. let inverse = ray.inverse.map(|x| {
  364. let x = self.binary(35, x, least);
  365. self.binary(36, x, most)
  366. });
  367. let c = join;
  368. let (none, infinity, fzero) = (
  369. self.s.m.i32(bvh::NONE),
  370. self.s.m.f32(f32::INFINITY.to_bits()),
  371. self.s.m.f32(0),
  372. );
  373. let mut ids = [none; 4];
  374. let mut distances = [infinity; 4];
  375. for n in 0..4 {
  376. let bx = &coords[6 * n..6 * n + 6];
  377. let (mut near, mut far) = ([fzero; 3], [fzero; 3]);
  378. for a in 0..3 {
  379. let low = self.s.m.bin(c, Bin::Sub, bx[a], ray.origin[a]);
  380. let low = self.s.m.bin(c, Bin::Mul, low, inverse[a]);
  381. let high = self.s.m.bin(c, Bin::Sub, bx[3 + a], ray.origin[a]);
  382. let high = self.s.m.bin(c, Bin::Mul, high, inverse[a]);
  383. near[a] = self.binary(36, low, high);
  384. far[a] = self.binary(35, low, high);
  385. }
  386. let enter = self.binary(35, near[0], near[1]);
  387. let enter = self.binary(35, enter, near[2]);
  388. let leave = self.binary(36, far[0], far[1]);
  389. let leave = self.binary(36, leave, far[2]);
  390. let from = self.binary(35, enter, fzero);
  391. // Ordered compares: a NaN anywhere is a miss.
  392. let through = self.s.m.cmp(c, pred::OGE, leave, from);
  393. let before = self.s.m.cmp(c, pred::OLT, enter, ray.extent);
  394. let off = self.is_nan_f32(bx[0]);
  395. let on = self.s.m.bool(true);
  396. let on = self.s.m.bin(c, Bin::Xor, off, on);
  397. let hit = self.s.m.bin(c, Bin::And, through, before);
  398. let hit = self.s.m.bin(c, Bin::And, hit, on);
  399. ids[n] = self.s.m.select(c, hit, children[n], none);
  400. distances[n] = self.s.m.select(c, hit, enter, infinity);
  401. }
  402. if sort {
  403. for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
  404. let swap = self.s.m.cmp(c, pred::OLT, distances[b], distances[a]);
  405. let (da, db) = (distances[a], distances[b]);
  406. distances[a] = self.s.m.select(c, swap, db, da);
  407. distances[b] = self.s.m.select(c, swap, da, db);
  408. let (ia, ib) = (ids[a], ids[b]);
  409. ids[a] = self.s.m.select(c, swap, ib, ia);
  410. ids[b] = self.s.m.select(c, swap, ia, ib);
  411. }
  412. }
  413. ids
  414. }
  415. /// The triangle test ([`bvh::triangle`] of [`bvh::triangle_vertices`]):
  416. /// four result dwords, made in the current block.
  417. fn bvh_triangle(&mut self, at: NodeAt, kind: V, ray: &Ray) -> [V; 4] {
  418. let c = self.cur;
  419. let k = |l: &mut Self, v: u32| l.s.m.i32(v);
  420. // The triangle's byte of the dword at byte 60: which of its
  421. // vertices barycentric I and J weigh.
  422. let id = self.bvh_node_words(at, None, 60, 1)[0];
  423. let (k2, k3, k12, k15) = (k(self, 2), k(self, 3), k(self, 12), k(self, 15));
  424. let shift = self.s.m.bin(c, Bin::Shl, kind, k3);
  425. let id = self.s.m.bin(c, Bin::LShr, id, shift);
  426. let i = self.s.m.bin(c, Bin::And, id, k3);
  427. let j = self.s.m.bin(c, Bin::LShr, id, k2);
  428. let j = self.s.m.bin(c, Bin::And, j, k3);
  429. let first = self.s.m.bin(c, Bin::Sub, k3, i);
  430. let first = self.s.m.bin(c, Bin::Sub, first, j);
  431. let first = self.s.m.bin(c, Bin::And, first, k3);
  432. // The node's vertices the triangle is made of, four bits each.
  433. let (k0, k1) = (k(self, 0), k(self, 1));
  434. let maps: [V; 4] = std::array::from_fn(|n| k(self, bvh::vertex_map(n as u32)));
  435. let (is0, is1, is2) = (
  436. self.s.m.cmp(c, pred::EQ, kind, k0),
  437. self.s.m.cmp(c, pred::EQ, kind, k1),
  438. self.s.m.cmp(c, pred::EQ, kind, k2),
  439. );
  440. let map = self.s.m.select(c, is2, maps[2], maps[3]);
  441. let map = self.s.m.select(c, is1, maps[1], map);
  442. let map = self.s.m.select(c, is0, maps[0], map);
  443. let mut p = Vec::with_capacity(3);
  444. for n in [first, i, j] {
  445. let nibble = self.s.m.bin(c, Bin::Shl, n, k2);
  446. let vertex = self.s.m.bin(c, Bin::LShr, map, nibble);
  447. let vertex = self.s.m.bin(c, Bin::And, vertex, k15);
  448. let byte = self.s.m.bin(c, Bin::Mul, vertex, k12);
  449. let words = self.bvh_node_words(at, Some(byte), 0, 3);
  450. // Relative to the ray's origin.
  451. let r: Vec<V> = (0..3)
  452. .map(|a| {
  453. let f = self.as_float(words[a]);
  454. self.s.m.bin(c, Bin::Sub, f, ray.origin[a])
  455. })
  456. .collect();
  457. p.push([r[0], r[1], r[2]]);
  458. }
  459. // The ray's largest axis z, and x and y after it in an order that
  460. // keeps the winding.
  461. let fzero = self.s.m.f32(0);
  462. let size = ray.direction.map(|d| self.unary(6, d));
  463. let xy = self.s.m.cmp(c, pred::OGE, size[0], size[1]);
  464. let xz = self.s.m.cmp(c, pred::OGE, size[0], size[2]);
  465. let yz = self.s.m.cmp(c, pred::OGE, size[1], size[2]);
  466. let z0 = self.s.m.bin(c, Bin::And, xy, xz);
  467. let on = self.s.m.bool(true);
  468. let not_xy = self.s.m.bin(c, Bin::Xor, xy, on);
  469. let z1 = self.s.m.bin(c, Bin::And, not_xy, yz);
  470. // Component (kz + n) % 3 of `q`.
  471. let pick = |l: &mut Self, q: [V; 3], n: usize| {
  472. let rest = l.s.m.select(c, z1, q[(1 + n) % 3], q[(2 + n) % 3]);
  473. l.s.m.select(c, z0, q[n % 3], rest)
  474. };
  475. let dz = pick(self, ray.direction, 0);
  476. let backwards = self.s.m.cmp(c, pred::OLT, dz, fzero);
  477. // (x, y, z) of `q`: the two after the largest axis, swapped for a
  478. // ray that runs backwards along it.
  479. let axes = |l: &mut Self, q: [V; 3]| {
  480. let (x, y) = (pick(l, q, 1), pick(l, q, 2));
  481. [
  482. l.s.m.select(c, backwards, y, x),
  483. l.s.m.select(c, backwards, x, y),
  484. pick(l, q, 0),
  485. ]
  486. };
  487. let d = axes(self, ray.direction);
  488. let sz = pick(self, ray.inverse, 0);
  489. let sx = self.s.m.bin(c, Bin::Mul, d[0], sz);
  490. let sy = self.s.m.bin(c, Bin::Mul, d[1], sz);
  491. let mut sheared = Vec::with_capacity(3);
  492. for r in p {
  493. let r = axes(self, r);
  494. let x = self.s.m.bin(c, Bin::Mul, sx, r[2]);
  495. let x = self.s.m.bin(c, Bin::Sub, r[0], x);
  496. let y = self.s.m.bin(c, Bin::Mul, sy, r[2]);
  497. let y = self.s.m.bin(c, Bin::Sub, r[1], y);
  498. let z = self.s.m.bin(c, Bin::Mul, sz, r[2]);
  499. sheared.push((x, y, z));
  500. }
  501. let [(ax, ay, az), (bx, by, bz), (cx, cy, cz)] = sheared[..] else {
  502. unreachable!()
  503. };
  504. // p * q - r * s.
  505. let cross = |l: &mut Self, p: V, q: V, r: V, s: V| {
  506. let a = l.s.m.bin(c, Bin::Mul, p, q);
  507. let b = l.s.m.bin(c, Bin::Mul, r, s);
  508. l.s.m.bin(c, Bin::Sub, a, b)
  509. };
  510. let u = cross(self, cx, by, cy, bx);
  511. let v = cross(self, ax, cy, ay, cx);
  512. let w = cross(self, bx, ay, by, ax);
  513. let any = |l: &mut Self, p: u8| {
  514. let a = l.s.m.cmp(c, p, u, fzero);
  515. let b = l.s.m.cmp(c, p, v, fzero);
  516. let d = l.s.m.cmp(c, p, w, fzero);
  517. let a = l.s.m.bin(c, Bin::Or, a, b);
  518. l.s.m.bin(c, Bin::Or, a, d)
  519. };
  520. let behind = any(self, pred::OLT);
  521. let before = any(self, pred::OGT);
  522. let outside = self.s.m.bin(c, Bin::And, behind, before);
  523. let inside = self.s.m.bin(c, Bin::Xor, outside, on);
  524. let det = self.s.m.bin(c, Bin::Add, v, w);
  525. let det = self.s.m.bin(c, Bin::Add, u, det);
  526. let t = self.s.m.bin(c, Bin::Mul, u, az);
  527. let t2 = self.s.m.bin(c, Bin::Mul, v, bz);
  528. let t = self.s.m.bin(c, Bin::Add, t, t2);
  529. let t2 = self.s.m.bin(c, Bin::Mul, w, cz);
  530. let t = self.s.m.bin(c, Bin::Add, t, t2);
  531. // The distance is not negative: the numerator has the
  532. // denominator's sign (or is 0). Ordered compares: a denominator
  533. // of 0 or a NaN is a miss.
  534. let front = self.s.m.cmp(c, pred::OGT, det, fzero);
  535. let front_ahead = self.s.m.cmp(c, pred::OGE, t, fzero);
  536. let front = self.s.m.bin(c, Bin::And, front, front_ahead);
  537. let back = self.s.m.cmp(c, pred::OLT, det, fzero);
  538. let back_ahead = self.s.m.cmp(c, pred::OLE, t, fzero);
  539. let back = self.s.m.bin(c, Bin::And, back, back_ahead);
  540. let ahead = self.s.m.bin(c, Bin::Or, front, back);
  541. let hit = self.s.m.bin(c, Bin::And, inside, ahead);
  542. let miss = bvh::MISS.map(|f| self.s.m.f32(f.to_bits()));
  543. let out = [t, det, v, w];
  544. std::array::from_fn(|n| {
  545. let f = self.s.m.select(c, hit, out[n], miss[n]);
  546. self.as_int(f)
  547. })
  548. }
  549. }