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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// mlodato, 20190806
use crate::geom::{
Bounds,
BoxTestGeometry,
IndexGenerator,
RayTestGeometry,
SystemBounds,
TestGeometry,
VecDim,
};
use crate::index::SpatialIndex;
use crate::traits::ObjectID;
use cgmath::prelude::*;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use std::fmt::Debug;
use std::ops::DerefMut;
#[cfg(feature="parallel")]
use rayon::prelude::*;
#[cfg(feature="parallel")]
use std::cell::{RefMut, RefCell};
#[cfg(feature="parallel")]
use thread_local::CachedThreadLocal;
/// [`SpatialIndex`]: trait.SpatialIndex.html
/// [`Index64_3D`]: struct.Index64_3D.html
/// A group of collision data
///
/// `Index` must be a type implmenting [`SpatialIndex`], such as [`Index64_3D`]
///
/// `ID` is the type representing object IDs
#[derive(Default)]
#[cfg_attr(any(test, feature="serde"), derive(Deserialize, Serialize))]
pub struct Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{
// persistant state:
min_depth: u32,
tree: (Vec<(Index, ID)>, bool),
// temporary data used within a method:
#[cfg_attr(any(test, feature="serde"), serde(skip))]
collisions: Vec<(ID, ID)>,
#[cfg_attr(any(test, feature="serde"), serde(skip))]
test_results: Vec<ID>,
#[cfg_attr(any(test, feature="serde"), serde(skip))]
processed: FxHashSet<ID>,
#[cfg_attr(any(test, feature="serde"), serde(skip))]
invalid: Vec<ID>,
#[cfg(feature="parallel")]
#[cfg_attr(any(test, feature="serde"), serde(skip))]
collisions_tls: CachedThreadLocal<RefCell<Vec<(ID, ID)>>>,
}
impl<Index, ID> Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{
/// Iterate over all indices in the `Layer`
///
/// This is primarily intended for visualization + debugging
pub fn iter(&self) -> std::slice::Iter<'_, (Index, ID)> {
self.tree.0.iter()
}
/// Clear all index-ID pairs
pub fn clear(&mut self) {
let (tree, sorted) = &mut self.tree;
tree.clear();
*sorted = true;
}
/// Append multiple objects to the `Layer`
///
/// Complex geometry may provide multiple bounds for a single object ID; this usage would be common
/// for static geometry, as it prevents extraneous self-collisions
pub fn extend<Iter, Point_>(&mut self, system_bounds: Bounds<Point_>, objects: Iter)
where
Iter: std::iter::Iterator<Item = (Bounds<Point_>, ID)>,
Point_: EuclideanSpace<Scalar = f32>,
Point_::Diff: ElementWise,
Bounds<Point_>: SystemBounds<Point_, Index::Point>
{
let (tree, sorted) = &mut self.tree;
if let (_, Some(max_objects)) = objects.size_hint() {
tree.reserve(max_objects);
}
for (bounds, id) in objects {
if !system_bounds.contains(bounds) {
self.invalid.push(id);
continue
}
tree.extend(system_bounds
.to_local(bounds)
.indices(Some(self.min_depth))
.into_iter()
.map(|index| (index, id)));
*sorted = false;
}
}
/// Merge another `Layer` into this `Layer`
///
/// This may be used, for example, to merge static scene `Layer` into the current
/// frames' dynamic `Layer` without having to recalculate indices for the static data
pub fn merge(&mut self, other: &Layer<Index, ID>) {
let (lhs_tree, sorted) = &mut self.tree;
let (rhs_tree, _) = &other.tree;
if other.min_depth < self.min_depth {
warn!("merging layer of lesser min_depth (lhs: {}, rhs: {})", self.min_depth, other.min_depth);
self.min_depth = other.min_depth;
}
lhs_tree.extend(rhs_tree.iter());
*sorted = false;
}
/// [`par_scan_filtered`]: struct.Layer.html#method.par_scan_filtered
/// [`par_scan`]: struct.Layer.html#method.par_scan
/// Sort indices to ready data for detection (parallel)
///
/// This will be called implicitly when necessary (i.e. by [`par_scan_filtered`], [`par_scan`], etc.)
#[cfg(feature="parallel")]
pub fn par_sort(&mut self) {
let (tree, sorted) = &mut self.tree;
if !*sorted {
tree.par_sort_unstable();
*sorted = true;
}
}
/// [`scan_filtered`]: struct.Layer.html#method.scan_filtered
/// [`scan`]: struct.Layer.html#method.scan
/// Sort indices to ready data for detection
///
/// This will be called implicitly when necessary (i.e. by [`scan_filtered`], [`scan`], etc.)
pub fn sort(&mut self) {
let (tree, sorted) = &mut self.tree;
if !*sorted {
tree.sort_unstable();
*sorted = true;
}
}
fn test_impl<TestGeom, Callback>(
tree: &[(Index, ID)],
cell: Index,
test_geom: &TestGeom,
mut nearest: f32,
max_depth: Option<u32>,
callback: &mut Callback) -> f32
where
TestGeom: TestGeometry,
Callback: FnMut(&TestGeom, f32, ID) -> f32
{
use std::cmp::Ordering::{Less, Greater};
if tree.is_empty() || !test_geom.should_test(nearest) {
return nearest;
}
if tree.first().unwrap().0 < cell || !cell.overlaps(tree.last().unwrap().0) {
panic!("test_impl called with non-overlapping indices");
}
let depth = cell.depth();
if let Some(max_depth) = max_depth {
if depth >= max_depth {
return tree.iter()
.map(|(_, id)| *id)
.fold(nearest, |nearest, id|
callback(test_geom, nearest, id).min(nearest));
}
}
if let Some(sub_cells) = cell.subdivide() {
let mut sub_trees = sub_cells.as_ref().iter()
.map(|cell| Some(*cell))
.chain((0..1).map(|_| None))
.scan(tree, |tree, cell| {
if let Some(cell) = cell {
let i = tree.binary_search_by(|&(index, _)| {
if index < cell { Less } else { Greater }
}).err().unwrap();
let (head, tail) = tree.split_at(i);
*tree = tail;
Some(head)
} else {
Some(tree)
}
});
nearest = sub_trees.next().unwrap().iter()
.map(|(_, id)| *id)
.fold(nearest, |nearest, id|
callback(test_geom, nearest, id).min(nearest));
let sub_trees: SmallVec<[_; 8]> = sub_trees.collect();
let sub_tests = test_geom.subdivide();
for &i in test_geom.test_order().as_ref() {
nearest = Self::test_impl(
sub_trees[i],
sub_cells.as_ref()[i],
&sub_tests.as_ref()[i],
nearest,
max_depth,
callback);
}
nearest
} else {
tree.iter()
.map(|(_, id)| *id)
.fold(nearest, |nearest, id|
callback(test_geom, nearest, id).min(nearest))
}
}
/// Run a single test on some geometry
///
/// This occurs by repeatedly subdividing both this `Layer`'s index-ID list and the provided
/// `test_geom`, returning any items at a given depth where both the resulting index list
/// is non-empty and [`TestGeometry::subdivide`] returns a result
///
/// _note: this method may do an implicit, non-parallel sort; you may call [`par_sort`] prior
/// to calling this method to perform a parallel sort instead_
///
/// [`TestGeometry::subdivide`]: trait.TestGeometry.html#tymethod.subdivide
/// [`par_sort`]: #method.par_sort
pub fn test<'a, TestGeom>(
&'a mut self,
test_geom: &TestGeom,
max_depth: Option<u32>) -> &'a Vec<ID>
where
TestGeom: TestGeometry
{
self.sort();
self.test_results.clear();
let (tree, _) = &self.tree;
let results = &mut self.test_results;
Self::test_impl(
tree,
Index::default(),
test_geom,
std::f32::INFINITY,
max_depth,
&mut |_, nearest, id| {
results.push(id);
nearest
});
results.sort();
results.dedup();
results
}
/// A special case of [`test`] for bounding box tests, see [`BoxTestGeometry`]
///
/// The `system_bounds` provided to this method should, in most cases, be identical to the
/// `system_bounds` provided to [`extend`]
///
/// _note: this method may do an implicit, non-parallel sort; you may call [`par_sort`] prior
/// to calling this method to perform a parallel sort instead_
///
/// [`test`]: #method.test
/// [`extend`]: #method.extend
/// [`par_sort`]: #method.par_sort
/// [`BoxTestGeometry`]: struct.BoxTestGeometry.html
pub fn test_box<'a, Point_>(
&'a mut self,
system_bounds: Bounds<Point_>,
test_bounds: Bounds<Point_>,
max_depth: Option<u32>) -> &'a Vec<ID>
where
Point_: EuclideanSpace<Scalar = f32> + Debug,
Point_::Diff: ElementWise + std::ops::Index<usize, Output = f32> + Debug,
BoxTestGeometry<Point_>: TestGeometry
{
let test_geom = BoxTestGeometry::with_system_bounds(
system_bounds,
test_bounds);
self.test(
&test_geom,
max_depth);
&self.test_results
}
/// A special case of [`test`] for ray-testing, see [`RayTestGeometry`]
///
/// The `system_bounds` provided to this method should, in most cases, be identical to the
/// `system_bounds` provided to [`extend`]
///
/// _note: this method may do an implicit, non-parallel sort; you may call [`par_sort`] prior
/// to calling this method to perform a parallel sort instead_
///
/// [`test`]: #method.test
/// [`extend`]: #method.extend
/// [`par_sort`]: #method.par_sort
/// [`RayTestGeometry`]: struct.RayTestGeometry.html
pub fn test_ray<'a, Point_>(
&'a mut self,
system_bounds: Bounds<Point_>,
origin : Point_,
direction: Point_::Diff,
range_min: f32,
range_max: f32,
max_depth: Option<u32>) -> &'a Vec<ID>
where
Point_: EuclideanSpace<Scalar = f32> + VecDim + Debug,
Point_::Diff: ElementWise + std::ops::Index<usize, Output = f32> + Debug,
RayTestGeometry<Point_>: TestGeometry
{
let test_geom = RayTestGeometry::with_system_bounds(
system_bounds,
origin,
direction,
range_min,
range_max);
self.test(
&test_geom,
max_depth);
&self.test_results
}
/// Run a picking or hit-test operation
///
/// This is implemented similarly to [`test`], but differs in that it returns only the nearest
/// result and may stop searching as soon as the nearest result is found
///
/// _note: this method may do an implicit, non-parallel sort; you may call [`par_sort`] prior
/// to calling this method to perform a parallel sort instead_
///
/// [`test`]: #method.test
/// [`par_sort`]: #method.par_sort
pub fn pick<TestGeom, GetDist>(
&mut self,
test_geom: &TestGeom,
max_dist: f32,
max_depth: Option<u32>,
mut get_dist: GetDist) -> Option<(f32, ID)>
where
TestGeom: TestGeometry,
GetDist: FnMut(&TestGeom, f32, ID) -> f32
{
self.sort();
self.processed.clear();
let (tree, _) = &self.tree;
let processed = &mut self.processed;
let mut result: Option<ID> = None;
let dist = Self::test_impl(
tree,
Index::default(),
test_geom,
max_dist,
max_depth,
&mut |test_geom, nearest, id| {
if processed.insert(id) {
let dist = get_dist(test_geom, nearest, id);
if dist.is_finite() {
if dist < nearest {
result = Some(id);
}
dist
} else {
std::f32::INFINITY
}
} else {
std::f32::INFINITY
}
});
result.map(|id| (dist, id))
}
/// A special case of [`pick`] for ray-testing, see [`RayTestGeometry`]
///
/// The `system_bounds` provided to this method should, in most cases, be identical to the
/// `system_bounds` provided to [`extend`]
///
/// _note: this method may do an implicit, non-parallel sort; you may call [`par_sort`] prior
/// to calling this method to perform a parallel sort instead_
///
/// [`pick`]: #method.pick
/// [`extend`]: #method.extend
/// [`par_sort`]: #method.par_sort
/// [`RayTestGeometry`]: struct.RayTestGeometry.html
pub fn pick_ray<Point_, GetDist>(
&mut self,
system_bounds: Bounds<Point_>,
origin : Point_,
direction: Point_::Diff,
max_dist: f32,
max_depth: Option<u32>,
mut get_dist: GetDist) -> Option<(f32, ID, Point_)>
where
Point_: EuclideanSpace<Scalar = f32> + VecDim + Debug,
Point_::Diff: VectorSpace<Scalar = f32> + ElementWise + std::ops::Index<usize, Output = f32> + Debug,
RayTestGeometry<Point_>: TestGeometry,
GetDist: FnMut(&Point_, &Point_::Diff, f32, ID) -> f32
{
let test_geom = RayTestGeometry::with_system_bounds(
system_bounds,
origin,
direction,
0f32,
max_dist);
self.pick(&test_geom, max_dist, max_depth, |_, max_dist, id| {
get_dist(&origin, &direction, max_dist, id)
})
.map(|(dist, id)| {
let point = origin + direction * dist;
(dist, id, point)
})
}
/// Detects collisions between all objects in the `Layer`
pub fn scan<'a>(&'a mut self)
-> &'a Vec<(ID, ID)>
{
self.scan_filtered(|_, _| true)
}
/// Detects collisions between all objects in the `Layer`, returning only those which pass a user-specified test
///
/// Collisions are filtered prior to duplicate removal. This may be faster or slower than filtering
/// post-duplicate-removal (i.e. by `scan().iter().filter()`) depending on the complexity
/// of the filter.
pub fn scan_filtered<'a, F>(&'a mut self, filter: F)
-> &'a Vec<(ID, ID)>
where
F: FnMut(ID, ID) -> bool
{
self.sort();
self.collisions.clear();
self.invalid.clear();
let (tree, _) = &self.tree;
Self::scan_impl(tree.as_slice(), &mut self.collisions, filter);
self.collisions.sort_unstable();
self.collisions.dedup();
&self.collisions
}
/// [`scan`]: struct.Layer.html#method.scan
/// Parallel version of [`scan`]
#[cfg(feature="parallel")]
pub fn par_scan<'a>(&'a mut self)
-> &'a Vec<(ID, ID)>
where
Index: Send + Sync
{
self.par_scan_filtered(|_, _| true)
}
/// [`scan_filtered`]: struct.Layer.html#method.scan_filtered
/// Parallel version of [`scan_filtered`]
#[cfg(feature="parallel")]
pub fn par_scan_filtered<'a, F>(&'a mut self, filter: F)
-> &'a Vec<(ID, ID)>
where
Index: Send + Sync,
F: Copy + Send + Sync + FnMut(ID, ID) -> bool
{
self.par_sort();
self.collisions.clear();
self.invalid.clear();
for set in self.collisions_tls.iter_mut() {
set.borrow_mut().clear();
}
self.par_scan_impl(rayon::current_num_threads(), self.tree.0.as_slice(), filter);
for set in self.collisions_tls.iter_mut() {
use std::borrow::Borrow;
let set_: RefMut<Vec<(ID, ID)>> = set.borrow_mut();
let set__: &Vec<(ID, ID)> = set_.borrow();
self.collisions.extend(set__.iter());
}
self.collisions.par_sort_unstable();
self.collisions.dedup();
&self.collisions
}
#[cfg(feature="parallel")]
fn par_scan_impl<F>(&self, threads: usize, tree: &[(Index, ID)], filter: F)
where
Index: Send + Sync,
F: Copy + Send + Sync + FnMut(ID, ID) -> bool
{
const SPLIT_THRESHOLD: usize = 64;
if threads <= 1 || tree.len() <= SPLIT_THRESHOLD {
let collisions = self.collisions_tls.get_or(|| RefCell::new(Vec::new()));
Self::scan_impl(tree, collisions.borrow_mut(), filter);
} else {
let n = tree.len();
let mut i = n / 2;
while i < n {
let (last, _) = tree[i-1];
let (next, _) = tree[i];
if !Index::same_cell_at_depth(last, next, self.min_depth) {
break;
}
i += 1;
}
let (head, tail) = tree.split_at(i);
rayon::join(
|| self.par_scan_impl(threads >> 1, head, filter),
|| self.par_scan_impl(threads >> 1, tail, filter));
}
}
fn scan_impl<C, F>(tree: &[(Index, ID)], mut collisions: C, mut filter: F)
where
C: DerefMut<Target = Vec<(ID, ID)>>,
F: FnMut(ID, ID) -> bool
{
let mut stack: SmallVec<[(Index, ID); 256]> = SmallVec::new();
for &(index, id) in tree {
while let Some(&(index_, _)) = stack.last() {
if index.overlaps(index_) {
break;
}
stack.pop();
}
if stack.iter().any(|&(_, id_)| id == id_) {
continue;
}
for &(_, id_) in &stack {
if id != id_ && filter(id, id_) {
collisions.push((id, id_));
}
}
stack.push((index, id))
}
}
}
impl<Index, ID> PartialEq<Self> for Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{
fn eq(&self, other: &Self) -> bool {
self.min_depth == other.min_depth &&
self.tree == other.tree
}
}
impl<Index, ID> Eq for Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{}
impl<Index, ID> Clone for Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{
fn clone(&self) -> Self {
Layer{
min_depth: self.min_depth,
tree: self.tree.clone(),
// don't bother cloning the contents of temporary buffers
collisions: Vec::with_capacity(self.collisions.capacity()),
test_results: Vec::with_capacity(self.test_results.capacity()),
processed: FxHashSet::default(),
invalid: Vec::new(),
#[cfg(feature="parallel")]
collisions_tls: CachedThreadLocal::new()
}
}
}
/// A builder for `Layer`s
#[derive(Default)]
pub struct LayerBuilder {
min_depth: u32,
index_capacity: Option<usize>,
collision_capacity: Option<usize>,
test_capacity: Option<usize>
}
impl LayerBuilder {
pub fn new() -> Self {
Self::default()
}
/// Set a minimum depth for index generation.
///
/// This parameter is important for parallel processing. A higher value improves the partitioning of data and
/// improves workload balancing. However, it can also create many more indices/object than is necessary. A
/// setting which is too high may result in an excessive number of dynamic allocations and duplication of
/// intermediate collision pairs, ultimately hurting worst-case performance.
///
/// A value of zero is the safest performance-wise for _single-threaded_ operations.
///
/// When using multi-threaded methods, try a value that between
/// _log<sub>4</sub> number_of_processors_ (2D) or
/// _log<sub>8</sub> number_of_processors_ (3D) and
/// _−log<sub>2</sub>(max_object_size/system_bounds_size)_
///
/// __It is generally better to set this too low than too high__
pub fn with_min_depth(&mut self, depth: u32) -> &mut Self {
self.min_depth = depth;
self
}
/// Set an _initial_ capacity for the index list.
pub fn with_index_capacity(&mut self, capacity: usize) -> &mut Self {
self.index_capacity = Some(capacity);
self
}
/// Set an _initial_ capacity for the collision results list, used by `Layer::scan`.
pub fn with_collision_capacity(&mut self, capacity: usize) -> &mut Self {
self.collision_capacity = Some(capacity);
self
}
/// Set an _initial_ capacity for the test results list, used by `Layer::test` and `Layer::pick`.
pub fn with_test_capacity(&mut self, capacity: usize) -> &mut Self {
self.test_capacity = Some(capacity);
self
}
pub fn build<Index, ID>(&self) -> Layer<Index, ID>
where
Index: SpatialIndex,
ID: ObjectID,
Bounds<Index::Point>: IndexGenerator<Index>
{
Layer{
min_depth: self.min_depth,
tree: (match self.index_capacity {
Some(capacity) => Vec::with_capacity(capacity),
None => Vec::new()
}, true),
collisions: match self.collision_capacity {
Some(capacity) => Vec::with_capacity(capacity),
None => Vec::new()
},
test_results: match self.test_capacity {
Some(capacity) => Vec::with_capacity(capacity),
None => Vec::new()
},
processed: FxHashSet::default(),
invalid: Vec::new(),
#[cfg(feature="parallel")]
collisions_tls: CachedThreadLocal::new()
}
}
}