Skip to main content

wgpu_core/
resource.rs

1use alloc::{
2    borrow::{Cow, ToOwned as _},
3    boxed::Box,
4    string::String,
5    sync::Arc,
6    vec::Vec,
7};
8use core::{
9    borrow::Borrow,
10    fmt,
11    mem::{self, size_of, ManuallyDrop},
12    num::NonZeroU64,
13    ops::Range,
14    ptr::NonNull,
15};
16use smallvec::SmallVec;
17use thiserror::Error;
18use wgt::{
19    error::{ErrorType, WebGpuError},
20    math::align_to,
21    MapMode, TextureSelector, WriteOnly,
22};
23
24#[cfg(feature = "trace")]
25use crate::device::trace;
26use crate::{
27    api_log,
28    binding_model::{BindGroup, BindingError},
29    device::{
30        queue, resource::DeferredDestroy, BufferMapPendingClosure, Device, DeviceError,
31        DeviceMismatch, MissingDownlevelFlags, MissingFeatures,
32    },
33    hal_label,
34    init_tracker::{BufferInitTracker, TextureInitTracker},
35    lock::{rank, Mutex, MutexGuard, RwLock},
36    ray_tracing::{BlasCompactReadyPendingClosure, BlasPrepareCompactError},
37    resource_log,
38    snatch::{SnatchGuard, Snatchable},
39    timestamp_normalization::TimestampNormalizationBindGroup,
40    track::{SharedTrackerIndexAllocator, TrackerIndex},
41    weak_vec::WeakVec,
42    Label, LabelHelpers, SubmissionIndex,
43};
44
45/// Information about the wgpu-core resource.
46///
47/// Each type representing a `wgpu-core` resource, like [`Device`],
48/// [`Buffer`], etc., contains a `ResourceInfo` which contains
49/// its latest submission index and label.
50///
51/// A resource may need to be retained for any of several reasons:
52/// and any lifetime logic will be handled by `Arc<Resource>` refcount
53///
54/// - The user may hold a reference to it (via a `wgpu::Buffer`, say).
55///
56/// - Other resources may depend on it (a texture view's backing
57///   texture, for example).
58///
59/// - It may be used by commands sent to the GPU that have not yet
60///   finished execution.
61///
62/// [`Device`]: crate::device::resource::Device
63/// [`Buffer`]: crate::resource::Buffer
64#[derive(Debug)]
65pub(crate) struct TrackingData {
66    tracker_index: TrackerIndex,
67    tracker_indices: Arc<SharedTrackerIndexAllocator>,
68}
69
70impl Drop for TrackingData {
71    fn drop(&mut self) {
72        self.tracker_indices.free(self.tracker_index);
73    }
74}
75
76impl TrackingData {
77    pub(crate) fn new(tracker_indices: Arc<SharedTrackerIndexAllocator>) -> Self {
78        Self {
79            tracker_index: tracker_indices.alloc(),
80            tracker_indices,
81        }
82    }
83
84    pub(crate) fn tracker_index(&self) -> TrackerIndex {
85        self.tracker_index
86    }
87}
88
89#[derive(Clone, Debug)]
90#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
91pub struct ResourceErrorIdent {
92    r#type: Cow<'static, str>,
93    label: String,
94}
95
96impl fmt::Display for ResourceErrorIdent {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
98        write!(f, "{} with '{}' label", self.r#type, self.label)
99    }
100}
101
102#[derive(Debug)]
103pub enum ResourceState<T> {
104    Valid(T),
105    Invalid,
106}
107
108impl<T> ResourceState<T> {
109    pub fn as_ref(&self) -> ResourceState<&T> {
110        match self {
111            ResourceState::Valid(v) => ResourceState::Valid(v),
112            ResourceState::Invalid => ResourceState::Invalid,
113        }
114    }
115
116    pub fn valid(self) -> Option<T> {
117        match self {
118            ResourceState::Valid(v) => Some(v),
119            ResourceState::Invalid => None,
120        }
121    }
122}
123
124#[derive(thiserror::Error, Debug)]
125pub enum InvalidOrDestroyedResourceError {
126    #[error(transparent)]
127    InvalidResource(#[from] InvalidResourceError),
128    #[error(transparent)]
129    DestroyedResource(#[from] DestroyedResourceError),
130}
131
132pub trait ParentDevice: Labeled {
133    fn device(&self) -> &Arc<Device>;
134
135    fn is_equal(self: &Arc<Self>, other: &Arc<Self>) -> bool {
136        Arc::ptr_eq(self, other)
137    }
138
139    fn same_device_as<O: ParentDevice>(&self, other: &O) -> Result<(), DeviceError> {
140        if Arc::ptr_eq(self.device(), other.device()) {
141            Ok(())
142        } else {
143            Err(DeviceError::DeviceMismatch(Box::new(DeviceMismatch {
144                res: self.error_ident(),
145                res_device: self.device().error_ident(),
146                target: Some(other.error_ident()),
147                target_device: other.device().error_ident(),
148            })))
149        }
150    }
151
152    fn same_device(&self, device: &Device) -> Result<(), DeviceError> {
153        if core::ptr::eq(&**self.device(), device) {
154            Ok(())
155        } else {
156            Err(DeviceError::DeviceMismatch(Box::new(DeviceMismatch {
157                res: self.error_ident(),
158                res_device: self.device().error_ident(),
159                target: None,
160                target_device: device.error_ident(),
161            })))
162        }
163    }
164}
165
166#[macro_export]
167macro_rules! impl_parent_device {
168    ($ty:ident) => {
169        impl $crate::resource::ParentDevice for $ty {
170            fn device(&self) -> &Arc<Device> {
171                &self.device
172            }
173        }
174    };
175}
176
177/// Allow access to the hal resource as guarded by the `SnatchGuard`.
178pub trait RawResourceAccess: ParentDevice {
179    type DynResource: hal::DynResource + ?Sized;
180
181    /// Get access to the raw resource if it is not destroyed.
182    ///
183    /// Returns `None` if the resource has been destroyed. This method
184    /// does not allocate in either case.
185    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource>;
186
187    /// Get access to the raw resource if it is not destroyed.
188    ///
189    /// Returns a full error if the resource has been destroyed. This
190    /// method allocates a label in the error case.
191    fn try_raw<'a>(
192        &'a self,
193        guard: &'a SnatchGuard,
194    ) -> Result<&'a Self::DynResource, DestroyedResourceError> {
195        self.raw(guard)
196            .ok_or_else(|| DestroyedResourceError(self.error_ident()))
197    }
198}
199
200pub trait ResourceType {
201    const TYPE: &'static str;
202}
203
204#[macro_export]
205macro_rules! impl_resource_type {
206    ($ty:ident) => {
207        impl $crate::resource::ResourceType for $ty {
208            const TYPE: &'static str = stringify!($ty);
209        }
210    };
211}
212
213pub trait Labeled: ResourceType {
214    /// Returns a string identifying this resource for logging and errors.
215    ///
216    /// It may be a user-provided string or it may be a placeholder from wgpu.
217    ///
218    /// It is non-empty unless the user-provided string was empty.
219    fn label(&self) -> &str;
220
221    fn error_ident(&self) -> ResourceErrorIdent {
222        ResourceErrorIdent {
223            r#type: Cow::Borrowed(Self::TYPE),
224            label: self.label().to_owned(),
225        }
226    }
227}
228
229#[macro_export]
230macro_rules! impl_labeled {
231    ($ty:ident) => {
232        impl $crate::resource::Labeled for $ty {
233            fn label(&self) -> &str {
234                &self.label
235            }
236        }
237    };
238}
239
240pub(crate) trait Trackable {
241    fn tracker_index(&self) -> TrackerIndex;
242}
243
244#[macro_export]
245macro_rules! impl_trackable {
246    ($ty:ident) => {
247        impl $crate::resource::Trackable for $ty {
248            fn tracker_index(&self) -> $crate::track::TrackerIndex {
249                self.tracking_data.tracker_index()
250            }
251        }
252    };
253}
254
255#[derive(Debug)]
256pub(crate) enum BufferMapState {
257    /// Mapped at creation.
258    Init { staging_buffer: StagingBuffer },
259    /// Waiting for GPU to be done before mapping
260    Waiting(BufferPendingMapping),
261    /// Mapped
262    Active {
263        mapping: hal::BufferMapping,
264        range: hal::MemoryRange,
265        host: MapMode,
266    },
267    /// Not mapped
268    Idle,
269}
270
271#[cfg(send_sync)]
272unsafe impl Send for BufferMapState {}
273#[cfg(send_sync)]
274unsafe impl Sync for BufferMapState {}
275
276/// Represents a mapped range in the buffer.
277///
278/// While returned [`BufferMapping`] is alive, [`Buffer::destroy`] and [`Buffer::unmap`] calls will block until [`BufferMapping`] is dropped.
279#[derive(Debug)]
280pub struct BufferMapping {
281    ptr: NonNull<u8>,
282    len: u64,
283    mode: MapMode,
284    // guard needs to be dropped before the lock
285    _guard: wgpu_sync::RwLockReadGuard<'static, BufferMapState>,
286    _lock: Arc<RwLock<BufferMapState>>,
287}
288
289impl BufferMapping {
290    fn new(ptr: NonNull<u8>, len: u64, mode: MapMode, lock: Arc<RwLock<BufferMapState>>) -> Self {
291        // SAFETY: We want to bypass the lock ranking system here,
292        // because the lock is exposed to users.
293        let guard = unsafe { lock.underlying() }.read();
294        Self {
295            ptr,
296            len,
297            mode,
298            // SAFETY: Guard is tied to the lifetime of the lock,
299            // and it will be dropped before the lock.
300            _guard: unsafe {
301                mem::transmute::<
302                    wgpu_sync::RwLockReadGuard<'_, BufferMapState>,
303                    wgpu_sync::RwLockReadGuard<'static, BufferMapState>,
304                >(guard)
305            },
306            _lock: lock,
307        }
308    }
309
310    /// ### How to safely use the pointer
311    ///
312    /// - Pointer is only accessed for the length returned by [`BufferMapping::len`].
313    /// - Pointer is only accessed while [`BufferMapping`] is alive.
314    /// - Reading is allowed if [`BufferMapping::mode`] is [`MapMode::Read`] (buffer has [`wgt::BufferUsages::MAP_READ`] set).
315    /// - Writing is allowed if [`BufferMapping::mode`] is [`MapMode::Write`] (buffer has [`wgt::BufferUsages::MAP_WRITE`] set).
316    /// - Atomics must not be used through the pointer since read-modify-write operations may not function on write-combining memory.
317    ///   This also means that it's not safe to create mutable rust references from this pointer since rust's memory model requires atomic operations to work.
318    pub fn ptr(&self) -> NonNull<u8> {
319        self.ptr
320    }
321
322    pub fn mode(&self) -> MapMode {
323        self.mode
324    }
325
326    #[expect(clippy::len_without_is_empty)]
327    pub fn len(&self) -> u64 {
328        self.len
329    }
330
331    /// Returns a read-only slice to the mapped buffer.
332    /// [`BufferMapping::mode`] must be [`MapMode::Read`] (buffer has [`wgt::BufferUsages::MAP_READ`] set) otherwise it will panic.
333    pub fn read_slice(&self) -> &[u8] {
334        assert!(self.mode == MapMode::Read);
335        unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len as usize) }
336    }
337
338    /// Returns a write-only slice to the mapped buffer.
339    /// [`BufferMapping::mode`] must be [`MapMode::Write`] (buffer has [`wgt::BufferUsages::MAP_WRITE`] set) otherwise it will panic.
340    pub fn write_slice(&'_ self) -> WriteOnly<'_, [u8]> {
341        assert!(self.mode == MapMode::Write);
342        unsafe { WriteOnly::new(NonNull::slice_from_raw_parts(self.ptr, self.len as usize)) }
343    }
344}
345
346#[cfg(send_sync)]
347pub type BufferMapCallback = Box<dyn FnOnce(BufferAccessResult) + Send + 'static>;
348#[cfg(not(send_sync))]
349pub type BufferMapCallback = Box<dyn FnOnce(BufferAccessResult) + 'static>;
350
351#[derive(Clone, Debug, Error)]
352#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
353#[non_exhaustive]
354pub enum BufferAccessError {
355    #[error(transparent)]
356    Device(#[from] DeviceError),
357    #[error("Buffer map failed")]
358    Failed,
359    #[error(transparent)]
360    DestroyedResource(#[from] DestroyedResourceError),
361    #[error("Buffer is already mapped")]
362    AlreadyMapped,
363    #[error("Buffer map is pending")]
364    MapAlreadyPending,
365    #[error(transparent)]
366    MissingBufferUsage(#[from] MissingBufferUsageError),
367    #[error("Buffer is not mapped")]
368    NotMapped,
369    #[error(
370        "Buffer map range must start aligned to `MAP_ALIGNMENT` and end to `COPY_BUFFER_ALIGNMENT`"
371    )]
372    UnalignedRange,
373    #[error("Buffer offset invalid: offset {offset} must be multiple of 8")]
374    UnalignedOffset { offset: wgt::BufferAddress },
375    #[error("Buffer range size invalid: range_size {range_size} must be multiple of 4")]
376    UnalignedRangeSize { range_size: wgt::BufferAddress },
377    #[error("Buffer access out of bounds: index {index} would underrun the buffer (limit: {min})")]
378    OutOfBoundsStartOffsetUnderrun {
379        index: wgt::BufferAddress,
380        min: wgt::BufferAddress,
381    },
382    #[error(
383        "Buffer access out of bounds: start offset {index} would overrun the buffer (limit: {max})"
384    )]
385    OutOfBoundsStartOffsetOverrun {
386        index: wgt::BufferAddress,
387        max: wgt::BufferAddress,
388    },
389    #[error(
390        "Buffer access out of bounds: start offset {index} + size {size} would overrun the buffer (limit: {max})"
391    )]
392    OutOfBoundsEndOffsetOverrun {
393        index: wgt::BufferAddress,
394        size: wgt::BufferAddress,
395        max: wgt::BufferAddress,
396    },
397    #[error("Buffer map aborted")]
398    MapAborted,
399    #[error(transparent)]
400    InvalidResource(#[from] InvalidResourceError),
401    #[error("Map start offset ({offset}) is out-of-bounds for buffer of size {buffer_size}")]
402    MapStartOffsetOverrun {
403        offset: wgt::BufferAddress,
404        buffer_size: wgt::BufferAddress,
405    },
406    #[error(
407        "Map end offset (start at {} + size of {}) is out-of-bounds for buffer of size {}",
408        offset,
409        size,
410        buffer_size
411    )]
412    MapEndOffsetOverrun {
413        offset: wgt::BufferAddress,
414        size: wgt::BufferAddress,
415        buffer_size: wgt::BufferAddress,
416    },
417    #[error(transparent)]
418    InvalidMapMode(#[from] BadMapMode),
419}
420
421#[derive(Clone, Debug, Error)]
422#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
423#[error("Invalid map mode: {0:?}, exactly one of READ or WRITE map mode must be set")]
424pub struct BadMapMode(MapModeFlags);
425
426bitflags::bitflags! {
427    /// Corresponds to [WebGPU `GPUMapModeFlags`](https://gpuweb.github.io/gpuweb/#dictdef-gpumapmodeflags).
428    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
429    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
430    pub struct MapModeFlags: u32 {
431        const READ = 0x0001;
432        const WRITE = 0x0002;
433    }
434}
435
436impl From<core::convert::Infallible> for BadMapMode {
437    fn from(_: core::convert::Infallible) -> Self {
438        unreachable!()
439    }
440}
441
442impl TryFrom<MapModeFlags> for MapMode {
443    type Error = BadMapMode;
444
445    fn try_from(mode: MapModeFlags) -> Result<Self, Self::Error> {
446        match mode {
447            m if m == MapModeFlags::READ => Ok(MapMode::Read),
448            m if m == MapModeFlags::WRITE => Ok(MapMode::Write),
449            m => Err(BadMapMode(m)),
450        }
451    }
452}
453
454impl WebGpuError for BufferAccessError {
455    fn webgpu_error_type(&self) -> ErrorType {
456        match self {
457            Self::Device(e) => e.webgpu_error_type(),
458            Self::InvalidResource(e) => e.webgpu_error_type(),
459            Self::DestroyedResource(e) => e.webgpu_error_type(),
460
461            Self::Failed
462            | Self::AlreadyMapped
463            | Self::MapAlreadyPending
464            | Self::MissingBufferUsage(_)
465            | Self::NotMapped
466            | Self::UnalignedRange
467            | Self::UnalignedOffset { .. }
468            | Self::UnalignedRangeSize { .. }
469            | Self::OutOfBoundsStartOffsetUnderrun { .. }
470            | Self::OutOfBoundsStartOffsetOverrun { .. }
471            | Self::OutOfBoundsEndOffsetOverrun { .. }
472            | Self::MapAborted
473            | Self::MapStartOffsetOverrun { .. }
474            | Self::MapEndOffsetOverrun { .. }
475            | Self::InvalidMapMode(_) => ErrorType::Validation,
476        }
477    }
478}
479
480#[derive(Clone, Debug, Error)]
481#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
482#[error("Usage flags {actual:?} of {res} do not contain required usage flags {expected:?}")]
483pub struct MissingBufferUsageError {
484    pub(crate) res: ResourceErrorIdent,
485    pub(crate) actual: wgt::BufferUsages,
486    pub(crate) expected: wgt::BufferUsages,
487}
488
489impl WebGpuError for MissingBufferUsageError {
490    fn webgpu_error_type(&self) -> ErrorType {
491        ErrorType::Validation
492    }
493}
494
495#[derive(Clone, Debug, Error)]
496#[error("Usage flags {actual:?} of {res} do not contain required usage flags {expected:?}")]
497pub struct MissingTextureUsageError {
498    pub(crate) res: ResourceErrorIdent,
499    pub(crate) actual: wgt::TextureUsages,
500    pub(crate) expected: wgt::TextureUsages,
501}
502
503impl WebGpuError for MissingTextureUsageError {
504    fn webgpu_error_type(&self) -> ErrorType {
505        ErrorType::Validation
506    }
507}
508
509#[derive(Clone, Debug, Error)]
510#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
511#[error("{0} has been destroyed")]
512pub struct DestroyedResourceError(pub ResourceErrorIdent);
513
514impl WebGpuError for DestroyedResourceError {
515    fn webgpu_error_type(&self) -> ErrorType {
516        ErrorType::Validation
517    }
518}
519
520#[derive(Clone, Debug, Error)]
521#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
522#[error("{0} is invalid")]
523pub struct InvalidResourceError(pub ResourceErrorIdent);
524
525impl WebGpuError for InvalidResourceError {
526    fn webgpu_error_type(&self) -> ErrorType {
527        ErrorType::Validation
528    }
529}
530
531pub type BufferAccessResult = Result<MapMode, BufferAccessError>;
532
533pub(crate) struct BufferPendingMapping {
534    pub(crate) range: Range<wgt::BufferAddress>,
535    pub(crate) callback: Option<BufferMapCallback>,
536    pub(crate) mode: MapMode,
537    // hold the parent alive while the mapping is active
538    pub(crate) _parent_buffer: Arc<Buffer>,
539}
540
541impl fmt::Debug for BufferPendingMapping {
542    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543        f.debug_struct("BufferPendingMapping")
544            .field("range", &self.range)
545            .field("callback", &self.callback.as_ref().map(|_| "?"))
546            .field("mode", &self.mode)
547            .field("_parent_buffer", &self._parent_buffer)
548            .finish()
549    }
550}
551
552pub type BufferDescriptor<'a> = wgt::BufferDescriptor<Label<'a>>;
553
554#[derive(Debug)]
555pub(crate) struct BufferState {
556    pub(crate) raw: Snatchable<Box<dyn hal::DynBuffer>>,
557}
558
559#[derive(Debug)]
560pub struct Buffer {
561    pub(crate) state: ResourceState<BufferState>,
562    pub(crate) device: Arc<Device>,
563    pub(crate) usage: wgt::BufferUsages,
564    pub(crate) size: wgt::BufferAddress,
565    pub(crate) initialization_status: RwLock<BufferInitTracker>,
566    /// The `label` from the descriptor used to create the resource.
567    pub(crate) label: String,
568    pub(crate) tracking_data: TrackingData,
569    pub(crate) map_state: Arc<RwLock<BufferMapState>>,
570    // Bind groups that reference this buffer. May contain duplicates.
571    pub(crate) bind_groups: Mutex<WeakVec<BindGroup>>,
572    pub(crate) timestamp_normalization_bind_group: Snatchable<TimestampNormalizationBindGroup>,
573    pub(crate) indirect_validation_bind_groups: Snatchable<crate::indirect_validation::BindGroups>,
574}
575
576impl Drop for Buffer {
577    #[allow(trivial_casts)]
578    fn drop(&mut self) {
579        profiling::scope!("Buffer::drop");
580        api_log!("Buffer::drop {:?}", self as *const _);
581        #[cfg(feature = "trace")]
582        if let Some(t) = self.device.trace.lock().as_mut() {
583            t.add(trace::Action::DropBuffer(unsafe { trace::to_trace(self) }));
584        }
585
586        if let Some(raw) = self.timestamp_normalization_bind_group.take() {
587            raw.dispose(self.device.raw());
588        }
589
590        if let Some(raw) = self.indirect_validation_bind_groups.take() {
591            raw.dispose(self.device.raw());
592        }
593
594        let map_state = mem::replace(&mut *self.map_state.write(), BufferMapState::Idle);
595        let active_map = match map_state {
596            BufferMapState::Init { staging_buffer } => {
597                staging_buffer.dispose();
598                false
599            }
600            BufferMapState::Waiting(buffer_pending_mapping) => {
601                if buffer_pending_mapping.callback.is_some() {
602                    let result = Err(BufferAccessError::DestroyedResource(
603                        DestroyedResourceError(self.error_ident()),
604                    ));
605                    self.device
606                        .deferred_buffer_map_pending_closures
607                        .push((buffer_pending_mapping.callback, result));
608                }
609                false
610            }
611            BufferMapState::Active { .. } => true,
612            BufferMapState::Idle => false,
613        };
614
615        let ResourceState::Valid(state) = &mut self.state else {
616            return;
617        };
618
619        if let Some(raw) = state.raw.take() {
620            if active_map {
621                unsafe { self.device.raw().unmap_buffer(raw.as_ref()) }
622            }
623            resource_log!("Destroy raw {}", self.error_ident());
624            unsafe {
625                self.device.raw().destroy_buffer(raw);
626            }
627        }
628    }
629}
630
631impl RawResourceAccess for Buffer {
632    type DynResource = dyn hal::DynBuffer;
633
634    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
635        self.state()
636            .ok()
637            .and_then(|state| state.raw.get(guard).map(|b| b.as_ref()))
638    }
639}
640
641impl Buffer {
642    pub(crate) fn check_destroyed(
643        &self,
644        guard: &SnatchGuard,
645    ) -> Result<(), DestroyedResourceError> {
646        let ResourceState::Valid(state) = &self.state else {
647            return Ok(());
648        };
649        state
650            .raw
651            .get(guard)
652            .map(|_| ())
653            .ok_or_else(|| DestroyedResourceError(self.error_ident()))
654    }
655
656    /// Checks that the given buffer usage contains the required buffer usage,
657    /// returns an error otherwise.
658    pub(crate) fn check_usage(
659        &self,
660        expected: wgt::BufferUsages,
661    ) -> Result<(), MissingBufferUsageError> {
662        if self.usage.contains(expected) {
663            Ok(())
664        } else {
665            Err(MissingBufferUsageError {
666                res: self.error_ident(),
667                actual: self.usage,
668                expected,
669            })
670        }
671    }
672
673    pub(crate) fn state(&self) -> Result<&BufferState, InvalidResourceError> {
674        match &self.state {
675            ResourceState::Valid(state) => Ok(state),
676            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
677        }
678    }
679
680    pub fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
681        self.state().map(|_| ())
682    }
683
684    pub fn invalid(device: Arc<Device>, desc: &BufferDescriptor) -> Arc<Self> {
685        Arc::new(Buffer {
686            state: ResourceState::Invalid,
687            usage: desc.usage,
688            size: desc.size,
689            initialization_status: RwLock::new(
690                rank::BUFFER_INITIALIZATION_STATUS,
691                BufferInitTracker::new(0),
692            ),
693            map_state: Arc::new(RwLock::new(rank::BUFFER_MAP_STATE, BufferMapState::Idle)),
694            label: desc.label.to_string(),
695            tracking_data: TrackingData::new(device.tracker_indices.buffers.clone()),
696            bind_groups: Mutex::new(rank::BUFFER_BIND_GROUPS, WeakVec::new()),
697            timestamp_normalization_bind_group: Snatchable::empty(),
698            indirect_validation_bind_groups: Snatchable::empty(),
699            device,
700        })
701    }
702
703    /// Resolve the size of a binding for buffer with `offset` and `size`.
704    ///
705    /// If `size` is `None`, then the remainder of the buffer starting from
706    /// `offset` is used.
707    ///
708    /// If the binding would overflow the buffer, then an error is returned.
709    ///
710    /// `S` is `wgt::BufferSize` (`NonZeroU64`) when called from [`Buffer::binding`]
711    /// for a storage or uniform buffer binding. `S` is `wgt::BufferAddress` (`u64`)
712    /// when called from `resolve_vertex_or_index_binding_range` for a vertex or
713    /// index buffer binding.
714    fn resolve_binding_size<S: Copy + Into<wgt::BufferAddress> + TryFrom<wgt::BufferAddress>>(
715        &self,
716        offset: wgt::BufferAddress,
717        binding_size: Option<S>,
718    ) -> Result<S, BindingError> {
719        let buffer_size = self.size;
720
721        match binding_size {
722            Some(binding_size) => match offset.checked_add(binding_size.into()) {
723                Some(end) if end <= buffer_size => Ok(binding_size),
724                _ => Err(BindingError::BindingRangeTooLarge {
725                    buffer: self.error_ident(),
726                    offset,
727                    binding_size: binding_size.into(),
728                    buffer_size,
729                }),
730            },
731            None => buffer_size
732                .checked_sub(offset)
733                .and_then(|remaining| S::try_from(remaining).ok())
734                .ok_or_else(|| {
735                    if offset <= buffer_size {
736                        debug_assert_eq!(offset, buffer_size);
737                        BindingError::BindingOffsetEqualsSize {
738                            buffer: self.error_ident(),
739                            offset,
740                            buffer_size,
741                        }
742                    } else {
743                        BindingError::BindingOffsetTooLarge {
744                            buffer: self.error_ident(),
745                            offset,
746                            buffer_size,
747                        }
748                    }
749                }),
750        }
751    }
752
753    /// Resolve the binding range for a vertex or index buffer.
754    ///
755    /// This function is for vertex and index buffer bindings, which WebGPU
756    /// allows to have zero size. For storage and uniform buffer bindings,
757    /// which must have non-zero size, use [`Buffer::binding`].
758    ///
759    /// Returns an error if the binding would overflow the buffer.
760    pub fn resolve_vertex_or_index_binding_range(
761        &self,
762        offset: wgt::BufferAddress,
763        size: Option<wgt::BufferAddress>,
764    ) -> Result<Range<wgt::BufferAddress>, BindingError> {
765        let resolved_size = self.resolve_binding_size(offset, size)?;
766        if resolved_size != 0 {
767            Ok(offset..offset + resolved_size)
768        } else {
769            // Relocate zero-size binding to end of buffer, because hal does not support
770            // zero-size bindings (ignores end offsets). `create_buffer` must have
771            // ensured sufficient padding.
772            const _: () = {
773                assert!(wgt::VERTEX_ALIGNMENT == wgt::COPY_BUFFER_ALIGNMENT);
774            };
775            let target = align_to(self.size, wgt::VERTEX_ALIGNMENT);
776            Ok(target..target)
777        }
778    }
779
780    /// Create a new [`hal::BufferBinding`] for the buffer with `offset` and
781    /// `binding_size`.
782    ///
783    /// If `binding_size` is `None`, then the remainder of the buffer starting
784    /// from `offset` is used.
785    ///
786    /// Returns an error if the binding would overflow the buffer.
787    ///
788    /// This function is for storage and uniform buffer bindings, which must have
789    /// non-zero size. For vertex and index buffer bindings, which may have zero
790    /// size, use [`Buffer::resolve_vertex_or_index_binding_range`].
791    pub fn binding<'a>(
792        &'a self,
793        offset: wgt::BufferAddress,
794        binding_size: Option<wgt::BufferSize>,
795        snatch_guard: &'a SnatchGuard,
796    ) -> Result<hal::BufferBinding<'a, dyn hal::DynBuffer, wgt::BufferSize>, BindingError> {
797        let buf_raw = self.try_raw(snatch_guard)?;
798        let resolved_size = self.resolve_binding_size(offset, binding_size)?;
799        // SAFETY: The offset and size passed to hal::BufferBinding::new_unchecked must
800        // define a binding contained within the buffer.
801        Ok(hal::BufferBinding::new_unchecked(
802            buf_raw,
803            offset,
804            resolved_size,
805        ))
806    }
807
808    /// Schedule buffer mapping.
809    ///
810    /// `op.callback` is guaranteed to be called, regardless of the outcome.
811    pub fn map_async<M>(
812        self: &Arc<Self>,
813        mode: M,
814        offset: wgt::BufferAddress,
815        size: Option<wgt::BufferAddress>,
816        callback: Option<BufferMapCallback>,
817    ) -> Option<SubmissionIndex>
818    where
819        M: fmt::Debug + TryInto<MapMode> + Copy,
820        M::Error: Into<BadMapMode>,
821    {
822        profiling::scope!("Buffer::map_async");
823        api_log!(
824            "Buffer::map_async {:?} mode {mode:?} offset {offset:?} size {size:?}",
825            Arc::as_ptr(self)
826        );
827
828        self.try_map_async(mode, offset, size, callback)
829            .map_err(|(mut callback, err)| {
830                self.device
831                    .handle_error(err.clone(), Some(&self.label), "Buffer::map_async");
832                if let Some(callback) = callback.take() {
833                    callback(Err(err));
834                }
835            })
836            .ok()
837    }
838
839    /// Try to schedule buffer mapping.
840    ///
841    /// The outcome of this function is one of the following:
842    /// - If there is a queue, and nothing pending in the queue that uses the
843    ///   buffer in question, the buffer is added to `Queue::ready_to_map`, and
844    ///   will be mapped the next time `Device::maintain` is called. The
845    ///   queue assumes responsibility for calling the callback, and this
846    ///   function returns `Ok(0)`, but the buffer has not yet been mapped.
847    /// - If there is a queue, and something is pending in the queue that uses
848    ///   the buffer in question, the buffer is scheduled for mapping after that
849    ///   submission completes. The queue assumes responsibility for calling the
850    ///   callback, and this function returns `Ok(index)` with the index of the
851    ///   submission that must complete. The buffer has not yet been mapped.
852    /// - If there is no queue, the buffer is mapped and the callback is called
853    ///   immediately. The return value is `Ok(0)`.
854    /// - Regardless of the queue state, if there is an error that terminates
855    ///   the buffer mapping attempt, this function returns the callback along
856    ///   with the error, and the caller is responsible for calling the
857    ///   callback.
858    ///
859    /// A return value of `Ok(0)` means that mapping does not need to wait on the queue, but
860    /// it does not mean that the buffer has already been mapped.
861    fn try_map_async<M>(
862        self: &Arc<Self>,
863        mode: M,
864        offset: wgt::BufferAddress,
865        size: Option<wgt::BufferAddress>,
866        callback: Option<BufferMapCallback>,
867    ) -> Result<SubmissionIndex, (Option<BufferMapCallback>, BufferAccessError)>
868    where
869        M: fmt::Debug + TryInto<MapMode> + Copy,
870        M::Error: Into<BadMapMode>,
871    {
872        let range_size = if let Some(size) = size {
873            size
874        } else {
875            self.size.saturating_sub(offset)
876        };
877
878        let device = &self.device;
879        if let Err(e) = device.check_is_valid() {
880            return Err((callback, e.into()));
881        }
882
883        if let Err(e) = self.check_is_valid() {
884            return Err((callback, e.into()));
885        }
886
887        if !offset.is_multiple_of(wgt::MAP_ALIGNMENT) {
888            return Err((callback, BufferAccessError::UnalignedOffset { offset }));
889        }
890        if !range_size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
891            return Err((
892                callback,
893                BufferAccessError::UnalignedRangeSize { range_size },
894            ));
895        }
896
897        if offset > self.size {
898            return Err((
899                callback,
900                BufferAccessError::MapStartOffsetOverrun {
901                    offset,
902                    buffer_size: self.size,
903                },
904            ));
905        }
906        // NOTE: Should never underflow because of our earlier check.
907        if range_size > self.size - offset {
908            return Err((
909                callback,
910                BufferAccessError::MapEndOffsetOverrun {
911                    offset,
912                    size: range_size,
913                    buffer_size: self.size,
914                },
915            ));
916        }
917        let end_offset = offset + range_size;
918
919        if !offset.is_multiple_of(wgt::MAP_ALIGNMENT)
920            || !end_offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT)
921        {
922            return Err((callback, BufferAccessError::UnalignedRange));
923        }
924
925        let mode = match mode.try_into() {
926            Ok(mode) => mode,
927            Err(e) => return Err((callback, e.into().into())),
928        };
929
930        let (pub_usage, internal_use) = match mode {
931            MapMode::Read => (wgt::BufferUsages::MAP_READ, wgt::BufferUses::MAP_READ),
932            MapMode::Write => (wgt::BufferUsages::MAP_WRITE, wgt::BufferUses::MAP_WRITE),
933        };
934
935        if let Err(e) = self.check_usage(pub_usage) {
936            return Err((callback, e.into()));
937        }
938
939        let submit_index = {
940            let snatch_guard = device.snatchable_lock.read();
941            if let Err(e) = self.check_destroyed(&snatch_guard) {
942                return Err((callback, e.into()));
943            }
944
945            {
946                let map_state = &mut *self.map_state.write();
947                *map_state = match *map_state {
948                    BufferMapState::Init { .. } | BufferMapState::Active { .. } => {
949                        return Err((callback, BufferAccessError::AlreadyMapped));
950                    }
951                    BufferMapState::Waiting(_) => {
952                        return Err((callback, BufferAccessError::MapAlreadyPending));
953                    }
954                    BufferMapState::Idle => BufferMapState::Waiting(BufferPendingMapping {
955                        range: offset..end_offset,
956                        mode,
957                        callback,
958                        _parent_buffer: self.clone(),
959                    }),
960                };
961            }
962
963            if let Some(queue) = device.get_queue().as_ref() {
964                match queue.flush_writes_for_buffer(self, snatch_guard) {
965                    Err(err) => {
966                        let state =
967                            mem::replace(&mut *self.map_state.write(), BufferMapState::Idle);
968                        let BufferMapState::Waiting(BufferPendingMapping { callback, .. }) = state
969                        else {
970                            unreachable!();
971                        };
972                        return Err((callback, err));
973                    }
974                    Ok(()) => {
975                        // Schedule the buffer map in the  lifetime tracker.
976                        //
977                        // This call searches for use of the buffer by pending submissions.
978                        // If we just flushed pending writes, that search is redundant; we
979                        // already know that mapping needs to wait for the latest submission
980                        // and could implement a special case to directly attach it to that
981                        // submission. However, the queue is searched in reverse, so finding
982                        // that the buffer is used by the latest submission will be fast.
983                        Some(queue.lock_life().map(self).unwrap_or(0))
984                    }
985                }
986            } else {
987                None
988            }
989        };
990
991        // At this point, `submit_index` is:
992        // - `Some(index)`, if there is a submission the mapping operation must wait for.
993        // - `Some(0)`, if we have a queue and there is no submission to wait for.
994        // - `None`, if we don't have a queue.
995        //
996        // TODO(https://github.com/gfx-rs/wgpu/issues/9306): we are ignoring the transition
997        // here, I think we need to add a barrier at the end of the submission
998        device
999            .trackers
1000            .lock()
1001            .buffers
1002            .set_single(self, internal_use);
1003
1004        if let Some(index) = submit_index {
1005            Ok(index)
1006        } else {
1007            // We don't have a queue, so go ahead and map the buffer.
1008            // We can safely unwrap below since we just set the `map_state` to `BufferMapState::Waiting`.
1009            let (mut callback, status) = self.map(&device.snatchable_lock.read()).unwrap();
1010            if let Some(callback) = callback.take() {
1011                callback(status);
1012            }
1013            Ok(0)
1014        }
1015    }
1016
1017    /// Get a guarded pointer to the mapped range of the buffer.
1018    ///
1019    /// While returned [`BufferMapping`] is alive,
1020    /// [`Buffer::destroy`] and [`Buffer::unmap`] calls will block until [`BufferMapping`] is dropped.
1021    pub fn get_mapped_range(
1022        self: &Arc<Self>,
1023        offset: wgt::BufferAddress,
1024        size: Option<wgt::BufferAddress>,
1025    ) -> Result<BufferMapping, BufferAccessError> {
1026        profiling::scope!("Buffer::get_mapped_range");
1027        api_log!(
1028            "Buffer::get_mapped_range {:?} offset {offset:?} size {size:?}",
1029            Arc::as_ptr(self)
1030        );
1031
1032        self.check_is_valid()?;
1033        {
1034            let snatch_guard = self.device.snatchable_lock.read();
1035            self.check_destroyed(&snatch_guard)?;
1036        }
1037
1038        let range_size = if let Some(size) = size {
1039            size
1040        } else {
1041            self.size.saturating_sub(offset)
1042        };
1043
1044        if !offset.is_multiple_of(wgt::MAP_ALIGNMENT) {
1045            return Err(BufferAccessError::UnalignedOffset { offset });
1046        }
1047        if !range_size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
1048            return Err(BufferAccessError::UnalignedRangeSize { range_size });
1049        }
1050        let map_state = &*self.map_state.read();
1051        match *map_state {
1052            BufferMapState::Init { ref staging_buffer } => {
1053                if offset > self.size {
1054                    return Err(BufferAccessError::MapStartOffsetOverrun {
1055                        offset,
1056                        buffer_size: self.size,
1057                    });
1058                }
1059                // NOTE: Should never underflow because of our earlier check.
1060                if range_size > self.size - offset {
1061                    return Err(BufferAccessError::MapEndOffsetOverrun {
1062                        offset,
1063                        size: range_size,
1064                        buffer_size: self.size,
1065                    });
1066                }
1067                let ptr = unsafe { staging_buffer.ptr() };
1068                let ptr = unsafe { NonNull::new_unchecked(ptr.as_ptr().offset(offset as isize)) };
1069                Ok(BufferMapping::new(
1070                    ptr,
1071                    range_size,
1072                    MapMode::Write,
1073                    self.map_state.clone(),
1074                ))
1075            }
1076            BufferMapState::Active {
1077                ref mapping,
1078                ref range,
1079                ref host,
1080            } => {
1081                if offset > range.end {
1082                    return Err(BufferAccessError::OutOfBoundsStartOffsetOverrun {
1083                        index: offset,
1084                        max: range.end,
1085                    });
1086                }
1087                if offset < range.start {
1088                    return Err(BufferAccessError::OutOfBoundsStartOffsetUnderrun {
1089                        index: offset,
1090                        min: range.start,
1091                    });
1092                }
1093                if range_size > range.end - offset {
1094                    return Err(BufferAccessError::OutOfBoundsEndOffsetOverrun {
1095                        index: offset,
1096                        size: range_size,
1097                        max: range.end,
1098                    });
1099                }
1100                // ptr points to the beginning of the range we mapped in map_async
1101                // rather than the beginning of the buffer.
1102                let relative_offset = (offset - range.start) as isize;
1103                unsafe {
1104                    Ok(BufferMapping::new(
1105                        NonNull::new_unchecked(mapping.ptr.as_ptr().offset(relative_offset)),
1106                        range_size,
1107                        *host,
1108                        self.map_state.clone(),
1109                    ))
1110                }
1111            }
1112            BufferMapState::Idle | BufferMapState::Waiting(_) => Err(BufferAccessError::NotMapped),
1113        }
1114    }
1115    /// This function returns [`None`] only if [`Self::map_state`] is not [`BufferMapState::Waiting`].
1116    /// Other errors are returned within `BufferMapPendingClosure`.
1117    #[must_use]
1118    pub(crate) fn map(&self, snatch_guard: &SnatchGuard) -> Option<BufferMapPendingClosure> {
1119        // Hold the lock on `map_state` until we have updated it with the
1120        // outcome of the mapping, to prevent concurrent activity from
1121        // observing an intermediate state.
1122        //
1123        // Unfortunately this does mean that we hold the guard across
1124        // `crate::device::map_buffer` and the associated call to
1125        // `handle_hal_error`, which may invoke a device loss callback.
1126        // See <https://github.com/gfx-rs/wgpu/issues/10031>.
1127        let mut map_state = self.map_state.write();
1128        let pending_mapping = match mem::replace(&mut *map_state, BufferMapState::Idle) {
1129            BufferMapState::Waiting(pending_mapping) => pending_mapping,
1130            // Mapping cancelled
1131            BufferMapState::Idle => return None,
1132            // Mapping queued at least twice by map -> unmap -> map
1133            // and was already successfully mapped below
1134            mapping @ BufferMapState::Active { .. } => {
1135                *map_state = mapping;
1136                return None;
1137            }
1138            _ => panic!("No pending mapping."),
1139        };
1140        let status = if let Err(error) = self.device.check_is_valid() {
1141            Err(error.into())
1142        } else if pending_mapping.range.start != pending_mapping.range.end {
1143            let host = pending_mapping.mode;
1144            let size = pending_mapping.range.end - pending_mapping.range.start;
1145            match crate::device::map_buffer(
1146                self,
1147                pending_mapping.range.start,
1148                size,
1149                host,
1150                snatch_guard,
1151            ) {
1152                Ok(mapping) => {
1153                    *map_state = BufferMapState::Active {
1154                        mapping,
1155                        range: pending_mapping.range.clone(),
1156                        host,
1157                    };
1158                    Ok(host)
1159                }
1160                Err(e) => Err(e),
1161            }
1162        } else {
1163            *map_state = BufferMapState::Active {
1164                mapping: hal::BufferMapping {
1165                    ptr: NonNull::dangling(),
1166                    is_coherent: true,
1167                },
1168                range: pending_mapping.range,
1169                host: pending_mapping.mode,
1170            };
1171            Ok(pending_mapping.mode)
1172        };
1173        Some((pending_mapping.callback, status))
1174    }
1175
1176    // Note: This must not be called while holding a lock.
1177    pub fn unmap(self: &Arc<Self>) {
1178        profiling::scope!("unmap", "Buffer");
1179        api_log!("Buffer::unmap {:?}", Arc::as_ptr(self));
1180        if let Some((mut callback, status)) = self.unmap_inner() {
1181            if let Some(callback) = callback.take() {
1182                callback(status);
1183            }
1184        }
1185    }
1186
1187    /// Per the WebGPU spec, unmap does not raise any errors
1188    /// it just resolves any pending map_async calls with a MapAborted error.
1189    /// It is okay to ignore errors because:
1190    /// - if the buffer or device was invalid from the start it couldn't have been mapped via `map_async` anyway (no callback to resolve)
1191    /// - if the device becomes invalid it calls the callback in `poll`/`maintain`
1192    /// - if the buffer was destroyed (via `Buffer::destroy`) it was first unmapped
1193    ///
1194    /// <https://gpuweb.github.io/gpuweb/#dom-gpubuffer-unmap>
1195    fn unmap_inner(self: &Arc<Self>) -> Option<BufferMapPendingClosure> {
1196        let device = &self.device;
1197        let snatch_guard = device.snatchable_lock.read();
1198        // We can stop here if the buffer is invalid or destroyed because:
1199        // - if the device was invalid from the start it couldn't have been mapped via `map_async` anyway
1200        // - if the buffer was destroyed (via `Buffer::destroy`) it was first unmapped
1201        let raw_buf = self.try_raw(&snatch_guard).ok()?;
1202        let map_state = mem::replace(&mut *self.map_state.write(), BufferMapState::Idle);
1203        match map_state {
1204            BufferMapState::Init { staging_buffer } => {
1205                if !self.device.is_valid() {
1206                    staging_buffer.dispose();
1207                    return None;
1208                }
1209                #[cfg(feature = "trace")]
1210                if let Some(ref mut trace) = *device.trace.lock() {
1211                    use crate::device::trace::{DataKind, IntoTrace};
1212
1213                    let data = trace.make_binary(DataKind::Bin, staging_buffer.get_data());
1214                    trace.add(trace::Action::WriteBuffer {
1215                        id: self.to_trace(),
1216                        data,
1217                        // NOTE: `self.size` here corresponds to `data`'s actual length.
1218                        offset: 0,
1219                        size: self.size,
1220                        queued: true,
1221                    });
1222                }
1223
1224                let staging_buffer = staging_buffer.flush();
1225
1226                if let Some(queue) = device.get_queue() {
1227                    // Copy the entire staging buffer, including any
1228                    // zero-initialized padding.
1229                    let region = Some(hal::BufferCopy {
1230                        src_offset: 0,
1231                        dst_offset: 0,
1232                        size: staging_buffer.size,
1233                    });
1234                    // The staging buffer's `MAP_WRITE` -> `COPY_SRC` transition
1235                    // is hoisted to the front of the batch by
1236                    // `PendingWrites::consume`, below.
1237                    let transition_dst = hal::BufferBarrier::<dyn hal::DynBuffer> {
1238                        buffer: raw_buf,
1239                        usage: hal::StateTransition {
1240                            from: wgt::BufferUses::empty(),
1241                            to: wgt::BufferUses::COPY_DST,
1242                        },
1243                    };
1244                    let mut pending_writes = queue.pending_writes.lock();
1245                    let encoder = pending_writes.activate();
1246                    unsafe {
1247                        encoder.transition_buffers(&[transition_dst]);
1248                        // Buffers allocate at least `COPY_BUFFER_ALIGNMENT` bytes, so
1249                        // there's always something to copy here.
1250                        encoder.copy_buffer_to_buffer(
1251                            staging_buffer.raw(),
1252                            raw_buf,
1253                            region.as_slice(),
1254                        );
1255                    }
1256                    pending_writes.consume(staging_buffer);
1257                    pending_writes.insert_buffer(self);
1258                }
1259                None
1260            }
1261            BufferMapState::Idle => None,
1262            BufferMapState::Waiting(pending) => {
1263                Some((pending.callback, Err(BufferAccessError::MapAborted)))
1264            }
1265            BufferMapState::Active {
1266                mapping,
1267                range,
1268                host,
1269            } => {
1270                self.device.check_is_valid().ok()?;
1271                if host == MapMode::Write {
1272                    #[cfg(feature = "trace")]
1273                    if let Some(ref mut trace) = *device.trace.lock() {
1274                        use crate::device::trace::{DataKind, IntoTrace};
1275
1276                        let size = range.end - range.start;
1277                        let data = trace.make_binary(DataKind::Bin, unsafe {
1278                            core::slice::from_raw_parts(mapping.ptr.as_ptr(), size as usize)
1279                        });
1280                        trace.add(trace::Action::WriteBuffer {
1281                            id: self.to_trace(),
1282                            data,
1283                            offset: range.start,
1284                            size,
1285                            queued: false,
1286                        });
1287                    }
1288                    if !mapping.is_coherent {
1289                        unsafe { device.raw().flush_mapped_ranges(raw_buf, &[range]) };
1290                    }
1291                }
1292                unsafe { device.raw().unmap_buffer(raw_buf) };
1293                None
1294            }
1295        }
1296    }
1297
1298    pub fn destroy(self: &Arc<Self>) {
1299        profiling::scope!("Buffer::destroy");
1300        api_log!("Buffer::destroy {:?}", Arc::as_ptr(self));
1301
1302        let device = &self.device;
1303
1304        #[cfg(feature = "trace")]
1305        if let Some(trace) = device.trace.lock().as_mut() {
1306            use crate::device::trace::IntoTrace;
1307            trace.add(trace::Action::DestroyBuffer(self.to_trace()));
1308        }
1309
1310        let ResourceState::Valid(state) = &self.state else {
1311            return;
1312        };
1313
1314        self.unmap();
1315
1316        let temp = {
1317            let mut snatch_guard = device.snatchable_lock.write();
1318
1319            let raw = match state.raw.snatch(&mut snatch_guard) {
1320                Some(raw) => raw,
1321                None => {
1322                    // Per spec, it is valid to call `destroy` multiple times.
1323                    return;
1324                }
1325            };
1326
1327            let timestamp_normalization_bind_group = self
1328                .timestamp_normalization_bind_group
1329                .snatch(&mut snatch_guard);
1330
1331            let indirect_validation_bind_groups = self
1332                .indirect_validation_bind_groups
1333                .snatch(&mut snatch_guard);
1334
1335            drop(snatch_guard);
1336
1337            let bind_groups = {
1338                let mut guard = self.bind_groups.lock();
1339                mem::take(&mut *guard)
1340            };
1341
1342            queue::TempResource::DestroyedBuffer(DestroyedBuffer {
1343                raw: ManuallyDrop::new(raw),
1344                device: Arc::clone(&self.device),
1345                label: self.label().to_owned(),
1346                bind_groups,
1347                timestamp_normalization_bind_group,
1348                indirect_validation_bind_groups,
1349            })
1350        };
1351
1352        let Some(queue) = device.get_queue() else {
1353            return;
1354        };
1355
1356        {
1357            let mut pending_writes = queue.pending_writes.lock();
1358            if pending_writes.contains_buffer(self) {
1359                pending_writes.consume_temp(temp);
1360                return;
1361            }
1362        }
1363
1364        let mut life_lock = queue.lock_life();
1365        let last_submit_index = life_lock.get_buffer_latest_submission_index(self);
1366        if let Some(last_submit_index) = last_submit_index {
1367            life_lock.schedule_resource_destruction(temp, last_submit_index);
1368        }
1369    }
1370
1371    pub fn size(&self) -> wgt::BufferAddress {
1372        self.size
1373    }
1374
1375    pub fn usage(&self) -> wgt::BufferUsages {
1376        self.usage
1377    }
1378}
1379
1380#[derive(Clone, Debug, Error)]
1381#[non_exhaustive]
1382pub enum CreateBufferError {
1383    #[error(transparent)]
1384    Device(#[from] DeviceError),
1385    #[error("Failed to map buffer while creating: {0}")]
1386    AccessError(#[from] BufferAccessError),
1387    #[error("Buffers that are mapped at creation have to be aligned to `COPY_BUFFER_ALIGNMENT`")]
1388    UnalignedSize,
1389    #[error("Invalid usage flags {0:?}")]
1390    InvalidUsage(wgt::BufferUsages),
1391    #[error("`MAP` usage can only be combined with the opposite `COPY`, requested {0:?}")]
1392    UsageMismatch(wgt::BufferUsages),
1393    #[error("Buffer size {requested} is greater than the maximum buffer size ({maximum})")]
1394    MaxBufferSize { requested: u64, maximum: u64 },
1395    #[error(transparent)]
1396    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
1397    #[error(transparent)]
1398    MissingFeatures(#[from] MissingFeatures),
1399    #[error("Failed to create bind group for indirect buffer validation: {0}")]
1400    IndirectValidationBindGroup(DeviceError),
1401    #[error("Error initializing buffer: {0}")]
1402    QueueWrite(#[from] queue::QueueWriteError),
1403}
1404
1405crate::impl_resource_type!(Buffer);
1406crate::impl_labeled!(Buffer);
1407crate::impl_parent_device!(Buffer);
1408crate::impl_storage_item!(Buffer);
1409crate::impl_trackable!(Buffer);
1410
1411impl WebGpuError for CreateBufferError {
1412    fn webgpu_error_type(&self) -> ErrorType {
1413        match self {
1414            Self::Device(e) => e.webgpu_error_type(),
1415            Self::AccessError(e) => e.webgpu_error_type(),
1416            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
1417            Self::IndirectValidationBindGroup(e) => e.webgpu_error_type(),
1418            Self::MissingFeatures(e) => e.webgpu_error_type(),
1419            Self::QueueWrite(e) => e.webgpu_error_type(),
1420
1421            Self::UnalignedSize
1422            | Self::InvalidUsage(_)
1423            | Self::UsageMismatch(_)
1424            | Self::MaxBufferSize { .. } => ErrorType::Validation,
1425        }
1426    }
1427}
1428
1429/// A buffer that has been marked as destroyed and is staged for actual deletion soon.
1430#[derive(Debug)]
1431pub struct DestroyedBuffer {
1432    raw: ManuallyDrop<Box<dyn hal::DynBuffer>>,
1433    device: Arc<Device>,
1434    label: String,
1435    bind_groups: WeakVec<BindGroup>,
1436    timestamp_normalization_bind_group: Option<TimestampNormalizationBindGroup>,
1437    indirect_validation_bind_groups: Option<crate::indirect_validation::BindGroups>,
1438}
1439
1440impl DestroyedBuffer {
1441    pub fn label(&self) -> &dyn fmt::Debug {
1442        &self.label
1443    }
1444}
1445
1446impl Drop for DestroyedBuffer {
1447    fn drop(&mut self) {
1448        let mut deferred = self.device.deferred_destroy.lock();
1449        deferred.push(DeferredDestroy::BindGroups(mem::take(
1450            &mut self.bind_groups,
1451        )));
1452        drop(deferred);
1453
1454        if let Some(raw) = self.timestamp_normalization_bind_group.take() {
1455            raw.dispose(self.device.raw());
1456        }
1457
1458        if let Some(raw) = self.indirect_validation_bind_groups.take() {
1459            raw.dispose(self.device.raw());
1460        }
1461
1462        resource_log!("Destroy raw Buffer (destroyed) {:?}", self.label());
1463        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1464        let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
1465        unsafe {
1466            hal::DynDevice::destroy_buffer(self.device.raw(), raw);
1467        }
1468    }
1469}
1470
1471#[cfg(send_sync)]
1472unsafe impl Send for StagingBuffer {}
1473#[cfg(send_sync)]
1474unsafe impl Sync for StagingBuffer {}
1475
1476/// A temporary buffer, consumed by the command that uses it.
1477///
1478/// A [`StagingBuffer`] is designed for one-shot uploads of data to the GPU. It
1479/// is always created mapped, and the command that uses it destroys the buffer
1480/// when it is done.
1481///
1482/// [`StagingBuffer`]s can be created with [`Queue::create_staging_buffer`] and
1483/// used with [`Queue::write_staging_buffer`]. They are also used internally by
1484/// operations like [`Queue::write_texture`] that need to upload data to the GPU,
1485/// but that don't belong to any particular wgpu command buffer.
1486///
1487/// Used `StagingBuffer`s are accumulated in [`Device::pending_writes`], to be
1488/// freed once their associated operation's queue submission has finished
1489/// execution.
1490///
1491/// [`Queue::create_staging_buffer`]: crate::device::queue::Queue::create_staging_buffer
1492/// [`Queue::write_staging_buffer`]: crate::device::queue::Queue::write_staging_buffer
1493/// [`Queue::write_texture`]: crate::device::queue::Queue::write_texture
1494/// [`Device::pending_writes`]: crate::device::Device
1495#[derive(Debug)]
1496pub struct StagingBuffer {
1497    raw: Box<dyn hal::DynBuffer>,
1498    device: Arc<Device>,
1499    pub(crate) size: wgt::BufferSize,
1500    is_coherent: bool,
1501    ptr: NonNull<u8>,
1502}
1503
1504impl StagingBuffer {
1505    pub(crate) fn new(device: &Arc<Device>, size: wgt::BufferSize) -> Result<Self, DeviceError> {
1506        profiling::scope!("StagingBuffer::new");
1507        let stage_desc = hal::BufferDescriptor {
1508            label: hal_label(Some("(wgpu internal) Staging"), device.instance_flags),
1509            size: size.get(),
1510            usage: wgt::BufferUses::MAP_WRITE | wgt::BufferUses::COPY_SRC,
1511            memory_flags: hal::MemoryFlags::TRANSIENT,
1512        };
1513
1514        let (raw, _) = unsafe { device.raw().create_buffer(&stage_desc) }
1515            .map_err(|e| device.handle_hal_error(e))?;
1516        let mapping = unsafe { device.raw().map_buffer(raw.as_ref(), 0..size.get()) }
1517            .map_err(|e| device.handle_hal_error(e))?;
1518
1519        let staging_buffer = StagingBuffer {
1520            raw,
1521            device: device.clone(),
1522            size,
1523            is_coherent: mapping.is_coherent,
1524            ptr: mapping.ptr,
1525        };
1526
1527        Ok(staging_buffer)
1528    }
1529
1530    /// # Safety
1531    /// You must not call any functions of `self`
1532    /// until you stopped using the returned pointer.
1533    pub unsafe fn ptr(&self) -> NonNull<u8> {
1534        self.ptr
1535    }
1536
1537    pub fn size(&self) -> wgt::BufferSize {
1538        self.size
1539    }
1540
1541    #[cfg(feature = "trace")]
1542    pub(crate) fn get_data(&self) -> &[u8] {
1543        unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.size.get() as usize) }
1544    }
1545
1546    pub(crate) fn write_zeros(&mut self) {
1547        unsafe { core::ptr::write_bytes(self.ptr.as_ptr(), 0, self.size.get() as usize) };
1548    }
1549
1550    /// Write the entire staging buffer.
1551    ///
1552    /// # Panics
1553    ///
1554    /// If `data.len()` is not equal to the size of the staging buffer.
1555    pub(crate) fn write_exact(&mut self, data: &[u8]) {
1556        assert_eq!(data.len(), self.size.get() as usize);
1557        // SAFETY: With the assert above, all of `copy_nonoverlapping`'s
1558        // requirements are satisfied.
1559        unsafe {
1560            core::ptr::copy_nonoverlapping(
1561                data.as_ptr(),
1562                self.ptr.as_ptr(),
1563                self.size.get() as usize,
1564            );
1565        }
1566    }
1567
1568    /// Write `data` to the staging buffer, filling any remainder with zeros.
1569    ///
1570    /// # Panics
1571    ///
1572    /// If `data` exceeds the size of the staging buffer.
1573    pub(crate) fn write_with_zero_padding(&mut self, data: &[u8]) {
1574        assert!(data.len() <= self.size.get() as usize);
1575        // SAFETY: The assert ensures the requirements of `copy_nonoverlapping`
1576        // and `write_bytes` are satisfied.
1577        unsafe {
1578            core::ptr::copy_nonoverlapping(data.as_ptr(), self.ptr.as_ptr(), data.len());
1579            core::ptr::write_bytes(
1580                self.ptr.as_ptr().add(data.len()),
1581                0,
1582                self.size.get() as usize - data.len(),
1583            );
1584        }
1585    }
1586
1587    /// SAFETY: The offsets and size must be in-bounds.
1588    pub(crate) unsafe fn write_with_offset(
1589        &mut self,
1590        data: &[u8],
1591        src_offset: isize,
1592        dst_offset: isize,
1593        size: usize,
1594    ) {
1595        unsafe {
1596            debug_assert!(
1597                (src_offset + size as isize) as usize <= data.len(),
1598                "src_offset + size must be in-bounds: src_offset = {}, size = {}, data.len() = {}",
1599                src_offset,
1600                size,
1601                data.len()
1602            );
1603            core::ptr::copy_nonoverlapping(
1604                data.as_ptr().offset(src_offset),
1605                self.ptr.as_ptr().offset(dst_offset),
1606                size,
1607            );
1608        }
1609    }
1610
1611    pub(crate) fn flush(self) -> FlushedStagingBuffer {
1612        let device = self.device.raw();
1613        if !self.is_coherent {
1614            #[allow(clippy::single_range_in_vec_init)]
1615            unsafe {
1616                device.flush_mapped_ranges(self.raw.as_ref(), &[0..self.size.get()])
1617            };
1618        }
1619        unsafe { device.unmap_buffer(self.raw.as_ref()) };
1620
1621        let StagingBuffer {
1622            raw, device, size, ..
1623        } = self;
1624
1625        FlushedStagingBuffer {
1626            raw: ManuallyDrop::new(raw),
1627            device,
1628            size,
1629        }
1630    }
1631
1632    pub(crate) fn dispose(self) {
1633        let device = self.device.raw();
1634        unsafe { device.unmap_buffer(self.raw.as_ref()) };
1635        unsafe { device.destroy_buffer(self.raw) };
1636    }
1637}
1638
1639crate::impl_resource_type!(StagingBuffer);
1640crate::impl_storage_item!(StagingBuffer);
1641
1642#[derive(Debug)]
1643pub struct FlushedStagingBuffer {
1644    raw: ManuallyDrop<Box<dyn hal::DynBuffer>>,
1645    device: Arc<Device>,
1646    pub(crate) size: wgt::BufferSize,
1647}
1648
1649impl FlushedStagingBuffer {
1650    pub(crate) fn raw(&self) -> &dyn hal::DynBuffer {
1651        self.raw.as_ref()
1652    }
1653}
1654
1655impl Drop for FlushedStagingBuffer {
1656    fn drop(&mut self) {
1657        resource_log!("Destroy raw StagingBuffer");
1658        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
1659        let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
1660        unsafe { self.device.raw().destroy_buffer(raw) };
1661    }
1662}
1663
1664pub type TextureDescriptor<'a> = wgt::TextureDescriptor<Label<'a>, Vec<wgt::TextureFormat>>;
1665
1666#[derive(Debug)]
1667pub(crate) enum TextureInner {
1668    Native {
1669        raw: Box<dyn hal::DynTexture>,
1670    },
1671    Surface {
1672        raw: Box<dyn hal::DynSurfaceTexture>,
1673    },
1674}
1675
1676impl TextureInner {
1677    pub(crate) fn raw(&self) -> &dyn hal::DynTexture {
1678        match self {
1679            Self::Native { raw } => raw.as_ref(),
1680            Self::Surface { raw, .. } => raw.as_ref().borrow(),
1681        }
1682    }
1683}
1684
1685/// Views for clearing a 2D texture with render passes. The contained views must be manually
1686/// destroyed by calling [`Self::destroy`].
1687///
1688/// This helper encapsulates the indexing logic for clear views (in [`Self::views`]),
1689/// to reduce the chance of doing so incorrectly and failing to properly clear a texture.
1690///
1691/// Color and depth/stencil textures have a single clear view with [`wgt::TextureAspect::All`].
1692/// This is true even for combined depth/stencil formats, which clear both aspects
1693/// simultaneously using a single view. The number of views is (mip level count) * (array
1694/// layer count).
1695///
1696/// Multi-planar textures have a clear view per plane. The number of views is (mip level
1697/// count) * (array layer count) * (plane count).
1698#[derive(Debug)]
1699pub struct ClearViews {
1700    views: SmallVec<[Box<dyn hal::DynTextureView>; 1]>,
1701    mip_level_count: u32,
1702    array_layer_count: u32,
1703    aspects: &'static [wgt::TextureAspect],
1704}
1705
1706impl ClearViews {
1707    /// Creates [`ClearViews`] by calling the provided `create_view` closure with `(mip_level,
1708    /// array_layer, aspect)` for each clear view of the texture.
1709    pub(crate) fn new<E>(
1710        label: hal::Label<'_>,
1711        usage: wgt::TextureUses,
1712        format: wgt::TextureFormat,
1713        mip_level_count: u32,
1714        array_layer_count: u32,
1715        mut create_view: impl FnMut(
1716            &hal::TextureViewDescriptor,
1717        ) -> Result<Box<dyn hal::DynTextureView>, E>,
1718    ) -> Result<Self, E> {
1719        const PLANES: [wgt::TextureAspect; 3] = [
1720            wgt::TextureAspect::Plane0,
1721            wgt::TextureAspect::Plane1,
1722            wgt::TextureAspect::Plane2,
1723        ];
1724        let aspects = match format.planes() {
1725            Some(planes) => &PLANES[..planes as usize],
1726            None => &[wgt::TextureAspect::All],
1727        };
1728
1729        let mut views = SmallVec::new();
1730        for mip_level in 0..mip_level_count {
1731            for array_layer in 0..array_layer_count {
1732                for &aspect in aspects {
1733                    let desc = hal::TextureViewDescriptor {
1734                        label,
1735                        format: format.aspect_specific_format(aspect).unwrap(),
1736                        dimension: wgt::TextureViewDimension::D2,
1737                        usage,
1738                        range: wgt::ImageSubresourceRange {
1739                            aspect,
1740                            base_mip_level: mip_level,
1741                            mip_level_count: Some(1),
1742                            base_array_layer: array_layer,
1743                            array_layer_count: Some(1),
1744                        },
1745                        swizzle: wgt::TextureComponentSwizzle::default(),
1746                    };
1747                    views.push(create_view(&desc)?);
1748                }
1749            }
1750        }
1751        Ok(Self {
1752            views,
1753            mip_level_count,
1754            array_layer_count,
1755            aspects,
1756        })
1757    }
1758
1759    /// Returns an iterator over the clear view(s) for the given mip level and array layer.
1760    ///
1761    /// The iterator yields tuples `(wgt::TextureAspect, &dyn hal::DynTextureView)` of
1762    /// clear views and their associated [`wgt::TextureAspect`]s.
1763    fn views(
1764        &self,
1765        mip_level: u32,
1766        array_layer: u32,
1767    ) -> impl Iterator<Item = (wgt::TextureAspect, &dyn hal::DynTextureView)> {
1768        assert!(mip_level < self.mip_level_count && array_layer < self.array_layer_count);
1769        let start =
1770            (mip_level * self.array_layer_count + array_layer) as usize * self.aspects.len();
1771        self.aspects.iter().copied().zip(
1772            self.views[start..start + self.aspects.len()]
1773                .iter()
1774                .map(|view| view.as_ref()),
1775        )
1776    }
1777
1778    /// Destroys the texture views.
1779    ///
1780    /// # Safety
1781    ///
1782    /// The views must not be in use by the device.
1783    unsafe fn destroy(&mut self, device: &dyn hal::DynDevice) {
1784        for view in self.views.drain(..) {
1785            unsafe { device.destroy_texture_view(view) };
1786        }
1787    }
1788}
1789
1790#[derive(Debug)]
1791pub enum TextureClearMode {
1792    BufferCopy,
1793    RenderPass {
1794        clear_views: ClearViews,
1795        is_color: bool,
1796    },
1797    Surface {
1798        clear_view: ManuallyDrop<Box<dyn hal::DynTextureView>>,
1799    },
1800    // Texture can't be cleared, attempting to do so will cause panic.
1801    // (either because it is impossible for the type of texture or it is being destroyed)
1802    None,
1803}
1804
1805impl TextureClearMode {
1806    /// Returns the views for clearing the given mip level and array layer with render
1807    /// passes, as a [`SmallVec`] of tuples `(wgt::TextureAspect, &dyn hal::DynTextureView)`
1808    /// of clear views and their associated [`wgt::TextureAspect`]s.
1809    ///
1810    /// # Panics
1811    ///
1812    /// If `self` does not use render passes.
1813    pub(crate) fn render_pass_views(
1814        &self,
1815        mip_level: u32,
1816        array_layer: u32,
1817    ) -> SmallVec<[(wgt::TextureAspect, &dyn hal::DynTextureView); 2]> {
1818        match *self {
1819            TextureClearMode::BufferCopy => {
1820                panic!("Given texture is cleared with buffer copies, not render passes")
1821            }
1822            TextureClearMode::None => {
1823                panic!("Given texture can't be cleared")
1824            }
1825            TextureClearMode::Surface { ref clear_view } => {
1826                SmallVec::from_iter([(wgt::TextureAspect::All, clear_view.as_ref())])
1827            }
1828            TextureClearMode::RenderPass {
1829                ref clear_views, ..
1830            } => clear_views.views(mip_level, array_layer).collect(),
1831        }
1832    }
1833}
1834
1835#[derive(Debug)]
1836pub struct TextureState {
1837    pub(crate) inner: Snatchable<TextureInner>,
1838}
1839
1840#[derive(Debug)]
1841pub struct Texture {
1842    pub(crate) state: ResourceState<TextureState>,
1843    pub(crate) device: Arc<Device>,
1844    pub(crate) desc: wgt::TextureDescriptor<String, Vec<wgt::TextureFormat>>,
1845    pub(crate) _hal_usage: wgt::TextureUses,
1846    pub(crate) format_features: wgt::TextureFormatFeatures,
1847    pub(crate) initialization_status: RwLock<TextureInitTracker>,
1848    pub(crate) full_range: TextureSelector,
1849    pub(crate) tracking_data: TrackingData,
1850    pub(crate) clear_mode: RwLock<TextureClearMode>,
1851    pub(crate) views: Mutex<WeakVec<TextureView>>,
1852    // Bind groups that reference this texture. May contain duplicates.
1853    pub(crate) bind_groups: Mutex<WeakVec<BindGroup>>,
1854    pub(crate) texture_binding_view_dimension: Option<wgt::TextureViewDimension>,
1855}
1856
1857impl Texture {
1858    pub(crate) fn new(
1859        device: &Arc<Device>,
1860        inner: TextureInner,
1861        hal_usage: wgt::TextureUses,
1862        desc: &TextureDescriptor,
1863        format_features: wgt::TextureFormatFeatures,
1864        clear_mode: TextureClearMode,
1865        init: bool,
1866        texture_binding_view_dimension: Option<wgt::TextureViewDimension>,
1867    ) -> Self {
1868        Texture {
1869            state: ResourceState::Valid(TextureState {
1870                inner: Snatchable::new(inner),
1871            }),
1872            device: device.clone(),
1873            desc: desc.map_label(|label| label.to_string()),
1874            _hal_usage: hal_usage,
1875            format_features,
1876            initialization_status: RwLock::new(
1877                rank::TEXTURE_INITIALIZATION_STATUS,
1878                if init {
1879                    TextureInitTracker::new(desc.mip_level_count, desc.array_layer_count())
1880                } else {
1881                    TextureInitTracker::new(desc.mip_level_count, 0)
1882                },
1883            ),
1884            full_range: TextureSelector {
1885                mips: 0..desc.mip_level_count,
1886                layers: 0..desc.array_layer_count(),
1887            },
1888            tracking_data: TrackingData::new(device.tracker_indices.textures.clone()),
1889            clear_mode: RwLock::new(rank::TEXTURE_CLEAR_MODE, clear_mode),
1890            views: Mutex::new(rank::TEXTURE_VIEWS, WeakVec::new()),
1891            bind_groups: Mutex::new(rank::TEXTURE_BIND_GROUPS, WeakVec::new()),
1892            texture_binding_view_dimension,
1893        }
1894    }
1895
1896    pub fn invalid(device: &Arc<Device>, desc: &TextureDescriptor) -> Arc<Self> {
1897        Arc::new(Texture {
1898            state: ResourceState::Invalid,
1899            device: device.clone(),
1900            desc: desc.map_label(|label| label.to_string()),
1901            _hal_usage: wgt::TextureUses::empty(),
1902            format_features: wgt::TextureFormatFeatures {
1903                allowed_usages: wgt::TextureUsages::empty(),
1904                flags: wgt::TextureFormatFeatureFlags::empty(),
1905            },
1906            initialization_status: RwLock::new(
1907                rank::TEXTURE_INITIALIZATION_STATUS,
1908                TextureInitTracker::new(0, 0),
1909            ),
1910            full_range: TextureSelector {
1911                mips: 0..desc.mip_level_count,
1912                layers: 0..desc.array_layer_count(),
1913            },
1914            tracking_data: TrackingData::new(device.tracker_indices.textures.clone()),
1915            clear_mode: RwLock::new(rank::TEXTURE_CLEAR_MODE, TextureClearMode::None),
1916            views: Mutex::new(rank::TEXTURE_VIEWS, WeakVec::new()),
1917            bind_groups: Mutex::new(rank::TEXTURE_BIND_GROUPS, WeakVec::new()),
1918            texture_binding_view_dimension: None,
1919        })
1920    }
1921
1922    /// Checks that the given texture usage contains the required texture usage,
1923    /// returns an error otherwise.
1924    pub(crate) fn check_usage(
1925        &self,
1926        expected: wgt::TextureUsages,
1927    ) -> Result<(), MissingTextureUsageError> {
1928        if self.desc.usage.contains(expected) {
1929            Ok(())
1930        } else {
1931            Err(MissingTextureUsageError {
1932                res: self.error_ident(),
1933                actual: self.desc.usage,
1934                expected,
1935            })
1936        }
1937    }
1938
1939    /// Return the resolved texture binding view dimension.
1940    pub fn texture_binding_view_dimension(&self) -> Option<wgt::TextureViewDimension> {
1941        self.texture_binding_view_dimension
1942    }
1943}
1944
1945impl Drop for Texture {
1946    #[allow(trivial_casts)]
1947    fn drop(&mut self) {
1948        profiling::scope!("Texture::drop");
1949        api_log!("Texture::drop {:?}", self as *const _);
1950
1951        #[cfg(feature = "trace")]
1952        {
1953            let mut t = self.device.trace.lock();
1954            if let Some(t) = t.as_mut() {
1955                use crate::device::trace::to_trace;
1956
1957                // SAFETY: All textures are constructed in Arc => are heap allocated
1958                t.add(trace::Action::DropTexture(unsafe { to_trace(self) }));
1959            }
1960        }
1961        match *self.clear_mode.write() {
1962            TextureClearMode::Surface {
1963                ref mut clear_view, ..
1964            } => {
1965                // SAFETY: We are in the Drop impl and we don't use clear_view anymore after this point.
1966                let raw = unsafe { ManuallyDrop::take(clear_view) };
1967                unsafe {
1968                    self.device.raw().destroy_texture_view(raw);
1969                }
1970            }
1971            TextureClearMode::RenderPass {
1972                ref mut clear_views,
1973                ..
1974            } => {
1975                // SAFETY: We are in the Drop impl and will not use the clear views after this point.
1976                unsafe { clear_views.destroy(self.device.raw()) };
1977            }
1978            _ => {}
1979        };
1980
1981        let ResourceState::Valid(state) = &mut self.state else {
1982            return;
1983        };
1984        if let Some(TextureInner::Native { raw }) = state.inner.take() {
1985            resource_log!("Destroy raw {}", self.error_ident());
1986            unsafe {
1987                self.device.raw().destroy_texture(raw);
1988            }
1989        }
1990    }
1991}
1992
1993impl RawResourceAccess for Texture {
1994    type DynResource = dyn hal::DynTexture;
1995
1996    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
1997        self.state
1998            .as_ref()
1999            .valid()
2000            .and_then(|t| t.inner.get(guard).map(|t| t.raw()))
2001    }
2002}
2003
2004impl Texture {
2005    pub(crate) fn state(&self) -> Result<&TextureState, InvalidResourceError> {
2006        match &self.state {
2007            ResourceState::Valid(state) => Ok(state),
2008            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
2009        }
2010    }
2011
2012    pub(crate) fn check_destroyed(
2013        &self,
2014        guard: &SnatchGuard,
2015    ) -> Result<(), DestroyedResourceError> {
2016        let Ok(state) = self.state() else {
2017            return Ok(());
2018        };
2019        state
2020            .inner
2021            .get(guard)
2022            .map(|_| ())
2023            .ok_or_else(|| DestroyedResourceError(self.error_ident()))
2024    }
2025
2026    pub fn check_valid(&self) -> Result<(), InvalidResourceError> {
2027        self.state().map(|_| ())
2028    }
2029
2030    pub(crate) fn try_inner<'a>(
2031        &'a self,
2032        guard: &'a SnatchGuard,
2033    ) -> Result<&'a TextureInner, InvalidOrDestroyedResourceError> {
2034        self.state()?
2035            .inner
2036            .get(guard)
2037            .ok_or_else(|| DestroyedResourceError(self.error_ident()).into())
2038    }
2039
2040    pub fn destroy(self: &Arc<Self>) {
2041        profiling::scope!("Texture::destroy");
2042        api_log!("Texture::destroy {:?}", Arc::as_ptr(self));
2043
2044        #[cfg(feature = "trace")]
2045        if let Some(trace) = self.device.trace.lock().as_mut() {
2046            use crate::device::trace::IntoTrace as _;
2047
2048            trace.add(trace::Action::DestroyTexture(self.to_trace()));
2049        }
2050
2051        let device = &self.device;
2052
2053        let ResourceState::Valid(state) = &self.state else {
2054            return;
2055        };
2056
2057        let temp = {
2058            let raw = match state.inner.snatch(&mut device.snatchable_lock.write()) {
2059                Some(TextureInner::Native { raw }) => raw,
2060                Some(TextureInner::Surface { .. }) => {
2061                    return;
2062                }
2063                None => {
2064                    // Per spec, it is valid to call `destroy` multiple times.
2065                    return;
2066                }
2067            };
2068
2069            let views = {
2070                let mut guard = self.views.lock();
2071                mem::take(&mut *guard)
2072            };
2073
2074            let bind_groups = {
2075                let mut guard = self.bind_groups.lock();
2076                mem::take(&mut *guard)
2077            };
2078
2079            queue::TempResource::DestroyedTexture(DestroyedTexture {
2080                raw: ManuallyDrop::new(raw),
2081                views,
2082                clear_mode: mem::replace(&mut *self.clear_mode.write(), TextureClearMode::None),
2083                bind_groups,
2084                device: Arc::clone(&self.device),
2085                label: self.label().to_owned(),
2086            })
2087        };
2088
2089        let Some(queue) = device.get_queue() else {
2090            return;
2091        };
2092
2093        {
2094            let mut pending_writes = queue.pending_writes.lock();
2095            if pending_writes.contains_texture(self) {
2096                pending_writes.consume_temp(temp);
2097                return;
2098            }
2099        }
2100
2101        let mut life_lock = queue.lock_life();
2102        let last_submit_index = life_lock.get_texture_latest_submission_index(self);
2103        if let Some(last_submit_index) = last_submit_index {
2104            life_lock.schedule_resource_destruction(temp, last_submit_index);
2105        }
2106    }
2107
2108    fn create_view_inner(
2109        self: &Arc<Self>,
2110        desc: &TextureViewDescriptor,
2111    ) -> Result<Arc<TextureView>, CreateTextureViewError> {
2112        let device = &self.device;
2113        device.check_is_valid()?;
2114
2115        if desc.swizzle != wgt::TextureComponentSwizzle::default() {
2116            self.device
2117                .require_features(wgt::Features::TEXTURE_COMPONENT_SWIZZLE)?;
2118        }
2119
2120        let snatch_guard = device.snatchable_lock.read();
2121
2122        let texture_raw = self.try_inner(&snatch_guard)?.raw();
2123
2124        // resolve TextureViewDescriptor defaults
2125        // https://gpuweb.github.io/gpuweb/#abstract-opdef-resolving-gputextureviewdescriptor-defaults
2126        let resolved_format = desc.format.unwrap_or_else(|| {
2127            self.desc
2128                .format
2129                .aspect_specific_format(desc.range.aspect)
2130                .unwrap_or(self.desc.format)
2131        });
2132
2133        let resolved_dimension = desc
2134            .dimension
2135            .unwrap_or_else(|| self.desc.default_view_dimension());
2136
2137        let resolved_mip_level_count = desc.range.mip_level_count.unwrap_or_else(|| {
2138            self.desc
2139                .mip_level_count
2140                .saturating_sub(desc.range.base_mip_level)
2141        });
2142
2143        let resolved_array_layer_count =
2144            desc.range
2145                .array_layer_count
2146                .unwrap_or_else(|| match resolved_dimension {
2147                    wgt::TextureViewDimension::D1
2148                    | wgt::TextureViewDimension::D2
2149                    | wgt::TextureViewDimension::D3 => 1,
2150                    wgt::TextureViewDimension::Cube => 6,
2151                    wgt::TextureViewDimension::D2Array | wgt::TextureViewDimension::CubeArray => {
2152                        self.desc
2153                            .array_layer_count()
2154                            .saturating_sub(desc.range.base_array_layer)
2155                    }
2156                });
2157
2158        let resolved_usage = {
2159            let usage = desc.usage.unwrap_or(wgt::TextureUsages::empty());
2160            if usage.is_empty() {
2161                self.desc.usage
2162            } else if self.desc.usage.contains(usage) {
2163                // Transient texture usage subsetting is disallowed
2164                if self
2165                    .desc
2166                    .usage
2167                    .contains(wgt::TextureUsages::TRANSIENT_ATTACHMENT)
2168                    && self.desc.usage != usage
2169                {
2170                    return Err(CreateTextureViewError::InvalidTransientTextureViewUsage {
2171                        texture: self.desc.usage,
2172                        view: usage,
2173                    });
2174                }
2175
2176                usage
2177            } else {
2178                return Err(CreateTextureViewError::InvalidTextureViewUsage {
2179                    view: usage,
2180                    texture: self.desc.usage,
2181                });
2182            }
2183        };
2184
2185        let format_features = device.describe_format_features(resolved_format)?;
2186        let allowed_format_usages = format_features.allowed_usages;
2187        if resolved_usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT)
2188            && !allowed_format_usages.contains(wgt::TextureUsages::RENDER_ATTACHMENT)
2189        {
2190            return Err(CreateTextureViewError::TextureViewFormatNotRenderable(
2191                resolved_format,
2192            ));
2193        }
2194
2195        if resolved_usage.contains(wgt::TextureUsages::STORAGE_BINDING)
2196            && !allowed_format_usages.contains(wgt::TextureUsages::STORAGE_BINDING)
2197        {
2198            return Err(CreateTextureViewError::TextureViewFormatNotStorage(
2199                resolved_format,
2200            ));
2201        }
2202
2203        // validate TextureViewDescriptor
2204
2205        let aspects = hal::FormatAspects::new(self.desc.format, desc.range.aspect);
2206        if aspects.is_empty() {
2207            return Err(CreateTextureViewError::InvalidAspect {
2208                texture_format: self.desc.format,
2209                requested_aspect: desc.range.aspect,
2210            });
2211        }
2212
2213        if desc.range.aspect == wgt::TextureAspect::All && resolved_format.is_multi_planar_format()
2214        {
2215            return Err(CreateTextureViewError::MultiplanarFullTexture(
2216                resolved_format,
2217            ));
2218        }
2219
2220        if desc.range.aspect == wgt::TextureAspect::All {
2221            if resolved_format != self.desc.format
2222                && !self.desc.view_formats.contains(&resolved_format)
2223            {
2224                return Err(CreateTextureViewError::FormatReinterpretation {
2225                    texture: self.desc.format,
2226                    view: resolved_format,
2227                });
2228            }
2229        } else {
2230            let aspect_format = self.desc.format.aspect_specific_format(desc.range.aspect);
2231            match aspect_format {
2232                Some(aspect_format) if aspect_format == resolved_format => (),
2233                Some(aspect_format) => {
2234                    return Err(CreateTextureViewError::WrongAspectReinterpretation {
2235                        texture: self.desc.format,
2236                        aspect: desc.range.aspect,
2237                        aspect_format,
2238                        requested_format: resolved_format,
2239                    })
2240                }
2241                None => {
2242                    // User requested a sub-aspect (not TextureAspect::All) that is not on the texture.
2243                    // This should've already returned with the InvalidAspect check above.
2244                    unreachable!()
2245                }
2246            }
2247        }
2248
2249        // check if multisampled texture is seen as anything but 2D
2250        if self.desc.sample_count > 1 && resolved_dimension != wgt::TextureViewDimension::D2 {
2251            // Multisample is allowed on 2D arrays, only if explicitly supported
2252            let multisample_array_exception = resolved_dimension
2253                == wgt::TextureViewDimension::D2Array
2254                && device.features.contains(wgt::Features::MULTISAMPLE_ARRAY);
2255
2256            if !multisample_array_exception {
2257                return Err(
2258                    CreateTextureViewError::InvalidMultisampledTextureViewDimension(
2259                        resolved_dimension,
2260                    ),
2261                );
2262            }
2263        }
2264
2265        // check if the dimension is compatible with the texture
2266        if self.desc.dimension != resolved_dimension.compatible_texture_dimension() {
2267            return Err(CreateTextureViewError::InvalidTextureViewDimension {
2268                view: resolved_dimension,
2269                texture: self.desc.dimension,
2270            });
2271        }
2272
2273        match resolved_dimension {
2274            wgt::TextureViewDimension::D1
2275            | wgt::TextureViewDimension::D2
2276            | wgt::TextureViewDimension::D3
2277                if resolved_array_layer_count != 1 =>
2278            {
2279                return Err(CreateTextureViewError::InvalidArrayLayerCount {
2280                    requested: resolved_array_layer_count,
2281                    dim: resolved_dimension,
2282                });
2283            }
2284            wgt::TextureViewDimension::Cube if resolved_array_layer_count != 6 => {
2285                return Err(CreateTextureViewError::InvalidCubemapTextureDepth {
2286                    depth: resolved_array_layer_count,
2287                });
2288            }
2289            wgt::TextureViewDimension::CubeArray
2290                if !resolved_array_layer_count.is_multiple_of(6) =>
2291            {
2292                return Err(CreateTextureViewError::InvalidCubemapArrayTextureDepth {
2293                    depth: resolved_array_layer_count,
2294                });
2295            }
2296            _ => {}
2297        }
2298
2299        match resolved_dimension {
2300            wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray
2301                if self.desc.size.width != self.desc.size.height =>
2302            {
2303                return Err(CreateTextureViewError::InvalidCubeTextureViewSize);
2304            }
2305            _ => {}
2306        }
2307
2308        if resolved_mip_level_count == 0 {
2309            return Err(CreateTextureViewError::ZeroMipLevelCount);
2310        }
2311
2312        let mip_level_end = desc
2313            .range
2314            .base_mip_level
2315            .saturating_add(resolved_mip_level_count);
2316
2317        let level_end = self.desc.mip_level_count;
2318        if mip_level_end > level_end {
2319            return Err(CreateTextureViewError::TooManyMipLevels {
2320                base_mip_level: desc.range.base_mip_level,
2321                mip_level_count: resolved_mip_level_count,
2322                total: level_end,
2323            });
2324        }
2325
2326        if resolved_array_layer_count == 0 {
2327            return Err(CreateTextureViewError::ZeroArrayLayerCount);
2328        }
2329
2330        let array_layer_end = desc
2331            .range
2332            .base_array_layer
2333            .saturating_add(resolved_array_layer_count);
2334
2335        let layer_end = self.desc.array_layer_count();
2336        if array_layer_end > layer_end {
2337            return Err(CreateTextureViewError::TooManyArrayLayers {
2338                base_array_layer: desc.range.base_array_layer,
2339                array_layer_count: resolved_array_layer_count,
2340                total: layer_end,
2341            });
2342        };
2343
2344        // https://gpuweb.github.io/gpuweb/#abstract-opdef-renderable-texture-view
2345        let render_extent = 'error: {
2346            if !resolved_usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT) {
2347                break 'error Err(TextureViewNotRenderableReason::Usage(resolved_usage));
2348            }
2349
2350            let allowed_view_dimensions = [
2351                wgt::TextureViewDimension::D2,
2352                wgt::TextureViewDimension::D2Array,
2353                wgt::TextureViewDimension::D3,
2354            ];
2355            if !allowed_view_dimensions.contains(&resolved_dimension) {
2356                break 'error Err(TextureViewNotRenderableReason::Dimension(
2357                    resolved_dimension,
2358                ));
2359            }
2360
2361            if resolved_mip_level_count != 1 {
2362                break 'error Err(TextureViewNotRenderableReason::MipLevelCount(
2363                    resolved_mip_level_count,
2364                ));
2365            }
2366
2367            if resolved_array_layer_count != 1
2368                && !(device.features.contains(wgt::Features::MULTIVIEW))
2369            {
2370                break 'error Err(TextureViewNotRenderableReason::ArrayLayerCount(
2371                    resolved_array_layer_count,
2372                ));
2373            }
2374
2375            if !self.desc.format.is_multi_planar_format()
2376                && aspects != hal::FormatAspects::from(self.desc.format)
2377            {
2378                break 'error Err(TextureViewNotRenderableReason::Aspects(aspects));
2379            }
2380
2381            if desc.swizzle != wgt::TextureComponentSwizzle::default() {
2382                break 'error Err(TextureViewNotRenderableReason::Swizzle(desc.swizzle));
2383            }
2384
2385            Ok(self
2386                .desc
2387                .compute_render_extent(desc.range.base_mip_level, desc.range.aspect.to_plane()))
2388        };
2389
2390        // filter the usages based on the other criteria
2391        let usage = {
2392            let resolved_hal_usage = crate::conv::map_texture_usage(
2393                resolved_usage,
2394                resolved_format.into(),
2395                format_features.flags,
2396            );
2397            let mask_copy = !(wgt::TextureUses::COPY_SRC | wgt::TextureUses::COPY_DST);
2398            let mask_dimension = match resolved_dimension {
2399                wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => {
2400                    wgt::TextureUses::RESOURCE
2401                }
2402                wgt::TextureViewDimension::D3 => {
2403                    wgt::TextureUses::RESOURCE
2404                        | wgt::TextureUses::STORAGE_READ_ONLY
2405                        | wgt::TextureUses::STORAGE_WRITE_ONLY
2406                        | wgt::TextureUses::STORAGE_READ_WRITE
2407                }
2408                _ => wgt::TextureUses::all(),
2409            };
2410            let mask_mip_level = if resolved_mip_level_count == 1 {
2411                wgt::TextureUses::all()
2412            } else {
2413                wgt::TextureUses::RESOURCE
2414            };
2415            resolved_hal_usage & mask_copy & mask_dimension & mask_mip_level
2416        };
2417
2418        // use the combined depth-stencil format for the view
2419        let format = if resolved_format.is_depth_stencil_component(self.desc.format) {
2420            self.desc.format
2421        } else {
2422            resolved_format
2423        };
2424
2425        let resolved_range = wgt::ImageSubresourceRange {
2426            aspect: desc.range.aspect,
2427            base_mip_level: desc.range.base_mip_level,
2428            mip_level_count: Some(resolved_mip_level_count),
2429            base_array_layer: desc.range.base_array_layer,
2430            array_layer_count: Some(resolved_array_layer_count),
2431        };
2432
2433        let hal_desc = hal::TextureViewDescriptor {
2434            label: desc.label.to_hal(device.instance_flags),
2435            format,
2436            dimension: resolved_dimension,
2437            usage,
2438            range: resolved_range,
2439            swizzle: desc.swizzle,
2440        };
2441
2442        let raw = unsafe { device.raw().create_texture_view(texture_raw, &hal_desc) }
2443            .map_err(|e| device.handle_hal_error(e))?;
2444
2445        let selector = TextureSelector {
2446            mips: desc.range.base_mip_level..mip_level_end,
2447            layers: desc.range.base_array_layer..array_layer_end,
2448        };
2449
2450        let view = TextureView {
2451            state: ResourceState::Valid(TextureViewState {
2452                raw: Snatchable::new(raw),
2453                render_extent,
2454            }),
2455            parent: self.clone(),
2456            device: device.clone(),
2457            desc: HalTextureViewDescriptor {
2458                texture_format: self.desc.format,
2459                format: resolved_format,
2460                dimension: resolved_dimension,
2461                usage: resolved_usage,
2462                range: resolved_range,
2463                swizzle: desc.swizzle,
2464            },
2465            format_features: self.format_features,
2466            samples: self.desc.sample_count,
2467            selector,
2468            label: desc.label.to_string(),
2469        };
2470
2471        let view = Arc::new(view);
2472
2473        {
2474            let mut views = self.views.lock();
2475            views.push(Arc::downgrade(&view));
2476        }
2477
2478        Ok(view)
2479    }
2480
2481    pub fn create_view(self: &Arc<Self>, desc: &TextureViewDescriptor) -> Arc<TextureView> {
2482        profiling::scope!("Texture::create_view");
2483
2484        let view = self.create_view_inner(desc).unwrap_or_else(|err| {
2485            self.device
2486                .handle_error(err, desc.label.as_deref(), "Texture::create_view failed");
2487            TextureView::invalid(&self.device, self, desc)
2488        });
2489
2490        api_log!(
2491            "Texture::create_view({:?}) -> {:?}",
2492            Arc::as_ptr(self),
2493            Arc::as_ptr(&view)
2494        );
2495
2496        #[cfg(feature = "trace")]
2497        if let Some(ref mut trace) = *self.device.trace.lock() {
2498            use crate::device::trace;
2499            use trace::IntoTrace as _;
2500            trace.add(trace::Action::CreateTextureView {
2501                id: view.to_trace(),
2502                parent: self.to_trace(),
2503                desc: desc.clone(),
2504            });
2505        }
2506
2507        view
2508    }
2509
2510    pub fn descriptor(&self) -> &wgt::TextureDescriptor<String, Vec<wgt::TextureFormat>> {
2511        &self.desc
2512    }
2513
2514    /// Marks the texture's entire contents as uninitialized, indicating that
2515    /// it must be fully initialized (zeroed) before being used.
2516    ///
2517    /// This is useful when you want zeroize texture,
2518    /// but want to defer the actual action to when it's actually needed,
2519    /// which allows to eliding the zeroing if the texture is never actually read.
2520    pub fn mark_uninitialized(&self) {
2521        let mut initialization_status = self.initialization_status.write();
2522        *initialization_status =
2523            TextureInitTracker::new(self.desc.mip_level_count, self.desc.array_layer_count());
2524    }
2525
2526    /// Marks the texture's entire contents as already initialized,
2527    /// skipping wgpu-core's lazy zero-initialization of it.
2528    ///
2529    /// # Safety
2530    ///
2531    /// The entire contents of the texture must already be initialized.
2532    pub unsafe fn mark_externally_initialized(&self) {
2533        let mut initialization_status = self.initialization_status.write();
2534        for mip_tracker in initialization_status.mips.iter_mut() {
2535            mip_tracker.drain(0..self.desc.array_layer_count());
2536        }
2537    }
2538}
2539
2540/// A texture that has been marked as destroyed and is staged for actual deletion soon.
2541#[derive(Debug)]
2542pub struct DestroyedTexture {
2543    raw: ManuallyDrop<Box<dyn hal::DynTexture>>,
2544    views: WeakVec<TextureView>,
2545    clear_mode: TextureClearMode,
2546    bind_groups: WeakVec<BindGroup>,
2547    device: Arc<Device>,
2548    label: String,
2549}
2550
2551impl DestroyedTexture {
2552    pub fn label(&self) -> &dyn fmt::Debug {
2553        &self.label
2554    }
2555}
2556
2557impl Drop for DestroyedTexture {
2558    fn drop(&mut self) {
2559        let device = &self.device;
2560
2561        let mut deferred = device.deferred_destroy.lock();
2562        deferred.push(DeferredDestroy::TextureViews(mem::take(&mut self.views)));
2563        deferred.push(DeferredDestroy::BindGroups(mem::take(
2564            &mut self.bind_groups,
2565        )));
2566        drop(deferred);
2567
2568        match mem::replace(&mut self.clear_mode, TextureClearMode::None) {
2569            TextureClearMode::RenderPass {
2570                mut clear_views, ..
2571            } => {
2572                unsafe { clear_views.destroy(self.device.raw()) };
2573            }
2574            TextureClearMode::Surface { clear_view } => {
2575                let raw = ManuallyDrop::into_inner(clear_view);
2576                unsafe { self.device.raw().destroy_texture_view(raw) };
2577            }
2578            _ => (),
2579        }
2580
2581        resource_log!("Destroy raw Texture (destroyed) {:?}", self.label());
2582        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
2583        let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
2584        unsafe {
2585            self.device.raw().destroy_texture(raw);
2586        }
2587    }
2588}
2589
2590#[derive(Clone, Copy, Debug)]
2591pub enum TextureErrorDimension {
2592    X,
2593    Y,
2594    Z,
2595}
2596
2597#[derive(Clone, Debug, Error)]
2598#[non_exhaustive]
2599pub enum TextureDimensionError {
2600    #[error("Dimension {0:?} is zero")]
2601    Zero(TextureErrorDimension),
2602    #[error("Dimension {dim:?} value {given} exceeds the limit of {limit}")]
2603    LimitExceeded {
2604        dim: TextureErrorDimension,
2605        given: u32,
2606        limit: u32,
2607    },
2608    #[error("Sample count {0} is invalid")]
2609    InvalidSampleCount(u32),
2610    #[error("Width {width} is not a multiple of {format:?}'s block width ({block_width})")]
2611    NotMultipleOfBlockWidth {
2612        width: u32,
2613        block_width: u32,
2614        format: wgt::TextureFormat,
2615    },
2616    #[error("Height {height} is not a multiple of {format:?}'s block height ({block_height})")]
2617    NotMultipleOfBlockHeight {
2618        height: u32,
2619        block_height: u32,
2620        format: wgt::TextureFormat,
2621    },
2622    #[error(
2623        "Width {width} is not a multiple of {format:?}'s width multiple requirement ({multiple})"
2624    )]
2625    WidthNotMultipleOf {
2626        width: u32,
2627        multiple: u32,
2628        format: wgt::TextureFormat,
2629    },
2630    #[error("Height {height} is not a multiple of {format:?}'s height multiple requirement ({multiple})")]
2631    HeightNotMultipleOf {
2632        height: u32,
2633        multiple: u32,
2634        format: wgt::TextureFormat,
2635    },
2636    #[error("Multisampled texture depth or array layers must be 1, got {0}")]
2637    MultisampledDepthOrArrayLayer(u32),
2638}
2639
2640impl WebGpuError for TextureDimensionError {
2641    fn webgpu_error_type(&self) -> ErrorType {
2642        ErrorType::Validation
2643    }
2644}
2645
2646#[derive(Clone, Debug, Error)]
2647#[non_exhaustive]
2648pub enum CreateTextureError {
2649    #[error(transparent)]
2650    Device(#[from] DeviceError),
2651    #[error(transparent)]
2652    CreateTextureView(#[from] CreateTextureViewError),
2653    #[error("Invalid usage flags {0:?}")]
2654    InvalidUsage(wgt::TextureUsages),
2655    #[error(transparent)]
2656    InvalidDimension(#[from] TextureDimensionError),
2657    #[error("Depth texture ({1:?}) can't be created as {0:?}")]
2658    InvalidDepthDimension(wgt::TextureDimension, wgt::TextureFormat),
2659    #[error("Compressed texture ({1:?}) can't be created as {0:?}")]
2660    InvalidCompressedDimension(wgt::TextureDimension, wgt::TextureFormat),
2661    #[error(
2662        "Texture descriptor mip level count {requested} is invalid, maximum allowed is {maximum}"
2663    )]
2664    InvalidMipLevelCount { requested: u32, maximum: u32 },
2665    #[error(
2666        "Texture usages {0:?} are not allowed on a texture of type {1:?}{downlevel_suffix}",
2667        downlevel_suffix = if *.2 { " due to downlevel restrictions" } else { "" }
2668    )]
2669    InvalidFormatUsages(wgt::TextureUsages, wgt::TextureFormat, bool),
2670    #[error("The view format {0:?} is not compatible with texture format {1:?}, only changing srgb-ness is allowed.")]
2671    InvalidViewFormat(wgt::TextureFormat, wgt::TextureFormat),
2672    #[error("Transient texture usage must be equal to `TRANSIENT_ATTACHMENT | RENDER_ATTACHMENT`, but got `{0:?}`")]
2673    InvalidTransientTextureUsage(wgt::TextureUsages),
2674    #[error("Transient texture view formats must be empty")]
2675    InvalidTransientTextureViewFormats,
2676    #[error("Texture usages {0:?} are not allowed on a texture of dimensions {1:?}")]
2677    InvalidDimensionUsages(wgt::TextureUsages, wgt::TextureDimension),
2678    #[error("Texture usage STORAGE_BINDING is not allowed for multisampled textures")]
2679    InvalidMultisampledStorageBinding,
2680    #[error("Format {0:?} does not support multisampling")]
2681    InvalidMultisampledFormat(wgt::TextureFormat),
2682    #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
2683    InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
2684    #[error("Multisampled textures must have RENDER_ATTACHMENT usage")]
2685    MultisampledNotRenderAttachment,
2686    #[error("Transient texture mip level count ({0}) must be 1")]
2687    InvalidTransientTextureMipLevelCount(u32),
2688    #[error("Transient texture layer count ({0}) must be 1")]
2689    InvalidTransientTextureLayerCount(u32),
2690    #[error("Texture format {0:?} can't be used due to missing features")]
2691    MissingFeatures(wgt::TextureFormat, #[source] MissingFeatures),
2692    #[error(transparent)]
2693    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
2694    #[error(transparent)]
2695    InvalidTextureBindingViewDimension(#[from] TextureBindingViewDimensionError),
2696}
2697
2698#[derive(Clone, Debug, Error)]
2699#[non_exhaustive]
2700pub enum TextureBindingViewDimensionError {
2701    #[error(
2702        "Texture binding view dimension {dimension:?} requires \
2703         depth_or_array_layers to be {required}, but it is {actual}"
2704    )]
2705    InvalidLayerCount {
2706        dimension: wgt::TextureViewDimension,
2707        required: u32,
2708        actual: u32,
2709    },
2710
2711    #[error(
2712        "Texture binding view dimension CubeArray requires \
2713         depth_or_array_layers to be a multiple of 6, but it is {0}"
2714    )]
2715    InvalidCubeArrayLayerCount(u32),
2716}
2717
2718crate::impl_resource_type!(Texture);
2719impl Labeled for Texture {
2720    fn label(&self) -> &str {
2721        &self.desc.label
2722    }
2723}
2724crate::impl_parent_device!(Texture);
2725crate::impl_storage_item!(Texture);
2726crate::impl_trackable!(Texture);
2727
2728impl Borrow<TextureSelector> for Texture {
2729    fn borrow(&self) -> &TextureSelector {
2730        &self.full_range
2731    }
2732}
2733
2734impl WebGpuError for CreateTextureError {
2735    fn webgpu_error_type(&self) -> ErrorType {
2736        match self {
2737            Self::Device(e) => e.webgpu_error_type(),
2738            Self::CreateTextureView(e) => e.webgpu_error_type(),
2739            Self::InvalidDimension(e) => e.webgpu_error_type(),
2740            Self::MissingFeatures(_, e) => e.webgpu_error_type(),
2741            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
2742
2743            Self::InvalidUsage(_)
2744            | Self::InvalidDepthDimension(_, _)
2745            | Self::InvalidCompressedDimension(_, _)
2746            | Self::InvalidMipLevelCount { .. }
2747            | Self::InvalidFormatUsages(_, _, _)
2748            | Self::InvalidViewFormat(_, _)
2749            | Self::InvalidDimensionUsages(_, _)
2750            | Self::InvalidMultisampledStorageBinding
2751            | Self::InvalidMultisampledFormat(_)
2752            | Self::InvalidSampleCount(..)
2753            | Self::InvalidTransientTextureUsage(_)
2754            | Self::InvalidTransientTextureMipLevelCount(_)
2755            | Self::InvalidTransientTextureLayerCount(_)
2756            | Self::InvalidTransientTextureViewFormats
2757            | Self::InvalidTextureBindingViewDimension(_)
2758            | Self::MultisampledNotRenderAttachment => ErrorType::Validation,
2759        }
2760    }
2761}
2762
2763/// Describes a [`TextureView`].
2764#[derive(Clone, Debug, Default, Eq, PartialEq)]
2765#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
2766#[cfg_attr(feature = "serde", serde(default))]
2767pub struct TextureViewDescriptor<'a> {
2768    /// Debug label of the texture view.
2769    ///
2770    /// This will show up in graphics debuggers for easy identification.
2771    pub label: Label<'a>,
2772    /// Format of the texture view, or `None` for the same format as the texture
2773    /// itself.
2774    ///
2775    /// At this time, it must be the same the underlying format of the texture.
2776    pub format: Option<wgt::TextureFormat>,
2777    /// The dimension of the texture view.
2778    ///
2779    /// - For 1D textures, this must be `D1`.
2780    /// - For 2D textures it must be one of `D2`, `D2Array`, `Cube`, or `CubeArray`.
2781    /// - For 3D textures it must be `D3`.
2782    pub dimension: Option<wgt::TextureViewDimension>,
2783    /// The allowed usage(s) for the texture view. Must be a subset of the usage flags of the texture.
2784    /// If not provided, defaults to the full set of usage flags of the texture.
2785    pub usage: Option<wgt::TextureUsages>,
2786    /// Range within the texture that is accessible via this view.
2787    pub range: wgt::ImageSubresourceRange,
2788    /// Texture component swizzle.
2789    /// When the texture view is accessed by a shader, the red/green/blue/alpha channels are replaced
2790    /// by the value corresponding to the component specified in [`wgt::TextureComponentSwizzle`].
2791    pub swizzle: wgt::TextureComponentSwizzle,
2792}
2793
2794#[derive(Debug)]
2795pub(crate) struct HalTextureViewDescriptor {
2796    pub texture_format: wgt::TextureFormat,
2797    pub format: wgt::TextureFormat,
2798    pub usage: wgt::TextureUsages,
2799    pub dimension: wgt::TextureViewDimension,
2800    pub range: wgt::ImageSubresourceRange,
2801    pub swizzle: wgt::TextureComponentSwizzle,
2802}
2803
2804impl HalTextureViewDescriptor {
2805    pub fn aspects(&self) -> hal::FormatAspects {
2806        hal::FormatAspects::new(self.texture_format, self.range.aspect)
2807    }
2808}
2809
2810#[derive(Debug, Copy, Clone, Error)]
2811pub enum TextureViewNotRenderableReason {
2812    #[error("The texture this view references doesn't include the RENDER_ATTACHMENT usage. Provided usages: {0:?}")]
2813    Usage(wgt::TextureUsages),
2814    #[error("The dimension of this texture view is not 2D. View dimension: {0:?}")]
2815    Dimension(wgt::TextureViewDimension),
2816    #[error("This texture view has more than one mipmap level. View mipmap levels: {0:?}")]
2817    MipLevelCount(u32),
2818    #[error("This texture view has more than one array layer. View array layers: {0:?}")]
2819    ArrayLayerCount(u32),
2820    #[error(
2821        "The aspects of this texture view are a subset of the aspects in the original texture. Aspects: {0:?}"
2822    )]
2823    Aspects(hal::FormatAspects),
2824    #[error("The texture view swizzle must be identity. View swizzle: {0:?}")]
2825    Swizzle(wgt::TextureComponentSwizzle),
2826}
2827
2828#[derive(Debug)]
2829pub struct TextureViewState {
2830    pub(crate) raw: Snatchable<Box<dyn hal::DynTextureView>>,
2831    /// This is `Err` only if the texture view is not renderable
2832    pub(crate) render_extent: Result<wgt::Extent3d, TextureViewNotRenderableReason>,
2833}
2834
2835#[derive(Debug)]
2836pub struct TextureView {
2837    pub(crate) state: ResourceState<TextureViewState>,
2838    // if it's a surface texture - it's none
2839    pub(crate) parent: Arc<Texture>,
2840    pub(crate) device: Arc<Device>,
2841    pub(crate) desc: HalTextureViewDescriptor,
2842    pub(crate) format_features: wgt::TextureFormatFeatures,
2843    pub(crate) samples: u32,
2844    pub(crate) selector: TextureSelector,
2845    /// The `label` from the descriptor used to create the resource.
2846    pub(crate) label: String,
2847}
2848
2849impl Drop for TextureView {
2850    #[expect(trivial_casts)]
2851    fn drop(&mut self) {
2852        profiling::scope!("TextureView::drop");
2853        api_log!("TextureView::drop {:?}", self as *const _);
2854        #[cfg(feature = "trace")]
2855        if let Some(t) = self.device.trace.lock().as_mut() {
2856            t.add(trace::Action::DropTextureView(unsafe {
2857                trace::to_trace(self)
2858            }));
2859        }
2860        let ResourceState::Valid(state) = &mut self.state else {
2861            return;
2862        };
2863
2864        if let Some(raw) = state.raw.take() {
2865            resource_log!("Destroy raw {}", self.error_ident());
2866            unsafe {
2867                self.device.raw().destroy_texture_view(raw);
2868            }
2869        }
2870    }
2871}
2872
2873impl RawResourceAccess for TextureView {
2874    type DynResource = dyn hal::DynTextureView;
2875
2876    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
2877        self.state()
2878            .ok()
2879            .and_then(|state| state.raw.get(guard).map(|it| it.as_ref()))
2880    }
2881
2882    fn try_raw<'a>(
2883        &'a self,
2884        guard: &'a SnatchGuard,
2885    ) -> Result<&'a Self::DynResource, DestroyedResourceError> {
2886        self.parent.check_destroyed(guard)?;
2887
2888        self.raw(guard)
2889            .ok_or_else(|| DestroyedResourceError(self.error_ident()))
2890    }
2891}
2892
2893impl TextureView {
2894    /// Checks that the given texture usage contains the required texture usage,
2895    /// returns an error otherwise.
2896    pub(crate) fn check_usage(
2897        &self,
2898        expected: wgt::TextureUsages,
2899    ) -> Result<(), MissingTextureUsageError> {
2900        if self.desc.usage.contains(expected) {
2901            Ok(())
2902        } else {
2903            Err(MissingTextureUsageError {
2904                res: self.error_ident(),
2905                actual: self.desc.usage,
2906                expected,
2907            })
2908        }
2909    }
2910
2911    pub(crate) fn state(&self) -> Result<&TextureViewState, InvalidResourceError> {
2912        match &self.state {
2913            ResourceState::Valid(state) => Ok(state),
2914            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
2915        }
2916    }
2917
2918    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
2919        self.state().map(|_| ())
2920    }
2921
2922    pub(crate) fn invalid(
2923        device: &Arc<Device>,
2924        texture: &Arc<Texture>,
2925        desc: &TextureViewDescriptor,
2926    ) -> Arc<Self> {
2927        // we do best effort to fill the descriptor with sensible values
2928        Arc::new(TextureView {
2929            state: ResourceState::Invalid,
2930            parent: texture.clone(),
2931            device: device.clone(),
2932            desc: HalTextureViewDescriptor {
2933                texture_format: texture.desc.format,
2934                format: desc.format.unwrap_or(texture.desc.format),
2935                usage: desc.usage.unwrap_or(texture.desc.usage),
2936                dimension: desc.dimension.unwrap_or(match texture.desc.dimension {
2937                    wgt::TextureDimension::D1 => wgt::TextureViewDimension::D1,
2938                    wgt::TextureDimension::D2 => wgt::TextureViewDimension::D2,
2939                    wgt::TextureDimension::D3 => wgt::TextureViewDimension::D3,
2940                }),
2941                range: desc.range,
2942                swizzle: desc.swizzle,
2943            },
2944            format_features: texture.format_features,
2945            samples: texture.desc.sample_count,
2946            selector: TextureSelector {
2947                mips: desc.range.mip_range(texture.desc.mip_level_count),
2948                layers: desc.range.layer_range(texture.desc.array_layer_count()),
2949            },
2950            label: desc.label.to_string(),
2951        })
2952    }
2953
2954    pub fn texture(&self) -> &Arc<Texture> {
2955        &self.parent
2956    }
2957}
2958
2959#[derive(Clone, Debug, Error)]
2960#[non_exhaustive]
2961pub enum CreateTextureViewError {
2962    #[error(transparent)]
2963    Device(#[from] DeviceError),
2964    #[error(transparent)]
2965    DestroyedResource(#[from] DestroyedResourceError),
2966    #[error("Invalid texture view dimension `{view:?}` with texture of dimension `{texture:?}`")]
2967    InvalidTextureViewDimension {
2968        view: wgt::TextureViewDimension,
2969        texture: wgt::TextureDimension,
2970    },
2971    #[error("Texture view format `{0:?}` cannot be used as a render attachment. Make sure the format supports RENDER_ATTACHMENT usage and required device features are enabled.")]
2972    TextureViewFormatNotRenderable(wgt::TextureFormat),
2973    #[error("Texture view format `{0:?}` cannot be used as a storage binding. Make sure the format supports STORAGE usage and required device features are enabled.")]
2974    TextureViewFormatNotStorage(wgt::TextureFormat),
2975    #[error("Texture view usages (`{view:?}`) must be a subset of the texture's original usages (`{texture:?}`)")]
2976    InvalidTextureViewUsage {
2977        view: wgt::TextureUsages,
2978        texture: wgt::TextureUsages,
2979    },
2980    #[error("Texture view dimension `{0:?}` cannot be used with a multisampled texture")]
2981    InvalidMultisampledTextureViewDimension(wgt::TextureViewDimension),
2982    #[error(
2983        "TextureView has an arrayLayerCount of {depth}. Views of type `Cube` must have arrayLayerCount of 6."
2984    )]
2985    InvalidCubemapTextureDepth { depth: u32 },
2986    #[error("TextureView has an arrayLayerCount of {depth}. Views of type `CubeArray` must have an arrayLayerCount that is a multiple of 6.")]
2987    InvalidCubemapArrayTextureDepth { depth: u32 },
2988    #[error("Source texture width and height must be equal for a texture view of dimension `Cube`/`CubeArray`")]
2989    InvalidCubeTextureViewSize,
2990    #[error("Mip level count is 0")]
2991    ZeroMipLevelCount,
2992    #[error("Array layer count is 0")]
2993    ZeroArrayLayerCount,
2994    #[error(
2995        "`TextureView` starts at mip level {base_mip_level} and spans {mip_level_count} mip \
2996        levels, but the texture view only has {total} total mip level(s)"
2997    )]
2998    TooManyMipLevels {
2999        base_mip_level: u32,
3000        mip_level_count: u32,
3001        total: u32,
3002    },
3003    #[error(
3004        "`TextureView` starts at array layer {base_array_layer} and spans {array_layer_count}) \
3005        array layers, but the texture view only has {total} total layer(s)"
3006    )]
3007    TooManyArrayLayers {
3008        base_array_layer: u32,
3009        array_layer_count: u32,
3010        total: u32,
3011    },
3012    #[error("Requested array layer count {requested} is not valid for the target view dimension {dim:?}")]
3013    InvalidArrayLayerCount {
3014        requested: u32,
3015        dim: wgt::TextureViewDimension,
3016    },
3017    #[error(
3018        "Aspect {requested_aspect:?} is not a valid aspect of the source texture format {texture_format:?}"
3019    )]
3020    InvalidAspect {
3021        texture_format: wgt::TextureFormat,
3022        requested_aspect: wgt::TextureAspect,
3023    },
3024    #[error(
3025        "Trying to create a view of format {view:?} of a texture with format {texture:?}, \
3026         but this view format is not present in the texture's viewFormat array"
3027    )]
3028    FormatReinterpretation {
3029        texture: wgt::TextureFormat,
3030        view: wgt::TextureFormat,
3031    },
3032    #[error(
3033        "The texture view (`{view:?}`) from transient texture (`{texture:?}`) must have the same usage"
3034    )]
3035    InvalidTransientTextureViewUsage {
3036        texture: wgt::TextureUsages,
3037        view: wgt::TextureUsages,
3038    },
3039    #[error(transparent)]
3040    InvalidResource(#[from] InvalidResourceError),
3041    #[error(transparent)]
3042    MissingFeatures(#[from] MissingFeatures),
3043
3044    #[error(
3045        "Trying to create a view of format {requested_format:?} on aspect {aspect:?} of format {texture:?}, \
3046         but the actual format of this aspect is {aspect_format:?}"
3047    )]
3048    WrongAspectReinterpretation {
3049        texture: wgt::TextureFormat,
3050        aspect: wgt::TextureAspect,
3051        aspect_format: wgt::TextureFormat,
3052        requested_format: wgt::TextureFormat,
3053    },
3054    #[error("TextureAspect::All cannot be used in texture views on multi-planar formats")]
3055    MultiplanarFullTexture(wgt::TextureFormat),
3056}
3057
3058impl From<InvalidOrDestroyedResourceError> for CreateTextureViewError {
3059    fn from(value: InvalidOrDestroyedResourceError) -> Self {
3060        match value {
3061            InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
3062            InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
3063        }
3064    }
3065}
3066
3067impl WebGpuError for CreateTextureViewError {
3068    fn webgpu_error_type(&self) -> ErrorType {
3069        match self {
3070            Self::Device(e) => e.webgpu_error_type(),
3071
3072            Self::InvalidTextureViewDimension { .. }
3073            | Self::InvalidResource(_)
3074            | Self::InvalidMultisampledTextureViewDimension(_)
3075            | Self::InvalidCubemapTextureDepth { .. }
3076            | Self::InvalidCubemapArrayTextureDepth { .. }
3077            | Self::InvalidCubeTextureViewSize
3078            | Self::ZeroMipLevelCount
3079            | Self::ZeroArrayLayerCount
3080            | Self::TooManyMipLevels { .. }
3081            | Self::TooManyArrayLayers { .. }
3082            | Self::InvalidArrayLayerCount { .. }
3083            | Self::InvalidAspect { .. }
3084            | Self::FormatReinterpretation { .. }
3085            | Self::DestroyedResource(_)
3086            | Self::TextureViewFormatNotRenderable(_)
3087            | Self::TextureViewFormatNotStorage(_)
3088            | Self::InvalidTextureViewUsage { .. }
3089            | Self::InvalidTransientTextureViewUsage { .. }
3090            | Self::MissingFeatures(_)
3091            | Self::WrongAspectReinterpretation { .. }
3092            | Self::MultiplanarFullTexture(_) => ErrorType::Validation,
3093        }
3094    }
3095}
3096
3097crate::impl_resource_type!(TextureView);
3098crate::impl_labeled!(TextureView);
3099crate::impl_parent_device!(TextureView);
3100crate::impl_storage_item!(TextureView);
3101
3102pub type ExternalTextureDescriptor<'a> = wgt::ExternalTextureDescriptor<Label<'a>>;
3103
3104#[derive(Debug)]
3105pub(crate) struct ExternalTextureState {
3106    /// Buffer containing a [`crate::device::resource::ExternalTextureParams`]
3107    /// describing the external texture.
3108    pub(crate) params: Arc<Buffer>,
3109}
3110
3111#[derive(Debug)]
3112pub struct ExternalTexture {
3113    pub(crate) state: ResourceState<ExternalTextureState>,
3114    pub(crate) device: Arc<Device>,
3115    /// Between 1 and 3 (inclusive) planes of texture data.
3116    pub(crate) planes: arrayvec::ArrayVec<Arc<TextureView>, 3>,
3117    /// The `label` from the descriptor used to create the resource.
3118    pub(crate) label: String,
3119    pub(crate) tracking_data: TrackingData,
3120}
3121
3122impl Drop for ExternalTexture {
3123    #[allow(trivial_casts)]
3124    fn drop(&mut self) {
3125        profiling::scope!("ExternalTexture::drop");
3126        api_log!("ExternalTexture::drop {:?}", self as *const _);
3127
3128        resource_log!("Destroy raw {}", self.error_ident());
3129        #[cfg(feature = "trace")]
3130        if let Some(t) = self.device.trace.lock().as_mut() {
3131            t.add(trace::Action::DropExternalTexture(unsafe {
3132                trace::to_trace(self)
3133            }));
3134        }
3135    }
3136}
3137
3138impl ExternalTexture {
3139    pub(crate) fn state(&self) -> Result<&ExternalTextureState, InvalidResourceError> {
3140        match &self.state {
3141            ResourceState::Valid(state) => Ok(state),
3142            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
3143        }
3144    }
3145
3146    pub fn destroy(self: &Arc<Self>) {
3147        profiling::scope!("ExternalTexture::destroy");
3148        api_log!("ExternalTexture::destroy {:?}", Arc::as_ptr(self));
3149
3150        #[cfg(feature = "trace")]
3151        if let Some(trace) = self.device.trace.lock().as_mut() {
3152            use crate::device::trace::IntoTrace as _;
3153
3154            trace.add(trace::Action::DestroyExternalTexture(self.to_trace()));
3155        }
3156        if let Ok(state) = self.state() {
3157            state.params.destroy();
3158        }
3159    }
3160
3161    pub fn invalid(device: Arc<Device>, desc: &ExternalTextureDescriptor) -> Arc<Self> {
3162        Arc::new(ExternalTexture {
3163            state: ResourceState::Invalid,
3164            planes: arrayvec::ArrayVec::new(),
3165            label: desc.label.to_string(),
3166            tracking_data: TrackingData::new(device.tracker_indices.external_textures.clone()),
3167            device,
3168        })
3169    }
3170}
3171
3172#[derive(Clone, Debug, Error)]
3173#[non_exhaustive]
3174pub enum CreateExternalTextureError {
3175    #[error(transparent)]
3176    Device(#[from] DeviceError),
3177    #[error(transparent)]
3178    MissingFeatures(#[from] MissingFeatures),
3179    #[error(transparent)]
3180    InvalidResource(#[from] InvalidResourceError),
3181    #[error(transparent)]
3182    CreateBuffer(#[from] CreateBufferError),
3183    #[error(transparent)]
3184    QueueWrite(#[from] queue::QueueWriteError),
3185    #[error("External texture format {format:?} expects {expected} planes, but given {provided}")]
3186    IncorrectPlaneCount {
3187        format: wgt::ExternalTextureFormat,
3188        expected: usize,
3189        provided: usize,
3190    },
3191    #[error("External texture planes cannot be multisampled, but given view with samples = {0}")]
3192    InvalidPlaneMultisample(u32),
3193    #[error("External texture planes expect a filterable float sample type, but given view with format {format:?} (sample type {sample_type:?})")]
3194    InvalidPlaneSampleType {
3195        format: wgt::TextureFormat,
3196        sample_type: wgt::TextureSampleType,
3197    },
3198    #[error("External texture planes expect 2D dimension, but given view with dimension = {0:?}")]
3199    InvalidPlaneDimension(wgt::TextureViewDimension),
3200    #[error(transparent)]
3201    MissingTextureUsage(#[from] MissingTextureUsageError),
3202    #[error("External texture format {format:?} plane {plane} expects format with {expected} components but given view with format {provided:?} ({} components)",
3203        provided.components())]
3204    InvalidPlaneFormat {
3205        format: wgt::ExternalTextureFormat,
3206        plane: usize,
3207        expected: u8,
3208        provided: wgt::TextureFormat,
3209    },
3210}
3211
3212impl WebGpuError for CreateExternalTextureError {
3213    fn webgpu_error_type(&self) -> ErrorType {
3214        match self {
3215            CreateExternalTextureError::Device(e) => e.webgpu_error_type(),
3216            CreateExternalTextureError::MissingFeatures(e) => e.webgpu_error_type(),
3217            CreateExternalTextureError::InvalidResource(e) => e.webgpu_error_type(),
3218            CreateExternalTextureError::CreateBuffer(e) => e.webgpu_error_type(),
3219            CreateExternalTextureError::QueueWrite(e) => e.webgpu_error_type(),
3220            CreateExternalTextureError::MissingTextureUsage(e) => e.webgpu_error_type(),
3221            CreateExternalTextureError::IncorrectPlaneCount { .. }
3222            | CreateExternalTextureError::InvalidPlaneMultisample(_)
3223            | CreateExternalTextureError::InvalidPlaneSampleType { .. }
3224            | CreateExternalTextureError::InvalidPlaneDimension(_)
3225            | CreateExternalTextureError::InvalidPlaneFormat { .. } => ErrorType::Validation,
3226        }
3227    }
3228}
3229
3230crate::impl_resource_type!(ExternalTexture);
3231crate::impl_labeled!(ExternalTexture);
3232crate::impl_parent_device!(ExternalTexture);
3233crate::impl_storage_item!(ExternalTexture);
3234crate::impl_trackable!(ExternalTexture);
3235
3236/// Describes a [`Sampler`]
3237#[derive(Clone, Debug, PartialEq)]
3238#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3239pub struct SamplerDescriptor<'a> {
3240    /// Debug label of the sampler.
3241    ///
3242    /// This will show up in graphics debuggers for easy identification.
3243    pub label: Label<'a>,
3244    /// How to deal with out of bounds accesses in the u (i.e. x) direction
3245    pub address_modes: [wgt::AddressMode; 3],
3246    /// How to filter the texture when it needs to be magnified (made larger)
3247    pub mag_filter: wgt::FilterMode,
3248    /// How to filter the texture when it needs to be minified (made smaller)
3249    pub min_filter: wgt::FilterMode,
3250    /// How to filter between mip map levels
3251    pub mipmap_filter: wgt::MipmapFilterMode,
3252    /// Minimum level of detail (i.e. mip level) to use
3253    pub lod_min_clamp: f32,
3254    /// Maximum level of detail (i.e. mip level) to use
3255    pub lod_max_clamp: f32,
3256    /// If this is enabled, this is a comparison sampler using the given comparison function.
3257    pub compare: Option<wgt::CompareFunction>,
3258    /// Must be at least 1. If this is not 1, all filter modes must be linear.
3259    pub anisotropy_clamp: u16,
3260    /// Border color to use when address_mode is
3261    /// [`AddressMode::ClampToBorder`](wgt::AddressMode::ClampToBorder)
3262    pub border_color: Option<wgt::SamplerBorderColor>,
3263}
3264
3265#[derive(Debug)]
3266pub struct Sampler {
3267    pub(crate) raw: ResourceState<Box<dyn hal::DynSampler>>,
3268    pub(crate) device: Arc<Device>,
3269    /// The `label` from the descriptor used to create the resource.
3270    pub(crate) label: String,
3271    pub(crate) tracking_data: TrackingData,
3272    /// `true` if this is a comparison sampler
3273    pub(crate) comparison: bool,
3274    /// `true` if this is a filtering sampler
3275    pub(crate) filtering: bool,
3276}
3277
3278impl Drop for Sampler {
3279    #[allow(trivial_casts)]
3280    fn drop(&mut self) {
3281        profiling::scope!("Sampler::drop");
3282        api_log!("Sampler::drop {:?}", self as *const _);
3283        #[cfg(feature = "trace")]
3284        if let Some(t) = self.device.trace.lock().as_mut() {
3285            t.add(trace::Action::DropSampler(unsafe { trace::to_trace(self) }));
3286        }
3287        resource_log!("Destroy raw {}", self.error_ident());
3288        if let ResourceState::Valid(raw) = mem::replace(&mut self.raw, ResourceState::Invalid) {
3289            unsafe {
3290                self.device.raw().destroy_sampler(raw);
3291            }
3292        }
3293    }
3294}
3295
3296impl Sampler {
3297    pub(crate) fn raw(&self) -> Result<&dyn hal::DynSampler, InvalidResourceError> {
3298        self.raw
3299            .as_ref()
3300            .valid()
3301            .map(|raw| raw.as_ref())
3302            .ok_or_else(|| InvalidResourceError(self.error_ident()))
3303    }
3304
3305    pub(crate) fn invalid(device: Arc<Device>, desc: &SamplerDescriptor) -> Arc<Self> {
3306        Arc::new(Sampler {
3307            raw: ResourceState::Invalid,
3308            label: desc.label.to_string(),
3309            tracking_data: TrackingData::new(device.tracker_indices.samplers.clone()),
3310            device,
3311            comparison: desc.compare.is_some(),
3312            filtering: desc.mag_filter == wgt::FilterMode::Linear
3313                || desc.min_filter == wgt::FilterMode::Linear
3314                || desc.mipmap_filter == wgt::MipmapFilterMode::Linear,
3315        })
3316    }
3317}
3318
3319#[derive(Copy, Clone)]
3320pub enum SamplerFilterErrorType {
3321    MagFilter,
3322    MinFilter,
3323    MipmapFilter,
3324}
3325
3326impl fmt::Debug for SamplerFilterErrorType {
3327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3328        match *self {
3329            SamplerFilterErrorType::MagFilter => write!(f, "magFilter"),
3330            SamplerFilterErrorType::MinFilter => write!(f, "minFilter"),
3331            SamplerFilterErrorType::MipmapFilter => write!(f, "mipmapFilter"),
3332        }
3333    }
3334}
3335
3336#[derive(Clone, Debug, Error)]
3337#[non_exhaustive]
3338pub enum CreateSamplerError {
3339    #[error(transparent)]
3340    Device(#[from] DeviceError),
3341    #[error("Invalid lodMinClamp: {0}. Must be greater or equal to 0.0")]
3342    InvalidLodMinClamp(f32),
3343    #[error("Invalid lodMaxClamp: {lod_max_clamp}. Must be greater or equal to lodMinClamp (which is {lod_min_clamp}).")]
3344    InvalidLodMaxClamp {
3345        lod_min_clamp: f32,
3346        lod_max_clamp: f32,
3347    },
3348    #[error("Invalid anisotropic clamp: {0}. Must be at least 1.")]
3349    InvalidAnisotropy(u16),
3350    #[error("Invalid filter mode for {filter_type:?}: {filter_mode:?}. When anistropic clamp is not 1 (it is {anisotropic_clamp}), all filter modes must be linear.")]
3351    InvalidFilterModeWithAnisotropy {
3352        filter_type: SamplerFilterErrorType,
3353        filter_mode: wgt::FilterMode,
3354        anisotropic_clamp: u16,
3355    },
3356    #[error("Invalid filter mode for {filter_type:?}: {filter_mode:?}. When anistropic clamp is not 1 (it is {anisotropic_clamp}), all filter modes must be linear.")]
3357    InvalidMipmapFilterModeWithAnisotropy {
3358        filter_type: SamplerFilterErrorType,
3359        filter_mode: wgt::MipmapFilterMode,
3360        anisotropic_clamp: u16,
3361    },
3362    #[error(transparent)]
3363    MissingFeatures(#[from] MissingFeatures),
3364}
3365
3366crate::impl_resource_type!(Sampler);
3367crate::impl_labeled!(Sampler);
3368crate::impl_parent_device!(Sampler);
3369crate::impl_storage_item!(Sampler);
3370crate::impl_trackable!(Sampler);
3371
3372impl WebGpuError for CreateSamplerError {
3373    fn webgpu_error_type(&self) -> ErrorType {
3374        match self {
3375            Self::Device(e) => e.webgpu_error_type(),
3376            Self::MissingFeatures(e) => e.webgpu_error_type(),
3377
3378            Self::InvalidLodMinClamp(_)
3379            | Self::InvalidLodMaxClamp { .. }
3380            | Self::InvalidAnisotropy(_)
3381            | Self::InvalidFilterModeWithAnisotropy { .. }
3382            | Self::InvalidMipmapFilterModeWithAnisotropy { .. } => ErrorType::Validation,
3383        }
3384    }
3385}
3386
3387#[derive(Clone, Debug, Error)]
3388#[non_exhaustive]
3389pub enum CreateQuerySetError {
3390    #[error(transparent)]
3391    Device(#[from] DeviceError),
3392    #[error("QuerySets cannot be made with zero queries")]
3393    ZeroCount,
3394    #[error("{count} is too many queries for a single QuerySet. QuerySets cannot be made more than {maximum} queries.")]
3395    TooManyQueries { count: u32, maximum: u32 },
3396    #[error(transparent)]
3397    MissingFeatures(#[from] MissingFeatures),
3398}
3399
3400impl WebGpuError for CreateQuerySetError {
3401    fn webgpu_error_type(&self) -> ErrorType {
3402        match self {
3403            Self::Device(e) => e.webgpu_error_type(),
3404            Self::MissingFeatures(e) => e.webgpu_error_type(),
3405
3406            Self::TooManyQueries { .. } | Self::ZeroCount => ErrorType::Validation,
3407        }
3408    }
3409}
3410
3411pub type QuerySetDescriptor<'a> = wgt::QuerySetDescriptor<Label<'a>>;
3412
3413#[derive(Debug)]
3414pub(crate) struct QuerySetState {
3415    pub(crate) raw: Snatchable<Box<dyn hal::DynQuerySet>>,
3416}
3417
3418#[derive(Debug)]
3419pub struct QuerySet {
3420    pub(crate) state: ResourceState<QuerySetState>,
3421    pub(crate) device: Arc<Device>,
3422    pub(crate) tracking_data: TrackingData,
3423    pub(crate) desc: wgt::QuerySetDescriptor<String>,
3424    pub(crate) initialized_slots: Mutex<bit_vec::BitVec>,
3425}
3426
3427impl RawResourceAccess for QuerySet {
3428    type DynResource = dyn hal::DynQuerySet;
3429
3430    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
3431        self.state().ok()?.raw.get(guard).map(|b| b.as_ref())
3432    }
3433}
3434
3435impl QuerySet {
3436    pub(crate) fn state(&self) -> Result<&QuerySetState, InvalidResourceError> {
3437        match &self.state {
3438            ResourceState::Valid(state) => Ok(state),
3439            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
3440        }
3441    }
3442
3443    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
3444        self.state().map(|_| ())
3445    }
3446
3447    pub fn invalid(device: Arc<Device>, desc: &QuerySetDescriptor) -> Arc<Self> {
3448        Arc::new(QuerySet {
3449            state: ResourceState::Invalid,
3450            tracking_data: TrackingData::new(device.tracker_indices.query_sets.clone()),
3451            desc: desc.map_label(|l| l.to_string()),
3452            initialized_slots: Mutex::new(
3453                rank::QUERY_SET_INITIALIZED_SLOTS,
3454                bit_vec::BitVec::new(),
3455            ),
3456            device,
3457        })
3458    }
3459
3460    pub fn destroy(self: &Arc<Self>) {
3461        let device = &self.device;
3462
3463        profiling::scope!("QuerySet::destroy");
3464        api_log!("QuerySet::destroy {:?}", Arc::as_ptr(self));
3465
3466        #[cfg(feature = "trace")]
3467        if let Some(trace) = device.trace.lock().as_mut() {
3468            use crate::device::trace::IntoTrace as _;
3469
3470            trace.add(trace::Action::DestroyQuerySet(self.to_trace()));
3471        };
3472
3473        let ResourceState::Valid(state) = &self.state else {
3474            return;
3475        };
3476
3477        let temp = {
3478            let mut snatch_guard = self.device.snatchable_lock.write();
3479
3480            let raw = match state.raw.snatch(&mut snatch_guard) {
3481                Some(raw) => raw,
3482                None => {
3483                    // Per spec, it is valid to call `destroy` multiple times.
3484                    return;
3485                }
3486            };
3487
3488            drop(snatch_guard);
3489
3490            queue::TempResource::DestroyedQuerySet(DestroyedQuerySet {
3491                raw: ManuallyDrop::new(raw),
3492                device: Arc::clone(&self.device),
3493                label: self.label().to_owned(),
3494            })
3495        };
3496
3497        let Some(queue) = device.get_queue() else {
3498            return;
3499        };
3500
3501        let mut life_lock = queue.lock_life();
3502        let last_submit_index = life_lock.get_query_set_latest_submission_index(self);
3503        if let Some(last_submit_index) = last_submit_index {
3504            life_lock.schedule_resource_destruction(temp, last_submit_index);
3505        }
3506    }
3507
3508    pub fn descriptor(&self) -> &wgt::QuerySetDescriptor<String> {
3509        &self.desc
3510    }
3511}
3512
3513impl Drop for QuerySet {
3514    #[allow(trivial_casts)]
3515    fn drop(&mut self) {
3516        profiling::scope!("QuerySet::drop");
3517        api_log!("QuerySet::drop {:?}", self as *const _);
3518        resource_log!("Destroy raw {}", self.error_ident());
3519        #[cfg(feature = "trace")]
3520        if let Some(trace) = self.device.trace.lock().as_mut() {
3521            use crate::device::trace::to_trace;
3522
3523            trace.add(trace::Action::DropQuerySet(unsafe { to_trace(self) }));
3524        }
3525        let ResourceState::Valid(state) = &mut self.state else {
3526            return;
3527        };
3528        if let Some(raw) = state.raw.take() {
3529            // SAFETY: We are in the Drop impl and we don't use raw anymore after this point.
3530            unsafe {
3531                self.device.raw().destroy_query_set(raw);
3532            }
3533        }
3534    }
3535}
3536
3537crate::impl_resource_type!(QuerySet);
3538impl Labeled for QuerySet {
3539    fn label(&self) -> &str {
3540        &self.desc.label
3541    }
3542}
3543crate::impl_parent_device!(QuerySet);
3544crate::impl_storage_item!(QuerySet);
3545crate::impl_trackable!(QuerySet);
3546
3547/// A query set that has been marked as destroyed and is staged for actual deletion soon
3548#[derive(Debug)]
3549pub struct DestroyedQuerySet {
3550    raw: ManuallyDrop<Box<dyn hal::DynQuerySet>>,
3551    device: Arc<Device>,
3552    label: String,
3553}
3554
3555impl DestroyedQuerySet {
3556    pub fn label(&self) -> &dyn fmt::Debug {
3557        &self.label
3558    }
3559}
3560
3561impl Drop for DestroyedQuerySet {
3562    fn drop(&mut self) {
3563        resource_log!("Destroy raw QuerySet (destroyed) {:?}", self.label());
3564        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
3565        let raw = unsafe { ManuallyDrop::take(&mut self.raw) };
3566        unsafe {
3567            hal::DynDevice::destroy_query_set(self.device.raw(), raw);
3568        }
3569    }
3570}
3571
3572pub type BlasDescriptor<'a> = wgt::CreateBlasDescriptor<Label<'a>>;
3573pub type TlasDescriptor<'a> = wgt::CreateTlasDescriptor<Label<'a>>;
3574
3575pub type BlasPrepareCompactResult = Result<(), BlasPrepareCompactError>;
3576
3577#[cfg(send_sync)]
3578pub type BlasCompactCallback = Box<dyn FnOnce(BlasPrepareCompactResult) + Send + 'static>;
3579#[cfg(not(send_sync))]
3580pub type BlasCompactCallback = Box<dyn FnOnce(BlasPrepareCompactResult) + 'static>;
3581
3582pub(crate) struct BlasPendingCompact {
3583    pub(crate) op: Option<BlasCompactCallback>,
3584    // hold the parent alive while the mapping is active
3585    pub(crate) _parent_blas: Arc<Blas>,
3586}
3587
3588impl fmt::Debug for BlasPendingCompact {
3589    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3590        f.debug_struct("BlasPendingCompact")
3591            .field("op", &())
3592            .field("_parent_blas", &self._parent_blas)
3593            .finish()
3594    }
3595}
3596
3597#[derive(Debug)]
3598pub(crate) enum BlasCompactState {
3599    /// Created from a compact operation.
3600    Compacted,
3601    /// Waiting for GPU to be done before mapping to get compacted size
3602    Waiting(BlasPendingCompact),
3603    /// Ready to be compacted
3604    Ready { size: wgt::BufferAddress },
3605    /// Ready to prepare to compact.
3606    Idle,
3607}
3608
3609#[cfg(send_sync)]
3610unsafe impl Send for BlasCompactState {}
3611#[cfg(send_sync)]
3612unsafe impl Sync for BlasCompactState {}
3613
3614#[derive(Debug)]
3615pub(crate) struct BlasState {
3616    pub(crate) raw: Snatchable<Box<dyn hal::DynAccelerationStructure>>,
3617}
3618
3619#[derive(Debug)]
3620pub struct Blas {
3621    pub(crate) state: ResourceState<BlasState>,
3622    pub(crate) device: Arc<Device>,
3623    pub(crate) size_info: hal::AccelerationStructureBuildSizes,
3624    pub(crate) sizes: wgt::BlasGeometrySizeDescriptors,
3625    pub(crate) flags: wgt::AccelerationStructureFlags,
3626    pub(crate) update_mode: wgt::AccelerationStructureUpdateMode,
3627    pub(crate) built_index: RwLock<Option<NonZeroU64>>,
3628    pub(crate) handle: u64,
3629    /// The `label` from the descriptor used to create the resource.
3630    pub(crate) label: String,
3631    pub(crate) tracking_data: TrackingData,
3632    pub(crate) compaction_buffer: Option<ManuallyDrop<Box<dyn hal::DynBuffer>>>,
3633    pub(crate) compacted_state: Mutex<BlasCompactState>,
3634}
3635
3636impl Drop for Blas {
3637    #[allow(trivial_casts)]
3638    fn drop(&mut self) {
3639        profiling::scope!("Blas::drop");
3640        api_log!("Blas::drop {:?}", self as *const _);
3641        #[cfg(feature = "trace")]
3642        if let Some(t) = self.device.trace.lock().as_mut() {
3643            use crate::device::trace::{to_trace, Action};
3644            t.add(Action::DropBlas(unsafe { to_trace(self) }));
3645        }
3646        resource_log!("Destroy raw {}", self.error_ident());
3647        // SAFETY: We are in the Drop impl, and we don't use self.raw or self.compaction_buffer anymore after this point.
3648        if let ResourceState::Valid(state) = &mut self.state {
3649            if let Some(raw) = state.raw.take() {
3650                unsafe {
3651                    self.device.raw().destroy_acceleration_structure(raw);
3652                }
3653            }
3654        }
3655        if let Some(mut raw) = self.compaction_buffer.take() {
3656            unsafe {
3657                self.device
3658                    .raw()
3659                    .destroy_buffer(ManuallyDrop::take(&mut raw))
3660            }
3661        }
3662    }
3663}
3664
3665impl RawResourceAccess for Blas {
3666    type DynResource = dyn hal::DynAccelerationStructure;
3667
3668    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
3669        self.state().ok()?.raw.get(guard).map(|it| it.as_ref())
3670    }
3671}
3672
3673impl Blas {
3674    pub(crate) fn state(&self) -> Result<&BlasState, InvalidResourceError> {
3675        match &self.state {
3676            ResourceState::Valid(state) => Ok(state),
3677            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
3678        }
3679    }
3680
3681    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
3682        self.state().map(|_| ())
3683    }
3684
3685    pub(crate) fn invalid(device: Arc<Device>, desc: &BlasDescriptor) -> Arc<Self> {
3686        Arc::new(Blas {
3687            state: ResourceState::Invalid,
3688            size_info: hal::AccelerationStructureBuildSizes {
3689                acceleration_structure_size: 0,
3690                update_scratch_size: 0,
3691                build_scratch_size: 0,
3692            },
3693            sizes: wgt::BlasGeometrySizeDescriptors::Triangles {
3694                descriptors: Vec::new(),
3695            },
3696            flags: desc.flags,
3697            update_mode: desc.update_mode,
3698            built_index: RwLock::new(rank::BLAS_BUILT_INDEX, None),
3699            handle: 0,
3700            label: desc.label.to_string(),
3701            tracking_data: TrackingData::new(device.tracker_indices.blas_s.clone()),
3702            device,
3703            compaction_buffer: None,
3704            compacted_state: Mutex::new(rank::BLAS_COMPACTION_STATE, BlasCompactState::Idle),
3705        })
3706    }
3707
3708    pub fn handle(&self) -> Option<u64> {
3709        Some(self.handle)
3710    }
3711
3712    pub fn ready_for_compaction(self: &Arc<Self>) -> Result<bool, InvalidResourceError> {
3713        profiling::scope!("Blas::prepare_compact_async");
3714        api_log!("Blas::prepare_compact_async {:?}", Arc::as_ptr(self));
3715
3716        self.check_is_valid()?;
3717        let state = self.compacted_state.lock();
3718        Ok(matches!(*state, BlasCompactState::Ready { .. }))
3719    }
3720
3721    pub fn prepare_compact_async(
3722        self: &Arc<Self>,
3723        callback: Option<BlasCompactCallback>,
3724    ) -> Result<SubmissionIndex, BlasPrepareCompactError> {
3725        profiling::scope!("Blas::prepare_compact_async");
3726        api_log!("Blas::prepare_compact_async {:?}", Arc::as_ptr(self));
3727
3728        let compact_result = self.prepare_compact_async_inner(callback);
3729
3730        match compact_result {
3731            Ok(submission_index) => Ok(submission_index),
3732            Err((mut callback, err)) => {
3733                if let Some(callback) = callback.take() {
3734                    callback(Err(err.clone()));
3735                }
3736                Err(err)
3737            }
3738        }
3739    }
3740
3741    fn prepare_compact_async_inner(
3742        self: &Arc<Self>,
3743        op: Option<BlasCompactCallback>,
3744    ) -> Result<SubmissionIndex, (Option<BlasCompactCallback>, BlasPrepareCompactError)> {
3745        let device = &self.device;
3746        if let Err(e) = device.check_is_valid() {
3747            return Err((op, e.into()));
3748        }
3749
3750        if let Err(e) = self.check_is_valid() {
3751            return Err((op, e.into()));
3752        }
3753
3754        if self.built_index.read().is_none() {
3755            return Err((op, BlasPrepareCompactError::NotBuilt));
3756        }
3757
3758        if !self
3759            .flags
3760            .contains(wgt::AccelerationStructureFlags::ALLOW_COMPACTION)
3761        {
3762            return Err((op, BlasPrepareCompactError::CompactionUnsupported));
3763        }
3764
3765        let mut state = self.compacted_state.lock();
3766        *state = match *state {
3767            BlasCompactState::Compacted => {
3768                return Err((op, BlasPrepareCompactError::DoubleCompaction))
3769            }
3770            BlasCompactState::Waiting(_) => {
3771                return Err((op, BlasPrepareCompactError::CompactionPreparingAlready))
3772            }
3773            BlasCompactState::Ready { .. } => {
3774                return Err((op, BlasPrepareCompactError::CompactionPreparingAlready))
3775            }
3776            BlasCompactState::Idle => BlasCompactState::Waiting(BlasPendingCompact {
3777                op,
3778                _parent_blas: self.clone(),
3779            }),
3780        };
3781
3782        let submit_index = if let Some(queue) = device.get_queue() {
3783            drop(state);
3784            queue.lock_life().prepare_compact(self).unwrap_or(0) // '0' means no wait is necessary
3785        } else {
3786            // We can safely unwrap below since we just set the `compacted_state` to `BlasCompactState::Waiting`.
3787            let (mut callback, status) = self.read_back_compact_size(state).unwrap();
3788            if let Some(callback) = callback.take() {
3789                callback(status);
3790            }
3791            0
3792        };
3793
3794        Ok(submit_index)
3795    }
3796
3797    /// This function returns [`None`] only if [`Self::compacted_state`] is not [`BlasCompactState::Waiting`].
3798    #[must_use]
3799    pub(crate) fn read_back_compact_size(
3800        &self,
3801        mut state: MutexGuard<'_, BlasCompactState>,
3802    ) -> Option<BlasCompactReadyPendingClosure> {
3803        let pending_compact = match mem::replace(&mut *state, BlasCompactState::Idle) {
3804            BlasCompactState::Waiting(pending_mapping) => pending_mapping,
3805            // Compaction cancelled e.g. by rebuild
3806            BlasCompactState::Idle => return None,
3807            BlasCompactState::Ready { .. } => {
3808                unreachable!("This should be validated out by `prepare_for_compaction`")
3809            }
3810            _ => panic!("No pending mapping."),
3811        };
3812        let status = {
3813            let compaction_buffer = self.compaction_buffer.as_ref().unwrap().as_ref();
3814            unsafe {
3815                let map_res = self.device.raw().map_buffer(
3816                    compaction_buffer,
3817                    0..size_of::<wgpu_types::BufferAddress>() as wgt::BufferAddress,
3818                );
3819                match map_res {
3820                    Ok(mapping) => {
3821                        if !mapping.is_coherent {
3822                            #[expect(clippy::single_range_in_vec_init, reason = "intentional")]
3823                            self.device.raw().invalidate_mapped_ranges(
3824                                compaction_buffer,
3825                                &[0..size_of::<wgpu_types::BufferAddress>() as wgt::BufferAddress],
3826                            );
3827                        }
3828                        let size = core::ptr::read_unaligned(
3829                            mapping.ptr.as_ptr().cast::<wgt::BufferAddress>(),
3830                        );
3831                        self.device.raw().unmap_buffer(compaction_buffer);
3832                        if self.size_info.acceleration_structure_size != 0 {
3833                            debug_assert_ne!(size, 0);
3834                        }
3835                        *state = BlasCompactState::Ready { size };
3836                        Ok(())
3837                    }
3838                    Err(err) => Err(BlasPrepareCompactError::from(DeviceError::from_hal(err))),
3839                }
3840            }
3841        };
3842        Some((pending_compact.op, status))
3843    }
3844}
3845
3846crate::impl_resource_type!(Blas);
3847crate::impl_labeled!(Blas);
3848crate::impl_parent_device!(Blas);
3849crate::impl_storage_item!(Blas);
3850crate::impl_trackable!(Blas);
3851
3852#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3853pub(crate) struct TlasIntersectionType {
3854    pub(crate) index: u32,
3855    pub(crate) required_intersection_ty: crate::ray_tracing_pipeline::RayTracingIntersectionType,
3856}
3857
3858#[derive(Debug)]
3859pub(crate) struct TlasState {
3860    pub(crate) raw: Snatchable<Box<dyn hal::DynAccelerationStructure>>,
3861    pub(crate) instance_buffer: Box<dyn hal::DynBuffer>,
3862}
3863
3864#[derive(Debug)]
3865pub struct Tlas {
3866    pub(crate) state: ResourceState<TlasState>,
3867    pub(crate) device: Arc<Device>,
3868    pub(crate) size_info: hal::AccelerationStructureBuildSizes,
3869    pub(crate) max_instance_count: u32,
3870    pub(crate) flags: wgt::AccelerationStructureFlags,
3871    pub(crate) update_mode: wgt::AccelerationStructureUpdateMode,
3872    pub(crate) built_index: RwLock<Option<NonZeroU64>>,
3873    pub(crate) dependencies: RwLock<Vec<Arc<Blas>>>,
3874    pub(crate) max_intersection_index: RwLock<Option<u32>>,
3875    /// The `label` from the descriptor used to create the resource.
3876    pub(crate) label: String,
3877    pub(crate) tracking_data: TrackingData,
3878    /// The intersections that are required to be of a certain type
3879    /// if using a ray tracing pipeline.
3880    pub(crate) required_intersection_types: RwLock<Vec<TlasIntersectionType>>,
3881}
3882
3883impl Drop for Tlas {
3884    #[allow(trivial_casts)]
3885    fn drop(&mut self) {
3886        profiling::scope!("Tlas::drop");
3887        api_log!("Tlas::drop {:?}", self as *const _);
3888
3889        #[cfg(feature = "trace")]
3890        if let Some(t) = self.device.trace.lock().as_mut() {
3891            use crate::device::trace::{to_trace, Action};
3892            t.add(Action::DropTlas(unsafe { to_trace(self) }));
3893        }
3894
3895        resource_log!("Destroy raw {}", self.error_ident());
3896        let ResourceState::Valid(mut state) = mem::replace(&mut self.state, ResourceState::Invalid)
3897        else {
3898            return;
3899        };
3900        if let Some(structure) = state.raw.take() {
3901            unsafe { self.device.raw().destroy_acceleration_structure(structure) };
3902        }
3903        unsafe { self.device.raw().destroy_buffer(state.instance_buffer) };
3904    }
3905}
3906
3907impl Tlas {
3908    pub(crate) fn state(&self) -> Result<&TlasState, InvalidResourceError> {
3909        match &self.state {
3910            ResourceState::Valid(state) => Ok(state),
3911            ResourceState::Invalid => Err(InvalidResourceError(self.error_ident())),
3912        }
3913    }
3914
3915    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
3916        self.state().map(|_| ())
3917    }
3918
3919    pub(crate) fn invalid(device: Arc<Device>, desc: &TlasDescriptor) -> Arc<Self> {
3920        Arc::new(Self {
3921            state: ResourceState::Invalid,
3922            label: desc.label.to_string(),
3923            tracking_data: TrackingData::new(device.tracker_indices.tlas_s.clone()),
3924            size_info: hal::AccelerationStructureBuildSizes {
3925                acceleration_structure_size: 0,
3926                update_scratch_size: 0,
3927                build_scratch_size: 0,
3928            },
3929            max_instance_count: desc.max_instances,
3930            flags: desc.flags,
3931            update_mode: desc.update_mode,
3932            built_index: RwLock::new(rank::TLAS_BUILT_INDEX, None),
3933            dependencies: RwLock::new(rank::TLAS_DEPENDENCIES, Vec::new()),
3934            device,
3935            max_intersection_index: RwLock::new(rank::TLAS_MAX_INTERSECTION_IDX, None),
3936            required_intersection_types: RwLock::new(
3937                rank::TLAS_REQUIRED_INTERSECTION_TYPES,
3938                Vec::new(),
3939            ),
3940        })
3941    }
3942}
3943
3944impl RawResourceAccess for Tlas {
3945    type DynResource = dyn hal::DynAccelerationStructure;
3946
3947    fn raw<'a>(&'a self, guard: &'a SnatchGuard) -> Option<&'a Self::DynResource> {
3948        self.state().ok()?.raw.get(guard).map(|raw| raw.as_ref())
3949    }
3950}
3951
3952crate::impl_resource_type!(Tlas);
3953crate::impl_labeled!(Tlas);
3954crate::impl_parent_device!(Tlas);
3955crate::impl_storage_item!(Tlas);
3956crate::impl_trackable!(Tlas);