spart 0.5.1

A collection of space partitioning tree data structures for Rust
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
//! ## Geometric Primitives and Operations for 2D and 3D Spaces
//!
//! This module provides geometric primitives and operations for both 2D and 3D spaces.
//! It defines types such as `Point2D`, `Rectangle`, `Point3D`, and `Cube` along with their associated
//! operations. These types form the basis for indexing and query algorithms in Spart.
//!
//! In addition to the basic types, the module defines several traits for operations such as
//! bounding volume calculations and minimum distance computations.

use ordered_float::OrderedFloat;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use tracing::debug;

// Import custom errors from the exceptions module.
use crate::errors::SpartError;

/// Represents a 2D point with an optional payload.
///
/// ### Example
///
/// ```
/// use spart::geometry::Point2D;
/// // Use an explicit type parameter (here, `()`) so that the type can be inferred.
/// let pt: Point2D<()> = Point2D::new(1.0, 2.0, None);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Point2D<T> {
    /// The x-coordinate of the point.
    pub x: f64,
    /// The y-coordinate of the point.
    pub y: f64,
    /// Optional associated data.
    pub data: Option<T>,
}

impl<T: PartialEq> PartialEq for Point2D<T> {
    fn eq(&self, other: &Self) -> bool {
        OrderedFloat(self.x) == OrderedFloat(other.x)
            && OrderedFloat(self.y) == OrderedFloat(other.y)
            && self.data == other.data
    }
}

impl<T: Eq> Eq for Point2D<T> {}

impl<T: PartialOrd> PartialOrd for Point2D<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (OrderedFloat(self.x), OrderedFloat(self.y))
            .partial_cmp(&(OrderedFloat(other.x), OrderedFloat(other.y)))
        {
            Some(Ordering::Equal) => self.data.partial_cmp(&other.data),
            other => other,
        }
    }
}

/// A trait for defining distance metrics.
pub trait DistanceMetric<P> {
    /// Computes the squared distance between two points.
    fn distance_sq(p1: &P, p2: &P) -> f64;
}

/// A struct for Euclidean distance calculations.
pub struct EuclideanDistance;

impl<T> DistanceMetric<Point2D<T>> for EuclideanDistance {
    fn distance_sq(p1: &Point2D<T>, p2: &Point2D<T>) -> f64 {
        (p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)
    }
}

impl<T> DistanceMetric<Point3D<T>> for EuclideanDistance {
    fn distance_sq(p1: &Point3D<T>, p2: &Point3D<T>) -> f64 {
        (p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2) + (p1.z - p2.z).powi(2)
    }
}

impl<T: Ord> Ord for Point2D<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        match (OrderedFloat(self.x), OrderedFloat(self.y))
            .cmp(&(OrderedFloat(other.x), OrderedFloat(other.y)))
        {
            Ordering::Equal => self.data.cmp(&other.data),
            other => other,
        }
    }
}

impl<T> Point2D<T> {
    /// Creates a new `Point2D` with the given coordinates and optional data.
    ///
    /// # Arguments
    ///
    /// * `x` - The x-coordinate.
    /// * `y` - The y-coordinate.
    /// * `data` - Optional data associated with the point.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Point2D;
    /// let pt: Point2D<()> = Point2D::new(1.0, 2.0, None);
    /// ```
    pub fn new(x: f64, y: f64, data: Option<T>) -> Self {
        let pt = Self { x, y, data };
        debug!("Point2D::new() -> x: {}, y: {}", pt.x, pt.y);
        pt
    }

    /// Computes the squared Euclidean distance between this point and another.
    ///
    /// # Arguments
    ///
    /// * `other` - The other point.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Point2D;
    /// let a: Point2D<()> = Point2D::new(0.0, 0.0, None);
    /// let b: Point2D<()> = Point2D::new(3.0, 4.0, None);
    /// assert_eq!(a.distance_sq(&b), 25.0);
    /// ```
    pub fn distance_sq(&self, other: &Point2D<T>) -> f64 {
        let dist = (self.x - other.x).powi(2) + (self.y - other.y).powi(2);
        debug!(
            "Point2D::distance_sq(): self: (x: {}, y: {}), other: (x: {}, y: {}), result: {}",
            self.x, self.y, other.x, other.y, dist
        );
        dist
    }
}

/// Represents a rectangle in 2D space.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Rectangle {
    /// The x-coordinate of the rectangle's top-left corner.
    pub x: f64,
    /// The y-coordinate of the rectangle's top-left corner.
    pub y: f64,
    /// The width of the rectangle.
    pub width: f64,
    /// The height of the rectangle.
    pub height: f64,
}

impl Rectangle {
    /// Determines if the rectangle contains the given point.
    ///
    /// # Arguments
    ///
    /// * `point` - The point to test.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::{Rectangle, Point2D};
    /// let rect = Rectangle { x: 0.0, y: 0.0, width: 10.0, height: 10.0 };
    /// let pt: Point2D<()> = Point2D::new(5.0, 5.0, None);
    /// assert!(rect.contains(&pt));
    /// ```
    pub fn contains<T>(&self, point: &Point2D<T>) -> bool {
        let res = point.x >= self.x
            && point.x <= self.x + self.width
            && point.y >= self.y
            && point.y <= self.y + self.height;
        debug!(
            "Rectangle::contains(): self: (x: {}, y: {}, w: {}, h: {}), point: (x: {}, y: {}), result: {}",
            self.x, self.y, self.width, self.height, point.x, point.y, res
        );
        res
    }

    /// Determines whether this rectangle intersects with another.
    ///
    /// # Arguments
    ///
    /// * `other` - The other rectangle.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Rectangle;
    /// let a = Rectangle { x: 0.0, y: 0.0, width: 10.0, height: 10.0 };
    /// let b = Rectangle { x: 5.0, y: 5.0, width: 10.0, height: 10.0 };
    /// assert!(a.intersects(&b));
    /// ```
    pub fn intersects(&self, other: &Rectangle) -> bool {
        let res = !(other.x > self.x + self.width
            || other.x + other.width < self.x
            || other.y > self.y + self.height
            || other.y + other.height < self.y);
        debug!(
            "Rectangle::intersects(): self: (x: {}, y: {}, w: {}, h: {}), other: (x: {}, y: {}, w: {}, h: {}), result: {}",
            self.x,
            self.y,
            self.width,
            self.height,
            other.x,
            other.y,
            other.width,
            other.height,
            res
        );
        res
    }

    /// Computes the area of the rectangle.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Rectangle;
    /// let rect = Rectangle { x: 0.0, y: 0.0, width: 4.0, height: 5.0 };
    /// assert_eq!(rect.area(), 20.0);
    /// ```
    pub fn area(&self) -> f64 {
        let area = self.width * self.height;
        debug!(
            "Rectangle::area(): (w: {}, h: {}) -> {}",
            self.width, self.height, area
        );
        area
    }

    /// Computes the union of this rectangle with another.
    ///
    /// The union is defined as the smallest rectangle that completely contains both rectangles.
    ///
    /// # Arguments
    ///
    /// * `other` - The other rectangle.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Rectangle;
    /// let a = Rectangle { x: 0.0, y: 0.0, width: 5.0, height: 5.0 };
    /// let b = Rectangle { x: 3.0, y: 3.0, width: 5.0, height: 5.0 };
    /// let union_rect = a.union(&b);
    /// assert_eq!(union_rect.x, 0.0);
    /// ```
    pub fn union(&self, other: &Rectangle) -> Rectangle {
        let x1 = self.x.min(other.x);
        let y1 = self.y.min(other.y);
        let x2 = (self.x + self.width).max(other.x + other.width);
        let y2 = (self.y + self.height).max(other.y + other.height);

        // Add small epsilon to width/height to account for floating-point precision errors
        // This guarantees that corner points are always contained in the union
        let eps = f64::EPSILON * 4.0 * (x2.abs() + x1.abs()).max(1.0);
        let width = (x2 - x1) + eps;

        let eps_y = f64::EPSILON * 4.0 * (y2.abs() + y1.abs()).max(1.0);
        let height = (y2 - y1) + eps_y;

        let union_rect = Rectangle {
            x: x1,
            y: y1,
            width,
            height,
        };
        debug!(
            "Rectangle::union(): self: (x: {}, y: {}, w: {}, h: {}), other: (x: {}, y: {}, w: {}, h: {}), result: (x: {}, y: {}, w: {}, h: {})",
            self.x,
            self.y,
            self.width,
            self.height,
            other.x,
            other.y,
            other.width,
            other.height,
            union_rect.x,
            union_rect.y,
            union_rect.width,
            union_rect.height
        );
        union_rect
    }

    /// Computes the enlargement needed to include another rectangle.
    ///
    /// The enlargement is defined as the difference between the area of the union and the area of this rectangle.
    ///
    /// # Arguments
    ///
    /// * `other` - The other rectangle.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Rectangle;
    /// let a = Rectangle { x: 0.0, y: 0.0, width: 4.0, height: 4.0 };
    /// let b = Rectangle { x: 2.0, y: 2.0, width: 4.0, height: 4.0 };
    /// let enlargement = a.enlargement(&b);
    /// assert!(enlargement >= 0.0);
    /// ```
    pub fn enlargement(&self, other: &Rectangle) -> f64 {
        let union_rect = self.union(other);
        let self_area = self.area();
        let union_area = union_rect.area();
        let extra = union_area - self_area;
        debug!(
            "Rectangle::enlargement(): self area: {}, union area: {}, enlargement: {}",
            self_area, union_area, extra
        );
        extra
    }
}

/// Represents a 3D point with an optional payload.
///
/// # Examples
///
/// ```
/// use spart::geometry::Point3D;
/// let pt: Point3D<()> = Point3D::new(1.0, 2.0, 3.0, None);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Point3D<T> {
    /// The x-coordinate of the point.
    pub x: f64,
    /// The y-coordinate of the point.
    pub y: f64,
    /// The z-coordinate of the point.
    pub z: f64,
    /// Optional associated data.
    pub data: Option<T>,
}

impl<T: PartialEq> PartialEq for Point3D<T> {
    fn eq(&self, other: &Self) -> bool {
        OrderedFloat(self.x) == OrderedFloat(other.x)
            && OrderedFloat(self.y) == OrderedFloat(other.y)
            && OrderedFloat(self.z) == OrderedFloat(other.z)
            && self.data == other.data
    }
}

impl<T: Eq> Eq for Point3D<T> {}

impl<T: PartialOrd> PartialOrd for Point3D<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (
            OrderedFloat(self.x),
            OrderedFloat(self.y),
            OrderedFloat(self.z),
        )
            .partial_cmp(&(
                OrderedFloat(other.x),
                OrderedFloat(other.y),
                OrderedFloat(other.z),
            )) {
            Some(Ordering::Equal) => self.data.partial_cmp(&other.data),
            other => other,
        }
    }
}

impl<T: Ord> Ord for Point3D<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        match (
            OrderedFloat(self.x),
            OrderedFloat(self.y),
            OrderedFloat(self.z),
        )
            .cmp(&(
                OrderedFloat(other.x),
                OrderedFloat(other.y),
                OrderedFloat(other.z),
            )) {
            Ordering::Equal => self.data.cmp(&other.data),
            other => other,
        }
    }
}

impl<T> Point3D<T> {
    /// Creates a new `Point3D` with the given coordinates and optional data.
    ///
    /// # Arguments
    ///
    /// * `x` - The x-coordinate.
    /// * `y` - The y-coordinate.
    /// * `z` - The z-coordinate.
    /// * `data` - Optional data associated with the point.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Point3D;
    /// let pt: Point3D<()> = Point3D::new(1.0, 2.0, 3.0, None);
    /// ```
    pub fn new(x: f64, y: f64, z: f64, data: Option<T>) -> Self {
        let pt = Self { x, y, z, data };
        debug!("Point3D::new() -> x: {}, y: {}, z: {}", pt.x, pt.y, pt.z);
        pt
    }

    /// Computes the squared Euclidean distance between this point and another.
    ///
    /// # Arguments
    ///
    /// * `other` - The other 3D point.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Point3D;
    /// let a: Point3D<()> = Point3D::new(0.0, 0.0, 0.0, None);
    /// let b: Point3D<()> = Point3D::new(1.0, 2.0, 2.0, None);
    /// assert_eq!(a.distance_sq(&b), 9.0);
    /// ```
    pub fn distance_sq(&self, other: &Point3D<T>) -> f64 {
        let dist =
            (self.x - other.x).powi(2) + (self.y - other.y).powi(2) + (self.z - other.z).powi(2);
        debug!(
            "Point3D::distance_sq(): self: (x: {}, y: {}, z: {}), other: (x: {}, y: {}, z: {}), result: {}",
            self.x, self.y, self.z, other.x, other.y, other.z, dist
        );
        dist
    }
}

/// Represents a cube (or cuboid) in 3D space.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Cube {
    /// The x-coordinate of the cube's top-left-front corner.
    pub x: f64,
    /// The y-coordinate of the cube's top-left-front corner.
    pub y: f64,
    /// The z-coordinate of the cube's top-left-front corner.
    pub z: f64,
    /// The width of the cube.
    pub width: f64,
    /// The height of the cube.
    pub height: f64,
    /// The depth of the cube.
    pub depth: f64,
}

impl Cube {
    /// Determines if the cube contains the given 3D point.
    ///
    /// # Arguments
    ///
    /// * `point` - The 3D point to test.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::{Cube, Point3D};
    /// let cube = Cube { x: 0.0, y: 0.0, z: 0.0, width: 10.0, height: 10.0, depth: 10.0 };
    /// let pt: Point3D<()> = Point3D::new(5.0, 5.0, 5.0, None);
    /// assert!(cube.contains(&pt));
    /// ```
    pub fn contains<T>(&self, point: &Point3D<T>) -> bool {
        let res = point.x >= self.x
            && point.x <= self.x + self.width
            && point.y >= self.y
            && point.y <= self.y + self.height
            && point.z >= self.z
            && point.z <= self.z + self.depth;
        debug!(
            "Cube::contains(): self: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {}), point: (x: {}, y: {}, z: {}), result: {}",
            self.x,
            self.y,
            self.z,
            self.width,
            self.height,
            self.depth,
            point.x,
            point.y,
            point.z,
            res
        );
        res
    }

    /// Determines whether this cube intersects with another cube.
    ///
    /// # Arguments
    ///
    /// * `other` - The other cube.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Cube;
    /// let a = Cube { x: 0.0, y: 0.0, z: 0.0, width: 5.0, height: 5.0, depth: 5.0 };
    /// let b = Cube { x: 3.0, y: 3.0, z: 3.0, width: 5.0, height: 5.0, depth: 5.0 };
    /// assert!(a.intersects(&b));
    /// ```
    pub fn intersects(&self, other: &Cube) -> bool {
        let res = !(other.x > self.x + self.width
            || other.x + other.width < self.x
            || other.y > self.y + self.height
            || other.y + other.height < self.y
            || other.z > self.z + self.depth
            || other.z + other.depth < self.z);
        debug!(
            "Cube::intersects(): self: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {}), other: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {}), result: {}",
            self.x,
            self.y,
            self.z,
            self.width,
            self.height,
            self.depth,
            other.x,
            other.y,
            other.z,
            other.width,
            other.height,
            other.depth,
            res
        );
        res
    }

    /// Computes the volume of the cube.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Cube;
    /// let cube = Cube { x: 0.0, y: 0.0, z: 0.0, width: 2.0, height: 3.0, depth: 4.0 };
    /// assert_eq!(cube.area(), 24.0);
    /// ```
    pub fn area(&self) -> f64 {
        let vol = self.width * self.height * self.depth;
        debug!(
            "Cube::area(): (w: {}, h: {}, d: {}) -> {}",
            self.width, self.height, self.depth, vol
        );
        vol
    }

    /// Computes the union of this cube with another.
    ///
    /// The union is defined as the smallest cube that completely contains both cubes.
    ///
    /// # Arguments
    ///
    /// * `other` - The other cube.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Cube;
    /// let a = Cube { x: 0.0, y: 0.0, z: 0.0, width: 3.0, height: 3.0, depth: 3.0 };
    /// let b = Cube { x: 2.0, y: 2.0, z: 2.0, width: 3.0, height: 3.0, depth: 3.0 };
    /// let union_cube = a.union(&b);
    /// assert_eq!(union_cube.x, 0.0);
    /// ```
    pub fn union(&self, other: &Cube) -> Cube {
        let x1 = self.x.min(other.x);
        let y1 = self.y.min(other.y);
        let z1 = self.z.min(other.z);
        let x2 = (self.x + self.width).max(other.x + other.width);
        let y2 = (self.y + self.height).max(other.y + other.height);
        let z2 = (self.z + self.depth).max(other.z + other.depth);

        // Add small epsilon to dimensions to account for floating-point precision errors
        let eps_x = f64::EPSILON * 4.0 * (x2.abs() + x1.abs()).max(1.0);
        let eps_y = f64::EPSILON * 4.0 * (y2.abs() + y1.abs()).max(1.0);
        let eps_z = f64::EPSILON * 4.0 * (z2.abs() + z1.abs()).max(1.0);

        let union_cube = Cube {
            x: x1,
            y: y1,
            z: z1,
            width: (x2 - x1) + eps_x,
            height: (y2 - y1) + eps_y,
            depth: (z2 - z1) + eps_z,
        };
        debug!(
            "Cube::union(): self: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {}), other: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {}), result: (x: {}, y: {}, z: {}, w: {}, h: {}, d: {})",
            self.x,
            self.y,
            self.z,
            self.width,
            self.height,
            self.depth,
            other.x,
            other.y,
            other.z,
            other.width,
            other.height,
            other.depth,
            union_cube.x,
            union_cube.y,
            union_cube.z,
            union_cube.width,
            union_cube.height,
            union_cube.depth
        );
        union_cube
    }

    /// Computes the enlargement needed to include another cube.
    ///
    /// The enlargement is defined as the difference between the volume of the union and the volume of this cube.
    ///
    /// # Arguments
    ///
    /// * `other` - The other cube.
    ///
    /// # Examples
    ///
    /// ```
    /// use spart::geometry::Cube;
    /// let a = Cube { x: 0.0, y: 0.0, z: 0.0, width: 2.0, height: 2.0, depth: 2.0 };
    /// let b = Cube { x: 1.0, y: 1.0, z: 1.0, width: 2.0, height: 2.0, depth: 2.0 };
    /// let enlargement = a.enlargement(&b);
    /// assert!(enlargement >= 0.0);
    /// ```
    pub fn enlargement(&self, other: &Cube) -> f64 {
        let union_cube = self.union(other);
        let self_area = self.area();
        let union_area = union_cube.area();
        let extra = union_area - self_area;
        debug!(
            "Cube::enlargement(): self volume: {}, union volume: {}, enlargement: {}",
            self_area, union_area, extra
        );
        extra
    }
}

/// Trait for types that can provide the center and extent along a specified dimension.
pub trait BSPBounds {
    /// The number of dimensions supported.
    const DIM: usize;
    /// Returns the center coordinate along the specified dimension.
    ///
    /// # Arguments
    ///
    /// * `dim` - The dimension index.
    ///
    /// # Errors
    ///
    /// Returns `SpartError::InvalidDimension` if `dim` is not within the valid range.
    fn center(&self, dim: usize) -> Result<f64, SpartError>;
    /// Returns the extent (width, height, or depth) along the specified dimension.
    ///
    /// # Arguments
    ///
    /// * `dim` - The dimension index.
    ///
    /// # Errors
    ///
    /// Returns `SpartError::InvalidDimension` if `dim` is not within the valid range.
    fn extent(&self, dim: usize) -> Result<f64, SpartError>;
}

impl BSPBounds for Rectangle {
    const DIM: usize = 2;
    fn center(&self, dim: usize) -> Result<f64, SpartError> {
        match dim {
            0 => Ok(self.x + self.width / 2.0),
            1 => Ok(self.y + self.height / 2.0),
            _ => Err(SpartError::InvalidDimension {
                requested: dim,
                available: 2,
            }),
        }
    }
    fn extent(&self, dim: usize) -> Result<f64, SpartError> {
        match dim {
            0 => Ok(self.width),
            1 => Ok(self.height),
            _ => Err(SpartError::InvalidDimension {
                requested: dim,
                available: 2,
            }),
        }
    }
}

impl BSPBounds for Cube {
    const DIM: usize = 3;
    fn center(&self, dim: usize) -> Result<f64, SpartError> {
        match dim {
            0 => Ok(self.x + self.width / 2.0),
            1 => Ok(self.y + self.height / 2.0),
            2 => Ok(self.z + self.depth / 2.0),
            _ => Err(SpartError::InvalidDimension {
                requested: dim,
                available: 3,
            }),
        }
    }
    fn extent(&self, dim: usize) -> Result<f64, SpartError> {
        match dim {
            0 => Ok(self.width),
            1 => Ok(self.height),
            2 => Ok(self.depth),
            _ => Err(SpartError::InvalidDimension {
                requested: dim,
                available: 3,
            }),
        }
    }
}

/// Trait representing a bounding volume, such as a rectangle or cube.
///
/// This trait abstracts common operations for geometric volumes used in indexing.
pub trait BoundingVolume: Clone {
    /// Returns the area (or volume for 3D objects) of the bounding volume.
    fn area(&self) -> f64;
    /// Returns the smallest bounding volume that contains both `self` and `other`.
    fn union(&self, other: &Self) -> Self;
    /// Computes the enlargement required to include `other` in the bounding volume.
    ///
    /// By default, this is calculated as `union(other).area() - self.area()`.
    fn enlargement(&self, other: &Self) -> f64 {
        self.union(other).area() - self.area()
    }
    /// Determines whether the bounding volume intersects with another.
    fn intersects(&self, other: &Self) -> bool;

    /// Computes the overlap between two bounding volumes
    fn overlap(&self, other: &Self) -> f64;

    /// Computes the margin of a bounding box
    fn margin(&self) -> f64;
}

impl BoundingVolume for Rectangle {
    fn area(&self) -> f64 {
        let a = Rectangle::area(self);
        debug!("BoundingVolume (Rectangle)::area() -> {}", a);
        a
    }
    fn union(&self, other: &Self) -> Self {
        let u = Rectangle::union(self, other);
        debug!("BoundingVolume (Rectangle)::union() computed.");
        u
    }
    fn intersects(&self, other: &Self) -> bool {
        let i = Rectangle::intersects(self, other);
        debug!("BoundingVolume (Rectangle)::intersects() -> {}", i);
        i
    }
    fn overlap(&self, other: &Self) -> f64 {
        let overlap_x = (self.x + self.width).min(other.x + other.width) - self.x.max(other.x);
        let overlap_y = (self.y + self.height).min(other.y + other.height) - self.y.max(other.y);
        if overlap_x > 0.0 && overlap_y > 0.0 {
            overlap_x * overlap_y
        } else {
            0.0
        }
    }

    fn margin(&self) -> f64 {
        2.0 * (self.width + self.height)
    }
}

impl BoundingVolume for Cube {
    fn area(&self) -> f64 {
        let a = Cube::area(self);
        debug!("BoundingVolume (Cube)::area() -> {}", a);
        a
    }
    fn union(&self, other: &Self) -> Self {
        let u = Cube::union(self, other);
        debug!("BoundingVolume (Cube)::union() computed.");
        u
    }
    fn intersects(&self, other: &Self) -> bool {
        let i = Cube::intersects(self, other);
        debug!("BoundingVolume (Cube)::intersects() -> {}", i);
        i
    }
    fn overlap(&self, other: &Self) -> f64 {
        let overlap_x = (self.x + self.width).min(other.x + other.width) - self.x.max(other.x);
        let overlap_y = (self.y + self.height).min(other.y + other.height) - self.y.max(other.y);
        let overlap_z = (self.z + self.depth).min(other.z + other.depth) - self.z.max(other.z);
        if overlap_x > 0.0 && overlap_y > 0.0 && overlap_z > 0.0 {
            overlap_x * overlap_y * overlap_z
        } else {
            0.0
        }
    }

    fn margin(&self) -> f64 {
        2.0 * (self.width + self.height + self.depth)
    }
}

/// Represents an item in a heap, typically used for nearest neighbor or best-first search algorithms.
///
/// The `neg_distance` field is used to order items in a max-heap by their (negated) distance value.
#[derive(Debug)]
pub struct HeapItem<T: Clone> {
    /// The negated distance, used for ordering.
    pub neg_distance: OrderedFloat<f64>,
    /// An optional 2D point associated with the heap item.
    pub point_2d: Option<Point2D<T>>,
    /// An optional 3D point associated with the heap item.
    pub point_3d: Option<Point3D<T>>,
}

impl<T: Clone> PartialEq for HeapItem<T> {
    fn eq(&self, other: &Self) -> bool {
        self.neg_distance == other.neg_distance
    }
}

impl<T: Clone> Eq for HeapItem<T> {}

impl<T: Clone> PartialOrd for HeapItem<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T: Clone> Ord for HeapItem<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        other.neg_distance.cmp(&self.neg_distance)
    }
}

/// Trait for types that can compute the minimum distance to a given query.
pub trait HasMinDistance<Q> {
    /// Computes the minimum distance from the bounding volume to the given query.
    fn min_distance(&self, query: &Q) -> f64;
}

/// Trait for constructing a bounding volume from a point and a radius.
pub trait BoundingVolumeFromPoint<Q>: BoundingVolume {
    /// Creates a bounding volume that encapsulates a point with the specified radius.
    fn from_point_radius(query: &Q, radius: f64) -> Self;
}

impl<T> HasMinDistance<Point2D<T>> for Rectangle {
    fn min_distance(&self, point: &Point2D<T>) -> f64 {
        let dx = if point.x < self.x {
            self.x - point.x
        } else if point.x > self.x + self.width {
            point.x - (self.x + self.width)
        } else {
            0.0
        };
        let dy = if point.y < self.y {
            self.y - point.y
        } else if point.y > self.y + self.height {
            point.y - (self.y + self.height)
        } else {
            0.0
        };
        (dx * dx + dy * dy).sqrt()
    }
}

impl<T> BoundingVolumeFromPoint<Point2D<T>> for Rectangle {
    fn from_point_radius(query: &Point2D<T>, radius: f64) -> Self {
        Rectangle {
            x: query.x - radius,
            y: query.y - radius,
            width: 2.0 * radius,
            height: 2.0 * radius,
        }
    }
}

impl<T> HasMinDistance<Point3D<T>> for Cube {
    fn min_distance(&self, point: &Point3D<T>) -> f64 {
        let dx = if point.x < self.x {
            self.x - point.x
        } else if point.x > self.x + self.width {
            point.x - (self.x + self.width)
        } else {
            0.0
        };
        let dy = if point.y < self.y {
            self.y - point.y
        } else if point.y > self.y + self.height {
            point.y - (self.y + self.height)
        } else {
            0.0
        };
        let dz = if point.z < self.z {
            self.z - point.z
        } else if point.z > self.z + self.depth {
            point.z - (self.z + self.depth)
        } else {
            0.0
        };
        (dx * dx + dy * dy + dz * dz).sqrt()
    }
}

impl<T> BoundingVolumeFromPoint<Point3D<T>> for Cube {
    fn from_point_radius(query: &Point3D<T>, radius: f64) -> Self {
        Cube {
            x: query.x - radius,
            y: query.y - radius,
            z: query.z - radius,
            width: 2.0 * radius,
            height: 2.0 * radius,
            depth: 2.0 * radius,
        }
    }
}

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

    #[test]
    fn test_rectangle_contains_edges() {
        let rect = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 10.0,
            height: 10.0,
        };
        let corners = [
            Point2D::new(0.0, 0.0, None::<()>),
            Point2D::new(10.0, 0.0, None::<()>),
            Point2D::new(0.0, 10.0, None::<()>),
            Point2D::new(10.0, 10.0, None::<()>),
        ];
        for corner in corners {
            assert!(rect.contains(&corner));
        }
    }

    #[test]
    fn test_rectangle_intersects_touching_edges() {
        let rect = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 10.0,
            height: 10.0,
        };
        let touching = Rectangle {
            x: 10.0,
            y: 2.0,
            width: 5.0,
            height: 5.0,
        };
        let separate = Rectangle {
            x: 10.01,
            y: 0.0,
            width: 5.0,
            height: 5.0,
        };
        assert!(rect.intersects(&touching));
        assert!(!rect.intersects(&separate));
    }

    #[test]
    fn test_cube_contains_edges() {
        let cube = Cube {
            x: 0.0,
            y: 0.0,
            z: 0.0,
            width: 10.0,
            height: 10.0,
            depth: 10.0,
        };
        let corners = [
            Point3D::new(0.0, 0.0, 0.0, None::<()>),
            Point3D::new(10.0, 0.0, 0.0, None::<()>),
            Point3D::new(0.0, 10.0, 0.0, None::<()>),
            Point3D::new(0.0, 0.0, 10.0, None::<()>),
            Point3D::new(10.0, 10.0, 10.0, None::<()>),
        ];
        for corner in corners {
            assert!(cube.contains(&corner));
        }
    }

    #[test]
    fn test_min_distance_inside_is_zero() {
        let rect = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 10.0,
            height: 10.0,
        };
        let inside = Point2D::new(5.0, 5.0, None::<()>);
        assert_eq!(rect.min_distance(&inside), 0.0);
    }

    #[test]
    fn test_bounding_volume_from_point_radius() {
        let query = Point2D::new(1.0, 2.0, None::<()>);
        let rect = Rectangle::from_point_radius(&query, 3.0);
        assert_eq!(rect.x, -2.0);
        assert_eq!(rect.y, -1.0);
        assert_eq!(rect.width, 6.0);
        assert_eq!(rect.height, 6.0);

        let query3 = Point3D::new(1.0, 2.0, 3.0, None::<()>);
        let cube = Cube::from_point_radius(&query3, 2.0);
        assert_eq!(cube.x, -1.0);
        assert_eq!(cube.y, 0.0);
        assert_eq!(cube.z, 1.0);
        assert_eq!(cube.width, 4.0);
        assert_eq!(cube.height, 4.0);
        assert_eq!(cube.depth, 4.0);
    }

    #[test]
    fn test_cube_intersects_touching_edges() {
        let c1 = Cube {
            x: 0.0,
            y: 0.0,
            z: 0.0,
            width: 10.0,
            height: 10.0,
            depth: 10.0,
        };
        let c2 = Cube {
            x: 10.0,
            y: 0.0,
            z: 0.0,
            width: 5.0,
            height: 5.0,
            depth: 5.0,
        };
        assert!(c1.intersects(&c2));
    }

    #[test]
    fn test_triangle_inequality_distance() {
        let p1 = Point2D::new(0.0, 0.0, Some(1));
        let p2 = Point2D::new(3.0, 0.0, Some(2));
        let p3 = Point2D::new(3.0, 4.0, Some(3));

        let d12 = p1.distance_sq(&p2).sqrt();
        let d23 = p2.distance_sq(&p3).sqrt();
        let d13 = p1.distance_sq(&p3).sqrt();

        assert!(d13 <= d12 + d23 + 1e-9);
    }

    #[test]
    fn test_rectangle_union_negative_coords_contains_corners() {
        let r1 = Rectangle {
            x: 0.0,
            y: 0.0,
            width: 111.08676433386941,
            height: 1.0,
        };
        let r2 = Rectangle {
            x: -191.20362538993982,
            y: 0.0,
            width: 1.0,
            height: 1.0,
        };

        let union = r1.union(&r2);

        let r1_min: Point2D<()> = Point2D::new(r1.x, r1.y, None);
        let r1_max: Point2D<()> = Point2D::new(r1.x + r1.width, r1.y + r1.height, None);
        assert!(union.contains(&r1_min));
        assert!(union.contains(&r1_max));

        let r2_min: Point2D<()> = Point2D::new(r2.x, r2.y, None);
        let r2_max: Point2D<()> = Point2D::new(r2.x + r2.width, r2.y + r2.height, None);
        assert!(union.contains(&r2_min));
        assert!(union.contains(&r2_max));
    }
}