Repository navigation
Expand file tree
/
Copy pathspatial_hash.rs
More file actions
636 lines (555 loc) · 22 KB
/
Copy pathspatial_hash.rs
File metadata and controls
636 lines (555 loc) · 22 KB
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
//! 3D spatial hash grid for efficient proximity queries.
//!
//! Entities are hashed into axis-aligned cells by position. Radius and KNN
//! queries only visit cells that overlap the search volume, giving O(1)
//! amortised lookup for uniformly distributed entities.
//!
//! The grid itself stores only `(cell_key -> [entity_id])`. Actual positions
//! are passed in by reference at query time so the caller keeps ownership.
use std::collections::HashMap;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
#[inline]
fn sq_dist_f32(a: [f32; 3], b: [f32; 3]) -> f32 {
let dx = a[0] - b[0];
let dy = a[1] - b[1];
let dz = a[2] - b[2];
dx * dx + dy * dy + dz * dz
}
// ---------------------------------------------------------------------------
// SpatialHash
// ---------------------------------------------------------------------------
/// 3D spatial hash. Entities are hashed into cells by position.
pub struct SpatialHash {
cell_size: f32,
inv_cell_size: f32,
grid: HashMap<(i32, i32, i32), Vec<u32>>,
}
impl SpatialHash {
/// Create a new spatial hash with the given cell size.
///
/// # Panics
/// Panics if `cell_size` is not positive and finite.
pub fn new(cell_size: f32) -> Self {
assert!(cell_size > 0.0 && cell_size.is_finite(), "cell_size must be positive and finite");
Self {
cell_size,
inv_cell_size: 1.0 / cell_size,
grid: HashMap::new(),
}
}
/// Insert an entity at the given position.
pub fn insert(&mut self, id: u32, x: f32, y: f32, z: f32) {
let key = self.cell_key(x, y, z);
self.grid.entry(key).or_default().push(id);
}
/// Remove an entity from its cell. Returns `true` if found and removed.
pub fn remove(&mut self, id: u32, x: f32, y: f32, z: f32) -> bool {
let key = self.cell_key(x, y, z);
if let Some(cell) = self.grid.get_mut(&key) {
if let Some(pos) = cell.iter().position(|&eid| eid == id) {
cell.swap_remove(pos);
if cell.is_empty() {
self.grid.remove(&key);
}
return true;
}
}
false
}
/// Move an entity from `old` position to `new` position.
pub fn update(&mut self, id: u32, old: [f32; 3], new: [f32; 3]) {
let old_key = self.cell_key(old[0], old[1], old[2]);
let new_key = self.cell_key(new[0], new[1], new[2]);
if old_key != new_key {
self.remove(id, old[0], old[1], old[2]);
self.insert(id, new[0], new[1], new[2]);
}
}
/// Remove all entities from the grid.
pub fn clear(&mut self) {
self.grid.clear();
}
/// Total number of entity entries across all cells.
pub fn len(&self) -> usize {
self.grid.values().map(|v| v.len()).sum()
}
/// Whether the grid contains zero entities.
pub fn is_empty(&self) -> bool {
self.grid.is_empty()
}
/// Find all entities within `radius` of `(x, y, z)`.
///
/// `positions` maps entity id to its `[x, y, z]`. Only entities present
/// in `positions` are considered. Returns `(entity_id, squared_distance)`
/// sorted ascending by distance.
pub fn query_radius(
&self, x: f32, y: f32, z: f32, radius: f32, positions: &HashMap<u32, [f32; 3]>,
) -> Vec<(u32, f32)> {
let radius_sq = radius * radius;
let query = [x, y, z];
// Determine cell range to search.
let min_cx = ((x - radius) * self.inv_cell_size).floor() as i32;
let max_cx = ((x + radius) * self.inv_cell_size).floor() as i32;
let min_cy = ((y - radius) * self.inv_cell_size).floor() as i32;
let max_cy = ((y + radius) * self.inv_cell_size).floor() as i32;
let min_cz = ((z - radius) * self.inv_cell_size).floor() as i32;
let max_cz = ((z + radius) * self.inv_cell_size).floor() as i32;
let mut results: Vec<(u32, f32)> = Vec::new();
for cx in min_cx..=max_cx {
for cy in min_cy..=max_cy {
for cz in min_cz..=max_cz {
if let Some(cell) = self.grid.get(&(cx, cy, cz)) {
for &eid in cell {
if let Some(&pos) = positions.get(&eid) {
let d2 = sq_dist_f32(query, pos);
if d2 <= radius_sq {
results.push((eid, d2));
}
}
}
}
}
}
}
results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
results
}
/// Find K nearest entities to `(x, y, z)`.
///
/// Uses expanding-ring search: starts at the cell containing the query
/// point and expands outward until at least K candidates are found, then
/// refines. Returns `(entity_id, squared_distance)` sorted ascending.
pub fn query_knn(&self, x: f32, y: f32, z: f32, k: usize, positions: &HashMap<u32, [f32; 3]>) -> Vec<(u32, f32)> {
if k == 0 {
return Vec::new();
}
let query = [x, y, z];
// Expand ring from 0 until we have enough candidates.
let mut candidates: Vec<(u32, f32)> = Vec::new();
let (cx, cy, cz) = self.cell_key(x, y, z);
let mut ring = 0i32;
let max_ring = 64; // safety cap
// Once every entry in the grid has been visited, no further ring can
// add a candidate. Without this, a query for more neighbours than the
// grid holds walks all 129^3 cells up to `max_ring`.
let total = self.len();
let mut visited = 0usize;
loop {
// Collect candidates from all cells in this ring shell.
for dx in -ring..=ring {
for dy in -ring..=ring {
for dz in -ring..=ring {
// Only visit cells on the shell (at least one coord at
// the ring boundary) to avoid re-visiting interior.
if dx.abs() != ring && dy.abs() != ring && dz.abs() != ring {
continue;
}
let key = (cx + dx, cy + dy, cz + dz);
if let Some(cell) = self.grid.get(&key) {
visited += cell.len();
for &eid in cell {
if let Some(&pos) = positions.get(&eid) {
let d2 = sq_dist_f32(query, pos);
candidates.push((eid, d2));
}
}
}
}
}
}
if ring >= max_ring || visited >= total {
break;
}
// If we have at least k candidates, check whether the k-th best
// is closer than the nearest possible point in the next ring.
// If so, no further ring can improve the result.
if candidates.len() >= k {
candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
let worst = candidates[k - 1].1;
// The nearest point in ring+1 is at least (ring * cell_size) away.
let next_ring_min = (ring as f32) * self.cell_size;
if worst <= next_ring_min * next_ring_min {
break;
}
}
ring += 1;
}
candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
candidates.truncate(k);
candidates
}
/// SIMD-accelerated radius query. Functionally identical to `query_radius`
/// but batches distance computations for entities within each cell.
///
/// Collects candidate positions from relevant cells, then uses SIMD to
/// compute squared distances and filter in bulk.
pub fn query_radius_simd(
&self, x: f32, y: f32, z: f32, radius: f32, positions: &HashMap<u32, [f32; 3]>,
) -> Vec<(u32, f32)> {
let radius_sq = radius * radius;
let query = [x, y, z];
let min_cx = ((x - radius) * self.inv_cell_size).floor() as i32;
let max_cx = ((x + radius) * self.inv_cell_size).floor() as i32;
let min_cy = ((y - radius) * self.inv_cell_size).floor() as i32;
let max_cy = ((y + radius) * self.inv_cell_size).floor() as i32;
let min_cz = ((z - radius) * self.inv_cell_size).floor() as i32;
let max_cz = ((z + radius) * self.inv_cell_size).floor() as i32;
// Collect all candidate (id, position) pairs from relevant cells
let mut candidate_ids = Vec::new();
let mut candidate_pos = Vec::new();
for cx in min_cx..=max_cx {
for cy in min_cy..=max_cy {
for cz in min_cz..=max_cz {
if let Some(cell) = self.grid.get(&(cx, cy, cz)) {
for &eid in cell {
if let Some(&pos) = positions.get(&eid) {
candidate_ids.push(eid);
candidate_pos.push(pos);
}
}
}
}
}
}
// Batch distance computation + filtering
let filtered = batch_sq_dist_filter(query, &candidate_pos, radius_sq);
let mut results: Vec<(u32, f32)> = filtered
.iter()
.map(|&(idx, d2)| (candidate_ids[idx], d2))
.collect();
results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
results
}
/// Compute the cell key for a world-space coordinate.
fn cell_key(&self, x: f32, y: f32, z: f32) -> (i32, i32, i32) {
(
(x * self.inv_cell_size).floor() as i32,
(y * self.inv_cell_size).floor() as i32,
(z * self.inv_cell_size).floor() as i32,
)
}
}
// ---------------------------------------------------------------------------
// SIMD batch distance computation
// ---------------------------------------------------------------------------
/// Batch squared-distance filter: compute squared distances from `query` to
/// each position in `candidates`, returning `(index, sq_dist)` for entries
/// within `radius_sq`.
fn batch_sq_dist_filter(query: [f32; 3], candidates: &[[f32; 3]], radius_sq: f32) -> Vec<(usize, f32)> {
#[cfg(target_arch = "x86_64")]
{
if candidates.len() >= 8 && super::simd_caps::simd_caps().avx2 {
// SAFETY: avx2 detected, enough candidates for SIMD.
return unsafe { batch_sq_dist_avx2(query, candidates, radius_sq) };
}
}
batch_sq_dist_scalar(query, candidates, radius_sq)
}
pub(crate) fn batch_sq_dist_scalar(query: [f32; 3], candidates: &[[f32; 3]], radius_sq: f32) -> Vec<(usize, f32)> {
let mut result = Vec::new();
for (i, pos) in candidates.iter().enumerate() {
let d2 = sq_dist_f32(query, *pos);
if d2 <= radius_sq {
result.push((i, d2));
}
}
result
}
/// AVX2 batch squared-distance filter: processes 8 candidates at a time
/// using F32x8 polyfill for arithmetic, scalar array comparison for filtering.
///
/// # Safety
/// Caller must ensure AVX2 is available.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
pub(crate) unsafe fn batch_sq_dist_avx2(query: [f32; 3], candidates: &[[f32; 3]], radius_sq: f32) -> Vec<(usize, f32)> {
use crate::simd::F32x8;
let mut result = Vec::new();
let qx = F32x8::splat(query[0]);
let qy = F32x8::splat(query[1]);
let qz = F32x8::splat(query[2]);
let chunks = candidates.len() / 8;
for c in 0..chunks {
let base = c * 8;
// Gather x, y, z coords for 8 candidates into SoA
let mut cx = [0.0f32; 8];
let mut cy = [0.0f32; 8];
let mut cz = [0.0f32; 8];
for i in 0..8 {
cx[i] = candidates[base + i][0];
cy[i] = candidates[base + i][1];
cz[i] = candidates[base + i][2];
}
let vx = F32x8::from_array(cx);
let vy = F32x8::from_array(cy);
let vz = F32x8::from_array(cz);
// Compute squared distances
let dx = vx - qx;
let dy = vy - qy;
let dz = vz - qz;
let d2 = dx * dx + dy * dy + dz * dz;
// Compare: d2 <= radius_sq (scalar array comparison — no F32x8 cmp polyfill)
let d2_arr = d2.to_array();
for (lane, &d2_lane) in d2_arr.iter().enumerate() {
if d2_lane <= radius_sq {
result.push((base + lane, d2_lane));
}
}
}
// Scalar tail
let tail_start = chunks * 8;
for (offset, &cand) in candidates[tail_start..].iter().enumerate() {
let d2 = sq_dist_f32(query, cand);
if d2 <= radius_sq {
result.push((tail_start + offset, d2));
}
}
result
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn make_positions(pts: &[(u32, [f32; 3])]) -> HashMap<u32, [f32; 3]> {
pts.iter().copied().collect()
}
// -- insert / remove --
#[test]
fn test_insert_and_len() {
let mut sh = SpatialHash::new(10.0);
assert!(sh.is_empty());
sh.insert(0, 1.0, 2.0, 3.0);
sh.insert(1, 11.0, 2.0, 3.0);
assert_eq!(sh.len(), 2);
assert!(!sh.is_empty());
}
#[test]
fn test_remove() {
let mut sh = SpatialHash::new(10.0);
sh.insert(0, 1.0, 2.0, 3.0);
assert!(sh.remove(0, 1.0, 2.0, 3.0));
assert!(sh.is_empty());
}
#[test]
fn test_remove_not_found() {
let mut sh = SpatialHash::new(10.0);
sh.insert(0, 1.0, 2.0, 3.0);
assert!(!sh.remove(99, 1.0, 2.0, 3.0));
assert!(!sh.remove(0, 999.0, 999.0, 999.0));
assert_eq!(sh.len(), 1);
}
// -- update --
#[test]
fn test_update_same_cell() {
let mut sh = SpatialHash::new(10.0);
sh.insert(0, 1.0, 1.0, 1.0);
sh.update(0, [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]); // same cell
assert_eq!(sh.len(), 1);
}
#[test]
fn test_update_different_cell() {
let mut sh = SpatialHash::new(10.0);
sh.insert(0, 1.0, 1.0, 1.0);
sh.update(0, [1.0, 1.0, 1.0], [100.0, 100.0, 100.0]); // different cell
assert_eq!(sh.len(), 1);
// Old cell should be empty now
assert!(sh.remove(0, 100.0, 100.0, 100.0));
assert!(sh.is_empty());
}
// -- clear --
#[test]
fn test_clear() {
let mut sh = SpatialHash::new(10.0);
for i in 0..50 {
sh.insert(i, i as f32, 0.0, 0.0);
}
assert_eq!(sh.len(), 50);
sh.clear();
assert!(sh.is_empty());
}
// -- radius query --
#[test]
fn test_query_radius_basic() {
let mut sh = SpatialHash::new(10.0);
let pts = vec![(0u32, [0.0f32, 0.0, 0.0]), (1, [5.0, 0.0, 0.0]), (2, [20.0, 0.0, 0.0]), (3, [100.0, 0.0, 0.0])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_radius(0.0, 0.0, 0.0, 10.0, &positions);
let ids: Vec<u32> = result.iter().map(|&(id, _)| id).collect();
assert!(ids.contains(&0));
assert!(ids.contains(&1));
assert!(!ids.contains(&2)); // dist=20 > radius=10
assert!(!ids.contains(&3));
}
#[test]
fn test_query_radius_sorted_by_distance() {
let mut sh = SpatialHash::new(5.0);
let pts = vec![(0u32, [10.0f32, 0.0, 0.0]), (1, [3.0, 0.0, 0.0]), (2, [1.0, 0.0, 0.0])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_radius(0.0, 0.0, 0.0, 20.0, &positions);
// Should be sorted: id=2 (d=1), id=1 (d=9), id=0 (d=100)
assert_eq!(result[0].0, 2);
assert_eq!(result[1].0, 1);
assert_eq!(result[2].0, 0);
}
#[test]
fn test_query_radius_empty() {
let sh = SpatialHash::new(10.0);
let positions: HashMap<u32, [f32; 3]> = HashMap::new();
let result = sh.query_radius(0.0, 0.0, 0.0, 100.0, &positions);
assert!(result.is_empty());
}
// -- knn --
#[test]
fn test_knn_basic() {
let mut sh = SpatialHash::new(10.0);
let pts = vec![(0u32, [30.0f32, 0.0, 0.0]), (1, [10.0, 0.0, 0.0]), (2, [20.0, 0.0, 0.0]), (3, [5.0, 0.0, 0.0])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_knn(0.0, 0.0, 0.0, 2, &positions);
assert_eq!(result.len(), 2);
assert_eq!(result[0].0, 3); // dist=25
assert_eq!(result[1].0, 1); // dist=100
}
#[test]
fn test_knn_vs_brute_force() {
let mut sh = SpatialHash::new(5.0);
let pts: Vec<(u32, [f32; 3])> = (0..50)
.map(|i| {
let v = i as f32 * 2.0;
(i as u32, [v, v * 0.5, v * 0.3])
})
.collect();
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let k = 5;
let result = sh.query_knn(10.0, 5.0, 3.0, k, &positions);
// Brute-force reference
let mut brute: Vec<(u32, f32)> = pts
.iter()
.map(|&(id, pos)| (id, sq_dist_f32([10.0, 5.0, 3.0], pos)))
.collect();
brute.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
brute.truncate(k);
assert_eq!(result.len(), brute.len());
// Compare distances (not IDs — ties may break differently)
for (r, b) in result.iter().zip(brute.iter()) {
assert!(
(r.1 - b.1).abs() < 1e-3,
"knn dist mismatch: spatial_hash=({},{:.2}) brute=({},{:.2})",
r.0,
r.1,
b.0,
b.1
);
}
}
#[test]
fn test_knn_k_zero() {
let sh = SpatialHash::new(10.0);
let positions: HashMap<u32, [f32; 3]> = HashMap::new();
let result = sh.query_knn(0.0, 0.0, 0.0, 0, &positions);
assert!(result.is_empty());
}
#[test]
fn test_knn_k_larger_than_count() {
let mut sh = SpatialHash::new(10.0);
sh.insert(0, 1.0, 2.0, 3.0);
let positions = make_positions(&[(0, [1.0, 2.0, 3.0])]);
let result = sh.query_knn(0.0, 0.0, 0.0, 100, &positions);
assert_eq!(result.len(), 1);
}
#[test]
fn test_knn_k_larger_than_count_still_reaches_far_rings() {
// One entry in ring 0 and one 10 rings out: the early exit on
// "every entry visited" must not fire before the far one is seen.
let mut sh = SpatialHash::new(1.0);
let pts = vec![(0u32, [0.5f32, 0.5, 0.5]), (1, [10.5, 0.5, 0.5])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_knn(0.5, 0.5, 0.5, 100, &positions);
let ids: Vec<u32> = result.iter().map(|r| r.0).collect();
assert_eq!(ids, vec![0, 1]);
// An empty grid answers empty.
assert!(SpatialHash::new(1.0)
.query_knn(0.0, 0.0, 0.0, 3, &positions)
.is_empty());
}
// -- negative coordinates --
#[test]
fn test_negative_coordinates() {
let mut sh = SpatialHash::new(10.0);
let pts = vec![(0u32, [-5.0f32, -5.0, -5.0]), (1, [5.0, 5.0, 5.0])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_radius(0.0, 0.0, 0.0, 20.0, &positions);
assert_eq!(result.len(), 2);
}
#[test]
#[should_panic]
fn test_invalid_cell_size() {
SpatialHash::new(0.0);
}
// ---------- SIMD radius query ----------
#[test]
fn test_query_radius_simd_basic() {
let mut sh = SpatialHash::new(10.0);
let pts = vec![(0u32, [0.0f32, 0.0, 0.0]), (1, [5.0, 0.0, 0.0]), (2, [20.0, 0.0, 0.0]), (3, [100.0, 0.0, 0.0])];
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let result = sh.query_radius_simd(0.0, 0.0, 0.0, 10.0, &positions);
let ids: Vec<u32> = result.iter().map(|&(id, _)| id).collect();
assert!(ids.contains(&0));
assert!(ids.contains(&1));
assert!(!ids.contains(&2));
assert!(!ids.contains(&3));
}
#[test]
fn test_query_radius_simd_matches_scalar() {
let mut sh = SpatialHash::new(5.0);
let pts: Vec<(u32, [f32; 3])> = (0..100)
.map(|i| {
let v = i as f32 * 1.5;
(i as u32, [v, v * 0.3, v * 0.7])
})
.collect();
for &(id, pos) in &pts {
sh.insert(id, pos[0], pos[1], pos[2]);
}
let positions = make_positions(&pts);
let scalar = sh.query_radius(10.0, 3.0, 7.0, 25.0, &positions);
let simd = sh.query_radius_simd(10.0, 3.0, 7.0, 25.0, &positions);
// Both should return the same set of (id, dist) pairs
assert_eq!(scalar.len(), simd.len(), "result count mismatch");
for (s, r) in scalar.iter().zip(simd.iter()) {
assert_eq!(s.0, r.0, "id mismatch");
assert!((s.1 - r.1).abs() < 1e-3, "distance mismatch: scalar={:.4} simd={:.4}", s.1, r.1);
}
}
#[test]
fn test_query_radius_simd_empty() {
let sh = SpatialHash::new(10.0);
let positions: HashMap<u32, [f32; 3]> = HashMap::new();
let result = sh.query_radius_simd(0.0, 0.0, 0.0, 100.0, &positions);
assert!(result.is_empty());
}
}