1use std::f64::consts::TAU;
19
20use glam::DVec3;
21
22use crate::geometry::bvh::{
23 Aabb,
24 Bvh,
25};
26use crate::geometry::model::{
27 BooleanOp,
28 Geometry,
29 Shape,
30 SolidId,
31};
32
33pub type Intervals = Vec<(f64, f64)>;
36
37const CROSSING_TOLERANCE : f64 = 1e-7;
40
41#[derive(Debug, Clone, PartialEq)]
46pub struct SolidRaycaster {
47 bounds : Vec<Aabb>,
49 bvhs : Vec<Option<Bvh>>,
51}
52
53impl SolidRaycaster {
54 pub fn new(geo : &Geometry) -> Self {
55 let mut bounds = Vec::with_capacity(geo.solids.len());
56 let mut bvhs = Vec::with_capacity(geo.solids.len());
57 for (k, solid) in geo.solids.iter().enumerate() {
58 bounds.push(solid_bounds(geo, k));
59 bvhs.push(match &solid.shape {
60 Shape::Tessellated { vertices, triangles } => {
61 let boxes : Vec<Aabb> = triangles.iter()
62 .map(|tri| Aabb::from_points(tri.iter().map(|&i| vertices[i as usize])))
63 .collect();
64 Some(Bvh::build(&boxes))
65 }
66 _ => None,
67 });
68 }
69 Self { bounds, bvhs }
70 }
71
72 pub fn bounds(&self, solid : SolidId) -> &Aabb {
74 &self.bounds[solid]
75 }
76
77 pub fn intervals(&self, geo : &Geometry, solid : SolidId,
84 origin : DVec3, dir : DVec3,
85 tmin : f64, tmax : f64) -> Option<Intervals> {
86 match &geo.solids[solid].shape {
87 Shape::Box { half_lengths } => {
88 let aabb = Aabb { min : -*half_lengths, max : *half_lengths };
89 Some(aabb.clip_line(origin, dir, tmin, tmax).into_iter().collect())
90 }
91 Shape::Tube { rmin, rmax, half_z, start_phi, delta_phi } => {
92 Some(tube_intervals(*rmin, *rmax, *half_z, *start_phi, *delta_phi, origin, dir, tmin, tmax))
93 }
94 Shape::Tessellated { vertices, triangles } => {
95 let bvh = self.bvhs[solid].as_ref().expect("Tessellated solid without BVH");
96 mesh_intervals(vertices, triangles, bvh, origin, dir, tmin, tmax)
97 }
98 Shape::Boolean { op, first, second, second_transform } => {
99 let a = self.intervals(geo, *first, origin, dir, tmin, tmax)?;
100 if a.is_empty() && *op != BooleanOp::Union {
101 return Some(a);
102 }
103 let b = self.intervals(geo, *second,
104 second_transform.inverse_apply_point(origin),
105 second_transform.inverse_apply_vector(dir),
106 tmin, tmax)?;
107 Some(match op {
108 BooleanOp::Union => combine(&a, &b, |x, y| x || y),
109 BooleanOp::Intersection => combine(&a, &b, |x, y| x && y),
110 BooleanOp::Subtraction => combine(&a, &b, |x, y| x && !y),
111 })
112 }
113 }
114 }
115}
116
117fn solid_bounds(geo : &Geometry, solid : SolidId) -> Aabb {
119 match &geo.solids[solid].shape {
120 Shape::Tessellated { vertices, .. } => Aabb::from_points(vertices.iter().copied()),
121 Shape::Box { half_lengths } => Aabb { min : -*half_lengths, max : *half_lengths },
122 Shape::Tube { rmax, half_z, .. } => Aabb {
123 min : DVec3::new(-rmax, -rmax, -half_z),
124 max : DVec3::new( *rmax, *rmax, *half_z),
125 },
126 Shape::Boolean { op, first, second, second_transform } => {
127 let a = solid_bounds(geo, *first);
128 let b = solid_bounds(geo, *second).transformed(second_transform);
129 match op {
130 BooleanOp::Union => { let mut u = a; u.merge(&b); u }
131 BooleanOp::Intersection => a.intersection(&b),
132 BooleanOp::Subtraction => a,
133 }
134 }
135 }
136}
137
138fn combine(a : &[(f64, f64)], b : &[(f64, f64)], keep : impl Fn(bool, bool) -> bool) -> Intervals {
143 let mut edges : Vec<f64> = a.iter().chain(b).flat_map(|&(t0, t1)| [t0, t1]).collect();
144 edges.sort_by(f64::total_cmp);
145 edges.dedup();
146 let contains = |iv : &[(f64, f64)], t : f64| iv.iter().any(|&(t0, t1)| t0 <= t && t <= t1);
147 let mut out = Intervals::new();
148 for w in edges.windows(2) {
149 let t = 0.5*(w[0] + w[1]);
150 if keep(contains(a, t), contains(b, t)) {
151 push_merged(&mut out, w[0], w[1]);
152 }
153 }
154 out
155}
156
157fn push_merged(iv : &mut Intervals, t0 : f64, t1 : f64) {
160 if let Some(last) = iv.last_mut() {
161 if last.1 >= t0 {
162 last.1 = last.1.max(t1);
163 return;
164 }
165 }
166 iv.push((t0, t1));
167}
168
169fn tube_intervals(rmin : f64, rmax : f64, half_z : f64, start_phi : f64, delta_phi : f64,
172 o : DVec3, d : DVec3, tmin : f64, tmax : f64) -> Intervals {
173 let slab = Aabb {
174 min : DVec3::new(-rmax, -rmax, -half_z),
175 max : DVec3::new( rmax, rmax, half_z),
176 };
177 let Some((t0, t1)) = slab.clip_line(o, d, tmin, tmax) else {
178 return Intervals::new();
179 };
180 let mut iv = disk_interval(rmax, o, d, t0, t1);
181 if rmin > 0.0 && !iv.is_empty() {
182 iv = combine(&iv, &disk_interval(rmin, o, d, t0, t1), |x, y| x && !y);
183 }
184 if delta_phi < TAU && !iv.is_empty() {
185 iv = combine(&iv, &wedge_intervals(start_phi, delta_phi, o, d, t0, t1), |x, y| x && y);
186 }
187 iv
188}
189
190fn disk_interval(r : f64, o : DVec3, d : DVec3, t0 : f64, t1 : f64) -> Intervals {
192 let a = d.x*d.x + d.y*d.y;
193 let b = o.x*d.x + o.y*d.y;
194 let c = o.x*o.x + o.y*o.y - r*r;
195 if a == 0.0 {
196 return if c <= 0.0 { vec![(t0, t1)] } else { Intervals::new() };
197 }
198 let disc = b*b - a*c;
199 if disc < 0.0 {
200 return Intervals::new();
201 }
202 let s = disc.sqrt();
203 let (ta, tb) = (((-b - s)/a).max(t0), ((-b + s)/a).min(t1));
204 if ta < tb { vec![(ta, tb)] } else { Intervals::new() }
205}
206
207fn wedge_intervals(start_phi : f64, delta_phi : f64, o : DVec3, d : DVec3, t0 : f64, t1 : f64) -> Intervals {
210 let inside = |t : f64| {
211 let p = o + t*d;
212 (p.y.atan2(p.x) - start_phi).rem_euclid(TAU) <= delta_phi
213 };
214 let mut ts = vec![t0, t1];
218 for phi in [start_phi, start_phi + delta_phi] {
219 let n = DVec3::new(-phi.sin(), phi.cos(), 0.0);
220 let dn = d.dot(n);
221 if dn != 0.0 {
222 let t = -o.dot(n)/dn;
223 if t > t0 && t < t1 {
224 ts.push(t);
225 }
226 }
227 }
228 ts.sort_by(f64::total_cmp);
229 let mut iv = Intervals::new();
230 for w in ts.windows(2) {
231 if w[1] > w[0] && inside(0.5*(w[0] + w[1])) {
232 push_merged(&mut iv, w[0], w[1]);
233 }
234 }
235 iv
236}
237
238struct WatertightRay {
244 origin : DVec3,
245 dir : DVec3,
246 kx : usize,
247 ky : usize,
248 kz : usize,
249 sx : f64,
250 sy : f64,
251 sz : f64,
252}
253
254impl WatertightRay {
255 fn new(origin : DVec3, dir : DVec3) -> Self {
256 let a = dir.abs();
257 let kz = if a.x >= a.y && a.x >= a.z { 0 } else if a.y >= a.z { 1 } else { 2 };
258 let mut kx = (kz + 1) % 3;
259 let mut ky = (kx + 1) % 3;
260 if dir[kz] < 0.0 {
262 std::mem::swap(&mut kx, &mut ky);
263 }
264 Self {
265 origin,
266 dir,
267 kx,
268 ky,
269 kz,
270 sx : dir[kx]/dir[kz],
271 sy : dir[ky]/dir[kz],
272 sz : 1.0/dir[kz],
273 }
274 }
275
276 fn intersect(&self, v0 : DVec3, v1 : DVec3, v2 : DVec3) -> Option<(f64, i32)> {
280 let (kx, ky, kz) = (self.kx, self.ky, self.kz);
281 let (a, b, c) = (v0 - self.origin, v1 - self.origin, v2 - self.origin);
282 let (ax, ay) = (a[kx] - self.sx*a[kz], a[ky] - self.sy*a[kz]);
283 let (bx, by) = (b[kx] - self.sx*b[kz], b[ky] - self.sy*b[kz]);
284 let (cx, cy) = (c[kx] - self.sx*c[kz], c[ky] - self.sy*c[kz]);
285 let u = cx*by - cy*bx;
286 let v = ax*cy - ay*cx;
287 let w = bx*ay - by*ax;
288 if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
289 return None;
290 }
291 let det = u + v + w;
292 if det == 0.0 {
293 return None;
294 }
295 let t = (u*a[kz] + v*b[kz] + w*c[kz])*self.sz/det;
296 let ndir = (v1 - v0).cross(v2 - v0).dot(self.dir);
297 if ndir == 0.0 {
298 return None;
299 }
300 Some((t, if ndir < 0.0 { 1 } else { -1 }))
301 }
302}
303
304fn mesh_intervals(vertices : &[DVec3], triangles : &[[u32; 3]], bvh : &Bvh,
305 origin : DVec3, dir : DVec3, tmin : f64, tmax : f64) -> Option<Intervals> {
306 let Some((ta, tb)) = bvh.bounds().expanded(1e-6).clip_line(origin, dir, f64::NEG_INFINITY, f64::INFINITY) else {
309 return Some(Intervals::new());
310 };
311 let ray = WatertightRay::new(origin, dir);
312 let mut crossings = Vec::new();
313 bvh.traverse(origin, dir, ta, tb, |i| {
314 let [a, b, c] = triangles[i as usize];
315 if let Some(crossing) = ray.intersect(vertices[a as usize], vertices[b as usize], vertices[c as usize]) {
316 crossings.push(crossing);
317 }
318 });
319 crossings.sort_by(|x, y| x.0.total_cmp(&y.0));
320
321 let mut iv = Intervals::new();
322 let mut winding = 0;
323 let mut start = 0.0;
324 let mut k = 0;
325 while k < crossings.len() {
326 let t = crossings[k].0;
331 let mut net = 0;
332 while k < crossings.len() && crossings[k].0 - t <= CROSSING_TOLERANCE {
333 net += crossings[k].1;
334 k += 1;
335 }
336 let before = winding;
337 winding += net.signum();
338 if winding < 0 {
339 return None;
340 }
341 if before == 0 && winding > 0 {
342 start = t;
343 } else if before > 0 && winding == 0 {
344 let (t0, t1) = (start.max(tmin), t.min(tmax));
345 if t0 < t1 {
346 push_merged(&mut iv, t0, t1);
347 }
348 }
349 }
350 if winding != 0 {
351 return None;
352 }
353 Some(iv)
354}
355
356#[cfg(test)]
359mod tests {
360 use super::*;
361 use std::f64::consts::FRAC_PI_2;
362 use crate::geometry::model::{
363 Material,
364 Solid,
365 Transform,
366 Volume,
367 };
368
369 fn geometry(shapes : Vec<Shape>) -> Geometry {
372 let solids = shapes.into_iter().enumerate()
373 .map(|(k, shape)| Solid { name : format!("s{k}"), shape })
374 .collect();
375 let world = Volume {
376 name : String::from("world"),
377 material : 0,
378 solid : 0,
379 daughters : Vec::new(),
380 auxiliary : Vec::new(),
381 };
382 Geometry::new(vec![Material { name : String::from("vacuum"), density : 0.0 }], solids, vec![world], 0).unwrap()
383 }
384
385 fn assert_intervals(iv : Option<Intervals>, expected : &[(f64, f64)]) {
386 let iv = iv.expect("line crosses the solid inconsistently");
387 assert_eq!(iv.len(), expected.len(), "{iv:?} != {expected:?}");
388 for (a, b) in iv.iter().zip(expected) {
389 assert!((a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9, "{iv:?} != {expected:?}");
390 }
391 }
392
393 fn cube() -> Shape {
395 let vertices : Vec<DVec3> = (0..8).map(|k| DVec3::new(
396 if k & 1 == 0 { -1.0 } else { 1.0 },
397 if k & 2 == 0 { -1.0 } else { 1.0 },
398 if k & 4 == 0 { -1.0 } else { 1.0 },
399 )).collect();
400 let quads = [[0, 2, 6, 4], [1, 3, 7, 5], [0, 1, 5, 4], [2, 3, 7, 6], [0, 1, 3, 2], [4, 5, 7, 6]];
401 let mut triangles = Vec::new();
402 for q in quads {
403 for mut tri in [[q[0], q[1], q[2]], [q[0], q[2], q[3]]] {
404 let [a, b, c] = tri.map(|i : u32| vertices[i as usize]);
405 if (b - a).cross(c - a).dot(a + b + c) < 0.0 {
406 tri.swap(1, 2);
407 }
408 triangles.push(tri);
409 }
410 }
411 Shape::Tessellated { vertices, triangles }
412 }
413
414 #[test]
415 fn box_and_tube() {
416 let geo = geometry(vec![
417 Shape::Box { half_lengths : DVec3::new(1.0, 2.0, 3.0) },
418 Shape::Tube { rmin : 1.0, rmax : 2.0, half_z : 1.0, start_phi : 0.0, delta_phi : TAU },
419 Shape::Tube { rmin : 0.0, rmax : 2.0, half_z : 1.0, start_phi : 0.0, delta_phi : FRAC_PI_2 },
420 ]);
421 let rc = SolidRaycaster::new(&geo);
422 let x0 = DVec3::new(-5.0, 0.0, 0.0);
423 assert_intervals(rc.intervals(&geo, 0, x0, DVec3::X, -10.0, 10.0), &[(4.0, 6.0)]);
424 assert_intervals(rc.intervals(&geo, 0, x0, DVec3::X, 0.0, 5.0), &[(4.0, 5.0)]);
425 assert_intervals(rc.intervals(&geo, 0, DVec3::new(0.0, 2.5, 0.0), DVec3::X, -10.0, 10.0), &[]);
426 assert_intervals(rc.intervals(&geo, 1, x0, DVec3::X, -10.0, 10.0), &[(3.0, 4.0), (6.0, 7.0)]);
428 assert_intervals(rc.intervals(&geo, 1, DVec3::ZERO, DVec3::Z, -10.0, 10.0), &[]);
429 assert_intervals(rc.intervals(&geo, 1, DVec3::new(1.5, 0.0, 0.0), DVec3::Z, -10.0, 10.0), &[(-1.0, 1.0)]);
430 let xq = (4.0f64 - 0.25).sqrt();
432 assert_intervals(rc.intervals(&geo, 2, DVec3::new(-5.0, 0.5, 0.0), DVec3::X, -10.0, 10.0), &[(5.0, 5.0 + xq)]);
433 assert_intervals(rc.intervals(&geo, 2, DVec3::new(-5.0, -0.5, 0.0), DVec3::X, -10.0, 10.0), &[]);
434 }
435
436 #[test]
437 fn booleans() {
438 let shift = Transform { rotation : glam::DMat3::IDENTITY, translation : DVec3::new(1.0, 0.0, 0.0) };
439 let geo = geometry(vec![
440 Shape::Box { half_lengths : DVec3::splat(2.0) },
441 Shape::Box { half_lengths : DVec3::splat(1.0) },
442 Shape::Boolean { op : BooleanOp::Subtraction, first : 0, second : 1, second_transform : Transform::IDENTITY },
443 Shape::Boolean { op : BooleanOp::Intersection, first : 0, second : 1, second_transform : shift },
444 Shape::Boolean { op : BooleanOp::Union, first : 1, second : 1, second_transform : shift },
445 ]);
446 let rc = SolidRaycaster::new(&geo);
447 let x0 = DVec3::new(-5.0, 0.0, 0.0);
448 assert_intervals(rc.intervals(&geo, 2, x0, DVec3::X, -10.0, 10.0), &[(3.0, 4.0), (6.0, 7.0)]);
449 assert_intervals(rc.intervals(&geo, 3, x0, DVec3::X, -10.0, 10.0), &[(5.0, 7.0)]);
450 assert_intervals(rc.intervals(&geo, 4, x0, DVec3::X, -10.0, 10.0), &[(4.0, 7.0)]);
451 assert_eq!(*rc.bounds(3), Aabb { min : DVec3::new(0.0, -1.0, -1.0), max : DVec3::new(2.0, 1.0, 1.0) });
452 }
453
454 #[test]
455 fn mesh_edges_and_vertices() {
456 let geo = geometry(vec![cube()]);
457 let rc = SolidRaycaster::new(&geo);
458 assert_intervals(rc.intervals(&geo, 0, DVec3::new(-5.0, 0.3, 0.2), DVec3::X, -10.0, 10.0), &[(4.0, 6.0)]);
460 assert_intervals(rc.intervals(&geo, 0, DVec3::new(0.0, 0.0, -5.0), DVec3::Z, -10.0, 10.0), &[(4.0, 6.0)]);
462 let d = DVec3::new(1.0, 1.0, 0.0).normalize();
464 let s = 2.0f64.sqrt();
465 assert_intervals(rc.intervals(&geo, 0, DVec3::new(-2.0, -2.0, 0.3), d, -10.0, 10.0), &[(s, 3.0*s)]);
466 let d = DVec3::ONE.normalize();
468 let s = 3.0f64.sqrt();
469 assert_intervals(rc.intervals(&geo, 0, DVec3::splat(-2.0), d, -10.0, 10.0), &[(s, 3.0*s)]);
470 assert_intervals(rc.intervals(&geo, 0, DVec3::ZERO, DVec3::X, 0.0, 10.0), &[(0.0, 1.0)]);
472 assert_intervals(rc.intervals(&geo, 0, DVec3::new(-5.0, 1.5, 0.0), DVec3::X, -10.0, 10.0), &[]);
474 }
475
476 #[test]
477 fn open_mesh_is_detected() {
478 let Shape::Tessellated { vertices, mut triangles } = cube() else { unreachable!() };
479 triangles.retain(|tri| !tri.iter().all(|&i| vertices[i as usize].x > 0.0));
481 let geo = geometry(vec![Shape::Tessellated { vertices, triangles }]);
482 let rc = SolidRaycaster::new(&geo);
483 assert!(rc.intervals(&geo, 0, DVec3::new(-5.0, 0.3, 0.2), DVec3::X, -10.0, 10.0).is_none());
484 assert_intervals(rc.intervals(&geo, 0, DVec3::new(0.3, -5.0, 0.2), DVec3::Y, -10.0, 10.0), &[(4.0, 6.0)]);
486 }
487
488 #[test]
489 fn mesh_volume() {
490 let vertices = vec![DVec3::ZERO, DVec3::new(3.0, 0.0, 0.0), DVec3::new(0.0, 2.0, 0.0), DVec3::new(0.0, 0.0, 1.0)];
493 let triangles = vec![[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3]];
494 let geo = geometry(vec![Shape::Tessellated { vertices, triangles }]);
495 let rc = SolidRaycaster::new(&geo);
496 let n = 500;
497 let dir = DVec3::new(0.1, 0.2, 1.0).normalize();
498 let mut volume = 0.0;
499 for i in 0..n {
500 for j in 0..n {
501 let (u, v) = (-5.0 + 10.0*(i as f64 + 0.5)/n as f64, -5.0 + 10.0*(j as f64 + 0.5)/n as f64);
503 let e1 = dir.any_orthonormal_vector();
504 let e2 = dir.cross(e1);
505 let o = u*e1 + v*e2 - 10.0*dir;
506 let iv = rc.intervals(&geo, 0, o, dir, -100.0, 100.0).unwrap();
507 volume += iv.iter().map(|(t0, t1)| t1 - t0).sum::<f64>()*(10.0/n as f64).powi(2);
508 }
509 }
510 assert!((volume - 1.0).abs() < 0.01, "volume {volume}");
511 }
512}