wgpu-core 31.0.1

Core implementation logic of wgpu, the cross-platform, safe, pure-rust graphics API
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
use alloc::{borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec, vec::Vec};
use core::{
    fmt,
    sync::atomic::{AtomicBool, Ordering},
};

use hashbrown::HashMap;
use thiserror::Error;

use crate::{
    api_log, api_log_debug,
    device::{
        queue::Queue, resource::Device, DeviceDescriptor, DeviceError, UserClosures, WaitIdleError,
    },
    id::markers,
    limits::{self, check_limits, FailedLimit},
    lock::{rank, Mutex, MutexGuard},
    present::{ConfigureSurfaceError, Presentation},
    resource::ResourceType,
    resource_log,
    timestamp_normalization::TimestampNormalizerInitError,
    weak_vec::WeakVec,
    DOWNLEVEL_WARNING_MESSAGE,
};

use wgt::{Backend, Backends, InstanceFlags, PowerPreference};

#[derive(Debug)]
pub(crate) struct InstanceDevices(Mutex<WeakVec<Device>>);

impl Default for InstanceDevices {
    fn default() -> Self {
        Self::new()
    }
}

impl InstanceDevices {
    pub(crate) fn new() -> Self {
        Self(Mutex::new(rank::INSTANCE_DEVICES, WeakVec::new()))
    }

    pub(crate) fn push(&self, device: &Arc<Device>) {
        self.0.lock().push(Arc::downgrade(device));
    }

    /// Poll all devices stored in this instance.
    ///
    /// If `force_wait` is true, block until all buffer mappings are done.
    ///
    /// Return `all_queue_empty` indicating whether there are more queue
    /// submissions still in flight.
    fn poll_all_devices(
        &self,
        force_wait: bool,
        closure_list: &mut UserClosures,
    ) -> Result<bool, WaitIdleError> {
        let mut all_queue_empty = true;
        {
            let device_guard = self.0.lock();

            for device in device_guard.iter().filter_map(|device| device.upgrade()) {
                let poll_type = if force_wait {
                    // TODO(#8286): Should expose timeout to poll_all.
                    wgt::PollType::wait_indefinitely()
                } else {
                    wgt::PollType::Poll
                };

                let (closures, result) = device.poll_and_return_closures(poll_type);

                let is_queue_empty = matches!(result, Ok(wgt::PollStatus::QueueEmpty));

                all_queue_empty &= is_queue_empty;

                closure_list.extend(closures);
            }
        }

        Ok(all_queue_empty)
    }
}

#[derive(Default)]
pub struct Instance {
    _name: String,

    /// List of instances per `wgpu-hal` backend.
    ///
    /// The ordering in this list implies prioritization and needs to be preserved.
    instance_per_backend: Vec<(Backend, Box<dyn hal::DynInstance>)>,

    /// The backends that were requested by the user.
    requested_backends: Backends,

    /// The backends that we could have attempted to obtain from `wgpu-hal` —
    /// those for which support is compiled in, currently.
    ///
    /// The union of this and `requested_backends` is the set of backends that would be used,
    /// independent of whether accessing the drivers/hardware for them succeeds.
    /// To obtain the set of backends actually in use by this instance, check
    /// `instance_per_backend` instead.
    supported_backends: Backends,

    pub flags: InstanceFlags,

    /// Non-lifetimed [`raw_window_handle::DisplayHandle`], for keepalive and validation purposes in
    /// [`Self::create_surface()`].
    ///
    /// When used with `winit`, callers are expected to pass its `OwnedDisplayHandle` (created from
    /// the `EventLoop`) here.
    display: Option<Box<dyn wgt::WgpuHasDisplayHandle>>,

    /// Keeps track of all devices created from this instance, so that they can be polled.
    devices: InstanceDevices,
}

impl Instance {
    pub fn new(
        name: &str,
        instance_desc: wgt::InstanceDescriptor,
        telemetry: Option<hal::Telemetry>,
    ) -> Arc<Self> {
        let mut this = InstanceBuilder::new(name, instance_desc, telemetry);

        #[cfg(all(vulkan, not(target_os = "netbsd")))]
        this.try_add_hal(hal::api::Vulkan);
        #[cfg(metal)]
        this.try_add_hal(hal::api::Metal);
        #[cfg(dx12)]
        this.try_add_hal(hal::api::Dx12);
        #[cfg(gles)]
        this.try_add_hal(hal::api::Gles);
        #[cfg(feature = "noop")]
        this.try_add_hal(hal::api::Noop);

        this.build()
    }

    pub fn from_hal_instance<A: hal::Api>(
        name: String,
        hal_instance: <A as hal::Api>::Instance,
    ) -> Arc<Self> {
        Arc::new(Self {
            _name: name,
            instance_per_backend: vec![(A::VARIANT, Box::new(hal_instance))],
            requested_backends: A::VARIANT.into(),
            supported_backends: A::VARIANT.into(),
            flags: InstanceFlags::default(),
            display: None, // TODO: Extract display from HAL instance if available?
            devices: InstanceDevices::new(),
        })
    }

    pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynInstance> {
        self.instance_per_backend
            .iter()
            .find_map(|(instance_backend, instance)| {
                (*instance_backend == backend).then(|| instance.as_ref())
            })
    }

    /// # Safety
    ///
    /// - The raw instance handle returned must not be manually destroyed.
    pub unsafe fn as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
        self.raw(A::VARIANT).map(|instance| {
            instance
                .as_any()
                .downcast_ref()
                // This should be impossible. It would mean that backend instance and enum type are mismatching.
                .expect("Stored instance is not of the correct type")
        })
    }

    /// Creates a new surface targeting the given display/window handles.
    ///
    /// Internally attempts to create hal surfaces for all enabled backends.
    ///
    /// Fails only if creation for surfaces for all enabled backends fails in which case
    /// the error for each enabled backend is listed.
    /// Vice versa, if creation for any backend succeeds, success is returned.
    /// Surface creation errors are logged to the debug log in any case.
    ///
    /// # Safety
    ///
    /// - `display_handle` must be a valid object to create a surface upon,
    ///   falls back to the instance display handle otherwise.
    /// - `window_handle` must remain valid as long as the returned
    ///   [`Surface`] is being used.
    pub unsafe fn create_surface(
        &self,
        display_handle: Option<raw_window_handle::RawDisplayHandle>,
        window_handle: raw_window_handle::RawWindowHandle,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::create_surface");

        let instance_display_handle = self.display.as_ref().map(|d| {
            d.display_handle()
                .expect("Implementation did not provide a DisplayHandle")
                .as_raw()
        });
        let display_handle = match (instance_display_handle, display_handle) {
            (Some(a), Some(b)) => {
                if a != b {
                    return Err(CreateSurfaceError::MismatchingDisplayHandle);
                }
                a
            }
            (Some(hnd), None) => hnd,
            (None, Some(hnd)) => hnd,
            (None, None) => return Err(CreateSurfaceError::MissingDisplayHandle),
        };

        let mut errors = HashMap::default();
        let mut surface_per_backend = HashMap::default();

        for (backend, instance) in &self.instance_per_backend {
            match unsafe {
                instance
                    .as_ref()
                    .create_surface(display_handle, window_handle)
            } {
                Ok(raw) => {
                    surface_per_backend.insert(*backend, raw);
                }
                Err(err) => {
                    log::debug!(
                        "Instance::create_surface: failed to create surface for {backend:?}: {err:?}"
                    );
                    errors.insert(*backend, err);
                }
            }
        }

        if surface_per_backend.is_empty() {
            Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
                errors,
            ))
        } else {
            let surface = Arc::new(Surface {
                presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
                surface_per_backend,
            });

            Ok(surface)
        }
    }

    /// Creates a new surface from the given drm configuration.
    ///
    /// # Safety
    ///
    /// - All parameters must point to valid DRM values.
    ///
    /// # Platform Support
    ///
    /// This function requires the `"drm"` feature. It is only available on
    /// non-apple Unix-like platforms (Linux, FreeBSD) and currently only works
    /// with the Vulkan backend.
    #[cfg(drm)]
    #[cfg_attr(not(vulkan), expect(unused_variables, unused_mut))]
    pub unsafe fn create_surface_from_drm(
        &self,
        fd: i32,
        plane: u32,
        connector_id: u32,
        width: u32,
        height: u32,
        refresh_rate: u32,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::create_surface_from_drm");

        let mut errors = HashMap::default();
        let mut surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>> =
            HashMap::default();

        #[cfg(vulkan)]
        {
            let instance = unsafe { self.as_hal::<hal::api::Vulkan>() }
                .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Vulkan))?;

            // Safety must be upheld by the caller
            match unsafe {
                instance.create_surface_from_drm(
                    fd,
                    plane,
                    connector_id,
                    width,
                    height,
                    refresh_rate,
                )
            } {
                Ok(surface) => {
                    surface_per_backend.insert(Backend::Vulkan, Box::new(surface));
                }
                Err(err) => {
                    errors.insert(Backend::Vulkan, err);
                }
            }
        }

        if surface_per_backend.is_empty() {
            Err(CreateSurfaceError::FailedToCreateSurfaceForAnyBackend(
                errors,
            ))
        } else {
            let surface = Arc::new(Surface {
                presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
                surface_per_backend,
            });

            Ok(surface)
        }
    }

    /// # Safety
    ///
    /// `layer` must be a valid pointer.
    #[cfg(metal)]
    pub unsafe fn create_surface_metal(
        &self,
        layer: *mut core::ffi::c_void,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::create_surface_metal");

        let instance = unsafe { self.as_hal::<hal::api::Metal>() }
            .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Metal))?;

        let layer = layer.cast();
        // SAFETY: We do this cast and deref. (rather than using `metal` to get the
        // object we want) to avoid direct coupling on the `metal` crate.
        //
        // To wit, this pointer…
        //
        // - …is properly aligned.
        // - …is dereferenceable to a `MetalLayerRef` as an invariant of the `metal`
        //   field.
        // - …points to an _initialized_ `MetalLayerRef`.
        // - …is only ever aliased via an immutable reference that lives within this
        //   lexical scope.
        let layer = unsafe { &*layer };
        let raw_surface: Box<dyn hal::DynSurface> =
            Box::new(instance.create_surface_from_layer(layer));

        let surface = Arc::new(Surface {
            presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
            surface_per_backend: core::iter::once((Backend::Metal, raw_surface)).collect(),
        });

        Ok(surface)
    }

    #[cfg(dx12)]
    fn create_surface_dx12(
        &self,
        create_surface_func: impl FnOnce(&hal::dx12::Instance) -> hal::dx12::Surface,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        let instance = unsafe { self.as_hal::<hal::api::Dx12>() }
            .ok_or(CreateSurfaceError::BackendNotEnabled(Backend::Dx12))?;
        let surface: Box<dyn hal::DynSurface> = Box::new(create_surface_func(instance));

        let surface = Arc::new(Surface {
            presentation: Mutex::new(rank::SURFACE_PRESENTATION, None),
            surface_per_backend: core::iter::once((Backend::Dx12, surface)).collect(),
        });

        Ok(surface)
    }

    #[cfg(dx12)]
    /// # Safety
    ///
    /// The visual must be valid and able to be used to make a swapchain with.
    pub unsafe fn create_surface_from_visual(
        &self,
        visual: *mut core::ffi::c_void,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::instance_create_surface_from_visual");
        self.create_surface_dx12(|inst| unsafe { inst.create_surface_from_visual(visual) })
    }

    #[cfg(dx12)]
    /// # Safety
    ///
    /// The surface_handle must be valid and able to be used to make a swapchain with.
    pub unsafe fn create_surface_from_surface_handle(
        &self,
        surface_handle: *mut core::ffi::c_void,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::instance_create_surface_from_surface_handle");
        self.create_surface_dx12(|inst| unsafe {
            inst.create_surface_from_surface_handle(surface_handle)
        })
    }

    #[cfg(dx12)]
    /// # Safety
    ///
    /// The swap_chain_panel must be valid and able to be used to make a swapchain with.
    pub unsafe fn create_surface_from_swap_chain_panel(
        &self,
        swap_chain_panel: *mut core::ffi::c_void,
    ) -> Result<Arc<Surface>, CreateSurfaceError> {
        profiling::scope!("Instance::instance_create_surface_from_swap_chain_panel");
        self.create_surface_dx12(|inst| unsafe {
            inst.create_surface_from_swap_chain_panel(swap_chain_panel)
        })
    }

    fn adapter_allowed(&self, raw: &hal::DynExposedAdapter) -> bool {
        adapter_allowed(
            self.flags,
            &raw.info,
            &raw.capabilities.limits,
            raw.features,
        )
    }

    pub fn enumerate_adapters(
        self: &Arc<Self>,
        backends: Backends,
        apply_limit_buckets: bool,
    ) -> Vec<Arc<Adapter>> {
        profiling::scope!("Instance::enumerate_adapters");
        api_log!("Instance::enumerate_adapters");

        self.request_adapters(
            &wgt::RequestAdapterOptions {
                power_preference: PowerPreference::None,
                force_fallback_adapter: false,
                compatible_surface: None,
                apply_limit_buckets,
            },
            backends,
        )
        .unwrap_or_default()
    }

    /// Returns a list of adapters that match the given request options and are compatible with the specified backends.
    ///
    /// On success at least one compatible adapter will be returned in the resulting vector.
    pub fn request_adapters(
        self: &Arc<Self>,
        desc: &wgt::RequestAdapterOptions<&Surface>,
        backends: Backends,
    ) -> Result<Vec<Arc<Adapter>>, wgt::RequestAdapterError> {
        let mut adapters = Vec::new();
        let mut incompatible_surface_backends = Backends::empty();
        let mut no_fallback_backends = Backends::empty();
        let mut no_adapter_backends = Backends::empty();

        for &(backend, ref instance) in self
            .instance_per_backend
            .iter()
            .filter(|&&(backend, _)| backends.contains(Backends::from(backend)))
        {
            profiling::scope!("enumerating", &*alloc::format!("{backend:?}"));

            let compatible_hal_surface = desc
                .compatible_surface
                .and_then(|surface| surface.raw(backend));

            let mut backend_adapters =
                unsafe { instance.enumerate_adapters(compatible_hal_surface) };
            if backend_adapters.is_empty() {
                log::debug!("enabled backend `{backend:?}` has no adapters");
                no_adapter_backends |= Backends::from(backend);
                // by continuing, we avoid setting the further error bits below
                continue;
            }

            if desc.force_fallback_adapter {
                log::debug!("Filtering `{backend:?}` for `force_fallback_adapter`");
                backend_adapters.retain(|exposed| {
                    let keep = exposed.info.device_type == wgt::DeviceType::Cpu;
                    if !keep {
                        log::debug!("* Eliminating adapter `{}`", exposed.info.name);
                    }
                    keep
                });
                if backend_adapters.is_empty() {
                    log::debug!("* Backend `{backend:?}` has no fallback adapters");
                    no_fallback_backends |= Backends::from(backend);
                    continue;
                }
            }

            if let Some(surface) = desc.compatible_surface {
                backend_adapters.retain(|exposed| {
                    let capabilities = surface.get_capabilities_with_raw(exposed);
                    if let Err(err) = capabilities {
                        log::debug!(
                            "Adapter {:?} not compatible with surface: {}",
                            exposed.info,
                            err
                        );
                        incompatible_surface_backends |= Backends::from(backend);
                        false
                    } else {
                        true
                    }
                });
                if backend_adapters.is_empty() {
                    incompatible_surface_backends |= Backends::from(backend);
                    continue;
                }
            }

            let backend_adapters = backend_adapters
                .into_iter()
                .map(|mut raw| {
                    self.adjust_limits_for_indirect_validation(&mut raw.capabilities.limits);
                    raw
                })
                .map(|mut raw| {
                    filter_features_and_limits(
                        self.flags,
                        &mut raw.features,
                        &mut raw.capabilities.limits,
                    );
                    raw
                })
                .filter(|raw| self.adapter_allowed(raw));

            if desc.apply_limit_buckets {
                adapters.extend(backend_adapters.filter_map(limits::apply_limit_buckets));
            } else {
                adapters.extend(backend_adapters);
            }
        }

        match desc.power_preference {
            PowerPreference::LowPower => {
                sort(&mut adapters, true);
            }
            PowerPreference::HighPerformance => {
                sort(&mut adapters, false);
            }
            PowerPreference::None => {}
        };

        fn sort(adapters: &mut [hal::DynExposedAdapter], prefer_integrated_gpu: bool) {
            adapters
                .sort_by_key(|adapter| get_order(adapter.info.device_type, prefer_integrated_gpu));
        }

        fn get_order(device_type: wgt::DeviceType, prefer_integrated_gpu: bool) -> u8 {
            // Since devices of type "Other" might really be "Unknown" and come
            // from APIs like OpenGL that don't specify device type, Prefer more
            // Specific types over Other.
            //
            // This means that backends which do provide accurate device types
            // will be preferred if their device type indicates an actual
            // hardware GPU (integrated or discrete).
            match device_type {
                wgt::DeviceType::DiscreteGpu if prefer_integrated_gpu => 2,
                wgt::DeviceType::IntegratedGpu if prefer_integrated_gpu => 1,
                wgt::DeviceType::DiscreteGpu => 1,
                wgt::DeviceType::IntegratedGpu => 2,
                wgt::DeviceType::Other => 3,
                wgt::DeviceType::VirtualGpu => 4,
                wgt::DeviceType::Cpu => 5,
            }
        }

        // `request_adapter` can be a bit of a black box.
        // Shine some light on its decision in debug log.
        if adapters.is_empty() {
            log::debug!("Request adapter didn't find compatible adapters.");
            Err(wgt::RequestAdapterError::NotFound {
                supported_backends: self.supported_backends,
                requested_backends: self.requested_backends,
                active_backends: self.active_backends(),
                no_fallback_backends,
                no_adapter_backends,
                incompatible_surface_backends,
            })
        } else {
            log::debug!(
                "Found {} compatible adapters. Sorted by preference:",
                adapters.len()
            );
            for adapter in &adapters {
                log::debug!("* {:?}", adapter.info);
            }
            Ok(adapters
                .into_iter()
                .map(|adapter| Adapter::new(adapter, self.clone()))
                .collect::<Vec<_>>())
        }
    }

    pub fn request_adapter(
        self: &Arc<Self>,
        desc: &wgt::RequestAdapterOptions<&Surface>,
        backends: Backends,
    ) -> Result<Arc<Adapter>, wgt::RequestAdapterError> {
        profiling::scope!("Instance::request_adapter");
        api_log!("Instance::request_adapter");

        let adapter = self
            .request_adapters(desc, backends)?
            .into_iter()
            .next()
            .expect(
                "request_adapters should always return at least one compatible adapter on success",
            );
        api_log_debug!("Request adapter result {:?}", adapter.get_info());
        Ok(adapter)
    }

    /// This is similar to wgpu-hal's `adjust_raw_limits` but tailored to
    /// wgpu-core's constraints.
    fn adjust_limits_for_indirect_validation(&self, limits: &mut wgt::Limits) {
        // Indirect draw validation can't support u64 offsets,
        // lower max buffer and binding size to fit in an u32.
        if self.flags.contains(InstanceFlags::VALIDATION_INDIRECT_CALL) {
            limits.max_buffer_size = limits.max_buffer_size.min(u32::MAX as u64);
            limits.max_uniform_buffer_binding_size =
                limits.max_uniform_buffer_binding_size.min(u32::MAX as u64);
            limits.max_storage_buffer_binding_size = limits
                .max_storage_buffer_binding_size
                .min(u32::MAX as u64 & !(wgt::STORAGE_BINDING_SIZE_ALIGNMENT as u64 - 1));
        }
    }

    fn active_backends(&self) -> Backends {
        self.instance_per_backend
            .iter()
            .map(|&(backend, _)| Backends::from(backend))
            .collect()
    }

    /// Create an adapter from a HAL adapter.
    ///
    /// The HAL adapter may be obtained e.g. by calling `enumerate_adapters` on
    /// the HAL directly.
    ///
    /// If [limit bucketing][lt] is desired, [`crate::limits::apply_limit_buckets`]
    /// should be called with the HAL adapter before calling this function.
    ///
    /// # Safety
    ///
    /// `hal_adapter` must be created from this global internal instance handle.
    ///
    /// [lt]: crate::limits#Limit-bucketing
    pub unsafe fn create_adapter_from_hal(
        self: &Arc<Self>,
        hal_adapter: hal::DynExposedAdapter,
    ) -> Arc<Adapter> {
        profiling::scope!("Instance::create_adapter_from_hal");

        let adapter = Adapter::new(hal_adapter, self.clone());

        resource_log!("Created Adapter {:?}", Arc::as_ptr(&adapter));
        adapter
    }

    /// Poll all devices on all backends.
    ///
    /// This is the implementation of `wgpu::Instance::poll_all`.
    ///
    /// Return `all_queue_empty` indicating whether there are more queue
    /// submissions still in flight.
    pub fn poll_all_devices(&self, force_wait: bool) -> Result<bool, WaitIdleError> {
        api_log!("poll_all_devices");
        let mut closures = UserClosures::default();
        let all_queue_empty = self.devices.poll_all_devices(force_wait, &mut closures)?;

        closures.fire();

        Ok(all_queue_empty)
    }
}

pub struct InstanceBuilder {
    instance: Instance,
    instance_desc: wgt::InstanceDescriptor,
    telemetry: Option<hal::Telemetry>,
}

impl InstanceBuilder {
    pub fn new(
        name: &str,
        mut desc: wgt::InstanceDescriptor,
        telemetry: Option<hal::Telemetry>,
    ) -> Self {
        Self {
            instance: Instance {
                _name: name.to_owned(),
                instance_per_backend: Vec::new(),
                requested_backends: desc.backends,
                supported_backends: Backends::empty(),
                flags: desc.flags,
                // HACK: We must take ownership of the field here, without being able to pass it into
                // try_add_hal(). Remove it from the mutable descriptor instead, while try_add_hal()
                // borrows the handle from `this.display` instead.
                display: desc.display.take(),
                devices: InstanceDevices::new(),
            },
            instance_desc: desc,
            telemetry,
        }
    }

    pub fn try_add_hal<A: hal::Api>(&mut self, api: A) {
        use hal::Instance as _;
        self.try_add_custom_hal(api, |hal_desc| unsafe { A::Instance::init(hal_desc) });
    }

    pub fn try_add_custom_hal<A: hal::Api>(
        &mut self,
        _: A,
        f: impl FnOnce(&hal::InstanceDescriptor) -> Result<A::Instance, hal::InstanceError>,
    ) {
        if self.instance.supported_backends.contains(A::VARIANT.into()) {
            return;
        }

        // Whether or not the backend was requested, and whether or not it succeeds,
        // note that we *could* try it.
        self.instance.supported_backends |= A::VARIANT.into();

        if !self.instance_desc.backends.contains(A::VARIANT.into()) {
            log::trace!("Instance::new: backend {:?} not requested", A::VARIANT);
            return;
        }

        // If this was Some, it was moved into self
        assert!(self.instance_desc.display.is_none());

        let hal_desc = hal::InstanceDescriptor {
            name: "wgpu",
            flags: self.instance.flags,
            memory_budget_thresholds: self.instance_desc.memory_budget_thresholds,
            backend_options: self.instance_desc.backend_options.clone(),
            telemetry: self.telemetry,
            // Pass a borrow, the core instance here keeps the owned handle alive already
            // WARNING: Using self here, not instance_desc!
            display: self.instance.display.as_ref().map(|hdh| {
                hdh.display_handle()
                    .expect("Implementation did not provide a DisplayHandle")
            }),
        };

        match f(&hal_desc) {
            Ok(instance) => {
                log::debug!("Instance::new: created {:?} backend", A::VARIANT);
                self.instance
                    .instance_per_backend
                    .push((A::VARIANT, Box::new(instance)));
            }
            Err(err) => {
                log::debug!(
                    "Instance::new: failed to create {:?} backend: {:?}",
                    A::VARIANT,
                    err
                );
            }
        }
    }

    pub fn build(self) -> Arc<Instance> {
        Arc::new(self.instance)
    }
}

pub struct Surface {
    pub(crate) presentation: Mutex<Option<Presentation>>,
    pub surface_per_backend: HashMap<Backend, Box<dyn hal::DynSurface>>,
}

impl ResourceType for Surface {
    const TYPE: &'static str = "Surface";
}
impl crate::storage::StorageItem for Surface {
    type Marker = markers::Surface;
}

impl Surface {
    pub fn get_capabilities(
        &self,
        adapter: &Adapter,
    ) -> Result<wgt::SurfaceCapabilities, GetSurfaceSupportError> {
        profiling::scope!("Surface::get_capabilities");
        let mut hal_caps = self.get_hal_capabilities(adapter)?;

        hal_caps
            .formats
            .sort_by_key(|fc| !fc.format.has_srgb_suffix());

        let usages = crate::conv::map_texture_usage_from_hal(hal_caps.usage);

        // `SurfaceCapabilities::formats` lists only the formats a
        // color-space-unaware application can configure via
        // `SurfaceColorSpace::Auto`, i.e. those for which `Auto` resolves to a
        // concrete color space. (The full `format_capabilities` still reports
        // every color space, including HDR ones, for explicit opt-in.)
        Ok(wgt::SurfaceCapabilities {
            formats: hal_caps
                .formats
                .iter()
                .filter(|fc| {
                    crate::device::surface_config::resolve_auto_color_space(
                        fc.format,
                        fc.color_spaces,
                    )
                    .is_some()
                })
                .map(|fc| fc.format)
                .collect(),
            format_capabilities: hal_caps.formats,
            present_modes: hal_caps.present_modes,
            alpha_modes: hal_caps.composite_alpha_modes,
            usages,
        })
    }

    pub fn get_hal_capabilities(
        &self,
        adapter: &Adapter,
    ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
        self.get_capabilities_with_raw(&adapter.raw)
    }

    pub fn get_capabilities_with_raw(
        &self,
        adapter: &hal::DynExposedAdapter,
    ) -> Result<hal::SurfaceCapabilities, GetSurfaceSupportError> {
        let backend = adapter.backend();
        let suf = self
            .raw(backend)
            .ok_or(GetSurfaceSupportError::NotSupportedByBackend(backend))?;
        profiling::scope!("surface_capabilities");
        let caps = unsafe { adapter.adapter.surface_capabilities(suf) }
            .ok_or(GetSurfaceSupportError::FailedToRetrieveSurfaceCapabilitiesForAdapter)?;
        Ok(caps)
    }

    /// Returns the HDR / luminance characteristics of the display backing this
    /// surface on `adapter`.
    ///
    /// Falls back to [`wgt::DisplayHdrInfo::default`] (all fields `None`) when the
    /// surface is not on `adapter`'s backend or the backend reports nothing.
    pub fn display_hdr_info(&self, adapter: &Adapter) -> wgt::DisplayHdrInfo {
        profiling::scope!("Surface::display_hdr_info");
        self.display_hdr_info_with_raw(&adapter.raw)
    }

    pub fn display_hdr_info_with_raw(
        &self,
        adapter: &hal::DynExposedAdapter,
    ) -> wgt::DisplayHdrInfo {
        let backend = adapter.backend();
        let Some(suf) = self.raw(backend) else {
            return wgt::DisplayHdrInfo::default();
        };
        profiling::scope!("surface_display_hdr_info");
        unsafe { adapter.adapter.surface_display_hdr_info(suf) }.unwrap_or_default()
    }

    pub fn raw(&self, backend: Backend) -> Option<&dyn hal::DynSurface> {
        self.surface_per_backend
            .get(&backend)
            .map(|surface| surface.as_ref())
    }

    /// Takes the current configuration, destroys its acquired texture and waits
    /// for all work on its device to finish.
    ///
    /// Returns the device the surface was configured for. The raw surface is
    /// still configured, so the caller must unconfigure it next.
    fn take_presentation<'a>(
        &self,
        presentation: &mut MutexGuard<'a, Option<Presentation>>,
    ) -> (Option<Arc<Device>>, UserClosures) {
        let mut result = UserClosures::default();
        let mut device = None;
        if let Some(mut present) = presentation.take() {
            if let Some(texture) = present.acquired_texture.take() {
                texture.destroy();
            }

            let user_callbacks;
            {
                // Wait for all work that uses the surface texture to finish
                let snatch_guard = present.device.snatchable_lock.read();

                let result;
                (user_callbacks, result) = present
                    .device
                    .maintain(wgt::PollType::wait_indefinitely(), snatch_guard);
                match result {
                    Ok(_) => {}
                    Err(WaitIdleError::Device(_)) => {
                        // we can ignore device lost errors here, since we are just cleaning up
                    }
                    Err(WaitIdleError::Timeout) if cfg!(target_family = "wasm") => {
                        // On wasm, you cannot actually successfully wait for the surface.
                        // However WebGL does not actually require you do this, so ignoring
                        // the failure is totally fine. See https://github.com/gfx-rs/wgpu/issues/7363
                    }
                    Err(WaitIdleError::Timeout) => {
                        unreachable!("wait_indefinitely() should never timeout")
                    }
                    Err(WaitIdleError::WrongSubmissionIndex(_, _)) => {
                        unreachable!("no submission index was provided")
                    }
                }
            }
            result.extend(user_callbacks);
            device = Some(present.device);
        }
        (device, result)
    }

    /// Unconfigures the raw surface from `device`.
    ///
    /// # Safety
    ///
    /// `device` must have been returned by [`Self::take_presentation`], and the
    /// surface must not have been configured since.
    unsafe fn unconfigure_raw(&self, device: &Device) {
        if let Some(surface) = self.raw(device.backend()) {
            let _command_indices = device.command_indices.write();
            unsafe { surface.unconfigure(device.raw()) };
        }
    }

    fn unconfigure_inner<'a>(
        &self,
        presentation: &mut MutexGuard<'a, Option<Presentation>>,
    ) -> UserClosures {
        let (device, user_callbacks) = self.take_presentation(presentation);
        if let Some(device) = device {
            unsafe { self.unconfigure_raw(&device) };
        }
        user_callbacks
    }

    pub fn unconfigure(self: &Arc<Self>) {
        profiling::scope!("Surface::unconfigure");
        let user_callbacks;
        {
            let mut presentation = self.presentation.lock();
            user_callbacks = self.unconfigure_inner(&mut presentation);
        }
        user_callbacks.fire();
    }

    pub fn configure(
        self: &Arc<Self>,
        device: &Arc<Device>,
        config: &wgt::SurfaceConfiguration<Vec<wgt::TextureFormat>>,
    ) -> Result<(), ConfigureSurfaceError> {
        use ConfigureSurfaceError as E;
        profiling::scope!("Surface::configure");

        #[cfg(feature = "trace")]
        if let Some(ref mut trace) = *device.trace.lock() {
            use crate::device::trace::{Action, IntoTrace};

            trace.add(Action::ConfigureSurface(self.to_trace(), config.clone()));
        }

        log::debug!("configuring surface with {config:?}");

        let caps = self
            .get_hal_capabilities(&device.adapter)
            .map_err(|_| E::UnsupportedQueueFamily)?;

        let mut hal_view_formats = Vec::new();
        for format in config.view_formats.iter() {
            if *format == config.format {
                continue;
            }
            if !caps.formats.iter().any(|fc| fc.format == config.format) {
                return Err(E::UnsupportedFormat {
                    requested: config.format,
                    available: caps.texture_formats().collect(),
                });
            }
            if config.format.remove_srgb_suffix() != format.remove_srgb_suffix() {
                return Err(E::InvalidViewFormat(*format, config.format));
            }
            hal_view_formats.push(*format);
        }

        if !hal_view_formats.is_empty() {
            device.require_downlevel_flags(wgt::DownlevelFlags::SURFACE_VIEW_FORMATS)?;
        }

        let maximum_frame_latency = config.desired_maximum_frame_latency.clamp(
            *caps.maximum_frame_latency.start(),
            *caps.maximum_frame_latency.end(),
        );
        let mut hal_config = hal::SurfaceConfiguration {
            maximum_frame_latency,
            present_mode: config.present_mode,
            composite_alpha_mode: config.alpha_mode,
            format: config.format,
            color_space: config.color_space,
            extent: wgt::Extent3d {
                width: config.width,
                height: config.height,
                depth_or_array_layers: 1,
            },
            usage: crate::conv::map_texture_usage(
                config.usage,
                hal::FormatAspects::COLOR,
                wgt::TextureFormatFeatureFlags::STORAGE_READ_ONLY
                    | wgt::TextureFormatFeatureFlags::STORAGE_WRITE_ONLY
                    | wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE,
            ),
            view_formats: hal_view_formats,
        };

        crate::device::surface_config::validate_surface_configuration(
            &mut hal_config,
            &caps,
            device.limits.max_texture_dimension_2d,
        )?;

        device.check_is_valid()?;

        let user_callbacks;
        let result = {
            // we keep presentation locked for the entire duration of the configure call,
            // so that no change can happen in the middle of it.
            let mut presentation = self.presentation.lock();

            let previous_device;
            (previous_device, user_callbacks) = self.take_presentation(&mut presentation);

            let surface_raw = self.raw(device.backend()).unwrap();
            // `command_indices` serializes these calls with other queue
            // operations. For the same device, hold it across both calls.
            let result = {
                let same_device = match previous_device {
                    Some(previous_device) if Arc::ptr_eq(&previous_device, device) => true,
                    Some(previous_device) => {
                        unsafe { self.unconfigure_raw(&previous_device) };
                        false
                    }
                    None => false,
                };
                let _command_indices = device.command_indices.write();
                if same_device {
                    unsafe { surface_raw.unconfigure(device.raw()) };
                }
                unsafe { surface_raw.configure(device.raw(), &hal_config) }
            };
            match result {
                Ok(()) => {
                    *presentation = Some(Presentation {
                        device: Arc::clone(device),
                        config: config.clone(),
                        acquired_texture: None,
                    });
                    Ok(())
                }
                Err(error) => Err(match error {
                    hal::SurfaceError::Outdated
                    | hal::SurfaceError::Lost
                    | hal::SurfaceError::Occluded
                    | hal::SurfaceError::Timeout => E::InvalidSurface,
                    hal::SurfaceError::Device(error) => E::Device(device.handle_hal_error(error)),
                    hal::SurfaceError::Other(message) => {
                        log::error!("surface configuration failed: {message}");
                        E::InvalidSurface
                    }
                }),
            }
        };
        user_callbacks.fire();

        result
    }
}

impl Drop for Surface {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("Surface::drop");

        api_log!("Surface::drop {:?}", self as *const _);
        let user_closures;
        {
            let mut presentation = self.presentation.lock();
            user_closures = self.unconfigure_inner(&mut presentation);
        }
        user_closures.fire();
    }
}

pub struct Adapter {
    pub(crate) raw: hal::DynExposedAdapter,
    pub(crate) instance: Arc<Instance>,
    consumed: AtomicBool,
}

impl Adapter {
    pub(crate) fn new(raw: hal::DynExposedAdapter, instance: Arc<Instance>) -> Arc<Self> {
        Arc::new(Self {
            raw,
            instance,
            consumed: AtomicBool::new(false),
        })
    }

    /// Returns the backend this adapter is using.
    pub fn backend(&self) -> Backend {
        self.raw.backend()
    }

    pub fn is_surface_supported(&self, surface: &Surface) -> bool {
        // If get_capabilities returns Err, then the API does not advertise support for the surface.
        //
        // This could occur if the user is running their app on Wayland but Vulkan does not support
        // VK_KHR_wayland_surface.
        surface.get_hal_capabilities(self).is_ok()
    }

    pub fn get_info(&self) -> wgt::AdapterInfo {
        self.raw.info.clone()
    }

    pub fn features(&self) -> wgt::Features {
        self.raw.features
    }

    pub fn limits(&self) -> wgt::Limits {
        self.raw.capabilities.limits.clone()
    }

    pub fn downlevel_capabilities(&self) -> wgt::DownlevelCapabilities {
        self.raw.capabilities.downlevel.clone()
    }

    pub fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
        unsafe { self.raw.adapter.get_presentation_timestamp() }
    }

    pub fn cooperative_matrix_properties(&self) -> Vec<wgt::CooperativeMatrixProperties> {
        self.raw.capabilities.cooperative_matrix_properties.clone()
    }

    pub fn ray_tracing_invocation_reorder_mode(&self) -> wgt::RayTracingInvocationReorderMode {
        self.raw.capabilities.ray_tracing_invocation_reorder_mode
    }

    pub fn get_texture_format_features(
        &self,
        format: wgt::TextureFormat,
    ) -> wgt::TextureFormatFeatures {
        use hal::TextureFormatCapabilities as Tfc;

        let mut caps = unsafe { self.raw.adapter.texture_format_capabilities(format) };

        // Storage bindings of multi-planar textures are not supported.
        if format.is_multi_planar_format() {
            caps -= Tfc::STORAGE_READ_ONLY
                | Tfc::STORAGE_WRITE_ONLY
                | Tfc::STORAGE_READ_WRITE
                | Tfc::STORAGE_ATOMIC;
        }

        let mut allowed_usages = wgt::TextureUsages::empty();

        allowed_usages.set(wgt::TextureUsages::COPY_SRC, caps.contains(Tfc::COPY_SRC));
        allowed_usages.set(wgt::TextureUsages::COPY_DST, caps.contains(Tfc::COPY_DST));
        allowed_usages.set(
            wgt::TextureUsages::TEXTURE_BINDING,
            caps.contains(Tfc::SAMPLED),
        );
        allowed_usages.set(
            wgt::TextureUsages::STORAGE_BINDING,
            caps.intersects(
                Tfc::STORAGE_WRITE_ONLY
                    | Tfc::STORAGE_READ_ONLY
                    | Tfc::STORAGE_READ_WRITE
                    | Tfc::STORAGE_ATOMIC,
            ),
        );
        allowed_usages.set(
            wgt::TextureUsages::RENDER_ATTACHMENT | wgt::TextureUsages::TRANSIENT_ATTACHMENT,
            caps.intersects(Tfc::COLOR_ATTACHMENT | Tfc::DEPTH_STENCIL_ATTACHMENT),
        );
        allowed_usages.set(
            wgt::TextureUsages::STORAGE_ATOMIC,
            caps.contains(Tfc::STORAGE_ATOMIC),
        );

        let mut flags = wgt::TextureFormatFeatureFlags::empty();
        flags.set(
            wgt::TextureFormatFeatureFlags::STORAGE_READ_ONLY,
            caps.contains(Tfc::STORAGE_READ_ONLY),
        );
        flags.set(
            wgt::TextureFormatFeatureFlags::STORAGE_WRITE_ONLY,
            caps.contains(Tfc::STORAGE_WRITE_ONLY),
        );
        flags.set(
            wgt::TextureFormatFeatureFlags::STORAGE_READ_WRITE,
            caps.contains(Tfc::STORAGE_READ_WRITE),
        );

        flags.set(
            wgt::TextureFormatFeatureFlags::STORAGE_ATOMIC,
            caps.contains(Tfc::STORAGE_ATOMIC),
        );

        flags.set(
            wgt::TextureFormatFeatureFlags::FILTERABLE,
            caps.contains(Tfc::SAMPLED_LINEAR),
        );

        flags.set(
            wgt::TextureFormatFeatureFlags::BLENDABLE,
            caps.contains(Tfc::COLOR_ATTACHMENT_BLEND),
        );

        flags.set(
            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X2,
            caps.contains(Tfc::MULTISAMPLE_X2),
        );
        flags.set(
            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4,
            caps.contains(Tfc::MULTISAMPLE_X4),
        );
        flags.set(
            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X8,
            caps.contains(Tfc::MULTISAMPLE_X8),
        );
        flags.set(
            wgt::TextureFormatFeatureFlags::MULTISAMPLE_X16,
            caps.contains(Tfc::MULTISAMPLE_X16),
        );

        flags.set(
            wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
            caps.contains(Tfc::MULTISAMPLE_RESOLVE),
        );

        wgt::TextureFormatFeatures {
            allowed_usages,
            flags,
        }
    }

    /// # Safety
    ///
    /// - `hal_device` must be created from this adapter.
    /// - `desc` must be a subset of `hal_device` features and limits.
    pub unsafe fn create_device_and_queue_from_hal(
        self: &Arc<Self>,
        hal_device: hal::DynOpenDevice,
        desc: &DeviceDescriptor,
    ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
        profiling::scope!("Adapter::create_device_and_queue_from_hal");
        api_log!("Adapter::create_device_and_queue_from_hal");

        if self
            .instance
            .flags
            .contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE)
            && self.consumed.load(Ordering::SeqCst)
        {
            return Err(RequestDeviceError::AdapterConsumed);
        }

        let default_queue_desc = desc.default_queue.clone();

        let device = Device::new(hal_device.device, self, desc, self.instance.flags)?;
        let device = Arc::new(device);

        let queue = Queue::new(
            device.clone(),
            hal_device.queue,
            default_queue_desc,
            self.instance.flags,
        )?;
        let queue = Arc::new(queue);

        device.set_queue(&queue);
        device.late_init_resources_with_queue()?;

        resource_log!("Created Device {:?}", Arc::as_ptr(&device));
        resource_log!("Created Queue {:?}", Arc::as_ptr(&queue));

        self.instance.devices.push(&device);

        self.consumed.store(true, Ordering::SeqCst);

        Ok((device, queue))
    }

    /// Implements the part of <https://gpuweb.github.io/gpuweb/#a-new-device>
    /// for applying the [default feature level](https://gpuweb.github.io/gpuweb/#feature-level-string)
    /// to the requested features and limits of a device descriptor.
    fn apply_default_feature_level(&self, features: &mut wgt::Features, limits: &mut wgt::Limits) {
        if self
            .raw
            .features
            .contains(wgt::Features::CORE_FEATURES_AND_LIMITS)
        {
            *features |= wgt::Features::CORE_FEATURES_AND_LIMITS;
            // Apply default limits if strict WebGPU compliance is enabled.
            // Sometimes it is useful to have lower limits than the default ones for testing.
            if self
                .instance
                .flags
                .contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE)
            {
                let mut default_limits = wgt::Limits::defaults();
                default_limits.zero_native_only();
                *limits = default_limits.or_better_values_from(limits);
            }
        } else {
            // here we should apply compatibility mode default limits
            // but we do not implement compatibility yet: https://github.com/gfx-rs/wgpu/issues/8124
        }
    }

    /// Validate a device descriptor.
    ///
    /// This validates the provided device descriptor as if it were passed to
    /// [`Self::request_device`]. If [`InstanceFlags::STRICT_WEBGPU_COMPLIANCE`] is active,
    /// the requested extensions in the descriptor will be filtered to remove `wgpu`
    /// extensions, except for those that are included in [`limits::EXEMPT_FEATURES`].
    ///
    /// This may be useful when it is necessary to obtain the device itself from a raw hal
    /// API, but the rest of the `request_device` validation is still desired.
    pub fn validate_device_descriptor(
        &self,
        desc: &mut DeviceDescriptor,
    ) -> Result<(), RequestDeviceError> {
        filter_features_and_limits(
            self.instance.flags,
            &mut desc.required_features,
            &mut desc.required_limits,
        );

        // Verify all features were exposed by the adapter
        if !self.raw.features.contains(desc.required_features) {
            return Err(RequestDeviceError::UnsupportedFeature(
                desc.required_features - self.raw.features,
            ));
        }

        // Check if experimental features are permitted to be enabled.
        if desc
            .required_features
            .intersects(wgt::Features::all_experimental_mask())
            && !desc.experimental_features.is_enabled()
        {
            return Err(RequestDeviceError::ExperimentalFeaturesNotEnabled(
                desc.required_features
                    .intersection(wgt::Features::all_experimental_mask()),
            ));
        }

        let caps = &self.raw.capabilities;
        if Backends::PRIMARY.contains(Backends::from(self.backend()))
            && !caps.downlevel.is_webgpu_compliant()
        {
            let missing_flags = wgt::DownlevelFlags::compliant() - caps.downlevel.flags;
            log::warn!("Missing downlevel flags: {missing_flags:?}\n{DOWNLEVEL_WARNING_MESSAGE}");
            log::warn!("{:#?}", caps.downlevel);
        }

        // Verify feature preconditions
        if desc
            .required_features
            .contains(wgt::Features::MAPPABLE_PRIMARY_BUFFERS)
            && self.raw.info.device_type == wgt::DeviceType::DiscreteGpu
        {
            log::warn!(
                "Feature MAPPABLE_PRIMARY_BUFFERS enabled on a discrete gpu. \
                        This is a massive performance footgun and likely not what you wanted"
            );
        }

        if let Some(failed) = check_limits(&desc.required_limits, &caps.limits).pop() {
            return Err(RequestDeviceError::LimitsExceeded(failed));
        }

        self.apply_default_feature_level(&mut desc.required_features, &mut desc.required_limits);

        normalize_max_resource_per_shader_stage_limits(&mut desc.required_limits);

        Ok(())
    }

    pub fn request_device(
        self: &Arc<Self>,
        desc: &DeviceDescriptor,
    ) -> Result<(Arc<Device>, Arc<Queue>), RequestDeviceError> {
        profiling::scope!("Adapter::request_device");
        api_log!("Adapter::request_device");

        let mut desc = desc.clone();
        self.validate_device_descriptor(&mut desc)?;

        let open = unsafe {
            self.raw.adapter.open(
                desc.required_features,
                &desc.required_limits,
                &desc.memory_hints,
            )
        }
        .map_err(DeviceError::from_hal)?;

        unsafe { self.create_device_and_queue_from_hal(open, &desc) }
    }
}

impl Drop for Adapter {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("Adapter::drop");
        api_log!("Adapter::drop {:?}", self as *const _);
    }
}

crate::impl_resource_type!(Adapter);
crate::impl_storage_item!(Adapter);

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum GetSurfaceSupportError {
    #[error("Surface is not supported for the specified backend {0}")]
    NotSupportedByBackend(Backend),
    #[error("Failed to retrieve surface capabilities for the specified adapter.")]
    FailedToRetrieveSurfaceCapabilitiesForAdapter,
}

#[derive(Clone, Debug, Error)]
/// Error when requesting a device from the adapter
#[non_exhaustive]
pub enum RequestDeviceError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error(transparent)]
    LimitsExceeded(#[from] FailedLimit),
    #[error("Failed to initialize Timestamp Normalizer")]
    TimestampNormalizerInitFailed(#[from] TimestampNormalizerInitError),
    #[error("Unsupported features were requested: {0}")]
    UnsupportedFeature(wgt::Features),
    #[error(
        "Some experimental features, {0}, were requested, but experimental features are not enabled"
    )]
    ExperimentalFeaturesNotEnabled(wgt::Features),
    #[error("The adapter has already been consumed.")]
    AdapterConsumed,
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreateSurfaceError {
    #[error("The backend {0} was not enabled on the instance.")]
    BackendNotEnabled(Backend),
    #[error("Failed to create surface for any enabled backend: {0:?}")]
    FailedToCreateSurfaceForAnyBackend(HashMap<Backend, hal::InstanceError>),
    #[error("The display handle used to create this Instance does not match the one used to create a surface on it")]
    MismatchingDisplayHandle,
    #[error(
        "No `DisplayHandle` is available to create this surface with.  When creating a surface with `create_surface()` \
        you must specify a display handle in `InstanceDescriptor::display`.  \
        Rarely, if you need to create surfaces from different `DisplayHandle`s (ex. different Wayland or X11 connections), \
        you must use `create_surface_unsafe()`."
    )]
    MissingDisplayHandle,
}

/// This function checks that the adapter obeys WebGPU's adapter capability
/// guarantees. Most of the limits are adjusted in wgpu-hal's
/// `adjust_raw_limits` fn. So we only check the remaining properties here.
/// See <https://gpuweb.github.io/gpuweb/#adapter-capability-guarantees>.
fn adapter_allowed(
    flags: InstanceFlags,
    info: &impl fmt::Debug,
    limits: &wgt::Limits,
    features: wgt::Features,
) -> bool {
    // Check "All alignment-class limits must be powers of 2."
    //
    // Even if the application has not requested strict WebGPU compliance,
    // non-power-of-two alignment limits are nonsensical, so don't attempt
    // to use such a device.
    let min_uniform_buffer_offset_alignment = limits.min_uniform_buffer_offset_alignment;
    if !min_uniform_buffer_offset_alignment.is_power_of_two() {
        log::error!(
            "Adapter {:?} min_uniform_buffer_offset_alignment limit is not a power of 2: {:?}",
            info,
            min_uniform_buffer_offset_alignment
        );
        return false;
    }
    let min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment;
    if !min_storage_buffer_offset_alignment.is_power_of_two() {
        log::error!(
            "Adapter {:?} min_storage_buffer_offset_alignment limit is not a power of 2: {:?}",
            info,
            min_storage_buffer_offset_alignment
        );
        return false;
    }

    // Following checks are only enabled if `STRICT_WEBGPU_COMPLIANCE` is set.
    if !flags.contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE) {
        return true;
    }

    if !features.contains(wgt::Features::CORE_FEATURES_AND_LIMITS) {
        log::debug!(
            "Adapter {:?} is not WebGPU compliant because it does not support \
            CORE_FEATURES_AND_LIMITS",
            info
        );
        return false;
    }

    true
}

fn filter_features_and_limits(
    flags: InstanceFlags,
    features: &mut wgt::Features,
    limits: &mut wgt::Limits,
) {
    if flags.contains(InstanceFlags::STRICT_WEBGPU_COMPLIANCE) {
        *features &= wgt::Features::all_webgpu_mask() | limits::EXEMPT_FEATURES;
        limits.zero_native_only();
    }
}

fn normalize_max_resource_per_shader_stage_limits(limits: &mut wgt::Limits) {
    // The next steps are from <https://www.w3.org/TR/webgpu/#a-new-device>.

    // > 7. Set `limits.maxStorageBuffersPerShaderStage` to
    // >    `max(limits.maxStorageBuffersPerShaderStage, limits.maxStorageBuffersInVertexStage,
    // >    limits.maxStorageBuffersInFragmentStage)`.

    limits.max_storage_buffers_per_shader_stage = [
        limits.max_storage_buffers_per_shader_stage,
        limits.max_storage_buffers_in_vertex_stage,
        limits.max_storage_buffers_in_fragment_stage,
    ]
    .into_iter()
    .max()
    .unwrap();

    // > 8. Set `limits.maxStorageTexturesPerShaderStage` to
    // >    `max(limits.maxStorageTexturesPerShaderStage, limits.maxStorageTexturesInVertexStage,
    // >    limits.maxStorageTexturesInFragmentStage)`.

    limits.max_storage_textures_per_shader_stage = [
        limits.max_storage_textures_per_shader_stage,
        limits.max_storage_textures_in_vertex_stage,
        limits.max_storage_textures_in_fragment_stage,
    ]
    .into_iter()
    .max()
    .unwrap();

    // > 9. If features contains "core-features-and-limits":
    //
    // NOTE: We don't implement compat (yet?), so we do this unconditionally. See also:
    // <https://github.com/gfx-rs/wgpu/issues/8124>

    // >   1. Set `limits.maxStorageBuffersInVertexStage` and
    // >      `limits.maxStorageBuffersInFragmentStage` to
    // >      `limits.maxStorageBuffersPerShaderStage`.
    limits.max_storage_buffers_in_vertex_stage = limits.max_storage_buffers_per_shader_stage;
    limits.max_storage_buffers_in_fragment_stage = limits.max_storage_buffers_per_shader_stage;

    // >   2. Set `limits.maxStorageTexturesInVertexStage` and
    // >      `limits.maxStorageTexturesInFragmentStage` to
    // >      `limits.maxStorageTexturesPerShaderStage`.
    limits.max_storage_textures_in_vertex_stage = limits.max_storage_textures_per_shader_stage;
    limits.max_storage_textures_in_fragment_stage = limits.max_storage_textures_per_shader_stage;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn non_power_of_two_uniform_alignment_always_rejected() {
        let limits = wgt::Limits {
            min_uniform_buffer_offset_alignment: 3,
            ..wgt::Limits::defaults()
        };
        assert!(!adapter_allowed(
            InstanceFlags::empty(),
            &"",
            &limits,
            wgt::Features::CORE_FEATURES_AND_LIMITS
        ));
        assert!(!adapter_allowed(
            InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
            &"",
            &limits,
            wgt::Features::CORE_FEATURES_AND_LIMITS
        ));
    }

    #[test]
    fn non_power_of_two_storage_alignment_always_rejected() {
        let limits = wgt::Limits {
            min_storage_buffer_offset_alignment: 96,
            ..wgt::Limits::defaults()
        };
        assert!(!adapter_allowed(
            InstanceFlags::empty(),
            &"",
            &limits,
            wgt::Features::CORE_FEATURES_AND_LIMITS
        ));
        assert!(!adapter_allowed(
            InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
            &"",
            &limits,
            wgt::Features::CORE_FEATURES_AND_LIMITS
        ));
    }

    #[test]
    fn low_limits_allowed_without_strict_compliance() {
        let limits = wgt::Limits {
            max_texture_dimension_1d: 1,
            ..wgt::Limits::defaults()
        };
        assert!(adapter_allowed(
            InstanceFlags::empty(),
            &"",
            &limits,
            wgt::Features::empty()
        ));
    }

    #[test]
    fn low_limits_rejected_with_strict_compliance() {
        let limits = wgt::Limits {
            max_texture_dimension_1d: 1,
            ..wgt::Limits::defaults()
        };
        assert!(!adapter_allowed(
            InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
            &"",
            &limits,
            wgt::Features::empty()
        ));
    }

    #[test]
    fn missing_core_features_and_limits_rejected_with_strict_compliance() {
        assert!(!adapter_allowed(
            InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
            &"",
            &wgt::Limits::defaults(),
            wgt::Features::empty()
        ));
    }

    #[test]
    fn fully_compliant_adapter_always_allowed() {
        assert!(adapter_allowed(
            InstanceFlags::STRICT_WEBGPU_COMPLIANCE,
            &"",
            &wgt::Limits::defaults(),
            wgt::Features::CORE_FEATURES_AND_LIMITS
        ));
    }

    mod storage_resource_limits {
        use super::*;

        #[track_caller]
        fn assert_normalized_eq(non_normalized: &wgt::Limits, expected: &wgt::Limits) {
            let mut normalized = non_normalized.clone();
            normalize_max_resource_per_shader_stage_limits(&mut normalized);
            assert_eq!(&normalized, expected);
        }

        #[test]
        fn normalization_is_idempotent() {
            let original = wgt::Limits {
                max_storage_buffers_in_vertex_stage: 16,
                max_storage_textures_in_vertex_stage: 9,
                ..wgt::Limits::defaults()
            };

            let mut first_normalization = original.clone();
            normalize_max_resource_per_shader_stage_limits(&mut first_normalization);
            assert_ne!(original, first_normalization);

            let mut second_normalization = first_normalization.clone();
            normalize_max_resource_per_shader_stage_limits(&mut second_normalization);
            assert_eq!(first_normalization, second_normalization);
        }

        #[test]
        fn limits_presets_already_normalized() {
            [
                wgt::Limits::defaults(),
                wgt::Limits::downlevel_defaults(),
                wgt::Limits::downlevel_webgl2_defaults(),
                wgt::Limits::unlimited(),
            ]
            .iter()
            .for_each(|l| assert_normalized_eq(l, l))
        }

        #[test]
        fn in_stage_raises_per_shader_stage() {
            assert_normalized_eq(
                &wgt::Limits {
                    max_storage_buffers_per_shader_stage: 8,
                    max_storage_buffers_in_vertex_stage: 16,
                    max_storage_buffers_in_fragment_stage: 16,
                    ..wgt::Limits::defaults()
                },
                &wgt::Limits {
                    max_storage_buffers_per_shader_stage: 16,
                    max_storage_buffers_in_vertex_stage: 16,
                    max_storage_buffers_in_fragment_stage: 16,
                    ..wgt::Limits::defaults()
                },
            );

            assert_normalized_eq(
                &wgt::Limits {
                    max_storage_textures_per_shader_stage: 8,
                    max_storage_textures_in_vertex_stage: 9,
                    max_storage_textures_in_fragment_stage: 9,
                    ..wgt::Limits::defaults()
                },
                &wgt::Limits {
                    max_storage_textures_per_shader_stage: 9,
                    max_storage_textures_in_vertex_stage: 9,
                    max_storage_textures_in_fragment_stage: 9,
                    ..wgt::Limits::defaults()
                },
            );
        }

        #[test]
        fn per_shader_stage_raises_in_stage() {
            assert_normalized_eq(
                &wgt::Limits {
                    max_storage_buffers_per_shader_stage: 16,
                    max_storage_buffers_in_vertex_stage: 4,
                    max_storage_buffers_in_fragment_stage: 4,
                    max_storage_textures_per_shader_stage: 8,
                    max_storage_textures_in_vertex_stage: 4,
                    max_storage_textures_in_fragment_stage: 4,
                    ..wgt::Limits::defaults()
                },
                &wgt::Limits {
                    max_storage_buffers_per_shader_stage: 16,
                    max_storage_buffers_in_vertex_stage: 16,
                    max_storage_buffers_in_fragment_stage: 16,
                    max_storage_textures_per_shader_stage: 8,
                    max_storage_textures_in_vertex_stage: 8,
                    max_storage_textures_in_fragment_stage: 8,
                    ..wgt::Limits::defaults()
                },
            );
        }

        #[test]
        fn lowering_per_shader_stage_noop() {
            assert_normalized_eq(
                &wgt::Limits {
                    max_storage_buffers_per_shader_stage: 1,
                    max_storage_textures_per_shader_stage: 1,
                    ..wgt::Limits::defaults()
                },
                &wgt::Limits::defaults(),
            );
        }
    }

    #[test]
    fn downlevel_default_limits_less_than_default_limits() {
        let res = check_limits(&wgt::Limits::downlevel_defaults(), &wgt::Limits::default());
        assert!(
            res.is_empty(),
            "Downlevel limits are greater than default limits",
        )
    }
}