bvh.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. //! The console GPU's ray-tracing node test, `image_bvh_intersect_ray` and
  2. //! `image_bvh64_intersect_ray`, on the CPU: the node formats, and what the
  3. //! instruction returns for one ray and one node. The emitter lowers the
  4. //! instruction to the same arithmetic in the same order
  5. //! (`emit/intersect.rs`), so its code can be compared against this dword
  6. //! for dword.
  7. //!
  8. //! The instruction tests one ray against one 64-byte node of a bounding
  9. //! volume hierarchy and returns four dwords. Traversal (the stack, instance
  10. //! transforms, culling, the hit distance `numerator / denominator`) is the
  11. //! program's own code.
  12. //!
  13. //! # Node pointers
  14. //!
  15. //! A node pointer's low three bits are the node's kind, the rest its byte
  16. //! offset in 8-byte units: the node is at `(pointer >> 3) << 6` past the
  17. //! base address of the descriptor (40 bits in dword 0 and the low byte of
  18. //! dword 1, in 256-byte units). The 32-bit form takes a 32-bit pointer;
  19. //! the 64-bit form a 64-bit one, with which a program uses one descriptor
  20. //! with base 0 for every structure and adds `address >> 3` itself.
  21. //!
  22. //! | kind | node |
  23. //! |---|---|
  24. //! | 0-3 | triangle 0-3 of a triangle node |
  25. //! | 4 | box node, 16-bit floats (64 bytes) |
  26. //! | 5 | box node, 32-bit floats (128 bytes) |
  27. //! | 6 | instance: not read by the instruction |
  28. //! | 7 | procedural primitive: not read by the instruction |
  29. //!
  30. //! # Box nodes
  31. //!
  32. //! Four child pointers at bytes 0-15 (`0xffff_ffff`: none), then four
  33. //! boxes, each minimum x y z, maximum x y z: 16-bit floats from byte 16
  34. //! (12 bytes a box), or 32-bit floats from byte 16 (24 bytes a box; bytes
  35. //! 112-127 are not read). The result is the pointers of the children whose
  36. //! box the ray enters before its extent, nearest entry first when the
  37. //! descriptor enables box sorting (bit 63), and `0xffff_ffff` for the rest.
  38. //!
  39. //! # Triangle nodes
  40. //!
  41. //! Five vertices of three 32-bit floats at bytes 0-59 and a dword at byte
  42. //! 60 with one byte per triangle: bits 1:0 name the triangle's vertex that
  43. //! barycentric I weighs, bits 3:2 the one J weighs (the builder stores an
  44. //! input triangle's second vertex at the former, its third at the latter
  45. //! and its first at the remaining one, so I and J are the weights of the
  46. //! input triangle's second and third vertices). Triangle `k` of the node
  47. //! uses the node's vertices [`TRIANGLE_VERTICES`]`[k]`. A program that
  48. //! keeps fewer triangles in a node uses the bytes of the unused vertices
  49. //! for its own data.
  50. //!
  51. //! With the descriptor's triangle return mode set (bit 120) the result is
  52. //! the hit distance's numerator, its denominator, and the numerators of I
  53. //! and J over the same denominator, as floats. The denominator is positive
  54. //! for a triangle whose vertices run clockwise seen from the ray's origin
  55. //! in a left-handed coordinate system. A miss returns +infinity, 1.0, 0, 0.
  56. //! The ray's extent is not tested for triangles.
  57. //!
  58. //! # Where this comes from
  59. //!
  60. //! The node formats, the descriptor bits and the tests are those of the
  61. //! public software emulation of this instruction in the open-source Vulkan
  62. //! driver for this GPU family (box test and sorting network as there; the
  63. //! triangle test is the watertight one it uses, Woop, Benthin and Wald,
  64. //! JCGT 2013), and agree with what the title's own structure
  65. //! builder writes and its trace programs read. Not known from either: how
  66. //! the console rounds, which of two boxes entered at the same distance it
  67. //! returns first, and what it returns for a ray exactly through an edge
  68. //! (here: a hit in both triangles of the edge) or for kinds 6 and 7 (here:
  69. //! a triangle miss; the title's programs do not read it).
  70. /// The result dword for a box the ray misses, or a child that is not there.
  71. pub const NONE: u32 = 0xffff_ffff;
  72. /// The node's vertices that make triangle 0-3, by the triangle's own
  73. /// vertex numbers 0-2.
  74. pub const TRIANGLE_VERTICES: [[u32; 3]; 4] = [[0, 1, 2], [1, 3, 2], [2, 3, 4], [2, 4, 0]];
  75. /// Descriptor dword 1: boxes are returned nearest first.
  76. pub const BOX_SORT: u32 = 1 << 31;
  77. /// Descriptor dword 3: triangles return the numerators of I and J (clear:
  78. /// a triangle id and a hit status, which nothing here produces).
  79. pub const RETURN_BARYCENTRICS: u32 = 1 << 24;
  80. /// Descriptor dword 3, bits 31:28: the descriptor's type, a ray-tracing
  81. /// structure.
  82. pub const DESCRIPTOR_TYPE: u32 = 8;
  83. /// The ray as the instruction takes it.
  84. #[derive(Debug, Clone, Copy, PartialEq)]
  85. pub struct Ray {
  86. pub extent: f32,
  87. pub origin: [f32; 3],
  88. pub direction: [f32; 3],
  89. /// What the program computed as `1 / direction`.
  90. pub inverse: [f32; 3],
  91. }
  92. impl Ray {
  93. /// A ray with the inverse direction a program computes by division.
  94. pub fn new(origin: [f32; 3], direction: [f32; 3], extent: f32) -> Self {
  95. Self {
  96. extent,
  97. origin,
  98. direction,
  99. inverse: direction.map(|d| 1.0 / d),
  100. }
  101. }
  102. }
  103. /// The kind of the node a pointer names.
  104. pub fn kind(pointer: u64) -> u32 {
  105. (pointer & 7) as u32
  106. }
  107. /// The byte address of the node `pointer` names, for a descriptor whose
  108. /// first two dwords are `word0` and `word1`.
  109. pub fn node_address(word0: u32, word1: u32, pointer: u64) -> u64 {
  110. let base = (u64::from(word1 & 0xff) << 32 | u64::from(word0)) << 8;
  111. base.wrapping_add((pointer >> 3) << 6)
  112. }
  113. /// What the instruction returns for the node at `words` (its first 28
  114. /// dwords; a 64-byte node's dwords 16-27 are not read) named by a pointer
  115. /// of this `kind`, with box sorting as `sort` says and the triangle return
  116. /// mode set.
  117. pub fn intersect(words: &[u32; 28], kind: u32, ray: &Ray, sort: bool) -> [u32; 4] {
  118. match kind & 7 {
  119. 4 => boxes(&children(words), &boxes16(words), ray, sort),
  120. 5 => boxes(&children(words), &boxes32(words), ray, sort),
  121. k @ 0..=3 => triangle(&triangle_vertices(words, k), ray).map(f32::to_bits),
  122. _ => MISS.map(f32::to_bits),
  123. }
  124. }
  125. /// A box node's four child pointers.
  126. pub fn children(words: &[u32; 28]) -> [u32; 4] {
  127. [words[0], words[1], words[2], words[3]]
  128. }
  129. /// The four boxes of a 16-bit box node: minimum x y z, maximum x y z.
  130. pub fn boxes16(words: &[u32; 28]) -> [[f32; 6]; 4] {
  131. std::array::from_fn(|b| {
  132. std::array::from_fn(|k| {
  133. let half = 6 * b + k;
  134. half_to_f32((words[4 + half / 2] >> (16 * (half % 2))) as u16)
  135. })
  136. })
  137. }
  138. /// The four boxes of a 32-bit box node.
  139. pub fn boxes32(words: &[u32; 28]) -> [[f32; 6]; 4] {
  140. std::array::from_fn(|b| std::array::from_fn(|k| f32::from_bits(words[4 + 6 * b + k])))
  141. }
  142. /// [`TRIANGLE_VERTICES`] of triangle `k` in four bits each, vertex 0 lowest
  143. /// (as the public descriptions of the format give it: 0x210, 0x231, 0x432,
  144. /// 0x042).
  145. pub fn vertex_map(k: u32) -> u32 {
  146. let v = TRIANGLE_VERTICES[(k & 3) as usize];
  147. v[0] | v[1] << 4 | v[2] << 8
  148. }
  149. /// The vertices of triangle `k` (0-3) of a triangle node, the first being
  150. /// the one neither barycentric weighs, then I's, then J's.
  151. pub fn triangle_vertices(words: &[u32; 28], k: u32) -> [[f32; 3]; 3] {
  152. let id = words[15] >> (8 * k);
  153. let (i, j) = (id & 3, id >> 2 & 3);
  154. // An id naming one vertex twice, or a vertex 3, is malformed; it reads
  155. // what this arithmetic lands on (a vertex of the node), as the emitted
  156. // code does.
  157. let first = 3u32.wrapping_sub(i).wrapping_sub(j) & 3;
  158. [first, i, j].map(|n| {
  159. let vertex = (vertex_map(k) >> (4 * n) & 0xf) as usize;
  160. std::array::from_fn(|c| f32::from_bits(words[3 * vertex + c]))
  161. })
  162. }
  163. /// The box test: child pointers of the boxes the ray enters, `NONE` for
  164. /// the others; sorted by entry distance when `sort`, in child order
  165. /// otherwise.
  166. pub fn boxes(children: &[u32; 4], boxes: &[[f32; 6]; 4], ray: &Ray, sort: bool) -> [u32; 4] {
  167. // An infinite inverse (a direction component of 0) would turn an
  168. // origin exactly on a box's face into a NaN. (Maximum then minimum, as
  169. // the emitted code: a NaN becomes the lower bound, where `clamp` would
  170. // keep it.)
  171. #[allow(clippy::manual_clamp)]
  172. let inverse = ray.inverse.map(|x| x.max(-f32::MAX).min(f32::MAX));
  173. let mut ids = [NONE; 4];
  174. let mut distances = [f32::INFINITY; 4];
  175. for (n, b) in boxes.iter().enumerate() {
  176. let (mut near, mut far) = ([0f32; 3], [0f32; 3]);
  177. for a in 0..3 {
  178. let low = (b[a] - ray.origin[a]) * inverse[a];
  179. let high = (b[3 + a] - ray.origin[a]) * inverse[a];
  180. near[a] = low.min(high);
  181. far[a] = low.max(high);
  182. }
  183. let enter = near[0].max(near[1]).max(near[2]);
  184. let leave = far[0].min(far[1]).min(far[2]);
  185. // A box whose minimum x is NaN is switched off.
  186. if !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
  187. ids[n] = children[n];
  188. distances[n] = enter;
  189. }
  190. }
  191. if sort {
  192. for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
  193. if distances[b] < distances[a] {
  194. distances.swap(a, b);
  195. ids.swap(a, b);
  196. }
  197. }
  198. }
  199. ids
  200. }
  201. /// What a triangle the ray misses returns.
  202. pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
  203. /// The triangle test: the hit distance's numerator, the denominator, and
  204. /// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
  205. /// Watertight: the vertices are sheared so the ray runs along its largest
  206. /// axis, and the signs of the three edge functions decide, so a ray
  207. /// between two triangles that share an edge cannot miss both. Any NaN
  208. /// misses, and so does a triangle seen edge-on.
  209. pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
  210. let d = ray.direction;
  211. let size = d.map(f32::abs);
  212. // The largest axis, and the other two in an order that keeps the
  213. // triangle's winding.
  214. let kz = if size[0] >= size[1] {
  215. if size[0] >= size[2] { 0 } else { 2 }
  216. } else if size[1] >= size[2] {
  217. 1
  218. } else {
  219. 2
  220. };
  221. let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
  222. if d[kz] < 0.0 {
  223. std::mem::swap(&mut kx, &mut ky);
  224. }
  225. let sz = ray.inverse[kz];
  226. let (sx, sy) = (d[kx] * sz, d[ky] * sz);
  227. let sheared = |v: &[f32; 3]| {
  228. let r = [
  229. v[0] - ray.origin[0],
  230. v[1] - ray.origin[1],
  231. v[2] - ray.origin[2],
  232. ];
  233. (r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
  234. };
  235. let (ax, ay, az) = sheared(&p[0]);
  236. let (bx, by, bz) = sheared(&p[1]);
  237. let (cx, cy, cz) = sheared(&p[2]);
  238. let u = cx * by - cy * bx;
  239. let v = ax * cy - ay * cx;
  240. let w = bx * ay - by * ax;
  241. let behind = u < 0.0 || v < 0.0 || w < 0.0;
  242. let before = u > 0.0 || v > 0.0 || w > 0.0;
  243. let det = u + (v + w);
  244. let t = (u * az + v * bz) + w * cz;
  245. let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
  246. if !(behind && before) && ahead {
  247. [t, det, v, w]
  248. } else {
  249. MISS
  250. }
  251. }
  252. /// A 16-bit float as a 32-bit one (exact).
  253. pub fn half_to_f32(h: u16) -> f32 {
  254. let sign = u32::from(h >> 15) << 31;
  255. let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
  256. let bits = match exponent {
  257. 0 if mantissa == 0 => sign,
  258. 0 => {
  259. // Subnormal: normalise.
  260. let shift = mantissa.leading_zeros() - 21;
  261. sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
  262. }
  263. 0x1f => sign | 0xff << 23 | mantissa << 13,
  264. e => sign | (e + 112) << 23 | mantissa << 13,
  265. };
  266. f32::from_bits(bits)
  267. }
  268. #[cfg(test)]
  269. pub(crate) mod tests {
  270. use super::*;
  271. /// The smallest 16-bit float not below `x` (`up`) or not above it.
  272. pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
  273. let mut best: Option<u16> = None;
  274. for h in 0..=0xffffu16 {
  275. let f = half_to_f32(h);
  276. if f.is_nan() || if up { f < x } else { f > x } {
  277. continue;
  278. }
  279. best = match best {
  280. Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
  281. _ => Some(h),
  282. };
  283. }
  284. best.expect("a half")
  285. }
  286. /// A 32-bit box node.
  287. pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
  288. let mut w = [0u32; 28];
  289. w[..4].copy_from_slice(&children);
  290. for (b, bx) in boxes.iter().enumerate() {
  291. for (k, x) in bx.iter().enumerate() {
  292. w[4 + 6 * b + k] = x.to_bits();
  293. }
  294. }
  295. w
  296. }
  297. /// A 16-bit box node holding `boxes` rounded outward.
  298. pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
  299. let mut w = [0u32; 28];
  300. w[..4].copy_from_slice(&children);
  301. for (b, bx) in boxes.iter().enumerate() {
  302. for (k, x) in bx.iter().enumerate() {
  303. let half = 6 * b + k;
  304. let h = if x.is_nan() {
  305. 0x7e00
  306. } else {
  307. f32_to_half(*x, k >= 3)
  308. };
  309. w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
  310. }
  311. }
  312. w
  313. }
  314. /// A triangle node: up to five vertices, and the dword at byte 60.
  315. pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
  316. let mut w = [0u32; 28];
  317. for (n, v) in vertices.iter().enumerate() {
  318. for (c, x) in v.iter().enumerate() {
  319. w[3 * n + c] = x.to_bits();
  320. }
  321. }
  322. w[15] = id;
  323. w
  324. }
  325. const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
  326. fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
  327. std::array::from_fn(|k| b[k] + by[k % 3])
  328. }
  329. const OFF: [f32; 6] = [f32::NAN; 6];
  330. #[test]
  331. fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
  332. // The 64-bit form as the title uses it: base 0, the structure's
  333. // address folded into the pointer.
  334. let structure = 0x12_3456_7800u64;
  335. let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
  336. assert_eq!(kind(pointer), 5);
  337. assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
  338. // The 32-bit form: the base in the descriptor.
  339. let word0 = (structure >> 8) as u32;
  340. let word1 = (structure >> 40) as u32 | BOX_SORT;
  341. assert_eq!(
  342. node_address(word0, word1, 0x1000 >> 3 | 4),
  343. structure + 0x1000
  344. );
  345. // A base past 4 GiB of 256-byte units.
  346. assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
  347. }
  348. #[test]
  349. fn halves_convert_exactly() {
  350. assert_eq!(half_to_f32(0x3c00), 1.0);
  351. assert_eq!(half_to_f32(0xc000), -2.0);
  352. assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
  353. assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
  354. assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
  355. assert_eq!(half_to_f32(0x7bff), 65504.0);
  356. assert!(half_to_f32(0x7e00).is_nan());
  357. assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
  358. // Outward rounding of the test helper.
  359. assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
  360. assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
  361. }
  362. #[test]
  363. fn boxes_are_returned_nearest_first_and_misses_last() {
  364. let children = [0x105, 0x20c, 0x304, 0x400];
  365. // Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
  366. let node = box32(
  367. children,
  368. [
  369. moved(UNIT, [30.0, 0.0, 0.0]),
  370. moved(UNIT, [10.0, 0.0, 0.0]),
  371. moved(UNIT, [10.0, 5.0, 0.0]),
  372. moved(UNIT, [20.0, 0.0, 0.0]),
  373. ],
  374. );
  375. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
  376. assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
  377. // Without sorting: child order, the miss in its place.
  378. assert_eq!(
  379. intersect(&node, 5, &ray, false),
  380. [0x105, 0x20c, NONE, 0x400]
  381. );
  382. // The extent cuts the far ones off (entered at 9, 19, 29).
  383. let short = Ray {
  384. extent: 19.5,
  385. ..ray
  386. };
  387. assert_eq!(
  388. intersect(&node, 5, &short, true),
  389. [0x20c, 0x400, NONE, NONE]
  390. );
  391. // An entry exactly at the extent is no hit.
  392. let exact = Ray {
  393. extent: 19.0,
  394. ..ray
  395. };
  396. assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
  397. // Backwards: nothing.
  398. let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
  399. assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
  400. }
  401. #[test]
  402. fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
  403. let node = box32(
  404. [8, 16, NONE, NONE],
  405. [UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
  406. );
  407. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
  408. // Box 0 is entered at -1 (behind the origin), box 1 at 2.
  409. assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
  410. // Even with a tiny extent the box around the origin is a hit.
  411. let tiny = Ray {
  412. extent: 1e-6,
  413. ..ray
  414. };
  415. assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
  416. }
  417. #[test]
  418. fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
  419. let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
  420. // Direction components of 0: the inverse is infinite.
  421. let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  422. assert!(ray.inverse[1].is_infinite());
  423. // The origin lies in the plane of the box's -y face: (-1 - -1) x inf
  424. // would be a NaN; with the inverse held finite it is 0, and the ray
  425. // running along the face is inside.
  426. assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
  427. // Along the +y face it is outside: the face's plane is left at 0
  428. // and the box is entered at 4 (as the public emulation has it).
  429. let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  430. assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
  431. let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
  432. assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
  433. // -0 gives -infinity.
  434. let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
  435. assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
  436. assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
  437. }
  438. #[test]
  439. fn a_box_switched_off_and_a_missing_child_return_none() {
  440. let node = box32(
  441. [8, NONE, 24, 32],
  442. [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
  443. );
  444. let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  445. // Child 1 is hit but is not there: its pointer is what "none" is.
  446. assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
  447. }
  448. #[test]
  449. fn equal_distances_keep_child_order() {
  450. let node = box32([8, 16, 24, 32], [UNIT; 4]);
  451. let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  452. assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
  453. }
  454. #[test]
  455. fn half_float_boxes_test_like_their_widened_values() {
  456. let boxes = [
  457. moved(UNIT, [30.0, 0.1, 0.0]),
  458. moved(UNIT, [10.0, 0.0, 0.3]),
  459. moved(UNIT, [10.0, 5.0, 0.0]),
  460. moved(UNIT, [20.7, 0.0, 0.0]),
  461. ];
  462. let children = [0x105, 0x20c, 0x304, 0x400];
  463. let node = box16(children, boxes);
  464. let wide = boxes16(&node);
  465. for (w, b) in wide.iter().zip(&boxes) {
  466. for k in 0..3 {
  467. assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
  468. }
  469. }
  470. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
  471. assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
  472. assert_eq!(
  473. intersect(&node, 4, &ray, true),
  474. intersect(&box32(children, wide), 5, &ray, true)
  475. );
  476. }
  477. /// The hit a result describes: distance, I, J, front face.
  478. fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
  479. let [t, det, i, j] = r.map(f32::from_bits);
  480. (t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
  481. }
  482. /// Clockwise seen from the origin looking down +z in a left-handed
  483. /// system (x right, y up): the front face.
  484. const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
  485. #[test]
  486. fn a_triangle_returns_distance_and_weights_over_one_denominator() {
  487. let node = triangles(&TRIANGLE, 9);
  488. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  489. let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  490. assert_eq!(t, 5.0);
  491. // (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
  492. assert_eq!((i, j), (0.25, 0.25));
  493. assert!(front);
  494. // Near vertex 1: I near 1.
  495. let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
  496. let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  497. assert!(i > 0.85 && j < 0.1, "{i} {j}");
  498. // From behind: the same weights, the back face.
  499. let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
  500. let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  501. assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
  502. // An unnormalised direction: the distance is in its units.
  503. let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
  504. assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
  505. }
  506. #[test]
  507. fn a_triangle_is_missed_beside_behind_and_edge_on() {
  508. let node = triangles(&TRIANGLE, 9);
  509. let miss = MISS.map(f32::to_bits);
  510. // Beside it.
  511. let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
  512. assert_eq!(intersect(&node, 0, &ray, true), miss);
  513. // It lies behind the origin.
  514. let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
  515. assert_eq!(intersect(&node, 0, &ray, true), miss);
  516. // In its plane.
  517. let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
  518. assert_eq!(intersect(&node, 0, &ray, true), miss);
  519. // A triangle with no area.
  520. let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
  521. let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
  522. assert_eq!(intersect(&flat, 0, &ray, true), miss);
  523. // A vertex that is not a number, a direction of zero.
  524. let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
  525. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  526. assert_eq!(intersect(&nan, 0, &ray, true), miss);
  527. let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
  528. assert_eq!(intersect(&node, 0, &still, true), miss);
  529. // The extent is the program's to test: a far triangle is a hit.
  530. let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
  531. assert!(hit(intersect(&node, 0, &short, true)).is_some());
  532. }
  533. #[test]
  534. fn a_ray_through_a_shared_edge_misses_neither_triangle() {
  535. // Two triangles of a quad sharing the diagonal, wound alike.
  536. let quad = [
  537. [-1.0, -1.0, 4.0],
  538. [-1.0, 1.0, 4.0],
  539. [1.0, 1.0, 4.0],
  540. [1.0, -1.0, 4.0],
  541. ];
  542. let first = triangles(&[quad[0], quad[1], quad[2]], 9);
  543. let second = triangles(&[quad[0], quad[2], quad[3]], 9);
  544. // A fan of rays crossing the diagonal, some exactly on it.
  545. for n in -40..=40 {
  546. let x = n as f32 / 64.0;
  547. for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
  548. for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
  549. // Aim at (ox, oy, 4).
  550. let s = 4.0 / d[2];
  551. let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
  552. let a = hit(intersect(&first, 0, &ray, true));
  553. let b = hit(intersect(&second, 0, &ray, true));
  554. assert!(
  555. a.is_some() || b.is_some(),
  556. "a hole at {ox} {oy} along {d:?}"
  557. );
  558. for h in [a, b].into_iter().flatten() {
  559. assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
  560. }
  561. }
  562. }
  563. }
  564. }
  565. #[test]
  566. fn the_id_dword_says_which_vertices_the_weights_belong_to() {
  567. // What the title's builder does with an input triangle (a, b, c)
  568. // and an id byte: a at the vertex neither field names, b at I's,
  569. // c at J's.
  570. let [a, b, c] = TRIANGLE;
  571. let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
  572. let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
  573. for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
  574. let mut stored = [[0f32; 3]; 3];
  575. stored[(3 - i - j) as usize] = a;
  576. stored[i as usize] = b;
  577. stored[j as usize] = c;
  578. let node = triangles(&stored, i | j << 2);
  579. assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
  580. }
  581. // The higher bits of the byte (opaque and the like) change nothing.
  582. let node = triangles(&[a, b, c], 9 | 0x80);
  583. assert_eq!(intersect(&node, 0, &ray, true), plain);
  584. }
  585. #[test]
  586. fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
  587. let [a, b, c] = TRIANGLE;
  588. let far = [50.0, 50.0, 50.0];
  589. let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
  590. let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
  591. for k in 1..4u32 {
  592. // Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
  593. let mut vertices = [far; 5];
  594. let at = TRIANGLE_VERTICES[k as usize];
  595. vertices[at[0] as usize] = a;
  596. vertices[at[1] as usize] = b;
  597. vertices[at[2] as usize] = c;
  598. // Triangle 0's byte would be malformed here; only byte k counts.
  599. let node = triangles(&vertices, 9 << (8 * k));
  600. assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
  601. }
  602. // A pair as the title's builder stores it: the second triangle's
  603. // own vertex at node vertex 3, named by I.
  604. let d = [2.0, 2.0, 5.0];
  605. // Input triangles (a, b, c) and (a, d, b): they share a and b.
  606. let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
  607. // Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
  608. let got = triangle_vertices(&node, 1);
  609. assert_eq!(got, [b, d, c]);
  610. }
  611. #[test]
  612. fn instances_and_procedural_nodes_return_a_triangle_miss() {
  613. let node = triangles(&TRIANGLE, 9);
  614. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  615. for k in [6, 7] {
  616. assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
  617. }
  618. }
  619. #[test]
  620. fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
  621. // The same triangle and ray turned so the ray's largest axis is each
  622. // of the three, forwards and backwards. Both turns are rotations,
  623. // so the facing stays.
  624. let turn = |v: [f32; 3], axis: usize, flip: bool| {
  625. let mut r = v;
  626. for _ in 0..axis {
  627. r = [r[2], r[0], r[1]];
  628. }
  629. if flip {
  630. // Half a turn about the axis after the largest one's next.
  631. let largest = (2 + axis) % 3;
  632. r[largest] = -r[largest];
  633. r[(largest + 1) % 3] = -r[(largest + 1) % 3];
  634. }
  635. r
  636. };
  637. let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
  638. let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
  639. for axis in 0..3 {
  640. for flip in [false, true] {
  641. let p = TRIANGLE.map(|v| turn(v, axis, flip));
  642. let r = Ray::new(
  643. turn(ray.origin, axis, flip),
  644. turn(ray.direction, axis, flip),
  645. 100.0,
  646. );
  647. let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
  648. assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
  649. assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
  650. assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
  651. }
  652. }
  653. }
  654. }