Skip to main content

spatialrust_features/
boundary.rs

1//! Boundary / edge point detection via tangent-plane angle gaps.
2//!
3//! A point on the interior of a well-sampled surface has neighbors spread all
4//! around it in its tangent plane; a point on a boundary (a hole rim or the edge
5//! of a scan) has a large empty angular wedge. Projecting neighbors into the
6//! tangent plane and measuring the largest gap between consecutive directions
7//! flags those boundary points.
8
9use spatialrust_core::{
10    HasNormals3, HasPositions3, PointBuffer, PointBufferSet, PointCloud, SpatialError,
11    SpatialResult,
12};
13use spatialrust_math::Vec3;
14use spatialrust_search::{parallel_worker_count, KdTree, RadiusSearchIndex};
15
16/// Configuration for [`BoundaryDetector`].
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct BoundaryConfig {
19    /// Neighborhood radius used to gather tangent-plane directions.
20    pub search_radius: f32,
21    /// A point is a boundary if its largest angular gap (radians) exceeds this.
22    pub angle_threshold: f32,
23    /// Minimum neighbors required to evaluate a point.
24    pub min_neighbors: usize,
25}
26
27impl Default for BoundaryConfig {
28    fn default() -> Self {
29        // ~90°: interior points have small gaps, boundary points a large wedge.
30        Self { search_radius: 0.1, angle_threshold: std::f32::consts::FRAC_PI_2, min_neighbors: 5 }
31    }
32}
33
34impl BoundaryConfig {
35    /// Creates a config from the search radius (90° threshold).
36    #[must_use]
37    pub fn with_radius(search_radius: f32) -> Self {
38        Self { search_radius, ..Self::default() }
39    }
40}
41
42/// Result of boundary detection.
43#[derive(Clone, Debug, PartialEq)]
44pub struct BoundaryResult {
45    /// Indices of the boundary points in the input cloud.
46    pub indices: Vec<usize>,
47    /// Sub-cloud containing only the boundary points (schema preserved).
48    pub boundary: PointCloud,
49}
50
51/// Tangent-plane boundary point detector. The input cloud must carry normals.
52#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct BoundaryDetector {
54    config: BoundaryConfig,
55}
56
57impl BoundaryDetector {
58    /// Creates a detector from config.
59    #[must_use]
60    pub const fn new(config: BoundaryConfig) -> Self {
61        Self { config }
62    }
63
64    /// Returns the detector config.
65    #[must_use]
66    pub const fn config(&self) -> BoundaryConfig {
67        self.config
68    }
69
70    /// Computes the per-point boundary mask (`true` = boundary).
71    ///
72    /// Shares one KD-tree across bounded scoped CPU workers using the existing
73    /// point-staging policy. Small clouds and one-worker calls run on the caller.
74    /// Point order, neighborhood order and per-point arithmetic are preserved.
75    pub fn boundary_mask(&self, input: &PointCloud) -> SpatialResult<Vec<bool>> {
76        self.boundary_mask_with_workers(input, parallel_worker_count(input.len()))
77    }
78
79    fn boundary_mask_with_workers(
80        &self,
81        input: &PointCloud,
82        workers: usize,
83    ) -> SpatialResult<Vec<bool>> {
84        if self.config.search_radius <= 0.0 || self.config.search_radius.is_nan() {
85            return Err(SpatialError::InvalidArgument("search_radius must be positive".to_owned()));
86        }
87        let len = input.len();
88        if len == 0 {
89            return Ok(Vec::new());
90        }
91
92        let (x, y, z) = input.positions3()?;
93        let (nx, ny, nz) = input.normals3()?;
94        let tree = KdTree::from_slices(x, y, z);
95
96        let mut mask = vec![false; len];
97        let fill = |start: usize, band: &mut [bool]| {
98            // Reuse angular scratch within each worker, without retaining an
99            // all-point neighbor table or allocating a worker result vector.
100            let mut angles: Vec<f32> = Vec::new();
101            for (offset, is_boundary) in band.iter_mut().enumerate() {
102                let i = start + offset;
103                let p = Vec3::new(x[i], y[i], z[i]);
104                let normal = Vec3::new(nx[i], ny[i], nz[i]);
105                let (u, v) = tangent_basis(normal);
106
107                let neighbors = tree.radius_search(p.x, p.y, p.z, self.config.search_radius);
108                angles.clear();
109                for neighbor in &neighbors {
110                    let j = neighbor.index;
111                    if j == i {
112                        continue;
113                    }
114                    let d = Vec3::new(x[j] - p.x, y[j] - p.y, z[j] - p.z);
115                    let (du, dv) = (d.dot(u), d.dot(v));
116                    if du * du + dv * dv > 1e-12 {
117                        angles.push(dv.atan2(du));
118                    }
119                }
120                if angles.len() < self.config.min_neighbors {
121                    continue;
122                }
123                *is_boundary = max_angle_gap(&mut angles) > self.config.angle_threshold;
124            }
125        };
126        let workers = workers.max(1).min(len);
127        if workers == 1 {
128            fill(0, &mut mask);
129        } else {
130            let chunk_size = len.div_ceil(workers);
131            std::thread::scope(|scope| {
132                for (band, chunk) in mask.chunks_mut(chunk_size).enumerate() {
133                    let fill = &fill;
134                    scope.spawn(move || fill(band * chunk_size, chunk));
135                }
136            });
137        }
138        Ok(mask)
139    }
140
141    /// Detects boundary points, returning their indices and a sub-cloud.
142    pub fn detect(&self, input: &PointCloud) -> SpatialResult<BoundaryResult> {
143        let mask = self.boundary_mask(input)?;
144        let indices: Vec<usize> =
145            mask.iter().enumerate().filter_map(|(i, &b)| b.then_some(i)).collect();
146        let boundary = gather_indices(input, &indices)?;
147        Ok(BoundaryResult { indices, boundary })
148    }
149}
150
151#[cfg(all(test, not(target_arch = "wasm32")))]
152#[path = "../tests/fixtures/boundary_serial.rs"]
153#[allow(dead_code)]
154mod previous;
155
156#[cfg(all(test, not(target_arch = "wasm32")))]
157#[path = "boundary_parallel_tests.rs"]
158mod parallel_tests;
159
160#[cfg(all(test, not(target_arch = "wasm32")))]
161#[path = "boundary_parallel_benchmark.rs"]
162mod parallel_benchmark;
163
164/// Builds an orthonormal basis `(u, v)` spanning the plane perpendicular to `n`.
165fn tangent_basis(n: Vec3<f32>) -> (Vec3<f32>, Vec3<f32>) {
166    let helper = if n.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
167    let u = n.cross(helper).normalize();
168    let v = n.cross(u);
169    (u, v)
170}
171
172/// Largest gap between consecutive sorted angles, wrapping around the circle.
173fn max_angle_gap(angles: &mut [f32]) -> f32 {
174    // A point with no in-plane neighbors has no gap to measure (reachable when
175    // `min_neighbors` is 0 and a point is isolated); treat it as non-salient.
176    if angles.is_empty() {
177        return 0.0;
178    }
179    angles.sort_by(f32::total_cmp);
180    let mut max_gap = 0.0_f32;
181    for w in angles.windows(2) {
182        max_gap = max_gap.max(w[1] - w[0]);
183    }
184    // Wrap-around gap between the last and first direction.
185    let wrap = (angles[0] + std::f32::consts::TAU) - angles[angles.len() - 1];
186    max_gap.max(wrap)
187}
188
189fn gather_indices(input: &PointCloud, indices: &[usize]) -> SpatialResult<PointCloud> {
190    let mut buffers = PointBufferSet::new();
191    for field in input.schema().fields() {
192        let source = input.field(&field.name)?;
193        buffers.insert(field.name.clone(), gather_buffer(source, indices));
194    }
195    PointCloud::try_from_parts(input.schema().clone(), buffers, input.metadata().clone())
196}
197
198fn gather_buffer(source: &PointBuffer, indices: &[usize]) -> PointBuffer {
199    match source {
200        PointBuffer::F32(v) => PointBuffer::from_f32(indices.iter().map(|&i| v[i]).collect()),
201        PointBuffer::F64(v) => PointBuffer::F64(indices.iter().map(|&i| v[i]).collect()),
202        PointBuffer::U8(v) => PointBuffer::U8(indices.iter().map(|&i| v[i]).collect()),
203        PointBuffer::U16(v) => PointBuffer::U16(indices.iter().map(|&i| v[i]).collect()),
204        PointBuffer::U32(v) => PointBuffer::U32(indices.iter().map(|&i| v[i]).collect()),
205        PointBuffer::I32(v) => PointBuffer::I32(indices.iter().map(|&i| v[i]).collect()),
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::{BoundaryConfig, BoundaryDetector};
212    use spatialrust_core::{DType, FieldSemantic, PointCloudBuilder, PointField, PointSchema};
213
214    fn schema() -> PointSchema {
215        PointSchema::new()
216            .with_field(PointField::scalar("x", FieldSemantic::PositionX, DType::F32))
217            .with_field(PointField::scalar("y", FieldSemantic::PositionY, DType::F32))
218            .with_field(PointField::scalar("z", FieldSemantic::PositionZ, DType::F32))
219            .with_field(PointField::scalar("normal_x", FieldSemantic::NormalX, DType::F32))
220            .with_field(PointField::scalar("normal_y", FieldSemantic::NormalY, DType::F32))
221            .with_field(PointField::scalar("normal_z", FieldSemantic::NormalZ, DType::F32))
222    }
223
224    /// A square planar patch (normal +Z): rim points are boundaries, the
225    /// interior is not.
226    fn square_patch(n: usize) -> spatialrust_core::PointCloud {
227        let mut builder = PointCloudBuilder::new(schema());
228        for i in 0..n {
229            for j in 0..n {
230                builder.push_point([i as f32 * 0.1, j as f32 * 0.1, 0.0, 0.0, 0.0, 1.0]).unwrap();
231            }
232        }
233        builder.build().unwrap()
234    }
235
236    #[test]
237    fn detects_patch_rim_not_interior() {
238        let n = 12;
239        let cloud = square_patch(n);
240        // min_neighbors=3 so sparse corners (only 3 in-radius neighbors) are
241        // still evaluated.
242        let config = BoundaryConfig { min_neighbors: 3, ..BoundaryConfig::with_radius(0.18) };
243        let result = BoundaryDetector::new(config).detect(&cloud).unwrap();
244        let mask = BoundaryDetector::new(config).boundary_mask(&cloud).unwrap();
245
246        // The center point is interior; a corner is on the boundary.
247        let center = (n / 2) * n + (n / 2);
248        let corner = 0;
249        assert!(!mask[center], "interior point flagged as boundary");
250        assert!(mask[corner], "corner not flagged as boundary");
251        // Boundaries are a minority of the patch.
252        assert!(!result.indices.is_empty());
253        assert!(result.indices.len() < cloud.len() / 2);
254        assert_eq!(result.boundary.len(), result.indices.len());
255    }
256
257    #[test]
258    fn rejects_bad_radius() {
259        let cloud = square_patch(5);
260        assert!(BoundaryDetector::new(BoundaryConfig::with_radius(0.0)).detect(&cloud).is_err());
261    }
262
263    #[test]
264    fn handles_isolated_point_with_zero_min_neighbors() {
265        // A lone point far from the patch has no in-radius neighbors. With
266        // min_neighbors = 0 this used to reach the angle-gap code with an empty
267        // angle list and panic; it must now just run.
268        let mut builder = PointCloudBuilder::new(schema());
269        builder.push_point([0.0, 0.0, 0.0, 0.0, 0.0, 1.0]).unwrap();
270        builder.push_point([100.0, 100.0, 100.0, 0.0, 0.0, 1.0]).unwrap();
271        let cloud = builder.build().unwrap();
272
273        let config = BoundaryConfig { min_neighbors: 0, ..BoundaryConfig::with_radius(0.1) };
274        let mask = BoundaryDetector::new(config).boundary_mask(&cloud).unwrap();
275        // Isolated points (no neighbors) are not flagged as surface boundaries.
276        assert_eq!(mask, vec![false, false]);
277    }
278}