rset=UTF-8 Last-Modified: Sat, 03 May 2025 04:22:22 GMT Expires: Sat, 03 May 2025 04:27:22 GMT hbmame - Emulator of homebrew and hacked games for arcade hardware
summaryrefslogtreecommitdiffstats
path: root/src/mame/machine/hp9825_tape.cpp
stat options
Period:
Authors:

Commits per author per week (path 'src/mame/machine/hp9825_tape.cpp')

AuthorW15 2025W16 2025W17 2025W18 2025Total
Total00000
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 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************

    render.c

    Core rendering system.

****************************************************************************

    Windows-specific to-do:
        * no fallback if we run out of video memory

    Longer-term to do: (once old renderer is gone)
        * make vector updates asynchronous

****************************************************************************

    Overview of objects:

        render_target -- This represents a final rendering target. It
            is specified using integer width/height values, can have
            non-square pixels, and you can specify its rotation. It is
            what really determines the final rendering details. The OSD
            layer creates one or more of these to encapsulate the
            rendering process. Each render_target holds a list of
            layout_files that it can use for drawing. When rendering, it
            makes use of both layout_files and render_containers.

        render_container -- Containers are the top of a hierarchy that is
            not directly related to the objects above. Containers hold
            high level primitives that are generated at runtime by the
            video system. They are used currently for each screen and
            the user interface. These high-level primitives are broken down
            into low-level primitives at render time.

***************************************************************************/

#include "emu.h"
#include "emuopts.h"
#include "render.h"
#include "rendfont.h"
#include "rendlay.h"
#include "rendutil.h"
#include "config.h"
#include "drivenum.h"
#include "xmlfile.h"
#include "ui/uimain.h"

#include <zlib.h>

#include <algorithm>
#include <functional>



//**************************************************************************
//  CONSTANTS
//**************************************************************************

#define INTERNAL_FLAG_CHAR      0x00000001

enum
{
	COMPONENT_TYPE_IMAGE = 0,
	COMPONENT_TYPE_RECT,
	COMPONENT_TYPE_DISK,
	COMPONENT_TYPE_MAX
};


enum
{
	CONTAINER_ITEM_LINE = 0,
	CONTAINER_ITEM_QUAD,
	CONTAINER_ITEM_MAX
};



//**************************************************************************
//  TYPE DEFINITIONS
//**************************************************************************

// an object_transform is used to track transformations when building an object list
struct render_target::object_transform
{
	float               xoffs, yoffs;       // offset transforms
	float               xscale, yscale;     // scale transforms
	render_color        color;              // color transform
	int                 orientation;        // orientation transform
	bool                no_center;          // center the container?
};



//**************************************************************************
//  GLOBAL VARIABLES
//**************************************************************************

// precomputed UV coordinates for various orientations
static const render_quad_texuv oriented_texcoords[8] =
{
	{ { 0,0 }, { 1,0 }, { 0,1 }, { 1,1 } },     // 0
	{ { 1,0 }, { 0,0 }, { 1,1 }, { 0,1 } },     // ORIENTATION_FLIP_X
	{ { 0,1 }, { 1,1 }, { 0,0 }, { 1,0 } },     // ORIENTATION_FLIP_Y
	{ { 1,1 }, { 0,1 }, { 1,0 }, { 0,0 } },     // ORIENTATION_FLIP_X | ORIENTATION_FLIP_Y
	{ { 0,0 }, { 0,1 }, { 1,0 }, { 1,1 } },     // ORIENTATION_SWAP_XY
	{ { 0,1 }, { 0,0 }, { 1,1 }, { 1,0 } },     // ORIENTATION_SWAP_XY | ORIENTATION_FLIP_X
	{ { 1,0 }, { 1,1 }, { 0,0 }, { 0,1 } },     // ORIENTATION_SWAP_XY | ORIENTATION_FLIP_Y
	{ { 1,1 }, { 1,0 }, { 0,1 }, { 0,0 } }      // ORIENTATION_SWAP_XY | ORIENTATION_FLIP_X | ORIENTATION_FLIP_Y
};



//**************************************************************************
//  INLINE FUNCTIONS
//**************************************************************************

//-------------------------------------------------
//  apply_orientation - apply orientation to a
//  set of bounds
//-------------------------------------------------

inline void apply_orientation(render_bounds &bounds, int orientation)
{
	// swap first
	if (orientation & ORIENTATION_SWAP_XY)
	{
		std::swap(bounds.x0, bounds.y0);
		std::swap(bounds.x1, bounds.y1);
	}

	// apply X flip
	if (orientation & ORIENTATION_FLIP_X)
	{
		bounds.x0 = 1.0f - bounds.x0;
		bounds.x1 = 1.0f - bounds.x1;
	}

	// apply Y flip
	if (orientation & ORIENTATION_FLIP_Y)
	{
		bounds.y0 = 1.0f - bounds.y0;
		bounds.y1 = 1.0f - bounds.y1;
	}
}


//-------------------------------------------------
//  normalize_bounds - normalize bounds so that
//  x0/y0 are less than x1/y1
//-------------------------------------------------

inline void normalize_bounds(render_bounds &bounds)
{
	if (bounds.x0 > bounds.x1)
		std::swap(bounds.x0, bounds.x1);
	if (bounds.y0 > bounds.y1)
		std::swap(bounds.y0, bounds.y1);
}


//**************************************************************************
//  RENDER PRIMITIVE
//**************************************************************************

//-------------------------------------------------
//  reset - reset the state of a primitive after
//  it is re-allocated
//-------------------------------------------------

void render_primitive::reset()
{
	// do not clear m_next!
	memset(&type, 0, uintptr_t(&texcoords + 1) - uintptr_t(&type));
}



//**************************************************************************
//  RENDER PRIMITIVE LIST
//**************************************************************************

//-------------------------------------------------
//  render_primitive_list - constructor
//-------------------------------------------------

render_primitive_list::render_primitive_list()
{
}


//-------------------------------------------------
//  ~render_primitive_list - destructor
//-------------------------------------------------

render_primitive_list::~render_primitive_list()
{
	release_all();
}


//-------------------------------------------------
//  add_reference - add a new reference
//-------------------------------------------------

inline void render_primitive_list::add_reference(void *refptr)
{
	// skip if we already have one
	if (has_reference(refptr))
		return;

	// set the refptr and link us into the list
	reference *ref = m_reference_allocator.alloc();
	ref->m_refptr = refptr;
	m_reflist.append(*ref);
}


//-------------------------------------------------
//  has_reference - find a refptr in a reference
//  list
//-------------------------------------------------

inline bool render_primitive_list::has_reference(void *refptr) const
{
	// skip if we already have one
	for (reference &ref : m_reflist)
		if (ref.m_refptr == refptr)
			return true;
	return false;
}


//-------------------------------------------------
//  alloc - allocate a new empty primitive
//-------------------------------------------------

inline render_primitive *render_primitive_list::alloc(render_primitive::primitive_type type)
{
	render_primitive *result = m_primitive_allocator.alloc();
	result->reset();
	result->type = type;
	return result;
}


//-------------------------------------------------
//  release_all - release the contents of
//  a render list
//-------------------------------------------------

void render_primitive_list::release_all()
{
	// release all the live items while under the lock
	m_primitive_allocator.reclaim_all(m_primlist);
	m_reference_allocator.reclaim_all(m_reflist);
}


//-------------------------------------------------
//  append_or_return - append a primitive to the
//  end of the list, or return it to the free
//  list, based on a flag
//-------------------------------------------------

void render_primitive_list::append_or_return(render_primitive &prim, bool clipped)
{
	if (!clipped)
		m_primlist.append(prim);
	else
		m_primitive_allocator.reclaim(prim);
}



//**************************************************************************
//  RENDER TEXTURE
//**************************************************************************

//-------------------------------------------------
//  render_texture - constructor
//-------------------------------------------------

render_texture::render_texture()
	: m_manager(nullptr),
		m_next(nullptr),
		m_bitmap(nullptr),
		m_format(TEXFORMAT_ARGB32),
		m_id(~0ULL),
		m_old_id(~0ULL),
		m_scaler(nullptr),
		m_param(nullptr),
		m_curseq(0)
{
	m_sbounds.set(0, -1, 0, -1);
	memset(m_scaled, 0, sizeof(m_scaled));
}


//-------------------------------------------------
//  ~render_texture - destructor
//-------------------------------------------------

render_texture::~render_texture()
{
	release();
}


//-------------------------------------------------
//  reset - reset the state of a texture after
//  it has been re-allocated
//-------------------------------------------------

void render_texture::reset(render_manager &manager, texture_scaler_func scaler, void *param)
{
	m_manager = &manager;
	if (scaler != nullptr)
	{
		assert(m_format == TEXFORMAT_ARGB32);
		m_scaler = scaler;
		m_param = param;
	}
	m_old_id = m_id;
	m_id = ~0L;
}


//-------------------------------------------------
//  release - release resources when we are freed
//-------------------------------------------------

void render_texture::release()
{
	// free all scaled versions
	for (auto & elem : m_scaled)
	{
		m_manager->invalidate_all(elem.bitmap);
		global_free(elem.bitmap);
		elem.bitmap = nullptr;
		elem.seqid = 0;
	}

	// invalidate references to the original bitmap as well
	m_manager->invalidate_all(m_bitmap);
	m_bitmap = nullptr;
	m_sbounds.set(0, -1, 0, -1);
	m_format = TEXFORMAT_ARGB32;
	m_curseq = 0;
}


//-------------------------------------------------
//  set_bitmap - set a new source bitmap
//-------------------------------------------------

void render_texture::set_bitmap(bitmap_t &bitmap, const rectangle &sbounds, texture_format format)
{
	assert(bitmap.cliprect().contains(sbounds));

	// ensure we have a valid palette for palettized modes
	if (format == TEXFORMAT_PALETTE16)
		assert(bitmap.palette() != nullptr);

	// invalidate references to the old bitmap
	if (&bitmap != m_bitmap && m_bitmap != nullptr)
		m_manager->invalidate_all(m_bitmap);

	// set the new bitmap/palette
	m_bitmap = &bitmap;
	m_sbounds = sbounds;
	m_format = format;

	// invalidate all scaled versions
	for (auto & elem : m_scaled)
	{
		if (elem.bitmap != nullptr)
		{
			m_manager->invalidate_all(elem.bitmap);
			global_free(elem.bitmap);
		}
		elem.bitmap = nullptr;
		elem.seqid = 0;
	}
}


//-------------------------------------------------
//  hq_scale - generic high quality resampling
//  scaler
//-------------------------------------------------

void render_texture::hq_scale(bitmap_argb32 &dest, bitmap_argb32 &source, const rectangle &sbounds, void *param)
{
	render_color color = { 1.0f, 1.0f, 1.0f, 1.0f };
	bitmap_argb32 sourcesub(source, sbounds);
	render_resample_argb_bitmap_hq(dest, sourcesub, color);
}


//-------------------------------------------------
//  get_scaled - get a scaled bitmap (if we can)
//-------------------------------------------------

void render_texture::get_scaled(u32 dwidth, u32 dheight, render_texinfo &texinfo, render_primitive_list &primlist, u32 flags)
{
	// source width/height come from the source bounds
	int swidth = m_sbounds.width();
	int sheight = m_sbounds.height();

	// ensure height/width are non-zero
	if (dwidth == 0) dwidth = 1;
	if (dheight == 0) dheight = 1;

	texinfo.unique_id = m_id;
	texinfo.old_id = m_old_id;
	if (m_old_id != ~0ULL)
		m_old_id = ~0ULL;

	// are we scaler-free? if so, just return the source bitmap
	if (m_scaler == nullptr || (m_bitmap != nullptr && swidth == dwidth && sheight == dheight))
	{
		if (m_bitmap == nullptr) return;

		// add a reference and set up the source bitmap
		primlist.add_reference(m_bitmap);
		texinfo.base = m_bitmap->raw_pixptr(m_sbounds.top(), m_sbounds.left());
		texinfo.rowpixels = m_bitmap->rowpixels();
		texinfo.width = swidth;
		texinfo.height = sheight;
		// palette will be set later
		texinfo.seqid = ++m_curseq;
	}
	else
	{
		// make sure we can recover the original argb32 bitmap
		bitmap_argb32 dummy;
		bitmap_argb32 &srcbitmap = (m_bitmap != nullptr) ? downcast<bitmap_argb32 &>(*m_bitmap) : dummy;

		// is it a size we already have?
		scaled_texture *scaled = nullptr;
		int scalenum;
		for (scalenum = 0; scalenum < ARRAY_LENGTH(m_scaled); scalenum++)
		{
			scaled = &m_scaled[scalenum];

			// we need a non-NULL bitmap with matching dest size
			if (scaled->bitmap != nullptr && dwidth == scaled->bitmap->width() && dheight == scaled->bitmap->height())
				break;
		}

		// did we get one?
		if (scalenum == ARRAY_LENGTH(m_scaled))
		{
			int lowest = -1;

			// didn't find one -- take the entry with the lowest seqnum
			for (scalenum = 0; scalenum < ARRAY_LENGTH(m_scaled); scalenum++)
				if ((lowest == -1 || m_scaled[scalenum].seqid < m_scaled[lowest].seqid) && !primlist.has_reference(m_scaled[scalenum].bitmap))
					lowest = scalenum;
			if (-1 == lowest)
				throw emu_fatalerror("render_texture::get_scaled: Too many live texture instances!");

			// throw out any existing entries
			scaled = &m_scaled[lowest];
			if (scaled->bitmap != nullptr)
			{
				m_manager->invalidate_all(scaled->bitmap);
				global_free(scaled->bitmap);
			}

			// allocate a new bitmap
			scaled->bitmap = global_alloc(bitmap_argb32(dwidth, dheight));
			scaled->seqid = ++m_curseq;

			// let the scaler do the work
			(*m_scaler)(*scaled->bitmap, srcbitmap, m_sbounds, m_param);
		}

		// finally fill out the new info
		primlist.add_reference(scaled->bitmap);
		texinfo.base = &scaled->bitmap->pix32(0);
		texinfo.rowpixels = scaled->bitmap->rowpixels();
		texinfo.width = dwidth;
		texinfo.height = dheight;
		// palette will be set later
		texinfo.seqid = scaled->seqid;
	}
}


//-------------------------------------------------
//  get_adjusted_palette - return the adjusted
//  palette for a texture
//-------------------------------------------------

const rgb_t *render_texture::get_adjusted_palette(render_container &container, u32 &out_length)
{
	// override the palette with our adjusted palette
	switch (m_format)
	{
		case TEXFORMAT_PALETTE16:

			assert(m_bitmap->palette() != nullptr);

			// return our adjusted palette
			return container.bcg_lookup_table(m_format, out_length, m_bitmap->palette());

		case TEXFORMAT_RGB32:
		case TEXFORMAT_ARGB32:
		case TEXFORMAT_YUY16:

			// if no adjustment necessary, return nullptr
			if (!container.has_brightness_contrast_gamma_changes())
				return nullptr;
			return container.bcg_lookup_table(m_format, out_length);

		default:
			assert(false);
	}

	return nullptr;
}



//**************************************************************************
//  RENDER CONTAINER
//**************************************************************************

//-------------------------------------------------
//  render_container - constructor
//-------------------------------------------------

render_container::render_container(render_manager &manager, screen_device *screen)
	: m_next(nullptr)
	, m_manager(manager)
	, m_screen(screen)
	, m_overlaybitmap(nullptr)
	, m_overlaytexture(nullptr)
{
	// make sure it is empty
	empty();

	// if we have a screen, read and apply the options
	if (m_screen)
	{
		// set the initial orientation and brightness/contrast/gamma
		m_user.m_orientation = m_screen->orientation();
		m_user.m_brightness = manager.machine().options().brightness();
		m_user.m_contrast = manager.machine().options().contrast();
		m_user.m_gamma = manager.machine().options().gamma();
		// palette client will be allocated later
	}

	recompute_lookups();
}


//-------------------------------------------------
//  ~render_container - destructor
//-------------------------------------------------

render_container::~render_container()
{
	// free all the container items
	empty();

	// free the overlay texture
	m_manager.texture_free(m_overlaytexture);
}


//-------------------------------------------------
//  set_overlay - set the overlay bitmap for the
//  container
//-------------------------------------------------

void render_container::set_overlay(bitmap_argb32 *bitmap)
{
	// free any existing texture
	m_manager.texture_free(m_overlaytexture);

	// set the new data and allocate the texture
	m_overlaybitmap = bitmap;
	if (m_overlaybitmap != nullptr)
	{
		m_overlaytexture = m_manager.texture_alloc(render_container::overlay_scale);
		m_overlaytexture->set_bitmap(*bitmap, bitmap->cliprect(), TEXFORMAT_ARGB32);
	}
}


//-------------------------------------------------
//  set_user_settings - set the current user
//  settings for a container
//-------------------------------------------------

void render_container::set_user_settings(const user_settings &settings)
{
	m_user = settings;
	recompute_lookups();
}


//-------------------------------------------------
//  add_line - add a line item to this container
//-------------------------------------------------

void render_container::add_line(float x0, float y0, float x1, float y1, float width, rgb_t argb, u32 flags)
{
	item &newitem = add_generic(CONTAINER_ITEM_LINE, x0, y0, x1, y1, argb);
	newitem.m_width = width;
	newitem.m_flags = flags;
}


//-------------------------------------------------
//  add_quad - add a quad item to this container
//-------------------------------------------------

void render_container::add_quad(float x0, float y0, float x1, float y1, rgb_t argb, render_texture *texture, u32 flags)
{
	item &newitem = add_generic(CONTAINER_ITEM_QUAD, x0, y0, x1, y1, argb);
	newitem.m_texture = texture;
	newitem.m_flags = flags;
}


//-------------------------------------------------
//  add_char - add a char item to this container
//-------------------------------------------------

void render_container::add_char(float x0, float y0, float height, float aspect, rgb_t argb, render_font &font, u16 ch)
{
	// compute the bounds of the character cell and get the texture
	render_bounds bounds;
	bounds.x0 = x0;
	bounds.y0 = y0;
	render_texture *texture = font.get_char_texture_and_bounds(height, aspect, ch, bounds);

	// add it like a quad
	item &newitem = add_generic(CONTAINER_ITEM_QUAD, bounds.x0, bounds.y0, bounds.x1, bounds.y1, argb);
	newitem.m_texture = texture;
	newitem.m_flags = PRIMFLAG_TEXORIENT(ROT0) | PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA) | PRIMFLAG_PACKABLE;
	newitem.m_internal = INTERNAL_FLAG_CHAR;
}


//-------------------------------------------------
//  apply_brightness_contrast_gamma - apply the
//  container's brightess, contrast, and gamma to
//  an 8-bit value
//-------------------------------------------------

u8 render_container::apply_brightness_contrast_gamma(u8 value)
{
	return ::apply_brightness_contrast_gamma(value, m_user.m_brightness, m_user.m_contrast, m_user.m_gamma);
}


//-------------------------------------------------
//  apply_brightness_contrast_gamma_fp - apply the
//  container's brightess, contrast, and gamma to
//  a floating-point value
//-------------------------------------------------

float render_container::apply_brightness_contrast_gamma_fp(float value)
{
	return ::apply_brightness_contrast_gamma_fp(value, m_user.m_brightness, m_user.m_contrast, m_user.m_gamma);
}


//-------------------------------------------------
//  bcg_lookup_table - return the appropriate
//  brightness/contrast/gamma lookup table for a
//  given texture mode
//-------------------------------------------------

const rgb_t *render_container::bcg_lookup_table(int texformat, u32 &out_length, palette_t *palette)
{
	switch (texformat)
	{
		case TEXFORMAT_PALETTE16:
			if (m_palclient == nullptr) // if adjusted palette hasn't been created yet, create it
			{
				m_palclient = std::make_unique<palette_client>(*palette);
				m_bcglookup.resize(palette->max_index());
				recompute_lookups();
			}
			assert (palette == &m_palclient->palette());
			out_length = palette->max_index();
			return &m_bcglookup[0];

		case TEXFORMAT_RGB32:
		case TEXFORMAT_ARGB32:
		case TEXFORMAT_YUY16:
			out_length = ARRAY_LENGTH(m_bcglookup256);
			return m_bcglookup256;

		default:
			out_length = 0;
			return nullptr;
	}
}


//-------------------------------------------------
//  overlay_scale - scaler for an overlay
//-------------------------------------------------

void render_container::overlay_scale(bitmap_argb32 &dest, bitmap_argb32 &source, const rectangle &sbounds, void *param)
{
	// simply replicate the source bitmap over the target
	for (int y = 0; y < dest.height(); y++)
	{
		u32 *src = &source.pix32(y % source.height());
		u32 *dst = &dest.pix32(y);
		int sx = 0;

		// loop over columns
		for (int x = 0; x < dest.width(); x++)
		{
			*dst++ = src[sx++];
			if (sx >= source.width())
				sx = 0;
		}
	}
}


//-------------------------------------------------
//  add_generic - add a generic item to a
//  container
//-------------------------------------------------

render_container::item &render_container::add_generic(u8 type, float x0, float y0, float x1, float y1, rgb_t argb)
{
	item *newitem = m_item_allocator.alloc();

	assert(x0 == x0);
	assert(x1 == x1);
	assert(y0 == y0);
	assert(y1 == y1);

	// copy the data into the new item
	newitem->m_type = type;
	newitem->m_bounds.x0 = x0;
	newitem->m_bounds.y0 = y0;
	newitem->m_bounds.x1 = x1;
	newitem->m_bounds.y1 = y1;
	newitem->m_color.r = (float)argb.r() * (1.0f / 255.0f);
	newitem->m_color.g = (float)argb.g() * (1.0f / 255.0f);
	newitem->m_color.b = (float)argb.b() * (1.0f / 255.0f);
	newitem->m_color.a = (float)argb.a() * (1.0f / 255.0f);
	newitem->m_flags = 0;
	newitem->m_internal = 0;
	newitem->m_width = 0;
	newitem->m_texture = nullptr;

	// add the item to the container
	return m_itemlist.append(*newitem);
}


//-------------------------------------------------
//  recompute_lookups - recompute the lookup table
//  for the render container
//-------------------------------------------------

void render_container::recompute_lookups()
{
	// recompute the 256 entry lookup table
	for (int i = 0; i < 0x100; i++)
	{
		u8 adjustedval = apply_brightness_contrast_gamma(i);
		m_bcglookup256[i + 0x000] = adjustedval << 0;
		m_bcglookup256[i + 0x100] = adjustedval << 8;
		m_bcglookup256[i + 0x200] = adjustedval << 16;
		m_bcglookup256[i + 0x300] = adjustedval << 24;
	}

	// recompute the palette entries
	if (m_palclient != nullptr)
	{
		palette_t &palette = m_palclient->palette();
		const rgb_t *adjusted_palette = palette.entry_list_adjusted();
		int colors = palette.max_index();

		if (has_brightness_contrast_gamma_changes())
		{
			for (int i = 0; i < colors; i++)
			{
				rgb_t newval = adjusted_palette[i];
				m_bcglookup[i] = (newval & 0xff000000) |
										m_bcglookup256[0x200 + newval.r()] |
										m_bcglookup256[0x100 + newval.g()] |
										m_bcglookup256[0x000 + newval.b()];
			}
		}
		else
			memcpy(&m_bcglookup[0], adjusted_palette, colors * sizeof(rgb_t));
	}
}


//-------------------------------------------------
//  update_palette - update any dirty palette
//  entries
//-------------------------------------------------

void render_container::update_palette()
{
	// skip if no client
	if (m_palclient == nullptr)
		return;

	// get the dirty list
	u32 mindirty, maxdirty;
	const u32 *dirty = m_palclient->dirty_list(mindirty, maxdirty);

	// iterate over dirty items and update them
	if (dirty != nullptr)
	{
		palette_t &palette = m_palclient->palette();
		const rgb_t *adjusted_palette = palette.entry_list_adjusted();

		if (has_brightness_contrast_gamma_changes())
		{
			// loop over chunks of 32 entries, since we can quickly examine 32 at a time
			for (u32 entry32 = mindirty / 32; entry32 <= maxdirty / 32; entry32++)
			{
				u32 dirtybits = dirty[entry32];
				if (dirtybits != 0)

					// this chunk of 32 has dirty entries; fix them up
					for (u32 entry = 0; entry < 32; entry++)
						if (dirtybits & (1 << entry))
						{
							u32 finalentry = entry32 * 32 + entry;
							rgb_t newval = adjusted_palette[finalentry];
							m_bcglookup[finalentry] = (newval & 0xff000000) |
														m_bcglookup256[0x200 + newval.r()] |
														m_bcglookup256[0x100 + newval.g()] |
														m_bcglookup256[0x000 + newval.b()];
						}
			}
		}
		else
			memcpy(&m_bcglookup[mindirty], &adjusted_palette[mindirty], (maxdirty - mindirty + 1) * sizeof(rgb_t));
	}
}


//-------------------------------------------------
//  user_settings - constructor
//-------------------------------------------------

render_container::user_settings::user_settings()
	: m_orientation(0)
	, m_brightness(1.0f)
	, m_contrast(1.0f)
	, m_gamma(1.0f)
	, m_xscale(1.0f)
	, m_yscale(1.0f)
	, m_xoffset(0.0f)
	, m_yoffset(0.0f)
{
}



//**************************************************************************
//  RENDER TARGET
//**************************************************************************

//-------------------------------------------------
//  render_target - constructor
//-------------------------------------------------

render_target::render_target(render_manager &manager, const internal_layout *layoutfile, u32 flags)
	: render_target(manager, layoutfile, flags, CONSTRUCTOR_IMPL)
{
}

render_target::render_target(render_manager &manager, util::xml::data_node const &layout, u32 flags)
	: render_target(manager, layout, flags, CONSTRUCTOR_IMPL)
{
}

template <typename T> render_target::render_target(render_manager &manager, T &&layout, u32 flags, constructor_impl_t)
	: m_next(nullptr)
	, m_manager(manager)
	, m_curview(nullptr)
	, m_flags(flags)
	, m_listindex(0)
	, m_width(640)
	, m_height(480)
	, m_pixel_aspect(0.0f)
	, m_max_refresh(0)
	, m_orientation(0)
	, m_base_view(nullptr)
	, m_base_orientation(ROT0)
	, m_maxtexwidth(65536)
	, m_maxtexheight(65536)
	, m_transform_container(true)
	, m_external_artwork(false)
{
	// determine the base layer configuration based on options
	m_base_layerconfig.set_zoom_to_screen(manager.machine().options().artwork_crop());

	// aspect and scale options
	m_keepaspect = (manager.machine().options().keep_aspect() && !(flags & RENDER_CREATE_HIDDEN));
	m_int_overscan = manager.machine().options().int_overscan();
	m_int_scale_x = manager.machine().options().int_scale_x();
	m_int_scale_y = manager.machine().options().int_scale_y();
	if (m_manager.machine().options().auto_stretch_xy())
		m_scale_mode = SCALE_FRACTIONAL_AUTO;
	else if (manager.machine().options().uneven_stretch_x())
		m_scale_mode = SCALE_FRACTIONAL_X;
	else if (manager.machine().options().uneven_stretch_y())
		m_scale_mode = SCALE_FRACTIONAL_Y;
	else if (manager.machine().options().uneven_stretch())
		m_scale_mode = SCALE_FRACTIONAL;
	else
		m_scale_mode = SCALE_INTEGER;

	// determine the base orientation based on options
	if (!manager.machine().options().rotate())
		m_base_orientation = orientation_reverse(manager.machine().system().flags & machine_flags::MASK_ORIENTATION);

	// rotate left/right
	if (manager.machine().options().ror() || (manager.machine().options().auto_ror() && (manager.machine().system().flags & ORIENTATION_SWAP_XY)))
		m_base_orientation = orientation_add(ROT90, m_base_orientation);
	if (manager.machine().options().rol() || (manager.machine().options().auto_rol() && (manager.machine().system().flags & ORIENTATION_SWAP_XY)))
		m_base_orientation = orientation_add(ROT270, m_base_orientation);

	// flip X/Y
	if (manager.machine().options().flipx())
		m_base_orientation ^= ORIENTATION_FLIP_X;
	if (manager.machine().options().flipy())
		m_base_orientation ^= ORIENTATION_FLIP_Y;

	// set the orientation and layerconfig equal to the base
	m_orientation = m_base_orientation;
	m_layerconfig = m_base_layerconfig;

	// load the layout files
	load_layout_files(std::forward<T>(layout), flags & RENDER_CREATE_SINGLE_FILE);

	// set the current view to the first one
	set_view(0);

	// make us the UI target if there is none
	if (!hidden() && manager.m_ui_target == nullptr)
		manager.set_ui_target(*this);
}


//-------------------------------------------------
//  ~render_target - destructor
//-------------------------------------------------

render_target::~render_target()
{
}


//-------------------------------------------------
//  is_ui_target - return true if this is the
//  UI target
//-------------------------------------------------

bool render_target::is_ui_target() const
{
	return (this == &m_manager.ui_target());
}


//-------------------------------------------------
//  index - return the index of this target
//-------------------------------------------------

int render_target::index() const
{
	return m_manager.m_targetlist.indexof(*this);
}


//-------------------------------------------------
//  set_bounds - set the bounds and pixel aspect
//  of a target
//-------------------------------------------------

void render_target::set_bounds(s32 width, s32 height, float pixel_aspect)
{
	m_width = width;
	m_height = height;
	m_bounds.x0 = m_bounds.y0 = 0;
	m_bounds.x1 = (float)width;
	m_bounds.y1 = (float)height;
	m_pixel_aspect = pixel_aspect != 0.0? pixel_aspect : 1.0;
}


//-------------------------------------------------
//  set_view - dynamically change the view for
//  a target
//-------------------------------------------------

void render_target::set_view(int viewindex)
{
	layout_view *view = view_by_index(viewindex);
	if (view)
	{
		m_curview = view;
		view->recompute(m_layerconfig);
	}
}


//-------------------------------------------------
//  set_max_texture_size - set the upper bound on
//  the texture size
//-------------------------------------------------

void render_target::set_max_texture_size(int maxwidth, int maxheight)
{
	m_maxtexwidth = maxwidth;
	m_maxtexheight = maxheight;
}


//-------------------------------------------------
//  configured_view - select a view for this
//  target based on the configuration parameters
//-------------------------------------------------

int render_target::configured_view(const char *viewname, int targetindex, int numtargets)
{
	layout_view *view = nullptr;
	int viewindex;

	// auto view just selects the nth view
	if (strcmp(viewname, "auto") != 0)
	{
		// scan for a matching view name
		size_t viewlen = strlen(viewname);
		for (view = view_by_index(viewindex = 0); view != nullptr; view = view_by_index(++viewindex))
			if (core_strnicmp(view->name().c_str(), viewname, viewlen) == 0)
				break;
	}

	// if we don't have a match, default to the nth view
	screen_device_iterator iter(m_manager.machine().root_device());
	int scrcount = iter.count();
	if (view == nullptr && scrcount > 0)
	{
		// if we have enough targets to be one per screen, assign in order
		if (numtargets >= scrcount)
		{
			int ourindex = index() % scrcount;
			screen_device *screen = iter.byindex(ourindex);
			assert(screen != nullptr);

			// find the first view with this screen and this screen only
			for (view = view_by_index(viewindex = 0); view != nullptr; view = view_by_index(++viewindex))
			{
				auto const &viewscreens = view->screens();
				if (viewscreens.empty())
				{
					view = nullptr;
					break;
				}
				else if (std::find_if(viewscreens.begin(), viewscreens.end(), [&screen](auto const &scr) { return &scr.get() != screen; }) == viewscreens.end())
					break;
			}
		}

		// otherwise, find the first view that has all the screens
		if (view == nullptr)
		{
			for (view = view_by_index(viewindex = 0); view != nullptr; view = view_by_index(++viewindex))
			{
				if (view->screen_count() >= scrcount)
				{
					bool screen_missing(false);
					for (screen_device &screen : iter)
					{
						if (!view->has_screen(screen))
						{
							screen_missing = true;
							break;
						}
					}
					if (!screen_missing)
						break;
				}
			}
		}
	}

	// make sure it's a valid view
	return (view != nullptr) ? view_index(*view) : 0;
}


//-------------------------------------------------
//  view_name - return the name of the given view
//-------------------------------------------------

const char *render_target::view_name(int viewindex)
{
	layout_view const *const view = view_by_index(viewindex);
	return view ? view->name().c_str() : nullptr;
}


//-------------------------------------------------
//  compute_visible_area - compute the visible
//  area for the given target with the current
//  layout and proposed new parameters
//-------------------------------------------------

void render_target::compute_visible_area(s32 target_width, s32 target_height, float target_pixel_aspect, int target_orientation, s32 &visible_width, s32 &visible_height)
{
	switch (m_scale_mode)
	{
	case SCALE_FRACTIONAL:
		{
			float width, height;
			float scale;

			// constrained case
			if (m_keepaspect)
			{
				// start with the aspect ratio of the square pixel layout
				width = m_curview->effective_aspect(m_layerconfig);
				height = 1.0f;

				// first apply target orientation
				if (target_orientation & ORIENTATION_SWAP_XY)
					std::swap(width, height);

				// apply the target pixel aspect ratio
				height *= target_pixel_aspect;

				// based on the height/width ratio of the source and target, compute the scale factor
				if (width / height > (float)target_width / (float)target_height)
					scale = (float)target_width / width;
				else
					scale = (float)target_height / height;
			}

			// stretch-to-fit case
			else
			{
				width = (float)target_width;
				height = (float)target_height;
				scale = 1.0f;
			}

			// set the final width/height
			visible_width = render_round_nearest(width * scale);
			visible_height = render_round_nearest(height * scale);
			break;
		}

	default:
		{
			// get source size and aspect
			s32 src_width, src_height;
			compute_minimum_size(src_width, src_height);
			float src_aspect = m_curview->effective_aspect(m_layerconfig);

			// apply orientation if required
			if (target_orientation & ORIENTATION_SWAP_XY)
				src_aspect = 1.0 / src_aspect;

			// get target aspect
			float target_aspect = (float)target_width / (float)target_height * target_pixel_aspect;
			bool target_is_portrait = (target_aspect < 1.0f);

			// apply automatic axial stretching if required
			int scale_mode = m_scale_mode;
			if (m_scale_mode == SCALE_FRACTIONAL_AUTO)
			{
				bool is_rotated = (m_manager.machine().system().flags & ORIENTATION_SWAP_XY) ^ (target_orientation & ORIENTATION_SWAP_XY);
				scale_mode = is_rotated ^ target_is_portrait ? SCALE_FRACTIONAL_Y : SCALE_FRACTIONAL_X;
			}

			// determine the scale mode for each axis
			bool x_is_integer = !((!target_is_portrait && scale_mode == SCALE_FRACTIONAL_X) || (target_is_portrait && scale_mode == SCALE_FRACTIONAL_Y));
			bool y_is_integer = !((target_is_portrait && scale_mode == SCALE_FRACTIONAL_X) || (!target_is_portrait && scale_mode == SCALE_FRACTIONAL_Y));

			// first compute scale factors to fit the screen
			float xscale = (float)target_width / src_width;
			float yscale = (float)target_height / src_height;
			float maxxscale = std::max(1.0f, float(m_int_overscan ? render_round_nearest(xscale) : floor(xscale)));
			float maxyscale = std::max(1.0f, float(m_int_overscan ? render_round_nearest(yscale) : floor(yscale)));

			// now apply desired scale mode and aspect correction
			if (m_keepaspect && target_aspect > src_aspect) xscale *= src_aspect / target_aspect * (maxyscale / yscale);
			if (m_keepaspect && target_aspect < src_aspect) yscale *= target_aspect / src_aspect * (maxxscale / xscale);
			if (x_is_integer) xscale = std::min(maxxscale, std::max(1.0f, render_round_nearest(xscale)));
			if (y_is_integer) yscale = std::min(maxyscale, std::max(1.0f, render_round_nearest(yscale)));

			// check if we have user defined scale factors, if so use them instead
			int user_scale_x = target_is_portrait? m_int_scale_y : m_int_scale_x;
			int user_scale_y = target_is_portrait? m_int_scale_x : m_int_scale_y;
			xscale = user_scale_x > 0 ? user_scale_x : xscale;
			yscale = user_scale_y > 0 ? user_scale_y : yscale;

			// set the final width/height
			visible_width = render_round_nearest(src_width * xscale);
			visible_height = render_round_nearest(src_height * yscale);
			break;
		}
	}
}


//-------------------------------------------------
//  compute_minimum_size - compute the "minimum"
//  size of a target, which is the smallest bounds
//  that will ensure at least 1 target pixel per
//  source pixel for all included screens
//-------------------------------------------------

void render_target::compute_minimum_size(s32 &minwidth, s32 &minheight)
{
	float maxxscale = 1.0f, maxyscale = 1.0f;
	int screens_considered = 0;

	// early exit in case we are called between device teardown and render teardown
	if (m_manager.machine().phase() == machine_phase::EXIT)
	{
		minwidth = 640;
		minheight = 480;
		return;
	}

	if (!m_curview)
		throw emu_fatalerror("Mandatory artwork is missing");

	// scan the current view for all screens
	for (layout_view::item &curitem : m_curview->items())
	{
		if (curitem.screen())
		{
			// use a hard-coded default visible area for vector screens
			screen_device *const screen = curitem.screen();
			const rectangle vectorvis(0, 639, 0, 479);
			const rectangle &visarea = (screen->screen_type() == SCREEN_TYPE_VECTOR) ? vectorvis : screen->visible_area();

			// apply target orientation to the bounds
			render_bounds bounds = curitem.bounds();
			apply_orientation(bounds, m_orientation);
			normalize_bounds(bounds);

			// based on the orientation of the screen container, check the bitmap
			float xscale, yscale;
			if (!(orientation_add(m_orientation, screen->container().orientation()) & ORIENTATION_SWAP_XY))
			{
				xscale = float(visarea.width()) / bounds.width();
				yscale = float(visarea.height()) / bounds.height();
			}
			else
			{
				xscale = float(visarea.height()) / bounds.width();
				yscale = float(visarea.width()) / bounds.height();
			}

			// pick the greater
			maxxscale = std::max(xscale, maxxscale);
			maxyscale = std::max(yscale, maxyscale);
			screens_considered++;
		}
	}

	// if there were no screens considered, pick a nominal default
	if (screens_considered == 0)
	{
		maxxscale = 640.0f;
		maxyscale = 480.0f;
	}

	// round up
	minwidth = render_round_nearest(maxxscale);
	minheight = render_round_nearest(maxyscale);
}


//-------------------------------------------------
//  get_primitives - return a list of primitives
//  for a given render target
//-------------------------------------------------

render_primitive_list &render_target::get_primitives()
{
	// remember the base values if this is the first frame
	if (m_base_view == nullptr)
		m_base_view = m_curview;

	// switch to the next primitive list
	render_primitive_list &list = m_primlist[m_listindex];
	m_listindex = (m_listindex + 1) % ARRAY_LENGTH(m_primlist);
	list.acquire_lock();

	// free any previous primitives
	list.release_all();

	// compute the visible width/height
	s32 viswidth, visheight;
	compute_visible_area(m_width, m_height, m_pixel_aspect, m_orientation, viswidth, visheight);

	// create a root transform for the target
	object_transform root_xform;
	root_xform.xoffs = (float)(m_width - viswidth) / 2;
	root_xform.yoffs = (float)(m_height - visheight) / 2;
	root_xform.xscale = (float)viswidth;
	root_xform.yscale = (float)visheight;
	root_xform.color.r = root_xform.color.g = root_xform.color.b = root_xform.color.a = 1.0f;
	root_xform.orientation = m_orientation;
	root_xform.no_center = false;

	// iterate over items in the view, but only if we're running
	if (m_manager.machine().phase() >= machine_phase::RESET)
		for (layout_view::item &curitem : m_curview->items())
		{
			// first apply orientation to the bounds
			render_bounds bounds = curitem.bounds();
			apply_orientation(bounds, root_xform.orientation);
			normalize_bounds(bounds);

			// apply the transform to the item
			object_transform item_xform;
			item_xform.xoffs = root_xform.xoffs + bounds.x0 * root_xform.xscale;
			item_xform.yoffs = root_xform.yoffs + bounds.y0 * root_xform.yscale;
			item_xform.xscale = (bounds.x1 - bounds.x0) * root_xform.xscale;
			item_xform.yscale = (bounds.y1 - bounds.y0) * root_xform.yscale;
			item_xform.color.r = curitem.color().r * root_xform.color.r;
			item_xform.color.g = curitem.color().g * root_xform.color.g;
			item_xform.color.b = curitem.color().b * root_xform.color.b;
			item_xform.color.a = curitem.color().a * root_xform.color.a;
			item_xform.orientation = orientation_add(curitem.orientation(), root_xform.orientation);
			item_xform.no_center = false;

			// if there is no associated element, it must be a screen element
			if (curitem.screen() != nullptr)
				add_container_primitives(list, root_xform, item_xform, curitem.screen()->container(), curitem.blend_mode());
			else
				add_element_primitives(list, item_xform, *curitem.element(), curitem.state(), curitem.blend_mode());
		}

	// if we are not in the running stage, draw an outer box
	else
	{
		render_primitive *prim = list.alloc(render_primitive::QUAD);
		set_render_bounds_xy(prim->bounds, 0.0f, 0.0f, (float)m_width, (float)m_height);
		prim->full_bounds = prim->bounds;
		set_render_color(&prim->color, 1.0f, 0.1f, 0.1f, 0.1f);
		prim->texture.base = nullptr;
		prim->flags = PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA);
		list.append(*prim);

		if (m_width > 1 && m_height > 1)
		{
			prim = list.alloc(render_primitive::QUAD);
			set_render_bounds_xy(prim->bounds, 1.0f, 1.0f, (float)(m_width - 1), (float)(m_height - 1));
			prim->full_bounds = prim->bounds;
			set_render_color(&prim->color, 1.0f, 0.0f, 0.0f, 0.0f);
			prim->texture.base = nullptr;
			prim->flags = PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA);
			list.append(*prim);
		}
	}

	// process the debug containers
	for (render_container &debug : m_debug_containers)
	{
		object_transform ui_xform;
		ui_xform.xoffs = 0;
		ui_xform.yoffs = 0;
		ui_xform.xscale = (float)m_width;
		ui_xform.yscale = (float)m_height;
		ui_xform.color.r = ui_xform.color.g = ui_xform.color.b = 1.0f;
		ui_xform.color.a = 0.9f;
		ui_xform.orientation = m_orientation;
		ui_xform.no_center = true;

		// add UI elements
		add_container_primitives(list, root_xform, ui_xform, debug, BLENDMODE_ALPHA);
	}

	// process the UI if we are the UI target
	if (is_ui_target())
	{
		// compute the transform for the UI
		object_transform ui_xform;
		ui_xform.xoffs = 0;
		ui_xform.yoffs = 0;
		ui_xform.xscale = (float) m_width;
		ui_xform.yscale = (float) m_height;
		ui_xform.color.r = ui_xform.color.g = ui_xform.color.b = ui_xform.color.a = 1.0f;
		ui_xform.orientation = m_orientation;
		ui_xform.no_center = false;

		// add UI elements
		add_container_primitives(list, root_xform, ui_xform, m_manager.ui_container(), BLENDMODE_ALPHA);
	}

	// optimize the list before handing it off
	add_clear_and_optimize_primitive_list(list);
	list.release_lock();
	return list;
}


//-------------------------------------------------
//  map_point_container - attempts to map a point
//  on the specified render_target to the
//  specified container, if possible
//-------------------------------------------------

bool render_target::map_point_container(s32 target_x, s32 target_y, render_container &container, float &container_x, float &container_y)
{
	ioport_port *input_port;
	ioport_value input_mask;
	return map_point_internal(target_x, target_y, &container, container_x, container_y, input_port, input_mask);
}


//-------------------------------------------------
//  map_point_input - attempts to map a point on
//  the specified render_target to the specified
//  container, if possible
//-------------------------------------------------

bool render_target::map_point_input(s32 target_x, s32 target_y, ioport_port *&input_port, ioport_value &input_mask, float &input_x, float &input_y)
{
	return map_point_internal(target_x, target_y, nullptr, input_x, input_y, input_port, input_mask);;
}


//-------------------------------------------------
//  invalidate_all - if any of our primitive lists
//  contain a reference to the given pointer,
//  clear them
//-------------------------------------------------

void render_target::invalidate_all(void *refptr)
{
	// iterate through all our primitive lists
	for (auto & list : m_primlist)
	{
		// if we have a reference to this object, release our list
		list.acquire_lock();
		if (list.has_reference(refptr))
			list.release_all();
		list.release_lock();
	}
}


//-------------------------------------------------
//  debug_alloc - allocate a container for a debug
//  view
//-------------------------------------------------

render_container *render_target::debug_alloc()
{
	return &m_debug_containers.append(*m_manager.container_alloc());
}


//-------------------------------------------------
//  debug_free - free a container for a debug view
//-------------------------------------------------

void render_target::debug_free(render_container &container)
{
	m_debug_containers.remove(container);
}


//-------------------------------------------------
//  debug_append - move a debug view container to
//  the end of the list
//-------------------------------------------------

void render_target::debug_append(render_container &container)
{
	m_debug_containers.append(m_debug_containers.detach(container));
}


//-------------------------------------------------
//  resolve_tags - resolve tag lookups
//-------------------------------------------------

void render_target::resolve_tags()
{
	for (layout_file &file : m_filelist)
	{
		for (layout_view &view : file.views())
		{
			view.resolve_tags();
		}
	}
}


//-------------------------------------------------
//  update_layer_config - recompute after a layer
//  config change
//-------------------------------------------------

void render_target::update_layer_config()
{
	m_curview->recompute(m_layerconfig);
}


//-------------------------------------------------
//  load_layout_files - load layout files for a
//  given render target
//-------------------------------------------------

void render_target::load_layout_files(const internal_layout *layoutfile, bool singlefile)
{
	bool have_artwork = false;

	// if there's an explicit file, load that first
	const std::string &basename = m_manager.machine().basename();
	if (layoutfile)
		have_artwork |= load_layout_file(basename.c_str(), *layoutfile);

	// if we're only loading this file, we know our final result
	if (!singlefile)
		load_additional_layout_files(basename.c_str(), have_artwork);
}

void render_target::load_layout_files(util::xml::data_node const &rootnode, bool singlefile)
{
	bool have_artwork = false;

	// if there's an explicit file, load that first
	const std::string &basename = m_manager.machine().basename();
	have_artwork |= load_layout_file(m_manager.machine().root_device(), basename.c_str(), rootnode);

	// if we're only loading this file, we know our final result
	if (!singlefile)
		load_additional_layout_files(basename.c_str(), have_artwork);
}

void render_target::load_additional_layout_files(const char *basename, bool have_artwork)
{
	m_external_artwork = false;

	// if override_artwork defined, load that and skip artwork other than default
	const char *const override_art = m_manager.machine().options().override_artwork();
	if (override_art && *override_art)
	{
		if (load_layout_file(override_art, override_art))
			m_external_artwork = true;
		else if (load_layout_file(override_art, "default"))
			m_external_artwork = true;
	}

	const game_driver &system = m_manager.machine().system();

	// Skip if override_artwork has found artwork
	if (!m_external_artwork)
	{
		// try to load a file based on the driver name
		if (!load_layout_file(basename, system.name))
			m_external_artwork |= load_layout_file(basename, "default");
		else
			m_external_artwork = true;

		// if a default view has been specified, use that as a fallback
		bool have_default = false;
		if (system.default_layout)
			have_default |= load_layout_file(nullptr, *system.default_layout);
		m_manager.machine().config().apply_default_layouts(
				[this, &have_default] (device_t &dev, internal_layout const &layout)
				{ have_default |= load_layout_file(nullptr, layout, &dev); });

		// try to load another file based on the parent driver name
		int cloneof = driver_list::clone(system);
		while (0 <= cloneof)
		{
			if (!load_layout_file(driver_list::driver(cloneof).name, driver_list::driver(cloneof).name))
				m_external_artwork |= load_layout_file(driver_list::driver(cloneof).name, "default");
			else
				m_external_artwork = true;

			// Check the parent of the parent to cover bios based artwork
			const game_driver &parent(driver_list::driver(cloneof));
			cloneof = driver_list::clone(parent);
		}

		have_artwork |= m_external_artwork;

		// Use fallback artwork if defined and no artwork has been found yet
		if (!have_artwork)
		{
			const char *const fallback_art = m_manager.machine().options().fallback_artwork();
			if (fallback_art && *fallback_art)
			{
				if (!load_layout_file(fallback_art, fallback_art))
					have_artwork |= load_layout_file(fallback_art, "default");
				else
					have_artwork = true;
			}
		}
	}

	// local screen info to avoid repeated code
	class screen_info
	{
	public:
		screen_info(screen_device const &screen)
			: m_device(screen)
			, m_rotated(screen.orientation() & ORIENTATION_SWAP_XY)
			, m_physical(screen.physical_aspect())
			, m_native(screen.visible_area().width(), screen.visible_area().height())
		{
			util::reduce_fraction(m_native.first, m_native.second);
			if (m_rotated)
			{
				std::swap(m_physical.first, m_physical.second);
				std::swap(m_native.first, m_native.second);
			}
		}

		screen_device const &device() const { return m_device.get(); }
		bool rotated() const { return m_rotated; }
		bool square() const { return m_physical == m_native; }
		unsigned physical_x() const { return m_physical.first; }
		unsigned physical_y() const { return m_physical.second; }
		unsigned native_x() const { return m_native.first; }
		unsigned native_y() const { return m_native.second; }

		std::pair<float, float> tiled_size() const
		{
			if (physical_x() == physical_y())
				return std::make_pair(1.0F, 1.0F);
			else if (physical_x() > physical_y())
				return std::make_pair(1.0F, float(physical_y()) / physical_x());
			else
				return std::make_pair(float(physical_x()) / physical_y(), 1.0F);
		}

	private:
		std::reference_wrapper<screen_device const> m_device;
		bool m_rotated;
		std::pair<unsigned, unsigned> m_physical, m_native;
	};
	screen_device_iterator iter(m_manager.machine().root_device());
	std::vector<screen_info> const screens(std::begin(iter), std::end(iter));


	if (screens.empty()) // ensure the fallback view for systems with no screens is loaded if necessary
	{
		if (!view_by_index(0))
		{
			load_layout_file(nullptr, layout_noscreens);
			if (m_filelist.empty())
				throw emu_fatalerror("Couldn't parse default layout??");
		}
	}
	else // generate default layouts for larger numbers of screens
	{
		util::xml::file::ptr const root(util::xml::file::create());
		if (!root)
			throw emu_fatalerror("Couldn't create XML document??");
		util::xml::data_node *const layoutnode(root->add_child("mamelayout", nullptr));
		if (!layoutnode)
			throw emu_fatalerror("Couldn't create XML node??");
		layoutnode->set_attribute_int("version", 2);

		// generate individual physical aspect views
		for (unsigned i = 0; screens.size() > i; ++i)
		{
			util::xml::data_node *const viewnode(layoutnode->add_child("view", nullptr));
			if (!viewnode)
				throw emu_fatalerror("Couldn't create XML node??");
			viewnode->set_attribute(
					"name",
					util::xml::normalize_string(
						util::string_format(
							"Screen %1$u Standard (%2$u:%3$u)",
							i, screens[i].physical_x(), screens[i].physical_y()).c_str()));
			util::xml::data_node *const screennode(viewnode->add_child("screen", nullptr));
			if (!screennode)
				throw emu_fatalerror("Couldn't create XML node??");
			screennode->set_attribute_int("index", i);
			util::xml::data_node *const boundsnode(screennode->add_child("bounds", nullptr));
			if (!boundsnode)
				throw emu_fatalerror("Couldn't create XML node??");
			boundsnode->set_attribute_int("x", 0);
			boundsnode->set_attribute_int("y", 0);
			boundsnode->set_attribute_int("width", screens[i].physical_x());
			boundsnode->set_attribute_int("height", screens[i].physical_y());
		}

		// generate individual pixel aspect views
		for (unsigned i = 0; screens.size() > i; ++i)
		{
			if (!screens[i].square())
			{
				util::xml::data_node *const viewnode(layoutnode->add_child("view", nullptr));
				if (!viewnode)
					throw emu_fatalerror("Couldn't create XML node??");
				viewnode->set_attribute(
						"name",
						util::xml::normalize_string(
							util::string_format(
								"Screen %1$u Pixel Aspect (%2$u:%3$u)",
								i, screens[i].native_x(), screens[i].native_y()).c_str()));
				util::xml::data_node *const screennode(viewnode->add_child("screen", nullptr));
				if (!screennode)
					throw emu_fatalerror("Couldn't create XML node??");
				screennode->set_attribute_int("index", i);
				util::xml::data_node *const boundsnode(screennode->add_child("bounds", nullptr));
				if (!boundsnode)
					throw emu_fatalerror("Couldn't create XML node??");
				boundsnode->set_attribute_int("x", 0);
				boundsnode->set_attribute_int("y", 0);
				boundsnode->set_attribute_int("width", screens[i].native_x());
				boundsnode->set_attribute_int("height", screens[i].native_y());
			}
		}

		// generate the fake cocktail view for single-screen systems
		if (screens.size() == 1U)
		{
			util::xml::data_node *const viewnode(layoutnode->add_child("view", nullptr));
			if (!viewnode)
				throw emu_fatalerror("Couldn't create XML node??");
			viewnode->set_attribute("name", "Cocktail");

			util::xml::data_node *const mirrornode(viewnode->add_child("screen", nullptr));
			if (!mirrornode)
				throw emu_fatalerror("Couldn't create XML node??");
			mirrornode->set_attribute_int("index", 0);
			util::xml::data_node *const mirrorbounds(mirrornode->add_child("bounds", nullptr));
			if (!mirrorbounds)
				throw emu_fatalerror("Couldn't create XML node??");
			mirrorbounds->set_attribute_int("x", 0);
			mirrorbounds->set_attribute_float("y", (-0.01 * (std::min)(screens[0].physical_x(), screens[0].physical_y())) - screens[0].physical_y());
			mirrorbounds->set_attribute_int("width", screens[0].physical_x());
			mirrorbounds->set_attribute_int("height", screens[0].physical_y());
			util::xml::data_node *const flipper(mirrornode->add_child("orientation", nullptr));
			if (!flipper)
				throw emu_fatalerror("Couldn't create XML node??");
			flipper->set_attribute_int("rotate", 180);

			util::xml::data_node *const screennode(viewnode->add_child("screen", nullptr));
			if (!screennode)
				throw emu_fatalerror("Couldn't create XML node??");
			screennode->set_attribute_int("index", 0);
			util::xml::data_node *const screenbounds(screennode->add_child("bounds", nullptr));
			if (!screenbounds)
				throw emu_fatalerror("Couldn't create XML node??");
			screenbounds->set_attribute_int("x", 0);
			screenbounds->set_attribute_int("y", 0);
			screenbounds->set_attribute_int("width", screens[0].physical_x());
			screenbounds->set_attribute_int("height", screens[0].physical_y());
		}

		// generate tiled views if the supplied artwork doesn't provide a view of all screens
		bool need_tiles(screens.size() >= 3);
		if (!need_tiles && (screens.size() >= 2))
		{
			need_tiles = true;
			int viewindex(0);
			for (layout_view *view = view_by_index(viewindex); need_tiles && view; view = view_by_index(++viewindex))
			{
				if (view->screen_count() >= screens.size())
				{
					bool screen_missing(false);
					for (screen_device &screen : iter)
					{
						if (!view->has_screen(screen))
						{
							screen_missing = true;
							break;
						}
					}
					if (!screen_missing)
						need_tiles = false;
				}
			}
		}
		if (need_tiles)
		{
			// helpers for generating a view since we do this a lot
			std::vector<float> widths(screens.size()), heights(screens.size());
			std::vector<std::pair<float, float> > sizes(screens.size());
			std::transform(screens.begin(), screens.end(), sizes.begin(), [] (screen_info const &s) { return s.tiled_size(); });
			auto const generate_view =
					[&layoutnode, &screens, &widths, &heights, &sizes] (char const *title, unsigned columns, bool gapless, auto &&mapper)
					{
						// calculate necessary widths/heights of rows/columns restricting screens to unit square
						assert(0U < columns);
						assert(screens.size() >= columns);
						unsigned const rows((screens.size() + columns - 1) / columns);
						std::fill_n(widths.begin(), columns, 0.0F);
						std::fill_n(heights.begin(), rows, 0.0F);
						for (unsigned y = 0U; rows > y; ++y)
						{
							for (unsigned x = 0U; columns > x; ++x)
							{
								int const i(mapper(x, y));
								if (0 <= i)
								{
									widths[x] = (std::max)(widths[x], sizes[i].first);
									heights[y] = (std::max)(heights[y], sizes[i].second);
								}
							}
						}

						// spacing is 1% of minor dimension
						float spacing(0.0F);
						if (!gapless)
						{
							spacing = 0.01F * (std::min)(
									*std::max_element(widths.begin(), widths.begin() + columns),
									*std::max_element(heights.begin(), heights.begin() + rows));
						}

						// actually generate elements
						util::xml::data_node *viewnode = layoutnode->add_child("view", nullptr);
						if (!viewnode)
							throw emu_fatalerror("Couldn't create XML node??");
						viewnode->set_attribute("name", util::xml::normalize_string(title));
						float ypos(0.0F);
						for (unsigned y = 0U; rows > y; ypos += heights[y] + spacing, ++y)
						{
							float xpos(0.0F);
							for (unsigned x = 0U; columns > x; xpos += widths[x] + spacing, ++x)
							{
								int const i(mapper(x, y));
								if (0 <= i)
								{
									util::xml::data_node *const screennode(viewnode->add_child("screen", nullptr));
									if (!screennode)
										throw emu_fatalerror("Couldn't create XML node??");
									screennode->set_attribute_int("index", i);
									util::xml::data_node *const boundsnode(screennode->add_child("bounds", nullptr));
									if (!boundsnode)
										throw emu_fatalerror("Couldn't create XML node??");
									boundsnode->set_attribute_float("x", xpos + ((widths[x] - sizes[i].first) / 2));
									boundsnode->set_attribute_float("y", ypos + ((heights[y] - sizes[i].second) / 2));
									boundsnode->set_attribute_float("width", sizes[i].first);
									boundsnode->set_attribute_float("height", sizes[i].second);
								}
							}
						}
					};

			// generate linear views
			generate_view("Left-to-Right", screens.size(), false, [] (unsigned x, unsigned y) { return x; });
			generate_view("Left-to-Right (Gapless)", screens.size(), true, [] (unsigned x, unsigned y) { return x; });
			generate_view("Top-to-Bottom", 1U, false, [] (unsigned x, unsigned y) { return y; });
			generate_view("Top-to-Bottom (Gapless)", 1U, true, [] (unsigned x, unsigned y) { return y; });

			// generate fake cocktail view for systems with two screens
			if (screens.size() == 2U)
			{
				float const height0(float(screens[0].physical_y()) / screens[0].physical_x());
				float const height1(float(screens[1].physical_y()) / screens[1].physical_x());
				float const minor_dim((std::max)((std::min)(height0, 1.0F), (std::min)(height1, 1.0F)));

				util::xml::data_node *const viewnode(layoutnode->add_child("view", nullptr));
				if (!viewnode)
					throw emu_fatalerror("Couldn't create XML node??");
				viewnode->set_attribute("name", "Cocktail");

				util::xml::data_node *const mirrornode(viewnode->add_child("screen", nullptr));
				if (!mirrornode)
					throw emu_fatalerror("Couldn't create XML node??");
				mirrornode->set_attribute_int("index", 1);
				util::xml::data_node *const mirrorbounds(mirrornode->add_child("bounds", nullptr));
				if (!mirrorbounds)
					throw emu_fatalerror("Couldn't create XML node??");
				mirrorbounds->set_attribute_int("x", 0);
				mirrorbounds->set_attribute_float("y", (-0.01 * minor_dim) - height1);
				mirrorbounds->set_attribute_int("width", 1);
				mirrorbounds->set_attribute_float("height", height1);
				util::xml::data_node *const flipper(mirrornode->add_child("orientation", nullptr));
				if (!flipper)
					throw emu_fatalerror("Couldn't create XML node??");
				flipper->set_attribute_int("rotate", 180);

				util::xml::data_node *const screennode(viewnode->add_child("screen", nullptr));
				if (!screennode)
					throw emu_fatalerror("Couldn't create XML node??");
				screennode->set_attribute_int("index", 0);
				util::xml::data_node *const screenbounds(screennode->add_child("bounds", nullptr));
				if (!screenbounds)
					throw emu_fatalerror("Couldn't create XML node??");
				screenbounds->set_attribute_int("x", 0);
				screenbounds->set_attribute_int("y", 0);
				screenbounds->set_attribute_int("width", 1);
				screenbounds->set_attribute_float("height", height0);
			}

			// generate tiled views
			for (unsigned mindim = 2; ((screens.size() + mindim - 1) / mindim) >= mindim; ++mindim)
			{
				unsigned const majdim((screens.size() + mindim - 1) / mindim);
				unsigned const remainder(screens.size() % majdim);
				if (!remainder || (((majdim + 1) / 2) <= remainder))
				{
					generate_view(
							util::string_format("%1$u\xC3\x97%2$u Left-to-Right, Top-to-Bottom", majdim, mindim).c_str(),
							majdim,
							false,
							[&screens, majdim] (unsigned x, unsigned y)
							{
								unsigned const i(x + (y * majdim));
								return (screens.size() > i) ? int(i) : -1;
							});
					generate_view(
							util::string_format("%1$u\xC3\x97%2$u Left-to-Right, Top-to-Bottom (Gapless)", majdim, mindim).c_str(),
							majdim,
							true,
							[&screens, majdim] (unsigned x, unsigned y)
							{
								unsigned const i(x + (y * majdim));
								return (screens.size() > i) ? int(i) : -1;
							});
					generate_view(
							util::string_format("%1$u\xC3\x97%2$u Top-to-Bottom, Left-to-Right", mindim, majdim).c_str(),
							mindim,
							false,
							[&screens, majdim] (unsigned x, unsigned y)
							{
								unsigned const i((x * majdim) + y);
								return (screens.size() > i) ? int(i) : -1;
							});
					generate_view(
							util::string_format("%1$u\xC3\x97%2$u Top-to-Bottom, Left-to-Right (Gapless)", mindim, majdim).c_str(),
							mindim,
							true,
							[&screens, majdim] (unsigned x, unsigned y)
							{
								unsigned const i((x * majdim) + y);
								return (screens.size() > i) ? int(i) : -1;
							});
				}
			}
		}

		// try to parse it
		if (!load_layout_file(m_manager.machine().root_device(), nullptr, *root))
			throw emu_fatalerror("Couldn't parse generated layout??");
	}
}


//-------------------------------------------------
//  load_layout_file - load a single layout file
//  and append it to our list
//-------------------------------------------------

bool render_target::load_layout_file(const char *dirname, const internal_layout &layout_data, device_t *device)
{
	// +1 to ensure data is terminated for XML parser
	auto tempout = make_unique_clear<u8 []>(layout_data.decompressed_size + 1);

	z_stream stream;
	int zerr;

	// initialize the stream
	memset(&stream, 0, sizeof(stream));
	stream.next_out = tempout.get();
	stream.avail_out = layout_data.decompressed_size;

	zerr = inflateInit(&stream);
	if (zerr != Z_OK)
	{
		fatalerror("could not inflateInit");
		return false;
	}

	// decompress this chunk
	stream.next_in = (unsigned char *)layout_data.data;
	stream.avail_in = layout_data.compressed_size;
	zerr = inflate(&stream, Z_NO_FLUSH);

	// stop at the end of the stream
	if (zerr == Z_STREAM_END)
	{
		// OK
	}
	else if (zerr != Z_OK)
	{
		fatalerror("decompression error\n");
		return false;
	}

	// clean up
	zerr = inflateEnd(&stream);
	if (zerr != Z_OK)
	{
		fatalerror("inflateEnd error\n");
		return false;
	}

	util::xml::file::ptr rootnode(util::xml::file::string_read(reinterpret_cast<char const *>(tempout.get()), nullptr));
	tempout.reset();

	// if we didn't get a properly-formatted XML file, record a warning and exit
	if (!load_layout_file(device ? *device : m_manager.machine().root_device(), dirname, *rootnode))
	{
		osd_printf_warning("Improperly formatted XML string, ignoring\n");
		return false;
	}
	else
	{
		return true;
	}
}

bool render_target::load_layout_file(const char *dirname, const char *filename)
{
	// build the path and optionally prepend the directory
	std::string fname = std::string(filename).append(".lay");
	if (dirname)
		fname.insert(0, PATH_SEPARATOR).insert(0, dirname);

	// attempt to open the file; bail if we can't
	emu_file layoutfile(m_manager.machine().options().art_path(), OPEN_FLAG_READ);
	layoutfile.set_restrict_to_mediapath(1);
	osd_file::error const filerr(layoutfile.open(fname));
	if (filerr != osd_file::error::NONE)
		return false;

	// read the file
	util::xml::parse_options parseopt;
	util::xml::parse_error parseerr;
	parseopt.error = &parseerr;
	util::xml::file::ptr rootnode(util::xml::file::read(layoutfile, &parseopt));
	if (!rootnode)
	{
		if (parseerr.error_message)
		{
			osd_printf_warning(
					"Error parsing XML file '%s' at line %d column %d: %s, ignoring\n",
					filename,
					parseerr.error_line,
					parseerr.error_column,
					parseerr.error_message);
		}
		else
		{
			osd_printf_warning("Error parsing XML file '%s', ignorning\n", filename);
		}
		return false;
	}

	// if we didn't get a properly-formatted XML file, record a warning and exit
	if (!load_layout_file(m_manager.machine().root_device(), dirname, *rootnode))
	{
		osd_printf_warning("Improperly formatted XML file '%s', ignoring\n", filename);
		return false;
	}
	else
	{
		return true;
	}
}

bool render_target::load_layout_file(device_t &device, const char *dirname, util::xml::data_node const &rootnode)
{
	// parse and catch any errors
	try
	{
		m_filelist.emplace_back(device, rootnode, dirname);
	}
	catch (emu_fatalerror &)
	{
		return false;
	}

	emulator_info::layout_file_cb(rootnode);

	return true;
}


//-------------------------------------------------
//  add_container_primitives - add primitives
//  based on the container
//-------------------------------------------------

void render_target::add_container_primitives(render_primitive_list &list, const object_transform &root_xform, const object_transform &xform, render_container &container, int blendmode)
{
	// first update the palette for the container, if it is dirty
	container.update_palette();

	// compute the clip rect
	render_bounds cliprect;
	cliprect.x0 = xform.xoffs;
	cliprect.y0 = xform.yoffs;
	cliprect.x1 = xform.xoffs + xform.xscale;
	cliprect.y1 = xform.yoffs + xform.yscale;
	sect_render_bounds(cliprect, m_bounds);

	float root_xoffs = root_xform.xoffs + fabsf(root_xform.xscale - xform.xscale) * 0.5f;
	float root_yoffs = root_xform.yoffs + fabsf(root_xform.yscale - xform.yscale) * 0.5f;

	render_bounds root_cliprect;
	root_cliprect.x0 = root_xoffs;
	root_cliprect.y0 = root_yoffs;
	root_cliprect.x1 = root_xoffs + root_xform.xscale;
	root_cliprect.y1 = root_yoffs + root_xform.yscale;
	sect_render_bounds(root_cliprect, m_bounds);

	// compute the container transform
	object_transform container_xform;
	container_xform.orientation = orientation_add(container.orientation(), xform.orientation);
	{
		float xscale = (container_xform.orientation & ORIENTATION_SWAP_XY) ? container.yscale() : container.xscale();
		float yscale = (container_xform.orientation & ORIENTATION_SWAP_XY) ? container.xscale() : container.yscale();
		float xoffs = (container_xform.orientation & ORIENTATION_SWAP_XY) ? container.yoffset() : container.xoffset();
		float yoffs = (container_xform.orientation & ORIENTATION_SWAP_XY) ? container.xoffset() : container.yoffset();
		if (container_xform.orientation & ORIENTATION_FLIP_X) xoffs = -xoffs;
		if (container_xform.orientation & ORIENTATION_FLIP_Y) yoffs = -yoffs;
		if (!m_transform_container)
		{
			xscale = 1.0f;
			yscale = 1.0f;
			xoffs = 0.0f;
			yoffs = 0.0f;
		}
		container_xform.xscale = xform.xscale * xscale;
		container_xform.yscale = xform.yscale * yscale;
		if (xform.no_center)
		{
			container_xform.xoffs = xform.xscale * (xoffs) + xform.xoffs;
			container_xform.yoffs = xform.yscale * (yoffs) + xform.yoffs;
		}
		else
		{
			container_xform.xoffs = xform.xscale * (0.5f - 0.5f * xscale + xoffs) + xform.xoffs;
			container_xform.yoffs = xform.yscale * (0.5f - 0.5f * yscale + yoffs) + xform.yoffs;
		}
		container_xform.color = xform.color;
	}

	// iterate over elements
	for (render_container::item &curitem : container.items())
	{
		// compute the oriented bounds
		render_bounds bounds = curitem.bounds();
		apply_orientation(bounds, container_xform.orientation);

		float xscale = container_xform.xscale;
		float yscale = container_xform.yscale;
		float xoffs = container_xform.xoffs;
		float yoffs = container_xform.yoffs;
		if (!m_transform_container && PRIMFLAG_GET_VECTOR(curitem.flags()))
		{
			xoffs = root_xoffs;
			yoffs = root_yoffs;
		}

		// allocate the primitive and set the transformed bounds/color data
		render_primitive *prim = list.alloc(render_primitive::INVALID);

		prim->container = &container; /* pass the container along for access to user_settings */

		prim->bounds.x0 = render_round_nearest(xoffs + bounds.x0 * xscale);
		prim->bounds.y0 = render_round_nearest(yoffs + bounds.y0 * yscale);
		if (curitem.internal() & INTERNAL_FLAG_CHAR)
		{
			prim->bounds.x1 = prim->bounds.x0 + render_round_nearest((bounds.x1 - bounds.x0) * xscale);
			prim->bounds.y1 = prim->bounds.y0 + render_round_nearest((bounds.y1 - bounds.y0) * yscale);
		}
		else
		{
			prim->bounds.x1 = render_round_nearest(xoffs + bounds.x1 * xscale);
			prim->bounds.y1 = render_round_nearest(yoffs + bounds.y1 * yscale);
		}

		// compute the color of the primitive
		prim->color.r = container_xform.color.r * curitem.color().r;
		prim->color.g = container_xform.color.g * curitem.color().g;
		prim->color.b = container_xform.color.b * curitem.color().b;
		prim->color.a = container_xform.color.a * curitem.color().a;

		// copy unclipped bounds
		prim->full_bounds = prim->bounds;

		// now switch off the type
		bool clipped = true;
		switch (curitem.type())
		{
			case CONTAINER_ITEM_LINE:
				// adjust the color for brightness/contrast/gamma
				prim->color.a = container.apply_brightness_contrast_gamma_fp(prim->color.a);
				prim->color.r = container.apply_brightness_contrast_gamma_fp(prim->color.r);
				prim->color.g = container.apply_brightness_contrast_gamma_fp(prim->color.g);
				prim->color.b = container.apply_brightness_contrast_gamma_fp(prim->color.b);

				// set the line type
				prim->type = render_primitive::LINE;
				prim->flags |= PRIMFLAG_TYPE_LINE;

				// scale the width by the minimum of X/Y scale factors
				prim->width = curitem.width() * std::min(container_xform.xscale, container_xform.yscale);
				prim->flags |= curitem.flags();

				// clip the primitive
				if (!m_transform_container && PRIMFLAG_GET_VECTOR(curitem.flags()))
				{
					clipped = render_clip_line(&prim->bounds, &root_cliprect);
				}
				else
				{
					clipped = render_clip_line(&prim->bounds, &cliprect);
				}
				break;

			case CONTAINER_ITEM_QUAD:
				// set the quad type
				prim->type = render_primitive::QUAD;
				prim->flags |= PRIMFLAG_TYPE_QUAD;

				// normalize the bounds
				normalize_bounds(prim->bounds);

				// get the scaled bitmap and set the resulting palette
				if (curitem.texture() != nullptr)
				{
					// determine the final orientation
					int finalorient = orientation_add(PRIMFLAG_GET_TEXORIENT(curitem.flags()), container_xform.orientation);

					// based on the swap values, get the scaled final texture
					int width = (finalorient & ORIENTATION_SWAP_XY) ? (prim->bounds.y1 - prim->bounds.y0) : (prim->bounds.x1 - prim->bounds.x0);
					int height = (finalorient & ORIENTATION_SWAP_XY) ? (prim->bounds.x1 - prim->bounds.x0) : (prim->bounds.y1 - prim->bounds.y0);
					width = std::min(width, m_maxtexwidth);
					height = std::min(height, m_maxtexheight);

					curitem.texture()->get_scaled(width, height, prim->texture, list, curitem.flags());

					// set the palette
					prim->texture.palette = curitem.texture()->get_adjusted_palette(container, prim->texture.palette_length);

					// determine UV coordinates
					prim->texcoords = oriented_texcoords[finalorient];

					// apply clipping
					clipped = render_clip_quad(&prim->bounds, &cliprect, &prim->texcoords);

					// apply the final orientation from the quad flags and then build up the final flags
					prim->flags |= (curitem.flags() & ~(PRIMFLAG_TEXORIENT_MASK | PRIMFLAG_BLENDMODE_MASK | PRIMFLAG_TEXFORMAT_MASK))
						| PRIMFLAG_TEXORIENT(finalorient)
						| PRIMFLAG_TEXFORMAT(curitem.texture()->format());
					prim->flags |= blendmode != -1
						? PRIMFLAG_BLENDMODE(blendmode)
						: PRIMFLAG_BLENDMODE(PRIMFLAG_GET_BLENDMODE(curitem.flags()));
				}
				else
				{
					// adjust the color for brightness/contrast/gamma
					prim->color.r = container.apply_brightness_contrast_gamma_fp(prim->color.r);
					prim->color.g = container.apply_brightness_contrast_gamma_fp(prim->color.g);
					prim->color.b = container.apply_brightness_contrast_gamma_fp(prim->color.b);

					// no texture
					prim->texture.base = nullptr;

					if (PRIMFLAG_GET_VECTORBUF(curitem.flags()))
					{
						// flags X(1) flip-x, Y(2) flip-y, S(4) swap-xy
						//
						// X  Y  S   e.g.       flips
						// 0  0  0   asteroid   !X !Y
						// 0  0  1   -           X  Y
						// 0  1  0   speedfrk   !X  Y
						// 0  1  1   tempest    !X  Y
						// 1  0  0   -           X !Y
						// 1  0  1   -           x !Y
						// 1  1  0   solarq      X  Y
						// 1  1  1   barrier    !X !Y

						bool flip_x = (m_manager.machine().system().flags & ORIENTATION_FLIP_X) == ORIENTATION_FLIP_X;
						bool flip_y = (m_manager.machine().system().flags & ORIENTATION_FLIP_Y) == ORIENTATION_FLIP_Y;
						bool swap_xy = (m_manager.machine().system().flags & ORIENTATION_SWAP_XY) == ORIENTATION_SWAP_XY;

						int vectororient = 0;
						if (flip_x)
						{
							vectororient |= ORIENTATION_FLIP_X;
						}
						if (flip_y)
						{
							vectororient |= ORIENTATION_FLIP_Y;
						}
						if ((flip_x && flip_y && swap_xy) || (!flip_x && !flip_y && swap_xy))
						{
							vectororient ^= ORIENTATION_FLIP_X;
							vectororient ^= ORIENTATION_FLIP_Y;
						}

						// determine the final orientation (textures are up-side down, so flip axis for vectors to immitate that behavior)
						int finalorient = orientation_add(vectororient, container_xform.orientation);

						// determine UV coordinates
						prim->texcoords = oriented_texcoords[finalorient];

						// apply clipping
						clipped = render_clip_quad(&prim->bounds, &cliprect, &prim->texcoords);

						// apply the final orientation from the quad flags and then build up the final flags
						prim->flags |= (curitem.flags() & ~(PRIMFLAG_TEXORIENT_MASK | PRIMFLAG_BLENDMODE_MASK | PRIMFLAG_TEXFORMAT_MASK))
							| PRIMFLAG_TEXORIENT(finalorient);
						prim->flags |= blendmode != -1
							? PRIMFLAG_BLENDMODE(blendmode)
							: PRIMFLAG_BLENDMODE(PRIMFLAG_GET_BLENDMODE(curitem.flags()));
					}
					else
					{
						// set the basic flags
						prim->flags |= (curitem.flags() & ~PRIMFLAG_BLENDMODE_MASK)
							| PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA);

						// apply clipping
						clipped = render_clip_quad(&prim->bounds, &cliprect, nullptr);
					}
				}
				break;
		}

		// add to the list or free if we're clipped out
		list.append_or_return(*prim, clipped);
	}

	// add the overlay if it exists
	if (container.overlay() != nullptr && m_layerconfig.screen_overlay_enabled())
	{
		s32 width, height;

		// allocate a primitive
		render_primitive *prim = list.alloc(render_primitive::QUAD);
		set_render_bounds_wh(prim->bounds, xform.xoffs, xform.yoffs, xform.xscale, xform.yscale);
		prim->full_bounds = prim->bounds;
		prim->color = container_xform.color;
		width = render_round_nearest(prim->bounds.x1) - render_round_nearest(prim->bounds.x0);
		height = render_round_nearest(prim->bounds.y1) - render_round_nearest(prim->bounds.y0);

		container.overlay()->get_scaled(
			(container_xform.orientation & ORIENTATION_SWAP_XY) ? height : width,
			(container_xform.orientation & ORIENTATION_SWAP_XY) ? width : height, prim->texture, list);

		// determine UV coordinates
		prim->texcoords = oriented_texcoords[container_xform.orientation];

		// set the flags and add it to the list
		prim->flags = PRIMFLAG_TEXORIENT(container_xform.orientation)
			| PRIMFLAG_BLENDMODE(BLENDMODE_RGB_MULTIPLY)
			| PRIMFLAG_TEXFORMAT(container.overlay()->format())
			| PRIMFLAG_TEXSHADE(1);

		list.append_or_return(*prim, false);
	}
}


//-------------------------------------------------
//  add_element_primitives - add the primitive
//  for an element in the current state
//-------------------------------------------------

void render_target::add_element_primitives(render_primitive_list &list, const object_transform &xform, layout_element &element, int state, int blendmode)
{
	// if we're out of range, bail
	if (state > element.maxstate())
		return;
	if (state < 0)
		state = 0;

	// get a pointer to the relevant texture
	render_texture *texture = element.state_texture(state);
	if (texture != nullptr)
	{
		render_primitive *prim = list.alloc(render_primitive::QUAD);

		// configure the basics
		prim->color = xform.color;
		prim->flags = PRIMFLAG_TEXORIENT(xform.orientation) | PRIMFLAG_BLENDMODE(blendmode) | PRIMFLAG_TEXFORMAT(texture->format());

		// compute the bounds
		s32 width = render_round_nearest(xform.xscale);
		s32 height = render_round_nearest(xform.yscale);
		set_render_bounds_wh(prim->bounds, render_round_nearest(xform.xoffs), render_round_nearest(xform.yoffs), (float) width, (float) height);
		prim->full_bounds = prim->bounds;
		if (xform.orientation & ORIENTATION_SWAP_XY)
			std::swap(width, height);
		width = std::min(width, m_maxtexwidth);
		height = std::min(height, m_maxtexheight);

		// get the scaled texture and append it

		texture->get_scaled(width, height, prim->texture, list, prim->flags);

		// compute the clip rect
		render_bounds cliprect;
		cliprect.x0 = render_round_nearest(xform.xoffs);
		cliprect.y0 = render_round_nearest(xform.yoffs);
		cliprect.x1 = render_round_nearest(xform.xoffs + xform.xscale);
		cliprect.y1 = render_round_nearest(xform.yoffs + xform.yscale);
		sect_render_bounds(cliprect, m_bounds);

		// determine UV coordinates and apply clipping
		prim->texcoords = oriented_texcoords[xform.orientation];
		bool clipped = render_clip_quad(&prim->bounds, &cliprect, &prim->texcoords);

		// add to the list or free if we're clipped out
		list.append_or_return(*prim, clipped);
	}
}


//-------------------------------------------------
//  map_point_internal - internal logic for
//  mapping points
//-------------------------------------------------

bool render_target::map_point_internal(s32 target_x, s32 target_y, render_container *container, float &mapped_x, float &mapped_y, ioport_port *&mapped_input_port, ioport_value &mapped_input_mask)
{
	// compute the visible width/height
	s32 viswidth, visheight;
	compute_visible_area(m_width, m_height, m_pixel_aspect, m_orientation, viswidth, visheight);

	// create a root transform for the target
	object_transform root_xform;
	root_xform.xoffs = (float)(m_width - viswidth) / 2;
	root_xform.yoffs = (float)(m_height - visheight) / 2;

	// default to point not mapped
	mapped_x = -1.0;
	mapped_y = -1.0;
	mapped_input_port = nullptr;
	mapped_input_mask = 0;

	// convert target coordinates to float
	float target_fx = (float)(target_x - root_xform.xoffs) / viswidth;
	float target_fy = (float)(target_y - root_xform.yoffs) / visheight;
	if (m_manager.machine().ui().is_menu_active())
	{
		target_fx = (float)target_x / m_width;
		target_fy = (float)target_y / m_height;
	}
	// explicitly check for the UI container
	if (container != nullptr && container == &m_manager.ui_container())
	{
		// this hit test went against the UI container
		if (target_fx >= 0.0f && target_fx < 1.0f && target_fy >= 0.0f && target_fy < 1.0f)
		{
			// this point was successfully mapped
			mapped_x = (float)target_x / m_width;
			mapped_y = (float)target_y / m_height;
			return true;
		}
		return false;
	}

	// iterate over items in the view
	for (layout_view::item &item : m_curview->items())
	{
		bool checkit;

		// if we're looking for a particular container, verify that we have the right one
		if (container != nullptr)
			checkit = (item.screen() != nullptr && &item.screen()->container() == container);

		// otherwise, assume we're looking for an input
		else
			checkit = item.has_input();

		// this target is worth looking at; now check the point
		if (checkit && target_fx >= item.bounds().x0 && target_fx < item.bounds().x1 && target_fy >= item.bounds().y0 && target_fy < item.bounds().y1)
		{
			// point successfully mapped
			mapped_x = (target_fx - item.bounds().x0) / (item.bounds().x1 - item.bounds().x0);
			mapped_y = (target_fy - item.bounds().y0) / (item.bounds().y1 - item.bounds().y0);
			mapped_input_port = item.input_tag_and_mask(mapped_input_mask);
			return true;
		}
	}

	return false;
}


//-------------------------------------------------
//  view_name - return the name of the indexed
//  view, or nullptr if it doesn't exist
//-------------------------------------------------

layout_view *render_target::view_by_index(int index)
{
	// scan the list of views within each layout, skipping those that don't apply
	for (layout_file &file : m_filelist)
		for (layout_view &view : file.views())
			if (!(m_flags & RENDER_CREATE_NO_ART) || !view.has_art())
				if (index-- == 0)
					return &view;
	return nullptr;
}


//-------------------------------------------------
//  view_index - return the index of the given
//  view
//-------------------------------------------------

int render_target::view_index(layout_view &targetview) const
{
	// find the first named match
	int index = 0;

	// scan the list of views within each layout, skipping those that don't apply
	for (layout_file const &file : m_filelist)
		for (layout_view const &view : file.views())
			if (!(m_flags & RENDER_CREATE_NO_ART) || !view.has_art())
			{
				if (&targetview == &view)
					return index;
				index++;
			}
	return 0;
}


//-------------------------------------------------
//  config_load - process config information
//-------------------------------------------------

void render_target::config_load(util::xml::data_node const &targetnode)
{
	int tmpint;

	// find the view
	const char *viewname = targetnode.get_attribute_string("view", nullptr);
	if (viewname != nullptr)
		for (int viewnum = 0; viewnum < 1000; viewnum++)
		{
			const char *testname = view_name(viewnum);
			if (testname == nullptr)
				break;
			if (!strcmp(viewname, testname))
			{
				set_view(viewnum);
				break;
			}
		}

	// modify the artwork config
	tmpint = targetnode.get_attribute_int("zoom", -1);
	if (tmpint == 0 || tmpint == 1)
		set_zoom_to_screen(tmpint);

	// apply orientation
	tmpint = targetnode.get_attribute_int("rotate", -1);
	if (tmpint != -1)
	{
		if (tmpint == 90)
			tmpint = ROT90;
		else if (tmpint == 180)
			tmpint = ROT180;
		else if (tmpint == 270)
			tmpint = ROT270;
		else
			tmpint = ROT0;
		set_orientation(orientation_add(tmpint, orientation()));

		// apply the opposite orientation to the UI
		if (is_ui_target())
		{
			render_container::user_settings settings;
			render_container &ui_container = m_manager.ui_container();

			ui_container.get_user_settings(settings);
			settings.m_orientation = orientation_add(orientation_reverse(tmpint), settings.m_orientation);
			ui_container.set_user_settings(settings);
		}
	}
}


//-------------------------------------------------
//  config_save - save our configuration, or
//  return false if we are the same as the default
//-------------------------------------------------

bool render_target::config_save(util::xml::data_node &targetnode)
{
	bool changed = false;

	// output the basics
	targetnode.set_attribute_int("index", index());

	// output the view
	if (m_curview != m_base_view)
	{
		targetnode.set_attribute("view", m_curview->name().c_str());
		changed = true;
	}

	// output the layer config
	if (m_layerconfig != m_base_layerconfig)
	{
		targetnode.set_attribute_int("zoom", m_layerconfig.zoom_to_screen());
		changed = true;
	}

	// output rotation
	if (m_orientation != m_base_orientation)
	{
		int rotate = 0;
		if (orientation_add(ROT90, m_base_orientation) == m_orientation)
			rotate = 90;
		else if (orientation_add(ROT180, m_base_orientation) == m_orientation)
			rotate = 180;
		else if (orientation_add(ROT270, m_base_orientation) == m_orientation)
			rotate = 270;
		assert(rotate != 0);
		targetnode.set_attribute_int("rotate", rotate);
		changed = true;
	}

	return changed;
}


//-------------------------------------------------
//  init_clear_extents - reset the extents list
//-------------------------------------------------

void render_target::init_clear_extents()
{
	m_clear_extents[0] = -m_height;
	m_clear_extents[1] = 1;
	m_clear_extents[2] = m_width;
	m_clear_extent_count = 3;
}


//-------------------------------------------------
//  remove_clear_extent - remove a quad from the
//  list of stuff to clear, unless it overlaps
//  a previous quad
//-------------------------------------------------

bool render_target::remove_clear_extent(const render_bounds &bounds)
{
	s32 *max = &m_clear_extents[MAX_CLEAR_EXTENTS];
	s32 *last = &m_clear_extents[m_clear_extent_count];
	s32 *ext = &m_clear_extents[0];
	s32 boundsx0 = ceil(bounds.x0);
	s32 boundsx1 = floor(bounds.x1);
	s32 boundsy0 = ceil(bounds.y0);
	s32 boundsy1 = floor(bounds.y1);
	s32 y0, y1 = 0;

	// loop over Y extents
	while (ext < last)
	{
		s32 *linelast;

		// first entry of each line should always be negative
		assert(ext[0] < 0.0f);
		y0 = y1;
		y1 = y0 - ext[0];

		// do we intersect this extent?
		if (boundsy0 < y1 && boundsy1 > y0)
		{
			s32 *xext;
			s32 x0, x1 = 0;

			// split the top
			if (y0 < boundsy0)
			{
				int diff = boundsy0 - y0;

				// make a copy of this extent
				memmove(&ext[ext[1] + 2], &ext[0], (last - ext) * sizeof(*ext));
				last += ext[1] + 2;
				if (last >= max)
					throw emu_fatalerror("render_target::remove_clear_extent: Ran out of clear extents!");

				// split the extent between pieces
				ext[ext[1] + 2] = -(-ext[0] - diff);
				ext[0] = -diff;

				// advance to the new extent
				y0 -= ext[0];
				ext += ext[1] + 2;
				y1 = y0 - ext[0];
			}

			// split the bottom
			if (y1 > boundsy1)
			{
				int diff = y1 - boundsy1;

				// make a copy of this extent
				memmove(&ext[ext[1] + 2], &ext[0], (last - ext) * sizeof(*ext));
				last += ext[1] + 2;
				if (last >= max)
					throw emu_fatalerror("render_target::remove_clear_extent: Ran out of clear extents!");

				// split the extent between pieces
				ext[ext[1] + 2] = -diff;
				ext[0] = -(-ext[0] - diff);

				// recompute y1
				y1 = y0 - ext[0];
			}

			// now remove the X extent
			linelast = &ext[ext[1] + 2];
			xext = &ext[2];
			while (xext < linelast)
			{
				x0 = x1;
				x1 = x0 + xext[0];

				// do we fully intersect this extent?
				if (boundsx0 >= x0 && boundsx1 <= x1)
				{
					// yes; split it
					memmove(&xext[2], &xext[0], (last - xext) * sizeof(*xext));
					last += 2;
					linelast += 2;
					if (last >= max)
						throw emu_fatalerror("render_target::remove_clear_extent: Ran out of clear extents!");

					// split this extent into three parts
					xext[0] = boundsx0 - x0;
					xext[1] = boundsx1 - boundsx0;
					xext[2] = x1 - boundsx1;

					// recompute x1
					x1 = boundsx1;
					xext += 2;
				}

				// do we partially intersect this extent?
				else if (boundsx0 < x1 && boundsx1 > x0)
					goto abort;

				// advance
				xext++;

				// do we partially intersect the next extent (which is a non-clear extent)?
				if (xext < linelast)
				{
					x0 = x1;
					x1 = x0 + xext[0];
					if (boundsx0 < x1 && boundsx1 > x0)
						goto abort;
					xext++;
				}
			}

			// update the count
			ext[1] = linelast - &ext[2];
		}

		// advance to the next row
		ext += 2 + ext[1];
	}

	// update the total count
	m_clear_extent_count = last - &m_clear_extents[0];
	return true;

abort:
	// update the total count even on a failure as we may have split extents
	m_clear_extent_count = last - &m_clear_extents[0];
	return false;
}


//-------------------------------------------------
//  add_clear_extents - add the accumulated
//  extents as a series of quads to clear
//-------------------------------------------------

void render_target::add_clear_extents(render_primitive_list &list)
{
	simple_list<render_primitive> clearlist;
	s32 *last = &m_clear_extents[m_clear_extent_count];
	s32 *ext = &m_clear_extents[0];
	s32 y0, y1 = 0;

	// loop over all extents
	while (ext < last)
	{
		s32 *linelast = &ext[ext[1] + 2];
		s32 *xext = &ext[2];
		s32 x0, x1 = 0;

		// first entry should always be negative
		assert(ext[0] < 0);
		y0 = y1;
		y1 = y0 - ext[0];

		// now remove the X extent
		while (xext < linelast)
		{
			x0 = x1;
			x1 = x0 + *xext++;

			// only add entries for non-zero widths
			if (x1 - x0 > 0)
			{
				render_primitive *prim = list.alloc(render_primitive::QUAD);
				set_render_bounds_xy(prim->bounds, (float)x0, (float)y0, (float)x1, (float)y1);
				prim->full_bounds = prim->bounds;
				set_render_color(&prim->color, 1.0f, 0.0f, 0.0f, 0.0f);
				prim->texture.base = nullptr;
				prim->flags = PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA);
				clearlist.append(*prim);
			}

			// skip the non-clearing extent
			x0 = x1;
			x1 = x0 + *xext++;
		}

		// advance to the next part
		ext += 2 + ext[1];
	}

	// we know that the first primitive in the list will be the global clip
	// so we insert the clears immediately after
	list.m_primlist.prepend_list(clearlist);
}


//-------------------------------------------------
//  add_clear_and_optimize_primitive_list -
//  optimize the primitive list
//-------------------------------------------------

void render_target::add_clear_and_optimize_primitive_list(render_primitive_list &list)
{
	// start with the assumption that we need to clear the whole screen
	init_clear_extents();

	// scan the list until we hit an intersection quad or a line
	for (render_primitive &prim : list)
	{
		// switch off the type
		switch (prim.type)
		{
			case render_primitive::LINE:
				goto done;

			case render_primitive::QUAD:
			{
				// stop when we hit an alpha texture
				if (PRIMFLAG_GET_TEXFORMAT(prim.flags) == TEXFORMAT_ARGB32)
					goto done;

				// if this quad can't be cleanly removed from the extents list, we're done
				if (!remove_clear_extent(prim.bounds))
					goto done;

				// change the blendmode on the first primitive to be NONE
				if (PRIMFLAG_GET_BLENDMODE(prim.flags) == BLENDMODE_RGB_MULTIPLY)
				{
					// RGB multiply will multiply against 0, leaving nothing
					set_render_color(&prim.color, 1.0f, 0.0f, 0.0f, 0.0f);
					prim.texture.base = nullptr;
					prim.flags = (prim.flags & ~PRIMFLAG_BLENDMODE_MASK) | PRIMFLAG_BLENDMODE(BLENDMODE_NONE);
				}
				else
				{
					// for alpha or add modes, we will blend against 0 or add to 0; treat it like none
					prim.flags = (prim.flags & ~PRIMFLAG_BLENDMODE_MASK) | PRIMFLAG_BLENDMODE(BLENDMODE_NONE);
				}

				// since alpha is disabled, premultiply the RGB values and reset the alpha to 1.0
				prim.color.r *= prim.color.a;
				prim.color.g *= prim.color.a;
				prim.color.b *= prim.color.a;
				prim.color.a = 1.0f;
				break;
			}

			default:
				throw emu_fatalerror("Unexpected primitive type");
		}
	}

done:
	// now add the extents to the clear list
	add_clear_extents(list);
}



//**************************************************************************
//  CORE IMPLEMENTATION
//**************************************************************************

//-------------------------------------------------
//  render_manager - constructor
//-------------------------------------------------

render_manager::render_manager(running_machine &machine)
	: m_machine(machine),
		m_ui_target(nullptr),
		m_live_textures(0),
		m_texture_id(0),
		m_ui_container(global_alloc(render_container(*this)))
{
	// register callbacks
	machine.configuration().config_register("video", config_load_delegate(&render_manager::config_load, this), config_save_delegate(&render_manager::config_save, this));

	// create one container per screen
	for (screen_device &screen : screen_device_iterator(machine.root_device()))
		screen.set_container(*container_alloc(&screen));
}


//-------------------------------------------------
//  ~render_manager - destructor
//-------------------------------------------------

render_manager::~render_manager()
{
	// free all the containers since they may own textures
	container_free(m_ui_container);
	m_screen_container_list.reset();

	// better not be any outstanding textures when we die
	assert(m_live_textures == 0);
}


//-------------------------------------------------
//  is_live - return if the screen is 'live'
//-------------------------------------------------

bool render_manager::is_live(screen_device &screen) const
{
	// iterate over all live targets and or together their screen masks
	for (render_target const &target : m_targetlist)
	{
		if (!target.hidden())
		{
			layout_view const *view = target.current_view();
			if (view != nullptr && view->has_screen(screen))
				return true;
		}
	}
	return false;
}


//-------------------------------------------------
//  max_update_rate - return the smallest maximum
//  update rate across all targets
//-------------------------------------------------

float render_manager::max_update_rate() const
{
	// iterate over all live targets and or together their screen masks
	float minimum = 0;
	for (render_target &target : m_targetlist)
		if (target.max_update_rate() != 0)
		{
			if (minimum == 0)
				minimum = target.max_update_rate();
			else
				minimum = std::min(target.max_update_rate(), minimum);
		}

	return minimum;
}


//-------------------------------------------------
//  target_alloc - allocate a new target
//-------------------------------------------------

render_target *render_manager::target_alloc(const internal_layout *layoutfile, u32 flags)
{
	return &m_targetlist.append(*global_alloc(render_target(*this, layoutfile, flags)));
}

render_target *render_manager::target_alloc(util::xml::data_node const &layout, u32 flags)
{
	return &m_targetlist.append(*global_alloc(render_target(*this, layout, flags)));
}


//-------------------------------------------------
//  target_free - free a target
//-------------------------------------------------

void render_manager::target_free(render_target *target)
{
	if (target != nullptr)
		m_targetlist.remove(*target);
}


//-------------------------------------------------
//  target_by_index - get a render_target by index
//-------------------------------------------------

render_target *render_manager::target_by_index(int index) const
{
	// count up the targets until we hit the requested index
	for (render_target &target : m_targetlist)
		if (!target.hidden())
			if (index-- == 0)
				return &target;
	return nullptr;
}


//-------------------------------------------------
//  ui_aspect - return the aspect ratio for UI
//  fonts
//-------------------------------------------------

float render_manager::ui_aspect(render_container *rc)
{
	int orient;
	float aspect;

	if (rc == m_ui_container || rc == nullptr) {
		// ui container, aggregated multi-screen target

		orient = orientation_add(m_ui_target->orientation(), m_ui_container->orientation());
		// based on the orientation of the target, compute height/width or width/height
		if (!(orient & ORIENTATION_SWAP_XY))
				aspect = (float)m_ui_target->height() / (float)m_ui_target->width();
		else
				aspect = (float)m_ui_target->width() / (float)m_ui_target->height();

		// if we have a valid pixel aspect, apply that and return
		if (m_ui_target->pixel_aspect() != 0.0f)
		{
			float pixel_aspect = m_ui_target->pixel_aspect();

			if (orient & ORIENTATION_SWAP_XY)
				pixel_aspect = 1.0f / pixel_aspect;

			return aspect /= pixel_aspect;
		}

	} else {
		// single screen container

		orient = rc->orientation();
		// based on the orientation of the target, compute height/width or width/height
		if (!(orient & ORIENTATION_SWAP_XY))
			aspect = (float)rc->screen()->visible_area().height() / (float)rc->screen()->visible_area().width();
		else
			aspect = (float)rc->screen()->visible_area().width() / (float)rc->screen()->visible_area().height();
	}

	// clamp for extreme proportions
	if (aspect < 0.66f)
		aspect = 0.66f;
	if (aspect > 1.5f)
		aspect = 1.5f;

	return aspect;
}


//-------------------------------------------------
//  texture_alloc - allocate a new texture
//-------------------------------------------------

render_texture *render_manager::texture_alloc(texture_scaler_func scaler, void *param)
{
	// allocate a new texture and reset it
	render_texture *tex = m_texture_allocator.alloc();
	tex->reset(*this, scaler, param);
	tex->set_id(m_texture_id);
	m_texture_id++;
	m_live_textures++;
	return tex;
}


//-------------------------------------------------
//  texture_free - release a texture
//-------------------------------------------------

void render_manager::texture_free(render_texture *texture)
{
	if (texture != nullptr)
	{
		m_live_textures--;
		texture->release();
	}
	m_texture_allocator.reclaim(texture);
}


//-------------------------------------------------
//  font_alloc - allocate a new font instance
//-------------------------------------------------

render_font *render_manager::font_alloc(const char *filename)
{
	return global_alloc(render_font(*this, filename));
}


//-------------------------------------------------
//  font_free - release a font instance
//-------------------------------------------------

void render_manager::font_free(render_font *font)
{
	global_free(font);
}


//-------------------------------------------------
//  invalidate_all - remove all refs to a
//  particular reference pointer
//-------------------------------------------------

void render_manager::invalidate_all(void *refptr)
{
	// permit nullptr
	if (refptr == nullptr)
		return;

	// loop over targets
	for (render_target &target : m_targetlist)
		target.invalidate_all(refptr);
}


//-------------------------------------------------
//  resolve_tags - resolve tag lookups
//-------------------------------------------------

void render_manager::resolve_tags()
{
	for (render_target &target : m_targetlist)
		target.resolve_tags();
}


//-------------------------------------------------
//  container_alloc - allocate a new container
//-------------------------------------------------

render_container *render_manager::container_alloc(screen_device *screen)
{
	auto container = global_alloc(render_container(*this, screen));
	if (screen != nullptr)
		m_screen_container_list.append(*container);
	return container;
}


//-------------------------------------------------
//  container_free - release a container
//-------------------------------------------------

void render_manager::container_free(render_container *container)
{
	m_screen_container_list.remove(*container);
}


//-------------------------------------------------
//  config_load - read and apply data from the
//  configuration file
//-------------------------------------------------

void render_manager::config_load(config_type cfg_type, util::xml::data_node const *parentnode)
{
	// we only care about game files
	if (cfg_type != config_type::GAME)
		return;

	// might not have any data
	if (parentnode == nullptr)
		return;

	// check the UI target
	util::xml::data_node const *const uinode = parentnode->get_child("interface");
	if (uinode != nullptr)
	{
		render_target *target = target_by_index(uinode->get_attribute_int("target", 0));
		if (target != nullptr)
			set_ui_target(*target);
	}

	// iterate over target nodes
	for (util::xml::data_node const *targetnode = parentnode->get_child("target"); targetnode; targetnode = targetnode->get_next_sibling("target"))
	{
		render_target *target = target_by_index(targetnode->get_attribute_int("index", -1));
		if (target != nullptr)
			target->config_load(*targetnode);
	}

	// iterate over screen nodes
	for (util::xml::data_node const *screennode = parentnode->get_child("screen"); screennode; screennode = screennode->get_next_sibling("screen"))
	{
		int index = screennode->get_attribute_int("index", -1);
		render_container *container = m_screen_container_list.find(index);
		render_container::user_settings settings;

		// fetch current settings
		container->get_user_settings(settings);

		// fetch color controls
		settings.m_brightness = screennode->get_attribute_float("brightness", settings.m_brightness);
		settings.m_contrast = screennode->get_attribute_float("contrast", settings.m_contrast);
		settings.m_gamma = screennode->get_attribute_float("gamma", settings.m_gamma);

		// fetch positioning controls
		settings.m_xoffset = screennode->get_attribute_float("hoffset", settings.m_xoffset);
		settings.m_xscale = screennode->get_attribute_float("hstretch", settings.m_xscale);
		settings.m_yoffset = screennode->get_attribute_float("voffset", settings.m_yoffset);
		settings.m_yscale = screennode->get_attribute_float("vstretch", settings.m_yscale);

		// set the new values
		container->set_user_settings(settings);
	}
}


//-------------------------------------------------
//  config_save - save data to the configuration
//  file
//-------------------------------------------------

void render_manager::config_save(config_type cfg_type, util::xml::data_node *parentnode)
{
	// we only care about game files
	if (cfg_type != config_type::GAME)
		return;

	// write out the interface target
	if (m_ui_target->index() != 0)
	{
		// create a node for it
		util::xml::data_node *const uinode = parentnode->add_child("interface", nullptr);
		if (uinode != nullptr)
			uinode->set_attribute_int("target", m_ui_target->index());
	}

	// iterate over targets
	for (int targetnum = 0; targetnum < 1000; targetnum++)
	{
		// get this target and break when we fail
		render_target *target = target_by_index(targetnum);
		if (target == nullptr)
			break;

		// create a node
		util::xml::data_node *const targetnode = parentnode->add_child("target", nullptr);
		if (targetnode != nullptr && !target->config_save(*targetnode))
			targetnode->delete_node();
	}

	// iterate over screen containers
	int scrnum = 0;
	for (render_container *container = m_screen_container_list.first(); container != nullptr; container = container->next(), scrnum++)
	{
		// create a node
		util::xml::data_node *const screennode = parentnode->add_child("screen", nullptr);
		if (screennode != nullptr)
		{
			bool changed = false;

			// output the basics
			screennode->set_attribute_int("index", scrnum);

			render_container::user_settings settings;
			container->get_user_settings(settings);

			// output the color controls
			if (settings.m_brightness != machine().options().brightness())
			{
				screennode->set_attribute_float("brightness", settings.m_brightness);
				changed = true;
			}

			if (settings.m_contrast != machine().options().contrast())
			{
				screennode->set_attribute_float("contrast", settings.m_contrast);
				changed = true;
			}

			if (settings.m_gamma != machine().options().gamma())
			{
				screennode->set_attribute_float("gamma", settings.m_gamma);
				changed = true;
			}

			// output the positioning controls
			if (settings.m_xoffset != 0.0f)
			{
				screennode->set_attribute_float("hoffset", settings.m_xoffset);
				changed = true;
			}

			if (settings.m_xscale != 1.0f)
			{
				screennode->set_attribute_float("hstretch", settings.m_xscale);
				changed = true;
			}

			if (settings.m_yoffset != 0.0f)
			{
				screennode->set_attribute_float("voffset", settings.m_yoffset);
				changed = true;
			}

			if (settings.m_yscale != 1.0f)
			{
				screennode->set_attribute_float("vstretch", settings.m_yscale);
				changed = true;
			}

			// if nothing changed, kill the node
			if (!changed)
				screennode->delete_node();
		}
	}
}