1use spatialrust_core::{
10 FieldSemantic, HasPositions3, PointBuffer, PointBufferSet, PointCloud, SpatialError,
11 SpatialResult,
12};
13use spatialrust_math::{solve_linear_system, symmetric_eigen3, LeastSquaresResult, Mat3, Vec3};
14use spatialrust_search::{parallel_worker_count, KdTree, RadiusSearchIndex};
15
16use crate::filter::PointCloudFilter;
17
18#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct MlsConfig {
21 pub search_radius: f32,
23 pub polynomial_order: u8,
25 pub min_neighbors: usize,
27}
28
29impl Default for MlsConfig {
30 fn default() -> Self {
31 Self { search_radius: 0.1, polynomial_order: 2, min_neighbors: 6 }
32 }
33}
34
35impl MlsConfig {
36 #[must_use]
38 pub const fn with_radius(search_radius: f32) -> Self {
39 Self { search_radius, polynomial_order: 2, min_neighbors: 6 }
40 }
41}
42
43#[cfg(feature = "filter-mls-gpu")]
45#[derive(Clone, Debug, PartialEq)]
46pub struct GpuMlsPositionResult {
47 pub positions: Vec<Vec3<f32>>,
49 pub modes: Vec<spatialrust_gpu::GpuMlsMode>,
51 pub diagnostics: spatialrust_gpu::GpuMlsDiagnostics,
53 pub transfers: spatialrust_core::TransferStats,
55}
56
57#[cfg(feature = "filter-mls-gpu")]
59#[derive(Clone, Debug, PartialEq)]
60pub struct GpuMlsFilterResult {
61 pub cloud: PointCloud,
63 pub modes: Vec<spatialrust_gpu::GpuMlsMode>,
65 pub diagnostics: spatialrust_gpu::GpuMlsDiagnostics,
67 pub transfers: spatialrust_core::TransferStats,
69}
70
71#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct MlsSmoothing {
74 config: MlsConfig,
75}
76
77impl MlsSmoothing {
78 #[must_use]
80 pub const fn new(config: MlsConfig) -> Self {
81 Self { config }
82 }
83
84 #[must_use]
86 pub const fn config(&self) -> MlsConfig {
87 self.config
88 }
89
90 pub fn smoothed_positions(&self, input: &PointCloud) -> SpatialResult<Vec<Vec3<f32>>> {
97 self.smoothed_positions_with_workers(input, parallel_worker_count(input.len()))
98 }
99
100 #[cfg(feature = "filter-mls-gpu")]
109 pub fn smoothed_positions_with_gpu(
110 &self,
111 runtime: &spatialrust_gpu::WgpuRuntime,
112 input: &PointCloud,
113 neighbor_capacity: u32,
114 ) -> SpatialResult<GpuMlsPositionResult> {
115 let radius = self.config.search_radius;
116 if !radius.is_finite()
117 || radius <= 0.0
118 || !(radius * radius).is_finite()
119 || radius * radius == 0.0
120 || self.config.polynomial_order > 2
121 {
122 return Err(SpatialError::InvalidArgument(
123 "GPU MLS requires a positive finite nonzero radius square and order 0..=2"
124 .to_owned(),
125 ));
126 }
127 let (x, y, z) = input.positions3()?;
128 if x.iter().chain(y).chain(z).any(|v| !v.is_finite()) {
129 return Err(SpatialError::InvalidArgument("GPU MLS requires finite XYZ".to_owned()));
130 }
131 let tree = KdTree::from_slices(x, y, z);
132 let device_input = spatialrust_gpu::GpuMlsInput::upload(runtime, &tree)?;
133 let rows = device_input.neighborhoods_resident(runtime, radius, neighbor_capacity)?;
134 let output = device_input.smooth_resident(
135 runtime,
136 &rows,
137 self.config.polynomial_order,
138 u32::try_from(self.config.min_neighbors).unwrap_or(u32::MAX),
139 )?;
140 let readback = output.download(runtime)?;
141 let mut transfers = device_input.upload_transfers();
142 transfers.record(
143 spatialrust_core::TransferDirection::DeviceToHost,
144 readback.transfers.device_to_host_bytes(),
145 );
146 let positions =
147 readback.positions.into_iter().map(|p| Vec3::new(p[0], p[1], p[2])).collect();
148 Ok(GpuMlsPositionResult {
149 positions,
150 modes: readback.modes,
151 diagnostics: readback.diagnostics,
152 transfers,
153 })
154 }
155
156 #[cfg(feature = "filter-mls-gpu")]
160 pub fn filter_with_gpu(
161 &self,
162 runtime: &spatialrust_gpu::WgpuRuntime,
163 input: &PointCloud,
164 neighbor_capacity: u32,
165 ) -> SpatialResult<GpuMlsFilterResult> {
166 let result = self.smoothed_positions_with_gpu(runtime, input, neighbor_capacity)?;
167 let cloud = build_output(input, &result.positions)?;
168 Ok(GpuMlsFilterResult {
169 cloud,
170 modes: result.modes,
171 diagnostics: result.diagnostics,
172 transfers: result.transfers,
173 })
174 }
175
176 fn smoothed_positions_with_workers(
177 &self,
178 input: &PointCloud,
179 workers: usize,
180 ) -> SpatialResult<Vec<Vec3<f32>>> {
181 if self.config.search_radius <= 0.0 || self.config.search_radius.is_nan() {
182 return Err(SpatialError::InvalidArgument("search_radius must be positive".to_owned()));
183 }
184 if self.config.polynomial_order > 2 {
185 return Err(SpatialError::InvalidArgument(
186 "polynomial_order must be 1 or 2".to_owned(),
187 ));
188 }
189
190 let (x, y, z) = input.positions3()?;
191 let len = input.len();
192 let tree = KdTree::from_slices(x, y, z);
193 let h_sq = (self.config.search_radius / 2.0).powi(2).max(1e-12);
196
197 let smooth = |i| smooth_point(i, &tree, x, y, z, self.config, h_sq);
198 let workers = workers.max(1).min(len.max(1));
199 if workers == 1 {
200 let mut out = Vec::with_capacity(len);
201 for i in 0..len {
202 out.push(smooth(i));
203 }
204 return Ok(out);
205 }
206
207 let mut out = vec![Vec3::new(0.0, 0.0, 0.0); len];
208 let chunk_size = len.div_ceil(workers);
209 std::thread::scope(|scope| {
210 for (band, chunk) in out.chunks_mut(chunk_size).enumerate() {
211 let start = band * chunk_size;
212 let smooth = &smooth;
213 scope.spawn(move || {
214 for (offset, position) in chunk.iter_mut().enumerate() {
215 *position = smooth(start + offset);
216 }
217 });
218 }
219 });
220 Ok(out)
221 }
222}
223
224fn smooth_point(
225 i: usize,
226 tree: &KdTree,
227 x: &[f32],
228 y: &[f32],
229 z: &[f32],
230 config: MlsConfig,
231 h_sq: f32,
232) -> Vec3<f32> {
233 let p = Vec3::new(x[i], y[i], z[i]);
234 let neighbors = tree.radius_search(p.x, p.y, p.z, config.search_radius);
235 if neighbors.len() < config.min_neighbors {
236 return p;
237 }
238 let pts: Vec<Vec3<f32>> = neighbors
241 .iter()
242 .filter(|n| n.index != i)
243 .map(|n| Vec3::new(x[n.index], y[n.index], z[n.index]))
244 .collect();
245 project_point(p, &pts, config.polynomial_order, h_sq).unwrap_or(p)
246}
247
248impl PointCloudFilter for MlsSmoothing {
249 fn name(&self) -> &'static str {
250 "MlsSmoothing"
251 }
252
253 fn filter(&self, input: &PointCloud) -> SpatialResult<PointCloud> {
254 let smoothed = self.smoothed_positions(input)?;
255 build_output(input, &smoothed)
256 }
257}
258
259fn project_point(p: Vec3<f32>, neighbors: &[Vec3<f32>], order: u8, h_sq: f32) -> Option<Vec3<f32>> {
261 let mut sum_w = 0.0_f64;
263 let mut centroid = [0.0_f64; 3];
264 let mut weights = Vec::with_capacity(neighbors.len());
265 for q in neighbors {
266 let d_sq = (*q - p).length_squared();
267 let w = f64::from((-d_sq / h_sq).exp());
268 weights.push(w);
269 sum_w += w;
270 centroid[0] += w * f64::from(q.x);
271 centroid[1] += w * f64::from(q.y);
272 centroid[2] += w * f64::from(q.z);
273 }
274 if sum_w < 1e-12 {
275 return None;
276 }
277 let c = Vec3::new(
278 (centroid[0] / sum_w) as f32,
279 (centroid[1] / sum_w) as f32,
280 (centroid[2] / sum_w) as f32,
281 );
282
283 let mut cov = [[0.0_f64; 3]; 3];
284 for (q, &w) in neighbors.iter().zip(&weights) {
285 let d = *q - c;
286 let d = [f64::from(d.x), f64::from(d.y), f64::from(d.z)];
287 for r in 0..3 {
288 for col in 0..3 {
289 cov[r][col] += w * d[r] * d[col];
290 }
291 }
292 }
293 let covariance = Mat3::<f64>::from_rows(cov[0], cov[1], cov[2]);
294 let eigen = symmetric_eigen3(covariance);
295 let normal = Vec3::new(
297 eigen.eigenvectors.m[0][0] as f32,
298 eigen.eigenvectors.m[1][0] as f32,
299 eigen.eigenvectors.m[2][0] as f32,
300 )
301 .normalize();
302
303 let helper =
305 if normal.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
306 let u = normal.cross(helper).normalize();
307 let v = normal.cross(u);
308
309 let rel = p - c;
311 let qu = rel.dot(u);
312 let qv = rel.dot(v);
313
314 let basis = |s: f32, t: f32| match order {
316 0 => vec![1.0_f64],
317 1 => vec![1.0, f64::from(s), f64::from(t)],
318 _ => vec![
319 1.0,
320 f64::from(s),
321 f64::from(t),
322 f64::from(s * s),
323 f64::from(s * t),
324 f64::from(t * t),
325 ],
326 };
327 let terms = basis(0.0, 0.0).len();
328 if neighbors.len() < terms {
329 return Some(c + scale(u, qu) + scale(v, qv));
331 }
332
333 let mut ata = vec![vec![0.0_f64; terms]; terms];
334 let mut atb = vec![0.0_f64; terms];
335 for (q, &w) in neighbors.iter().zip(&weights) {
336 let d = *q - c;
337 let s = d.dot(u);
338 let t = d.dot(v);
339 let height = f64::from(d.dot(normal));
340 let row = basis(s, t);
341 for a in 0..terms {
342 atb[a] += w * row[a] * height;
343 for b in 0..terms {
344 ata[a][b] += w * row[a] * row[b];
345 }
346 }
347 }
348
349 let coeffs = match solve_linear_system(ata, atb) {
350 LeastSquaresResult::Solved(c) => c,
351 LeastSquaresResult::Singular => return Some(c + scale(u, qu) + scale(v, qv)),
352 };
353 let query_basis = basis(qu, qv);
354 let height: f64 = coeffs.iter().zip(&query_basis).map(|(c, b)| c * b).sum();
355
356 Some(c + scale(u, qu) + scale(v, qv) + scale(normal, height as f32))
357}
358
359fn scale(v: Vec3<f32>, s: f32) -> Vec3<f32> {
360 Vec3::new(v.x * s, v.y * s, v.z * s)
361}
362
363fn build_output(input: &PointCloud, positions: &[Vec3<f32>]) -> SpatialResult<PointCloud> {
365 let schema = input.schema().clone();
366 let name_for = |sem| schema.find_semantic(sem).map(|f| f.name.clone());
367 let (xn, yn, zn) = (
368 name_for(FieldSemantic::PositionX),
369 name_for(FieldSemantic::PositionY),
370 name_for(FieldSemantic::PositionZ),
371 );
372
373 let mut buffers = PointBufferSet::new();
374 for field in schema.fields() {
375 let name = &field.name;
376 let buffer = if Some(name) == xn.as_ref() {
377 PointBuffer::from_f32(positions.iter().map(|p| p.x).collect())
378 } else if Some(name) == yn.as_ref() {
379 PointBuffer::from_f32(positions.iter().map(|p| p.y).collect())
380 } else if Some(name) == zn.as_ref() {
381 PointBuffer::from_f32(positions.iter().map(|p| p.z).collect())
382 } else {
383 clone_buffer(input.field(name)?)
384 };
385 buffers.insert(name.clone(), buffer);
386 }
387 PointCloud::try_from_parts(schema, buffers, input.metadata().clone())
388}
389
390fn clone_buffer(buffer: &PointBuffer) -> PointBuffer {
391 match buffer {
392 PointBuffer::F32(v) => PointBuffer::from_f32(v.clone()),
393 PointBuffer::F64(v) => PointBuffer::F64(v.clone()),
394 PointBuffer::U8(v) => PointBuffer::U8(v.clone()),
395 PointBuffer::U16(v) => PointBuffer::U16(v.clone()),
396 PointBuffer::U32(v) => PointBuffer::U32(v.clone()),
397 PointBuffer::I32(v) => PointBuffer::I32(v.clone()),
398 }
399}
400
401#[cfg(test)]
402#[allow(dead_code)]
403#[path = "../tests/fixtures/mls_serial.rs"]
404mod previous;
405
406#[cfg(test)]
407#[path = "mls_parallel_tests.rs"]
408mod parallel_tests;
409
410#[cfg(test)]
411#[path = "mls_parallel_benchmark.rs"]
412mod parallel_benchmark;
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use spatialrust_core::{PointCloudBuilder, StandardSchemas};
418
419 #[test]
421 fn flattens_noisy_plane() {
422 let mut seed = 12345_u64;
424 let mut noise = || {
425 seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
426 let unit = (seed >> 32) as u32 as f32 / u32::MAX as f32;
428 (unit * 2.0 - 1.0) * 0.02
429 };
430
431 let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
432 let mut z_before = Vec::new();
433 for i in 0..25 {
434 for j in 0..25 {
435 let z = noise();
436 z_before.push(z);
437 builder.push_point([i as f32 * 0.05, j as f32 * 0.05, z]).unwrap();
438 }
439 }
440 let cloud = builder.build().unwrap();
441
442 let smoother = MlsSmoothing::new(MlsConfig {
444 search_radius: 0.2,
445 polynomial_order: 1,
446 min_neighbors: 6,
447 });
448 let out = smoother.filter(&cloud).unwrap();
449 assert_eq!(out.len(), cloud.len());
450
451 let (_, _, z) = out.positions3().unwrap();
452 let interior = |k: usize| {
453 let (i, j) = (k / 25, k % 25);
454 (4..21).contains(&i) && (4..21).contains(&j)
455 };
456 let rms = |get: &dyn Fn(usize) -> f32| {
458 let vals: Vec<f32> = (0..cloud.len()).filter(|&k| interior(k)).map(get).collect();
459 (vals.iter().map(|v| v * v).sum::<f32>() / vals.len() as f32).sqrt()
460 };
461 let before = rms(&|k| z_before[k]);
462 let after = rms(&|k| z[k]);
463 assert!(after < before * 0.6, "MLS did not flatten: rms {after} vs {before}");
464 }
465
466 #[test]
467 fn rejects_bad_params() {
468 let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
469 builder.push_point([0.0, 0.0, 0.0]).unwrap();
470 let cloud = builder.build().unwrap();
471 assert!(MlsSmoothing::new(MlsConfig::with_radius(0.0)).smoothed_positions(&cloud).is_err());
472 assert!(MlsSmoothing::new(MlsConfig {
473 search_radius: 0.1,
474 polynomial_order: 3,
475 min_neighbors: 6
476 })
477 .smoothed_positions(&cloud)
478 .is_err());
479 }
480}