1use crate::{scratch::ScratchBuffers, GpuKdTree, GpuNeighborhoods, GpuQueryBatch, WgpuRuntime};
2use bytemuck::{Pod, Zeroable};
3use spatialrust_core::{SpatialError, SpatialResult, TransferDirection, TransferStats};
4use spatialrust_search::KdTree;
5use std::sync::Arc;
6use wgpu::util::DeviceExt;
7
8#[repr(C)]
9#[derive(Clone, Copy, Pod, Zeroable)]
10struct Params {
11 count: u32,
12 capacity: u32,
13 min_neighbors: u32,
14 padding: u32,
15 radius_squared: f32,
16 weight_scale_squared: f32,
17 unused: [f32; 2],
18}
19
20fn invalid() -> SpatialError {
21 SpatialError::InvalidArgument("GPU MLS requires matching input/runtime ownership, finite XYZ/extents, positive finite nonzero radius squares, order 0..=2 and supported buffers/dispatch".to_owned())
22}
23
24fn valid_radius(radius: f32) -> bool {
25 radius.is_finite() && radius > 0.0 && (radius * radius).is_finite() && radius * radius > 0.0
26}
27
28fn plan(points: u64, limits: &wgpu::Limits) -> SpatialResult<u32> {
29 let bytes = points.checked_mul(192).ok_or_else(invalid)?;
30 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
31 if points > u64::from(u32::MAX)
32 || bytes > bound
33 || bytes > isize::MAX as u64
34 || bound < 192
35 || limits.max_compute_workgroup_size_x < 64
36 || limits.max_compute_workgroup_size_y == 0
37 || limits.max_compute_workgroup_size_z == 0
38 || limits.max_compute_invocations_per_workgroup < 64
39 || points.div_ceil(64) > u64::from(limits.max_compute_workgroups_per_dimension)
40 || limits.max_storage_buffers_per_shader_stage < 6
41 || limits.max_bindings_per_bind_group < 7
42 || limits.max_bind_groups == 0
43 || limits.max_uniform_buffers_per_shader_stage == 0
44 || limits.max_uniform_buffer_binding_size < 32
45 || points
46 .checked_mul(16)
47 .and_then(|n| n.checked_add(32))
48 .map_or(true, |n| n > limits.max_buffer_size || n > isize::MAX as u64)
49 {
50 return Err(invalid());
51 }
52 Ok(points as u32)
53}
54
55pub struct GpuMlsInput {
58 tree: GpuKdTree,
59 queries: GpuQueryBatch,
60 count: u32,
61 identity: Arc<()>,
62 input_identity: Arc<()>,
63 transfers: TransferStats,
64}
65
66impl GpuMlsInput {
67 pub fn upload(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
71 Self::upload_impl(runtime, tree, false)
72 }
73
74 pub fn upload_with_gpu_gather(runtime: &WgpuRuntime, tree: &KdTree) -> SpatialResult<Self> {
82 Self::upload_impl(runtime, tree, true)
83 }
84
85 fn upload_impl(runtime: &WgpuRuntime, tree: &KdTree, gpu_gather: bool) -> SpatialResult<Self> {
86 let layout = tree.layout();
87 let (x, y, z) = layout.positions();
88 let count = plan(x.len() as u64, &runtime.device().limits())?;
89 if !super::feature_validation::valid([x, y, z], None) {
90 return Err(invalid());
91 }
92 let (tree, queries) = if gpu_gather {
93 GpuKdTree::upload_and_queries_with_gpu_gather(runtime, tree)?
94 } else {
95 (GpuKdTree::upload(runtime, tree)?, GpuQueryBatch::upload_soa(runtime, [x, y, z])?)
96 };
97 let mut transfers = tree.upload_transfers();
98 transfers.record(
99 TransferDirection::HostToDevice,
100 queries.upload_transfers().host_to_device_bytes(),
101 );
102 transfers.record(
103 TransferDirection::DeviceToDevice,
104 queries.upload_transfers().device_to_device_bytes(),
105 );
106 Ok(Self {
107 tree,
108 queries,
109 count,
110 identity: runtime.profiling_identity(),
111 input_identity: Arc::new(()),
112 transfers,
113 })
114 }
115
116 #[must_use]
118 pub const fn point_count(&self) -> u32 {
119 self.count
120 }
121
122 #[must_use]
125 pub const fn upload_transfers(&self) -> TransferStats {
126 self.transfers
127 }
128
129 pub fn neighborhoods_resident(
132 &self,
133 runtime: &WgpuRuntime,
134 radius: f32,
135 capacity: u32,
136 ) -> SpatialResult<GpuMlsNeighborhoods> {
137 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) || !valid_radius(radius) {
138 return Err(invalid());
139 }
140 let rows = self.tree.radius_neighbors_resident(runtime, &self.queries, radius, capacity)?;
141 Ok(GpuMlsNeighborhoods { rows, radius, input_identity: Arc::clone(&self.input_identity) })
142 }
143
144 pub fn smooth_resident(
155 &self,
156 runtime: &WgpuRuntime,
157 neighbors: &GpuMlsNeighborhoods,
158 polynomial_order: u8,
159 min_neighbors: u32,
160 ) -> SpatialResult<GpuMlsPositions> {
161 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity())
162 || !Arc::ptr_eq(&self.input_identity, &neighbors.input_identity)
163 || polynomial_order > 2
164 {
165 return Err(invalid());
166 }
167 plan(u64::from(self.count), &runtime.device().limits())?;
168 let create = |label, size| {
169 runtime.device().create_buffer(&wgpu::BufferDescriptor {
170 label: Some(label),
171 size,
172 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
173 mapped_at_creation: false,
174 })
175 };
176 let result = GpuMlsPositions {
177 buffer: create("mls-positions", (u64::from(self.count) * 16).max(16)),
178 status: create("mls-status", 32),
179 count: self.count,
180 identity: Arc::clone(&self.identity),
181 };
182 if self.count == 0 {
183 return Ok(result);
184 }
185 let cache = runtime.mls_pipelines.get_or_init(|| MlsPipelines::new(runtime.device()));
186 let params = Params {
187 count: self.count,
188 capacity: neighbors.rows.capacity(),
189 min_neighbors,
190 padding: 0,
191 radius_squared: neighbors.radius * neighbors.radius,
192 weight_scale_squared: (neighbors.radius * 0.5).powi(2).max(1e-12),
193 unused: [0.0; 2],
194 };
195 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
196 label: Some("mls-params"),
197 contents: bytemuck::bytes_of(¶ms),
198 usage: wgpu::BufferUsages::UNIFORM,
199 });
200 let mut scratch = ScratchBuffers::new(runtime);
201 let frames = scratch.acquire("mls-frames", u64::from(self.count) * 64);
202 let systems = scratch.acquire("mls-systems", u64::from(self.count) * 192);
203 let buffers = [
204 &uniform,
205 self.queries.buffer().unwrap(),
206 neighbors.rows.buffer(),
207 &frames,
208 &systems,
209 &result.buffer,
210 &result.status,
211 ];
212 let entries: Vec<_> = buffers
213 .iter()
214 .enumerate()
215 .map(|(binding, buffer)| wgpu::BindGroupEntry {
216 binding: binding as u32,
217 resource: buffer.as_entire_binding(),
218 })
219 .collect();
220 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
221 label: Some("mls-bindings"),
222 layout: &cache.layout,
223 entries: &entries,
224 });
225 let mut encoder = runtime.device().create_command_encoder(&Default::default());
226 for pipeline in [&cache.frames, &cache.fits[polynomial_order as usize], &cache.finalize] {
227 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
228 label: Some("mls-compute"),
229 timestamp_writes: None,
230 });
231 pass.set_pipeline(pipeline);
232 pass.set_bind_group(0, &group, &[]);
233 pass.dispatch_workgroups(self.count.div_ceil(64), 1, 1);
234 }
235 scratch.submit_and_recycle(encoder);
236 Ok(result)
237 }
238}
239
240pub struct GpuMlsNeighborhoods {
242 rows: GpuNeighborhoods,
243 radius: f32,
244 input_identity: Arc<()>,
245}
246impl GpuMlsNeighborhoods {
247 #[must_use]
249 pub fn rows(&self) -> &GpuNeighborhoods {
250 &self.rows
251 }
252}
253
254#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
256pub struct GpuMlsDiagnostics {
257 pub unchanged: u32,
259 pub plane_fallback: u32,
261 pub polynomial: u32,
263}
264
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub enum GpuMlsMode {
268 Unchanged,
270 PlaneFallback,
272 Polynomial,
274}
275
276#[derive(Clone, Debug, PartialEq)]
278pub struct GpuMlsReadback {
279 pub positions: Vec<[f32; 3]>,
281 pub modes: Vec<GpuMlsMode>,
283 pub diagnostics: GpuMlsDiagnostics,
285 pub transfers: TransferStats,
287}
288
289pub struct GpuMlsPositions {
292 buffer: wgpu::Buffer,
293 status: wgpu::Buffer,
294 count: u32,
295 identity: Arc<()>,
296}
297impl GpuMlsPositions {
298 #[must_use]
301 pub fn buffer(&self) -> &wgpu::Buffer {
302 &self.buffer
303 }
304 #[must_use]
308 pub fn status_buffer(&self) -> &wgpu::Buffer {
309 &self.status
310 }
311 #[must_use]
313 pub const fn point_count(&self) -> u32 {
314 self.count
315 }
316 #[must_use]
318 pub const fn readback_bytes(&self) -> u64 {
319 if self.count == 0 {
320 0
321 } else {
322 self.count as u64 * 16 + 32
323 }
324 }
325 pub fn download(&self, runtime: &WgpuRuntime) -> SpatialResult<GpuMlsReadback> {
329 if !Arc::ptr_eq(&self.identity, &runtime.profiling_identity()) {
330 return Err(invalid());
331 }
332 if self.count == 0 {
333 return Ok(GpuMlsReadback {
334 positions: vec![],
335 modes: vec![],
336 diagnostics: Default::default(),
337 transfers: Default::default(),
338 });
339 }
340 let bytes = u64::from(self.count) * 16;
341 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
342 label: Some("mls-readback"),
343 size: bytes + 32,
344 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
345 mapped_at_creation: false,
346 });
347 let mut encoder = runtime.device().create_command_encoder(&Default::default());
348 encoder.copy_buffer_to_buffer(&self.buffer, 0, &staging, 0, bytes);
349 encoder.copy_buffer_to_buffer(&self.status, 0, &staging, bytes, 32);
350 runtime.queue().submit(Some(encoder.finish()));
351 let slice = staging.slice(..);
352 let (sender, receiver) = std::sync::mpsc::channel();
353 slice.map_async(wgpu::MapMode::Read, move |r| {
354 let _ = sender.send(r);
355 });
356 runtime.device().poll(wgpu::Maintain::Wait);
357 receiver
358 .recv()
359 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?
360 .map_err(|e| SpatialError::InvalidArgument(e.to_string()))?;
361 let mapped = slice.get_mapped_range();
362 let words: &[u32] = bytemuck::cast_slice(&mapped);
363 let status = &words[bytes as usize / 4..];
364 let decoded = (|| {
365 if status[..5].iter().any(|&v| v != 0)
366 || u64::from(status[5]) + u64::from(status[6]) + u64::from(status[7])
367 != u64::from(self.count)
368 {
369 return Err(SpatialError::InvalidArgument(format!("GPU MLS rejected incomplete/malformed neighborhoods or numerical output; status={status:?}")));
370 }
371 let mut positions = Vec::with_capacity(self.count as usize);
372 let mut modes = Vec::with_capacity(self.count as usize);
373 let mut counts = [0u32; 3];
374 for row in words[..bytes as usize / 4].chunks_exact(4) {
375 let values: [f32; 4] = std::array::from_fn(|i| f32::from_bits(row[i]));
376 if values.iter().any(|v| !v.is_finite()) || ![0.0, 1.0, 2.0].contains(&values[3]) {
377 return Err(invalid());
378 }
379 counts[values[3] as usize] += 1;
380 modes.push(match values[3] as u32 {
381 0 => GpuMlsMode::Unchanged,
382 1 => GpuMlsMode::PlaneFallback,
383 _ => GpuMlsMode::Polynomial,
384 });
385 positions.push([values[0], values[1], values[2]]);
386 }
387 if counts != status[5..] {
388 return Err(invalid());
389 }
390 Ok((
391 positions,
392 modes,
393 GpuMlsDiagnostics {
394 unchanged: status[5],
395 plane_fallback: status[6],
396 polynomial: status[7],
397 },
398 ))
399 })();
400 drop(mapped);
401 staging.unmap();
402 let (positions, modes, diagnostics) = decoded?;
403 let mut transfers = TransferStats::default();
404 transfers.record(TransferDirection::DeviceToHost, bytes + 32);
405 Ok(GpuMlsReadback { positions, modes, diagnostics, transfers })
406 }
407}
408
409pub(crate) struct MlsPipelines {
410 layout: wgpu::BindGroupLayout,
411 frames: wgpu::ComputePipeline,
412 fits: [wgpu::ComputePipeline; 3],
413 finalize: wgpu::ComputePipeline,
414}
415impl MlsPipelines {
416 fn new(device: &wgpu::Device) -> Self {
417 let entries: Vec<_> = (0..7)
418 .map(|binding| wgpu::BindGroupLayoutEntry {
419 binding,
420 visibility: wgpu::ShaderStages::COMPUTE,
421 ty: wgpu::BindingType::Buffer {
422 ty: if binding == 0 {
423 wgpu::BufferBindingType::Uniform
424 } else {
425 wgpu::BufferBindingType::Storage { read_only: binding < 3 }
426 },
427 has_dynamic_offset: false,
428 min_binding_size: None,
429 },
430 count: None,
431 })
432 .collect();
433 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
434 label: Some("mls-layout"),
435 entries: &entries,
436 });
437 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
438 label: Some("mls-layout"),
439 bind_group_layouts: &[&layout],
440 push_constant_ranges: &[],
441 });
442 let common = include_str!("../shaders/mls_common.wgsl");
443 let frame_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
444 label: Some("mls-frame-shader"),
445 source: wgpu::ShaderSource::Wgsl(
446 format!("{common}{}", include_str!("../shaders/mls_frames.wgsl")).into(),
447 ),
448 });
449 let create = |shader: &wgpu::ShaderModule, entry| {
450 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
451 label: Some("mls-pipeline"),
452 layout: Some(&pipeline_layout),
453 module: shader,
454 entry_point: Some(entry),
455 compilation_options: Default::default(),
456 cache: None,
457 })
458 };
459 let frames = create(&frame_shader, "prepare_frames");
460 let fits = std::array::from_fn(|order| {
461 let terms = [1, 3, 6][order];
462 let template = if order == 0 {
463 include_str!("../shaders/mls_constant.wgsl").to_owned()
464 } else {
465 include_str!("../shaders/mls_fit.wgsl").replace(
466 "const FIT_TERMS: u32 = 6u;",
467 &format!("const FIT_TERMS: u32 = {terms}u;"),
468 )
469 };
470 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
471 label: Some("mls-fit-shader"),
472 source: wgpu::ShaderSource::Wgsl(format!("{common}{template}").into()),
473 });
474 create(&shader, "fit_surface")
475 });
476 Self { frames, fits, finalize: create(&frame_shader, "finalize"), layout }
477 }
478}
479
480#[cfg(all(test, not(target_arch = "wasm32")))]
481#[path = "mls_tests.rs"]
482mod tests;
483
484#[cfg(all(test, not(target_arch = "wasm32")))]
485#[path = "mls_soa_upload_reference.rs"]
486pub(crate) mod soa_upload_reference;
487
488#[cfg(all(test, not(target_arch = "wasm32")))]
489#[path = "mls_validation_reference.rs"]
490pub(crate) mod validation_reference;