wgpu_core/command/
clear.rs

1use alloc::{sync::Arc, vec::Vec};
2use core::ops::Range;
3
4use crate::{
5    api_log,
6    command::{encoder::EncodingState, ArcCommand, EncoderStateError},
7    device::{DeviceError, MissingFeatures},
8    get_lowest_common_denom,
9    global::Global,
10    hal_label,
11    id::{BufferId, CommandEncoderId, TextureId},
12    init_tracker::{MemoryInitKind, TextureInitRange},
13    resource::{
14        Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError,
15        ParentDevice, RawResourceAccess, ResourceErrorIdent, Texture, TextureClearMode,
16    },
17    snatch::SnatchGuard,
18    track::TextureTrackerSetSingle,
19};
20
21use thiserror::Error;
22use wgt::{
23    error::{ErrorType, WebGpuError},
24    math::align_to,
25    BufferAddress, BufferUsages, ImageSubresourceRange, TextureAspect, TextureSelector,
26};
27
28/// Error encountered while attempting a clear.
29#[derive(Clone, Debug, Error)]
30#[non_exhaustive]
31pub enum ClearError {
32    #[error(transparent)]
33    DestroyedResource(#[from] DestroyedResourceError),
34    #[error(transparent)]
35    MissingFeatures(#[from] MissingFeatures),
36    #[error("{0} can not be cleared")]
37    NoValidTextureClearMode(ResourceErrorIdent),
38    #[error("Buffer clear size {0:?} is not a multiple of `COPY_BUFFER_ALIGNMENT`")]
39    UnalignedFillSize(BufferAddress),
40    #[error("Buffer offset {0:?} is not a multiple of `COPY_BUFFER_ALIGNMENT`")]
41    UnalignedBufferOffset(BufferAddress),
42    #[error("Clear starts at offset {start_offset} with size of {requested_size}, but these added together exceed `u64::MAX`")]
43    OffsetPlusSizeExceeds64BitBounds {
44        start_offset: BufferAddress,
45        requested_size: BufferAddress,
46    },
47    #[error("Clear of {start_offset}..{end_offset} would end up overrunning the bounds of the buffer of size {buffer_size}")]
48    BufferOverrun {
49        start_offset: BufferAddress,
50        end_offset: BufferAddress,
51        buffer_size: BufferAddress,
52    },
53    #[error(transparent)]
54    MissingBufferUsage(#[from] MissingBufferUsageError),
55    #[error("Texture lacks the aspects that were specified in the image subresource range. Texture with format {texture_format:?}, specified was {subresource_range_aspects:?}")]
56    MissingTextureAspect {
57        texture_format: wgt::TextureFormat,
58        subresource_range_aspects: TextureAspect,
59    },
60    #[error("Image subresource level range is outside of the texture's level range. texture range is {texture_level_range:?},  \
61whereas subesource range specified start {subresource_base_mip_level} and count {subresource_mip_level_count:?}")]
62    InvalidTextureLevelRange {
63        texture_level_range: Range<u32>,
64        subresource_base_mip_level: u32,
65        subresource_mip_level_count: Option<u32>,
66    },
67    #[error("Image subresource layer range is outside of the texture's layer range. texture range is {texture_layer_range:?},  \
68whereas subesource range specified start {subresource_base_array_layer} and count {subresource_array_layer_count:?}")]
69    InvalidTextureLayerRange {
70        texture_layer_range: Range<u32>,
71        subresource_base_array_layer: u32,
72        subresource_array_layer_count: Option<u32>,
73    },
74    #[error(transparent)]
75    Device(#[from] DeviceError),
76    #[error(transparent)]
77    EncoderState(#[from] EncoderStateError),
78    #[error(transparent)]
79    InvalidResource(#[from] InvalidResourceError),
80}
81
82impl WebGpuError for ClearError {
83    fn webgpu_error_type(&self) -> ErrorType {
84        let e: &dyn WebGpuError = match self {
85            Self::DestroyedResource(e) => e,
86            Self::MissingFeatures(e) => e,
87            Self::MissingBufferUsage(e) => e,
88            Self::Device(e) => e,
89            Self::EncoderState(e) => e,
90            Self::InvalidResource(e) => e,
91            Self::NoValidTextureClearMode(..)
92            | Self::UnalignedFillSize(..)
93            | Self::UnalignedBufferOffset(..)
94            | Self::OffsetPlusSizeExceeds64BitBounds { .. }
95            | Self::BufferOverrun { .. }
96            | Self::MissingTextureAspect { .. }
97            | Self::InvalidTextureLevelRange { .. }
98            | Self::InvalidTextureLayerRange { .. } => return ErrorType::Validation,
99        };
100        e.webgpu_error_type()
101    }
102}
103
104impl Global {
105    pub fn command_encoder_clear_buffer(
106        &self,
107        command_encoder_id: CommandEncoderId,
108        dst: BufferId,
109        offset: BufferAddress,
110        size: Option<BufferAddress>,
111    ) -> Result<(), EncoderStateError> {
112        profiling::scope!("CommandEncoder::clear_buffer");
113        api_log!("CommandEncoder::clear_buffer {dst:?}");
114
115        let hub = &self.hub;
116
117        let cmd_enc = hub.command_encoders.get(command_encoder_id);
118        let mut cmd_buf_data = cmd_enc.data.lock();
119
120        cmd_buf_data.push_with(|| -> Result<_, ClearError> {
121            Ok(ArcCommand::ClearBuffer {
122                dst: self.resolve_buffer_id(dst)?,
123                offset,
124                size,
125            })
126        })
127    }
128
129    pub fn command_encoder_clear_texture(
130        &self,
131        command_encoder_id: CommandEncoderId,
132        dst: TextureId,
133        subresource_range: &ImageSubresourceRange,
134    ) -> Result<(), EncoderStateError> {
135        profiling::scope!("CommandEncoder::clear_texture");
136        api_log!("CommandEncoder::clear_texture {dst:?}");
137
138        let hub = &self.hub;
139
140        let cmd_enc = hub.command_encoders.get(command_encoder_id);
141        let mut cmd_buf_data = cmd_enc.data.lock();
142
143        cmd_buf_data.push_with(|| -> Result<_, ClearError> {
144            Ok(ArcCommand::ClearTexture {
145                dst: self.resolve_texture_id(dst)?,
146                subresource_range: *subresource_range,
147            })
148        })
149    }
150}
151
152pub(super) fn clear_buffer(
153    state: &mut EncodingState,
154    dst_buffer: Arc<Buffer>,
155    offset: BufferAddress,
156    size: Option<BufferAddress>,
157) -> Result<(), ClearError> {
158    dst_buffer.same_device(state.device)?;
159
160    let dst_pending = state
161        .tracker
162        .buffers
163        .set_single(&dst_buffer, wgt::BufferUses::COPY_DST);
164
165    let dst_raw = dst_buffer.try_raw(state.snatch_guard)?;
166    dst_buffer.check_usage(BufferUsages::COPY_DST)?;
167
168    // Check if offset & size are valid.
169    if offset % wgt::COPY_BUFFER_ALIGNMENT != 0 {
170        return Err(ClearError::UnalignedBufferOffset(offset));
171    }
172
173    let size = size.unwrap_or(dst_buffer.size.saturating_sub(offset));
174    if size % wgt::COPY_BUFFER_ALIGNMENT != 0 {
175        return Err(ClearError::UnalignedFillSize(size));
176    }
177    let end_offset =
178        offset
179            .checked_add(size)
180            .ok_or(ClearError::OffsetPlusSizeExceeds64BitBounds {
181                start_offset: offset,
182                requested_size: size,
183            })?;
184    if end_offset > dst_buffer.size {
185        return Err(ClearError::BufferOverrun {
186            start_offset: offset,
187            end_offset,
188            buffer_size: dst_buffer.size,
189        });
190    }
191
192    if offset == end_offset {
193        log::trace!("Ignoring fill_buffer of size 0");
194        return Ok(());
195    }
196
197    // Mark dest as initialized.
198    state
199        .buffer_memory_init_actions
200        .extend(dst_buffer.initialization_status.read().create_action(
201            &dst_buffer,
202            offset..end_offset,
203            MemoryInitKind::ImplicitlyInitialized,
204        ));
205
206    // actual hal barrier & operation
207    let dst_barrier = dst_pending.map(|pending| pending.into_hal(&dst_buffer, state.snatch_guard));
208    unsafe {
209        state.raw_encoder.transition_buffers(dst_barrier.as_slice());
210        state.raw_encoder.clear_buffer(dst_raw, offset..end_offset);
211    }
212
213    Ok(())
214}
215
216/// Validate and encode a "Clear Texture" command.
217///
218/// This function implements `CommandEncoder::clear_texture` when invoked via
219/// the command encoder APIs or trace playback. It has the suffix `_cmd` to
220/// distinguish it from [`clear_texture`]. [`clear_texture`], used internally by
221/// this function, is a lower-level function that encodes a texture clear
222/// operation without validating it.
223pub(super) fn clear_texture_cmd(
224    state: &mut EncodingState,
225    dst_texture: Arc<Texture>,
226    subresource_range: &ImageSubresourceRange,
227) -> Result<(), ClearError> {
228    dst_texture.same_device(state.device)?;
229    state
230        .device
231        .require_features(wgt::Features::CLEAR_TEXTURE)?;
232
233    // Check if subresource aspects are valid.
234    let clear_aspects = hal::FormatAspects::new(dst_texture.desc.format, subresource_range.aspect);
235    if clear_aspects.is_empty() {
236        return Err(ClearError::MissingTextureAspect {
237            texture_format: dst_texture.desc.format,
238            subresource_range_aspects: subresource_range.aspect,
239        });
240    };
241
242    // Check if subresource level range is valid
243    let subresource_mip_range = subresource_range.mip_range(dst_texture.full_range.mips.end);
244    if dst_texture.full_range.mips.start > subresource_mip_range.start
245        || dst_texture.full_range.mips.end < subresource_mip_range.end
246    {
247        return Err(ClearError::InvalidTextureLevelRange {
248            texture_level_range: dst_texture.full_range.mips.clone(),
249            subresource_base_mip_level: subresource_range.base_mip_level,
250            subresource_mip_level_count: subresource_range.mip_level_count,
251        });
252    }
253    // Check if subresource layer range is valid
254    let subresource_layer_range = subresource_range.layer_range(dst_texture.full_range.layers.end);
255    if dst_texture.full_range.layers.start > subresource_layer_range.start
256        || dst_texture.full_range.layers.end < subresource_layer_range.end
257    {
258        return Err(ClearError::InvalidTextureLayerRange {
259            texture_layer_range: dst_texture.full_range.layers.clone(),
260            subresource_base_array_layer: subresource_range.base_array_layer,
261            subresource_array_layer_count: subresource_range.array_layer_count,
262        });
263    }
264
265    clear_texture(
266        &dst_texture,
267        TextureInitRange {
268            mip_range: subresource_mip_range,
269            layer_range: subresource_layer_range,
270        },
271        state.raw_encoder,
272        &mut state.tracker.textures,
273        &state.device.alignments,
274        state.device.zero_buffer.as_ref(),
275        state.snatch_guard,
276        state.device.instance_flags,
277    )?;
278
279    Ok(())
280}
281
282/// Encode a texture clear operation.
283///
284/// This function encodes a texture clear operation without validating it.
285/// Texture clears requested via the API call this function via
286/// [`clear_texture_cmd`], which does the validation. This function is also
287/// called directly from various places within wgpu that need to clear a
288/// texture.
289pub(crate) fn clear_texture<T: TextureTrackerSetSingle>(
290    dst_texture: &Arc<Texture>,
291    range: TextureInitRange,
292    encoder: &mut dyn hal::DynCommandEncoder,
293    texture_tracker: &mut T,
294    alignments: &hal::Alignments,
295    zero_buffer: &dyn hal::DynBuffer,
296    snatch_guard: &SnatchGuard<'_>,
297    instance_flags: wgt::InstanceFlags,
298) -> Result<(), ClearError> {
299    let dst_raw = dst_texture.try_raw(snatch_guard)?;
300
301    // Issue the right barrier.
302    let clear_usage = match *dst_texture.clear_mode.read() {
303        TextureClearMode::BufferCopy => wgt::TextureUses::COPY_DST,
304        TextureClearMode::RenderPass {
305            is_color: false, ..
306        } => wgt::TextureUses::DEPTH_STENCIL_WRITE,
307        TextureClearMode::Surface { .. } | TextureClearMode::RenderPass { is_color: true, .. } => {
308            wgt::TextureUses::COLOR_TARGET
309        }
310        TextureClearMode::None => {
311            return Err(ClearError::NoValidTextureClearMode(
312                dst_texture.error_ident(),
313            ));
314        }
315    };
316
317    let selector = TextureSelector {
318        mips: range.mip_range.clone(),
319        layers: range.layer_range.clone(),
320    };
321
322    // If we're in a texture-init usecase, we know that the texture is already
323    // tracked since whatever caused the init requirement, will have caused the
324    // usage tracker to be aware of the texture. Meaning, that it is safe to
325    // call call change_replace_tracked if the life_guard is already gone (i.e.
326    // the user no longer holds on to this texture).
327    //
328    // On the other hand, when coming via command_encoder_clear_texture, the
329    // life_guard is still there since in order to call it a texture object is
330    // needed.
331    //
332    // We could in theory distinguish these two scenarios in the internal
333    // clear_texture api in order to remove this check and call the cheaper
334    // change_replace_tracked whenever possible.
335    let dst_barrier = texture_tracker
336        .set_single(dst_texture, selector, clear_usage)
337        .map(|pending| pending.into_hal(dst_raw))
338        .collect::<Vec<_>>();
339    unsafe {
340        encoder.transition_textures(&dst_barrier);
341    }
342
343    // Record actual clearing
344    let clear_mode = dst_texture.clear_mode.read();
345    match *clear_mode {
346        TextureClearMode::BufferCopy => clear_texture_via_buffer_copies(
347            &dst_texture.desc,
348            alignments,
349            zero_buffer,
350            range,
351            encoder,
352            dst_raw,
353        ),
354        TextureClearMode::Surface { .. } => {
355            drop(clear_mode);
356            clear_texture_via_render_passes(dst_texture, range, true, encoder, instance_flags)?
357        }
358        TextureClearMode::RenderPass { is_color, .. } => {
359            drop(clear_mode);
360            clear_texture_via_render_passes(dst_texture, range, is_color, encoder, instance_flags)?
361        }
362        TextureClearMode::None => {
363            return Err(ClearError::NoValidTextureClearMode(
364                dst_texture.error_ident(),
365            ));
366        }
367    }
368    Ok(())
369}
370
371fn clear_texture_via_buffer_copies(
372    texture_desc: &wgt::TextureDescriptor<(), Vec<wgt::TextureFormat>>,
373    alignments: &hal::Alignments,
374    zero_buffer: &dyn hal::DynBuffer, // Buffer of size device::ZERO_BUFFER_SIZE
375    range: TextureInitRange,
376    encoder: &mut dyn hal::DynCommandEncoder,
377    dst_raw: &dyn hal::DynTexture,
378) {
379    assert!(!texture_desc.format.is_depth_stencil_format());
380
381    if texture_desc.format == wgt::TextureFormat::NV12
382        || texture_desc.format == wgt::TextureFormat::P010
383    {
384        // TODO: Currently COPY_DST for NV12 and P010 textures is unsupported.
385        return;
386    }
387
388    // Gather list of zero_buffer copies and issue a single command then to perform them
389    let mut zero_buffer_copy_regions = Vec::new();
390    let buffer_copy_pitch = alignments.buffer_copy_pitch.get() as u32;
391    let (block_width, block_height) = texture_desc.format.block_dimensions();
392    let block_size = texture_desc.format.block_copy_size(None).unwrap();
393
394    let bytes_per_row_alignment = get_lowest_common_denom(buffer_copy_pitch, block_size);
395
396    for mip_level in range.mip_range {
397        let mut mip_size = texture_desc.mip_level_size(mip_level).unwrap();
398        // Round to multiple of block size
399        mip_size.width = align_to(mip_size.width, block_width);
400        mip_size.height = align_to(mip_size.height, block_height);
401
402        let bytes_per_row = align_to(
403            mip_size.width / block_width * block_size,
404            bytes_per_row_alignment,
405        );
406
407        let max_rows_per_copy = crate::device::ZERO_BUFFER_SIZE as u32 / bytes_per_row;
408        // round down to a multiple of rows needed by the texture format
409        let max_rows_per_copy = max_rows_per_copy / block_height * block_height;
410        assert!(
411            max_rows_per_copy > 0,
412            "Zero buffer size is too small to fill a single row \
413            of a texture with format {:?} and desc {:?}",
414            texture_desc.format,
415            texture_desc.size
416        );
417
418        let z_range = 0..(if texture_desc.dimension == wgt::TextureDimension::D3 {
419            mip_size.depth_or_array_layers
420        } else {
421            1
422        });
423
424        for array_layer in range.layer_range.clone() {
425            // TODO: Only doing one layer at a time for volume textures right now.
426            for z in z_range.clone() {
427                // May need multiple copies for each subresource! However, we
428                // assume that we never need to split a row.
429                let mut num_rows_left = mip_size.height;
430                while num_rows_left > 0 {
431                    let num_rows = num_rows_left.min(max_rows_per_copy);
432
433                    zero_buffer_copy_regions.push(hal::BufferTextureCopy {
434                        buffer_layout: wgt::TexelCopyBufferLayout {
435                            offset: 0,
436                            bytes_per_row: Some(bytes_per_row),
437                            rows_per_image: None,
438                        },
439                        texture_base: hal::TextureCopyBase {
440                            mip_level,
441                            array_layer,
442                            origin: wgt::Origin3d {
443                                x: 0, // Always full rows
444                                y: mip_size.height - num_rows_left,
445                                z,
446                            },
447                            aspect: hal::FormatAspects::COLOR,
448                        },
449                        size: hal::CopyExtent {
450                            width: mip_size.width, // full row
451                            height: num_rows,
452                            depth: 1, // Only single slice of volume texture at a time right now
453                        },
454                    });
455
456                    num_rows_left -= num_rows;
457                }
458            }
459        }
460    }
461
462    unsafe {
463        encoder.copy_buffer_to_texture(zero_buffer, dst_raw, &zero_buffer_copy_regions);
464    }
465}
466
467fn clear_texture_via_render_passes(
468    dst_texture: &Texture,
469    range: TextureInitRange,
470    is_color: bool,
471    encoder: &mut dyn hal::DynCommandEncoder,
472    instance_flags: wgt::InstanceFlags,
473) -> Result<(), ClearError> {
474    assert_eq!(dst_texture.desc.dimension, wgt::TextureDimension::D2);
475
476    let extent_base = wgt::Extent3d {
477        width: dst_texture.desc.size.width,
478        height: dst_texture.desc.size.height,
479        depth_or_array_layers: 1, // Only one layer is cleared at a time.
480    };
481
482    let clear_mode = dst_texture.clear_mode.read();
483
484    for mip_level in range.mip_range {
485        let extent = extent_base.mip_level_size(mip_level, dst_texture.desc.dimension);
486        for depth_or_layer in range.layer_range.clone() {
487            let color_attachments_tmp;
488            let (color_attachments, depth_stencil_attachment) = if is_color {
489                color_attachments_tmp = [Some(hal::ColorAttachment {
490                    target: hal::Attachment {
491                        view: Texture::get_clear_view(
492                            &clear_mode,
493                            &dst_texture.desc,
494                            mip_level,
495                            depth_or_layer,
496                        ),
497                        usage: wgt::TextureUses::COLOR_TARGET,
498                    },
499                    depth_slice: None,
500                    resolve_target: None,
501                    ops: hal::AttachmentOps::STORE,
502                    clear_value: wgt::Color::TRANSPARENT,
503                })];
504                (&color_attachments_tmp[..], None)
505            } else {
506                (
507                    &[][..],
508                    Some(hal::DepthStencilAttachment {
509                        target: hal::Attachment {
510                            view: Texture::get_clear_view(
511                                &clear_mode,
512                                &dst_texture.desc,
513                                mip_level,
514                                depth_or_layer,
515                            ),
516                            usage: wgt::TextureUses::DEPTH_STENCIL_WRITE,
517                        },
518                        depth_ops: hal::AttachmentOps::STORE,
519                        stencil_ops: hal::AttachmentOps::STORE,
520                        clear_value: (0.0, 0),
521                    }),
522                )
523            };
524            unsafe {
525                encoder
526                    .begin_render_pass(&hal::RenderPassDescriptor {
527                        label: hal_label(
528                            Some("(wgpu internal) clear_texture clear pass"),
529                            instance_flags,
530                        ),
531                        extent,
532                        sample_count: dst_texture.desc.sample_count,
533                        color_attachments,
534                        depth_stencil_attachment,
535                        multiview_mask: None,
536                        timestamp_writes: None,
537                        occlusion_query_set: None,
538                    })
539                    .map_err(|e| dst_texture.device.handle_hal_error(e))?;
540                encoder.end_render_pass();
541            }
542        }
543    }
544
545    Ok(())
546}