This file is indexed.

/usr/include/osg/State is in libopenscenegraph-dev 3.0.1-4.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#ifndef OSG_STATE
#define OSG_STATE 1

#include <osg/Export>
#include <osg/StateSet>
#include <osg/Matrix>
#include <osg/Uniform>
#include <osg/BufferObject>
#include <osg/Observer>
#include <osg/Timer>

#include <osg/ShaderComposer>
#include <osg/FrameStamp>
#include <osg/DisplaySettings>
#include <osg/Polytope>
#include <osg/Viewport>
#include <osg/GLBeginEndAdapter>
#include <osg/ArrayDispatchers>
#include <osg/GraphicsCostEstimator>

#include <iosfwd>
#include <vector>
#include <map>
#include <set>
#include <string>

#ifndef GL_FOG_COORDINATE_ARRAY
    #ifdef GL_FOG_COORDINATE_ARRAY_EXT
        #define GL_FOG_COORDINATE_ARRAY GL_FOG_COORDINATE_ARRAY_EXT
    #else
        #define GL_FOG_COORDINATE_ARRAY 0x8457
    #endif
#endif

#ifndef GL_SECONDARY_COLOR_ARRAY
    #ifdef GL_SECONDARY_COLOR_ARRAY_EXT
        #define GL_SECONDARY_COLOR_ARRAY GL_SECONDARY_COLOR_ARRAY_EXT
    #else
        #define GL_SECONDARY_COLOR_ARRAY 0x845E
    #endif
#endif

#if !defined(GL_EXT_timer_query) && !defined(OSG_GL3_AVAILABLE)
    #ifdef _WIN32
        typedef          __int64 GLint64EXT;
        typedef unsigned __int64 GLuint64EXT;
    #else
        typedef long long int GLint64EXT;
        typedef unsigned long long int GLuint64EXT;
    #endif
#endif

namespace osg {

/** macro for use with osg::StateAttribute::apply methods for detecting and
  * reporting OpenGL error messages.*/
#define OSG_GL_DEBUG(message) \
    if (state.getFineGrainedErrorDetection()) \
    { \
        GLenum errorNo = glGetError(); \
        if (errorNo!=GL_NO_ERROR) \
        { \
            osg::notify(WARN)<<"Warning: detected OpenGL error '"<<gluErrorString(errorNo)<<" "<<message<<endl; \
        }\
    }


// forward declare GraphicsContext, View and State
class GraphicsContext;

class VertexAttribAlias
{
    public:
        VertexAttribAlias():
            _location(0) {}

        VertexAttribAlias(const VertexAttribAlias& rhs):
            _location(rhs._location),
            _glName(rhs._glName),
            _osgName(rhs._osgName),
            _declaration(rhs._declaration) {}

        VertexAttribAlias(GLuint location, const std::string glName, const std::string osgName, const std::string& declaration):
            _location(location),
            _glName(glName),
            _osgName(osgName),
            _declaration(declaration) {}

        GLuint      _location;
        std::string _glName;
        std::string _osgName;
        std::string _declaration;
};


/** Encapsulates the current applied OpenGL modes, attributes and vertex arrays settings,
  * implements lazy state updating and provides accessors for querying the current state.
  * The venerable Red Book says that "OpenGL is a state machine", and this class
  * represents the OpenGL state in OSG. Furthermore, \c State also has other
  * important features:
  * - It works as a stack of states (see \c pushStateSet() and
  *   \c popStateSet()). Manipulating this stack of OpenGL states manually is
  *   seldom needed, since OSG does this in the most common situations.
  * - It implements lazy state updating. This means that, if one requests a
  *   state change and that particular state is already in the requested state,
  *   no OpenGL call will be made. This ensures that the OpenGL pipeline is not
  *   stalled by unnecessary state changes.
  * - It allows to query the current OpenGL state without calls to \c glGet*(),
  *   which typically stall the graphics pipeline (see, for instance,
  *   \c captureCurrentState() and \c getModelViewMatrix()).
  */
class OSG_EXPORT State : public Referenced, public Observer
{
    public :

        State();


        /** Set the graphics context associated with that owns this State object.*/
        void setGraphicsContext(GraphicsContext* context) { _graphicsContext = context; }

        /** Get the graphics context associated with that owns this State object.*/
        GraphicsContext* getGraphicsContext() { return _graphicsContext; }

        /** Get the const graphics context associated with that owns this State object.*/
        const GraphicsContext* getGraphicsContext() const { return _graphicsContext; }


        /** Set the current OpenGL context uniqueID.
         *  The ContextID is used by classes like osg::StateAttribute's and osg::Drawable's to
         *  help manage seperate OpenGL objects, such as display lists, vertex buffer objects
         *  and texture object for each graphics context. The ContextID simply acts as an index 
         *  into arrays that these classes maintain for the purpose of storing GL object handles.
         * 
         *  Note, osgViewer::GraphicsWindow will automatically set up the ContextID for you,
         *  so you will rearely need to set this yourself.
         * 
         *  The exception is when creating your own graphics context, where you should set
         *  the ContextID uniquely for each graphics context.
         * 
         *  Typical settings for ContextID are 0,1,2,3... up to the maximum
         *  number of graphics contexts you have set up. By default contextID is 0.
         */
        inline void setContextID(unsigned int contextID) { _contextID=contextID; }

        /** Get the current OpenGL context unique ID.*/
        inline unsigned int getContextID() const { return _contextID; }


        /* Set whether shader composition is enabled.*/
        void setShaderCompositionEnabled(bool flag) { _shaderCompositionEnabled = flag; }

        /* Get whether shader composition is enabled.*/
        bool getShaderCompositionEnabled() const { return _shaderCompositionEnabled; }

        /** Set the ShaderComposor object that implements shader composition.*/
        void setShaderComposer(ShaderComposer* sc) { _shaderComposer = sc; }

        /** Get the ShaderComposor object.*/
        ShaderComposer* getShaderComposer() { return _shaderComposer.get(); }

        /** Get the const ShaderComposor object.*/
        const ShaderComposer* getShaderComposer() const { return _shaderComposer.get(); }

        /** Get the unform list in which to inject any uniforms that StateAttribute::apply(State&) methods provide.*/
        StateSet::UniformList& getCurrentShaderCompositionUniformList() { return _currentShaderCompositionUniformList; }

        /** Convinience method for StateAttribute:::apply(State&) methods to pass on their uniforms to osg::State so it can apply them at the appropriate point.*/
        void applyShaderCompositionUniform(const osg::Uniform* uniform, StateAttribute::OverrideValue value=StateAttribute::ON)
        {
            StateSet::RefUniformPair& up = _currentShaderCompositionUniformList[uniform->getName()];
            up.first = const_cast<Uniform*>(uniform);
            up.second = value;
        }


        /** Push stateset onto state stack.*/
        void pushStateSet(const StateSet* dstate);

        /** Pop stateset off state stack.*/
        void popStateSet();

        /** pop all statesets off state stack, ensuring it is empty ready for the next frame.
          * Note, to return OpenGL to default state, one should do any state.popAllStatSets(); state.apply().*/
        void popAllStateSets();

        /** Insert stateset onto state stack.*/
        void insertStateSet(unsigned int pos,const StateSet* dstate);

        /** Pop stateset off state stack.*/
        void removeStateSet(unsigned int pos);

        /** Get the number of StateSet's on the StateSet stack.*/
        unsigned int getStateSetStackSize() { return static_cast<unsigned int>(_stateStateStack.size()); }

        /** Pop StateSet's for the StateSet stack till its size equals the specified size.*/
        void popStateSetStackToSize(unsigned int size) { while (_stateStateStack.size()>size) popStateSet(); }

        typedef std::vector<const StateSet*> StateSetStack;

        /** Get the StateSet stack.*/
        StateSetStack& getStateSetStack() { return _stateStateStack; }


        /** Copy the modes and attributes which capture the current state.*/
        void captureCurrentState(StateSet& stateset) const;

        /** reset the state object to an empty stack.*/
        void reset();


        inline const Viewport* getCurrentViewport() const
        {
            return static_cast<const Viewport*>(getLastAppliedAttribute(osg::StateAttribute::VIEWPORT));
        }


        void setInitialViewMatrix(const osg::RefMatrix* matrix);

        inline const osg::Matrix& getInitialViewMatrix() const { return *_initialViewMatrix; }
        inline const osg::Matrix& getInitialInverseViewMatrix() const { return _initialInverseViewMatrix; }

        void applyProjectionMatrix(const osg::RefMatrix* matrix);

        inline const osg::Matrix& getProjectionMatrix() const { return *_projection; }

        void applyModelViewMatrix(const osg::RefMatrix* matrix);
        void applyModelViewMatrix(const osg::Matrix&);

        const osg::Matrix& getModelViewMatrix() const { return *_modelView; }

        void setUseModelViewAndProjectionUniforms(bool flag) { _useModelViewAndProjectionUniforms = flag; }
        bool getUseModelViewAndProjectionUniforms() const { return _useModelViewAndProjectionUniforms; }

        void updateModelViewAndProjectionMatrixUniforms();

        void applyModelViewAndProjectionUniformsIfRequired();

        osg::Uniform* getModelViewMatrixUniform() { return _modelViewMatrixUniform.get(); }
        osg::Uniform* getProjectionMatrixUniform() { return _projectionMatrixUniform.get(); }
        osg::Uniform* getModelViewProjectionMatrixUniform() { return _modelViewProjectionMatrixUniform.get(); }
        osg::Uniform* getNormalMatrixUniform() { return _normalMatrixUniform.get(); }


        Polytope getViewFrustum() const;


        void setUseVertexAttributeAliasing(bool flag) { _useVertexAttributeAliasing = flag; }
        bool getUseVertexAttributeAliasing() const { return _useVertexAttributeAliasing ; }

        typedef std::vector<VertexAttribAlias> VertexAttribAliasList;

        const VertexAttribAlias& getVertexAlias() { return _vertexAlias; }
        const VertexAttribAlias& getNormalAlias() { return _normalAlias; }
        const VertexAttribAlias& getColorAlias() { return _colorAlias; }
        const VertexAttribAlias& getSecondaryColorAlias() { return _secondaryColorAlias; }
        const VertexAttribAlias& getFogCoordAlias() { return _fogCoordAlias; }
        const VertexAttribAliasList& getTexCoordAliasList() { return _texCoordAliasList; }


        const Program::AttribBindingList&  getAttributeBindingList() { return _attributeBindingList; }

        bool convertVertexShaderSourceToOsgBuiltIns(std::string& source) const;


        /** Apply stateset.*/
        void apply(const StateSet* dstate);

        /** Updates the OpenGL state so that it matches the \c StateSet at the
          * top of the stack of <tt>StateSet</tt>s maintained internally by a
          * \c State.
         */
        void apply();

        /** Apply any shader composed state.*/
        void applyShaderComposition();

        /** Set whether a particular OpenGL mode is valid in the current graphics context.
          * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/
        inline void setModeValidity(StateAttribute::GLMode mode,bool valid)
        {
            ModeStack& ms = _modeMap[mode];
            ms.valid = valid;
        }

        /** Get whether a particular OpenGL mode is valid in the current graphics context.
          * Use to disable OpenGL modes that are not supported by current graphics drivers/context.*/
        inline bool getModeValidity(StateAttribute::GLMode mode)
        {
            ModeStack& ms = _modeMap[mode];
            return ms.valid;
        }

        inline void setGlobalDefaultModeValue(StateAttribute::GLMode mode,bool enabled)
        {
            ModeStack& ms = _modeMap[mode];
            ms.global_default_value = enabled;
        }

        inline bool getGlobalDefaultModeValue(StateAttribute::GLMode mode)
        {
            return _modeMap[mode].global_default_value;
        }


        /** Apply an OpenGL mode if required. This is a wrapper around
          * \c glEnable() and \c glDisable(), that just actually calls these
          * functions if the \c enabled flag is different than the current
          * state.
          * @return \c true if the state was actually changed. \c false
          *         otherwise. Notice that a \c false return does not indicate
          *         an error, it just means that the mode was already set to the
          *         same value as the \c enabled parameter.
        */
        inline bool applyMode(StateAttribute::GLMode mode,bool enabled)
        {
            ModeStack& ms = _modeMap[mode];
            ms.changed = true;
            return applyMode(mode,enabled,ms);
        }

        inline void setGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode,bool enabled)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            ms.global_default_value = enabled;
        }

        inline bool getGlobalDefaultTextureModeValue(unsigned int unit, StateAttribute::GLMode mode)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            return ms.global_default_value;
        }

        inline bool applyTextureMode(unsigned int unit, StateAttribute::GLMode mode,bool enabled)
        {
            ModeMap& modeMap = getOrCreateTextureModeMap(unit);
            ModeStack& ms = modeMap[mode];
            ms.changed = true;
            return applyModeOnTexUnit(unit,mode,enabled,ms);
        }

        inline void setGlobalDefaultAttribute(const StateAttribute* attribute)
        {
            AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()];
            as.global_default_attribute = attribute;
        }

        inline const StateAttribute* getGlobalDefaultAttribute(StateAttribute::Type type, unsigned int member=0)
        {
            AttributeStack& as = _attributeMap[StateAttribute::TypeMemberPair(type,member)];
            return as.global_default_attribute.get();
        }

        /** Apply an attribute if required. */
        inline bool applyAttribute(const StateAttribute* attribute)
        {
            AttributeStack& as = _attributeMap[attribute->getTypeMemberPair()];
            as.changed = true;
            return applyAttribute(attribute,as);
        }

        inline void setGlobalDefaultTextureAttribute(unsigned int unit, const StateAttribute* attribute)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[attribute->getTypeMemberPair()];
            as.global_default_attribute = attribute;
        }

        inline const StateAttribute* getGlobalDefaultTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member = 0)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[StateAttribute::TypeMemberPair(type,member)];
            return as.global_default_attribute.get();
        }


        inline bool applyTextureAttribute(unsigned int unit, const StateAttribute* attribute)
        {
            AttributeMap& attributeMap = getOrCreateTextureAttributeMap(unit);
            AttributeStack& as = attributeMap[attribute->getTypeMemberPair()];
            as.changed = true;
            return applyAttributeOnTexUnit(unit,attribute,as);
        }

        /** Mode has been set externally, update state to reflect this setting.*/
        void haveAppliedMode(StateAttribute::GLMode mode,StateAttribute::GLModeValue value);

        /** Mode has been set externally, therefore dirty the associated mode in osg::State
          * so it is applied on next call to osg::State::apply(..)*/
        void haveAppliedMode(StateAttribute::GLMode mode);

        /** Attribute has been applied externally, update state to reflect this setting.*/
        void haveAppliedAttribute(const StateAttribute* attribute);

        /** Attribute has been applied externally, 
          * and therefore this attribute type has been dirtied 
          * and will need to be re-applied on next osg::State.apply(..).
          * note, if you have an osg::StateAttribute which you have applied externally
          * then use the have_applied(attribute) method as this will cause the osg::State to
          * track the current state more accurately and enable lazy state updating such
          * that only changed state will be applied.*/
        void haveAppliedAttribute(StateAttribute::Type type, unsigned int member=0);

        /** Get whether the current specified mode is enabled (true) or disabled (false).*/
        bool getLastAppliedMode(StateAttribute::GLMode mode) const;

        /** Get the current specified attribute, return NULL if one has not yet been applied.*/
        const StateAttribute* getLastAppliedAttribute(StateAttribute::Type type, unsigned int member=0) const;

        /** texture Mode has been set externally, update state to reflect this setting.*/
        void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode,StateAttribute::GLModeValue value);

        /** texture Mode has been set externally, therefore dirty the associated mode in osg::State
          * so it is applied on next call to osg::State::apply(..)*/
        void haveAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode);

        /** texture Attribute has been applied externally, update state to reflect this setting.*/
        void haveAppliedTextureAttribute(unsigned int unit, const StateAttribute* attribute);

        /** texture Attribute has been applied externally,
          * and therefore this attribute type has been dirtied
          * and will need to be re-applied on next osg::State.apply(..).
          * note, if you have an osg::StateAttribute which you have applied externally
          * then use the have_applied(attribute) method as this will the osg::State to
          * track the current state more accurately and enable lazy state updating such
          * that only changed state will be applied.*/
        void haveAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0);

        /** Get whether the current specified texture mode is enabled (true) or disabled (false).*/
        bool getLastAppliedTextureMode(unsigned int unit, StateAttribute::GLMode mode) const;

        /** Get the current specified texture attribute, return NULL if one has not yet been applied.*/
        const StateAttribute* getLastAppliedTextureAttribute(unsigned int unit, StateAttribute::Type type, unsigned int member=0) const;


        /** Dirty the modes previously applied in osg::State.*/
        void dirtyAllModes();

        /** Dirty the modes attributes previously applied in osg::State.*/
        void dirtyAllAttributes();

        /** disable the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/
        void disableAllVertexArrays();

        /** dirty the vertex, normal, color, tex coords, secondary color, fog coord and index arrays.*/
        void dirtyAllVertexArrays();


        void setCurrentVertexBufferObject(osg::GLBufferObject* vbo) { _currentVBO = vbo; }
        const GLBufferObject* getCurrentVertexBufferObject() { return _currentVBO; }
        inline void bindVertexBufferObject(osg::GLBufferObject* vbo)
        {
            if (vbo == _currentVBO) return;
            if (vbo->isDirty()) vbo->compileBuffer();
            else vbo->bindBuffer();
            _currentVBO = vbo;
        }

        inline void unbindVertexBufferObject()
        {
            if (!_currentVBO) return;
            _glBindBuffer(GL_ARRAY_BUFFER_ARB,0);
            _currentVBO = 0;
        }

        void setCurrentElementBufferObject(osg::GLBufferObject* ebo) { _currentEBO = ebo; }
        const GLBufferObject* getCurrentElementBufferObject() { return _currentEBO; }

        inline void bindElementBufferObject(osg::GLBufferObject* ebo)
        {
            if (ebo == _currentEBO) return;
            if (ebo->isDirty()) ebo->compileBuffer();
            else ebo->bindBuffer();
            _currentEBO = ebo;
        }

        inline void unbindElementBufferObject()
        {
            if (!_currentEBO) return;
            _glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB,0);
            _currentEBO = 0;
        }

        void setCurrentPixelBufferObject(osg::GLBufferObject* pbo) { _currentPBO = pbo; }
        const GLBufferObject* getCurrentPixelBufferObject() { return _currentPBO; }

        inline void bindPixelBufferObject(osg::GLBufferObject* pbo)
        {
            if (pbo == _currentPBO) return;

            if (pbo->isDirty()) pbo->compileBuffer();
            else pbo->bindBuffer();

            _currentPBO = pbo;
        }

        inline void unbindPixelBufferObject()
        {
            if (!_currentPBO) return;

            _glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB,0);
            _currentPBO = 0;
        }

        typedef std::vector<GLushort> IndicesGLushort;
        IndicesGLushort _quadIndicesGLushort[4];

        typedef std::vector<GLuint> IndicesGLuint;
        IndicesGLuint _quadIndicesGLuint[4];

        void drawQuads(GLint first, GLsizei count, GLsizei primCount=0);

        inline void glDrawArraysInstanced(GLenum mode, GLint first, GLsizei count, GLsizei primcount)
        {
            if (primcount>=1 && _glDrawArraysInstanced!=0) _glDrawArraysInstanced(mode, first, count, primcount);
            else glDrawArrays(mode, first, count);
        }

        inline void glDrawElementsInstanced(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount )
        {
            if (primcount>=1 && _glDrawElementsInstanced!=0) _glDrawElementsInstanced(mode, count, type, indices, primcount);
            else glDrawElements(mode, count, type, indices);
        }


        inline void Vertex(float x, float y, float z, float w=1.0f)
        {
        #if defined(OSG_GL_VERTEX_FUNCS_AVAILABLE) && !defined(OSG_GLES1_AVAILABLE)
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _vertexAlias._location, x,y,z,w);
            else glVertex4f(x,y,z,w);
        #else
            _glVertexAttrib4f( _vertexAlias._location, x,y,z,w);
        #endif
        }

        inline void Color(float r, float g, float b, float a=1.0f)
        {
        #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _colorAlias._location, r,g,b,a);
            else glColor4f(r,g,b,a);
        #else
            _glVertexAttrib4f( _colorAlias._location, r,g,b,a);
        #endif
        }

        void Normal(float x, float y, float z)
        {
        #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing) _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0);
            else glNormal3f(x,y,z);
        #else
            _glVertexAttrib4f( _normalAlias._location, x,y,z,0.0);
        #endif
        }

        void TexCoord(float x, float y=0.0f, float z=0.0f, float w=1.0f)
        {
        #if !defined(OSG_GLES1_AVAILABLE)
            #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
                if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w);
                else glTexCoord4f(x,y,z,w);
            #else
                _glVertexAttrib4f( _texCoordAliasList[0]._location, x,y,z,w);
            #endif
        #endif
        }

        void MultiTexCoord(unsigned int unit, float x, float y=0.0f, float z=0.0f, float w=1.0f)
        {
        #if !defined(OSG_GLES1_AVAILABLE)
            #ifdef OSG_GL_VERTEX_FUNCS_AVAILABLE
                if (_useVertexAttributeAliasing) _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w);
                else _glMultiTexCoord4f(GL_TEXTURE0+unit,x,y,z,w);
            #else
                _glVertexAttrib4f( _texCoordAliasList[unit]._location, x,y,z,w);
            #endif
        #endif
        }

        void VerteAttrib(unsigned int location, float x, float y=0.0f, float z=0.0f, float w=0.0f)
        {
            _glVertexAttrib4f( location, x,y,z,w);
        }


        /** Mark all the vertex attributes as being disabled but leave the disabling till a later call to applyDisablingOfVertexAttributes.*/
        void lazyDisablingOfVertexAttributes();

        /** Disable all the vertex attributes that have been marked as to be disabled.*/
        void applyDisablingOfVertexAttributes();

        /** Wrapper around glInterleavedArrays(..).
          * also resets the internal array points and modes within osg::State to keep the other
          * vertex array operations consistent. */
        void setInterleavedArrays( GLenum format, GLsizei stride, const GLvoid* pointer);

        /** Set the vertex pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setVertexPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setVertexPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setVertexPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_VERTEX_ARRAY);glVertexPointer(..);
          * note, only updates values that change.*/
        inline void setVertexPointer( GLint size, GLenum type,
                                      GLsizei stride, const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_vertexAlias._location, size, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_vertexArray._enabled || _vertexArray._dirty)
                {
                    _vertexArray._enabled = true;
                    glEnableClientState(GL_VERTEX_ARRAY);
                }
                //if (_vertexArray._pointer!=ptr || _vertexArray._dirty)
                {
                    _vertexArray._pointer=ptr;
                    glVertexPointer( size, type, stride, ptr );
                }
                _vertexArray._lazy_disable = false;
                _vertexArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_vertexAlias._location, size, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_VERTEX_ARRAY).
          * note, only updates values that change.*/
        inline void disableVertexPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_vertexAlias._location);
            }
            else
            {
                if (_vertexArray._enabled || _vertexArray._dirty)
                {
                    _vertexArray._lazy_disable = false;
                    _vertexArray._enabled = false;
                    _vertexArray._dirty = false;
                    glDisableClientState(GL_VERTEX_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_vertexAlias._location);
        #endif
        }

        inline void dirtyVertexPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_vertexAlias._location);
            }
            else
            {
                _vertexArray._pointer = 0;
                _vertexArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_vertexAlias._location);
        #endif
        }


        /** Set the normal pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setNormalPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setNormalPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setNormalPointer(array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_NORMAL_ARRAY);glNormalPointer(..);
          * note, only updates values that change.*/
        inline void setNormalPointer( GLenum type, GLsizei stride,
                                      const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_normalAlias._location, 3, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_normalArray._enabled || _normalArray._dirty)
                {
                    _normalArray._enabled = true;
                    glEnableClientState(GL_NORMAL_ARRAY);
                }
                //if (_normalArray._pointer!=ptr || _normalArray._dirty)
                {
                    _normalArray._pointer=ptr;
                    glNormalPointer( type, stride, ptr );
                }
                _normalArray._lazy_disable = false;
                _normalArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_normalAlias._location, 3, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_NORMAL_ARRAY);
          * note, only updates values that change.*/
        inline void disableNormalPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_normalAlias._location);
            }
            else
            {
                if (_normalArray._enabled || _normalArray._dirty)
                {
                    _normalArray._lazy_disable = false;
                    _normalArray._enabled = false;
                    _normalArray._dirty = false;
                    glDisableClientState(GL_NORMAL_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_normalAlias._location);
        #endif
        }

        inline void dirtyNormalPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_normalAlias._location);
            }
            else
            {
                _normalArray._pointer = 0;
                _normalArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_normalAlias._location);
        #endif
        }

        /** Set the color pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setColorPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }


        /** wrapper around glEnableClientState(GL_COLOR_ARRAY);glColorPointer(..);
          * note, only updates values that change.*/
        inline void setColorPointer( GLint size, GLenum type,
                                     GLsizei stride, const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_colorAlias._location, size, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (!_colorArray._enabled || _colorArray._dirty)
                {
                    _colorArray._enabled = true;
                    glEnableClientState(GL_COLOR_ARRAY);
                }
                //if (_colorArray._pointer!=ptr || _colorArray._dirty)
                {
                    _colorArray._pointer=ptr;
                    glColorPointer( size, type, stride, ptr );
                }
                _colorArray._lazy_disable = false;
                _colorArray._dirty = false;
            }
        #else
            setVertexAttribPointer(_colorAlias._location, size, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_COLOR_ARRAY);
          * note, only updates values that change.*/
        inline void disableColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_colorAlias._location);
            }
            else
            {
                if (_colorArray._enabled || _colorArray._dirty)
                {
                    _colorArray._lazy_disable = false;
                    _colorArray._enabled = false;
                    _colorArray._dirty = false;
                    glDisableClientState(GL_COLOR_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_colorAlias._location);
        #endif
        }

        inline void dirtyColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_colorAlias._location);
            }
            else
            {
                _colorArray._pointer = 0;
                _colorArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_colorAlias._location);
        #endif
        }


        inline bool isSecondaryColorSupported() const { return _isSecondaryColorSupportResolved?_isSecondaryColorSupported:computeSecondaryColorSupported(); }


        /** Set the secondary color pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setSecondaryColorPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setSecondaryColorPointer(array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_SECONDARY_COLOR_ARRAY);glSecondayColorPointer(..);
          * note, only updates values that change.*/
        void setSecondaryColorPointer( GLint size, GLenum type, GLsizei stride, const GLvoid *ptr );

        /** wrapper around glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
          * note, only updates values that change.*/
        inline void disableSecondaryColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_secondaryColorAlias._location);
            }
            else
            {
                if (_secondaryColorArray._enabled || _secondaryColorArray._dirty)
                {
                    _secondaryColorArray._lazy_disable = false;
                    _secondaryColorArray._enabled = false;
                    _secondaryColorArray._dirty = false;
                    if (isSecondaryColorSupported()) glDisableClientState(GL_SECONDARY_COLOR_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_secondaryColorAlias._location);
        #endif
        }

        inline void dirtySecondaryColorPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_secondaryColorAlias._location);
            }
            else
            {
                _secondaryColorArray._pointer = 0;
                _secondaryColorArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_secondaryColorAlias._location);
        #endif
        }

        inline bool isFogCoordSupported() const { return _isFogCoordSupportResolved?_isFogCoordSupported:computeFogCoordSupported(); }


        /** Set the fog coord pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setFogCoordPointer(const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setFogCoordPointer(array->getDataType(),0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setFogCoordPointer(array->getDataType(),0,array->getDataPointer());
                }
            }
        }


        /** wrapper around glEnableClientState(GL_FOG_COORDINATE_ARRAY);glFogCoordPointer(..);
          * note, only updates values that change.*/
        void setFogCoordPointer( GLenum type, GLsizei stride, const GLvoid *ptr );

        /** wrapper around glDisableClientState(GL_FOG_COORDINATE_ARRAY);
          * note, only updates values that change.*/
        inline void disableFogCoordPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_fogCoordAlias._location);
            }
            else
            {
                if (_fogArray._enabled || _fogArray._dirty)
                {
                    _fogArray._lazy_disable = false;
                    _fogArray._enabled = false;
                    _fogArray._dirty = false;
                    if (isFogCoordSupported()) glDisableClientState(GL_FOG_COORDINATE_ARRAY);
                }
            }
        #else
            disableVertexAttribPointer(_fogCoordAlias._location);
        #endif
        }

        inline void dirtyFogCoordPointer()
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_fogCoordAlias._location);
            }
            else
            {
                _fogArray._pointer = 0;
                _fogArray._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_fogCoordAlias._location);
        #endif
        }



        /** Set the tex coord pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setTexCoordPointer(unsigned int unit, const Array* array)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setTexCoordPointer(unit, array->getDataSize(),array->getDataType(),0, (const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setTexCoordPointer(unit, array->getDataSize(),array->getDataType(),0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableClientState(GL_TEXTURE_COORD_ARRAY);glTexCoordPointer(..);
          * note, only updates values that change.*/
        inline void setTexCoordPointer( unsigned int unit,
                                        GLint size, GLenum type,
                                        GLsizei stride, const GLvoid *ptr )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                setVertexAttribPointer(_texCoordAliasList[unit]._location, size, type, GL_FALSE, stride, ptr);
            }
            else
            {
                if (setClientActiveTextureUnit(unit))
                {
                    if ( unit >= _texCoordArrayList.size()) _texCoordArrayList.resize(unit+1);
                    EnabledArrayPair& eap = _texCoordArrayList[unit];

                    if (!eap._enabled || eap._dirty)
                    {
                        eap._enabled = true;
                        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
                    }
                    //if (eap._pointer!=ptr || eap._dirty)
                    {
                        glTexCoordPointer( size, type, stride, ptr );
                        eap._pointer = ptr;
                    }
                    eap._lazy_disable = false;
                    eap._dirty = false;
                }
            }
        #else
            setVertexAttribPointer(_texCoordAliasList[unit]._location, size, type, GL_FALSE, stride, ptr);
        #endif
        }

        /** wrapper around glDisableClientState(GL_TEXTURE_COORD_ARRAY);
          * note, only updates values that change.*/
        inline void disableTexCoordPointer( unsigned int unit )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointer(_texCoordAliasList[unit]._location);
            }
            else
            {
                if (setClientActiveTextureUnit(unit))
                {
                    if ( unit >= _texCoordArrayList.size()) _texCoordArrayList.resize(unit+1);
                    EnabledArrayPair& eap = _texCoordArrayList[unit];

                    if (eap._enabled || eap._dirty)
                    {
                        eap._lazy_disable = false;
                        eap._enabled = false;
                        eap._dirty = false;
                        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
                    }
                }
            }
        #else
            disableVertexAttribPointer(_texCoordAliasList[unit]._location);
        #endif
        }

        inline void dirtyTexCoordPointer( unsigned int unit )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointer(_texCoordAliasList[unit]._location);
            }
            else
            {
                if ( unit >= _texCoordArrayList.size()) return; // _texCoordArrayList.resize(unit+1);
                EnabledArrayPair& eap = _texCoordArrayList[unit];
                eap._pointer = 0;
                eap._dirty = true;
            }
        #else
            dirtyVertexAttribPointer(_texCoordAliasList[unit]._location);
        #endif
        }


        inline void disableTexCoordPointersAboveAndIncluding( unsigned int unit )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                disableVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location);
            }
            else
            {
                while (unit<_texCoordArrayList.size())
                {
                    EnabledArrayPair& eap = _texCoordArrayList[unit];
                    if (eap._enabled || eap._dirty)
                    {
                        if (setClientActiveTextureUnit(unit))
                        {
                            eap._lazy_disable = false;
                            eap._enabled = false;
                            eap._dirty = false;
                            glDisableClientState(GL_TEXTURE_COORD_ARRAY);
                        }
                    }
                    ++unit;
                }
            }
        #else
            disableVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location);
        #endif
        }

        inline void dirtyTexCoordPointersAboveAndIncluding( unsigned int unit )
        {
        #ifdef OSG_GL_VERTEX_ARRAY_FUNCS_AVAILABLE
            if (_useVertexAttributeAliasing)
            {
                dirtyVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location);
            }
            else
            {
                while (unit<_texCoordArrayList.size())
                {
                    EnabledArrayPair& eap = _texCoordArrayList[unit];
                    eap._pointer = 0;
                    eap._dirty = true;
                    ++unit;
                }
            }
        #else
            dirtyVertexAttribPointersAboveAndIncluding(_texCoordAliasList[unit]._location);
        #endif
        }


        /** Set the current texture unit, return true if selected,
          * false if selection failed such as when multi texturing is not supported.
          * note, only updates values that change.*/
        inline bool setActiveTextureUnit( unsigned int unit );
        
        /** Get the current texture unit.*/
        unsigned int getActiveTextureUnit() const { return _currentActiveTextureUnit; }

        /** Set the current tex coord array texture unit, return true if selected,
          * false if selection failed such as when multi texturing is not supported.
          * note, only updates values that change.*/
        bool setClientActiveTextureUnit( unsigned int unit );

        /** Get the current tex coord array texture unit.*/
        unsigned int getClientActiveTextureUnit() const { return _currentClientActiveTextureUnit; }

        /** Set the vertex attrib pointer using an osg::Array, and manage any VBO that are required.*/
        inline void setVertexAttribPointer(unsigned int unit, const Array* array, GLboolean normalized)
        {
            if (array)
            {
                GLBufferObject* vbo = array->getOrCreateGLBufferObject(_contextID);
                if (vbo)
                {
                    bindVertexBufferObject(vbo);
                    setVertexAttribPointer(unit, array->getDataSize(),array->getDataType(),normalized,0,(const GLvoid *)(vbo->getOffset(array->getBufferIndex())));
                }
                else
                {
                    unbindVertexBufferObject();
                    setVertexAttribPointer(unit, array->getDataSize(),array->getDataType(),normalized,0,array->getDataPointer());
                }
            }
        }

        /** wrapper around glEnableVertexAttribArrayARB(index);glVertexAttribPointerARB(..);
          * note, only updates values that change.*/
        void setVertexAttribPointer( unsigned int index,
                                     GLint size, GLenum type, GLboolean normalized,
                                     GLsizei stride, const GLvoid *ptr );

        /** wrapper around DisableVertexAttribArrayARB(index);
          * note, only updates values that change.*/
        void disableVertexAttribPointer( unsigned int index );

        void disableVertexAttribPointersAboveAndIncluding( unsigned int index );

        inline void dirtyVertexAttribPointer( unsigned int index )
        {
            if (index<_vertexAttribArrayList.size())
            {
                EnabledArrayPair& eap = _vertexAttribArrayList[index];
                eap._pointer = 0;
                eap._dirty = true;
            }
        }

        inline void dirtyVertexAttribPointersAboveAndIncluding( unsigned int index )
        {
            while (index<_vertexAttribArrayList.size())
            {
                EnabledArrayPair& eap = _vertexAttribArrayList[index];
                eap._pointer = 0;
                eap._dirty = true;
                ++index;
            }
        }

        bool isVertexBufferObjectSupported() const { return _isVertexBufferObjectSupportResolved?_isVertexBufferObjectSupported:computeVertexBufferObjectSupported(); }


        inline void setLastAppliedProgramObject(const Program::PerContextProgram* program)
        {
            if (_lastAppliedProgramObject!=program)
            {
                _lastAppliedProgramObject = program;
                if (program && _appliedProgramObjectSet.count(program)==0)
                {
                    _appliedProgramObjectSet.insert(program);
                    program->addObserver(this);
                }
            }
        }
        inline const Program::PerContextProgram* getLastAppliedProgramObject() const { return _lastAppliedProgramObject; }

        inline GLint getUniformLocation( unsigned int uniformNameID ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformNameID) : -1; }
        /**
          * Alternative version of getUniformLocation( unsigned int uniformNameID )
          * retrofited into OSG for backward compatibility with osgCal,
          * after uniform ids were refactored from std::strings to GLints in OSG version 2.9.10.
          * 
          * Drawbacks: This method is not particularly fast. It has to access mutexed static 
          * map of uniform ids. So don't overuse it or your app performance will suffer.
        */
        inline GLint getUniformLocation( const std::string & uniformName ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getUniformLocation(uniformName) : -1; }
        inline GLint getAttribLocation( const std::string& name ) const { return _lastAppliedProgramObject ? _lastAppliedProgramObject->getAttribLocation(name) : -1; }

        typedef std::pair<const StateAttribute*,StateAttribute::OverrideValue>  AttributePair;
        typedef std::vector<AttributePair>                                      AttributeVec;

        AttributeVec& getAttributeVec( const osg::StateAttribute* attribute )
        {
                AttributeStack& as = _attributeMap[ attribute->getTypeMemberPair() ];
                return as.attributeVec;
        }

        /** Set the frame stamp for the current frame.*/
        inline void setFrameStamp(FrameStamp* fs) { _frameStamp = fs; }

        /** Get the frame stamp for the current frame.*/
        inline FrameStamp* getFrameStamp() { return _frameStamp.get(); }

        /** Get the const frame stamp for the current frame.*/
        inline const FrameStamp* getFrameStamp() const { return _frameStamp.get(); }


        /** Set the DisplaySettings. Note, nothing is applied, the visual settings are just
          * used in the State object to pass the current visual settings to Drawables
          * during rendering. */
        inline void setDisplaySettings(DisplaySettings* vs) { _displaySettings = vs; }

        /** Get the DisplaySettings */
        inline const DisplaySettings* getDisplaySettings() const { return _displaySettings.get(); }



        /** Set flag for early termination of the draw traversal.*/
        void setAbortRenderingPtr(bool* abortPtr) { _abortRenderingPtr = abortPtr; }

        /** Get flag for early termination of the draw traversal,
          * if true steps should be taken to complete rendering early.*/
        bool getAbortRendering() const { return _abortRenderingPtr!=0?(*_abortRenderingPtr):false; }


        struct DynamicObjectRenderingCompletedCallback : public osg::Referenced
        {
            virtual void completed(osg::State*) = 0;
        };

        /** Set the callback to be called when the dynamic object count hits 0.*/
        void setDynamicObjectRenderingCompletedCallback(DynamicObjectRenderingCompletedCallback* cb){ _completeDynamicObjectRenderingCallback = cb; }

        /** Get the callback to be called when the dynamic object count hits 0.*/
        DynamicObjectRenderingCompletedCallback* getDynamicObjectRenderingCompletedCallback() { return _completeDynamicObjectRenderingCallback.get(); }

        /** Set the number of dynamic objects that will be rendered in this graphics context this frame.*/
        void setDynamicObjectCount(unsigned int count, bool callCallbackOnZero = false)
        {
            if (_dynamicObjectCount != count)
            {
                _dynamicObjectCount = count;
                if (_dynamicObjectCount==0 && callCallbackOnZero && _completeDynamicObjectRenderingCallback.valid())
                {
                    _completeDynamicObjectRenderingCallback->completed(this);
                }
            }
        }

        /** Get the number of dynamic objects that will be rendered in this graphics context this frame.*/
        unsigned int getDynamicObjectCount() const { return _dynamicObjectCount; }
        
        /** Decrement the number of dynamic objects left to render this frame, and once the count goes to zero call the 
          * DynamicObjectRenderingCompletedCallback to inform of completion.*/
        inline void decrementDynamicObjectCount()
        {
            --_dynamicObjectCount;
            if (_dynamicObjectCount==0 && _completeDynamicObjectRenderingCallback.valid())
            {
                _completeDynamicObjectRenderingCallback->completed(this);
            }
        }

        void setMaxTexturePoolSize(unsigned int size);
        unsigned int getMaxTexturePoolSize() const { return _maxTexturePoolSize; }

        void setMaxBufferObjectPoolSize(unsigned int size);
        unsigned int getMaxBufferObjectPoolSize() const { return _maxBufferObjectPoolSize; }


        enum CheckForGLErrors
        {
            /** NEVER_CHECK_GL_ERRORS hints that OpenGL need not be checked for, this
                is the fastest option since checking for errors does incurr a small overhead.*/
            NEVER_CHECK_GL_ERRORS,
            /** ONCE_PER_FRAME means that OpenGl errors will be checked for once per
                frame, the overhead is still small, but at least OpenGL errors that are occurring
                will be caught, the reporting isn't fine grained enough for debugging purposes.*/
            ONCE_PER_FRAME,
            /** ONCE_PER_ATTRIBUTE means that OpenGL errors will be checked for after
                every attribute is applied, allow errors to be directly associated with
                particular operations which makes debugging much easier.*/
            ONCE_PER_ATTRIBUTE
        };

        /** Set whether and how often OpenGL errors should be checked for.*/
        void setCheckForGLErrors(CheckForGLErrors check) { _checkGLErrors = check; }

        /** Get whether and how often OpenGL errors should be checked for.*/
        CheckForGLErrors getCheckForGLErrors() const { return _checkGLErrors; }

        bool checkGLErrors(const char* str) const;
        bool checkGLErrors(StateAttribute::GLMode mode) const;
        bool checkGLErrors(const StateAttribute* attribute) const;

        /** print out the internal details of osg::State - useful for debugging.*/
        void print(std::ostream& fout) const;

        /** Initialize extension used by osg:::State.*/
        void initializeExtensionProcs();

        virtual void objectDeleted(void* object);

        /** Get the GL adapter object used to map OpenGL 1.0 glBegin/glEnd usage to vertex arrays.*/
        inline GLBeginEndAdapter& getGLBeginEndAdapter() { return _glBeginEndAdapter; }

        /** Get the helper class for dispatching osg::Arrays as OpenGL attribute data.*/
        inline ArrayDispatchers& getArrayDispatchers() { return _arrayDispatchers; }


        /** Set the helper class that provides applications with estimate on how much different graphics operations will cost.*/
        inline void setGraphicsCostEstimator(GraphicsCostEstimator* gce) { _graphicsCostEstimator = gce; }

        /** Get the helper class that provides applications with estimate on how much different graphics operations will cost.*/
        inline GraphicsCostEstimator* getGraphicsCostEstimator() { return _graphicsCostEstimator.get(); }

        /** Get the cont helper class that provides applications with estimate on how much different graphics operations will cost.*/
        inline const GraphicsCostEstimator* getGraphicsCostEstimator() const { return _graphicsCostEstimator.get(); }



        /** Support for synchronizing the system time and the timestamp
         * counter available with ARB_timer_query. Note that State
         * doesn't update these values itself.
         */
        Timer_t getStartTick() const { return _startTick; }
        void setStartTick(Timer_t tick) { _startTick = tick; }
        Timer_t getGpuTick() const { return _gpuTick; }

        double getGpuTime() const
        {
            return osg::Timer::instance()->delta_s(_startTick, _gpuTick);
        }
        GLuint64EXT getGpuTimestamp() const { return _gpuTimestamp; }

        void setGpuTimestamp(Timer_t tick, GLuint64EXT timestamp)
        {
            _gpuTick = tick;
            _gpuTimestamp = timestamp;
        }
        int getTimestampBits() const { return _timestampBits; }
        void setTimestampBits(int bits) { _timestampBits = bits; }

        /** called by the GraphicsContext just before GraphicsContext::swapBuffersImplementation().*/
        virtual void frameCompleted();

    protected:

        virtual ~State();

        GraphicsContext*            _graphicsContext;
        unsigned int                _contextID;

        bool                            _shaderCompositionEnabled;
        bool                            _shaderCompositionDirty;
        osg::ref_ptr<ShaderComposer>    _shaderComposer;
        osg::Program*                   _currentShaderCompositionProgram;
        StateSet::UniformList           _currentShaderCompositionUniformList;

        ref_ptr<FrameStamp>         _frameStamp;

        ref_ptr<const RefMatrix>    _identity;
        ref_ptr<const RefMatrix>    _initialViewMatrix;
        ref_ptr<const RefMatrix>    _projection;
        ref_ptr<const RefMatrix>    _modelView;
        ref_ptr<RefMatrix>          _modelViewCache;

        bool                        _useModelViewAndProjectionUniforms;
        ref_ptr<Uniform>            _modelViewMatrixUniform;
        ref_ptr<Uniform>            _projectionMatrixUniform;
        ref_ptr<Uniform>            _modelViewProjectionMatrixUniform;
        ref_ptr<Uniform>            _normalMatrixUniform;

        Matrix                      _initialInverseViewMatrix;

        ref_ptr<DisplaySettings>    _displaySettings;

        bool*                       _abortRenderingPtr;
        CheckForGLErrors            _checkGLErrors;


        bool                        _useVertexAttributeAliasing;
        VertexAttribAlias           _vertexAlias;
        VertexAttribAlias           _normalAlias;
        VertexAttribAlias           _colorAlias;
        VertexAttribAlias           _secondaryColorAlias;
        VertexAttribAlias           _fogCoordAlias;
        VertexAttribAliasList       _texCoordAliasList;

        Program::AttribBindingList  _attributeBindingList;

        void setUpVertexAttribAlias(VertexAttribAlias& alias, GLuint location, const std::string glName, const std::string osgName, const std::string& declaration);


        struct ModeStack
        {
            typedef std::vector<StateAttribute::GLModeValue> ValueVec;

            ModeStack()
            {
                valid = true;
                changed = false;
                last_applied_value = false;
                global_default_value = false;
            }

            void print(std::ostream& fout) const;

            bool        valid;
            bool        changed;
            bool        last_applied_value;
            bool        global_default_value;
            ValueVec    valueVec;
        };

        struct AttributeStack
        {
            AttributeStack()
            {
                changed = false;
                last_applied_attribute = 0L;
                last_applied_shadercomponent = 0L;
                global_default_attribute = 0L;
                
            }

            void print(std::ostream& fout) const;

            /** apply an attribute if required, passing in attribute and appropriate attribute stack */
            bool                    changed;
            const StateAttribute*   last_applied_attribute;
            const ShaderComponent*  last_applied_shadercomponent;
            ref_ptr<const StateAttribute> global_default_attribute;
            AttributeVec            attributeVec;
        };


        struct UniformStack
        {
            typedef std::pair<const Uniform*,StateAttribute::OverrideValue>         UniformPair;
            typedef std::vector<UniformPair>                                        UniformVec;

            UniformStack() {}

            void print(std::ostream& fout) const;

            UniformVec              uniformVec;
        };


        /** Apply an OpenGL mode if required, passing in mode, enable flag and
          * appropriate mode stack. This is a wrapper around \c glEnable() and
          * \c glDisable(), that just actually calls these functions if the
          * \c enabled flag is different than the current state.
          * @return \c true if the state was actually changed. \c false
          *         otherwise. Notice that a \c false return does not indicate
          *         an error, it just means that the mode was already set to the
          *         same value as the \c enabled parameter.
        */
        inline bool applyMode(StateAttribute::GLMode mode,bool enabled,ModeStack& ms)
        {
            if (ms.valid && ms.last_applied_value != enabled)
            {
                ms.last_applied_value = enabled;

                if (enabled) glEnable(mode);
                else glDisable(mode);

                if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(mode);

                return true;
            }
            else
                return false;
        }

        inline bool applyModeOnTexUnit(unsigned int unit,StateAttribute::GLMode mode,bool enabled,ModeStack& ms)
        {
            if (ms.valid && ms.last_applied_value != enabled)
            {
                if (setActiveTextureUnit(unit))
                {
                    ms.last_applied_value = enabled;

                    if (enabled) glEnable(mode);
                    else glDisable(mode);

                    if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(mode);

                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }

        /** apply an attribute if required, passing in attribute and appropriate attribute stack */
        inline bool applyAttribute(const StateAttribute* attribute,AttributeStack& as)
        {
            if (as.last_applied_attribute != attribute)
            {
                if (!as.global_default_attribute.valid()) as.global_default_attribute = dynamic_cast<StateAttribute*>(attribute->cloneType());

                as.last_applied_attribute = attribute;
                attribute->apply(*this);

                const ShaderComponent* sc = attribute->getShaderComponent();
                if (as.last_applied_shadercomponent != sc)
                {
                    as.last_applied_shadercomponent = sc;
                    _shaderCompositionDirty = true;
                }

                if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(attribute);

                return true;
            }
            else
                return false;
        }

        inline bool applyAttributeOnTexUnit(unsigned int unit,const StateAttribute* attribute,AttributeStack& as)
        {
            if (as.last_applied_attribute != attribute)
            {
                if (setActiveTextureUnit(unit))
                {
                    if (!as.global_default_attribute.valid()) as.global_default_attribute = dynamic_cast<StateAttribute*>(attribute->cloneType());

                    as.last_applied_attribute = attribute;
                    attribute->apply(*this);

                    const ShaderComponent* sc = attribute->getShaderComponent();
                    if (as.last_applied_shadercomponent != sc)
                    {
                        as.last_applied_shadercomponent = sc;
                        _shaderCompositionDirty = true;
                    }

                    if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(attribute);

                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }


        inline bool applyGlobalDefaultAttribute(AttributeStack& as)
        {
            if (as.last_applied_attribute != as.global_default_attribute.get())
            {
                as.last_applied_attribute = as.global_default_attribute.get();
                if (as.global_default_attribute.valid())
                {
                    as.global_default_attribute->apply(*this);
                    const ShaderComponent* sc = as.global_default_attribute->getShaderComponent();
                    if (as.last_applied_shadercomponent != sc)
                    {
                        as.last_applied_shadercomponent = sc;
                        _shaderCompositionDirty = true;
                    }

                    if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(as.global_default_attribute.get());
                }
                return true;
            }
            else
                return false;
        }

        inline bool applyGlobalDefaultAttributeOnTexUnit(unsigned int unit,AttributeStack& as)
        {
            if (as.last_applied_attribute != as.global_default_attribute.get())
            {
                if (setActiveTextureUnit(unit))
                {
                    as.last_applied_attribute = as.global_default_attribute.get();
                    if (as.global_default_attribute.valid())
                    {
                        as.global_default_attribute->apply(*this);
                        const ShaderComponent* sc = as.global_default_attribute->getShaderComponent();
                        if (as.last_applied_shadercomponent != sc)
                        {
                            as.last_applied_shadercomponent = sc;
                            _shaderCompositionDirty = true;
                        }
                        if (_checkGLErrors==ONCE_PER_ATTRIBUTE) checkGLErrors(as.global_default_attribute.get());
                    }
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }


        typedef std::map<StateAttribute::GLMode,ModeStack>              ModeMap;
        typedef std::vector<ModeMap>                                    TextureModeMapList;

        typedef std::map<StateAttribute::TypeMemberPair,AttributeStack> AttributeMap;
        typedef std::vector<AttributeMap>                               TextureAttributeMapList;

        typedef std::map<std::string,UniformStack>                      UniformMap;

        typedef std::vector<ref_ptr<const Matrix> >                     MatrixStack;

        typedef std::set<const Program::PerContextProgram* >            AppliedProgramObjectSet;

        ModeMap                                                         _modeMap;
        AttributeMap                                                    _attributeMap;
        UniformMap                                                      _uniformMap;

        TextureModeMapList                                              _textureModeMapList;
        TextureAttributeMapList                                         _textureAttributeMapList;

        AppliedProgramObjectSet                                         _appliedProgramObjectSet;
        const Program::PerContextProgram*                               _lastAppliedProgramObject;

        StateSetStack                                                   _stateStateStack;

        unsigned int                                                    _maxTexturePoolSize;
        unsigned int                                                    _maxBufferObjectPoolSize;


        struct EnabledArrayPair
        {
            EnabledArrayPair():_lazy_disable(false),_dirty(true),_enabled(false),_normalized(0),_pointer(0) {}
            EnabledArrayPair(const EnabledArrayPair& eap):_lazy_disable(eap._lazy_disable),_dirty(eap._dirty), _enabled(eap._enabled),_normalized(eap._normalized),_pointer(eap._pointer) {}
            EnabledArrayPair& operator = (const EnabledArrayPair& eap) { _lazy_disable = eap._lazy_disable;_dirty=eap._dirty; _enabled=eap._enabled; _normalized=eap._normalized;_pointer=eap._pointer; return *this; }

            bool            _lazy_disable;
            bool            _dirty;
            bool            _enabled;
            GLboolean       _normalized;
            const GLvoid*   _pointer;
        };

        typedef std::vector<EnabledArrayPair>                   EnabledTexCoordArrayList;
        typedef std::vector<EnabledArrayPair>                   EnabledVertexAttribArrayList;

        EnabledArrayPair                _vertexArray;
        EnabledArrayPair                _normalArray;
        EnabledArrayPair                _colorArray;
        EnabledArrayPair                _secondaryColorArray;
        EnabledArrayPair                _fogArray;
        EnabledTexCoordArrayList        _texCoordArrayList;
        EnabledVertexAttribArrayList    _vertexAttribArrayList;

        unsigned int                    _currentActiveTextureUnit;
        unsigned int                    _currentClientActiveTextureUnit;
        GLBufferObject*                 _currentVBO;
        GLBufferObject*                 _currentEBO;
        GLBufferObject*                 _currentPBO;


        inline ModeMap& getOrCreateTextureModeMap(unsigned int unit)
        {
            if (unit>=_textureModeMapList.size()) _textureModeMapList.resize(unit+1);
            return _textureModeMapList[unit];
        }


        inline AttributeMap& getOrCreateTextureAttributeMap(unsigned int unit)
        {
            if (unit>=_textureAttributeMapList.size()) _textureAttributeMapList.resize(unit+1);
            return _textureAttributeMapList[unit];
        }

        inline void pushModeList(ModeMap& modeMap,const StateSet::ModeList& modeList);
        inline void pushAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList);
        inline void pushUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList);

        inline void popModeList(ModeMap& modeMap,const StateSet::ModeList& modeList);
        inline void popAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList);
        inline void popUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList);

        inline void applyModeList(ModeMap& modeMap,const StateSet::ModeList& modeList);
        inline void applyAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList);
        inline void applyUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList);

        inline void applyModeMap(ModeMap& modeMap);
        inline void applyAttributeMap(AttributeMap& attributeMap);
        inline void applyUniformMap(UniformMap& uniformMap);

        inline void applyModeListOnTexUnit(unsigned int unit,ModeMap& modeMap,const StateSet::ModeList& modeList);
        inline void applyAttributeListOnTexUnit(unsigned int unit,AttributeMap& attributeMap,const StateSet::AttributeList& attributeList);

        inline void applyModeMapOnTexUnit(unsigned int unit,ModeMap& modeMap);
        inline void applyAttributeMapOnTexUnit(unsigned int unit,AttributeMap& attributeMap);

        void haveAppliedMode(ModeMap& modeMap,StateAttribute::GLMode mode,StateAttribute::GLModeValue value);
        void haveAppliedMode(ModeMap& modeMap,StateAttribute::GLMode mode);
        void haveAppliedAttribute(AttributeMap& attributeMap,const StateAttribute* attribute);
        void haveAppliedAttribute(AttributeMap& attributeMap,StateAttribute::Type type, unsigned int member);
        bool getLastAppliedMode(const ModeMap& modeMap,StateAttribute::GLMode mode) const;
        const StateAttribute* getLastAppliedAttribute(const AttributeMap& attributeMap,StateAttribute::Type type, unsigned int member) const;

        void loadModelViewMatrix();


        mutable bool _isSecondaryColorSupportResolved;
        mutable bool _isSecondaryColorSupported;
        bool computeSecondaryColorSupported() const;

        mutable bool _isFogCoordSupportResolved;
        mutable bool _isFogCoordSupported;
        bool computeFogCoordSupported() const;

        mutable bool _isVertexBufferObjectSupportResolved;
        mutable bool _isVertexBufferObjectSupported;
        bool computeVertexBufferObjectSupported() const;

        typedef void (GL_APIENTRY * ActiveTextureProc) (GLenum texture);
        typedef void (GL_APIENTRY * FogCoordPointerProc) (GLenum type, GLsizei stride, const GLvoid *pointer);
        typedef void (GL_APIENTRY * SecondaryColorPointerProc) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
        typedef void (GL_APIENTRY * MultiTexCoord4fProc) (GLenum target, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
        typedef void (GL_APIENTRY * VertexAttrib4fProc)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
        typedef void (GL_APIENTRY * VertexAttrib4fvProc)(GLuint index, const GLfloat *v);
        typedef void (GL_APIENTRY * VertexAttribPointerProc) (unsigned int, GLint, GLenum, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
        typedef void (GL_APIENTRY * EnableVertexAttribProc) (unsigned int);
        typedef void (GL_APIENTRY * DisableVertexAttribProc) (unsigned int);
        typedef void (GL_APIENTRY * BindBufferProc) (GLenum target, GLuint buffer);

        typedef void (GL_APIENTRY * DrawArraysInstancedProc)( GLenum mode, GLint first, GLsizei count, GLsizei primcount );
        typedef void (GL_APIENTRY * DrawElementsInstancedProc)( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei primcount );

        bool                        _extensionProcsInitialized;
        GLint                       _glMaxTextureCoords;
        GLint                       _glMaxTextureUnits;
        ActiveTextureProc           _glClientActiveTexture;
        ActiveTextureProc           _glActiveTexture;
        MultiTexCoord4fProc         _glMultiTexCoord4f;
        VertexAttrib4fProc          _glVertexAttrib4f;
        VertexAttrib4fvProc         _glVertexAttrib4fv;
        FogCoordPointerProc         _glFogCoordPointer;
        SecondaryColorPointerProc   _glSecondaryColorPointer;
        VertexAttribPointerProc     _glVertexAttribPointer;
        EnableVertexAttribProc      _glEnableVertexAttribArray;
        DisableVertexAttribProc     _glDisableVertexAttribArray;
        BindBufferProc              _glBindBuffer;
        DrawArraysInstancedProc     _glDrawArraysInstanced;
        DrawElementsInstancedProc   _glDrawElementsInstanced;

        unsigned int                                            _dynamicObjectCount;
        osg::ref_ptr<DynamicObjectRenderingCompletedCallback>   _completeDynamicObjectRenderingCallback;

        GLBeginEndAdapter           _glBeginEndAdapter;
        ArrayDispatchers            _arrayDispatchers;

        osg::ref_ptr<GraphicsCostEstimator> _graphicsCostEstimator;
        
        Timer_t                      _startTick;
        Timer_t                      _gpuTick;
        GLuint64EXT                 _gpuTimestamp;
        int                         _timestampBits;
};

inline void State::pushModeList(ModeMap& modeMap,const StateSet::ModeList& modeList)
{
    for(StateSet::ModeList::const_iterator mitr=modeList.begin();
        mitr!=modeList.end();
        ++mitr)
    {
        // get the mode stack for incoming GLmode {mitr->first}.
        ModeStack& ms = modeMap[mitr->first];
        if (ms.valueVec.empty())
        {
            // first pair so simply push incoming pair to back.
            ms.valueVec.push_back(mitr->second);
        }
        else if ((ms.valueVec.back() & StateAttribute::OVERRIDE) && !(mitr->second & StateAttribute::PROTECTED)) // check the existing override flag
        {
            // push existing back since override keeps the previous value.
            ms.valueVec.push_back(ms.valueVec.back());
        }
        else
        {
            // no override on so simply push incoming pair to back.
            ms.valueVec.push_back(mitr->second);
        }
        ms.changed = true;
    }
}

inline void State::pushAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList)
{
    for(StateSet::AttributeList::const_iterator aitr=attributeList.begin();
        aitr!=attributeList.end();
        ++aitr)
    {
        // get the attribute stack for incoming type {aitr->first}.
        AttributeStack& as = attributeMap[aitr->first];
        if (as.attributeVec.empty())
        {
            // first pair so simply push incoming pair to back.
            as.attributeVec.push_back(
                AttributePair(aitr->second.first.get(),aitr->second.second));
        }
        else if ((as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(aitr->second.second & StateAttribute::PROTECTED)) // check the existing override flag
        {
            // push existing back since override keeps the previous value.
            as.attributeVec.push_back(as.attributeVec.back());
        }
        else
        {
            // no override on so simply push incoming pair to back.
            as.attributeVec.push_back(
                AttributePair(aitr->second.first.get(),aitr->second.second));
        }
        as.changed = true;
    }
}


inline void State::pushUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList)
{
    for(StateSet::UniformList::const_iterator aitr=uniformList.begin();
        aitr!=uniformList.end();
        ++aitr)
    {
        // get the attribute stack for incoming type {aitr->first}.
        UniformStack& us = uniformMap[aitr->first];
        if (us.uniformVec.empty())
        {
            // first pair so simply push incoming pair to back.
            us.uniformVec.push_back(
                UniformStack::UniformPair(aitr->second.first.get(),aitr->second.second));
        }
        else if ((us.uniformVec.back().second & StateAttribute::OVERRIDE) && !(aitr->second.second & StateAttribute::PROTECTED)) // check the existing override flag
        {
            // push existing back since override keeps the previous value.
            us.uniformVec.push_back(us.uniformVec.back());
        }
        else
        {
            // no override on so simply push incoming pair to back.
            us.uniformVec.push_back(
                UniformStack::UniformPair(aitr->second.first.get(),aitr->second.second));
        }
    }
}

inline void State::popModeList(ModeMap& modeMap,const StateSet::ModeList& modeList)
{
    for(StateSet::ModeList::const_iterator mitr=modeList.begin();
        mitr!=modeList.end();
        ++mitr)
    {
        // get the mode stack for incoming GLmode {mitr->first}.
        ModeStack& ms = modeMap[mitr->first];
        if (!ms.valueVec.empty())
        {
            ms.valueVec.pop_back();
        }
        ms.changed = true;
    }
}

inline void State::popAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList)
{
    for(StateSet::AttributeList::const_iterator aitr=attributeList.begin();
        aitr!=attributeList.end();
        ++aitr)
    {
        // get the attribute stack for incoming type {aitr->first}.
        AttributeStack& as = attributeMap[aitr->first];
        if (!as.attributeVec.empty())
        {
            as.attributeVec.pop_back();
        }
        as.changed = true;
    }
}

inline void State::popUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList)
{
    for(StateSet::UniformList::const_iterator aitr=uniformList.begin();
        aitr!=uniformList.end();
        ++aitr)
    {
        // get the attribute stack for incoming type {aitr->first}.
        UniformStack& us = uniformMap[aitr->first];
        if (!us.uniformVec.empty())
        {
            us.uniformVec.pop_back();
        }
    }
}

inline void State::applyModeList(ModeMap& modeMap,const StateSet::ModeList& modeList)
{
    StateSet::ModeList::const_iterator ds_mitr = modeList.begin();
    ModeMap::iterator this_mitr=modeMap.begin();

    while (this_mitr!=modeMap.end() && ds_mitr!=modeList.end())
    {
        if (this_mitr->first<ds_mitr->first)
        {

            // note GLMode = this_mitr->first
            ModeStack& ms = this_mitr->second;
            if (ms.changed)
            {
                ms.changed = false;
                if (!ms.valueVec.empty())
                {
                    bool new_value = ms.valueVec.back() & StateAttribute::ON;
                    applyMode(this_mitr->first,new_value,ms);
                }
                else
                {
                    // assume default of disabled.
                    applyMode(this_mitr->first,ms.global_default_value,ms);

                }

            }

            ++this_mitr;

        }
        else if (ds_mitr->first<this_mitr->first)
        {

            // ds_mitr->first is a new mode, therefore
            // need to insert a new mode entry for ds_mistr->first.
            ModeStack& ms = modeMap[ds_mitr->first];

            bool new_value = ds_mitr->second & StateAttribute::ON;
            applyMode(ds_mitr->first,new_value,ms);

            // will need to disable this mode on next apply so set it to changed.
            ms.changed = true;

            ++ds_mitr;

        }
        else
        {
            // this_mitr & ds_mitr refer to the same mode, check the override
            // if any otherwise just apply the incoming mode.

            ModeStack& ms = this_mitr->second;

            if (!ms.valueVec.empty() && (ms.valueVec.back() & StateAttribute::OVERRIDE) && !(ds_mitr->second & StateAttribute::PROTECTED))
            {
                // override is on, just treat as a normal apply on modes.

                if (ms.changed)
                {
                    ms.changed = false;
                    bool new_value = ms.valueVec.back() & StateAttribute::ON;
                    applyMode(this_mitr->first,new_value,ms);

                }
            }
            else
            {
                // no override on or no previous entry, therefore consider incoming mode.
                bool new_value = ds_mitr->second & StateAttribute::ON;
                if (applyMode(ds_mitr->first,new_value,ms))
                {
                    ms.changed = true;
                }
            }

            ++this_mitr;
            ++ds_mitr;
        }
    }

    // iterator over the remaining state modes to apply any previous changes.
    for(;
        this_mitr!=modeMap.end();
        ++this_mitr)
    {
        // note GLMode = this_mitr->first
        ModeStack& ms = this_mitr->second;
        if (ms.changed)
        {
            ms.changed = false;
            if (!ms.valueVec.empty())
            {
                bool new_value = ms.valueVec.back() & StateAttribute::ON;
                applyMode(this_mitr->first,new_value,ms);
            }
            else
            {
                // assume default of disabled.
                applyMode(this_mitr->first,ms.global_default_value,ms);

            }

        }
    }

    // iterator over the remaining incoming modes to apply any new mode.
    for(;
        ds_mitr!=modeList.end();
        ++ds_mitr)
    {
        ModeStack& ms = modeMap[ds_mitr->first];

        bool new_value = ds_mitr->second & StateAttribute::ON;
        applyMode(ds_mitr->first,new_value,ms);

        // will need to disable this mode on next apply so set it to changed.
        ms.changed = true;
    }
}

inline void State::applyModeListOnTexUnit(unsigned int unit,ModeMap& modeMap,const StateSet::ModeList& modeList)
{
    StateSet::ModeList::const_iterator ds_mitr = modeList.begin();
    ModeMap::iterator this_mitr=modeMap.begin();

    while (this_mitr!=modeMap.end() && ds_mitr!=modeList.end())
    {
        if (this_mitr->first<ds_mitr->first)
        {

            // note GLMode = this_mitr->first
            ModeStack& ms = this_mitr->second;
            if (ms.changed)
            {
                ms.changed = false;
                if (!ms.valueVec.empty())
                {
                    bool new_value = ms.valueVec.back() & StateAttribute::ON;
                    applyModeOnTexUnit(unit,this_mitr->first,new_value,ms);
                }
                else
                {
                    // assume default of disabled.
                    applyModeOnTexUnit(unit,this_mitr->first,ms.global_default_value,ms);

                }

            }

            ++this_mitr;

        }
        else if (ds_mitr->first<this_mitr->first)
        {

            // ds_mitr->first is a new mode, therefore
            // need to insert a new mode entry for ds_mistr->first.
            ModeStack& ms = modeMap[ds_mitr->first];

            bool new_value = ds_mitr->second & StateAttribute::ON;
            applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms);

            // will need to disable this mode on next apply so set it to changed.
            ms.changed = true;

            ++ds_mitr;

        }
        else
        {
            // this_mitr & ds_mitr refer to the same mode, check the override
            // if any otherwise just apply the incoming mode.

            ModeStack& ms = this_mitr->second;

            if (!ms.valueVec.empty() && (ms.valueVec.back() & StateAttribute::OVERRIDE) && !(ds_mitr->second & StateAttribute::PROTECTED))
            {
                // override is on, just treat as a normal apply on modes.

                if (ms.changed)
                {
                    ms.changed = false;
                    bool new_value = ms.valueVec.back() & StateAttribute::ON;
                    applyModeOnTexUnit(unit,this_mitr->first,new_value,ms);

                }
            }
            else
            {
                // no override on or no previous entry, therefore consider incoming mode.
                bool new_value = ds_mitr->second & StateAttribute::ON;
                if (applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms))
                {
                    ms.changed = true;
                }
            }

            ++this_mitr;
            ++ds_mitr;
        }
    }

    // iterator over the remaining state modes to apply any previous changes.
    for(;
        this_mitr!=modeMap.end();
        ++this_mitr)
    {
        // note GLMode = this_mitr->first
        ModeStack& ms = this_mitr->second;
        if (ms.changed)
        {
            ms.changed = false;
            if (!ms.valueVec.empty())
            {
                bool new_value = ms.valueVec.back() & StateAttribute::ON;
                applyModeOnTexUnit(unit,this_mitr->first,new_value,ms);
            }
            else
            {
                // assume default of disabled.
                applyModeOnTexUnit(unit,this_mitr->first,ms.global_default_value,ms);

            }

        }
    }

    // iterator over the remaining incoming modes to apply any new mode.
    for(;
        ds_mitr!=modeList.end();
        ++ds_mitr)
    {
        ModeStack& ms = modeMap[ds_mitr->first];

        bool new_value = ds_mitr->second & StateAttribute::ON;
        applyModeOnTexUnit(unit,ds_mitr->first,new_value,ms);

        // will need to disable this mode on next apply so set it to changed.
        ms.changed = true;
    }
}

inline void State::applyAttributeList(AttributeMap& attributeMap,const StateSet::AttributeList& attributeList)
{
    StateSet::AttributeList::const_iterator ds_aitr=attributeList.begin();

    AttributeMap::iterator this_aitr=attributeMap.begin();

    while (this_aitr!=attributeMap.end() && ds_aitr!=attributeList.end())
    {
        if (this_aitr->first<ds_aitr->first)
        {

            // note attribute type = this_aitr->first
            AttributeStack& as = this_aitr->second;
            if (as.changed)
            {
                as.changed = false;
                if (!as.attributeVec.empty())
                {
                    const StateAttribute* new_attr = as.attributeVec.back().first;
                    applyAttribute(new_attr,as);
                }
                else
                {
                    applyGlobalDefaultAttribute(as);
                }
            }

            ++this_aitr;

        }
        else if (ds_aitr->first<this_aitr->first)
        {

            // ds_aitr->first is a new attribute, therefore
            // need to insert a new attribute entry for ds_aitr->first.
            AttributeStack& as = attributeMap[ds_aitr->first];

            const StateAttribute* new_attr = ds_aitr->second.first.get();
            applyAttribute(new_attr,as);

            as.changed = true;

            ++ds_aitr;

        }
        else
        {
            // this_mitr & ds_mitr refer to the same attribute, check the override
            // if any otherwise just apply the incoming attribute

            AttributeStack& as = this_aitr->second;

            if (!as.attributeVec.empty() && (as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED))
            {
                // override is on, just treat as a normal apply on attribute.

                if (as.changed)
                {
                    as.changed = false;
                    const StateAttribute* new_attr = as.attributeVec.back().first;
                    applyAttribute(new_attr,as);
                }
            }
            else
            {
                // no override on or no previous entry, therefore consider incoming attribute.
                const StateAttribute* new_attr = ds_aitr->second.first.get();
                if (applyAttribute(new_attr,as))
                {
                    as.changed = true;
                }
            }

            ++this_aitr;
            ++ds_aitr;
        }
    }

    // iterator over the remaining state attributes to apply any previous changes.
    for(;
        this_aitr!=attributeMap.end();
        ++this_aitr)
    {
        // note attribute type = this_aitr->first
        AttributeStack& as = this_aitr->second;
        if (as.changed)
        {
            as.changed = false;
            if (!as.attributeVec.empty())
            {
                const StateAttribute* new_attr = as.attributeVec.back().first;
                applyAttribute(new_attr,as);
            }
            else
            {
                applyGlobalDefaultAttribute(as);
            }
        }
    }

    // iterator over the remaining incoming attribute to apply any new attribute.
    for(;
        ds_aitr!=attributeList.end();
        ++ds_aitr)
    {
        // ds_aitr->first is a new attribute, therefore
        // need to insert a new attribute entry for ds_aitr->first.
        AttributeStack& as = attributeMap[ds_aitr->first];

        const StateAttribute* new_attr = ds_aitr->second.first.get();
        applyAttribute(new_attr,as);

        // will need to update this attribute on next apply so set it to changed.
        as.changed = true;
    }

}

inline void State::applyAttributeListOnTexUnit(unsigned int unit,AttributeMap& attributeMap,const StateSet::AttributeList& attributeList)
{
    StateSet::AttributeList::const_iterator ds_aitr=attributeList.begin();

    AttributeMap::iterator this_aitr=attributeMap.begin();

    while (this_aitr!=attributeMap.end() && ds_aitr!=attributeList.end())
    {
        if (this_aitr->first<ds_aitr->first)
        {

            // note attribute type = this_aitr->first
            AttributeStack& as = this_aitr->second;
            if (as.changed)
            {
                as.changed = false;
                if (!as.attributeVec.empty())
                {
                    const StateAttribute* new_attr = as.attributeVec.back().first;
                    applyAttributeOnTexUnit(unit,new_attr,as);
                }
                else
                {
                    applyGlobalDefaultAttributeOnTexUnit(unit,as);
                }
            }

            ++this_aitr;

        }
        else if (ds_aitr->first<this_aitr->first)
        {

            // ds_aitr->first is a new attribute, therefore
            // need to insert a new attribute entry for ds_aitr->first.
            AttributeStack& as = attributeMap[ds_aitr->first];

            const StateAttribute* new_attr = ds_aitr->second.first.get();
            applyAttributeOnTexUnit(unit,new_attr,as);

            as.changed = true;

            ++ds_aitr;

        }
        else
        {
            // this_mitr & ds_mitr refer to the same attribute, check the override
            // if any otherwise just apply the incoming attribute

            AttributeStack& as = this_aitr->second;

            if (!as.attributeVec.empty() && (as.attributeVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED))
            {
                // override is on, just treat as a normal apply on attribute.

                if (as.changed)
                {
                    as.changed = false;
                    const StateAttribute* new_attr = as.attributeVec.back().first;
                    applyAttributeOnTexUnit(unit,new_attr,as);
                }
            }
            else
            {
                // no override on or no previous entry, therefore consider incoming attribute.
                const StateAttribute* new_attr = ds_aitr->second.first.get();
                if (applyAttributeOnTexUnit(unit,new_attr,as))
                {
                    as.changed = true;
                }
            }

            ++this_aitr;
            ++ds_aitr;
        }
    }

    // iterator over the remaining state attributes to apply any previous changes.
    for(;
        this_aitr!=attributeMap.end();
        ++this_aitr)
    {
        // note attribute type = this_aitr->first
        AttributeStack& as = this_aitr->second;
        if (as.changed)
        {
            as.changed = false;
            if (!as.attributeVec.empty())
            {
                const StateAttribute* new_attr = as.attributeVec.back().first;
                applyAttributeOnTexUnit(unit,new_attr,as);
            }
            else
            {
                applyGlobalDefaultAttributeOnTexUnit(unit,as);
            }
        }
    }

    // iterator over the remaining incoming attribute to apply any new attribute.
    for(;
        ds_aitr!=attributeList.end();
        ++ds_aitr)
    {
        // ds_aitr->first is a new attribute, therefore
        // need to insert a new attribute entry for ds_aitr->first.
        AttributeStack& as = attributeMap[ds_aitr->first];

        const StateAttribute* new_attr = ds_aitr->second.first.get();
        applyAttributeOnTexUnit(unit,new_attr,as);

        // will need to update this attribute on next apply so set it to changed.
        as.changed = true;
    }

}

inline void State::applyUniformList(UniformMap& uniformMap,const StateSet::UniformList& uniformList)
{
    if (!_lastAppliedProgramObject) return;

    StateSet::UniformList::const_iterator ds_aitr=uniformList.begin();

    UniformMap::iterator this_aitr=uniformMap.begin();

    while (this_aitr!=uniformMap.end() && ds_aitr!=uniformList.end())
    {
        if (this_aitr->first<ds_aitr->first)
        {
            // note attribute type = this_aitr->first
            UniformStack& as = this_aitr->second;
            if (!as.uniformVec.empty())
            {
                _lastAppliedProgramObject->apply(*as.uniformVec.back().first);
            }

            ++this_aitr;

        }
        else if (ds_aitr->first<this_aitr->first)
        {
            _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get()));

            ++ds_aitr;
        }
        else
        {
            // this_mitr & ds_mitr refer to the same attribute, check the override
            // if any otherwise just apply the incoming attribute

            UniformStack& as = this_aitr->second;

            if (!as.uniformVec.empty() && (as.uniformVec.back().second & StateAttribute::OVERRIDE) && !(ds_aitr->second.second & StateAttribute::PROTECTED))
            {
                // override is on, just treat as a normal apply on uniform.
                _lastAppliedProgramObject->apply(*as.uniformVec.back().first);
            }
            else
            {
                // no override on or no previous entry, therefore consider incoming attribute.
                _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get()));
            }

            ++this_aitr;
            ++ds_aitr;
        }
    }

    // iterator over the remaining state attributes to apply any previous changes.
    for(;
        this_aitr!=uniformMap.end();
        ++this_aitr)
    {
        // note attribute type = this_aitr->first
        UniformStack& as = this_aitr->second;
        if (!as.uniformVec.empty())
        {
            _lastAppliedProgramObject->apply(*as.uniformVec.back().first);
        }
    }

    // iterator over the remaining incoming attribute to apply any new attribute.
    for(;
        ds_aitr!=uniformList.end();
        ++ds_aitr)
    {
        _lastAppliedProgramObject->apply(*(ds_aitr->second.first.get()));
    }

}

inline void State::applyModeMap(ModeMap& modeMap)
{
    for(ModeMap::iterator mitr=modeMap.begin();
        mitr!=modeMap.end();
        ++mitr)
    {
        // note GLMode = mitr->first
        ModeStack& ms = mitr->second;
        if (ms.changed)
        {
            ms.changed = false;
            if (!ms.valueVec.empty())
            {
                bool new_value = ms.valueVec.back() & StateAttribute::ON;
                applyMode(mitr->first,new_value,ms);
            }
            else
            {
                // assume default of disabled.
                applyMode(mitr->first,ms.global_default_value,ms);
            }

        }
    }
}

inline void State::applyModeMapOnTexUnit(unsigned int unit,ModeMap& modeMap)
{
    for(ModeMap::iterator mitr=modeMap.begin();
        mitr!=modeMap.end();
        ++mitr)
    {
        // note GLMode = mitr->first
        ModeStack& ms = mitr->second;
        if (ms.changed)
        {
            ms.changed = false;
            if (!ms.valueVec.empty())
            {
                bool new_value = ms.valueVec.back() & StateAttribute::ON;
                applyModeOnTexUnit(unit,mitr->first,new_value,ms);
            }
            else
            {
                // assume default of disabled.
                applyModeOnTexUnit(unit,mitr->first,ms.global_default_value,ms);
            }

        }
    }
}

inline void State::applyAttributeMap(AttributeMap& attributeMap)
{
    for(AttributeMap::iterator aitr=attributeMap.begin();
        aitr!=attributeMap.end();
        ++aitr)
    {
        AttributeStack& as = aitr->second;
        if (as.changed)
        {
            as.changed = false;
            if (!as.attributeVec.empty())
            {
                const StateAttribute* new_attr = as.attributeVec.back().first;
                applyAttribute(new_attr,as);
            }
            else
            {
                applyGlobalDefaultAttribute(as);
            }

        }
    }
}

inline void State::applyAttributeMapOnTexUnit(unsigned int unit,AttributeMap& attributeMap)
{
    for(AttributeMap::iterator aitr=attributeMap.begin();
        aitr!=attributeMap.end();
        ++aitr)
    {
        AttributeStack& as = aitr->second;
        if (as.changed)
        {
            as.changed = false;
            if (!as.attributeVec.empty())
            {
                const StateAttribute* new_attr = as.attributeVec.back().first;
                applyAttributeOnTexUnit(unit,new_attr,as);
            }
            else
            {
                applyGlobalDefaultAttributeOnTexUnit(unit,as);
            }

        }
    }
}

inline void State::applyUniformMap(UniformMap& uniformMap)
{
    if (!_lastAppliedProgramObject) return;

    for(UniformMap::iterator aitr=uniformMap.begin();
        aitr!=uniformMap.end();
        ++aitr)
    {
        UniformStack& as = aitr->second;
        if (!as.uniformVec.empty())
        {
            _lastAppliedProgramObject->apply(*as.uniformVec.back().first);
        }
    }
}

inline bool State::setActiveTextureUnit( unsigned int unit )
{
    if (unit!=_currentActiveTextureUnit)
    {
        if (_glActiveTexture && unit < (unsigned int)(maximum(_glMaxTextureCoords,_glMaxTextureUnits)) )
        {
            _glActiveTexture(GL_TEXTURE0+unit);
            _currentActiveTextureUnit = unit;
        }
        else
        {
            return unit==0;
        }
    }
    return true;
}

}

#endif