1use alloc::{format, string::String, sync::Arc, vec::Vec};
2
3use arrayvec::ArrayVec;
4use thiserror::Error;
5use wgt::{
6 error::{ErrorType, WebGpuError},
7 BufferAddress, BufferTextureCopyInfoError, BufferUsages, Extent3d, TextureSelector,
8 TextureUsages,
9};
10
11use crate::{
12 api_log,
13 command::{
14 clear_texture, encoder::EncodingState, ArcCommand, CommandEncoderError, EncoderStateError,
15 },
16 device::MissingDownlevelFlags,
17 global::Global,
18 id::{BufferId, CommandEncoderId, TextureId},
19 init_tracker::{
20 has_copy_partial_init_tracker_coverage, MemoryInitKind, TextureInitRange,
21 TextureInitTrackerAction,
22 },
23 resource::{
24 Buffer, MissingBufferUsageError, MissingTextureUsageError, ParentDevice, RawResourceAccess,
25 Texture, TextureErrorDimension,
26 },
27};
28
29use super::ClearError;
30
31type TexelCopyBufferInfo = wgt::TexelCopyBufferInfo<BufferId>;
32type TexelCopyTextureInfo = wgt::TexelCopyTextureInfo<Arc<Texture>>;
33
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum CopySide {
36 Source,
37 Destination,
38}
39
40#[derive(Clone, Debug, Error)]
42#[non_exhaustive]
43pub enum TransferError {
44 #[error("Source and destination cannot be the same buffer")]
45 SameSourceDestinationBuffer,
46 #[error(transparent)]
47 MissingBufferUsage(#[from] MissingBufferUsageError),
48 #[error(transparent)]
49 MissingTextureUsage(#[from] MissingTextureUsageError),
50 #[error(
51 "Copy at offset {start_offset} bytes would end up overrunning the bounds of the {side:?} buffer of size {buffer_size}"
52 )]
53 BufferStartOffsetOverrun {
54 start_offset: BufferAddress,
55 buffer_size: BufferAddress,
56 side: CopySide,
57 },
58 #[error(
59 "Copy at offset {start_offset} for {size} bytes would end up overrunning the bounds of the {side:?} buffer of size {buffer_size}"
60 )]
61 BufferEndOffsetOverrun {
62 start_offset: BufferAddress,
63 size: BufferAddress,
64 buffer_size: BufferAddress,
65 side: CopySide,
66 },
67 #[error("Copy of {dimension:?} {start_offset}..{end_offset} would end up overrunning the bounds of the {side:?} texture of {dimension:?} size {texture_size}")]
68 TextureOverrun {
69 start_offset: u32,
70 end_offset: u32,
71 texture_size: u32,
72 dimension: TextureErrorDimension,
73 side: CopySide,
74 },
75 #[error("Partial copy of {start_offset}..{end_offset} on {dimension:?} dimension with size {texture_size} \
76 is not supported for the {side:?} texture format {format:?} with {sample_count} samples")]
77 UnsupportedPartialTransfer {
78 format: wgt::TextureFormat,
79 sample_count: u32,
80 start_offset: u32,
81 end_offset: u32,
82 texture_size: u32,
83 dimension: TextureErrorDimension,
84 side: CopySide,
85 },
86 #[error(
87 "Copying{} layers {}..{} to{} layers {}..{} of the same texture is not allowed",
88 if *src_aspects == wgt::TextureAspect::All { String::new() } else { format!(" {src_aspects:?}") },
89 src_origin_z,
90 src_origin_z + array_layer_count,
91 if *dst_aspects == wgt::TextureAspect::All { String::new() } else { format!(" {dst_aspects:?}") },
92 dst_origin_z,
93 dst_origin_z + array_layer_count,
94 )]
95 InvalidCopyWithinSameTexture {
96 src_aspects: wgt::TextureAspect,
97 dst_aspects: wgt::TextureAspect,
98 src_origin_z: u32,
99 dst_origin_z: u32,
100 array_layer_count: u32,
101 },
102 #[error("Unable to select texture aspect {aspect:?} from format {format:?}")]
103 InvalidTextureAspect {
104 format: wgt::TextureFormat,
105 aspect: wgt::TextureAspect,
106 },
107 #[error("Unable to select texture mip level {level} out of {total}")]
108 InvalidTextureMipLevel { level: u32, total: u32 },
109 #[error("Texture dimension must be 2D when copying from an external texture")]
110 InvalidDimensionExternal,
111 #[error("Buffer offset {0} is not aligned to block size or `COPY_BUFFER_ALIGNMENT`")]
112 UnalignedBufferOffset(BufferAddress),
113 #[error("Copy size {0} does not respect `COPY_BUFFER_ALIGNMENT`")]
114 UnalignedCopySize(BufferAddress),
115 #[error("Copy width is not a multiple of block width")]
116 UnalignedCopyWidth,
117 #[error("Copy height is not a multiple of block height")]
118 UnalignedCopyHeight,
119 #[error("Copy origin's x component is not a multiple of block width")]
120 UnalignedCopyOriginX,
121 #[error("Copy origin's y component is not a multiple of block height")]
122 UnalignedCopyOriginY,
123 #[error("Bytes per row does not respect `COPY_BYTES_PER_ROW_ALIGNMENT`")]
124 UnalignedBytesPerRow,
125 #[error("Number of bytes per row needs to be specified since more than one row is copied")]
126 UnspecifiedBytesPerRow,
127 #[error("Number of rows per image needs to be specified since more than one image is copied")]
128 UnspecifiedRowsPerImage,
129 #[error("Number of bytes per row is less than the number of bytes in a complete row")]
130 InvalidBytesPerRow,
131 #[error("Number of rows per image is invalid")]
132 InvalidRowsPerImage,
133 #[error("Overflow while computing the size of the copy")]
134 SizeOverflow,
135 #[error("Copy source aspects must refer to all aspects of the source texture format")]
136 CopySrcMissingAspects,
137 #[error(
138 "Copy destination aspects must refer to all aspects of the destination texture format"
139 )]
140 CopyDstMissingAspects,
141 #[error("Copy aspect must refer to a single aspect of texture format")]
142 CopyAspectNotOne,
143 #[error("Copying from textures with format {0:?} is forbidden")]
144 CopyFromForbiddenTextureFormat(wgt::TextureFormat),
145 #[error("Copying from textures with format {format:?} and aspect {aspect:?} is forbidden")]
146 CopyFromForbiddenTextureFormatAspect {
147 format: wgt::TextureFormat,
148 aspect: wgt::TextureAspect,
149 },
150 #[error("Copying to textures with format {0:?} is forbidden")]
151 CopyToForbiddenTextureFormat(wgt::TextureFormat),
152 #[error("Copying to textures with format {format:?} and aspect {aspect:?} is forbidden")]
153 CopyToForbiddenTextureFormatAspect {
154 format: wgt::TextureFormat,
155 aspect: wgt::TextureAspect,
156 },
157 #[error(
158 "Copying to textures with format {0:?} is forbidden when copying from external texture"
159 )]
160 ExternalCopyToForbiddenTextureFormat(wgt::TextureFormat),
161 #[error(
162 "Source format ({src_format:?}) and destination format ({dst_format:?}) are not copy-compatible (they may only differ in srgb-ness)"
163 )]
164 TextureFormatsNotCopyCompatible {
165 src_format: wgt::TextureFormat,
166 dst_format: wgt::TextureFormat,
167 },
168 #[error(transparent)]
169 MemoryInitFailure(#[from] ClearError),
170 #[error("Cannot encode this copy because of a missing downelevel flag")]
171 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
172 #[error("Source texture sample count must be 1, got {sample_count}")]
173 InvalidSampleCount { sample_count: u32 },
174 #[error(
175 "Source sample count ({src_sample_count:?}) and destination sample count ({dst_sample_count:?}) are not equal"
176 )]
177 SampleCountNotEqual {
178 src_sample_count: u32,
179 dst_sample_count: u32,
180 },
181 #[error("Requested mip level {requested} does not exist (count: {count})")]
182 InvalidMipLevel { requested: u32, count: u32 },
183 #[error("Buffer is expected to be unmapped, but was not")]
184 BufferNotAvailable,
185}
186
187impl WebGpuError for TransferError {
188 fn webgpu_error_type(&self) -> ErrorType {
189 match self {
190 Self::MissingBufferUsage(e) => e.webgpu_error_type(),
191 Self::MissingTextureUsage(e) => e.webgpu_error_type(),
192 Self::MemoryInitFailure(e) => e.webgpu_error_type(),
193
194 Self::BufferEndOffsetOverrun { .. }
195 | Self::TextureOverrun { .. }
196 | Self::BufferStartOffsetOverrun { .. }
197 | Self::UnsupportedPartialTransfer { .. }
198 | Self::InvalidCopyWithinSameTexture { .. }
199 | Self::InvalidTextureAspect { .. }
200 | Self::InvalidTextureMipLevel { .. }
201 | Self::InvalidDimensionExternal
202 | Self::UnalignedBufferOffset(..)
203 | Self::UnalignedCopySize(..)
204 | Self::UnalignedCopyWidth
205 | Self::UnalignedCopyHeight
206 | Self::UnalignedCopyOriginX
207 | Self::UnalignedCopyOriginY
208 | Self::UnalignedBytesPerRow
209 | Self::UnspecifiedBytesPerRow
210 | Self::UnspecifiedRowsPerImage
211 | Self::InvalidBytesPerRow
212 | Self::InvalidRowsPerImage
213 | Self::SizeOverflow
214 | Self::CopySrcMissingAspects
215 | Self::CopyDstMissingAspects
216 | Self::CopyAspectNotOne
217 | Self::CopyFromForbiddenTextureFormat(..)
218 | Self::CopyFromForbiddenTextureFormatAspect { .. }
219 | Self::CopyToForbiddenTextureFormat(..)
220 | Self::CopyToForbiddenTextureFormatAspect { .. }
221 | Self::ExternalCopyToForbiddenTextureFormat(..)
222 | Self::TextureFormatsNotCopyCompatible { .. }
223 | Self::MissingDownlevelFlags(..)
224 | Self::InvalidSampleCount { .. }
225 | Self::SampleCountNotEqual { .. }
226 | Self::InvalidMipLevel { .. }
227 | Self::SameSourceDestinationBuffer
228 | Self::BufferNotAvailable => ErrorType::Validation,
229 }
230 }
231}
232
233impl From<BufferTextureCopyInfoError> for TransferError {
234 fn from(value: BufferTextureCopyInfoError) -> Self {
235 match value {
236 BufferTextureCopyInfoError::InvalidBytesPerRow => Self::InvalidBytesPerRow,
237 BufferTextureCopyInfoError::InvalidRowsPerImage => Self::InvalidRowsPerImage,
238 BufferTextureCopyInfoError::ImageStrideOverflow
239 | BufferTextureCopyInfoError::ImageBytesOverflow(_)
240 | BufferTextureCopyInfoError::ArraySizeOverflow(_) => Self::SizeOverflow,
241 }
242 }
243}
244
245pub(crate) fn extract_texture_selector<T>(
246 copy_texture: &wgt::TexelCopyTextureInfo<T>,
247 copy_size: &Extent3d,
248 texture: &Texture,
249) -> Result<(TextureSelector, hal::TextureCopyBase), TransferError> {
250 let format = texture.desc.format;
251 let copy_aspect = hal::FormatAspects::new(format, copy_texture.aspect);
252 if copy_aspect.is_empty() {
253 return Err(TransferError::InvalidTextureAspect {
254 format,
255 aspect: copy_texture.aspect,
256 });
257 }
258
259 let (layers, origin_z) = match texture.desc.dimension {
260 wgt::TextureDimension::D1 => (0..1, 0),
261 wgt::TextureDimension::D2 => (
262 copy_texture.origin.z..copy_texture.origin.z + copy_size.depth_or_array_layers,
263 0,
264 ),
265 wgt::TextureDimension::D3 => (0..1, copy_texture.origin.z),
266 };
267 let base = hal::TextureCopyBase {
268 origin: wgt::Origin3d {
269 x: copy_texture.origin.x,
270 y: copy_texture.origin.y,
271 z: origin_z,
272 },
273 array_layer: layers.start,
275 mip_level: copy_texture.mip_level,
276 aspect: copy_aspect,
277 };
278 let selector = TextureSelector {
279 mips: copy_texture.mip_level..copy_texture.mip_level + 1,
280 layers,
281 };
282
283 Ok((selector, base))
284}
285
286pub(crate) fn validate_linear_texture_data(
298 layout: &wgt::TexelCopyBufferLayout,
299 format: wgt::TextureFormat,
300 aspect: wgt::TextureAspect,
301 buffer_size: BufferAddress,
302 buffer_side: CopySide,
303 copy_size: &Extent3d,
304) -> Result<(BufferAddress, BufferAddress, bool), TransferError> {
305 let wgt::BufferTextureCopyInfo {
306 copy_width,
307 copy_height,
308 depth_or_array_layers,
309
310 offset,
311
312 block_size_bytes: _,
313 block_width_texels,
314 block_height_texels,
315
316 width_blocks: _,
317 height_blocks,
318
319 row_bytes_dense,
320 row_stride_bytes,
321
322 image_stride_rows: _,
323 image_stride_bytes,
324
325 image_rows_dense: _,
326 image_bytes_dense,
327
328 bytes_in_copy,
329 } = layout.get_buffer_texture_copy_info(format, aspect, copy_size)?;
330
331 if !copy_width.is_multiple_of(block_width_texels) {
332 return Err(TransferError::UnalignedCopyWidth);
333 }
334 if !copy_height.is_multiple_of(block_height_texels) {
335 return Err(TransferError::UnalignedCopyHeight);
336 }
337
338 let requires_multiple_rows = depth_or_array_layers > 1 || height_blocks > 1;
339 let requires_multiple_images = depth_or_array_layers > 1;
340
341 if layout.bytes_per_row.is_none() && requires_multiple_rows {
346 return Err(TransferError::UnspecifiedBytesPerRow);
347 }
348
349 if layout.rows_per_image.is_none() && requires_multiple_images {
350 return Err(TransferError::UnspecifiedRowsPerImage);
351 };
352
353 if offset > buffer_size {
354 return Err(TransferError::BufferStartOffsetOverrun {
355 start_offset: offset,
356 buffer_size,
357 side: buffer_side,
358 });
359 }
360 if bytes_in_copy > buffer_size - offset {
362 return Err(TransferError::BufferEndOffsetOverrun {
363 start_offset: offset,
364 size: bytes_in_copy,
365 buffer_size,
366 side: buffer_side,
367 });
368 }
369
370 let is_contiguous = (row_stride_bytes == row_bytes_dense || !requires_multiple_rows)
371 && (image_stride_bytes == image_bytes_dense || !requires_multiple_images);
372
373 Ok((bytes_in_copy, image_stride_bytes, is_contiguous))
374}
375
376pub(crate) fn validate_texture_copy_src_format(
385 format: wgt::TextureFormat,
386 aspect: wgt::TextureAspect,
387) -> Result<(), TransferError> {
388 use wgt::TextureAspect as Ta;
389 use wgt::TextureFormat as Tf;
390 match (format, aspect) {
391 (Tf::Depth24Plus, _) => Err(TransferError::CopyFromForbiddenTextureFormat(format)),
392 (Tf::Depth24PlusStencil8, Ta::DepthOnly) => {
393 Err(TransferError::CopyFromForbiddenTextureFormatAspect { format, aspect })
394 }
395 _ => Ok(()),
396 }
397}
398
399pub(crate) fn validate_texture_copy_dst_format(
408 format: wgt::TextureFormat,
409 aspect: wgt::TextureAspect,
410) -> Result<(), TransferError> {
411 use wgt::TextureAspect as Ta;
412 use wgt::TextureFormat as Tf;
413 match (format, aspect) {
414 (Tf::Depth24Plus | Tf::Depth32Float, _) => {
415 Err(TransferError::CopyToForbiddenTextureFormat(format))
416 }
417 (Tf::Depth24PlusStencil8 | Tf::Depth32FloatStencil8, Ta::DepthOnly) => {
418 Err(TransferError::CopyToForbiddenTextureFormatAspect { format, aspect })
419 }
420 _ => Ok(()),
421 }
422}
423
424pub(crate) fn validate_texture_buffer_copy<T>(
452 texture_copy_view: &wgt::TexelCopyTextureInfo<T>,
453 aspect: hal::FormatAspects,
454 desc: &wgt::TextureDescriptor<(), Vec<wgt::TextureFormat>>,
455 layout: &wgt::TexelCopyBufferLayout,
456 aligned: bool,
457) -> Result<(), TransferError> {
458 if desc.sample_count != 1 {
459 return Err(TransferError::InvalidSampleCount {
460 sample_count: desc.sample_count,
461 });
462 }
463
464 if !aspect.is_one() {
465 return Err(TransferError::CopyAspectNotOne);
466 }
467
468 let offset_alignment = if desc.format.is_depth_stencil_format() {
469 4
470 } else {
471 desc.format
476 .block_copy_size(Some(texture_copy_view.aspect))
477 .expect("non-copyable formats should have been rejected previously")
478 };
479
480 if aligned && !layout.offset.is_multiple_of(u64::from(offset_alignment)) {
481 return Err(TransferError::UnalignedBufferOffset(layout.offset));
482 }
483
484 if let Some(bytes_per_row) = layout.bytes_per_row {
485 if aligned && bytes_per_row % wgt::COPY_BYTES_PER_ROW_ALIGNMENT != 0 {
486 return Err(TransferError::UnalignedBytesPerRow);
487 }
488 }
489
490 Ok(())
491}
492
493pub(crate) fn validate_texture_copy_range<T>(
504 texture_copy_view: &wgt::TexelCopyTextureInfo<T>,
505 desc: &wgt::TextureDescriptor<(), Vec<wgt::TextureFormat>>,
506 texture_side: CopySide,
507 copy_size: &Extent3d,
508) -> Result<(hal::CopyExtent, u32), TransferError> {
509 let (block_width, block_height) = desc.format.block_dimensions();
510
511 let extent_virtual = desc.mip_level_size(texture_copy_view.mip_level).ok_or(
512 TransferError::InvalidTextureMipLevel {
513 level: texture_copy_view.mip_level,
514 total: desc.mip_level_count,
515 },
516 )?;
517 let extent = extent_virtual.physical_size(desc.format);
519
520 let requires_exact_size = desc.format.is_depth_stencil_format() || desc.sample_count > 1;
523
524 let check_dimension = |dimension: TextureErrorDimension,
527 start_offset: u32,
528 size: u32,
529 texture_size: u32,
530 requires_exact_size: bool|
531 -> Result<(), TransferError> {
532 if requires_exact_size && (start_offset != 0 || size != texture_size) {
533 Err(TransferError::UnsupportedPartialTransfer {
534 format: desc.format,
535 sample_count: desc.sample_count,
536 start_offset,
537 end_offset: start_offset.wrapping_add(size),
538 texture_size,
539 dimension,
540 side: texture_side,
541 })
542 } else if start_offset > texture_size || texture_size - start_offset < size {
545 Err(TransferError::TextureOverrun {
546 start_offset,
547 end_offset: start_offset.wrapping_add(size),
548 texture_size,
549 dimension,
550 side: texture_side,
551 })
552 } else {
553 Ok(())
554 }
555 };
556
557 check_dimension(
558 TextureErrorDimension::X,
559 texture_copy_view.origin.x,
560 copy_size.width,
561 extent.width,
562 requires_exact_size,
563 )?;
564 check_dimension(
565 TextureErrorDimension::Y,
566 texture_copy_view.origin.y,
567 copy_size.height,
568 extent.height,
569 requires_exact_size,
570 )?;
571 check_dimension(
572 TextureErrorDimension::Z,
573 texture_copy_view.origin.z,
574 copy_size.depth_or_array_layers,
575 extent.depth_or_array_layers,
576 false, )?;
578
579 if !texture_copy_view.origin.x.is_multiple_of(block_width) {
580 return Err(TransferError::UnalignedCopyOriginX);
581 }
582 if !texture_copy_view.origin.y.is_multiple_of(block_height) {
583 return Err(TransferError::UnalignedCopyOriginY);
584 }
585 if !copy_size.width.is_multiple_of(block_width) {
586 return Err(TransferError::UnalignedCopyWidth);
587 }
588 if !copy_size.height.is_multiple_of(block_height) {
589 return Err(TransferError::UnalignedCopyHeight);
590 }
591
592 let (depth, array_layer_count) = match desc.dimension {
593 wgt::TextureDimension::D1 => (1, 1),
594 wgt::TextureDimension::D2 => (1, copy_size.depth_or_array_layers),
595 wgt::TextureDimension::D3 => (copy_size.depth_or_array_layers, 1),
596 };
597
598 let copy_extent = hal::CopyExtent {
599 width: copy_size.width,
600 height: copy_size.height,
601 depth,
602 };
603 Ok((copy_extent, array_layer_count))
604}
605
606pub(crate) fn validate_copy_within_same_texture<T>(
617 src: &wgt::TexelCopyTextureInfo<T>,
618 dst: &wgt::TexelCopyTextureInfo<T>,
619 format: wgt::TextureFormat,
620 array_layer_count: u32,
621) -> Result<(), TransferError> {
622 let src_aspects = hal::FormatAspects::new(format, src.aspect);
623 let dst_aspects = hal::FormatAspects::new(format, dst.aspect);
624 if (src_aspects & dst_aspects).is_empty() {
625 return Ok(());
627 }
628
629 if src.origin.z >= dst.origin.z + array_layer_count
630 || dst.origin.z >= src.origin.z + array_layer_count
631 {
632 return Ok(());
634 }
635
636 if src.mip_level != dst.mip_level {
637 return Ok(());
639 }
640
641 Err(TransferError::InvalidCopyWithinSameTexture {
642 src_aspects: src.aspect,
643 dst_aspects: dst.aspect,
644 src_origin_z: src.origin.z,
645 dst_origin_z: dst.origin.z,
646 array_layer_count,
647 })
648}
649
650fn handle_texture_init(
651 state: &mut EncodingState,
652 init_kind: MemoryInitKind,
653 copy_texture: &TexelCopyTextureInfo,
654 copy_size: &Extent3d,
655 texture: &Arc<Texture>,
656) -> Result<(), ClearError> {
657 let init_action = TextureInitTrackerAction {
658 texture: texture.clone(),
659 range: TextureInitRange {
660 mip_range: copy_texture.mip_level..copy_texture.mip_level + 1,
661 layer_range: copy_texture.origin.z
662 ..(copy_texture.origin.z + copy_size.depth_or_array_layers),
663 },
664 kind: init_kind,
665 };
666
667 let immediate_inits = state
669 .texture_memory_actions
670 .register_init_action(&{ init_action });
671
672 if !immediate_inits.is_empty() {
674 for init in immediate_inits {
675 clear_texture(
676 &init.texture,
677 TextureInitRange {
678 mip_range: init.mip_level..(init.mip_level + 1),
679 layer_range: init.layer..(init.layer + 1),
680 },
681 state.raw_encoder,
682 &mut state.tracker.textures,
683 &state.device.alignments,
684 state.device.zero_buffer.as_ref(),
685 state.snatch_guard,
686 state.device.instance_flags,
687 )?;
688 }
689 }
690
691 Ok(())
692}
693
694fn handle_src_texture_init(
699 state: &mut EncodingState,
700 source: &TexelCopyTextureInfo,
701 copy_size: &Extent3d,
702 texture: &Arc<Texture>,
703) -> Result<(), TransferError> {
704 handle_texture_init(
705 state,
706 MemoryInitKind::NeedsInitializedMemory,
707 source,
708 copy_size,
709 texture,
710 )?;
711 Ok(())
712}
713
714fn handle_dst_texture_init(
719 state: &mut EncodingState,
720 destination: &wgt::TexelCopyTextureInfo<Arc<Texture>>,
721 copy_size: &Extent3d,
722 texture: &Arc<Texture>,
723) -> Result<(), TransferError> {
724 let dst_init_kind =
729 if has_copy_partial_init_tracker_coverage(copy_size, destination, &texture.desc) {
730 MemoryInitKind::NeedsInitializedMemory
731 } else {
732 MemoryInitKind::ImplicitlyInitialized
733 };
734
735 handle_texture_init(state, dst_init_kind, destination, copy_size, texture)?;
736 Ok(())
737}
738
739fn handle_buffer_init(
744 state: &mut EncodingState,
745 info: &wgt::TexelCopyBufferInfo<Arc<Buffer>>,
746 direction: CopySide,
747 required_buffer_bytes_in_copy: BufferAddress,
748 is_contiguous: bool,
749) {
750 const ALIGN_SIZE: BufferAddress = wgt::COPY_BUFFER_ALIGNMENT;
751 const ALIGN_MASK: BufferAddress = wgt::COPY_BUFFER_ALIGNMENT - 1;
752
753 let buffer = &info.buffer;
754 let start = info.layout.offset;
755 let end = info.layout.offset + required_buffer_bytes_in_copy;
756 if !is_contiguous || direction == CopySide::Source {
757 let aligned_start = start & !ALIGN_MASK;
768 let aligned_end = (end + ALIGN_MASK) & !ALIGN_MASK;
769 state
770 .buffer_memory_init_actions
771 .extend(buffer.initialization_status.read().create_action(
772 buffer,
773 aligned_start..aligned_end,
774 MemoryInitKind::NeedsInitializedMemory,
775 ));
776 } else {
777 let aligned_start = (start + ALIGN_MASK) & !ALIGN_MASK;
787 let aligned_end = end & !ALIGN_MASK;
788 if aligned_start != start {
789 state.buffer_memory_init_actions.extend(
790 buffer.initialization_status.read().create_action(
791 buffer,
792 aligned_start - ALIGN_SIZE..aligned_start,
793 MemoryInitKind::NeedsInitializedMemory,
794 ),
795 );
796 }
797 if aligned_start != aligned_end {
798 state.buffer_memory_init_actions.extend(
799 buffer.initialization_status.read().create_action(
800 buffer,
801 aligned_start..aligned_end,
802 MemoryInitKind::ImplicitlyInitialized,
803 ),
804 );
805 }
806 if aligned_end != end {
807 state.buffer_memory_init_actions.extend(
813 buffer.initialization_status.read().create_action(
814 buffer,
815 aligned_end..aligned_end + ALIGN_SIZE,
816 MemoryInitKind::NeedsInitializedMemory,
817 ),
818 );
819 }
820 }
821}
822
823impl Global {
824 pub fn command_encoder_copy_buffer_to_buffer(
825 &self,
826 command_encoder_id: CommandEncoderId,
827 source: BufferId,
828 source_offset: BufferAddress,
829 destination: BufferId,
830 destination_offset: BufferAddress,
831 size: Option<BufferAddress>,
832 ) -> Result<(), EncoderStateError> {
833 profiling::scope!("CommandEncoder::copy_buffer_to_buffer");
834 api_log!(
835 "CommandEncoder::copy_buffer_to_buffer {source:?} -> {destination:?} {size:?}bytes"
836 );
837
838 let hub = &self.hub;
839
840 let cmd_enc = hub.command_encoders.get(command_encoder_id);
841 let mut cmd_buf_data = cmd_enc.data.lock();
842
843 cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
844 Ok(ArcCommand::CopyBufferToBuffer {
845 src: self.resolve_buffer_id(source)?,
846 src_offset: source_offset,
847 dst: self.resolve_buffer_id(destination)?,
848 dst_offset: destination_offset,
849 size,
850 })
851 })
852 }
853
854 pub fn command_encoder_copy_buffer_to_texture(
855 &self,
856 command_encoder_id: CommandEncoderId,
857 source: &TexelCopyBufferInfo,
858 destination: &wgt::TexelCopyTextureInfo<TextureId>,
859 copy_size: &Extent3d,
860 ) -> Result<(), EncoderStateError> {
861 profiling::scope!("CommandEncoder::copy_buffer_to_texture");
862 api_log!(
863 "CommandEncoder::copy_buffer_to_texture {:?} -> {:?} {copy_size:?}",
864 source.buffer,
865 destination.texture
866 );
867
868 let cmd_enc = self.hub.command_encoders.get(command_encoder_id);
869 let mut cmd_buf_data = cmd_enc.data.lock();
870
871 cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
872 Ok(ArcCommand::CopyBufferToTexture {
873 src: wgt::TexelCopyBufferInfo::<Arc<Buffer>> {
874 buffer: self.resolve_buffer_id(source.buffer)?,
875 layout: source.layout,
876 },
877 dst: wgt::TexelCopyTextureInfo::<Arc<Texture>> {
878 texture: self.resolve_texture_id(destination.texture)?,
879 mip_level: destination.mip_level,
880 origin: destination.origin,
881 aspect: destination.aspect,
882 },
883 size: *copy_size,
884 })
885 })
886 }
887
888 pub fn command_encoder_copy_texture_to_buffer(
889 &self,
890 command_encoder_id: CommandEncoderId,
891 source: &wgt::TexelCopyTextureInfo<TextureId>,
892 destination: &TexelCopyBufferInfo,
893 copy_size: &Extent3d,
894 ) -> Result<(), EncoderStateError> {
895 profiling::scope!("CommandEncoder::copy_texture_to_buffer");
896 api_log!(
897 "CommandEncoder::copy_texture_to_buffer {:?} -> {:?} {copy_size:?}",
898 source.texture,
899 destination.buffer
900 );
901
902 let cmd_enc = self.hub.command_encoders.get(command_encoder_id);
903 let mut cmd_buf_data = cmd_enc.data.lock();
904
905 cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
906 Ok(ArcCommand::CopyTextureToBuffer {
907 src: wgt::TexelCopyTextureInfo::<Arc<Texture>> {
908 texture: self.resolve_texture_id(source.texture)?,
909 mip_level: source.mip_level,
910 origin: source.origin,
911 aspect: source.aspect,
912 },
913 dst: wgt::TexelCopyBufferInfo::<Arc<Buffer>> {
914 buffer: self.resolve_buffer_id(destination.buffer)?,
915 layout: destination.layout,
916 },
917 size: *copy_size,
918 })
919 })
920 }
921
922 pub fn command_encoder_copy_texture_to_texture(
923 &self,
924 command_encoder_id: CommandEncoderId,
925 source: &wgt::TexelCopyTextureInfo<TextureId>,
926 destination: &wgt::TexelCopyTextureInfo<TextureId>,
927 copy_size: &Extent3d,
928 ) -> Result<(), EncoderStateError> {
929 profiling::scope!("CommandEncoder::copy_texture_to_texture");
930 api_log!(
931 "CommandEncoder::copy_texture_to_texture {:?} -> {:?} {copy_size:?}",
932 source.texture,
933 destination.texture
934 );
935
936 let cmd_enc = self.hub.command_encoders.get(command_encoder_id);
937 let mut cmd_buf_data = cmd_enc.data.lock();
938
939 cmd_buf_data.push_with(|| -> Result<_, CommandEncoderError> {
940 Ok(ArcCommand::CopyTextureToTexture {
941 src: wgt::TexelCopyTextureInfo {
942 texture: self.resolve_texture_id(source.texture)?,
943 mip_level: source.mip_level,
944 origin: source.origin,
945 aspect: source.aspect,
946 },
947 dst: wgt::TexelCopyTextureInfo {
948 texture: self.resolve_texture_id(destination.texture)?,
949 mip_level: destination.mip_level,
950 origin: destination.origin,
951 aspect: destination.aspect,
952 },
953 size: *copy_size,
954 })
955 })
956 }
957}
958
959pub(super) fn copy_buffer_to_buffer(
960 state: &mut EncodingState,
961 src_buffer: &Arc<Buffer>,
962 source_offset: BufferAddress,
963 dst_buffer: &Arc<Buffer>,
964 destination_offset: BufferAddress,
965 size: Option<BufferAddress>,
966) -> Result<(), CommandEncoderError> {
967 if src_buffer.is_equal(dst_buffer) {
968 return Err(TransferError::SameSourceDestinationBuffer.into());
969 }
970
971 src_buffer.same_device(state.device)?;
972
973 let src_pending = state
974 .tracker
975 .buffers
976 .set_single(src_buffer, wgt::BufferUses::COPY_SRC);
977
978 let src_raw = src_buffer.try_raw(state.snatch_guard)?;
979 src_buffer
980 .check_usage(BufferUsages::COPY_SRC)
981 .map_err(TransferError::MissingBufferUsage)?;
982 let src_barrier = src_pending.map(|pending| pending.into_hal(src_buffer, state.snatch_guard));
984
985 dst_buffer.same_device(state.device)?;
986
987 let dst_pending = state
988 .tracker
989 .buffers
990 .set_single(dst_buffer, wgt::BufferUses::COPY_DST);
991
992 let dst_raw = dst_buffer.try_raw(state.snatch_guard)?;
993 dst_buffer
994 .check_usage(BufferUsages::COPY_DST)
995 .map_err(TransferError::MissingBufferUsage)?;
996 let dst_barrier = dst_pending.map(|pending| pending.into_hal(dst_buffer, state.snatch_guard));
997
998 if source_offset > src_buffer.size {
999 return Err(TransferError::BufferStartOffsetOverrun {
1000 start_offset: source_offset,
1001 buffer_size: src_buffer.size,
1002 side: CopySide::Source,
1003 }
1004 .into());
1005 }
1006 let size = size.unwrap_or_else(|| {
1007 src_buffer.size - source_offset
1009 });
1010
1011 if !size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1012 return Err(TransferError::UnalignedCopySize(size).into());
1013 }
1014 if !source_offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1015 return Err(TransferError::UnalignedBufferOffset(source_offset).into());
1016 }
1017 if !destination_offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1018 return Err(TransferError::UnalignedBufferOffset(destination_offset).into());
1019 }
1020 if !state
1021 .device
1022 .downlevel
1023 .flags
1024 .contains(wgt::DownlevelFlags::UNRESTRICTED_INDEX_BUFFER)
1025 && (src_buffer.usage.contains(BufferUsages::INDEX)
1026 || dst_buffer.usage.contains(BufferUsages::INDEX))
1027 {
1028 let forbidden_usages = BufferUsages::VERTEX
1029 | BufferUsages::UNIFORM
1030 | BufferUsages::INDIRECT
1031 | BufferUsages::STORAGE;
1032 if src_buffer.usage.intersects(forbidden_usages)
1033 || dst_buffer.usage.intersects(forbidden_usages)
1034 {
1035 return Err(TransferError::MissingDownlevelFlags(MissingDownlevelFlags(
1036 wgt::DownlevelFlags::UNRESTRICTED_INDEX_BUFFER,
1037 ))
1038 .into());
1039 }
1040 }
1041
1042 if size > src_buffer.size - source_offset {
1043 return Err(TransferError::BufferEndOffsetOverrun {
1044 start_offset: source_offset,
1045 size,
1046 buffer_size: src_buffer.size,
1047 side: CopySide::Source,
1048 }
1049 .into());
1050 }
1051 let source_end_offset = source_offset + size;
1053
1054 if destination_offset > dst_buffer.size {
1055 return Err(TransferError::BufferStartOffsetOverrun {
1056 start_offset: destination_offset,
1057 buffer_size: dst_buffer.size,
1058 side: CopySide::Destination,
1059 }
1060 .into());
1061 }
1062 if size > dst_buffer.size - destination_offset {
1064 return Err(TransferError::BufferEndOffsetOverrun {
1065 start_offset: destination_offset,
1066 size,
1067 buffer_size: dst_buffer.size,
1068 side: CopySide::Destination,
1069 }
1070 .into());
1071 }
1072 let destination_end_offset = destination_offset + size;
1074
1075 if size == 0 {
1078 log::trace!("Ignoring copy_buffer_to_buffer of size 0");
1079 return Ok(());
1080 }
1081
1082 state
1084 .buffer_memory_init_actions
1085 .extend(dst_buffer.initialization_status.read().create_action(
1086 dst_buffer,
1087 destination_offset..destination_end_offset,
1088 MemoryInitKind::ImplicitlyInitialized,
1089 ));
1090 state
1091 .buffer_memory_init_actions
1092 .extend(src_buffer.initialization_status.read().create_action(
1093 src_buffer,
1094 source_offset..source_end_offset,
1095 MemoryInitKind::NeedsInitializedMemory,
1096 ));
1097
1098 let region = hal::BufferCopy {
1099 src_offset: source_offset,
1100 dst_offset: destination_offset,
1101 size: wgt::BufferSize::new(size).unwrap(),
1102 };
1103 let barriers = src_barrier
1104 .into_iter()
1105 .chain(dst_barrier)
1106 .collect::<Vec<_>>();
1107 unsafe {
1108 state.raw_encoder.transition_buffers(&barriers);
1109 state
1110 .raw_encoder
1111 .copy_buffer_to_buffer(src_raw, dst_raw, &[region]);
1112 }
1113
1114 Ok(())
1115}
1116
1117pub(super) fn copy_buffer_to_texture(
1118 state: &mut EncodingState,
1119 source: &wgt::TexelCopyBufferInfo<Arc<Buffer>>,
1120 destination: &wgt::TexelCopyTextureInfo<Arc<Texture>>,
1121 copy_size: &Extent3d,
1122) -> Result<(), CommandEncoderError> {
1123 let dst_texture = &destination.texture;
1124 let src_buffer = &source.buffer;
1125
1126 dst_texture.same_device(state.device)?;
1127 src_buffer.same_device(state.device)?;
1128
1129 let (hal_copy_size, array_layer_count) = validate_texture_copy_range(
1130 destination,
1131 &dst_texture.desc,
1132 CopySide::Destination,
1133 copy_size,
1134 )?;
1135
1136 let (dst_range, dst_base) = extract_texture_selector(destination, copy_size, dst_texture)?;
1137
1138 let src_raw = src_buffer.try_raw(state.snatch_guard)?;
1139 src_buffer
1140 .check_usage(BufferUsages::COPY_SRC)
1141 .map_err(TransferError::MissingBufferUsage)?;
1142
1143 let dst_raw = dst_texture.try_raw(state.snatch_guard)?;
1144 dst_texture
1145 .check_usage(TextureUsages::COPY_DST)
1146 .map_err(TransferError::MissingTextureUsage)?;
1147
1148 validate_texture_copy_dst_format(dst_texture.desc.format, destination.aspect)?;
1149
1150 validate_texture_buffer_copy(
1151 destination,
1152 dst_base.aspect,
1153 &dst_texture.desc,
1154 &source.layout,
1155 true, )?;
1157
1158 let (required_buffer_bytes_in_copy, bytes_per_array_layer, is_contiguous) =
1159 validate_linear_texture_data(
1160 &source.layout,
1161 dst_texture.desc.format,
1162 destination.aspect,
1163 src_buffer.size,
1164 CopySide::Source,
1165 copy_size,
1166 )?;
1167
1168 if dst_texture.desc.format.is_depth_stencil_format() {
1169 state
1170 .device
1171 .require_downlevel_flags(wgt::DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES)
1172 .map_err(TransferError::from)?;
1173 }
1174
1175 if copy_size.width == 0 || copy_size.height == 0 || copy_size.depth_or_array_layers == 0 {
1178 log::trace!("Ignoring copy_buffer_to_texture of size 0");
1179 return Ok(());
1180 }
1181
1182 handle_dst_texture_init(state, destination, copy_size, dst_texture)?;
1186
1187 let src_pending = state
1188 .tracker
1189 .buffers
1190 .set_single(src_buffer, wgt::BufferUses::COPY_SRC);
1191 let src_barrier = src_pending.map(|pending| pending.into_hal(src_buffer, state.snatch_guard));
1192
1193 let dst_pending =
1194 state
1195 .tracker
1196 .textures
1197 .set_single(dst_texture, dst_range, wgt::TextureUses::COPY_DST);
1198 let dst_barrier = dst_pending
1199 .map(|pending| pending.into_hal(dst_raw))
1200 .collect::<Vec<_>>();
1201
1202 handle_buffer_init(
1203 state,
1204 source,
1205 CopySide::Source,
1206 required_buffer_bytes_in_copy,
1207 is_contiguous,
1208 );
1209
1210 let regions = (0..array_layer_count)
1211 .map(|rel_array_layer| {
1212 let mut texture_base = dst_base.clone();
1213 texture_base.array_layer += rel_array_layer;
1214 let mut buffer_layout = source.layout;
1215 buffer_layout.offset += rel_array_layer as u64 * bytes_per_array_layer;
1216 hal::BufferTextureCopy {
1217 buffer_layout,
1218 texture_base,
1219 size: hal_copy_size,
1220 }
1221 })
1222 .collect::<Vec<_>>();
1223
1224 unsafe {
1225 state.raw_encoder.transition_textures(&dst_barrier);
1226 state.raw_encoder.transition_buffers(src_barrier.as_slice());
1227 state
1228 .raw_encoder
1229 .copy_buffer_to_texture(src_raw, dst_raw, ®ions);
1230 }
1231
1232 Ok(())
1233}
1234
1235pub(super) fn copy_texture_to_buffer(
1236 state: &mut EncodingState,
1237 source: &TexelCopyTextureInfo,
1238 destination: &wgt::TexelCopyBufferInfo<Arc<Buffer>>,
1239 copy_size: &Extent3d,
1240) -> Result<(), CommandEncoderError> {
1241 let src_texture = &source.texture;
1242 let dst_buffer = &destination.buffer;
1243
1244 src_texture.same_device(state.device)?;
1245 dst_buffer.same_device(state.device)?;
1246
1247 let (hal_copy_size, array_layer_count) =
1248 validate_texture_copy_range(source, &src_texture.desc, CopySide::Source, copy_size)?;
1249
1250 let (src_range, src_base) = extract_texture_selector(source, copy_size, src_texture)?;
1251
1252 let src_raw = src_texture.try_raw(state.snatch_guard)?;
1253 src_texture
1254 .check_usage(TextureUsages::COPY_SRC)
1255 .map_err(TransferError::MissingTextureUsage)?;
1256
1257 if source.mip_level >= src_texture.desc.mip_level_count {
1258 return Err(TransferError::InvalidMipLevel {
1259 requested: source.mip_level,
1260 count: src_texture.desc.mip_level_count,
1261 }
1262 .into());
1263 }
1264
1265 validate_texture_copy_src_format(src_texture.desc.format, source.aspect)?;
1266
1267 validate_texture_buffer_copy(
1268 source,
1269 src_base.aspect,
1270 &src_texture.desc,
1271 &destination.layout,
1272 true, )?;
1274
1275 let (required_buffer_bytes_in_copy, bytes_per_array_layer, is_contiguous) =
1276 validate_linear_texture_data(
1277 &destination.layout,
1278 src_texture.desc.format,
1279 source.aspect,
1280 dst_buffer.size,
1281 CopySide::Destination,
1282 copy_size,
1283 )?;
1284
1285 if src_texture.desc.format.is_depth_stencil_format() {
1286 state
1287 .device
1288 .require_downlevel_flags(wgt::DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES)
1289 .map_err(TransferError::from)?;
1290 }
1291
1292 let dst_raw = dst_buffer.try_raw(state.snatch_guard)?;
1293 dst_buffer
1294 .check_usage(BufferUsages::COPY_DST)
1295 .map_err(TransferError::MissingBufferUsage)?;
1296
1297 if copy_size.width == 0 || copy_size.height == 0 || copy_size.depth_or_array_layers == 0 {
1300 log::trace!("Ignoring copy_texture_to_buffer of size 0");
1301 return Ok(());
1302 }
1303
1304 handle_src_texture_init(state, source, copy_size, src_texture)?;
1308
1309 let src_pending =
1310 state
1311 .tracker
1312 .textures
1313 .set_single(src_texture, src_range, wgt::TextureUses::COPY_SRC);
1314 let src_barrier = src_pending
1315 .map(|pending| pending.into_hal(src_raw))
1316 .collect::<Vec<_>>();
1317
1318 let dst_pending = state
1319 .tracker
1320 .buffers
1321 .set_single(dst_buffer, wgt::BufferUses::COPY_DST);
1322
1323 let dst_barrier = dst_pending.map(|pending| pending.into_hal(dst_buffer, state.snatch_guard));
1324
1325 handle_buffer_init(
1326 state,
1327 destination,
1328 CopySide::Destination,
1329 required_buffer_bytes_in_copy,
1330 is_contiguous,
1331 );
1332
1333 let regions = (0..array_layer_count)
1334 .map(|rel_array_layer| {
1335 let mut texture_base = src_base.clone();
1336 texture_base.array_layer += rel_array_layer;
1337 let mut buffer_layout = destination.layout;
1338 buffer_layout.offset += rel_array_layer as u64 * bytes_per_array_layer;
1339 hal::BufferTextureCopy {
1340 buffer_layout,
1341 texture_base,
1342 size: hal_copy_size,
1343 }
1344 })
1345 .collect::<Vec<_>>();
1346 unsafe {
1347 state.raw_encoder.transition_buffers(dst_barrier.as_slice());
1348 state.raw_encoder.transition_textures(&src_barrier);
1349 state.raw_encoder.copy_texture_to_buffer(
1350 src_raw,
1351 wgt::TextureUses::COPY_SRC,
1352 dst_raw,
1353 ®ions,
1354 );
1355 }
1356
1357 Ok(())
1358}
1359
1360pub(super) fn copy_texture_to_texture(
1361 state: &mut EncodingState,
1362 source: &TexelCopyTextureInfo,
1363 destination: &TexelCopyTextureInfo,
1364 copy_size: &Extent3d,
1365) -> Result<(), CommandEncoderError> {
1366 let src_texture = &source.texture;
1367 let dst_texture = &destination.texture;
1368
1369 src_texture.same_device(state.device)?;
1370 dst_texture.same_device(state.device)?;
1371
1372 let src_fmt_no_srgb = src_texture.desc.format.remove_srgb_suffix();
1386 let dst_fmt_no_srgb = dst_texture.desc.format.remove_srgb_suffix();
1387 let planar_split_ok = src_fmt_no_srgb.is_multi_planar_format()
1388 && src_fmt_no_srgb.aspect_specific_format(source.aspect) == Some(dst_fmt_no_srgb);
1389 if src_fmt_no_srgb != dst_fmt_no_srgb && !planar_split_ok {
1390 return Err(TransferError::TextureFormatsNotCopyCompatible {
1391 src_format: src_texture.desc.format,
1392 dst_format: dst_texture.desc.format,
1393 }
1394 .into());
1395 }
1396
1397 let (src_copy_size, array_layer_count) =
1398 validate_texture_copy_range(source, &src_texture.desc, CopySide::Source, copy_size)?;
1399 let (dst_copy_size, _) = validate_texture_copy_range(
1400 destination,
1401 &dst_texture.desc,
1402 CopySide::Destination,
1403 copy_size,
1404 )?;
1405
1406 if planar_split_ok {
1412 let plane = source.aspect.to_plane().expect("planar_split_ok aspect");
1415 let plane_extent = src_texture
1416 .desc
1417 .compute_render_extent(source.mip_level, Some(plane));
1418 let check = |dimension, start: u32, size: u32, plane_size: u32| {
1419 if start > plane_size || plane_size - start < size {
1420 Err(TransferError::TextureOverrun {
1421 start_offset: start,
1422 end_offset: start.wrapping_add(size),
1423 texture_size: plane_size,
1424 dimension,
1425 side: CopySide::Source,
1426 })
1427 } else {
1428 Ok(())
1429 }
1430 };
1431 check(
1432 TextureErrorDimension::X,
1433 source.origin.x,
1434 copy_size.width,
1435 plane_extent.width,
1436 )?;
1437 check(
1438 TextureErrorDimension::Y,
1439 source.origin.y,
1440 copy_size.height,
1441 plane_extent.height,
1442 )?;
1443 }
1444
1445 if Arc::as_ptr(src_texture) == Arc::as_ptr(dst_texture) {
1446 validate_copy_within_same_texture(
1447 source,
1448 destination,
1449 src_texture.desc.format,
1450 array_layer_count,
1451 )?;
1452 }
1453
1454 let (src_range, src_tex_base) = extract_texture_selector(source, copy_size, src_texture)?;
1455 let (dst_range, dst_tex_base) = extract_texture_selector(destination, copy_size, dst_texture)?;
1456 let src_texture_aspects = hal::FormatAspects::from(src_texture.desc.format);
1457 let dst_texture_aspects = hal::FormatAspects::from(dst_texture.desc.format);
1458 if src_tex_base.aspect != src_texture_aspects && !planar_split_ok {
1460 return Err(TransferError::CopySrcMissingAspects.into());
1461 }
1462 if dst_tex_base.aspect != dst_texture_aspects {
1463 return Err(TransferError::CopyDstMissingAspects.into());
1464 }
1465
1466 if src_texture.desc.sample_count != dst_texture.desc.sample_count {
1467 return Err(TransferError::SampleCountNotEqual {
1468 src_sample_count: src_texture.desc.sample_count,
1469 dst_sample_count: dst_texture.desc.sample_count,
1470 }
1471 .into());
1472 }
1473
1474 let src_raw = src_texture.try_raw(state.snatch_guard)?;
1475 src_texture
1476 .check_usage(TextureUsages::COPY_SRC)
1477 .map_err(TransferError::MissingTextureUsage)?;
1478 let dst_raw = dst_texture.try_raw(state.snatch_guard)?;
1479 dst_texture
1480 .check_usage(TextureUsages::COPY_DST)
1481 .map_err(TransferError::MissingTextureUsage)?;
1482
1483 if copy_size.width == 0 || copy_size.height == 0 || copy_size.depth_or_array_layers == 0 {
1486 log::trace!("Ignoring copy_texture_to_texture of size 0");
1487 return Ok(());
1488 }
1489
1490 handle_src_texture_init(state, source, copy_size, src_texture)?;
1494 handle_dst_texture_init(state, destination, copy_size, dst_texture)?;
1495
1496 let src_pending =
1497 state
1498 .tracker
1499 .textures
1500 .set_single(src_texture, src_range, wgt::TextureUses::COPY_SRC);
1501
1502 let mut barriers: ArrayVec<_, 2> = src_pending
1505 .map(|pending| pending.into_hal(src_raw))
1506 .collect();
1507
1508 let dst_pending =
1509 state
1510 .tracker
1511 .textures
1512 .set_single(dst_texture, dst_range, wgt::TextureUses::COPY_DST);
1513 barriers.extend(dst_pending.map(|pending| pending.into_hal(dst_raw)));
1514
1515 let hal_copy_size = hal::CopyExtent {
1516 width: src_copy_size.width.min(dst_copy_size.width),
1517 height: src_copy_size.height.min(dst_copy_size.height),
1518 depth: src_copy_size.depth.min(dst_copy_size.depth),
1519 };
1520
1521 let dst_format = dst_texture.desc.format;
1522
1523 let regions = (0..array_layer_count).map(|rel_array_layer| {
1524 let mut src_base = src_tex_base.clone();
1525 let mut dst_base = dst_tex_base.clone();
1526 src_base.array_layer += rel_array_layer;
1527 dst_base.array_layer += rel_array_layer;
1528 hal::TextureCopy {
1529 src_base,
1530 dst_base,
1531 size: hal_copy_size,
1532 }
1533 });
1534
1535 let regions = if dst_tex_base.aspect == hal::FormatAspects::DEPTH_STENCIL {
1536 regions
1537 .flat_map(|region| {
1538 let (mut depth, mut stencil) = (region.clone(), region);
1539 depth.src_base.aspect = hal::FormatAspects::DEPTH;
1540 depth.dst_base.aspect = hal::FormatAspects::DEPTH;
1541 stencil.src_base.aspect = hal::FormatAspects::STENCIL;
1542 stencil.dst_base.aspect = hal::FormatAspects::STENCIL;
1543 [depth, stencil]
1544 })
1545 .collect::<Vec<_>>()
1546 } else if let Some(plane_count) = dst_format.planes() {
1547 regions
1548 .into_iter()
1549 .flat_map(|region| {
1550 (0..plane_count).map(move |plane| {
1551 let mut plane_region = region.clone();
1552
1553 let plane_aspect = wgt::TextureAspect::from_plane(plane)
1554 .expect("expected texture aspect to exist for the plane");
1555 let plane_aspect = hal::FormatAspects::new(dst_format, plane_aspect);
1556 plane_region.src_base.aspect = plane_aspect;
1557 plane_region.dst_base.aspect = plane_aspect;
1558
1559 let (w_subsampling, h_subsampling) =
1560 dst_format.subsampling_factors(Some(plane));
1561 plane_region.src_base.origin.x /= w_subsampling;
1562 plane_region.src_base.origin.y /= h_subsampling;
1563 plane_region.dst_base.origin.x /= w_subsampling;
1564 plane_region.dst_base.origin.y /= h_subsampling;
1565
1566 plane_region.size.width /= w_subsampling;
1567 plane_region.size.height /= h_subsampling;
1568
1569 plane_region
1570 })
1571 })
1572 .collect::<Vec<_>>()
1573 } else {
1574 regions.collect::<Vec<_>>()
1575 };
1576 unsafe {
1577 state.raw_encoder.transition_textures(&barriers);
1578 state.raw_encoder.copy_texture_to_texture(
1579 src_raw,
1580 wgt::TextureUses::COPY_SRC,
1581 dst_raw,
1582 ®ions,
1583 );
1584 }
1585
1586 Ok(())
1587}