Skip to main content

spatialrust_search/
kdtree_build.rs

1//! Disjoint subtree construction with the unchanged partition/tie convention.
2use super::*;
3
4/// Minimum points before the explicit KD-tree builder uses scoped CPU workers.
5pub const PARALLEL_KDTREE_BUILD_MIN_POINTS: usize = 32_768;
6#[cfg(not(target_arch = "wasm32"))]
7const MIN_WORKER_POINTS: usize = PARALLEL_KDTREE_BUILD_MIN_POINTS / 2;
8
9impl KdTree {
10    /// Builds with bounded scoped CPU workers under the `parallel` feature.
11    /// Point permutation, split bits, preorder node layout and query ties match
12    /// `from_slices` exactly. Native workers per call are bounded by available
13    /// parallelism and one per 16,384 points; inputs below 32,768 points or one
14    /// useful worker keep the serial constructor. WASM also stays serial.
15    /// Axes are copied once; one exact-sized node array is split into disjoint
16    /// subtree ranges without locks, unsafe, per-worker trees or a merge copy.
17    /// This is a per-call bound, not a process-wide thread/stack limit.
18    /// Panics on unequal axis lengths, or counts exceeding u32 original indices.
19    #[must_use]
20    pub fn from_slices_parallel(x: &[f32], y: &[f32], z: &[f32]) -> Self {
21        if x.len() < PARALLEL_KDTREE_BUILD_MIN_POINTS {
22            return Self::from_slices(x, y, z);
23        }
24        #[cfg(not(target_arch = "wasm32"))]
25        {
26            let workers = std::thread::available_parallelism().map_or(1, |n| n.get());
27            from_slices_with_workers(x, y, z, workers)
28        }
29        #[cfg(target_arch = "wasm32")]
30        {
31            assert!(x.len() <= u32::MAX as usize, "KD-tree original indices must fit u32");
32            Self::from_slices(x, y, z)
33        }
34    }
35
36    /// Builds an explicit parallel tree from a cloud, retaining position order.
37    pub fn from_point_cloud_parallel(cloud: &PointCloud) -> SpatialResult<Self> {
38        let (x, y, z) = cloud.positions3()?;
39        Ok(Self::from_slices_parallel(x, y, z))
40    }
41}
42
43#[cfg(not(target_arch = "wasm32"))]
44fn worker_count(points: usize, available: usize) -> usize {
45    if points < PARALLEL_KDTREE_BUILD_MIN_POINTS {
46        1
47    } else {
48        available.max(1).min(points / MIN_WORKER_POINTS)
49    }
50}
51
52// All levels above a power-of-two frontier split. At that frontier, bucket
53// sizes are floor(N/frontier) or ceil(N/frontier). With the power-of-two leaf
54// size, either every bucket splits once, or only N-LEAF_SIZE*frontier do.
55// This gives exact preorder subtree sizes in O(1), including odd boundaries.
56#[cfg(not(target_arch = "wasm32"))]
57fn node_count(points: usize) -> usize {
58    if points == 0 {
59        return 0;
60    }
61    if points <= LEAF_SIZE {
62        return 1;
63    }
64    debug_assert!(LEAF_SIZE.is_power_of_two());
65    let quotient = points / LEAF_SIZE;
66    let frontier = 1usize << (usize::BITS - 1 - quotient.leading_zeros());
67    if points / frontier == LEAF_SIZE {
68        2 * frontier - 1 + 2 * (points - LEAF_SIZE * frontier)
69    } else {
70        4 * frontier - 1
71    }
72}
73
74#[cfg(not(target_arch = "wasm32"))]
75fn from_slices_with_workers(x: &[f32], y: &[f32], z: &[f32], available: usize) -> KdTree {
76    assert_eq!(x.len(), y.len());
77    assert_eq!(x.len(), z.len());
78    assert!(x.len() <= u32::MAX as usize, "KD-tree original indices must fit u32");
79    let workers = worker_count(x.len(), available);
80    if workers == 1 {
81        return KdTree::from_slices(x, y, z);
82    }
83    let mut points_order: Vec<u32> = (0..x.len() as u32).collect();
84    let empty =
85        KdNode { split: 0.0, left: INVALID_NODE, right: INVALID_NODE, start: 0, end: 0, axis: 0 };
86    let mut nodes = vec![empty; node_count(x.len())];
87    build_into([x, y, z], &mut points_order, &mut nodes, 0, 0, workers);
88    KdTree { x: x.to_vec(), y: y.to_vec(), z: z.to_vec(), points_order, nodes, root: 0 }
89}
90
91#[cfg(not(target_arch = "wasm32"))]
92fn build_into(
93    xyz: [&[f32]; 3],
94    order: &mut [u32],
95    nodes: &mut [KdNode],
96    point_offset: usize,
97    node_offset: usize,
98    workers: usize,
99) {
100    let count = order.len();
101    let (node, children) = nodes.split_first_mut().expect("nonempty subtree node range");
102    node.start = point_offset as u32;
103    node.end = (point_offset + count) as u32;
104    if count <= LEAF_SIZE {
105        node.axis = AXIS_LEAF;
106        return;
107    }
108    let [x, y, z] = xyz;
109    let (axis, minimum) = select_axis(x, y, z, order, 0, count);
110    let mid = count / 2;
111    select_nth_by_axis(x, y, z, order, 0, count, (axis, minimum), mid);
112    node.axis = axis;
113    node.split = coordinate(x, y, z, order[mid], axis);
114    let left_count = node_count(mid);
115    let left_offset = node_offset + 1;
116    let right_offset = left_offset + left_count;
117    node.left = left_offset as u32;
118    node.right = right_offset as u32;
119    let (left_order, right_order) = order.split_at_mut(mid);
120    let (left_nodes, right_nodes) = children.split_at_mut(left_count);
121    if workers == 1 || count < PARALLEL_KDTREE_BUILD_MIN_POINTS {
122        build_into(xyz, left_order, left_nodes, point_offset, left_offset, 1);
123        build_into(xyz, right_order, right_nodes, point_offset + mid, right_offset, 1);
124    } else {
125        let left_workers = workers / 2;
126        let right_workers = workers - left_workers;
127        std::thread::scope(|scope| {
128            let left = scope.spawn(move || {
129                build_into(xyz, left_order, left_nodes, point_offset, left_offset, left_workers)
130            });
131            build_into(
132                xyz,
133                right_order,
134                right_nodes,
135                point_offset + mid,
136                right_offset,
137                right_workers,
138            );
139            left.join().expect("bounded KD-tree build worker panicked");
140        });
141    }
142}
143
144#[cfg(all(test, not(target_arch = "wasm32")))]
145#[path = "kdtree_build_tests.rs"]
146mod tests;