1use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use std::sync::OnceLock;
6use wgpu::util::DeviceExt;
7
8use super::{gpu_image::create_texture, GpuImage};
9use crate::{scratch::ScratchBuffers, GpuStageProfiler, WgpuRuntime};
10
11#[path = "clahe_split.rs"]
12mod split;
13
14const GEOMETRY_SHADER: &str = concat!(
15 include_str!("rounding_u32.wgsl"),
16 include_str!("binary64_positive.wgsl"),
17 include_str!("clahe_params.wgsl"),
18 include_str!("clahe_geometry.wgsl")
19);
20const LOOKUP_SHADER: &str = concat!(
21 include_str!("rounding_u32.wgsl"),
22 include_str!("clahe_params.wgsl"),
23 include_str!("clahe_clip_scan.wgsl"),
24 include_str!("clahe_lookup.wgsl")
25);
26const APPLY_SHADER: &str = concat!(
27 include_str!("rounding_u32.wgsl"),
28 include_str!("binary64_positive.wgsl"),
29 include_str!("clahe_params.wgsl"),
30 include_str!("clahe_apply.wgsl")
31);
32
33#[repr(C)]
34#[derive(Clone, Copy, Pod, Zeroable)]
35struct Params {
36 width: u32,
37 height: u32,
38 tile_width: u32,
39 tile_height: u32,
40 tiles_x: u32,
41 tiles_y: u32,
42 clip_count: u32,
43 tile_count: u32,
44 tile_groups: u32,
45 geometry_groups: u32,
46 groups_x: u32,
47 groups_y: u32,
48}
49
50struct Plan {
51 params: Params,
52 geometry_bytes: u64,
53 lookup_bytes: u64,
54 split: Option<split::Plan>,
55}
56
57fn plan(
58 width: u32,
59 height: u32,
60 clip_limit: f64,
61 tiles_x: u32,
62 tiles_y: u32,
63 limits: &wgpu::Limits,
64) -> SpatialResult<Plan> {
65 let invalid = || {
66 error("GPU CLAHE requires positive supported dimensions/grid, finite non-negative clip limit, bounded u32 tile counts and supported compute/buffer limits")
67 };
68 if width == 0
69 || height == 0
70 || tiles_x == 0
71 || tiles_y == 0
72 || !clip_limit.is_finite()
73 || clip_limit < 0.0
74 || width > limits.max_texture_dimension_2d
75 || height > limits.max_texture_dimension_2d
76 || width > i32::MAX as u32
77 || height > i32::MAX as u32
78 || limits.max_compute_invocations_per_workgroup < 256
79 || limits.max_compute_workgroup_size_x < 256
80 || limits.max_compute_workgroup_size_y < 16
81 || limits.max_compute_workgroup_storage_size < 4096
82 || limits.max_compute_workgroups_per_dimension == 0
83 || limits.max_storage_buffers_per_shader_stage < 2
84 || limits.max_sampled_textures_per_shader_stage == 0
85 || limits.max_storage_textures_per_shader_stage == 0
86 || limits.max_uniform_buffers_per_shader_stage == 0
87 || limits.max_uniform_buffer_binding_size < std::mem::size_of::<Params>() as u32
88 {
89 return Err(invalid());
90 }
91 let tile_width = width.div_ceil(tiles_x);
92 let tile_height = height.div_ceil(tiles_y);
93 let area = u64::from(tile_width) * u64::from(tile_height);
94 let tile_count = u64::from(tiles_x) * u64::from(tiles_y);
95 let geometry_count = u64::from(width) + u64::from(height);
96 let geometry_bytes = geometry_count * 16;
97 let lookup_bytes = tile_count.checked_mul(1024).ok_or_else(invalid)?;
98 let bound = limits.max_buffer_size.min(u64::from(limits.max_storage_buffer_binding_size));
99 if area > u64::from(u32::MAX)
100 || tile_count > u64::from(u32::MAX)
101 || geometry_count > u64::from(u32::MAX)
102 || u64::from(tiles_x) * u64::from(tile_width) > u64::from(u32::MAX)
103 || u64::from(tiles_y) * u64::from(tile_height) > u64::from(u32::MAX)
104 || geometry_bytes > bound
105 || lookup_bytes > bound
106 {
107 return Err(invalid());
108 }
109 let clip_count = if clip_limit > 0.0 {
112 (clip_limit * area as f64 / 256.0).max(1.0).min(area as f64) as u32
113 } else {
114 0
115 };
116 let groups = |count: u32, lanes: u32, cap: u32| {
117 count.div_ceil(lanes).min(cap).min(limits.max_compute_workgroups_per_dimension)
118 };
119 let params = Params {
120 width,
121 height,
122 tile_width,
123 tile_height,
124 tiles_x,
125 tiles_y,
126 clip_count,
127 tile_count: tile_count as u32,
128 tile_groups: groups(tile_count as u32, 1, 256),
129 geometry_groups: groups(geometry_count as u32, 256, 256),
130 groups_x: groups(width, 16, 64),
131 groups_y: groups(height, 16, 64),
132 };
133 Ok(Plan { split: split::plan(¶ms, limits), params, geometry_bytes, lookup_bytes })
134}
135
136pub(crate) struct ClahePipelines {
137 layouts: [wgpu::BindGroupLayout; 3],
138 pipelines: [wgpu::ComputePipeline; 3],
139 split: OnceLock<split::Pipelines>,
140}
141
142impl ClahePipelines {
143 fn new(device: &wgpu::Device) -> Self {
144 let buffer = |binding, ty| wgpu::BindGroupLayoutEntry {
145 binding,
146 visibility: wgpu::ShaderStages::COMPUTE,
147 ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None },
148 count: None,
149 };
150 let texture = wgpu::BindGroupLayoutEntry {
151 binding: 1,
152 visibility: wgpu::ShaderStages::COMPUTE,
153 ty: wgpu::BindingType::Texture {
154 sample_type: wgpu::TextureSampleType::Uint,
155 view_dimension: wgpu::TextureViewDimension::D2,
156 multisampled: false,
157 },
158 count: None,
159 };
160 let uniform = buffer(0, wgpu::BufferBindingType::Uniform);
161 let writable = wgpu::BufferBindingType::Storage { read_only: false };
162 let readonly = wgpu::BufferBindingType::Storage { read_only: true };
163 let layout = |entries| {
164 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
165 label: Some("gpu-clahe-layout"),
166 entries,
167 })
168 };
169 let layouts = [
170 layout(&[uniform, buffer(1, writable)]),
171 layout(&[uniform, texture, buffer(2, writable)]),
172 layout(&[
173 uniform,
174 texture,
175 buffer(2, readonly),
176 buffer(3, readonly),
177 wgpu::BindGroupLayoutEntry {
178 binding: 4,
179 visibility: wgpu::ShaderStages::COMPUTE,
180 ty: wgpu::BindingType::StorageTexture {
181 access: wgpu::StorageTextureAccess::WriteOnly,
182 format: wgpu::TextureFormat::Rgba8Uint,
183 view_dimension: wgpu::TextureViewDimension::D2,
184 },
185 count: None,
186 },
187 ]),
188 ];
189 let pipelines = std::array::from_fn(|i| {
190 let (source, entry) = [
191 (GEOMETRY_SHADER, "clahe_geometry"),
192 (LOOKUP_SHADER, "clahe_lookup"),
193 (APPLY_SHADER, "clahe_apply"),
194 ][i];
195 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
196 label: Some(entry),
197 source: wgpu::ShaderSource::Wgsl(source.into()),
198 });
199 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
200 label: Some(entry),
201 bind_group_layouts: &[&layouts[i]],
202 push_constant_ranges: &[],
203 });
204 device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
205 label: Some(entry),
206 layout: Some(&layout),
207 module: &shader,
208 entry_point: Some(entry),
209 compilation_options: wgpu::PipelineCompilationOptions::default(),
210 cache: None,
211 })
212 });
213 Self { layouts, pipelines, split: OnceLock::new() }
214 }
215}
216
217pub fn clahe_gpu(
228 runtime: &WgpuRuntime,
229 source: &GpuImage,
230 clip_limit: f64,
231 tiles_x: u32,
232 tiles_y: u32,
233) -> SpatialResult<GpuImage> {
234 clahe_with_profiler(runtime, source, clip_limit, tiles_x, tiles_y, None)
235}
236
237pub fn clahe_gpu_profiled(
241 runtime: &WgpuRuntime,
242 source: &GpuImage,
243 clip_limit: f64,
244 tiles_x: u32,
245 tiles_y: u32,
246 profiler: &mut GpuStageProfiler,
247) -> SpatialResult<GpuImage> {
248 let stages = plan(
249 source.width(),
250 source.height(),
251 clip_limit,
252 tiles_x,
253 tiles_y,
254 &runtime.device().limits(),
255 )
256 .map_or(3, |p| if p.split.is_some() { 4 } else { 3 });
257 profiler.validate(runtime, stages)?;
258 let result = clahe_with_profiler(runtime, source, clip_limit, tiles_x, tiles_y, Some(profiler));
259 profiler.finish_recording(&result);
260 result
261}
262
263fn clahe_with_profiler(
264 runtime: &WgpuRuntime,
265 source: &GpuImage,
266 clip_limit: f64,
267 tiles_x: u32,
268 tiles_y: u32,
269 profiler: Option<&mut GpuStageProfiler>,
270) -> SpatialResult<GpuImage> {
271 source.validate_runtime(runtime)?;
272 if source.channels() != 1 {
273 return Err(error("GPU CLAHE requires one logical channel"));
274 }
275 let plan = plan(
276 source.width(),
277 source.height(),
278 clip_limit,
279 tiles_x,
280 tiles_y,
281 &runtime.device().limits(),
282 )?;
283 let pipelines =
284 runtime.image_clahe_pipelines.get_or_init(|| ClahePipelines::new(runtime.device()));
285 execute_clahe(runtime, source, &plan, pipelines, &pipelines.pipelines[1], profiler)
286}
287
288fn execute_clahe(
289 runtime: &WgpuRuntime,
290 source: &GpuImage,
291 plan: &Plan,
292 pipelines: &ClahePipelines,
293 direct_lookup: &wgpu::ComputePipeline,
294 mut profiler: Option<&mut GpuStageProfiler>,
295) -> SpatialResult<GpuImage> {
296 let mut scratch = ScratchBuffers::new(runtime);
297 let geometry = scratch.acquire("gpu-clahe-geometry", plan.geometry_bytes);
298 let lookup = scratch.acquire("gpu-clahe-lookups", plan.lookup_bytes);
299 let partials = plan
300 .split
301 .as_ref()
302 .map(|p| scratch.acquire("gpu-clahe-partial-histograms", p.partial_bytes));
303 let output = create_texture(runtime, source.width(), source.height(), "gpu-clahe-output");
304 let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
305 label: Some("gpu-clahe-params"),
306 contents: bytemuck::bytes_of(&plan.params),
307 usage: wgpu::BufferUsages::UNIFORM,
308 });
309 let split_uniform = plan.split.as_ref().map(|p| {
310 runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
311 label: Some("gpu-clahe-split-params"),
312 contents: bytemuck::bytes_of(&p.params),
313 usage: wgpu::BufferUsages::UNIFORM,
314 })
315 });
316 let source_view = source.view();
317 let output_view = output.create_view(&Default::default());
318 fn entry(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
319 wgpu::BindGroupEntry { binding, resource: buffer.as_entire_binding() }
320 }
321 let entries = [
322 vec![entry(0, &uniform), entry(1, &geometry)],
323 vec![
324 entry(0, &uniform),
325 wgpu::BindGroupEntry {
326 binding: 1,
327 resource: wgpu::BindingResource::TextureView(&source_view),
328 },
329 entry(2, &lookup),
330 ],
331 vec![
332 entry(0, &uniform),
333 wgpu::BindGroupEntry {
334 binding: 1,
335 resource: wgpu::BindingResource::TextureView(&source_view),
336 },
337 entry(2, &geometry),
338 entry(3, &lookup),
339 wgpu::BindGroupEntry {
340 binding: 4,
341 resource: wgpu::BindingResource::TextureView(&output_view),
342 },
343 ],
344 ];
345 let [geometry_entries, direct_entries, apply_entries] = entries;
346 let mut passes = vec![(
347 "clahe_geometry_gpu",
348 &pipelines.layouts[0],
349 &pipelines.pipelines[0],
350 geometry_entries,
351 plan.params.geometry_groups,
352 1,
353 )];
354 if let Some(p) = &plan.split {
355 let split_pipelines =
356 pipelines.split.get_or_init(|| split::Pipelines::new(runtime.device()));
357 let split_uniform = split_uniform.as_ref().unwrap();
358 let partials = partials.as_ref().unwrap();
359 passes.push((
360 "clahe_histogram_gpu",
361 &split_pipelines.layouts[0],
362 &split_pipelines.pipelines[0],
363 vec![
364 entry(0, split_uniform),
365 wgpu::BindGroupEntry {
366 binding: 1,
367 resource: wgpu::BindingResource::TextureView(&source_view),
368 },
369 entry(2, partials),
370 ],
371 p.params.partial_groups,
372 1,
373 ));
374 passes.push((
375 "clahe_lookup_gpu",
376 &split_pipelines.layouts[1],
377 &split_pipelines.pipelines[1],
378 vec![entry(0, split_uniform), entry(1, partials), entry(2, &lookup)],
379 p.params.tile_groups,
380 1,
381 ));
382 } else {
383 passes.push((
384 "clahe_lookup_gpu",
385 &pipelines.layouts[1],
386 direct_lookup,
387 direct_entries,
388 plan.params.tile_groups,
389 1,
390 ));
391 }
392 passes.push((
393 "clahe_apply_gpu",
394 &pipelines.layouts[2],
395 &pipelines.pipelines[2],
396 apply_entries,
397 plan.params.groups_x,
398 plan.params.groups_y,
399 ));
400 let mut encoder = runtime.device().create_command_encoder(&Default::default());
401 for (stage, layout, pipeline, entries, x, y) in passes {
402 let group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
403 label: Some(stage),
404 layout,
405 entries: &entries,
406 });
407 let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
408 label: Some(stage),
409 timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, stage),
410 });
411 pass.set_pipeline(pipeline);
412 pass.set_bind_group(0, &group, &[]);
413 pass.dispatch_workgroups(x, y, 1);
414 }
415 scratch.submit_and_recycle(encoder);
416 let mut receipt = source.receipt().clone();
417 receipt.record_gpu_to_gpu(plan.geometry_bytes, "clahe_geometry_gpu");
418 if let Some(p) = &plan.split {
419 receipt.record_gpu_to_gpu(p.partial_bytes, "clahe_histogram_gpu");
420 }
421 receipt.record_gpu_to_gpu(plan.lookup_bytes, "clahe_lookup_gpu");
422 receipt.record_gpu_to_gpu(source.storage_bytes(), "clahe_apply_gpu");
423 GpuImage::from_parts(
424 runtime,
425 source.width(),
426 source.height(),
427 1,
428 output,
429 source.metadata(),
430 receipt,
431 )
432}
433
434fn error(message: &str) -> SpatialError {
435 SpatialError::InvalidArgument(message.to_owned())
436}
437
438#[cfg(all(test, not(target_arch = "wasm32")))]
439#[path = "clahe_tests.rs"]
440mod tests;
441
442#[cfg(all(test, not(target_arch = "wasm32")))]
443#[path = "clahe_lookup_tests.rs"]
444mod lookup_tests;