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
use super::*;

///A read only colliding pair reference
pub struct ColPair<'a, T, D> {
    pub first: &'a T,
    pub second: &'a T,
    pub extra: D,
}

struct ColPairPtr<T, D> {
    first: Ptr<T>,
    second: Ptr<T>,
    extra: D,
}
///CollidingPairs created via [`TreeInd::collect_colliding_pairs`]
pub struct CollidingPairs<T, D> {
    ///See collect_intersections_list()
    ///The same elements can be part of
    ///multiple intersecting pairs.
    ///So pointer aliasing rules are not
    ///being met if we were to just use this
    ///vec according to its type signature.
    cols: Vec<ColPairPtr<T, D>>,
    orig: Ptr<[T]>,
}
impl<T, D> CollidingPairs<T, D> {
    ///Return a read only list of colliding pairs.
    ///We can't return a list of mutable pairs since some might
    ///alias, but we can return a list if they are not mutable.
    #[inline(always)]
    pub fn get(&self, arr: &[T]) -> &[ColPair<T, D>] {
        assert_eq!(self.orig.0 as *const _, arr as *const _);
        unsafe { &*(self.cols.as_slice() as *const _ as *const _) }
    }

    ///Visit every colliding pair.
    ///panics if the slice passed is not the slice used to create this
    ///`CollidingPairs` object.
    pub fn for_every_pair_mut(
        &mut self,
        arr: &mut [T],
        mut func: impl FnMut(&mut T, &mut T, &mut D),
    ) {
        assert_eq!(self.orig.0, arr as *mut _);

        for ColPairPtr {
            first,
            second,
            extra,
        } in self.cols.iter_mut()
        {
            func(
                unsafe { &mut *(*first).0 },
                unsafe { &mut *(*second).0 },
                extra,
            )
        }
    }
}

///CollidingPairsPar created via [`TreeInd::collect_colliding_pairs_par`]
///All colliding pairs partitioned into
///mutually exclusive sets so that they can be traversed in parallel
pub struct CollidingPairsPar<T, D> {
    cols: Vec<Vec<ColPairPtr<T, D>>>,
    original: Ptr<[T]>,
}

impl<T, D> From<CollidingPairsPar<T, D>> for CollidingPairs<T, D> {
    fn from(a: CollidingPairsPar<T, D>) -> Self {
        let cols = a.cols.into_iter().flatten().collect();
        CollidingPairs {
            cols,
            orig: a.original,
        }
    }
}

impl<T, D> CollidingPairsPar<T, D> {
    pub fn get(&self, arr: &[T]) -> &[Vec<ColPair<T, D>>] {
        assert_eq!(arr as *const _, self.original.0 as *const _);
        unsafe { &*(self.cols.as_slice() as *const _ as *const _) }
    }
}
impl<T: Send + Sync, D: Send + Sync> CollidingPairsPar<T, D> {
    pub fn for_every_pair_mut_par(
        &mut self,
        arr: &mut [T],
        func: impl Fn(&mut T, &mut T, &mut D) + Send + Sync + Copy,
    ) {
        assert_eq!(arr as *mut _, self.original.0);
        use rayon::prelude::*;
        self.cols.par_iter_mut().for_each(|a| {
            for ColPairPtr {
                first,
                second,
                extra,
            } in a.iter_mut()
            {
                let a = unsafe { &mut *first.0 };
                let b = unsafe { &mut *second.0 };
                func(a, b, extra)
            }
        });
    }
}

///Contains a filtered list of all elements in the tree from calling [`TreeInd::collect_all`].
pub struct FilteredElements<T, D> {
    elems: Vec<(Ptr<T>, D)>,
    orig: Ptr<[T]>,
}
impl<T, D> FilteredElements<T, D> {
    #[inline(always)]
    pub fn get(&self, arr: &[T]) -> &[(&T, D)] {
        assert_eq!(self.orig.0 as *const _, arr as *const _);
        unsafe { &*(self.elems.as_slice() as *const _ as *const _) }
    }
    #[inline(always)]
    pub fn get_mut(&mut self, arr: &mut [T]) -> &mut [(&mut T, D)] {
        assert_eq!(self.orig.0, arr as *mut _);
        unsafe { &mut *(self.elems.as_mut_slice() as *mut _ as *mut _) }
    }
}





///This is a `Vec<BBox<N,&'a mut T>>` under the hood
///with the added guarentee that all the `&'a mut T`
///point to the same slice.
///
///From this struct a user can create a [`TreeInd`].
pub struct TreeIndBase<'a,N:Num,T>{
    aabbs:Box<[BBox<N,&'a mut T>]>,
    orig:Ptr<[T]>
}
impl<'a,N:Num,T> TreeIndBase<'a,N,T>{

    /// Create a [`TreeIndBase`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    /// ```
    pub fn new(bots:&'a mut [T],mut func:impl FnMut(&mut T)->Rect<N>)->TreeIndBase<'a,N,T>{
        let orig = Ptr(bots as *mut _);

        TreeIndBase{
            orig,
            aabbs:bots.iter_mut().map(|a|crate::bbox(func(a),a)).collect::<Vec<_>>().into_boxed_slice()
        }
    }

    /// Extra the internals of a [`TreeIndBase`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut inner=base.into_inner();
    /// let mut tree = broccoli::new(&mut inner);
    /// //We can make a tree using the internals, but we lost the guarentee
    /// //that all the `&'a mut T` belong to the same slice.
    /// ```
    pub fn into_inner(self)->Box<[BBox<N,&'a mut T>]>{
        self.aabbs
    }

    /// Build a [`TreeInd`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    /// ```
    pub fn build<'b>(&'b mut self)->TreeInd<'a,'b,N,T>{
        let tree=crate::new(&mut self.aabbs);

        TreeInd{
            tree,
            orig:self.orig
        }
    }

    /// Build a [`TreeInd`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build_par();
    /// ```
    pub fn build_par<'b>(&'b mut self)->TreeInd<'a,'b,N,T> where N:Send+Sync,T:Send+Sync{
        let tree=crate::new_par(&mut self.aabbs);

        TreeInd{
            tree,
            orig:self.orig
        }
    }

}



/// A less general tree that provides `collect` functions
/// and also derefs to a [`Tree`].
///
/// [`TreeInd`] assumes there is a layer of indirection where
/// all the pointers point to the same slice.
/// It uses this assumption to provide `collect` functions that allow
/// storing query results that can then be iterated through multiple times
/// quickly.
///
#[repr(C)]
pub struct TreeInd<'a,'b,N:Num,T>{
    tree:Tree<'b,BBox<N,&'a mut T>>,
    orig:Ptr<[T]>
}

#[repr(C)]
pub(super) struct TreeIndPtr<N:Num,T>{
    pub(super) tree:TreePtr<BBox<N,Ptr<T>>>,
    pub(super) orig:Ptr<[T]>
}


impl<'a,'b, N:Num,T> From<TreeInd<'a,'b,N,T>> for Tree<'b, BBox<N,&'a mut T>> {
    #[inline(always)]
    fn from(a: TreeInd<'a,'b,N,T>) -> Self {
        a.tree
    }
}


impl<'a,'b, N: Num , T> core::ops::Deref for TreeInd<'a,'b, N, T> {
    type Target = Tree<'b, BBox<N, &'a mut T>>;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.tree
    }
}
impl<'a, 'b,N: Num, T> core::ops::DerefMut for TreeInd<'a, 'b,N, T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.tree
    }
}

impl<'a,'b,N:Num,T> TreeInd<'a,'b,N,T>{


    pub(super) fn into_ptr(self)->TreeIndPtr<N,T>{
        
        TreeIndPtr{
            tree:TreePtr{
                _inner:unsafe{self.tree.inner.convert()},
                _num_aabbs:self.tree.num_aabbs
            },
            orig:self.orig
        }
    }


    /// Retrieve the underlying list of elements.
    /// Unlike [`Tree::get_elements_mut()`] which
    /// returns the aabbs of the tree, this returns the
    /// list of T that each aabb points to.
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    /// let bots=tree.get_inner_elements_mut();
    ///
    /// ```
    #[inline(always)]
    pub fn get_inner_elements_mut(&mut self)->&mut [T]{
        unsafe{&mut *self.orig.0}
    }

    /// Retrieve the underlying list of elements.
    /// Unlike [`Tree::get_elements_mut()`] which
    /// returns the aabbs of the tree, this returns the
    /// list of T that each aabb points to.
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    /// let bots=tree.get_inner_elements();
    ///
    /// ```
    #[inline(always)]
    pub fn get_inner_elements(&self)->&[T]{
        unsafe{&*self.orig.0}
    }
    /// Collect all elements based off of a predicate and return a [`FilteredElements`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///    broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    ///    broccoli::bbox(broccoli::rect(15, 20, 15, 20), 1),
    ///    broccoli::bbox(broccoli::rect(5, 15, 5, 15), 2),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    ///
    /// //Find a group of elements only once.
    /// let mut pairs=tree.collect_all(|_,b| {
    ///    if b.inner % 2 ==0{
    ///        Some(())
    ///    }else{
    ///        None
    ///    }
    /// });
    ///
    /// //Iterate over that group multiple times
    /// for _ in 0..3{
    ///     //mutate every colliding pair.
    ///     for (a,()) in pairs.get_mut(&mut aabbs){
    ///         a.inner+=1;
    ///     }
    /// }
    pub fn collect_all<D: Send + Sync>(
        &mut self,
        mut func: impl FnMut(&Rect<N>, &mut T) -> Option<D>,
    ) -> FilteredElements<T, D> {
        let mut elems = Vec::new();
        for node in self.get_nodes_mut().iter_mut() {
            for b in node.into_range().iter_mut() {
                let (x, y) = b.unpack();
                if let Some(d) = func(x, y) {
                    elems.push((Ptr(*y as *mut _), d));
                }
            }
        }
        FilteredElements {
            orig: self.orig,
            elems,
        }
    }

    /// Find all colliding pairs based on a predicate and return a [`CollidingPairs`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///     broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    ///     broccoli::bbox(broccoli::rect(15, 20, 15, 20), 1),
    ///     broccoli::bbox(broccoli::rect(5, 15, 5, 15), 2),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    ///
    /// //Find all colliding aabbs only once.
    /// let mut pairs=tree.collect_colliding_pairs(|a, b| {
    ///    a.inner += 1;
    ///    b.inner += 1;
    ///    Some(())
    /// });
    ///
    /// //Iterate over the pairs multiple times
    /// for _ in 0..3{
    ///     //mutate every colliding pair.
    ///     pairs.for_every_pair_mut(&mut aabbs,|a,b,()|{
    ///         a.inner+=1;
    ///         b.inner+=1;
    ///     })
    /// }
    pub fn collect_colliding_pairs<D: Send + Sync>(
        &mut self,
        mut func: impl FnMut(&mut T, &mut T) -> Option<D> + Send + Sync,
    ) -> CollidingPairs<T, D> {
        let mut cols: Vec<_> = Vec::new();
        self.tree.find_colliding_pairs_mut(|a, b| {
            let a = a.unpack_inner();
            let b = b.unpack_inner();
            if let Some(extra) = func(a, b) {
                //We use unsafe to collect mutable references of
                //all colliding pairs.
                //This is safe to do because the user is forced
                //to iterate through all the colliding pairs
                //one at a time.
                let first = Ptr(*a as *mut T);
                let second = Ptr(*b as *mut T);

                cols.push(ColPairPtr {
                    first,
                    second,
                    extra,
                });
            }
        });

        CollidingPairs {
            cols,
            orig: self.orig,
        }
    }

    /// The parallel version of [`TreeInd::collect_colliding_pairs`] that instead
    /// returns a [`CollidingPairsPar`].
    ///
    /// # Examples
    ///
    ///```
    /// let mut aabbs = [
    ///     broccoli::bbox(broccoli::rect(0isize, 10, 0, 10), 0),
    ///     broccoli::bbox(broccoli::rect(15, 20, 15, 20), 1),
    ///     broccoli::bbox(broccoli::rect(5, 15, 5, 15), 2),
    /// ];
    ///
    /// let mut base=broccoli::container::TreeIndBase::new(&mut aabbs,|a|a.rect); 
    /// let mut tree = base.build();
    ///
    /// //Find all colliding aabbs only once.
    /// let mut pairs=tree.collect_colliding_pairs_par(|a, b| {
    ///    a.inner += 1;
    ///    b.inner += 1;
    ///    Some(())
    /// });
    ///
    /// //Iterate over the pairs multiple times
    /// for _ in 0..3{
    ///     //mutate every colliding pair.
    ///     pairs.for_every_pair_mut_par(&mut aabbs,|a,b,()|{
    ///         a.inner+=1;
    ///         b.inner+=1;
    ///     })
    /// }
    pub fn collect_colliding_pairs_par<D: Send + Sync>(
        &mut self,
        func: impl Fn(&mut T, &mut T) -> Option<D> + Send + Sync + Copy,
    ) -> CollidingPairsPar<T, D> where N:Send+Sync,T:Send+Sync{
        let cols = self.collect_colliding_pairs_par_inner(|a, b| match func(a, b) {
            Some(extra) => Some(ColPairPtr {
                first: Ptr(a as *mut _),
                second: Ptr(b as *mut _),
                extra,
            }),
            None => None,
        });
        CollidingPairsPar {
            cols,
            original: self.orig,
        }
    }

    fn collect_colliding_pairs_par_inner<D: Send + Sync>(
        &mut self,
        func: impl Fn(&mut T, &mut T) -> Option<D> + Send + Sync + Copy,
    ) -> Vec<Vec<D>> where N:Send+Sync,T:Send+Sync {
        let mut handler = crate::query::colfind::builder::from_closure(
            self,
            vec![Vec::new()],
            move |_| (vec![Vec::new()], vec![Vec::new()]),
            move |a, mut b, mut c| {
                a.first_mut().unwrap().append(&mut b.pop().unwrap());
                a.append(&mut c);
            },
            move |c, a, b| {
                if let Some(d) = func(a.unpack_inner(), b.unpack_inner()) {
                    c.first_mut().unwrap().push(d);
                }
            },
        );

        use crate::query::colfind::builder::*;
        self.new_builder()
            .query_par_ext(&mut handler, &mut SplitterEmpty);
        handler.consume()
    }
}