wgpu_hal/noop/
mod.rs

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