1use bytemuck::{Pod, Zeroable};
2use spatialrust_core::{SpatialError, SpatialResult};
3use std::sync::OnceLock;
4use wgpu::util::DeviceExt;
5
6use crate::runtime::WgpuRuntime;
7
8const WORKGROUP_SIZE: u32 = 256;
9const POINT_PARALLEL_MIN: u32 = 1024;
10
11struct Plan {
12 point_count: u32,
13 hypothesis_count: u32,
14 groups: u32,
15 parallel: bool,
16 output_bytes: u64,
17}
18
19fn plan(points: usize, hypotheses: usize, limits: &wgpu::Limits) -> SpatialResult<Plan> {
20 let invalid = || {
21 SpatialError::InvalidArgument("RANSAC scoring requires non-empty u32-sized arrays and supported buffer/compute limits".to_owned())
22 };
23 let point_count = u32::try_from(points).map_err(|_| invalid())?;
24 let hypothesis_count = u32::try_from(hypotheses).map_err(|_| invalid())?;
25 let parallel = point_count >= POINT_PARALLEL_MIN;
26 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
27 let output_bytes = u64::from(hypothesis_count) * std::mem::size_of::<GpuPlaneScore>() as u64;
28 if points == 0
29 || hypotheses == 0
30 || u64::from(point_count) * 4 > bound
31 || u64::from(hypothesis_count) * 16 > bound
32 || output_bytes > bound
33 || limits.max_compute_invocations_per_workgroup < WORKGROUP_SIZE
34 || limits.max_compute_workgroup_size_x < WORKGROUP_SIZE
35 || limits.max_compute_workgroups_per_dimension == 0
36 || (parallel && limits.max_compute_workgroup_storage_size < 2048)
37 || limits.max_storage_buffers_per_shader_stage < 5
38 || limits.max_uniform_buffers_per_shader_stage == 0
39 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<RansacPlaneUniform>() as u32
40 {
41 return Err(invalid());
42 }
43 let groups =
44 if parallel { hypothesis_count } else { hypothesis_count.div_ceil(WORKGROUP_SIZE) }
45 .min(256)
46 .min(limits.max_compute_workgroups_per_dimension);
47 Ok(Plan { point_count, hypothesis_count, groups, parallel, output_bytes })
48}
49
50pub(crate) struct RansacPlanePipelines {
51 layout: wgpu::BindGroupLayout,
52 pipelines: [OnceLock<wgpu::ComputePipeline>; 2],
53}
54
55impl RansacPlanePipelines {
56 fn new(device: &wgpu::Device) -> Self {
57 let entries: [wgpu::BindGroupLayoutEntry; 6] =
58 std::array::from_fn(|binding| wgpu::BindGroupLayoutEntry {
59 binding: binding as u32,
60 visibility: wgpu::ShaderStages::COMPUTE,
61 ty: wgpu::BindingType::Buffer {
62 ty: if binding == 0 {
63 wgpu::BufferBindingType::Uniform
64 } else {
65 wgpu::BufferBindingType::Storage { read_only: binding != 5 }
66 },
67 has_dynamic_offset: false,
68 min_binding_size: None,
69 },
70 count: None,
71 });
72 Self {
73 layout: device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
74 label: Some("ransac-plane-layout"),
75 entries: &entries,
76 }),
77 pipelines: std::array::from_fn(|_| OnceLock::new()),
78 }
79 }
80
81 fn pipeline(&self, device: &wgpu::Device, parallel: bool) -> &wgpu::ComputePipeline {
82 self.pipelines[usize::from(parallel)].get_or_init(|| {
83 let source = if parallel {
84 include_str!("../shaders/ransac_plane_parallel.wgsl")
85 } else {
86 include_str!("../shaders/ransac_plane_serial.wgsl")
87 };
88 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
89 label: Some("ransac-plane-shader"),
90 source: wgpu::ShaderSource::Wgsl(source.into()),
91 });
92 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
93 label: Some("ransac-plane-pipeline-layout"),
94 bind_group_layouts: &[&self.layout],
95 push_constant_ranges: &[],
96 });
97 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
98 label: Some("ransac-plane-pipeline"),
99 layout: Some(&layout),
100 module: &module,
101 entry_point: Some("main"),
102 compilation_options: Default::default(),
103 cache: None,
104 })
105 })
106 }
107}
108
109#[repr(C)]
110#[derive(Clone, Copy, Debug, Pod, Zeroable)]
111struct RansacPlaneUniform {
112 point_count: u32,
113 hypothesis_count: u32,
114 distance_threshold: f32,
115 groups: u32,
116}
117
118#[repr(C)]
119#[derive(Clone, Copy, Debug, Pod, Zeroable)]
120struct RansacHypothesisPod {
121 i0: u32,
122 i1: u32,
123 i2: u32,
124 _pad: u32,
125}
126
127#[repr(C)]
129#[derive(Clone, Copy, Debug, Pod, Zeroable)]
130pub struct GpuPlaneScore {
131 pub inlier_count: u32,
133 pub normal: [f32; 3],
135 pub d: f32,
137}
138
139pub fn score_ransac_plane_hypotheses_gpu(
146 runtime: &WgpuRuntime,
147 x: &[f32],
148 y: &[f32],
149 z: &[f32],
150 hypotheses: &[[u32; 3]],
151 distance_threshold: f32,
152) -> SpatialResult<Vec<GpuPlaneScore>> {
153 if x.len() != y.len() || x.len() != z.len() {
154 return Err(SpatialError::InvalidArgument("xyz arrays must have equal length".to_owned()));
155 }
156 if hypotheses.is_empty() {
157 return Ok(Vec::new());
158 }
159
160 let plan = plan(x.len(), hypotheses.len(), &runtime.device().limits())?;
161 if hypotheses.iter().flatten().any(|&index| index >= plan.point_count) {
162 return Err(SpatialError::InvalidArgument(
163 "RANSAC hypothesis index exceeds point array".to_owned(),
164 ));
165 }
166 let device = runtime.device();
167 let queue = runtime.queue();
168 let pipelines =
169 runtime.ransac_plane_pipelines.get_or_init(|| RansacPlanePipelines::new(device));
170 let pipeline = pipelines.pipeline(device, plan.parallel);
171
172 let x_buffer = runtime.upload_f32_storage("ransac-plane-x", x)?;
173 let y_buffer = runtime.upload_f32_storage("ransac-plane-y", y)?;
174 let z_buffer = runtime.upload_f32_storage("ransac-plane-z", z)?;
175
176 let hypothesis_pods: Vec<RansacHypothesisPod> = hypotheses
177 .iter()
178 .map(|indices| RansacHypothesisPod {
179 i0: indices[0],
180 i1: indices[1],
181 i2: indices[2],
182 _pad: 0,
183 })
184 .collect();
185 let hypothesis_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
186 label: Some("ransac-plane-hypotheses"),
187 contents: bytemuck::cast_slice(&hypothesis_pods),
188 usage: wgpu::BufferUsages::STORAGE,
189 });
190
191 let output_len = plan.output_bytes;
192 let output_buffer = device.create_buffer(&wgpu::BufferDescriptor {
193 label: Some("ransac-plane-scores"),
194 size: output_len,
195 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
196 mapped_at_creation: false,
197 });
198
199 let uniform = RansacPlaneUniform {
200 point_count: plan.point_count,
201 hypothesis_count: plan.hypothesis_count,
202 distance_threshold,
203 groups: plan.groups,
204 };
205 let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
206 label: Some("ransac-plane-uniform"),
207 contents: bytemuck::bytes_of(&uniform),
208 usage: wgpu::BufferUsages::UNIFORM,
209 });
210
211 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
212 label: Some("ransac-plane-bind-group"),
213 layout: &pipelines.layout,
214 entries: &[
215 wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding() },
216 wgpu::BindGroupEntry { binding: 1, resource: x_buffer.as_entire_binding() },
217 wgpu::BindGroupEntry { binding: 2, resource: y_buffer.as_entire_binding() },
218 wgpu::BindGroupEntry { binding: 3, resource: z_buffer.as_entire_binding() },
219 wgpu::BindGroupEntry { binding: 4, resource: hypothesis_buffer.as_entire_binding() },
220 wgpu::BindGroupEntry { binding: 5, resource: output_buffer.as_entire_binding() },
221 ],
222 });
223
224 let staging = device.create_buffer(&wgpu::BufferDescriptor {
225 label: Some("ransac-plane-staging"),
226 size: output_len,
227 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
228 mapped_at_creation: false,
229 });
230 let mut encoder = device
231 .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("ransac-plane") });
232 {
233 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
234 label: Some("ransac-plane-pass"),
235 timestamp_writes: None,
236 });
237 pass.set_pipeline(pipeline);
238 pass.set_bind_group(0, &bind_group, &[]);
239 pass.dispatch_workgroups(plan.groups, 1, 1);
240 }
241 encoder.copy_buffer_to_buffer(&output_buffer, 0, &staging, 0, output_len);
242 queue.submit(Some(encoder.finish()));
243
244 let slice = staging.slice(..);
245 let (sender, receiver) = std::sync::mpsc::channel();
246 slice.map_async(wgpu::MapMode::Read, move |result| {
247 let _ = sender.send(result);
248 });
249 device.poll(wgpu::Maintain::Wait);
250 receiver
251 .recv()
252 .map_err(|_| SpatialError::InvalidArgument("failed to receive wgpu map result".to_owned()))?
253 .map_err(|error| {
254 SpatialError::InvalidArgument(format!("failed to map wgpu buffer: {error}"))
255 })?;
256
257 let data = slice.get_mapped_range();
258 let scores: Vec<GpuPlaneScore> = bytemuck::cast_slice(&data).to_vec();
259 drop(data);
260 staging.unmap();
261
262 drop(bind_group);
263 runtime.recycle_storage(std::mem::size_of_val(x) as u64, x_buffer);
264 runtime.recycle_storage(std::mem::size_of_val(y) as u64, y_buffer);
265 runtime.recycle_storage(std::mem::size_of_val(z) as u64, z_buffer);
266
267 Ok(scores)
268}
269
270#[cfg(all(test, not(target_arch = "wasm32")))]
271#[path = "ransac_plane_tests.rs"]
272mod regression;
273
274#[cfg(test)]
275mod tests {
276 use super::{score_ransac_plane_hypotheses_gpu, GpuPlaneScore};
277 use crate::runtime::WgpuRuntime;
278
279 #[test]
280 fn scores_planar_patch_hypothesis() {
281 let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
282 let mut x = Vec::new();
283 let mut y = Vec::new();
284 let mut z = Vec::new();
285 for i in 0..10 {
286 for j in 0..10 {
287 x.push(i as f32);
288 y.push(j as f32);
289 z.push(0.0);
290 }
291 }
292 let hypotheses = [[0u32, 1, 10], [5, 15, 50]];
293 let scores = score_ransac_plane_hypotheses_gpu(&runtime, &x, &y, &z, &hypotheses, 0.05)
294 .expect("gpu scores");
295 assert_eq!(scores.len(), 2);
296 assert!(scores.iter().all(|score: &GpuPlaneScore| score.inlier_count >= 90));
297 assert!(scores[0].normal[2].abs() > 0.9);
298 }
299}