linear-sim 0.7.0

Minimal linear 3D simulation library
Documentation
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use std;
use geometry::Aabb3;
use vec_map::VecMap;
use sorted_vec::SortedSet;
#[cfg(feature = "derive_serdes")]
use serde::{Deserialize, Serialize};

use crate::{geometry, math, object};

use super::{InternalId, ObjectPair};

/// Data for broad-phase "sort and sweep" ("sweep and prune (SAP)") collision detection
#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default)]
pub(crate) struct Broad {
  /// Each sorted axis of both static and instantaneous dynamic AABB intervals
  axes_discrete   : SortedAxes,
  /// Each sorted axis of both static and swept dynamic AABB intervals
  axes_continuous : SortedAxes,
  /// Object pairs involved in last resolve collision; when calling
  /// `overlap_pairs_continuous`, these pairs will be excluded
  resolved        : SortedSet <ObjectPair>,
  /// Dynamic objects that were modified in the last resolve collision; when calling
  /// `overlap_pairs_continuous`, only overlaps involving these objects will be
  /// considered
  modified        : SortedSet <InternalId>
}

#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default)]
struct SortedAxes {
  axes          : [Vec <Endpoint>; 3],
  overlap_pairs : OverlapPairs,
  order_indices : OrderIndices
}

/// Min or max point of an AABB dimension
#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, PartialEq)]
enum Endpoint {
  Min (f64, InternalId),
  Max (f64, InternalId)
}

/// Keeps track of the ordered (min, max) endpoint indices in the sorted axes
#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default)]
struct OrderIndices {
  // static is a keyword in rust
  static_ : VecMap <[(u32, u32); 3]>,
  dynamic : VecMap <[(u32, u32); 3]>
}

/// We only track overlap pairs involving at least one dynamic object (not static vs.
/// static).
///
/// To take advantage of temporal coherence, overlap pairs should be preserved between
/// steps.
///
/// The 4th set of overlap pairs contains the pairs that overlap on all 3 axes.
#[cfg_attr(feature = "derive_serdes", derive(Deserialize, Serialize))]
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct OverlapPairs ([SortedSet <ObjectPair>; 4]);

////////////////////////////////////////////////////////////////////////////////
//  impls                                                                     //
////////////////////////////////////////////////////////////////////////////////

impl Broad {
  #[inline]
  pub(crate) fn overlaps_discrete (&self, aabb : Aabb3 <f64>) -> Vec <InternalId> {
    self.axes_discrete.overlaps (aabb)
  }

  pub(super) fn add_object_static (&mut self, aabb : Aabb3 <f64>, key : object::Key) {
    let id = InternalId::new_static (key);
    self.axes_discrete.insert (aabb, id);
    self.axes_continuous.insert (aabb, id);
  }
  pub(super) fn add_object_dynamic (&mut self,
    aabb_discrete   : Aabb3 <f64>,
    aabb_continuous : Aabb3 <f64>,
    key             : object::Key
  ) {
    let id = InternalId::new_dynamic (key);
    self.axes_discrete.insert (aabb_discrete, id);
    self.axes_continuous.insert (aabb_continuous, id);
  }
  pub(super) fn remove_object (&mut self, id : InternalId) {
    // ensures this object does not exist in the resolved ids
    debug_assert!(self.resolved.is_empty());
    self.axes_discrete.remove (id);
    self.axes_continuous.remove (id);
  }
  #[inline]
  pub(super) fn get_aabb_static (&self, key : object::Key) -> Aabb3 <f64> {
    let id = InternalId::new_static (key);
    debug_assert_eq!(
      self.axes_discrete.get_aabb (id), self.axes_continuous.get_aabb (id));
    self.axes_discrete.get_aabb (id)
  }
  #[inline]
  pub(super) fn get_aabb_dynamic_discrete (&self, key : object::Key) -> Aabb3 <f64> {
    let id = InternalId::new_dynamic (key);
    self.axes_discrete.get_aabb (id)
  }
  #[inline]
  pub(super) fn get_aabb_dynamic_continuous (&self, key : object::Key) -> Aabb3 <f64> {
    let id = InternalId::new_dynamic (key);
    self.axes_continuous.get_aabb (id)
  }
  #[inline]
  pub(super) fn update_aabb_static (&mut self, aabb : Aabb3 <f64>, key : object::Key) {
    let id = InternalId::new_static (key);
    self.axes_discrete.update (aabb, id);
    self.axes_continuous.update (aabb, id);
  }
  #[inline]
  pub(super) fn update_aabb_dynamic_discrete (&mut self,
    aabb : Aabb3 <f64>,
    key  : object::Key
  ) {
    let id = InternalId::new_dynamic (key);
    self.axes_discrete.update (aabb, id);
  }
  #[inline]
  pub(super) fn update_aabb_dynamic_continuous (&mut self,
    aabb : Aabb3 <f64>,
    key  : object::Key
  ) {
    let id = InternalId::new_dynamic (key);
    self.axes_continuous.update (aabb, id);
  }

  #[inline]
  pub(super) fn add_resolved (&mut self, object_pair : ObjectPair) {
    use sorted_vec::FindOrInsert;
    match self.resolved.find_or_insert (object_pair) {
      FindOrInsert::Inserted (_) => {}
      FindOrInsert::Found    (_) => unreachable!()
    }
  }

  #[inline]
  pub(super) fn set_modified (&mut self, modified : SortedSet <InternalId>) {
    self.modified = modified;
  }

  /// Update dynamic AABBs
  #[inline]
  pub(super) fn begin_step (&mut self,
    objects_dynamic : &VecMap <object::Dynamic>,
    _step            : u64
  ) {
    for (i, object) in objects_dynamic.iter() {
      let key        = object::Key::from (i);
      let id         = InternalId::new_dynamic (key);
      let old_aabb   = self.axes_discrete.get_aabb (id);
      let new_aabb   = object.aabb_dilated();
      let swept_aabb = Aabb3::union (old_aabb, new_aabb);
      self.update_aabb_dynamic_discrete (new_aabb, key);
      self.update_aabb_dynamic_continuous (swept_aabb, key);
    }
  }

  pub(super) fn overlap_pairs_continuous (&mut self,
    overlap_pairs : &mut Vec <ObjectPair>,
    iter          : u64
  ) {
    debug_assert!(overlap_pairs.is_empty());
    if self.resolved.is_empty() && iter == 0 {
      // collect all overlaps on initial iteration
      overlap_pairs.extend (self.axes_continuous.overlap_pairs.0[3].iter().copied());
    } else if !self.resolved.is_empty() {
      // on subsequent iterations, only collect overlaps involving resolved
      // dynamic objects, and clear the list of resolved objects when finished
      for pair in self.axes_continuous.overlap_pairs.0[3].iter().copied() {
        if self.resolved.contains (&pair) {
          continue
        }
        let (id_a, id_b) = pair.into();
        debug_assert_eq!(id_b.kind(), object::Kind::Dynamic);
        if self.modified.binary_search_by_key (&id_b, |x| *x).is_ok() ||
          id_a.kind() == object::Kind::Dynamic &&
          self.modified.binary_search_by_key (&id_a, |x| *x).is_ok()
        {
          overlap_pairs.push (pair);
        }
      }
      self.resolved.clear();
      self.modified.clear();
    }
  }
}

impl SortedAxes {
  fn get_aabb (&self, id : InternalId) -> Aabb3 <f64> {
    let &[
      (index_min_x, index_max_x),
      (index_min_y, index_max_y),
      (index_min_z, index_max_z)
    ] = self.order_indices.get (id);
    let min = [
      self.axes[0][index_min_x as usize].point(),
      self.axes[1][index_min_y as usize].point(),
      self.axes[2][index_min_z as usize].point()
    ].into();
    let max = [
      self.axes[0][index_max_x as usize].point(),
      self.axes[1][index_max_y as usize].point(),
      self.axes[2][index_max_z as usize].point()
    ].into();
    Aabb3::with_minmax_unchecked (min, max)
  }
  /// Overlap query
  fn overlaps (&self, aabb : Aabb3 <f64>) -> Vec <InternalId> {
    let mut out     = SortedSet::new();
    let mut collect = SortedSet::new();
    for (i, axis) in self.axes.iter().enumerate() {
      let min       = aabb.min().0[i];
      let max       = aabb.max().0[i];
      let index_min = axis.binary_search_by (|p| p.point().partial_cmp (&min).unwrap())
        .unwrap_or_else (|i| i);
      collect.clear();
      let mut mins = vec![];
      for other_endpoint in axis.iter().skip (index_min) {
        // TODO: currently we traverse the axis from the given min to the end of
        // the axis; we could also traverse from the start of the axis until the
        // given max; a possible optimization would be to choose whichever
        // direction is shorter
        let (other_point, other_id) = other_endpoint.pair();
        if other_point > min {
          if other_point < max {
            if i == 0 {
              // could be inserted twice if both endpoints are found
              let _result = collect.find_or_insert (other_id);
            } else if out.binary_search (&other_id).is_ok() {
              debug_assert!(!out.is_empty());
              // could be inserted twice if both endpoints are found
              let _result = collect.find_or_insert (other_id);
            }
          } else if other_endpoint.is_min() {
            mins.push (other_id);
          } else if !mins.contains (&other_id) {
            if i == 0 {
              let _result = collect.find_or_insert (other_id);
            } else if out.binary_search (&other_id).is_ok() {
              debug_assert!(!out.is_empty());
              // could be inserted twice if both endpoints are found
              let _result = collect.find_or_insert (other_id);
            }
          }
        }
      }
      std::mem::swap (&mut out, &mut collect);
      if out.is_empty() {
        break
      }
    }
    out.into_vec()
  }
  fn insert (&mut self, aabb : Aabb3 <f64>, id : InternalId) {
    let mins  = aabb.min().0.into_array().map (|s| Endpoint::Min (s, id));
    let maxes = aabb.max().0.into_array().map (|s| Endpoint::Max (s, id));
    let mut order_indices = [(u32::MAX, u32::MAX); 3];
    for (i, axis) in self.axes.iter_mut().enumerate() {
      // TODO: currently we traverse the axis from the inserted min to the end
      // of the axis; we could also traverse from the start of the axis until
      // the inserted max; a possible optimization would be to choose whichever
      // direction is shorter
      let axis3 = math::Axis3::from_repr (i as u8).unwrap();
      // find location and insert min/max
      let min       = mins[i];
      let index_min = axis.binary_search_by (|p| p.partial_cmp (&min).unwrap())
        .unwrap_or_else (|i| i);
      axis.insert (index_min, min);
      let max       = maxes[i];
      let index_max = axis[index_min+1..]
        .binary_search_by (|p| p.partial_cmp (&max).unwrap())
        .unwrap_or_else (|i| i) + index_min + 1;
      axis.insert (index_max, max);
      order_indices[i] = (index_min as u32, index_max as u32);
      // for endpoints between min/max, collect overlaps and increment order
      // indices by one
      let mut min_overlapped = vec![];
      for endpoint in axis[index_min+1..index_max].iter() {
        let (_, other_id) = endpoint.pair();
        if id.kind() == object::Kind::Dynamic ||
          other_id.kind() == object::Kind::Dynamic
        {
          if endpoint.is_min() {
            min_overlapped.push (other_id);
            self.overlap_pairs.insert (axis3, (id, other_id).into());
          } else if !min_overlapped.contains (&other_id) {
            self.overlap_pairs.insert (axis3, (id, other_id).into());
          }
        }
        let order_indices = self.order_indices.get_mut (other_id);
        match endpoint {
          Endpoint::Min (..) => order_indices[i].0 += 1,
          Endpoint::Max (..) => order_indices[i].1 += 1
        }
      }
      // for endpoints after max, collect overlaps and increment indices by two
      let mut mins = vec![];
      for endpoint in axis[index_max+1..].iter() {
        let (_, other_id) = endpoint.pair();
        if id.kind() == object::Kind::Dynamic ||
          other_id.kind() == object::Kind::Dynamic
        {
          if endpoint.is_min() {
            mins.push (other_id);
          } else if !min_overlapped.contains (&other_id) &&
            !mins.contains (&other_id)
          {
            self.overlap_pairs.insert (axis3, (id, other_id).into());
          }
        }
        let order_indices = self.order_indices.get_mut (other_id);
        match endpoint {
          Endpoint::Min (..) => order_indices[i].0 += 2,
          Endpoint::Max (..) => order_indices[i].1 += 2
        }
      }
      debug_assert!(axis.is_sorted());
    }
    self.order_indices.insert (id, order_indices);
    if cfg!(debug_assertions) {
      self.verify_order_indices();
    }
    debug_assert_eq!(self.sweep(), self.overlap_pairs);
  }
  fn update (&mut self, aabb : Aabb3 <f64>, id : InternalId) {
    let order_indices = *self.order_indices.get (id);
    log::trace!(id:?; "sorted axes update");
    for (i, axis) in self.axes.iter_mut().enumerate() {
      let axis3 = math::Axis3::from_repr (i as u8).unwrap();
      let min_new = aabb.min().0[i];
      let max_new = aabb.max().0[i];
      let (index_min, index_max) = order_indices[i];
      let min_old = axis[index_min as usize].point();
      let max_old = axis[index_max as usize].point();
      let mut new_index_min = index_min as usize;
      let mut new_index_max = index_max as usize;
      axis[new_index_max].set_point (max_new);
      axis[new_index_min].set_point (min_new);
      // first perform operations that add overlaps (move min down or max up),
      // followed by operations that remove overlaps (move min up or max down)
      // TODO: doing things this way means that overlaps may be added only to be
      // removed when the other endpoint is moved; is it possible to avoid this
      // by looking at the old/new endpoints?
      if min_old > min_new {
        // sort min down: only add overlaps
        loop {
          if new_index_min == 0 {
            break
          }
          let index_left = new_index_min - 1;
          let other_endpoint = axis[index_left];
          let (other_point, other_id) = other_endpoint.pair();
          if min_new < other_point {
            if other_endpoint.is_max() && (
              id.kind() == object::Kind::Dynamic ||
              other_id.kind() == object::Kind::Dynamic
            ) {
              // add overlap
              self.overlap_pairs.insert (axis3, (id, other_id).into());
            }
            // update order indices
            self.order_indices.get_mut (id)[i].0 -= 1;
            match other_endpoint {
              Endpoint::Min (..) =>
                self.order_indices.get_mut (other_id)[i].0 += 1,
              Endpoint::Max (..) =>
                self.order_indices.get_mut (other_id)[i].1 += 1
            }
            // swap
            axis.swap (new_index_min, index_left);
            new_index_min = index_left;
          } else {
            break
          }
        }
      }
      if max_new > max_old {
        // sort max up: only add overlaps
        loop {
          if new_index_max == axis.len() - 1 {
            break
          }
          let index_right = new_index_max + 1;
          let other_endpoint = axis[index_right];
          let (other_point, other_id) = axis[index_right].pair();
          if max_new > other_point {
            if other_endpoint.is_min() && (
              id.kind() == object::Kind::Dynamic ||
              other_id.kind() == object::Kind::Dynamic
            ) {
              // add overlap
              self.overlap_pairs.insert (axis3, (id, other_id).into());
            }
            // update order indices
            match other_endpoint {
              Endpoint::Min (..) =>
                self.order_indices.get_mut (other_id)[i].0 -= 1,
              Endpoint::Max (..) =>
                self.order_indices.get_mut (other_id)[i].1 -= 1
            }
            // swap
            axis.swap (new_index_max, index_right);
            new_index_max = index_right;
          } else {
            break
          }
        }
      }
      if min_new > min_old {
        // sort min up: only remove overlaps
        loop {
          if new_index_min == axis.len() - 1 {
            break
          }
          let index_right = new_index_min + 1;
          let other_endpoint = axis[index_right];
          let (other_point, other_id) = axis[index_right].pair();
          if min_new > other_point {
            if other_endpoint.is_max() && (
              id.kind() == object::Kind::Dynamic ||
              other_id.kind() == object::Kind::Dynamic
            ) {
              // remove overlap
              self.overlap_pairs.remove (axis3, (id, other_id).into());
            }
            // update order indices
            match other_endpoint {
              Endpoint::Min (..) =>
                self.order_indices.get_mut (other_id)[i].0 -= 1,
              Endpoint::Max (..) =>
                self.order_indices.get_mut (other_id)[i].1 -= 1
            }
            // swap
            axis.swap (new_index_min, index_right);
            new_index_min = index_right;
          } else {
            break
          }
        }
      }
      if max_old > max_new {
        // sort max down: only remove overlaps
        loop {
          if new_index_max == 0 {
            break
          }
          let index_left = new_index_max - 1;
          let other_endpoint = axis[index_left];
          let (other_point, other_id) = other_endpoint.pair();
          if max_new < other_point {
            if other_endpoint.is_min() && (
              id.kind() == object::Kind::Dynamic ||
              other_id.kind() == object::Kind::Dynamic
            ) {
              // remove overlap
              self.overlap_pairs.remove (axis3, (id, other_id).into());
            }
            // update order indices
            match other_endpoint {
              Endpoint::Min (..) =>
                self.order_indices.get_mut (other_id)[i].0 += 1,
              Endpoint::Max (..) =>
                self.order_indices.get_mut (other_id)[i].1 += 1
            }
            // swap
            axis.swap (new_index_max, index_left);
            new_index_max = index_left;
          } else {
            break
          }
        }
      }
      self.order_indices.get_mut (id)[i] =
        (new_index_min as u32, new_index_max as u32);
      log::trace!(index=i, axis:?; "sorted axis update after");
      //debug_assert!(axis.is_sorted());
    }
    /*
    if cfg!(debug_assertions) {
      self.verify_order_indices();
    }
    debug_assert_eq!(self.sweep(), self.overlap_pairs);
    debug_assert_eq!(self.aabb_check(), self.overlap_pairs.0[3]);
    */
  }
  fn remove (&mut self, id : InternalId) {
    let order_indices = self.order_indices.remove (id);
    for (i, axis) in self.axes.iter_mut().enumerate() {
      let (index_min, index_max) = order_indices[i];
      // for endpoints between min/max, decrement order indices by one
      for endpoint in axis[index_min as usize+1..index_max as usize].iter() {
        let (_, other_id) = endpoint.pair();
        let order_indices = self.order_indices.get_mut (other_id);
        match endpoint {
          Endpoint::Min (..) => order_indices[i].0 -= 1,
          Endpoint::Max (..) => order_indices[i].1 -= 1
        }
      }
      // for endpoints after max, decrement order indices by two
      for endpoint in axis[index_max as usize+1..].iter() {
        let (_, other_id) = endpoint.pair();
        let order_indices = self.order_indices.get_mut (other_id);
        match endpoint {
          Endpoint::Min (..) => order_indices[i].0 -= 2,
          Endpoint::Max (..) => order_indices[i].1 -= 2
        }
      }
      // remove endpoints
      axis.remove (index_max as usize);
      axis.remove (index_min as usize);
    }
    self.overlap_pairs.remove_id (id);
    if cfg!(debug_assertions) {
      self.verify_order_indices();
    }
    debug_assert_eq!(self.sweep(), self.overlap_pairs);
  }
  #[expect(clippy::needless_range_loop)]
  fn verify_order_indices (&self) {
    for (index, indices) in self.order_indices.static_.iter() {
      let id = InternalId::new_static (object::Key::from (index));
      for i in 0..3 {
        let min = self.axes[i][indices[i].0 as usize];
        debug_assert_eq!(min.id(), id, "axis[{i}], id: {id:?}");
        debug_assert!(min.is_min(), "axis[{i}], id: {id:?}");
        let max = self.axes[i][indices[i].1 as usize];
        debug_assert_eq!(max.id(), id, "axis[{i}], id: {id:?}");
        debug_assert!(max.is_max(), "axis[{i}], id: {id:?}");
      }
    }
    for (index, indices) in self.order_indices.dynamic.iter() {
      let id = InternalId::new_dynamic (object::Key::from (index));
      for i in 0..3 {
        let min = self.axes[i][indices[i].0 as usize];
        debug_assert_eq!(min.id(), id, "axis[{i}], id: {id:?}");
        debug_assert!(min.is_min(), "axis[{i}], id: {id:?}");
        let max = self.axes[i][indices[i].1 as usize];
        debug_assert_eq!(max.id(), id, "axis[{i}], id: {id:?}");
        debug_assert!(max.is_max(), "axis[{i}], id: {id:?}");
      }
    }
  }
  fn sweep (&self) -> OverlapPairs {
    let mut overlaps = OverlapPairs::default();
    for (i, axis) in self.axes.iter().enumerate() {
      let axis3 = math::Axis3::from_repr (i as u8).unwrap();
      let mut open : Vec <InternalId> = vec![];
      for endpoint in axis.iter() {
        let id = endpoint.id();
        if endpoint.is_min() {
          for open_id in open.iter() {
            if open_id.kind() == object::Kind::Dynamic ||
              id.kind() == object::Kind::Dynamic
            {
              overlaps.insert (axis3, (*open_id, id).into());
            }
          }
          open.push (id);
        } else {
          open.remove (open.iter().position (|x| x == &id).unwrap());
        }
      }
    }
    overlaps
  }
  /// Do pair-wise overlap check on all AABBs
  #[expect(dead_code)]
  fn aabb_check (&self) -> SortedSet <ObjectPair> {
    let mut overlaps = vec![];
    for i in self.order_indices.static_.keys() {
      let id_static   = InternalId::new_static (object::Key::from (i));
      let aabb_static = self.get_aabb (id_static);
      for j in self.order_indices.dynamic.keys() {
        let id_dynamic   = InternalId::new_dynamic (object::Key::from (j));
        let aabb_dynamic = self.get_aabb (id_dynamic);
        if aabb_static.intersects (aabb_dynamic) {
          overlaps.push (ObjectPair::from ((id_static, id_dynamic)));
        }
      }
    }
    for (n, i) in self.order_indices.dynamic.keys().enumerate() {
      let id_a   = InternalId::new_dynamic (object::Key::from (i));
      let aabb_a = self.get_aabb (id_a);
      for (m, j) in self.order_indices.dynamic.keys().enumerate() {
        if m >= n {
          break
        }
        let id_b   = InternalId::new_dynamic (object::Key::from (j));
        let aabb_b = self.get_aabb (id_b);
        if aabb_a.intersects (aabb_b) {
          overlaps.push (ObjectPair::from ((id_a, id_b)));
        }
      }
    }
    SortedSet::from_unsorted (overlaps)
  }
}

impl OrderIndices {
  fn get (&self, id : InternalId) -> &[(u32, u32); 3] {
    self.get_map (id).get (id.key().index()).unwrap()
  }

  fn get_mut (&mut self, id : InternalId) -> &mut [(u32, u32); 3] {
    self.get_map_mut (id).get_mut (id.key().index()).unwrap()
  }

  fn insert (&mut self, id : InternalId, indices : [(u32, u32); 3]) {
    let result = self.get_map_mut (id).insert (id.key().index(), indices);
    debug_assert!(result.is_none());
  }

  fn remove (&mut self, id : InternalId) -> [(u32, u32); 3] {
    self.get_map_mut (id).remove (id.key().index()).unwrap()
  }

  fn get_map (&self, id : InternalId) -> &VecMap <[(u32, u32); 3]> {
    match id.kind() {
      object::Kind::Static   => &self.static_,
      object::Kind::Dynamic  => &self.dynamic,
      object::Kind::Nodetect => unreachable!()
    }
  }

  fn get_map_mut (&mut self, id : InternalId) -> &mut VecMap <[(u32, u32); 3]> {
    match id.kind() {
      object::Kind::Static   => &mut self.static_,
      object::Kind::Dynamic  => &mut self.dynamic,
      object::Kind::Nodetect => unreachable!()
    }
  }
}

impl OverlapPairs {
  fn insert (&mut self, axis : math::Axis3, pair : ObjectPair) {
    let component_index = axis.component();
    let result = self.0[component_index].find_or_insert (pair);
    debug_assert!(result.is_inserted());
    let mut overlap_all = true;
    for i in 0..3 {
      if i != component_index && self.0[i].binary_search (&pair).is_err() {
        overlap_all = false;
        break
      }
    }
    if overlap_all {
      let result = self.0[3].find_or_insert (pair);
      debug_assert!(result.is_inserted());
    }
  }

  fn remove (&mut self, axis : math::Axis3, pair : ObjectPair) {
    let component_index = axis.component();
    let result = self.0[component_index].remove_item (&pair);
    debug_assert!(result.is_some());
    self.0[3].remove_item (&pair);
  }

  fn remove_id (&mut self, id : InternalId) {
    for overlaps in self.0.iter_mut() {
      overlaps.retain (|ObjectPair (id_a, id_b)| id_a != &id && id_b != &id);
    }
  }
}

impl Endpoint {
  const fn pair (self) -> (f64, InternalId) {
    match self {
      Endpoint::Min (point, id) | Endpoint::Max (point, id) => (point, id)
    }
  }

  const fn point (self) -> f64 {
    match self {
      Endpoint::Min (point, _) | Endpoint::Max (point, _) => point
    }
  }

  const fn id (self) -> InternalId {
    match self {
      Endpoint::Min (_, id) | Endpoint::Max (_, id) => id
    }
  }

  const fn is_min (&self) -> bool {
    match self {
      Endpoint::Min (..) => true,
      Endpoint::Max (..) => false
    }
  }

  const fn is_max (&self) -> bool {
    match self {
      Endpoint::Min (..) => false,
      Endpoint::Max (..) => true
    }
  }

  const fn set_point (&mut self, point : f64) {
    match self {
      Endpoint::Min (p, _) | Endpoint::Max (p, _) => *p = point
    }
  }
}

impl PartialOrd for Endpoint {
  fn partial_cmp (&self, other : &Endpoint) -> Option <std::cmp::Ordering> {
    self.point().partial_cmp (&other.point())
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use geometry::Aabb3;

  #[test]
  fn add_object() {
    let mut broad = Broad::default();
    let aabb1 = Aabb3::with_minmax_unchecked (
      [0.0, 0.0, 0.0].into(), [2.0, 2.0, 2.0].into());
    let aabb2 = Aabb3::with_minmax_unchecked (
      [1.0, 1.0, -2.0].into(), [3.0, 3.0, -1.0].into());
    let aabb3 = Aabb3::with_minmax_unchecked (
      [2.0, 2.0, -3.0].into(), [3.0, 3.0, 0.0].into());
    broad.add_object_static (aabb1, 0u32.into());
    broad.add_object_dynamic (aabb2, aabb2, 0u32.into());
    broad.add_object_dynamic (aabb3, aabb3, 1u32.into());
    println!("{broad:?}");
  }

  #[test]
  fn remove_object() {
    let mut broad = Broad::default();
    let aabb1 = Aabb3::with_minmax_unchecked (
      [0.0, 0.0, 0.0].into(), [2.0, 2.0, 2.0].into());
    let aabb2 = Aabb3::with_minmax_unchecked (
      [1.0, 1.0, -2.0].into(), [3.0, 3.0, -1.0].into());
    let aabb3 = Aabb3::with_minmax_unchecked (
      [2.0, 2.0, -3.0].into(), [3.0, 3.0, 0.0].into());
    broad.add_object_static (aabb1, 0u32.into());
    broad.add_object_dynamic (aabb2, aabb2, 0u32.into());
    broad.add_object_dynamic (aabb3, aabb3, 1u32.into());
    broad.remove_object (InternalId::new_dynamic (0u32.into()));
    println!("{broad:?}");
  }
}