euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
use super::*;

/// Geometric helpers for axis-aligned 2D bounds `Bounds2D`.
impl Bounds2D {
    /// Creates a normalized `Bounds2D` ensuring `min <= max` per axis.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - First corner coordinate.
    /// - `Vec2` - Opposite corner coordinate.
    ///
    /// # Returns
    ///
    /// - `Self` - Normalized axis-aligned 2D rectangle.
    #[must_use]
    pub fn new(corner_a: Vec2, corner_b: Vec2) -> Self {
        let min_x: f32 = corner_a.get_x().min(corner_b.get_x());
        let min_y: f32 = corner_a.get_y().min(corner_b.get_y());
        let max_x: f32 = corner_a.get_x().max(corner_b.get_x());
        let max_y: f32 = corner_a.get_y().max(corner_b.get_y());
        Self {
            min: Vec2::new(min_x, min_y),
            max: Vec2::new(max_x, max_y),
        }
    }

    /// Creates a `Bounds2D` centered at `center` with positive `half_extents`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Center point.
    /// - `Vec2` - Half-width and half-height extents.
    ///
    /// # Returns
    ///
    /// - `Self` - Axis-aligned 2D rectangle.
    #[must_use]
    pub fn from_center_half(center: Vec2, half_extents: Vec2) -> Self {
        let hx: f32 = half_extents.get_x().abs();
        let hy: f32 = half_extents.get_y().abs();
        Self {
            min: Vec2::new(center.get_x() - hx, center.get_y() - hy),
            max: Vec2::new(center.get_x() + hx, center.get_y() + hy),
        }
    }

    /// Returns the geometric center of this rectangle.
    ///
    /// # Returns
    ///
    /// - `Vec2` - Center coordinates.
    #[must_use]
    pub fn center(&self) -> Vec2 {
        Vec2::new(
            (self.get_min().get_x() + self.get_max().get_x()) * 0.5,
            (self.get_min().get_y() + self.get_max().get_y()) * 0.5,
        )
    }

    /// Returns width and height `(max - min)` of this rectangle.
    ///
    /// # Returns
    ///
    /// - `Vec2` - Rectangle size vector.
    #[must_use]
    pub fn size(&self) -> Vec2 {
        Vec2::new(
            self.get_max().get_x() - self.get_min().get_x(),
            self.get_max().get_y() - self.get_min().get_y(),
        )
    }

    /// Tests whether `point` lies inside or on the boundary of this rectangle.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query 2D point.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when contained inclusively.
    #[must_use]
    pub fn contains_point(&self, point: Vec2) -> bool {
        let mn: Vec2 = self.get_min();
        let mx: Vec2 = self.get_max();
        point.get_x() >= mn.get_x()
            && point.get_x() <= mx.get_x()
            && point.get_y() >= mn.get_y()
            && point.get_y() <= mx.get_y()
    }

    /// Tests whether this rectangle overlaps `other` inclusively.
    ///
    /// # Arguments
    ///
    /// - `Self` - Other 2D rectangle.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when overlapping.
    #[must_use]
    pub fn intersects(&self, other: Self) -> bool {
        let lmin: Vec2 = self.get_min();
        let lmax: Vec2 = self.get_max();
        let rmin: Vec2 = other.get_min();
        let rmax: Vec2 = other.get_max();
        lmin.get_x() <= rmax.get_x()
            && lmax.get_x() >= rmin.get_x()
            && lmin.get_y() <= rmax.get_y()
            && lmax.get_y() >= rmin.get_y()
    }

    /// Computes squared minimum Euclidean distance from `point` to this rectangle.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query 2D point.
    ///
    /// # Returns
    ///
    /// - `f32` - Zero inside the rectangle, or squared distance to its nearest edge/corner.
    #[must_use]
    pub fn min_dist_sq_to_point(&self, point: Vec2) -> f32 {
        let mn: Vec2 = self.get_min();
        let mx: Vec2 = self.get_max();
        let cx: f32 = point.get_x().clamp(mn.get_x(), mx.get_x());
        let cy: f32 = point.get_y().clamp(mn.get_y(), mx.get_y());
        let dx: f32 = point.get_x() - cx;
        let dy: f32 = point.get_y() - cy;
        dx * dx + dy * dy
    }

    /// Tests whether this rectangle overlaps a closed circle `(center, radius)`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Circle center.
    /// - `f32` - Circle radius.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when overlapping.
    #[must_use]
    pub fn intersects_circle(&self, center: Vec2, radius: f32) -> bool {
        if !radius.is_finite() || radius < 0.0 {
            return false;
        }
        self.min_dist_sq_to_point(center) <= radius * radius
    }
}

/// Default subdivision configuration for `QuadtreeConfig`.
impl Default for QuadtreeConfig {
    /// Returns balanced leaf capacity (`8`) and maximum depth (`10`).
    ///
    /// # Returns
    ///
    /// - `Self` - Default quadtree settings.
    fn default() -> Self {
        Self {
            max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
            max_depth: DEFAULT_QUADTREE_MAX_DEPTH,
        }
    }
}

/// Dynamic insertion, update, removal, and spatial queries for `Quadtree2D`.
impl Quadtree2D {
    /// Creates an empty `Quadtree2D` spanning `root_bounds`.
    ///
    /// # Arguments
    ///
    /// - `Bounds2D` - World-space root bounds.
    /// - `QuadtreeConfig` - Leaf capacity and depth parameters.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty adaptive 2D quadtree.
    #[must_use]
    pub fn new(root_bounds: Bounds2D, config: QuadtreeConfig) -> Self {
        let safe_config: QuadtreeConfig = QuadtreeConfig::new(
            config.get_max_leaf_items().max(1),
            config.get_max_depth().max(1),
        );
        let root: QuadtreeNode2D = QuadtreeNode2D {
            bounds: root_bounds,
            depth: 0,
            children: [SPATIAL_EMPTY_SLOT; 4],
            items: Vec::with_capacity(safe_config.get_max_leaf_items()),
        };
        Self {
            root_bounds,
            config: safe_config,
            nodes: vec![root],
            positions: HashMap::new(),
            scratch: QuadtreeScratch::default(),
        }
    }

    /// Returns the total number of indexed items currently stored in this quadtree.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of stored items.
    #[must_use]
    pub fn len(&self) -> usize {
        self.get_positions().len()
    }

    /// Returns `true` when the quadtree contains no items.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the quadtree is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.get_positions().is_empty()
    }

    /// Removes all items and resets the tree to a single empty root node.
    pub fn clear(&mut self) {
        let root_bounds: Bounds2D = self.get_root_bounds();
        let cap: usize = self.get_config().get_max_leaf_items();
        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
        nodes.clear();
        nodes.push(QuadtreeNode2D {
            bounds: root_bounds,
            depth: 0,
            children: [SPATIAL_EMPTY_SLOT; 4],
            items: Vec::with_capacity(cap),
        });
        self.get_mut_positions().clear();
    }

    /// Computes child quadrant index `0..4` for `point` relative to `bounds` center.
    ///
    /// # Arguments
    ///
    /// - `Bounds2D` - Parent node bounds.
    /// - `Vec2` - Point inside `bounds`.
    ///
    /// # Returns
    ///
    /// - `usize` - Quadrant index (`0`=SW, `1`=SE, `2`=NW, `3`=NE).
    fn quadrant_index(bounds: Bounds2D, point: Vec2) -> usize {
        let center: Vec2 = bounds.center();
        let east: usize = usize::from(point.get_x() >= center.get_x());
        let north: usize = usize::from(point.get_y() >= center.get_y());
        (north << 1) | east
    }

    /// Computes the bounding rectangle of child quadrant `quad_idx` within `bounds`.
    ///
    /// # Arguments
    ///
    /// - `Bounds2D` - Parent node bounds.
    /// - `usize` - Quadrant index in `0..4`.
    ///
    /// # Returns
    ///
    /// - `Bounds2D` - Sub-quadrant bounding rectangle.
    fn quadrant_bounds(bounds: Bounds2D, quad_idx: usize) -> Bounds2D {
        let mn: Vec2 = bounds.get_min();
        let mx: Vec2 = bounds.get_max();
        let center: Vec2 = bounds.center();
        let (x0, x1): (f32, f32) = if (quad_idx & 1) == 0 {
            (mn.get_x(), center.get_x())
        } else {
            (center.get_x(), mx.get_x())
        };
        let (y0, y1): (f32, f32) = if (quad_idx & 2) == 0 {
            (mn.get_y(), center.get_y())
        } else {
            (center.get_y(), mx.get_y())
        };
        Bounds2D::new(Vec2::new(x0, y0), Vec2::new(x1, y1))
    }

    /// Subdivides leaf `node_idx` into four children and redistributes its items.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<QuadtreeNode2D>` - Node arena.
    /// - `usize` - Leaf node index to subdivide.
    /// - `usize` - Initial item capacity for newly created leaf nodes.
    fn subdivide_node(nodes: &mut Vec<QuadtreeNode2D>, node_idx: usize, leaf_cap: usize) {
        let parent_bounds: Bounds2D = nodes[node_idx].bounds;
        let next_depth: usize = nodes[node_idx].depth + 1;
        let base_idx: usize = nodes.len();
        let mut child_indices: [usize; 4] = [SPATIAL_EMPTY_SLOT; 4];
        for (q, slot) in child_indices.iter_mut().enumerate() {
            *slot = base_idx + q;
            nodes.push(QuadtreeNode2D {
                bounds: Self::quadrant_bounds(parent_bounds, q),
                depth: next_depth,
                children: [SPATIAL_EMPTY_SLOT; 4],
                items: Vec::with_capacity(leaf_cap),
            });
        }
        let existing: Vec<SpatialItem2D> = take(&mut nodes[node_idx].items);
        nodes[node_idx].children = child_indices;
        for item in existing {
            let quad: usize = Self::quadrant_index(parent_bounds, item.get_position());
            nodes[child_indices[quad]].items.push(item);
        }
    }

    /// Inserts `item` into the node arena starting at `root_idx`.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<QuadtreeNode2D>` - Node arena.
    /// - `usize` - Starting node index.
    /// - `SpatialItem2D` - Item to insert.
    /// - `QuadtreeConfig` - Subdivision parameters.
    fn insert_into_nodes(
        nodes: &mut Vec<QuadtreeNode2D>,
        mut node_idx: usize,
        item: SpatialItem2D,
        config: QuadtreeConfig,
    ) {
        loop {
            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, item.get_position());
                node_idx = nodes[node_idx].children[quad];
                continue;
            }
            if nodes[node_idx].items.len() >= config.get_max_leaf_items()
                && nodes[node_idx].depth < config.get_max_depth()
            {
                Self::subdivide_node(nodes, node_idx, config.get_max_leaf_items());
                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, item.get_position());
                node_idx = nodes[node_idx].children[quad];
                continue;
            }
            nodes[node_idx].items.push(item);
            break;
        }
    }

    /// Inserts or updates an item `(id, position)`; returns `false` if `position` is outside root bounds or non-finite.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unique item identifier.
    /// - `Vec2` - World-space 2D position.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when inserted or updated inside root bounds.
    pub fn insert(&mut self, id: u64, position: Vec2) -> bool {
        if !position.get_x().is_finite()
            || !position.get_y().is_finite()
            || !self.get_root_bounds().contains_point(position)
        {
            return false;
        }
        if self.get_positions().contains_key(&id) {
            return self.update(id, position);
        }
        let cfg: QuadtreeConfig = self.get_config();
        let item: SpatialItem2D = SpatialItem2D::new(id, position);
        Self::insert_into_nodes(self.get_mut_nodes(), 0, item, cfg);
        let _: Option<Vec2> = self.get_mut_positions().insert(id, position);
        true
    }

    /// Removes the item with identifier `id` from the quadtree.
    ///
    /// # Arguments
    ///
    /// - `u64` - Item identifier to remove.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the item existed and was removed.
    pub fn remove(&mut self, id: u64) -> bool {
        let Some(old_pos) = self.get_mut_positions().remove(&id) else {
            return false;
        };
        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
        let mut node_idx: usize = 0;
        loop {
            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, old_pos);
                node_idx = nodes[node_idx].children[quad];
                continue;
            }
            if let Some(pos_idx) = nodes[node_idx]
                .items
                .iter()
                .position(|entry: &SpatialItem2D| entry.get_id() == id)
            {
                let _: SpatialItem2D = nodes[node_idx].items.swap_remove(pos_idx);
            }
            break;
        }
        true
    }

    /// Moves an existing item `id` to `new_position`, updating in place when remaining in the same leaf.
    ///
    /// # Arguments
    ///
    /// - `u64` - Existing item identifier.
    /// - `Vec2` - New world-space 2D position.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `id` existed and `new_position` lies inside root bounds.
    pub fn update(&mut self, id: u64, new_position: Vec2) -> bool {
        if !new_position.get_x().is_finite()
            || !new_position.get_y().is_finite()
            || !self.get_root_bounds().contains_point(new_position)
        {
            return false;
        }
        let Some(&old_pos) = self.get_positions().get(&id) else {
            return false;
        };
        let mut leaf_idx: usize = 0;
        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
        while nodes[leaf_idx].children[0] != SPATIAL_EMPTY_SLOT {
            let quad: usize = Self::quadrant_index(nodes[leaf_idx].bounds, old_pos);
            leaf_idx = nodes[leaf_idx].children[quad];
        }
        if nodes[leaf_idx].bounds.contains_point(new_position) {
            if let Some(entry) = nodes[leaf_idx]
                .items
                .iter_mut()
                .find(|entry: &&mut SpatialItem2D| entry.get_id() == id)
            {
                entry.set_position(new_position);
            }
            let _: Option<Vec2> = self.get_mut_positions().insert(id, new_position);
            return true;
        }
        let _: bool = self.remove(id);
        self.insert(id, new_position)
    }

    /// Recursively collects all item IDs inside `query_bounds`.
    ///
    /// # Arguments
    ///
    /// - `&[QuadtreeNode2D]` - Node arena slice.
    /// - `usize` - Current node index.
    /// - `Bounds2D` - Query rectangle.
    /// - `&mut Vec<u64>` - Output ID buffer.
    fn query_rect_rec(
        nodes: &[QuadtreeNode2D],
        node_idx: usize,
        query_bounds: Bounds2D,
        out: &mut Vec<u64>,
    ) {
        let node: &QuadtreeNode2D = &nodes[node_idx];
        if !node.bounds.intersects(query_bounds) {
            return;
        }
        if node.children[0] != SPATIAL_EMPTY_SLOT {
            for &child in &node.children {
                Self::query_rect_rec(nodes, child, query_bounds, out);
            }
            return;
        }
        for item in &node.items {
            if query_bounds.contains_point(item.get_position()) {
                out.push(item.get_id());
            }
        }
    }

    /// Queries all items whose positions lie inside `query_bounds`, writing IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Bounds2D` - Axis-aligned query rectangle.
    /// - `&mut Vec<u64>` - Reusable output identifier buffer (cleared first).
    pub fn query_rect(&self, query_bounds: Bounds2D, out: &mut Vec<u64>) {
        out.clear();
        if self.get_nodes().is_empty() {
            return;
        }
        Self::query_rect_rec(self.get_nodes(), 0, query_bounds, out);
    }

    /// Recursively collects all item IDs within closed circle `(center, radius)`.
    ///
    /// # Arguments
    ///
    /// - `&[QuadtreeNode2D]` - Node arena slice.
    /// - `usize` - Current node index.
    /// - `Vec2` - Query circle center.
    /// - `f32` - Query circle radius.
    /// - `f32` - Precomputed squared radius.
    /// - `&mut Vec<u64>` - Output ID buffer.
    fn query_radius_rec(
        nodes: &[QuadtreeNode2D],
        node_idx: usize,
        center: Vec2,
        radius: f32,
        radius_sq: f32,
        out: &mut Vec<u64>,
    ) {
        let node: &QuadtreeNode2D = &nodes[node_idx];
        if !node.bounds.intersects_circle(center, radius) {
            return;
        }
        if node.children[0] != SPATIAL_EMPTY_SLOT {
            for &child in &node.children {
                Self::query_radius_rec(nodes, child, center, radius, radius_sq, out);
            }
            return;
        }
        for item in &node.items {
            if spatial_dist_sq_2d(item.get_position(), center) <= radius_sq {
                out.push(item.get_id());
            }
        }
    }

    /// Queries all items within Euclidean distance `<= radius` of `center`, writing IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query circle center.
    /// - `f32` - Query radius (non-negative).
    /// - `&mut Vec<u64>` - Reusable output identifier buffer (cleared first).
    pub fn query_radius(&self, center: Vec2, radius: f32, out: &mut Vec<u64>) {
        out.clear();
        let valid_radius: bool = radius.is_finite() && radius >= 0.0;
        if !valid_radius || self.get_nodes().is_empty() {
            return;
        }
        Self::query_radius_rec(self.get_nodes(), 0, center, radius, radius * radius, out);
    }

    /// Finds the exact `k` nearest items to `center` using best-first branch-and-bound traversal.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query center point.
    /// - `usize` - Maximum number of nearest neighbors to return.
    /// - `&mut Vec<(u64, f32)>` - Reusable output receiving `(id, euclidean_distance)` sorted ascending.
    pub fn query_k_nearest(&mut self, center: Vec2, k: usize, out: &mut Vec<(u64, f32)>) {
        out.clear();
        if k == 0 || self.get_nodes().is_empty() || self.is_empty() {
            return;
        }
        let mut scratch: QuadtreeScratch = take(self.get_mut_scratch());
        scratch.node_heap.clear();
        scratch.best_items.clear();
        let nodes: &[QuadtreeNode2D] = self.get_nodes();
        let root_dist_sq: f32 = nodes[0].bounds.min_dist_sq_to_point(center);
        spatial_heap_push(&mut scratch.node_heap, root_dist_sq, 0);
        while let Some((node_dist_sq, node_idx)) = spatial_heap_pop(&mut scratch.node_heap) {
            if scratch.best_items.len() == k
                && let Some(&(worst_sq, _)) = scratch.best_items.last()
                && node_dist_sq > worst_sq
            {
                break;
            }
            let node: &QuadtreeNode2D = &nodes[node_idx];
            if node.children[0] != SPATIAL_EMPTY_SLOT {
                for &child in &node.children {
                    let child_dist_sq: f32 = nodes[child].bounds.min_dist_sq_to_point(center);
                    let prune: bool = if scratch.best_items.len() == k {
                        scratch
                            .best_items
                            .last()
                            .is_some_and(|&(worst_sq, _): &(f32, u64)| child_dist_sq > worst_sq)
                    } else {
                        false
                    };
                    if !prune {
                        spatial_heap_push(&mut scratch.node_heap, child_dist_sq, child);
                    }
                }
            } else {
                for item in &node.items {
                    let d_sq: f32 = spatial_dist_sq_2d(item.get_position(), center);
                    let id: u64 = item.get_id();
                    if scratch.best_items.len() < k {
                        scratch.best_items.push((d_sq, id));
                        scratch
                            .best_items
                            .sort_by(|lhs: &(f32, u64), rhs: &(f32, u64)| {
                                lhs.0.total_cmp(&rhs.0).then_with(|| lhs.1.cmp(&rhs.1))
                            });
                    } else if let Some(&(worst_sq, worst_id)) = scratch.best_items.last()
                        && (d_sq < worst_sq || (d_sq == worst_sq && id < worst_id))
                    {
                        let last_slot: usize = scratch.best_items.len() - 1;
                        scratch.best_items[last_slot] = (d_sq, id);
                        scratch
                            .best_items
                            .sort_by(|lhs: &(f32, u64), rhs: &(f32, u64)| {
                                lhs.0.total_cmp(&rhs.0).then_with(|| lhs.1.cmp(&rhs.1))
                            });
                    }
                }
            }
        }
        for &(d_sq, id) in &scratch.best_items {
            out.push((id, d_sq.sqrt()));
        }
        self.set_scratch(scratch);
    }
}

/// Default subdivision configuration for `OctreeConfig`.
impl Default for OctreeConfig {
    /// Returns balanced leaf capacity (`8`) and maximum depth (`8`).
    ///
    /// # Returns
    ///
    /// - `Self` - Default octree settings.
    fn default() -> Self {
        Self {
            max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
            max_depth: DEFAULT_OCTREE_MAX_DEPTH,
        }
    }
}

/// Dynamic insertion, update, removal, and AABB/sphere/ray queries for `Octree3D`.
impl Octree3D {
    /// Creates an empty `Octree3D` spanning `root_bounds`.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - World-space root volume.
    /// - `OctreeConfig` - Leaf capacity and maximum depth parameters.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty adaptive 3D octree.
    #[must_use]
    pub fn new(root_bounds: AxisAlignedBox3D, config: OctreeConfig) -> Self {
        let safe_config: OctreeConfig = OctreeConfig::new(
            config.get_max_leaf_items().max(1),
            config.get_max_depth().max(1),
        );
        let root: OctreeNode3D = OctreeNode3D {
            bounds: root_bounds,
            depth: 0,
            children: [SPATIAL_EMPTY_SLOT; 8],
            items: Vec::with_capacity(safe_config.get_max_leaf_items()),
        };
        Self {
            root_bounds,
            config: safe_config,
            nodes: vec![root],
            item_bounds: HashMap::new(),
        }
    }

    /// Returns the number of indexed items stored in this octree.
    ///
    /// # Returns
    ///
    /// - `usize` - Total stored item count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.get_item_bounds().len()
    }

    /// Returns `true` when the octree contains no items.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.get_item_bounds().is_empty()
    }

    /// Removes all items and resets the octree to a single empty root node.
    pub fn clear(&mut self) {
        let root_bounds: AxisAlignedBox3D = self.get_root_bounds();
        let cap: usize = self.get_config().get_max_leaf_items();
        let nodes: &mut Vec<OctreeNode3D> = self.get_mut_nodes();
        nodes.clear();
        nodes.push(OctreeNode3D {
            bounds: root_bounds,
            depth: 0,
            children: [SPATIAL_EMPTY_SLOT; 8],
            items: Vec::with_capacity(cap),
        });
        self.get_mut_item_bounds().clear();
    }

    /// Computes child octant bounds `oct_idx` in `0..8` of `bounds`.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - Parent bounding box.
    /// - `usize` - Octant bitmask index (`bit 0 = +X`, `bit 1 = +Y`, `bit 2 = +Z`).
    ///
    /// # Returns
    ///
    /// - `AxisAlignedBox3D` - Sub-octant bounding box.
    fn octant_bounds(bounds: AxisAlignedBox3D, oct_idx: usize) -> AxisAlignedBox3D {
        let mn: Vec3 = bounds.get_min();
        let mx: Vec3 = bounds.get_max();
        let c: Vec3 = bounds.center();
        let (x0, x1): (f32, f32) = if (oct_idx & 1) == 0 {
            (mn.get_x(), c.get_x())
        } else {
            (c.get_x(), mx.get_x())
        };
        let (y0, y1): (f32, f32) = if (oct_idx & 2) == 0 {
            (mn.get_y(), c.get_y())
        } else {
            (c.get_y(), mx.get_y())
        };
        let (z0, z1): (f32, f32) = if (oct_idx & 4) == 0 {
            (mn.get_z(), c.get_z())
        } else {
            (c.get_z(), mx.get_z())
        };
        AxisAlignedBox3D::new(Vec3::new(x0, y0, z0), Vec3::new(x1, y1, z1))
    }

    /// Returns the single child octant index that completely encloses `item_box`, if any.
    ///
    /// # Arguments
    ///
    /// - `&[OctreeNode3D]` - Node arena.
    /// - `[usize; 8]` - Child node indices.
    /// - `AxisAlignedBox3D` - Candidate item bounds.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Enclosing child node index, or `None` if `item_box` straddles a split plane.
    fn enclosing_child(
        nodes: &[OctreeNode3D],
        children: [usize; 8],
        item_box: AxisAlignedBox3D,
    ) -> Option<usize> {
        children
            .iter()
            .copied()
            .find(|child: &usize| aabb3d_contains_box(nodes[*child].bounds, item_box))
    }

    /// Subdivides `node_idx` into eight octants and pushes enclosed items into matching children.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<OctreeNode3D>` - Node arena.
    /// - `usize` - Node index to subdivide.
    /// - `usize` - Leaf item capacity hint.
    fn subdivide_node(nodes: &mut Vec<OctreeNode3D>, node_idx: usize, leaf_cap: usize) {
        let parent_bounds: AxisAlignedBox3D = nodes[node_idx].bounds;
        let next_depth: usize = nodes[node_idx].depth + 1;
        let base_idx: usize = nodes.len();
        let mut child_indices: [usize; 8] = [SPATIAL_EMPTY_SLOT; 8];
        for (oct, slot) in child_indices.iter_mut().enumerate() {
            *slot = base_idx + oct;
            nodes.push(OctreeNode3D {
                bounds: Self::octant_bounds(parent_bounds, oct),
                depth: next_depth,
                children: [SPATIAL_EMPTY_SLOT; 8],
                items: Vec::with_capacity(leaf_cap),
            });
        }
        let existing: Vec<SpatialItem3D> = take(&mut nodes[node_idx].items);
        nodes[node_idx].children = child_indices;
        let mut straddling: Vec<SpatialItem3D> = Vec::new();
        for item in existing {
            if let Some(child_idx) = Self::enclosing_child(nodes, child_indices, item.get_bounds())
            {
                nodes[child_idx].items.push(item);
            } else {
                straddling.push(item);
            }
        }
        nodes[node_idx].items = straddling;
    }

    /// Inserts `item` into the octree node arena.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<OctreeNode3D>` - Node arena.
    /// - `usize` - Starting node index.
    /// - `SpatialItem3D` - Item to insert.
    /// - `OctreeConfig` - Subdivision configuration.
    fn insert_into_nodes(
        nodes: &mut Vec<OctreeNode3D>,
        mut node_idx: usize,
        item: SpatialItem3D,
        config: OctreeConfig,
    ) {
        loop {
            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
                let children: [usize; 8] = nodes[node_idx].children;
                if let Some(child_idx) = Self::enclosing_child(nodes, children, item.get_bounds()) {
                    node_idx = child_idx;
                    continue;
                }
                nodes[node_idx].items.push(item);
                break;
            }
            if nodes[node_idx].items.len() >= config.get_max_leaf_items()
                && nodes[node_idx].depth < config.get_max_depth()
            {
                Self::subdivide_node(nodes, node_idx, config.get_max_leaf_items());
                let children: [usize; 8] = nodes[node_idx].children;
                if let Some(child_idx) = Self::enclosing_child(nodes, children, item.get_bounds()) {
                    node_idx = child_idx;
                    continue;
                }
                nodes[node_idx].items.push(item);
                break;
            }
            nodes[node_idx].items.push(item);
            break;
        }
    }

    /// Inserts or updates a 3D bounding-box item; returns `false` if outside root bounds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unique item identifier.
    /// - `AxisAlignedBox3D` - Item axis-aligned bounding box.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when indexed inside root bounds.
    pub fn insert(&mut self, id: u64, bounds: AxisAlignedBox3D) -> bool {
        let norm: AxisAlignedBox3D = AxisAlignedBox3D::new(
            bounds.get_min().min(bounds.get_max()),
            bounds.get_min().max(bounds.get_max()),
        );
        if !aabb3d_contains_box(self.get_root_bounds(), norm) {
            return false;
        }
        if self.get_item_bounds().contains_key(&id) {
            let _: bool = self.remove(id);
        }
        let cfg: OctreeConfig = self.get_config();
        Self::insert_into_nodes(self.get_mut_nodes(), 0, SpatialItem3D::new(id, norm), cfg);
        let _: Option<AxisAlignedBox3D> = self.get_mut_item_bounds().insert(id, norm);
        true
    }

    /// Inserts a point item as a zero-volume `AxisAlignedBox3D` at `position`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Unique item identifier.
    /// - `Vec3` - World-space 3D position.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when indexed inside root bounds.
    pub fn insert_point(&mut self, id: u64, position: Vec3) -> bool {
        self.insert(id, AxisAlignedBox3D::new(position, position))
    }

    /// Removes item `id` from the octree.
    ///
    /// # Arguments
    ///
    /// - `u64` - Item identifier to remove.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when present and removed.
    pub fn remove(&mut self, id: u64) -> bool {
        let Some(old_bounds) = self.get_mut_item_bounds().remove(&id) else {
            return false;
        };
        let nodes: &mut Vec<OctreeNode3D> = self.get_mut_nodes();
        let mut node_idx: usize = 0;
        loop {
            if let Some(pos) = nodes[node_idx]
                .items
                .iter()
                .position(|entry: &SpatialItem3D| entry.get_id() == id)
            {
                let _: SpatialItem3D = nodes[node_idx].items.swap_remove(pos);
                return true;
            }
            if nodes[node_idx].children[0] == SPATIAL_EMPTY_SLOT {
                break;
            }
            let children: [usize; 8] = nodes[node_idx].children;
            if let Some(child_idx) = Self::enclosing_child(nodes, children, old_bounds) {
                node_idx = child_idx;
            } else {
                break;
            }
        }
        true
    }

    /// Updates an existing item's bounding box in the octree.
    ///
    /// # Arguments
    ///
    /// - `u64` - Existing item identifier.
    /// - `AxisAlignedBox3D` - Updated 3D bounding box.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `id` existed and `new_bounds` lies inside root bounds.
    pub fn update(&mut self, id: u64, new_bounds: AxisAlignedBox3D) -> bool {
        if !self.get_item_bounds().contains_key(&id) {
            return false;
        }
        self.insert(id, new_bounds)
    }

    /// Recursively collects all item IDs overlapping `query_box`.
    ///
    /// # Arguments
    ///
    /// - `&[OctreeNode3D]` - Node arena slice.
    /// - `usize` - Active node index.
    /// - `AxisAlignedBox3D` - Query volume.
    /// - `&mut Vec<u64>` - Output ID buffer.
    fn query_aabb_rec(
        nodes: &[OctreeNode3D],
        node_idx: usize,
        query_box: AxisAlignedBox3D,
        out: &mut Vec<u64>,
    ) {
        let node: &OctreeNode3D = &nodes[node_idx];
        if !aabb3d_intersects(node.bounds, query_box) {
            return;
        }
        for item in &node.items {
            if aabb3d_intersects(item.get_bounds(), query_box) {
                out.push(item.get_id());
            }
        }
        if node.children[0] != SPATIAL_EMPTY_SLOT {
            for &child in &node.children {
                Self::query_aabb_rec(nodes, child, query_box, out);
            }
        }
    }

    /// Queries all items overlapping `query_box`, writing matching IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - Query bounding box.
    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
    pub fn query_aabb(&self, query_box: AxisAlignedBox3D, out: &mut Vec<u64>) {
        out.clear();
        if self.get_nodes().is_empty() {
            return;
        }
        Self::query_aabb_rec(self.get_nodes(), 0, query_box, out);
    }

    /// Recursively collects all item IDs intersecting sphere `(center, radius)`.
    ///
    /// # Arguments
    ///
    /// - `&[OctreeNode3D]` - Node arena slice.
    /// - `usize` - Active node index.
    /// - `Vec3` - Sphere center.
    /// - `f32` - Sphere radius.
    /// - `&mut Vec<u64>` - Output ID buffer.
    fn query_sphere_rec(
        nodes: &[OctreeNode3D],
        node_idx: usize,
        center: Vec3,
        radius: f32,
        out: &mut Vec<u64>,
    ) {
        let node: &OctreeNode3D = &nodes[node_idx];
        if !aabb3d_intersects_sphere(node.bounds, center, radius) {
            return;
        }
        for item in &node.items {
            if aabb3d_intersects_sphere(item.get_bounds(), center, radius) {
                out.push(item.get_id());
            }
        }
        if node.children[0] != SPATIAL_EMPTY_SLOT {
            for &child in &node.children {
                Self::query_sphere_rec(nodes, child, center, radius, out);
            }
        }
    }

    /// Queries all items intersecting sphere `(center, radius)`, writing IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Query sphere center.
    /// - `f32` - Query sphere radius.
    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
    pub fn query_sphere(&self, center: Vec3, radius: f32, out: &mut Vec<u64>) {
        out.clear();
        let valid_radius: bool = radius.is_finite() && radius >= 0.0;
        if !valid_radius || self.get_nodes().is_empty() {
            return;
        }
        Self::query_sphere_rec(self.get_nodes(), 0, center, radius, out);
    }

    /// Recursively collects all item IDs intersected by `ray` within `[0.0, max_distance]`.
    ///
    /// # Arguments
    ///
    /// - `&[OctreeNode3D]` - Node arena slice.
    /// - `usize` - Active node index.
    /// - `&Ray3D` - Query ray.
    /// - `f32` - Maximum hit distance.
    /// - `&mut Vec<u64>` - Output ID buffer.
    fn query_ray_rec(
        nodes: &[OctreeNode3D],
        node_idx: usize,
        ray: &Ray3D,
        max_distance: f32,
        out: &mut Vec<u64>,
    ) {
        let node: &OctreeNode3D = &nodes[node_idx];
        if !node.bounds.intersects_ray(ray, 0.0, max_distance) {
            return;
        }
        for item in &node.items {
            if item.get_bounds().intersects_ray(ray, 0.0, max_distance) {
                out.push(item.get_id());
            }
        }
        if node.children[0] != SPATIAL_EMPTY_SLOT {
            for &child in &node.children {
                Self::query_ray_rec(nodes, child, ray, max_distance, out);
            }
        }
    }

    /// Queries all items intersected by `ray` within `[0.0, max_distance]`, writing IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Ray3D` - 3D ray with precomputed reciprocal direction.
    /// - `f32` - Maximum valid ray distance.
    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
    pub fn query_ray(&self, ray: Ray3D, max_distance: f32, out: &mut Vec<u64>) {
        out.clear();
        let valid_dist: bool = max_distance.is_finite() && max_distance >= 0.0;
        if !valid_dist || self.get_nodes().is_empty() {
            return;
        }
        Self::query_ray_rec(self.get_nodes(), 0, &ray, max_distance, out);
    }
}

/// Zero-allocation open-addressed uniform-cell 2D spatial hash grid operations.
impl SpatialHashGrid2D {
    /// Creates an empty `SpatialHashGrid2D` with uniform `cell_size`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Cell edge length (clamped to `>= 1e-4`).
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated 2D spatial hash grid.
    #[must_use]
    pub fn new(cell_size: f32) -> Self {
        let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
            cell_size
        } else {
            1.0
        };
        Self {
            cell_size: safe_size,
            inv_cell_size: 1.0 / safe_size,
            occupied_buckets: 0,
            buckets: vec![
                SpatialHashBucket2D {
                    cx: 0,
                    cy: 0,
                    head: SPATIAL_EMPTY_SLOT,
                };
                SPATIAL_HASH_INIT_CAP
            ],
            touched_buckets: Vec::with_capacity(SPATIAL_HASH_INIT_CAP / 2),
            entries: Vec::with_capacity(SPATIAL_HASH_INIT_CAP),
            query_scratch: Vec::with_capacity(64),
        }
    }

    /// Clears all entries in O(active_cells) time while retaining every internal buffer's capacity.
    pub fn clear(&mut self) {
        let mut touched: Vec<usize> = take(self.get_mut_touched_buckets());
        let buckets: &mut Vec<SpatialHashBucket2D> = self.get_mut_buckets();
        for &slot in &touched {
            buckets[slot].head = SPATIAL_EMPTY_SLOT;
        }
        touched.clear();
        self.set_touched_buckets(touched);
        self.get_mut_entries().clear();
        self.set_occupied_buckets(0);
    }

    /// Doubles the open-addressed bucket table when load exceeds 65% and rehashes active cells.
    fn grow_buckets(&mut self) {
        let old_buckets: Vec<SpatialHashBucket2D> = take(self.get_mut_buckets());
        let old_touched: Vec<usize> = take(self.get_mut_touched_buckets());
        let new_cap: usize = (old_buckets.len() * 2).max(SPATIAL_HASH_INIT_CAP);
        let mask: usize = new_cap - 1;
        let mut new_buckets: Vec<SpatialHashBucket2D> = vec![
            SpatialHashBucket2D {
                cx: 0,
                cy: 0,
                head: SPATIAL_EMPTY_SLOT,
            };
            new_cap
        ];
        let mut new_touched: Vec<usize> = Vec::with_capacity(old_touched.len() * 2);
        for &old_slot in &old_touched {
            let bucket: SpatialHashBucket2D = old_buckets[old_slot];
            if bucket.head == SPATIAL_EMPTY_SLOT {
                continue;
            }
            let mut slot: usize = spatial_hash_2d(bucket.cx, bucket.cy) & mask;
            while new_buckets[slot].head != SPATIAL_EMPTY_SLOT {
                slot = (slot + 1) & mask;
            }
            new_buckets[slot] = bucket;
            new_touched.push(slot);
        }
        self.set_buckets(new_buckets);
        self.set_touched_buckets(new_touched);
    }

    /// Inserts an item `(id, bounds)` into every cell overlapped by `bounds`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Entity identifier.
    /// - `Bounds2D` - World-space 2D bounding rectangle.
    pub fn insert_bounds(&mut self, id: u64, bounds: Bounds2D) {
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = (bounds.get_min().get_x() * inv).floor() as i32;
        let max_cx: i32 = (bounds.get_max().get_x() * inv).floor() as i32;
        let min_cy: i32 = (bounds.get_min().get_y() * inv).floor() as i32;
        let max_cy: i32 = (bounds.get_max().get_y() * inv).floor() as i32;
        for cy in min_cy..=max_cy {
            for cx in min_cx..=max_cx {
                if self.get_occupied_buckets() * 10 >= self.get_buckets().len() * 6 {
                    self.grow_buckets();
                }
                let mask: usize = self.get_buckets().len() - 1;
                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
                let mut is_new_bucket: bool = false;
                loop {
                    let bucket: SpatialHashBucket2D = self.get_buckets()[slot];
                    if bucket.head == SPATIAL_EMPTY_SLOT {
                        is_new_bucket = true;
                        break;
                    }
                    if bucket.cx == cx && bucket.cy == cy {
                        break;
                    }
                    slot = (slot + 1) & mask;
                }
                let prev_head: usize = self.get_buckets()[slot].head;
                let entry_idx: usize = self.get_entries().len();
                self.get_mut_entries().push(SpatialHashEntry2D {
                    id,
                    bounds,
                    next: prev_head,
                });
                let bucket_mut: &mut SpatialHashBucket2D = &mut self.get_mut_buckets()[slot];
                bucket_mut.cx = cx;
                bucket_mut.cy = cy;
                bucket_mut.head = entry_idx;
                if is_new_bucket {
                    self.get_mut_touched_buckets().push(slot);
                    let next_occ: usize = self.get_occupied_buckets() + 1;
                    self.set_occupied_buckets(next_occ);
                }
            }
        }
    }

    /// Inserts a point item `(id, position)` into its enclosing cell.
    ///
    /// # Arguments
    ///
    /// - `u64` - Entity identifier.
    /// - `Vec2` - World-space 2D position.
    pub fn insert_point(&mut self, id: u64, position: Vec2) {
        if !position.get_x().is_finite() || !position.get_y().is_finite() {
            return;
        }
        self.insert_bounds(id, Bounds2D::new(position, position));
    }

    /// Queries all items overlapping `query_bounds`, writing deduplicated IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Bounds2D` - Query rectangle.
    /// - `&mut Vec<u64>` - Reusable output buffer (cleared and deduplicated).
    pub fn query_rect_into(&self, query_bounds: Bounds2D, out: &mut Vec<u64>) {
        out.clear();
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = (query_bounds.get_min().get_x() * inv).floor() as i32;
        let max_cx: i32 = (query_bounds.get_max().get_x() * inv).floor() as i32;
        let min_cy: i32 = (query_bounds.get_min().get_y() * inv).floor() as i32;
        let max_cy: i32 = (query_bounds.get_max().get_y() * inv).floor() as i32;
        let buckets: &[SpatialHashBucket2D] = self.get_buckets();
        let entries: &[SpatialHashEntry2D] = self.get_entries();
        let mask: usize = buckets.len() - 1;
        for cy in min_cy..=max_cy {
            for cx in min_cx..=max_cx {
                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
                loop {
                    let bucket: SpatialHashBucket2D = buckets[slot];
                    if bucket.head == SPATIAL_EMPTY_SLOT {
                        break;
                    }
                    if bucket.cx == cx && bucket.cy == cy {
                        let mut cursor: usize = bucket.head;
                        while cursor != SPATIAL_EMPTY_SLOT {
                            let entry: SpatialHashEntry2D = entries[cursor];
                            if entry.bounds.intersects(query_bounds) {
                                out.push(entry.id);
                            }
                            cursor = entry.next;
                        }
                        break;
                    }
                    slot = (slot + 1) & mask;
                }
            }
        }
        out.sort_unstable();
        out.dedup();
    }

    /// Queries all items overlapping circle `(center, radius)`, writing deduplicated IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query circle center.
    /// - `f32` - Query radius.
    /// - `&mut Vec<u64>` - Reusable output buffer (cleared and deduplicated).
    pub fn query_radius_into(&self, center: Vec2, radius: f32, out: &mut Vec<u64>) {
        out.clear();
        if !radius.is_finite() || radius < 0.0 {
            return;
        }
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = ((center.get_x() - radius) * inv).floor() as i32;
        let max_cx: i32 = ((center.get_x() + radius) * inv).floor() as i32;
        let min_cy: i32 = ((center.get_y() - radius) * inv).floor() as i32;
        let max_cy: i32 = ((center.get_y() + radius) * inv).floor() as i32;
        let buckets: &[SpatialHashBucket2D] = self.get_buckets();
        let entries: &[SpatialHashEntry2D] = self.get_entries();
        let mask: usize = buckets.len() - 1;
        for cy in min_cy..=max_cy {
            for cx in min_cx..=max_cx {
                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
                loop {
                    let bucket: SpatialHashBucket2D = buckets[slot];
                    if bucket.head == SPATIAL_EMPTY_SLOT {
                        break;
                    }
                    if bucket.cx == cx && bucket.cy == cy {
                        let mut cursor: usize = bucket.head;
                        while cursor != SPATIAL_EMPTY_SLOT {
                            let entry: SpatialHashEntry2D = entries[cursor];
                            if entry.bounds.intersects_circle(center, radius) {
                                out.push(entry.id);
                            }
                            cursor = entry.next;
                        }
                        break;
                    }
                    slot = (slot + 1) & mask;
                }
            }
        }
        out.sort_unstable();
        out.dedup();
    }

    /// Queries items within `(center, radius)` into the grid's internal reusable scratch slice.
    ///
    /// # Arguments
    ///
    /// - `Vec2` - Query circle center.
    /// - `f32` - Query radius.
    ///
    /// # Returns
    ///
    /// - `&[u64]` - Deduplicated matching IDs stored in the internal scratch buffer.
    #[must_use]
    pub fn query_radius(&mut self, center: Vec2, radius: f32) -> &[u64] {
        let mut scratch: Vec<u64> = take(self.get_mut_query_scratch());
        self.query_radius_into(center, radius, &mut scratch);
        self.set_query_scratch(scratch);
        self.get_query_scratch()
    }
}

/// Zero-allocation open-addressed uniform-cell 3D spatial hash grid operations.
impl SpatialHashGrid3D {
    /// Creates an empty `SpatialHashGrid3D` with uniform `cell_size`.
    ///
    /// # Arguments
    ///
    /// - `f32` - Cell edge length (clamped to `>= 1e-4`).
    ///
    /// # Returns
    ///
    /// - `Self` - Pre-allocated 3D spatial hash grid.
    #[must_use]
    pub fn new(cell_size: f32) -> Self {
        let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
            cell_size
        } else {
            1.0
        };
        Self {
            cell_size: safe_size,
            inv_cell_size: 1.0 / safe_size,
            occupied_buckets: 0,
            buckets: vec![
                SpatialHashBucket3D {
                    cx: 0,
                    cy: 0,
                    cz: 0,
                    head: SPATIAL_EMPTY_SLOT,
                };
                SPATIAL_HASH_INIT_CAP
            ],
            touched_buckets: Vec::with_capacity(SPATIAL_HASH_INIT_CAP / 2),
            entries: Vec::with_capacity(SPATIAL_HASH_INIT_CAP),
            query_scratch: Vec::with_capacity(64),
        }
    }

    /// Clears all entries in O(active_cells) time while retaining every internal buffer's capacity.
    pub fn clear(&mut self) {
        let mut touched: Vec<usize> = take(self.get_mut_touched_buckets());
        let buckets: &mut Vec<SpatialHashBucket3D> = self.get_mut_buckets();
        for &slot in &touched {
            buckets[slot].head = SPATIAL_EMPTY_SLOT;
        }
        touched.clear();
        self.set_touched_buckets(touched);
        self.get_mut_entries().clear();
        self.set_occupied_buckets(0);
    }

    /// Doubles the open-addressed 3D bucket table when load exceeds 65% and rehashes active cells.
    fn grow_buckets(&mut self) {
        let old_buckets: Vec<SpatialHashBucket3D> = take(self.get_mut_buckets());
        let old_touched: Vec<usize> = take(self.get_mut_touched_buckets());
        let new_cap: usize = (old_buckets.len() * 2).max(SPATIAL_HASH_INIT_CAP);
        let mask: usize = new_cap - 1;
        let mut new_buckets: Vec<SpatialHashBucket3D> = vec![
            SpatialHashBucket3D {
                cx: 0,
                cy: 0,
                cz: 0,
                head: SPATIAL_EMPTY_SLOT,
            };
            new_cap
        ];
        let mut new_touched: Vec<usize> = Vec::with_capacity(old_touched.len() * 2);
        for &old_slot in &old_touched {
            let bucket: SpatialHashBucket3D = old_buckets[old_slot];
            if bucket.head == SPATIAL_EMPTY_SLOT {
                continue;
            }
            let mut slot: usize = spatial_hash_3d(bucket.cx, bucket.cy, bucket.cz) & mask;
            while new_buckets[slot].head != SPATIAL_EMPTY_SLOT {
                slot = (slot + 1) & mask;
            }
            new_buckets[slot] = bucket;
            new_touched.push(slot);
        }
        self.set_buckets(new_buckets);
        self.set_touched_buckets(new_touched);
    }

    /// Inserts an item `(id, bounds)` into every 3D cell overlapped by `bounds`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Entity identifier.
    /// - `AxisAlignedBox3D` - World-space 3D bounding box.
    pub fn insert_aabb(&mut self, id: u64, bounds: AxisAlignedBox3D) {
        let norm: AxisAlignedBox3D = AxisAlignedBox3D::new(
            bounds.get_min().min(bounds.get_max()),
            bounds.get_min().max(bounds.get_max()),
        );
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = (norm.get_min().get_x() * inv).floor() as i32;
        let max_cx: i32 = (norm.get_max().get_x() * inv).floor() as i32;
        let min_cy: i32 = (norm.get_min().get_y() * inv).floor() as i32;
        let max_cy: i32 = (norm.get_max().get_y() * inv).floor() as i32;
        let min_cz: i32 = (norm.get_min().get_z() * inv).floor() as i32;
        let max_cz: i32 = (norm.get_max().get_z() * inv).floor() as i32;
        for cz in min_cz..=max_cz {
            for cy in min_cy..=max_cy {
                for cx in min_cx..=max_cx {
                    if self.get_occupied_buckets() * 10 >= self.get_buckets().len() * 6 {
                        self.grow_buckets();
                    }
                    let mask: usize = self.get_buckets().len() - 1;
                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
                    let mut is_new_bucket: bool = false;
                    loop {
                        let bucket: SpatialHashBucket3D = self.get_buckets()[slot];
                        if bucket.head == SPATIAL_EMPTY_SLOT {
                            is_new_bucket = true;
                            break;
                        }
                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
                            break;
                        }
                        slot = (slot + 1) & mask;
                    }
                    let prev_head: usize = self.get_buckets()[slot].head;
                    let entry_idx: usize = self.get_entries().len();
                    self.get_mut_entries().push(SpatialHashEntry3D {
                        id,
                        bounds: norm,
                        next: prev_head,
                    });
                    let bucket_mut: &mut SpatialHashBucket3D = &mut self.get_mut_buckets()[slot];
                    bucket_mut.cx = cx;
                    bucket_mut.cy = cy;
                    bucket_mut.cz = cz;
                    bucket_mut.head = entry_idx;
                    if is_new_bucket {
                        self.get_mut_touched_buckets().push(slot);
                        let next_occ: usize = self.get_occupied_buckets() + 1;
                        self.set_occupied_buckets(next_occ);
                    }
                }
            }
        }
    }

    /// Inserts a 3D point `(id, position)` into its enclosing grid cell.
    ///
    /// # Arguments
    ///
    /// - `u64` - Entity identifier.
    /// - `Vec3` - World-space 3D position.
    pub fn insert_point(&mut self, id: u64, position: Vec3) {
        if !position.get_x().is_finite()
            || !position.get_y().is_finite()
            || !position.get_z().is_finite()
        {
            return;
        }
        self.insert_aabb(id, AxisAlignedBox3D::new(position, position));
    }

    /// Queries all items overlapping `query_box`, writing deduplicated IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `AxisAlignedBox3D` - Query 3D bounding box.
    /// - `&mut Vec<u64>` - Reusable output buffer.
    pub fn query_aabb_into(&self, query_box: AxisAlignedBox3D, out: &mut Vec<u64>) {
        out.clear();
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = (query_box.get_min().get_x() * inv).floor() as i32;
        let max_cx: i32 = (query_box.get_max().get_x() * inv).floor() as i32;
        let min_cy: i32 = (query_box.get_min().get_y() * inv).floor() as i32;
        let max_cy: i32 = (query_box.get_max().get_y() * inv).floor() as i32;
        let min_cz: i32 = (query_box.get_min().get_z() * inv).floor() as i32;
        let max_cz: i32 = (query_box.get_max().get_z() * inv).floor() as i32;
        let buckets: &[SpatialHashBucket3D] = self.get_buckets();
        let entries: &[SpatialHashEntry3D] = self.get_entries();
        let mask: usize = buckets.len() - 1;
        for cz in min_cz..=max_cz {
            for cy in min_cy..=max_cy {
                for cx in min_cx..=max_cx {
                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
                    loop {
                        let bucket: SpatialHashBucket3D = buckets[slot];
                        if bucket.head == SPATIAL_EMPTY_SLOT {
                            break;
                        }
                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
                            let mut cursor: usize = bucket.head;
                            while cursor != SPATIAL_EMPTY_SLOT {
                                let entry: SpatialHashEntry3D = entries[cursor];
                                if aabb3d_intersects(entry.bounds, query_box) {
                                    out.push(entry.id);
                                }
                                cursor = entry.next;
                            }
                            break;
                        }
                        slot = (slot + 1) & mask;
                    }
                }
            }
        }
        out.sort_unstable();
        out.dedup();
    }

    /// Queries all items intersecting sphere `(center, radius)`, writing deduplicated IDs into `out`.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Query sphere center.
    /// - `f32` - Query sphere radius.
    /// - `&mut Vec<u64>` - Reusable output buffer.
    pub fn query_sphere_into(&self, center: Vec3, radius: f32, out: &mut Vec<u64>) {
        out.clear();
        if !radius.is_finite() || radius < 0.0 {
            return;
        }
        let inv: f32 = self.get_inv_cell_size();
        let min_cx: i32 = ((center.get_x() - radius) * inv).floor() as i32;
        let max_cx: i32 = ((center.get_x() + radius) * inv).floor() as i32;
        let min_cy: i32 = ((center.get_y() - radius) * inv).floor() as i32;
        let max_cy: i32 = ((center.get_y() + radius) * inv).floor() as i32;
        let min_cz: i32 = ((center.get_z() - radius) * inv).floor() as i32;
        let max_cz: i32 = ((center.get_z() + radius) * inv).floor() as i32;
        let buckets: &[SpatialHashBucket3D] = self.get_buckets();
        let entries: &[SpatialHashEntry3D] = self.get_entries();
        let mask: usize = buckets.len() - 1;
        for cz in min_cz..=max_cz {
            for cy in min_cy..=max_cy {
                for cx in min_cx..=max_cx {
                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
                    loop {
                        let bucket: SpatialHashBucket3D = buckets[slot];
                        if bucket.head == SPATIAL_EMPTY_SLOT {
                            break;
                        }
                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
                            let mut cursor: usize = bucket.head;
                            while cursor != SPATIAL_EMPTY_SLOT {
                                let entry: SpatialHashEntry3D = entries[cursor];
                                if aabb3d_intersects_sphere(entry.bounds, center, radius) {
                                    out.push(entry.id);
                                }
                                cursor = entry.next;
                            }
                            break;
                        }
                        slot = (slot + 1) & mask;
                    }
                }
            }
        }
        out.sort_unstable();
        out.dedup();
    }

    /// Queries items intersecting `(center, radius)` into the grid's internal reusable scratch slice.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Query sphere center.
    /// - `f32` - Query sphere radius.
    ///
    /// # Returns
    ///
    /// - `&[u64]` - Deduplicated matching IDs stored in the internal scratch buffer.
    #[must_use]
    pub fn query_sphere(&mut self, center: Vec3, radius: f32) -> &[u64] {
        let mut scratch: Vec<u64> = take(self.get_mut_query_scratch());
        self.query_sphere_into(center, radius, &mut scratch);
        self.set_query_scratch(scratch);
        self.get_query_scratch()
    }
}