Skip to main content

wgpu_hal/noop/
mod.rs

1#![allow(unused_variables)]
2
3use alloc::{string::String, sync::Arc, vec, vec::Vec};
4use core::{ptr, sync::atomic::Ordering, time::Duration};
5
6use wgpu_sync::atomic::AtomicU64;
7
8use crate::TlasInstance;
9
10mod buffer;
11pub use buffer::Buffer;
12mod command;
13pub use command::CommandBuffer;
14
15#[derive(Clone, Debug)]
16pub struct Api;
17
18#[derive(Debug)]
19pub struct Context {
20    options: Arc<wgt::NoopBackendOptions>,
21}
22#[derive(Debug)]
23pub struct Encoder;
24#[derive(Debug)]
25pub struct Resource;
26
27#[derive(Debug)]
28pub struct Fence {
29    value: AtomicU64,
30}
31
32type DeviceResult<T> = Result<T, crate::DeviceError>;
33
34impl crate::Api for Api {
35    const VARIANT: wgt::Backend = wgt::Backend::Noop;
36
37    type Instance = Context;
38    type Surface = Context;
39    type Adapter = Context;
40    type Device = Context;
41
42    type Queue = Context;
43    type CommandEncoder = CommandBuffer;
44    type CommandBuffer = CommandBuffer;
45
46    type Buffer = Buffer;
47    type Texture = Resource;
48    type SurfaceTexture = Resource;
49    type TextureView = Resource;
50    type Sampler = Resource;
51    type QuerySet = Resource;
52    type Fence = Fence;
53    type AccelerationStructure = Resource;
54    type PipelineCache = Resource;
55
56    type BindGroupLayout = Resource;
57    type BindGroup = Resource;
58    type PipelineLayout = Resource;
59    type ShaderModule = Resource;
60    type RenderPipeline = Resource;
61    type RayTracingPipeline = Resource;
62    type ComputePipeline = Resource;
63}
64
65crate::impl_dyn_resource!(Buffer, CommandBuffer, Context, Fence, Resource);
66
67impl crate::DynAccelerationStructure for Resource {}
68impl crate::DynBindGroup for Resource {}
69impl crate::DynBindGroupLayout for Resource {}
70impl crate::DynBuffer for Buffer {}
71impl crate::DynCommandBuffer for CommandBuffer {}
72impl crate::DynComputePipeline for Resource {}
73impl crate::DynFence for Fence {}
74impl crate::DynPipelineCache for Resource {}
75impl crate::DynPipelineLayout for Resource {}
76impl crate::DynQuerySet for Resource {}
77impl crate::DynRenderPipeline for Resource {}
78impl crate::DynRayTracingPipeline for Resource {}
79impl crate::DynSampler for Resource {}
80impl crate::DynShaderModule for Resource {}
81impl crate::DynSurfaceTexture for Resource {}
82impl crate::DynTexture for Resource {}
83impl crate::DynTextureView for Resource {}
84
85impl core::borrow::Borrow<dyn crate::DynTexture> for Resource {
86    fn borrow(&self) -> &dyn crate::DynTexture {
87        self
88    }
89}
90
91impl crate::Instance for Context {
92    type A = Api;
93
94    unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
95        let options = Arc::new(desc.backend_options.noop.clone());
96        if options.enable {
97            Ok(Context { options })
98        } else {
99            Err(crate::InstanceError::new(String::from(
100                "noop backend disabled because NoopBackendOptions::enable is false",
101            )))
102        }
103    }
104    unsafe fn create_surface(
105        &self,
106        _display_handle: raw_window_handle::RawDisplayHandle,
107        _window_handle: raw_window_handle::RawWindowHandle,
108    ) -> Result<Context, crate::InstanceError> {
109        Ok(Context {
110            options: Arc::clone(&self.options),
111        })
112    }
113    unsafe fn enumerate_adapters(
114        &self,
115        _surface_hint: Option<&Context>,
116    ) -> Vec<crate::ExposedAdapter<Api>> {
117        let device_type = self.options.device_type.unwrap_or(wgt::DeviceType::Other);
118        let subgroup_min_size = self
119            .options
120            .subgroup_min_size
121            .unwrap_or(wgt::MINIMUM_SUBGROUP_MIN_SIZE);
122        let subgroup_max_size = self
123            .options
124            .subgroup_max_size
125            .unwrap_or(wgt::MAXIMUM_SUBGROUP_MAX_SIZE);
126        let features = self.options.features.unwrap_or(wgt::Features::all());
127        let limits = self
128            .options
129            .limits
130            .clone()
131            .unwrap_or(CAPABILITIES.limits.clone());
132
133        let info = wgt::AdapterInfo {
134            subgroup_min_size,
135            subgroup_max_size,
136            ..adapter_info()
137        };
138
139        let capabilities = crate::Capabilities {
140            limits,
141            ..CAPABILITIES
142        };
143
144        vec![crate::ExposedAdapter {
145            adapter: Context {
146                options: Arc::clone(&self.options),
147            },
148            info,
149            features,
150            capabilities,
151        }]
152    }
153}
154
155/// Returns the adapter info for the noop backend.
156///
157/// This is used in the test harness to construct info about
158/// the noop backend adapter without actually initializing wgpu.
159pub fn adapter_info() -> wgt::AdapterInfo {
160    wgt::AdapterInfo {
161        name: String::from("noop wgpu backend"),
162        driver: String::from("wgpu"),
163        ..wgt::AdapterInfo::new(wgt::DeviceType::Cpu, wgt::Backend::Noop)
164    }
165}
166
167/// The capabilities of the noop backend.
168///
169/// This is used in the test harness to construct capabilities
170/// of the noop backend without actually initializing wgpu.
171pub const CAPABILITIES: crate::Capabilities = {
172    crate::Capabilities {
173        limits: wgt::Limits::unlimited(),
174        alignments: crate::Alignments {
175            // All maximally permissive
176            buffer_copy_offset: wgt::BufferSize::MIN,
177            buffer_copy_pitch: wgt::BufferSize::MIN,
178            uniform_bounds_check_alignment: wgt::BufferSize::MIN,
179            raw_tlas_instance_size: 0,
180            ray_tracing_scratch_buffer_alignment: 1,
181            ray_tracing_pipeline_group_data_size: 1,
182            ray_tracing_pipeline_group_data_alignment: 1,
183            ray_tracing_pipeline_data_offset_alignment: 1,
184        },
185        downlevel: wgt::DownlevelCapabilities {
186            flags: wgt::DownlevelFlags::all(),
187            limits: wgt::DownlevelLimits {},
188            shader_model: wgt::ShaderModel::Sm5,
189        },
190        cooperative_matrix_properties: Vec::new(),
191        ray_tracing_invocation_reorder_mode: wgt::RayTracingInvocationReorderMode::None,
192    }
193};
194
195impl crate::Surface for Context {
196    type A = Api;
197
198    unsafe fn configure(
199        &self,
200        device: &Context,
201        config: &crate::SurfaceConfiguration,
202    ) -> Result<(), crate::SurfaceError> {
203        Ok(())
204    }
205
206    unsafe fn unconfigure(&self, device: &Context) {}
207
208    unsafe fn acquire_texture(
209        &self,
210        _timeout: Option<Duration>,
211        _fence: &Fence,
212    ) -> Result<crate::AcquiredSurfaceTexture<Api>, crate::SurfaceError> {
213        Err(crate::SurfaceError::Timeout)
214    }
215    unsafe fn discard_texture(&self, texture: Resource) {}
216}
217
218impl crate::Adapter for Context {
219    type A = Api;
220
221    unsafe fn open(
222        &self,
223        features: wgt::Features,
224        _limits: &wgt::Limits,
225        _memory_hints: &wgt::MemoryHints,
226    ) -> DeviceResult<crate::OpenDevice<Api>> {
227        Ok(crate::OpenDevice {
228            device: Context {
229                options: Arc::clone(&self.options),
230            },
231            queue: Context {
232                options: Arc::clone(&self.options),
233            },
234        })
235    }
236    unsafe fn texture_format_capabilities(
237        &self,
238        format: wgt::TextureFormat,
239    ) -> crate::TextureFormatCapabilities {
240        crate::TextureFormatCapabilities::empty()
241    }
242
243    unsafe fn surface_capabilities(&self, surface: &Context) -> Option<crate::SurfaceCapabilities> {
244        None
245    }
246
247    unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
248        wgt::PresentationTimestamp::INVALID_TIMESTAMP
249    }
250
251    fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
252        wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE
253    }
254
255    fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
256        wgt::TextureUses::INCLUSIVE
257            | wgt::TextureUses::COLOR_TARGET
258            | wgt::TextureUses::DEPTH_WRITE
259            | wgt::TextureUses::STENCIL_WRITE
260    }
261}
262
263impl crate::Queue for Context {
264    type A = Api;
265
266    unsafe fn submit(
267        &self,
268        command_buffers: &[&CommandBuffer],
269        surface_textures: &[&Resource],
270        (fence, fence_value): (&Fence, crate::FenceValue),
271    ) -> DeviceResult<()> {
272        // All commands are executed synchronously.
273        for cb in command_buffers {
274            // SAFETY: Caller is responsible for ensuring synchronization between commands and
275            // other mutations.
276            unsafe {
277                cb.execute();
278            }
279        }
280        fence.value.store(fence_value, Ordering::Release);
281        Ok(())
282    }
283    unsafe fn present(
284        &self,
285        surface: &Context,
286        texture: Resource,
287        _damage_rects: &[wgt::Rect<u32>],
288    ) -> Result<(), crate::SurfaceError> {
289        Ok(())
290    }
291
292    unsafe fn get_timestamp_period(&self) -> f32 {
293        1.0
294    }
295
296    unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> {
297        Ok(())
298    }
299}
300
301impl crate::Device for Context {
302    type A = Api;
303
304    unsafe fn create_buffer(
305        &self,
306        desc: &crate::BufferDescriptor,
307    ) -> DeviceResult<(Buffer, wgt::BufferAddress)> {
308        Buffer::new(desc)
309    }
310
311    unsafe fn destroy_buffer(&self, buffer: Buffer) {}
312    unsafe fn add_raw_buffer(&self, _buffer: &Buffer) {}
313
314    unsafe fn map_buffer(
315        &self,
316        buffer: &Buffer,
317        range: crate::MemoryRange,
318    ) -> DeviceResult<crate::BufferMapping> {
319        // Safety: the `wgpu-core` validation layer will prevent any user-accessible aliasing
320        // mappings from being created, so we don’t need to perform any checks here, except for
321        // bounds checks on the range which are built into `get_slice_ptr()`.
322        Ok(crate::BufferMapping {
323            ptr: ptr::NonNull::new(buffer.get_slice_ptr(range).cast::<u8>()).unwrap(),
324            is_coherent: true,
325        })
326    }
327    unsafe fn unmap_buffer(&self, buffer: &Buffer) {}
328    unsafe fn flush_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {}
329    unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {}
330
331    unsafe fn create_texture(&self, desc: &crate::TextureDescriptor) -> DeviceResult<Resource> {
332        Ok(Resource)
333    }
334    unsafe fn destroy_texture(&self, texture: Resource) {}
335    unsafe fn add_raw_texture(&self, _texture: &Resource) {}
336
337    unsafe fn create_texture_view(
338        &self,
339        texture: &Resource,
340        desc: &crate::TextureViewDescriptor,
341    ) -> DeviceResult<Resource> {
342        Ok(Resource)
343    }
344    unsafe fn destroy_texture_view(&self, view: Resource) {}
345    unsafe fn create_sampler(&self, desc: &crate::SamplerDescriptor) -> DeviceResult<Resource> {
346        Ok(Resource)
347    }
348    unsafe fn destroy_sampler(&self, sampler: Resource) {}
349
350    unsafe fn create_command_encoder(
351        &self,
352        desc: &crate::CommandEncoderDescriptor<Context>,
353    ) -> DeviceResult<CommandBuffer> {
354        Ok(CommandBuffer::new())
355    }
356
357    unsafe fn create_bind_group_layout(
358        &self,
359        desc: &crate::BindGroupLayoutDescriptor,
360    ) -> DeviceResult<Resource> {
361        Ok(Resource)
362    }
363    unsafe fn destroy_bind_group_layout(&self, bg_layout: Resource) {}
364    unsafe fn create_pipeline_layout(
365        &self,
366        desc: &crate::PipelineLayoutDescriptor<Resource>,
367    ) -> DeviceResult<Resource> {
368        Ok(Resource)
369    }
370    unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Resource) {}
371    unsafe fn create_bind_group(
372        &self,
373        desc: &crate::BindGroupDescriptor<Resource, Buffer, Resource, Resource, Resource>,
374    ) -> DeviceResult<Resource> {
375        Ok(Resource)
376    }
377    unsafe fn destroy_bind_group(&self, group: Resource) {}
378
379    unsafe fn create_shader_module(
380        &self,
381        desc: &crate::ShaderModuleDescriptor,
382        shader: crate::ShaderInput,
383    ) -> Result<Resource, crate::ShaderError> {
384        Ok(Resource)
385    }
386    unsafe fn destroy_shader_module(&self, module: Resource) {}
387    unsafe fn create_render_pipeline(
388        &self,
389        desc: &crate::RenderPipelineDescriptor<Resource, Resource, Resource>,
390    ) -> Result<Resource, crate::PipelineError> {
391        Ok(Resource)
392    }
393    unsafe fn destroy_render_pipeline(&self, pipeline: Resource) {}
394    unsafe fn create_compute_pipeline(
395        &self,
396        desc: &crate::ComputePipelineDescriptor<Resource, Resource, Resource>,
397    ) -> Result<Resource, crate::PipelineError> {
398        Ok(Resource)
399    }
400    unsafe fn destroy_compute_pipeline(&self, pipeline: Resource) {}
401    unsafe fn create_ray_tracing_pipeline(
402        &self,
403        desc: &crate::RayTracingPipelineDescriptor<Resource, Resource, Resource>,
404    ) -> Result<Resource, crate::PipelineError> {
405        Ok(Resource)
406    }
407    unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Resource) {}
408    unsafe fn get_raytracing_pipeline_group_data(
409        &self,
410        pipeline: &Resource,
411        groups: core::ops::Range<u32>,
412    ) -> Result<Vec<u8>, crate::DeviceError> {
413        Ok(vec![0; groups.count()])
414    }
415    unsafe fn create_pipeline_cache(
416        &self,
417        desc: &crate::PipelineCacheDescriptor<'_>,
418    ) -> Result<Resource, crate::PipelineCacheError> {
419        Ok(Resource)
420    }
421    unsafe fn destroy_pipeline_cache(&self, cache: Resource) {}
422
423    unsafe fn create_query_set(
424        &self,
425        desc: &wgt::QuerySetDescriptor<crate::Label>,
426    ) -> DeviceResult<Resource> {
427        Ok(Resource)
428    }
429    unsafe fn destroy_query_set(&self, set: Resource) {}
430    unsafe fn create_fence(&self) -> DeviceResult<Fence> {
431        Ok(Fence {
432            value: AtomicU64::new(0),
433        })
434    }
435    unsafe fn destroy_fence(&self, fence: Fence) {}
436    unsafe fn get_fence_value(&self, fence: &Fence) -> DeviceResult<crate::FenceValue> {
437        Ok(fence.value.load(Ordering::Acquire))
438    }
439    unsafe fn wait(
440        &self,
441        fence: &Fence,
442        value: crate::FenceValue,
443        timeout: Option<Duration>,
444    ) -> DeviceResult<bool> {
445        // The relevant commands must have already been submitted, and noop-backend commands are
446        // executed synchronously, so there is no waiting — either it is already done,
447        // or this method was called incorrectly.
448        assert!(
449            fence.value.load(Ordering::Acquire) >= value,
450            "submission must have already been done"
451        );
452        Ok(true)
453    }
454
455    unsafe fn start_graphics_debugger_capture(&self) -> bool {
456        false
457    }
458    unsafe fn stop_graphics_debugger_capture(&self) {}
459    unsafe fn create_acceleration_structure(
460        &self,
461        desc: &crate::AccelerationStructureDescriptor,
462    ) -> DeviceResult<Resource> {
463        Ok(Resource)
464    }
465    unsafe fn get_acceleration_structure_build_sizes<'a>(
466        &self,
467        _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, Buffer>,
468    ) -> crate::AccelerationStructureBuildSizes {
469        Default::default()
470    }
471    unsafe fn get_acceleration_structure_device_address(
472        &self,
473        _acceleration_structure: &Resource,
474    ) -> wgt::BufferAddress {
475        Default::default()
476    }
477    unsafe fn destroy_acceleration_structure(&self, _acceleration_structure: Resource) {}
478
479    fn tlas_instance_to_bytes(&self, instance: TlasInstance, to_extend: &mut Vec<u8>) {}
480
481    fn get_internal_counters(&self) -> wgt::HalCounters {
482        Default::default()
483    }
484
485    fn check_if_oom(&self) -> DeviceResult<()> {
486        Ok(())
487    }
488}