Skip to main content

spatialrust_gpu/image/kernels/
gray.rs

1//! BT.601 RGB to gray on the GPU.
2
3use bytemuck::{Pod, Zeroable};
4use spatialrust_core::{SpatialError, SpatialResult};
5use spatialrust_image::{ColorSpace, ImageMetadata};
6use std::sync::OnceLock;
7use wgpu::util::DeviceExt;
8
9use crate::image::gpu_image::{create_texture, GpuImage, GpuImageReceipt};
10use crate::WgpuRuntime;
11
12const WORKGROUP: u32 = 256;
13
14#[repr(C)]
15#[derive(Clone, Copy, Pod, Zeroable)]
16struct GrayParams {
17    width: u32,
18    height: u32,
19    groups_per_row: u32,
20    group_count: u32,
21}
22
23#[derive(Clone, Copy, Debug)]
24struct GrayPlan {
25    groups_x: u32,
26    groups_y: u32,
27    group_count: u32,
28}
29
30fn gray_plan(width: u32, height: u32, limits: &wgpu::Limits) -> SpatialResult<GrayPlan> {
31    let invalid = || {
32        SpatialError::InvalidArgument(
33        "GPU gray requires positive dimensions, u32 pixel counts and supported texture/compute/binding limits".to_owned(),
34    )
35    };
36    let pixels = u64::from(width) * u64::from(height);
37    if width == 0
38        || height == 0
39        || width > limits.max_texture_dimension_2d
40        || height > limits.max_texture_dimension_2d
41        || width > i32::MAX as u32
42        || height > i32::MAX as u32
43        || pixels > u64::from(u32::MAX)
44        || limits.max_compute_invocations_per_workgroup < WORKGROUP
45        || limits.max_compute_workgroup_size_x < WORKGROUP
46        || limits.max_compute_workgroup_size_y == 0
47        || limits.max_compute_workgroup_size_z == 0
48        || limits.max_compute_workgroups_per_dimension == 0
49        || limits.max_sampled_textures_per_shader_stage == 0
50        || limits.max_storage_textures_per_shader_stage == 0
51        || limits.max_uniform_buffers_per_shader_stage == 0
52        || limits.max_uniform_buffer_binding_size < std::mem::size_of::<GrayParams>() as u32
53        || limits.max_buffer_size < std::mem::size_of::<GrayParams>() as u64
54        || limits.max_bind_groups == 0
55        || limits.max_bindings_per_bind_group < 3
56    {
57        return Err(invalid());
58    }
59    let group_count = pixels.div_ceil(u64::from(WORKGROUP)) as u32;
60    let groups_y = group_count.div_ceil(limits.max_compute_workgroups_per_dimension);
61    if groups_y > limits.max_compute_workgroups_per_dimension {
62        return Err(invalid());
63    }
64    let groups_x = group_count.div_ceil(groups_y);
65    Ok(GrayPlan { groups_x, groups_y, group_count })
66}
67
68const GRAY_WGSL: &str = r#"
69struct Params { width: u32, height: u32, pad0: u32, pad1: u32, };
70
71@group(0) @binding(0) var<uniform> params: Params;
72@group(0) @binding(1) var input_px: texture_2d<u32>;
73@group(0) @binding(2) var output_px: texture_storage_2d<rgba8uint, write>;
74
75@compute @workgroup_size(256)
76fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
77    let index = gid.x;
78    let pixel_count = params.width * params.height;
79    if (index >= pixel_count) {
80        return;
81    }
82    let xy = vec2<i32>(i32(index % params.width), i32(index / params.width));
83    let rgb = textureLoad(input_px, xy, 0).rgb;
84    // Match CPU BT.601 fixed-point: (77*R + 150*G + 29*B + 128) >> 8
85    let gray = (77u * rgb.r + 150u * rgb.g + 29u * rgb.b + 128u) >> 8u;
86    textureStore(output_px, xy, vec4<u32>(gray, 0u, 0u, 0u));
87}
88"#;
89
90pub(crate) struct GrayPipeline {
91    bind_group_layout: wgpu::BindGroupLayout,
92    pipeline: OnceLock<wgpu::ComputePipeline>,
93    grid_pipeline: OnceLock<wgpu::ComputePipeline>,
94}
95
96pub(crate) fn create_gray_pipeline(device: &wgpu::Device) -> GrayPipeline {
97    let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
98        label: Some("gpu-image-gray-bgl"),
99        entries: &[
100            wgpu::BindGroupLayoutEntry {
101                binding: 0,
102                visibility: wgpu::ShaderStages::COMPUTE,
103                ty: wgpu::BindingType::Buffer {
104                    ty: wgpu::BufferBindingType::Uniform,
105                    has_dynamic_offset: false,
106                    min_binding_size: None,
107                },
108                count: None,
109            },
110            wgpu::BindGroupLayoutEntry {
111                binding: 1,
112                visibility: wgpu::ShaderStages::COMPUTE,
113                ty: wgpu::BindingType::Texture {
114                    sample_type: wgpu::TextureSampleType::Uint,
115                    view_dimension: wgpu::TextureViewDimension::D2,
116                    multisampled: false,
117                },
118                count: None,
119            },
120            wgpu::BindGroupLayoutEntry {
121                binding: 2,
122                visibility: wgpu::ShaderStages::COMPUTE,
123                ty: wgpu::BindingType::StorageTexture {
124                    access: wgpu::StorageTextureAccess::WriteOnly,
125                    format: wgpu::TextureFormat::Rgba8Uint,
126                    view_dimension: wgpu::TextureViewDimension::D2,
127                },
128                count: None,
129            },
130        ],
131    });
132    GrayPipeline { bind_group_layout, pipeline: OnceLock::new(), grid_pipeline: OnceLock::new() }
133}
134
135fn create_pipeline(
136    device: &wgpu::Device,
137    bind_group_layout: &wgpu::BindGroupLayout,
138    source: &str,
139) -> wgpu::ComputePipeline {
140    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
141        label: Some("gpu-image-gray-shader"),
142        source: wgpu::ShaderSource::Wgsl(source.into()),
143    });
144    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
145        label: Some("gpu-image-gray-pl"),
146        bind_group_layouts: &[bind_group_layout],
147        push_constant_ranges: &[],
148    });
149    device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
150        label: Some("gpu-image-gray-pipeline"),
151        layout: Some(&pipeline_layout),
152        module: &shader,
153        entry_point: Some("main"),
154        compilation_options: wgpu::PipelineCompilationOptions::default(),
155        cache: None,
156    })
157}
158
159/// Converts an RGB `GpuImage` to a gray `GpuImage` using BT.601 fixed-point luma.
160///
161/// Large images distribute flat workgroups across bounded dispatch rows. Runtime,
162/// dimensions and device limits are checked before allocation or pipeline setup.
163pub fn rgb_to_gray_gpu(runtime: &WgpuRuntime, source: &GpuImage) -> SpatialResult<GpuImage> {
164    rgb_to_gray_gpu_with_profiler(runtime, source, None)
165}
166
167pub(crate) fn rgb_to_gray_gpu_with_profiler(
168    runtime: &WgpuRuntime,
169    source: &GpuImage,
170    profiler: Option<&mut crate::GpuStageProfiler>,
171) -> SpatialResult<GpuImage> {
172    source.validate_runtime(runtime)?;
173    if source.channels() != 3 {
174        return Err(SpatialError::InvalidArgument(
175            "rgb_to_gray_gpu requires a 3-channel RGB GpuImage".to_owned(),
176        ));
177    }
178    let plan = gray_plan(source.width(), source.height(), &runtime.device().limits())?;
179    if let Some(profiler) = &profiler {
180        profiler.validate(runtime, 1)?;
181    }
182    let cache = runtime.image_gray_pipeline.get_or_init(|| create_gray_pipeline(runtime.device()));
183    let pipeline = if plan.groups_y == 1 {
184        cache
185            .pipeline
186            .get_or_init(|| create_pipeline(runtime.device(), &cache.bind_group_layout, GRAY_WGSL))
187    } else {
188        cache.grid_pipeline.get_or_init(|| {
189            create_pipeline(
190                runtime.device(),
191                &cache.bind_group_layout,
192                include_str!("gray_grid.wgsl"),
193            )
194        })
195    };
196    gray_dispatch(runtime, source, plan, cache, pipeline, profiler)
197}
198
199fn gray_dispatch(
200    runtime: &WgpuRuntime,
201    source: &GpuImage,
202    plan: GrayPlan,
203    cache: &GrayPipeline,
204    pipeline: &wgpu::ComputePipeline,
205    mut profiler: Option<&mut crate::GpuStageProfiler>,
206) -> SpatialResult<GpuImage> {
207    let output = create_texture(runtime, source.width(), source.height(), "gpu-image-gray-out");
208    let out_bytes = u64::from(source.width()) * u64::from(source.height()) * 4;
209    let params = GrayParams {
210        width: source.width(),
211        height: source.height(),
212        groups_per_row: plan.groups_x,
213        group_count: plan.group_count,
214    };
215    let uniform = runtime.device().create_buffer_init(&wgpu::util::BufferInitDescriptor {
216        label: Some("gpu-image-gray-params"),
217        contents: bytemuck::bytes_of(&params),
218        usage: wgpu::BufferUsages::UNIFORM,
219    });
220    let source_view = source.view();
221    let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
222    let bind_group = runtime.device().create_bind_group(&wgpu::BindGroupDescriptor {
223        label: Some("gpu-image-gray-bg"),
224        layout: &cache.bind_group_layout,
225        entries: &[
226            wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() },
227            wgpu::BindGroupEntry {
228                binding: 1,
229                resource: wgpu::BindingResource::TextureView(&source_view),
230            },
231            wgpu::BindGroupEntry {
232                binding: 2,
233                resource: wgpu::BindingResource::TextureView(&output_view),
234            },
235        ],
236    });
237    let mut encoder = runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
238        label: Some("gpu-image-gray-encoder"),
239    });
240    {
241        let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
242            label: Some("gpu-image-gray-pass"),
243            timestamp_writes: crate::profiling::timestamp_writes(&mut profiler, "rgb_to_gray_gpu"),
244        });
245        pass.set_pipeline(pipeline);
246        pass.set_bind_group(0, &bind_group, &[]);
247        pass.dispatch_workgroups(plan.groups_x, plan.groups_y, 1);
248    }
249    runtime.queue().submit(Some(encoder.finish()));
250    let mut receipt = GpuImageReceipt::default();
251    receipt.merge_from(source.receipt());
252    receipt.record_gpu_to_gpu(out_bytes, "rgb_to_gray_gpu");
253    let metadata = ImageMetadata { color_space: ColorSpace::Gray, ..source.metadata() };
254    GpuImage::from_parts(runtime, source.width(), source.height(), 1, output, metadata, receipt)
255}
256
257#[cfg(all(test, not(target_arch = "wasm32")))]
258#[path = "gray_tests.rs"]
259mod tests;