dijkstra3d-core 0.1.0

Voxel-grid Dijkstra and rolling-ball invalidation, ported from seung-lab/dijkstra3d and seung-lab/kimimaro
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
//! Anisotropic Euclidean (chamfer) distance field.
//!
//! Upstream reference: `dijkstra3d.hpp::euclidean_distance_field3d`.

use crate::atomic_dist::{atomic_dist_parent_vec, atomic_dist_vec, AtomicDist, AtomicDistParent};
use crate::neighborhood::{neighborhood_offsets, neighborhood_weights, DIRECTIONS_26};
use crate::parental::{
    is_neighbor_in_bounds, LibstdcxxCompatHeap, UpstreamCompatEntry, UPSTREAM_DIRECTIONS_26,
};
use crate::queue::binary_heap::BinaryHeapQueue;
use crate::queue::PriorityQueue;
use crate::voxel::{Anisotropy, VoxelSource};
use crate::{Connectivity, Dijkstra3dError, Result};
use num_traits::ToPrimitive;
use num_traits::Zero;
use rayon::prelude::*;

/// Output of the EDF computation.
#[derive(Debug, Clone)]
pub struct EdfOutput {
    pub distances: Vec<f32>,

    pub feature_map: Option<Vec<u64>>,

    pub max_location: Option<u64>,
}

/// Configuration for `euclidean_distance_field`.
#[derive(Debug, Clone, Copy)]
pub struct EdfConfig {
    pub anisotropy: Anisotropy,

    pub free_space_radius: f32,

    pub return_feature_map: bool,

    pub return_max_location: bool,
}

impl Default for EdfConfig {
    fn default() -> Self {
        Self {
            anisotropy: Anisotropy::default(),
            free_space_radius: 0.0,
            return_feature_map: false,
            return_max_location: false,
        }
    }
}

/// Contiguous x-fastest specialization of upstream's binary chamfer EDF.
///
/// This compatibility kernel mirrors upstream's logical axis order, direction
/// order, `f32` arithmetic, visited-marker behavior, and pinned libstdc++ heap
/// tie order. `field` must use `x + sx * (y + sy * z)` linear order; values
/// equal to `background` are impassable.
pub fn euclidean_distance_field_upstream_compat_slice<T>(
    field: &[T],
    shape: crate::voxel::VolumeShape,
    sources: &[u64],
    anisotropy: Anisotropy,
    background: T,
) -> Result<EdfOutput>
where
    T: Copy + PartialEq,
{
    let total = shape.total();
    if field.len() as u64 != total {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "euclidean_distance_field_upstream_compat_slice: slice length {} != shape.total() {total}",
            field.len()
        )));
    }
    if total > u32::MAX as u64 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "euclidean_distance_field_upstream_compat_slice: volume {total} exceeds u32::MAX voxels"
        )));
    }
    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }
    for &source in sources {
        if source >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: source,
                volume_size: total,
            });
        }
    }

    let mut distances = vec![f32::INFINITY; total as usize];
    let mut queue = LibstdcxxCompatHeap::<u32>::default();
    for &source in sources {
        distances[source as usize] = 0.0;
        queue.push(UpstreamCompatEntry {
            priority: 0.0,
            payload: source as u32,
        });
    }

    let stride_y = shape.sx as i64;
    let stride_z = (shape.sx * shape.sy) as i64;
    let offsets = UPSTREAM_DIRECTIONS_26
        .map(|(dx, dy, dz)| dx as i64 + dy as i64 * stride_y + dz as i64 * stride_z);
    let weights = UPSTREAM_DIRECTIONS_26.map(|(dx, dy, dz)| {
        let x = dx as f32 * anisotropy.wx;
        let y = dy as f32 * anisotropy.wy;
        let z = dz as f32 * anisotropy.wz;
        (x * x + y * y + z * z).sqrt()
    });

    let mut max_distance = -1.0f32;
    let mut max_location = total + 1;
    while let Some(entry) = queue.pop() {
        let loc = entry.payload as usize;
        let absolute_distance = distances[loc].abs();
        if max_distance < absolute_distance {
            max_distance = absolute_distance;
            max_location = loc as u64;
        }
        if distances[loc].is_sign_negative() {
            continue;
        }

        let (x, y, z) = shape.coords(loc as u64);
        let interior =
            x > 0 && x + 1 < shape.sx && y > 0 && y + 1 < shape.sy && z > 0 && z + 1 < shape.sz;
        let current_distance = distances[loc];
        for ((direction, &offset), &weight) in
            UPSTREAM_DIRECTIONS_26.iter().zip(&offsets).zip(&weights)
        {
            let (dx, dy, dz) = *direction;
            if !interior
                && !is_neighbor_in_bounds(
                    x,
                    y,
                    z,
                    dx,
                    dy,
                    dz,
                    shape.sx as i64,
                    shape.sy as i64,
                    shape.sz as i64,
                )
            {
                continue;
            }

            let neighbor = (loc as i64 + offset) as usize;
            if field[neighbor] == background {
                continue;
            }
            let new_distance = current_distance + weight;
            if new_distance < distances[neighbor] {
                distances[neighbor] = new_distance;
                queue.push(UpstreamCompatEntry {
                    priority: new_distance,
                    payload: neighbor as u32,
                });
            }
        }
        distances[loc] *= -1.0;
    }

    for distance in &mut distances {
        *distance = distance.abs();
    }

    Ok(EdfOutput {
        distances,
        feature_map: None,
        max_location: (max_location < total).then_some(max_location),
    })
}

/// Compute Euclidean distance field on a boolean (foreground/background) volume.
///
/// Uses geometric edge costs: `cost(u → v) = weights[i]`, where weights are
/// computed from anisotropy via `neighborhood_weights()`.
///
/// Field must be binary: 0 = background (impassable), non-zero = foreground.
pub fn euclidean_distance_field<V>(field: &V, sources: &[u64], cfg: EdfConfig) -> Result<EdfOutput>
where
    V: VoxelSource,
    V::Item: ToPrimitive + num_traits::Zero + PartialEq,
{
    let shape = field.shape();
    let total = shape.total();

    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }

    // Validate all sources are foreground
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
        // let val = field.get(src)?;
        // if val == V::Item::zero() {
        //     return Err(Dijkstra3dError::InvalidInput("source is in background".into()));
        // }
    }

    // Initialize distances to infinity
    let mut distances = vec![f32::INFINITY; total as usize];

    // Optional feature map (tracks which source claimed each voxel)
    let mut feature_map = if cfg.return_feature_map {
        Some(vec![u64::MAX; total as usize])
    } else {
        None
    };

    // Initialize queue with all sources at distance 0
    let mut queue = BinaryHeapQueue::new();
    for (src_idx, &src) in sources.iter().enumerate() {
        distances[src as usize] = 0.0;
        if let Some(ref mut fm) = feature_map {
            fm[src as usize] = src_idx as u64;
        }
        queue.push(0.0, src);
    }

    // Precompute neighbor offsets and geometric weights
    let offsets = neighborhood_offsets(shape.sx as i64, shape.stride_z() as i64);
    let weights = neighborhood_weights(cfg.anisotropy);
    let connectivity = Connectivity::TwentySix; // EDF always uses 26-connectivity
    let neighbor_count = connectivity.count();

    // Dijkstra expansion with geometric weights
    while let Some((_dist, loc)) = queue.pop() {
        let current_dist = distances[loc as usize];

        // Lazy deletion: skip stale entries
        if _dist > current_dist {
            continue;
        }

        // Get feature ID if tracking
        let current_feature = feature_map.as_ref().map(|fm| fm[loc as usize]);

        // Compute current coordinates for bounds checking
        let (x, y, z) = shape.coords(loc);

        // Expand to neighbors
        for i in 0..neighbor_count {
            // Per-axis bounds check using DIRECTIONS_26
            let dir = crate::neighborhood::DIRECTIONS_26[i];
            let nx = x as i64 + dir.0 as i64;
            let ny = y as i64 + dir.1 as i64;
            let nz = z as i64 + dir.2 as i64;

            if nx < 0
                || nx >= shape.sx as i64
                || ny < 0
                || ny >= shape.sy as i64
                || nz < 0
                || nz >= shape.sz as i64
            {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;

            // Skip background voxels (value == 0)
            let neighbor_val = field.get(neighbor)?;
            if neighbor_val == V::Item::zero() {
                continue;
            }

            // Edge cost: geometric weight (no field value multiplier)
            let step_cost = weights[i];
            let new_dist = current_dist + step_cost;

            if new_dist < distances[neighbor as usize] {
                distances[neighbor as usize] = new_dist;

                // Update feature map if tracking
                if let (Some(ref mut fm), Some(feat)) = (&mut feature_map, current_feature) {
                    fm[neighbor as usize] = feat;
                }

                queue.push(new_dist, neighbor);
            }
        }
    }

    // Find max location if requested
    let max_location = if cfg.return_max_location {
        let mut max_idx = None;
        let mut max_dist = f32::NEG_INFINITY;

        for (idx, &dist) in distances.iter().enumerate() {
            if dist.is_finite() && dist > max_dist {
                max_dist = dist;
                max_idx = Some(idx as u64);
            }
        }

        max_idx
    } else {
        None
    };

    Ok(EdfOutput {
        distances,
        feature_map,
        max_location,
    })
}

/// Compute Euclidean distance field on a binary volume, using parallel relaxation.
pub fn euclidean_distance_field_parallel<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
) -> Result<EdfOutput>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive + Zero + PartialEq + Send + Sync,
{
    // Fall back to sequential if free_space_radius is requested.
    if cfg.free_space_radius > 0.0 {
        return euclidean_distance_field(field, sources, cfg);
    }

    let shape = field.shape();
    let total = shape.total();

    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
    }

    // Feature ID safety check
    if cfg.return_feature_map && sources.len() >= u32::MAX as usize - 1 {
        return Err(Dijkstra3dError::InvalidInput(format!(
            "euclidean_distance_field_parallel: too many sources ({}) for feature map; \
             max {} when return_feature_map=true",
            sources.len(),
            u32::MAX - 2
        )));
    }

    if cfg.return_feature_map {
        edf_parallel_with_feature_map(field, sources, cfg, shape, total)
    } else {
        edf_parallel_distance_only(field, sources, cfg, shape, total)
    }
}

/// EDF parallel without feature map. Uses AtomicDist.
fn edf_parallel_distance_only<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
    shape: crate::voxel::VolumeShape,
    total: u64,
) -> Result<EdfOutput>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive + Zero + PartialEq + Send + Sync,
{
    let dist = atomic_dist_vec(total as usize);
    for &src in sources {
        dist[src as usize].store_zero();
    }

    let mut frontier: Vec<u64> = sources.to_vec();

    let offsets = neighborhood_offsets(shape.sx as i64, shape.stride_z() as i64);
    let weights = neighborhood_weights(cfg.anisotropy);
    let neighbor_count = Connectivity::TwentySix.count();
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;

    while !frontier.is_empty() {
        let next_frontier: Vec<u64> = frontier
            .par_iter()
            .flat_map_iter(|&loc| {
                expand_voxel_edf_dist_only(
                    field,
                    loc,
                    &dist,
                    &offsets,
                    &weights,
                    neighbor_count,
                    &shape,
                    sx,
                    sy,
                    sz,
                )
            })
            .collect();
        frontier = next_frontier;
    }

    let distances: Vec<f32> = dist.iter().map(|d| d.load()).collect();

    let max_location = if cfg.return_max_location {
        find_max_finite_edf(&distances)
    } else {
        None
    };

    Ok(EdfOutput {
        distances,
        feature_map: None,
        max_location,
    })
}

/// EDF parallel with feature map. Uses AtomicDistParent.
fn edf_parallel_with_feature_map<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
    shape: crate::voxel::VolumeShape,
    total: u64,
) -> Result<EdfOutput>
where
    V: VoxelSource + Sync,
    V::Item: ToPrimitive + Zero + PartialEq + Send + Sync,
{
    let dist_feat = atomic_dist_parent_vec(total as usize);
    for (src_idx, &src) in sources.iter().enumerate() {
        dist_feat[src as usize].relax_with_parent(0.0, src_idx as u32);
    }

    let mut frontier: Vec<u64> = sources.to_vec();

    let offsets = neighborhood_offsets(shape.sx as i64, shape.stride_z() as i64);
    let weights = neighborhood_weights(cfg.anisotropy);
    let neighbor_count = Connectivity::TwentySix.count();
    let sx = shape.sx as i64;
    let sy = shape.sy as i64;
    let sz = shape.sz as i64;

    while !frontier.is_empty() {
        let next_frontier: Vec<u64> = frontier
            .par_iter()
            .flat_map_iter(|&loc| {
                expand_voxel_edf_with_feature(
                    field,
                    loc,
                    &dist_feat,
                    &offsets,
                    &weights,
                    neighbor_count,
                    &shape,
                    sx,
                    sy,
                    sz,
                )
            })
            .collect();
        frontier = next_frontier;
    }

    let mut distances = Vec::with_capacity(total as usize);
    let mut feature_map = Vec::with_capacity(total as usize);
    for dp in dist_feat.iter() {
        let (feat_plus_one, d) = dp.load();
        distances.push(d);
        feature_map.push(if feat_plus_one == 0 {
            u64::MAX
        } else {
            (feat_plus_one - 1) as u64
        });
    }

    let max_location = if cfg.return_max_location {
        find_max_finite_edf(&distances)
    } else {
        None
    };

    Ok(EdfOutput {
        distances,
        feature_map: Some(feature_map),
        max_location,
    })
}

/// Expand neighbors for the distance-only EDF parallel path.
#[inline]
#[allow(clippy::too_many_arguments)]
fn expand_voxel_edf_dist_only<V>(
    field: &V,
    loc: u64,
    dist: &[AtomicDist],
    offsets: &[i64; 26],
    weights: &[f32; 26],
    neighbor_count: usize,
    shape: &crate::voxel::VolumeShape,
    sx: i64,
    sy: i64,
    sz: i64,
) -> Vec<u64>
where
    V: VoxelSource,
    V::Item: ToPrimitive + Zero + PartialEq,
{
    let current_dist = dist[loc as usize].load();
    if !current_dist.is_finite() {
        return Vec::new();
    }

    let (x, y, z) = shape.coords(loc);
    let mut newly_relaxed: Vec<u64> = Vec::with_capacity(neighbor_count);

    for i in 0..neighbor_count {
        let dir = DIRECTIONS_26[i];
        let nx = x as i64 + dir.0 as i64;
        let ny = y as i64 + dir.1 as i64;
        let nz = z as i64 + dir.2 as i64;
        if nx < 0 || nx >= sx || ny < 0 || ny >= sy || nz < 0 || nz >= sz {
            continue;
        }

        let neighbor = (loc as i64 + offsets[i]) as u64;

        let neighbor_val = match field.get(neighbor) {
            Ok(v) => v,
            Err(_) => continue,
        };
        if neighbor_val == V::Item::zero() {
            continue;
        }

        let new_dist = current_dist + weights[i];
        if dist[neighbor as usize].relax(new_dist) {
            newly_relaxed.push(neighbor);
        }
    }

    newly_relaxed
}

/// Expand neighbors for the feature-map-tracking EDF parallel path.
#[inline]
#[allow(clippy::too_many_arguments)]
fn expand_voxel_edf_with_feature<V>(
    field: &V,
    loc: u64,
    dist_feat: &[AtomicDistParent],
    offsets: &[i64; 26],
    weights: &[f32; 26],
    neighbor_count: usize,
    shape: &crate::voxel::VolumeShape,
    sx: i64,
    sy: i64,
    sz: i64,
) -> Vec<u64>
where
    V: VoxelSource,
    V::Item: ToPrimitive + Zero + PartialEq,
{
    let (current_feat_plus_one, current_dist) = dist_feat[loc as usize].load();
    if !current_dist.is_finite() || current_feat_plus_one == 0 {
        return Vec::new();
    }
    let current_feat_idx = current_feat_plus_one - 1;

    let (x, y, z) = shape.coords(loc);
    let mut newly_relaxed: Vec<u64> = Vec::with_capacity(neighbor_count);

    for i in 0..neighbor_count {
        let dir = DIRECTIONS_26[i];
        let nx = x as i64 + dir.0 as i64;
        let ny = y as i64 + dir.1 as i64;
        let nz = z as i64 + dir.2 as i64;
        if nx < 0 || nx >= sx || ny < 0 || ny >= sy || nz < 0 || nz >= sz {
            continue;
        }

        let neighbor = (loc as i64 + offsets[i]) as u64;

        let neighbor_val = match field.get(neighbor) {
            Ok(v) => v,
            Err(_) => continue,
        };
        if neighbor_val == V::Item::zero() {
            continue;
        }

        let new_dist = current_dist + weights[i];
        if dist_feat[neighbor as usize].relax_with_parent(new_dist, current_feat_idx) {
            newly_relaxed.push(neighbor);
        }
    }

    newly_relaxed
}

/// Linear scan for the max-finite-distance voxel.
#[inline]
fn find_max_finite_edf(distances: &[f32]) -> Option<u64> {
    let mut max_idx = None;
    let mut max_dist = f32::NEG_INFINITY;
    for (idx, &d) in distances.iter().enumerate() {
        if d.is_finite() && d > max_dist {
            max_dist = d;
            max_idx = Some(idx as u64);
        }
    }
    max_idx
}

/// Which axis a separable pass runs along.
#[derive(Debug, Clone, Copy)]
enum Axis {
    X,
    Y,
    Z,
}

#[derive(Clone, Copy)]
struct SyncMutPtr<T>(*mut T);
// SAFETY: the algorithm guarantees disjoint per-line address ranges; see
// `edt_pass` / `edt_pass_feat` for the partitioning argument.
unsafe impl<T> Send for SyncMutPtr<T> {}
unsafe impl<T> Sync for SyncMutPtr<T> {}

impl<T> SyncMutPtr<T> {
    #[inline]
    unsafe fn read_at(self, i: usize) -> T
    where
        T: Copy,
    {
        unsafe { *self.0.add(i) }
    }

    #[inline]
    unsafe fn write_at(self, i: usize, val: T) {
        unsafe { *self.0.add(i) = val }
    }
}

/// Storage element type for the full-volume squared-distance buffer.
trait FieldStore: Copy + Send + Sync {
    const INF: Self;
    fn to_f64(self) -> f64;
    fn from_f64(x: f64) -> Self;
}

impl FieldStore for f64 {
    const INF: Self = f64::INFINITY;
    #[inline]
    fn to_f64(self) -> f64 {
        self
    }
    #[inline]
    fn from_f64(x: f64) -> Self {
        x
    }
}

impl FieldStore for f32 {
    const INF: Self = f32::INFINITY;
    #[inline]
    fn to_f64(self) -> f64 {
        self as f64
    }
    #[inline]
    fn from_f64(x: f64) -> Self {
        x as f32
    }
}

/// Largest exactly-representable integer in `f32` (2^24).
const F32_EXACT_INT_MAX: f64 = (1u64 << 24) as f64;

#[inline]
fn f32_field_is_exact(shape: crate::voxel::VolumeShape, a_x: f64, a_y: f64, a_z: f64) -> bool {
    let integral = a_x.fract() == 0.0 && a_y.fract() == 0.0 && a_z.fract() == 0.0;
    if !integral {
        return false;
    }
    let dx = (shape.sx as f64 - 1.0).max(0.0);
    let dy = (shape.sy as f64 - 1.0).max(0.0);
    let dz = (shape.sz as f64 - 1.0).max(0.0);
    let max_sq = a_x * dx * dx + a_y * dy * dy + a_z * dz * dz;
    max_sq <= F32_EXACT_INT_MAX
}

struct EdtScratch {
    f_line: Vec<f64>,
    out_line: Vec<f64>,
    v: Vec<usize>,
    z: Vec<f64>,
    feat_line: Vec<u64>,
    feat_out: Vec<u64>,
}

impl EdtScratch {
    fn new(n: usize) -> Self {
        Self {
            f_line: vec![0.0; n],
            out_line: vec![0.0; n],
            v: vec![0usize; n],
            z: vec![0.0; n + 1],
            feat_line: vec![u64::MAX; n],
            feat_out: vec![u64::MAX; n],
        }
    }
}

/// 1-D exact squared-distance lower-envelope transform (distance only).
#[inline]
#[allow(clippy::needless_range_loop)]
fn edt_1d(f: &[f64], a: f64, out: &mut [f64], v: &mut [usize], z: &mut [f64]) {
    let n = f.len();
    let mut k: isize = -1;
    for q in 0..n {
        let fq = f[q];
        if !fq.is_finite() {
            continue;
        }
        if k < 0 {
            k = 0;
            v[0] = q;
            z[0] = f64::NEG_INFINITY;
            z[1] = f64::INFINITY;
            continue;
        }
        let aq2 = a * (q as f64) * (q as f64);
        loop {
            let p = v[k as usize];
            let s = ((fq + aq2) - (f[p] + a * (p as f64) * (p as f64)))
                / (2.0 * a * (q as f64 - p as f64));
            // z[0] == -inf and `s` is finite, so at k == 0 this is always false
            // ⇒ `k` never underflows below 0.
            if s <= z[k as usize] {
                k -= 1;
            } else {
                k += 1;
                v[k as usize] = q;
                z[k as usize] = s;
                z[(k + 1) as usize] = f64::INFINITY;
                break;
            }
        }
    }
    if k < 0 {
        // No finite seed on this line yet — leave everything at INFINITY.
        for o in out.iter_mut() {
            *o = f64::INFINITY;
        }
        return;
    }
    let mut kk: usize = 0;
    for q in 0..n {
        let qf = q as f64;
        while z[kk + 1] < qf {
            kk += 1;
        }
        let p = v[kk];
        let d = qf - p as f64;
        out[q] = a * d * d + f[p];
    }
}

/// 1-D transform variant that also propagates the nearest-seed feature index
#[inline]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::needless_range_loop)]
fn edt_1d_feat(
    f: &[f64],
    feat_in: &[u64],
    a: f64,
    out: &mut [f64],
    feat_out: &mut [u64],
    v: &mut [usize],
    z: &mut [f64],
) {
    let n = f.len();
    let mut k: isize = -1;
    for q in 0..n {
        let fq = f[q];
        if !fq.is_finite() {
            continue;
        }
        if k < 0 {
            k = 0;
            v[0] = q;
            z[0] = f64::NEG_INFINITY;
            z[1] = f64::INFINITY;
            continue;
        }
        let aq2 = a * (q as f64) * (q as f64);
        loop {
            let p = v[k as usize];
            let s = ((fq + aq2) - (f[p] + a * (p as f64) * (p as f64)))
                / (2.0 * a * (q as f64 - p as f64));
            if s <= z[k as usize] {
                k -= 1;
            } else {
                k += 1;
                v[k as usize] = q;
                z[k as usize] = s;
                z[(k + 1) as usize] = f64::INFINITY;
                break;
            }
        }
    }
    if k < 0 {
        for o in out.iter_mut() {
            *o = f64::INFINITY;
        }
        for fo in feat_out.iter_mut() {
            *fo = u64::MAX;
        }
        return;
    }
    let mut kk: usize = 0;
    for q in 0..n {
        let qf = q as f64;
        while z[kk + 1] < qf {
            kk += 1;
        }
        let p = v[kk];
        let d = qf - p as f64;
        out[q] = a * d * d + f[p];
        feat_out[q] = feat_in[p];
    }
}

/// Geometry of the independent lines along one axis: `(stride, len, num_lines)`.
#[inline]
fn axis_geometry(axis: Axis, sx: usize, sy: usize, sz: usize) -> (usize, usize, usize) {
    let sxy = sx * sy;
    match axis {
        Axis::X => (1, sx, sy * sz),
        Axis::Y => (sx, sy, sx * sz),
        Axis::Z => (sxy, sz, sx * sy),
    }
}

/// Start index of line `l` along `axis`. Together with the stride/len from
/// [`axis_geometry`] this enumerates a partition of `[0, total)`.
#[inline]
fn line_start(axis: Axis, l: usize, sx: usize, sxy: usize) -> usize {
    match axis {
        Axis::X => l * sx,
        Axis::Y => (l % sx) + (l / sx) * sxy,
        Axis::Z => l,
    }
}

#[inline]
fn run_lines<F>(num_lines: usize, n: usize, parallel: bool, body: F)
where
    F: Fn(usize, &mut EdtScratch) + Sync,
{
    if parallel {
        let threads = rayon::current_num_threads().max(1);

        let target_tasks = threads.saturating_mul(8).max(1);
        let chunk = num_lines.div_ceil(target_tasks).max(1);
        let n_chunks = num_lines.div_ceil(chunk);
        (0..n_chunks).into_par_iter().for_each_init(
            || EdtScratch::new(n),
            |scratch, c| {
                let lo = c * chunk;
                let hi = ((c + 1) * chunk).min(num_lines);
                for l in lo..hi {
                    body(l, scratch);
                }
            },
        );
    } else {
        let mut scratch = EdtScratch::new(n);
        for l in 0..num_lines {
            body(l, &mut scratch);
        }
    }
}

/// Run the 1-D lower-envelope transform along `axis` in place over the whole
/// volume `f`, with squared spacing `a = w²`.
fn edt_pass<S: FieldStore>(
    f: &mut [S],
    a: f64,
    axis: Axis,
    shape: crate::voxel::VolumeShape,
    parallel: bool,
) {
    let sx = shape.sx as usize;
    let sy = shape.sy as usize;
    let sz = shape.sz as usize;
    let sxy = sx * sy;
    let (stride, n, num_lines) = axis_geometry(axis, sx, sy, sz);
    let ptr = SyncMutPtr(f.as_mut_ptr());

    let body = move |l: usize, scratch: &mut EdtScratch| {
        let start = line_start(axis, l, sx, sxy);
        // SAFETY: line `l` owns exactly the indices { start + j*stride : j<n },
        // and these sets are disjoint across lines (they partition [0,total)),
        // so no two tasks touch the same address. Every index is < total.
        unsafe {
            for j in 0..n {
                scratch.f_line[j] = ptr.read_at(start + j * stride).to_f64();
            }
        }
        edt_1d(
            &scratch.f_line[..n],
            a,
            &mut scratch.out_line[..n],
            &mut scratch.v[..n],
            &mut scratch.z[..=n],
        );
        unsafe {
            for j in 0..n {
                ptr.write_at(start + j * stride, S::from_f64(scratch.out_line[j]));
            }
        }
    };

    run_lines(num_lines, n, parallel, body);
}

/// Feature-tracking counterpart of [`edt_pass`]: transforms `f` and propagates
/// the nearest-seed index array `feat` in lockstep.
fn edt_pass_feat<S: FieldStore>(
    f: &mut [S],
    feat: &mut [u64],
    a: f64,
    axis: Axis,
    shape: crate::voxel::VolumeShape,
    parallel: bool,
) {
    let sx = shape.sx as usize;
    let sy = shape.sy as usize;
    let sz = shape.sz as usize;
    let sxy = sx * sy;
    let (stride, n, num_lines) = axis_geometry(axis, sx, sy, sz);
    let fptr = SyncMutPtr(f.as_mut_ptr());
    let featptr = SyncMutPtr(feat.as_mut_ptr());

    let body = move |l: usize, scratch: &mut EdtScratch| {
        let start = line_start(axis, l, sx, sxy);
        // SAFETY: same disjoint-partition argument as `edt_pass`; `f` and `feat`
        // are distinct allocations of equal length, indexed identically.
        unsafe {
            for j in 0..n {
                let idx = start + j * stride;
                scratch.f_line[j] = fptr.read_at(idx).to_f64();
                scratch.feat_line[j] = featptr.read_at(idx);
            }
        }
        edt_1d_feat(
            &scratch.f_line[..n],
            &scratch.feat_line[..n],
            a,
            &mut scratch.out_line[..n],
            &mut scratch.feat_out[..n],
            &mut scratch.v[..n],
            &mut scratch.z[..=n],
        );
        unsafe {
            for j in 0..n {
                let idx = start + j * stride;
                fptr.write_at(idx, S::from_f64(scratch.out_line[j]));
                featptr.write_at(idx, scratch.feat_out[j]);
            }
        }
    };

    run_lines(num_lines, n, parallel, body);
}

/// Shared driver for the exact separable EDT. `parallel` selects rayon-over-rows.
fn exact_edf_impl<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
    parallel: bool,
) -> Result<EdfOutput>
where
    V: VoxelSource,
{
    let shape = field.shape();
    let total = shape.total();

    if sources.is_empty() {
        return Err(Dijkstra3dError::InvalidInput(
            "sources cannot be empty".into(),
        ));
    }
    for &src in sources {
        if src >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: src,
                volume_size: total,
            });
        }
    }

    // Squared per-axis spacings.
    let a_x = (cfg.anisotropy.wx as f64).powi(2);
    let a_y = (cfg.anisotropy.wy as f64).powi(2);
    let a_z = (cfg.anisotropy.wz as f64).powi(2);

    let out = if f32_field_is_exact(shape, a_x, a_y, a_z) {
        exact_edf_run::<f32>(sources, cfg, parallel, shape, total, a_x, a_y, a_z)
    } else {
        exact_edf_run::<f64>(sources, cfg, parallel, shape, total, a_x, a_y, a_z)
    };
    Ok(out)
}

#[allow(clippy::too_many_arguments)]
fn exact_edf_run<S: FieldStore>(
    sources: &[u64],
    cfg: EdfConfig,
    parallel: bool,
    shape: crate::voxel::VolumeShape,
    total: u64,
    a_x: f64,
    a_y: f64,
    a_z: f64,
) -> EdfOutput {
    // Seed the squared-distance field: 0 at sources, +inf elsewhere.
    let mut f = vec![S::INF; total as usize];
    let want_feat = cfg.return_feature_map;
    let mut feat: Vec<u64> = if want_feat {
        vec![u64::MAX; total as usize]
    } else {
        Vec::new()
    };
    let zero = S::from_f64(0.0);
    for (i, &src) in sources.iter().enumerate() {
        f[src as usize] = zero;
        if want_feat {
            feat[src as usize] = i as u64;
        }
    }

    if want_feat {
        edt_pass_feat(&mut f, &mut feat, a_x, Axis::X, shape, parallel);
        edt_pass_feat(&mut f, &mut feat, a_y, Axis::Y, shape, parallel);
        edt_pass_feat(&mut f, &mut feat, a_z, Axis::Z, shape, parallel);
    } else {
        edt_pass(&mut f, a_x, Axis::X, shape, parallel);
        edt_pass(&mut f, a_y, Axis::Y, shape, parallel);
        edt_pass(&mut f, a_z, Axis::Z, shape, parallel);
    }

    let to_dist = |d: &S| -> f32 {
        let d = d.to_f64();
        if d.is_finite() {
            d.sqrt() as f32
        } else {
            f32::INFINITY
        }
    };
    let distances: Vec<f32> = if parallel {
        f.par_iter().map(to_dist).collect()
    } else {
        f.iter().map(to_dist).collect()
    };

    let feature_map = if want_feat { Some(feat) } else { None };

    let max_location = if cfg.return_max_location {
        find_max_finite_edf(&distances)
    } else {
        None
    };

    EdfOutput {
        distances,
        feature_map,
        max_location,
    }
}

/// Opt-in **exact** anisotropic Euclidean distance field (sequential reference).
pub fn exact_euclidean_distance_field<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
) -> Result<EdfOutput>
where
    V: VoxelSource,
{
    exact_edf_impl(field, sources, cfg, false)
}

/// Opt-in exact anisotropic Euclidean distance field, parallelized with rayon
/// over the independent rows of each separable pass.
pub fn exact_euclidean_distance_field_parallel<V>(
    field: &V,
    sources: &[u64],
    cfg: EdfConfig,
) -> Result<EdfOutput>
where
    V: VoxelSource,
{
    exact_edf_impl(field, sources, cfg, true)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::voxel::ArrayView3Source;
    use ndarray::Array3;

    #[test]
    fn edf_parallel_matches_sequential_no_feature_map() {
        let arr = Array3::<u8>::from_elem((8, 8, 8), 1);
        let source = ArrayView3Source::new(arr.view());

        let cfg = EdfConfig::default();
        let seq = euclidean_distance_field(&source, &[0], cfg).unwrap();
        let par = euclidean_distance_field_parallel(&source, &[0], cfg).unwrap();

        for i in 0..seq.distances.len() {
            assert!(
                (seq.distances[i] - par.distances[i]).abs() < 1e-5,
                "voxel {}: seq {} != par {}",
                i,
                seq.distances[i],
                par.distances[i]
            );
        }
    }

    #[test]
    fn edf_parallel_matches_sequential_with_feature_map() {
        let arr = Array3::<u8>::from_elem((6, 6, 6), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let s0 = shape.linear(0, 0, 0);
        let s1 = shape.linear(5, 5, 5);

        let mut cfg = EdfConfig::default();
        cfg.return_feature_map = true;

        let seq = euclidean_distance_field(&source, &[s0, s1], cfg).unwrap();
        let par = euclidean_distance_field_parallel(&source, &[s0, s1], cfg).unwrap();

        for i in 0..seq.distances.len() {
            assert!((seq.distances[i] - par.distances[i]).abs() < 1e-5);
        }

        let seq_fm = seq.feature_map.unwrap();
        let par_fm = par.feature_map.unwrap();
        for i in 0..seq_fm.len() {
            let seq_unclaimed = seq_fm[i] == u64::MAX;
            let par_unclaimed = par_fm[i] == u64::MAX;
            assert_eq!(
                seq_unclaimed, par_unclaimed,
                "voxel {} unclaimed mismatch",
                i
            );
        }
    }

    #[test]
    fn edf_parallel_anisotropy() {
        let arr = Array3::<u8>::from_elem((8, 8, 8), 1);
        let source = ArrayView3Source::new(arr.view());

        let mut cfg = EdfConfig::default();
        cfg.anisotropy = crate::voxel::Anisotropy::new(4.0, 4.0, 40.0);

        let seq = euclidean_distance_field(&source, &[0], cfg).unwrap();
        let par = euclidean_distance_field_parallel(&source, &[0], cfg).unwrap();

        for i in 0..seq.distances.len() {
            assert!(
                (seq.distances[i] - par.distances[i]).abs() < 1e-3,
                "voxel {}: seq {} != par {}",
                i,
                seq.distances[i],
                par.distances[i]
            );
        }
    }

    #[test]
    fn edf_parallel_falls_back_for_free_space_radius() {
        let arr = Array3::<u8>::from_elem((4, 4, 4), 1);
        let source = ArrayView3Source::new(arr.view());

        let mut cfg = EdfConfig::default();
        cfg.free_space_radius = 2.0;

        let result = euclidean_distance_field_parallel(&source, &[0], cfg);
        assert!(result.is_ok());
    }

    // ---------------------------------------------------------------------
    // Exact separable EDT tests. The reference is a brute-force O(n·|sources|)
    // "min over sources of the anisotropic Euclidean distance" — the exact
    // quantity the seung-lab `edt` package computes (which is unavailable in
    // the definition is used as the differential reference).
    // ---------------------------------------------------------------------

    /// Brute-force exact anisotropic Euclidean distance to the nearest source.
    fn brute_force_exact(
        shape: crate::voxel::VolumeShape,
        sources: &[u64],
        aniso: crate::voxel::Anisotropy,
    ) -> Vec<f32> {
        let total = shape.total() as usize;
        let mut out = vec![f32::INFINITY; total];
        let src_coords: Vec<(i64, i64, i64)> = sources
            .iter()
            .map(|&s| {
                let (x, y, z) = shape.coords(s);
                (x as i64, y as i64, z as i64)
            })
            .collect();
        for idx in 0..total {
            let (x, y, z) = shape.coords(idx as u64);
            let (x, y, z) = (x as i64, y as i64, z as i64);
            let mut best = f64::INFINITY;
            for &(sx, sy, sz) in &src_coords {
                let dx = (x - sx) as f64 * aniso.wx as f64;
                let dy = (y - sy) as f64 * aniso.wy as f64;
                let dz = (z - sz) as f64 * aniso.wz as f64;
                let d2 = dx * dx + dy * dy + dz * dz;
                if d2 < best {
                    best = d2;
                }
            }
            out[idx] = best.sqrt() as f32;
        }
        out
    }

    fn assert_close(a: &[f32], b: &[f32], tol: f32, ctx: &str) {
        assert_eq!(a.len(), b.len(), "{ctx}: length mismatch");
        for i in 0..a.len() {
            assert!(
                (a[i] - b[i]).abs() <= tol,
                "{ctx}: voxel {i}: {} vs {} (tol {})",
                a[i],
                b[i],
                tol
            );
        }
    }

    #[test]
    fn exact_edf_matches_bruteforce_isotropic() {
        // Non-cubic shape catches axis/stride mistakes in the separable passes.
        let arr = Array3::<u8>::from_elem((5, 6, 7), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![
            shape.linear(0, 0, 0),
            shape.linear(4, 5, 6),
            shape.linear(2, 1, 3),
        ];

        let cfg = EdfConfig::default();
        let got = exact_euclidean_distance_field(&source, &sources, cfg).unwrap();
        let want = brute_force_exact(shape, &sources, cfg.anisotropy);
        assert_close(&got.distances, &want, 1e-4, "exact isotropic");
    }

    #[test]
    fn exact_edf_matches_bruteforce_anisotropic() {
        let arr = Array3::<u8>::from_elem((7, 5, 4), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![shape.linear(0, 0, 0), shape.linear(6, 4, 3)];

        let mut cfg = EdfConfig::default();
        cfg.anisotropy = crate::voxel::Anisotropy::new(4.0, 4.0, 40.0);

        let got = exact_euclidean_distance_field(&source, &sources, cfg).unwrap();
        let want = brute_force_exact(shape, &sources, cfg.anisotropy);
        // Larger absolute distances (z spacing 40) ⇒ a slightly looser abs tol.
        assert_close(&got.distances, &want, 1e-2, "exact anisotropic");
    }

    #[test]
    fn exact_edf_parallel_matches_sequential() {
        let arr = Array3::<u8>::from_elem((9, 8, 10), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![
            shape.linear(0, 0, 0),
            shape.linear(8, 7, 9),
            shape.linear(4, 0, 5),
        ];

        let cfg = EdfConfig::default();
        let seq = exact_euclidean_distance_field(&source, &sources, cfg).unwrap();
        let par = exact_euclidean_distance_field_parallel(&source, &sources, cfg).unwrap();
        // Same code path arithmetic ⇒ bit-for-bit identical.
        assert_eq!(seq.distances, par.distances, "seq vs par distances");
    }

    #[test]
    fn exact_edf_deterministic_across_thread_counts() {
        let arr = Array3::<u8>::from_elem((12, 11, 10), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![shape.linear(0, 0, 0), shape.linear(11, 10, 9)];
        let cfg = EdfConfig::default();

        let run = |threads: usize| {
            let pool = rayon::ThreadPoolBuilder::new()
                .num_threads(threads)
                .build()
                .unwrap();
            pool.install(|| {
                exact_euclidean_distance_field_parallel(&source, &sources, cfg)
                    .unwrap()
                    .distances
            })
        };
        let d1 = run(1);
        let d4 = run(4);
        assert_eq!(d1, d4, "exact EDT must be identical at 1 vs 4 threads");
    }

    #[test]
    fn exact_edf_is_more_accurate_than_chamfer_off_diagonal() {
        // All-foreground volume, single corner source.
        let n = 16usize;
        let arr = Array3::<u8>::from_elem((n, n, n), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let corner = shape.linear(0, 0, 0);
        let (tx, ty, tz) = (15u64, 7u64, 3u64);
        let target = shape.linear(tx, ty, tz);
        let cfg = EdfConfig::default();

        let exact = exact_euclidean_distance_field(&source, &[corner], cfg).unwrap();
        let chamfer = euclidean_distance_field(&source, &[corner], cfg).unwrap();

        let true_dist = ((tx * tx + ty * ty + tz * tz) as f32).sqrt();
        let exact_d = exact.distances[target as usize];
        let chamfer_d = chamfer.distances[target as usize];

        assert!(
            (exact_d - true_dist).abs() < 1e-3,
            "exact {exact_d} != true Euclidean {true_dist}"
        );
        // Chamfer over-estimates the true Euclidean distance at this target.
        assert!(
            chamfer_d > exact_d + 0.5,
            "chamfer {chamfer_d} should exceed exact {exact_d} by the diagonal error"
        );
    }

    #[test]
    fn exact_edf_feature_map_is_a_nearest_source() {
        let arr = Array3::<u8>::from_elem((8, 8, 8), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![
            shape.linear(0, 0, 0),
            shape.linear(7, 7, 7),
            shape.linear(7, 0, 0),
        ];
        let mut cfg = EdfConfig::default();
        cfg.return_feature_map = true;

        let got = exact_euclidean_distance_field_parallel(&source, &sources, cfg).unwrap();
        let fm = got.feature_map.expect("feature map requested");

        for idx in 0..shape.total() as usize {
            let feat = fm[idx];
            assert!(feat != u64::MAX, "voxel {idx} unclaimed");
            let s = sources[feat as usize];
            let (sx, sy, sz) = shape.coords(s);
            let (x, y, z) = shape.coords(idx as u64);
            let dx = x as f64 - sx as f64;
            let dy = y as f64 - sy as f64;
            let dz = z as f64 - sz as f64;
            let feat_dist = (dx * dx + dy * dy + dz * dz).sqrt() as f32;
            assert!(
                (feat_dist - got.distances[idx]).abs() < 1e-3,
                "voxel {idx}: feature source dist {feat_dist} != reported {}",
                got.distances[idx]
            );
        }
    }

    #[test]
    fn exact_edf_source_voxels_are_zero() {
        let arr = Array3::<u8>::from_elem((6, 7, 5), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![shape.linear(3, 2, 4), shape.linear(0, 6, 0)];
        let cfg = EdfConfig::default();
        let got = exact_euclidean_distance_field(&source, &sources, cfg).unwrap();
        for &s in &sources {
            assert_eq!(got.distances[s as usize], 0.0, "source {s} not zero");
        }
    }

    #[test]
    fn exact_edf_rejects_empty_and_oob_sources() {
        let arr = Array3::<u8>::from_elem((4, 4, 4), 1);
        let source = ArrayView3Source::new(arr.view());
        let cfg = EdfConfig::default();
        assert!(exact_euclidean_distance_field(&source, &[], cfg).is_err());
        assert!(exact_euclidean_distance_field(&source, &[9999], cfg).is_err());
    }

    #[test]
    fn f32_field_is_exact_decision() {
        use crate::voxel::VolumeShape;
        // Isotropic (a=1): exact well past 512³ (3·511² = 783 363 ≪ 2^24).
        let iso512 = VolumeShape::new(512, 512, 512);
        assert!(f32_field_is_exact(iso512, 1.0, 1.0, 1.0));

        let aniso256 = VolumeShape::new(256, 256, 256);
        assert!(!f32_field_is_exact(aniso256, 16.0, 16.0, 1600.0));

        assert!(!f32_field_is_exact(iso512, 2.25, 1.0, 1.0));

        assert!(f32_field_is_exact(
            VolumeShape::new(4097, 1, 1),
            1.0,
            1.0,
            1.0
        ));
        assert!(!f32_field_is_exact(
            VolumeShape::new(4098, 1, 1),
            1.0,
            1.0,
            1.0
        ));
    }

    #[test]
    fn exact_edf_f32_storage_exact_near_boundary() {
        let n = 4096usize;
        let arr = Array3::<u8>::from_elem((n, 1, 1), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let src = shape.linear(0, 0, 0);
        let cfg = EdfConfig::default();
        assert!(
            f32_field_is_exact(shape, 1.0, 1.0, 1.0),
            "should pick f32 path"
        );
        let got = exact_euclidean_distance_field(&source, &[src], cfg).unwrap();
        for x in 0..n as u64 {
            let idx = shape.linear(x, 0, 0) as usize;
            // Exact integer distance — zero tolerance.
            assert_eq!(
                got.distances[idx], x as f32,
                "voxel x={x}: f32 storage lost the exact distance"
            );
        }
    }

    #[test]
    fn exact_edf_f64_fallback_non_integer_anisotropy_matches_bruteforce() {
        let arr = Array3::<u8>::from_elem((9, 7, 6), 1);
        let source = ArrayView3Source::new(arr.view());
        let shape = source.shape();
        let sources = vec![shape.linear(0, 0, 0), shape.linear(8, 6, 5)];
        let mut cfg = EdfConfig::default();
        cfg.anisotropy = crate::voxel::Anisotropy::new(1.5, 1.0, 1.0); // a_x = 2.25
        let a_x = (cfg.anisotropy.wx as f64).powi(2);
        assert!(
            !f32_field_is_exact(shape, a_x, 1.0, 1.0),
            "non-integer anisotropy must take the f64 fallback"
        );
        let got = exact_euclidean_distance_field(&source, &sources, cfg).unwrap();
        let want = brute_force_exact(shape, &sources, cfg.anisotropy);
        assert_close(&got.distances, &want, 1e-4, "f64 fallback anisotropic");
    }
}