1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#![allow(clippy::needless_range_loop)] // This tends to make the traversal code much more verbose that necessary.

use crate::bounding_volume::{Aabb, SimdAabb};
use crate::math::Real;
use crate::partitioning::visitor::SimdSimultaneousVisitStatus;
use crate::partitioning::{
    GenericQbvh, QbvhStorage, SimdBestFirstVisitStatus, SimdBestFirstVisitor,
    SimdSimultaneousVisitor, SimdVisitStatus, SimdVisitor,
};
use crate::simd::SIMD_WIDTH;
use crate::utils::Array1;
use crate::utils::WeightedValue;
use num::Bounded;
use simba::simd::SimdBool;
use std::collections::BinaryHeap;
#[cfg(feature = "parallel")]
use {
    crate::partitioning::{ParallelSimdSimultaneousVisitor, ParallelSimdVisitor},
    arrayvec::ArrayVec,
    rayon::prelude::*,
    std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering},
};

use super::{IndexedData, NodeIndex, Qbvh};

impl<LeafData: IndexedData, Storage: QbvhStorage<LeafData>> GenericQbvh<LeafData, Storage> {
    /// Performs a depth-first traversal on the BVH.
    ///
    /// # Return
    ///
    /// Returns `false` if the traversal exitted early, and `true` otherwise.
    pub fn traverse_depth_first(&self, visitor: &mut impl SimdVisitor<LeafData, SimdAabb>) -> bool {
        self.traverse_depth_first_node(visitor, 0)
    }

    /// Performs a depth-first traversal on the BVH, starting at the given node.
    ///
    /// # Return
    ///
    /// Returns `false` if the traversal exitted early, and `true` otherwise.
    pub fn traverse_depth_first_node(
        &self,
        visitor: &mut impl SimdVisitor<LeafData, SimdAabb>,
        start_node: u32,
    ) -> bool {
        self.traverse_depth_first_node_with_stack(visitor, &mut Vec::new(), start_node)
    }

    /// Performs a depth-first traversal on the BVH.
    ///
    /// # Return
    ///
    /// Returns `false` if the traversal exited early, and `true` otherwise.
    pub fn traverse_depth_first_with_stack(
        &self,
        visitor: &mut impl SimdVisitor<LeafData, SimdAabb>,
        stack: &mut Vec<u32>,
    ) -> bool {
        self.traverse_depth_first_node_with_stack(visitor, stack, 0)
    }

    /// Performs a depth-first traversal on the BVH.
    ///
    /// # Return
    ///
    /// Returns `false` if the traversal exited early, and `true` otherwise.
    pub fn traverse_depth_first_node_with_stack(
        &self,
        visitor: &mut impl SimdVisitor<LeafData, SimdAabb>,
        stack: &mut Vec<u32>,
        start_node: u32,
    ) -> bool {
        stack.clear();

        if !self.nodes.is_empty() {
            stack.push(start_node);
        }
        while let Some(entry) = stack.pop() {
            let node = &self.nodes[entry as usize];
            let leaf_data = if node.is_leaf() {
                Some(
                    array![|ii| Some(&self.proxies.get_at(node.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            match visitor.visit(&node.simd_aabb, leaf_data) {
                SimdVisitStatus::ExitEarly => {
                    return false;
                }
                SimdVisitStatus::MaybeContinue(mask) => {
                    let bitmask = mask.bitmask();

                    for ii in 0..SIMD_WIDTH {
                        if (bitmask & (1 << ii)) != 0 && !node.is_leaf() {
                            // Internal node, visit the child.
                            // Un fortunately, we have this check because invalid Aabbs
                            // return a hit as well.
                            if node.children[ii] as usize <= self.nodes.len() {
                                stack.push(node.children[ii]);
                            }
                        }
                    }
                }
            }
        }

        true
    }

    /// Performs a best-first-search on the BVH.
    ///
    /// Returns the content of the leaf with the smallest associated cost, and a result of
    /// user-defined type.
    pub fn traverse_best_first<BFS>(&self, visitor: &mut BFS) -> Option<(NodeIndex, BFS::Result)>
    where
        BFS: SimdBestFirstVisitor<LeafData, SimdAabb>,
        BFS::Result: Clone, // Because we cannot move out of an array…
    {
        self.traverse_best_first_node(visitor, 0, Real::max_value())
    }

    /// Performs a best-first-search on the BVH, starting at the given node.
    ///
    /// Returns the content of the leaf with the smallest associated cost, and a result of
    /// user-defined type.
    pub fn traverse_best_first_node<BFS>(
        &self,
        visitor: &mut BFS,
        start_node: u32,
        init_cost: Real,
    ) -> Option<(NodeIndex, BFS::Result)>
    where
        BFS: SimdBestFirstVisitor<LeafData, SimdAabb>,
        BFS::Result: Clone, // Because we cannot move out of an array…
    {
        if self.nodes.is_empty() {
            return None;
        }

        let mut queue: BinaryHeap<WeightedValue<u32>> = BinaryHeap::new();

        let mut best_cost = init_cost;
        let mut best_result = None;
        queue.push(WeightedValue::new(start_node, -best_cost / 2.0));

        while let Some(entry) = queue.pop() {
            if -entry.cost >= best_cost {
                // No BV left in the tree that has a lower cost than best_result
                break; // Solution found.
            }

            let node = &self.nodes[entry.value as usize];
            let leaf_data = if node.is_leaf() {
                Some(
                    array![|ii| Some(&self.proxies.get_at(node.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            match visitor.visit(best_cost, &node.simd_aabb, leaf_data) {
                SimdBestFirstVisitStatus::ExitEarly(result) => {
                    return result.map(|r| (node.parent, r)).or(best_result);
                }
                SimdBestFirstVisitStatus::MaybeContinue {
                    weights,
                    mask,
                    results,
                } => {
                    let bitmask = mask.bitmask();
                    let weights: [Real; SIMD_WIDTH] = weights.into();

                    for ii in 0..SIMD_WIDTH {
                        if (bitmask & (1 << ii)) != 0 {
                            if node.is_leaf() {
                                if weights[ii] < best_cost && results[ii].is_some() {
                                    // We found a leaf!
                                    if let Some(proxy) =
                                        self.proxies.get_at(node.children[ii] as usize)
                                    {
                                        best_cost = weights[ii];
                                        best_result =
                                            Some((proxy.node, results[ii].clone().unwrap()))
                                    }
                                }
                            } else {
                                // Internal node, visit the child.
                                // Un fortunately, we have this check because invalid Aabbs
                                // return a hit as well.
                                if (node.children[ii] as usize) < self.nodes.len() {
                                    queue.push(WeightedValue::new(node.children[ii], -weights[ii]));
                                }
                            }
                        }
                    }
                }
            }
        }

        best_result
    }

    /// Retrieve all the data of the nodes with Aabbs intersecting
    /// the given Aabb:
    // FIXME: implement a visitor pattern to merge intersect_aabb
    // and intersect_ray into a single method.
    pub fn intersect_aabb(&self, aabb: &Aabb, out: &mut Vec<LeafData>) {
        if self.nodes.is_empty() {
            return;
        }

        // Special case for the root.
        let mut stack = vec![0u32];
        let simd_aabb = SimdAabb::splat(*aabb);
        while let Some(inode) = stack.pop() {
            let node = &self.nodes[inode as usize];
            let intersections = node.simd_aabb.intersects(&simd_aabb);
            let bitmask = intersections.bitmask();

            for ii in 0..SIMD_WIDTH {
                if (bitmask & (1 << ii)) != 0 {
                    if node.is_leaf() {
                        // We found a leaf!
                        // Unfortunately, invalid Aabbs return a intersection as well.
                        if let Some(proxy) = self.proxies.get_at(node.children[ii] as usize) {
                            out.push(proxy.data);
                        }
                    } else {
                        // Internal node, visit the child.
                        // Unfortunately, we have this check because invalid Aabbs
                        // return a intersection as well.
                        if node.children[ii] as usize <= self.nodes.len() {
                            stack.push(node.children[ii]);
                        }
                    }
                }
            }
        }
    }

    /// Performs a simultaneous traversal of two Qbvh.
    pub fn traverse_bvtt<LeafData2: IndexedData>(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &mut impl SimdSimultaneousVisitor<LeafData, LeafData2, SimdAabb>,
    ) {
        self.traverse_bvtt_with_stack(qbvh2, visitor, &mut Vec::new())
    }

    /// Performs a simultaneous traversal of two Qbvh.
    pub fn traverse_bvtt_with_stack<LeafData2: IndexedData>(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &mut impl SimdSimultaneousVisitor<LeafData, LeafData2, SimdAabb>,
        stack: &mut Vec<(u32, u32)>,
    ) {
        let qbvh1 = self;
        stack.clear();

        if !qbvh1.nodes.is_empty() && !qbvh2.nodes.is_empty() {
            stack.push((0, 0));
        }

        while let Some(entry) = stack.pop() {
            let node1 = &qbvh1.nodes[entry.0 as usize];
            let node2 = &qbvh2.nodes[entry.1 as usize];

            let leaf_data1 = if node1.is_leaf() {
                Some(
                    array![|ii| Some(&qbvh1.proxies.get_at(node1.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            let leaf_data2 = if node2.is_leaf() {
                Some(
                    array![|ii| Some(&qbvh2.proxies.get_at(node2.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            match visitor.visit(&node1.simd_aabb, leaf_data1, &node2.simd_aabb, leaf_data2) {
                SimdSimultaneousVisitStatus::ExitEarly => {
                    return;
                }
                SimdSimultaneousVisitStatus::MaybeContinue(mask) => {
                    match (node1.is_leaf(), node2.is_leaf()) {
                        (true, true) => { /* Can’t go deeper. */ }
                        (true, false) => {
                            let mut bitmask = 0;
                            for ii in 0..SIMD_WIDTH {
                                bitmask |= mask[ii].bitmask();
                            }

                            for jj in 0..SIMD_WIDTH {
                                if (bitmask & (1 << jj)) != 0
                                    && node2.children[jj] as usize <= qbvh2.nodes.len()
                                {
                                    stack.push((entry.0, node2.children[jj]));
                                }
                            }
                        }
                        (false, true) => {
                            for ii in 0..SIMD_WIDTH {
                                let bitmask = mask[ii].bitmask();

                                if bitmask != 0 && node1.children[ii] as usize <= qbvh1.nodes.len()
                                {
                                    stack.push((node1.children[ii], entry.1));
                                }
                            }
                        }
                        (false, false) => {
                            for ii in 0..SIMD_WIDTH {
                                let bitmask = mask[ii].bitmask();

                                for jj in 0..SIMD_WIDTH {
                                    if (bitmask & (1 << jj)) != 0
                                        && node1.children[ii] as usize <= qbvh1.nodes.len()
                                        && node2.children[jj] as usize <= qbvh2.nodes.len()
                                    {
                                        stack.push((node1.children[ii], node2.children[jj]));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Performs a simultaneous traversal of two Qbvh.
    pub fn traverse_modified_bvtt<LeafData2: IndexedData>(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &mut impl SimdSimultaneousVisitor<LeafData, LeafData2, SimdAabb>,
    ) {
        self.traverse_modified_bvtt_with_stack(qbvh2, visitor, &mut Vec::new())
    }

    /// Performs a simultaneous traversal of two Qbvh.
    pub fn traverse_modified_bvtt_with_stack<LeafData2: IndexedData>(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &mut impl SimdSimultaneousVisitor<LeafData, LeafData2, SimdAabb>,
        stack: &mut Vec<(u32, u32)>,
    ) {
        let qbvh1 = self;
        stack.clear();

        if !qbvh1.nodes.is_empty() && !qbvh2.nodes.is_empty() && qbvh1.nodes[0].is_changed() {
            stack.push((0, 0));
        }

        while let Some(entry) = stack.pop() {
            let node1 = &qbvh1.nodes[entry.0 as usize];
            let node2 = &qbvh2.nodes[entry.1 as usize];

            if !node1.is_changed() {
                continue;
            }

            let leaf_data1 = if node1.is_leaf() {
                Some(
                    array![|ii| Some(&qbvh1.proxies.get_at(node1.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            let leaf_data2 = if node2.is_leaf() {
                Some(
                    array![|ii| Some(&qbvh2.proxies.get_at(node2.children[ii] as usize)?.data); SIMD_WIDTH],
                )
            } else {
                None
            };

            match visitor.visit(&node1.simd_aabb, leaf_data1, &node2.simd_aabb, leaf_data2) {
                SimdSimultaneousVisitStatus::ExitEarly => {
                    return;
                }
                SimdSimultaneousVisitStatus::MaybeContinue(mask) => {
                    match (node1.is_leaf(), node2.is_leaf()) {
                        (true, true) => { /* Can’t go deeper. */ }
                        (true, false) => {
                            let mut bitmask = 0;
                            for ii in 0..SIMD_WIDTH {
                                bitmask |= mask[ii].bitmask();
                            }

                            for jj in 0..SIMD_WIDTH {
                                if (bitmask & (1 << jj)) != 0
                                    && node2.children[jj] as usize <= qbvh2.nodes.len()
                                {
                                    stack.push((entry.0, node2.children[jj]));
                                }
                            }
                        }
                        (false, true) => {
                            for ii in 0..SIMD_WIDTH {
                                let bitmask = mask[ii].bitmask();

                                if bitmask != 0 && node1.children[ii] as usize <= qbvh1.nodes.len()
                                {
                                    stack.push((node1.children[ii], entry.1));
                                }
                            }
                        }
                        (false, false) => {
                            for ii in 0..SIMD_WIDTH {
                                let bitmask = mask[ii].bitmask();

                                for jj in 0..SIMD_WIDTH {
                                    if (bitmask & (1 << jj)) != 0
                                        && node1.children[ii] as usize <= qbvh1.nodes.len()
                                        && node2.children[jj] as usize <= qbvh2.nodes.len()
                                    {
                                        stack.push((node1.children[ii], node2.children[jj]));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(feature = "parallel")]
impl<LeafData: IndexedData + Sync> Qbvh<LeafData> {
    /// Performs a depth-first traversal of two Qbvh using
    /// parallelism internally for better performances with large tree.
    pub fn traverse_depth_first_parallel(&self, visitor: &impl ParallelSimdVisitor<LeafData>) {
        if !self.nodes.is_empty() {
            let exit_early = AtomicBool::new(false);
            self.traverse_depth_first_node_parallel(visitor, &exit_early, 0);
        }
    }

    /// Runs a parallel depth-first traversal of the sub-tree starting at the given node.
    pub fn traverse_depth_first_node_parallel(
        &self,
        visitor: &impl ParallelSimdVisitor<LeafData>,
        exit_early: &AtomicBool,
        entry: u32,
    ) {
        if exit_early.load(AtomicOrdering::Relaxed) {
            return;
        }

        let mut stack: ArrayVec<u32, SIMD_WIDTH> = ArrayVec::new();
        let node = &self.nodes[entry as usize];
        let leaf_data = if node.is_leaf() {
            Some(
                array![|ii| Some(&self.proxies.get_at(node.children[ii] as usize)?.data); SIMD_WIDTH],
            )
        } else {
            None
        };

        match visitor.visit(entry, node, leaf_data) {
            SimdVisitStatus::ExitEarly => {
                exit_early.store(true, AtomicOrdering::Relaxed);
                return;
            }
            SimdVisitStatus::MaybeContinue(mask) => {
                let bitmask = mask.bitmask();

                for ii in 0..SIMD_WIDTH {
                    if (bitmask & (1 << ii)) != 0 {
                        if !node.is_leaf() {
                            // Internal node, visit the child.
                            // Un fortunately, we have this check because invalid Aabbs
                            // return a hit as well.
                            if node.children[ii] as usize <= self.nodes.len() {
                                stack.push(node.children[ii]);
                            }
                        }
                    }
                }
            }
        }

        stack
            .as_slice()
            .par_iter()
            .copied()
            .for_each(|entry| self.traverse_depth_first_node_parallel(visitor, exit_early, entry));
    }

    /// Performs a simultaneous traversal of two Qbvh using
    /// parallelism internally for better performances with large tree.
    pub fn traverse_bvtt_parallel<
        LeafData2: IndexedData + Sync,
        Visitor: ParallelSimdSimultaneousVisitor<LeafData, LeafData2>,
    >(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &Visitor,
    ) {
        if !self.nodes.is_empty() && !qbvh2.nodes.is_empty() {
            let exit_early = AtomicBool::new(false);
            self.traverse_bvtt_node_parallel(
                qbvh2,
                visitor,
                &exit_early,
                Visitor::Data::default(),
                (0, 0),
            );
        }
    }

    /// Runs a parallel simultaneous traversal of the sub-tree starting at the given nodes.
    pub fn traverse_bvtt_node_parallel<
        LeafData2: IndexedData + Sync,
        Visitor: ParallelSimdSimultaneousVisitor<LeafData, LeafData2>,
    >(
        &self,
        qbvh2: &Qbvh<LeafData2>,
        visitor: &Visitor,
        exit_early: &AtomicBool,
        data: Visitor::Data,
        entry: (u32, u32),
    ) {
        if exit_early.load(AtomicOrdering::Relaxed) {
            return;
        }

        let qbvh1 = self;
        let node1 = &qbvh1.nodes[entry.0 as usize];
        let node2 = &qbvh2.nodes[entry.1 as usize];

        const SQUARE_SIMD_WIDTH: usize = SIMD_WIDTH * SIMD_WIDTH;
        let mut stack: ArrayVec<(u32, u32), SQUARE_SIMD_WIDTH> = ArrayVec::new();

        let leaf_data1 = if node1.is_leaf() {
            Some(
                array![|ii| Some(&qbvh1.proxies.get_at(node1.children[ii] as usize)?.data); SIMD_WIDTH],
            )
        } else {
            None
        };

        let leaf_data2 = if node2.is_leaf() {
            Some(
                array![|ii| Some(&qbvh2.proxies.get_at(node2.children[ii] as usize)?.data); SIMD_WIDTH],
            )
        } else {
            None
        };

        let (status, data) = visitor.visit(
            entry.0, &node1, leaf_data1, entry.1, &node2, leaf_data2, data,
        );

        match status {
            SimdSimultaneousVisitStatus::ExitEarly => {
                exit_early.store(true, AtomicOrdering::Relaxed);
                return;
            }
            SimdSimultaneousVisitStatus::MaybeContinue(mask) => {
                match (node1.is_leaf(), node2.is_leaf()) {
                    (true, true) => { /* Can’t go deeper. */ }
                    (true, false) => {
                        let mut bitmask = 0;
                        for ii in 0..SIMD_WIDTH {
                            bitmask |= mask[ii].bitmask();
                        }

                        for jj in 0..SIMD_WIDTH {
                            if (bitmask & (1 << jj)) != 0 {
                                if node2.children[jj] as usize <= qbvh2.nodes.len() {
                                    stack.push((entry.0, node2.children[jj]));
                                }
                            }
                        }
                    }
                    (false, true) => {
                        for ii in 0..SIMD_WIDTH {
                            let bitmask = mask[ii].bitmask();

                            if bitmask != 0 {
                                if node1.children[ii] as usize <= qbvh1.nodes.len() {
                                    stack.push((node1.children[ii], entry.1));
                                }
                            }
                        }
                    }
                    (false, false) => {
                        for ii in 0..SIMD_WIDTH {
                            let bitmask = mask[ii].bitmask();

                            for jj in 0..SIMD_WIDTH {
                                if (bitmask & (1 << jj)) != 0 {
                                    if node1.children[ii] as usize <= qbvh1.nodes.len()
                                        && node2.children[jj] as usize <= qbvh2.nodes.len()
                                    {
                                        stack.push((node1.children[ii], node2.children[jj]));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        stack.as_slice().par_iter().copied().for_each(|entry| {
            self.traverse_bvtt_node_parallel(qbvh2, visitor, exit_early, data, entry)
        });
    }
}