forked from gfx-rs/wgpu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource.rs
More file actions
5688 lines (5100 loc) · 221 KB
/
Copy pathresource.rs
File metadata and controls
5688 lines (5100 loc) · 221 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use alloc::{
borrow::Cow,
boxed::Box,
string::{String, ToString as _},
sync::{Arc, Weak},
vec::Vec,
};
use core::{
fmt,
mem::{self, ManuallyDrop},
num::NonZeroU32,
sync::atomic::{AtomicBool, Ordering},
};
use hal::ShouldBeNonZeroExt;
use arrayvec::ArrayVec;
use bitflags::Flags;
use smallvec::SmallVec;
use wgt::{
math::align_to, ColorWrites, DeviceLostReason, TextureFormat, TextureSampleType,
TextureViewDimension,
};
#[cfg(feature = "trace")]
use crate::device::trace::{self, IntoTrace as _};
use crate::{
api_log,
binding_model::{
self, BindGroup, BindGroupLateBufferBindingInfo, BindGroupLayout,
BindGroupLayoutEntryError, BindGroupLayoutState, BindGroupState, CreateBindGroupError,
CreateBindGroupLayoutError,
},
command, conv,
device::{
bgl, create_validator, life::WaitIdleError, map_buffer, AttachmentData,
BufferMapPendingClosure, DeviceLostInvocation, HostMap, MissingDownlevelFlags,
MissingFeatures, RenderPassContext,
},
hal_label,
init_tracker::{
BufferInitTracker, BufferInitTrackerAction, MemoryInitKind, TextureInitRange,
TextureInitTrackerAction,
},
instance::{Adapter, RequestDeviceError},
lock::{rank, Mutex, RwLock},
pipeline::{self, ColorStateError},
pool::ResourcePool,
resource::{
self, Buffer, BufferState, ExternalTexture, ExternalTextureState, Labeled, ParentDevice,
QuerySet, QuerySetState, RawResourceAccess, ResourceState, Sampler, StagingBuffer, Texture,
TextureView, Tlas, TrackingData,
},
resource_log,
snatch::{SnatchGuard, SnatchLock, Snatchable},
timestamp_normalization::TIMESTAMP_NORMALIZATION_BUFFER_USES,
track::{BindGroupStates, DeviceTracker, TrackerIndexAllocators, UsageScope, UsageScopePool},
validation::{self, check_color_attachment_count, PassthroughInterface, ShaderMetaData},
weak_vec::WeakVec,
FastHashMap, LabelHelpers, OnceCellOrLock,
};
use super::{
queue::Queue, DeviceDescriptor, DeviceError, DeviceLostClosure, UserClosures,
ENTRYPOINT_FAILURE_ERROR, ZERO_BUFFER_SIZE,
};
#[cfg(supports_64bit_atomics)]
use core::sync::atomic::AtomicU64;
#[cfg(not(supports_64bit_atomics))]
use portable_atomic::AtomicU64;
pub(crate) struct CommandIndices {
/// The index of the last command submission that was attempted.
///
/// Note that `fence` may never be signalled with this value, if the command
/// submission failed. If you need to wait for everything running on a
/// `Queue` to complete, wait for [`last_successful_submission_index`].
///
/// [`last_successful_submission_index`]: Device::last_successful_submission_index
pub(crate) active_submission_index: hal::FenceValue,
pub(crate) next_acceleration_structure_build_command_index: u64,
}
/// Parameters provided to shaders via a uniform buffer of the type
/// [`NagaExternalTextureParams`], describing an [`ExternalTexture`] resource
/// binding.
///
/// [`NagaExternalTextureParams`]: naga::SpecialTypes::external_texture_params
/// [`ExternalTexture`]: binding_model::BindingResource::ExternalTexture
#[repr(C)]
#[derive(Copy, Clone, bytemuck::Zeroable, bytemuck::Pod)]
pub struct ExternalTextureParams {
/// 4x4 column-major matrix with which to convert sampled YCbCr values
/// to RGBA.
///
/// This is ignored when `num_planes` is 1.
pub yuv_conversion_matrix: [f32; 16],
/// 3x3 column-major matrix to transform linear RGB values in the source
/// color space to linear RGB values in the destination color space. In
/// combination with [`Self::src_transfer_function`] and
/// [`Self::dst_transfer_function`] this can be used to ensure that
/// [`ImageSample`] and [`ImageLoad`] operations return values in the
/// desired destination color space rather than the source color space of
/// the underlying planes.
///
/// Includes a padding element after each column.
///
/// [`ImageSample`]: naga::ir::Expression::ImageSample
/// [`ImageLoad`]: naga::ir::Expression::ImageLoad
pub gamut_conversion_matrix: [f32; 12],
/// Transfer function for the source color space. The *inverse* of this
/// will be applied to decode non-linear RGB to linear RGB in the source
/// color space.
pub src_transfer_function: wgt::ExternalTextureTransferFunction,
/// Transfer function for the destination color space. This will be applied
/// to encode linear RGB to non-linear RGB in the destination color space.
pub dst_transfer_function: wgt::ExternalTextureTransferFunction,
/// Transform to apply to [`ImageSample`] coordinates.
///
/// This is a 3x2 column-major matrix representing an affine transform from
/// normalized texture coordinates to the normalized coordinates that should
/// be sampled from the external texture's underlying plane(s).
///
/// This transform may scale, translate, flip, and rotate in 90-degree
/// increments, but the result of transforming the rectangle (0,0)..(1,1)
/// must be an axis-aligned rectangle that falls within the bounds of
/// (0,0)..(1,1).
///
/// [`ImageSample`]: naga::ir::Expression::ImageSample
pub sample_transform: [f32; 6],
/// Transform to apply to [`ImageLoad`] coordinates.
///
/// This is a 3x2 column-major matrix representing an affine transform from
/// non-normalized texel coordinates to the non-normalized coordinates of
/// the texel that should be loaded from the external texture's underlying
/// plane 0. For planes 1 and 2, if present, plane 0's coordinates are
/// scaled according to the textures' relative sizes.
///
/// This transform may scale, translate, flip, and rotate in 90-degree
/// increments, but the result of transforming the rectangle (0,0)..[`size`]
/// must be an axis-aligned rectangle that falls within the bounds of
/// (0,0)..[`size`].
///
/// [`ImageLoad`]: naga::ir::Expression::ImageLoad
/// [`size`]: Self::size
pub load_transform: [f32; 6],
/// Size of the external texture.
///
/// This is the value that should be returned by size queries in shader
/// code; it does not necessarily match the dimensions of the underlying
/// texture(s). As a special case, if this is `[0, 0]`, the actual size of
/// plane 0 should be used instead.
///
/// This must be consistent with [`sample_transform`]: it should be the size
/// in texels of the rectangle covered by the square (0,0)..(1,1) after
/// [`sample_transform`] has been applied to it.
///
/// [`sample_transform`]: Self::sample_transform
pub size: [u32; 2],
/// Number of planes. 1 indicates a single RGBA plane. 2 indicates a Y
/// plane and an interleaved CbCr plane. 3 indicates separate Y, Cb, and Cr
/// planes.
pub num_planes: u32,
// Ensure the size of this struct matches the type generated by Naga.
pub _padding: [u8; 4],
}
impl ExternalTextureParams {
pub fn from_desc<L>(desc: &wgt::ExternalTextureDescriptor<L>) -> Self {
let gamut_conversion_matrix = [
desc.gamut_conversion_matrix[0],
desc.gamut_conversion_matrix[1],
desc.gamut_conversion_matrix[2],
0.0, // padding
desc.gamut_conversion_matrix[3],
desc.gamut_conversion_matrix[4],
desc.gamut_conversion_matrix[5],
0.0, // padding
desc.gamut_conversion_matrix[6],
desc.gamut_conversion_matrix[7],
desc.gamut_conversion_matrix[8],
0.0, // padding
];
Self {
yuv_conversion_matrix: desc.yuv_conversion_matrix,
gamut_conversion_matrix,
src_transfer_function: desc.src_transfer_function,
dst_transfer_function: desc.dst_transfer_function,
size: [desc.width, desc.height],
sample_transform: desc.sample_transform,
load_transform: desc.load_transform,
num_planes: desc.num_planes() as u32,
_padding: Default::default(),
}
}
}
/// Because all operations are push/swap (no longlived lock),
/// we can have mutex without lock rank
pub(crate) struct DeferredBufferMapPendingClosures(
parking_lot::Mutex<Vec<BufferMapPendingClosure>>,
);
impl DeferredBufferMapPendingClosures {
pub(crate) fn new() -> Self {
Self(parking_lot::Mutex::new(Vec::new()))
}
pub(crate) fn push(&self, closure: BufferMapPendingClosure) {
self.0.lock().push(closure);
}
pub(crate) fn swap(&self, other: &mut Vec<BufferMapPendingClosure>) {
mem::swap(&mut *self.0.lock(), other)
}
}
/// Resources associated with a device.
///
/// This struct exists so that resources can be cleaned up properly on error returns
/// from [`Device::new`].
///
/// [`Device::timestamp_normalizer`] is late-initialized after [`Device::new`], so it is not
/// included here.
struct DeviceResources<'a> {
raw: &'a dyn hal::DynDevice,
zero_buffer: Option<Box<dyn hal::DynBuffer>>,
empty_bgl: Option<Box<dyn hal::DynBindGroupLayout>>,
default_external_texture_params_buffer: Option<Box<dyn hal::DynBuffer>>,
fence: Option<Box<dyn hal::DynFence>>,
indirect_validation: Option<crate::indirect_validation::IndirectValidation>,
}
/// Structure describing a logical device. Some members are internally mutable,
/// stored behind mutexes.
pub struct Device {
raw: Box<dyn hal::DynDevice>,
pub(crate) adapter: Arc<Adapter>,
pub(crate) queue: OnceCellOrLock<Weak<Queue>>,
pub(crate) zero_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
pub(crate) empty_bgl: ManuallyDrop<Box<dyn hal::DynBindGroupLayout>>,
/// The `label` from the descriptor used to create the resource.
label: String,
pub(crate) command_allocator: command::CommandAllocator,
pub(crate) command_indices: RwLock<CommandIndices>,
/// The index of the last successful submission to this device's
/// [`hal::Queue`].
///
/// Unlike [`active_submission_index`], which is incremented each time
/// submission is attempted, this is updated only when submission succeeds,
/// so waiting for this value won't hang waiting for work that was never
/// submitted.
///
/// [`active_submission_index`]: CommandIndices::active_submission_index
pub(crate) last_successful_submission_index: hal::AtomicFenceValue,
pub(crate) fence: ManuallyDrop<Box<dyn hal::DynFence>>,
pub(crate) snatchable_lock: SnatchLock,
/// Is this device valid? Valid is closely associated with "lose the device",
/// which can be triggered by various methods, including at the end of device
/// destroy, and by any GPU errors that cause us to no longer trust the state
/// of the device. Ideally we would like to fold valid into the storage of
/// the device itself (for example as an Error enum), but unfortunately we
/// need to continue to be able to retrieve the device in poll_devices to
/// determine if it can be dropped. If our internal accesses of devices were
/// done through ref-counted references and external accesses checked for
/// Error enums, we wouldn't need this. For now, we need it. All the call
/// sites where we check it are areas that should be revisited if we start
/// using ref-counted references for internal access.
pub(crate) valid: AtomicBool,
/// Closure to be called on "lose the device". This is invoked directly by
/// device.lose or by the UserCallbacks returned from maintain when the device
/// has been destroyed and its queues are empty.
pub(crate) device_lost_closure: Mutex<Option<DeviceLostClosure>>,
/// Stores the state of buffers and textures.
pub(crate) trackers: Mutex<DeviceTracker>,
pub(crate) tracker_indices: TrackerIndexAllocators,
/// Pool of bind group layouts, allowing deduplication.
pub(crate) bgl_pool: ResourcePool<bgl::EntryMap, BindGroupLayout>,
pub(crate) alignments: hal::Alignments,
pub(crate) limits: wgt::Limits,
pub(crate) features: wgt::Features,
pub(crate) downlevel: wgt::DownlevelCapabilities,
/// Buffer uses listed here, are expected to be ordered by the underlying hardware.
/// If a usage is ordered, then if the buffer state doesn't change between draw calls,
/// there are no barriers needed for synchronization.
/// See the implementations of [`hal::Adapter::get_ordered_buffer_usages`] for hardware specific info
pub(crate) ordered_buffer_usages: wgt::BufferUses,
/// Texture uses listed here, are expected to be ordered by the underlying hardware.
/// If a usage is ordered, then if the buffer state doesn't change between draw calls,
/// there are no barriers needed for synchronization.
/// See the implementations of [`hal::Adapter::get_ordered_texture_usages`] for hardware specific info
pub(crate) ordered_texture_usages: wgt::TextureUses,
pub(crate) instance_flags: wgt::InstanceFlags,
pub(crate) deferred_destroy: Mutex<Vec<DeferredDestroy>>,
/// This closures were created in [`Buffer::drop`] where we do not run them to prevent locking problems.
pub(crate) deferred_buffer_map_pending_closures: DeferredBufferMapPendingClosures,
pub(crate) usage_scopes: UsageScopePool,
pub(crate) indirect_validation: Option<crate::indirect_validation::IndirectValidation>,
// Optional so that we can late-initialize this after the queue is created.
pub(crate) timestamp_normalizer:
OnceCellOrLock<crate::timestamp_normalization::TimestampNormalizer>,
/// Uniform buffer containing [`ExternalTextureParams`] with values such
/// that a [`TextureView`] bound to a [`wgt::BindingType::ExternalTexture`]
/// binding point will be rendered correctly. Intended to be used as the
/// [`hal::ExternalTextureBinding::params`] field.
pub(crate) default_external_texture_params_buffer: ManuallyDrop<Box<dyn hal::DynBuffer>>,
// needs to be dropped last
#[cfg(feature = "trace")]
pub(crate) trace: Mutex<Option<Box<dyn trace::Trace + Send + Sync + 'static>>>,
}
pub(crate) enum DeferredDestroy {
TextureViews(WeakVec<TextureView>),
BindGroups(WeakVec<BindGroup>),
}
impl fmt::Debug for Device {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Device")
.field("label", &self.label())
.field("limits", &self.limits)
.field("features", &self.features)
.field("downlevel", &self.downlevel)
.finish()
}
}
impl Drop for DeviceResources<'_> {
fn drop(&mut self) {
if let Some(indirect_validation) = self.indirect_validation.take() {
indirect_validation.dispose(self.raw);
}
unsafe {
if let Some(zero_buffer) = self.zero_buffer.take() {
self.raw.destroy_buffer(zero_buffer);
}
if let Some(empty_bgl) = self.empty_bgl.take() {
self.raw.destroy_bind_group_layout(empty_bgl);
}
if let Some(default_external_texture_params_buffer) =
self.default_external_texture_params_buffer.take()
{
self.raw
.destroy_buffer(default_external_texture_params_buffer);
}
if let Some(fence) = self.fence.take() {
self.raw.destroy_fence(fence);
}
}
}
}
impl Drop for Device {
#[allow(trivial_casts)]
fn drop(&mut self) {
profiling::scope!("Device::drop");
api_log!("Device::drop {:?}", self as *const _);
resource_log!("Drop {}", self.error_ident());
// The timestamp normalizer is late-initialized, so it is not included in `DeviceResources`.
if let Some(timestamp_normalizer) = self.timestamp_normalizer.take() {
timestamp_normalizer.dispose(self.raw.as_ref());
}
// Transfer the rest of the resources back to `DeviceResources`, which cleans them
// up for us.
// SAFETY: We are in the Drop impl and we don't use self.zero_buffer anymore after this
// point.
let zero_buffer = unsafe { ManuallyDrop::take(&mut self.zero_buffer) };
// SAFETY: We are in the Drop impl and we don't use self.empty_bgl anymore after this point.
let empty_bgl = unsafe { ManuallyDrop::take(&mut self.empty_bgl) };
// SAFETY: We are in the Drop impl and we don't use
// self.default_external_texture_params_buffer anymore after this point.
let default_external_texture_params_buffer =
unsafe { ManuallyDrop::take(&mut self.default_external_texture_params_buffer) };
// SAFETY: We are in the Drop impl and we don't use self.fence anymore after this point.
let fence = unsafe { ManuallyDrop::take(&mut self.fence) };
drop(DeviceResources {
raw: self.raw.as_ref(),
zero_buffer: Some(zero_buffer),
empty_bgl: Some(empty_bgl),
default_external_texture_params_buffer: Some(default_external_texture_params_buffer),
fence: Some(fence),
indirect_validation: self.indirect_validation.take(),
});
}
}
impl Device {
pub fn features(&self) -> &wgt::Features {
&self.features
}
pub fn limits(&self) -> &wgt::Limits {
&self.limits
}
pub fn downlevel(&self) -> &wgt::DownlevelCapabilities {
&self.downlevel
}
}
impl Device {
pub(crate) fn raw(&self) -> &dyn hal::DynDevice {
self.raw.as_ref()
}
pub(crate) fn require_features(&self, feature: wgt::Features) -> Result<(), MissingFeatures> {
if self.features.contains(feature) {
Ok(())
} else {
Err(MissingFeatures(feature))
}
}
pub(crate) fn require_downlevel_flags(
&self,
flags: wgt::DownlevelFlags,
) -> Result<(), MissingDownlevelFlags> {
if self.downlevel.flags.contains(flags) {
Ok(())
} else {
Err(MissingDownlevelFlags(flags))
}
}
/// # Safety
///
/// - See [wgpu::Device::start_graphics_debugger_capture][api] for details the safety.
///
/// [api]: ../../wgpu/struct.Device.html#method.start_graphics_debugger_capture
pub unsafe fn start_graphics_debugger_capture(&self) {
api_log!("Device::start_graphics_debugger_capture");
if !self.is_valid() {
return;
}
unsafe { self.raw().start_graphics_debugger_capture() };
}
/// # Safety
///
/// - See [wgpu::Device::stop_graphics_debugger_capture][api] for details the safety.
///
/// [api]: ../../wgpu/struct.Device.html#method.stop_graphics_debugger_capture
pub unsafe fn stop_graphics_debugger_capture(&self) {
api_log!("Device::stop_graphics_debugger_capture");
if !self.is_valid() {
return;
}
unsafe { self.raw().stop_graphics_debugger_capture() };
}
}
impl Device {
pub(crate) fn new(
raw_device: Box<dyn hal::DynDevice>,
adapter: &Arc<Adapter>,
desc: &DeviceDescriptor,
instance_flags: wgt::InstanceFlags,
) -> Result<Self, DeviceError> {
#[cfg(not(feature = "trace"))]
match &desc.trace {
wgt::Trace::Off => {}
_ => {
log::error!("wgpu-core feature 'trace' is not enabled");
}
};
#[cfg(feature = "trace")]
let trace: Option<Box<dyn trace::Trace + Send + Sync + 'static>> = match &desc.trace {
wgt::Trace::Off => None,
wgt::Trace::Directory(dir) => match trace::DiskTrace::new(dir.clone()) {
Ok(mut trace) => {
trace::Trace::add(
&mut trace,
trace::Action::Init {
desc: wgt::DeviceDescriptor {
trace: wgt::Trace::Off,
..desc.clone()
},
backend: adapter.backend(),
},
);
Some(Box::new(trace))
}
Err(e) => {
log::error!("Unable to start a trace in '{dir:?}': {e}");
None
}
},
wgt::Trace::Memory => {
let mut trace = trace::MemoryTrace::new();
trace::Trace::add(
&mut trace,
trace::Action::Init {
desc: wgt::DeviceDescriptor {
trace: wgt::Trace::Off,
..desc.clone()
},
backend: adapter.backend(),
},
);
Some(Box::new(trace))
}
// The enum is non_exhaustive, so we must have a fallback arm (that should be
// unreachable in practice).
t => {
log::error!("unimplemented wgpu_types::Trace variant {t:?}");
None
}
};
let ordered_buffer_usages = adapter.raw.adapter.get_ordered_buffer_usages();
let ordered_texture_usages = adapter.raw.adapter.get_ordered_texture_usages();
let mut resources = DeviceResources {
raw: raw_device.as_ref(),
zero_buffer: None,
empty_bgl: None,
default_external_texture_params_buffer: None,
fence: None,
indirect_validation: None,
};
resources.fence =
Some(unsafe { raw_device.create_fence() }.map_err(DeviceError::from_hal)?);
let command_allocator = command::CommandAllocator::new();
let rt_uses = if desc
.required_features
.intersects(wgt::Features::EXPERIMENTAL_RAY_QUERY)
{
wgt::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT
} else {
wgt::BufferUses::empty()
};
// Create zeroed buffer used for texture clears (and raytracing if required).
resources.zero_buffer = Some(
unsafe {
raw_device.create_buffer(&hal::BufferDescriptor {
label: hal_label(Some("(wgpu internal) zero init buffer"), instance_flags),
size: ZERO_BUFFER_SIZE,
usage: wgt::BufferUses::COPY_SRC | wgt::BufferUses::COPY_DST | rt_uses,
memory_flags: hal::MemoryFlags::empty(),
})
}
.map_err(DeviceError::from_hal)?,
);
resources.empty_bgl = Some(
unsafe {
raw_device.create_bind_group_layout(&hal::BindGroupLayoutDescriptor {
label: None,
flags: hal::BindGroupLayoutFlags::empty(),
entries: &[],
})
}
.map_err(DeviceError::from_hal)?,
);
resources.default_external_texture_params_buffer = Some(
unsafe {
raw_device.create_buffer(&hal::BufferDescriptor {
label: hal_label(
Some("(wgpu internal) default external texture params buffer"),
instance_flags,
),
size: size_of::<ExternalTextureParams>() as _,
usage: wgt::BufferUses::COPY_DST | wgt::BufferUses::UNIFORM,
memory_flags: hal::MemoryFlags::empty(),
})
}
.map_err(DeviceError::from_hal)?,
);
// Cloned as we need them below anyway.
let alignments = adapter.raw.capabilities.alignments.clone();
let downlevel = adapter.raw.capabilities.downlevel.clone();
let limits = &adapter.raw.capabilities.limits;
let enable_indirect_validation = instance_flags
.contains(wgt::InstanceFlags::VALIDATION_INDIRECT_CALL)
&& downlevel.flags.contains(
wgt::DownlevelFlags::INDIRECT_EXECUTION | wgt::DownlevelFlags::COMPUTE_SHADERS,
)
&& limits.max_storage_buffers_per_shader_stage >= 2;
if enable_indirect_validation {
resources.indirect_validation =
Some(crate::indirect_validation::IndirectValidation::new(
raw_device.as_ref(),
&desc.required_limits,
&desc.required_features,
instance_flags,
adapter.backend(),
)?);
}
// Error returns after this point could bypass resource cleanup.
#[deny(clippy::question_mark_used)]
{
let zero_buffer = resources.zero_buffer.take().unwrap();
let empty_bgl = resources.empty_bgl.take().unwrap();
let default_external_texture_params_buffer = resources
.default_external_texture_params_buffer
.take()
.unwrap();
let fence = resources.fence.take().unwrap();
let indirect_validation = resources.indirect_validation.take();
drop(resources);
Ok(Self {
raw: raw_device,
adapter: adapter.clone(),
queue: OnceCellOrLock::new(),
zero_buffer: ManuallyDrop::new(zero_buffer),
empty_bgl: ManuallyDrop::new(empty_bgl),
default_external_texture_params_buffer: ManuallyDrop::new(
default_external_texture_params_buffer,
),
label: desc.label.to_string(),
command_allocator,
command_indices: RwLock::new(
rank::DEVICE_COMMAND_INDICES,
CommandIndices {
active_submission_index: 0,
// By starting at one, we can put the result in a NonZeroU64.
next_acceleration_structure_build_command_index: 1,
},
),
last_successful_submission_index: AtomicU64::new(0),
fence: ManuallyDrop::new(fence),
snatchable_lock: unsafe { SnatchLock::new(rank::DEVICE_SNATCHABLE_LOCK) },
valid: AtomicBool::new(true),
device_lost_closure: Mutex::new(rank::DEVICE_LOST_CLOSURE, None),
trackers: Mutex::new(
rank::DEVICE_TRACKERS,
DeviceTracker::new(ordered_buffer_usages, ordered_texture_usages),
),
tracker_indices: TrackerIndexAllocators::new(),
bgl_pool: ResourcePool::new(),
#[cfg(feature = "trace")]
trace: Mutex::new(rank::DEVICE_TRACE, trace),
alignments,
limits: desc.required_limits.clone(),
features: desc.required_features,
downlevel,
ordered_buffer_usages,
ordered_texture_usages,
instance_flags,
deferred_destroy: Mutex::new(rank::DEVICE_DEFERRED_DESTROY, Vec::new()),
usage_scopes: Mutex::new(rank::DEVICE_USAGE_SCOPES, Default::default()),
timestamp_normalizer: OnceCellOrLock::new(),
indirect_validation,
deferred_buffer_map_pending_closures: DeferredBufferMapPendingClosures::new(),
})
}
}
/// Initializes [`Device::default_external_texture_params_buffer`] with
/// required values such that a [`TextureView`] bound to a
/// [`wgt::BindingType::ExternalTexture`] binding point will be rendered
/// correctly.
fn init_default_external_texture_params_buffer(self: &Arc<Self>) -> Result<(), DeviceError> {
let data = ExternalTextureParams {
#[rustfmt::skip]
yuv_conversion_matrix: [
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
],
#[rustfmt::skip]
gamut_conversion_matrix: [
1.0, 0.0, 0.0, /* padding */ 0.0,
0.0, 1.0, 0.0, /* padding */ 0.0,
0.0, 0.0, 1.0, /* padding */ 0.0,
],
src_transfer_function: Default::default(),
dst_transfer_function: Default::default(),
size: [0, 0],
#[rustfmt::skip]
sample_transform: [
1.0, 0.0,
0.0, 1.0,
0.0, 0.0
],
#[rustfmt::skip]
load_transform: [
1.0, 0.0,
0.0, 1.0,
0.0, 0.0
],
num_planes: 1,
_padding: Default::default(),
};
let mut staging_buffer =
StagingBuffer::new(self, wgt::BufferSize::new(size_of_val(&data) as _).unwrap())?;
staging_buffer.write(bytemuck::bytes_of(&data));
let staging_buffer = staging_buffer.flush();
let params_buffer = self.default_external_texture_params_buffer.as_ref();
let queue = self.get_queue().unwrap();
let mut pending_writes = queue.pending_writes.lock();
unsafe {
pending_writes
.command_encoder
.transition_buffers(&[hal::BufferBarrier {
buffer: params_buffer,
usage: hal::StateTransition {
from: wgt::BufferUses::MAP_WRITE,
to: wgt::BufferUses::COPY_DST,
},
}]);
pending_writes.command_encoder.copy_buffer_to_buffer(
staging_buffer.raw(),
params_buffer,
&[hal::BufferCopy {
src_offset: 0,
dst_offset: 0,
size: staging_buffer.size,
}],
);
pending_writes.consume(staging_buffer);
pending_writes
.command_encoder
.transition_buffers(&[hal::BufferBarrier {
buffer: params_buffer,
usage: hal::StateTransition {
from: wgt::BufferUses::COPY_DST,
to: wgt::BufferUses::UNIFORM,
},
}]);
}
Ok(())
}
pub fn late_init_resources_with_queue(self: &Arc<Self>) -> Result<(), RequestDeviceError> {
let queue = self.get_queue().unwrap();
let timestamp_normalizer = crate::timestamp_normalization::TimestampNormalizer::new(
self,
queue.get_timestamp_period(),
)?;
self.timestamp_normalizer
.set(timestamp_normalizer)
.unwrap_or_else(|_| panic!("Called late_init_resources_with_queue twice"));
self.init_default_external_texture_params_buffer()?;
Ok(())
}
/// Returns the backend this device is using.
pub fn backend(&self) -> wgt::Backend {
self.adapter.backend()
}
pub fn is_valid(&self) -> bool {
self.valid.load(Ordering::Acquire)
}
pub fn check_is_valid(&self) -> Result<(), DeviceError> {
if self.is_valid() {
Ok(())
} else {
Err(DeviceError::Lost)
}
}
/// Stop tracing and return the trace object.
///
/// This is mostly useful for in-memory traces.
#[cfg(feature = "trace")]
pub fn take_trace(&self) -> Option<Box<dyn trace::Trace + Send + Sync + 'static>> {
self.trace.lock().take()
}
/// Checks that we are operating within the memory budget reported by the native APIs.
///
/// If we are not, the device gets invalidated.
///
/// The budget might fluctuate over the lifetime of the application, so it should be checked
/// somewhat frequently.
pub fn lose_if_oom(&self) {
let _ = self
.raw()
.check_if_oom()
.map_err(|e| self.handle_hal_error(e));
}
pub fn handle_hal_error(&self, error: hal::DeviceError) -> DeviceError {
match error {
hal::DeviceError::OutOfMemory
| hal::DeviceError::Lost
| hal::DeviceError::Unexpected => {
self.lose(&error.to_string());
}
}
DeviceError::from_hal(error)
}
pub fn handle_hal_error_with_nonfatal_oom(&self, error: hal::DeviceError) -> DeviceError {
match error {
hal::DeviceError::OutOfMemory => DeviceError::from_hal(error),
error => self.handle_hal_error(error),
}
}
/// Run some destroy operations that were deferred.
///
/// Destroying the resources requires taking a write lock on the device's snatch lock,
/// so a good reason for deferring resource destruction is when we don't know for sure
/// how risky it is to take the lock (typically, it shouldn't be taken from the drop
/// implementation of a reference-counted structure).
/// The snatch lock must not be held while this function is called.
pub(crate) fn deferred_resource_destruction(&self) {
// Note that the deferred_destroy list may contain duplicate entries.
let deferred_destroy = mem::take(&mut *self.deferred_destroy.lock());
for item in deferred_destroy {
match item {
DeferredDestroy::TextureViews(views) => {
for view in views {
let Some(view) = view.upgrade() else {
continue;
};
let Ok(view_state) = view.state() else {
continue;
};
let Some(raw_view) =
view_state.raw.snatch(&mut self.snatchable_lock.write())
else {
continue;
};
resource_log!("Destroy raw {}", view.error_ident());
unsafe {
self.raw().destroy_texture_view(raw_view);
}
}
}
DeferredDestroy::BindGroups(bind_groups) => {
for bind_group in bind_groups {
let Some(bind_group) = bind_group.upgrade() else {
continue;
};
let Ok(bind_group_state) = bind_group.state() else {
continue;
};
let Some(raw_bind_group) = bind_group_state
.raw
.snatch(&mut self.snatchable_lock.write())
else {
continue;
};
resource_log!("Destroy raw {}", bind_group.error_ident());
unsafe {
self.raw().destroy_bind_group(raw_bind_group);
}
}
}
}
}
}
pub fn get_queue(&self) -> Option<Arc<Queue>> {
self.queue.get().as_ref()?.upgrade()
}
pub fn set_queue(&self, queue: &Arc<Queue>) {
assert!(self.queue.set(Arc::downgrade(queue)).is_ok());
}
/// Check device for freeable resources and completed buffer mappings.
///
/// Return `queue_empty` indicating whether there are more queue submissions still in flight.
pub fn poll(
&self,
poll_type: wgt::PollType<crate::SubmissionIndex>,
) -> Result<wgt::PollStatus, WaitIdleError> {
api_log!("Device::poll {poll_type:?}");
let (user_closures, result) = self.poll_and_return_closures(poll_type);
user_closures.fire();
result
}
/// Poll the device, returning any `UserClosures` that need to be executed.
///
/// The caller must invoke the `UserClosures` even if this function returns
/// an error. This is an internal helper, used by [`Device::poll`] and
/// [`Instance::poll_all_devices`], so that `poll_all_devices` can invoke
/// closures once after all devices have been polled.
///
/// [`Instance::poll_all_devices`]: crate::instance::Instance::poll_all_devices
pub(crate) fn poll_and_return_closures(
&self,
poll_type: wgt::PollType<crate::SubmissionIndex>,
) -> (UserClosures, Result<wgt::PollStatus, WaitIdleError>) {
let snatch_guard = self.snatchable_lock.read();
let maintain_result = self.maintain(poll_type, snatch_guard);
self.lose_if_oom();
// Some deferred destroys are scheduled in maintain so run this right after
// to avoid holding on to them until the next device poll.
self.deferred_resource_destruction();
maintain_result
}
/// Check the current status of the GPU and process any submissions that have
/// finished.
///
/// The `poll_type` argument tells if this function should wait for a particular
/// submission index to complete, or if it should just poll the current status.
///
/// This will process _all_ completed submissions, even if the caller only asked
/// us to poll to a given submission index.
///
/// Return a pair `(closures, result)`, where:
///
/// - `closures` is a list of callbacks that need to be invoked informing the user
/// about various things occurring. These happen and should be handled even if
/// this function returns an error, hence they are outside of the result.
///
/// - `results` is a boolean indicating the result of the wait operation, including
/// if there was a timeout or a validation error.
pub(crate) fn maintain<'this>(
&'this self,
poll_type: wgt::PollType<crate::SubmissionIndex>,
snatch_guard: SnatchGuard,
) -> (UserClosures, Result<wgt::PollStatus, WaitIdleError>) {
profiling::scope!("Device::maintain");
let mut user_closures = UserClosures::default();
self.deferred_buffer_map_pending_closures
.swap(&mut user_closures.mappings);
// If a wait was requested, determine which submission index to wait for.
let wait_submission_index = match poll_type {
wgt::PollType::Wait {
submission_index: Some(submission_index),
..
} => {
let last_successful_submission_index = self
.last_successful_submission_index
.load(Ordering::Acquire);
if submission_index > last_successful_submission_index {
let result = Err(WaitIdleError::WrongSubmissionIndex(
submission_index,
last_successful_submission_index,
));
return (user_closures, result);
}
Some(submission_index)
}
wgt::PollType::Wait {
submission_index: None,
..
} => Some(
self.last_successful_submission_index
.load(Ordering::Acquire),
),
wgt::PollType::Poll => None,
};
// Wait for the submission index if requested.
if let Some(target_submission_index) = wait_submission_index {
log::trace!("Device::maintain: waiting for submission index {target_submission_index}");
let wait_timeout = match poll_type {