bvh.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. A child that is not
  186. // there may have inverted infinite bounds, which every ray enters at
  187. // minus infinity: it would be first of the sorted children and end
  188. // the walk before them (DexNom/VIctory bc3cd4b0).
  189. if children[n] != NONE && !b[0].is_nan() && leave >= enter.max(0.0) && enter < ray.extent {
  190. ids[n] = children[n];
  191. distances[n] = enter;
  192. }
  193. }
  194. if sort {
  195. for (a, b) in [(0, 1), (2, 3), (0, 2), (1, 3), (1, 2)] {
  196. if distances[b] < distances[a] {
  197. distances.swap(a, b);
  198. ids.swap(a, b);
  199. }
  200. }
  201. }
  202. ids
  203. }
  204. /// What a triangle the ray misses returns.
  205. pub const MISS: [f32; 4] = [f32::INFINITY, 1.0, 0.0, 0.0];
  206. /// The triangle test: the hit distance's numerator, the denominator, and
  207. /// the numerators of the weights of vertices 1 and 2; [`MISS`] otherwise.
  208. /// Watertight: the vertices are sheared so the ray runs along its largest
  209. /// axis, and the signs of the three edge functions decide, so a ray
  210. /// between two triangles that share an edge cannot miss both. Any NaN
  211. /// misses, and so does a triangle seen edge-on.
  212. pub fn triangle(p: &[[f32; 3]; 3], ray: &Ray) -> [f32; 4] {
  213. let d = ray.direction;
  214. let size = d.map(f32::abs);
  215. // The largest axis, and the other two in an order that keeps the
  216. // triangle's winding.
  217. let kz = if size[0] >= size[1] {
  218. if size[0] >= size[2] { 0 } else { 2 }
  219. } else if size[1] >= size[2] {
  220. 1
  221. } else {
  222. 2
  223. };
  224. let (mut kx, mut ky) = ((kz + 1) % 3, (kz + 2) % 3);
  225. if d[kz] < 0.0 {
  226. std::mem::swap(&mut kx, &mut ky);
  227. }
  228. let sz = ray.inverse[kz];
  229. let (sx, sy) = (d[kx] * sz, d[ky] * sz);
  230. let sheared = |v: &[f32; 3]| {
  231. let r = [
  232. v[0] - ray.origin[0],
  233. v[1] - ray.origin[1],
  234. v[2] - ray.origin[2],
  235. ];
  236. (r[kx] - sx * r[kz], r[ky] - sy * r[kz], sz * r[kz])
  237. };
  238. let (ax, ay, az) = sheared(&p[0]);
  239. let (bx, by, bz) = sheared(&p[1]);
  240. let (cx, cy, cz) = sheared(&p[2]);
  241. let u = cx * by - cy * bx;
  242. let v = ax * cy - ay * cx;
  243. let w = bx * ay - by * ax;
  244. let behind = u < 0.0 || v < 0.0 || w < 0.0;
  245. let before = u > 0.0 || v > 0.0 || w > 0.0;
  246. let det = u + (v + w);
  247. let t = (u * az + v * bz) + w * cz;
  248. let ahead = det > 0.0 && t >= 0.0 || det < 0.0 && t <= 0.0;
  249. if !(behind && before) && ahead {
  250. [t, det, v, w]
  251. } else {
  252. MISS
  253. }
  254. }
  255. /// A 16-bit float as a 32-bit one (exact).
  256. pub fn half_to_f32(h: u16) -> f32 {
  257. let sign = u32::from(h >> 15) << 31;
  258. let (exponent, mantissa) = (u32::from(h >> 10 & 0x1f), u32::from(h & 0x3ff));
  259. let bits = match exponent {
  260. 0 if mantissa == 0 => sign,
  261. 0 => {
  262. // Subnormal: normalise.
  263. let shift = mantissa.leading_zeros() - 21;
  264. sign | (113 - shift) << 23 | (mantissa << shift & 0x3ff) << 13
  265. }
  266. 0x1f => sign | 0xff << 23 | mantissa << 13,
  267. e => sign | (e + 112) << 23 | mantissa << 13,
  268. };
  269. f32::from_bits(bits)
  270. }
  271. #[cfg(test)]
  272. pub(crate) mod tests {
  273. use super::*;
  274. /// An empty slot's inverted infinite bounds do not come before the
  275. /// children a ray enters (after DexNom/VIctory bc3cd4b0).
  276. #[test]
  277. fn an_empty_slot_is_never_entered() {
  278. let inside = |x: f32| [x - 1.0, -1.0, -1.0, x + 1.0, 1.0, 1.0];
  279. let (up, down) = (f32::INFINITY, f32::NEG_INFINITY);
  280. let bounds = [inside(30.0), [up, up, up, down, down, down], inside(10.0), [up, up, up, down, down, down]];
  281. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
  282. assert_eq!(boxes(&[8, NONE, 16, NONE], &bounds, &ray, true), [16, 8, NONE, NONE]);
  283. }
  284. /// The smallest 16-bit float not below `x` (`up`) or not above it.
  285. pub(crate) fn f32_to_half(x: f32, up: bool) -> u16 {
  286. let mut best: Option<u16> = None;
  287. for h in 0..=0xffffu16 {
  288. let f = half_to_f32(h);
  289. if f.is_nan() || if up { f < x } else { f > x } {
  290. continue;
  291. }
  292. best = match best {
  293. Some(b) if (half_to_f32(b) - x).abs() <= (f - x).abs() => Some(b),
  294. _ => Some(h),
  295. };
  296. }
  297. best.expect("a half")
  298. }
  299. /// A 32-bit box node.
  300. pub(crate) fn box32(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
  301. let mut w = [0u32; 28];
  302. w[..4].copy_from_slice(&children);
  303. for (b, bx) in boxes.iter().enumerate() {
  304. for (k, x) in bx.iter().enumerate() {
  305. w[4 + 6 * b + k] = x.to_bits();
  306. }
  307. }
  308. w
  309. }
  310. /// A 16-bit box node holding `boxes` rounded outward.
  311. pub(crate) fn box16(children: [u32; 4], boxes: [[f32; 6]; 4]) -> [u32; 28] {
  312. let mut w = [0u32; 28];
  313. w[..4].copy_from_slice(&children);
  314. for (b, bx) in boxes.iter().enumerate() {
  315. for (k, x) in bx.iter().enumerate() {
  316. let half = 6 * b + k;
  317. let h = if x.is_nan() {
  318. 0x7e00
  319. } else {
  320. f32_to_half(*x, k >= 3)
  321. };
  322. w[4 + half / 2] |= u32::from(h) << (16 * (half % 2));
  323. }
  324. }
  325. w
  326. }
  327. /// A triangle node: up to five vertices, and the dword at byte 60.
  328. pub(crate) fn triangles(vertices: &[[f32; 3]], id: u32) -> [u32; 28] {
  329. let mut w = [0u32; 28];
  330. for (n, v) in vertices.iter().enumerate() {
  331. for (c, x) in v.iter().enumerate() {
  332. w[3 * n + c] = x.to_bits();
  333. }
  334. }
  335. w[15] = id;
  336. w
  337. }
  338. const UNIT: [f32; 6] = [-1.0, -1.0, -1.0, 1.0, 1.0, 1.0];
  339. fn moved(b: [f32; 6], by: [f32; 3]) -> [f32; 6] {
  340. std::array::from_fn(|k| b[k] + by[k % 3])
  341. }
  342. const OFF: [f32; 6] = [f32::NAN; 6];
  343. #[test]
  344. fn node_pointers_name_64_byte_nodes_past_the_descriptors_base() {
  345. // The 64-bit form as the title uses it: base 0, the structure's
  346. // address folded into the pointer.
  347. let structure = 0x12_3456_7800u64;
  348. let pointer = (structure >> 8 << 5) + (0x40 >> 3 | 5);
  349. assert_eq!(kind(pointer), 5);
  350. assert_eq!(node_address(0, BOX_SORT, pointer), structure + 0x40);
  351. // The 32-bit form: the base in the descriptor.
  352. let word0 = (structure >> 8) as u32;
  353. let word1 = (structure >> 40) as u32 | BOX_SORT;
  354. assert_eq!(
  355. node_address(word0, word1, 0x1000 >> 3 | 4),
  356. structure + 0x1000
  357. );
  358. // A base past 4 GiB of 256-byte units.
  359. assert_eq!(node_address(0, 0x8000_0001, 8), (1 << 40) + 64);
  360. }
  361. #[test]
  362. fn halves_convert_exactly() {
  363. assert_eq!(half_to_f32(0x3c00), 1.0);
  364. assert_eq!(half_to_f32(0xc000), -2.0);
  365. assert_eq!(half_to_f32(0x7c00), f32::INFINITY);
  366. assert_eq!(half_to_f32(0x0001), 2f32.powi(-24));
  367. assert_eq!(half_to_f32(0x03ff), 1023.0 * 2f32.powi(-24));
  368. assert_eq!(half_to_f32(0x7bff), 65504.0);
  369. assert!(half_to_f32(0x7e00).is_nan());
  370. assert_eq!(half_to_f32(0x8000).to_bits(), 0x8000_0000);
  371. // Outward rounding of the test helper.
  372. assert!(half_to_f32(f32_to_half(0.1, true)) >= 0.1);
  373. assert!(half_to_f32(f32_to_half(0.1, false)) <= 0.1);
  374. }
  375. #[test]
  376. fn boxes_are_returned_nearest_first_and_misses_last() {
  377. let children = [0x105, 0x20c, 0x304, 0x400];
  378. // Along +x from the origin: boxes at x = 30, 10, (off axis), 20.
  379. let node = box32(
  380. children,
  381. [
  382. moved(UNIT, [30.0, 0.0, 0.0]),
  383. moved(UNIT, [10.0, 0.0, 0.0]),
  384. moved(UNIT, [10.0, 5.0, 0.0]),
  385. moved(UNIT, [20.0, 0.0, 0.0]),
  386. ],
  387. );
  388. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
  389. assert_eq!(intersect(&node, 5, &ray, true), [0x20c, 0x400, 0x105, NONE]);
  390. // Without sorting: child order, the miss in its place.
  391. assert_eq!(
  392. intersect(&node, 5, &ray, false),
  393. [0x105, 0x20c, NONE, 0x400]
  394. );
  395. // The extent cuts the far ones off (entered at 9, 19, 29).
  396. let short = Ray {
  397. extent: 19.5,
  398. ..ray
  399. };
  400. assert_eq!(
  401. intersect(&node, 5, &short, true),
  402. [0x20c, 0x400, NONE, NONE]
  403. );
  404. // An entry exactly at the extent is no hit.
  405. let exact = Ray {
  406. extent: 19.0,
  407. ..ray
  408. };
  409. assert_eq!(intersect(&node, 5, &exact, true), [0x20c, NONE, NONE, NONE]);
  410. // Backwards: nothing.
  411. let back = Ray::new([0.0; 3], [-1.0, 0.0, 0.0], 1000.0);
  412. assert_eq!(intersect(&node, 5, &back, true), [NONE; 4]);
  413. }
  414. #[test]
  415. fn a_ray_starting_inside_a_box_enters_it_at_its_origin() {
  416. let node = box32(
  417. [8, 16, NONE, NONE],
  418. [UNIT, moved(UNIT, [3.0, 0.0, 0.0]), OFF, OFF],
  419. );
  420. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 100.0);
  421. // Box 0 is entered at -1 (behind the origin), box 1 at 2.
  422. assert_eq!(intersect(&node, 5, &ray, true), [8, 16, NONE, NONE]);
  423. // Even with a tiny extent the box around the origin is a hit.
  424. let tiny = Ray {
  425. extent: 1e-6,
  426. ..ray
  427. };
  428. assert_eq!(intersect(&node, 5, &tiny, true), [8, NONE, NONE, NONE]);
  429. }
  430. #[test]
  431. fn axis_aligned_rays_and_origins_on_a_face_make_no_nan() {
  432. let node = box32([8, 16, 24, 32], [UNIT, OFF, OFF, OFF]);
  433. // Direction components of 0: the inverse is infinite.
  434. let ray = Ray::new([-5.0, -1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  435. assert!(ray.inverse[1].is_infinite());
  436. // The origin lies in the plane of the box's -y face: (-1 - -1) x inf
  437. // would be a NaN; with the inverse held finite it is 0, and the ray
  438. // running along the face is inside.
  439. assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
  440. // Along the +y face it is outside: the face's plane is left at 0
  441. // and the box is entered at 4 (as the public emulation has it).
  442. let top = Ray::new([-5.0, 1.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  443. assert_eq!(intersect(&node, 5, &top, true), [NONE; 4]);
  444. let outside = Ray::new([-5.0, 1.5, 0.0], [1.0, 0.0, 0.0], 100.0);
  445. assert_eq!(intersect(&node, 5, &outside, true), [NONE; 4]);
  446. // -0 gives -infinity.
  447. let minus = Ray::new([-5.0, 0.5, 0.0], [1.0, -0.0, 0.0], 100.0);
  448. assert_eq!(minus.inverse[1], f32::NEG_INFINITY);
  449. assert_eq!(intersect(&node, 5, &minus, true), [8, NONE, NONE, NONE]);
  450. }
  451. #[test]
  452. fn a_box_switched_off_and_a_missing_child_return_none() {
  453. let node = box32(
  454. [8, NONE, 24, 32],
  455. [UNIT, UNIT, [f32::NAN, -1.0, -1.0, 1.0, 1.0, 1.0], OFF],
  456. );
  457. let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  458. // Child 1 is hit but is not there: its pointer is what "none" is.
  459. assert_eq!(intersect(&node, 5, &ray, true), [8, NONE, NONE, NONE]);
  460. }
  461. #[test]
  462. fn equal_distances_keep_child_order() {
  463. let node = box32([8, 16, 24, 32], [UNIT; 4]);
  464. let ray = Ray::new([-5.0, 0.0, 0.0], [1.0, 0.0, 0.0], 100.0);
  465. assert_eq!(intersect(&node, 5, &ray, true), [8, 16, 24, 32]);
  466. }
  467. #[test]
  468. fn half_float_boxes_test_like_their_widened_values() {
  469. let boxes = [
  470. moved(UNIT, [30.0, 0.1, 0.0]),
  471. moved(UNIT, [10.0, 0.0, 0.3]),
  472. moved(UNIT, [10.0, 5.0, 0.0]),
  473. moved(UNIT, [20.7, 0.0, 0.0]),
  474. ];
  475. let children = [0x105, 0x20c, 0x304, 0x400];
  476. let node = box16(children, boxes);
  477. let wide = boxes16(&node);
  478. for (w, b) in wide.iter().zip(&boxes) {
  479. for k in 0..3 {
  480. assert!(w[k] <= b[k] && w[3 + k] >= b[3 + k], "rounded outward");
  481. }
  482. }
  483. let ray = Ray::new([0.0; 3], [1.0, 0.0, 0.0], 1000.0);
  484. assert_eq!(intersect(&node, 4, &ray, true), [0x20c, 0x400, 0x105, NONE]);
  485. assert_eq!(
  486. intersect(&node, 4, &ray, true),
  487. intersect(&box32(children, wide), 5, &ray, true)
  488. );
  489. }
  490. /// The hit a result describes: distance, I, J, front face.
  491. fn hit(r: [u32; 4]) -> Option<(f32, f32, f32, bool)> {
  492. let [t, det, i, j] = r.map(f32::from_bits);
  493. (t != f32::INFINITY).then(|| (t / det, i / det, j / det, det > 0.0))
  494. }
  495. /// Clockwise seen from the origin looking down +z in a left-handed
  496. /// system (x right, y up): the front face.
  497. const TRIANGLE: [[f32; 3]; 3] = [[0.0, 2.0, 5.0], [2.0, -2.0, 5.0], [-2.0, -2.0, 5.0]];
  498. #[test]
  499. fn a_triangle_returns_distance_and_weights_over_one_denominator() {
  500. let node = triangles(&TRIANGLE, 9);
  501. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  502. let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  503. assert_eq!(t, 5.0);
  504. // (0, 0) = 0.5 v0 + 0.25 v1 + 0.25 v2.
  505. assert_eq!((i, j), (0.25, 0.25));
  506. assert!(front);
  507. // Near vertex 1: I near 1.
  508. let ray = Ray::new([1.75, -1.75, 0.0], [0.0, 0.0, 1.0], 100.0);
  509. let (_, i, j, _) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  510. assert!(i > 0.85 && j < 0.1, "{i} {j}");
  511. // From behind: the same weights, the back face.
  512. let ray = Ray::new([0.0, 0.0, 10.0], [0.0, 0.0, -1.0], 100.0);
  513. let (t, i, j, front) = hit(intersect(&node, 0, &ray, true)).expect("a hit");
  514. assert_eq!((t, i, j, front), (5.0, 0.25, 0.25, false));
  515. // An unnormalised direction: the distance is in its units.
  516. let ray = Ray::new([0.0; 3], [0.0, 0.0, 4.0], 100.0);
  517. assert_eq!(hit(intersect(&node, 0, &ray, true)).unwrap().0, 1.25);
  518. }
  519. #[test]
  520. fn a_triangle_is_missed_beside_behind_and_edge_on() {
  521. let node = triangles(&TRIANGLE, 9);
  522. let miss = MISS.map(f32::to_bits);
  523. // Beside it.
  524. let ray = Ray::new([3.0, 0.0, 0.0], [0.0, 0.0, 1.0], 100.0);
  525. assert_eq!(intersect(&node, 0, &ray, true), miss);
  526. // It lies behind the origin.
  527. let ray = Ray::new([0.0, 0.0, 6.0], [0.0, 0.0, 1.0], 100.0);
  528. assert_eq!(intersect(&node, 0, &ray, true), miss);
  529. // In its plane.
  530. let ray = Ray::new([-5.0, 0.0, 5.0], [1.0, 0.0, 0.0], 100.0);
  531. assert_eq!(intersect(&node, 0, &ray, true), miss);
  532. // A triangle with no area.
  533. let flat = triangles(&[[0.0, 0.0, 5.0], [1.0, 1.0, 5.0], [2.0, 2.0, 5.0]], 9);
  534. let ray = Ray::new([1.0, 1.0, 0.0], [0.0, 0.0, 1.0], 100.0);
  535. assert_eq!(intersect(&flat, 0, &ray, true), miss);
  536. // A vertex that is not a number, a direction of zero.
  537. let nan = triangles(&[[f32::NAN, 2.0, 5.0], TRIANGLE[1], TRIANGLE[2]], 9);
  538. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  539. assert_eq!(intersect(&nan, 0, &ray, true), miss);
  540. let still = Ray::new([0.0; 3], [0.0; 3], 100.0);
  541. assert_eq!(intersect(&node, 0, &still, true), miss);
  542. // The extent is the program's to test: a far triangle is a hit.
  543. let short = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 1.0);
  544. assert!(hit(intersect(&node, 0, &short, true)).is_some());
  545. }
  546. #[test]
  547. fn a_ray_through_a_shared_edge_misses_neither_triangle() {
  548. // Two triangles of a quad sharing the diagonal, wound alike.
  549. let quad = [
  550. [-1.0, -1.0, 4.0],
  551. [-1.0, 1.0, 4.0],
  552. [1.0, 1.0, 4.0],
  553. [1.0, -1.0, 4.0],
  554. ];
  555. let first = triangles(&[quad[0], quad[1], quad[2]], 9);
  556. let second = triangles(&[quad[0], quad[2], quad[3]], 9);
  557. // A fan of rays crossing the diagonal, some exactly on it.
  558. for n in -40..=40 {
  559. let x = n as f32 / 64.0;
  560. for (ox, oy) in [(x, x), (x, x + 1.0 / 1024.0), (x + 1.0 / 1024.0, x)] {
  561. for d in [[0.0, 0.0, 1.0], [0.125, -0.0625, 1.0], [0.25, 0.5, 2.0]] {
  562. // Aim at (ox, oy, 4).
  563. let s = 4.0 / d[2];
  564. let ray = Ray::new([ox - d[0] * s, oy - d[1] * s, 0.0], d, 100.0);
  565. let a = hit(intersect(&first, 0, &ray, true));
  566. let b = hit(intersect(&second, 0, &ray, true));
  567. assert!(
  568. a.is_some() || b.is_some(),
  569. "a hole at {ox} {oy} along {d:?}"
  570. );
  571. for h in [a, b].into_iter().flatten() {
  572. assert!((h.0 - s).abs() < 1e-5 && h.3, "{h:?}");
  573. }
  574. }
  575. }
  576. }
  577. }
  578. #[test]
  579. fn the_id_dword_says_which_vertices_the_weights_belong_to() {
  580. // What the title's builder does with an input triangle (a, b, c)
  581. // and an id byte: a at the vertex neither field names, b at I's,
  582. // c at J's.
  583. let [a, b, c] = TRIANGLE;
  584. let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
  585. let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
  586. for (i, j) in [(1u32, 2u32), (2, 0), (0, 1), (2, 1), (0, 2), (1, 0)] {
  587. let mut stored = [[0f32; 3]; 3];
  588. stored[(3 - i - j) as usize] = a;
  589. stored[i as usize] = b;
  590. stored[j as usize] = c;
  591. let node = triangles(&stored, i | j << 2);
  592. assert_eq!(intersect(&node, 0, &ray, true), plain, "I {i} J {j}");
  593. }
  594. // The higher bits of the byte (opaque and the like) change nothing.
  595. let node = triangles(&[a, b, c], 9 | 0x80);
  596. assert_eq!(intersect(&node, 0, &ray, true), plain);
  597. }
  598. #[test]
  599. fn triangles_one_to_three_take_their_vertices_and_their_id_byte() {
  600. let [a, b, c] = TRIANGLE;
  601. let far = [50.0, 50.0, 50.0];
  602. let ray = Ray::new([0.5, -0.25, 0.0], [0.0, 0.0, 1.0], 100.0);
  603. let plain = intersect(&triangles(&[a, b, c], 9), 0, &ray, true);
  604. for k in 1..4u32 {
  605. // Triangle k's vertices 0, 1, 2 are the node's `TRIANGLE_VERTICES[k]`.
  606. let mut vertices = [far; 5];
  607. let at = TRIANGLE_VERTICES[k as usize];
  608. vertices[at[0] as usize] = a;
  609. vertices[at[1] as usize] = b;
  610. vertices[at[2] as usize] = c;
  611. // Triangle 0's byte would be malformed here; only byte k counts.
  612. let node = triangles(&vertices, 9 << (8 * k));
  613. assert_eq!(intersect(&node, k, &ray, true), plain, "triangle {k}");
  614. }
  615. // A pair as the title's builder stores it: the second triangle's
  616. // own vertex at node vertex 3, named by I.
  617. let d = [2.0, 2.0, 5.0];
  618. // Input triangles (a, b, c) and (a, d, b): they share a and b.
  619. let node = triangles(&[a, b, c, d], 9 | (1 | 2 << 2) << 8);
  620. // Triangle 1 = node vertices (1, 3, 2) = (b, d, c) as vertices 0, 1, 2.
  621. let got = triangle_vertices(&node, 1);
  622. assert_eq!(got, [b, d, c]);
  623. }
  624. #[test]
  625. fn instances_and_procedural_nodes_return_a_triangle_miss() {
  626. let node = triangles(&TRIANGLE, 9);
  627. let ray = Ray::new([0.0; 3], [0.0, 0.0, 1.0], 100.0);
  628. for k in [6, 7] {
  629. assert_eq!(intersect(&node, k, &ray, true), MISS.map(f32::to_bits));
  630. }
  631. }
  632. #[test]
  633. fn the_largest_axis_and_its_sign_do_not_change_the_answer() {
  634. // The same triangle and ray turned so the ray's largest axis is each
  635. // of the three, forwards and backwards. Both turns are rotations,
  636. // so the facing stays.
  637. let turn = |v: [f32; 3], axis: usize, flip: bool| {
  638. let mut r = v;
  639. for _ in 0..axis {
  640. r = [r[2], r[0], r[1]];
  641. }
  642. if flip {
  643. // Half a turn about the axis after the largest one's next.
  644. let largest = (2 + axis) % 3;
  645. r[largest] = -r[largest];
  646. r[(largest + 1) % 3] = -r[(largest + 1) % 3];
  647. }
  648. r
  649. };
  650. let ray = Ray::new([0.25, -0.5, 0.0], [0.0625, 0.125, 1.0], 100.0);
  651. let base = hit(triangle(&TRIANGLE, &ray).map(f32::to_bits)).expect("a hit");
  652. for axis in 0..3 {
  653. for flip in [false, true] {
  654. let p = TRIANGLE.map(|v| turn(v, axis, flip));
  655. let r = Ray::new(
  656. turn(ray.origin, axis, flip),
  657. turn(ray.direction, axis, flip),
  658. 100.0,
  659. );
  660. let h = hit(triangle(&p, &r).map(f32::to_bits)).expect("a hit");
  661. assert!((h.0 - base.0).abs() < 1e-5, "{axis} {flip}: {h:?} {base:?}");
  662. assert!((h.1 - base.1).abs() < 1e-5 && (h.2 - base.2).abs() < 1e-5);
  663. assert_eq!(h.3, base.3, "facing, axis {axis} flip {flip}");
  664. }
  665. }
  666. }
  667. }