La spécification de Vulkan est disponible !
Le successeur d'OpenGL est disponible avec des outils et des exemples open source

Le , par LittleWhite, Responsable 2D/3D/Jeux
Cela fait plus d'une année que nous en parlions. Vulkan est enfin là. Vulkan est le successeur d'OpenGL, la spécification ouverte d'une bibliothèque pour les applications utilisant les ressources des cartes graphiques. Son but : repartir de zéro afin de se débarrasser de l'héritage d'OpenGL (créé il y a plus de 20 ans !). Ainsi, Vulkan propose une nouvelle bibliothèque :
  • plus légère ;
  • compatible avec les applications multithread ;
  • assure un comportement homogène des shaders et leur précompilation.



Le but est d'alléger l'utilisation du CPU et de permettre une meilleure utilisation du GPU. En effet, le CPU est souvent l'élément ralentissant le rendu, notamment car celui-ci ne peut pas communiquer avec le GPU en utilisant plusieurs fils. La raison est que le pilote n'expose pas assez d'éléments de la carte graphique, du coup, le pilote fait tout son possible pour assurer la cohérence des objets exposés. La méthode la plus simple est d'éviter que plusieurs fils interagissent avec les objets. Mais du coup, les CPU multicœurs sont sous-utilisés. La réponse qu'apporte Vulkan est d'exposer l'intégralité de la carte graphique et de permettre de les utiliser en parallèle. C'est au développeur de prendre ses précautions.
Une fois que tout se combine, il est possible d'accélérer le rendu.

Dès 2015, Developpez.com vous a proposé une introduction de la nouvelle spécification que vous pouvez consulter à tout moment.

Au jour de la sortie de la spécification, les constructeurs proposent dès à présent le support de Vulkan. Pour NVIDIA, les cartes
  • Quadro Series: Quadro M6000, Quadro M5000, Quadro M4000, Quadro K6000, Quadro K5200, Quadro K5000, Quadro K4000, Quadro K4200, Quadro K2200, Quadro K2000, Quadro K2000D, Quadro K1200, Quadro K620, Quadro K420 ;
  • Quadro Series (Notebooks): Quadro K5100M, Quadro K5000M, Quadro K4100M, Quadro K4000M, Quadro K3100M, Quadro K2200M, Quadro K2100M, Quadro K3000M, Quadro K2000M, Quadro K1100M, Quadro K1000M, Quadro K620M, Quadro K610M, Quadro K510M, Quadro K500M ;
  • GeForce 900 Series: GeForce GTX TITAN X, GeForce GTX 980 Ti, GeForce GTX 980, GeForce GTX 970, GeForce GTX 960, GeForce GTX 950 ;
  • GeForce 700 Series: GeForce GTX TITAN Z, GeForce GTX TITAN Black, GeForce GTX TITAN, GeForce GTX 780 Ti, GeForce GTX 780, GeForce GTX 770, GeForce GTX 760, GeForce GTX 760 Ti (OEM), GeForce GTX 750 Ti, GeForce GTX 750, GeForce GTX 745, GeForce GT 740, GeForce GT 730, GeForce GT 720, GeForce GT 710, GeForce GT 705 ;
  • GeForce 600 Series: GeForce GTX 690, GeForce GTX 680, GeForce GTX 670, GeForce GTX 660 Ti, GeForce GTX 660, GeForce GTX 650 Ti BOOST, GeForce GTX 650 Ti, GeForce GTX 650, GeForce GTX 645, GeForce GT 645, GeForce GT 640, GeForce GT 630
sont supportées.
Pour AMD :
  • AMD Radeon™ R9 Series graphics ;
  • AMD Radeon™ R7 Series graphics ;
  • AMD Radeon™ R5 240 graphics ;
  • AMD Radeon™ HD 8000 Series graphics pour les systèmes OEM (HD 8570 et supérieur) ;
  • AMD Radeon™ HD 8000M Series graphics pour notebooks ;
  • AMD Radeon™ HD 7000 Series graphics (HD 7730 et supérieur) ;
  • AMD Radeon™ HD 7000M Series graphics pour notebooks (HD 7730M et supérieur) ;
  • AMD A4/A6/A8/A10-7000 Series APUs (nom de code “Kaveri”) ;
  • AMD A6/A8/A10 PRO-7000 Series APUs (nom de code “Kaveri”) ;
  • AMD A6/A8/A10/FX™ 8000 Series APUs (nom de code “Carrizo”) ;
  • AMD E1/A4/A10 Micro-6000 Series APUs (nom de code “Mullins”) ;
  • AMD E1/E2/A4/A6/A8-6000 Series APUs (nom de code “Beema”) ;
  • AMD A4-1200, A4-1300 et A6-1400 Series APUs (nom de code “Temash”) ;
  • AMD E1-2000, E2-3000, A4-5000, A6-5000, et A4 Pro-3000 Series APUs (nom de code “Kabini”).

De même, Intel, Imagination Technologies, Qualcomm ont leur solution.

Mais ce n'est pas tout. Vous pouvez accéder à des exemples et des démonstrations :


En résumé, tout est prévu pour démarrer tout de suite. Vous pouvez consulter la spécification sur le site officiel, la documentation de toutes les fonctions, en ligne et un aide-mémoire.

Votre opinion

Aimez-vous la spécification ?
Pensez-vous que la bibliothèque est facile à utiliser ? Avez-vous déjà eu l'occasion de l'utiliser ?
Croyez-vous que Vulkan est au même niveau que Direct3D 12 ?

Ressources

Les ressources Developpez.com sur Vulkan
Connectez-vous au flux RSS de la rubrique 2D/3D/Jeux, de nouvelles ressources sont en préparation !

Source

Site officiel Khronos


Vous avez aimé cette actualité ? Alors partagez-la avec vos amis en cliquant sur les boutons ci-dessous :


 Poster une réponse Signaler un problème

Avatar de smartties smartties - Membre averti https://www.developpez.com
le 16/02/2016 à 19:23
J'ai testé les démos mais malheureusement ma carte graphique ne possède pas encore les drivers compatibles, donc impossible de lancer les démos .

Sinon voici 3000 lignes de code pour afficher un cube avec Vulkan :

Code : Sélectionner tout
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
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
 
#define _GNU_SOURCE 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdbool.h> 
#include <assert.h> 
#include <signal.h> 
 
 
#ifdef _WIN32 
#pragma comment(linker, "/subsystem:windows") 
#define APP_NAME_STR_LEN 80 
#endif // _WIN32 
 
 
#include <vulkan/vulkan.h> 
 
 
#include <vulkan/vk_sdk_platform.h> 
#include "linmath.h" 
 
 
#define DEMO_TEXTURE_COUNT 1 
#define APP_SHORT_NAME "cube" 
#define APP_LONG_NAME "The Vulkan Cube Demo Program" 
 
 
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) 
 
 
#if defined(NDEBUG) && defined(__GNUC__) 
#define U_ASSERT_ONLY __attribute__((unused)) 
#else 
#define U_ASSERT_ONLY 
#endif 
 
 
#ifdef _WIN32 
#define ERR_EXIT(err_msg, err_class)                                           \ 
    do {                                                                       \ 
        MessageBox(NULL, err_msg, err_class, MB_OK);                           \ 
        exit(1);                                                               \ 
    } while (0) 
 
 
#else // _WIN32 
 
 
#define ERR_EXIT(err_msg, err_class)                                           \ 
    do {                                                                       \ 
        printf(err_msg);                                                       \ 
        fflush(stdout);                                                        \ 
        exit(1);                                                               \ 
    } while (0) 
#endif // _WIN32 
 
 
#define GET_INSTANCE_PROC_ADDR(inst, entrypoint)                               \ 
    {                                                                          \ 
        demo->fp##entrypoint =                                                 \ 
            (PFN_vk##entrypoint)vkGetInstanceProcAddr(inst, "vk" #entrypoint); \ 
        if (demo->fp##entrypoint == NULL) {                                    \ 
            ERR_EXIT("vkGetInstanceProcAddr failed to find vk" #entrypoint,    \ 
                     "vkGetInstanceProcAddr Failure");                         \ 
        }                                                                      \ 
    } 
 
 
static PFN_vkGetDeviceProcAddr g_gdpa = NULL; 
 
 
#define GET_DEVICE_PROC_ADDR(dev, entrypoint)                                  \ 
    {                                                                          \ 
        if (!g_gdpa)                                                           \ 
            g_gdpa = (PFN_vkGetDeviceProcAddr)vkGetInstanceProcAddr(           \ 
                demo->inst, "vkGetDeviceProcAddr");                            \ 
        demo->fp##entrypoint =                                                 \ 
            (PFN_vk##entrypoint)g_gdpa(dev, "vk" #entrypoint);                 \ 
        if (demo->fp##entrypoint == NULL) {                                    \ 
            ERR_EXIT("vkGetDeviceProcAddr failed to find vk" #entrypoint,      \ 
                     "vkGetDeviceProcAddr Failure");                           \ 
        }                                                                      \ 
    } 
 
struct texture_object { 
    VkSampler sampler; 
 
 
    VkImage image; 
    VkImageLayout imageLayout; 
 
 
    VkMemoryAllocateInfo mem_alloc; 
    VkDeviceMemory mem; 
    VkImageView view; 
    int32_t tex_width, tex_height; 
}; 
 
 
static char *tex_files[] = {"lunarg.ppm"}; 
 
 
struct vkcube_vs_uniform { 
    // Must start with MVP 
    float mvp[4][4]; 
    float position[12 * 3][4]; 
    float color[12 * 3][4]; 
}; 
 
 
struct vktexcube_vs_uniform { 
    // Must start with MVP 
    float mvp[4][4]; 
    float position[12 * 3][4]; 
    float attr[12 * 3][4]; 
}; 
 
 
struct Vertex 
{ 
    float     posX, posY, posZ, posW;    // Position data 
    float     r, g, b, a;                // Color 
}; 
 
 
struct VertexPosTex 
{ 
    float     posX, posY, posZ, posW;    // Position data 
    float     u, v, s, t;                // Texcoord 
}; 
 
 
#define XYZ1(_x_, _y_, _z_)         (_x_), (_y_), (_z_), 1.f 
#define UV(_u_, _v_)                (_u_), (_v_), 0.f, 1.f 
 
 
static const float g_vertex_buffer_data[] = { 
    -1.0f,-1.0f,-1.0f,  // -X side 
    -1.0f,-1.0f, 1.0f, 
    -1.0f, 1.0f, 1.0f, 
    -1.0f, 1.0f, 1.0f, 
    -1.0f, 1.0f,-1.0f, 
    -1.0f,-1.0f,-1.0f, 
 
 
    -1.0f,-1.0f,-1.0f,  // -Z side 
     1.0f, 1.0f,-1.0f, 
     1.0f,-1.0f,-1.0f, 
    -1.0f,-1.0f,-1.0f, 
    -1.0f, 1.0f,-1.0f, 
     1.0f, 1.0f,-1.0f, 
 
 
    -1.0f,-1.0f,-1.0f,  // -Y side 
     1.0f,-1.0f,-1.0f, 
     1.0f,-1.0f, 1.0f, 
    -1.0f,-1.0f,-1.0f, 
     1.0f,-1.0f, 1.0f, 
    -1.0f,-1.0f, 1.0f, 
 
 
    -1.0f, 1.0f,-1.0f,  // +Y side 
    -1.0f, 1.0f, 1.0f, 
     1.0f, 1.0f, 1.0f, 
    -1.0f, 1.0f,-1.0f, 
     1.0f, 1.0f, 1.0f, 
     1.0f, 1.0f,-1.0f, 
 
 
     1.0f, 1.0f,-1.0f,  // +X side 
     1.0f, 1.0f, 1.0f, 
     1.0f,-1.0f, 1.0f, 
     1.0f,-1.0f, 1.0f, 
     1.0f,-1.0f,-1.0f, 
     1.0f, 1.0f,-1.0f, 
 
 
    -1.0f, 1.0f, 1.0f,  // +Z side 
    -1.0f,-1.0f, 1.0f, 
     1.0f, 1.0f, 1.0f, 
    -1.0f,-1.0f, 1.0f, 
     1.0f,-1.0f, 1.0f, 
     1.0f, 1.0f, 1.0f, 
}; 
 
 
static const float g_uv_buffer_data[] = { 
    0.0f, 0.0f,  // -X side 
    1.0f, 0.0f, 
    1.0f, 1.0f, 
    1.0f, 1.0f, 
    0.0f, 1.0f, 
    0.0f, 0.0f, 
 
 
    1.0f, 0.0f,  // -Z side 
    0.0f, 1.0f, 
    0.0f, 0.0f, 
    1.0f, 0.0f, 
    1.0f, 1.0f, 
    0.0f, 1.0f, 
 
 
    1.0f, 1.0f,  // -Y side 
    1.0f, 0.0f, 
    0.0f, 0.0f, 
    1.0f, 1.0f, 
    0.0f, 0.0f, 
    0.0f, 1.0f, 
 
 
    1.0f, 1.0f,  // +Y side 
    0.0f, 1.0f, 
    0.0f, 0.0f, 
    1.0f, 1.0f, 
    0.0f, 0.0f, 
    1.0f, 0.0f, 
 
 
    1.0f, 1.0f,  // +X side 
    0.0f, 1.0f, 
    0.0f, 0.0f, 
    0.0f, 0.0f, 
    1.0f, 0.0f, 
    1.0f, 1.0f, 
 
 
    0.0f, 1.0f,  // +Z side 
    0.0f, 0.0f, 
    1.0f, 1.0f, 
    0.0f, 0.0f, 
    1.0f, 0.0f, 
    1.0f, 1.0f, 
}; 
// clang-format on 
 
 
void dumpMatrix(const char *note, mat4x4 MVP) { 
    int i; 
 
 
    printf("%s: \n", note); 
    for (i = 0; i < 4; i++) { 
        printf("%f, %f, %f, %f\n", MVP[i][0], MVP[i][1], MVP[i][2], MVP[i][3]); 
    } 
    printf("\n"); 
    fflush(stdout); 
} 
 
 
void dumpVec4(const char *note, vec4 vector) { 
    printf("%s: \n", note); 
    printf("%f, %f, %f, %f\n", vector[0], vector[1], vector[2], vector[3]); 
    printf("\n"); 
    fflush(stdout); 
} 
 
 
VKAPI_ATTR VkBool32 VKAPI_CALL 
dbgFunc(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, 
        uint64_t srcObject, size_t location, int32_t msgCode, 
        const char *pLayerPrefix, const char *pMsg, void *pUserData) { 
    char *message = (char *)malloc(strlen(pMsg) + 100); 
 
 
    assert(message); 
 
 
    if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) { 
        sprintf(message, "ERROR: [%s] Code %d : %s", pLayerPrefix, msgCode, 
                pMsg); 
    } else if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) { 
        // We know that we're submitting queues without fences, ignore this 
        // warning 
        if (strstr(pMsg, 
                   "vkQueueSubmit parameter, VkFence fence, is null pointer")) { 
            return false; 
        } 
        sprintf(message, "WARNING: [%s] Code %d : %s", pLayerPrefix, msgCode, 
                pMsg); 
    } else { 
        return false; 
    } 
 
 
#ifdef _WIN32 
    MessageBox(NULL, message, "Alert", MB_OK); 
#else 
    printf("%s\n", message); 
    fflush(stdout); 
#endif 
    free(message); 
 
 
    /* 
     * false indicates that layer should not bail-out of an 
     * API call that had validation failures. This may mean that the 
     * app dies inside the driver due to invalid parameter(s). 
     * That's what would happen without validation layers, so we'll 
     * keep that behavior here. 
     */ 
    return false; 
} 
 
 
VkBool32 BreakCallback(VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, 
                       uint64_t srcObject, size_t location, int32_t msgCode, 
                       const char *pLayerPrefix, const char *pMsg, 
                       void *pUserData) { 
#ifndef WIN32 
    raise(SIGTRAP); 
#else 
    DebugBreak(); 
#endif 
 
 
    return false; 
} 
 
 
typedef struct _SwapchainBuffers { 
    VkImage image; 
    VkCommandBuffer cmd; 
    VkImageView view; 
} SwapchainBuffers; 
 
 
struct demo { 
#ifdef _WIN32 
#define APP_NAME_STR_LEN 80 
    HINSTANCE connection;        // hInstance - Windows Instance 
    char name[APP_NAME_STR_LEN]; // Name to put on the window/icon 
    HWND window;                 // hWnd - window handle 
#else                            // _WIN32 
    xcb_connection_t *connection; 
    xcb_screen_t *screen; 
    xcb_window_t window; 
    xcb_intern_atom_reply_t *atom_wm_delete_window; 
#endif                           // _WIN32 
    VkSurfaceKHR surface; 
    bool prepared; 
    bool use_staging_buffer; 
 
 
    VkInstance inst; 
    VkPhysicalDevice gpu; 
    VkDevice device; 
    VkQueue queue; 
    uint32_t graphics_queue_node_index; 
    VkPhysicalDeviceProperties gpu_props; 
    VkQueueFamilyProperties *queue_props; 
    VkPhysicalDeviceMemoryProperties memory_properties; 
 
 
    uint32_t enabled_extension_count; 
    uint32_t enabled_layer_count; 
    char *extension_names[64]; 
    char *device_validation_layers[64]; 
 
 
    int width, height; 
    VkFormat format; 
    VkColorSpaceKHR color_space; 
 
 
    PFN_vkGetPhysicalDeviceSurfaceSupportKHR 
        fpGetPhysicalDeviceSurfaceSupportKHR; 
    PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR 
        fpGetPhysicalDeviceSurfaceCapabilitiesKHR; 
    PFN_vkGetPhysicalDeviceSurfaceFormatsKHR 
        fpGetPhysicalDeviceSurfaceFormatsKHR; 
    PFN_vkGetPhysicalDeviceSurfacePresentModesKHR 
        fpGetPhysicalDeviceSurfacePresentModesKHR; 
    PFN_vkCreateSwapchainKHR fpCreateSwapchainKHR; 
    PFN_vkDestroySwapchainKHR fpDestroySwapchainKHR; 
    PFN_vkGetSwapchainImagesKHR fpGetSwapchainImagesKHR; 
    PFN_vkAcquireNextImageKHR fpAcquireNextImageKHR; 
    PFN_vkQueuePresentKHR fpQueuePresentKHR; 
    uint32_t swapchainImageCount; 
    VkSwapchainKHR swapchain; 
    SwapchainBuffers *buffers; 
 
 
    VkCommandPool cmd_pool; 
 
 
    struct { 
        VkFormat format; 
 
 
        VkImage image; 
        VkMemoryAllocateInfo mem_alloc; 
        VkDeviceMemory mem; 
        VkImageView view; 
    } depth; 
 
 
    struct texture_object textures[DEMO_TEXTURE_COUNT]; 
 
 
    struct { 
        VkBuffer buf; 
        VkMemoryAllocateInfo mem_alloc; 
        VkDeviceMemory mem; 
        VkDescriptorBufferInfo buffer_info; 
    } uniform_data; 
 
 
    VkCommandBuffer cmd; // Buffer for initialization commands 
    VkPipelineLayout pipeline_layout; 
    VkDescriptorSetLayout desc_layout; 
    VkPipelineCache pipelineCache; 
    VkRenderPass render_pass; 
    VkPipeline pipeline; 
 
 
    mat4x4 projection_matrix; 
    mat4x4 view_matrix; 
    mat4x4 model_matrix; 
 
 
    float spin_angle; 
    float spin_increment; 
    bool pause; 
 
 
    VkShaderModule vert_shader_module; 
    VkShaderModule frag_shader_module; 
 
 
    VkDescriptorPool desc_pool; 
    VkDescriptorSet desc_set; 
 
 
    VkFramebuffer *framebuffers; 
 
 
    bool quit; 
    int32_t curFrame; 
    int32_t frameCount; 
    bool validate; 
    bool use_break; 
    PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback; 
    PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback; 
    VkDebugReportCallbackEXT msg_callback; 
    PFN_vkDebugReportMessageEXT DebugReportMessage; 
 
 
    uint32_t current_buffer; 
    uint32_t queue_count; 
}; 
 
static void demo_resize(struct demo *demo); 
 
 
static bool memory_type_from_properties(struct demo *demo, uint32_t typeBits, 
                                        VkFlags requirements_mask, 
                                        uint32_t *typeIndex) { 
    // Search memtypes to find first index with those properties 
    for (uint32_t i = 0; i < 32; i++) { 
        if ((typeBits & 1) == 1) { 
            // Type is available, does it match user properties? 
            if ((demo->memory_properties.memoryTypes[i].propertyFlags & 
                 requirements_mask) == requirements_mask) { 
                *typeIndex = i; 
                return true; 
            } 
        } 
        typeBits >>= 1; 
    } 
    // No memory types matched, return failure 
    return false; 
} 
 
 
static void demo_flush_init_cmd(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
 
 
    if (demo->cmd == VK_NULL_HANDLE) 
        return; 
 
 
    err = vkEndCommandBuffer(demo->cmd); 
    assert(!err); 
 
 
    const VkCommandBuffer cmd_bufs[] = {demo->cmd}; 
    VkFence nullFence = VK_NULL_HANDLE; 
    VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, 
                                .pNext = NULL, 
                                .waitSemaphoreCount = 0, 
                                .pWaitSemaphores = NULL, 
                                .pWaitDstStageMask = NULL, 
                                .commandBufferCount = 1, 
                                .pCommandBuffers = cmd_bufs, 
                                .signalSemaphoreCount = 0, 
                                .pSignalSemaphores = NULL}; 
 
 
    err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); 
    assert(!err); 
 
 
    err = vkQueueWaitIdle(demo->queue); 
    assert(!err); 
 
 
    vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, cmd_bufs); 
    demo->cmd = VK_NULL_HANDLE; 
} 
 
 
static void demo_set_image_layout(struct demo *demo, VkImage image, 
                                  VkImageAspectFlags aspectMask, 
                                  VkImageLayout old_image_layout, 
                                  VkImageLayout new_image_layout) { 
    VkResult U_ASSERT_ONLY err; 
 
 
    if (demo->cmd == VK_NULL_HANDLE) { 
        const VkCommandBufferAllocateInfo cmd = { 
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, 
            .pNext = NULL, 
            .commandPool = demo->cmd_pool, 
            .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, 
            .commandBufferCount = 1, 
        }; 
 
 
        err = vkAllocateCommandBuffers(demo->device, &cmd, &demo->cmd); 
        assert(!err); 
 
 
        VkCommandBufferInheritanceInfo cmd_buf_hinfo = { 
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, 
            .pNext = NULL, 
            .renderPass = VK_NULL_HANDLE, 
            .subpass = 0, 
            .framebuffer = VK_NULL_HANDLE, 
            .occlusionQueryEnable = VK_FALSE, 
            .queryFlags = 0, 
            .pipelineStatistics = 0, 
        }; 
        VkCommandBufferBeginInfo cmd_buf_info = { 
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, 
            .pNext = NULL, 
            .flags = 0, 
            .pInheritanceInfo = &cmd_buf_hinfo, 
        }; 
        err = vkBeginCommandBuffer(demo->cmd, &cmd_buf_info); 
        assert(!err); 
    } 
 
 
    VkImageMemoryBarrier image_memory_barrier = { 
        .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, 
        .pNext = NULL, 
        .srcAccessMask = 0, 
        .dstAccessMask = 0, 
        .oldLayout = old_image_layout, 
        .newLayout = new_image_layout, 
        .image = image, 
        .subresourceRange = {aspectMask, 0, 1, 0, 1}}; 
 
 
    if (new_image_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { 
        image_memory_barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; 
    } 
 
 
    if (new_image_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) { 
        image_memory_barrier.dstAccessMask = 
            VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; 
    } 
 
 
    if (new_image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) { 
        image_memory_barrier.dstAccessMask = 
            VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; 
    } 
 
 
    if (new_image_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { 
            VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; 
    } 
 
 
    VkImageMemoryBarrier *pmemory_barrier = &image_memory_barrier; 
 
 
    VkPipelineStageFlags src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; 
    VkPipelineStageFlags dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; 
 
 
    vkCmdPipelineBarrier(demo->cmd, src_stages, dest_stages, 0, 0, NULL, 0, 
                         NULL, 1, pmemory_barrier); 
} 
 
 
static void demo_draw_build_cmd(struct demo *demo, VkCommandBuffer cmd_buf) { 
    VkCommandBufferInheritanceInfo cmd_buf_hinfo = { 
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, 
        .pNext = NULL, 
        .renderPass = VK_NULL_HANDLE, 
        .subpass = 0, 
        .framebuffer = VK_NULL_HANDLE, 
        .occlusionQueryEnable = VK_FALSE, 
        .queryFlags = 0, 
        .pipelineStatistics = 0, 
    }; 
    const VkCommandBufferBeginInfo cmd_buf_info = { 
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, 
        .pNext = NULL, 
        .flags = 0, 
        .pInheritanceInfo = &cmd_buf_hinfo, 
    }; 
    const VkClearValue clear_values[2] = { 
            [0] = {.color.float32 = {0.2f, 0.2f, 0.2f, 0.2f}}, 
            [1] = {.depthStencil = {1.0f, 0}}, 
    }; 
    const VkRenderPassBeginInfo rp_begin = { 
        .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, 
        .pNext = NULL, 
        .renderPass = demo->render_pass, 
        .framebuffer = demo->framebuffers[demo->current_buffer], 
        .renderArea.offset.x = 0, 
        .renderArea.offset.y = 0, 
        .renderArea.extent.width = demo->width, 
        .renderArea.extent.height = demo->height, 
        .clearValueCount = 2, 
        .pClearValues = clear_values, 
    }; 
    VkResult U_ASSERT_ONLY err; 
 
 
    err = vkBeginCommandBuffer(cmd_buf, &cmd_buf_info); 
    assert(!err); 
 
 
    vkCmdBeginRenderPass(cmd_buf, &rp_begin, VK_SUBPASS_CONTENTS_INLINE); 
 
 
    vkCmdBindPipeline(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, demo->pipeline); 
    vkCmdBindDescriptorSets(cmd_buf, VK_PIPELINE_BIND_POINT_GRAPHICS, 
                            demo->pipeline_layout, 0, 1, &demo->desc_set, 0, 
                            NULL); 
 
 
    VkViewport viewport; 
    memset(&viewport, 0, sizeof(viewport)); 
    viewport.height = (float)demo->height; 
    viewport.width = (float)demo->width; 
    viewport.minDepth = (float)0.0f; 
    viewport.maxDepth = (float)1.0f; 
    vkCmdSetViewport(cmd_buf, 0, 1, &viewport); 
 
 
    VkRect2D scissor; 
    memset(&scissor, 0, sizeof(scissor)); 
    scissor.extent.width = demo->width; 
    scissor.extent.height = demo->height; 
    scissor.offset.x = 0; 
    scissor.offset.y = 0; 
    vkCmdSetScissor(cmd_buf, 0, 1, &scissor); 
 
 
    vkCmdDraw(cmd_buf, 12 * 3, 1, 0, 0); 
    vkCmdEndRenderPass(cmd_buf); 
 
 
    VkImageMemoryBarrier prePresentBarrier = { 
        .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, 
        .pNext = NULL, 
        .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, 
        .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT, 
        .oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 
        .newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, 
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, 
        .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, 
        .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; 
 
 
    prePresentBarrier.image = demo->buffers[demo->current_buffer].image; 
    VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier; 
    vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 
                         VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, 
                         NULL, 1, pmemory_barrier); 
 
 
    err = vkEndCommandBuffer(cmd_buf); 
    assert(!err); 
} 
 
 
void demo_update_data_buffer(struct demo *demo) { 
    mat4x4 MVP, Model, VP; 
    int matrixSize = sizeof(MVP); 
    uint8_t *pData; 
    VkResult U_ASSERT_ONLY err; 
 
 
    mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix); 
 
    mat4x4_dup(Model, demo->model_matrix); 
    mat4x4_rotate(demo->model_matrix, Model, 0.0f, 1.0f, 0.0f, 
                  (float)degreesToRadians(demo->spin_angle)); 
    mat4x4_mul(MVP, VP, demo->model_matrix); 
 
 
    err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, 
                      demo->uniform_data.mem_alloc.allocationSize, 0, 
                      (void **)&pData); 
    assert(!err); 
 
 
    memcpy(pData, (const void *)&MVP[0][0], matrixSize); 
 
 
    vkUnmapMemory(demo->device, demo->uniform_data.mem); 
} 
 
 
static void demo_draw(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
    VkSemaphore presentCompleteSemaphore; 
    VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo = { 
        .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, 
        .pNext = NULL, 
        .flags = 0, 
    }; 
    VkFence nullFence = VK_NULL_HANDLE; 
 
 
    err = vkCreateSemaphore(demo->device, &presentCompleteSemaphoreCreateInfo, 
                            NULL, &presentCompleteSemaphore); 
    assert(!err); 
 
 
    err = demo->fpAcquireNextImageKHR(demo->device, demo->swapchain, UINT64_MAX, 
                                      presentCompleteSemaphore, 
                                      (VkFence)0, // TODO: Show use of fence 
                                      &demo->current_buffer); 
    if (err == VK_ERROR_OUT_OF_DATE_KHR) { 
        demo_resize(demo); 
        demo_draw(demo); 
        vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL); 
        return; 
    } else if (err == VK_SUBOPTIMAL_KHR) { 
    } else { 
        assert(!err); 
    } 
 
 
    demo_set_image_layout(demo, demo->buffers[demo->current_buffer].image, 
                          VK_IMAGE_ASPECT_COLOR_BIT, 
                          VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, 
                          VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL); 
    demo_flush_init_cmd(demo); 
 
 
 
    VkPipelineStageFlags pipe_stage_flags = 
        VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; 
    VkSubmitInfo submit_info = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, 
                                .pNext = NULL, 
                                .waitSemaphoreCount = 1, 
                                .pWaitSemaphores = &presentCompleteSemaphore, 
                                .pWaitDstStageMask = &pipe_stage_flags, 
                                .commandBufferCount = 1, 
                                .pCommandBuffers = 
                                    &demo->buffers[demo->current_buffer].cmd, 
                                .signalSemaphoreCount = 0, 
                                .pSignalSemaphores = NULL}; 
 
 
    err = vkQueueSubmit(demo->queue, 1, &submit_info, nullFence); 
    assert(!err); 
 
 
    VkPresentInfoKHR present = { 
        .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, 
        .pNext = NULL, 
        .swapchainCount = 1, 
        .pSwapchains = &demo->swapchain, 
        .pImageIndices = &demo->current_buffer, 
    }; 
 
 
    err = demo->fpQueuePresentKHR(demo->queue, &present); 
    if (err == VK_ERROR_OUT_OF_DATE_KHR) { 
        demo_resize(demo); 
    } else if (err == VK_SUBOPTIMAL_KHR) { 
    } else { 
        assert(!err); 
    } 
 
 
    err = vkQueueWaitIdle(demo->queue); 
    assert(err == VK_SUCCESS); 
 
 
    vkDestroySemaphore(demo->device, presentCompleteSemaphore, NULL); 
} 
 
 
static void demo_prepare_buffers(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
    VkSwapchainKHR oldSwapchain = demo->swapchain; 
 
    VkSurfaceCapabilitiesKHR surfCapabilities; 
    err = demo->fpGetPhysicalDeviceSurfaceCapabilitiesKHR( 
        demo->gpu, demo->surface, &surfCapabilities); 
    assert(!err); 
 
 
    uint32_t presentModeCount; 
    err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( 
        demo->gpu, demo->surface, &presentModeCount, NULL); 
    assert(!err); 
    VkPresentModeKHR *presentModes = 
        (VkPresentModeKHR *)malloc(presentModeCount * sizeof(VkPresentModeKHR)); 
    assert(presentModes); 
    err = demo->fpGetPhysicalDeviceSurfacePresentModesKHR( 
        demo->gpu, demo->surface, &presentModeCount, presentModes); 
    assert(!err); 
 
 
    VkExtent2D swapchainExtent; 
    if (surfCapabilities.currentExtent.width == (uint32_t)-1) { 
        swapchainExtent.width = demo->width; 
        swapchainExtent.height = demo->height; 
    } else { 
        // If the surface size is defined, the swap chain size must match 
        swapchainExtent = surfCapabilities.currentExtent; 
        demo->width = surfCapabilities.currentExtent.width; 
        demo->height = surfCapabilities.currentExtent.height; 
    } 
 
    VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR; 
    for (size_t i = 0; i < presentModeCount; i++) { 
        if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR) { 
            swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR; 
            break; 
        } 
        if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR) && 
            (presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR)) { 
            swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; 
        } 
    } 
 
    uint32_t desiredNumberOfSwapchainImages = 
        surfCapabilities.minImageCount + 1; 
    if ((surfCapabilities.maxImageCount > 0) && 
        (desiredNumberOfSwapchainImages > surfCapabilities.maxImageCount)) { 
        // Application must settle for fewer images than desired: 
        desiredNumberOfSwapchainImages = surfCapabilities.maxImageCount; 
    } 
 
 
    VkSurfaceTransformFlagsKHR preTransform; 
    if (surfCapabilities.supportedTransforms & 
        VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) { 
        preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; 
    } else { 
        preTransform = surfCapabilities.currentTransform; 
    } 
 
 
    const VkSwapchainCreateInfoKHR swapchain = { 
        .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, 
        .pNext = NULL, 
        .surface = demo->surface, 
        .minImageCount = desiredNumberOfSwapchainImages, 
        .imageFormat = demo->format, 
        .imageColorSpace = demo->color_space, 
        .imageExtent = 
            { 
             .width = swapchainExtent.width, .height = swapchainExtent.height, 
            }, 
        .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, 
        .preTransform = preTransform, 
        .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, 
        .imageArrayLayers = 1, 
        .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE, 
        .queueFamilyIndexCount = 0, 
        .pQueueFamilyIndices = NULL, 
        .presentMode = swapchainPresentMode, 
        .oldSwapchain = oldSwapchain, 
        .clipped = true, 
    }; 
    uint32_t i; 
 
 
    err = demo->fpCreateSwapchainKHR(demo->device, &swapchain, NULL, 
                                     &demo->swapchain); 
    assert(!err); 
 
 
    if (oldSwapchain != VK_NULL_HANDLE) { 
        demo->fpDestroySwapchainKHR(demo->device, oldSwapchain, NULL); 
    } 
 
 
    err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, 
                                        &demo->swapchainImageCount, NULL); 
    assert(!err); 
 
 
    VkImage *swapchainImages = 
        (VkImage *)malloc(demo->swapchainImageCount * sizeof(VkImage)); 
    assert(swapchainImages); 
    err = demo->fpGetSwapchainImagesKHR(demo->device, demo->swapchain, 
                                        &demo->swapchainImageCount, 
                                        swapchainImages); 
    assert(!err); 
 
 
    demo->buffers = (SwapchainBuffers *)malloc(sizeof(SwapchainBuffers) * 
                                               demo->swapchainImageCount); 
    assert(demo->buffers); 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        VkImageViewCreateInfo color_image_view = { 
            .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, 
            .pNext = NULL, 
            .format = demo->format, 
            .components = 
                { 
                 .r = VK_COMPONENT_SWIZZLE_R, 
                 .g = VK_COMPONENT_SWIZZLE_G, 
                 .b = VK_COMPONENT_SWIZZLE_B, 
                 .a = VK_COMPONENT_SWIZZLE_A, 
                }, 
            .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, 
                                 .baseMipLevel = 0, 
                                 .levelCount = 1, 
                                 .baseArrayLayer = 0, 
                                 .layerCount = 1}, 
            .viewType = VK_IMAGE_VIEW_TYPE_2D, 
            .flags = 0, 
        }; 
 
 
        demo->buffers[i].image = swapchainImages[i]; 
 
 
        demo_set_image_layout( 
            demo, demo->buffers[i].image, VK_IMAGE_ASPECT_COLOR_BIT, 
            VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); 
 
 
        color_image_view.image = demo->buffers[i].image; 
 
 
        err = vkCreateImageView(demo->device, &color_image_view, NULL, 
                                &demo->buffers[i].view); 
        assert(!err); 
    } 
 
 
    if (NULL != presentModes) { 
        free(presentModes); 
    } 
} 
 
 
static void demo_prepare_depth(struct demo *demo) { 
    const VkFormat depth_format = VK_FORMAT_D16_UNORM; 
    const VkImageCreateInfo image = { 
        .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, 
        .pNext = NULL, 
        .imageType = VK_IMAGE_TYPE_2D, 
        .format = depth_format, 
        .extent = {demo->width, demo->height, 1}, 
        .mipLevels = 1, 
        .arrayLayers = 1, 
        .samples = VK_SAMPLE_COUNT_1_BIT, 
        .tiling = VK_IMAGE_TILING_OPTIMAL, 
        .usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, 
        .flags = 0, 
    }; 
 
 
    VkImageViewCreateInfo view = { 
        .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, 
        .pNext = NULL, 
        .image = VK_NULL_HANDLE, 
        .format = depth_format, 
        .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT, 
                             .baseMipLevel = 0, 
                             .levelCount = 1, 
                             .baseArrayLayer = 0, 
                             .layerCount = 1}, 
        .flags = 0, 
        .viewType = VK_IMAGE_VIEW_TYPE_2D, 
    }; 
 
 
    VkMemoryRequirements mem_reqs; 
    VkResult U_ASSERT_ONLY err; 
    bool U_ASSERT_ONLY pass; 
 
 
    demo->depth.format = depth_format; 
 
 
    /* create image */ 
    err = vkCreateImage(demo->device, &image, NULL, &demo->depth.image); 
    assert(!err); 
 
 
    vkGetImageMemoryRequirements(demo->device, demo->depth.image, &mem_reqs); 
    assert(!err); 
 
 
    demo->depth.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; 
    demo->depth.mem_alloc.pNext = NULL; 
    demo->depth.mem_alloc.allocationSize = mem_reqs.size; 
    demo->depth.mem_alloc.memoryTypeIndex = 0; 
 
 
    pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, 
                                       0, /* No requirements */ 
                                       &demo->depth.mem_alloc.memoryTypeIndex); 
    assert(pass); 
 
 
    /* allocate memory */ 
    err = vkAllocateMemory(demo->device, &demo->depth.mem_alloc, NULL, 
                           &demo->depth.mem); 
    assert(!err); 
 
 
    /* bind memory */ 
    err = 
        vkBindImageMemory(demo->device, demo->depth.image, demo->depth.mem, 0); 
    assert(!err); 
 
 
    demo_set_image_layout(demo, demo->depth.image, VK_IMAGE_ASPECT_DEPTH_BIT, 
                          VK_IMAGE_LAYOUT_UNDEFINED, 
                          VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL); 
 
 
    /* create image view */ 
    view.image = demo->depth.image; 
    err = vkCreateImageView(demo->device, &view, NULL, &demo->depth.view); 
    assert(!err); 
} 
 
 
/* Load a ppm file into memory */ 
bool loadTexture(const char *filename, uint8_t *rgba_data, 
                 VkSubresourceLayout *layout, int32_t *width, int32_t *height) { 
    FILE *fPtr = fopen(filename, "rb"); 
    char header[256], *cPtr, *tmp; 
 
 
    if (!fPtr) 
        return false; 
 
 
    cPtr = fgets(header, 256, fPtr); // P6 
    if (cPtr == NULL || strncmp(header, "P6\n", 3)) { 
        fclose(fPtr); 
        return false; 
    } 
 
 
    do { 
        cPtr = fgets(header, 256, fPtr); 
        if (cPtr == NULL) { 
            fclose(fPtr); 
            return false; 
        } 
    } while (!strncmp(header, "#", 1)); 
 
 
    sscanf(header, "%u %u", height, width); 
    if (rgba_data == NULL) { 
        fclose(fPtr); 
        return true; 
    } 
    tmp = fgets(header, 256, fPtr); // Format 
    (void)tmp; 
    if (cPtr == NULL || strncmp(header, "255\n", 3)) { 
        fclose(fPtr); 
        return false; 
    } 
 
 
    for (int y = 0; y < *height; y++) { 
        uint8_t *rowPtr = rgba_data; 
        for (int x = 0; x < *width; x++) { 
            size_t s = fread(rowPtr, 3, 1, fPtr); 
            (void)s; 
            rowPtr[3] = 255; /* Alpha of 1 */ 
            rowPtr += 4; 
        } 
        rgba_data += layout->rowPitch; 
    } 
    fclose(fPtr); 
    return true; 
} 
 
 
static void demo_prepare_texture_image(struct demo *demo, const char *filename, 
                                       struct texture_object *tex_obj, 
                                       VkImageTiling tiling, 
                                       VkImageUsageFlags usage, 
                                       VkFlags required_props) { 
    const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM; 
    int32_t tex_width; 
    int32_t tex_height; 
    VkResult U_ASSERT_ONLY err; 
    bool U_ASSERT_ONLY pass; 
 
 
    if (!loadTexture(filename, NULL, NULL, &tex_width, &tex_height)) { 
        printf("Failed to load textures\n"); 
        fflush(stdout); 
        exit(1); 
    } 
 
 
    tex_obj->tex_width = tex_width; 
    tex_obj->tex_height = tex_height; 
 
 
    const VkImageCreateInfo image_create_info = { 
        .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, 
        .pNext = NULL, 
        .imageType = VK_IMAGE_TYPE_2D, 
        .format = tex_format, 
        .extent = {tex_width, tex_height, 1}, 
        .mipLevels = 1, 
        .arrayLayers = 1, 
        .samples = VK_SAMPLE_COUNT_1_BIT, 
        .tiling = tiling, 
        .usage = usage, 
        .flags = 0, 
    }; 
 
 
    VkMemoryRequirements mem_reqs; 
 
 
    err = 
        vkCreateImage(demo->device, &image_create_info, NULL, &tex_obj->image); 
    assert(!err); 
 
 
    vkGetImageMemoryRequirements(demo->device, tex_obj->image, &mem_reqs); 
 
 
    tex_obj->mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; 
    tex_obj->mem_alloc.pNext = NULL; 
    tex_obj->mem_alloc.allocationSize = mem_reqs.size; 
    tex_obj->mem_alloc.memoryTypeIndex = 0; 
 
 
    pass = memory_type_from_properties(demo, mem_reqs.memoryTypeBits, 
                                       required_props, 
                                       &tex_obj->mem_alloc.memoryTypeIndex); 
    assert(pass); 
 
 
    /* allocate memory */ 
    err = vkAllocateMemory(demo->device, &tex_obj->mem_alloc, NULL, 
                           &(tex_obj->mem)); 
    assert(!err); 
 
 
    /* bind memory */ 
    err = vkBindImageMemory(demo->device, tex_obj->image, tex_obj->mem, 0); 
    assert(!err); 
 
 
    if (required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) { 
        const VkImageSubresource subres = { 
            .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, 
            .mipLevel = 0, 
            .arrayLayer = 0, 
        }; 
        VkSubresourceLayout layout; 
        void *data; 
 
 
        vkGetImageSubresourceLayout(demo->device, tex_obj->image, &subres, 
                                    &layout); 
 
 
        err = vkMapMemory(demo->device, tex_obj->mem, 0, 
                          tex_obj->mem_alloc.allocationSize, 0, &data); 
        assert(!err); 
 
 
        if (!loadTexture(filename, data, &layout, &tex_width, &tex_height)) { 
            fprintf(stderr, "Error loading texture: %s\n", filename); 
        } 
 
 
        vkUnmapMemory(demo->device, tex_obj->mem); 
    } 
 
 
    tex_obj->imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; 
    demo_set_image_layout(demo, tex_obj->image, VK_IMAGE_ASPECT_COLOR_BIT, 
                          VK_IMAGE_LAYOUT_UNDEFINED, tex_obj->imageLayout); 
    /* setting the image layout does not reference the actual memory so no need 
     * to add a mem ref */ 
} 
 
 
static void demo_destroy_texture_image(struct demo *demo, 
                                       struct texture_object *tex_objs) { 
    /* clean up staging resources */ 
    vkFreeMemory(demo->device, tex_objs->mem, NULL); 
    vkDestroyImage(demo->device, tex_objs->image, NULL); 
} 
 
 
static void demo_prepare_textures(struct demo *demo) { 
    const VkFormat tex_format = VK_FORMAT_R8G8B8A8_UNORM; 
    VkFormatProperties props; 
    uint32_t i; 
 
 
    vkGetPhysicalDeviceFormatProperties(demo->gpu, tex_format, &props); 
 
 
    for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { 
        VkResult U_ASSERT_ONLY err; 
 
 
        if ((props.linearTilingFeatures & 
             VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) && 
            !demo->use_staging_buffer) { 
            /* Device can texture using linear textures */ 
            demo_prepare_texture_image(demo, tex_files[i], &demo->textures[i], 
                                       VK_IMAGE_TILING_LINEAR, 
                                       VK_IMAGE_USAGE_SAMPLED_BIT, 
                                       VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); 
        } else if (props.optimalTilingFeatures & 
                   VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { 
            /* Must use staging buffer to copy linear texture to optimized */ 
            struct texture_object staging_texture; 
 
 
            memset(&staging_texture, 0, sizeof(staging_texture)); 
            demo_prepare_texture_image(demo, tex_files[i], &staging_texture, 
                                       VK_IMAGE_TILING_LINEAR, 
                                       VK_IMAGE_USAGE_TRANSFER_SRC_BIT, 
                                       VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); 
 
 
            demo_prepare_texture_image( 
                demo, tex_files[i], &demo->textures[i], VK_IMAGE_TILING_OPTIMAL, 
                (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), 
                VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); 
 
 
            demo_set_image_layout(demo, staging_texture.image, 
                                  VK_IMAGE_ASPECT_COLOR_BIT, 
                                  staging_texture.imageLayout, 
                                  VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); 
 
 
            demo_set_image_layout(demo, demo->textures[i].image, 
                                  VK_IMAGE_ASPECT_COLOR_BIT, 
                                  demo->textures[i].imageLayout, 
                                  VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); 
 
 
            VkImageCopy copy_region = { 
                .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, 
                .srcOffset = {0, 0, 0}, 
                .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, 
                .dstOffset = {0, 0, 0}, 
                .extent = {staging_texture.tex_width, 
                           staging_texture.tex_height, 1}, 
            }; 
            vkCmdCopyImage( 
                demo->cmd, staging_texture.image, 
                VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, demo->textures[i].image, 
                VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©_region); 
 
 
            demo_set_image_layout(demo, demo->textures[i].image, 
                                  VK_IMAGE_ASPECT_COLOR_BIT, 
                                  VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 
                                  demo->textures[i].imageLayout); 
 
 
            demo_flush_init_cmd(demo); 
 
 
            demo_destroy_texture_image(demo, &staging_texture); 
        } else { 
            /* Can't support VK_FORMAT_R8G8B8A8_UNORM !? */ 
            assert(!"No support for R8G8B8A8_UNORM as texture image format"); 
        } 
 
 
        const VkSamplerCreateInfo sampler = { 
            .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, 
            .pNext = NULL, 
            .magFilter = VK_FILTER_NEAREST, 
            .minFilter = VK_FILTER_NEAREST, 
            .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, 
            .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 
            .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 
            .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, 
            .mipLodBias = 0.0f, 
            .anisotropyEnable = VK_FALSE, 
            .maxAnisotropy = 1, 
            .compareOp = VK_COMPARE_OP_NEVER, 
            .minLod = 0.0f, 
            .maxLod = 0.0f, 
            .borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, 
            .unnormalizedCoordinates = VK_FALSE, 
        }; 
 
 
        VkImageViewCreateInfo view = { 
            .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, 
            .pNext = NULL, 
            .image = VK_NULL_HANDLE, 
            .viewType = VK_IMAGE_VIEW_TYPE_2D, 
            .format = tex_format, 
            .components = 
                { 
                 VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, 
                 VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A, 
                }, 
            .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}, 
            .flags = 0, 
        }; 
 
 
        /* create sampler */ 
        err = vkCreateSampler(demo->device, &sampler, NULL, 
                              &demo->textures[i].sampler); 
        assert(!err); 
 
 
        /* create image view */ 
        view.image = demo->textures[i].image; 
        err = vkCreateImageView(demo->device, &view, NULL, 
                                &demo->textures[i].view); 
        assert(!err); 
    } 
} 
 
 
void demo_prepare_cube_data_buffer(struct demo *demo) { 
    VkBufferCreateInfo buf_info; 
    VkMemoryRequirements mem_reqs; 
    uint8_t *pData; 
    int i; 
    mat4x4 MVP, VP; 
    VkResult U_ASSERT_ONLY err; 
    bool U_ASSERT_ONLY pass; 
    struct vktexcube_vs_uniform data; 
 
 
    mat4x4_mul(VP, demo->projection_matrix, demo->view_matrix); 
    mat4x4_mul(MVP, VP, demo->model_matrix); 
    memcpy(data.mvp, MVP, sizeof(MVP)); 
    //    dumpMatrix("MVP", MVP); 
 
 
    for (i = 0; i < 12 * 3; i++) { 
        data.position[i][0] = g_vertex_buffer_data[i * 3]; 
        data.position[i][1] = g_vertex_buffer_data[i * 3 + 1]; 
        data.position[i][2] = g_vertex_buffer_data[i * 3 + 2]; 
        data.position[i][3] = 1.0f; 
        data.attr[i][0] = g_uv_buffer_data[2 * i]; 
        data.attr[i][1] = g_uv_buffer_data[2 * i + 1]; 
        data.attr[i][2] = 0; 
        data.attr[i][3] = 0; 
    } 
 
 
    memset(&buf_info, 0, sizeof(buf_info)); 
    buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; 
    buf_info.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; 
    buf_info.size = sizeof(data); 
    err = 
        vkCreateBuffer(demo->device, &buf_info, NULL, &demo->uniform_data.buf); 
    assert(!err); 
 
 
    vkGetBufferMemoryRequirements(demo->device, demo->uniform_data.buf, 
                                  &mem_reqs); 
 
 
    demo->uniform_data.mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; 
    demo->uniform_data.mem_alloc.pNext = NULL; 
    demo->uniform_data.mem_alloc.allocationSize = mem_reqs.size; 
    demo->uniform_data.mem_alloc.memoryTypeIndex = 0; 
 
 
    pass = memory_type_from_properties( 
        demo, mem_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 
        &demo->uniform_data.mem_alloc.memoryTypeIndex); 
    assert(pass); 
 
 
    err = vkAllocateMemory(demo->device, &demo->uniform_data.mem_alloc, NULL, 
                           &(demo->uniform_data.mem)); 
    assert(!err); 
 
 
    err = vkMapMemory(demo->device, demo->uniform_data.mem, 0, 
                      demo->uniform_data.mem_alloc.allocationSize, 0, 
                      (void **)&pData); 
    assert(!err); 
 
 
    memcpy(pData, &data, sizeof data); 
 
 
    vkUnmapMemory(demo->device, demo->uniform_data.mem); 
 
 
    err = vkBindBufferMemory(demo->device, demo->uniform_data.buf, 
                             demo->uniform_data.mem, 0); 
    assert(!err); 
 
 
    demo->uniform_data.buffer_info.buffer = demo->uniform_data.buf; 
    demo->uniform_data.buffer_info.offset = 0; 
    demo->uniform_data.buffer_info.range = sizeof(data); 
} 
 
 
static void demo_prepare_descriptor_layout(struct demo *demo) { 
    const VkDescriptorSetLayoutBinding layout_bindings[2] = { 
            [0] = 
                { 
                 .binding = 0, 
                 .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 
                 .descriptorCount = 1, 
                 .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, 
                 .pImmutableSamplers = NULL, 
                }, 
            [1] = 
                { 
                 .binding = 1, 
                 .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 
                 .descriptorCount = DEMO_TEXTURE_COUNT, 
                 .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, 
                 .pImmutableSamplers = NULL, 
                }, 
    }; 
    const VkDescriptorSetLayoutCreateInfo descriptor_layout = { 
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, 
        .pNext = NULL, 
        .bindingCount = 2, 
        .pBindings = layout_bindings, 
    }; 
    VkResult U_ASSERT_ONLY err; 
 
 
    err = vkCreateDescriptorSetLayout(demo->device, &descriptor_layout, NULL, 
                                      &demo->desc_layout); 
    assert(!err); 
 
 
    const VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = { 
        .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, 
        .pNext = NULL, 
        .setLayoutCount = 1, 
        .pSetLayouts = &demo->desc_layout, 
    }; 
 
 
    err = vkCreatePipelineLayout(demo->device, &pPipelineLayoutCreateInfo, NULL, 
                                 &demo->pipeline_layout); 
    assert(!err); 
} 
 
 
static void demo_prepare_render_pass(struct demo *demo) { 
    const VkAttachmentDescription attachments[2] = { 
            [0] = 
                { 
                 .format = demo->format, 
                 .samples = VK_SAMPLE_COUNT_1_BIT, 
                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, 
                 .storeOp = VK_ATTACHMENT_STORE_OP_STORE, 
                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, 
                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, 
                 .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 
                 .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 
                }, 
            [1] = 
                { 
                 .format = demo->depth.format, 
                 .samples = VK_SAMPLE_COUNT_1_BIT, 
                 .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, 
                 .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, 
                 .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, 
                 .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, 
                 .initialLayout = 
                     VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 
                 .finalLayout = 
                     VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 
                }, 
    }; 
    const VkAttachmentReference color_reference = { 
        .attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, 
    }; 
    const VkAttachmentReference depth_reference = { 
        .attachment = 1, 
        .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 
    }; 
    const VkSubpassDescription subpass = { 
        .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, 
        .flags = 0, 
        .inputAttachmentCount = 0, 
        .pInputAttachments = NULL, 
        .colorAttachmentCount = 1, 
        .pColorAttachments = &color_reference, 
        .pResolveAttachments = NULL, 
        .pDepthStencilAttachment = &depth_reference, 
        .preserveAttachmentCount = 0, 
        .pPreserveAttachments = NULL, 
    }; 
    const VkRenderPassCreateInfo rp_info = { 
        .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, 
        .pNext = NULL, 
        .attachmentCount = 2, 
        .pAttachments = attachments, 
        .subpassCount = 1, 
        .pSubpasses = &subpass, 
        .dependencyCount = 0, 
        .pDependencies = NULL, 
    }; 
    VkResult U_ASSERT_ONLY err; 
 
 
    err = vkCreateRenderPass(demo->device, &rp_info, NULL, &demo->render_pass); 
    assert(!err); 
} 
 
 
static VkShaderModule 
demo_prepare_shader_module(struct demo *demo, const void *code, size_t size) { 
    VkShaderModule module; 
    VkShaderModuleCreateInfo moduleCreateInfo; 
    VkResult U_ASSERT_ONLY err; 
 
 
    moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; 
    moduleCreateInfo.pNext = NULL; 
 
 
    moduleCreateInfo.codeSize = size; 
    moduleCreateInfo.pCode = code; 
    moduleCreateInfo.flags = 0; 
    err = vkCreateShaderModule(demo->device, &moduleCreateInfo, NULL, &module); 
    assert(!err); 
 
 
    return module; 
} 
 
 
char *demo_read_spv(const char *filename, size_t *psize) { 
    long int size; 
    size_t U_ASSERT_ONLY retval; 
    void *shader_code; 
 
 
    FILE *fp = fopen(filename, "rb"); 
    if (!fp) 
        return NULL; 
 
 
    fseek(fp, 0L, SEEK_END); 
    size = ftell(fp); 
 
 
    fseek(fp, 0L, SEEK_SET); 
 
 
    shader_code = malloc(size); 
    retval = fread(shader_code, size, 1, fp); 
    assert(retval == 1); 
 
 
    *psize = size; 
 
 
    fclose(fp); 
    return shader_code; 
} 
 
 
static VkShaderModule demo_prepare_vs(struct demo *demo) { 
    void *vertShaderCode; 
    size_t size; 
 
 
    vertShaderCode = demo_read_spv("cube-vert.spv", &size); 
 
 
    demo->vert_shader_module = 
        demo_prepare_shader_module(demo, vertShaderCode, size); 
 
 
    free(vertShaderCode); 
 
 
    return demo->vert_shader_module; 
} 
 
 
static VkShaderModule demo_prepare_fs(struct demo *demo) { 
    void *fragShaderCode; 
    size_t size; 
 
 
    fragShaderCode = demo_read_spv("cube-frag.spv", &size); 
 
 
    demo->frag_shader_module = 
        demo_prepare_shader_module(demo, fragShaderCode, size); 
 
 
    free(fragShaderCode); 
 
 
    return demo->frag_shader_module; 
} 
 
 
static void demo_prepare_pipeline(struct demo *demo) { 
    VkGraphicsPipelineCreateInfo pipeline; 
    VkPipelineCacheCreateInfo pipelineCache; 
    VkPipelineVertexInputStateCreateInfo vi; 
    VkPipelineInputAssemblyStateCreateInfo ia; 
    VkPipelineRasterizationStateCreateInfo rs; 
    VkPipelineColorBlendStateCreateInfo cb; 
    VkPipelineDepthStencilStateCreateInfo ds; 
    VkPipelineViewportStateCreateInfo vp; 
    VkPipelineMultisampleStateCreateInfo ms; 
    VkDynamicState dynamicStateEnables[VK_DYNAMIC_STATE_RANGE_SIZE]; 
    VkPipelineDynamicStateCreateInfo dynamicState; 
    VkResult U_ASSERT_ONLY err; 
 
 
    memset(dynamicStateEnables, 0, sizeof dynamicStateEnables); 
    memset(&dynamicState, 0, sizeof dynamicState); 
    dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; 
    dynamicState.pDynamicStates = dynamicStateEnables; 
 
 
    memset(&pipeline, 0, sizeof(pipeline)); 
    pipeline.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; 
    pipeline.layout = demo->pipeline_layout; 
 
 
    memset(&vi, 0, sizeof(vi)); 
    vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; 
 
 
    memset(&ia, 0, sizeof(ia)); 
    ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; 
    ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; 
 
 
    memset(&rs, 0, sizeof(rs)); 
    rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; 
    rs.polygonMode = VK_POLYGON_MODE_FILL; 
    rs.cullMode = VK_CULL_MODE_BACK_BIT; 
    rs.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; 
    rs.depthClampEnable = VK_FALSE; 
    rs.rasterizerDiscardEnable = VK_FALSE; 
    rs.depthBiasEnable = VK_FALSE; 
 
 
    memset(&cb, 0, sizeof(cb)); 
    cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; 
    VkPipelineColorBlendAttachmentState att_state[1]; 
    memset(att_state, 0, sizeof(att_state)); 
    att_state[0].colorWriteMask = 0xf; 
    att_state[0].blendEnable = VK_FALSE; 
    cb.attachmentCount = 1; 
    cb.pAttachments = att_state; 
 
 
    memset(&vp, 0, sizeof(vp)); 
    vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; 
    vp.viewportCount = 1; 
    dynamicStateEnables[dynamicState.dynamicStateCount++] = 
        VK_DYNAMIC_STATE_VIEWPORT; 
    vp.scissorCount = 1; 
    dynamicStateEnables[dynamicState.dynamicStateCount++] = 
        VK_DYNAMIC_STATE_SCISSOR; 
 
 
    memset(&ds, 0, sizeof(ds)); 
    ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; 
    ds.depthTestEnable = VK_TRUE; 
    ds.depthWriteEnable = VK_TRUE; 
    ds.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL; 
    ds.depthBoundsTestEnable = VK_FALSE; 
    ds.back.failOp = VK_STENCIL_OP_KEEP; 
    ds.back.passOp = VK_STENCIL_OP_KEEP; 
    ds.back.compareOp = VK_COMPARE_OP_ALWAYS; 
    ds.stencilTestEnable = VK_FALSE; 
    ds.front = ds.back; 
 
 
    memset(&ms, 0, sizeof(ms)); 
    ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; 
    ms.pSampleMask = NULL; 
    ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; 
 
 
    // Two stages: vs and fs 
    pipeline.stageCount = 2; 
    VkPipelineShaderStageCreateInfo shaderStages[2]; 
    memset(&shaderStages, 0, 2 * sizeof(VkPipelineShaderStageCreateInfo)); 
 
 
    shaderStages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; 
    shaderStages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; 
    shaderStages[0].module = demo_prepare_vs(demo); 
    shaderStages[0].pName = "main"; 
 
 
    shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; 
    shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; 
    shaderStages[1].module = demo_prepare_fs(demo); 
    shaderStages[1].pName = "main"; 
 
 
    memset(&pipelineCache, 0, sizeof(pipelineCache)); 
    pipelineCache.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; 
 
 
    err = vkCreatePipelineCache(demo->device, &pipelineCache, NULL, 
                                &demo->pipelineCache); 
    assert(!err); 
 
 
    pipeline.pVertexInputState = &vi; 
    pipeline.pInputAssemblyState = &ia; 
    pipeline.pRasterizationState = &rs; 
    pipeline.pColorBlendState = &cb; 
    pipeline.pMultisampleState = &ms; 
    pipeline.pViewportState = &vp; 
    pipeline.pDepthStencilState = &ds; 
    pipeline.pStages = shaderStages; 
    pipeline.renderPass = demo->render_pass; 
    pipeline.pDynamicState = &dynamicState; 
 
 
    pipeline.renderPass = demo->render_pass; 
 
 
    err = vkCreateGraphicsPipelines(demo->device, demo->pipelineCache, 1, 
                                    &pipeline, NULL, &demo->pipeline); 
    assert(!err); 
 
 
    vkDestroyShaderModule(demo->device, demo->frag_shader_module, NULL); 
    vkDestroyShaderModule(demo->device, demo->vert_shader_module, NULL); 
} 
 
 
static void demo_prepare_descriptor_pool(struct demo *demo) { 
    const VkDescriptorPoolSize type_counts[2] = { 
            [0] = 
                { 
                 .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 
                 .descriptorCount = 1, 
                }, 
            [1] = 
                { 
                 .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 
                 .descriptorCount = DEMO_TEXTURE_COUNT, 
                }, 
    }; 
    const VkDescriptorPoolCreateInfo descriptor_pool = { 
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, 
        .pNext = NULL, 
        .maxSets = 1, 
        .poolSizeCount = 2, 
        .pPoolSizes = type_counts, 
    }; 
    VkResult U_ASSERT_ONLY err; 
 
 
    err = vkCreateDescriptorPool(demo->device, &descriptor_pool, NULL, 
                                 &demo->desc_pool); 
    assert(!err); 
} 
 
 
static void demo_prepare_descriptor_set(struct demo *demo) { 
    VkDescriptorImageInfo tex_descs[DEMO_TEXTURE_COUNT]; 
    VkWriteDescriptorSet writes[2]; 
    VkResult U_ASSERT_ONLY err; 
    uint32_t i; 
 
 
    VkDescriptorSetAllocateInfo alloc_info = { 
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, 
        .pNext = NULL, 
        .descriptorPool = demo->desc_pool, 
        .descriptorSetCount = 1, 
        .pSetLayouts = &demo->desc_layout}; 
    err = vkAllocateDescriptorSets(demo->device, &alloc_info, &demo->desc_set); 
    assert(!err); 
 
 
    memset(&tex_descs, 0, sizeof(tex_descs)); 
    for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { 
        tex_descs[i].sampler = demo->textures[i].sampler; 
        tex_descs[i].imageView = demo->textures[i].view; 
        tex_descs[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL; 
    } 
 
 
    memset(&writes, 0, sizeof(writes)); 
 
 
    writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; 
    writes[0].dstSet = demo->desc_set; 
    writes[0].descriptorCount = 1; 
    writes[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; 
    writes[0].pBufferInfo = &demo->uniform_data.buffer_info; 
 
 
    writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; 
    writes[1].dstSet = demo->desc_set; 
    writes[1].dstBinding = 1; 
    writes[1].descriptorCount = DEMO_TEXTURE_COUNT; 
    writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; 
    writes[1].pImageInfo = tex_descs; 
 
 
    vkUpdateDescriptorSets(demo->device, 2, writes, 0, NULL); 
} 
 
 
static void demo_prepare_framebuffers(struct demo *demo) { 
    VkImageView attachments[2]; 
    attachments[1] = demo->depth.view; 
 
 
    const VkFramebufferCreateInfo fb_info = { 
        .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, 
        .pNext = NULL, 
        .renderPass = demo->render_pass, 
        .attachmentCount = 2, 
        .pAttachments = attachments, 
        .width = demo->width, 
        .height = demo->height, 
        .layers = 1, 
    }; 
    VkResult U_ASSERT_ONLY err; 
    uint32_t i; 
 
 
    demo->framebuffers = (VkFramebuffer *)malloc(demo->swapchainImageCount * 
                                                 sizeof(VkFramebuffer)); 
    assert(demo->framebuffers); 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        attachments[0] = demo->buffers[i].view; 
        err = vkCreateFramebuffer(demo->device, &fb_info, NULL, 
                                  &demo->framebuffers[i]); 
        assert(!err); 
    } 
} 
 
 
static void demo_prepare(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
 
 
    const VkCommandPoolCreateInfo cmd_pool_info = { 
        .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, 
        .pNext = NULL, 
        .queueFamilyIndex = demo->graphics_queue_node_index, 
        .flags = 0, 
    }; 
    err = vkCreateCommandPool(demo->device, &cmd_pool_info, NULL, 
                              &demo->cmd_pool); 
    assert(!err); 
 
 
    const VkCommandBufferAllocateInfo cmd = { 
        .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, 
        .pNext = NULL, 
        .commandPool = demo->cmd_pool, 
        .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, 
        .commandBufferCount = 1, 
    }; 
 
 
    demo_prepare_buffers(demo); 
    demo_prepare_depth(demo); 
    demo_prepare_textures(demo); 
    demo_prepare_cube_data_buffer(demo); 
 
 
    demo_prepare_descriptor_layout(demo); 
    demo_prepare_render_pass(demo); 
    demo_prepare_pipeline(demo); 
 
 
    for (uint32_t i = 0; i < demo->swapchainImageCount; i++) { 
        err = 
            vkAllocateCommandBuffers(demo->device, &cmd, &demo->buffers[i].cmd); 
        assert(!err); 
    } 
 
 
    demo_prepare_descriptor_pool(demo); 
    demo_prepare_descriptor_set(demo); 
 
 
    demo_prepare_framebuffers(demo); 
 
 
    for (uint32_t i = 0; i < demo->swapchainImageCount; i++) { 
        demo->current_buffer = i; 
        demo_draw_build_cmd(demo, demo->buffers[i].cmd); 
    } 
 
 
    /* 
     * Prepare functions above may generate pipeline commands 
     * that need to be flushed before beginning the render loop. 
     */ 
    demo_flush_init_cmd(demo); 
 
 
    demo->current_buffer = 0; 
    demo->prepared = true; 
} 
 
 
static void demo_cleanup(struct demo *demo) { 
    uint32_t i; 
 
 
    demo->prepared = false; 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL); 
    } 
    free(demo->framebuffers); 
    vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL); 
 
 
    vkDestroyPipeline(demo->device, demo->pipeline, NULL); 
    vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL); 
    vkDestroyRenderPass(demo->device, demo->render_pass, NULL); 
    vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL); 
    vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL); 
 
 
    for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { 
        vkDestroyImageView(demo->device, demo->textures[i].view, NULL); 
        vkDestroyImage(demo->device, demo->textures[i].image, NULL); 
        vkFreeMemory(demo->device, demo->textures[i].mem, NULL); 
        vkDestroySampler(demo->device, demo->textures[i].sampler, NULL); 
    } 
    demo->fpDestroySwapchainKHR(demo->device, demo->swapchain, NULL); 
 
 
    vkDestroyImageView(demo->device, demo->depth.view, NULL); 
    vkDestroyImage(demo->device, demo->depth.image, NULL); 
    vkFreeMemory(demo->device, demo->depth.mem, NULL); 
 
 
    vkDestroyBuffer(demo->device, demo->uniform_data.buf, NULL); 
    vkFreeMemory(demo->device, demo->uniform_data.mem, NULL); 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        vkDestroyImageView(demo->device, demo->buffers[i].view, NULL); 
        vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, 
                             &demo->buffers[i].cmd); 
    } 
    free(demo->buffers); 
 
 
    free(demo->queue_props); 
 
 
    vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL); 
    vkDestroyDevice(demo->device, NULL); 
    if (demo->validate) { 
        demo->DestroyDebugReportCallback(demo->inst, demo->msg_callback, NULL); 
    } 
    vkDestroySurfaceKHR(demo->inst, demo->surface, NULL); 
    vkDestroyInstance(demo->inst, NULL); 
 
 
#ifndef _WIN32 
    xcb_destroy_window(demo->connection, demo->window); 
    xcb_disconnect(demo->connection); 
    free(demo->atom_wm_delete_window); 
#endif // _WIN32 
} 
 
 
static void demo_resize(struct demo *demo) { 
    uint32_t i; 
 
 
    // Don't react to resize until after first initialization. 
    if (!demo->prepared) { 
        return; 
    } 
    // In order to properly resize the window, we must re-create the swapchain 
    // AND redo the command buffers, etc. 
    // 
    // First, perform part of the demo_cleanup() function: 
    demo->prepared = false; 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        vkDestroyFramebuffer(demo->device, demo->framebuffers[i], NULL); 
    } 
    free(demo->framebuffers); 
    vkDestroyDescriptorPool(demo->device, demo->desc_pool, NULL); 
 
 
    vkDestroyPipeline(demo->device, demo->pipeline, NULL); 
    vkDestroyPipelineCache(demo->device, demo->pipelineCache, NULL); 
    vkDestroyRenderPass(demo->device, demo->render_pass, NULL); 
    vkDestroyPipelineLayout(demo->device, demo->pipeline_layout, NULL); 
    vkDestroyDescriptorSetLayout(demo->device, demo->desc_layout, NULL); 
 
 
    for (i = 0; i < DEMO_TEXTURE_COUNT; i++) { 
        vkDestroyImageView(demo->device, demo->textures[i].view, NULL); 
        vkDestroyImage(demo->device, demo->textures[i].image, NULL); 
        vkFreeMemory(demo->device, demo->textures[i].mem, NULL); 
        vkDestroySampler(demo->device, demo->textures[i].sampler, NULL); 
    } 
 
 
    vkDestroyImageView(demo->device, demo->depth.view, NULL); 
    vkDestroyImage(demo->device, demo->depth.image, NULL); 
    vkFreeMemory(demo->device, demo->depth.mem, NULL); 
 
 
    vkDestroyBuffer(demo->device, demo->uniform_data.buf, NULL); 
    vkFreeMemory(demo->device, demo->uniform_data.mem, NULL); 
 
 
    for (i = 0; i < demo->swapchainImageCount; i++) { 
        vkDestroyImageView(demo->device, demo->buffers[i].view, NULL); 
        vkFreeCommandBuffers(demo->device, demo->cmd_pool, 1, 
                             &demo->buffers[i].cmd); 
    } 
    vkDestroyCommandPool(demo->device, demo->cmd_pool, NULL); 
    free(demo->buffers); 
 
 
    // Second, re-perform the demo_prepare() function, which will re-create the 
    // swapchain: 
    demo_prepare(demo); 
} 
 
 
// On MS-Windows, make this a global, so it's available to WndProc() 
struct demo demo; 
 
 
#ifdef _WIN32 
static void demo_run(struct demo *demo) { 
    if (!demo->prepared) 
        return; 
    // Wait for work to finish before updating MVP. 
    vkDeviceWaitIdle(demo->device); 
    demo_update_data_buffer(demo); 
 
 
    demo_draw(demo); 
 
 
    // Wait for work to finish before updating MVP. 
    vkDeviceWaitIdle(demo->device); 
 
 
    demo->curFrame++; 
 
 
    if (demo->frameCount != INT_MAX && demo->curFrame == demo->frameCount) { 
        demo->quit = true; 
        demo_cleanup(demo); 
        ExitProcess(0); 
    } 
} 
 
 
// MS-Windows event handling function: 
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { 
    switch (uMsg) { 
    case WM_CLOSE: 
        PostQuitMessage(0); 
        break; 
    case WM_PAINT: 
        demo_run(&demo); 
        break; 
    case WM_SIZE: 
        demo.width = lParam & 0xffff; 
        demo.height = lParam & 0xffff0000 >> 16; 
        demo_resize(&demo); 
        break; 
    default: 
        break; 
    } 
    return (DefWindowProc(hWnd, uMsg, wParam, lParam)); 
} 
 
 
static void demo_create_window(struct demo *demo) { 
    WNDCLASSEX win_class; 
 
 
    // Initialize the window class structure: 
    win_class.cbSize = sizeof(WNDCLASSEX); 
    win_class.style = CS_HREDRAW | CS_VREDRAW; 
    win_class.lpfnWndProc = WndProc; 
    win_class.cbClsExtra = 0; 
    win_class.cbWndExtra = 0; 
    win_class.hInstance = demo->connection; // hInstance 
    win_class.hIcon = LoadIcon(NULL, IDI_APPLICATION); 
    win_class.hCursor = LoadCursor(NULL, IDC_ARROW); 
    win_class.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); 
    win_class.lpszMenuName = NULL; 
    win_class.lpszClassName = demo->name; 
    win_class.hIconSm = LoadIcon(NULL, IDI_WINLOGO); 
    // Register window class: 
    if (!RegisterClassEx(&win_class)) { 
        // It didn't work, so try to give a useful error: 
        printf("Unexpected error trying to start the application!\n"); 
        fflush(stdout); 
        exit(1); 
    } 
    // Create window with the registered class: 
    RECT wr = {0, 0, demo->width, demo->height}; 
    AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); 
    demo->window = CreateWindowEx(0, 
                                  demo->name,           // class name 
                                  demo->name,           // app name 
                                  WS_OVERLAPPEDWINDOW | // window style 
                                      WS_VISIBLE | WS_SYSMENU, 
                                  100, 100,           // x/y coords 
                                  wr.right - wr.left, // width 
                                  wr.bottom - wr.top, // height 
                                  NULL,               // handle to parent 
                                  NULL,               // handle to menu 
                                  demo->connection,   // hInstance 
                                  NULL);              // no extra parameters 
    if (!demo->window) { 
        // It didn't work, so try to give a useful error: 
        printf("Cannot create a window in which to draw!\n"); 
        fflush(stdout); 
        exit(1); 
    } 
} 
#else  // _WIN32 
static void demo_handle_event(struct demo *demo, 
                              const xcb_generic_event_t *event) { 
    uint8_t event_code = event->response_type & 0x7f; 
    switch (event_code) { 
    case XCB_EXPOSE: 
        // TODO: Resize window 
        break; 
    case XCB_CLIENT_MESSAGE: 
        if ((*(xcb_client_message_event_t *)event).data.data32[0] == 
            (*demo->atom_wm_delete_window).atom) { 
            demo->quit = true; 
        } 
        break; 
    case XCB_KEY_RELEASE: { 
        const xcb_key_release_event_t *key = 
            (const xcb_key_release_event_t *)event; 
 
 
        switch (key->detail) { 
        case 0x9: // Escape 
            demo->quit = true; 
            break; 
        case 0x71: // left arrow key 
            demo->spin_angle += demo->spin_increment; 
            break; 
        case 0x72: // right arrow key 
            demo->spin_angle -= demo->spin_increment; 
            break; 
        case 0x41: 
            demo->pause = !demo->pause; 
            break; 
        } 
    } break; 
    case XCB_CONFIGURE_NOTIFY: { 
        const xcb_configure_notify_event_t *cfg = 
            (const xcb_configure_notify_event_t *)event; 
        if ((demo->width != cfg->width) || (demo->height != cfg->height)) { 
            demo->width = cfg->width; 
            demo->height = cfg->height; 
            demo_resize(demo); 
        } 
    } break; 
    default: 
        break; 
    } 
} 
 
 
static void demo_run(struct demo *demo) { 
    xcb_flush(demo->connection); 
 
 
    while (!demo->quit) { 
        xcb_generic_event_t *event; 
 
 
        if (demo->pause) { 
            event = xcb_wait_for_event(demo->connection); 
        } else { 
            event = xcb_poll_for_event(demo->connection); 
        } 
        if (event) { 
            demo_handle_event(demo, event); 
            free(event); 
        } 
 
 
        // Wait for work to finish before updating MVP. 
        vkDeviceWaitIdle(demo->device); 
        demo_update_data_buffer(demo); 
 
 
        demo_draw(demo); 
 
 
        // Wait for work to finish before updating MVP. 
        vkDeviceWaitIdle(demo->device); 
        demo->curFrame++; 
        if (demo->frameCount != INT32_MAX && demo->curFrame == demo->frameCount) 
            demo->quit = true; 
    } 
} 
 
 
static void demo_create_window(struct demo *demo) { 
    uint32_t value_mask, value_list[32]; 
 
 
    demo->window = xcb_generate_id(demo->connection); 
 
 
    value_mask = XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; 
    value_list[0] = demo->screen->black_pixel; 
    value_list[1] = XCB_EVENT_MASK_KEY_RELEASE | XCB_EVENT_MASK_EXPOSURE | 
                    XCB_EVENT_MASK_STRUCTURE_NOTIFY; 
 
 
    xcb_create_window(demo->connection, XCB_COPY_FROM_PARENT, demo->window, 
                      demo->screen->root, 0, 0, demo->width, demo->height, 0, 
                      XCB_WINDOW_CLASS_INPUT_OUTPUT, demo->screen->root_visual, 
                      value_mask, value_list); 
 
 
    /* Magic code that will send notification when window is destroyed */ 
    xcb_intern_atom_cookie_t cookie = 
        xcb_intern_atom(demo->connection, 1, 12, "WM_PROTOCOLS"); 
    xcb_intern_atom_reply_t *reply = 
        xcb_intern_atom_reply(demo->connection, cookie, 0); 
 
 
    xcb_intern_atom_cookie_t cookie2 = 
        xcb_intern_atom(demo->connection, 0, 16, "WM_DELETE_WINDOW"); 
    demo->atom_wm_delete_window = 
        xcb_intern_atom_reply(demo->connection, cookie2, 0); 
 
 
    xcb_change_property(demo->connection, XCB_PROP_MODE_REPLACE, demo->window, 
                        (*reply).atom, 4, 32, 1, 
                        &(*demo->atom_wm_delete_window).atom); 
    free(reply); 
 
 
    xcb_map_window(demo->connection, demo->window); 
 
 
    // Force the x/y coordinates to 100,100 results are identical in consecutive 
    // runs 
    const uint32_t coords[] = {100, 100}; 
    xcb_configure_window(demo->connection, demo->window, 
                         XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, coords); 
} 
#endif // _WIN32 
 
 
/* 
 * Return 1 (true) if all layer names specified in check_names 
 * can be found in given layer properties. 
 */ 
static VkBool32 demo_check_layers(uint32_t check_count, char **check_names, 
                                  uint32_t layer_count, 
                                  VkLayerProperties *layers) { 
    for (uint32_t i = 0; i < check_count; i++) { 
        VkBool32 found = 0; 
        for (uint32_t j = 0; j < layer_count; j++) { 
            if (!strcmp(check_names[i], layers[j].layerName)) { 
                found = 1; 
                break; 
            } 
        } 
        if (!found) { 
            fprintf(stderr, "Cannot find layer: %s\n", check_names[i]); 
            return 0; 
        } 
    } 
    return 1; 
} 
 
 
static void demo_init_vk(struct demo *demo) { 
    VkResult err; 
    char *extension_names[64]; 
    uint32_t instance_extension_count = 0; 
    uint32_t instance_layer_count = 0; 
    uint32_t device_validation_layer_count = 0; 
    uint32_t enabled_extension_count = 0; 
    uint32_t enabled_layer_count = 0; 
 
 
    char *instance_validation_layers[] = { 
        "VK_LAYER_LUNARG_threading",      "VK_LAYER_LUNARG_mem_tracker", 
        "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_draw_state", 
        "VK_LAYER_LUNARG_param_checker",  "VK_LAYER_LUNARG_swapchain", 
        "VK_LAYER_LUNARG_device_limits",  "VK_LAYER_LUNARG_image", 
        "VK_LAYER_GOOGLE_unique_objects", 
    }; 
 
 
    demo->device_validation_layers[0] = "VK_LAYER_LUNARG_threading"; 
    demo->device_validation_layers[1] = "VK_LAYER_LUNARG_mem_tracker"; 
    demo->device_validation_layers[2] = "VK_LAYER_LUNARG_object_tracker"; 
    demo->device_validation_layers[3] = "VK_LAYER_LUNARG_draw_state"; 
    demo->device_validation_layers[4] = "VK_LAYER_LUNARG_param_checker"; 
    demo->device_validation_layers[5] = "VK_LAYER_LUNARG_swapchain"; 
    demo->device_validation_layers[6] = "VK_LAYER_LUNARG_device_limits"; 
    demo->device_validation_layers[7] = "VK_LAYER_LUNARG_image"; 
    demo->device_validation_layers[8] = "VK_LAYER_GOOGLE_unique_objects"; 
    device_validation_layer_count = 9; 
 
 
    /* Look for validation layers */ 
    VkBool32 validation_found = 0; 
    err = vkEnumerateInstanceLayerProperties(&instance_layer_count, NULL); 
    assert(!err); 
 
 
    if (instance_layer_count > 0) { 
        VkLayerProperties *instance_layers = 
            malloc(sizeof(VkLayerProperties) * instance_layer_count); 
        err = vkEnumerateInstanceLayerProperties(&instance_layer_count, 
                                                 instance_layers); 
        assert(!err); 
 
 
        if (demo->validate) { 
            validation_found = demo_check_layers( 
                ARRAY_SIZE(instance_validation_layers), 
                instance_validation_layers, instance_layer_count, 
                instance_layers); 
 
 
            enabled_layer_count = ARRAY_SIZE(instance_validation_layers); 
        } 
 
 
        free(instance_layers); 
    } 
 
 
    if (demo->validate && !validation_found) { 
        ERR_EXIT("vkEnumerateInstanceLayerProperties failed to find" 
                 "required validation layer.\n\n" 
                 "Please look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateInstance Failure"); 
    } 
 
 
    /* Look for instance extensions */ 
    VkBool32 surfaceExtFound = 0; 
    VkBool32 platformSurfaceExtFound = 0; 
    memset(extension_names, 0, sizeof(extension_names)); 
 
 
    err = vkEnumerateInstanceExtensionProperties( 
        NULL, &instance_extension_count, NULL); 
    assert(!err); 
 
 
    if (instance_extension_count > 0) { 
        VkExtensionProperties *instance_extensions = 
            malloc(sizeof(VkExtensionProperties) * instance_extension_count); 
        err = vkEnumerateInstanceExtensionProperties( 
            NULL, &instance_extension_count, instance_extensions); 
        assert(!err); 
        for (uint32_t i = 0; i < instance_extension_count; i++) { 
            if (!strcmp(VK_KHR_SURFACE_EXTENSION_NAME, 
                        instance_extensions[i].extensionName)) { 
                surfaceExtFound = 1; 
                extension_names[enabled_extension_count++] = 
                    VK_KHR_SURFACE_EXTENSION_NAME; 
            } 
#ifdef _WIN32 
            if (!strcmp(VK_KHR_WIN32_SURFACE_EXTENSION_NAME, 
                        instance_extensions[i].extensionName)) { 
                platformSurfaceExtFound = 1; 
                extension_names[enabled_extension_count++] = 
                    VK_KHR_WIN32_SURFACE_EXTENSION_NAME; 
            } 
#else  // _WIN32 
            if (!strcmp(VK_KHR_XCB_SURFACE_EXTENSION_NAME, 
                        instance_extensions[i].extensionName)) { 
                platformSurfaceExtFound = 1; 
                extension_names[enabled_extension_count++] = 
                    VK_KHR_XCB_SURFACE_EXTENSION_NAME; 
            } 
#endif // _WIN32 
            if (!strcmp(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, 
                        instance_extensions[i].extensionName)) { 
                if (demo->validate) { 
                    extension_names[enabled_extension_count++] = 
                        VK_EXT_DEBUG_REPORT_EXTENSION_NAME; 
                } 
            } 
            assert(enabled_extension_count < 64); 
        } 
 
 
        free(instance_extensions); 
    } 
 
 
    if (!surfaceExtFound) { 
        ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " 
                 "the " VK_KHR_SURFACE_EXTENSION_NAME 
                 " extension.\n\nDo you have a compatible " 
                 "Vulkan installable client driver (ICD) installed?\nPlease " 
                 "look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateInstance Failure"); 
    } 
    if (!platformSurfaceExtFound) { 
#ifdef _WIN32 
        ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " 
                 "the " VK_KHR_WIN32_SURFACE_EXTENSION_NAME 
                 " extension.\n\nDo you have a compatible " 
                 "Vulkan installable client driver (ICD) installed?\nPlease " 
                 "look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateInstance Failure"); 
#else  // _WIN32 
        ERR_EXIT("vkEnumerateInstanceExtensionProperties failed to find " 
                 "the " VK_KHR_XCB_SURFACE_EXTENSION_NAME 
                 " extension.\n\nDo you have a compatible " 
                 "Vulkan installable client driver (ICD) installed?\nPlease " 
                 "look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateInstance Failure"); 
#endif // _WIN32 
    } 
    const VkApplicationInfo app = { 
        .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, 
        .pNext = NULL, 
        .pApplicationName = APP_SHORT_NAME, 
        .applicationVersion = 0, 
        .pEngineName = APP_SHORT_NAME, 
        .engineVersion = 0, 
        .apiVersion = VK_API_VERSION, 
    }; 
    VkInstanceCreateInfo inst_info = { 
        .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, 
        .pNext = NULL, 
        .pApplicationInfo = &app, 
        .enabledLayerCount = enabled_layer_count, 
        .ppEnabledLayerNames = 
            (const char *const *)((demo->validate) ? instance_validation_layers 
                                                   : NULL), 
        .enabledExtensionCount = enabled_extension_count, 
        .ppEnabledExtensionNames = (const char *const *)extension_names, 
    }; 
 
 
    uint32_t gpu_count; 
 
 
    err = vkCreateInstance(&inst_info, NULL, &demo->inst); 
    if (err == VK_ERROR_INCOMPATIBLE_DRIVER) { 
        ERR_EXIT("Cannot find a compatible Vulkan installable client driver " 
                 "(ICD).\n\nPlease look at the Getting Started guide for " 
                 "additional information.\n", 
                 "vkCreateInstance Failure"); 
    } else if (err == VK_ERROR_EXTENSION_NOT_PRESENT) { 
        ERR_EXIT("Cannot find a specified extension library" 
                 ".\nMake sure your layers path is set appropriately.\n", 
                 "vkCreateInstance Failure"); 
    } else if (err) { 
        ERR_EXIT("vkCreateInstance failed.\n\nDo you have a compatible Vulkan " 
                 "installable client driver (ICD) installed?\nPlease look at " 
                 "the Getting Started guide for additional information.\n", 
                 "vkCreateInstance Failure"); 
    } 
 
 
    /* Make initial call to query gpu_count, then second call for gpu info*/ 
    err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, NULL); 
    assert(!err && gpu_count > 0); 
 
 
    if (gpu_count > 0) { 
        VkPhysicalDevice *physical_devices = malloc(sizeof(VkPhysicalDevice) * gpu_count); 
        err = vkEnumeratePhysicalDevices(demo->inst, &gpu_count, physical_devices); 
        assert(!err); 
        /* For cube demo we just grab the first physical device */ 
        demo->gpu = physical_devices[0]; 
        free(physical_devices); 
    } else { 
        ERR_EXIT("vkEnumeratePhysicalDevices reported zero accessible devices.\n\n" 
                 "Do you have a compatible Vulkan installable client driver (ICD) " 
                 "installed?\nPlease look at the Getting Started guide for " 
                 "additional information.\n", 
                 "vkEnumeratePhysicalDevices Failure"); 
    } 
 
 
    /* Look for validation layers */ 
    validation_found = 0; 
    demo->enabled_layer_count = 0; 
    uint32_t device_layer_count = 0; 
    err = 
        vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, NULL); 
    assert(!err); 
 
 
    if (device_layer_count > 0) { 
        VkLayerProperties *device_layers = 
            malloc(sizeof(VkLayerProperties) * device_layer_count); 
        err = vkEnumerateDeviceLayerProperties(demo->gpu, &device_layer_count, 
                                               device_layers); 
        assert(!err); 
 
 
        if (demo->validate) { 
            validation_found = demo_check_layers(device_validation_layer_count, 
                                                 demo->device_validation_layers, 
                                                 device_layer_count, 
                                                 device_layers); 
            demo->enabled_layer_count = device_validation_layer_count; 
        } 
 
 
        free(device_layers); 
    } 
 
 
    if (demo->validate && !validation_found) { 
        ERR_EXIT("vkEnumerateDeviceLayerProperties failed to find" 
                 "a required validation layer.\n\n" 
                 "Please look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateDevice Failure"); 
    } 
 
 
    /* Look for device extensions */ 
    uint32_t device_extension_count = 0; 
    VkBool32 swapchainExtFound = 0; 
    demo->enabled_extension_count = 0; 
    memset(extension_names, 0, sizeof(extension_names)); 
 
 
    err = vkEnumerateDeviceExtensionProperties(demo->gpu, NULL, 
                                               &device_extension_count, NULL); 
    assert(!err); 
 
 
    if (device_extension_count > 0) { 
        VkExtensionProperties *device_extensions = 
            malloc(sizeof(VkExtensionProperties) * device_extension_count); 
        err = vkEnumerateDeviceExtensionProperties( 
            demo->gpu, NULL, &device_extension_count, device_extensions); 
        assert(!err); 
 
 
        for (uint32_t i = 0; i < device_extension_count; i++) { 
            if (!strcmp(VK_KHR_SWAPCHAIN_EXTENSION_NAME, 
                        device_extensions[i].extensionName)) { 
                swapchainExtFound = 1; 
                demo->extension_names[demo->enabled_extension_count++] = 
                    VK_KHR_SWAPCHAIN_EXTENSION_NAME; 
            } 
            assert(demo->enabled_extension_count < 64); 
        } 
 
 
        free(device_extensions); 
    } 
 
 
    if (!swapchainExtFound) { 
        ERR_EXIT("vkEnumerateDeviceExtensionProperties failed to find " 
                 "the " VK_KHR_SWAPCHAIN_EXTENSION_NAME 
                 " extension.\n\nDo you have a compatible " 
                 "Vulkan installable client driver (ICD) installed?\nPlease " 
                 "look at the Getting Started guide for additional " 
                 "information.\n", 
                 "vkCreateInstance Failure"); 
    } 
 
 
    if (demo->validate) { 
        demo->CreateDebugReportCallback = 
            (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr( 
                demo->inst, "vkCreateDebugReportCallbackEXT"); 
        demo->DestroyDebugReportCallback = 
            (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr( 
                demo->inst, "vkDestroyDebugReportCallbackEXT"); 
        if (!demo->CreateDebugReportCallback) { 
            ERR_EXIT( 
                "GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT\n", 
                "vkGetProcAddr Failure"); 
        } 
        if (!demo->DestroyDebugReportCallback) { 
            ERR_EXIT( 
                "GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT\n", 
                "vkGetProcAddr Failure"); 
        } 
        demo->DebugReportMessage = 
            (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr( 
                demo->inst, "vkDebugReportMessageEXT"); 
        if (!demo->DebugReportMessage) { 
            ERR_EXIT("GetProcAddr: Unable to find vkDebugReportMessageEXT\n", 
                     "vkGetProcAddr Failure"); 
        } 
 
 
        PFN_vkDebugReportCallbackEXT callback; 
 
 
        if (!demo->use_break) { 
            callback = dbgFunc; 
        } else { 
            callback = dbgFunc; 
            // TODO add a break callback defined locally since there is no 
            // longer 
            // one included in the loader 
        } 
        VkDebugReportCallbackCreateInfoEXT dbgCreateInfo; 
        dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT; 
        dbgCreateInfo.pNext = NULL; 
        dbgCreateInfo.pfnCallback = callback; 
        dbgCreateInfo.pUserData = NULL; 
        dbgCreateInfo.flags = 
            VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; 
        err = demo->CreateDebugReportCallback(demo->inst, &dbgCreateInfo, NULL, 
                                              &demo->msg_callback); 
        switch (err) { 
        case VK_SUCCESS: 
            break; 
        case VK_ERROR_OUT_OF_HOST_MEMORY: 
            ERR_EXIT("CreateDebugReportCallback: out of host memory\n", 
                     "CreateDebugReportCallback Failure"); 
            break; 
        default: 
            ERR_EXIT("CreateDebugReportCallback: unknown failure\n", 
                     "CreateDebugReportCallback Failure"); 
            break; 
        } 
    } 
    vkGetPhysicalDeviceProperties(demo->gpu, &demo->gpu_props); 
 
 
    /* Call with NULL data to get count */ 
    vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, 
                                             NULL); 
    assert(demo->queue_count >= 1); 
 
 
    demo->queue_props = (VkQueueFamilyProperties *)malloc( 
        demo->queue_count * sizeof(VkQueueFamilyProperties)); 
    vkGetPhysicalDeviceQueueFamilyProperties(demo->gpu, &demo->queue_count, 
                                             demo->queue_props); 
    // Find a queue that supports gfx 
    uint32_t gfx_queue_idx = 0; 
    for (gfx_queue_idx = 0; gfx_queue_idx < demo->queue_count; 
         gfx_queue_idx++) { 
        if (demo->queue_props[gfx_queue_idx].queueFlags & VK_QUEUE_GRAPHICS_BIT) 
            break; 
    } 
    assert(gfx_queue_idx < demo->queue_count); 
    // Query fine-grained feature support for this device. 
    //  If app has specific feature requirements it should check supported 
    //  features based on this query 
    VkPhysicalDeviceFeatures physDevFeatures; 
    vkGetPhysicalDeviceFeatures(demo->gpu, &physDevFeatures); 
 
 
    GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceSupportKHR); 
    GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceCapabilitiesKHR); 
    GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfaceFormatsKHR); 
    GET_INSTANCE_PROC_ADDR(demo->inst, GetPhysicalDeviceSurfacePresentModesKHR); 
    GET_INSTANCE_PROC_ADDR(demo->inst, GetSwapchainImagesKHR); 
} 
 
 
static void demo_create_device(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
    float queue_priorities[1] = {0.0}; 
    const VkDeviceQueueCreateInfo queue = { 
        .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, 
        .pNext = NULL, 
        .queueFamilyIndex = demo->graphics_queue_node_index, 
        .queueCount = 1, 
        .pQueuePriorities = queue_priorities}; 
 
 
    VkDeviceCreateInfo device = { 
        .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, 
        .pNext = NULL, 
        .queueCreateInfoCount = 1, 
        .pQueueCreateInfos = &queue, 
        .enabledLayerCount = demo->enabled_layer_count, 
        .ppEnabledLayerNames = 
            (const char *const *)((demo->validate) 
                                      ? demo->device_validation_layers 
                                      : NULL), 
        .enabledExtensionCount = demo->enabled_extension_count, 
        .ppEnabledExtensionNames = (const char *const *)demo->extension_names, 
        .pEnabledFeatures = 
            NULL, // If specific features are required, pass them in here 
    }; 
 
 
    err = vkCreateDevice(demo->gpu, &device, NULL, &demo->device); 
    assert(!err); 
} 
 
 
static void demo_init_vk_swapchain(struct demo *demo) { 
    VkResult U_ASSERT_ONLY err; 
    uint32_t i; 
 
 
// Create a WSI surface for the window: 
#ifdef _WIN32 
    VkWin32SurfaceCreateInfoKHR createInfo; 
    createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR; 
    createInfo.pNext = NULL; 
    createInfo.flags = 0; 
    createInfo.hinstance = demo->connection; 
    createInfo.hwnd = demo->window; 
 
 
    err = 
        vkCreateWin32SurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); 
 
 
#else  // _WIN32 
    VkXcbSurfaceCreateInfoKHR createInfo; 
    createInfo.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR; 
    createInfo.pNext = NULL; 
    createInfo.flags = 0; 
    createInfo.connection = demo->connection; 
    createInfo.window = demo->window; 
 
 
    err = vkCreateXcbSurfaceKHR(demo->inst, &createInfo, NULL, &demo->surface); 
#endif // _WIN32 
 
 
    // Iterate over each queue to learn whether it supports presenting: 
    VkBool32 *supportsPresent = 
        (VkBool32 *)malloc(demo->queue_count * sizeof(VkBool32)); 
    for (i = 0; i < demo->queue_count; i++) { 
        demo->fpGetPhysicalDeviceSurfaceSupportKHR(demo->gpu, i, demo->surface, 
                                                   &supportsPresent[i]); 
    } 
 
 
    // Search for a graphics and a present queue in the array of queue 
    // families, try to find one that supports both 
    uint32_t graphicsQueueNodeIndex = UINT32_MAX; 
    uint32_t presentQueueNodeIndex = UINT32_MAX; 
    for (i = 0; i < demo->queue_count; i++) { 
        if ((demo->queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0) { 
            if (graphicsQueueNodeIndex == UINT32_MAX) { 
                graphicsQueueNodeIndex = i; 
            } 
 
 
            if (supportsPresent[i] == VK_TRUE) { 
                graphicsQueueNodeIndex = i; 
                presentQueueNodeIndex = i; 
                break; 
            } 
        } 
    } 
    if (presentQueueNodeIndex == UINT32_MAX) { 
        // If didn't find a queue that supports both graphics and present, then 
        // find a separate present queue. 
        for (uint32_t i = 0; i < demo->queue_count; ++i) { 
            if (supportsPresent[i] == VK_TRUE) { 
                presentQueueNodeIndex = i; 
                break; 
            } 
        } 
    } 
    free(supportsPresent); 
 
 
    // Generate error if could not find both a graphics and a present queue 
    if (graphicsQueueNodeIndex == UINT32_MAX || 
        presentQueueNodeIndex == UINT32_MAX) { 
        ERR_EXIT("Could not find a graphics and a present queue\n", 
                 "Swapchain Initialization Failure"); 
    } 
 
 
    // TODO: Add support for separate queues, including presentation, 
    //       synchronization, and appropriate tracking for QueueSubmit. 
    // NOTE: While it is possible for an application to use a separate graphics 
    //       and a present queues, this demo program assumes it is only using 
    //       one: 
    if (graphicsQueueNodeIndex != presentQueueNodeIndex) { 
        ERR_EXIT("Could not find a common graphics and a present queue\n", 
                 "Swapchain Initialization Failure"); 
    } 
 
 
    demo->graphics_queue_node_index = graphicsQueueNodeIndex; 
 
 
    demo_create_device(demo); 
 
 
    GET_DEVICE_PROC_ADDR(demo->device, CreateSwapchainKHR); 
    GET_DEVICE_PROC_ADDR(demo->device, DestroySwapchainKHR); 
    GET_DEVICE_PROC_ADDR(demo->device, GetSwapchainImagesKHR); 
    GET_DEVICE_PROC_ADDR(demo->device, AcquireNextImageKHR); 
    GET_DEVICE_PROC_ADDR(demo->device, QueuePresentKHR); 
 
 
    vkGetDeviceQueue(demo->device, demo->graphics_queue_node_index, 0, 
                     &demo->queue); 
 
 
    // Get the list of VkFormat's that are supported: 
    uint32_t formatCount; 
    err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, 
                                                     &formatCount, NULL); 
    assert(!err); 
    VkSurfaceFormatKHR *surfFormats = 
        (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR)); 
    err = demo->fpGetPhysicalDeviceSurfaceFormatsKHR(demo->gpu, demo->surface, 
                                                     &formatCount, surfFormats); 
    assert(!err); 
    // If the format list includes just one entry of VK_FORMAT_UNDEFINED, 
    // the surface has no preferred format.  Otherwise, at least one 
    // supported format will be returned. 
    if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED) { 
        demo->format = VK_FORMAT_B8G8R8A8_UNORM; 
    } else { 
        assert(formatCount >= 1); 
        demo->format = surfFormats[0].format; 
    } 
    demo->color_space = surfFormats[0].colorSpace; 
 
 
    demo->quit = false; 
    demo->curFrame = 0; 
 
 
    // Get Memory information and properties 
    vkGetPhysicalDeviceMemoryProperties(demo->gpu, &demo->memory_properties); 
} 
 
 
static void demo_init_connection(struct demo *demo) { 
#ifndef _WIN32 
    const xcb_setup_t *setup; 
    xcb_screen_iterator_t iter; 
    int scr; 
 
 
    demo->connection = xcb_connect(NULL, &scr); 
    if (demo->connection == NULL) { 
        printf("Cannot find a compatible Vulkan installable client driver " 
               "(ICD).\nExiting ...\n"); 
        fflush(stdout); 
        exit(1); 
    } 
 
 
    setup = xcb_get_setup(demo->connection); 
    iter = xcb_setup_roots_iterator(setup); 
    while (scr-- > 0) 
        xcb_screen_next(&iter); 
 
 
    demo->screen = iter.data; 
#endif // _WIN32 
} 
 
 
static void demo_init(struct demo *demo, int argc, char **argv) { 
    vec3 eye = {0.0f, 3.0f, 5.0f}; 
    vec3 origin = {0, 0, 0}; 
    vec3 up = {0.0f, 1.0f, 0.0}; 
 
 
    memset(demo, 0, sizeof(*demo)); 
    demo->frameCount = INT32_MAX; 
 
 
    for (int i = 1; i < argc; i++) { 
        if (strcmp(argv[i], "--use_staging") == 0) { 
            demo->use_staging_buffer = true; 
            continue; 
        } 
        if (strcmp(argv[i], "--break") == 0) { 
            demo->use_break = true; 
            continue; 
        } 
        if (strcmp(argv[i], "--validate") == 0) { 
            demo->validate = true; 
            continue; 
        } 
        if (strcmp(argv[i], "--c") == 0 && demo->frameCount == INT32_MAX && 
            i < argc - 1 && sscanf(argv[i + 1], "%d", &demo->frameCount) == 1 && 
            demo->frameCount >= 0) { 
            i++; 
            continue; 
        } 
 
 
        fprintf(stderr, "Usage:\n  %s [--use_staging] [--validate] [--break] " 
                        "[--c <framecount>]\n", 
                APP_SHORT_NAME); 
        fflush(stderr); 
        exit(1); 
    } 
 
 
    demo_init_connection(demo); 
    demo_init_vk(demo); 
 
 
    demo->width = 500; 
    demo->height = 500; 
 
 
    demo->spin_angle = 0.01f; 
    demo->spin_increment = 0.01f; 
    demo->pause = false; 
 
 
    mat4x4_perspective(demo->projection_matrix, (float)degreesToRadians(45.0f), 
                       1.0f, 0.1f, 100.0f); 
    mat4x4_look_at(demo->view_matrix, eye, origin, up); 
    mat4x4_identity(demo->model_matrix); 
} 
 
 
#ifdef _WIN32 
// Include header required for parsing the command line options. 
#include <shellapi.h> 
 
 
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, 
                   int nCmdShow) { 
    MSG msg;   // message 
    bool done; // flag saying when app is complete 
    int argc; 
    char **argv; 
 
 
    // Use the CommandLine functions to get the command line arguments. 
    // Unfortunately, Microsoft outputs 
    // this information as wide characters for Unicode, and we simply want the 
    // Ascii version to be compatible 
    // with the non-Windows side.  So, we have to convert the information to 
    // Ascii character strings. 
    LPWSTR *commandLineArgs = CommandLineToArgvW(GetCommandLineW(), &argc); 
    if (NULL == commandLineArgs) { 
        argc = 0; 
    } 
 
 
    if (argc > 0) { 
        argv = (char **)malloc(sizeof(char *) * argc); 
        if (argv == NULL) { 
            argc = 0; 
        } else { 
            for (int iii = 0; iii < argc; iii++) { 
                size_t wideCharLen = wcslen(commandLineArgs[iii]); 
                size_t numConverted = 0; 
 
 
                argv[iii] = (char *)malloc(sizeof(char) * (wideCharLen + 1)); 
                if (argv[iii] != NULL) { 
                    wcstombs_s(&numConverted, argv[iii], wideCharLen + 1, 
                               commandLineArgs[iii], wideCharLen + 1); 
                } 
            } 
        } 
    } else { 
        argv = NULL; 
    } 
 
 
    demo_init(&demo, argc, argv); 
 
 
    // Free up the items we had to allocate for the command line arguments. 
    if (argc > 0 && argv != NULL) { 
        for (int iii = 0; iii < argc; iii++) { 
            if (argv[iii] != NULL) { 
                free(argv[iii]); 
            } 
        } 
        free(argv); 
    } 
 
 
    demo.connection = hInstance; 
    strncpy(demo.name, "cube", APP_NAME_STR_LEN); 
    demo_create_window(&demo); 
    demo_init_vk_swapchain(&demo); 
 
 
    demo_prepare(&demo); 
 
 
    done = false; // initialize loop condition variable 
 
 
    // main message loop 
    while (!done) { 
        PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); 
        if (msg.message == WM_QUIT) // check for a quit message 
        { 
            done = true; // if found, quit app 
        } else { 
            /* Translate and dispatch to event queue*/ 
            TranslateMessage(&msg); 
            DispatchMessage(&msg); 
        } 
        RedrawWindow(demo.window, NULL, NULL, RDW_INTERNALPAINT); 
    } 
 
 
    demo_cleanup(&demo); 
 
 
    return (int)msg.wParam; 
} 
#else  // _WIN32 
int main(int argc, char **argv) { 
    struct demo demo; 
 
 
    demo_init(&demo, argc, argv); 
    demo_create_window(&demo); 
    demo_init_vk_swapchain(&demo); 
 
 
    demo_prepare(&demo); 
    demo_run(&demo); 
 
 
    demo_cleanup(&demo); 
 
 
    return 0; 
} 
#endif // _WIN32
Avatar de RyzenOC RyzenOC - Inactif https://www.developpez.com
le 16/02/2016 à 19:29
Je code pas mal en python, je fais actuellement un jeu (projet personnel juste pour le fun) avec panda3d (qui utilise OpenGL4.3).

En résumé, tout est prévu pour démarrer tout de suite.
Je pense que dans mon cas, ils vas falloir attendre quelques mois/années avant que mes bibliothèques (Panda3D, PyOpenCL...etc) soient compatibles.

les CPU multicœurs sont sous-utilisés.
Parfois je fais des calcules sur gpu avec PyOpenCL, j'ai pas trop compris le problème de fil évoqué ?
En Python je lance des fonctions en multi-processing, ces fonctions lance des calcules sur gpu avec PyOpenCL. J'arrive à bien exploité les cpu multi-coeur.

Sinon voici 3000 lignes de code pour afficher un cube avec Vulkan :
Je crois que je vais rester avec mes librairies/surcouches Python ou j'arrive à le faire en 5 ligne

Sinon, pour mon jeu, j'avoue que le cpu est mal exploité, tous mon programme tourne sur 1 coeur , sa commence a un peut a laguer quand mon ia gere plus de 500 objets (ma carte graphique aussi).

Mais dans mon cas je bloque plus sur la fait de na pas pouvoir partager certaines variables en mémoire que sur OpenGL, je pense que l'on retrouve ce problème dans les autres moteurs de jeux.
Avatar de Aurelien Plazzotta Aurelien Plazzotta - Membre éprouvé https://www.developpez.com
le 16/02/2016 à 19:37
Bonjour,

Le titre est erroné comme à chaque fois que LittleWhite utilise Google Translate au lieu d'apprendre l'anglais; ça devient vraiment pénible.

Vulkan n'est pas le successeur mais une alternative à OpenGL car c'est une marque déposée. Le "tm" pour Trade Mark indique que le format est propriétaire. Il y aura donc une licence à payer pour ceux qui veulent commercialiser des applications graphiques en utilisant Vulkan.

Pour l'anecdote, OpenGL était hybride, un mélange de licence open source BSD et de licence propriétaire (source : http://www.sgi.com/tech/opengl/?/license.html).

A noter que les pilotes Vulkan pour chipsets graphiques AMD sont en bêta et compatibles Windows uniquement ( source : http://support.amd.com/en-us/kb-arti...lkan-Beta.aspx).
Avatar de - https://www.developpez.com
le 16/02/2016 à 20:32
Citation Envoyé par Aurelien Plazzotta Voir le message
Le titre est erroné comme à chaque fois que LittleWhite utilise Google Translate au lieu d'apprendre l'anglais; ça devient vraiment pénible.
Tu devrais peut-être faire le boulot à sa place au lieu de critiquer alors.

Pour en revenir à Vulkan, tout le monde semble présenter cela comme la nouvelle merveille du monde mais pour les développeurs c'est un retour en arrière avec une API plus bas-niveau qui va donc demander plus de travail. Avec un peu de chance, on va voir apparaitre des bibliothèques pour corriger ce problème mais ça risque de prendre encore du temps avant qu'on ait un écosystème satisfaisant pour cette technologie.
Avatar de Mc geek Mc geek - Membre régulier https://www.developpez.com
le 16/02/2016 à 21:21
Citation Envoyé par groharpon42 Voir le message

Pour en revenir à Vulkan, tout le monde semble présenter cela comme la nouvelle merveille du monde mais pour les développeurs c'est un retour en arrière avec une API plus bas-niveau qui va donc demander plus de travail. Avec un peu de chance, on va voir apparaitre des bibliothèques pour corriger ce problème mais ça risque de prendre encore du temps avant qu'on ait un écosystème satisfaisant pour cette technologie.
Et c'est le but de Vulkan justement : proposer une API bas-niveau alternative à DirectX pour permettre de mieux exploiter les capacités de la machine en étant plus proche du matériel, quitte à perdre en facilité d'écriture.
Avatar de codec_abc codec_abc - Membre averti https://www.developpez.com
le 16/02/2016 à 21:30
Citation Envoyé par Aurelien Plazzotta Voir le message
Bonjour,

Le titre est erroné comme à chaque fois que LittleWhite utilise Google Translate au lieu d'apprendre l'anglais; ça devient vraiment pénible.

Vulkan n'est pas le successeur mais une alternative à OpenGL car c'est une marque déposée. Le "tm" pour Trade Mark indique que le format est propriétaire. Il y aura donc une licence à payer pour ceux qui veulent commercialiser des applications graphiques en utilisant Vulkan.

Pour l'anecdote, OpenGL était hybride, un mélange de licence open source BSD et de licence propriétaire (source : http://www.sgi.com/tech/opengl/?/license.html).

A noter que les pilotes Vulkan pour chipsets graphiques AMD sont en bêta et compatibles Windows uniquement ( source : http://support.amd.com/en-us/kb-arti...lkan-Beta.aspx).
Je suis assez prompt à signaler aux rédacteurs quand ils se trompent mais sur ce coup il n'y a pas grand chose à redire. Alors, oui officiellement Vulkan est une alternative à OpenGL mais dans les faits c'est plutôt son successeur car :
  • C'est fait par le Khronos group qui se charge d'OpenGL. Or pourquoi il ferai une nouvelle spec si l'ancienne n'était pas d'une certaine façon obsolète ?
  • OpenGL ne permettait pas de répondre de façon satisfaisante à la programmation parallèle. Or le besoin se fait de plus en plus ressentir sur les grosses applications.


Ensuite, je veux bien que tu me cites une source qui dit qu'il y aura des licences à payer pour faire une application qui utilise l'API vulcan. Le trademark s'applique sur le logo et la spec. Ça m'étonnerai qu'il porte sur autre chose.
Enfin, parler d'open source avec OpenGL n'a pas vraiment de sens puisque OpenGL est une API et c'est les fabricants de hardware qui doivent implémenter l'interface (ce qui se traduit par l'écriture de drivers). Après certains sont open source (comme ceux d'Intel) et d'autres sont fermés (ceux d'AMD par exemple).
Avatar de LittleWhite LittleWhite - Responsable 2D/3D/Jeux https://www.developpez.com
le 16/02/2016 à 21:37
Citation Envoyé par sazearte Voir le message
Je pense que dans mon cas, ils vas falloir attendre quelques mois/années avant que mes bibliothèques (Panda3D, PyOpenCL...etc) soient compatibles.
Les développeurs de GLFW (une bibliothèque pour ouvrir une fenêtre et contexte OpenGL) commence déjà à avoir le support initial (commit GIT de ce soir, un peu après ou avant ma news).
Donc, je pense que cela sera plus une question de mois, pour les développeurs proche de ces technologies.

Parfois je fais des calcules sur gpu avec PyOpenCL, j'ai pas trop compris le problème de fil évoqué ?
Pour le calcul GPU, c'est pas le problème, car de mémoire, le calcul GPU n'est pas nourri par le CPU. Ce qui n'est pas le cas dans les programmes de rendu graphique. D'ailleurs, la suite de votre message donne argument à l'explication de la news.

EDIT : un petit outil en plus VulkanCapsViewer
Avatar de laerne laerne - Membre éprouvé https://www.developpez.com
le 16/02/2016 à 22:17
Citation Envoyé par Aurelien Plazzotta Voir le message
Le "tm" pour Trade Mark indique que le format est propriétaire. Il y aura donc une licence à payer pour ceux qui veulent commercialiser des applications graphiques en utilisant Vulkan.
Non. Trademark et licences ce n'est pas la même chose. Par exemple firefox utilise une license libre, ce qui veut dire qu'on peut le modifier et le redistribuer, mais a aussi un trademark, ce qui veut dire qu'on ne peut pas redistribuer ses modifications sous le terme “firefox”, son logo, et tout ce qui fait l'image de la marque. Ce qui explique que debian distribue “iceweasel” à la place de “firefox”.

Sinon le site dit aussi que c'est une licence proprio en disant “Copyright ©2016 Khronos Group. All rights reserved”. Mais vu que c'est qu'une API, dont la spécification est libre d'accès et d'implémentation, je vois pas trop le problème. Même si je préférerais une licence explicite.
Avatar de - https://www.developpez.com
le 17/02/2016 à 0:01
Citation Envoyé par Mc geek Voir le message
Et c'est le but de Vulkan justement : proposer une API bas-niveau alternative à DirectX pour permettre de mieux exploiter les capacités de la machine en étant plus proche du matériel, quitte à perdre en facilité d'écriture.

Oui mais la performance pure n'est pas toujours le critère principal. Quand j'ai besoin d'écrire une appli 3D toute simple, je me fiche pas mal d'avoir 400 fps au lieu de 200 (surtout quand c'est finalement synchronisé à 60 à l'écran); par contre, s'il me faut deux fois plus de temps pour l'écrire, ça devient gênant.

D'ailleurs, kronos conseille de continuer à utiliser OpenGL si on a plus besoin de facilité d'écriture que de performances. Cependant, je crains qu'à plus ou moins court terme les constructeurs ne développent plus du tout les drivers OpenGL; d'autant plus que les drivers Vulkan sont censés être beaucoup plus simples pour eux à écrire.
Avatar de Uther Uther - Expert éminent https://www.developpez.com
le 17/02/2016 à 1:29
Citation Envoyé par Aurelien Plazzotta Voir le message
Vulkan n'est pas le successeur mais une alternative à OpenGL car c'est une marque déposée. Le "tm" pour Trade Mark indique que le format est propriétaire. Il y aura donc une licence à payer pour ceux qui veulent commercialiser des applications graphiques en utilisant Vulkan.
Pour l'anecdote, OpenGL était hybride, un mélange de licence open source BSD et de licence propriétaire (source : http://www.sgi.com/tech/opengl/?/license.html).
Vulkan est en effet plus une alternative qu'un remplaçant de OpenGL. Mais ça n'a absolument rien a voir avec les raisons que tu donnes.

SGI, ne gère plus OpenGL depuis très longtemps : la gestion des spécification OpenGL ont été transférées à Khronos depuis 2006, et l'accès aux spécifications établies par Khronos est complètement libre. Après chacun est libre d'en faire une implémentation libre ou pas.

Si la marque Vulkan a été déposée s'est juste pour s'assurer que n'importe qui ne puisse pas utiliser le nom Vulkan pour des implémentations incompatibles.

Citation Envoyé par codec_abc Voir le message
C'est fait par le Khronos group qui se charge d'OpenGL. Or pourquoi il ferai une nouvelle spec si l'ancienne n'était pas d'une certaine façon obsolète ?
Ils ont annoncé qu'il continuaient a faire évoluer OpenGL.
Les deux vont cohabiter OpenGL restera pour ceux qui veulent garder une API simple qui ne requiert pas d'agir a bas niveau, Vulkan sera pour ceux qui ont besoin d'un meilleur contrôle du matériel.
Responsable bénévole de la rubrique 2D - 3D - Jeux : LittleWhite -