Hash :
1b4d6185
Author :
Date :
2024-09-12T09:18:46
Vulkan: Cleanup sRGB related code Image and image view code is littered with sRGB related enums, even in places that don't deal with sRGB. Remove sRGB related parameters from initLayerImageView and getLevelLayerDrawImageView methods, which now assume default values. Add dedicated methods that allow overriding sRGB state values. Also introduce ColorspaceState struct that consolidates all sRGB related states, this will be used in follow up changes to track and infer colorspace of image views Bug: angleproject:40644776 Change-Id: Ifb366db48043e376f9ff6c30c852c44dd96562a1 Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/5860808 Reviewed-by: Shahbaz Youssefi <syoussefi@chromium.org> Reviewed-by: Charlie Lao <cclao@google.com> Commit-Queue: mohan maiya <m.maiya@samsung.com>
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 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SurfaceVk.cpp:
// Implements the class methods for SurfaceVk.
//
#include "libANGLE/renderer/vulkan/SurfaceVk.h"
#include "common/debug.h"
#include "libANGLE/Context.h"
#include "libANGLE/Display.h"
#include "libANGLE/Overlay.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/driver_utils.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/DisplayVk.h"
#include "libANGLE/renderer/vulkan/FramebufferVk.h"
#include "libANGLE/renderer/vulkan/OverlayVk.h"
#include "libANGLE/renderer/vulkan/vk_format_utils.h"
#include "libANGLE/renderer/vulkan/vk_renderer.h"
#include "libANGLE/trace.h"
namespace rx
{
namespace
{
angle::SubjectIndex kAnySurfaceImageSubjectIndex = 0;
// Special value for currentExtent if surface size is determined by the swapchain's extent. See
// the VkSurfaceCapabilitiesKHR spec for more details.
constexpr uint32_t kSurfaceSizedBySwapchain = 0xFFFFFFFFu;
// Special value for ImagePresentOperation::imageIndex meaning that VK_EXT_swapchain_maintenance1 is
// supported and fence is used instead of queueSerial.
constexpr uint32_t kInvalidImageIndex = std::numeric_limits<uint32_t>::max();
GLint GetSampleCount(const egl::Config *config)
{
GLint samples = 1;
if (config->sampleBuffers && config->samples > 1)
{
samples = config->samples;
}
return samples;
}
vk::PresentMode GetDesiredPresentMode(const std::vector<vk::PresentMode> &presentModes,
EGLint interval)
{
ASSERT(!presentModes.empty());
// If v-sync is enabled, use FIFO, which throttles you to the display rate and is guaranteed to
// always be supported.
if (interval > 0)
{
return vk::PresentMode::FifoKHR;
}
// Otherwise, choose either of the following, if available, in order specified here:
//
// - Mailbox is similar to triple-buffering.
// - Immediate is similar to single-buffering.
//
// If neither is supported, we fallback to FIFO.
bool mailboxAvailable = false;
bool immediateAvailable = false;
bool sharedPresent = false;
for (vk::PresentMode presentMode : presentModes)
{
switch (presentMode)
{
case vk::PresentMode::MailboxKHR:
mailboxAvailable = true;
break;
case vk::PresentMode::ImmediateKHR:
immediateAvailable = true;
break;
case vk::PresentMode::SharedDemandRefreshKHR:
sharedPresent = true;
break;
default:
break;
}
}
if (mailboxAvailable)
{
return vk::PresentMode::MailboxKHR;
}
if (immediateAvailable)
{
return vk::PresentMode::ImmediateKHR;
}
if (sharedPresent)
{
return vk::PresentMode::SharedDemandRefreshKHR;
}
// Note again that VK_PRESENT_MODE_FIFO_KHR is guaranteed to be available.
return vk::PresentMode::FifoKHR;
}
uint32_t GetMinImageCount(vk::Renderer *renderer,
const VkSurfaceCapabilitiesKHR &surfaceCaps,
vk::PresentMode presentMode)
{
// - On mailbox, we need at least three images; one is being displayed to the user until the
// next v-sync, and the application alternatingly renders to the other two, one being
// recorded, and the other queued for presentation if v-sync happens in the meantime.
// - On immediate, we need at least two images; the application alternates between the two
// images.
// - On fifo, we use at least three images. Triple-buffering allows us to present an image,
// have one in the queue, and record in another. Note: on certain configurations (windows +
// nvidia + windowed mode), we could get away with a smaller number.
// For simplicity, we always allocate at least three images, unless double buffer FIFO is
// specifically preferred.
const uint32_t imageCount =
renderer->getFeatures().preferDoubleBufferSwapchainOnFifoMode.enabled &&
presentMode == vk::PresentMode::FifoKHR
? 0x2u
: 0x3u;
uint32_t minImageCount = std::max(imageCount, surfaceCaps.minImageCount);
// Make sure we don't exceed maxImageCount.
if (surfaceCaps.maxImageCount > 0 && minImageCount > surfaceCaps.maxImageCount)
{
minImageCount = surfaceCaps.maxImageCount;
}
return minImageCount;
}
constexpr VkImageUsageFlags kSurfaceVkImageUsageFlags =
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
constexpr VkImageUsageFlags kSurfaceVkColorImageUsageFlags =
kSurfaceVkImageUsageFlags | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
constexpr VkImageUsageFlags kSurfaceVkDepthStencilImageUsageFlags =
kSurfaceVkImageUsageFlags | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
// If the device is rotated with any of the following transform flags, the swapchain width and
// height must be swapped (e.g. make a landscape window portrait). This must also be done for all
// attachments used with the swapchain (i.e. depth, stencil, and multisample buffers).
constexpr VkSurfaceTransformFlagsKHR k90DegreeRotationVariants =
VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
bool Is90DegreeRotation(VkSurfaceTransformFlagsKHR transform)
{
return ((transform & k90DegreeRotationVariants) != 0);
}
bool NeedsInputAttachmentUsage(const angle::FeaturesVk &features)
{
return features.supportsShaderFramebufferFetch.enabled ||
features.supportsShaderFramebufferFetchNonCoherent.enabled ||
features.emulateAdvancedBlendEquations.enabled;
}
angle::Result InitImageHelper(DisplayVk *displayVk,
EGLint width,
EGLint height,
const vk::Format &vkFormat,
GLint samples,
bool isRobustResourceInitEnabled,
bool hasProtectedContent,
vk::ImageHelper *imageHelper)
{
const angle::Format &textureFormat = vkFormat.getActualRenderableImageFormat();
bool isDepthOrStencilFormat = textureFormat.hasDepthOrStencilBits();
VkImageUsageFlags usage = isDepthOrStencilFormat ? kSurfaceVkDepthStencilImageUsageFlags
: kSurfaceVkColorImageUsageFlags;
vk::Renderer *renderer = displayVk->getRenderer();
// If shaders may be fetching from this, we need this image to be an input
if (NeedsInputAttachmentUsage(renderer->getFeatures()))
{
usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
VkExtent3D extents = {std::max(static_cast<uint32_t>(width), 1u),
std::max(static_cast<uint32_t>(height), 1u), 1u};
angle::FormatID renderableFormatId = vkFormat.getActualRenderableImageFormatID();
// For devices that don't support creating swapchain images with RGB8, emulate with RGBA8.
if (renderer->getFeatures().overrideSurfaceFormatRGB8ToRGBA8.enabled &&
renderableFormatId == angle::FormatID::R8G8B8_UNORM)
{
renderableFormatId = angle::FormatID::R8G8B8A8_UNORM;
}
VkImageCreateFlags imageCreateFlags =
hasProtectedContent ? VK_IMAGE_CREATE_PROTECTED_BIT : vk::kVkImageCreateFlagsNone;
ANGLE_TRY(imageHelper->initExternal(
displayVk, gl::TextureType::_2D, extents, vkFormat.getIntendedFormatID(),
renderableFormatId, samples, usage, imageCreateFlags, vk::ImageLayout::Undefined, nullptr,
gl::LevelIndex(0), 1, 1, isRobustResourceInitEnabled, hasProtectedContent,
vk::YcbcrConversionDesc{}));
return angle::Result::Continue;
}
VkColorSpaceKHR MapEglColorSpaceToVkColorSpace(vk::Renderer *renderer, EGLenum EGLColorspace)
{
switch (EGLColorspace)
{
case EGL_NONE:
return VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
case EGL_GL_COLORSPACE_LINEAR:
case EGL_GL_COLORSPACE_SRGB_KHR:
return VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
case EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT:
return VK_COLOR_SPACE_DISPLAY_P3_LINEAR_EXT;
case EGL_GL_COLORSPACE_DISPLAY_P3_EXT:
case EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT:
return VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT;
case EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT:
return VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT;
case EGL_GL_COLORSPACE_SCRGB_EXT:
return VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT;
case EGL_GL_COLORSPACE_BT2020_LINEAR_EXT:
return VK_COLOR_SPACE_BT2020_LINEAR_EXT;
case EGL_GL_COLORSPACE_BT2020_PQ_EXT:
return VK_COLOR_SPACE_HDR10_ST2084_EXT;
case EGL_GL_COLORSPACE_BT2020_HLG_EXT:
return VK_COLOR_SPACE_HDR10_HLG_EXT;
default:
UNREACHABLE();
return VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
}
}
angle::Result LockSurfaceImpl(DisplayVk *displayVk,
vk::ImageHelper *image,
vk::BufferHelper &lockBufferHelper,
EGLint width,
EGLint height,
EGLint usageHint,
bool preservePixels,
uint8_t **bufferPtrOut,
EGLint *bufferPitchOut)
{
const gl::InternalFormat &internalFormat =
gl::GetSizedInternalFormatInfo(image->getActualFormat().glInternalFormat);
GLuint rowStride = image->getActualFormat().pixelBytes * width;
VkDeviceSize bufferSize =
(static_cast<VkDeviceSize>(rowStride) * static_cast<VkDeviceSize>(height));
if (!lockBufferHelper.valid() || (lockBufferHelper.getSize() != bufferSize))
{
lockBufferHelper.destroy(displayVk->getRenderer());
VkBufferCreateInfo bufferCreateInfo = {};
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.pNext = nullptr;
bufferCreateInfo.flags = 0;
bufferCreateInfo.size = bufferSize;
bufferCreateInfo.usage =
(VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufferCreateInfo.queueFamilyIndexCount = 0;
bufferCreateInfo.pQueueFamilyIndices = 0;
VkMemoryPropertyFlags memoryFlags =
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
ANGLE_TRY(lockBufferHelper.init(displayVk, bufferCreateInfo, memoryFlags));
uint8_t *bufferPtr = nullptr;
ANGLE_TRY(lockBufferHelper.map(displayVk, &bufferPtr));
}
if (lockBufferHelper.valid())
{
if (preservePixels)
{
gl::LevelIndex sourceLevelGL(0);
const VkClearColorValue *clearColor;
if (image->removeStagedClearUpdatesAndReturnColor(sourceLevelGL, &clearColor))
{
ASSERT(!image->hasStagedUpdatesForSubresource(sourceLevelGL, 0, 1));
angle::Color<uint8_t> color((uint8_t)(clearColor->float32[0] * 255.0),
(uint8_t)(clearColor->float32[1] * 255.0),
(uint8_t)(clearColor->float32[2] * 255.0),
(uint8_t)(clearColor->float32[3] * 255.0));
lockBufferHelper.fillWithColor(color, internalFormat);
}
else
{
gl::Box sourceArea(0, 0, 0, width, height, 1);
ANGLE_TRY(image->copySurfaceImageToBuffer(displayVk, sourceLevelGL, 1, 0,
sourceArea, &lockBufferHelper));
}
}
*bufferPitchOut = rowStride;
*bufferPtrOut = lockBufferHelper.getMappedMemory();
}
return angle::Result::Continue;
}
angle::Result UnlockSurfaceImpl(DisplayVk *displayVk,
vk::ImageHelper *image,
vk::BufferHelper &lockBufferHelper,
EGLint width,
EGLint height,
bool preservePixels)
{
if (preservePixels)
{
ASSERT(image->valid());
gl::Box destArea(0, 0, 0, width, height, 1);
gl::LevelIndex destLevelGL(0);
ANGLE_TRY(image->copyBufferToSurfaceImage(displayVk, destLevelGL, 1, 0, destArea,
&lockBufferHelper));
}
return angle::Result::Continue;
}
// Converts an EGL rectangle, which is relative to the bottom-left of the surface,
// to a VkRectLayerKHR, relative to Vulkan framebuffer-space, with top-left origin.
// No rotation is done to these damage rectangles per the Vulkan spec.
// The bottomLeftOrigin parameter is true on Android which assumes VkRectLayerKHR to
// have a bottom-left origin.
VkRectLayerKHR ToVkRectLayer(const EGLint *eglRect,
EGLint width,
EGLint height,
bool bottomLeftOrigin)
{
VkRectLayerKHR rect;
// Make sure the damage rects are within swapchain bounds.
rect.offset.x = gl::clamp(eglRect[0], 0, width);
if (bottomLeftOrigin)
{
// EGL rectangles are already specified with a bottom-left origin, therefore the conversion
// is trivial as we just get its Y coordinate as it is
rect.offset.y = gl::clamp(eglRect[1], 0, height);
}
else
{
rect.offset.y =
gl::clamp(height - gl::clamp(eglRect[1], 0, height) - gl::clamp(eglRect[3], 0, height),
0, height);
}
rect.extent.width = gl::clamp(eglRect[2], 0, width - rect.offset.x);
rect.extent.height = gl::clamp(eglRect[3], 0, height - rect.offset.y);
rect.layer = 0;
return rect;
}
angle::Result GetPresentModes(DisplayVk *displayVk,
VkPhysicalDevice physicalDevice,
VkSurfaceKHR surface,
std::vector<vk::PresentMode> *outPresentModes)
{
uint32_t presentModeCount = 0;
ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface,
&presentModeCount, nullptr));
ASSERT(presentModeCount > 0);
std::vector<VkPresentModeKHR> vkPresentModes(presentModeCount);
ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfacePresentModesKHR(
physicalDevice, surface, &presentModeCount, vkPresentModes.data()));
outPresentModes->resize(presentModeCount);
std::transform(begin(vkPresentModes), end(vkPresentModes), begin(*outPresentModes),
vk::ConvertVkPresentModeToPresentMode);
return angle::Result::Continue;
}
angle::Result NewSemaphore(vk::Context *context,
vk::Recycler<vk::Semaphore> *semaphoreRecycler,
vk::Semaphore *semaphoreOut)
{
if (semaphoreRecycler->empty())
{
ANGLE_VK_TRY(context, semaphoreOut->init(context->getDevice()));
}
else
{
semaphoreRecycler->fetch(semaphoreOut);
}
return angle::Result::Continue;
}
VkResult NewFence(VkDevice device, vk::Recycler<vk::Fence> *fenceRecycler, vk::Fence *fenceOut)
{
VkResult result = VK_SUCCESS;
if (fenceRecycler->empty())
{
VkFenceCreateInfo fenceCreateInfo = {};
fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceCreateInfo.flags = 0;
result = fenceOut->init(device, fenceCreateInfo);
}
else
{
fenceRecycler->fetch(fenceOut);
ASSERT(fenceOut->getStatus(device) == VK_NOT_READY);
}
return result;
}
void RecycleUsedFence(VkDevice device, vk::Recycler<vk::Fence> *fenceRecycler, vk::Fence &&fence)
{
// Reset fence now to mitigate Intel driver bug, when accessing fence after Swapchain
// destruction causes crash.
VkResult result = fence.reset(device);
if (result != VK_SUCCESS)
{
ERR() << "Fence reset failed: " << result << "! Destroying fence...";
fence.destroy(device);
return;
}
fenceRecycler->recycle(std::move(fence));
}
void AssociateQueueSerialWithPresentHistory(uint32_t imageIndex,
QueueSerial queueSerial,
std::deque<impl::ImagePresentOperation> *presentHistory)
{
// Walk the list backwards and find the entry for the given image index. That's the last
// present with that image. Associate the QueueSerial with that present operation.
for (size_t historyIndex = 0; historyIndex < presentHistory->size(); ++historyIndex)
{
impl::ImagePresentOperation &presentOperation =
(*presentHistory)[presentHistory->size() - historyIndex - 1];
// Must not use this function when VK_EXT_swapchain_maintenance1 is supported.
ASSERT(!presentOperation.fence.valid());
ASSERT(presentOperation.imageIndex != kInvalidImageIndex);
if (presentOperation.imageIndex == imageIndex)
{
ASSERT(!presentOperation.queueSerial.valid());
presentOperation.queueSerial = queueSerial;
return;
}
}
}
bool HasAnyOldSwapchains(const std::deque<impl::ImagePresentOperation> &presentHistory)
{
// Used to validate that swapchain clean up data can only be carried by the first present
// operation of a swapchain. That operation is already removed from history when this call is
// made, so this verifies that no clean up data exists in the history.
for (const impl::ImagePresentOperation &presentOperation : presentHistory)
{
if (!presentOperation.oldSwapchains.empty())
{
return true;
}
}
return false;
}
bool IsCompatiblePresentMode(vk::PresentMode mode,
VkPresentModeKHR *compatibleModes,
size_t compatibleModesCount)
{
VkPresentModeKHR vkMode = vk::ConvertPresentModeToVkPresentMode(mode);
VkPresentModeKHR *compatibleModesEnd = compatibleModes + compatibleModesCount;
return std::find(compatibleModes, compatibleModesEnd, vkMode) != compatibleModesEnd;
}
void TryAcquireNextImageUnlocked(VkDevice device,
VkSwapchainKHR swapchain,
impl::ImageAcquireOperation *acquire)
{
// Check if need to acquire before taking the lock, in case it's unnecessary.
if (!acquire->needToAcquireNextSwapchainImage)
{
return;
}
impl::UnlockedTryAcquireData *tryAcquire = &acquire->unlockedTryAcquireData;
impl::UnlockedTryAcquireResult *result = &acquire->unlockedTryAcquireResult;
std::lock_guard<angle::SimpleMutex> lock(tryAcquire->mutex);
// Check again under lock if acquire is still needed. Another thread might have done it before
// the lock is taken.
if (!acquire->needToAcquireNextSwapchainImage)
{
return;
}
result->result = VK_SUCCESS;
result->imageIndex = std::numeric_limits<uint32_t>::max();
// Get a semaphore to signal.
result->acquireSemaphore = tryAcquire->acquireImageSemaphores.front().getHandle();
// Try to acquire an image.
if (result->result == VK_SUCCESS)
{
result->result =
vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, result->acquireSemaphore,
VK_NULL_HANDLE, &result->imageIndex);
}
// Don't process the results. It will be done later when the share group lock is held.
// The contents of *result can now be used by any thread.
acquire->needToAcquireNextSwapchainImage = false;
}
// Checks whether a call to TryAcquireNextImageUnlocked has been made whose result is pending
// processing. This function is called when the share group lock is taken, so no need for
// UnlockedTryAcquireData::mutex.
bool NeedToProcessAcquireNextImageResult(const impl::UnlockedTryAcquireResult &result)
{
// TryAcquireNextImageUnlocked always creates a new acquire semaphore, use that as indication
// that there's something to process.
return result.acquireSemaphore != VK_NULL_HANDLE;
}
bool AreAllFencesSignaled(VkDevice device, const std::vector<vk::Fence> &fences)
{
for (const vk::Fence &fence : fences)
{
if (fence.getStatus(device) != VK_SUCCESS)
{
return false;
}
}
return true;
}
} // namespace
SurfaceVk::SurfaceVk(const egl::SurfaceState &surfaceState)
: SurfaceImpl(surfaceState),
mWidth(mState.attributes.getAsInt(EGL_WIDTH, 0)),
mHeight(mState.attributes.getAsInt(EGL_HEIGHT, 0))
{}
SurfaceVk::~SurfaceVk() {}
void SurfaceVk::destroy(const egl::Display *display)
{
DisplayVk *displayVk = vk::GetImpl(display);
vk::Renderer *renderer = displayVk->getRenderer();
mColorRenderTarget.destroy(renderer);
mDepthStencilRenderTarget.destroy(renderer);
}
angle::Result SurfaceVk::getAttachmentRenderTarget(const gl::Context *context,
GLenum binding,
const gl::ImageIndex &imageIndex,
GLsizei samples,
FramebufferAttachmentRenderTarget **rtOut)
{
ASSERT(samples == 0);
if (binding == GL_BACK)
{
*rtOut = &mColorRenderTarget;
}
else
{
ASSERT(binding == GL_DEPTH || binding == GL_STENCIL || binding == GL_DEPTH_STENCIL);
*rtOut = &mDepthStencilRenderTarget;
}
return angle::Result::Continue;
}
void SurfaceVk::onSubjectStateChange(angle::SubjectIndex index, angle::SubjectMessage message)
{
// Forward the notification to parent class that the staging buffer changed.
onStateChange(angle::SubjectMessage::SubjectChanged);
}
EGLint SurfaceVk::getWidth() const
{
return mWidth;
}
EGLint SurfaceVk::getHeight() const
{
return mHeight;
}
OffscreenSurfaceVk::AttachmentImage::AttachmentImage(SurfaceVk *surfaceVk)
: imageObserverBinding(surfaceVk, kAnySurfaceImageSubjectIndex)
{
imageObserverBinding.bind(&image);
}
OffscreenSurfaceVk::AttachmentImage::~AttachmentImage() = default;
angle::Result OffscreenSurfaceVk::AttachmentImage::initialize(DisplayVk *displayVk,
EGLint width,
EGLint height,
const vk::Format &vkFormat,
GLint samples,
bool isRobustResourceInitEnabled,
bool hasProtectedContent)
{
ANGLE_TRY(InitImageHelper(displayVk, width, height, vkFormat, samples,
isRobustResourceInitEnabled, hasProtectedContent, &image));
vk::Renderer *renderer = displayVk->getRenderer();
VkMemoryPropertyFlags flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
if (hasProtectedContent)
{
flags |= VK_MEMORY_PROPERTY_PROTECTED_BIT;
}
ANGLE_TRY(image.initMemoryAndNonZeroFillIfNeeded(
displayVk, hasProtectedContent, renderer->getMemoryProperties(), flags,
vk::MemoryAllocationType::OffscreenSurfaceAttachmentImage));
imageViews.init(renderer);
return angle::Result::Continue;
}
void OffscreenSurfaceVk::AttachmentImage::destroy(const egl::Display *display)
{
DisplayVk *displayVk = vk::GetImpl(display);
vk::Renderer *renderer = displayVk->getRenderer();
// Front end must ensure all usage has been submitted.
imageViews.release(renderer, image.getResourceUse());
image.releaseImage(renderer);
image.releaseStagedUpdates(renderer);
}
OffscreenSurfaceVk::OffscreenSurfaceVk(const egl::SurfaceState &surfaceState,
vk::Renderer *renderer)
: SurfaceVk(surfaceState),
mColorAttachment(this),
mDepthStencilAttachment(this)
{
mColorRenderTarget.init(&mColorAttachment.image, &mColorAttachment.imageViews, nullptr, nullptr,
{}, gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
mDepthStencilRenderTarget.init(&mDepthStencilAttachment.image,
&mDepthStencilAttachment.imageViews, nullptr, nullptr, {},
gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
}
OffscreenSurfaceVk::~OffscreenSurfaceVk() {}
egl::Error OffscreenSurfaceVk::initialize(const egl::Display *display)
{
DisplayVk *displayVk = vk::GetImpl(display);
angle::Result result = initializeImpl(displayVk);
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
angle::Result OffscreenSurfaceVk::initializeImpl(DisplayVk *displayVk)
{
vk::Renderer *renderer = displayVk->getRenderer();
const egl::Config *config = mState.config;
renderer->reloadVolkIfNeeded();
GLint samples = GetSampleCount(mState.config);
ANGLE_VK_CHECK(displayVk, samples > 0, VK_ERROR_INITIALIZATION_FAILED);
bool robustInit = mState.isRobustResourceInitEnabled();
if (config->renderTargetFormat != GL_NONE)
{
ANGLE_TRY(mColorAttachment.initialize(displayVk, mWidth, mHeight,
renderer->getFormat(config->renderTargetFormat),
samples, robustInit, mState.hasProtectedContent()));
mColorRenderTarget.init(&mColorAttachment.image, &mColorAttachment.imageViews, nullptr,
nullptr, {}, gl::LevelIndex(0), 0, 1,
RenderTargetTransience::Default);
}
if (config->depthStencilFormat != GL_NONE)
{
ANGLE_TRY(mDepthStencilAttachment.initialize(
displayVk, mWidth, mHeight, renderer->getFormat(config->depthStencilFormat), samples,
robustInit, mState.hasProtectedContent()));
mDepthStencilRenderTarget.init(&mDepthStencilAttachment.image,
&mDepthStencilAttachment.imageViews, nullptr, nullptr, {},
gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
}
return angle::Result::Continue;
}
void OffscreenSurfaceVk::destroy(const egl::Display *display)
{
mColorAttachment.destroy(display);
mDepthStencilAttachment.destroy(display);
if (mLockBufferHelper.valid())
{
mLockBufferHelper.destroy(vk::GetImpl(display)->getRenderer());
}
// Call parent class to destroy any resources parent owns.
SurfaceVk::destroy(display);
}
egl::Error OffscreenSurfaceVk::unMakeCurrent(const gl::Context *context)
{
ContextVk *contextVk = vk::GetImpl(context);
angle::Result result = contextVk->onSurfaceUnMakeCurrent(this);
return angle::ToEGL(result, EGL_BAD_CURRENT_SURFACE);
}
egl::Error OffscreenSurfaceVk::swap(const gl::Context *context)
{
return egl::NoError();
}
egl::Error OffscreenSurfaceVk::postSubBuffer(const gl::Context * /*context*/,
EGLint /*x*/,
EGLint /*y*/,
EGLint /*width*/,
EGLint /*height*/)
{
return egl::NoError();
}
egl::Error OffscreenSurfaceVk::querySurfacePointerANGLE(EGLint /*attribute*/, void ** /*value*/)
{
UNREACHABLE();
return egl::EglBadCurrentSurface();
}
egl::Error OffscreenSurfaceVk::bindTexImage(const gl::Context * /*context*/,
gl::Texture * /*texture*/,
EGLint /*buffer*/)
{
return egl::NoError();
}
egl::Error OffscreenSurfaceVk::releaseTexImage(const gl::Context * /*context*/, EGLint /*buffer*/)
{
return egl::NoError();
}
egl::Error OffscreenSurfaceVk::getSyncValues(EGLuint64KHR * /*ust*/,
EGLuint64KHR * /*msc*/,
EGLuint64KHR * /*sbc*/)
{
UNIMPLEMENTED();
return egl::EglBadAccess();
}
egl::Error OffscreenSurfaceVk::getMscRate(EGLint * /*numerator*/, EGLint * /*denominator*/)
{
UNIMPLEMENTED();
return egl::EglBadAccess();
}
void OffscreenSurfaceVk::setSwapInterval(const egl::Display *display, EGLint /*interval*/) {}
EGLint OffscreenSurfaceVk::isPostSubBufferSupported() const
{
return EGL_FALSE;
}
EGLint OffscreenSurfaceVk::getSwapBehavior() const
{
return EGL_BUFFER_DESTROYED;
}
angle::Result OffscreenSurfaceVk::initializeContents(const gl::Context *context,
GLenum binding,
const gl::ImageIndex &imageIndex)
{
ContextVk *contextVk = vk::GetImpl(context);
switch (binding)
{
case GL_BACK:
ASSERT(mColorAttachment.image.valid());
mColorAttachment.image.stageRobustResourceClear(imageIndex);
ANGLE_TRY(mColorAttachment.image.flushAllStagedUpdates(contextVk));
break;
case GL_DEPTH:
case GL_STENCIL:
ASSERT(mDepthStencilAttachment.image.valid());
mDepthStencilAttachment.image.stageRobustResourceClear(imageIndex);
ANGLE_TRY(mDepthStencilAttachment.image.flushAllStagedUpdates(contextVk));
break;
default:
UNREACHABLE();
break;
}
return angle::Result::Continue;
}
vk::ImageHelper *OffscreenSurfaceVk::getColorAttachmentImage()
{
return &mColorAttachment.image;
}
egl::Error OffscreenSurfaceVk::lockSurface(const egl::Display *display,
EGLint usageHint,
bool preservePixels,
uint8_t **bufferPtrOut,
EGLint *bufferPitchOut)
{
ANGLE_TRACE_EVENT0("gpu.angle", "OffscreenSurfaceVk::lockSurface");
vk::ImageHelper *image = &mColorAttachment.image;
ASSERT(image->valid());
angle::Result result =
LockSurfaceImpl(vk::GetImpl(display), image, mLockBufferHelper, getWidth(), getHeight(),
usageHint, preservePixels, bufferPtrOut, bufferPitchOut);
return angle::ToEGL(result, EGL_BAD_ACCESS);
}
egl::Error OffscreenSurfaceVk::unlockSurface(const egl::Display *display, bool preservePixels)
{
vk::ImageHelper *image = &mColorAttachment.image;
ASSERT(image->valid());
ASSERT(mLockBufferHelper.valid());
return angle::ToEGL(UnlockSurfaceImpl(vk::GetImpl(display), image, mLockBufferHelper,
getWidth(), getHeight(), preservePixels),
EGL_BAD_ACCESS);
}
EGLint OffscreenSurfaceVk::origin() const
{
return EGL_UPPER_LEFT_KHR;
}
egl::Error OffscreenSurfaceVk::attachToFramebuffer(const gl::Context *context,
gl::Framebuffer *framebuffer)
{
return egl::NoError();
}
egl::Error OffscreenSurfaceVk::detachFromFramebuffer(const gl::Context *context,
gl::Framebuffer *framebuffer)
{
return egl::NoError();
}
namespace impl
{
SwapchainCleanupData::SwapchainCleanupData() = default;
SwapchainCleanupData::~SwapchainCleanupData()
{
ASSERT(swapchain == VK_NULL_HANDLE);
ASSERT(fences.empty());
ASSERT(semaphores.empty());
}
SwapchainCleanupData::SwapchainCleanupData(SwapchainCleanupData &&other)
: swapchain(other.swapchain),
fences(std::move(other.fences)),
semaphores(std::move(other.semaphores))
{
other.swapchain = VK_NULL_HANDLE;
}
VkResult SwapchainCleanupData::getFencesStatus(VkDevice device) const
{
// From VkSwapchainPresentFenceInfoEXT documentation:
// Fences associated with presentations to the same swapchain on the same VkQueue must be
// signaled in the same order as the present operations.
ASSERT(!fences.empty());
VkResult result = fences.back().getStatus(device);
ASSERT(result != VK_SUCCESS || AreAllFencesSignaled(device, fences));
return result;
}
void SwapchainCleanupData::waitFences(VkDevice device, uint64_t timeout) const
{
if (!fences.empty())
{
VkResult result = fences.back().wait(device, timeout);
ASSERT(result != VK_SUCCESS || AreAllFencesSignaled(device, fences));
}
}
void SwapchainCleanupData::destroy(VkDevice device,
vk::Recycler<vk::Fence> *fenceRecycler,
vk::Recycler<vk::Semaphore> *semaphoreRecycler)
{
for (vk::Fence &fence : fences)
{
RecycleUsedFence(device, fenceRecycler, std::move(fence));
}
fences.clear();
for (vk::Semaphore &semaphore : semaphores)
{
semaphoreRecycler->recycle(std::move(semaphore));
}
semaphores.clear();
if (swapchain)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
ImagePresentOperation::ImagePresentOperation() : imageIndex(kInvalidImageIndex) {}
ImagePresentOperation::~ImagePresentOperation()
{
ASSERT(!fence.valid());
ASSERT(!semaphore.valid());
ASSERT(oldSwapchains.empty());
}
ImagePresentOperation::ImagePresentOperation(ImagePresentOperation &&other)
: fence(std::move(other.fence)),
semaphore(std::move(other.semaphore)),
imageIndex(other.imageIndex),
queueSerial(other.queueSerial),
oldSwapchains(std::move(other.oldSwapchains))
{}
ImagePresentOperation &ImagePresentOperation::operator=(ImagePresentOperation &&other)
{
std::swap(fence, other.fence);
std::swap(semaphore, other.semaphore);
std::swap(imageIndex, other.imageIndex);
std::swap(queueSerial, other.queueSerial);
std::swap(oldSwapchains, other.oldSwapchains);
return *this;
}
void ImagePresentOperation::destroy(VkDevice device,
vk::Recycler<vk::Fence> *fenceRecycler,
vk::Recycler<vk::Semaphore> *semaphoreRecycler)
{
// fence is only used when VK_EXT_swapchain_maintenance1 is supported.
if (fence.valid())
{
RecycleUsedFence(device, fenceRecycler, std::move(fence));
}
ASSERT(semaphore.valid());
semaphoreRecycler->recycle(std::move(semaphore));
// Destroy old swapchains (relevant only when VK_EXT_swapchain_maintenance1 is not supported).
for (SwapchainCleanupData &oldSwapchain : oldSwapchains)
{
oldSwapchain.destroy(device, fenceRecycler, semaphoreRecycler);
}
oldSwapchains.clear();
}
SwapchainImage::SwapchainImage() = default;
SwapchainImage::~SwapchainImage() = default;
SwapchainImage::SwapchainImage(SwapchainImage &&other)
: image(std::move(other.image)),
imageViews(std::move(other.imageViews)),
framebuffer(std::move(other.framebuffer)),
fetchFramebuffer(std::move(other.fetchFramebuffer)),
frameNumber(other.frameNumber)
{}
ImageAcquireOperation::ImageAcquireOperation() : needToAcquireNextSwapchainImage(false) {}
} // namespace impl
using namespace impl;
WindowSurfaceVk::WindowSurfaceVk(const egl::SurfaceState &surfaceState, EGLNativeWindowType window)
: SurfaceVk(surfaceState),
mNativeWindowType(window),
mSurface(VK_NULL_HANDLE),
mSupportsProtectedSwapchain(false),
mSwapchain(VK_NULL_HANDLE),
mSwapchainPresentMode(vk::PresentMode::FifoKHR),
mDesiredSwapchainPresentMode(vk::PresentMode::FifoKHR),
mMinImageCount(0),
mPreTransform(VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR),
mEmulatedPreTransform(VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR),
mCompositeAlpha(VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR),
mSurfaceColorSpace(VK_COLOR_SPACE_SRGB_NONLINEAR_KHR),
mCurrentSwapchainImageIndex(0),
mDepthStencilImageBinding(this, kAnySurfaceImageSubjectIndex),
mColorImageMSBinding(this, kAnySurfaceImageSubjectIndex),
mFrameCount(1),
mBufferAgeQueryFrameNumber(0)
{
// Initialize the color render target with the multisampled targets. If not multisampled, the
// render target will be updated to refer to a swapchain image on every acquire.
mColorRenderTarget.init(&mColorImageMS, &mColorImageMSViews, nullptr, nullptr, {},
gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
mDepthStencilRenderTarget.init(&mDepthStencilImage, &mDepthStencilImageViews, nullptr, nullptr,
{}, gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
mDepthStencilImageBinding.bind(&mDepthStencilImage);
mColorImageMSBinding.bind(&mColorImageMS);
mSwapchainStatus.isPending = false;
}
WindowSurfaceVk::~WindowSurfaceVk()
{
ASSERT(mSurface == VK_NULL_HANDLE);
ASSERT(mSwapchain == VK_NULL_HANDLE);
}
void WindowSurfaceVk::destroy(const egl::Display *display)
{
DisplayVk *displayVk = vk::GetImpl(display);
vk::Renderer *renderer = displayVk->getRenderer();
VkDevice device = renderer->getDevice();
VkInstance instance = renderer->getInstance();
// flush the pipe.
(void)renderer->waitForPresentToBeSubmitted(&mSwapchainStatus);
(void)finish(displayVk);
if (!needsAcquireImageOrProcessResult() && !mSwapchainImages.empty())
{
// swapchain image doesn't own ANI semaphore. Release ANI semaphore from image so that it
// can destroy cleanly without hitting assertion..
// Only single swapchain image may have semaphore associated.
ASSERT(mCurrentSwapchainImageIndex < mSwapchainImages.size());
mSwapchainImages[mCurrentSwapchainImageIndex].image->resetAcquireNextImageSemaphore();
}
if (mLockBufferHelper.valid())
{
mLockBufferHelper.destroy(renderer);
}
for (impl::ImagePresentOperation &presentOperation : mPresentHistory)
{
if (presentOperation.fence.valid())
{
(void)presentOperation.fence.wait(device, renderer->getMaxFenceWaitTimeNs());
}
presentOperation.destroy(device, &mPresentFenceRecycler, &mPresentSemaphoreRecycler);
}
mPresentHistory.clear();
destroySwapChainImages(displayVk);
if (mSwapchain)
{
vkDestroySwapchainKHR(device, mSwapchain, nullptr);
mSwapchain = VK_NULL_HANDLE;
}
for (vk::Semaphore &semaphore : mAcquireOperation.unlockedTryAcquireData.acquireImageSemaphores)
{
semaphore.destroy(device);
}
for (SwapchainCleanupData &oldSwapchain : mOldSwapchains)
{
oldSwapchain.waitFences(device, renderer->getMaxFenceWaitTimeNs());
oldSwapchain.destroy(device, &mPresentFenceRecycler, &mPresentSemaphoreRecycler);
}
mOldSwapchains.clear();
mPresentSemaphoreRecycler.destroy(device);
mPresentFenceRecycler.destroy(device);
// Call parent class to destroy any resources parent owns.
SurfaceVk::destroy(display);
// Destroy the surface without holding the EGL lock. This works around a specific deadlock
// in Android. On this platform:
//
// - For EGL applications, parts of surface creation and destruction are handled by the
// platform, and parts of it are done by the native EGL driver. Namely, on surface
// destruction, native_window_api_disconnect is called outside the EGL driver.
// - For Vulkan applications, vkDestroySurfaceKHR takes full responsibility for destroying
// the surface, including calling native_window_api_disconnect.
//
// Unfortunately, native_window_api_disconnect may use EGL sync objects and can lead to
// calling into the EGL driver. For ANGLE, this is particularly problematic because it is
// simultaneously a Vulkan application and the EGL driver, causing `vkDestroySurfaceKHR` to
// call back into ANGLE and attempt to reacquire the EGL lock.
//
// Since there are no users of the surface when calling vkDestroySurfaceKHR, it is safe for
// ANGLE to destroy it without holding the EGL lock, effectively simulating the situation
// for EGL applications, where native_window_api_disconnect is called after the EGL driver
// has returned.
if (mSurface)
{
egl::Display::GetCurrentThreadUnlockedTailCall()->add(
[surface = mSurface, instance](void *resultOut) {
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::destroy:vkDestroySurfaceKHR");
ANGLE_UNUSED_VARIABLE(resultOut);
vkDestroySurfaceKHR(instance, surface, nullptr);
});
mSurface = VK_NULL_HANDLE;
}
}
egl::Error WindowSurfaceVk::initialize(const egl::Display *display)
{
DisplayVk *displayVk = vk::GetImpl(display);
bool anyMatches = false;
angle::Result result = initializeImpl(displayVk, &anyMatches);
if (result == angle::Result::Continue && !anyMatches)
{
return angle::ToEGL(angle::Result::Stop, EGL_BAD_MATCH);
}
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
egl::Error WindowSurfaceVk::unMakeCurrent(const gl::Context *context)
{
ContextVk *contextVk = vk::GetImpl(context);
angle::Result result = contextVk->onSurfaceUnMakeCurrent(this);
// Even though all swap chain images are tracked individually, the semaphores are not
// tracked by ResourceUse. This propagates context's queue serial to surface when it
// detaches from context so that surface will always wait until context is finished.
mUse.merge(contextVk->getSubmittedResourceUse());
return angle::ToEGL(result, EGL_BAD_CURRENT_SURFACE);
}
angle::FormatID WindowSurfaceVk::getIntendedFormatID(vk::Renderer *renderer)
{
// Ensure that the format and colorspace pair is supported.
const vk::Format &format = renderer->getFormat(mState.config->renderTargetFormat);
return format.getIntendedFormatID();
}
angle::FormatID WindowSurfaceVk::getActualFormatID(vk::Renderer *renderer)
{
// Ensure that the format and colorspace pair is supported.
const vk::Format &format = renderer->getFormat(mState.config->renderTargetFormat);
angle::FormatID actualFormatID = format.getActualRenderableImageFormatID();
angle::FormatID intendedFormatID = format.getIntendedFormatID();
// For devices that don't support creating swapchain images with RGB8, emulate with RGBA8.
if (renderer->getFeatures().overrideSurfaceFormatRGB8ToRGBA8.enabled &&
intendedFormatID == angle::FormatID::R8G8B8_UNORM)
{
actualFormatID = angle::FormatID::R8G8B8A8_UNORM;
}
return actualFormatID;
}
bool WindowSurfaceVk::updateColorSpace(DisplayVk *displayVk)
{
vk::Renderer *renderer = displayVk->getRenderer();
VkFormat vkFormat = vk::GetVkFormatFromFormatID(getActualFormatID(renderer));
EGLenum eglColorSpaceEnum =
static_cast<EGLenum>(mState.attributes.get(EGL_GL_COLORSPACE, EGL_NONE));
// If EGL did not specify color space, we will use VK_COLOR_SPACE_PASS_THROUGH_EXT if supported.
if (eglColorSpaceEnum == EGL_NONE &&
renderer->getFeatures().mapUnspecifiedColorSpaceToPassThrough.enabled &&
displayVk->isSurfaceFormatColorspacePairSupported(mSurface, vkFormat,
VK_COLOR_SPACE_PASS_THROUGH_EXT))
{
mSurfaceColorSpace = VK_COLOR_SPACE_PASS_THROUGH_EXT;
return true;
}
mSurfaceColorSpace = MapEglColorSpaceToVkColorSpace(renderer, eglColorSpaceEnum);
return displayVk->isSurfaceFormatColorspacePairSupported(mSurface, vkFormat,
mSurfaceColorSpace);
}
angle::Result WindowSurfaceVk::initializeImpl(DisplayVk *displayVk, bool *anyMatchesOut)
{
vk::Renderer *renderer = displayVk->getRenderer();
mColorImageMSViews.init(renderer);
mDepthStencilImageViews.init(renderer);
renderer->reloadVolkIfNeeded();
gl::Extents windowSize;
ANGLE_TRY(createSurfaceVk(displayVk, &windowSize));
// Check if the selected queue created supports present to this surface.
bool presentSupported = false;
ANGLE_TRY(renderer->checkQueueForSurfacePresent(displayVk, mSurface, &presentSupported));
if (!presentSupported)
{
return angle::Result::Continue;
}
const VkPhysicalDevice &physicalDevice = renderer->getPhysicalDevice();
if (renderer->getFeatures().supportsSurfaceCapabilities2Extension.enabled)
{
VkPhysicalDeviceSurfaceInfo2KHR surfaceInfo2 = {};
surfaceInfo2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR;
surfaceInfo2.surface = mSurface;
VkSurfaceCapabilities2KHR surfaceCaps2 = {};
surfaceCaps2.sType = VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR;
VkSharedPresentSurfaceCapabilitiesKHR sharedPresentSurfaceCaps = {};
if (renderer->getFeatures().supportsSharedPresentableImageExtension.enabled)
{
sharedPresentSurfaceCaps.sType =
VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR;
sharedPresentSurfaceCaps.sharedPresentSupportedUsageFlags =
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
vk::AddToPNextChain(&surfaceCaps2, &sharedPresentSurfaceCaps);
}
VkSurfaceProtectedCapabilitiesKHR surfaceProtectedCaps = {};
if (renderer->getFeatures().supportsSurfaceProtectedCapabilitiesExtension.enabled)
{
surfaceProtectedCaps.sType = VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR;
vk::AddToPNextChain(&surfaceCaps2, &surfaceProtectedCaps);
}
ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceCapabilities2KHR(
physicalDevice, &surfaceInfo2, &surfaceCaps2));
mSurfaceCaps = surfaceCaps2.surfaceCapabilities;
mSupportsProtectedSwapchain = surfaceProtectedCaps.supportsProtected;
}
else
{
ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, mSurface,
&mSurfaceCaps));
}
if (IsAndroid())
{
mSupportsProtectedSwapchain = true;
}
ANGLE_VK_CHECK(displayVk, (mState.hasProtectedContent() ? mSupportsProtectedSwapchain : true),
VK_ERROR_FEATURE_NOT_PRESENT);
// Adjust width and height to the swapchain if necessary.
uint32_t width = mSurfaceCaps.currentExtent.width;
uint32_t height = mSurfaceCaps.currentExtent.height;
ANGLE_VK_CHECK(displayVk,
(mSurfaceCaps.supportedUsageFlags & kSurfaceVkColorImageUsageFlags) ==
kSurfaceVkColorImageUsageFlags,
VK_ERROR_INITIALIZATION_FAILED);
EGLAttrib attribWidth = mState.attributes.get(EGL_WIDTH, 0);
EGLAttrib attribHeight = mState.attributes.get(EGL_HEIGHT, 0);
if (mSurfaceCaps.currentExtent.width == kSurfaceSizedBySwapchain)
{
ASSERT(mSurfaceCaps.currentExtent.height == kSurfaceSizedBySwapchain);
width = (attribWidth != 0) ? static_cast<uint32_t>(attribWidth) : windowSize.width;
height = (attribHeight != 0) ? static_cast<uint32_t>(attribHeight) : windowSize.height;
}
gl::Extents extents(static_cast<int>(width), static_cast<int>(height), 1);
// Introduction to Android rotation and pre-rotation:
//
// Android devices have one native orientation, but a window may be displayed in a different
// orientation. This results in the window being "rotated" relative to the native orientation.
// For example, the native orientation of a Pixel 4 is portrait (i.e. height > width).
// However, many games want to be landscape (i.e. width > height). Some applications will
// adapt to whatever orientation the user places the device in (e.g. auto-rotation).
//
// A convention is used within ANGLE of referring to the "rotated" and "non-rotated" aspects of
// a topic (e.g. a window's extents, a scissor, a viewport):
//
// - Non-rotated. This refers to the way that the application views the window. Rotation is
// an Android concept, not a GL concept. An application may view its window as landscape or
// portrait, but not necessarily view its window as being rotated. For example, an
// application will set a scissor and viewport in a manner consistent with its view of the
// window size (i.e. a non-rotated manner).
//
// - Rotated. This refers to the way that Vulkan views the window. If the window's
// orientation is the same as the native orientation, the rotated view will happen to be
// equivalent to the non-rotated view, but regardless of the window's orientation, ANGLE uses
// the "rotated" term as whatever the Vulkan view of the window is.
//
// Most of ANGLE is designed to work with the non-rotated view of the window. This is
// certainly true of the ANGLE front-end. It is also true of most of the Vulkan back-end,
// which is still translating GL to Vulkan. Only part of the Vulkan back-end needs to
// communicate directly to Vulkan in terms of the window's rotation. For example, the viewport
// and scissor calculations are done with non-rotated values; and then the final values are
// rotated.
//
// ANGLE learns about the window's rotation from mSurfaceCaps.currentTransform. If
// currentTransform is non-IDENTITY, ANGLE must "pre-rotate" various aspects of its work
// (e.g. rotate vertices in the vertex shaders, change scissor, viewport, and render-pass
// renderArea). The swapchain's transform is given the value of mSurfaceCaps.currentTransform.
// That prevents SurfaceFlinger from doing a rotation blit for every frame (which is costly in
// terms of performance and power).
//
// When a window is rotated 90 or 270 degrees, the aspect ratio changes. The width and height
// are swapped. The x/y and width/height of various values in ANGLE must also be swapped
// before communicating the values to Vulkan.
if (renderer->getFeatures().enablePreRotateSurfaces.enabled)
{
// Use the surface's transform. For many platforms, this will always be identity (ANGLE
// does not need to do any pre-rotation). However, when mSurfaceCaps.currentTransform is
// not identity, the device has been rotated away from its natural orientation. In such a
// case, ANGLE must rotate all rendering in order to avoid the compositor
// (e.g. SurfaceFlinger on Android) performing an additional rotation blit. In addition,
// ANGLE must create the swapchain with VkSwapchainCreateInfoKHR::preTransform set to the
// value of mSurfaceCaps.currentTransform.
mPreTransform = mSurfaceCaps.currentTransform;
}
else
{
// Default to identity transform.
mPreTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
if ((mSurfaceCaps.supportedTransforms & mPreTransform) == 0)
{
mPreTransform = mSurfaceCaps.currentTransform;
}
}
// Set emulated pre-transform if any emulated prerotation features are set.
if (renderer->getFeatures().emulatedPrerotation90.enabled)
{
mEmulatedPreTransform = VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
}
else if (renderer->getFeatures().emulatedPrerotation180.enabled)
{
mEmulatedPreTransform = VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
}
else if (renderer->getFeatures().emulatedPrerotation270.enabled)
{
mEmulatedPreTransform = VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
}
// If prerotation is emulated, the window is physically rotated. With real prerotation, the
// surface reports the rotated sizes. With emulated prerotation however, the surface reports
// the actual window sizes. Adjust the window extents to match what real prerotation would have
// reported.
if (Is90DegreeRotation(mEmulatedPreTransform))
{
ASSERT(mPreTransform == VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR);
std::swap(extents.width, extents.height);
}
ANGLE_TRY(GetPresentModes(displayVk, physicalDevice, mSurface, &mPresentModes));
// Select appropriate present mode based on vsync parameter. Default to 1 (FIFO), though it
// will get clamped to the min/max values specified at display creation time.
setSwapInterval(displayVk, mState.getPreferredSwapInterval());
if (!updateColorSpace(displayVk))
{
return angle::Result::Continue;
}
// Android used to only advertise INHERIT bit, but might update to advertise OPAQUE bit as a
// hint for RGBX backed VK_FORMAT_R8G8B8A8_* surface format. So here we would default to the
// INHERTI bit if detecting Android and the client has explicitly requested alpha channel.
mCompositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
if (IsAndroid() && mState.config->alphaSize != 0)
{
mCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
}
if ((mSurfaceCaps.supportedCompositeAlpha & mCompositeAlpha) == 0)
{
mCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
}
ANGLE_VK_CHECK(displayVk, (mSurfaceCaps.supportedCompositeAlpha & mCompositeAlpha) != 0,
VK_ERROR_INITIALIZATION_FAILED);
// Single buffer, if supported
if ((mState.attributes.getAsInt(EGL_RENDER_BUFFER, EGL_BACK_BUFFER) == EGL_SINGLE_BUFFER) &&
supportsPresentMode(vk::PresentMode::SharedDemandRefreshKHR))
{
std::vector<vk::PresentMode> presentModes = {vk::PresentMode::SharedDemandRefreshKHR};
mDesiredSwapchainPresentMode = GetDesiredPresentMode(presentModes, 0);
}
ANGLE_TRY(createSwapChain(displayVk, extents, VK_NULL_HANDLE));
// Create the semaphores that will be used for vkAcquireNextImageKHR.
for (vk::Semaphore &semaphore : mAcquireOperation.unlockedTryAcquireData.acquireImageSemaphores)
{
ANGLE_VK_TRY(displayVk, semaphore.init(displayVk->getDevice()));
}
VkResult vkResult = acquireNextSwapchainImage(displayVk);
ASSERT(vkResult != VK_SUBOPTIMAL_KHR);
ANGLE_VK_TRY(displayVk, vkResult);
*anyMatchesOut = true;
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::getAttachmentRenderTarget(const gl::Context *context,
GLenum binding,
const gl::ImageIndex &imageIndex,
GLsizei samples,
FramebufferAttachmentRenderTarget **rtOut)
{
if (needsAcquireImageOrProcessResult())
{
// Acquire the next image (previously deferred) before it is drawn to or read from.
ContextVk *contextVk = vk::GetImpl(context);
ANGLE_VK_TRACE_EVENT_AND_MARKER(contextVk, "First Swap Image Use");
ANGLE_TRY(doDeferredAcquireNextImage(context, false));
}
return SurfaceVk::getAttachmentRenderTarget(context, binding, imageIndex, samples, rtOut);
}
angle::Result WindowSurfaceVk::recreateSwapchain(ContextVk *contextVk, const gl::Extents &extents)
{
ASSERT(!mSwapchainStatus.isPending);
// If no present operation has been done on the new swapchain, it can be destroyed right away.
// This means that a new swapchain was created, but before any of its images were presented,
// it's asked to be recreated. This can happen for example if vkQueuePresentKHR returns
// OUT_OF_DATE, the swapchain is recreated and the following vkAcquireNextImageKHR again
// returns OUT_OF_DATE. Otherwise, keep the current swapchain as the old swapchain to be
// scheduled for destruction.
//
// The old(er) swapchains still need to be kept to be scheduled for destruction.
VkSwapchainKHR swapchainToDestroy = VK_NULL_HANDLE;
if (mPresentHistory.empty())
{
// Destroy the current (never-used) swapchain.
swapchainToDestroy = mSwapchain;
}
// Place all present operation into mOldSwapchains. That gets scheduled for destruction when the
// semaphore of the first image of the next swapchain can be recycled or when fences are
// signaled (when VK_EXT_swapchain_maintenance1 is supported).
SwapchainCleanupData cleanupData;
// If the swapchain is not being immediately destroyed, schedule it for destruction.
if (swapchainToDestroy == VK_NULL_HANDLE)
{
cleanupData.swapchain = mSwapchain;
}
for (impl::ImagePresentOperation &presentOperation : mPresentHistory)
{
// fence is only used when VK_EXT_swapchain_maintenance1 is supported.
if (presentOperation.fence.valid())
{
cleanupData.fences.emplace_back(std::move(presentOperation.fence));
}
ASSERT(presentOperation.semaphore.valid());
cleanupData.semaphores.emplace_back(std::move(presentOperation.semaphore));
// Accumulate any previous swapchains that are pending destruction too.
for (SwapchainCleanupData &oldSwapchain : presentOperation.oldSwapchains)
{
mOldSwapchains.emplace_back(std::move(oldSwapchain));
}
presentOperation.oldSwapchains.clear();
}
mPresentHistory.clear();
// If too many old swapchains have accumulated, wait idle and destroy them. This is to prevent
// failures due to too many swapchains allocated.
//
// Note: Nvidia has been observed to fail creation of swapchains after 20 are allocated on
// desktop, or less than 10 on Quadro P400.
static constexpr size_t kMaxOldSwapchains = 5;
if (mOldSwapchains.size() > kMaxOldSwapchains)
{
mUse.merge(contextVk->getSubmittedResourceUse());
ANGLE_TRY(finish(contextVk));
for (SwapchainCleanupData &oldSwapchain : mOldSwapchains)
{
oldSwapchain.waitFences(contextVk->getDevice(),
contextVk->getRenderer()->getMaxFenceWaitTimeNs());
oldSwapchain.destroy(contextVk->getDevice(), &mPresentFenceRecycler,
&mPresentSemaphoreRecycler);
}
mOldSwapchains.clear();
}
if (cleanupData.swapchain != VK_NULL_HANDLE || !cleanupData.fences.empty() ||
!cleanupData.semaphores.empty())
{
mOldSwapchains.emplace_back(std::move(cleanupData));
}
// Recreate the swapchain based on the most recent one.
VkSwapchainKHR lastSwapchain = mSwapchain;
mSwapchain = VK_NULL_HANDLE;
releaseSwapchainImages(contextVk);
// If prerotation is emulated, adjust the window extents to match what real prerotation would
// have reported.
gl::Extents swapchainExtents = extents;
if (Is90DegreeRotation(mEmulatedPreTransform))
{
ASSERT(mPreTransform == VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR);
std::swap(swapchainExtents.width, swapchainExtents.height);
}
// On Android, vkCreateSwapchainKHR destroys lastSwapchain, which is incorrect. Wait idle in
// that case as a workaround.
if (lastSwapchain &&
contextVk->getRenderer()->getFeatures().waitIdleBeforeSwapchainRecreation.enabled)
{
mUse.merge(contextVk->getSubmittedResourceUse());
ANGLE_TRY(finish(contextVk));
}
angle::Result result = createSwapChain(contextVk, swapchainExtents, lastSwapchain);
// Notify the parent classes of the surface's new state.
onStateChange(angle::SubjectMessage::SurfaceChanged);
// If the most recent swapchain was never used, destroy it right now.
if (swapchainToDestroy)
{
vkDestroySwapchainKHR(contextVk->getDevice(), swapchainToDestroy, nullptr);
}
return result;
}
angle::Result WindowSurfaceVk::resizeSwapchainImages(vk::Context *context, uint32_t imageCount)
{
if (static_cast<size_t>(imageCount) != mSwapchainImages.size())
{
mSwapchainImageBindings.clear();
mSwapchainImages.resize(imageCount);
// Update the image bindings. Because the observer binding class uses raw pointers we
// need to first ensure the entire image vector is fully allocated before binding the
// subject and observer together.
for (uint32_t index = 0; index < imageCount; ++index)
{
mSwapchainImageBindings.push_back(
angle::ObserverBinding(this, kAnySurfaceImageSubjectIndex));
}
for (uint32_t index = 0; index < imageCount; ++index)
{
mSwapchainImages[index].image = std::make_unique<vk::ImageHelper>();
mSwapchainImageBindings[index].bind(mSwapchainImages[index].image.get());
}
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::createSwapChain(vk::Context *context,
const gl::Extents &extents,
VkSwapchainKHR lastSwapchain)
{
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::createSwapchain");
ASSERT(mSwapchain == VK_NULL_HANDLE);
vk::Renderer *renderer = context->getRenderer();
VkDevice device = renderer->getDevice();
const vk::Format &format = renderer->getFormat(mState.config->renderTargetFormat);
gl::Extents rotatedExtents = extents;
if (Is90DegreeRotation(getPreTransform()))
{
// The Surface is oriented such that its aspect ratio no longer matches that of the
// device. In this case, the width and height of the swapchain images must be swapped to
// match the device's native orientation. This must also be done for other attachments
// used with the swapchain (e.g. depth buffer). The width and height of the viewport,
// scissor, and render-pass render area must also be swapped. Then, when ANGLE rotates
// gl_Position in the vertex shader, the rendering will look the same as if no
// pre-rotation had been done.
std::swap(rotatedExtents.width, rotatedExtents.height);
}
// We need transfer src for reading back from the backbuffer.
VkImageUsageFlags imageUsageFlags = kSurfaceVkColorImageUsageFlags;
// If shaders may be fetching from this, we need this image to be an input
if (NeedsInputAttachmentUsage(renderer->getFeatures()))
{
imageUsageFlags |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
VkSwapchainCreateInfoKHR swapchainInfo = {};
swapchainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainInfo.flags = mState.hasProtectedContent() ? VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR : 0;
swapchainInfo.surface = mSurface;
swapchainInfo.minImageCount = mMinImageCount;
swapchainInfo.imageFormat = vk::GetVkFormatFromFormatID(getActualFormatID(renderer));
swapchainInfo.imageColorSpace = mSurfaceColorSpace;
// Note: Vulkan doesn't allow 0-width/height swapchains.
swapchainInfo.imageExtent.width = std::max(rotatedExtents.width, 1);
swapchainInfo.imageExtent.height = std::max(rotatedExtents.height, 1);
swapchainInfo.imageArrayLayers = 1;
swapchainInfo.imageUsage = imageUsageFlags;
swapchainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchainInfo.queueFamilyIndexCount = 0;
swapchainInfo.pQueueFamilyIndices = nullptr;
swapchainInfo.preTransform = mPreTransform;
swapchainInfo.compositeAlpha = mCompositeAlpha;
swapchainInfo.presentMode = vk::ConvertPresentModeToVkPresentMode(mDesiredSwapchainPresentMode);
swapchainInfo.clipped = VK_TRUE;
swapchainInfo.oldSwapchain = lastSwapchain;
#if defined(ANGLE_PLATFORM_WINDOWS)
// On some AMD drivers we need to explicitly enable the extension and set
// it to "disallowed" mode in order to avoid seeing impossible-to-handle
// extension-specific error codes from swapchain functions.
VkSurfaceFullScreenExclusiveInfoEXT fullscreen = {};
fullscreen.sType = VK_STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_INFO_EXT;
fullscreen.fullScreenExclusive = VK_FULL_SCREEN_EXCLUSIVE_DISALLOWED_EXT;
VkSurfaceFullScreenExclusiveWin32InfoEXT fullscreenWin32 = {};
fullscreenWin32.sType = VK_STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_WIN32_INFO_EXT;
fullscreenWin32.hmonitor = MonitorFromWindow((HWND)mNativeWindowType, MONITOR_DEFAULTTONEAREST);
if (renderer->getFeatures().supportsFullScreenExclusive.enabled &&
renderer->getFeatures().forceDisableFullScreenExclusive.enabled)
{
vk::AddToPNextChain(&swapchainInfo, &fullscreen);
vk::AddToPNextChain(&swapchainInfo, &fullscreenWin32);
}
#endif
if (context->getFeatures().supportsSwapchainMaintenance1.enabled)
{
swapchainInfo.flags |= VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT;
}
if (isSharedPresentModeDesired())
{
swapchainInfo.minImageCount = 1;
// This feature is by default disabled, and only affects Android platform wsi behavior
// transparent to angle internal tracking for shared present.
if (renderer->getFeatures().forceContinuousRefreshOnSharedPresent.enabled)
{
swapchainInfo.presentMode = VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
}
}
// Get the list of compatible present modes to avoid unnecessary swapchain recreation. Also
// update minImageCount with the per-present limit.
if (renderer->getFeatures().supportsSurfaceMaintenance1.enabled)
{
VkPhysicalDeviceSurfaceInfo2KHR surfaceInfo2 = {};
surfaceInfo2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR;
surfaceInfo2.surface = mSurface;
VkSurfacePresentModeEXT surfacePresentMode = {};
surfacePresentMode.sType = VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT;
surfacePresentMode.presentMode = swapchainInfo.presentMode;
vk::AddToPNextChain(&surfaceInfo2, &surfacePresentMode);
VkSurfaceCapabilities2KHR surfaceCaps2 = {};
surfaceCaps2.sType = VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR;
mCompatiblePresentModes.resize(kMaxCompatiblePresentModes);
VkSurfacePresentModeCompatibilityEXT compatibleModes = {};
compatibleModes.sType = VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT;
compatibleModes.presentModeCount = kMaxCompatiblePresentModes;
compatibleModes.pPresentModes = mCompatiblePresentModes.data();
vk::AddToPNextChain(&surfaceCaps2, &compatibleModes);
ANGLE_VK_TRY(context, vkGetPhysicalDeviceSurfaceCapabilities2KHR(
renderer->getPhysicalDevice(), &surfaceInfo2, &surfaceCaps2));
mCompatiblePresentModes.resize(compatibleModes.presentModeCount);
// The implementation must always return the given present mode as compatible with itself.
ASSERT(IsCompatiblePresentMode(mDesiredSwapchainPresentMode, mCompatiblePresentModes.data(),
mCompatiblePresentModes.size()));
// Vulkan spec says "The per-present mode image counts may be less-than or greater-than the
// image counts returned when VkSurfacePresentModeEXT is not provided.". Use the per present
// mode imageCount here. Otherwise we may get into
// VUID-VkSwapchainCreateInfoKHR-presentMode-02839.
mSurfaceCaps = surfaceCaps2.surfaceCapabilities;
mMinImageCount = GetMinImageCount(renderer, mSurfaceCaps, mDesiredSwapchainPresentMode);
swapchainInfo.minImageCount = mMinImageCount;
}
VkSwapchainPresentModesCreateInfoEXT compatibleModesInfo = {};
if (renderer->getFeatures().supportsSwapchainMaintenance1.enabled)
{
if (mCompatiblePresentModes.size() > 1)
{
compatibleModesInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODES_CREATE_INFO_EXT;
compatibleModesInfo.presentModeCount =
static_cast<uint32_t>(mCompatiblePresentModes.size());
compatibleModesInfo.pPresentModes = mCompatiblePresentModes.data();
vk::AddToPNextChain(&swapchainInfo, &compatibleModesInfo);
}
}
else
{
// Without VK_EXT_swapchain_maintenance1, each present mode can be considered only
// compatible with itself.
mCompatiblePresentModes.resize(1);
mCompatiblePresentModes[0] = swapchainInfo.presentMode;
}
// TODO: Once EGL_SWAP_BEHAVIOR_PRESERVED_BIT is supported, the contents of the old swapchain
// need to carry over to the new one. http://anglebug.com/42261637
VkSwapchainKHR newSwapChain = VK_NULL_HANDLE;
ANGLE_VK_TRY(context, vkCreateSwapchainKHR(device, &swapchainInfo, nullptr, &newSwapChain));
mSwapchain = newSwapChain;
mSwapchainPresentMode = mDesiredSwapchainPresentMode;
mWidth = extents.width;
mHeight = extents.height;
// If frame timestamp was enabled for the surface, [re]enable it when [re]creating the swapchain
if (renderer->getFeatures().supportsTimestampSurfaceAttribute.enabled &&
mState.timestampsEnabled)
{
// The implementation of "vkGetPastPresentationTimingGOOGLE" on Android calls into the
// appropriate ANativeWindow API that enables frame timestamps.
uint32_t count = 0;
ANGLE_VK_TRY(context,
vkGetPastPresentationTimingGOOGLE(device, mSwapchain, &count, nullptr));
}
// Initialize the swapchain image views.
uint32_t imageCount = 0;
ANGLE_VK_TRY(context, vkGetSwapchainImagesKHR(device, mSwapchain, &imageCount, nullptr));
std::vector<VkImage> swapchainImages(imageCount);
ANGLE_VK_TRY(context,
vkGetSwapchainImagesKHR(device, mSwapchain, &imageCount, swapchainImages.data()));
// If multisampling is enabled, create a multisampled image which gets resolved just prior to
// present.
GLint samples = GetSampleCount(mState.config);
ANGLE_VK_CHECK(context, samples > 0, VK_ERROR_INITIALIZATION_FAILED);
VkExtent3D vkExtents;
gl_vk::GetExtent(rotatedExtents, &vkExtents);
bool robustInit = mState.isRobustResourceInitEnabled();
if (samples > 1)
{
VkImageUsageFlags usage = kSurfaceVkColorImageUsageFlags;
if (NeedsInputAttachmentUsage(renderer->getFeatures()))
{
usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
}
// Create a multisampled image that will be rendered to, and then resolved to a swapchain
// image. The actual VkImage is created with rotated coordinates to make it easier to do
// the resolve. The ImageHelper::mExtents will have non-rotated extents in order to fit
// with the rest of ANGLE, (e.g. which calculates the Vulkan scissor with non-rotated
// values and then rotates the final rectangle).
ANGLE_TRY(mColorImageMS.initMSAASwapchain(
context, gl::TextureType::_2D, vkExtents, Is90DegreeRotation(getPreTransform()), format,
samples, usage, gl::LevelIndex(0), 1, 1, robustInit, mState.hasProtectedContent()));
ANGLE_TRY(mColorImageMS.initMemoryAndNonZeroFillIfNeeded(
context, mState.hasProtectedContent(), renderer->getMemoryProperties(),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vk::MemoryAllocationType::SwapchainMSAAImage));
// Initialize the color render target with the multisampled targets. If not multisampled,
// the render target will be updated to refer to a swapchain image on every acquire.
mColorRenderTarget.init(&mColorImageMS, &mColorImageMSViews, nullptr, nullptr, {},
gl::LevelIndex(0), 0, 1, RenderTargetTransience::Default);
}
ANGLE_TRY(resizeSwapchainImages(context, imageCount));
for (uint32_t imageIndex = 0; imageIndex < imageCount; ++imageIndex)
{
SwapchainImage &member = mSwapchainImages[imageIndex];
// Convert swapchain create flags to image create flags
const VkImageCreateFlags createFlags =
(swapchainInfo.flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) != 0
? VK_IMAGE_CREATE_PROTECTED_BIT
: 0;
ASSERT(member.image);
member.image->init2DWeakReference(
context, swapchainImages[imageIndex], extents, Is90DegreeRotation(getPreTransform()),
getIntendedFormatID(renderer), getActualFormatID(renderer), createFlags,
imageUsageFlags, 1, robustInit);
member.imageViews.init(renderer);
member.frameNumber = 0;
}
// Initialize depth/stencil if requested.
if (mState.config->depthStencilFormat != GL_NONE)
{
const vk::Format &dsFormat = renderer->getFormat(mState.config->depthStencilFormat);
const VkImageUsageFlags dsUsage = kSurfaceVkDepthStencilImageUsageFlags;
ANGLE_TRY(mDepthStencilImage.init(context, gl::TextureType::_2D, vkExtents, dsFormat,
samples, dsUsage, gl::LevelIndex(0), 1, 1, robustInit,
mState.hasProtectedContent()));
ANGLE_TRY(mDepthStencilImage.initMemoryAndNonZeroFillIfNeeded(
context, mState.hasProtectedContent(), renderer->getMemoryProperties(),
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
vk::MemoryAllocationType::SwapchainDepthStencilImage));
mDepthStencilRenderTarget.init(&mDepthStencilImage, &mDepthStencilImageViews, nullptr,
nullptr, {}, gl::LevelIndex(0), 0, 1,
RenderTargetTransience::Default);
// We will need to pass depth/stencil image views to the RenderTargetVk in the future.
}
// Need to acquire a new image before the swapchain can be used.
mAcquireOperation.needToAcquireNextSwapchainImage = true;
return angle::Result::Continue;
}
bool WindowSurfaceVk::isMultiSampled() const
{
return mColorImageMS.valid();
}
angle::Result WindowSurfaceVk::queryAndAdjustSurfaceCaps(ContextVk *contextVk,
VkSurfaceCapabilitiesKHR *surfaceCaps)
{
vk::Renderer *renderer = contextVk->getRenderer();
const VkPhysicalDevice &physicalDevice = renderer->getPhysicalDevice();
if (renderer->getFeatures().supportsSwapchainMaintenance1.enabled)
{
VkPhysicalDeviceSurfaceInfo2KHR surfaceInfo2 = {};
surfaceInfo2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR;
surfaceInfo2.surface = mSurface;
VkSurfacePresentModeEXT surfacePresentMode = {};
surfacePresentMode.sType = VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT;
surfacePresentMode.presentMode =
vk::ConvertPresentModeToVkPresentMode(mDesiredSwapchainPresentMode);
vk::AddToPNextChain(&surfaceInfo2, &surfacePresentMode);
VkSurfaceCapabilities2KHR surfaceCaps2 = {};
surfaceCaps2.sType = VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR;
ANGLE_VK_TRY(contextVk, vkGetPhysicalDeviceSurfaceCapabilities2KHR(
renderer->getPhysicalDevice(), &surfaceInfo2, &surfaceCaps2));
*surfaceCaps = surfaceCaps2.surfaceCapabilities;
}
else
{
ANGLE_VK_TRY(contextVk, vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, mSurface,
surfaceCaps));
}
if (surfaceCaps->currentExtent.width == kSurfaceSizedBySwapchain)
{
ASSERT(surfaceCaps->currentExtent.height == kSurfaceSizedBySwapchain);
ASSERT(!IsAndroid());
// vkGetPhysicalDeviceSurfaceCapabilitiesKHR does not provide useful extents for some
// platforms (e.g. Fuschia). Therefore, we must query the window size via a
// platform-specific mechanism. Add those extents to the surfaceCaps
gl::Extents currentExtents;
ANGLE_TRY(getCurrentWindowSize(contextVk, ¤tExtents));
surfaceCaps->currentExtent.width = currentExtents.width;
surfaceCaps->currentExtent.height = currentExtents.height;
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::checkForOutOfDateSwapchain(ContextVk *contextVk,
bool presentOutOfDate)
{
bool swapIntervalChanged =
!IsCompatiblePresentMode(mDesiredSwapchainPresentMode, mCompatiblePresentModes.data(),
mCompatiblePresentModes.size());
presentOutOfDate = presentOutOfDate || swapIntervalChanged;
// If there's no change, early out.
if (!contextVk->getRenderer()->getFeatures().perFrameWindowSizeQuery.enabled &&
!presentOutOfDate)
{
return angle::Result::Continue;
}
// Get the latest surface capabilities.
ANGLE_TRY(queryAndAdjustSurfaceCaps(contextVk, &mSurfaceCaps));
if (contextVk->getRenderer()->getFeatures().perFrameWindowSizeQuery.enabled)
{
// On Android, rotation can cause the minImageCount to change
uint32_t minImageCount =
GetMinImageCount(contextVk->getRenderer(), mSurfaceCaps, mDesiredSwapchainPresentMode);
if (mMinImageCount != minImageCount)
{
presentOutOfDate = true;
mMinImageCount = minImageCount;
}
if (!presentOutOfDate)
{
// This device generates neither VK_ERROR_OUT_OF_DATE_KHR nor VK_SUBOPTIMAL_KHR. Check
// for whether the size and/or rotation have changed since the swapchain was created.
uint32_t swapchainWidth = getWidth();
uint32_t swapchainHeight = getHeight();
presentOutOfDate = mSurfaceCaps.currentTransform != mPreTransform ||
mSurfaceCaps.currentExtent.width != swapchainWidth ||
mSurfaceCaps.currentExtent.height != swapchainHeight;
}
}
// If anything has changed, recreate the swapchain.
if (!presentOutOfDate)
{
return angle::Result::Continue;
}
gl::Extents newSwapchainExtents(mSurfaceCaps.currentExtent.width,
mSurfaceCaps.currentExtent.height, 1);
if (contextVk->getFeatures().enablePreRotateSurfaces.enabled)
{
// Update the surface's transform, which can change even if the window size does not.
mPreTransform = mSurfaceCaps.currentTransform;
}
return recreateSwapchain(contextVk, newSwapchainExtents);
}
void WindowSurfaceVk::releaseSwapchainImages(ContextVk *contextVk)
{
vk::Renderer *renderer = contextVk->getRenderer();
mColorRenderTarget.releaseImageAndViews(contextVk);
mDepthStencilRenderTarget.releaseImageAndViews(contextVk);
if (mDepthStencilImage.valid())
{
mDepthStencilImageViews.release(renderer, mDepthStencilImage.getResourceUse());
mDepthStencilImage.releaseImageFromShareContexts(renderer, contextVk, {});
mDepthStencilImage.releaseStagedUpdates(renderer);
}
if (mColorImageMS.valid())
{
mColorImageMSViews.release(renderer, mColorImageMS.getResourceUse());
mColorImageMS.releaseImageFromShareContexts(renderer, contextVk, {});
mColorImageMS.releaseStagedUpdates(renderer);
contextVk->addGarbage(&mFramebufferMS);
}
mSwapchainImageBindings.clear();
for (SwapchainImage &swapchainImage : mSwapchainImages)
{
ASSERT(swapchainImage.image);
swapchainImage.imageViews.release(renderer, swapchainImage.image->getResourceUse());
// swapchain image must not have ANI semaphore assigned here, since acquired image must be
// presented before swapchain recreation.
swapchainImage.image->resetImageWeakReference();
swapchainImage.image->destroy(renderer);
contextVk->addGarbage(&swapchainImage.framebuffer);
if (swapchainImage.fetchFramebuffer.valid())
{
contextVk->addGarbage(&swapchainImage.fetchFramebuffer);
}
}
mSwapchainImages.clear();
}
angle::Result WindowSurfaceVk::finish(vk::Context *context)
{
vk::Renderer *renderer = context->getRenderer();
mUse.merge(mDepthStencilImage.getResourceUse());
mUse.merge(mColorImageMS.getResourceUse());
for (SwapchainImage &swapchainImage : mSwapchainImages)
{
mUse.merge(swapchainImage.image->getResourceUse());
}
return renderer->finishResourceUse(context, mUse);
}
void WindowSurfaceVk::destroySwapChainImages(DisplayVk *displayVk)
{
vk::Renderer *renderer = displayVk->getRenderer();
VkDevice device = displayVk->getDevice();
mDepthStencilImage.destroy(renderer);
mDepthStencilImageViews.destroy(device);
mColorImageMS.destroy(renderer);
mColorImageMSViews.destroy(device);
mFramebufferMS.destroy(device);
for (SwapchainImage &swapchainImage : mSwapchainImages)
{
ASSERT(swapchainImage.image);
// swapchain image must not have ANI semaphore assigned here, because it should be released
// in the destroy() prior to calling this method.
// We don't own the swapchain image handles, so we just remove our reference to it.
swapchainImage.image->resetImageWeakReference();
swapchainImage.image->destroy(renderer);
swapchainImage.imageViews.destroy(device);
swapchainImage.framebuffer.destroy(device);
if (swapchainImage.fetchFramebuffer.valid())
{
swapchainImage.fetchFramebuffer.destroy(device);
}
}
mSwapchainImages.clear();
}
egl::Error WindowSurfaceVk::prepareSwap(const gl::Context *context)
{
// Image is only required to be acquired here in case of a blocking present modes (FIFO).
// However, we will acquire the image in any case, for simplicity and possibly for performance.
if (!mAcquireOperation.needToAcquireNextSwapchainImage)
{
return egl::NoError();
}
vk::Renderer *renderer = vk::GetImpl(context)->getRenderer();
angle::Result result = prepareForAcquireNextSwapchainImage(context, false);
if (result != angle::Result::Continue)
{
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
// |mColorRenderTarget| may be invalid at this point (in case of swapchain recreate above),
// however it will not be accessed until update in the |postProcessUnlockedTryAcquire| call.
// Must check present mode after the above prepare (in case of swapchain recreate).
if (isSharedPresentMode())
{
// Shared present mode requires special handling, because it requires use of
// |skipAcquireNextSwapchainImageForSharedPresentMode| method.
// Below call is not going to block.
result = doDeferredAcquireNextImageWithUsableSwapchain(context);
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
// Call vkAcquireNextImageKHR without holding the share group lock. The following are accessed
// by this function:
//
// - mAcquireOperation.needToAcquireNextSwapchainImage, which is atomic
// - Contents of mAcquireOperation.unlockedTryAcquireData and
// mAcquireOperation.unlockedTryAcquireResult, which are protected by
// unlockedTryAcquireData.mutex
// - context->getDevice(), which doesn't need external synchronization
// - mSwapchain
//
// The latter two are also protected by unlockedTryAcquireData.mutex during this call. Note
// that due to the presence of needToAcquireNextSwapchainImage, the threads may be in either of
// these states:
//
// 1. Calling eglPrepareSwapBuffersANGLE; in this case, they are accessing mSwapchain protected
// by the aforementioned mutex
// 2. Calling doDeferredAcquireNextImage() through an EGL/GL call
// * If needToAcquireNextSwapchainImage is true, these variables are protected by the same
// mutex in the same TryAcquireNextImageUnlocked call.
// * If needToAcquireNextSwapchainImage is false, these variables are not protected by this
// mutex. However, in this case no thread could be calling TryAcquireNextImageUnlocked
// because needToAcquireNextSwapchainImage is false (and hence there is no data race).
// Note that needToAcquireNextSwapchainImage's atomic store and load ensure
// availability/visibility of changes to these variables between threads.
//
// The result of this call is processed in doDeferredAcquireNextImage() by whoever ends up
// calling it (likely the eglSwapBuffers call that follows)
egl::Display::GetCurrentThreadUnlockedTailCall()->add(
[device = renderer->getDevice(), swapchain = mSwapchain,
acquire = &mAcquireOperation](void *resultOut) {
ANGLE_TRACE_EVENT0("gpu.angle", "Acquire Swap Image Before Swap");
ANGLE_UNUSED_VARIABLE(resultOut);
TryAcquireNextImageUnlocked(device, swapchain, acquire);
});
return egl::NoError();
}
egl::Error WindowSurfaceVk::swapWithDamage(const gl::Context *context,
const EGLint *rects,
EGLint n_rects)
{
const angle::Result result = swapImpl(context, rects, n_rects, nullptr);
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
egl::Error WindowSurfaceVk::swap(const gl::Context *context)
{
// When in shared present mode, eglSwapBuffers is unnecessary except for mode change. When mode
// change is not expected, the eglSwapBuffers call is forwarded to the context as a glFlush.
// This allows the context to skip it if there's nothing to flush. Otherwise control is bounced
// back swapImpl().
//
// Some apps issue eglSwapBuffers after glFlush unnecessary, causing the CPU throttling logic to
// effectively wait for the just submitted commands.
if (isSharedPresentMode() && mSwapchainPresentMode == mDesiredSwapchainPresentMode)
{
const angle::Result result = vk::GetImpl(context)->flush(context);
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
const angle::Result result = swapImpl(context, nullptr, 0, nullptr);
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
angle::Result WindowSurfaceVk::computePresentOutOfDate(vk::Context *context,
VkResult result,
bool *presentOutOfDate)
{
// If OUT_OF_DATE is returned, it's ok, we just need to recreate the swapchain before
// continuing. We do the same when VK_SUBOPTIMAL_KHR is returned to avoid visual degradation
// and handle device rotation / screen resize.
*presentOutOfDate = result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR;
if (!*presentOutOfDate)
{
ANGLE_VK_TRY(context, result);
}
return angle::Result::Continue;
}
vk::Framebuffer &WindowSurfaceVk::chooseFramebuffer()
{
if (isMultiSampled())
{
return mFramebufferMS;
}
// Choose which framebuffer to use based on fetch, so it will have a matching renderpass
return mFramebufferFetchMode == FramebufferFetchMode::Enabled
? mSwapchainImages[mCurrentSwapchainImageIndex].fetchFramebuffer
: mSwapchainImages[mCurrentSwapchainImageIndex].framebuffer;
}
angle::Result WindowSurfaceVk::prePresentSubmit(ContextVk *contextVk,
const vk::Semaphore &presentSemaphore)
{
vk::Renderer *renderer = contextVk->getRenderer();
SwapchainImage &image = mSwapchainImages[mCurrentSwapchainImageIndex];
// Make sure deferred clears are applied, if any.
if (mColorImageMS.valid())
{
ANGLE_TRY(mColorImageMS.flushStagedUpdates(contextVk, gl::LevelIndex(0), gl::LevelIndex(1),
0, 1, {}));
}
else
{
ANGLE_TRY(image.image->flushStagedUpdates(contextVk, gl::LevelIndex(0), gl::LevelIndex(1),
0, 1, {}));
}
// If user calls eglSwapBuffer without use it, image may already in Present layout (if swap
// without any draw) or Undefined (first time present). In this case, if
// acquireNextImageSemaphore has not been waited, we must add to context will force the
// semaphore wait so that it will be in unsignaled state and ready to use for ANI call.
if (image.image->getAcquireNextImageSemaphore().valid())
{
ASSERT(!renderer->getFeatures().supportsPresentation.enabled ||
image.image->getCurrentImageLayout() == vk::ImageLayout::Present ||
image.image->getCurrentImageLayout() == vk::ImageLayout::Undefined);
contextVk->addWaitSemaphore(image.image->getAcquireNextImageSemaphore().getHandle(),
vk::kSwapchainAcquireImageWaitStageFlags);
image.image->resetAcquireNextImageSemaphore();
}
// We can only do present related optimization if this is the last renderpass that touches the
// swapchain image. MSAA resolve and overlay will insert another renderpass which disqualifies
// the optimization.
bool imageResolved = false;
if (contextVk->hasStartedRenderPassWithDefaultFramebuffer())
{
ANGLE_TRY(contextVk->optimizeRenderPassForPresent(&image.imageViews, image.image.get(),
&mColorImageMS, mSwapchainPresentMode,
&imageResolved));
}
// Because the color attachment defers layout changes until endRenderPass time, we must call
// finalize the layout transition in the renderpass before we insert layout change to
// ImageLayout::Present bellow.
contextVk->finalizeImageLayout(image.image.get(), {});
contextVk->finalizeImageLayout(&mColorImageMS, {});
vk::OutsideRenderPassCommandBufferHelper *commandBufferHelper;
ANGLE_TRY(contextVk->getOutsideRenderPassCommandBufferHelper({}, &commandBufferHelper));
if (mColorImageMS.valid() && !imageResolved)
{
// Transition the multisampled image to TRANSFER_SRC for resolve.
vk::CommandBufferAccess access;
access.onImageTransferRead(VK_IMAGE_ASPECT_COLOR_BIT, &mColorImageMS);
access.onImageTransferWrite(gl::LevelIndex(0), 1, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
image.image.get());
ANGLE_TRY(contextVk->getOutsideRenderPassCommandBufferHelper(access, &commandBufferHelper));
VkImageResolve resolveRegion = {};
resolveRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
resolveRegion.srcSubresource.mipLevel = 0;
resolveRegion.srcSubresource.baseArrayLayer = 0;
resolveRegion.srcSubresource.layerCount = 1;
resolveRegion.srcOffset = {};
resolveRegion.dstSubresource = resolveRegion.srcSubresource;
resolveRegion.dstOffset = {};
resolveRegion.extent = image.image->getRotatedExtents();
mColorImageMS.resolve(image.image.get(), resolveRegion,
&commandBufferHelper->getCommandBuffer());
contextVk->getPerfCounters().swapchainResolveOutsideSubpass++;
}
// The overlay is drawn after this. This ensures that drawing the overlay does not interfere
// with other functionality, especially counters used to validate said functionality.
const bool shouldDrawOverlay = overlayHasEnabledWidget(contextVk);
if (renderer->getFeatures().supportsPresentation.enabled && !shouldDrawOverlay)
{
// This does nothing if it's already in the requested layout
image.image->recordReadBarrier(contextVk, VK_IMAGE_ASPECT_COLOR_BIT,
vk::ImageLayout::Present, commandBufferHelper);
}
ANGLE_TRY(contextVk->flushImpl(shouldDrawOverlay ? nullptr : &presentSemaphore, nullptr,
RenderPassClosureReason::EGLSwapBuffers));
if (shouldDrawOverlay)
{
updateOverlay(contextVk);
ANGLE_TRY(drawOverlay(contextVk, &image));
if (renderer->getFeatures().supportsPresentation.enabled)
{
ANGLE_TRY(contextVk->getOutsideRenderPassCommandBufferHelper({}, &commandBufferHelper));
image.image->recordReadBarrier(contextVk, VK_IMAGE_ASPECT_COLOR_BIT,
vk::ImageLayout::Present, commandBufferHelper);
}
ANGLE_TRY(contextVk->flushImpl(&presentSemaphore, nullptr,
RenderPassClosureReason::AlreadySpecifiedElsewhere));
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::present(ContextVk *contextVk,
const EGLint *rects,
EGLint n_rects,
const void *pNextChain,
bool *presentOutOfDate)
{
ASSERT(!mAcquireOperation.needToAcquireNextSwapchainImage);
ASSERT(!NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult));
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::present");
vk::Renderer *renderer = contextVk->getRenderer();
// Clean up whatever present is already finished. Do this before allocating new semaphore/fence
// to reduce number of allocations.
ANGLE_TRY(cleanUpPresentHistory(contextVk));
// Get a new semaphore to use for present.
vk::Semaphore presentSemaphore;
ANGLE_TRY(NewSemaphore(contextVk, &mPresentSemaphoreRecycler, &presentSemaphore));
// Make a submission before present to flush whatever's pending. In the very least, a
// submission is necessary to make sure the present semaphore is signaled.
ANGLE_TRY(prePresentSubmit(contextVk, presentSemaphore));
QueueSerial swapSerial = contextVk->getLastSubmittedQueueSerial();
if (!contextVk->getFeatures().supportsSwapchainMaintenance1.enabled)
{
// Associate swapSerial of this present with the previous present of the same imageIndex.
// Completion of swapSerial implies that current ANI semaphore was waited. See
// doc/PresentSemaphores.md for details.
AssociateQueueSerialWithPresentHistory(mCurrentSwapchainImageIndex, swapSerial,
&mPresentHistory);
}
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.pNext = pNextChain;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = presentSemaphore.ptr();
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &mSwapchain;
presentInfo.pImageIndices = &mCurrentSwapchainImageIndex;
presentInfo.pResults = nullptr;
VkPresentRegionKHR presentRegion = {};
VkPresentRegionsKHR presentRegions = {};
std::vector<VkRectLayerKHR> vkRects;
if (contextVk->getFeatures().supportsIncrementalPresent.enabled && (n_rects > 0))
{
EGLint width = getWidth();
EGLint height = getHeight();
const EGLint *eglRects = rects;
presentRegion.rectangleCount = n_rects;
vkRects.resize(n_rects);
for (EGLint i = 0; i < n_rects; i++)
{
vkRects[i] = ToVkRectLayer(
eglRects + i * 4, width, height,
contextVk->getFeatures().bottomLeftOriginPresentRegionRectangles.enabled);
}
presentRegion.pRectangles = vkRects.data();
presentRegions.sType = VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR;
presentRegions.swapchainCount = 1;
presentRegions.pRegions = &presentRegion;
vk::AddToPNextChain(&presentInfo, &presentRegions);
}
VkSwapchainPresentFenceInfoEXT presentFenceInfo = {};
VkSwapchainPresentModeInfoEXT presentModeInfo = {};
vk::Fence presentFence;
VkPresentModeKHR presentMode;
if (contextVk->getFeatures().supportsSwapchainMaintenance1.enabled)
{
ANGLE_VK_TRY(contextVk,
NewFence(contextVk->getDevice(), &mPresentFenceRecycler, &presentFence));
presentFenceInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT;
presentFenceInfo.swapchainCount = 1;
presentFenceInfo.pFences = presentFence.ptr();
vk::AddToPNextChain(&presentInfo, &presentFenceInfo);
// Update the present mode if necessary and possible
if (mSwapchainPresentMode != mDesiredSwapchainPresentMode &&
IsCompatiblePresentMode(mDesiredSwapchainPresentMode, mCompatiblePresentModes.data(),
mCompatiblePresentModes.size()))
{
presentMode = vk::ConvertPresentModeToVkPresentMode(mDesiredSwapchainPresentMode);
presentModeInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT;
presentModeInfo.swapchainCount = 1;
presentModeInfo.pPresentModes = &presentMode;
vk::AddToPNextChain(&presentInfo, &presentModeInfo);
mSwapchainPresentMode = mDesiredSwapchainPresentMode;
}
}
// The ANI semaphore must have been submitted and waited.
ASSERT(!mSwapchainImages[mCurrentSwapchainImageIndex]
.image->getAcquireNextImageSemaphore()
.valid());
renderer->queuePresent(contextVk, contextVk->getPriority(), presentInfo, &mSwapchainStatus);
// EGL_EXT_buffer_age
// 4) What is the buffer age of a single buffered surface?
// RESOLVED: 0. This falls out implicitly from the buffer age
// calculations, which dictate that a buffer's age starts at 0,
// and is only incremented by frame boundaries. Since frame
// boundary functions do not affect single buffered surfaces,
// their age will always be 0.
if (!isSharedPresentMode())
{
// Set FrameNumber for the presented image.
mSwapchainImages[mCurrentSwapchainImageIndex].frameNumber = mFrameCount++;
}
// Place the semaphore in the present history. Schedule pending old swapchains to be destroyed
// at the same time the semaphore for this present can be destroyed.
mPresentHistory.emplace_back();
mPresentHistory.back().semaphore = std::move(presentSemaphore);
if (contextVk->getFeatures().supportsSwapchainMaintenance1.enabled)
{
mPresentHistory.back().imageIndex = kInvalidImageIndex;
mPresentHistory.back().fence = std::move(presentFence);
ANGLE_TRY(cleanUpOldSwapchains(contextVk));
}
else
{
// Image index is used to associate swapSerial in the next present.
mPresentHistory.back().imageIndex = mCurrentSwapchainImageIndex;
mPresentHistory.back().oldSwapchains = std::move(mOldSwapchains);
}
ANGLE_TRY(
computePresentOutOfDate(contextVk, mSwapchainStatus.lastPresentResult, presentOutOfDate));
// Now apply CPU throttle if needed
ANGLE_TRY(throttleCPU(contextVk, swapSerial));
contextVk->resetPerFramePerfCounters();
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::throttleCPU(vk::Context *context,
const QueueSerial ¤tSubmitSerial)
{
// Wait on the oldest serial and replace it with the newest as the circular buffer moves
// forward.
QueueSerial swapSerial = mSwapHistory.front();
mSwapHistory.front() = currentSubmitSerial;
mSwapHistory.next();
if (swapSerial.valid() && !context->getRenderer()->hasQueueSerialFinished(swapSerial))
{
// Make this call after unlocking the EGL lock. Renderer::finishQueueSerial is necessarily
// thread-safe because it can get called from any number of GL commands, which don't
// necessarily hold the EGL lock.
//
// As this is an unlocked tail call, it must not access anything else in Renderer. The
// display passed to |finishQueueSerial| is a |vk::Context|, and the only possible
// modification to it is through |handleError()|.
egl::Display::GetCurrentThreadUnlockedTailCall()->add(
[context, swapSerial](void *resultOut) {
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::throttleCPU");
ANGLE_UNUSED_VARIABLE(resultOut);
(void)context->getRenderer()->finishQueueSerial(context, swapSerial);
});
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::cleanUpPresentHistory(vk::Context *context)
{
const VkDevice device = context->getDevice();
while (!mPresentHistory.empty())
{
impl::ImagePresentOperation &presentOperation = mPresentHistory.front();
// If there is no fence associated with the history, check queueSerial.
if (!presentOperation.fence.valid())
{
// |kInvalidImageIndex| is only possible when |VkSwapchainPresentFenceInfoEXT| is used,
// in which case |fence| is always valid.
ASSERT(presentOperation.imageIndex != kInvalidImageIndex);
// If queueSerial already assigned, check if it is finished.
if (!presentOperation.queueSerial.valid() ||
!context->getRenderer()->hasQueueSerialFinished(presentOperation.queueSerial))
{
// Not yet
break;
}
}
// Otherwise check to see if the fence is signaled.
else
{
VkResult result = presentOperation.fence.getStatus(device);
if (result == VK_NOT_READY)
{
// Not yet
break;
}
ANGLE_VK_TRY(context, result);
}
presentOperation.destroy(device, &mPresentFenceRecycler, &mPresentSemaphoreRecycler);
mPresentHistory.pop_front();
}
// The present history can grow indefinitely if a present operation is done on an index that's
// never presented in the future. In that case, there's no queueSerial associated with that
// present operation. Move the offending entry to last, so the resources associated with the
// rest of the present operations can be duly freed.
if (mPresentHistory.size() > mSwapchainImages.size() * 2 &&
!mPresentHistory.front().fence.valid() && !mPresentHistory.front().queueSerial.valid())
{
impl::ImagePresentOperation presentOperation = std::move(mPresentHistory.front());
mPresentHistory.pop_front();
// |kInvalidImageIndex| is only possible when |VkSwapchainPresentFenceInfoEXT| is used, in
// which case |fence| is always valid.
ASSERT(presentOperation.imageIndex != kInvalidImageIndex);
// Move clean up data to the next (now first) present operation, if any. Note that there
// cannot be any clean up data on the rest of the present operations, because the first
// present already gathers every old swapchain to clean up.
ASSERT(!HasAnyOldSwapchains(mPresentHistory));
mPresentHistory.front().oldSwapchains = std::move(presentOperation.oldSwapchains);
// Put the present operation at the end of the queue so it's revisited after the rest of the
// present operations are cleaned up.
mPresentHistory.push_back(std::move(presentOperation));
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::cleanUpOldSwapchains(vk::Context *context)
{
const VkDevice device = context->getDevice();
ASSERT(context->getFeatures().supportsSwapchainMaintenance1.enabled);
while (!mOldSwapchains.empty())
{
impl::SwapchainCleanupData &oldSwapchain = mOldSwapchains.front();
VkResult result = oldSwapchain.getFencesStatus(device);
if (result == VK_NOT_READY)
{
break;
}
ANGLE_VK_TRY(context, result);
oldSwapchain.destroy(device, &mPresentFenceRecycler, &mPresentSemaphoreRecycler);
mOldSwapchains.pop_front();
}
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::swapImpl(const gl::Context *context,
const EGLint *rects,
EGLint n_rects,
const void *pNextChain)
{
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::swapImpl");
ContextVk *contextVk = vk::GetImpl(context);
// prepareSwap() has already called vkAcquireNextImageKHR if necessary, but its results need to
// be processed now if not already. doDeferredAcquireNextImage() will
// automatically skip the prepareForAcquireNextSwapchainImage() and vkAcquireNextImageKHR calls
// in that case. The swapchain recreation path in
// doDeferredAcquireNextImageWithUsableSwapchain() is acceptable because it only happens if
// previous vkAcquireNextImageKHR failed.
// Note: this method may be called from |onSharedPresentContextFlush|, therefore can't assume
// that image is always acquired at this point.
if (needsAcquireImageOrProcessResult())
{
ANGLE_TRY(doDeferredAcquireNextImage(context, false));
}
bool presentOutOfDate = false;
ANGLE_TRY(present(contextVk, rects, n_rects, pNextChain, &presentOutOfDate));
if (!presentOutOfDate)
{
// Defer acquiring the next swapchain image since the swapchain is not out-of-date.
deferAcquireNextImage();
}
else
{
// Immediately try to acquire the next image, which will recognize the out-of-date
// swapchain (potentially because of a rotation change), and recreate it.
ANGLE_VK_TRACE_EVENT_AND_MARKER(contextVk, "Out-of-Date Swapbuffer");
ANGLE_TRY(doDeferredAcquireNextImage(context, presentOutOfDate));
}
vk::Renderer *renderer = contextVk->getRenderer();
ANGLE_TRY(renderer->syncPipelineCacheVk(contextVk, renderer->getGlobalOps(), context));
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::onSharedPresentContextFlush(const gl::Context *context)
{
return swapImpl(context, nullptr, 0, nullptr);
}
bool WindowSurfaceVk::hasStagedUpdates() const
{
return !needsAcquireImageOrProcessResult() &&
mSwapchainImages[mCurrentSwapchainImageIndex].image->hasStagedUpdatesInAllocatedLevels();
}
void WindowSurfaceVk::setTimestampsEnabled(bool enabled)
{
// The frontend has already cached the state, nothing to do.
ASSERT(IsAndroid());
}
void WindowSurfaceVk::deferAcquireNextImage()
{
mAcquireOperation.needToAcquireNextSwapchainImage = true;
// Set gl::Framebuffer::DIRTY_BIT_COLOR_BUFFER_CONTENTS_0 via subject-observer message-passing
// to the front-end Surface, Framebuffer, and Context classes. The DIRTY_BIT_COLOR_ATTACHMENT_0
// is processed before all other dirty bits. However, since the attachments of the default
// framebuffer cannot change, this bit will be processed before all others. It will cause
// WindowSurfaceVk::getAttachmentRenderTarget() to be called (which will acquire the next image)
// before any RenderTargetVk accesses. The processing of other dirty bits as well as other
// setup for draws and reads will then access a properly-updated RenderTargetVk.
onStateChange(angle::SubjectMessage::SwapchainImageChanged);
}
angle::Result WindowSurfaceVk::prepareForAcquireNextSwapchainImage(const gl::Context *context,
bool presentOutOfDate)
{
ASSERT(!NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult));
ContextVk *contextVk = vk::GetImpl(context);
vk::Renderer *renderer = contextVk->getRenderer();
// TODO(jmadill): Expose in CommandQueueInterface, or manage in CommandQueue. b/172704839
if (renderer->isAsyncCommandQueueEnabled())
{
ANGLE_TRY(renderer->waitForPresentToBeSubmitted(&mSwapchainStatus));
VkResult result = mSwapchainStatus.lastPresentResult;
// Now that we have the result from the last present need to determine if it's out of date
// or not.
ANGLE_TRY(computePresentOutOfDate(contextVk, result, &presentOutOfDate));
}
return checkForOutOfDateSwapchain(contextVk, presentOutOfDate);
}
angle::Result WindowSurfaceVk::doDeferredAcquireNextImage(const gl::Context *context,
bool presentOutOfDate)
{
// prepareForAcquireNextSwapchainImage() may recreate Swapchain even if there is an image
// acquired. Avoid this, by skipping the prepare call.
if (!NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult))
{
ANGLE_TRY(prepareForAcquireNextSwapchainImage(context, presentOutOfDate));
}
return doDeferredAcquireNextImageWithUsableSwapchain(context);
}
angle::Result WindowSurfaceVk::doDeferredAcquireNextImageWithUsableSwapchain(
const gl::Context *context)
{
ContextVk *contextVk = vk::GetImpl(context);
{
// Note: TRACE_EVENT0 is put here instead of inside the function to workaround this issue:
// http://anglebug.com/42261625
ANGLE_TRACE_EVENT0("gpu.angle", "acquireNextSwapchainImage");
// Get the next available swapchain image.
VkResult result = acquireNextSwapchainImage(contextVk);
ASSERT(result != VK_SUBOPTIMAL_KHR);
// If OUT_OF_DATE is returned, it's ok, we just need to recreate the swapchain before
// continuing.
if (ANGLE_UNLIKELY(result == VK_ERROR_OUT_OF_DATE_KHR))
{
ANGLE_TRY(checkForOutOfDateSwapchain(contextVk, true));
// Try one more time and bail if we fail
result = acquireNextSwapchainImage(contextVk);
}
ANGLE_VK_TRY(contextVk, result);
}
// Auto-invalidate the contents of the surface. According to EGL, on swap:
//
// - When EGL_BUFFER_DESTROYED is specified, the contents of the color image can be
// invalidated.
// * This is disabled when buffer age has been queried to work around a dEQP test bug.
// - Depth/Stencil can always be invalidated
//
// In all cases, when in shared present mode, swap is implicit and the swap behavior
// doesn't apply so no invalidation is done.
if (!isSharedPresentMode())
{
if (mState.swapBehavior == EGL_BUFFER_DESTROYED && mBufferAgeQueryFrameNumber == 0)
{
mSwapchainImages[mCurrentSwapchainImageIndex].image->invalidateSubresourceContent(
contextVk, gl::LevelIndex(0), 0, 1, nullptr);
if (mColorImageMS.valid())
{
mColorImageMS.invalidateSubresourceContent(contextVk, gl::LevelIndex(0), 0, 1,
nullptr);
}
}
if (mDepthStencilImage.valid())
{
mDepthStencilImage.invalidateSubresourceContent(contextVk, gl::LevelIndex(0), 0, 1,
nullptr);
mDepthStencilImage.invalidateSubresourceStencilContent(contextVk, gl::LevelIndex(0), 0,
1, nullptr);
}
}
return angle::Result::Continue;
}
bool WindowSurfaceVk::skipAcquireNextSwapchainImageForSharedPresentMode() const
{
if (isSharedPresentMode())
{
ASSERT(mSwapchainImages.size());
const SwapchainImage &image = mSwapchainImages[0];
if (image.image->valid() &&
image.image->getCurrentImageLayout() == vk::ImageLayout::SharedPresent)
{
return true;
}
}
return false;
}
// This method will either return VK_SUCCESS or VK_ERROR_*. Thus, it is appropriate to ASSERT that
// the return value won't be VK_SUBOPTIMAL_KHR.
VkResult WindowSurfaceVk::acquireNextSwapchainImage(vk::Context *context)
{
VkDevice device = context->getDevice();
if (skipAcquireNextSwapchainImageForSharedPresentMode())
{
ASSERT(!NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult));
// This will check for OUT_OF_DATE when in single image mode. and prevent
// re-AcquireNextImage.
VkResult result = vkGetSwapchainStatusKHR(device, mSwapchain);
if (ANGLE_UNLIKELY(result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR))
{
return result;
}
// Note that an acquire is no longer needed.
mAcquireOperation.needToAcquireNextSwapchainImage = false;
return VK_SUCCESS;
}
// If calling vkAcquireNextImageKHR is necessary, do so first.
if (mAcquireOperation.needToAcquireNextSwapchainImage)
{
TryAcquireNextImageUnlocked(context->getDevice(), mSwapchain, &mAcquireOperation);
}
// If the result of vkAcquireNextImageKHR is not yet processed, do so now.
if (NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult))
{
return postProcessUnlockedTryAcquire(context);
}
return VK_SUCCESS;
}
VkResult WindowSurfaceVk::postProcessUnlockedTryAcquire(vk::Context *context)
{
const VkResult result = mAcquireOperation.unlockedTryAcquireResult.result;
const VkSemaphore acquireImageSemaphore =
mAcquireOperation.unlockedTryAcquireResult.acquireSemaphore;
mAcquireOperation.unlockedTryAcquireResult.acquireSemaphore = VK_NULL_HANDLE;
// VK_SUBOPTIMAL_KHR is ok since we still have an Image that can be presented successfully
if (ANGLE_UNLIKELY(result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR))
{
// vkAcquireNextImageKHR still needs to be called after swapchain recreation:
mAcquireOperation.needToAcquireNextSwapchainImage = true;
return result;
}
mCurrentSwapchainImageIndex = mAcquireOperation.unlockedTryAcquireResult.imageIndex;
ASSERT(!isSharedPresentMode() || mCurrentSwapchainImageIndex == 0);
SwapchainImage &image = mSwapchainImages[mCurrentSwapchainImageIndex];
// Let Image keep the ani semaphore so that it can add to the semaphore wait list if it is
// being used. Image's barrier code will move the semaphore into CommandBufferHelper object
// and then added to waitSemaphores when commands gets flushed and submitted. Since all
// image use after ANI must go through barrier code, this approach is very robust. And since
// this is tracked bny ImageHelper object, it also ensures it only added to command that
// image is actually being referenced, thus avoid potential bugs.
image.image->setAcquireNextImageSemaphore(acquireImageSemaphore);
// Single Image Mode
if (isSharedPresentMode())
{
ASSERT(image.image->valid() &&
image.image->getCurrentImageLayout() != vk::ImageLayout::SharedPresent);
rx::vk::Renderer *renderer = context->getRenderer();
rx::vk::PrimaryCommandBuffer primaryCommandBuffer;
auto protectionType = vk::ConvertProtectionBoolToType(mState.hasProtectedContent());
if (renderer->getCommandBufferOneOff(context, protectionType, &primaryCommandBuffer) ==
angle::Result::Continue)
{
VkSemaphore semaphore;
// Note return errors is early exit may leave new Image and Swapchain in unknown state.
image.image->recordWriteBarrierOneOff(context, vk::ImageLayout::SharedPresent,
&primaryCommandBuffer, &semaphore);
ASSERT(semaphore == acquireImageSemaphore);
if (primaryCommandBuffer.end() != VK_SUCCESS)
{
mDesiredSwapchainPresentMode = vk::PresentMode::FifoKHR;
return VK_ERROR_OUT_OF_DATE_KHR;
}
QueueSerial queueSerial;
if (renderer->queueSubmitOneOff(context, std::move(primaryCommandBuffer),
protectionType, egl::ContextPriority::Medium, semaphore,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
vk::SubmitPolicy::EnsureSubmitted,
&queueSerial) != angle::Result::Continue)
{
mDesiredSwapchainPresentMode = vk::PresentMode::FifoKHR;
return VK_ERROR_OUT_OF_DATE_KHR;
}
mUse.setQueueSerial(queueSerial);
}
}
// The semaphore will be waited on in the next flush.
mAcquireOperation.unlockedTryAcquireData.acquireImageSemaphores.next();
// Update RenderTarget pointers to this swapchain image if not multisampling. Note: a possible
// optimization is to defer the |vkAcquireNextImageKHR| call itself to |present()| if
// multisampling, as the swapchain image is essentially unused until then.
if (!mColorImageMS.valid())
{
mColorRenderTarget.updateSwapchainImage(image.image.get(), &image.imageViews, nullptr,
nullptr);
}
// Notify the owning framebuffer there may be staged updates.
if (image.image->hasStagedUpdatesInAllocatedLevels())
{
onStateChange(angle::SubjectMessage::SwapchainImageChanged);
}
ASSERT(!needsAcquireImageOrProcessResult());
return VK_SUCCESS;
}
bool WindowSurfaceVk::needsAcquireImageOrProcessResult() const
{
// Go down the acquireNextSwapchainImage() path if either vkAcquireNextImageKHR needs to be
// called, or its results processed
return mAcquireOperation.needToAcquireNextSwapchainImage ||
NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult);
}
egl::Error WindowSurfaceVk::postSubBuffer(const gl::Context *context,
EGLint x,
EGLint y,
EGLint width,
EGLint height)
{
// TODO(jmadill)
return egl::NoError();
}
egl::Error WindowSurfaceVk::querySurfacePointerANGLE(EGLint attribute, void **value)
{
UNREACHABLE();
return egl::EglBadCurrentSurface();
}
egl::Error WindowSurfaceVk::bindTexImage(const gl::Context *context,
gl::Texture *texture,
EGLint buffer)
{
return egl::NoError();
}
egl::Error WindowSurfaceVk::releaseTexImage(const gl::Context *context, EGLint buffer)
{
return egl::NoError();
}
egl::Error WindowSurfaceVk::getSyncValues(EGLuint64KHR * /*ust*/,
EGLuint64KHR * /*msc*/,
EGLuint64KHR * /*sbc*/)
{
UNIMPLEMENTED();
return egl::EglBadAccess();
}
egl::Error WindowSurfaceVk::getMscRate(EGLint * /*numerator*/, EGLint * /*denominator*/)
{
UNIMPLEMENTED();
return egl::EglBadAccess();
}
void WindowSurfaceVk::setSwapInterval(DisplayVk *displayVk, EGLint interval)
{
// Don't let setSwapInterval change presentation mode if using SHARED present.
if (isSharedPresentMode())
{
return;
}
const EGLint minSwapInterval = mState.config->minSwapInterval;
const EGLint maxSwapInterval = mState.config->maxSwapInterval;
ASSERT(minSwapInterval == 0 || minSwapInterval == 1);
ASSERT(maxSwapInterval == 0 || maxSwapInterval == 1);
interval = gl::clamp(interval, minSwapInterval, maxSwapInterval);
mDesiredSwapchainPresentMode = GetDesiredPresentMode(mPresentModes, interval);
// minImageCount may vary based on the Present Mode
mMinImageCount =
GetMinImageCount(displayVk->getRenderer(), mSurfaceCaps, mDesiredSwapchainPresentMode);
// On the next swap, if the desired present mode is different from the current one, the
// swapchain will be recreated.
}
void WindowSurfaceVk::setSwapInterval(const egl::Display *display, EGLint interval)
{
DisplayVk *displayVk = vk::GetImpl(display);
setSwapInterval(displayVk, interval);
}
egl::Error WindowSurfaceVk::getUserWidth(const egl::Display *display, EGLint *value) const
{
DisplayVk *displayVk = vk::GetImpl(display);
if (mSurfaceCaps.currentExtent.width == kSurfaceSizedBySwapchain)
{
// Surface has no intrinsic size; use current size.
*value = getWidth();
return egl::NoError();
}
VkSurfaceCapabilitiesKHR surfaceCaps;
angle::Result result = getUserExtentsImpl(displayVk, &surfaceCaps);
if (result == angle::Result::Continue)
{
// The EGL spec states that value is not written if there is an error
ASSERT(surfaceCaps.currentExtent.width != kSurfaceSizedBySwapchain);
*value = static_cast<EGLint>(surfaceCaps.currentExtent.width);
}
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
egl::Error WindowSurfaceVk::getUserHeight(const egl::Display *display, EGLint *value) const
{
DisplayVk *displayVk = vk::GetImpl(display);
if (mSurfaceCaps.currentExtent.height == kSurfaceSizedBySwapchain)
{
// Surface has no intrinsic size; use current size.
*value = getHeight();
return egl::NoError();
}
VkSurfaceCapabilitiesKHR surfaceCaps;
angle::Result result = getUserExtentsImpl(displayVk, &surfaceCaps);
if (result == angle::Result::Continue)
{
// The EGL spec states that value is not written if there is an error
ASSERT(surfaceCaps.currentExtent.height != kSurfaceSizedBySwapchain);
*value = static_cast<EGLint>(surfaceCaps.currentExtent.height);
}
return angle::ToEGL(result, EGL_BAD_SURFACE);
}
angle::Result WindowSurfaceVk::getUserExtentsImpl(DisplayVk *displayVk,
VkSurfaceCapabilitiesKHR *surfaceCaps) const
{
const VkPhysicalDevice &physicalDevice = displayVk->getRenderer()->getPhysicalDevice();
ANGLE_VK_TRY(displayVk,
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, mSurface, surfaceCaps));
// With real prerotation, the surface reports the rotated sizes. With emulated prerotation,
// adjust the window extents to match what real pre-rotation would have reported.
if (Is90DegreeRotation(mEmulatedPreTransform))
{
std::swap(surfaceCaps->currentExtent.width, surfaceCaps->currentExtent.height);
}
return angle::Result::Continue;
}
EGLint WindowSurfaceVk::isPostSubBufferSupported() const
{
// TODO(jmadill)
return EGL_FALSE;
}
EGLint WindowSurfaceVk::getSwapBehavior() const
{
// TODO(jmadill)
return EGL_BUFFER_DESTROYED;
}
angle::Result WindowSurfaceVk::getCurrentFramebuffer(ContextVk *contextVk,
FramebufferFetchMode fetchMode,
const vk::RenderPass &compatibleRenderPass,
vk::Framebuffer *framebufferOut)
{
ASSERT(!contextVk->getFeatures().preferDynamicRendering.enabled);
// FramebufferVk dirty-bit processing should ensure that a new image was acquired.
ASSERT(!needsAcquireImageOrProcessResult());
// Track the new fetch mode
mFramebufferFetchMode = fetchMode;
SwapchainImage &swapchainImage = mSwapchainImages[mCurrentSwapchainImageIndex];
vk::Framebuffer *currentFramebuffer = &chooseFramebuffer();
if (currentFramebuffer->valid())
{
// Validation layers should detect if the render pass is really compatible.
framebufferOut->setHandle(currentFramebuffer->getHandle());
return angle::Result::Continue;
}
const gl::Extents rotatedExtents = mColorRenderTarget.getRotatedExtents();
const uint32_t attachmentCount = 1 + (mDepthStencilImage.valid() ? 1 : 0);
std::array<VkImageView, 3> imageViews = {};
if (mDepthStencilImage.valid())
{
const vk::ImageView *imageView = nullptr;
ANGLE_TRY(mDepthStencilRenderTarget.getImageView(contextVk, &imageView));
imageViews[1] = imageView->getHandle();
}
if (isMultiSampled())
{
const vk::ImageView *imageView = nullptr;
ANGLE_TRY(mColorRenderTarget.getImageView(contextVk, &imageView));
imageViews[0] = imageView->getHandle();
}
else
{
const vk::ImageView *imageView = nullptr;
ANGLE_TRY(swapchainImage.imageViews.getLevelLayerDrawImageView(
contextVk, *swapchainImage.image, vk::LevelIndex(0), 0, &imageView));
imageViews[0] = imageView->getHandle();
}
VkFramebufferCreateInfo framebufferInfo = {};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.flags = 0;
framebufferInfo.renderPass = compatibleRenderPass.getHandle();
framebufferInfo.attachmentCount = attachmentCount;
framebufferInfo.pAttachments = imageViews.data();
framebufferInfo.width = static_cast<uint32_t>(rotatedExtents.width);
framebufferInfo.height = static_cast<uint32_t>(rotatedExtents.height);
framebufferInfo.layers = 1;
ANGLE_VK_TRY(contextVk, currentFramebuffer->init(contextVk->getDevice(), framebufferInfo));
framebufferOut->setHandle(currentFramebuffer->getHandle());
return angle::Result::Continue;
}
angle::Result WindowSurfaceVk::initializeContents(const gl::Context *context,
GLenum binding,
const gl::ImageIndex &imageIndex)
{
ContextVk *contextVk = vk::GetImpl(context);
if (needsAcquireImageOrProcessResult())
{
// Acquire the next image (previously deferred). Some tests (e.g.
// GenerateMipmapWithRedefineBenchmark.Run/vulkan_webgl) cause this path to be taken,
// because of dirty-object processing.
ANGLE_VK_TRACE_EVENT_AND_MARKER(contextVk, "Initialize Swap Image");
ANGLE_TRY(doDeferredAcquireNextImage(context, false));
}
ASSERT(mSwapchainImages.size() > 0);
ASSERT(mCurrentSwapchainImageIndex < mSwapchainImages.size());
switch (binding)
{
case GL_BACK:
{
vk::ImageHelper *image =
isMultiSampled() ? &mColorImageMS
: mSwapchainImages[mCurrentSwapchainImageIndex].image.get();
image->stageRobustResourceClear(imageIndex);
ANGLE_TRY(image->flushAllStagedUpdates(contextVk));
break;
}
case GL_DEPTH:
case GL_STENCIL:
ASSERT(mDepthStencilImage.valid());
mDepthStencilImage.stageRobustResourceClear(gl::ImageIndex::Make2D(0));
ANGLE_TRY(mDepthStencilImage.flushAllStagedUpdates(contextVk));
break;
default:
UNREACHABLE();
break;
}
return angle::Result::Continue;
}
void WindowSurfaceVk::updateOverlay(ContextVk *contextVk) const
{
const gl::OverlayType *overlay = contextVk->getOverlay();
// If overlay is disabled, nothing to do.
if (!overlay->isEnabled())
{
return;
}
vk::Renderer *renderer = contextVk->getRenderer();
uint32_t validationMessageCount = 0;
std::string lastValidationMessage =
renderer->getAndClearLastValidationMessage(&validationMessageCount);
if (validationMessageCount)
{
overlay->getTextWidget(gl::WidgetId::VulkanLastValidationMessage)
->set(std::move(lastValidationMessage));
overlay->getCountWidget(gl::WidgetId::VulkanValidationMessageCount)
->set(validationMessageCount);
}
contextVk->updateOverlayOnPresent();
}
ANGLE_INLINE bool WindowSurfaceVk::overlayHasEnabledWidget(ContextVk *contextVk) const
{
const gl::OverlayType *overlay = contextVk->getOverlay();
OverlayVk *overlayVk = vk::GetImpl(overlay);
return overlayVk && overlayVk->getEnabledWidgetCount() > 0;
}
angle::Result WindowSurfaceVk::drawOverlay(ContextVk *contextVk, SwapchainImage *image) const
{
const gl::OverlayType *overlay = contextVk->getOverlay();
OverlayVk *overlayVk = vk::GetImpl(overlay);
// Draw overlay
const vk::ImageView *imageView = nullptr;
ANGLE_TRY(image->imageViews.getLevelLayerDrawImageView(contextVk, *image->image,
vk::LevelIndex(0), 0, &imageView));
ANGLE_TRY(overlayVk->onPresent(contextVk, image->image.get(), imageView,
Is90DegreeRotation(getPreTransform())));
return angle::Result::Continue;
}
egl::Error WindowSurfaceVk::setAutoRefreshEnabled(bool enabled)
{
if (enabled && !supportsPresentMode(vk::PresentMode::SharedContinuousRefreshKHR))
{
return egl::EglBadMatch();
}
vk::PresentMode newDesiredSwapchainPresentMode =
enabled ? vk::PresentMode::SharedContinuousRefreshKHR
: vk::PresentMode::SharedDemandRefreshKHR;
// Auto refresh is only applicable in shared present mode
if (isSharedPresentModeDesired() &&
(mDesiredSwapchainPresentMode != newDesiredSwapchainPresentMode))
{
// In cases where the user switches to single buffer and have yet to call eglSwapBuffer,
// enabling/disabling auto refresh should only change mDesiredSwapchainPresentMode as we
// have not yet actually switched to single buffer mode.
mDesiredSwapchainPresentMode = newDesiredSwapchainPresentMode;
// If auto refresh is updated and we are already in single buffer mode we may need to
// recreate swapchain. We need the deferAcquireNextImage() call as unlike setRenderBuffer(),
// the user does not have to call eglSwapBuffers after setting the auto refresh attribute
if (isSharedPresentMode() &&
!IsCompatiblePresentMode(mDesiredSwapchainPresentMode, mCompatiblePresentModes.data(),
mCompatiblePresentModes.size()))
{
deferAcquireNextImage();
}
}
return egl::NoError();
}
egl::Error WindowSurfaceVk::getBufferAge(const gl::Context *context, EGLint *age)
{
ContextVk *contextVk = vk::GetImpl(context);
ANGLE_TRACE_EVENT0("gpu.angle", "getBufferAge");
// ANI may be skipped in case of multi sampled surface.
if (isMultiSampled())
{
*age = 0;
return egl::NoError();
}
// Image must be already acquired in the |prepareSwap| call.
ASSERT(!mAcquireOperation.needToAcquireNextSwapchainImage);
// If the result of vkAcquireNextImageKHR is not yet processed, do so now.
if (NeedToProcessAcquireNextImageResult(mAcquireOperation.unlockedTryAcquireResult))
{
// Using this method and not |postProcessUnlockedTryAcquire|, in order to handle possible
// VK_ERROR_OUT_OF_DATE_KHR error and recreate the swapchain, instead of failing.
egl::Error result =
angle::ToEGL(doDeferredAcquireNextImageWithUsableSwapchain(context), EGL_BAD_SURFACE);
if (result.isError())
{
return result;
}
}
if (mBufferAgeQueryFrameNumber == 0)
{
ANGLE_VK_PERF_WARNING(contextVk, GL_DEBUG_SEVERITY_LOW,
"Querying age of a surface will make it retain its content");
mBufferAgeQueryFrameNumber = mFrameCount;
}
if (age != nullptr)
{
if (mState.swapBehavior == EGL_BUFFER_PRESERVED)
{
// EGL_EXT_buffer_age
//
// 1) What are the semantics if EGL_BUFFER_PRESERVED is in use
//
// RESOLVED: The age will always be 1 in this case.
// Note: if the query is made before the 1st swap then age needs to be 0
*age = (mFrameCount == 1) ? 0 : 1;
return egl::NoError();
}
uint64_t frameNumber = mSwapchainImages[mCurrentSwapchainImageIndex].frameNumber;
if (frameNumber < mBufferAgeQueryFrameNumber)
{
*age = 0; // Has not been used for rendering yet or since age was queried, no age.
}
else
{
*age = static_cast<EGLint>(mFrameCount - frameNumber);
}
}
return egl::NoError();
}
bool WindowSurfaceVk::supportsPresentMode(vk::PresentMode presentMode) const
{
return (std::find(mPresentModes.begin(), mPresentModes.end(), presentMode) !=
mPresentModes.end());
}
egl::Error WindowSurfaceVk::setRenderBuffer(EGLint renderBuffer)
{
if (renderBuffer == EGL_SINGLE_BUFFER)
{
vk::PresentMode presentMode = mState.autoRefreshEnabled
? vk::PresentMode::SharedContinuousRefreshKHR
: vk::PresentMode::SharedDemandRefreshKHR;
if (!supportsPresentMode(presentMode))
{
return egl::EglBadMatch();
}
mDesiredSwapchainPresentMode = presentMode;
}
else // EGL_BACK_BUFFER
{
mDesiredSwapchainPresentMode = vk::PresentMode::FifoKHR;
}
return egl::NoError();
}
egl::Error WindowSurfaceVk::lockSurface(const egl::Display *display,
EGLint usageHint,
bool preservePixels,
uint8_t **bufferPtrOut,
EGLint *bufferPitchOut)
{
ANGLE_TRACE_EVENT0("gpu.angle", "WindowSurfaceVk::lockSurface");
vk::ImageHelper *image = mSwapchainImages[mCurrentSwapchainImageIndex].image.get();
if (!image->valid())
{
mAcquireOperation.needToAcquireNextSwapchainImage = true;
if (acquireNextSwapchainImage(vk::GetImpl(display)) != VK_SUCCESS)
{
return egl::EglBadAccess();
}
}
image = mSwapchainImages[mCurrentSwapchainImageIndex].image.get();
ASSERT(image->valid());
angle::Result result =
LockSurfaceImpl(vk::GetImpl(display), image, mLockBufferHelper, getWidth(), getHeight(),
usageHint, preservePixels, bufferPtrOut, bufferPitchOut);
return angle::ToEGL(result, EGL_BAD_ACCESS);
}
egl::Error WindowSurfaceVk::unlockSurface(const egl::Display *display, bool preservePixels)
{
vk::ImageHelper *image = mSwapchainImages[mCurrentSwapchainImageIndex].image.get();
ASSERT(image->valid());
ASSERT(mLockBufferHelper.valid());
return angle::ToEGL(UnlockSurfaceImpl(vk::GetImpl(display), image, mLockBufferHelper,
getWidth(), getHeight(), preservePixels),
EGL_BAD_ACCESS);
}
EGLint WindowSurfaceVk::origin() const
{
return EGL_UPPER_LEFT_KHR;
}
egl::Error WindowSurfaceVk::attachToFramebuffer(const gl::Context *context,
gl::Framebuffer *framebuffer)
{
FramebufferVk *framebufferVk = GetImplAs<FramebufferVk>(framebuffer);
ASSERT(!framebufferVk->getBackbuffer());
framebufferVk->setBackbuffer(this);
return egl::NoError();
}
egl::Error WindowSurfaceVk::detachFromFramebuffer(const gl::Context *context,
gl::Framebuffer *framebuffer)
{
FramebufferVk *framebufferVk = GetImplAs<FramebufferVk>(framebuffer);
ASSERT(framebufferVk->getBackbuffer() == this);
framebufferVk->setBackbuffer(nullptr);
return egl::NoError();
}
} // namespace rx