wgpu_core/command/
clear.rs

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