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
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! Link between Vulkan and a window and/or the screen.
//!
//! Before you can draw on the screen or a window, you have to create two objects:
//!
//! - Create a `Surface` object that represents the location where the image will show up (either
//!   a window or a monitor).
//! - Create a `Swapchain` that uses that `Surface`.
//!
//! Creating a surface can be done with only an `Instance` object. However creating a swapchain
//! requires a `Device` object.
//!
//! Once you have a swapchain, you can retrieve `Image` objects from it and draw to them just like
//! you would draw on any other image.
//!
//! # Surfaces
//!
//! A surface is an object that represents a location where to render. It can be created from an
//! instance and either a window handle (in a platform-specific way) or a monitor.
//!
//! In order to use surfaces, you will have to enable the `VK_KHR_surface` extension on the
//! instance. See the `instance` module for more information about how to enable extensions.
//!
//! ## Creating a surface from a window
//!
//! There are 5 extensions that each allow you to create a surface from a type of window:
//!
//! - `VK_KHR_xlib_surface`
//! - `VK_KHR_xcb_surface`
//! - `VK_KHR_wayland_surface`
//! - `VK_KHR_android_surface`
//! - `VK_KHR_win32_surface`
//!
//! For example if you want to create a surface from an Android surface, you will have to enable
//! the `VK_KHR_android_surface` extension and use `Surface::from_android`.
//! See the documentation of `Surface` for all the possible constructors.
//!
//! Trying to use one of these functions without enabling the proper extension will result in an
//! error.
//!
//! **Note that the `Surface` object is potentially unsafe**. It is your responsibility to
//! keep the window alive for at least as long as the surface exists. In many cases Surface
//! may be able to do this for you, if you pass it ownership of your Window (or a
//! reference-counting container for it).
//!
//! ### Examples
//!
//! ```no_run
//! use std::ptr;
//! use vulkano::{
//!     instance::{Instance, InstanceCreateInfo, InstanceExtensions},
//!     swapchain::Surface,
//!     Version, VulkanLibrary,
//! };
//!
//! let instance = {
//!     let library = VulkanLibrary::new()
//!         .unwrap_or_else(|err| panic!("Couldn't load Vulkan library: {:?}", err));
//!
//!     let extensions = InstanceExtensions {
//!         khr_surface: true,
//!         khr_win32_surface: true,        // If you don't enable this, `from_hwnd` will fail.
//!         .. InstanceExtensions::empty()
//!     };
//!
//!     Instance::new(
//!         library,
//!         InstanceCreateInfo {
//!             enabled_extensions: extensions,
//!             ..Default::default()
//!         },
//!     )
//!     .unwrap_or_else(|err| panic!("Couldn't create instance: {:?}", err))
//! };
//!
//! # use std::sync::Arc;
//! # struct Window(*const u32);
//! # impl Window { fn hwnd(&self) -> *const u32 { self.0 } }
//! # unsafe impl Send for Window {}
//! # unsafe impl Sync for Window {}
//! # fn build_window() -> Arc<Window> { Arc::new(Window(ptr::null())) }
//! let window = build_window(); // Third-party function, not provided by vulkano
//! let _surface = unsafe {
//!     let hinstance: *const () = ptr::null(); // Windows-specific object
//!     Surface::from_win32(
//!         instance.clone(),
//!         hinstance, window.hwnd(),
//!         Some(window),
//!     ).unwrap()
//! };
//! ```
//!
//! # Swapchains
//!
//! A surface represents a location on the screen and can be created from an instance. Once you
//! have a surface, the next step is to create a swapchain. Creating a swapchain requires a device,
//! and allocates the resources that will be used to display images on the screen.
//!
//! A swapchain is composed of one or multiple images. Each image of the swapchain is presented in
//! turn on the screen, one after another. More information below.
//!
//! Swapchains have several properties:
//!
//!  - The number of images that will cycle on the screen.
//!  - The format of the images.
//!  - The 2D dimensions of the images, plus a number of layers, for a total of three dimensions.
//!  - The usage of the images, similar to creating other images.
//!  - The queue families that are going to use the images, similar to creating other images.
//!  - An additional transformation (rotation or mirroring) to perform on the final output.
//!  - How the alpha of the final output will be interpreted.
//!  - How to perform the cycling between images in regard to vsync.
//!
//! You can query the supported values of all these properties from the physical device.
//!
//! ## Creating a swapchain
//!
//! In order to create a swapchain, you will first have to enable the `VK_KHR_swapchain` extension
//! on the device (and not on the instance like `VK_KHR_surface`):
//!
//! ```no_run
//! # use vulkano::device::DeviceExtensions;
//! let ext = DeviceExtensions {
//!     khr_swapchain: true,
//!     .. DeviceExtensions::empty()
//! };
//! ```
//!
//! Then, query the capabilities of the surface with
//! [`PhysicalDevice::surface_capabilities`](crate::device::physical::PhysicalDevice::surface_capabilities)
//! and
//! [`PhysicalDevice::surface_formats`](crate::device::physical::PhysicalDevice::surface_formats)
//! and choose which values you are going to use.
//!
//! ```no_run
//! # use std::{error::Error, sync::Arc};
//! # use vulkano::device::Device;
//! # use vulkano::swapchain::Surface;
//! # use std::cmp::{max, min};
//! # fn choose_caps(device: Arc<Device>, surface: Arc<Surface>) -> Result<(), Box<dyn Error>> {
//! let surface_capabilities = device
//!     .physical_device()
//!     .surface_capabilities(&surface, Default::default())?;
//!
//! // Use the current window size or some fixed resolution.
//! let image_extent = surface_capabilities.current_extent.unwrap_or([640, 480]);
//!
//! // Try to use double-buffering.
//! let min_image_count = match surface_capabilities.max_image_count {
//!     None => max(2, surface_capabilities.min_image_count),
//!     Some(limit) => min(max(2, surface_capabilities.min_image_count), limit)
//! };
//!
//! // Preserve the current surface transform.
//! let pre_transform = surface_capabilities.current_transform;
//!
//! // Use the first available format.
//! let (image_format, color_space) = device
//!     .physical_device()
//!     .surface_formats(&surface, Default::default())?[0];
//! # Ok(())
//! # }
//! ```
//!
//! Then, call [`Swapchain::new`](crate::swapchain::Swapchain::new).
//!
//! ```no_run
//! # use std::{error::Error, sync::Arc};
//! # use vulkano::device::{Device, Queue};
//! # use vulkano::image::ImageUsage;
//! # use vulkano::sync::SharingMode;
//! # use vulkano::format::Format;
//! # use vulkano::swapchain::{Surface, Swapchain, SurfaceTransform, PresentMode, CompositeAlpha, ColorSpace, FullScreenExclusive, SwapchainCreateInfo};
//! # fn create_swapchain(
//! #     device: Arc<Device>, surface: Arc<Surface>,
//! #     min_image_count: u32, image_format: Format, image_extent: [u32; 2],
//! #     pre_transform: SurfaceTransform, composite_alpha: CompositeAlpha,
//! #     present_mode: PresentMode, full_screen_exclusive: FullScreenExclusive
//! # ) -> Result<(), Box<dyn Error>> {
//! // Create the swapchain and its images.
//! let (swapchain, images) = Swapchain::new(
//!     // Create the swapchain in this `device`'s memory.
//!     device,
//!     // The surface where the images will be presented.
//!     surface,
//!     // The creation parameters.
//!     SwapchainCreateInfo {
//!         // How many images to use in the swapchain.
//!         min_image_count,
//!         // The format of the images.
//!         image_format,
//!         // The size of each image.
//!         image_extent,
//!         // The created swapchain images will be used as a color attachment for rendering.
//!         image_usage: ImageUsage::COLOR_ATTACHMENT,
//!         // What transformation to use with the surface.
//!         pre_transform,
//!         // How to handle the alpha channel.
//!         composite_alpha,
//!         // How to present images.
//!         present_mode,
//!         // How to handle full-screen exclusivity
//!         full_screen_exclusive,
//!         ..Default::default()
//!     }
//! )?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! Creating a swapchain not only returns the swapchain object, but also all the images that belong
//! to it.
//!
//! ## Acquiring and presenting images
//!
//! Once you created a swapchain and retrieved all the images that belong to it (see previous
//! section), you can draw on it. This is done in three steps:
//!
//!  - Call `swapchain::acquire_next_image`. This function will return the index of the image
//!    (within the list returned by `Swapchain::new`) that is available to draw, plus a future
//!    representing the moment when the GPU will gain access to that image.
//!  - Draw on that image just like you would draw to any other image (see the documentation of
//!    the `pipeline` module). You need to chain the draw after the future that was returned by
//!    `acquire_next_image`.
//!  - Call `Swapchain::present` with the same index and by chaining the futures, in order to tell
//!    the implementation that you are finished drawing to the image and that it can queue a
//!    command to present the image on the screen after the draw operations are finished.
//!
//! ```
//! use vulkano::swapchain::{self, SwapchainPresentInfo};
//! use vulkano::sync::GpuFuture;
//! # let queue: ::std::sync::Arc<::vulkano::device::Queue> = return;
//! # let mut swapchain: ::std::sync::Arc<swapchain::Swapchain> = return;
//! // let mut (swapchain, images) = Swapchain::new(...);
//! loop {
//!     # let mut command_buffer: ::std::sync::Arc<::vulkano::command_buffer::PrimaryAutoCommandBuffer> = return;
//!     let (image_index, suboptimal, acquire_future)
//!         = swapchain::acquire_next_image(swapchain.clone(), None).unwrap();
//!
//!     // The command_buffer contains the draw commands that modify the framebuffer
//!     // constructed from images[image_index]
//!     acquire_future
//!         .then_execute(queue.clone(), command_buffer)
//!         .unwrap()
//!         .then_swapchain_present(
//!             queue.clone(),
//!             SwapchainPresentInfo::swapchain_image_index(swapchain.clone(), image_index),
//!         )
//!         .then_signal_fence_and_flush()
//!         .unwrap();
//! }
//! ```
//!
//! ## Recreating a swapchain
//!
//! In some situations, the swapchain will become invalid by itself. This includes for example when
//! the window is resized (as the images of the swapchain will no longer match the window's) or,
//! on Android, when the application went to the background and goes back to the foreground.
//!
//! In this situation, acquiring a swapchain image or presenting it will return an error. Rendering
//! to an image of that swapchain will not produce any error, but may or may not work. To continue
//! rendering, you will need to *recreate* the swapchain by creating a new swapchain and passing
//! as last parameter the old swapchain.
//!
//! ```
//! use vulkano::{
//!     swapchain::{self, SwapchainCreateInfo, SwapchainPresentInfo},
//!     sync::GpuFuture, Validated, VulkanError,
//! };
//!
//! // let (swapchain, images) = Swapchain::new(...);
//! # let mut swapchain: ::std::sync::Arc<::vulkano::swapchain::Swapchain> = return;
//! # let mut images: Vec<::std::sync::Arc<::vulkano::image::Image>> = return;
//! # let queue: ::std::sync::Arc<::vulkano::device::Queue> = return;
//! let mut recreate_swapchain = false;
//!
//! loop {
//!     if recreate_swapchain {
//!         let (new_swapchain, new_images) = swapchain.recreate(SwapchainCreateInfo {
//!             image_extent: [1024, 768],
//!             ..swapchain.create_info()
//!         })
//!         .unwrap();
//!         swapchain = new_swapchain;
//!         images = new_images;
//!         recreate_swapchain = false;
//!     }
//!
//!     let (image_index, suboptimal, acq_future) =
//!         match swapchain::acquire_next_image(swapchain.clone(), None).map_err(Validated::unwrap) {
//!             Ok(r) => r,
//!             Err(VulkanError::OutOfDate) => { recreate_swapchain = true; continue; },
//!             Err(err) => panic!("{:?}", err),
//!         };
//!
//!     // ...
//!
//!     let final_future = acq_future
//!         // .then_execute(...)
//!         .then_swapchain_present(
//!             queue.clone(),
//!             SwapchainPresentInfo::swapchain_image_index(swapchain.clone(), image_index),
//!         )
//!         .then_signal_fence_and_flush()
//!         .unwrap(); // TODO: PresentError?
//!
//!     if suboptimal {
//!         recreate_swapchain = true;
//!     }
//! }
//! ```

pub use self::{acquire_present::*, surface::*};
#[cfg(target_os = "ios")]
pub use surface::IOSMetalLayer;

mod acquire_present;
mod surface;

use crate::{
    device::{Device, DeviceOwned},
    format::Format,
    image::{Image, ImageCreateFlags, ImageFormatInfo, ImageTiling, ImageType, ImageUsage},
    instance::InstanceOwnedDebugWrapper,
    macros::{impl_id_counter, vulkan_bitflags, vulkan_bitflags_enum, vulkan_enum},
    sync::Sharing,
    Requires, RequiresAllOf, RequiresOneOf, Validated, ValidationError, Version, VulkanError,
    VulkanObject,
};
use parking_lot::Mutex;
use smallvec::SmallVec;
use std::{
    fmt::Debug,
    mem::MaybeUninit,
    num::NonZeroU64,
    ptr,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc,
    },
};

/// Contains the swapping system and the images that can be shown on a surface.
#[derive(Debug)]
pub struct Swapchain {
    handle: ash::vk::SwapchainKHR,
    device: InstanceOwnedDebugWrapper<Arc<Device>>,
    surface: InstanceOwnedDebugWrapper<Arc<Surface>>,
    id: NonZeroU64,

    flags: SwapchainCreateFlags,
    min_image_count: u32,
    image_format: Format,
    image_view_formats: Vec<Format>,
    image_color_space: ColorSpace,
    image_extent: [u32; 2],
    image_array_layers: u32,
    image_usage: ImageUsage,
    image_sharing: Sharing<SmallVec<[u32; 4]>>,
    pre_transform: SurfaceTransform,
    composite_alpha: CompositeAlpha,
    present_mode: PresentMode,
    present_modes: SmallVec<[PresentMode; PresentMode::COUNT]>,
    clipped: bool,
    scaling_behavior: Option<PresentScaling>,
    present_gravity: Option<[PresentGravity; 2]>,
    full_screen_exclusive: FullScreenExclusive,
    win32_monitor: Option<Win32Monitor>,

    prev_present_id: AtomicU64,

    // Whether full-screen exclusive is currently held.
    full_screen_exclusive_held: AtomicBool,

    // The images of this swapchain.
    images: Vec<ImageEntry>,

    // If true, that means we have tried to use this swapchain to recreate a new swapchain. The
    // current swapchain can no longer be used for anything except presenting already-acquired
    // images.
    //
    // We use a `Mutex` instead of an `AtomicBool` because we want to keep that locked while
    // we acquire the image.
    is_retired: Mutex<bool>,
}

#[derive(Debug)]
struct ImageEntry {
    handle: ash::vk::Image,
    layout_initialized: AtomicBool,
}

impl Swapchain {
    /// Creates a new `Swapchain`.
    ///
    /// This function returns the swapchain plus a list of the images that belong to the
    /// swapchain. The order in which the images are returned is important for the
    /// `acquire_next_image` and `present` functions.
    ///
    /// # Panics
    ///
    /// - Panics if the device and the surface don't belong to the same instance.
    /// - Panics if `create_info.usage` is empty.
    ///
    // TODO: isn't it unsafe to take the surface through an Arc when it comes to vulkano-win?
    #[inline]
    pub fn new(
        device: Arc<Device>,
        surface: Arc<Surface>,
        create_info: SwapchainCreateInfo,
    ) -> Result<(Arc<Swapchain>, Vec<Arc<Image>>), Validated<VulkanError>> {
        Self::validate_new_inner(&device, &surface, &create_info)?;

        unsafe { Ok(Self::new_unchecked(device, surface, create_info)?) }
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    #[inline]
    pub unsafe fn new_unchecked(
        device: Arc<Device>,
        surface: Arc<Surface>,
        create_info: SwapchainCreateInfo,
    ) -> Result<(Arc<Swapchain>, Vec<Arc<Image>>), VulkanError> {
        let (handle, image_handles) =
            Self::new_inner_unchecked(&device, &surface, &create_info, None)?;

        Self::from_handle(device, handle, image_handles, surface, create_info)
    }

    /// Creates a new swapchain from this one.
    ///
    /// Use this when a swapchain has become invalidated, such as due to window resizes.
    ///
    /// # Panics
    ///
    /// - Panics if `create_info.usage` is empty.
    pub fn recreate(
        self: &Arc<Self>,
        create_info: SwapchainCreateInfo,
    ) -> Result<(Arc<Swapchain>, Vec<Arc<Image>>), Validated<VulkanError>> {
        Self::validate_new_inner(&self.device, &self.surface, &create_info)?;

        {
            let mut is_retired = self.is_retired.lock();

            // The swapchain has already been used to create a new one.
            if *is_retired {
                return Err(Box::new(ValidationError {
                    context: "self".into(),
                    problem: "has already been used to recreate a swapchain".into(),
                    vuids: &["VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933"],
                    ..Default::default()
                })
                .into());
            } else {
                // According to the documentation of VkSwapchainCreateInfoKHR:
                //
                // > Upon calling vkCreateSwapchainKHR with a oldSwapchain that is not VK_NULL_HANDLE,
                // > any images not acquired by the application may be freed by the implementation,
                // > which may occur even if creation of the new swapchain fails.
                //
                // Therefore, we set retired to true and keep it to true even if the call to `vkCreateSwapchainKHR` below fails.
                *is_retired = true;
            }
        }

        unsafe { Ok(self.recreate_unchecked(create_info)?) }
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn recreate_unchecked(
        self: &Arc<Self>,
        create_info: SwapchainCreateInfo,
    ) -> Result<(Arc<Swapchain>, Vec<Arc<Image>>), VulkanError> {
        // According to the documentation of VkSwapchainCreateInfoKHR:
        //
        // > Upon calling vkCreateSwapchainKHR with a oldSwapchain that is not VK_NULL_HANDLE,
        // > any images not acquired by the application may be freed by the implementation,
        // > which may occur even if creation of the new swapchain fails.
        //
        // Therefore, we set retired to true and keep it to true,
        // even if the call to `vkCreateSwapchainKHR` below fails.
        *self.is_retired.lock() = true;

        let (handle, image_handles) = unsafe {
            Self::new_inner_unchecked(&self.device, &self.surface, &create_info, Some(self))?
        };

        let (mut swapchain, swapchain_images) = Self::from_handle(
            self.device.clone(),
            handle,
            image_handles,
            self.surface.clone(),
            create_info,
        )?;

        if self.full_screen_exclusive == FullScreenExclusive::ApplicationControlled {
            Arc::get_mut(&mut swapchain)
                .unwrap()
                .full_screen_exclusive_held =
                AtomicBool::new(self.full_screen_exclusive_held.load(Ordering::Relaxed))
        };

        Ok((swapchain, swapchain_images))
    }

    fn validate_new_inner(
        device: &Device,
        surface: &Surface,
        create_info: &SwapchainCreateInfo,
    ) -> Result<(), Box<ValidationError>> {
        if !device.enabled_extensions().khr_swapchain {
            return Err(Box::new(ValidationError {
                requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                    "khr_swapchain",
                )])]),
                ..Default::default()
            }));
        }

        create_info
            .validate(device)
            .map_err(|err| err.add_context("create_info"))?;

        let &SwapchainCreateInfo {
            flags: _,
            min_image_count,
            image_format,
            image_view_formats: _,
            image_color_space,
            image_extent,
            image_array_layers,
            image_usage,
            image_sharing: _,
            pre_transform,
            composite_alpha,
            present_mode,
            ref present_modes,
            clipped: _,
            scaling_behavior,
            present_gravity,
            full_screen_exclusive,
            win32_monitor,
            _ne: _,
        } = create_info;

        assert_eq!(device.instance(), surface.instance());

        // VUID-VkSwapchainCreateInfoKHR-surface-01270
        if !device
            .active_queue_family_indices()
            .iter()
            .any(|&index| unsafe {
                device
                    .physical_device()
                    .surface_support_unchecked(index, surface)
                    .unwrap_or_default()
            })
        {
            return Err(Box::new(ValidationError {
                context: "surface".into(),
                problem: "is not supported by the physical device".into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-surface-01270"],
                ..Default::default()
            }));
        }

        let surface_capabilities = unsafe {
            device
                .physical_device()
                .surface_capabilities_unchecked(
                    surface,
                    SurfaceInfo {
                        present_mode: (device.enabled_extensions().ext_swapchain_maintenance1)
                            .then_some(present_mode),
                        full_screen_exclusive,
                        win32_monitor,
                        ..Default::default()
                    },
                )
                .map_err(|_err| {
                    Box::new(ValidationError {
                        problem: "`PhysicalDevice::surface_capabilities` \
                            returned an error"
                            .into(),
                        ..Default::default()
                    })
                })?
        };
        let surface_formats = unsafe {
            device
                .physical_device()
                .surface_formats_unchecked(
                    surface,
                    SurfaceInfo {
                        present_mode: (device.enabled_extensions().ext_swapchain_maintenance1)
                            .then_some(present_mode),
                        full_screen_exclusive,
                        win32_monitor,
                        ..Default::default()
                    },
                )
                .map_err(|_err| {
                    Box::new(ValidationError {
                        problem: "`PhysicalDevice::surface_formats` \
                            returned an error"
                            .into(),
                        ..Default::default()
                    })
                })?
        };
        let surface_present_modes: SmallVec<[_; PresentMode::COUNT]> = unsafe {
            device
                .physical_device()
                .surface_present_modes_unchecked(
                    surface,
                    SurfaceInfo {
                        full_screen_exclusive,
                        win32_monitor,
                        ..Default::default()
                    },
                )
                .map_err(|_err| {
                    Box::new(ValidationError {
                        problem: "`PhysicalDevice::surface_present_modes` \
                            returned an error"
                            .into(),
                        ..Default::default()
                    })
                })?
                .collect()
        };

        if surface_capabilities
            .max_image_count
            .map_or(false, |c| min_image_count > c)
        {
            return Err(Box::new(ValidationError {
                problem: "`create_info.min_image_count` is greater than the `max_image_count` \
                    value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-minImageCount-01272"],
                ..Default::default()
            }));
        }

        if min_image_count < surface_capabilities.min_image_count {
            return Err(Box::new(ValidationError {
                problem: "`create_info.min_image_count` is less than the `min_image_count` \
                    value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-presentMode-02839"],
                ..Default::default()
            }));
        }

        if !surface_formats
            .iter()
            .any(|&fc| fc == (image_format, image_color_space))
        {
            return Err(Box::new(ValidationError {
                problem: "the combination of `create_info.image_format` and \
                    `create_info.image_color_space` is not supported for `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageFormat-01273"],
                ..Default::default()
            }));
        }

        if image_array_layers > surface_capabilities.max_image_array_layers {
            return Err(Box::new(ValidationError {
                problem: "`create_info.image_array_layers` is greater than the \
                    `max_image_array_layers` value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275"],
                ..Default::default()
            }));
        }

        if matches!(
            present_mode,
            PresentMode::Immediate
                | PresentMode::Mailbox
                | PresentMode::Fifo
                | PresentMode::FifoRelaxed
        ) && !surface_capabilities
            .supported_usage_flags
            .contains(image_usage)
        {
            return Err(Box::new(ValidationError {
                problem: "`create_info.present_mode` is `PresentMode::Immediate`, \
                    `PresentMode::Mailbox`, `PresentMode::Fifo` or `PresentMode::FifoRelaxed`, \
                    and `create_info.image_usage` contains flags that are not set in \
                    the `supported_usage_flags` value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-presentMode-01427"],
                ..Default::default()
            }));
        }

        if !surface_capabilities
            .supported_transforms
            .contains_enum(pre_transform)
        {
            return Err(Box::new(ValidationError {
                problem: "`create_info.pre_transform` is not present in the \
                    `supported_transforms` value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-preTransform-01279"],
                ..Default::default()
            }));
        }

        if !surface_capabilities
            .supported_composite_alpha
            .contains_enum(composite_alpha)
        {
            return Err(Box::new(ValidationError {
                problem: "`create_info.composite_alpha` is not present in the \
                    `supported_composite_alpha` value of the capabilities of `surface`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280"],
                ..Default::default()
            }));
        }

        if !surface_present_modes.contains(&present_mode) {
            return Err(Box::new(ValidationError {
                problem: "`create_info.present_mode` is not supported for `surface`".into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-presentMode-01281"],
                ..Default::default()
            }));
        }

        if present_modes.is_empty() {
            if let Some(scaling_behavior) = scaling_behavior {
                if !surface_capabilities
                    .supported_present_scaling
                    .contains_enum(scaling_behavior)
                {
                    return Err(Box::new(ValidationError {
                        problem: "`create_info.scaling_behavior` is not present in the \
                            `supported_present_scaling` value of the \
                            capabilities of `surface`"
                            .into(),
                        vuids: &[
                            "VUID-VkSwapchainPresentScalingCreateInfoEXT-scalingBehavior-07770",
                        ],
                        ..Default::default()
                    }));
                }
            }

            if let Some(present_gravity) = present_gravity {
                for (axis_index, (present_gravity, supported_present_gravity)) in present_gravity
                    .into_iter()
                    .zip(surface_capabilities.supported_present_gravity)
                    .enumerate()
                {
                    if !supported_present_gravity.contains_enum(present_gravity) {
                        return Err(Box::new(ValidationError {
                            problem: format!(
                                "`create_info.present_gravity[{0}]` is not present in the \
                                `supported_present_gravity[{0}]` value of the \
                                capabilities of `surface`",
                                axis_index,
                            )
                            .into(),
                            vuids: &[
                                "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-07772",
                                "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityY-07774",
                            ],
                            ..Default::default()
                        }));
                    }
                }
            }
        } else {
            for (index, &present_mode) in present_modes.iter().enumerate() {
                if !surface_present_modes.contains(&present_mode) {
                    return Err(Box::new(ValidationError {
                        problem: format!(
                            "`create_info.present_modes[{}]` is not supported for `surface`",
                            index,
                        )
                        .into(),
                        vuids: &["VUID-VkSwapchainPresentModesCreateInfoEXT-None-07762"],
                        ..Default::default()
                    }));
                }

                if !surface_capabilities
                    .compatible_present_modes
                    .contains(&present_mode)
                {
                    return Err(Box::new(ValidationError {
                        problem: format!(
                            "`create_info.present_modes[{}]` is not present in the \
                            `compatible_present_modes` value of the \
                            capabilities of `surface`",
                            index,
                        )
                        .into(),
                        vuids: &["VUID-VkSwapchainPresentModesCreateInfoEXT-pPresentModes-07763"],
                        ..Default::default()
                    }));
                }

                if scaling_behavior.is_some() || present_gravity.is_some() {
                    let surface_capabilities = unsafe {
                        device
                            .physical_device()
                            .surface_capabilities_unchecked(
                                surface,
                                SurfaceInfo {
                                    present_mode: Some(present_mode),
                                    full_screen_exclusive,
                                    win32_monitor,
                                    ..Default::default()
                                },
                            )
                            .map_err(|_err| {
                                Box::new(ValidationError {
                                    problem: "`PhysicalDevice::surface_capabilities` \
                                        returned an error"
                                        .into(),
                                    ..Default::default()
                                })
                            })?
                    };

                    if let Some(scaling_behavior) = scaling_behavior {
                        if !surface_capabilities
                            .supported_present_scaling
                            .contains_enum(scaling_behavior)
                        {
                            return Err(Box::new(ValidationError {
                                problem: format!(
                                    "`create_info.scaling_behavior` is not present in the \
                                    `supported_present_scaling` value of the \
                                    capabilities of `surface` for \
                                    `create_info.present_modes[{}]`",
                                    index,
                                )
                                .into(),
                                vuids: &[
                                    "VUID-VkSwapchainPresentScalingCreateInfoEXT-scalingBehavior-07771",
                                ],
                                ..Default::default()
                            }));
                        }
                    }

                    if let Some(present_gravity) = present_gravity {
                        for (axis_index, (present_gravity, supported_present_gravity)) in
                            present_gravity
                                .into_iter()
                                .zip(surface_capabilities.supported_present_gravity)
                                .enumerate()
                        {
                            if !supported_present_gravity.contains_enum(present_gravity) {
                                return Err(Box::new(ValidationError {
                                    problem: format!(
                                        "`create_info.present_gravity[{0}]` is not present in the \
                                        `supported_present_gravity[{0}]` value of the \
                                        capabilities of `surface` for \
                                        `create_info.present_modes[{1}]`",
                                        axis_index, index,
                                    )
                                    .into(),
                                    vuids: &[
                                        "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-07773",
                                        "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityY-07775",
                                    ],
                                    ..Default::default()
                                }));
                            }
                        }
                    }
                }
            }
        }

        if scaling_behavior.is_some() {
            if let Some(min_scaled_image_extent) = surface_capabilities.min_scaled_image_extent {
                if image_extent[0] < min_scaled_image_extent[0]
                    || image_extent[1] < min_scaled_image_extent[1]
                {
                    return Err(Box::new(ValidationError {
                        problem: "`scaling_behavior` is `Some`, and an element of \
                            `create_info.image_extent` is less than the corresponding element \
                            of the `min_scaled_image_extent` value of the \
                            capabilities of `surface`"
                            .into(),
                        vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-07782"],
                        ..Default::default()
                    }));
                }
            }

            if let Some(max_scaled_image_extent) = surface_capabilities.max_scaled_image_extent {
                if image_extent[0] > max_scaled_image_extent[0]
                    || image_extent[1] > max_scaled_image_extent[1]
                {
                    return Err(Box::new(ValidationError {
                        problem: "`scaling_behavior` is `Some`, and an element of \
                            `create_info.image_extent` is greater than the corresponding element \
                            of the `max_scaled_image_extent` value of the \
                            capabilities of `surface`"
                            .into(),
                        vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-07782"],
                        ..Default::default()
                    }));
                }
            }
        } else {
            /*
            This check is in the spec, but in practice leads to race conditions.
            The window can be resized between calling `surface_capabilities` to get the
            min/max extent, and then creating the swapchain.

            See this discussion:
            https://github.com/KhronosGroup/Vulkan-Docs/issues/1144

            if image_extent[0] < surface_capabilities.min_image_extent[0]
                || image_extent[1] < surface_capabilities.min_image_extent[1]
            {
                return Err(Box::new(ValidationError {
                    problem: "`scaling_behavior` is `Some`, and an element of \
                        `create_info.image_extent` is less than the corresponding element \
                        of the `min_image_extent` value of the \
                        capabilities of `surface`"
                        .into(),
                    vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-07781"],
                    ..Default::default()
                }));
            }

            if image_extent[0] > surface_capabilities.max_image_extent[0]
                || image_extent[1] > surface_capabilities.max_image_extent[1]
            {
                return Err(Box::new(ValidationError {
                    problem: "`scaling_behavior` is `Some`, and an element of \
                        `create_info.image_extent` is greater than the corresponding element \
                        of the `max_image_extent` value of the \
                        capabilities of `surface`"
                        .into(),
                    vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-07781"],
                    ..Default::default()
                }));
            }
            */
        }

        if surface.api() == SurfaceApi::Win32
            && full_screen_exclusive == FullScreenExclusive::ApplicationControlled
        {
            if win32_monitor.is_none() {
                return Err(Box::new(ValidationError {
                    problem: "`surface` is a Win32 surface, and \
                        `create_info.full_screen_exclusive` is \
                        `FullScreenExclusive::ApplicationControlled`, but \
                        `create_info.win32_monitor` is `None`"
                        .into(),
                    vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-02679"],
                    ..Default::default()
                }));
            }
        } else {
            if win32_monitor.is_some() {
                return Err(Box::new(ValidationError {
                    problem: "`surface` is not a Win32 surface, or \
                        `create_info.full_screen_exclusive` is not \
                        `FullScreenExclusive::ApplicationControlled`, but \
                        `create_info.win32_monitor` is `Some`"
                        .into(),
                    ..Default::default()
                }));
            }
        }

        Ok(())
    }

    unsafe fn new_inner_unchecked(
        device: &Device,
        surface: &Surface,
        create_info: &SwapchainCreateInfo,
        old_swapchain: Option<&Swapchain>,
    ) -> Result<(ash::vk::SwapchainKHR, Vec<ash::vk::Image>), VulkanError> {
        let &SwapchainCreateInfo {
            flags,
            min_image_count,
            image_format,
            ref image_view_formats,
            image_color_space,
            image_extent,
            image_array_layers,
            image_usage,
            ref image_sharing,
            pre_transform,
            composite_alpha,
            present_mode,
            ref present_modes,
            clipped,
            scaling_behavior,
            present_gravity,
            full_screen_exclusive,
            win32_monitor,
            _ne: _,
        } = create_info;

        let (image_sharing_mode_vk, queue_family_index_count_vk, p_queue_family_indices_vk) =
            match image_sharing {
                Sharing::Exclusive => (ash::vk::SharingMode::EXCLUSIVE, 0, ptr::null()),
                Sharing::Concurrent(ref ids) => (
                    ash::vk::SharingMode::CONCURRENT,
                    ids.len() as u32,
                    ids.as_ptr(),
                ),
            };

        let mut create_info_vk = ash::vk::SwapchainCreateInfoKHR {
            flags: flags.into(),
            surface: surface.handle(),
            min_image_count,
            image_format: image_format.into(),
            image_color_space: image_color_space.into(),
            image_extent: ash::vk::Extent2D {
                width: image_extent[0],
                height: image_extent[1],
            },
            image_array_layers,
            image_usage: image_usage.into(),
            image_sharing_mode: image_sharing_mode_vk,
            queue_family_index_count: queue_family_index_count_vk,
            p_queue_family_indices: p_queue_family_indices_vk,
            pre_transform: pre_transform.into(),
            composite_alpha: composite_alpha.into(),
            present_mode: present_mode.into(),
            clipped: clipped as ash::vk::Bool32,
            old_swapchain: old_swapchain.map_or(ash::vk::SwapchainKHR::null(), |os| os.handle),
            ..Default::default()
        };
        let mut format_list_info_vk = None;
        let format_list_view_formats_vk: Vec<_>;
        let mut full_screen_exclusive_info_vk = None;
        let mut full_screen_exclusive_win32_info_vk = None;
        let mut present_modes_info_vk = None;
        let present_modes_vk: SmallVec<[ash::vk::PresentModeKHR; PresentMode::COUNT]>;
        let mut present_scaling_info_vk = None;

        if !image_view_formats.is_empty() {
            format_list_view_formats_vk = image_view_formats
                .iter()
                .copied()
                .map(ash::vk::Format::from)
                .collect();

            let next = format_list_info_vk.insert(ash::vk::ImageFormatListCreateInfo {
                view_format_count: format_list_view_formats_vk.len() as u32,
                p_view_formats: format_list_view_formats_vk.as_ptr(),
                ..Default::default()
            });

            next.p_next = create_info_vk.p_next;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        if full_screen_exclusive != FullScreenExclusive::Default {
            let next =
                full_screen_exclusive_info_vk.insert(ash::vk::SurfaceFullScreenExclusiveInfoEXT {
                    full_screen_exclusive: full_screen_exclusive.into(),
                    ..Default::default()
                });

            next.p_next = create_info_vk.p_next as *mut _;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        if let Some(Win32Monitor(hmonitor)) = win32_monitor {
            let next = full_screen_exclusive_win32_info_vk.insert(
                ash::vk::SurfaceFullScreenExclusiveWin32InfoEXT {
                    hmonitor,
                    ..Default::default()
                },
            );

            next.p_next = create_info_vk.p_next as *mut _;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        if !present_modes.is_empty() {
            present_modes_vk = present_modes.iter().copied().map(Into::into).collect();

            let next = present_modes_info_vk.insert(ash::vk::SwapchainPresentModesCreateInfoEXT {
                present_mode_count: present_modes_vk.len() as u32,
                p_present_modes: present_modes_vk.as_ptr(),
                ..Default::default()
            });

            next.p_next = create_info_vk.p_next as *mut _;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        if scaling_behavior.is_some() || present_gravity.is_some() {
            let [present_gravity_x, present_gravity_y] =
                present_gravity.map_or_else(Default::default, |pg| pg.map(Into::into));
            let next =
                present_scaling_info_vk.insert(ash::vk::SwapchainPresentScalingCreateInfoEXT {
                    scaling_behavior: scaling_behavior.map_or_else(Default::default, Into::into),
                    present_gravity_x,
                    present_gravity_y,
                    ..Default::default()
                });

            next.p_next = create_info_vk.p_next as *mut _;
            create_info_vk.p_next = next as *const _ as *const _;
        }

        let fns = device.fns();

        let handle = {
            let mut output = MaybeUninit::uninit();
            (fns.khr_swapchain.create_swapchain_khr)(
                device.handle(),
                &create_info_vk,
                ptr::null(),
                output.as_mut_ptr(),
            )
            .result()
            .map_err(VulkanError::from)?;
            output.assume_init()
        };

        let image_handles = loop {
            let mut count = 0;
            (fns.khr_swapchain.get_swapchain_images_khr)(
                device.handle(),
                handle,
                &mut count,
                ptr::null_mut(),
            )
            .result()
            .map_err(VulkanError::from)?;

            let mut images = Vec::with_capacity(count as usize);
            let result = (fns.khr_swapchain.get_swapchain_images_khr)(
                device.handle(),
                handle,
                &mut count,
                images.as_mut_ptr(),
            );

            match result {
                ash::vk::Result::SUCCESS => {
                    images.set_len(count as usize);
                    break images;
                }
                ash::vk::Result::INCOMPLETE => (),
                err => return Err(VulkanError::from(err)),
            }
        };

        Ok((handle, image_handles))
    }

    /// Creates a new `Swapchain` from a raw object handle.
    ///
    /// # Safety
    ///
    /// - `handle` and `image_handles` must be valid Vulkan object handles created from `device`.
    /// - `handle` must not be retired.
    /// - `image_handles` must be swapchain images owned by `handle`,
    ///   in the same order as they were returned by `vkGetSwapchainImagesKHR`.
    /// - `surface` and `create_info` must match the info used to create the object.
    pub unsafe fn from_handle(
        device: Arc<Device>,
        handle: ash::vk::SwapchainKHR,
        image_handles: impl IntoIterator<Item = ash::vk::Image>,
        surface: Arc<Surface>,
        create_info: SwapchainCreateInfo,
    ) -> Result<(Arc<Swapchain>, Vec<Arc<Image>>), VulkanError> {
        let SwapchainCreateInfo {
            flags,
            min_image_count,
            image_format,
            image_view_formats,
            image_color_space,
            image_extent,
            image_array_layers,
            image_usage,
            image_sharing,
            pre_transform,
            composite_alpha,
            present_mode,
            present_modes,
            clipped,
            scaling_behavior,
            present_gravity,
            full_screen_exclusive,
            win32_monitor,
            _ne: _,
        } = create_info;

        let swapchain = Arc::new(Swapchain {
            handle,
            device: InstanceOwnedDebugWrapper(device),
            surface: InstanceOwnedDebugWrapper(surface),
            id: Self::next_id(),

            flags,
            min_image_count,
            image_format,
            image_view_formats,
            image_color_space,
            image_extent,
            image_array_layers,
            image_usage,
            image_sharing,
            pre_transform,
            composite_alpha,
            present_mode,
            present_modes,
            clipped,
            scaling_behavior,
            present_gravity,
            full_screen_exclusive,
            win32_monitor,

            prev_present_id: Default::default(),
            full_screen_exclusive_held: AtomicBool::new(false),
            images: image_handles
                .into_iter()
                .map(|handle| ImageEntry {
                    handle,
                    layout_initialized: AtomicBool::new(false),
                })
                .collect(),
            is_retired: Mutex::new(false),
        });

        let swapchain_images = swapchain
            .images
            .iter()
            .enumerate()
            .map(|(image_index, entry)| unsafe {
                Ok(Arc::new(Image::from_swapchain(
                    entry.handle,
                    swapchain.clone(),
                    image_index as u32,
                )?))
            })
            .collect::<Result<_, VulkanError>>()?;

        Ok((swapchain, swapchain_images))
    }

    /// Returns the creation parameters of the swapchain.
    #[inline]
    pub fn create_info(&self) -> SwapchainCreateInfo {
        SwapchainCreateInfo {
            flags: self.flags,
            min_image_count: self.min_image_count,
            image_format: self.image_format,
            image_view_formats: self.image_view_formats.clone(),
            image_color_space: self.image_color_space,
            image_extent: self.image_extent,
            image_array_layers: self.image_array_layers,
            image_usage: self.image_usage,
            image_sharing: self.image_sharing.clone(),
            pre_transform: self.pre_transform,
            composite_alpha: self.composite_alpha,
            present_mode: self.present_mode,
            present_modes: self.present_modes.clone(),
            clipped: self.clipped,
            scaling_behavior: self.scaling_behavior,
            present_gravity: self.present_gravity,
            full_screen_exclusive: self.full_screen_exclusive,
            win32_monitor: self.win32_monitor,
            _ne: crate::NonExhaustive(()),
        }
    }

    /// Returns the surface that the swapchain was created from.
    #[inline]
    pub fn surface(&self) -> &Arc<Surface> {
        &self.surface
    }

    /// Returns the flags that the swapchain was created with.
    #[inline]
    pub fn flags(&self) -> SwapchainCreateFlags {
        self.flags
    }

    /// If `image` is one of the images of this swapchain, returns its index within the swapchain.
    #[inline]
    pub fn index_of_image(&self, image: &Image) -> Option<u32> {
        self.images
            .iter()
            .position(|entry| entry.handle == image.handle())
            .map(|i| i as u32)
    }

    /// Returns the number of images of the swapchain.
    #[inline]
    pub fn image_count(&self) -> u32 {
        self.images.len() as u32
    }

    /// Returns the format of the images of the swapchain.
    #[inline]
    pub fn image_format(&self) -> Format {
        self.image_format
    }

    /// Returns the formats that an image view created from a swapchain image can have.
    #[inline]
    pub fn image_view_formats(&self) -> &[Format] {
        &self.image_view_formats
    }

    /// Returns the color space of the images of the swapchain.
    #[inline]
    pub fn image_color_space(&self) -> ColorSpace {
        self.image_color_space
    }

    /// Returns the extent of the images of the swapchain.
    #[inline]
    pub fn image_extent(&self) -> [u32; 2] {
        self.image_extent
    }

    /// Returns the number of array layers of the images of the swapchain.
    #[inline]
    pub fn image_array_layers(&self) -> u32 {
        self.image_array_layers
    }

    /// Returns the usage of the images of the swapchain.
    #[inline]
    pub fn image_usage(&self) -> ImageUsage {
        self.image_usage
    }

    /// Returns the sharing of the images of the swapchain.
    #[inline]
    pub fn image_sharing(&self) -> &Sharing<SmallVec<[u32; 4]>> {
        &self.image_sharing
    }

    #[inline]
    pub(crate) unsafe fn full_screen_exclusive_held(&self) -> &AtomicBool {
        &self.full_screen_exclusive_held
    }

    #[inline]
    pub(crate) unsafe fn try_claim_present_id(&self, present_id: NonZeroU64) -> bool {
        let present_id = u64::from(present_id);
        self.prev_present_id.fetch_max(present_id, Ordering::SeqCst) < present_id
    }

    /// Returns the pre-transform that was passed when creating the swapchain.
    #[inline]
    pub fn pre_transform(&self) -> SurfaceTransform {
        self.pre_transform
    }

    /// Returns the alpha mode that was passed when creating the swapchain.
    #[inline]
    pub fn composite_alpha(&self) -> CompositeAlpha {
        self.composite_alpha
    }

    /// Returns the present mode that was passed when creating the swapchain.
    #[inline]
    pub fn present_mode(&self) -> PresentMode {
        self.present_mode
    }

    /// Returns the alternative present modes that were passed when creating the swapchain.
    #[inline]
    pub fn present_modes(&self) -> &[PresentMode] {
        &self.present_modes
    }

    /// Returns the value of `clipped` that was passed when creating the swapchain.
    #[inline]
    pub fn clipped(&self) -> bool {
        self.clipped
    }

    /// Returns the scaling behavior that was passed when creating the swapchain.
    #[inline]
    pub fn scaling_behavior(&self) -> Option<PresentScaling> {
        self.scaling_behavior
    }

    /// Returns the scaling behavior that was passed when creating the swapchain.
    #[inline]
    pub fn present_gravity(&self) -> Option<[PresentGravity; 2]> {
        self.present_gravity
    }

    /// Returns the value of 'full_screen_exclusive` that was passed when creating the swapchain.
    #[inline]
    pub fn full_screen_exclusive(&self) -> FullScreenExclusive {
        self.full_screen_exclusive
    }

    /// Acquires full-screen exclusivity.
    ///
    /// The swapchain must have been created with [`FullScreenExclusive::ApplicationControlled`],
    /// and must not already hold full-screen exclusivity. Full-screen exclusivity is held until
    /// either the `release_full_screen_exclusive` is called, or if any of the the other `Swapchain`
    /// functions return `FullScreenExclusiveLost`.
    #[inline]
    pub fn acquire_full_screen_exclusive_mode(&self) -> Result<(), Validated<VulkanError>> {
        self.validate_acquire_full_screen_exclusive_mode()?;

        unsafe { Ok(self.acquire_full_screen_exclusive_mode_unchecked()?) }
    }

    fn validate_acquire_full_screen_exclusive_mode(&self) -> Result<(), Box<ValidationError>> {
        if *self.is_retired.lock() {
            return Err(Box::new(ValidationError {
                problem: "this swapchain is retired".into(),
                vuids: &["VUID-vkAcquireFullScreenExclusiveModeEXT-swapchain-02674"],
                ..Default::default()
            }));
        }

        if self.full_screen_exclusive != FullScreenExclusive::ApplicationControlled {
            return Err(Box::new(ValidationError {
                context: "self.full_screen_exclusive()".into(),
                problem: "is not `FullScreenExclusive::ApplicationControlled`".into(),
                vuids: &["VUID-vkAcquireFullScreenExclusiveModeEXT-swapchain-02675"],
                ..Default::default()
            }));
        }

        // This must be the last check in this function.
        if self
            .full_screen_exclusive_held
            .swap(true, Ordering::Acquire)
        {
            return Err(Box::new(ValidationError {
                problem: "this swapchain already holds full-screen exclusive access".into(),
                vuids: &["VUID-vkAcquireFullScreenExclusiveModeEXT-swapchain-02676"],
                ..Default::default()
            }));
        }

        Ok(())
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn acquire_full_screen_exclusive_mode_unchecked(&self) -> Result<(), VulkanError> {
        self.full_screen_exclusive_held
            .store(true, Ordering::Relaxed);

        let fns = self.device.fns();
        (fns.ext_full_screen_exclusive
            .acquire_full_screen_exclusive_mode_ext)(self.device.handle(), self.handle)
        .result()
        .map_err(VulkanError::from)?;

        Ok(())
    }

    /// Releases full-screen exclusivity.
    ///
    /// The swapchain must have been created with [`FullScreenExclusive::ApplicationControlled`],
    /// and must currently hold full-screen exclusivity.
    #[inline]
    pub fn release_full_screen_exclusive_mode(&self) -> Result<(), Validated<VulkanError>> {
        self.validate_release_full_screen_exclusive_mode()?;

        unsafe { Ok(self.release_full_screen_exclusive_mode_unchecked()?) }
    }

    fn validate_release_full_screen_exclusive_mode(&self) -> Result<(), Box<ValidationError>> {
        if *self.is_retired.lock() {
            return Err(Box::new(ValidationError {
                problem: "this swapchain is retired".into(),
                vuids: &["VUID-vkReleaseFullScreenExclusiveModeEXT-swapchain-02677"],
                ..Default::default()
            }));
        }

        if self.full_screen_exclusive != FullScreenExclusive::ApplicationControlled {
            return Err(Box::new(ValidationError {
                context: "self.full_screen_exclusive()".into(),
                problem: "is not `FullScreenExclusive::ApplicationControlled`".into(),
                vuids: &["VUID-vkReleaseFullScreenExclusiveModeEXT-swapchain-02678"],
                ..Default::default()
            }));
        }

        Ok(())
    }

    #[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
    pub unsafe fn release_full_screen_exclusive_mode_unchecked(&self) -> Result<(), VulkanError> {
        self.full_screen_exclusive_held
            .store(false, Ordering::Release);

        let fns = self.device.fns();
        (fns.ext_full_screen_exclusive
            .release_full_screen_exclusive_mode_ext)(self.device.handle(), self.handle)
        .result()
        .map_err(VulkanError::from)?;

        Ok(())
    }

    /// `FullScreenExclusive::AppControlled` is not the active full-screen exclusivity mode,
    /// then this function will always return false. If true is returned the swapchain
    /// is in `FullScreenExclusive::AppControlled` full-screen exclusivity mode and exclusivity
    /// is currently acquired.
    #[inline]
    pub fn is_full_screen_exclusive(&self) -> bool {
        if self.full_screen_exclusive != FullScreenExclusive::ApplicationControlled {
            false
        } else {
            self.full_screen_exclusive_held.load(Ordering::SeqCst)
        }
    }

    // This method is necessary to allow `SwapchainImage`s to signal when they have been
    // transitioned out of their initial `undefined` image layout.
    //
    // See the `ImageAccess::layout_initialized` method documentation for more details.
    pub(crate) fn image_layout_initialized(&self, image_index: u32) {
        let image_entry = self.images.get(image_index as usize);
        if let Some(image_entry) = image_entry {
            image_entry
                .layout_initialized
                .store(true, Ordering::Relaxed);
        }
    }

    pub(crate) fn is_image_layout_initialized(&self, image_index: u32) -> bool {
        let image_entry = self.images.get(image_index as usize);
        if let Some(image_entry) = image_entry {
            image_entry.layout_initialized.load(Ordering::Relaxed)
        } else {
            false
        }
    }
}

impl Drop for Swapchain {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            let fns = self.device.fns();
            (fns.khr_swapchain.destroy_swapchain_khr)(
                self.device.handle(),
                self.handle,
                ptr::null(),
            );
        }
    }
}

unsafe impl VulkanObject for Swapchain {
    type Handle = ash::vk::SwapchainKHR;

    #[inline]
    fn handle(&self) -> Self::Handle {
        self.handle
    }
}

unsafe impl DeviceOwned for Swapchain {
    #[inline]
    fn device(&self) -> &Arc<Device> {
        &self.device
    }
}

impl_id_counter!(Swapchain);

/// Parameters to create a new `Swapchain`.
///
/// Many of the values here must be supported by the physical device.
/// [`PhysicalDevice`](crate::device::physical::PhysicalDevice) has several
/// methods to query what is supported.
#[derive(Clone, Debug)]
pub struct SwapchainCreateInfo {
    /// Additional properties of the swapchain.
    ///
    /// The default value is empty.
    pub flags: SwapchainCreateFlags,

    /// The minimum number of images that will be created.
    ///
    /// The implementation is allowed to create more than this number, but never less.
    ///
    /// The default value is `2`.
    pub min_image_count: u32,

    /// The format of the created images.
    ///
    /// The default value is `Format::UNDEFINED`.
    pub image_format: Format,

    /// The formats that an image view can have when it is created from one of the swapchain images.
    ///
    /// If the list is not empty, and `flags` does not contain
    /// [`SwapchainCreateFlags::MUTABLE_FORMAT`], then the list must contain at most one element,
    /// otherwise any number of elements are allowed.
    /// The view formats must be compatible with `format`.
    ///
    /// If `flags` contains [`SwapchainCreateFlags::MUTABLE_FORMAT`], then the list must contain
    /// `image_format.
    ///
    /// If this is not empty, then the device API version must be at least 1.2, or the
    /// [`khr_image_format_list`] extension must be enabled on the device.
    ///
    /// The default value is empty.
    ///
    /// [`khr_image_format_list`]: crate::device::DeviceExtensions::khr_image_format_list
    pub image_view_formats: Vec<Format>,

    /// The color space of the created images.
    ///
    /// The default value is [`ColorSpace::SrgbNonLinear`].
    pub image_color_space: ColorSpace,

    /// The extent of the created images.
    ///
    /// Both values must be greater than zero. Note that on some platforms,
    /// [`SurfaceCapabilities::current_extent`] will be zero if the surface is minimized.
    /// Care must be taken to check for this, to avoid trying to create a zero-size swapchain.
    ///
    /// The default value is `[0, 0]`, which must be overridden.
    pub image_extent: [u32; 2],

    /// The number of array layers of the created images.
    ///
    /// The default value is `1`.
    pub image_array_layers: u32,

    /// How the created images will be used.
    ///
    /// The default value is [`ImageUsage::empty()`], which must be overridden.
    pub image_usage: ImageUsage,

    /// Whether the created images can be shared across multiple queues, or are limited to a single
    /// queue.
    ///
    /// The default value is [`Sharing::Exclusive`].
    pub image_sharing: Sharing<SmallVec<[u32; 4]>>,

    /// The transform that should be applied to an image before it is presented.
    ///
    /// The default value is [`SurfaceTransform::Identity`].
    pub pre_transform: SurfaceTransform,

    /// How alpha values of the pixels in the image are to be treated.
    ///
    /// The default value is [`CompositeAlpha::Opaque`].
    pub composite_alpha: CompositeAlpha,

    /// How the swapchain should behave when multiple images are waiting in the queue to be
    /// presented.
    ///
    /// The default value is [`PresentMode::Fifo`].
    pub present_mode: PresentMode,

    /// Alternative present modes that can be used with this swapchain. The mode specified in
    /// `present_mode` is the default mode, but can be changed for future present operations by
    /// specifying it when presenting.
    ///
    /// If this is not empty, then the
    /// [`ext_swapchain_maintenance1`](crate::device::DeviceExtensions::ext_swapchain_maintenance1)
    /// extension must be enabled on the device.
    /// It must always contain the mode specified in `present_mode`.
    ///
    /// The default value is empty.
    pub present_modes: SmallVec<[PresentMode; PresentMode::COUNT]>,

    /// Whether the implementation is allowed to discard rendering operations that affect regions of
    /// the surface which aren't visible. This is important to take into account if your fragment
    /// shader has side-effects or if you want to read back the content of the image afterwards.
    ///
    /// The default value is `true`.
    pub clipped: bool,

    /// The scaling method to use when the surface is not the same size as the swapchain image.
    ///
    /// `None` means the behavior is implementation defined.
    ///
    /// If this is `Some`, then the
    /// [`ext_swapchain_maintenance1`](crate::device::DeviceExtensions::ext_swapchain_maintenance1)
    /// extension must be enabled on the device.
    ///
    /// The default value is `None`.
    pub scaling_behavior: Option<PresentScaling>,

    /// The horizontal and vertical alignment to use when the swapchain image, after applying
    /// scaling, does not fill the whole surface.
    ///
    /// `None` means the behavior is implementation defined.
    ///
    /// If this is `Some`, then the
    /// [`ext_swapchain_maintenance1`](crate::device::DeviceExtensions::ext_swapchain_maintenance1)
    /// extension must be enabled on the device.
    ///
    /// The default value is `None`.
    pub present_gravity: Option<[PresentGravity; 2]>,

    /// How full-screen exclusivity is to be handled.
    ///
    /// If set to anything other than [`FullScreenExclusive::Default`], then the
    /// [`ext_full_screen_exclusive`](crate::device::DeviceExtensions::ext_full_screen_exclusive)
    /// extension must be enabled on the device.
    ///
    /// The default value is [`FullScreenExclusive::Default`].
    pub full_screen_exclusive: FullScreenExclusive,

    /// For Win32 surfaces, if `full_screen_exclusive` is
    /// [`FullScreenExclusive::ApplicationControlled`], this specifies the monitor on which
    /// full-screen exclusivity should be used.
    ///
    /// For this case, the value must be `Some`, and for all others it must be `None`.
    ///
    /// The default value is `None`.
    pub win32_monitor: Option<Win32Monitor>,

    pub _ne: crate::NonExhaustive,
}

impl Default for SwapchainCreateInfo {
    #[inline]
    fn default() -> Self {
        Self {
            flags: SwapchainCreateFlags::empty(),
            min_image_count: 2,
            image_format: Format::UNDEFINED,
            image_view_formats: Vec::new(),
            image_color_space: ColorSpace::SrgbNonLinear,
            image_extent: [0, 0],
            image_array_layers: 1,
            image_usage: ImageUsage::empty(),
            image_sharing: Sharing::Exclusive,
            pre_transform: SurfaceTransform::Identity,
            composite_alpha: CompositeAlpha::Opaque,
            present_mode: PresentMode::Fifo,
            present_modes: SmallVec::new(),
            clipped: true,
            scaling_behavior: None,
            present_gravity: None,
            full_screen_exclusive: FullScreenExclusive::Default,
            win32_monitor: None,
            _ne: crate::NonExhaustive(()),
        }
    }
}

impl SwapchainCreateInfo {
    pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
        let &Self {
            flags,
            min_image_count: _,
            image_format,
            ref image_view_formats,
            image_color_space,
            image_extent,
            image_array_layers,
            image_usage,
            ref image_sharing,
            pre_transform,
            composite_alpha,
            present_mode,
            ref present_modes,
            clipped: _,
            scaling_behavior,
            present_gravity,
            full_screen_exclusive,
            win32_monitor: _,
            _ne: _,
        } = self;

        flags.validate_device(device).map_err(|err| {
            err.add_context("flags")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-flags-parameter"])
        })?;

        image_format.validate_device(device).map_err(|err| {
            err.add_context("image_format")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-imageFormat-parameter"])
        })?;

        image_color_space.validate_device(device).map_err(|err| {
            err.add_context("image_color_space")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-imageColorSpace-parameter"])
        })?;

        image_usage.validate_device(device).map_err(|err| {
            err.add_context("image_usage")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-imageUsage-parameter"])
        })?;

        if image_usage.is_empty() {
            return Err(Box::new(ValidationError {
                context: "image_usage".into(),
                problem: "is empty".into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageUsage-requiredbitmask"],
                ..Default::default()
            }));
        }

        pre_transform.validate_device(device).map_err(|err| {
            err.add_context("pre_transform")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-preTransform-parameter"])
        })?;

        composite_alpha.validate_device(device).map_err(|err| {
            err.add_context("composite_alpha")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-compositeAlpha-parameter"])
        })?;

        present_mode.validate_device(device).map_err(|err| {
            err.add_context("present_mode")
                .set_vuids(&["VUID-VkSwapchainCreateInfoKHR-presentMode-parameter"])
        })?;

        if image_extent.contains(&0) {
            return Err(Box::new(ValidationError {
                context: "image_extent".into(),
                problem: "one or more elements are zero".into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageExtent-01689"],
                ..Default::default()
            }));
        }

        if image_array_layers == 0 {
            return Err(Box::new(ValidationError {
                context: "image_array_layers".into(),
                problem: "is zero".into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275"],
                ..Default::default()
            }));
        }

        match image_sharing {
            Sharing::Exclusive => (),
            Sharing::Concurrent(queue_family_indices) => {
                if queue_family_indices.len() < 2 {
                    return Err(Box::new(ValidationError {
                        context: "image_sharing".into(),
                        problem: "is `Sharing::Concurrent`, and contains less than 2 \
                            queue family indices"
                            .into(),
                        vuids: &["VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01278"],
                        ..Default::default()
                    }));
                }

                let queue_family_count =
                    device.physical_device().queue_family_properties().len() as u32;

                for (index, &queue_family_index) in queue_family_indices.iter().enumerate() {
                    if queue_family_indices[..index].contains(&queue_family_index) {
                        return Err(Box::new(ValidationError {
                            context: "queue_family_indices".into(),
                            problem: format!(
                                "the queue family index in the list at index {} is contained in \
                                the list more than once",
                                index,
                            )
                            .into(),
                            vuids: &["VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428"],
                            ..Default::default()
                        }));
                    }

                    if queue_family_index >= queue_family_count {
                        return Err(Box::new(ValidationError {
                            context: format!("queue_family_indices[{}]", index).into(),
                            problem: "is not less than the number of queue families in the \
                                physical device"
                                .into(),
                            vuids: &["VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428"],
                            ..Default::default()
                        }));
                    }
                }
            }
        };

        let image_format_properties = unsafe {
            device
                .physical_device()
                .image_format_properties_unchecked(ImageFormatInfo {
                    format: image_format,
                    image_type: ImageType::Dim2d,
                    tiling: ImageTiling::Optimal,
                    usage: image_usage,
                    ..Default::default()
                })
                .map_err(|_err| {
                    Box::new(ValidationError {
                        problem: "`PhysicalDevice::image_format_properties` \
                            returned an error"
                            .into(),
                        ..Default::default()
                    })
                })?
        };

        if image_format_properties.is_none() {
            return Err(Box::new(ValidationError {
                problem: "the combination of `image_format` and `image_usage` is not supported \
                    for images by the physical device"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-imageFormat-01778"],
                ..Default::default()
            }));
        }

        if flags.intersects(SwapchainCreateFlags::MUTABLE_FORMAT)
            && !image_view_formats.contains(&image_format)
        {
            return Err(Box::new(ValidationError {
                problem: "`flags` contains `SwapchainCreateFlags::MUTABLE_FORMAT`, but \
                    `image_view_formats` does not contain `image_format`"
                    .into(),
                vuids: &["VUID-VkSwapchainCreateInfoKHR-flags-03168"],
                ..Default::default()
            }));
        }

        if !image_view_formats.is_empty() {
            if !(device.api_version() >= Version::V1_2
                || device.enabled_extensions().khr_image_format_list)
            {
                return Err(Box::new(ValidationError {
                    context: "image_view_formats".into(),
                    problem: "is not empty".into(),
                    requires_one_of: RequiresOneOf(&[
                        RequiresAllOf(&[Requires::APIVersion(Version::V1_2)]),
                        RequiresAllOf(&[Requires::DeviceExtension("khr_image_format_list")]),
                    ]),
                    ..Default::default()
                }));
            }

            if !flags.intersects(SwapchainCreateFlags::MUTABLE_FORMAT)
                && image_view_formats.len() != 1
            {
                return Err(Box::new(ValidationError {
                    problem: "`flags` does not contain `SwapchainCreateFlags::MUTABLE_FORMAT`, \
                        but `image_view_formats` contains more than one element"
                        .into(),
                    vuids: &["VUID-VkSwapchainCreateInfoKHR-flags-04100"],
                    ..Default::default()
                }));
            }

            for (index, &image_view_format) in image_view_formats.iter().enumerate() {
                image_view_format.validate_device(device).map_err(|err| {
                    err.add_context(format!("image_view_formats[{}]", index))
                        .set_vuids(&["VUID-VkImageFormatListCreateInfo-pViewFormats-parameter"])
                })?;

                if image_view_format.compatibility() != image_format.compatibility() {
                    return Err(Box::new(ValidationError {
                        problem: format!(
                            "`image_view_formats[{}]` is not compatible with `image_format`",
                            index
                        )
                        .into(),
                        vuids: &["VUID-VkSwapchainCreateInfoKHR-pNext-04099"],
                        ..Default::default()
                    }));
                }
            }
        }

        if !present_modes.is_empty() {
            if !device.enabled_extensions().ext_swapchain_maintenance1 {
                return Err(Box::new(ValidationError {
                    context: "present_modes".into(),
                    problem: "is not empty".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_swapchain_maintenance1",
                    )])]),
                    ..Default::default()
                }));
            }

            for (index, &present_mode) in present_modes.iter().enumerate() {
                present_mode.validate_device(device).map_err(|err| {
                    err.add_context(format!("present_modes[{}]", index))
                        .set_vuids(&[
                            "VUID-VkSwapchainPresentModesCreateInfoEXT-pPresentModes-parameter",
                        ])
                })?;
            }

            if !present_modes.contains(&present_mode) {
                return Err(Box::new(ValidationError {
                    problem: "`present_modes` is not empty, but does not contain `present_mode`"
                        .into(),
                    vuids: &["VUID-VkSwapchainPresentModesCreateInfoEXT-presentMode-07764"],
                    ..Default::default()
                }));
            }
        }

        if let Some(scaling_behavior) = scaling_behavior {
            if !device.enabled_extensions().ext_swapchain_maintenance1 {
                return Err(Box::new(ValidationError {
                    context: "scaling_behavior".into(),
                    problem: "is `Some`".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_swapchain_maintenance1",
                    )])]),
                    ..Default::default()
                }));
            }

            scaling_behavior.validate_device(device).map_err(|err| {
                err.add_context("scaling_behavior").set_vuids(&[
                    "VUID-VkSwapchainPresentScalingCreateInfoEXT-scalingBehavior-parameter",
                ])
            })?;

            // VUID-VkSwapchainPresentScalingCreateInfoEXT-scalingBehavior-07767
            // Ensured by the use of an enum.
        }

        if let Some(present_gravity) = present_gravity {
            if !device.enabled_extensions().ext_swapchain_maintenance1 {
                return Err(Box::new(ValidationError {
                    context: "present_gravity".into(),
                    problem: "is `Some`".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_swapchain_maintenance1",
                    )])]),
                    ..Default::default()
                }));
            }

            for (axis_index, present_gravity) in present_gravity.into_iter().enumerate() {
                present_gravity.validate_device(device).map_err(|err| {
                    err.add_context(format!("present_gravity[{}]", axis_index))
                        .set_vuids(&[
                            "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-parameter",
                            "VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityY-parameter",
                        ])
                })?;
            }

            // VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-07765
            // VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-07766
            // Ensured by the use of an array of enums wrapped in `Option`.

            // VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityX-07768
            // VUID-VkSwapchainPresentScalingCreateInfoEXT-presentGravityY-07769
            // Ensured by the use of an enum.
        }

        if full_screen_exclusive != FullScreenExclusive::Default {
            if !device.enabled_extensions().ext_full_screen_exclusive {
                return Err(Box::new(ValidationError {
                    context: "full_screen_exclusive".into(),
                    problem: "is not `FullScreenExclusive::Default`".into(),
                    requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
                        "ext_full_screen_exclusive",
                    )])]),
                    ..Default::default()
                }));
            }

            full_screen_exclusive
                .validate_device(device)
                .map_err(|err| {
                    err.add_context("full_screen_exclusive").set_vuids(&[
                        "VUID-VkSurfaceFullScreenExclusiveInfoEXT-fullScreenExclusive-parameter",
                    ])
                })?;
        }

        Ok(())
    }
}

vulkan_bitflags! {
    #[non_exhaustive]

    /// Flags specifying additional properties of a swapchain.
    SwapchainCreateFlags = SwapchainCreateFlagsKHR(u32);

    /* TODO: enable
    /// Creates swapchain images with the [`ImageCreateFlags::SPLIT_INSTANCE_BIND_REGIONS`] flag.
    SPLIT_INSTANCE_BIND_REGIONS = SPLIT_INSTANCE_BIND_REGIONS
    RequiresOneOf([
        RequiresAllOf([APIVersion(V1_1)]),
        RequiresAllOf([DeviceExtension(khr_device_group)]),
    ]),*/

    /* TODO: enable
    /// Creates swapchain images with the [`ImageCreateFlags::PROTECTED`] flag.
    PROTECTED = PROTECTED
    RequiresOneOf([
        RequiresAllOf([APIVersion(V1_1)]),
    ]),*/

    /// Creates swapchain images with both the [`ImageCreateFlags::MUTABLE_FORMAT`] and
    /// [`ImageCreateFlags::EXTENDED_USAGE`] flags.
    MUTABLE_FORMAT = MUTABLE_FORMAT
    RequiresOneOf([
        RequiresAllOf([DeviceExtension(khr_swapchain_mutable_format)]),
    ]),

    /* TODO: enable
    // TODO: document
    DEFERRED_MEMORY_ALLOCATION = DEFERRED_MEMORY_ALLOCATION_EXT {
        device_extensions: [ext_swapchain_maintenance1],
    },*/
}

impl From<SwapchainCreateFlags> for ImageCreateFlags {
    #[inline]
    fn from(flags: SwapchainCreateFlags) -> Self {
        // Per https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateSwapchainKHR.html#_description
        let mut result = ImageCreateFlags::empty();

        /* TODO: enable
        if flags.intersects(SwapchainCreateFlags::SPLIT_INSTANCE_BIND_REGIONS) {
            result |= ImageCreateFlags::SPLIT_INSTANCE_BIND_REGIONS;
        } */

        /* TODO: enable
        if flags.intersects(SwapchainCreateFlags::PROTECTED) {
            result |= ImageCreateFlags::PROTECTED;
        } */

        if flags.intersects(SwapchainCreateFlags::MUTABLE_FORMAT) {
            result |= ImageCreateFlags::MUTABLE_FORMAT | ImageCreateFlags::EXTENDED_USAGE;
        }

        result
    }
}

vulkan_bitflags_enum! {
    #[non_exhaustive]

    /// A set of [`PresentScaling`] values.
    PresentScalingFlags,

    /// The way a swapchain image is scaled, if it does not exactly fit the surface.
    PresentScaling,

    = PresentScalingFlagsEXT(u32);

    /// No scaling is performed; one swapchain image pixel maps to one surface pixel.
    ONE_TO_ONE, OneToOne = ONE_TO_ONE,

    /// Both axes of the image are scaled equally, without changing the aspect ratio of the image,
    /// to the largest size in which both axes fit inside the surface.
    ASPECT_RATIO_STRETCH, AspectRatioStretch = ASPECT_RATIO_STRETCH,

    /// Each axis of the image is scaled independently to fit the surface,
    /// which may change the aspect ratio of the image.
    STRETCH, Stretch = STRETCH,
}

vulkan_bitflags_enum! {
    #[non_exhaustive]

    /// A set of [`PresentGravity`] values.
    PresentGravityFlags,

    /// The way a swapchain image is aligned, if it does not exactly fit the surface.
    PresentGravity,

    = PresentGravityFlagsEXT(u32);

    /// Aligned to the top or left side of the surface.
    MIN, Min = MIN,

    /// Aligned to the bottom or right side of the surface.
    MAX, Max = MAX,

    /// Aligned to the middle of the surface.
    CENTERED, Centered = CENTERED,
}

vulkan_enum! {
    #[non_exhaustive]

    /// The way full-screen exclusivity is handled.
    FullScreenExclusive = FullScreenExclusiveEXT(i32);

    /// Indicates that the driver should determine the appropriate full-screen method
    /// by whatever means it deems appropriate.
    Default = DEFAULT,

    /// Indicates that the driver may use full-screen exclusive mechanisms when available.
    /// Such mechanisms may result in better performance and/or the availability of
    /// different presentation capabilities, but may require a more disruptive transition
    // during swapchain initialization, first presentation and/or destruction.
    Allowed = ALLOWED,

    /// Indicates that the driver should avoid using full-screen mechanisms which rely
    /// on disruptive transitions.
    Disallowed = DISALLOWED,

    /// Indicates the application will manage full-screen exclusive mode by using the
    /// [`Swapchain::acquire_full_screen_exclusive_mode`] and
    /// [`Swapchain::release_full_screen_exclusive_mode`] functions.
    ApplicationControlled = APPLICATION_CONTROLLED,
}

/// A wrapper around a Win32 monitor handle.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Win32Monitor(pub(crate) ash::vk::HMONITOR);

impl Win32Monitor {
    /// Wraps a Win32 monitor handle.
    ///
    /// # Safety
    ///
    /// - `hmonitor` must be a valid handle as returned by the Win32 API.
    pub unsafe fn new<T>(hmonitor: *const T) -> Self {
        Self(hmonitor as _)
    }
}

// Winit's `MonitorHandle` is Send on Win32, so this seems safe.
unsafe impl Send for Win32Monitor {}
unsafe impl Sync for Win32Monitor {}