liyujie
2025-08-28 786ff4f4ca2374bdd9177f2e24b503d43e7a3b93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
/*-------------------------------------------------------------------------
 * drawElements Quality Program OpenGL (ES) Module
 * -----------------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Draw tests
 *//*--------------------------------------------------------------------*/
 
#include "glsDrawTest.hpp"
 
#include "deRandom.h"
#include "deRandom.hpp"
#include "deMath.h"
#include "deStringUtil.hpp"
#include "deFloat16.h"
#include "deUniquePtr.hpp"
#include "deArrayUtil.hpp"
 
#include "tcuTestLog.hpp"
#include "tcuPixelFormat.hpp"
#include "tcuRGBA.hpp"
#include "tcuSurface.hpp"
#include "tcuVector.hpp"
#include "tcuTestLog.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuStringTemplate.hpp"
#include "tcuImageCompare.hpp"
#include "tcuFloat.hpp"
#include "tcuTextureUtil.hpp"
 
#include "gluContextInfo.hpp"
#include "gluPixelTransfer.hpp"
#include "gluCallLogWrapper.hpp"
 
#include "sglrContext.hpp"
#include "sglrReferenceContext.hpp"
#include "sglrGLContext.hpp"
 
#include "rrGenericVector.hpp"
 
#include <cstring>
#include <cmath>
#include <vector>
#include <sstream>
#include <limits>
 
#include "glwDefs.hpp"
#include "glwEnums.hpp"
 
namespace deqp
{
namespace gls
{
namespace
{
 
using tcu::TestLog;
using namespace glw; // GL types
 
const int MAX_RENDER_TARGET_SIZE = 512;
 
// Utils
 
static GLenum targetToGL (DrawTestSpec::Target target)
{
   static const GLenum targets[] =
   {
       GL_ELEMENT_ARRAY_BUFFER,    // TARGET_ELEMENT_ARRAY = 0,
       GL_ARRAY_BUFFER                // TARGET_ARRAY,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::TARGET_LAST>(targets, (int)target);
}
 
static GLenum usageToGL (DrawTestSpec::Usage usage)
{
   static const GLenum usages[] =
   {
       GL_DYNAMIC_DRAW,    // USAGE_DYNAMIC_DRAW = 0,
       GL_STATIC_DRAW,        // USAGE_STATIC_DRAW,
       GL_STREAM_DRAW,        // USAGE_STREAM_DRAW,
 
       GL_STREAM_READ,        // USAGE_STREAM_READ,
       GL_STREAM_COPY,        // USAGE_STREAM_COPY,
 
       GL_STATIC_READ,        // USAGE_STATIC_READ,
       GL_STATIC_COPY,        // USAGE_STATIC_COPY,
 
       GL_DYNAMIC_READ,    // USAGE_DYNAMIC_READ,
       GL_DYNAMIC_COPY        // USAGE_DYNAMIC_COPY,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::USAGE_LAST>(usages, (int)usage);
}
 
static GLenum inputTypeToGL (DrawTestSpec::InputType type)
{
   static const GLenum types[] =
   {
       GL_FLOAT,                // INPUTTYPE_FLOAT = 0,
       GL_FIXED,                // INPUTTYPE_FIXED,
       GL_DOUBLE,                // INPUTTYPE_DOUBLE
       GL_BYTE,                // INPUTTYPE_BYTE,
       GL_SHORT,                // INPUTTYPE_SHORT,
       GL_UNSIGNED_BYTE,        // INPUTTYPE_UNSIGNED_BYTE,
       GL_UNSIGNED_SHORT,        // INPUTTYPE_UNSIGNED_SHORT,
 
       GL_INT,                    // INPUTTYPE_INT,
       GL_UNSIGNED_INT,        // INPUTTYPE_UNSIGNED_INT,
       GL_HALF_FLOAT,            // INPUTTYPE_HALF,
       GL_UNSIGNED_INT_2_10_10_10_REV, // INPUTTYPE_UNSIGNED_INT_2_10_10_10,
       GL_INT_2_10_10_10_REV            // INPUTTYPE_INT_2_10_10_10,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INPUTTYPE_LAST>(types, (int)type);
}
 
static std::string outputTypeToGLType (DrawTestSpec::OutputType type)
{
   static const char* types[] =
   {
       "float",        // OUTPUTTYPE_FLOAT = 0,
       "vec2",            // OUTPUTTYPE_VEC2,
       "vec3",            // OUTPUTTYPE_VEC3,
       "vec4",            // OUTPUTTYPE_VEC4,
 
       "int",            // OUTPUTTYPE_INT,
       "uint",            // OUTPUTTYPE_UINT,
 
       "ivec2",        // OUTPUTTYPE_IVEC2,
       "ivec3",        // OUTPUTTYPE_IVEC3,
       "ivec4",        // OUTPUTTYPE_IVEC4,
 
       "uvec2",        // OUTPUTTYPE_UVEC2,
       "uvec3",        // OUTPUTTYPE_UVEC3,
       "uvec4",        // OUTPUTTYPE_UVEC4,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::OUTPUTTYPE_LAST>(types, (int)type);
}
 
static GLenum primitiveToGL (DrawTestSpec::Primitive primitive)
{
   static const GLenum primitives[] =
   {
       GL_POINTS,                        // PRIMITIVE_POINTS = 0,
       GL_TRIANGLES,                    // PRIMITIVE_TRIANGLES,
       GL_TRIANGLE_FAN,                // PRIMITIVE_TRIANGLE_FAN,
       GL_TRIANGLE_STRIP,                // PRIMITIVE_TRIANGLE_STRIP,
       GL_LINES,                        // PRIMITIVE_LINES
       GL_LINE_STRIP,                    // PRIMITIVE_LINE_STRIP
       GL_LINE_LOOP,                    // PRIMITIVE_LINE_LOOP
       GL_LINES_ADJACENCY,                // PRIMITIVE_LINES_ADJACENCY
       GL_LINE_STRIP_ADJACENCY,        // PRIMITIVE_LINE_STRIP_ADJACENCY
       GL_TRIANGLES_ADJACENCY,            // PRIMITIVE_TRIANGLES_ADJACENCY
       GL_TRIANGLE_STRIP_ADJACENCY,    // PRIMITIVE_TRIANGLE_STRIP_ADJACENCY
   };
 
   return de::getSizedArrayElement<DrawTestSpec::PRIMITIVE_LAST>(primitives, (int)primitive);
}
 
static deUint32 indexTypeToGL (DrawTestSpec::IndexType indexType)
{
   static const GLenum indexTypes[] =
   {
       GL_UNSIGNED_BYTE,    // INDEXTYPE_BYTE = 0,
       GL_UNSIGNED_SHORT,    // INDEXTYPE_SHORT,
       GL_UNSIGNED_INT,    // INDEXTYPE_INT,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INDEXTYPE_LAST>(indexTypes, (int)indexType);
}
 
static bool inputTypeIsFloatType (DrawTestSpec::InputType type)
{
   if (type == DrawTestSpec::INPUTTYPE_FLOAT)
       return true;
   if (type == DrawTestSpec::INPUTTYPE_FIXED)
       return true;
   if (type == DrawTestSpec::INPUTTYPE_HALF)
       return true;
   if (type == DrawTestSpec::INPUTTYPE_DOUBLE)
       return true;
   return false;
}
 
static bool outputTypeIsFloatType (DrawTestSpec::OutputType type)
{
   if (type == DrawTestSpec::OUTPUTTYPE_FLOAT
       || type == DrawTestSpec::OUTPUTTYPE_VEC2
       || type == DrawTestSpec::OUTPUTTYPE_VEC3
       || type == DrawTestSpec::OUTPUTTYPE_VEC4)
       return true;
 
   return false;
}
 
static bool outputTypeIsIntType (DrawTestSpec::OutputType type)
{
   if (type == DrawTestSpec::OUTPUTTYPE_INT
       || type == DrawTestSpec::OUTPUTTYPE_IVEC2
       || type == DrawTestSpec::OUTPUTTYPE_IVEC3
       || type == DrawTestSpec::OUTPUTTYPE_IVEC4)
       return true;
 
   return false;
}
 
static bool outputTypeIsUintType (DrawTestSpec::OutputType type)
{
   if (type == DrawTestSpec::OUTPUTTYPE_UINT
       || type == DrawTestSpec::OUTPUTTYPE_UVEC2
       || type == DrawTestSpec::OUTPUTTYPE_UVEC3
       || type == DrawTestSpec::OUTPUTTYPE_UVEC4)
       return true;
 
   return false;
}
 
static size_t getElementCount (DrawTestSpec::Primitive primitive, size_t primitiveCount)
{
   switch (primitive)
   {
       case DrawTestSpec::PRIMITIVE_POINTS:                        return primitiveCount;
       case DrawTestSpec::PRIMITIVE_TRIANGLES:                        return primitiveCount * 3;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_FAN:                    return primitiveCount + 2;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP:                return primitiveCount + 2;
       case DrawTestSpec::PRIMITIVE_LINES:                            return primitiveCount * 2;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP:                    return primitiveCount + 1;
       case DrawTestSpec::PRIMITIVE_LINE_LOOP:                        return (primitiveCount==1) ? (2) : (primitiveCount);
       case DrawTestSpec::PRIMITIVE_LINES_ADJACENCY:                return primitiveCount * 4;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP_ADJACENCY:            return primitiveCount + 3;
       case DrawTestSpec::PRIMITIVE_TRIANGLES_ADJACENCY:            return primitiveCount * 6;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP_ADJACENCY:        return primitiveCount * 2 + 4;
       default:
           DE_ASSERT(false);
           return 0;
   }
}
 
struct MethodInfo
{
   bool indexed;
   bool instanced;
   bool ranged;
   bool first;
   bool baseVertex;
   bool indirect;
};
 
static MethodInfo getMethodInfo (gls::DrawTestSpec::DrawMethod method)
{
   static const MethodInfo infos[] =
   {
       //    indexed        instanced    ranged        first        baseVertex    indirect
       {    false,        false,        false,        true,        false,        false    }, //!< DRAWMETHOD_DRAWARRAYS,
       {    false,        true,        false,        true,        false,        false    }, //!< DRAWMETHOD_DRAWARRAYS_INSTANCED,
       {    false,        true,        false,        true,        false,        true    }, //!< DRAWMETHOD_DRAWARRAYS_INDIRECT,
       {    true,        false,        false,        false,        false,        false    }, //!< DRAWMETHOD_DRAWELEMENTS,
       {    true,        false,        true,        false,        false,        false    }, //!< DRAWMETHOD_DRAWELEMENTS_RANGED,
       {    true,        true,        false,        false,        false,        false    }, //!< DRAWMETHOD_DRAWELEMENTS_INSTANCED,
       {    true,        true,        false,        false,        true,        true    }, //!< DRAWMETHOD_DRAWELEMENTS_INDIRECT,
       {    true,        false,        false,        false,        true,        false    }, //!< DRAWMETHOD_DRAWELEMENTS_BASEVERTEX,
       {    true,        true,        false,        false,        true,        false    }, //!< DRAWMETHOD_DRAWELEMENTS_INSTANCED_BASEVERTEX,
       {    true,        false,        true,        false,        true,        false    }, //!< DRAWMETHOD_DRAWELEMENTS_RANGED_BASEVERTEX,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::DRAWMETHOD_LAST>(infos, (int)method);
}
 
template<class T>
inline static void alignmentSafeAssignment (char* dst, T val)
{
   std::memcpy(dst, &val, sizeof(T));
}
 
static bool checkSpecsShaderCompatible (const DrawTestSpec& a, const DrawTestSpec& b)
{
   // Only the attributes matter
   if (a.attribs.size() != b.attribs.size())
       return false;
 
   for (size_t ndx = 0; ndx < a.attribs.size(); ++ndx)
   {
       // Only the output type (== shader input type) matters and the usage in the shader.
 
       if (a.attribs[ndx].additionalPositionAttribute != b.attribs[ndx].additionalPositionAttribute)
           return false;
 
       // component counts need not to match
       if (outputTypeIsFloatType(a.attribs[ndx].outputType) && outputTypeIsFloatType(b.attribs[ndx].outputType))
           continue;
       if (outputTypeIsIntType(a.attribs[ndx].outputType) && outputTypeIsIntType(b.attribs[ndx].outputType))
           continue;
       if (outputTypeIsUintType(a.attribs[ndx].outputType) && outputTypeIsUintType(b.attribs[ndx].outputType))
           continue;
 
       return false;
   }
 
   return true;
}
 
// generate random vectors in a way that does not depend on argument evaluation order
 
tcu::Vec4 generateRandomVec4 (de::Random& random)
{
   tcu::Vec4 retVal;
 
   for (int i = 0; i < 4; ++i)
       retVal[i] = random.getFloat();
 
   return retVal;
}
 
tcu::IVec4 generateRandomIVec4 (de::Random& random)
{
   tcu::IVec4 retVal;
 
   for (int i = 0; i < 4; ++i)
       retVal[i] = random.getUint32();
 
   return retVal;
}
 
tcu::UVec4 generateRandomUVec4 (de::Random& random)
{
   tcu::UVec4 retVal;
 
   for (int i = 0; i < 4; ++i)
       retVal[i] = random.getUint32();
 
   return retVal;
}
 
// IterationLogSectionEmitter
 
class IterationLogSectionEmitter
{
public:
                               IterationLogSectionEmitter        (tcu::TestLog& log, size_t testIteration, size_t testIterations, const std::string& description, bool enabled);
                               ~IterationLogSectionEmitter        (void);
private:
                               IterationLogSectionEmitter        (const IterationLogSectionEmitter&); // delete
   IterationLogSectionEmitter&    operator=                        (const IterationLogSectionEmitter&); // delete
 
   tcu::TestLog&                m_log;
   bool                        m_enabled;
};
 
IterationLogSectionEmitter::IterationLogSectionEmitter (tcu::TestLog& log, size_t testIteration, size_t testIterations, const std::string& description, bool enabled)
   : m_log        (log)
   , m_enabled    (enabled)
{
   if (m_enabled)
   {
       std::ostringstream buf;
       buf << "Iteration " << (testIteration+1) << "/" << testIterations;
 
       if (!description.empty())
           buf << " - " << description;
 
       m_log << tcu::TestLog::Section(buf.str(), buf.str());
   }
}
 
IterationLogSectionEmitter::~IterationLogSectionEmitter (void)
{
   if (m_enabled)
       m_log << tcu::TestLog::EndSection;
}
 
// GLValue
 
class GLValue
{
public:
 
   template<class Type>
   class WrappedType
   {
   public:
       static WrappedType<Type>    create            (Type value)                            { WrappedType<Type> v; v.m_value = value; return v; }
       inline Type                    getValue        (void) const                            { return m_value; }
 
       inline WrappedType<Type>    operator+        (const WrappedType<Type>& other) const    { return WrappedType<Type>::create((Type)(m_value + other.getValue())); }
       inline WrappedType<Type>    operator*        (const WrappedType<Type>& other) const    { return WrappedType<Type>::create((Type)(m_value * other.getValue())); }
       inline WrappedType<Type>    operator/        (const WrappedType<Type>& other) const    { return WrappedType<Type>::create((Type)(m_value / other.getValue())); }
       inline WrappedType<Type>    operator-        (const WrappedType<Type>& other) const    { return WrappedType<Type>::create((Type)(m_value - other.getValue())); }
 
       inline WrappedType<Type>&    operator+=        (const WrappedType<Type>& other)        { m_value += other.getValue(); return *this; }
       inline WrappedType<Type>&    operator*=        (const WrappedType<Type>& other)        { m_value *= other.getValue(); return *this; }
       inline WrappedType<Type>&    operator/=        (const WrappedType<Type>& other)        { m_value /= other.getValue(); return *this; }
       inline WrappedType<Type>&    operator-=        (const WrappedType<Type>& other)        { m_value -= other.getValue(); return *this; }
 
       inline bool                    operator==        (const WrappedType<Type>& other) const    { return m_value == other.m_value; }
       inline bool                    operator!=        (const WrappedType<Type>& other) const    { return m_value != other.m_value; }
       inline bool                    operator<        (const WrappedType<Type>& other) const    { return m_value < other.m_value; }
       inline bool                    operator>        (const WrappedType<Type>& other) const    { return m_value > other.m_value; }
       inline bool                    operator<=        (const WrappedType<Type>& other) const    { return m_value <= other.m_value; }
       inline bool                    operator>=        (const WrappedType<Type>& other) const    { return m_value >= other.m_value; }
 
       inline                        operator Type    (void) const                            { return m_value; }
       template<class T>
       inline T                    to                (void) const                            { return (T)m_value; }
   private:
       Type    m_value;
   };
 
   typedef WrappedType<deInt16>    Short;
   typedef WrappedType<deUint16>    Ushort;
 
   typedef WrappedType<deInt8>        Byte;
   typedef WrappedType<deUint8>    Ubyte;
 
   typedef WrappedType<float>        Float;
   typedef WrappedType<double>        Double;
 
   typedef WrappedType<deInt32>    Int;
   typedef WrappedType<deUint32>    Uint;
 
   class Half
   {
   public:
       static Half            create            (float value)                { Half h; h.m_value = floatToHalf(value); return h; }
       inline deFloat16    getValue        (void) const                { return m_value; }
 
       inline Half            operator+        (const Half& other) const    { return create(halfToFloat(m_value) + halfToFloat(other.getValue())); }
       inline Half            operator*        (const Half& other) const    { return create(halfToFloat(m_value) * halfToFloat(other.getValue())); }
       inline Half            operator/        (const Half& other) const    { return create(halfToFloat(m_value) / halfToFloat(other.getValue())); }
       inline Half            operator-        (const Half& other) const    { return create(halfToFloat(m_value) - halfToFloat(other.getValue())); }
 
       inline Half&        operator+=        (const Half& other)            { m_value = floatToHalf(halfToFloat(other.getValue()) + halfToFloat(m_value)); return *this; }
       inline Half&        operator*=        (const Half& other)            { m_value = floatToHalf(halfToFloat(other.getValue()) * halfToFloat(m_value)); return *this; }
       inline Half&        operator/=        (const Half& other)            { m_value = floatToHalf(halfToFloat(other.getValue()) / halfToFloat(m_value)); return *this; }
       inline Half&        operator-=        (const Half& other)            { m_value = floatToHalf(halfToFloat(other.getValue()) - halfToFloat(m_value)); return *this; }
 
       inline bool            operator==        (const Half& other) const    { return m_value == other.m_value; }
       inline bool            operator!=        (const Half& other) const    { return m_value != other.m_value; }
       inline bool            operator<        (const Half& other) const    { return halfToFloat(m_value) < halfToFloat(other.m_value); }
       inline bool            operator>        (const Half& other) const    { return halfToFloat(m_value) > halfToFloat(other.m_value); }
       inline bool            operator<=        (const Half& other) const    { return halfToFloat(m_value) <= halfToFloat(other.m_value); }
       inline bool            operator>=        (const Half& other) const    { return halfToFloat(m_value) >= halfToFloat(other.m_value); }
 
       template<class T>
       inline T            to                (void) const                { return (T)halfToFloat(m_value); }
 
       inline static deFloat16    floatToHalf        (float f);
       inline static float        halfToFloat        (deFloat16 h);
   private:
       deFloat16 m_value;
   };
 
   class Fixed
   {
   public:
       static Fixed        create            (deInt32 value)                { Fixed v; v.m_value = value; return v; }
       inline deInt32        getValue        (void) const                { return m_value; }
 
       inline Fixed        operator+        (const Fixed& other) const    { return create(m_value + other.getValue()); }
       inline Fixed        operator*        (const Fixed& other) const    { return create(m_value * other.getValue()); }
       inline Fixed        operator/        (const Fixed& other) const    { return create(m_value / other.getValue()); }
       inline Fixed        operator-        (const Fixed& other) const    { return create(m_value - other.getValue()); }
 
       inline Fixed&        operator+=        (const Fixed& other)        { m_value += other.getValue(); return *this; }
       inline Fixed&        operator*=        (const Fixed& other)        { m_value *= other.getValue(); return *this; }
       inline Fixed&        operator/=        (const Fixed& other)        { m_value /= other.getValue(); return *this; }
       inline Fixed&        operator-=        (const Fixed& other)        { m_value -= other.getValue(); return *this; }
 
       inline bool            operator==        (const Fixed& other) const    { return m_value == other.m_value; }
       inline bool            operator!=        (const Fixed& other) const    { return m_value != other.m_value; }
       inline bool            operator<        (const Fixed& other) const    { return m_value < other.m_value; }
       inline bool            operator>        (const Fixed& other) const    { return m_value > other.m_value; }
       inline bool            operator<=        (const Fixed& other) const    { return m_value <= other.m_value; }
       inline bool            operator>=        (const Fixed& other) const    { return m_value >= other.m_value; }
 
       inline                operator deInt32 (void) const                { return m_value; }
       template<class T>
       inline T            to                (void) const                { return (T)m_value; }
   private:
       deInt32                m_value;
   };
 
   // \todo [mika] This is pretty messy
                       GLValue            (void)            : type(DrawTestSpec::INPUTTYPE_LAST) {}
   explicit            GLValue            (Float value)    : type(DrawTestSpec::INPUTTYPE_FLOAT),                fl(value)    {}
   explicit            GLValue            (Fixed value)    : type(DrawTestSpec::INPUTTYPE_FIXED),                fi(value)    {}
   explicit            GLValue            (Byte value)    : type(DrawTestSpec::INPUTTYPE_BYTE),                b(value)    {}
   explicit            GLValue            (Ubyte value)    : type(DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE),        ub(value)    {}
   explicit            GLValue            (Short value)    : type(DrawTestSpec::INPUTTYPE_SHORT),                s(value)    {}
   explicit            GLValue            (Ushort value)    : type(DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT),        us(value)    {}
   explicit            GLValue            (Int value)        : type(DrawTestSpec::INPUTTYPE_INT),                i(value)    {}
   explicit            GLValue            (Uint value)    : type(DrawTestSpec::INPUTTYPE_UNSIGNED_INT),        ui(value)    {}
   explicit            GLValue            (Half value)    : type(DrawTestSpec::INPUTTYPE_HALF),                h(value)    {}
   explicit            GLValue            (Double value)    : type(DrawTestSpec::INPUTTYPE_DOUBLE),                d(value)    {}
 
   float                toFloat            (void) const;
 
   static GLValue        getMaxValue        (DrawTestSpec::InputType type);
   static GLValue        getMinValue        (DrawTestSpec::InputType type);
 
   DrawTestSpec::InputType    type;
 
   union
   {
       Float        fl;
       Fixed        fi;
       Double        d;
       Byte        b;
       Ubyte        ub;
       Short        s;
       Ushort        us;
       Int            i;
       Uint        ui;
       Half        h;
   };
};
 
inline deFloat16 GLValue::Half::floatToHalf (float f)
{
   // No denorm support.
   tcu::Float<deUint16, 5, 10, 15, tcu::FLOAT_HAS_SIGN> v(f);
   DE_ASSERT(!v.isNaN() && !v.isInf());
   return v.bits();
}
 
inline float GLValue::Half::halfToFloat (deFloat16 h)
{
   return tcu::Float16((deUint16)h).asFloat();
}
 
float GLValue::toFloat (void) const
{
   switch (type)
   {
       case DrawTestSpec::INPUTTYPE_FLOAT:
           return fl.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_BYTE:
           return b.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE:
           return ub.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_SHORT:
           return s.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT:
           return us.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_FIXED:
       {
           int maxValue = 65536;
           return (float)(double(2 * fi.getValue() + 1) / (maxValue - 1));
 
           break;
       }
 
       case DrawTestSpec::INPUTTYPE_UNSIGNED_INT:
           return (float)ui.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_INT:
           return (float)i.getValue();
           break;
 
       case DrawTestSpec::INPUTTYPE_HALF:
           return h.to<float>();
           break;
 
       case DrawTestSpec::INPUTTYPE_DOUBLE:
           return d.to<float>();
           break;
 
       default:
           DE_ASSERT(false);
           return 0.0f;
           break;
   };
}
 
GLValue GLValue::getMaxValue (DrawTestSpec::InputType type)
{
   GLValue rangesHi[(int)DrawTestSpec::INPUTTYPE_LAST];
 
   rangesHi[(int)DrawTestSpec::INPUTTYPE_FLOAT]            = GLValue(Float::create(127.0f));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_DOUBLE]            = GLValue(Double::create(127.0f));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_BYTE]                = GLValue(Byte::create(127));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE]    = GLValue(Ubyte::create(255));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT]    = GLValue(Ushort::create(65530));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_SHORT]            = GLValue(Short::create(32760));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_FIXED]            = GLValue(Fixed::create(32760));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_INT]                = GLValue(Int::create(2147483647));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_INT]        = GLValue(Uint::create(4294967295u));
   rangesHi[(int)DrawTestSpec::INPUTTYPE_HALF]                = GLValue(Half::create(256.0f));
 
   return rangesHi[(int)type];
}
 
GLValue GLValue::getMinValue (DrawTestSpec::InputType type)
{
   GLValue rangesLo[(int)DrawTestSpec::INPUTTYPE_LAST];
 
   rangesLo[(int)DrawTestSpec::INPUTTYPE_FLOAT]            = GLValue(Float::create(-127.0f));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_DOUBLE]            = GLValue(Double::create(-127.0f));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_BYTE]                = GLValue(Byte::create(-127));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE]    = GLValue(Ubyte::create(0));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT]    = GLValue(Ushort::create(0));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_SHORT]            = GLValue(Short::create(-32760));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_FIXED]            = GLValue(Fixed::create(-32760));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_INT]                = GLValue(Int::create(-2147483647));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_UNSIGNED_INT]        = GLValue(Uint::create(0));
   rangesLo[(int)DrawTestSpec::INPUTTYPE_HALF]                = GLValue(Half::create(-256.0f));
 
   return rangesLo[(int)type];
}
 
template<typename T>
struct GLValueTypeTraits;
 
template<> struct GLValueTypeTraits<GLValue::Float>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_FLOAT;            };
template<> struct GLValueTypeTraits<GLValue::Double> { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_DOUBLE;            };
template<> struct GLValueTypeTraits<GLValue::Byte>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_BYTE;            };
template<> struct GLValueTypeTraits<GLValue::Ubyte>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE;    };
template<> struct GLValueTypeTraits<GLValue::Ushort> { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT;    };
template<> struct GLValueTypeTraits<GLValue::Short>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_SHORT;            };
template<> struct GLValueTypeTraits<GLValue::Fixed>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_FIXED;            };
template<> struct GLValueTypeTraits<GLValue::Int>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_INT;            };
template<> struct GLValueTypeTraits<GLValue::Uint>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_UNSIGNED_INT;    };
template<> struct GLValueTypeTraits<GLValue::Half>     { static const DrawTestSpec::InputType Type = DrawTestSpec::INPUTTYPE_HALF;            };
 
template<typename T>
inline T extractGLValue (const GLValue& v);
 
template<> GLValue::Float    inline extractGLValue<GLValue::Float>        (const GLValue& v) { return v.fl; };
template<> GLValue::Double    inline extractGLValue<GLValue::Double>        (const GLValue& v) { return v.d; };
template<> GLValue::Byte    inline extractGLValue<GLValue::Byte>        (const GLValue& v) { return v.b; };
template<> GLValue::Ubyte    inline extractGLValue<GLValue::Ubyte>        (const GLValue& v) { return v.ub; };
template<> GLValue::Ushort    inline extractGLValue<GLValue::Ushort>        (const GLValue& v) { return v.us; };
template<> GLValue::Short    inline extractGLValue<GLValue::Short>        (const GLValue& v) { return v.s; };
template<> GLValue::Fixed    inline extractGLValue<GLValue::Fixed>        (const GLValue& v) { return v.fi; };
template<> GLValue::Int        inline extractGLValue<GLValue::Int>            (const GLValue& v) { return v.i; };
template<> GLValue::Uint    inline extractGLValue<GLValue::Uint>        (const GLValue& v) { return v.ui; };
template<> GLValue::Half    inline extractGLValue<GLValue::Half>        (const GLValue& v) { return v.h; };
 
template<class T>
inline T getRandom (deRandom& rnd, T min, T max);
 
template<>
inline GLValue::Float getRandom (deRandom& rnd, GLValue::Float min, GLValue::Float max)
{
   if (max < min)
       return min;
 
   return GLValue::Float::create(min + deRandom_getFloat(&rnd) * (max.to<float>() - min.to<float>()));
}
 
template<>
inline GLValue::Double getRandom (deRandom& rnd, GLValue::Double min, GLValue::Double max)
{
   if (max < min)
       return min;
 
   return GLValue::Double::create(min + deRandom_getFloat(&rnd) * (max.to<float>() - min.to<float>()));
}
 
template<>
inline GLValue::Short getRandom (deRandom& rnd, GLValue::Short min, GLValue::Short max)
{
   if (max < min)
       return min;
 
   return GLValue::Short::create((min == max ? min : (deInt16)(min + (deRandom_getUint32(&rnd) % (max.to<int>() - min.to<int>())))));
}
 
template<>
inline GLValue::Ushort getRandom (deRandom& rnd, GLValue::Ushort min, GLValue::Ushort max)
{
   if (max < min)
       return min;
 
   return GLValue::Ushort::create((min == max ? min : (deUint16)(min + (deRandom_getUint32(&rnd) % (max.to<int>() - min.to<int>())))));
}
 
template<>
inline GLValue::Byte getRandom (deRandom& rnd, GLValue::Byte min, GLValue::Byte max)
{
   if (max < min)
       return min;
 
   return GLValue::Byte::create((min == max ? min : (deInt8)(min + (deRandom_getUint32(&rnd) % (max.to<int>() - min.to<int>())))));
}
 
template<>
inline GLValue::Ubyte getRandom (deRandom& rnd, GLValue::Ubyte min, GLValue::Ubyte max)
{
   if (max < min)
       return min;
 
   return GLValue::Ubyte::create((min == max ? min : (deUint8)(min + (deRandom_getUint32(&rnd) % (max.to<int>() - min.to<int>())))));
}
 
template<>
inline GLValue::Fixed getRandom (deRandom& rnd, GLValue::Fixed min, GLValue::Fixed max)
{
   if (max < min)
       return min;
 
   return GLValue::Fixed::create((min == max ? min : min + (deRandom_getUint32(&rnd) % (max.to<deUint32>() - min.to<deUint32>()))));
}
 
template<>
inline GLValue::Half getRandom (deRandom& rnd, GLValue::Half min, GLValue::Half max)
{
   if (max < min)
       return min;
 
   float fMax = max.to<float>();
   float fMin = min.to<float>();
   GLValue::Half h = GLValue::Half::create(fMin + deRandom_getFloat(&rnd) * (fMax - fMin));
   return h;
}
 
template<>
inline GLValue::Int getRandom (deRandom& rnd, GLValue::Int min, GLValue::Int max)
{
   if (max < min)
       return min;
 
   return GLValue::Int::create((min == max ? min : min + (deRandom_getUint32(&rnd) % (max.to<deUint32>() - min.to<deUint32>()))));
}
 
template<>
inline GLValue::Uint getRandom (deRandom& rnd, GLValue::Uint min, GLValue::Uint max)
{
   if (max < min)
       return min;
 
   return GLValue::Uint::create((min == max ? min : min + (deRandom_getUint32(&rnd) % (max.to<deUint32>() - min.to<deUint32>()))));
}
 
// Minimum difference required between coordinates
template<class T>
inline T minValue (void);
 
template<>
inline GLValue::Float minValue (void)
{
   return GLValue::Float::create(4 * 1.0f);
}
 
template<>
inline GLValue::Double minValue (void)
{
   return GLValue::Double::create(4 * 1.0f);
}
 
template<>
inline GLValue::Short minValue (void)
{
   return GLValue::Short::create(4 * 256);
}
 
template<>
inline GLValue::Ushort minValue (void)
{
   return GLValue::Ushort::create(4 * 256);
}
 
template<>
inline GLValue::Byte minValue (void)
{
   return GLValue::Byte::create(4 * 1);
}
 
template<>
inline GLValue::Ubyte minValue (void)
{
   return GLValue::Ubyte::create(4 * 2);
}
 
template<>
inline GLValue::Fixed minValue (void)
{
   return GLValue::Fixed::create(4 * 1);
}
 
template<>
inline GLValue::Int minValue (void)
{
   return GLValue::Int::create(4 * 16777216);
}
 
template<>
inline GLValue::Uint minValue (void)
{
   return GLValue::Uint::create(4 * 16777216);
}
 
template<>
inline GLValue::Half minValue (void)
{
   return GLValue::Half::create(4 * 1.0f);
}
 
template<class T>
inline T abs (T val);
 
template<>
inline GLValue::Fixed abs (GLValue::Fixed val)
{
   return GLValue::Fixed::create(0x7FFFu & val.getValue());
}
 
template<>
inline GLValue::Ubyte abs (GLValue::Ubyte val)
{
   return val;
}
 
template<>
inline GLValue::Byte abs (GLValue::Byte val)
{
   return GLValue::Byte::create(0x7Fu & val.getValue());
}
 
template<>
inline GLValue::Ushort abs (GLValue::Ushort val)
{
   return val;
}
 
template<>
inline GLValue::Short abs (GLValue::Short val)
{
   return GLValue::Short::create(0x7FFFu & val.getValue());
}
 
template<>
inline GLValue::Float abs (GLValue::Float val)
{
   return GLValue::Float::create(std::fabs(val.to<float>()));
}
 
template<>
inline GLValue::Double abs (GLValue::Double val)
{
   return GLValue::Double::create(std::fabs(val.to<float>()));
}
 
template<>
inline GLValue::Uint abs (GLValue::Uint val)
{
   return val;
}
 
template<>
inline GLValue::Int abs (GLValue::Int val)
{
   return GLValue::Int::create(0x7FFFFFFFu & val.getValue());
}
 
template<>
inline GLValue::Half abs (GLValue::Half val)
{
   return GLValue::Half::create(std::fabs(val.to<float>()));
}
 
// AttributeArray
 
class AttributeArray
{
public:
                               AttributeArray        (DrawTestSpec::Storage storage, sglr::Context& context);
                               ~AttributeArray        (void);
 
   void                        data                (DrawTestSpec::Target target, size_t size, const char* data, DrawTestSpec::Usage usage);
   void                        setupArray            (bool bound, int offset, int size, DrawTestSpec::InputType inType, DrawTestSpec::OutputType outType, bool normalized, int stride, int instanceDivisor, const rr::GenericVec4& defaultAttrib, bool isPositionAttr, bool bgraComponentOrder);
   void                        bindAttribute        (deUint32 loc);
   void                        bindIndexArray        (DrawTestSpec::Target storage);
 
   int                            getComponentCount    (void) const { return m_componentCount; }
   DrawTestSpec::Target        getTarget            (void) const { return m_target; }
   DrawTestSpec::InputType        getInputType        (void) const { return m_inputType; }
   DrawTestSpec::OutputType    getOutputType        (void) const { return m_outputType; }
   DrawTestSpec::Storage        getStorageType        (void) const { return m_storage; }
   bool                        getNormalized        (void) const { return m_normalize; }
   int                            getStride            (void) const { return m_stride; }
   bool                        isBound                (void) const { return m_bound; }
   bool                        isPositionAttribute    (void) const { return m_isPositionAttr; }
 
private:
   DrawTestSpec::Storage        m_storage;
   sglr::Context&                m_ctx;
   deUint32                    m_glBuffer;
 
   int                            m_size;
   char*                        m_data;
   int                            m_componentCount;
   bool                        m_bound;
   DrawTestSpec::Target        m_target;
   DrawTestSpec::InputType        m_inputType;
   DrawTestSpec::OutputType    m_outputType;
   bool                        m_normalize;
   int                            m_stride;
   int                            m_offset;
   rr::GenericVec4                m_defaultAttrib;
   int                            m_instanceDivisor;
   bool                        m_isPositionAttr;
   bool                        m_bgraOrder;
};
 
AttributeArray::AttributeArray (DrawTestSpec::Storage storage, sglr::Context& context)
   : m_storage            (storage)
   , m_ctx                (context)
   , m_glBuffer        (0)
   , m_size            (0)
   , m_data            (DE_NULL)
   , m_componentCount    (1)
   , m_bound            (false)
   , m_target            (DrawTestSpec::TARGET_ARRAY)
   , m_inputType        (DrawTestSpec::INPUTTYPE_FLOAT)
   , m_outputType        (DrawTestSpec::OUTPUTTYPE_VEC4)
   , m_normalize        (false)
   , m_stride            (0)
   , m_offset            (0)
   , m_instanceDivisor    (0)
   , m_isPositionAttr    (false)
   , m_bgraOrder        (false)
{
   if (m_storage == DrawTestSpec::STORAGE_BUFFER)
   {
       m_ctx.genBuffers(1, &m_glBuffer);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glGenBuffers()");
   }
}
 
AttributeArray::~AttributeArray    (void)
{
   if (m_storage == DrawTestSpec::STORAGE_BUFFER)
   {
       m_ctx.deleteBuffers(1, &m_glBuffer);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDeleteBuffers()");
   }
   else if (m_storage == DrawTestSpec::STORAGE_USER)
       delete[] m_data;
   else
       DE_ASSERT(false);
}
 
void AttributeArray::data (DrawTestSpec::Target target, size_t size, const char* ptr, DrawTestSpec::Usage usage)
{
   m_size = (int)size;
   m_target = target;
 
   if (m_storage == DrawTestSpec::STORAGE_BUFFER)
   {
       m_ctx.bindBuffer(targetToGL(target), m_glBuffer);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glBindBuffer()");
 
       m_ctx.bufferData(targetToGL(target), size, ptr, usageToGL(usage));
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glBufferData()");
   }
   else if (m_storage == DrawTestSpec::STORAGE_USER)
   {
       if (m_data)
           delete[] m_data;
 
       m_data = new char[size];
       std::memcpy(m_data, ptr, size);
   }
   else
       DE_ASSERT(false);
}
 
void AttributeArray::setupArray (bool bound, int offset, int size, DrawTestSpec::InputType inputType, DrawTestSpec::OutputType outType, bool normalized, int stride, int instanceDivisor, const rr::GenericVec4& defaultAttrib, bool isPositionAttr, bool bgraComponentOrder)
{
   m_componentCount    = size;
   m_bound                = bound;
   m_inputType            = inputType;
   m_outputType        = outType;
   m_normalize            = normalized;
   m_stride            = stride;
   m_offset            = offset;
   m_defaultAttrib        = defaultAttrib;
   m_instanceDivisor    = instanceDivisor;
   m_isPositionAttr    = isPositionAttr;
   m_bgraOrder            = bgraComponentOrder;
}
 
void AttributeArray::bindAttribute (deUint32 loc)
{
   if (!isBound())
   {
       switch (m_inputType)
       {
           case DrawTestSpec::INPUTTYPE_FLOAT:
           {
               tcu::Vec4 attr = m_defaultAttrib.get<float>();
 
               switch (m_componentCount)
               {
                   case 1: m_ctx.vertexAttrib1f(loc, attr.x()); break;
                   case 2: m_ctx.vertexAttrib2f(loc, attr.x(), attr.y()); break;
                   case 3: m_ctx.vertexAttrib3f(loc, attr.x(), attr.y(), attr.z()); break;
                   case 4: m_ctx.vertexAttrib4f(loc, attr.x(), attr.y(), attr.z(), attr.w()); break;
                   default: DE_ASSERT(DE_FALSE); break;
               }
               break;
           }
           case DrawTestSpec::INPUTTYPE_INT:
           {
               tcu::IVec4 attr = m_defaultAttrib.get<deInt32>();
               m_ctx.vertexAttribI4i(loc, attr.x(), attr.y(), attr.z(), attr.w());
               break;
           }
           case DrawTestSpec::INPUTTYPE_UNSIGNED_INT:
           {
               tcu::UVec4 attr = m_defaultAttrib.get<deUint32>();
               m_ctx.vertexAttribI4ui(loc, attr.x(), attr.y(), attr.z(), attr.w());
               break;
           }
           default:
               DE_ASSERT(DE_FALSE);
               break;
       }
   }
   else
   {
       const deUint8* basePtr = DE_NULL;
 
       if (m_storage == DrawTestSpec::STORAGE_BUFFER)
       {
           m_ctx.bindBuffer(targetToGL(m_target), m_glBuffer);
           GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glBindBuffer()");
 
           basePtr = DE_NULL;
       }
       else if (m_storage == DrawTestSpec::STORAGE_USER)
       {
           m_ctx.bindBuffer(targetToGL(m_target), 0);
           GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glBindBuffer()");
 
           basePtr = (const deUint8*)m_data;
       }
       else
           DE_ASSERT(DE_FALSE);
 
       if (!inputTypeIsFloatType(m_inputType))
       {
           // Input is not float type
 
           if (outputTypeIsFloatType(m_outputType))
           {
               const int size = (m_bgraOrder) ? (GL_BGRA) : (m_componentCount);
 
               DE_ASSERT(!(m_bgraOrder && m_componentCount != 4));
 
               // Output type is float type
               m_ctx.vertexAttribPointer(loc, size, inputTypeToGL(m_inputType), m_normalize, m_stride, basePtr + m_offset);
               GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glVertexAttribPointer()");
           }
           else
           {
               // Output type is int type
               m_ctx.vertexAttribIPointer(loc, m_componentCount, inputTypeToGL(m_inputType), m_stride, basePtr + m_offset);
               GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glVertexAttribIPointer()");
           }
       }
       else
       {
           // Input type is float type
 
           // Output type must be float type
           DE_ASSERT(outputTypeIsFloatType(m_outputType));
 
           m_ctx.vertexAttribPointer(loc, m_componentCount, inputTypeToGL(m_inputType), m_normalize, m_stride, basePtr + m_offset);
           GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glVertexAttribPointer()");
       }
 
       if (m_instanceDivisor)
           m_ctx.vertexAttribDivisor(loc, m_instanceDivisor);
   }
}
 
void AttributeArray::bindIndexArray (DrawTestSpec::Target target)
{
   if (m_storage == DrawTestSpec::STORAGE_USER)
   {
   }
   else if (m_storage == DrawTestSpec::STORAGE_BUFFER)
   {
       m_ctx.bindBuffer(targetToGL(target), m_glBuffer);
   }
}
 
// DrawTestShaderProgram
 
class DrawTestShaderProgram : public sglr::ShaderProgram
{
public:
                                               DrawTestShaderProgram        (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays);
 
   void                                        shadeVertices                (const rr::VertexAttrib* inputs, rr::VertexPacket* const* packets, const int numPackets) const;
   void                                        shadeFragments                (rr::FragmentPacket* packets, const int numPackets, const rr::FragmentShadingContext& context) const;
 
private:
   static std::string                            genVertexSource                (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays);
   static std::string                            genFragmentSource            (const glu::RenderContext& ctx);
   static void                                    generateShaderParams        (std::map<std::string, std::string>& params, glu::ContextType type);
   static rr::GenericVecType                    mapOutputType                (const DrawTestSpec::OutputType& type);
   static int                                    getComponentCount            (const DrawTestSpec::OutputType& type);
 
   static sglr::pdec::ShaderProgramDeclaration createProgramDeclaration    (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays);
 
   std::vector<int>                            m_componentCount;
   std::vector<bool>                            m_isCoord;
   std::vector<rr::GenericVecType>                m_attrType;
};
 
DrawTestShaderProgram::DrawTestShaderProgram (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays)
   : sglr::ShaderProgram    (createProgramDeclaration(ctx, arrays))
   , m_componentCount        (arrays.size())
   , m_isCoord                (arrays.size())
   , m_attrType            (arrays.size())
{
   for (int arrayNdx = 0; arrayNdx < (int)arrays.size(); arrayNdx++)
   {
       m_componentCount[arrayNdx]    = getComponentCount(arrays[arrayNdx]->getOutputType());
       m_isCoord[arrayNdx]            = arrays[arrayNdx]->isPositionAttribute();
       m_attrType[arrayNdx]        = mapOutputType(arrays[arrayNdx]->getOutputType());
   }
}
 
template <typename T>
void calcShaderColorCoord (tcu::Vec2& coord, tcu::Vec3& color, const tcu::Vector<T, 4>& attribValue, bool isCoordinate, int numComponents)
{
   if (isCoordinate)
       switch (numComponents)
       {
           case 1:    coord += tcu::Vec2((float)attribValue.x(),                            (float)attribValue.x());                            break;
           case 2:    coord += tcu::Vec2((float)attribValue.x(),                            (float)attribValue.y());                            break;
           case 3:    coord += tcu::Vec2((float)attribValue.x() + (float)attribValue.z(),    (float)attribValue.y());                            break;
           case 4:    coord += tcu::Vec2((float)attribValue.x() + (float)attribValue.z(),    (float)attribValue.y() + (float)attribValue.w());    break;
 
           default:
               DE_ASSERT(false);
       }
   else
   {
       switch (numComponents)
       {
           case 1:
               color = color * (float)attribValue.x();
               break;
 
           case 2:
               color.x() = color.x() * (float)attribValue.x();
               color.y() = color.y() * (float)attribValue.y();
               break;
 
           case 3:
               color.x() = color.x() * (float)attribValue.x();
               color.y() = color.y() * (float)attribValue.y();
               color.z() = color.z() * (float)attribValue.z();
               break;
 
           case 4:
               color.x() = color.x() * (float)attribValue.x() * (float)attribValue.w();
               color.y() = color.y() * (float)attribValue.y() * (float)attribValue.w();
               color.z() = color.z() * (float)attribValue.z() * (float)attribValue.w();
               break;
 
           default:
               DE_ASSERT(false);
       }
   }
}
 
void DrawTestShaderProgram::shadeVertices (const rr::VertexAttrib* inputs, rr::VertexPacket* const* packets, const int numPackets) const
{
   const float    u_coordScale = getUniformByName("u_coordScale").value.f;
   const float u_colorScale = getUniformByName("u_colorScale").value.f;
 
   for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
   {
       const size_t varyingLocColor = 0;
 
       rr::VertexPacket& packet = *packets[packetNdx];
 
       // Calc output color
       tcu::Vec2 coord = tcu::Vec2(0.0, 0.0);
       tcu::Vec3 color = tcu::Vec3(1.0, 1.0, 1.0);
 
       for (int attribNdx = 0; attribNdx < (int)m_attrType.size(); attribNdx++)
       {
           const int    numComponents    = m_componentCount[attribNdx];
           const bool    isCoord            = m_isCoord[attribNdx];
 
           switch (m_attrType[attribNdx])
           {
               case rr::GENERICVECTYPE_FLOAT:    calcShaderColorCoord(coord, color, rr::readVertexAttribFloat(inputs[attribNdx], packet.instanceNdx, packet.vertexNdx), isCoord, numComponents);    break;
               case rr::GENERICVECTYPE_INT32:    calcShaderColorCoord(coord, color, rr::readVertexAttribInt    (inputs[attribNdx], packet.instanceNdx, packet.vertexNdx), isCoord, numComponents);    break;
               case rr::GENERICVECTYPE_UINT32:    calcShaderColorCoord(coord, color, rr::readVertexAttribUint    (inputs[attribNdx], packet.instanceNdx, packet.vertexNdx), isCoord, numComponents);    break;
               default:
                   DE_ASSERT(false);
           }
       }
 
       // Transform position
       {
           packet.position = tcu::Vec4(u_coordScale * coord.x(), u_coordScale * coord.y(), 1.0f, 1.0f);
           packet.pointSize = 1.0f;
       }
 
       // Pass color to FS
       {
           packet.outputs[varyingLocColor] = tcu::Vec4(u_colorScale * color.x(), u_colorScale * color.y(), u_colorScale * color.z(), 1.0f) * 0.5f + tcu::Vec4(0.5f, 0.5f, 0.5f, 0.5f);
       }
   }
}
 
void DrawTestShaderProgram::shadeFragments (rr::FragmentPacket* packets, const int numPackets, const rr::FragmentShadingContext& context) const
{
   const size_t varyingLocColor = 0;
 
   for (int packetNdx = 0; packetNdx < numPackets; ++packetNdx)
   {
       rr::FragmentPacket& packet = packets[packetNdx];
 
       for (int fragNdx = 0; fragNdx < 4; ++fragNdx)
           rr::writeFragmentOutput(context, packetNdx, fragNdx, 0, rr::readVarying<float>(packet, context, varyingLocColor, fragNdx));
   }
}
 
std::string DrawTestShaderProgram::genVertexSource (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays)
{
   std::map<std::string, std::string>    params;
   std::stringstream                    vertexShaderTmpl;
 
   generateShaderParams(params, ctx.getType());
 
   vertexShaderTmpl << "${VTX_HDR}";
 
   for (int arrayNdx = 0; arrayNdx < (int)arrays.size(); arrayNdx++)
   {
       vertexShaderTmpl
           << "${VTX_IN} highp " << outputTypeToGLType(arrays[arrayNdx]->getOutputType()) << " a_" << arrayNdx << ";\n";
   }
 
   vertexShaderTmpl <<
       "uniform highp float u_coordScale;\n"
       "uniform highp float u_colorScale;\n"
       "${VTX_OUT} ${COL_PRECISION} vec4 v_color;\n"
       "void main(void)\n"
       "{\n"
       "\tgl_PointSize = 1.0;\n"
       "\thighp vec2 coord = vec2(0.0, 0.0);\n"
       "\thighp vec3 color = vec3(1.0, 1.0, 1.0);\n";
 
   for (int arrayNdx = 0; arrayNdx < (int)arrays.size(); arrayNdx++)
   {
       const bool isPositionAttr = arrays[arrayNdx]->isPositionAttribute();
 
       if (isPositionAttr)
       {
           switch (arrays[arrayNdx]->getOutputType())
           {
               case (DrawTestSpec::OUTPUTTYPE_FLOAT):
               case (DrawTestSpec::OUTPUTTYPE_INT):
               case (DrawTestSpec::OUTPUTTYPE_UINT):
                   vertexShaderTmpl <<
                       "\tcoord += vec2(float(a_" << arrayNdx << "), float(a_" << arrayNdx << "));\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC2):
               case (DrawTestSpec::OUTPUTTYPE_IVEC2):
               case (DrawTestSpec::OUTPUTTYPE_UVEC2):
                   vertexShaderTmpl <<
                       "\tcoord += vec2(a_" << arrayNdx << ".xy);\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC3):
               case (DrawTestSpec::OUTPUTTYPE_IVEC3):
               case (DrawTestSpec::OUTPUTTYPE_UVEC3):
                   vertexShaderTmpl <<
                       "\tcoord += vec2(a_" << arrayNdx << ".xy);\n"
                       "\tcoord.x += float(a_" << arrayNdx << ".z);\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC4):
               case (DrawTestSpec::OUTPUTTYPE_IVEC4):
               case (DrawTestSpec::OUTPUTTYPE_UVEC4):
                   vertexShaderTmpl <<
                       "\tcoord += vec2(a_" << arrayNdx << ".xy);\n"
                       "\tcoord += vec2(a_" << arrayNdx << ".zw);\n";
                   break;
 
               default:
                   DE_ASSERT(false);
                   break;
           }
       }
       else
       {
           switch (arrays[arrayNdx]->getOutputType())
           {
               case (DrawTestSpec::OUTPUTTYPE_FLOAT):
               case (DrawTestSpec::OUTPUTTYPE_INT):
               case (DrawTestSpec::OUTPUTTYPE_UINT):
                   vertexShaderTmpl <<
                       "\tcolor = color * float(a_" << arrayNdx << ");\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC2):
               case (DrawTestSpec::OUTPUTTYPE_IVEC2):
               case (DrawTestSpec::OUTPUTTYPE_UVEC2):
                   vertexShaderTmpl <<
                       "\tcolor.rg = color.rg * vec2(a_" << arrayNdx << ".xy);\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC3):
               case (DrawTestSpec::OUTPUTTYPE_IVEC3):
               case (DrawTestSpec::OUTPUTTYPE_UVEC3):
                   vertexShaderTmpl <<
                       "\tcolor = color.rgb * vec3(a_" << arrayNdx << ".xyz);\n";
                   break;
 
               case (DrawTestSpec::OUTPUTTYPE_VEC4):
               case (DrawTestSpec::OUTPUTTYPE_IVEC4):
               case (DrawTestSpec::OUTPUTTYPE_UVEC4):
                   vertexShaderTmpl <<
                       "\tcolor = color.rgb * vec3(a_" << arrayNdx << ".xyz) * float(a_" << arrayNdx << ".w);\n";
                   break;
 
               default:
                   DE_ASSERT(false);
                   break;
           }
       }
   }
 
   vertexShaderTmpl <<
       "\tv_color = vec4(u_colorScale * color, 1.0) * 0.5 + vec4(0.5, 0.5, 0.5, 0.5);\n"
       "\tgl_Position = vec4(u_coordScale * coord, 1.0, 1.0);\n"
       "}\n";
 
   return tcu::StringTemplate(vertexShaderTmpl.str().c_str()).specialize(params);
}
 
std::string DrawTestShaderProgram::genFragmentSource (const glu::RenderContext& ctx)
{
   std::map<std::string, std::string> params;
 
   generateShaderParams(params, ctx.getType());
 
   static const char* fragmentShaderTmpl =
       "${FRAG_HDR}"
       "${FRAG_IN} ${COL_PRECISION} vec4 v_color;\n"
       "void main(void)\n"
       "{\n"
       "\t${FRAG_COLOR} = v_color;\n"
       "}\n";
 
   return tcu::StringTemplate(fragmentShaderTmpl).specialize(params);
}
 
void DrawTestShaderProgram::generateShaderParams (std::map<std::string, std::string>& params, glu::ContextType type)
{
   if (glu::isGLSLVersionSupported(type, glu::GLSL_VERSION_300_ES))
   {
       params["VTX_IN"]        = "in";
       params["VTX_OUT"]        = "out";
       params["FRAG_IN"]        = "in";
       params["FRAG_COLOR"]    = "dEQP_FragColor";
       params["VTX_HDR"]        = "#version 300 es\n";
       params["FRAG_HDR"]        = "#version 300 es\nlayout(location = 0) out mediump vec4 dEQP_FragColor;\n";
       params["COL_PRECISION"]    = "mediump";
   }
   else if (glu::isGLSLVersionSupported(type, glu::GLSL_VERSION_100_ES))
   {
       params["VTX_IN"]        = "attribute";
       params["VTX_OUT"]        = "varying";
       params["FRAG_IN"]        = "varying";
       params["FRAG_COLOR"]    = "gl_FragColor";
       params["VTX_HDR"]        = "";
       params["FRAG_HDR"]        = "";
       params["COL_PRECISION"]    = "mediump";
   }
   else if (glu::isGLSLVersionSupported(type, glu::GLSL_VERSION_430))
   {
       params["VTX_IN"]        = "in";
       params["VTX_OUT"]        = "out";
       params["FRAG_IN"]        = "in";
       params["FRAG_COLOR"]    = "dEQP_FragColor";
       params["VTX_HDR"]        = "#version 430\n";
       params["FRAG_HDR"]        = "#version 430\nlayout(location = 0) out highp vec4 dEQP_FragColor;\n";
       params["COL_PRECISION"]    = "highp";
   }
   else if (glu::isGLSLVersionSupported(type, glu::GLSL_VERSION_330))
   {
       params["VTX_IN"]        = "in";
       params["VTX_OUT"]        = "out";
       params["FRAG_IN"]        = "in";
       params["FRAG_COLOR"]    = "dEQP_FragColor";
       params["VTX_HDR"]        = "#version 330\n";
       params["FRAG_HDR"]        = "#version 330\nlayout(location = 0) out mediump vec4 dEQP_FragColor;\n";
       params["COL_PRECISION"]    = "mediump";
   }
   else
       DE_ASSERT(DE_FALSE);
}
 
rr::GenericVecType DrawTestShaderProgram::mapOutputType (const DrawTestSpec::OutputType& type)
{
   switch (type)
   {
       case (DrawTestSpec::OUTPUTTYPE_FLOAT):
       case (DrawTestSpec::OUTPUTTYPE_VEC2):
       case (DrawTestSpec::OUTPUTTYPE_VEC3):
       case (DrawTestSpec::OUTPUTTYPE_VEC4):
           return rr::GENERICVECTYPE_FLOAT;
 
       case (DrawTestSpec::OUTPUTTYPE_INT):
       case (DrawTestSpec::OUTPUTTYPE_IVEC2):
       case (DrawTestSpec::OUTPUTTYPE_IVEC3):
       case (DrawTestSpec::OUTPUTTYPE_IVEC4):
           return rr::GENERICVECTYPE_INT32;
 
       case (DrawTestSpec::OUTPUTTYPE_UINT):
       case (DrawTestSpec::OUTPUTTYPE_UVEC2):
       case (DrawTestSpec::OUTPUTTYPE_UVEC3):
       case (DrawTestSpec::OUTPUTTYPE_UVEC4):
           return rr::GENERICVECTYPE_UINT32;
 
       default:
           DE_ASSERT(false);
           return rr::GENERICVECTYPE_LAST;
   }
}
 
int DrawTestShaderProgram::getComponentCount (const DrawTestSpec::OutputType& type)
{
   switch (type)
   {
       case (DrawTestSpec::OUTPUTTYPE_FLOAT):
       case (DrawTestSpec::OUTPUTTYPE_INT):
       case (DrawTestSpec::OUTPUTTYPE_UINT):
           return 1;
 
       case (DrawTestSpec::OUTPUTTYPE_VEC2):
       case (DrawTestSpec::OUTPUTTYPE_IVEC2):
       case (DrawTestSpec::OUTPUTTYPE_UVEC2):
           return 2;
 
       case (DrawTestSpec::OUTPUTTYPE_VEC3):
       case (DrawTestSpec::OUTPUTTYPE_IVEC3):
       case (DrawTestSpec::OUTPUTTYPE_UVEC3):
           return 3;
 
       case (DrawTestSpec::OUTPUTTYPE_VEC4):
       case (DrawTestSpec::OUTPUTTYPE_IVEC4):
       case (DrawTestSpec::OUTPUTTYPE_UVEC4):
           return 4;
 
       default:
           DE_ASSERT(false);
           return 0;
   }
}
 
sglr::pdec::ShaderProgramDeclaration DrawTestShaderProgram::createProgramDeclaration (const glu::RenderContext& ctx, const std::vector<AttributeArray*>& arrays)
{
   sglr::pdec::ShaderProgramDeclaration decl;
 
   for (int arrayNdx = 0; arrayNdx < (int)arrays.size(); arrayNdx++)
       decl << sglr::pdec::VertexAttribute(std::string("a_") + de::toString(arrayNdx), mapOutputType(arrays[arrayNdx]->getOutputType()));
 
   decl << sglr::pdec::VertexToFragmentVarying(rr::GENERICVECTYPE_FLOAT);
   decl << sglr::pdec::FragmentOutput(rr::GENERICVECTYPE_FLOAT);
 
   decl << sglr::pdec::VertexSource(genVertexSource(ctx, arrays));
   decl << sglr::pdec::FragmentSource(genFragmentSource(ctx));
 
   decl << sglr::pdec::Uniform("u_coordScale", glu::TYPE_FLOAT);
   decl << sglr::pdec::Uniform("u_colorScale", glu::TYPE_FLOAT);
 
   return decl;
}
 
class RandomArrayGenerator
{
public:
   static char*            generateArray            (int seed, int elementCount, int componentCount, int offset, int stride, DrawTestSpec::InputType type);
   static char*            generateIndices            (int seed, int elementCount, DrawTestSpec::IndexType type, int offset, int min, int max, int indexBase);
   static rr::GenericVec4    generateAttributeValue    (int seed, DrawTestSpec::InputType type);
 
private:
   template<typename T>
   static char*            createIndices            (int seed, int elementCount, int offset, int min, int max, int indexBase);
 
   static char*            generateBasicArray        (int seed, int elementCount, int componentCount, int offset, int stride, DrawTestSpec::InputType type);
   template<typename T, typename GLType>
   static char*            createBasicArray        (int seed, int elementCount, int componentCount, int offset, int stride);
   static char*            generatePackedArray        (int seed, int elementCount, int componentCount, int offset, int stride);
};
 
char* RandomArrayGenerator::generateArray (int seed, int elementCount, int componentCount, int offset, int stride, DrawTestSpec::InputType type)
{
   if (type == DrawTestSpec::INPUTTYPE_INT_2_10_10_10 || type == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10)
       return generatePackedArray(seed, elementCount, componentCount, offset, stride);
   else
       return generateBasicArray(seed, elementCount, componentCount, offset, stride, type);
}
 
char* RandomArrayGenerator::generateBasicArray (int seed, int elementCount, int componentCount, int offset, int stride, DrawTestSpec::InputType type)
{
   switch (type)
   {
       case DrawTestSpec::INPUTTYPE_FLOAT:                return createBasicArray<float,        GLValue::Float>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_DOUBLE:            return createBasicArray<double,        GLValue::Double>(seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_SHORT:                return createBasicArray<deInt16,    GLValue::Short>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT:    return createBasicArray<deUint16,    GLValue::Ushort>(seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_BYTE:                return createBasicArray<deInt8,        GLValue::Byte>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE:        return createBasicArray<deUint8,    GLValue::Ubyte>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_FIXED:                return createBasicArray<deInt32,    GLValue::Fixed>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_INT:                return createBasicArray<deInt32,    GLValue::Int>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_UNSIGNED_INT:        return createBasicArray<deUint32,    GLValue::Uint>    (seed, elementCount, componentCount, offset, stride);
       case DrawTestSpec::INPUTTYPE_HALF:                return createBasicArray<deFloat16,    GLValue::Half>    (seed, elementCount, componentCount, offset, stride);
       default:
           DE_ASSERT(false);
           break;
   }
   return DE_NULL;
}
 
#if (DE_COMPILER == DE_COMPILER_GCC) && (__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)
   // GCC 4.8/4.9 incorrectly emits array-bounds warning from createBasicArray()
#    define GCC_ARRAY_BOUNDS_FALSE_NEGATIVE 1
#endif
 
#if defined(GCC_ARRAY_BOUNDS_FALSE_NEGATIVE)
#    pragma GCC diagnostic push
#    pragma GCC diagnostic ignored "-Warray-bounds"
#endif
 
template<typename T, typename GLType>
char* RandomArrayGenerator::createBasicArray (int seed, int elementCount, int componentCount, int offset, int stride)
{
   DE_ASSERT(componentCount >= 1 && componentCount <= 4);
 
   const GLType min = extractGLValue<GLType>(GLValue::getMinValue(GLValueTypeTraits<GLType>::Type));
   const GLType max = extractGLValue<GLType>(GLValue::getMaxValue(GLValueTypeTraits<GLType>::Type));
 
   const size_t componentSize    = sizeof(T);
   const size_t elementSize    = componentSize * componentCount;
   const size_t bufferSize        = offset + (elementCount - 1) * stride + elementSize;
 
   char* data = new char[bufferSize];
   char* writePtr = data + offset;
 
   GLType previousComponents[4];
 
   deRandom rnd;
   deRandom_init(&rnd, seed);
 
   for (int vertexNdx = 0; vertexNdx < elementCount; vertexNdx++)
   {
       GLType components[4];
 
       for (int componentNdx = 0; componentNdx < componentCount; componentNdx++)
       {
           components[componentNdx] = getRandom<GLType>(rnd, min, max);
 
           // Try to not create vertex near previous
           if (vertexNdx != 0 && abs(components[componentNdx] - previousComponents[componentNdx]) < minValue<GLType>())
           {
               // Too close, try again (but only once)
               components[componentNdx] = getRandom<GLType>(rnd, min, max);
           }
       }
 
       for (int componentNdx = 0; componentNdx < componentCount; componentNdx++)
           previousComponents[componentNdx] = components[componentNdx];
 
       for (int componentNdx = 0; componentNdx < componentCount; componentNdx++)
           alignmentSafeAssignment(writePtr + componentNdx*componentSize, components[componentNdx].getValue());
 
       writePtr += stride;
   }
 
   return data;
}
 
#if defined(GCC_ARRAY_BOUNDS_FALSE_NEGATIVE)
#    pragma GCC diagnostic pop
#endif
 
char* RandomArrayGenerator::generatePackedArray (int seed, int elementCount, int componentCount, int offset, int stride)
{
   DE_ASSERT(componentCount == 4);
   DE_UNREF(componentCount);
 
   const deUint32 limit10        = (1 << 10);
   const deUint32 limit2        = (1 << 2);
   const size_t elementSize    = 4;
   const size_t bufferSize        = offset + (elementCount - 1) * stride + elementSize;
 
   char* data = new char[bufferSize];
   char* writePtr = data + offset;
 
   deRandom rnd;
   deRandom_init(&rnd, seed);
 
   for (int vertexNdx = 0; vertexNdx < elementCount; vertexNdx++)
   {
       const deUint32 x            = deRandom_getUint32(&rnd) % limit10;
       const deUint32 y            = deRandom_getUint32(&rnd) % limit10;
       const deUint32 z            = deRandom_getUint32(&rnd) % limit10;
       const deUint32 w            = deRandom_getUint32(&rnd) % limit2;
       const deUint32 packedValue    = (w << 30) | (z << 20) | (y << 10) | (x);
 
       alignmentSafeAssignment(writePtr, packedValue);
       writePtr += stride;
   }
 
   return data;
}
 
char* RandomArrayGenerator::generateIndices (int seed, int elementCount, DrawTestSpec::IndexType type, int offset, int min, int max, int indexBase)
{
   char* data = DE_NULL;
 
   switch (type)
   {
       case DrawTestSpec::INDEXTYPE_BYTE:
           data = createIndices<deUint8>(seed, elementCount, offset, min, max, indexBase);
           break;
 
       case DrawTestSpec::INDEXTYPE_SHORT:
           data = createIndices<deUint16>(seed, elementCount, offset, min, max, indexBase);
           break;
 
       case DrawTestSpec::INDEXTYPE_INT:
           data = createIndices<deUint32>(seed, elementCount, offset, min, max, indexBase);
           break;
 
       default:
           DE_ASSERT(false);
           break;
   }
 
   return data;
}
 
template<typename T>
char* RandomArrayGenerator::createIndices (int seed, int elementCount, int offset, int min, int max, int indexBase)
{
   const size_t elementSize    = sizeof(T);
   const size_t bufferSize        = offset + elementCount * elementSize;
 
   char* data = new char[bufferSize];
   char* writePtr = data + offset;
 
   deUint32 oldNdx1 = deUint32(-1);
   deUint32 oldNdx2 = deUint32(-1);
 
   deRandom rnd;
   deRandom_init(&rnd, seed);
 
   DE_ASSERT(indexBase >= 0); // watch for underflows
 
   if (min < 0 || (size_t)min > std::numeric_limits<T>::max() ||
       max < 0 || (size_t)max > std::numeric_limits<T>::max() ||
       min > max)
       DE_FATAL("Invalid range");
 
   for (int elementNdx = 0; elementNdx < elementCount; ++elementNdx)
   {
       deUint32 ndx = getRandom(rnd, GLValue::Uint::create(min), GLValue::Uint::create(max)).getValue();
 
       // Try not to generate same index as any of previous two. This prevents
       // generation of degenerate triangles and lines. If [min, max] is too
       // small this cannot be guaranteed.
 
       if (ndx == oldNdx1)            ++ndx;
       if (ndx > (deUint32)max)    ndx = min;
       if (ndx == oldNdx2)            ++ndx;
       if (ndx > (deUint32)max)    ndx = min;
       if (ndx == oldNdx1)            ++ndx;
       if (ndx > (deUint32)max)    ndx = min;
 
       oldNdx2 = oldNdx1;
       oldNdx1 = ndx;
 
       ndx += indexBase;
 
       alignmentSafeAssignment<T>(writePtr + elementSize * elementNdx, T(ndx));
   }
 
   return data;
}
 
rr::GenericVec4    RandomArrayGenerator::generateAttributeValue (int seed, DrawTestSpec::InputType type)
{
   de::Random random(seed);
 
   switch (type)
   {
       case DrawTestSpec::INPUTTYPE_FLOAT:
           return rr::GenericVec4(generateRandomVec4(random));
 
       case DrawTestSpec::INPUTTYPE_INT:
           return rr::GenericVec4(generateRandomIVec4(random));
 
       case DrawTestSpec::INPUTTYPE_UNSIGNED_INT:
           return rr::GenericVec4(generateRandomUVec4(random));
 
       default:
           DE_ASSERT(false);
           return rr::GenericVec4(tcu::Vec4(1, 1, 1, 1));
   }
}
 
} // anonymous
 
// AttributePack
 
class AttributePack
{
public:
 
                               AttributePack        (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, sglr::Context& drawContext, const tcu::UVec2& screenSize, bool useVao, bool logEnabled);
                               ~AttributePack        (void);
 
   AttributeArray*                getArray            (int i);
   int                            getArrayCount        (void);
 
   void                        newArray            (DrawTestSpec::Storage storage);
   void                        clearArrays            (void);
   void                        updateProgram        (void);
 
   void                        render                (DrawTestSpec::Primitive primitive, DrawTestSpec::DrawMethod drawMethod, int firstVertex, int vertexCount, DrawTestSpec::IndexType indexType, const void* indexOffset, int rangeStart, int rangeEnd, int instanceCount, int indirectOffset, int baseVertex, float coordScale, float colorScale, AttributeArray* indexArray);
 
   const tcu::Surface&            getSurface            (void) const { return m_screen; }
private:
   tcu::TestContext&            m_testCtx;
   glu::RenderContext&            m_renderCtx;
   sglr::Context&                m_ctx;
 
   std::vector<AttributeArray*>m_arrays;
   sglr::ShaderProgram*        m_program;
   tcu::Surface                m_screen;
   const bool                    m_useVao;
   const bool                    m_logEnabled;
   deUint32                    m_programID;
   deUint32                    m_vaoID;
};
 
AttributePack::AttributePack (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, sglr::Context& drawContext, const tcu::UVec2& screenSize, bool useVao, bool logEnabled)
   : m_testCtx        (testCtx)
   , m_renderCtx    (renderCtx)
   , m_ctx            (drawContext)
   , m_program        (DE_NULL)
   , m_screen        (screenSize.x(), screenSize.y())
   , m_useVao        (useVao)
   , m_logEnabled    (logEnabled)
   , m_programID    (0)
   , m_vaoID        (0)
{
   if (m_useVao)
       m_ctx.genVertexArrays(1, &m_vaoID);
}
 
AttributePack::~AttributePack (void)
{
   clearArrays();
 
   if (m_programID)
       m_ctx.deleteProgram(m_programID);
 
   if (m_program)
       delete m_program;
 
   if (m_useVao)
       m_ctx.deleteVertexArrays(1, &m_vaoID);
}
 
AttributeArray* AttributePack::getArray (int i)
{
   return m_arrays.at(i);
}
 
int AttributePack::getArrayCount (void)
{
   return (int)m_arrays.size();
}
 
void AttributePack::newArray (DrawTestSpec::Storage storage)
{
   m_arrays.push_back(new AttributeArray(storage, m_ctx));
}
 
void AttributePack::clearArrays (void)
{
   for (std::vector<AttributeArray*>::iterator itr = m_arrays.begin(); itr != m_arrays.end(); itr++)
       delete *itr;
   m_arrays.clear();
}
 
void AttributePack::updateProgram (void)
{
   if (m_programID)
       m_ctx.deleteProgram(m_programID);
   if (m_program)
       delete m_program;
 
   m_program = new DrawTestShaderProgram(m_renderCtx, m_arrays);
   m_programID = m_ctx.createProgram(m_program);
}
 
void AttributePack::render (DrawTestSpec::Primitive primitive, DrawTestSpec::DrawMethod drawMethod, int firstVertex, int vertexCount, DrawTestSpec::IndexType indexType, const void* indexOffset, int rangeStart, int rangeEnd, int instanceCount, int indirectOffset, int baseVertex, float coordScale, float colorScale, AttributeArray* indexArray)
{
   DE_ASSERT(m_program != DE_NULL);
   DE_ASSERT(m_programID != 0);
 
   m_ctx.viewport(0, 0, m_screen.getWidth(), m_screen.getHeight());
   m_ctx.clearColor(0.0, 0.0, 0.0, 1.0);
   m_ctx.clear(GL_COLOR_BUFFER_BIT);
 
   m_ctx.useProgram(m_programID);
   GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glUseProgram()");
 
   m_ctx.uniform1f(m_ctx.getUniformLocation(m_programID, "u_coordScale"), coordScale);
   m_ctx.uniform1f(m_ctx.getUniformLocation(m_programID, "u_colorScale"), colorScale);
 
   if (m_useVao)
       m_ctx.bindVertexArray(m_vaoID);
 
   if (indexArray)
       indexArray->bindIndexArray(DrawTestSpec::TARGET_ELEMENT_ARRAY);
 
   for (int arrayNdx = 0; arrayNdx < (int)m_arrays.size(); arrayNdx++)
   {
       std::stringstream attribName;
       attribName << "a_" << arrayNdx;
 
       deUint32 loc = m_ctx.getAttribLocation(m_programID, attribName.str().c_str());
 
       if (m_arrays[arrayNdx]->isBound())
       {
           m_ctx.enableVertexAttribArray(loc);
           GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glEnableVertexAttribArray()");
       }
 
       m_arrays[arrayNdx]->bindAttribute(loc);
   }
 
   if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWARRAYS)
   {
       m_ctx.drawArrays(primitiveToGL(primitive), firstVertex, vertexCount);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawArrays()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INSTANCED)
   {
       m_ctx.drawArraysInstanced(primitiveToGL(primitive), firstVertex, vertexCount, instanceCount);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawArraysInstanced()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS)
   {
       m_ctx.drawElements(primitiveToGL(primitive), vertexCount, indexTypeToGL(indexType), indexOffset);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawElements()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED)
   {
       m_ctx.drawRangeElements(primitiveToGL(primitive), rangeStart, rangeEnd, vertexCount, indexTypeToGL(indexType), indexOffset);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawRangeElements()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED)
   {
       m_ctx.drawElementsInstanced(primitiveToGL(primitive), vertexCount, indexTypeToGL(indexType), indexOffset, instanceCount);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawElementsInstanced()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWARRAYS_INDIRECT)
   {
       struct DrawCommand
       {
           GLuint count;
           GLuint primCount;
           GLuint first;
           GLuint reservedMustBeZero;
       };
       deUint8* buffer = new deUint8[sizeof(DrawCommand) + indirectOffset];
 
       {
           DrawCommand command;
 
           command.count                = vertexCount;
           command.primCount            = instanceCount;
           command.first                = firstVertex;
           command.reservedMustBeZero    = 0;
 
           memcpy(buffer + indirectOffset, &command, sizeof(command));
 
           if (m_logEnabled)
               m_testCtx.getLog()
                   << tcu::TestLog::Message
                   << "DrawArraysIndirectCommand:\n"
                   << "\tcount: " << command.count << "\n"
                   << "\tprimCount: " << command.primCount << "\n"
                   << "\tfirst: " << command.first << "\n"
                   << "\treservedMustBeZero: " << command.reservedMustBeZero << "\n"
                   << tcu::TestLog::EndMessage;
       }
 
       GLuint indirectBuf = 0;
       m_ctx.genBuffers(1, &indirectBuf);
       m_ctx.bindBuffer(GL_DRAW_INDIRECT_BUFFER, indirectBuf);
       m_ctx.bufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(DrawCommand) + indirectOffset, buffer, GL_STATIC_DRAW);
       delete [] buffer;
 
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "Setup draw indirect buffer");
 
       m_ctx.drawArraysIndirect(primitiveToGL(primitive), glu::BufferOffsetAsPointer(indirectOffset));
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawArraysIndirect()");
 
       m_ctx.deleteBuffers(1, &indirectBuf);
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INDIRECT)
   {
       struct DrawCommand
       {
           GLuint count;
           GLuint primCount;
           GLuint firstIndex;
           GLint  baseVertex;
           GLuint reservedMustBeZero;
       };
       deUint8* buffer = new deUint8[sizeof(DrawCommand) + indirectOffset];
 
       {
           DrawCommand command;
 
           // index offset must be converted to firstIndex by dividing with the index element size
           DE_ASSERT(((const deUint8*)indexOffset - (const deUint8*)DE_NULL) % gls::DrawTestSpec::indexTypeSize(indexType) == 0); // \note This is checked in spec validation
 
           command.count                = vertexCount;
           command.primCount            = instanceCount;
           command.firstIndex            = (glw::GLuint)(((const deUint8*)indexOffset - (const deUint8*)DE_NULL) / gls::DrawTestSpec::indexTypeSize(indexType));
           command.baseVertex            = baseVertex;
           command.reservedMustBeZero    = 0;
 
           memcpy(buffer + indirectOffset, &command, sizeof(command));
 
           if (m_logEnabled)
               m_testCtx.getLog()
                   << tcu::TestLog::Message
                   << "DrawElementsIndirectCommand:\n"
                   << "\tcount: " << command.count << "\n"
                   << "\tprimCount: " << command.primCount << "\n"
                   << "\tfirstIndex: " << command.firstIndex << "\n"
                   << "\tbaseVertex: " << command.baseVertex << "\n"
                   << "\treservedMustBeZero: " << command.reservedMustBeZero << "\n"
                   << tcu::TestLog::EndMessage;
       }
 
       GLuint indirectBuf = 0;
       m_ctx.genBuffers(1, &indirectBuf);
       m_ctx.bindBuffer(GL_DRAW_INDIRECT_BUFFER, indirectBuf);
       m_ctx.bufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(DrawCommand) + indirectOffset, buffer, GL_STATIC_DRAW);
       delete [] buffer;
 
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "Setup draw indirect buffer");
 
       m_ctx.drawElementsIndirect(primitiveToGL(primitive), indexTypeToGL(indexType), glu::BufferOffsetAsPointer(indirectOffset));
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawArraysIndirect()");
 
       m_ctx.deleteBuffers(1, &indirectBuf);
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_BASEVERTEX)
   {
       m_ctx.drawElementsBaseVertex(primitiveToGL(primitive), vertexCount, indexTypeToGL(indexType), indexOffset, baseVertex);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawElementsBaseVertex()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED_BASEVERTEX)
   {
       m_ctx.drawElementsInstancedBaseVertex(primitiveToGL(primitive), vertexCount, indexTypeToGL(indexType), indexOffset, instanceCount, baseVertex);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawElementsInstancedBaseVertex()");
   }
   else if (drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED_BASEVERTEX)
   {
       m_ctx.drawRangeElementsBaseVertex(primitiveToGL(primitive), rangeStart, rangeEnd, vertexCount, indexTypeToGL(indexType), indexOffset, baseVertex);
       GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDrawRangeElementsBaseVertex()");
   }
   else
       DE_ASSERT(DE_FALSE);
 
   for (int arrayNdx = 0; arrayNdx < (int)m_arrays.size(); arrayNdx++)
   {
       if (m_arrays[arrayNdx]->isBound())
       {
           std::stringstream attribName;
           attribName << "a_" << arrayNdx;
 
           deUint32 loc = m_ctx.getAttribLocation(m_programID, attribName.str().c_str());
 
           m_ctx.disableVertexAttribArray(loc);
           GLU_EXPECT_NO_ERROR(m_ctx.getError(), "glDisableVertexAttribArray()");
       }
   }
 
   if (m_useVao)
       m_ctx.bindVertexArray(0);
 
   m_ctx.useProgram(0);
   m_ctx.readPixels(m_screen, 0, 0, m_screen.getWidth(), m_screen.getHeight());
}
 
// DrawTestSpec
 
DrawTestSpec::AttributeSpec    DrawTestSpec::AttributeSpec::createAttributeArray (InputType inputType, OutputType outputType, Storage storage, Usage usage, int componentCount, int offset, int stride, bool normalize, int instanceDivisor)
{
   DrawTestSpec::AttributeSpec spec;
 
   spec.inputType            = inputType;
   spec.outputType            = outputType;
   spec.storage            = storage;
   spec.usage                = usage;
   spec.componentCount        = componentCount;
   spec.offset                = offset;
   spec.stride                = stride;
   spec.normalize            = normalize;
   spec.instanceDivisor    = instanceDivisor;
 
   spec.useDefaultAttribute= false;
 
   return spec;
}
 
DrawTestSpec::AttributeSpec    DrawTestSpec::AttributeSpec::createDefaultAttribute (InputType inputType, OutputType outputType, int componentCount)
{
   DE_ASSERT(inputType == INPUTTYPE_INT || inputType == INPUTTYPE_UNSIGNED_INT || inputType == INPUTTYPE_FLOAT);
   DE_ASSERT(inputType == INPUTTYPE_FLOAT || componentCount == 4);
 
   DrawTestSpec::AttributeSpec spec;
 
   spec.inputType                = inputType;
   spec.outputType                = outputType;
   spec.storage                = DrawTestSpec::STORAGE_LAST;
   spec.usage                    = DrawTestSpec::USAGE_LAST;
   spec.componentCount            = componentCount;
   spec.offset                    = 0;
   spec.stride                    = 0;
   spec.normalize                = 0;
   spec.instanceDivisor        = 0;
 
   spec.useDefaultAttribute    = true;
 
   return spec;
}
 
DrawTestSpec::AttributeSpec::AttributeSpec (void)
{
   inputType                    = DrawTestSpec::INPUTTYPE_LAST;
   outputType                    = DrawTestSpec::OUTPUTTYPE_LAST;
   storage                        = DrawTestSpec::STORAGE_LAST;
   usage                        = DrawTestSpec::USAGE_LAST;
   componentCount                = 0;
   offset                        = 0;
   stride                        = 0;
   normalize                    = false;
   instanceDivisor                = 0;
   useDefaultAttribute            = false;
   additionalPositionAttribute = false;
   bgraComponentOrder            = false;
}
 
int DrawTestSpec::AttributeSpec::hash (void) const
{
   if (useDefaultAttribute)
   {
       return 1 * int(inputType) + 7 * int(outputType) + 13 * componentCount;
   }
   else
   {
       return 1 * int(inputType) + 2 * int(outputType) + 3 * int(storage) + 5 * int(usage) + 7 * componentCount + 11 * offset + 13 * stride + 17 * (normalize ? 0 : 1) + 19 * instanceDivisor;
   }
}
 
bool DrawTestSpec::AttributeSpec::valid (glu::ApiType ctxType) const
{
   const bool inputTypeFloat                = inputType == DrawTestSpec::INPUTTYPE_FLOAT || inputType  == DrawTestSpec::INPUTTYPE_FIXED || inputType == DrawTestSpec::INPUTTYPE_HALF;
   const bool inputTypeUnsignedInteger        = inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE || inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT || inputType  == DrawTestSpec::INPUTTYPE_UNSIGNED_INT || inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10;
   const bool inputTypeSignedInteger        = inputType == DrawTestSpec::INPUTTYPE_BYTE  || inputType == DrawTestSpec::INPUTTYPE_SHORT || inputType == DrawTestSpec::INPUTTYPE_INT || inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10;
   const bool inputTypePacked                = inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10 || inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10;
 
   const bool outputTypeFloat                = outputType == DrawTestSpec::OUTPUTTYPE_FLOAT || outputType == DrawTestSpec::OUTPUTTYPE_VEC2  || outputType == DrawTestSpec::OUTPUTTYPE_VEC3  || outputType == DrawTestSpec::OUTPUTTYPE_VEC4;
   const bool outputTypeSignedInteger        = outputType == DrawTestSpec::OUTPUTTYPE_INT   || outputType == DrawTestSpec::OUTPUTTYPE_IVEC2 || outputType == DrawTestSpec::OUTPUTTYPE_IVEC3 || outputType == DrawTestSpec::OUTPUTTYPE_IVEC4;
   const bool outputTypeUnsignedInteger    = outputType == DrawTestSpec::OUTPUTTYPE_UINT  || outputType == DrawTestSpec::OUTPUTTYPE_UVEC2 || outputType == DrawTestSpec::OUTPUTTYPE_UVEC3 || outputType == DrawTestSpec::OUTPUTTYPE_UVEC4;
 
   if (useDefaultAttribute)
   {
       if (inputType != DrawTestSpec::INPUTTYPE_INT && inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_INT && inputType != DrawTestSpec::INPUTTYPE_FLOAT)
           return false;
 
       if (inputType != DrawTestSpec::INPUTTYPE_FLOAT && componentCount != 4)
           return false;
 
       // no casting allowed (undefined results)
       if (inputType == DrawTestSpec::INPUTTYPE_INT && !outputTypeSignedInteger)
           return false;
       if (inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT && !outputTypeUnsignedInteger)
           return false;
   }
 
   if (inputTypePacked && componentCount != 4)
       return false;
 
   // Invalid conversions:
 
   // float -> [u]int
   if (inputTypeFloat && !outputTypeFloat)
       return false;
 
   // uint -> int        (undefined results)
   if (inputTypeUnsignedInteger && outputTypeSignedInteger)
       return false;
 
   // int -> uint        (undefined results)
   if (inputTypeSignedInteger && outputTypeUnsignedInteger)
       return false;
 
   // packed -> non-float (packed formats are converted to floats)
   if (inputTypePacked && !outputTypeFloat)
       return false;
 
   // Invalid normalize. Normalize is only valid if output type is float
   if (normalize && !outputTypeFloat)
       return false;
 
   // Allow reverse order (GL_BGRA) only for packed and 4-component ubyte
   if (bgraComponentOrder && componentCount != 4)
       return false;
   if (bgraComponentOrder && inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10 && inputType != DrawTestSpec::INPUTTYPE_INT_2_10_10_10 && inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE)
       return false;
   if (bgraComponentOrder && normalize != true)
       return false;
 
   // GLES2 limits
   if (ctxType == glu::ApiType::es(2,0))
   {
       if (inputType != DrawTestSpec::INPUTTYPE_FLOAT && inputType != DrawTestSpec::INPUTTYPE_FIXED &&
           inputType != DrawTestSpec::INPUTTYPE_BYTE  && inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_BYTE &&
           inputType != DrawTestSpec::INPUTTYPE_SHORT && inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_SHORT)
           return false;
 
       if (!outputTypeFloat)
           return false;
 
       if (bgraComponentOrder)
           return false;
   }
 
   // GLES3 limits
   if (ctxType.getProfile() == glu::PROFILE_ES && ctxType.getMajorVersion() == 3)
   {
       if (bgraComponentOrder)
           return false;
   }
 
   // No user pointers in GL core
   if (ctxType.getProfile() == glu::PROFILE_CORE)
   {
       if (!useDefaultAttribute && storage == DrawTestSpec::STORAGE_USER)
           return false;
   }
 
   return true;
}
 
bool DrawTestSpec::AttributeSpec::isBufferAligned (void) const
{
   const bool inputTypePacked = inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10 || inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10;
 
   // Buffer alignment, offset is a multiple of underlying data type size?
   if (storage == STORAGE_BUFFER)
   {
       int dataTypeSize = gls::DrawTestSpec::inputTypeSize(inputType);
       if (inputTypePacked)
           dataTypeSize = 4;
 
       if (offset % dataTypeSize != 0)
           return false;
   }
 
   return true;
}
 
bool DrawTestSpec::AttributeSpec::isBufferStrideAligned (void) const
{
   const bool inputTypePacked = inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10 || inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10;
 
   // Buffer alignment, offset is a multiple of underlying data type size?
   if (storage == STORAGE_BUFFER)
   {
       int dataTypeSize = gls::DrawTestSpec::inputTypeSize(inputType);
       if (inputTypePacked)
           dataTypeSize = 4;
 
       if (stride % dataTypeSize != 0)
           return false;
   }
 
   return true;
}
 
std::string DrawTestSpec::targetToString(Target target)
{
   static const char* targets[] =
   {
       "element_array",    // TARGET_ELEMENT_ARRAY = 0,
       "array"                // TARGET_ARRAY,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::TARGET_LAST>(targets, (int)target);
}
 
std::string DrawTestSpec::inputTypeToString(InputType type)
{
   static const char* types[] =
   {
       "float",            // INPUTTYPE_FLOAT = 0,
       "fixed",            // INPUTTYPE_FIXED,
       "double",            // INPUTTYPE_DOUBLE
 
       "byte",                // INPUTTYPE_BYTE,
       "short",            // INPUTTYPE_SHORT,
 
       "unsigned_byte",    // INPUTTYPE_UNSIGNED_BYTE,
       "unsigned_short",    // INPUTTYPE_UNSIGNED_SHORT,
 
       "int",                        // INPUTTYPE_INT,
       "unsigned_int",                // INPUTTYPE_UNSIGNED_INT,
       "half",                        // INPUTTYPE_HALF,
       "unsigned_int2_10_10_10",    // INPUTTYPE_UNSIGNED_INT_2_10_10_10,
       "int2_10_10_10"                // INPUTTYPE_INT_2_10_10_10,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INPUTTYPE_LAST>(types, (int)type);
}
 
std::string DrawTestSpec::outputTypeToString(OutputType type)
{
   static const char* types[] =
   {
       "float",        // OUTPUTTYPE_FLOAT = 0,
       "vec2",            // OUTPUTTYPE_VEC2,
       "vec3",            // OUTPUTTYPE_VEC3,
       "vec4",            // OUTPUTTYPE_VEC4,
 
       "int",            // OUTPUTTYPE_INT,
       "uint",            // OUTPUTTYPE_UINT,
 
       "ivec2",        // OUTPUTTYPE_IVEC2,
       "ivec3",        // OUTPUTTYPE_IVEC3,
       "ivec4",        // OUTPUTTYPE_IVEC4,
 
       "uvec2",        // OUTPUTTYPE_UVEC2,
       "uvec3",        // OUTPUTTYPE_UVEC3,
       "uvec4",        // OUTPUTTYPE_UVEC4,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::OUTPUTTYPE_LAST>(types, (int)type);
}
 
std::string DrawTestSpec::usageTypeToString(Usage usage)
{
   static const char* usages[] =
   {
       "dynamic_draw",    // USAGE_DYNAMIC_DRAW = 0,
       "static_draw",    // USAGE_STATIC_DRAW,
       "stream_draw",    // USAGE_STREAM_DRAW,
 
       "stream_read",    // USAGE_STREAM_READ,
       "stream_copy",    // USAGE_STREAM_COPY,
 
       "static_read",    // USAGE_STATIC_READ,
       "static_copy",    // USAGE_STATIC_COPY,
 
       "dynamic_read",    // USAGE_DYNAMIC_READ,
       "dynamic_copy",    // USAGE_DYNAMIC_COPY,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::USAGE_LAST>(usages, (int)usage);
}
 
std::string    DrawTestSpec::storageToString (Storage storage)
{
   static const char* storages[] =
   {
       "user_ptr",    // STORAGE_USER = 0,
       "buffer"    // STORAGE_BUFFER,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::STORAGE_LAST>(storages, (int)storage);
}
 
std::string DrawTestSpec::primitiveToString (Primitive primitive)
{
   static const char* primitives[] =
   {
       "points",                    // PRIMITIVE_POINTS ,
       "triangles",                // PRIMITIVE_TRIANGLES,
       "triangle_fan",                // PRIMITIVE_TRIANGLE_FAN,
       "triangle_strip",            // PRIMITIVE_TRIANGLE_STRIP,
       "lines",                    // PRIMITIVE_LINES
       "line_strip",                // PRIMITIVE_LINE_STRIP
       "line_loop",                // PRIMITIVE_LINE_LOOP
       "lines_adjacency",            // PRIMITIVE_LINES_ADJACENCY
       "line_strip_adjacency",        // PRIMITIVE_LINE_STRIP_ADJACENCY
       "triangles_adjacency",        // PRIMITIVE_TRIANGLES_ADJACENCY
       "triangle_strip_adjacency",    // PRIMITIVE_TRIANGLE_STRIP_ADJACENCY
   };
 
   return de::getSizedArrayElement<DrawTestSpec::PRIMITIVE_LAST>(primitives, (int)primitive);
}
 
std::string DrawTestSpec::indexTypeToString (IndexType type)
{
   static const char* indexTypes[] =
   {
       "byte",        // INDEXTYPE_BYTE = 0,
       "short",    // INDEXTYPE_SHORT,
       "int",        // INDEXTYPE_INT,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INDEXTYPE_LAST>(indexTypes, (int)type);
}
 
std::string DrawTestSpec::drawMethodToString (DrawTestSpec::DrawMethod method)
{
   static const char* methods[] =
   {
       "draw_arrays",                            //!< DRAWMETHOD_DRAWARRAYS
       "draw_arrays_instanced",                //!< DRAWMETHOD_DRAWARRAYS_INSTANCED
       "draw_arrays_indirect",                    //!< DRAWMETHOD_DRAWARRAYS_INDIRECT
       "draw_elements",                        //!< DRAWMETHOD_DRAWELEMENTS
       "draw_range_elements",                    //!< DRAWMETHOD_DRAWELEMENTS_RANGED
       "draw_elements_instanced",                //!< DRAWMETHOD_DRAWELEMENTS_INSTANCED
       "draw_elements_indirect",                //!< DRAWMETHOD_DRAWELEMENTS_INDIRECT
       "draw_elements_base_vertex",            //!< DRAWMETHOD_DRAWELEMENTS_BASEVERTEX,
       "draw_elements_instanced_base_vertex",    //!< DRAWMETHOD_DRAWELEMENTS_INSTANCED_BASEVERTEX,
       "draw_range_elements_base_vertex",        //!< DRAWMETHOD_DRAWELEMENTS_RANGED_BASEVERTEX,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::DRAWMETHOD_LAST>(methods, (int)method);
}
 
int DrawTestSpec::inputTypeSize (InputType type)
{
   static const int size[] =
   {
       (int)sizeof(float),            // INPUTTYPE_FLOAT = 0,
       (int)sizeof(deInt32),        // INPUTTYPE_FIXED,
       (int)sizeof(double),        // INPUTTYPE_DOUBLE
 
       (int)sizeof(deInt8),        // INPUTTYPE_BYTE,
       (int)sizeof(deInt16),        // INPUTTYPE_SHORT,
 
       (int)sizeof(deUint8),        // INPUTTYPE_UNSIGNED_BYTE,
       (int)sizeof(deUint16),        // INPUTTYPE_UNSIGNED_SHORT,
 
       (int)sizeof(deInt32),        // INPUTTYPE_INT,
       (int)sizeof(deUint32),        // INPUTTYPE_UNSIGNED_INT,
       (int)sizeof(deFloat16),        // INPUTTYPE_HALF,
       (int)sizeof(deUint32) / 4,    // INPUTTYPE_UNSIGNED_INT_2_10_10_10,
       (int)sizeof(deUint32) / 4    // INPUTTYPE_INT_2_10_10_10,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INPUTTYPE_LAST>(size, (int)type);
}
 
int DrawTestSpec::indexTypeSize (IndexType type)
{
   static const int size[] =
   {
       sizeof(deUint8),    // INDEXTYPE_BYTE,
       sizeof(deUint16),    // INDEXTYPE_SHORT,
       sizeof(deUint32),    // INDEXTYPE_INT,
   };
 
   return de::getSizedArrayElement<DrawTestSpec::INDEXTYPE_LAST>(size, (int)type);
}
 
std::string DrawTestSpec::getName (void) const
{
   const MethodInfo    methodInfo    = getMethodInfo(drawMethod);
   const bool            hasFirst    = methodInfo.first;
   const bool            instanced    = methodInfo.instanced;
   const bool            ranged        = methodInfo.ranged;
   const bool            indexed        = methodInfo.indexed;
 
   std::stringstream name;
 
   for (size_t ndx = 0; ndx < attribs.size(); ++ndx)
   {
       const AttributeSpec& attrib = attribs[ndx];
 
       if (attribs.size() > 1)
           name << "attrib" << ndx << "_";
 
       if (ndx == 0|| attrib.additionalPositionAttribute)
           name << "pos_";
       else
           name << "col_";
 
       if (attrib.useDefaultAttribute)
       {
           name
               << "non_array_"
               << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType) << "_"
               << attrib.componentCount << "_"
               << DrawTestSpec::outputTypeToString(attrib.outputType) << "_";
       }
       else
       {
           name
               << DrawTestSpec::storageToString(attrib.storage) << "_"
               << attrib.offset << "_"
               << attrib.stride << "_"
               << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType);
           if (attrib.inputType != DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10 && attrib.inputType != DrawTestSpec::INPUTTYPE_INT_2_10_10_10)
               name << attrib.componentCount;
           name
               << "_"
               << (attrib.normalize ? "normalized_" : "")
               << DrawTestSpec::outputTypeToString(attrib.outputType) << "_"
               << DrawTestSpec::usageTypeToString(attrib.usage) << "_"
               << attrib.instanceDivisor << "_";
       }
   }
 
   if (indexed)
       name
           << "index_" << DrawTestSpec::indexTypeToString(indexType) << "_"
           << DrawTestSpec::storageToString(indexStorage) << "_"
           << "offset" << indexPointerOffset << "_";
   if (hasFirst)
       name << "first" << first << "_";
   if (ranged)
       name << "ranged_" << indexMin << "_" << indexMax << "_";
   if (instanced)
       name << "instances" << instanceCount << "_";
 
   switch (primitive)
   {
       case DrawTestSpec::PRIMITIVE_POINTS:
           name << "points_";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES:
           name << "triangles_";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_FAN:
           name << "triangle_fan_";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP:
           name << "triangle_strip_";
           break;
       case DrawTestSpec::PRIMITIVE_LINES:
           name << "lines_";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP:
           name << "line_strip_";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_LOOP:
           name << "line_loop_";
           break;
       case DrawTestSpec::PRIMITIVE_LINES_ADJACENCY:
           name << "line_adjancency";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP_ADJACENCY:
           name << "line_strip_adjancency";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES_ADJACENCY:
           name << "triangles_adjancency";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP_ADJACENCY:
           name << "triangle_strip_adjancency";
           break;
       default:
           DE_ASSERT(false);
           break;
   }
 
   name << primitiveCount;
 
   return name.str();
}
 
std::string DrawTestSpec::getDesc (void) const
{
   std::stringstream desc;
 
   for (size_t ndx = 0; ndx < attribs.size(); ++ndx)
   {
       const AttributeSpec& attrib = attribs[ndx];
 
       if (attrib.useDefaultAttribute)
       {
           desc
               << "Attribute " << ndx << ": default, " << ((ndx == 0|| attrib.additionalPositionAttribute) ? ("position ,") : ("color ,"))
               << "input datatype " << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType) << ", "
               << "input component count " << attrib.componentCount << ", "
               << "used as " << DrawTestSpec::outputTypeToString(attrib.outputType) << ", ";
       }
       else
       {
           desc
               << "Attribute " << ndx << ": " << ((ndx == 0|| attrib.additionalPositionAttribute) ? ("position ,") : ("color ,"))
               << "Storage in " << DrawTestSpec::storageToString(attrib.storage) << ", "
               << "stride " << attrib.stride << ", "
               << "input datatype " << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType) << ", "
               << "input component count " << attrib.componentCount << ", "
               << (attrib.normalize ? "normalized, " : "")
               << "used as " << DrawTestSpec::outputTypeToString(attrib.outputType) << ", "
               << "instance divisor " << attrib.instanceDivisor << ", ";
       }
   }
 
   if (drawMethod == DRAWMETHOD_DRAWARRAYS)
   {
       desc
           << "drawArrays(), "
           << "first " << first << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWARRAYS_INSTANCED)
   {
       desc
           << "drawArraysInstanced(), "
           << "first " << first << ", "
           << "instance count " << instanceCount << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS)
   {
       desc
           << "drawElements(), "
           << "index type " << DrawTestSpec::indexTypeToString(indexType) << ", "
           << "index storage in " << DrawTestSpec::storageToString(indexStorage) << ", "
           << "index offset " << indexPointerOffset << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_RANGED)
   {
       desc
           << "drawElementsRanged(), "
           << "index type " << DrawTestSpec::indexTypeToString(indexType) << ", "
           << "index storage in " << DrawTestSpec::storageToString(indexStorage) << ", "
           << "index offset " << indexPointerOffset << ", "
           << "range start " << indexMin << ", "
           << "range end " << indexMax << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INSTANCED)
   {
       desc
           << "drawElementsInstanced(), "
           << "index type " << DrawTestSpec::indexTypeToString(indexType) << ", "
           << "index storage in " << DrawTestSpec::storageToString(indexStorage) << ", "
           << "index offset " << indexPointerOffset << ", "
           << "instance count " << instanceCount << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWARRAYS_INDIRECT)
   {
       desc
           << "drawArraysIndirect(), "
           << "first " << first << ", "
           << "instance count " << instanceCount << ", "
           << "indirect offset " << indirectOffset << ", ";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INDIRECT)
   {
       desc
           << "drawElementsIndirect(), "
           << "index type " << DrawTestSpec::indexTypeToString(indexType) << ", "
           << "index storage in " << DrawTestSpec::storageToString(indexStorage) << ", "
           << "index offset " << indexPointerOffset << ", "
           << "instance count " << instanceCount << ", "
           << "indirect offset " << indirectOffset << ", "
           << "base vertex " << baseVertex << ", ";
   }
   else
       DE_ASSERT(DE_FALSE);
 
   desc << primitiveCount;
 
   switch (primitive)
   {
       case DrawTestSpec::PRIMITIVE_POINTS:
           desc << "points";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES:
           desc << "triangles";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_FAN:
           desc << "triangles (fan)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP:
           desc << "triangles (strip)";
           break;
       case DrawTestSpec::PRIMITIVE_LINES:
           desc << "lines";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP:
           desc << "lines (strip)";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_LOOP:
           desc << "lines (loop)";
           break;
       case DrawTestSpec::PRIMITIVE_LINES_ADJACENCY:
           desc << "lines (adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP_ADJACENCY:
           desc << "lines (strip, adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES_ADJACENCY:
           desc << "triangles (adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP_ADJACENCY:
           desc << "triangles (strip, adjancency)";
           break;
       default:
           DE_ASSERT(false);
           break;
   }
 
   return desc.str();
}
 
std::string DrawTestSpec::getMultilineDesc (void) const
{
   std::stringstream desc;
 
   for (size_t ndx = 0; ndx < attribs.size(); ++ndx)
   {
       const AttributeSpec& attrib = attribs[ndx];
 
       if (attrib.useDefaultAttribute)
       {
           desc
               << "Attribute " << ndx << ": default, " << ((ndx == 0|| attrib.additionalPositionAttribute) ? ("position\n") : ("color\n"))
               << "\tinput datatype " << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType) << "\n"
               << "\tinput component count " << attrib.componentCount << "\n"
               << "\tused as " << DrawTestSpec::outputTypeToString(attrib.outputType) << "\n";
       }
       else
       {
           desc
               << "Attribute " << ndx << ": " << ((ndx == 0|| attrib.additionalPositionAttribute) ? ("position\n") : ("color\n"))
               << "\tStorage in " << DrawTestSpec::storageToString(attrib.storage) << "\n"
               << "\tstride " << attrib.stride << "\n"
               << "\tinput datatype " << DrawTestSpec::inputTypeToString((DrawTestSpec::InputType)attrib.inputType) << "\n"
               << "\tinput component count " << attrib.componentCount << "\n"
               << (attrib.normalize ? "\tnormalized\n" : "")
               << "\tused as " << DrawTestSpec::outputTypeToString(attrib.outputType) << "\n"
               << "\tinstance divisor " << attrib.instanceDivisor << "\n";
       }
   }
 
   if (drawMethod == DRAWMETHOD_DRAWARRAYS)
   {
       desc
           << "drawArrays()\n"
           << "\tfirst " << first << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWARRAYS_INSTANCED)
   {
       desc
           << "drawArraysInstanced()\n"
           << "\tfirst " << first << "\n"
           << "\tinstance count " << instanceCount << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS)
   {
       desc
           << "drawElements()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_RANGED)
   {
       desc
           << "drawElementsRanged()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\trange start " << indexMin << "\n"
           << "\trange end " << indexMax << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INSTANCED)
   {
       desc
           << "drawElementsInstanced()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\tinstance count " << instanceCount << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWARRAYS_INDIRECT)
   {
       desc
           << "drawArraysIndirect()\n"
           << "\tfirst " << first << "\n"
           << "\tinstance count " << instanceCount << "\n"
           << "\tindirect offset " << indirectOffset << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INDIRECT)
   {
       desc
           << "drawElementsIndirect()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\tinstance count " << instanceCount << "\n"
           << "\tindirect offset " << indirectOffset << "\n"
           << "\tbase vertex " << baseVertex << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_BASEVERTEX)
   {
       desc
           << "drawElementsBaseVertex()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\tbase vertex " << baseVertex << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INSTANCED_BASEVERTEX)
   {
       desc
           << "drawElementsInstancedBaseVertex()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\tinstance count " << instanceCount << "\n"
           << "\tbase vertex " << baseVertex << "\n";
   }
   else if (drawMethod == DRAWMETHOD_DRAWELEMENTS_RANGED_BASEVERTEX)
   {
       desc
           << "drawRangeElementsBaseVertex()\n"
           << "\tindex type " << DrawTestSpec::indexTypeToString(indexType) << "\n"
           << "\tindex storage in " << DrawTestSpec::storageToString(indexStorage) << "\n"
           << "\tindex offset " << indexPointerOffset << "\n"
           << "\tbase vertex " << baseVertex << "\n"
           << "\trange start " << indexMin << "\n"
           << "\trange end " << indexMax << "\n";
   }
   else
       DE_ASSERT(DE_FALSE);
 
   desc << "\t" << primitiveCount << " ";
 
   switch (primitive)
   {
       case DrawTestSpec::PRIMITIVE_POINTS:
           desc << "points";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES:
           desc << "triangles";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_FAN:
           desc << "triangles (fan)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP:
           desc << "triangles (strip)";
           break;
       case DrawTestSpec::PRIMITIVE_LINES:
           desc << "lines";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP:
           desc << "lines (strip)";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_LOOP:
           desc << "lines (loop)";
           break;
       case DrawTestSpec::PRIMITIVE_LINES_ADJACENCY:
           desc << "lines (adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_LINE_STRIP_ADJACENCY:
           desc << "lines (strip, adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLES_ADJACENCY:
           desc << "triangles (adjancency)";
           break;
       case DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP_ADJACENCY:
           desc << "triangles (strip, adjancency)";
           break;
       default:
           DE_ASSERT(false);
           break;
   }
 
   desc << "\n";
 
   return desc.str();
}
 
DrawTestSpec::DrawTestSpec (void)
{
   primitive            = PRIMITIVE_LAST;
   primitiveCount        = 0;
   drawMethod            = DRAWMETHOD_LAST;
   indexType            = INDEXTYPE_LAST;
   indexPointerOffset    = 0;
   indexStorage        = STORAGE_LAST;
   first                = 0;
   indexMin            = 0;
   indexMax            = 0;
   instanceCount        = 0;
   indirectOffset        = 0;
   baseVertex            = 0;
}
 
int DrawTestSpec::hash (void) const
{
   // Use only drawmode-relevant values in "hashing" as the unrelevant values might not be set (causing non-deterministic behavior).
   const MethodInfo    methodInfo        = getMethodInfo(drawMethod);
   const bool            arrayed            = methodInfo.first;
   const bool            instanced        = methodInfo.instanced;
   const bool            ranged            = methodInfo.ranged;
   const bool            indexed            = methodInfo.indexed;
   const bool            indirect        = methodInfo.indirect;
   const bool            hasBaseVtx        = methodInfo.baseVertex;
 
   const int            indexHash        = (!indexed)    ? (0) : (int(indexType) + 10 * indexPointerOffset + 100 * int(indexStorage));
   const int            arrayHash        = (!arrayed)    ? (0) : (first);
   const int            indexRangeHash    = (!ranged)        ? (0) : (indexMin + 10 * indexMax);
   const int            instanceHash    = (!instanced)    ? (0) : (instanceCount);
   const int            indirectHash    = (!indirect)    ? (0) : (indirectOffset);
   const int            baseVtxHash        = (!hasBaseVtx)    ? (0) : (baseVertex);
   const int            basicHash        = int(primitive) + 10 * primitiveCount + 100 * int(drawMethod);
 
   return indexHash + 3 * arrayHash + 5 * indexRangeHash + 7 * instanceHash + 13 * basicHash + 17 * (int)attribs.size() + 19 * primitiveCount + 23 * indirectHash + 27 * baseVtxHash;
}
 
bool DrawTestSpec::valid (void) const
{
   DE_ASSERT(apiType.getProfile() != glu::PROFILE_LAST);
   DE_ASSERT(primitive != PRIMITIVE_LAST);
   DE_ASSERT(drawMethod != DRAWMETHOD_LAST);
 
   const MethodInfo methodInfo = getMethodInfo(drawMethod);
 
   for (int ndx = 0; ndx < (int)attribs.size(); ++ndx)
       if (!attribs[ndx].valid(apiType))
           return false;
 
   if (methodInfo.ranged)
   {
       deUint32 maxIndexValue = 0;
       if (indexType == INDEXTYPE_BYTE)
           maxIndexValue = GLValue::getMaxValue(INPUTTYPE_UNSIGNED_BYTE).ub.getValue();
       else if (indexType == INDEXTYPE_SHORT)
           maxIndexValue = GLValue::getMaxValue(INPUTTYPE_UNSIGNED_SHORT).us.getValue();
       else if (indexType == INDEXTYPE_INT)
           maxIndexValue = GLValue::getMaxValue(INPUTTYPE_UNSIGNED_INT).ui.getValue();
       else
           DE_ASSERT(DE_FALSE);
 
       if (indexMin > indexMax)
           return false;
       if (indexMin < 0 || indexMax < 0)
           return false;
       if ((deUint32)indexMin > maxIndexValue || (deUint32)indexMax > maxIndexValue)
           return false;
   }
 
   if (methodInfo.first && first < 0)
       return false;
 
   // GLES2 limits
   if (apiType == glu::ApiType::es(2,0))
   {
       if (drawMethod != gls::DrawTestSpec::DRAWMETHOD_DRAWARRAYS && drawMethod != gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS)
           return false;
       if (drawMethod == gls::DrawTestSpec::DRAWMETHOD_DRAWELEMENTS && (indexType != INDEXTYPE_BYTE && indexType != INDEXTYPE_SHORT))
           return false;
   }
 
   // Indirect limitations
   if (methodInfo.indirect)
   {
       // Indirect offset alignment
       if (indirectOffset % 4 != 0)
           return false;
 
       // All attribute arrays must be stored in a buffer
       for (int ndx = 0; ndx < (int)attribs.size(); ++ndx)
           if (!attribs[ndx].useDefaultAttribute && attribs[ndx].storage == gls::DrawTestSpec::STORAGE_USER)
               return false;
   }
   if (drawMethod == DRAWMETHOD_DRAWELEMENTS_INDIRECT)
   {
       // index offset must be convertable to firstIndex
       if (indexPointerOffset % gls::DrawTestSpec::indexTypeSize(indexType) != 0)
           return false;
 
       // Indices must be in a buffer
       if (indexStorage != STORAGE_BUFFER)
           return false;
   }
 
   // Do not allow user pointer in GL core
   if (apiType.getProfile() == glu::PROFILE_CORE)
   {
       if (methodInfo.indexed && indexStorage == DrawTestSpec::STORAGE_USER)
           return false;
   }
 
   return true;
}
 
DrawTestSpec::CompatibilityTestType DrawTestSpec::isCompatibilityTest (void) const
{
   const MethodInfo methodInfo = getMethodInfo(drawMethod);
 
   bool bufferAlignmentBad = false;
   bool strideAlignmentBad = false;
 
   // Attribute buffer alignment
   for (int ndx = 0; ndx < (int)attribs.size(); ++ndx)
       if (!attribs[ndx].isBufferAligned())
           bufferAlignmentBad = true;
 
   // Attribute stride alignment
   for (int ndx = 0; ndx < (int)attribs.size(); ++ndx)
       if (!attribs[ndx].isBufferStrideAligned())
           strideAlignmentBad = true;
 
   // Index buffer alignment
   if (methodInfo.indexed)
   {
       if (indexStorage == STORAGE_BUFFER)
       {
           int indexSize = 0;
           if (indexType == INDEXTYPE_BYTE)
               indexSize = 1;
           else if (indexType == INDEXTYPE_SHORT)
               indexSize = 2;
           else if (indexType == INDEXTYPE_INT)
               indexSize = 4;
           else
               DE_ASSERT(DE_FALSE);
 
           if (indexPointerOffset % indexSize != 0)
               bufferAlignmentBad = true;
       }
   }
 
   // \note combination bad alignment & stride is treated as bad offset
   if (bufferAlignmentBad)
       return COMPATIBILITY_UNALIGNED_OFFSET;
   else if (strideAlignmentBad)
       return COMPATIBILITY_UNALIGNED_STRIDE;
   else
       return COMPATIBILITY_NONE;
}
 
enum PrimitiveClass
{
   PRIMITIVECLASS_POINT = 0,
   PRIMITIVECLASS_LINE,
   PRIMITIVECLASS_TRIANGLE,
 
   PRIMITIVECLASS_LAST
};
 
static PrimitiveClass getDrawPrimitiveClass (gls::DrawTestSpec::Primitive primitiveType)
{
   switch (primitiveType)
   {
       case gls::DrawTestSpec::PRIMITIVE_POINTS:
           return PRIMITIVECLASS_POINT;
 
       case gls::DrawTestSpec::PRIMITIVE_LINES:
       case gls::DrawTestSpec::PRIMITIVE_LINE_STRIP:
       case gls::DrawTestSpec::PRIMITIVE_LINE_LOOP:
       case gls::DrawTestSpec::PRIMITIVE_LINES_ADJACENCY:
       case gls::DrawTestSpec::PRIMITIVE_LINE_STRIP_ADJACENCY:
           return PRIMITIVECLASS_LINE;
 
       case gls::DrawTestSpec::PRIMITIVE_TRIANGLES:
       case gls::DrawTestSpec::PRIMITIVE_TRIANGLE_FAN:
       case gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP:
       case gls::DrawTestSpec::PRIMITIVE_TRIANGLES_ADJACENCY:
       case gls::DrawTestSpec::PRIMITIVE_TRIANGLE_STRIP_ADJACENCY:
           return PRIMITIVECLASS_TRIANGLE;
 
       default:
           DE_ASSERT(false);
           return PRIMITIVECLASS_LAST;
   }
}
 
static bool containsLineCases (const std::vector<DrawTestSpec>& m_specs)
{
   for (int ndx = 0; ndx < (int)m_specs.size(); ++ndx)
   {
       if (getDrawPrimitiveClass(m_specs[ndx].primitive) == PRIMITIVECLASS_LINE)
           return true;
   }
   return false;
}
 
// DrawTest
 
DrawTest::DrawTest (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const DrawTestSpec& spec, const char* name, const char* desc)
   : TestCase            (testCtx, name, desc)
   , m_renderCtx        (renderCtx)
   , m_contextInfo        (DE_NULL)
   , m_refBuffers        (DE_NULL)
   , m_refContext        (DE_NULL)
   , m_glesContext        (DE_NULL)
   , m_glArrayPack        (DE_NULL)
   , m_rrArrayPack        (DE_NULL)
   , m_maxDiffRed        (-1)
   , m_maxDiffGreen    (-1)
   , m_maxDiffBlue        (-1)
   , m_iteration        (0)
   , m_result            ()    // \note no per-iteration result logging (only one iteration)
{
   addIteration(spec);
}
 
DrawTest::DrawTest (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* desc)
   : TestCase            (testCtx, name, desc)
   , m_renderCtx        (renderCtx)
   , m_contextInfo        (DE_NULL)
   , m_refBuffers        (DE_NULL)
   , m_refContext        (DE_NULL)
   , m_glesContext        (DE_NULL)
   , m_glArrayPack        (DE_NULL)
   , m_rrArrayPack        (DE_NULL)
   , m_maxDiffRed        (-1)
   , m_maxDiffGreen    (-1)
   , m_maxDiffBlue        (-1)
   , m_iteration        (0)
   , m_result            (testCtx.getLog(), "Iteration result: ")
{
}
 
DrawTest::~DrawTest    (void)
{
   deinit();
}
 
void DrawTest::addIteration (const DrawTestSpec& spec, const char* description)
{
   // Validate spec
   const bool validSpec = spec.valid();
   DE_ASSERT(validSpec);
 
   if (!validSpec)
       return;
 
   // Check the context type is the same with other iterations
   if (!m_specs.empty())
   {
       const bool validContext = m_specs[0].apiType == spec.apiType;
       DE_ASSERT(validContext);
 
       if (!validContext)
           return;
   }
 
   m_specs.push_back(spec);
 
   if (description)
       m_iteration_descriptions.push_back(std::string(description));
   else
       m_iteration_descriptions.push_back(std::string());
}
 
void DrawTest::init (void)
{
   DE_ASSERT(!m_specs.empty());
   DE_ASSERT(contextSupports(m_renderCtx.getType(), m_specs[0].apiType));
 
   const int                        renderTargetWidth    = de::min(MAX_RENDER_TARGET_SIZE, m_renderCtx.getRenderTarget().getWidth());
   const int                        renderTargetHeight    = de::min(MAX_RENDER_TARGET_SIZE, m_renderCtx.getRenderTarget().getHeight());
 
   // lines have significantly different rasterization in MSAA mode
   const bool                        isLineCase            = containsLineCases(m_specs);
   const bool                        isMSAACase            = m_renderCtx.getRenderTarget().getNumSamples() > 1;
   const int                        renderTargetSamples    = (isMSAACase && isLineCase) ? (4) : (1);
 
   sglr::ReferenceContextLimits    limits                (m_renderCtx);
   bool                            useVao                = false;
 
   m_glesContext = new sglr::GLContext(m_renderCtx, m_testCtx.getLog(), sglr::GLCONTEXT_LOG_CALLS | sglr::GLCONTEXT_LOG_PROGRAMS, tcu::IVec4(0, 0, renderTargetWidth, renderTargetHeight));
 
   if (m_renderCtx.getType().getAPI() == glu::ApiType::es(2,0) || m_renderCtx.getType().getAPI() == glu::ApiType::es(3,0))
       useVao = false;
   else if (contextSupports(m_renderCtx.getType(), glu::ApiType::es(3,1)) || glu::isContextTypeGLCore(m_renderCtx.getType()))
       useVao = true;
   else
       DE_FATAL("Unknown context type");
 
   m_refBuffers    = new sglr::ReferenceContextBuffers(m_renderCtx.getRenderTarget().getPixelFormat(), 0, 0, renderTargetWidth, renderTargetHeight, renderTargetSamples);
   m_refContext    = new sglr::ReferenceContext(limits, m_refBuffers->getColorbuffer(), m_refBuffers->getDepthbuffer(), m_refBuffers->getStencilbuffer());
 
   m_glArrayPack    = new AttributePack(m_testCtx, m_renderCtx, *m_glesContext, tcu::UVec2(renderTargetWidth, renderTargetHeight), useVao, true);
   m_rrArrayPack    = new AttributePack(m_testCtx, m_renderCtx, *m_refContext,  tcu::UVec2(renderTargetWidth, renderTargetHeight), useVao, false);
 
   m_maxDiffRed    = deCeilFloatToInt32(256.0f * (6.0f / (float)(1 << m_renderCtx.getRenderTarget().getPixelFormat().redBits)));
   m_maxDiffGreen    = deCeilFloatToInt32(256.0f * (6.0f / (float)(1 << m_renderCtx.getRenderTarget().getPixelFormat().greenBits)));
   m_maxDiffBlue    = deCeilFloatToInt32(256.0f * (6.0f / (float)(1 << m_renderCtx.getRenderTarget().getPixelFormat().blueBits)));
   m_contextInfo    = glu::ContextInfo::create(m_renderCtx);
}
 
void DrawTest::deinit (void)
{
   delete m_glArrayPack;
   delete m_rrArrayPack;
   delete m_refBuffers;
   delete m_refContext;
   delete m_glesContext;
   delete m_contextInfo;
 
   m_glArrayPack    = DE_NULL;
   m_rrArrayPack    = DE_NULL;
   m_refBuffers    = DE_NULL;
   m_refContext    = DE_NULL;
   m_glesContext    = DE_NULL;
   m_contextInfo    = DE_NULL;
}
 
DrawTest::IterateResult DrawTest::iterate (void)
{
   const int                    specNdx            = (m_iteration / 2);
   const DrawTestSpec&            spec            = m_specs[specNdx];
 
   if (spec.drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_BASEVERTEX ||
       spec.drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_INSTANCED_BASEVERTEX ||
       spec.drawMethod == DrawTestSpec::DRAWMETHOD_DRAWELEMENTS_RANGED_BASEVERTEX)
   {
       const bool supportsES32 = contextSupports(m_renderCtx.getType(), glu::ApiType::es(3, 2));
       TCU_CHECK_AND_THROW(NotSupportedError, supportsES32 || m_contextInfo->isExtensionSupported("GL_EXT_draw_elements_base_vertex"), "GL_EXT_draw_elements_base_vertex is not supported.");
   }
 
   const bool                    drawStep        = (m_iteration % 2) == 0;
   const bool                    compareStep        = (m_iteration % 2) == 1;
   const IterateResult            iterateResult    = ((size_t)m_iteration + 1 == m_specs.size()*2) ? (STOP) : (CONTINUE);
   const bool                    updateProgram    = (m_iteration == 0) || (drawStep && !checkSpecsShaderCompatible(m_specs[specNdx], m_specs[specNdx-1])); // try to use the same shader in all iterations
   IterationLogSectionEmitter    sectionEmitter    (m_testCtx.getLog(), specNdx, m_specs.size(), m_iteration_descriptions[specNdx], drawStep && m_specs.size()!=1);
 
   if (drawStep)
   {
       const MethodInfo    methodInfo                = getMethodInfo(spec.drawMethod);
       const bool            indexed                    = methodInfo.indexed;
       const bool            instanced                = methodInfo.instanced;
       const bool            ranged                    = methodInfo.ranged;
       const bool            hasFirst                = methodInfo.first;
       const bool            hasBaseVtx                = methodInfo.baseVertex;
 
       const size_t        primitiveElementCount    = getElementCount(spec.primitive, spec.primitiveCount);                        // !< elements to be drawn
       const int            indexMin                = (ranged) ? (spec.indexMin) : (0);
       const int            firstAddition            = (hasFirst) ? (spec.first) : (0);
       const int            baseVertexAddition        = (hasBaseVtx && spec.baseVertex > 0) ? ( spec.baseVertex) : (0);            // spec.baseVertex > 0 => Create bigger attribute buffer
       const int            indexBase                = (hasBaseVtx && spec.baseVertex < 0) ? (-spec.baseVertex) : (0);            // spec.baseVertex < 0 => Create bigger indices
       const size_t        elementCount            = primitiveElementCount + indexMin + firstAddition + baseVertexAddition;    // !< elements in buffer (buffer should have at least primitiveElementCount ACCESSIBLE (index range, first) elements)
       const int            maxElementIndex            = (int)primitiveElementCount + indexMin + firstAddition - 1;
       const int            indexMax                = de::max(0, (ranged) ? (de::clamp<int>(spec.indexMax, 0, maxElementIndex)) : (maxElementIndex));
       float                coordScale                = getCoordScale(spec);
       float                colorScale                = getColorScale(spec);
 
       rr::GenericVec4        nullAttribValue;
 
       // Log info
       m_testCtx.getLog() << TestLog::Message << spec.getMultilineDesc() << TestLog::EndMessage;
       m_testCtx.getLog() << TestLog::Message << TestLog::EndMessage; // extra line for clarity
 
       // Data
 
       m_glArrayPack->clearArrays();
       m_rrArrayPack->clearArrays();
 
       for (int attribNdx = 0; attribNdx < (int)spec.attribs.size(); attribNdx++)
       {
           DrawTestSpec::AttributeSpec attribSpec        = spec.attribs[attribNdx];
           const bool                    isPositionAttr    = (attribNdx == 0) || (attribSpec.additionalPositionAttribute);
 
           if (attribSpec.useDefaultAttribute)
           {
               const int        seed        = 10 * attribSpec.hash() + 100 * spec.hash() + attribNdx;
               rr::GenericVec4 attribValue = RandomArrayGenerator::generateAttributeValue(seed, attribSpec.inputType);
 
               m_glArrayPack->newArray(DrawTestSpec::STORAGE_USER);
               m_rrArrayPack->newArray(DrawTestSpec::STORAGE_USER);
 
               m_glArrayPack->getArray(attribNdx)->setupArray(false, 0, attribSpec.componentCount, attribSpec.inputType, attribSpec.outputType, false, 0, 0, attribValue, isPositionAttr, false);
               m_rrArrayPack->getArray(attribNdx)->setupArray(false, 0, attribSpec.componentCount, attribSpec.inputType, attribSpec.outputType, false, 0, 0, attribValue, isPositionAttr, false);
           }
           else
           {
               const int                    seed                    = attribSpec.hash() + 100 * spec.hash() + attribNdx;
               const size_t                elementSize                = attribSpec.componentCount * DrawTestSpec::inputTypeSize(attribSpec.inputType);
               const size_t                stride                    = (attribSpec.stride == 0) ? (elementSize) : (attribSpec.stride);
               const size_t                evaluatedElementCount    = (instanced && attribSpec.instanceDivisor > 0) ? (spec.instanceCount / attribSpec.instanceDivisor + 1) : (elementCount);
               const size_t                referencedElementCount    = (ranged) ? (de::max<size_t>(evaluatedElementCount, spec.indexMax + 1)) : (evaluatedElementCount);
               const size_t                bufferSize                = attribSpec.offset + stride * (referencedElementCount - 1) + elementSize;
               const char*                    data                    = RandomArrayGenerator::generateArray(seed, (int)referencedElementCount, attribSpec.componentCount, attribSpec.offset, (int)stride, attribSpec.inputType);
 
               try
               {
                   m_glArrayPack->newArray(attribSpec.storage);
                   m_rrArrayPack->newArray(attribSpec.storage);
 
                   m_glArrayPack->getArray(attribNdx)->data(DrawTestSpec::TARGET_ARRAY, bufferSize, data, attribSpec.usage);
                   m_rrArrayPack->getArray(attribNdx)->data(DrawTestSpec::TARGET_ARRAY, bufferSize, data, attribSpec.usage);
 
                   m_glArrayPack->getArray(attribNdx)->setupArray(true, attribSpec.offset, attribSpec.componentCount, attribSpec.inputType, attribSpec.outputType, attribSpec.normalize, attribSpec.stride, attribSpec.instanceDivisor, nullAttribValue, isPositionAttr, attribSpec.bgraComponentOrder);
                   m_rrArrayPack->getArray(attribNdx)->setupArray(true, attribSpec.offset, attribSpec.componentCount, attribSpec.inputType, attribSpec.outputType, attribSpec.normalize, attribSpec.stride, attribSpec.instanceDivisor, nullAttribValue, isPositionAttr, attribSpec.bgraComponentOrder);
 
                   delete [] data;
                   data = NULL;
               }
               catch (...)
               {
                   delete [] data;
                   throw;
               }
           }
       }
 
       // Shader program
       if (updateProgram)
       {
           m_glArrayPack->updateProgram();
           m_rrArrayPack->updateProgram();
       }
 
       // Draw
       try
       {
           // indices
           if (indexed)
           {
               const int        seed                = spec.hash();
               const size_t    indexElementSize    = DrawTestSpec::indexTypeSize(spec.indexType);
               const size_t    indexArraySize        = spec.indexPointerOffset + indexElementSize * elementCount;
               const char*        indexArray            = RandomArrayGenerator::generateIndices(seed, (int)elementCount, spec.indexType, spec.indexPointerOffset, indexMin, indexMax, indexBase);
               const char*        indexPointerBase    = (spec.indexStorage == DrawTestSpec::STORAGE_USER) ? (indexArray) : ((char*)DE_NULL);
               const char*        indexPointer        = indexPointerBase + spec.indexPointerOffset;
 
               de::UniquePtr<AttributeArray> glArray    (new AttributeArray(spec.indexStorage, *m_glesContext));
               de::UniquePtr<AttributeArray> rrArray    (new AttributeArray(spec.indexStorage, *m_refContext));
 
               try
               {
                   glArray->data(DrawTestSpec::TARGET_ELEMENT_ARRAY, indexArraySize, indexArray, DrawTestSpec::USAGE_STATIC_DRAW);
                   rrArray->data(DrawTestSpec::TARGET_ELEMENT_ARRAY, indexArraySize, indexArray, DrawTestSpec::USAGE_STATIC_DRAW);
 
                   m_glArrayPack->render(spec.primitive, spec.drawMethod, 0, (int)primitiveElementCount, spec.indexType, indexPointer, spec.indexMin, spec.indexMax, spec.instanceCount, spec.indirectOffset, spec.baseVertex, coordScale, colorScale, glArray.get());
                   m_rrArrayPack->render(spec.primitive, spec.drawMethod, 0, (int)primitiveElementCount, spec.indexType, indexPointer, spec.indexMin, spec.indexMax, spec.instanceCount, spec.indirectOffset, spec.baseVertex, coordScale, colorScale, rrArray.get());
 
                   delete [] indexArray;
                   indexArray = NULL;
               }
               catch (...)
               {
                   delete [] indexArray;
                   throw;
               }
           }
           else
           {
               m_glArrayPack->render(spec.primitive, spec.drawMethod, spec.first, (int)primitiveElementCount, DrawTestSpec::INDEXTYPE_LAST, DE_NULL, 0, 0, spec.instanceCount, spec.indirectOffset, 0, coordScale, colorScale, DE_NULL);
               m_testCtx.touchWatchdog();
               m_rrArrayPack->render(spec.primitive, spec.drawMethod, spec.first, (int)primitiveElementCount, DrawTestSpec::INDEXTYPE_LAST, DE_NULL, 0, 0, spec.instanceCount, spec.indirectOffset, 0, coordScale, colorScale, DE_NULL);
           }
       }
       catch (glu::Error& err)
       {
           // GL Errors are ok if the mode is not properly aligned
 
           const DrawTestSpec::CompatibilityTestType ctype = spec.isCompatibilityTest();
 
           m_testCtx.getLog() << TestLog::Message << "Got error: " << err.what() << TestLog::EndMessage;
 
           if (ctype == DrawTestSpec::COMPATIBILITY_UNALIGNED_OFFSET)
               m_result.addResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, "Failed to draw with unaligned buffers.");
           else if (ctype == DrawTestSpec::COMPATIBILITY_UNALIGNED_STRIDE)
               m_result.addResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, "Failed to draw with unaligned stride.");
           else
               throw;
       }
   }
   else if (compareStep)
   {
       if (!compare(spec.primitive))
       {
           const DrawTestSpec::CompatibilityTestType ctype = spec.isCompatibilityTest();
 
           if (ctype == DrawTestSpec::COMPATIBILITY_UNALIGNED_OFFSET)
               m_result.addResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, "Failed to draw with unaligned buffers.");
           else if (ctype == DrawTestSpec::COMPATIBILITY_UNALIGNED_STRIDE)
               m_result.addResult(QP_TEST_RESULT_COMPATIBILITY_WARNING, "Failed to draw with unaligned stride.");
           else
               m_result.addResult(QP_TEST_RESULT_FAIL, "Image comparison failed.");
       }
   }
   else
   {
       DE_ASSERT(false);
       return STOP;
   }
 
   m_result.setTestContextResult(m_testCtx);
 
   m_iteration++;
   return iterateResult;
}
 
static bool isBlack (const tcu::RGBA& c)
{
   // ignore alpha channel
   return c.getRed() == 0 && c.getGreen() == 0 && c.getBlue() == 0;
}
 
static bool isEdgeTripletComponent (int c1, int c2, int c3, int renderTargetDifference)
{
   const int    roundingDifference    = 2 * renderTargetDifference; // src and dst pixels rounded to different directions
   const int    d1                    = c2 - c1;
   const int    d2                    = c3 - c2;
   const int    rampDiff            = de::abs(d2 - d1);
 
   return rampDiff > roundingDifference;
}
 
static bool isEdgeTriplet (const tcu::RGBA& c1, const tcu::RGBA& c2, const tcu::RGBA& c3, const tcu::IVec3& renderTargetThreshold)
{
   // black (background color) and non-black is always an edge
   {
       const bool b1 = isBlack(c1);
       const bool b2 = isBlack(c2);
       const bool b3 = isBlack(c3);
 
       // both pixels with coverage and pixels without coverage
       if ((b1 && b2 && b3) == false && (b1 || b2 || b3) == true)
           return true;
       // all black
       if (b1 && b2 && b3)
           return false;
       // all with coverage
       DE_ASSERT(!b1 && !b2 && !b3);
   }
 
   // Color is always linearly interpolated => component values change nearly linearly
   // in any constant direction on triangle hull. (df/dx ~= C).
 
   // Edge detection (this function) is run against the reference image
   // => no dithering to worry about
 
   return    isEdgeTripletComponent(c1.getRed(),        c2.getRed(),    c3.getRed(),    renderTargetThreshold.x())    ||
           isEdgeTripletComponent(c1.getGreen(),    c2.getGreen(),    c3.getGreen(),    renderTargetThreshold.y())    ||
           isEdgeTripletComponent(c1.getBlue(),    c2.getBlue(),    c3.getBlue(),    renderTargetThreshold.z());
}
 
static bool pixelNearEdge (int x, int y, const tcu::Surface& ref, const tcu::IVec3& renderTargetThreshold)
{
   // should not be called for edge pixels
   DE_ASSERT(x >= 1 && x <= ref.getWidth()-2);
   DE_ASSERT(y >= 1 && y <= ref.getHeight()-2);
 
   // horizontal
 
   for (int dy = -1; dy < 2; ++dy)
   {
       const tcu::RGBA c1 = ref.getPixel(x-1, y+dy);
       const tcu::RGBA c2 = ref.getPixel(x,   y+dy);
       const tcu::RGBA c3 = ref.getPixel(x+1, y+dy);
       if (isEdgeTriplet(c1, c2, c3, renderTargetThreshold))
           return true;
   }
 
   // vertical
 
   for (int dx = -1; dx < 2; ++dx)
   {
       const tcu::RGBA c1 = ref.getPixel(x+dx, y-1);
       const tcu::RGBA c2 = ref.getPixel(x+dx, y);
       const tcu::RGBA c3 = ref.getPixel(x+dx, y+1);
       if (isEdgeTriplet(c1, c2, c3, renderTargetThreshold))
           return true;
   }
 
   return false;
}
 
static deUint32 getVisualizationGrayscaleColor (const tcu::RGBA& c)
{
   // make triangle coverage and error pixels obvious by converting coverage to grayscale
   if (isBlack(c))
       return 0;
   else
       return 50u + (deUint32)(c.getRed() + c.getBlue() + c.getGreen()) / 8u;
}
 
static bool pixelNearLineIntersection (int x, int y, const tcu::Surface& target)
{
   // should not be called for edge pixels
   DE_ASSERT(x >= 1 && x <= target.getWidth()-2);
   DE_ASSERT(y >= 1 && y <= target.getHeight()-2);
 
   int coveredPixels = 0;
 
   for (int dy = -1; dy < 2; dy++)
   for (int dx = -1; dx < 2; dx++)
   {
       const bool targetCoverage = !isBlack(target.getPixel(x+dx, y+dy));
       if (targetCoverage)
       {
           ++coveredPixels;
 
           // A single thin line cannot have more than 3 covered pixels in a 3x3 area
           if (coveredPixels >= 4)
               return true;
       }
   }
 
   return false;
}
 
static inline bool colorsEqual (const tcu::RGBA& colorA, const tcu::RGBA& colorB, const tcu::IVec3& compareThreshold)
{
   enum
   {
       TCU_RGBA_RGB_MASK = tcu::RGBA::RED_MASK | tcu::RGBA::GREEN_MASK | tcu::RGBA::BLUE_MASK
   };
 
   return tcu::compareThresholdMasked(colorA, colorB, tcu::RGBA(compareThreshold.x(), compareThreshold.y(), compareThreshold.z(), 0), TCU_RGBA_RGB_MASK);
}
 
// search 3x3 are for matching color
static bool pixelNeighborhoodContainsColor (const tcu::Surface& target, int x, int y, const tcu::RGBA& color, const tcu::IVec3& compareThreshold)
{
   // should not be called for edge pixels
   DE_ASSERT(x >= 1 && x <= target.getWidth()-2);
   DE_ASSERT(y >= 1 && y <= target.getHeight()-2);
 
   for (int dy = -1; dy < 2; dy++)
   for (int dx = -1; dx < 2; dx++)
   {
       const tcu::RGBA    targetCmpPixel = target.getPixel(x+dx, y+dy);
       if (colorsEqual(color, targetCmpPixel, compareThreshold))
           return true;
   }
 
   return false;
}
 
// search 3x3 are for matching coverage (coverage == (color != background color))
static bool pixelNeighborhoodContainsCoverage (const tcu::Surface& target, int x, int y, bool coverage)
{
   // should not be called for edge pixels
   DE_ASSERT(x >= 1 && x <= target.getWidth()-2);
   DE_ASSERT(y >= 1 && y <= target.getHeight()-2);
 
   for (int dy = -1; dy < 2; dy++)
   for (int dx = -1; dx < 2; dx++)
   {
       const bool targetCmpCoverage = !isBlack(target.getPixel(x+dx, y+dy));
       if (targetCmpCoverage == coverage)
           return true;
   }
 
   return false;
}
 
static bool edgeRelaxedImageCompare (tcu::TestLog& log, const char* imageSetName, const char* imageSetDesc, const tcu::Surface& reference, const tcu::Surface& result, const tcu::IVec3& compareThreshold, const tcu::IVec3& renderTargetThreshold, int maxAllowedInvalidPixels)
{
   DE_ASSERT(result.getWidth() == reference.getWidth() && result.getHeight() == reference.getHeight());
 
   const tcu::IVec4                green                        (0, 255, 0, 255);
   const tcu::IVec4                red                            (255, 0, 0, 255);
   const int                        width                        = reference.getWidth();
   const int                        height                        = reference.getHeight();
   tcu::TextureLevel                errorMask                    (tcu::TextureFormat(tcu::TextureFormat::RGB, tcu::TextureFormat::UNORM_INT8), width, height);
   const tcu::PixelBufferAccess    errorAccess                    = errorMask.getAccess();
   int                                numFailingPixels            = 0;
 
   // clear errormask edges which would otherwise be transparent
 
   tcu::clear(tcu::getSubregion(errorAccess, 0,            0,            width,    1),            green);
   tcu::clear(tcu::getSubregion(errorAccess, 0,            height-1,    width,    1),            green);
   tcu::clear(tcu::getSubregion(errorAccess, 0,            0,            1,        height),    green);
   tcu::clear(tcu::getSubregion(errorAccess, width-1,        0,            1,        height),    green);
 
   // skip edge pixels since coverage on edge cannot be verified
 
   for (int y = 1; y < height - 1; ++y)
   for (int x = 1; x < width - 1; ++x)
   {
       const tcu::RGBA    refPixel            = reference.getPixel(x, y);
       const tcu::RGBA    screenPixel            = result.getPixel(x, y);
       const bool        directMatch            = colorsEqual(refPixel, screenPixel, compareThreshold);
       const bool        isOkReferencePixel    = directMatch || pixelNeighborhoodContainsColor(result, x, y, refPixel, compareThreshold);            // screen image has a matching pixel nearby (~= If something is drawn on reference, it must be drawn to screen too.)
       const bool        isOkScreenPixel        = directMatch || pixelNeighborhoodContainsColor(reference, x, y, screenPixel, compareThreshold);    // reference image has a matching pixel nearby (~= If something is drawn on screen, it must be drawn to reference too.)
 
       if (isOkScreenPixel && isOkReferencePixel)
       {
           // pixel valid, write greenish pixels to make the result image easier to read
           const deUint32 grayscaleValue = getVisualizationGrayscaleColor(screenPixel);
           errorAccess.setPixel(tcu::UVec4(grayscaleValue, 255, grayscaleValue, 255), x, y);
       }
       else if (!pixelNearEdge(x, y, reference, renderTargetThreshold))
       {
           // non-edge pixel values must be within threshold of the reference values
           errorAccess.setPixel(red, x, y);
           ++numFailingPixels;
       }
       else
       {
           // we are on/near an edge, verify only coverage (coverage == not background colored)
           const bool    referenceCoverage        = !isBlack(refPixel);
           const bool    screenCoverage            = !isBlack(screenPixel);
           const bool    isOkReferenceCoverage    = pixelNeighborhoodContainsCoverage(result, x, y, referenceCoverage);    // Check reference pixel against screen pixel
           const bool    isOkScreenCoverage        = pixelNeighborhoodContainsCoverage(reference, x, y, screenCoverage);    // Check screen pixels against reference pixel
 
           if (isOkScreenCoverage && isOkReferenceCoverage)
           {
               // pixel valid, write greenish pixels to make the result image easier to read
               const deUint32 grayscaleValue = getVisualizationGrayscaleColor(screenPixel);
               errorAccess.setPixel(tcu::UVec4(grayscaleValue, 255, grayscaleValue, 255), x, y);
           }
           else
           {
               // coverage does not match
               errorAccess.setPixel(red, x, y);
               ++numFailingPixels;
           }
       }
   }
 
   log    << TestLog::Message
       << "Comparing images:\n"
       << "\tallowed deviation in pixel positions = 1\n"
       << "\tnumber of allowed invalid pixels = " << maxAllowedInvalidPixels << "\n"
       << "\tnumber of invalid pixels = " << numFailingPixels
       << TestLog::EndMessage;
 
   if (numFailingPixels > maxAllowedInvalidPixels)
   {
       log << TestLog::Message
           << "Image comparison failed. Color threshold = (" << compareThreshold.x() << ", " << compareThreshold.y() << ", " << compareThreshold.z() << ")"
           << TestLog::EndMessage
           << TestLog::ImageSet(imageSetName, imageSetDesc)
           << TestLog::Image("Result",        "Result",        result)
           << TestLog::Image("Reference",    "Reference",    reference)
           << TestLog::Image("ErrorMask",    "Error mask",    errorMask)
           << TestLog::EndImageSet;
 
       return false;
   }
   else
   {
       log << TestLog::ImageSet(imageSetName, imageSetDesc)
           << TestLog::Image("Result", "Result", result)
           << TestLog::EndImageSet;
 
       return true;
   }
}
 
static bool intersectionRelaxedLineImageCompare (tcu::TestLog& log, const char* imageSetName, const char* imageSetDesc, const tcu::Surface& reference, const tcu::Surface& result, const tcu::IVec3& compareThreshold, int maxAllowedInvalidPixels)
{
   DE_ASSERT(result.getWidth() == reference.getWidth() && result.getHeight() == reference.getHeight());
 
   const tcu::IVec4                green                        (0, 255, 0, 255);
   const tcu::IVec4                red                            (255, 0, 0, 255);
   const int                        width                        = reference.getWidth();
   const int                        height                        = reference.getHeight();
   tcu::TextureLevel                errorMask                    (tcu::TextureFormat(tcu::TextureFormat::RGB, tcu::TextureFormat::UNORM_INT8), width, height);
   const tcu::PixelBufferAccess    errorAccess                    = errorMask.getAccess();
   int                                numFailingPixels            = 0;
 
   // clear errormask edges which would otherwise be transparent
 
   tcu::clear(tcu::getSubregion(errorAccess, 0,            0,            width,    1),            green);
   tcu::clear(tcu::getSubregion(errorAccess, 0,            height-1,    width,    1),            green);
   tcu::clear(tcu::getSubregion(errorAccess, 0,            0,            1,        height),    green);
   tcu::clear(tcu::getSubregion(errorAccess, width-1,        0,            1,        height),    green);
 
   // skip edge pixels since coverage on edge cannot be verified
 
   for (int y = 1; y < height - 1; ++y)
   for (int x = 1; x < width - 1; ++x)
   {
       const tcu::RGBA    refPixel            = reference.getPixel(x, y);
       const tcu::RGBA    screenPixel            = result.getPixel(x, y);
       const bool        directMatch            = colorsEqual(refPixel, screenPixel, compareThreshold);
       const bool        isOkScreenPixel        = directMatch || pixelNeighborhoodContainsColor(reference, x, y, screenPixel, compareThreshold);    // reference image has a matching pixel nearby (~= If something is drawn on screen, it must be drawn to reference too.)
       const bool        isOkReferencePixel    = directMatch || pixelNeighborhoodContainsColor(result, x, y, refPixel, compareThreshold);            // screen image has a matching pixel nearby (~= If something is drawn on reference, it must be drawn to screen too.)
 
       if (isOkScreenPixel && isOkReferencePixel)
       {
           // pixel valid, write greenish pixels to make the result image easier to read
           const deUint32 grayscaleValue = getVisualizationGrayscaleColor(screenPixel);
           errorAccess.setPixel(tcu::UVec4(grayscaleValue, 255, grayscaleValue, 255), x, y);
       }
       else if (!pixelNearLineIntersection(x, y, reference) &&
                !pixelNearLineIntersection(x, y, result))
       {
           // non-intersection pixel values must be within threshold of the reference values
           errorAccess.setPixel(red, x, y);
           ++numFailingPixels;
       }
       else
       {
           // pixel is near a line intersection
           // we are on/near an edge, verify only coverage (coverage == not background colored)
           const bool    referenceCoverage        = !isBlack(refPixel);
           const bool    screenCoverage            = !isBlack(screenPixel);
           const bool    isOkScreenCoverage        = pixelNeighborhoodContainsCoverage(reference, x, y, screenCoverage);    // Check screen pixels against reference pixel
           const bool    isOkReferenceCoverage    = pixelNeighborhoodContainsCoverage(result, x, y, referenceCoverage);    // Check reference pixel against screen pixel
 
           if (isOkScreenCoverage && isOkReferenceCoverage)
           {
               // pixel valid, write greenish pixels to make the result image easier to read
               const deUint32 grayscaleValue = getVisualizationGrayscaleColor(screenPixel);
               errorAccess.setPixel(tcu::UVec4(grayscaleValue, 255, grayscaleValue, 255), x, y);
           }
           else
           {
               // coverage does not match
               errorAccess.setPixel(red, x, y);
               ++numFailingPixels;
           }
       }
   }
 
   log    << TestLog::Message
       << "Comparing images:\n"
       << "\tallowed deviation in pixel positions = 1\n"
       << "\tnumber of allowed invalid pixels = " << maxAllowedInvalidPixels << "\n"
       << "\tnumber of invalid pixels = " << numFailingPixels
       << TestLog::EndMessage;
 
   if (numFailingPixels > maxAllowedInvalidPixels)
   {
       log << TestLog::Message
           << "Image comparison failed. Color threshold = (" << compareThreshold.x() << ", " << compareThreshold.y() << ", " << compareThreshold.z() << ")"
           << TestLog::EndMessage
           << TestLog::ImageSet(imageSetName, imageSetDesc)
           << TestLog::Image("Result",        "Result",        result)
           << TestLog::Image("Reference",    "Reference",    reference)
           << TestLog::Image("ErrorMask",    "Error mask",    errorMask)
           << TestLog::EndImageSet;
 
       return false;
   }
   else
   {
       log << TestLog::ImageSet(imageSetName, imageSetDesc)
           << TestLog::Image("Result", "Result", result)
           << TestLog::EndImageSet;
 
       return true;
   }
}
 
bool DrawTest::compare (gls::DrawTestSpec::Primitive primitiveType)
{
   const tcu::Surface&    ref        = m_rrArrayPack->getSurface();
   const tcu::Surface&    screen    = m_glArrayPack->getSurface();
 
   if (m_renderCtx.getRenderTarget().getNumSamples() > 1)
   {
       // \todo [mika] Improve compare when using multisampling
       m_testCtx.getLog() << tcu::TestLog::Message << "Warning: Comparision of result from multisample render targets are not as stricts as without multisampling. Might produce false positives!" << tcu::TestLog::EndMessage;
       return tcu::fuzzyCompare(m_testCtx.getLog(), "Compare Results", "Compare Results", ref.getAccess(), screen.getAccess(), 0.3f, tcu::COMPARE_LOG_RESULT);
   }
   else
   {
       const PrimitiveClass    primitiveClass                            = getDrawPrimitiveClass(primitiveType);
       const int                maxAllowedInvalidPixelsWithPoints        = 0;    //!< points are unlikely to have overlapping fragments
       const int                maxAllowedInvalidPixelsWithLines        = 5;    //!< line are allowed to have a few bad pixels
       const int                maxAllowedInvalidPixelsWithTriangles    = 10;
 
       switch (primitiveClass)
       {
           case PRIMITIVECLASS_POINT:
           {
               // Point are extremely unlikely to have overlapping regions, don't allow any no extra / missing pixels
               return tcu::intThresholdPositionDeviationErrorThresholdCompare(m_testCtx.getLog(),
                                                                              "CompareResult",
                                                                              "Result of rendering",
                                                                              ref.getAccess(),
                                                                              screen.getAccess(),
                                                                              tcu::UVec4(m_maxDiffRed, m_maxDiffGreen, m_maxDiffBlue, 256),
                                                                              tcu::IVec3(1, 1, 0),                    //!< 3x3 search kernel
                                                                              true,                                //!< relax comparison on the image boundary
                                                                              maxAllowedInvalidPixelsWithPoints,    //!< error threshold
                                                                              tcu::COMPARE_LOG_RESULT);
           }
 
           case PRIMITIVECLASS_LINE:
           {
               // Lines can potentially have a large number of overlapping pixels. Pixel comparison may potentially produce
               // false negatives in such pixels if for example the pixel in question is overdrawn by another line in the
               // reference image but not in the resultin image. Relax comparison near line intersection points (areas) and
               // compare only coverage, not color, in such pixels
               return intersectionRelaxedLineImageCompare(m_testCtx.getLog(),
                                                          "CompareResult",
                                                          "Result of rendering",
                                                          ref,
                                                          screen,
                                                          tcu::IVec3(m_maxDiffRed, m_maxDiffGreen, m_maxDiffBlue),
                                                          maxAllowedInvalidPixelsWithLines);
           }
 
           case PRIMITIVECLASS_TRIANGLE:
           {
               // Triangles are likely to partially or fully overlap. Pixel difference comparison is fragile in pixels
               // where there could be potential overlapping since the  pixels might be covered by one triangle in the
               // reference image and by the other in the result image. Relax comparsion near primitive edges and
               // compare only coverage, not color, in such pixels.
               const tcu::IVec3    renderTargetThreshold                    = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold().toIVec().xyz();
 
               return edgeRelaxedImageCompare(m_testCtx.getLog(),
                                              "CompareResult",
                                              "Result of rendering",
                                              ref,
                                              screen,
                                              tcu::IVec3(m_maxDiffRed, m_maxDiffGreen, m_maxDiffBlue),
                                              renderTargetThreshold,
                                              maxAllowedInvalidPixelsWithTriangles);
           }
 
           default:
               DE_ASSERT(false);
               return false;
       }
   }
}
 
float DrawTest::getCoordScale (const DrawTestSpec& spec) const
{
   float maxValue = 1.0f;
 
   for (int arrayNdx = 0; arrayNdx < (int)spec.attribs.size(); arrayNdx++)
   {
       DrawTestSpec::AttributeSpec attribSpec        = spec.attribs[arrayNdx];
       const bool                    isPositionAttr    = (arrayNdx == 0) || (attribSpec.additionalPositionAttribute);
       float                        attrMaxValue    = 0;
 
       if (!isPositionAttr)
           continue;
 
       if (attribSpec.inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10)
       {
           if (attribSpec.normalize)
               attrMaxValue += 1.0f;
           else
               attrMaxValue += 1024.0f;
       }
       else if (attribSpec.inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10)
       {
           if (attribSpec.normalize)
               attrMaxValue += 1.0f;
           else
               attrMaxValue += 512.0f;
       }
       else
       {
           const float max = GLValue::getMaxValue(attribSpec.inputType).toFloat();
 
           attrMaxValue += (attribSpec.normalize && !inputTypeIsFloatType(attribSpec.inputType)) ? (1.0f) : (max * 1.1f);
       }
 
       if (attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_VEC3 || attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_VEC4
           || attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_IVEC3 || attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_IVEC4
           || attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_UVEC3 || attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_UVEC4)
               attrMaxValue *= 2;
 
       maxValue += attrMaxValue;
   }
 
   return 1.0f / maxValue;
}
 
float DrawTest::getColorScale (const DrawTestSpec& spec) const
{
   float colorScale = 1.0f;
 
   for (int arrayNdx = 1; arrayNdx < (int)spec.attribs.size(); arrayNdx++)
   {
       DrawTestSpec::AttributeSpec attribSpec        = spec.attribs[arrayNdx];
       const bool                    isPositionAttr    = (arrayNdx == 0) || (attribSpec.additionalPositionAttribute);
 
       if (isPositionAttr)
           continue;
 
       if (attribSpec.inputType == DrawTestSpec::INPUTTYPE_UNSIGNED_INT_2_10_10_10)
       {
           if (!attribSpec.normalize)
               colorScale *= 1.0f / 1024.0f;
       }
       else if (attribSpec.inputType == DrawTestSpec::INPUTTYPE_INT_2_10_10_10)
       {
           if (!attribSpec.normalize)
               colorScale *= 1.0f / 512.0f;
       }
       else
       {
           const float max = GLValue::getMaxValue(attribSpec.inputType).toFloat();
 
           colorScale *= (attribSpec.normalize && !inputTypeIsFloatType(attribSpec.inputType) ? 1.0f : float(1.0 / double(max)));
           if (attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_VEC4 ||
               attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_UVEC4 ||
               attribSpec.outputType == DrawTestSpec::OUTPUTTYPE_IVEC4)
               colorScale *= (attribSpec.normalize && !inputTypeIsFloatType(attribSpec.inputType) ? 1.0f : float(1.0 / double(max)));
       }
   }
 
   return colorScale;
}
 
} // gls
} // deqp