aboutsummaryrefslogtreecommitdiffstats
path: root/src/native/ogl/Canvas3D.c
blob: 146d53115ad64c1e9c3bfb4be63ee977f3e76fb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
/*
 * $RCSfile$
 *
 * Copyright (c) 2004 Sun Microsystems, Inc. All rights reserved.
 *
 * Use is subject to license terms.
 *
 * $Revision$
 * $Date$
 * $State$
 */

/*
 * Portions of this code were derived from work done by the Blackdown
 * group (www.blackdown.org), who did the initial Linux implementation
 * of the Java 3D API.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <jni.h>


#include "gldefs.h"

#ifdef DEBUG
/* Uncomment the following for VERBOSE debug messages */
/* #define VERBOSE */
#endif /* DEBUG */


#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE 1
#endif

#ifndef BOOL
#define BOOL int
#endif

static char *gl_VERSION;
static char *gl_VENDOR;
                         
void initializeCtxInfo(JNIEnv *env, GraphicsContextPropertiesInfo* ctxInfo);
void cleanupCtxInfo(GraphicsContextPropertiesInfo* ctxInfo);

/*
 * Class:     javax_media_j3d_Canvas3D
 * Method:    getTextureColorTableSize
 * Signature: ()I
 */
int getTextureColorTableSize(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    char *extensionStr,
    int minorVersion);


#ifdef WIN32
  extern HDC getMonitorDC(int screen);
#endif

/*
 * extract the version numbers
 * when return , numbers[0] contains major version number
 * numbers[1] contains minor version number
 */
void extractVersionInfo(char *versionStr, int* numbers){
    char *majorNumStr;
    char *minorNumStr;
    majorNumStr = strtok(versionStr, (char *)".");
    minorNumStr = strtok(0, (char *)".");
    if (majorNumStr != NULL)
	numbers[0] = atoi(majorNumStr);
    if (minorNumStr != NULL)
	numbers[1] = atoi(minorNumStr);

    /* fprintf(stderr, "majorNumStr = %d, minNumStr = %d \n", numbers[0], numbers[1]); */
    return; 
}

/*
 * check if the extension is supported
 */
int isExtensionSupported(const char *allExtensions, const char *extension)
{
    const char *start;
    const char *where, *terminator;

    /* Extension names should not have spaces. */
    where = (const char *) strchr(extension, ' ');
    if (where || *extension == '\0')
	return 0;
    
    /*
     * It takes a bit of care to be fool-proof about parsing the
     * OpenGL extensions string. Don't be fooled by sub-strings,
     * etc.
     */
    start = allExtensions;
    for (;;) {
	where = (const char *) strstr((const char *) start, extension);
	if (!where)
	    break;
	terminator = where + strlen(extension);
	if (where == start || *(where - 1) == ' ')
	    if (*terminator == ' ' || *terminator == '\0')
		return 1;
	start = terminator;
    }
    return 0;
}

void checkTextureExtensions(
    JNIEnv *env,
    jobject obj,
    char *tmpExtensionStr,
    int versionNumber,
    GraphicsContextPropertiesInfo* ctxInfo) {

    if(isExtensionSupported(tmpExtensionStr, "GL_ARB_multitexture")) {
	ctxInfo->arb_multitexture = JNI_TRUE ;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_MULTI_TEXTURE;
        glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &ctxInfo->textureUnitCount);

    }
    
    if(isExtensionSupported(tmpExtensionStr,"GL_SGI_texture_color_table" )){
	ctxInfo->textureColorTableAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COLOR_TABLE;

	/* get texture color table size */
	/* need to check later */
	ctxInfo->textureColorTableSize = getTextureColorTableSize(env, obj, (jlong)ctxInfo, tmpExtensionStr, versionNumber);
	if (ctxInfo->textureColorTableSize <= 0) {
	    ctxInfo->textureColorTableAvailable = JNI_FALSE;
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_COLOR_TABLE;
	}
	if (ctxInfo->textureColorTableSize > 256) {
	    ctxInfo->textureColorTableSize = 256;
	}
    }

    if(isExtensionSupported(tmpExtensionStr,"GL_ARB_texture_env_combine" )){
	ctxInfo->textureEnvCombineAvailable = JNI_TRUE;
	ctxInfo->textureCombineSubtractAvailable = JNI_TRUE;

	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COMBINE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COMBINE_SUBTRACT;
	ctxInfo->combine_enum = GL_COMBINE_ARB;
	ctxInfo->combine_add_signed_enum = GL_ADD_SIGNED_ARB;
	ctxInfo->combine_interpolate_enum = GL_INTERPOLATE_ARB;
	ctxInfo->combine_subtract_enum = GL_SUBTRACT_ARB;

    } else if(isExtensionSupported(tmpExtensionStr,"GL_EXT_texture_env_combine" )){
	ctxInfo->textureEnvCombineAvailable = JNI_TRUE;
	ctxInfo->textureCombineSubtractAvailable = JNI_FALSE;

	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COMBINE;
	ctxInfo->combine_enum = GL_COMBINE_EXT;
	ctxInfo->combine_add_signed_enum = GL_ADD_SIGNED_EXT;
	ctxInfo->combine_interpolate_enum = GL_INTERPOLATE_EXT;

	/* EXT_texture_env_combine does not include subtract */
	ctxInfo->combine_subtract_enum = 0;
    }

    if(isExtensionSupported(tmpExtensionStr,"GL_NV_register_combiners" )) {
	ctxInfo->textureRegisterCombinersAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_REGISTER_COMBINERS;
#if defined(SOLARIS) || defined(__linux__)
       ctxInfo->glCombinerInputNV =
         (MYPFNGLCOMBINERINPUTNV) glCombinerInputNV;
       ctxInfo->glFinalCombinerInputNV =
         (MYPFNGLFINALCOMBINERINPUTNV) glFinalCombinerInputNV;
       ctxInfo->glCombinerOutputNV =
         (MYPFNGLCOMBINEROUTPUTNV) glCombinerOutputNV;
       ctxInfo->glCombinerParameterfvNV =
         (MYPFNGLCOMBINERPARAMETERFVNV) glCombinerParameterfvNV;
       ctxInfo->glCombinerParameterivNV =
          (MYPFNGLCOMBINERPARAMETERIVNV) glCombinerParameterivNV;
       ctxInfo->glCombinerParameterfNV =
         (MYPFNGLCOMBINERPARAMETERFNV) glCombinerParameterfNV;
       ctxInfo->glCombinerParameteriNV =
         (MYPFNGLCOMBINERPARAMETERINV) glCombinerParameteriNV;
       if (ctxInfo->glCombinerInputNV == NULL ||
           ctxInfo->glFinalCombinerInputNV == NULL ||
           ctxInfo->glCombinerOutputNV == NULL ||
           ctxInfo->glCombinerParameterfvNV == NULL ||
           ctxInfo->glCombinerParameterivNV == NULL ||
           ctxInfo->glCombinerParameterfNV == NULL ||
           ctxInfo->glCombinerParameteriNV == NULL) {
            /* lets play safe: */
           ctxInfo->textureExtMask &=
                ~javax_media_j3d_Canvas3D_TEXTURE_REGISTER_COMBINERS;
           ctxInfo->textureRegisterCombinersAvailable = JNI_FALSE;
       }
#endif

#ifdef WIN32
	ctxInfo->glCombinerInputNV = 
	  (MYPFNGLCOMBINERINPUTNV) wglGetProcAddress("glCombinerInputNV");
	ctxInfo->glFinalCombinerInputNV = 
	  (MYPFNGLFINALCOMBINERINPUTNV) wglGetProcAddress("glFinalCombinerInputNV");
	ctxInfo->glCombinerOutputNV = 
	  (MYPFNGLCOMBINEROUTPUTNV) wglGetProcAddress("glCombinerOutputNV");
	ctxInfo->glCombinerParameterfvNV = 
	  (MYPFNGLCOMBINERPARAMETERFVNV) wglGetProcAddress("glCombinerParameterfvNV");
	ctxInfo->glCombinerParameterivNV = 
	  (MYPFNGLCOMBINERPARAMETERIVNV) wglGetProcAddress("glCombinerParameterivNV");
	ctxInfo->glCombinerParameterfNV = 
	  (MYPFNGLCOMBINERPARAMETERFNV) wglGetProcAddress("glCombinerParameterfNV");
	ctxInfo->glCombinerParameteriNV = 
	  (MYPFNGLCOMBINERPARAMETERINV) wglGetProcAddress("glCombinerParameteriNV");

	/*
	if (ctxInfo->glCombinerInputNV == NULL) {
	    printf("glCombinerInputNV == NULL\n");
	}
	if (ctxInfo->glFinalCombinerInputNV == NULL) {
	    printf("glFinalCombinerInputNV == NULL\n");
	}
	if (ctxInfo->glCombinerOutputNV == NULL) {
	    printf("ctxInfo->glCombinerOutputNV == NULL\n");
	}
	if (ctxInfo->glCombinerParameterfvNV == NULL) {
	    printf("ctxInfo->glCombinerParameterfvNV == NULL\n");
	}
	if (ctxInfo->glCombinerParameterivNV == NULL) {
	    printf("ctxInfo->glCombinerParameterivNV == NULL\n");
	}
	if (ctxInfo->glCombinerParameterfNV == NULL) {
	    printf("ctxInfo->glCombinerParameterfNV == NULL\n");
	}
	if (ctxInfo->glCombinerParameteriNV == NULL) {
	    printf("ctxInfo->glCombinerParameteriNV == NULL\n");
	}
	*/
	if ((ctxInfo->glCombinerInputNV == NULL) ||
	    (ctxInfo->glFinalCombinerInputNV == NULL) ||
	    (ctxInfo->glCombinerOutputNV == NULL) ||
	    (ctxInfo->glCombinerParameterfvNV == NULL) ||
	    (ctxInfo->glCombinerParameterivNV == NULL) ||
	    (ctxInfo->glCombinerParameterfNV == NULL) ||
	    (ctxInfo->glCombinerParameteriNV == NULL)) {
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_REGISTER_COMBINERS;	    
	    ctxInfo->textureRegisterCombinersAvailable = JNI_FALSE;
	}
	    
#endif

    }

    if(isExtensionSupported(tmpExtensionStr,"GL_ARB_texture_env_dot3" )) {
	ctxInfo->textureCombineDot3Available = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COMBINE_DOT3;
	ctxInfo->combine_dot3_rgb_enum = GL_DOT3_RGB_ARB;
	ctxInfo->combine_dot3_rgba_enum = GL_DOT3_RGBA_ARB;
    } else if(isExtensionSupported(tmpExtensionStr,"GL_EXT_texture_env_dot3" )) {
	ctxInfo->textureCombineDot3Available = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_COMBINE_DOT3;
	ctxInfo->combine_dot3_rgb_enum = GL_DOT3_RGB_EXT;
	ctxInfo->combine_dot3_rgba_enum = GL_DOT3_RGBA_EXT;
    }

    if (isExtensionSupported(tmpExtensionStr, "GL_ARB_texture_cube_map")) {
	ctxInfo->texture_cube_map_ext_enum = GL_TEXTURE_CUBE_MAP_ARB;
	ctxInfo->textureCubeMapAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_CUBE_MAP;
    } else if (isExtensionSupported(tmpExtensionStr, "GL_EXT_texture_cube_map")) {
	ctxInfo->texture_cube_map_ext_enum = GL_TEXTURE_CUBE_MAP_EXT;
	ctxInfo->textureCubeMapAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_CUBE_MAP;
    }

    if (isExtensionSupported(tmpExtensionStr, "GL_SGIS_sharpen_texture")) {
	ctxInfo->textureSharpenAvailable = JNI_TRUE;
        ctxInfo->linear_sharpen_enum = GL_LINEAR_SHARPEN_SGIS;
        ctxInfo->linear_sharpen_rgb_enum = GL_LINEAR_SHARPEN_COLOR_SGIS;
        ctxInfo->linear_sharpen_alpha_enum = GL_LINEAR_SHARPEN_ALPHA_SGIS;
 	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_SHARPEN;
#if defined(SOLARIS) || defined(__linux__)
	ctxInfo->glSharpenTexFuncSGIS = 
		(MYPFNGLSHARPENTEXFUNCSGI) glSharpenTexFuncSGIS;
#endif
#ifdef WIN32
	ctxInfo->glSharpenTexFuncSGIS = (MYPFNGLSHARPENTEXFUNCSGI) 
			wglGetProcAddress("glSharpenTexFuncSGIS");
	if (ctxInfo->glSharpenTexFuncSGIS == NULL) {
	    /*	    printf("ctxInfo->glSharpenTexFuncSGIS == NULL\n"); */
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_SHARPEN;
	    ctxInfo->textureSharpenAvailable = JNI_FALSE;
	}
#endif
    }

    if (isExtensionSupported(tmpExtensionStr, "GL_SGIS_detail_texture")) {
	ctxInfo->textureDetailAvailable = JNI_TRUE;
	ctxInfo->texture_detail_ext_enum = GL_DETAIL_TEXTURE_2D_SGIS;
        ctxInfo->linear_detail_enum = GL_LINEAR_DETAIL_SGIS;
        ctxInfo->linear_detail_rgb_enum = GL_LINEAR_DETAIL_COLOR_SGIS;
        ctxInfo->linear_detail_alpha_enum = GL_LINEAR_DETAIL_ALPHA_SGIS;
	ctxInfo->texture_detail_mode_enum = GL_DETAIL_TEXTURE_MODE_SGIS;
	ctxInfo->texture_detail_level_enum = GL_DETAIL_TEXTURE_LEVEL_SGIS;
 	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_DETAIL;
#if defined(SOLARIS) || defined(__linux__)
	ctxInfo->glDetailTexFuncSGIS = 
		(MYPFNGLDETAILTEXFUNCSGI) glDetailTexFuncSGIS;
#endif
#ifdef WIN32
	ctxInfo->glDetailTexFuncSGIS = (MYPFNGLDETAILTEXFUNCSGI) 
			wglGetProcAddress("glDetailTexFuncSGIS");
	if (ctxInfo->glDetailTexFuncSGIS == NULL) {
	    /*	    printf("ctxInfo->glDetailTexFuncSGIS == NULL\n"); */
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_DETAIL;	    
	    ctxInfo->textureDetailAvailable = JNI_FALSE;
	}
#endif
    }

    if (isExtensionSupported(tmpExtensionStr, "GL_SGIS_texture_filter4")) {
	ctxInfo->textureFilter4Available = JNI_TRUE;
        ctxInfo->filter4_enum = GL_FILTER4_SGIS;
 	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_FILTER4;
#if defined(SOLARIS) || defined(__linux__)
	ctxInfo->glTexFilterFuncSGIS = 
		(MYPFNGLTEXFILTERFUNCSGI) glTexFilterFuncSGIS;
#endif
#ifdef WIN32
	ctxInfo->glTexFilterFuncSGIS = (MYPFNGLTEXFILTERFUNCSGI) 
			wglGetProcAddress("glTexFilterFuncSGIS");
	if (ctxInfo->glTexFilterFuncSGIS == NULL) {
	    /*	    printf("ctxInfo->glTexFilterFuncSGIS == NULL\n"); */
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_FILTER4;	    
	    ctxInfo->textureFilter4Available = JNI_FALSE;
	}
#endif
    }

    if (isExtensionSupported(tmpExtensionStr, 
				"GL_EXT_texture_filter_anisotropic")) {
	ctxInfo->textureAnisotropicFilterAvailable = JNI_TRUE;
	ctxInfo->texture_filter_anisotropic_ext_enum = 
				GL_TEXTURE_MAX_ANISOTROPY_EXT;
        ctxInfo->max_texture_filter_anisotropy_enum =
				GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT;
	ctxInfo->textureExtMask |= 
			javax_media_j3d_Canvas3D_TEXTURE_ANISOTROPIC_FILTER;
    }

    if (isExtensionSupported(tmpExtensionStr,
				"GL_ARB_texture_border_clamp")) {
	ctxInfo->texture_clamp_to_border_enum = GL_CLAMP_TO_BORDER_ARB;
    } else if (isExtensionSupported(tmpExtensionStr,
				"GL_SGIS_texture_border_clamp")) {
	ctxInfo->texture_clamp_to_border_enum = GL_CLAMP_TO_BORDER_SGIS;
    } else {
	ctxInfo->texture_clamp_to_border_enum = GL_CLAMP;
    }
    
    if (isExtensionSupported(tmpExtensionStr,
				"GL_SGIX_texture_lod_bias")) {
	ctxInfo->textureLodBiasAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |=
			javax_media_j3d_Canvas3D_TEXTURE_LOD_OFFSET;
    }
}

BOOL getJavaBoolEnv(JNIEnv *env, char* envStr)
{
    JNIEnv table = *env;
    jclass cls;
    jfieldID fieldID;
    jobject obj;
    
    cls = (jclass) (*(table->FindClass))(env, "javax/media/j3d/VirtualUniverse");

    if (cls == NULL) {
	return FALSE;
    }
    
    fieldID = (jfieldID) (*(table->GetStaticFieldID))(env, cls, "mc",
						      "Ljavax/media/j3d/MasterControl;");
    if (fieldID == NULL) {
	return FALSE;	
    }

    obj = (*(table->GetStaticObjectField))(env, cls, fieldID);

    if (obj == NULL) {
	return FALSE;
    }

    cls = (jclass) (*(table->FindClass))(env, "javax/media/j3d/MasterControl");    

    if (cls == NULL) {
	return FALSE;
    }

    fieldID = (jfieldID) (*(table->GetFieldID))(env, cls, envStr, "Z");

    if (fieldID == NULL ) {
	return FALSE;
    }

    return (*(table->GetBooleanField))(env, obj, fieldID);
}


/*
 * get properties from current context
 */
BOOL getPropertiesFromCurrentContext(
    JNIEnv *env,
    jobject obj,
    GraphicsContextPropertiesInfo *ctxInfo,
    jlong hdc,
    int pixelFormat,
    long display,
    jlong vinfo)
{
    JNIEnv table = *env; 

    /* version and extension */
    char *glversion;
    char *extensionStr;
    char *tmpVersionStr;
    char *tmpExtensionStr;
    int   versionNumbers[2];
    char *cgHwStr = 0;
    int stencilSize;
    
#ifdef WIN32
    PFNWGLGETPIXELFORMATATTRIBIVEXTPROC wglGetPixelFormatAttribivEXT = NULL;
    PIXELFORMATDESCRIPTOR pfd;
    int attr[3];
    int piValues[2];
#endif
    
    /* get OpenGL version */
    glversion = (char *)glGetString(GL_VERSION);
    if (glversion == NULL) {
	fprintf(stderr, "glversion == null\n");
	return FALSE;
    }
    gl_VERSION = glversion;
    tmpVersionStr = strdup(glversion);
    gl_VENDOR = (char *)glGetString(GL_VENDOR);
    if (gl_VENDOR == NULL) {
        gl_VENDOR = "<unkown vendor>";
    }
    
    /* Get the extension */
    extensionStr = (char *)glGetString(GL_EXTENSIONS);
    if (extensionStr == NULL) {
        fprintf(stderr, "extensionStr == null\n");
        return FALSE;
    }
    tmpExtensionStr = strdup(extensionStr);
    
    ctxInfo->versionStr = strdup(glversion);
    ctxInfo->extensionStr = strdup(extensionStr);

    
    /* find out the version, major and minor version number */
    extractVersionInfo(tmpVersionStr, versionNumbers);

    /* *********************************************************/
    /* setup the graphics context properties */
    if (versionNumbers[1] >= 2) { /* check 1.2 core and above */
	/* 1.2 core */
        ctxInfo->rescale_normal_ext = JNI_TRUE;
	ctxInfo->rescale_normal_ext_enum = GL_RESCALE_NORMAL;
	ctxInfo->bgr_ext = JNI_TRUE;
	ctxInfo->bgr_ext_enum = GL_BGR;
	ctxInfo->texture3DAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_3D;
#if defined(SOLARIS) || defined(__linux__)
	ctxInfo->glTexImage3DEXT = (MYPFNGLTEXIMAGE3DPROC )glTexImage3D;
	ctxInfo->glTexSubImage3DEXT = (MYPFNGLTEXSUBIMAGE3DPROC )glTexSubImage3D;
#endif
#ifdef WIN32
	ctxInfo->glTexImage3DEXT = (MYPFNGLTEXIMAGE3DPROC )wglGetProcAddress("glTexImage3D");
	ctxInfo->glTexSubImage3DEXT = (MYPFNGLTEXSUBIMAGE3DPROC )wglGetProcAddress("glTexSubImage3D");
	if ((ctxInfo->glTexImage3DEXT == NULL) || (ctxInfo->glTexSubImage3DEXT == NULL)) {
	    ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_3D;
	    ctxInfo->texture3DAvailable = JNI_FALSE;
	}
#endif
	ctxInfo->texture_3D_ext_enum = GL_TEXTURE_3D;
	ctxInfo->texture_wrap_r_ext_enum = GL_TEXTURE_WRAP_R;
	ctxInfo->texture_clamp_to_edge_enum = GL_CLAMP_TO_EDGE;

	if(isExtensionSupported(tmpExtensionStr, "GL_ARB_imaging")){	
	    ctxInfo->blend_color_ext = JNI_TRUE;
	    ctxInfo->blendFunctionTable[7] = GL_CONSTANT_COLOR;
#if defined(SOLARIS) || defined(__linux__)
	    ctxInfo->glBlendColor = (MYPFNGLBLENDCOLORPROC )glBlendColor;
#endif
#ifdef WIN32	    
	    ctxInfo->glBlendColor = (MYPFNGLBLENDCOLORPROC )wglGetProcAddress("glBlendColor");
	    if (ctxInfo->glBlendColor == NULL) {
		ctxInfo->blend_color_ext = JNI_FALSE;
	    }
#endif
	}
	
	ctxInfo->seperate_specular_color = JNI_TRUE;
	ctxInfo->light_model_color_control_enum =  GL_LIGHT_MODEL_COLOR_CONTROL;
	ctxInfo->single_color_enum = GL_SINGLE_COLOR;
	ctxInfo->seperate_specular_color_enum =  GL_SEPARATE_SPECULAR_COLOR; 

	ctxInfo->textureLodAvailable = JNI_TRUE;
	ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_LOD_RANGE;
	ctxInfo->texture_min_lod_enum = GL_TEXTURE_MIN_LOD;
	ctxInfo->texture_max_lod_enum = GL_TEXTURE_MAX_LOD;
	ctxInfo->texture_base_level_enum = GL_TEXTURE_BASE_LEVEL;
	ctxInfo->texture_max_level_enum = GL_TEXTURE_MAX_LEVEL;

	/* ...  */
	
    } else { /* check 1.1 extension */
	if(isExtensionSupported(tmpExtensionStr,"GL_EXT_rescale_normal")){
   	    ctxInfo->rescale_normal_ext = JNI_TRUE;
	    ctxInfo->rescale_normal_ext_enum = GL_RESCALE_NORMAL_EXT;
	}
	if(isExtensionSupported(tmpExtensionStr,"GL_BGR_EXT")) {
	    ctxInfo->bgr_ext = 1;
	    ctxInfo->bgr_ext_enum = GL_BGR_EXT;
	}
	
	if(isExtensionSupported(tmpExtensionStr,"GL_EXT_texture3D" )){
	    ctxInfo->texture3DAvailable = JNI_TRUE;
	    ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_3D;
	    ctxInfo->texture_3D_ext_enum = GL_TEXTURE_3D_EXT;
	    ctxInfo->texture_wrap_r_ext_enum = GL_TEXTURE_WRAP_R_EXT;
#if defined(SOLARIS) || defined(__linux__)
	    ctxInfo->glTexImage3DEXT = (MYPFNGLTEXIMAGE3DPROC )glTexImage3DEXT;
	    ctxInfo->glTexSubImage3DEXT = (MYPFNGLTEXSUBIMAGE3DPROC )glTexSubImage3DEXT;
            /* Fallback to non-EXT variants, needed for older
               NVIDIA drivers which announce GL_EXT_texture3D but
               don't have the EXT variants */
           if (ctxInfo->glTexImage3DEXT == NULL ||
                ctxInfo->glTexSubImage3DEXT == NULL) {

                ctxInfo->glTexImage3DEXT =
                    (MYPFNGLTEXIMAGE3DPROC) glTexImage3D;
                ctxInfo->glTexSubImage3DEXT =
                    (MYPFNGLTEXSUBIMAGE3DPROC) glTexSubImage3D;

                if (ctxInfo->glTexImage3DEXT == NULL ||
                    ctxInfo->glTexSubImage3DEXT == NULL) {

                    ctxInfo->textureExtMask &=
                        ~javax_media_j3d_Canvas3D_TEXTURE_3D;
                    ctxInfo->texture3DAvailable = JNI_FALSE;
                }
            }

#endif
#ifdef WIN32
	    ctxInfo->glTexImage3DEXT = (MYPFNGLTEXIMAGE3DPROC )wglGetProcAddress("glTexImage3DEXT");
	    ctxInfo->glTexSubImage3DEXT = (MYPFNGLTEXSUBIMAGE3DPROC )wglGetProcAddress("glTexSubImage3DEXT");
	    if ((ctxInfo->glTexImage3DEXT == NULL) || (ctxInfo->glTexSubImage3DEXT == NULL)) {
		ctxInfo->textureExtMask &= ~javax_media_j3d_Canvas3D_TEXTURE_3D;
		ctxInfo->texture3DAvailable = JNI_FALSE;
	    }   
#endif	    
	}


	if(isExtensionSupported(tmpExtensionStr, "GL_EXT_texture_edge_clamp")) {
	    ctxInfo->texture_clamp_to_edge_enum = GL_CLAMP_TO_EDGE_EXT;
	} else if(isExtensionSupported(tmpExtensionStr, "GL_SGIS_texture_edge_clamp")) {
	    ctxInfo->texture_clamp_to_edge_enum = GL_CLAMP_TO_EDGE_SGIS;
	} else {
	    /* fallback to GL_CLAMP */
	    ctxInfo->texture_clamp_to_edge_enum = GL_CLAMP;
	}
	    

	if(isExtensionSupported(tmpExtensionStr, "GL_EXT_blend_color")){
	    ctxInfo->blend_color_ext = JNI_TRUE;
#if defined(SOLARIS) || defined(__linux__)
	    ctxInfo->glBlendColor = (MYPFNGLBLENDCOLOREXTPROC )glBlendColorEXT;
#endif
#ifdef WIN32	    
	    ctxInfo->glBlendColor = (MYPFNGLBLENDCOLOREXTPROC )wglGetProcAddress("glBlendColorEXT");
	    if (ctxInfo->glBlendColor == NULL) {
		ctxInfo->blend_color_ext = JNI_FALSE;
	    }
#endif
	    ctxInfo->blendFunctionTable[7] = GL_CONSTANT_COLOR_EXT;
	}
	
	if(isExtensionSupported(tmpExtensionStr,"GL_EXT_separate_specular_color" )){
	    ctxInfo->seperate_specular_color = JNI_TRUE;
	    ctxInfo->light_model_color_control_enum =  GL_LIGHT_MODEL_COLOR_CONTROL_EXT;
	    ctxInfo->single_color_enum = GL_SINGLE_COLOR_EXT;
	    ctxInfo->seperate_specular_color_enum =  GL_SEPARATE_SPECULAR_COLOR_EXT ;
	}

	if (isExtensionSupported(tmpExtensionStr,"GL_SGIS_texture_lod")) {
	    ctxInfo->textureLodAvailable = JNI_TRUE;
	    ctxInfo->textureExtMask |= javax_media_j3d_Canvas3D_TEXTURE_LOD_RANGE;
	    ctxInfo->texture_min_lod_enum = GL_TEXTURE_MIN_LOD_SGIS;
	    ctxInfo->texture_max_lod_enum = GL_TEXTURE_MAX_LOD_SGIS;
	    ctxInfo->texture_base_level_enum = GL_TEXTURE_BASE_LEVEL_SGIS;
	    ctxInfo->texture_max_level_enum = GL_TEXTURE_MAX_LEVEL_SGIS;
	}


  	/* ... */
    }


	
    /* check extensions for remaining of 1.1 and 1.2 */
    if(isExtensionSupported(tmpExtensionStr, "GL_EXT_multi_draw_arrays")){
	ctxInfo->multi_draw_arrays_ext = JNI_TRUE;
    }
    if(isExtensionSupported(tmpExtensionStr, "GL_SUN_multi_draw_arrays")){
	ctxInfo->multi_draw_arrays_sun = JNI_TRUE;
    }


    if (isExtensionSupported(tmpExtensionStr, "GL_EXT_compiled_vertex_array") &&
	getJavaBoolEnv(env, "isCompiledVertexArray")) {
	ctxInfo->compiled_vertex_array_ext = JNI_TRUE;
    }


    if(isExtensionSupported(tmpExtensionStr, "GLX_SUN_video_resize")){
	ctxInfo->videoResizeAvailable = JNI_TRUE;
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_SUN_VIDEO_RESIZE;
    }
    
    if(isExtensionSupported(tmpExtensionStr, "GL_SUN_global_alpha")){
	ctxInfo->global_alpha_sun = JNI_TRUE;
    }

    if(isExtensionSupported(tmpExtensionStr, "GL_SUNX_constant_data")){
	ctxInfo->constant_data_sun = JNI_TRUE;
    }

    if(isExtensionSupported(tmpExtensionStr, "GL_EXT_abgr")) {
	ctxInfo->abgr_ext = JNI_TRUE;
    }
    
    if(isExtensionSupported(tmpExtensionStr, "GL_ARB_transpose_matrix")) {
	ctxInfo->arb_transpose_matrix = JNI_TRUE;
    }

    if(isExtensionSupported(tmpExtensionStr, "GL_SUNX_geometry_compression")) {
	ctxInfo->geometry_compression_sunx = JNI_TRUE ;
    }
    
#if defined(SOLARIS) || defined(__linux__)
    /*
     * setup ARB_multisample, under windows this is setup in
     * NativeConfigTemplate when pixel format is choose
     */
    if (isExtensionSupported(tmpExtensionStr, "GL_ARB_multisample")){
	ctxInfo->arb_multisample = JNI_TRUE;

    }
#endif

#ifdef WIN32
    wglGetPixelFormatAttribivEXT = (PFNWGLGETPIXELFORMATATTRIBIVEXTPROC)
	wglGetProcAddress("wglGetPixelFormatAttribivARB");

    if (wglGetPixelFormatAttribivEXT == NULL) {
	wglGetPixelFormatAttribivEXT = (PFNWGLGETPIXELFORMATATTRIBIVEXTPROC)
	    wglGetProcAddress("wglGetPixelFormatAttribivEXT");
    } 

    ctxInfo->arb_multisample = JNI_FALSE;    
    if (wglGetPixelFormatAttribivEXT != NULL) {
	attr[0] = WGL_SAMPLE_BUFFERS_ARB;
	attr[1] = WGL_SAMPLES_ARB;
	attr[2] = 0;

	if (wglGetPixelFormatAttribivEXT((HDC) hdc, pixelFormat, 0, 2, attr, piValues)) {
	    if ((piValues[0] == TRUE) && (piValues[1] > 1)) {
		ctxInfo->arb_multisample = JNI_TRUE;
	    }
	} 
    }
#endif
    
    /*
     * Disable multisample by default since OpenGL will enable
     * it by default if the surface is multisample capable.
     */
    if (ctxInfo->arb_multisample && !ctxInfo->implicit_multisample) {
	glDisable(MULTISAMPLE_ARB);
    }
    /*
     * checking of the texture extensions is done in checkTextureExtensions(),
     * so that the same function can be used for queryContext as well
     */
    checkTextureExtensions(env, obj, tmpExtensionStr, versionNumbers[1],
				ctxInfo);



    
    /* ... */
    
    /* *********************************************************/
    /* Set up rescale_normal if extension supported */
    if (ctxInfo->rescale_normal_ext ) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_RESCALE_NORMAL;
    }

    /* Setup the multi_draw_array */
    if(ctxInfo->multi_draw_arrays_ext) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_MULTI_DRAW_ARRAYS;
    } else if (ctxInfo->multi_draw_arrays_sun) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_SUN_MULTI_DRAW_ARRAYS;
    }
    if(ctxInfo->compiled_vertex_array_ext) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_COMPILED_VERTEX_ARRAYS;
    }
    

    /* Setup GL_SUN_gloabl_alpha */
    if (ctxInfo->global_alpha_sun) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_SUN_GLOBAL_ALPHA;
    }

    /* Setup GL_SUNX_constant_data */
    if (ctxInfo->constant_data_sun) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_SUN_CONSTANT_DATA;
    }

    /* Setup GL_EXT_abgr */
    if (ctxInfo->abgr_ext) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_ABGR;
    }

    /* Setup GL_BGR_EXT */
    if (ctxInfo->bgr_ext) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_BGR;
    }

    /* Setup  GL_ARB_transpose_matrix */
    if (ctxInfo->arb_transpose_matrix) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_ARB_TRANSPOSE_MATRIX;
    }
    
    /*
     * Check for compressed geometry extensions and see if hardware
     * acceleration is supported in the runtime environment.
     */
    if (ctxInfo->geometry_compression_sunx) {
	cgHwStr = (char *)glGetString(GL_COMPRESSED_GEOM_ACCELERATED_SUNX) ;
    }

    if (cgHwStr == 0 || strstr(cgHwStr, " ")) {
	ctxInfo->geometry_compression_accelerated = 0 ;
       
    } else {
	char *tmp = strdup(cgHwStr) ;

	ctxInfo->geometry_compression_accelerated_major_version =
	    atoi(strtok(tmp, ".")) ;
	ctxInfo->geometry_compression_accelerated_minor_version =
	    atoi(strtok(0, ".")) ;
	ctxInfo->geometry_compression_accelerated_subminor_version =
	    atoi(strtok(0, ".")) ;

	free(tmp) ;
	ctxInfo->geometry_compression_accelerated = 1 ;
    }


    /* Setup GL_EXT_separate_specular_color */
    if(ctxInfo->seperate_specular_color) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_EXT_SEPARATE_SPECULAR_COLOR;
    }
    
    if (ctxInfo->constant_data_sun) {
	/*        glPixelStorei(GL_UNPACK_CONSTANT_DATA_SUNX, GL_TRUE); */
    }
    
    if(ctxInfo->arb_multisample) {
	ctxInfo->extMask |= javax_media_j3d_Canvas3D_ARB_MULTISAMPLE;
    }
    
    /* setup those functions pointers */
#ifdef WIN32
   
    if (ctxInfo->multi_draw_arrays_ext) {
	ctxInfo->glMultiDrawArraysEXT = (MYPFNGLMULTIDRAWARRAYSEXTPROC)wglGetProcAddress("glMultiDrawArraysEXT");
	ctxInfo->glMultiDrawElementsEXT = (MYPFNGLMULTIDRAWELEMENTSEXTPROC)wglGetProcAddress("glMultiDrawElementsEXT");
	if ((ctxInfo->glMultiDrawArraysEXT == NULL) ||
	    (ctxInfo->glMultiDrawElementsEXT == NULL)) {
	    ctxInfo->multi_draw_arrays_ext = JNI_FALSE;
	}
    }
    else if (ctxInfo->multi_draw_arrays_sun) {
	ctxInfo->glMultiDrawArraysEXT = (MYPFNGLMULTIDRAWARRAYSEXTPROC)wglGetProcAddress("glMultiDrawArraysSUN");
	ctxInfo->glMultiDrawElementsEXT = (MYPFNGLMULTIDRAWELEMENTSEXTPROC)wglGetProcAddress("glMultiDrawElementsSUN");
	if ((ctxInfo->glMultiDrawArraysEXT == NULL) ||
	    (ctxInfo->glMultiDrawElementsEXT == NULL)) {
	    ctxInfo->multi_draw_arrays_sun = JNI_FALSE;
	}
	    
    }
    if (ctxInfo->compiled_vertex_array_ext) {
	ctxInfo->glLockArraysEXT = (MYPFNGLLOCKARRAYSEXTPROC)wglGetProcAddress("glLockArraysEXT");
	ctxInfo->glUnlockArraysEXT = (MYPFNGLUNLOCKARRAYSEXTPROC)wglGetProcAddress("glUnlockArraysEXT");
	if ((ctxInfo->glLockArraysEXT == NULL) ||
	    (ctxInfo->glUnlockArraysEXT == NULL)) {
	    ctxInfo->compiled_vertex_array_ext = JNI_FALSE;
	}
    }

    if (ctxInfo->arb_multitexture) {
	ctxInfo->glClientActiveTextureARB = (MYPFNGLCLIENTACTIVETEXTUREARBPROC)wglGetProcAddress("glClientActiveTextureARB");
	ctxInfo->glMultiTexCoord2fvARB = (MYPFNGLMULTITEXCOORD2FVARBPROC)wglGetProcAddress("glMultiTexCoord2fvARB");
	ctxInfo->glMultiTexCoord3fvARB = (MYPFNGLMULTITEXCOORD3FVARBPROC)wglGetProcAddress("glMultiTexCoord3fvARB");
	ctxInfo->glMultiTexCoord4fvARB = (MYPFNGLMULTITEXCOORD4FVARBPROC)wglGetProcAddress("glMultiTexCoord4fvARB");
	ctxInfo->glActiveTextureARB = (MYPFNGLACTIVETEXTUREARBPROC) wglGetProcAddress("glActiveTextureARB");
	/*
	if (ctxInfo->glClientActiveTextureARB == NULL) {
	    printf("ctxInfo->glClientActiveTextureARB == NULL\n");
	}
	if (ctxInfo->glMultiTexCoord2fvARB == NULL) {
	    printf("ctxInfo->glMultiTexCoord2fvARB == NULL\n");
	}
	if (ctxInfo->glMultiTexCoord3fvARB == NULL) {
	    printf("ctxInfo->glMultiTexCoord3fvARB == NULL\n");
	}
	if (ctxInfo->glMultiTexCoord4fvARB == NULL) {
	    printf("ctxInfo->glMultiTexCoord4fvARB == NULL\n");
	}
	if (ctxInfo->glActiveTextureARB == NULL) {
	    printf("ctxInfo->glActiveTextureARB == NULL\n");
	}
	*/  
	if ((ctxInfo->glClientActiveTextureARB == NULL) ||
	    (ctxInfo->glMultiTexCoord2fvARB == NULL) ||
	    (ctxInfo->glMultiTexCoord3fvARB == NULL) ||
	    (ctxInfo->glMultiTexCoord4fvARB == NULL) ||
	    (ctxInfo->glActiveTextureARB == NULL)) {
	    ctxInfo->arb_multitexture = JNI_FALSE;
	}
    }
    
    if(ctxInfo->arb_transpose_matrix) {
	ctxInfo->glLoadTransposeMatrixdARB = (MYPFNGLLOADTRANSPOSEMATRIXDARBPROC)wglGetProcAddress("glLoadTransposeMatrixdARB");
	ctxInfo->glMultTransposeMatrixdARB = (MYPFNGLMULTTRANSPOSEMATRIXDARBPROC)wglGetProcAddress("glMultTransposeMatrixdARB");
	/*
	if (ctxInfo->glLoadTransposeMatrixdARB == NULL) {
	    printf("ctxInfo->glLoadTransposeMatrixdARB == NULL\n");
	}
	if (ctxInfo->glMultTransposeMatrixdARB == NULL) {
	    printf("ctxInfo->glMultTransposeMatrixdARB == NULL\n");
	}
	*/
	if ((ctxInfo->glLoadTransposeMatrixdARB == NULL) ||
	    (ctxInfo->glMultTransposeMatrixdARB == NULL)) {
	    ctxInfo->arb_transpose_matrix = JNI_FALSE;
	}
    }

    if (ctxInfo->global_alpha_sun) {
	ctxInfo->glGlobalAlphaFactorfSUN = (MYPFNGLGLOBALALPHAFACTORFSUNPROC )wglGetProcAddress("glGlobalAlphaFactorfSUN");

	if (ctxInfo->glGlobalAlphaFactorfSUN == NULL) {
	    /* printf("ctxInfo->glGlobalAlphaFactorfSUN == NULL\n");*/
	    ctxInfo->global_alpha_sun = JNI_FALSE;
	}
    }


    DescribePixelFormat((HDC) hdc, pixelFormat, sizeof(pfd), &pfd);

    stencilSize = pfd.cStencilBits;
#endif
    
#if defined(SOLARIS) || defined(__linux__)
    if(ctxInfo->multi_draw_arrays_ext) {
	ctxInfo->glMultiDrawArraysEXT = glMultiDrawArraysEXT;
	ctxInfo->glMultiDrawElementsEXT = glMultiDrawElementsEXT;
	if ((ctxInfo->glMultiDrawArraysEXT == NULL) ||
	    (ctxInfo->glMultiDrawElementsEXT == NULL)) {
	    ctxInfo->multi_draw_arrays_ext = JNI_FALSE;
	}
    }
    else if (ctxInfo->multi_draw_arrays_sun) {
	ctxInfo->glMultiDrawArraysEXT = glMultiDrawArraysSUN;
	ctxInfo->glMultiDrawElementsEXT = glMultiDrawElementsSUN;
	if ((ctxInfo->glMultiDrawArraysEXT == NULL) ||
	    (ctxInfo->glMultiDrawElementsEXT == NULL)) {
	    ctxInfo->multi_draw_arrays_ext = JNI_FALSE;
	}
    }
    if(ctxInfo->compiled_vertex_array_ext) {
	ctxInfo->glLockArraysEXT = glLockArraysEXT;
	ctxInfo->glUnlockArraysEXT = glUnlockArraysEXT;
	if ((ctxInfo->glLockArraysEXT == NULL) ||
	    (ctxInfo->glUnlockArraysEXT == NULL)) {
	    ctxInfo->compiled_vertex_array_ext = JNI_FALSE;
	}
    }
    
    if(ctxInfo->arb_multitexture){
	ctxInfo->glClientActiveTextureARB = glClientActiveTextureARB;
	ctxInfo->glMultiTexCoord2fvARB = glMultiTexCoord2fvARB;
	ctxInfo->glMultiTexCoord3fvARB = glMultiTexCoord3fvARB;
	ctxInfo->glMultiTexCoord4fvARB = glMultiTexCoord4fvARB;
	ctxInfo->glActiveTextureARB = glActiveTextureARB;
	if ((ctxInfo->glClientActiveTextureARB == NULL) ||
	    (ctxInfo->glMultiTexCoord2fvARB == NULL) ||
	    (ctxInfo->glMultiTexCoord3fvARB == NULL) ||
	    (ctxInfo->glMultiTexCoord4fvARB == NULL) ||
	    (ctxInfo->glActiveTextureARB == NULL)) {
	    ctxInfo->arb_multitexture = JNI_FALSE;
	}
    }
    if(ctxInfo->arb_transpose_matrix) {
	ctxInfo->glLoadTransposeMatrixdARB = glLoadTransposeMatrixdARB;
	ctxInfo->glMultTransposeMatrixdARB = glMultTransposeMatrixdARB; 
	if ((ctxInfo->glLoadTransposeMatrixdARB == NULL) ||
	    (ctxInfo->glMultTransposeMatrixdARB == NULL)) {
	    ctxInfo->arb_transpose_matrix = JNI_FALSE;
	}
    }
    if(ctxInfo->global_alpha_sun) {
	ctxInfo->glGlobalAlphaFactorfSUN = glGlobalAlphaFactorfSUN;
	if (ctxInfo->glGlobalAlphaFactorfSUN == NULL) {
	    ctxInfo->global_alpha_sun = JNI_FALSE;
	}
    }

    glXGetConfig((Display *) display, (XVisualInfo *) vinfo, GLX_STENCIL_SIZE, &stencilSize);
    
#endif

    if (stencilSize > 1) {
      ctxInfo->extMask |= javax_media_j3d_Canvas3D_STENCIL_BUFFER;
    }

    
    /* ... */
    
    /* clearing up the memory */
    free(tmpExtensionStr);
    free(tmpVersionStr);
    return TRUE;
}


/*
 * put properties to the java side
 */
void setupCanvasProperties(
    JNIEnv *env, 
    jobject obj,
    GraphicsContextPropertiesInfo *ctxInfo) 
{
    jclass cv_class;
    jfieldID rsc_field;
    JNIEnv table = *env;
    GLint param;
    
    cv_class =  (jclass) (*(table->GetObjectClass))(env, obj);
    
    /* set the canvas.multiTexAccelerated flag */
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "multiTexAccelerated", "Z");
    (*(table->SetBooleanField))(env, obj, rsc_field, ctxInfo->arb_multitexture);

    if (ctxInfo->arb_multitexture) {
	rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "numTexUnitSupported", "I");
	(*(table->SetIntField))(env, obj, rsc_field, ctxInfo->textureUnitCount);
	rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "numTexCoordSupported", "I");
	(*(table->SetIntField))(env, obj, rsc_field, ctxInfo->textureUnitCount);
    }
    
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "extensionsSupported", "I");
    (*(table->SetIntField))(env, obj, rsc_field, ctxInfo->extMask);

    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "textureExtendedFeatures", "I");
    (*(table->SetIntField))(env, obj, rsc_field, ctxInfo->textureExtMask);
    
    /* get texture color table size */
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "textureColorTableSize", "I");
    (*(table->SetIntField))(env, obj, rsc_field, ctxInfo->textureColorTableSize);
    
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "nativeGraphicsVersion", "Ljava/lang/String;");
    (*(table->SetObjectField))(env, obj, rsc_field, (*env)->NewStringUTF(env, ctxInfo->versionStr));

    if (ctxInfo->textureAnisotropicFilterAvailable) {

	float degree;

        glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &degree);
        rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "anisotropicDegreeMax", "F");
        (*(table->SetFloatField))(env, obj, rsc_field, degree);
    }

    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "textureBoundaryWidthMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, 1);

    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &param);
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "textureWidthMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, param);

    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "textureHeightMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, param);

    param = -1;
    glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &param);
    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "texture3DWidthMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, param);

    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "texture3DHeightMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, param);

    rsc_field = (jfieldID) (*(table->GetFieldID))(env, cv_class, "texture3DDepthMax", "I");
    (*(table->SetIntField))(env, obj, rsc_field, param);
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_destroyContext(
    JNIEnv *env,
    jclass cl,
    jlong display,
    jint window,
    jlong ctxInfo)
{
    GraphicsContextPropertiesInfo* s =  (GraphicsContextPropertiesInfo* )ctxInfo;
    jlong context = s->context;
    
#ifdef WIN32
    /*
     * It is possible the window is removed by removeNotify()
     * before the following is invoked :
     * wglMakeCurrent((HDC)window, NULL);
     * This will cause WinMe crash on swapBuffers()
     */
    wglDeleteContext((HGLRC)context);
#endif /* WIN32 */
    
#if defined(SOLARIS) || defined(__linux__)
    /*
    glXMakeCurrent((Display *)display, (GLXDrawable)window, NULL);
    */
    glXDestroyContext((Display *)display, (GLXContext)context);
#endif /* SOLARIS */
    /* cleanup CtxInfo and free its memory */
    cleanupCtxInfo(s); 
   
    free(s);
 
    
}

/*
 * A dummy WndProc for dummy window
 */
#ifdef WIN32
LONG WINAPI WndProc( HWND hWnd, UINT msg,
                     WPARAM wParam, LPARAM lParam )
{
            
    /* This function handles any messages that we didn't. */
    /* (Which is most messages) It belongs to the OS. */
    return DefWindowProc( hWnd, msg, wParam, lParam );
}
#endif /*end of WIN32 */




JNIEXPORT
jlong JNICALL Java_javax_media_j3d_Canvas3D_createContext(
    JNIEnv *env, 
    jobject obj, 
    jlong display,
    jint window, 
    jint vid,
    jlong visInfo,
    jlong sharedCtxInfo,
    jboolean isSharedCtx,
    jboolean offScreen)
{
    jlong gctx;
    jlong sharedCtx;

    static GLboolean first_time = GL_TRUE;
    static GLboolean force_normalize = GL_FALSE;
    
    GraphicsContextPropertiesInfo *ctxInfo = NULL;
    GraphicsContextPropertiesInfo *sharedCtxStructure;
    int PixelFormatID=0;
    
#if defined(SOLARIS) || defined(__linux__)
    GLXContext ctx;
    jlong hdc;
    
    if(sharedCtxInfo == 0)
	sharedCtx = 0;
    else {
	sharedCtxStructure = (GraphicsContextPropertiesInfo *)sharedCtxInfo;
	sharedCtx = sharedCtxStructure->context;
    }

    if (display == 0) {
	fprintf(stderr, "Canvas3D_createContext: display is null\n");
	ctx = NULL;
    }
    else if (visInfo == 0) {
	/*
	 * visInfo must be a valid pointer to an XVisualInfo struct returned
	 * by glXChooseVisual() for a physical screen.  The visual id in vid
	 * is not sufficient for handling OpenGL with Xinerama mode disabled:
	 * it doesn't distinguish between the physical screens making up the
	 * virtual screen when the X server is running in Xinerama mode.
	 */
	fprintf(stderr, "Canvas3D_createContext: visual is null\n");
	ctx = NULL;
    }
    else {
	ctx = glXCreateContext((Display *)display, (XVisualInfo *)visInfo,
	 		       (GLXContext)sharedCtx, True);
    }

    
    if (ctx == NULL) {
 	fprintf(stderr, "Canvas3D_createContext: couldn't create context\n");
	return 0;
    } 

    if (!glXMakeCurrent((Display *)display, (GLXDrawable)window, 
			(GLXContext)ctx)) {
        fprintf( stderr, "Canvas3D_createContext: couldn't make current\n");
        return 0;
    }

    gctx = (jlong)ctx;
#endif /* SOLARIS */

#ifdef WIN32
    HGLRC hrc; /* HW Rendering Context */
    HDC hdc;   /* HW Device Context */
    jboolean rescale = JNI_FALSE;
    JNIEnv table = *env;
    DWORD err;
    LPTSTR errString;

       
    static PIXELFORMATDESCRIPTOR pfd = {
	sizeof(PIXELFORMATDESCRIPTOR),
	1,                      /* Version number */
	PFD_DRAW_TO_WINDOW |
	PFD_SUPPORT_OPENGL|
	PFD_DOUBLEBUFFER,
	PFD_TYPE_RGBA,
	24,                     /* 24 bit color depth */
	0, 0, 0,                /* RGB bits and pixel sizes */
	0, 0, 0,                /* Do not care about them */
	0, 0,                   /* no alpha buffer info */
	0, 0, 0, 0, 0,          /* no accumulation buffer */
	32,                     /* 16 bit depth buffer */
	0,                      /* no stencil buffer */
	0,                      /* no auxiliary buffers */
	PFD_MAIN_PLANE,         /* layer type */
	0,                      /* reserved, must be 0 */
	0,                      /* no layer mask */
	0,                      /* no visible mask */
	0                       /* no damage mask */
    };

    jboolean result;

    /* hWnd = (HWND) window; */
    /* or could use: hDC = GetDC(hWnd); */
    
    if(sharedCtxInfo == 0)
	sharedCtx = 0;
    else {
	sharedCtxStructure = (GraphicsContextPropertiesInfo *)sharedCtxInfo;
	sharedCtx = sharedCtxStructure->context;
    }

    
    hdc =  (HDC) window;
    
    if (offScreen)  {
	pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL |
	    PFD_SUPPORT_GDI;
	vid = -1;
	sharedCtx = 0;
    }

    /* vid of -1 means no vid was specified - do the old way */
    if (vid == -1) {
	/* choose the "pixel format", terminology is equivalent */
	/* to UNIX "visual" */
	PixelFormatID = ChoosePixelFormat(hdc, &pfd);

	if(PixelFormatID == 0) {
	    fprintf(stderr,"\nERROR: pixel format ID = 0");
	    return 0;
	}
    }
    else {
	PixelFormatID = vid;
    }


    SetPixelFormat(hdc, PixelFormatID, &pfd);

    hrc = wglCreateContext( hdc );

    if (!hrc) {
	err = GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		      FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL, err, 0, (LPTSTR)&errString, 0, NULL);

	fprintf(stderr, "wglCreateContext Failed: %s\n", errString);
	return 0;
    }

    if (sharedCtx != 0) {
	wglShareLists( (HGLRC) sharedCtx, hrc );
    } 

    result = wglMakeCurrent(hdc, hrc);

    if (!result) {
	err = GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		      FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL, err, 0, (LPTSTR)&errString, 0, NULL);
	fprintf(stderr, "wglMakeCurrent Failed: %s\n", errString);
	return 0;
    }

    gctx = (jlong)hrc;
#endif /* WIN32 */

    /* allocate the structure */
    ctxInfo = (GraphicsContextPropertiesInfo *)malloc(sizeof(GraphicsContextPropertiesInfo));
    
    /* initialize the structure */
    initializeCtxInfo(env, ctxInfo);
    ctxInfo->context = gctx; 

    if (!getPropertiesFromCurrentContext(env, obj, ctxInfo, (jlong) hdc, PixelFormatID,  display, (jlong) visInfo)) {
	return 0;
    }


    /* setup structure */
    
    if(!isSharedCtx){
	/* Setup field in Java side */
	setupCanvasProperties(env, obj, ctxInfo);
    }
    
    /* Set up rescale_normal if extension supported */
    if (first_time && getJavaBoolEnv(env, "isForceNormalized")) {      
      force_normalize = GL_TRUE;
      first_time = GL_FALSE;
    }

    if (force_normalize) {
      /* Disable rescale normal */
      ctxInfo->rescale_normal_ext = GL_FALSE;      
    }
    
    if (ctxInfo->rescale_normal_ext ) {
        glEnable(ctxInfo->rescale_normal_ext_enum);
    }
    else {
        glEnable(GL_NORMALIZE);
    }

    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_COLOR_MATERIAL);
    glReadBuffer(GL_FRONT);
    return ((jlong)ctxInfo);
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_useCtx(
    JNIEnv *env, 
    jclass cl, 
    jlong ctxInfo,
    jlong display, 
    jint window)
{
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;
#if defined(SOLARIS) || defined(__linux__)
    glXMakeCurrent((Display *)display, (GLXDrawable)window, (GLXContext)ctx);
#endif

#ifdef WIN32
    wglMakeCurrent((HDC) window, (HGLRC) ctx);
#endif
}

JNIEXPORT
jint JNICALL Java_javax_media_j3d_Canvas3D_getNumCtxLights(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo)
{
    GLint nlights;

    glGetIntegerv(GL_MAX_LIGHTS, &nlights);
    return((jint)nlights);
}



JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_composite(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jint px,
    jint py,
    jint minX,
    jint minY,
    jint maxX,
    jint maxY,
    jint rasWidth,
    jbyteArray imageYdown,
    jint winWidth,
    jint winHeight)
{
    GLenum gltype;
    JNIEnv table;
    jbyte *byteData;
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;
    GLboolean tex3d, texCubeMap;
    
    table = *env;
   
#ifdef VERBOSE
    fprintf(stderr, "Canvas3D.composite()\n");
#endif
    /* temporarily disable fragment operations */
    /* TODO: the GL_TEXTURE_BIT may not be necessary */
    glPushAttrib(GL_ENABLE_BIT|GL_TEXTURE_BIT|GL_DEPTH_BUFFER_BIT);
    
    if(ctxProperties->texture3DAvailable) 
	tex3d = glIsEnabled(ctxProperties->texture_3D_ext_enum);

    if(ctxProperties->textureCubeMapAvailable) 
	texCubeMap = glIsEnabled(ctxProperties->texture_cube_map_ext_enum);
    
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_FOG);
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    if(ctxProperties->texture3DAvailable) 
	glDisable(ctxProperties->texture_3D_ext_enum);
    if(ctxProperties->textureCubeMapAvailable) 
	glDisable(ctxProperties->texture_cube_map_ext_enum);

    glEnable(GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    /* loaded identity modelview and projection matrix */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, (double)winWidth, 0.0, (double)winHeight, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    /* start from upper left corner */
    glRasterPos2i(px + minX, winHeight-(py + minY));
    
    glPixelZoom(1.0, -1.0);

    byteData = (jbyte *)(*(table->GetPrimitiveArrayCritical))(env,
							      imageYdown,
							      NULL);
    /* if abgr_ext is supported then the data will be in that format */
    if (ctxProperties->abgr_ext) {
	gltype = GL_ABGR_EXT;
    } else {
	gltype = GL_RGBA;
    }

    /*
     * set the actual width of data which is the width of the canvas
     * because what needs to be drawn may be smaller than the canvas
     */
    glPixelStorei(GL_UNPACK_ROW_LENGTH, rasWidth);

    /*
     * we only need to skip pixels if width of the area to draw is smaller
     * than the width of the raster
     */
    
    /*
     * skip this many rows in the data because the size of what
     * needs to be drawn may be smaller than the canvas
     */
    glPixelStorei(GL_UNPACK_SKIP_ROWS, minY);
    /*
     * skip this many pixels in the data before drawing because
     * the size of what needs to be drawn may be smaller than the
     * canvas
     */
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, minX);


    glDrawPixels(maxX - minX, maxY - minY,
		 gltype, GL_UNSIGNED_BYTE,  byteData);

    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
    
    glMatrixMode(GL_PROJECTION);

    glLoadIdentity();

    (*(table->ReleasePrimitiveArrayCritical))(env, imageYdown, byteData, 0);

    /* re-enable fragment operation if necessary */
    if(ctxProperties->texture3DAvailable)
	if (tex3d) glEnable(ctxProperties->texture_3D_ext_enum);
    
    if(ctxProperties->textureCubeMapAvailable)
	if (texCubeMap) glEnable(ctxProperties->texture_cube_map_ext_enum);
    
    /* Java 3D always clears the Z-buffer */
    glDepthMask(GL_TRUE);
    glClear(GL_DEPTH_BUFFER_BIT);

    glPopAttrib();
}


JNIEXPORT
jboolean JNICALL Java_javax_media_j3d_Canvas3D_initTexturemapping(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jint texWidth,
    jint texHeight,
    jint objectId)
{
    GraphicsContextPropertiesInfo *ctxProperties =
	(GraphicsContextPropertiesInfo *)ctxInfo;
    GLint gltype;
    GLint width;

    gltype = (ctxProperties->abgr_ext ? GL_ABGR_EXT : GL_RGBA);

    glBindTexture(GL_TEXTURE_2D, objectId);


    glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, texWidth,
		 texHeight, 0, gltype, GL_UNSIGNED_BYTE,  NULL);

    glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0,
			     GL_TEXTURE_WIDTH, &width);

    if (width <= 0) {
	return JNI_FALSE;
    }

    /* init texture size only without filling the pixels */
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth,
		 texHeight, 0, gltype, GL_UNSIGNED_BYTE,  NULL);


    return JNI_TRUE;
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_texturemapping(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jint px,
    jint py,
    jint minX,
    jint minY,
    jint maxX,
    jint maxY,
    jint texWidth,
    jint texHeight,
    jint rasWidth,
    jint format,
    jint objectId,
    jbyteArray imageYdown,
    jint winWidth,
    jint winHeight)
{
    JNIEnv table;
    GLint gltype;
    GLfloat texMinU,texMinV,texMaxU,texMaxV;
    GLfloat mapMinX,mapMinY,mapMaxX,mapMaxY;
    GLfloat halfWidth,halfHeight;
    jbyte *byteData;
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;
    GLboolean tex3d, texCubeMap;
    
    table = *env;
    gltype = GL_RGBA;
    
    /* temporary disable fragment operation */
    glPushAttrib(GL_ENABLE_BIT|GL_TEXTURE_BIT|GL_DEPTH_BUFFER_BIT);
    
    if (ctxProperties->texture3DAvailable) {
	tex3d = glIsEnabled(ctxProperties->texture_3D_ext_enum);
    }
    
    if (ctxProperties->textureCubeMapAvailable) {
	texCubeMap = glIsEnabled(ctxProperties->texture_cube_map_ext_enum);
    }
    glDisable(GL_ALPHA_TEST);
    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_FOG);
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);
    if (ctxProperties->texture3DAvailable) {
	glDisable(ctxProperties->texture_3D_ext_enum);
    }
    if (ctxProperties->textureCubeMapAvailable) {
	glDisable(ctxProperties->texture_cube_map_ext_enum);
    }
    /* glGetIntegerv(GL_TEXTURE_BINDING_2D,&binding); */
    glDepthMask(GL_FALSE);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glBindTexture(GL_TEXTURE_2D, objectId);
    /* set up texture parameter */
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

#ifdef VERBOSE
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
#endif
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_TEXTURE_2D);

    /* glGetIntegerv (GL_VIEWPORT, viewport); */

    /* loaded identity modelview and projection matrix */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0.0, (double)winWidth, 0.0, (double)winHeight,0.0, 0.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    byteData = (jbyte *)(*(table->GetPrimitiveArrayCritical))(env,
							      imageYdown,
							      NULL);

    if (ctxProperties->abgr_ext) {
	gltype = GL_ABGR_EXT;
    } else { 
	switch (format) {
	case FORMAT_BYTE_RGBA:
	    gltype = GL_RGBA;
	    break;
	case FORMAT_BYTE_RGB:
	    gltype = GL_RGB;
	    break;
	}
    }
    glPixelStorei(GL_UNPACK_ROW_LENGTH, rasWidth);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, minX);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, minY);
    glTexSubImage2D(GL_TEXTURE_2D, 0, minX, minY,
		    maxX - minX, maxY - minY,
		    gltype, GL_UNSIGNED_BYTE,
		    byteData);
    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);

    
    (*(table->ReleasePrimitiveArrayCritical))(env, imageYdown, byteData, 0);

    texMinU = (float) minX/ (float) texWidth; 
    texMinV = (float) minY/ (float) texHeight; 
    texMaxU = (float) maxX/ (float) texWidth;
    texMaxV = (float) maxY/ (float) texHeight; 
    halfWidth = (GLfloat)winWidth/2.0f;
    halfHeight = (GLfloat)winHeight/2.0f;

    mapMinX = (float) (((px + minX)- halfWidth)/halfWidth);
    mapMinY = (float) ((halfHeight - (py + maxY))/halfHeight);
    mapMaxX = (float) ((px + maxX - halfWidth)/halfWidth);
    mapMaxY = (float) ((halfHeight - (py + minY))/halfHeight);

#ifdef VERBOSE
    printf("(texMinU,texMinV,texMaxU,texMaxV) = (%3.2f,%3.2f,%3.2f,%3.2f)\n",
	   texMinU,texMinV,texMaxU,texMaxV);
    printf("(mapMinX,mapMinY,mapMaxX,mapMaxY) = (%3.2f,%3.2f,%3.2f,%3.2f)\n",
	   mapMinX,mapMinY,mapMaxX,mapMaxY);

#endif
    glBegin(GL_QUADS);

    glTexCoord2f(texMinU, texMaxV); glVertex2f(mapMinX,mapMinY);
    glTexCoord2f(texMaxU, texMaxV); glVertex2f(mapMaxX,mapMinY);
    glTexCoord2f(texMaxU, texMinV); glVertex2f(mapMaxX,mapMaxY);
    glTexCoord2f(texMinU, texMinV); glVertex2f(mapMinX,mapMaxY);
    glEnd();

    /* re-enable fragment operation if necessary */
    if (ctxProperties->texture3DAvailable)
	if (tex3d) glEnable(ctxProperties->texture_3D_ext_enum);
    
    if (ctxProperties->textureCubeMapAvailable)
	if (texCubeMap) glEnable(ctxProperties->texture_cube_map_ext_enum);


    /* Java 3D always clears the Z-buffer */
    glDepthMask(GL_TRUE);
    glClear(GL_DEPTH_BUFFER_BIT);
    glPopAttrib();
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_clear(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jfloat r, 
    jfloat g, 
    jfloat b,
    jint winWidth,
    jint winHeight, 
    jobject pa2d,
    jint imageScaleMode, 
    jbyteArray pixels_obj)

{
    jclass pa2d_class;
    jfieldID format_field, width_field, height_field;
    int format, width, height;
    GLubyte * pixels;
    JNIEnv table;
    GLenum gltype;
    float xzoom, yzoom, zoom;
    float rasterX, rasterY;
    int repeatX, repeatY, i, j;
    int row_length, skip_pixels, skip_rows, subwidth, subheight; 
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo; 
    jlong ctx = ctxProperties->context;
    table = *env;
   
#ifdef VERBOSE
    fprintf(stderr, "Canvas3D.clear()\n");
#endif
    
    if(!pa2d) {
	glClearColor((float)r, (float)g, (float)b, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT); 
    }
    else {
	GLboolean tex3d, texCubeMap;

	/* Do a cool image blit */
	pa2d_class = (jclass) (*(table->GetObjectClass))(env, pa2d);
	format_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class, 
							 "storedYdownFormat", "I");
	width_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class, 
							"width", "I");
	height_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class, 
							 "height", "I");

	format = (int) (*(table->GetIntField))(env, pa2d, format_field);
	width = (int) (*(table->GetIntField))(env, pa2d, width_field);
	height = (int) (*(table->GetIntField))(env, pa2d, height_field);

	pixels = (GLubyte *) (*(table->GetPrimitiveArrayCritical))(env, 
								   pixels_obj, NULL);

	/* temporarily disable fragment operations */
	/* TODO: the GL_TEXTURE_BIT may not be necessary */
	glPushAttrib(GL_ENABLE_BIT|GL_TEXTURE_BIT); 
	
	if(ctxProperties->texture3DAvailable)
	    tex3d = glIsEnabled(ctxProperties->texture_3D_ext_enum);

	if(ctxProperties->textureCubeMapAvailable)
	    texCubeMap = glIsEnabled(ctxProperties->texture_cube_map_ext_enum);

	glDisable(GL_ALPHA_TEST);                 
	glDisable(GL_BLEND);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_FOG);
	glDisable(GL_LIGHTING);
	glDisable(GL_TEXTURE_2D);
	if(ctxProperties->texture3DAvailable)
	    glDisable(ctxProperties->texture_3D_ext_enum);
	
	if(ctxProperties->textureCubeMapAvailable)
	    glDisable(ctxProperties->texture_cube_map_ext_enum);

	/* loaded identity modelview and projection matrix */
	glMatrixMode(GL_PROJECTION); 
	glLoadIdentity();
	glMatrixMode(GL_MODELVIEW); 
	glLoadIdentity();
	
	switch (format) {
        case FORMAT_BYTE_RGBA:
            gltype = GL_RGBA;
            break;
        case FORMAT_BYTE_RGB:
            gltype = GL_RGB;
            break;
	    
        case FORMAT_BYTE_ABGR:         
	    if (ctxProperties->abgr_ext) { /* If its zero, should never come here! */
		gltype = GL_ABGR_EXT;
	    }
	    break;
	    
        case FORMAT_BYTE_BGR:         
	    if (ctxProperties->bgr_ext) { /* If its zero, should never come here! */
		gltype = ctxProperties->bgr_ext_enum ;
	    }
	    break;
	    
        case FORMAT_BYTE_LA:
            gltype = GL_LUMINANCE_ALPHA;
            break;
        case FORMAT_BYTE_GRAY:
        case FORMAT_USHORT_GRAY:	    
            /* TODO: throw exception */
            break;
        }
	
	/* start from upper left corner */
	glRasterPos3f(-1.0, 1.0, 0.0);
	
	/* setup the pixel zoom */
	xzoom = (float)winWidth/width;
	yzoom = (float)winHeight/height;
	switch(imageScaleMode){
	case javax_media_j3d_Background_SCALE_NONE:
	     if(xzoom > 1.0f || yzoom > 1.0f)
		{
		/* else don't need to clear the background with background color */
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }
	    glPixelZoom(1.0, -1.0);
	    glDrawPixels(width, height, gltype, GL_UNSIGNED_BYTE,
			 pixels);

	    break;
	case javax_media_j3d_Background_SCALE_FIT_MIN:
	    if(xzoom != yzoom ) {
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }
	    zoom = xzoom < yzoom? xzoom:yzoom;
	    glPixelZoom(zoom, -zoom);
	    glDrawPixels(width, height, gltype, GL_UNSIGNED_BYTE,
			 pixels);

	    break;
	case javax_media_j3d_Background_SCALE_FIT_MAX:
	    zoom = xzoom > yzoom? xzoom:yzoom;
	    glPixelZoom(zoom, -zoom);
	    glDrawPixels(width, height, gltype, GL_UNSIGNED_BYTE,
			 pixels);

	    break;
	case javax_media_j3d_Background_SCALE_FIT_ALL:
	    glPixelZoom(xzoom, -yzoom);
	    glDrawPixels(width, height, gltype, GL_UNSIGNED_BYTE,
			 pixels);
	    break;
	case javax_media_j3d_Background_SCALE_REPEAT:	    
	    glPixelZoom(1.0, -1.0);
	    /* get those raster positions */
	    repeatX = winWidth/width;
	    if(repeatX * width < winWidth)
		repeatX++;
	    repeatY = winHeight/height;
	    if(repeatY * height < winHeight)
		repeatY++;
	    for(i = 0; i < repeatX; i++)
		for(j = 0; j < repeatY; j++) {
		    rasterX =  -1.0f + (float)width/winWidth * i * 2;
		    rasterY =  1.0f - (float)height/winHeight * j * 2;
		    glRasterPos3f(rasterX, rasterY, 0.0);
		    glDrawPixels(width, height, gltype, GL_UNSIGNED_BYTE,
			 pixels);
		}
	    break;
	        
	case javax_media_j3d_Background_SCALE_NONE_CENTER:
	    if(xzoom > 1.0f || yzoom > 1.0f){
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }
	    if(xzoom >= 1.0f){
		rasterX = -(float)width/winWidth;
		subwidth = width; 
	    }
	    else {
		rasterX = -1.0;
		row_length = width;
		glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
		skip_pixels = (width-winWidth)/2;
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels); 
		subwidth = winWidth;
	    }
	    if(yzoom >= 1.0f){
		rasterY = (float)height/winHeight;
		subheight = height; 
	    }
	    else {
		rasterY = 1.0f;
		skip_rows = (height-winHeight)/2;
		glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
		subheight = winHeight; 
	    } 
	    glRasterPos3f(rasterX, rasterY, 0.0);
	    glPixelZoom(1.0, -1.0);
	    glDrawPixels(subwidth, subheight, gltype, GL_UNSIGNED_BYTE,
			 pixels);
	    glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
	    glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
	    glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
	    break;
	}
	/* re-enable fragment operation if necessary */
	glPopAttrib();
		
	if(ctxProperties->texture3DAvailable)
	    if (tex3d) glEnable(ctxProperties->texture_3D_ext_enum);

	if(ctxProperties->textureCubeMapAvailable)
	    if (texCubeMap) glEnable(ctxProperties->texture_cube_map_ext_enum);

	(*(table->ReleasePrimitiveArrayCritical))(env, pixels_obj, 
						  (jbyte *)pixels, 0);
    }
    /* Java 3D always clears the Z-buffer */
    glPushAttrib(GL_DEPTH_BUFFER_BIT);
    glDepthMask(GL_TRUE);
    glClear(GL_DEPTH_BUFFER_BIT);
    glPopAttrib();
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_textureclear(JNIEnv *env,
							jobject obj,
							jlong ctxInfo,
							jint maxX, 
							jint maxY,
							jfloat r, 
							jfloat g, 
							jfloat b,
							jint winWidth,
							jint winHeight,
							jint objectId,
							jint imageScaleMode,
							jobject pa2d,
							jboolean update)
{ 
    jclass pa2d_class; 
    jfieldID pixels_field, format_field, width_field, height_field; 
    jbyteArray pixels_obj; 
    int format, width, height;
    GLubyte * pixels;  
    JNIEnv table; 
    GLenum gltype; 
    GLfloat texMinU, texMinV, texMaxU, texMaxV, adjustV; 
    GLfloat mapMinX, mapMinY, mapMaxX, mapMaxY; 
    GLfloat halfWidth, halfHeight; 
    float xzoom, yzoom, zoom;
    int i, j;
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo; 
    jlong ctx = ctxProperties->context;
    
    table = *env; 

    /* update = 1; */ 
    
#ifdef VERBOSE 
    fprintf(stderr, "Canvas3D.textureclear()\n");  
#endif 
    if(!pa2d){
	glClearColor((float)r, (float)g, (float)b, 1.0f); 
	glClear(GL_COLOR_BUFFER_BIT); 
    }
    /* glPushAttrib(GL_DEPTH_BUFFER_BIT); */
    if (pa2d) { 
	GLboolean tex3d, texCubeMap; 
	  
	
	/* Do a cool image blit */ 
	pa2d_class = (jclass) (*(table->GetObjectClass))(env, pa2d);

	pixels_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class, 
							 "imageYup", "[B"); 
	format_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class,  
							 "storedYupFormat", "I"); 
	pixels_obj = (jbyteArray)(*(table->GetObjectField))(env, pa2d,  
							pixels_field);
	
	width_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class,  
							"width", "I"); 
	height_field = (jfieldID) (*(table->GetFieldID))(env, pa2d_class,  
							 "height", "I");

	format = (int) (*(table->GetIntField))(env, pa2d, format_field); 
	width = (int) (*(table->GetIntField))(env, pa2d, width_field); 
	height = (int) (*(table->GetIntField))(env, pa2d, height_field);	
 	pixels = (GLubyte *) (*(table->GetPrimitiveArrayCritical))(env,   
 								   pixels_obj, NULL);

#ifdef VERBOSE
	fprintf(stderr, "width = %d height = %d \n", width, height);
#endif
	
	/* temporary disable fragment operation */ 
	glPushAttrib(GL_ENABLE_BIT|GL_TEXTURE_BIT|GL_POLYGON_BIT); 

	if(ctxProperties->texture3DAvailable) 
	    tex3d = glIsEnabled(ctxProperties->texture_3D_ext_enum);
	if(ctxProperties->textureCubeMapAvailable) 
	    texCubeMap = glIsEnabled(ctxProperties->texture_cube_map_ext_enum);
	glDisable(GL_ALPHA_TEST);                  
	glDisable(GL_BLEND); 
	glDisable(GL_DEPTH_TEST); 
	glDisable(GL_FOG); 
	glDisable(GL_LIGHTING);
	
	if(ctxProperties->texture3DAvailable)
	    glDisable(ctxProperties->texture_3D_ext_enum);
	
	if(ctxProperties->textureCubeMapAvailable)
	    glDisable(ctxProperties->texture_cube_map_ext_enum);
	
	Java_javax_media_j3d_Canvas3D_resetTexCoordGeneration(env, obj, ctxInfo); 

	glEnable(GL_TEXTURE_2D);

	/* reset the polygon mode */
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	glDepthMask(GL_FALSE);  
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1); 
	glBindTexture(GL_TEXTURE_2D, objectId);

	/* set up texture parameter */
	if(update){
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 
	    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 
	}
#ifdef VERBOSE 
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); 
#endif 
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
	
 	
	
	 if(update){
	    switch (format) { 
	    case FORMAT_BYTE_RGBA: 
		gltype = GL_RGBA;
#ifdef VERBOSE
		fprintf(stderr, "FORMAT_BYTE_RGBA\n");
#endif
		break; 
	    case FORMAT_BYTE_RGB: 
		gltype = GL_RGB;
#ifdef VERBOSE
		fprintf(stderr, "FORMAT_BYTE_RGB\n");
#endif
		break; 

		/* GL_ABGR_EXT */
	    case FORMAT_BYTE_ABGR:           
		if (ctxProperties->abgr_ext) { /* If its zero, should never come here! */  
		    gltype = GL_ABGR_EXT;  
		}  
		break;

		/* GL_BGR_EXT or GL_BGR */
	    case FORMAT_BYTE_BGR:           
		if (ctxProperties->bgr_ext) { /* If its zero, should never come here! */  
		    gltype = ctxProperties->bgr_ext_enum;  
		}  
		break;  
  
	    case FORMAT_BYTE_LA:  
		gltype = GL_LUMINANCE_ALPHA;  
		break;  
	    case FORMAT_BYTE_GRAY:  
	    case FORMAT_USHORT_GRAY:	       
		/* TODO: throw exception */  
		break;  
	    } 
	
	    /* texture map here! */ 
	    glTexImage2D(GL_TEXTURE_2D, 0, gltype, width,  
			 height, 0, gltype, GL_UNSIGNED_BYTE,  
			 pixels);
	}
	/* loaded identity modelview and projection matrix */ 
	glMatrixMode(GL_PROJECTION);  
	glLoadIdentity();
	glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
	glMatrixMode(GL_MODELVIEW);  
	glLoadIdentity(); 
	glMatrixMode(GL_TEXTURE);
	glPushMatrix();
	glLoadIdentity();

	xzoom = (float)winWidth/maxX;
	yzoom = (float)winHeight/maxY;
	switch(imageScaleMode) {
	case javax_media_j3d_Background_SCALE_NONE:
	    if(xzoom > 1.0f || yzoom > 1.0f){
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }
	    texMinU = 0.0f; 
	    texMinV = 0.0f; 
	    texMaxU = 1.0f; 
	    texMaxV = 1.0f;
	    halfWidth = (GLfloat)winWidth/2.0f;  
	    halfHeight = (GLfloat)winHeight/2.0f;  
	    mapMinX = (float) ((0 - halfWidth)/halfWidth);   
	    mapMinY = (float) ((0 - halfHeight)/halfHeight);
	    mapMaxX = (float) ((maxX - halfWidth)/halfWidth);    
	    mapMaxY = (float) ((maxY - halfHeight)/halfHeight);
	    adjustV = ((float)winHeight - (float)maxY)/halfHeight; 
	    mapMinY += adjustV;
	    mapMaxY += adjustV;
	    break;
	case javax_media_j3d_Background_SCALE_FIT_MIN:
	    if(xzoom != yzoom){
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }

	    zoom = xzoom < yzoom? xzoom: yzoom;
	    texMinU = 0.0f; 
	    texMinV = 0.0f; 
	    texMaxU = 1.0f; 
	    texMaxV = 1.0f;
	    mapMinX = -1.0f;
	    mapMaxY = 1.0f;
	    if(xzoom < yzoom){
		mapMaxX = 1.0f;
		mapMinY = -1.0f + 2.0f * ( 1.0f - zoom * (float)maxY/(float) winHeight );
	    } else {
		mapMaxX = -1.0f + zoom * (float)maxX/winWidth * 2;
		mapMinY = -1.0f;
	    }
	    break;
	case javax_media_j3d_Background_SCALE_FIT_MAX: 
	    zoom = xzoom > yzoom? xzoom: yzoom;
	    /*fprintf(stderr, "zoom: %f, xzoom: %f, yzoom: %f\n", zoom, xzoom, yzoom);*/
	    mapMinX = -1.0f;
	    mapMinY = -1.0f;
	    mapMaxX = 1.0f; 
	    mapMaxY = 1.0f;
	    if(xzoom < yzoom) {
		texMinU = 0.0f;
		texMinV = 0.0f;
		texMaxU = (float)winWidth/maxX/zoom; 
		texMaxV = 1.0f;
	    } else {
		texMinU = 0.0f;
		texMinV = 1.0f - (float)winHeight/maxY/zoom; 
		texMaxU = 1.0f;
		texMaxV = 1.0f;
	    }
	    break;
	case javax_media_j3d_Background_SCALE_FIT_ALL:
	    texMinU = 0.0f; 
	    texMinV = 0.0f; 
	    texMaxU = 1.0f; 
	    texMaxV = 1.0f;
	    mapMinX = -1.0f;
	    mapMinY = -1.0f;
	    mapMaxX = 1.0f; 
	    mapMaxY = 1.0f;   
	    break;
	case javax_media_j3d_Background_SCALE_REPEAT:
	    /* glScalef(1.0f, -1.0f, 1.0f); */
	    i = winWidth/width;
	    j = winHeight/height; 
	    texMinU = 0.0f;
	    texMinV = (float)(j + 1) - yzoom;
	    texMaxU = xzoom;
	    texMaxV = (float)(j + 1);
	    mapMinX = -1.0f;
	    mapMinY = -1.0f;
	    mapMaxX = 1.0f; 
	    mapMaxY = 1.0f;	    
	    break;
	case javax_media_j3d_Background_SCALE_NONE_CENTER:
	    if(xzoom > 1.0f || yzoom > 1.0f){
		glClearColor((float)r, (float)g, (float)b, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT); 
	    }
	    if(xzoom >= 1.0f){
		texMinU = 0.0f;
		texMaxU = 1.0f;
		mapMinX = -(float)maxX/winWidth;
		mapMaxX = (float)maxX/winWidth;
	    } else {
		texMinU = 0.5f - (float)winWidth/maxX/2;
		texMaxU = 0.5f + (float)winWidth/maxX/2;
		mapMinX = -1.0f;
		mapMaxX = 1.0f;
	    }
	    if(yzoom >= 1.0f) {
		texMinV = 0.0f;
		texMaxV = 1.0f;
		mapMinY = -(float)maxY/winHeight;
		mapMaxY = (float)maxY/winHeight;
	    }else {
		texMinV = 0.5f - (float)winHeight/maxY/2; 
		texMaxV = 0.5f + (float)winHeight/maxY/2;
		mapMinY = -1.0f;
		mapMaxY = 1.0f;	
	    }
	    break;
	}
#ifdef VERBOSE 
        printf("adjustV = %3.2f\n",adjustV);  
        printf("(texMinU,texMinV,texMaxU,texMaxV) = (%3.2f,%3.2f,%3.2f,%3.2f)\n", 
	       texMinU,texMinV,texMaxU,texMaxV); 
        printf("(mapMinX,mapMinY,mapMaxX,mapMaxY) = (%3.2f,%3.2f,%3.2f,%3.2f)\n", 
    	       mapMinX,mapMinY,mapMaxX,mapMaxY);
#endif


	glBegin(GL_QUADS); 
#ifdef VERBOSE	
	/* 	glTexCoord2f(0.2, 0.2); glVertex2f(0.0,0.0);  */
	/* 	glTexCoord2f(0.4, 0.2); glVertex2f(0.2,0.0);  */
	/* 	glTexCoord2f(0.4, 0.4); glVertex2f(0.2,0.2);  */
	/* 	glTexCoord2f(0.2, 0.4); glVertex2f(0.0,0.2); */
	glColor3f(1.0, 0.0, 0.0);
#endif
	glTexCoord2f(texMinU, texMinV); glVertex2f(mapMinX,mapMinY); 
	glTexCoord2f(texMaxU, texMinV); glVertex2f(mapMaxX,mapMinY); 
	glTexCoord2f(texMaxU, texMaxV); glVertex2f(mapMaxX,mapMaxY); 
	glTexCoord2f(texMinU, texMaxV); glVertex2f(mapMinX,mapMaxY);	
	glEnd(); 

	/* Restore texture Matrix transform */	
	glPopMatrix();
	
	glMatrixMode(GL_MODELVIEW);      	
	/* re-enable fragment operation if necessary */
	glPopAttrib();	
	if(ctxProperties->texture3DAvailable)
	    if (tex3d) glEnable(ctxProperties->texture_3D_ext_enum); 
	
	if(ctxProperties->textureCubeMapAvailable)
	    if (texCubeMap) glEnable(ctxProperties->texture_cube_map_ext_enum); 
	
	(*(table->ReleasePrimitiveArrayCritical))(env, pixels_obj,  
						  (jbyte *)pixels, 0); 
    }

    /* Java 3D always clears the Z-buffer */
    glPushAttrib(GL_DEPTH_BUFFER_BIT);
    glDepthMask(GL_TRUE);
    glClear(GL_DEPTH_BUFFER_BIT);
    glPopAttrib();
    
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_setRenderMode(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jint mode,
    jboolean dbEnable)
{
    GLint drawBuf;
    
    if (dbEnable) {
        drawBuf = GL_BACK;
        switch (mode) {
	case 0:				/* FIELD_LEFT */
	    drawBuf = GL_BACK_LEFT;
	    break;
	case 1:				/* FIELD_RIGHT */
	    drawBuf = GL_BACK_RIGHT;
	    break;
	case 2:				/* FIELD_ALL */
	    drawBuf = GL_BACK;
	    break;
        }
    }
    else {
        drawBuf = GL_FRONT;
        switch (mode) {
	case 0:                             /* FIELD_LEFT */
	    drawBuf = GL_FRONT_LEFT;
	    break;
	case 1:                             /* FIELD_RIGHT */
	    drawBuf = GL_FRONT_RIGHT;
	    break;
	case 2:                             /* FIELD_ALL */
	    drawBuf = GL_FRONT;
	    break;
        }
    }

#ifdef VERBOSE
    switch (drawBuf) {
    case GL_FRONT_LEFT:
        fprintf(stderr, "glDrawBuffer(GL_FRONT_LEFT)\n");
        break;
    case GL_FRONT_RIGHT:
        fprintf(stderr, "glDrawBuffer(GL_FRONT_RIGHT)\n");
        break;
    case GL_FRONT:
        fprintf(stderr, "glDrawBuffer(GL_FRONT)\n");
        break;
    case GL_BACK_LEFT:
	fprintf(stderr, "glDrawBuffer(GL_BACK_LEFT)\n");
	break;
    case GL_BACK_RIGHT:
	fprintf(stderr, "glDrawBuffer(GL_BACK_RIGHT)\n");
	break;
    case GL_BACK:
	fprintf(stderr, "glDrawBuffer(GL_BACK)\n");
	break;
    default:
	fprintf(stderr, "Unknown glDrawBuffer!!!\n");
	break;
    }
#endif

    glDrawBuffer(drawBuf);
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_clearAccum(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo)
{
    
    glClear(GL_ACCUM_BUFFER_BIT);

}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_accum(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jfloat value)
{
    
    glReadBuffer(GL_BACK);
    
    glAccum(GL_ACCUM, (float)value);

    glReadBuffer(GL_FRONT);

}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_accumReturn(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo)
{

    glAccum(GL_RETURN, 1.0);

}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_setDepthBufferWriteEnable(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jboolean mode)
{    
    if (mode)  
	glDepthMask(GL_TRUE);
    else
	glDepthMask(GL_FALSE);

}


JNIEXPORT
jint JNICALL Java_javax_media_j3d_Canvas3D_swapBuffers(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jlong display, 
    jint win)
{
    
#if defined(SOLARIS) || defined(__linux__)
   glXSwapBuffers((Display *)display, (Window)win);
   
#endif

#ifdef WIN32
   HDC hdc;

   hdc = (HDC) win;

   SwapBuffers(hdc);
#endif
  /*
   * It would be nice to do a glFinish here, but we can't do this
   * in the ViewThread Java thread in MT-aware OGL libraries without
   * switching from the ViewThread to the Renderer thread an extra time
   * per frame. Instead, we do glFinish after every rendering but before
   * swap in the Renderer thread.
   */
   /* glFinish(); */
   return 0;
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_syncRender(
      JNIEnv *env,
      jobject obj,
      jlong ctxInfo,
      jboolean waitFlag)  
{
	
    if (waitFlag == JNI_TRUE)
        glFinish();  
    else
	glFlush();
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_newDisplayList(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jint id)
{
    
    glNewList(id, GL_COMPILE);
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_endDisplayList(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo)
{
    
    glEndList();
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_setGlobalAlpha(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jfloat alpha)
{
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;
    
    /* GL_GLOBAL_ALPHA_SUN */
    if(ctxProperties->global_alpha_sun){
	glEnable(GL_GLOBAL_ALPHA_SUN);
	ctxProperties->glGlobalAlphaFactorfSUN(alpha);
    }
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_disableGlobalAlpha(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo)
{

    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;
	
    /* GL_GLOBAL_ALPHA_SUN */
    if(ctxProperties->global_alpha_sun){
	glDisable(GL_GLOBAL_ALPHA_SUN);
    }
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_callDisplayList(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    jint id,
    jboolean isNonUniformScale)
{
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo; 
    jlong ctx = ctxProperties->context;

    /* resale_normal_ext */
    if (ctxProperties->rescale_normal_ext && isNonUniformScale) {
	glEnable(GL_NORMALIZE);
    } 
    
    glCallList(id);

    if (ctxProperties->rescale_normal_ext && isNonUniformScale) {
	glDisable(GL_NORMALIZE);
    } 
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_freeDisplayList(
    JNIEnv *env,
    jclass cl,
    jlong ctxInfo,
    jint id)
{
    
    glDeleteLists(id, 1);
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_freeTexture(
    JNIEnv *env,
    jclass cl,
    jlong ctxInfo,
    jint id)
{    
    GLuint texObj;

    if(id > 0) {
	texObj = id;
	glDeleteTextures(1, &texObj);
    }
    else
	fprintf(stderr, "try to delete tex with texid <= 0. \n");
	
}



JNIEXPORT jint JNICALL Java_javax_media_j3d_Canvas3D_getTextureUnitCount(
    JNIEnv *env,
    jobject obj,
    jlong  ctxInfo)
{
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo; 
    
    return ctxProperties->textureUnitCount;
}

/*
 * Method:    getTextureColorTableSize
 */
int getTextureColorTableSize(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,
    char *extensionStr,
    int minorVersion)
{
    GraphicsContextPropertiesInfo* ctxProperties =  (GraphicsContextPropertiesInfo* )ctxInfo;
    int size;
    
    if(minorVersion >= 2 && isExtensionSupported(extensionStr, "GL_ARB_imaging")){
	
#ifdef WIN32
	ctxProperties->glColorTable = (MYPFNGLCOLORTABLEPROC)wglGetProcAddress("glColorTable");
	ctxProperties->glGetColorTableParameteriv =
	    (MYPFNGLGETCOLORTABLEPARAMETERIVPROC)wglGetProcAddress("glGetColorTableParameteriv");
#endif
#if defined(SOLARIS) || defined(__linux__)
	ctxProperties->glColorTable = glColorTable;
	ctxProperties->glGetColorTableParameteriv = glGetColorTableParameteriv;
#endif

    } else if(isExtensionSupported(extensionStr, "GL_SGI_color_table")) {
#ifdef WIN32	
	ctxProperties->glColorTable = (MYPFNGLCOLORTABLEPROC)wglGetProcAddress("glColorTableSGI");
        ctxProperties->glGetColorTableParameteriv =
                (MYPFNGLGETCOLORTABLEPARAMETERIVPROC)wglGetProcAddress("glGetColorTableParameterivSGI");
#endif
#if defined(SOLARIS) || defined(__linux__)
	ctxProperties->glColorTable = glColorTableSGI;
	ctxProperties->glGetColorTableParameteriv = glGetColorTableParameterivSGI; 
#endif
	
    } else {
	return 0;
    }

    if ((ctxProperties->glColorTable == NULL) ||
	(ctxProperties->glGetColorTableParameteriv == NULL)) {
	return 0;
    }
    
    ctxProperties->glColorTable(GL_PROXY_TEXTURE_COLOR_TABLE_SGI, GL_RGBA, 256, GL_RGB,
                                GL_INT,  NULL);
    ctxProperties->glGetColorTableParameteriv(GL_PROXY_TEXTURE_COLOR_TABLE_SGI,
                                GL_COLOR_TABLE_WIDTH_SGI, &size);
    return size;
}

/* we want to use this if available: */
#define GLX_SGIX_pbuffer 1

#ifndef GLX_VERSION_1_3
#ifdef GLX_SGIX_pbuffer
#ifdef __linux__
typedef XID GLXPbuffer;
typedef struct __GLXFBConfigRec *GLXFBConfig;
typedef struct __GLXFBConfigRec *GLXFBConfigSGIX;
extern GLXFBConfig * glXChooseFBConfig (Display *dpy, int screen, const int *attrib_list, int *nelements);
extern GLXPbuffer glXCreatePbuffer (Display *dpy, GLXFBConfig config, const int *attrib_list);
extern void glXDestroyPbuffer (Display *dpy, GLXPbuffer pbuf);
extern GLXFBConfigSGIX *glXChooseFBConfigSGIX(Display *dpy, int screen, const int *attribList, int *nitems);
extern GLXPbuffer glXCreateGLXPbufferSGIX(Display *dpy, GLXFBConfig config, unsigned int width, unsigned int height, const int *attribList);
extern void glXDestroyGLXPbufferSGIX(Display *dpy, GLXPbuffer pbuf);
#define GLX_DRAWABLE_TYPE               0x8010
#define GLX_PBUFFER_BIT                 0x00000004
#define GLX_RENDER_TYPE                 0x8011
#define GLX_RGBA_BIT                    0x00000001
#define GLX_MAX_PBUFFER_WIDTH           0x8016
#define GLX_MAX_PBUFFER_HEIGHT          0x8017
#define GLX_PRESERVED_CONTENTS          0x801B
#define GLX_PBUFFER_HEIGHT              0x8040  /* New for GLX 1.3 */
#define GLX_PBUFFER_WIDTH               0x8041  /* New for GLX 1.3 */
#define GLX_LARGEST_PBUFFER             0x801C
#define GLX_LARGEST_PBUFFER_SGIX        GLX_LARGEST_PBUFFER
#else

#define GLX_DRAWABLE_TYPE GLX_DRAWABLE_TYPE_SGIX
#define GLX_PBUFFER_BIT   GLX_PBUFFER_BIT_SGIX
#define GLX_RENDER_TYPE   GLX_RENDER_TYPE_SGIX
#define GLX_RGBA_BIT      GLX_RGBA_BIT_SGIX
#endif
#endif /* GLX_SGIX_pbuffer */
#else
#ifdef __linux__
typedef struct __GLXFBConfigRec *GLXFBConfigSGIX;
#endif /* __linux__ */
#endif /* GLX_VERSION_1_3 */

#if defined(SOLARIS) || defined(__linux__)
#pragma weak glXChooseFBConfig
#pragma weak glXCreatePbuffer
#pragma weak glXDestroyPbuffer
#pragma weak glXChooseFBConfigSGIX
#pragma weak glXCreateGLXPbufferSGIX
#pragma weak glXDestroyGLXPbufferSGIX
#endif /* SOLARIS */



/* For dvr support */
JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_videoResize(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jlong display, 
    jint win,
    jfloat dvrFactor)
{
    
#if defined(SOLARIS) || defined(__linux__)
    /* Not need to do ext. supported checking. This check is done in java. */

    /* fprintf(stderr, "Canvas3D.c -- glXVideoResize -- %d %f\n", win, dvrFactor); */
    glXVideoResizeSUN((Display *)display, (Window)win, (float) dvrFactor);
#endif

}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_videoResizeCompensation(
    JNIEnv *env, 
    jobject obj,
    jlong ctxInfo,
    jboolean enable)
{
    
#if defined(SOLARIS) || defined(__linux__)
    GraphicsContextPropertiesInfo *ctxProperties = 
	(GraphicsContextPropertiesInfo *)ctxInfo; 

    if (ctxProperties->videoResizeAvailable) {
	if(enable == JNI_TRUE) {
	    /* fprintf(stderr, "videoResizeCompensation - glEnable"); */
	    glEnable(GL_VIDEO_RESIZE_COMPENSATION_SUN);
	}
	else {
	    /* fprintf(stderr, "videoResizeCompensation - glDisable"); */
	    glDisable(GL_VIDEO_RESIZE_COMPENSATION_SUN);
	}
    }

#endif

}

JNIEXPORT
jint JNICALL Java_javax_media_j3d_Canvas3D_createOffScreenBuffer(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,    
    jlong display,
    jint vid,
    jint width,
    jint height)
{
    
#if defined(SOLARIS) || defined(__linux__)
   XVisualInfo *vinfo, template;
   int nitems, depth, redSize;
   Display *dpy;
   static GLboolean pbufferSupported = GL_FALSE;
   static GLboolean pbufferExtSupported = GL_FALSE;
   int major, minor;
   const char *extStr;
   int status;

   dpy = (Display *)display;

   if (dpy == NULL)
        dpy = XOpenDisplay(NULL);

   template.visualid = vid;
   vinfo = XGetVisualInfo(dpy, VisualIDMask, &template, &nitems);
   if (nitems != 1) {
      fprintf(stderr, "Warning Canvas3D_createContext got unexpected number of matching visuals %d\n", nitems);
   }

   glXGetConfig (dpy, vinfo, GLX_BUFFER_SIZE, &depth);
   glXGetConfig (dpy, vinfo, GLX_RED_SIZE, &redSize);

   if (status = glXQueryVersion(dpy, &major, &minor)) {

#if 0
       /* don't use the 1.3 pbuffer interface for now. */
	if ((major > 1) || (major == 1 && minor >= 3))
	    pbufferSupported = GL_TRUE;
	else 
#endif
	{
	    extStr = glXQueryExtensionsString(dpy, DefaultScreen(dpy));
	    if ((extStr != NULL) && (strstr(extStr, "GLX_SGIX_pbuffer"))) {
		pbufferExtSupported = GL_TRUE;
	    }
	}
   }

#if defined(GLX_VERSION_1_3) || defined(GLX_SGIX_pbuffer)
   if (pbufferExtSupported || pbufferSupported) {


        int attrCount, configAttr[10], numConfig, val;
        GLXPbuffer pbuff;

        /* Initialize the attribute list to be used for choosing FBConfig */
        attrCount = 0;
        configAttr[attrCount++] = GLX_DRAWABLE_TYPE;
        configAttr[attrCount++] = GLX_PBUFFER_BIT;
        configAttr[attrCount++] = GLX_RENDER_TYPE;
        configAttr[attrCount++] = GLX_RGBA_BIT;
        configAttr[attrCount++] = GLX_RED_SIZE;
        configAttr[attrCount++] = redSize;
        configAttr[attrCount++] = None;
/*
        configAttr[attrCount++] = GLX_DEPTH_SIZE;
        configAttr[attrCount++] = depth;
*/


#ifdef GLX_VERSION_1_3
	if (pbufferSupported) {
            GLXFBConfig *fbconfiglst;

            fbconfiglst = glXChooseFBConfig(dpy, DefaultScreen(dpy),
                        configAttr, &numConfig);

            if (numConfig < 1) {
                fprintf(stderr, "# of configs returned is %d\n", numConfig);
                return None;
            }

	    attrCount = 0;
            configAttr[attrCount++] = GLX_PBUFFER_WIDTH;
            configAttr[attrCount++] = width;
            configAttr[attrCount++] = GLX_PBUFFER_HEIGHT;
            configAttr[attrCount++] = height;
            configAttr[attrCount++] = GLX_PRESERVED_CONTENTS;
            configAttr[attrCount++] = GL_TRUE;
            configAttr[attrCount++] = None;
	

            pbuff = glXCreatePbuffer(dpy, fbconfiglst[0], configAttr);
	}
#endif /* GLX_VERSION_1_3 */

#ifdef GLX_SGIX_pbuffer
	if (pbufferExtSupported && !pbufferSupported) {
            GLXFBConfigSGIX *fbconfiglst;


            /* Determine what config to use according to config_attr */
            fbconfiglst = glXChooseFBConfigSGIX(dpy, DefaultScreen(dpy),
                        configAttr, &numConfig);

            if (numConfig < 1) {
                fprintf(stderr, "# of configs returned is %d\n", numConfig);
                return None;
            }

           attrCount = 0;
            configAttr[attrCount++] = GLX_PRESERVED_CONTENTS;
            configAttr[attrCount++] = GL_TRUE;
            configAttr[attrCount++] = None;
            pbuff = glXCreateGLXPbufferSGIX(dpy, fbconfiglst[0], width, height,
                        configAttr );
	}
#endif /* GLX_SGIX_pbuffer */
        if (pbuff == None) {
            fprintf(stderr, "glXCreateGLXPbuffer() returns None\n");
        }

        return pbuff;

   } else 
#endif /* GLX_VERSION_1_3 || GLX_SGIX_pbuffer */

   {
        Pixmap pixmap;
        GLXPixmap glxpixmap;

        /* fall back to pixmap */
        pixmap = XCreatePixmap(dpy, DefaultRootWindow(dpy), width, height, 
				vinfo->depth);

        glxpixmap = glXCreateGLXPixmap(dpy, vinfo, pixmap);
        if (glxpixmap == None) {
           fprintf(stderr, "glXCreateGLXPixmap() returns None\n");
        }

        return glxpixmap;
   }

#endif /* SOLARIS */

#ifdef WIN32
    int PixelFormatID=0;
    int dpy = (int)display;
    HDC hdc;          /* HW Device Context */
    jboolean rescale = JNI_FALSE;
    JNIEnv table = *env;
    
   HBITMAP hbitmap, oldhbitmap;

   BITMAPINFOHEADER bih;
   void *ppvBits;
   int err;
   LPTSTR errString;
   HDC hdcMonitor;

   /* create a DIB */
   memset(&bih, 0, sizeof(BITMAPINFOHEADER));

   bih.biSize = sizeof(BITMAPINFOHEADER);
   bih.biWidth = width;
   bih.biHeight = height;
   bih.biPlanes = 1;
   bih.biBitCount = 24;
   bih.biCompression = BI_RGB;

   /* create a new device context */

   if (dpy == 0) {
       hdc = CreateCompatibleDC(0);
   } else {
       /*
	* Should be getMonitorDC(screen)
        * but display and screen are the same under windows
        * They are return from NativeScreenInfo
	*/
       hdcMonitor = getMonitorDC((int) display);       
       hdc = CreateCompatibleDC(hdcMonitor);
       DeleteDC(hdcMonitor);
       
   }
   hbitmap = CreateDIBSection(hdc, (BITMAPINFO *)&bih,
				DIB_PAL_COLORS, &ppvBits, NULL, 0);

   if (!hbitmap) {
	err = GetLastError();
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_FROM_SYSTEM,
			NULL, err, 0, (LPTSTR)&errString, 0, NULL);
	fprintf(stderr, "CreateDIBSection failed: %s\n", errString);
   }

   oldhbitmap = SelectObject(hdc, hbitmap);

   /* Choosing and setting of pixel format is done in createContext */

   return ((jint)hdc);
#endif /* WIN32 */
}

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_destroyOffScreenBuffer(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,    
    jlong display,
    jint window)
{
#if defined(SOLARIS) || defined(__linux__)
   Display *dpy = (Display*)display;
     
   GLboolean pbufferSupported = GL_FALSE;
   GLboolean pbufferExtSupported = GL_TRUE;
   int major, minor;
   char *extStr;

   if (glXQueryVersion(dpy, &major, &minor)) {

#if 0
       /* don't use the 1.3 pbuffer interface for now. */
	if ((major > 1) || (major == 1 && minor >= 3))
	    pbufferSupported = GL_TRUE;
	else 
#endif
	{
	    extStr = (char *)glXQueryExtensionsString(dpy, 
		DefaultScreen(dpy));
	    if ((extStr != NULL) && (strstr(extStr, "GLX_SGIX_pbuffer"))) {
		pbufferExtSupported = GL_TRUE;
	    }
	}
   }

#if defined(GLX_VERSION_1_3) || defined(GLX_SGIX_pbuffer)
   
   if (pbufferSupported) {
	glXDestroyPbuffer(dpy, (GLXPbuffer)window);
   } else if (pbufferExtSupported) {
	glXDestroyGLXPbufferSGIX(dpy, (GLXPbuffer)window);
   } else
#endif
 
   {
	glXDestroyGLXPixmap(dpy, (GLXPixmap)window);
   }
#endif /* SOLARIS */

#ifdef WIN32
   HBITMAP oldhbitmap;
   HDC hdc = (HDC) window;

   oldhbitmap = SelectObject(hdc, NULL);
   DeleteObject(oldhbitmap);
   DeleteDC(hdc);
#endif /* WIN32 */
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_readOffScreenBuffer(
    JNIEnv *env,
    jobject obj,
    jlong ctxInfo,    
    jint format,
    jint width,
    jint height)
{
    JNIEnv table = *env;
    jclass cv_class;
    jfieldID byteData_field;
    jbyteArray byteData_array;
    jbyte *byteData;
    int type;
    
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo; 
    jlong ctx = ctxProperties->context;

    glPixelStorei(GL_PACK_ROW_LENGTH, width);
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    cv_class =  (jclass) (*(table->GetObjectClass))(env, obj);
    byteData_field = (jfieldID) (*(table->GetFieldID))(env, cv_class,
                                        "byteBuffer", "[B");
    byteData_array = (jbyteArray)(*(table->GetObjectField))(env, obj,
                                        byteData_field);
    byteData = (jbyte *)(*(table->GetPrimitiveArrayCritical))(env,
                                        byteData_array, NULL);

       
    switch (format) {
    case FORMAT_BYTE_RGBA:
	type = GL_RGBA;
	break;
    case FORMAT_BYTE_RGB:
	type = GL_RGB;
	break;
	
	/* GL_ABGR_EXT */
    case FORMAT_BYTE_ABGR:         
	if (ctxProperties->abgr_ext) { /* If its zero, should never come here! */
	    type = GL_ABGR_EXT;
	}
	break;

	/* GL_BGR_EXT */
    case FORMAT_BYTE_BGR:         
	if (ctxProperties->bgr_ext) { /* If its zero, should never come here! */
	    type = ctxProperties->bgr_ext_enum;
	}
	break;
	
    case FORMAT_BYTE_LA:
	type = GL_LUMINANCE_ALPHA;
	break;
    case FORMAT_BYTE_GRAY:
    case FORMAT_USHORT_GRAY:	    
	/* TODO: throw exception */
	break;
    }
  

    glReadPixels(0, 0, width, height, type, GL_UNSIGNED_BYTE, byteData);

    (*(table->ReleasePrimitiveArrayCritical))(env, byteData_array,
                byteData, 0);
}

void initializeCtxInfo(JNIEnv *env , GraphicsContextPropertiesInfo* ctxInfo){
    ctxInfo->context = 0; 
    
    /* version and extension info */
    ctxInfo->versionStr = NULL;
    ctxInfo->extensionStr = NULL;
    ctxInfo->versionNumbers[0] = 1;
    ctxInfo->versionNumbers[1] = 1; 

    /* both in 1.2 core part and 1.1 extensions */
    ctxInfo->rescale_normal_ext = JNI_FALSE;
    ctxInfo->bgr_ext = JNI_FALSE;
    ctxInfo->texture3DAvailable = JNI_FALSE;
    ctxInfo->seperate_specular_color = JNI_FALSE;
    
    /* 1.2 and GL_ARB_imaging */
    ctxInfo->blend_color_ext = JNI_FALSE;
    ctxInfo->color_table_ext = JNI_FALSE;    
    ctxInfo->blendFunctionTable[0] = GL_ZERO;
    ctxInfo->blendFunctionTable[1] = GL_ONE;
    ctxInfo->blendFunctionTable[2] = GL_SRC_ALPHA;
    ctxInfo->blendFunctionTable[3] = GL_ONE_MINUS_SRC_ALPHA;
    ctxInfo->blendFunctionTable[4] = GL_DST_COLOR;
    ctxInfo->blendFunctionTable[5] = GL_SRC_COLOR;
    ctxInfo->blendFunctionTable[6] = GL_ONE_MINUS_SRC_COLOR;
    ctxInfo->blendFunctionTable[7] = GL_SRC_COLOR;

    /* 1.1 extensions or 1.2 extensions */
    /* sun extensions */
    ctxInfo->multi_draw_arrays_sun = JNI_FALSE;
    ctxInfo->compiled_vertex_array_ext = JNI_FALSE;

    ctxInfo->videoResizeAvailable = JNI_FALSE;
    ctxInfo->global_alpha_sun = JNI_FALSE;
    ctxInfo->constant_data_sun = JNI_FALSE;
    ctxInfo->geometry_compression_sunx = JNI_FALSE;
    
    /* EXT extensions */
    ctxInfo->abgr_ext = JNI_FALSE;

    ctxInfo->multi_draw_arrays_ext = JNI_FALSE;

    ctxInfo->implicit_multisample = getJavaBoolEnv(env, "implicitAntialiasing");

    /* ARB extensions */
    ctxInfo->arb_transpose_matrix = JNI_FALSE;
    ctxInfo->arb_multitexture = JNI_FALSE;

    ctxInfo->arb_multisample = JNI_FALSE;
    ctxInfo->textureUnitCount = 1;
    ctxInfo->textureEnvCombineAvailable = JNI_FALSE;
    ctxInfo->textureCombineDot3Available = JNI_FALSE;
    ctxInfo->textureCombineSubtractAvailable = JNI_FALSE;
    ctxInfo->textureCubeMapAvailable = JNI_FALSE;

    /* NV extensions */
    ctxInfo->textureRegisterCombinersAvailable = JNI_FALSE;

    /* SGI extensions */
    ctxInfo->textureSharpenAvailable = JNI_FALSE;
    ctxInfo->textureDetailAvailable = JNI_FALSE;
    ctxInfo->textureFilter4Available = JNI_FALSE;
    ctxInfo->textureAnisotropicFilterAvailable = JNI_FALSE;
    ctxInfo->textureColorTableAvailable = JNI_FALSE;
    ctxInfo->textureColorTableSize = 0;
    ctxInfo->textureLodAvailable = JNI_FALSE;
    ctxInfo->textureLodBiasAvailable = JNI_FALSE;
    
    ctxInfo->geometry_compression_accelerated = JNI_FALSE;
    ctxInfo->geometry_compression_accelerated_major_version = 0;
    ctxInfo->geometry_compression_accelerated_minor_version = 0;
    ctxInfo->geometry_compression_accelerated_subminor_version = 0;

    /* extension mask */
    ctxInfo->extMask = 0;
    ctxInfo->textureExtMask = 0;

    ctxInfo->glBlendColor = NULL;
    ctxInfo->glBlendColorEXT = NULL;    
    ctxInfo->glColorTable =  NULL;
    ctxInfo->glGetColorTableParameteriv =  NULL;
    ctxInfo->glTexImage3DEXT = NULL;
    ctxInfo->glTexSubImage3DEXT = NULL;
    ctxInfo->glClientActiveTextureARB =   NULL;
    ctxInfo->glMultiDrawArraysEXT =  NULL;
    ctxInfo->glMultiDrawElementsEXT =  NULL;
    ctxInfo->glLockArraysEXT =  NULL;
    ctxInfo->glUnlockArraysEXT =  NULL;
    ctxInfo->glMultiTexCoord2fvARB = NULL;
    ctxInfo->glMultiTexCoord3fvARB = NULL;
    ctxInfo->glMultiTexCoord4fvARB = NULL;
    ctxInfo->glLoadTransposeMatrixdARB = NULL;
    ctxInfo->glMultTransposeMatrixdARB = NULL;
    ctxInfo->glActiveTextureARB = NULL;
    ctxInfo->glGlobalAlphaFactorfSUN = NULL;

    ctxInfo->glCombinerInputNV = NULL;
    ctxInfo->glCombinerOutputNV = NULL;
    ctxInfo->glFinalCombinerInputNV = NULL;
    ctxInfo->glCombinerParameterfvNV = NULL;
    ctxInfo->glCombinerParameterivNV= NULL;
    ctxInfo->glCombinerParameterfNV = NULL;
    ctxInfo->glCombinerParameteriNV = NULL;

    ctxInfo->glSharpenTexFuncSGIS = NULL;
    ctxInfo->glDetailTexFuncSGIS = NULL;
    ctxInfo->glTexFilterFuncSGIS = NULL;
}

void cleanupCtxInfo(GraphicsContextPropertiesInfo* ctxInfo){
    if( ctxInfo->versionStr != NULL)
	free(ctxInfo->versionStr);
    if( ctxInfo->extensionStr != NULL)
	free(ctxInfo->extensionStr);
    ctxInfo->versionStr = NULL;
    ctxInfo->extensionStr = NULL;
}

#ifdef WIN32
HWND createDummyWindow(const char* szAppName) {
    static char szTitle[]="A Simple C OpenGL Program";
    WNDCLASS wc;   /* windows class sruct */
   
    HWND hWnd; 

    /* Fill in window class structure with parameters that */
    /*  describe the main window. */

    wc.style         =
	CS_HREDRAW | CS_VREDRAW;/* Class style(s). */
    wc.lpfnWndProc   = 
	(WNDPROC)WndProc;      /* Window Procedure */
    wc.cbClsExtra    = 0;     /* No per-class extra data. */
    wc.cbWndExtra    = 0;     /* No per-window extra data. */
    wc.hInstance     =
	NULL;            /* Owner of this class */
    wc.hIcon         = NULL;  /* Icon name */
    wc.hCursor       =
	NULL;/* Cursor */
    wc.hbrBackground = 
	(HBRUSH)(COLOR_WINDOW+1);/* Default color */
    wc.lpszMenuName  = NULL;  /* Menu from .RC */
    wc.lpszClassName =
	szAppName;            /* Name to register as

				 /* Register the window class */
    
    if(RegisterClass( &wc )==0)
	fprintf(stdout, "Couldn't register class\n");
  
    /* Create a main window for this application instance. */

    hWnd = CreateWindow(
			szAppName, /* app name */
			szTitle,   /* Text for window title bar */
			WS_OVERLAPPEDWINDOW/* Window style */
			/* NEED THESE for OpenGL calls to work!*/
			| WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
			CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
			NULL,     /* no parent window */
			NULL,     /* Use the window class menu.*/
			NULL,     /* This instance owns this window */
			NULL      /* We don't use any extra data */
			);

    /* If window could not be created, return zero */
    if ( !hWnd ){
	fprintf(stdout, "Couldn't Create window\n");
	return NULL;
    }
    return hWnd; 
}
#endif

JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_createQueryContext(
    JNIEnv *env,
    jobject obj,
    jlong display,
    jint window,
    jint vid,
    jboolean offScreen,
    jint width,
    jint height)
{
    JNIEnv table = *env;
    jlong gctx;
    long newWin;
    int PixelFormatID=0;
    GraphicsContextPropertiesInfo* ctxInfo = (GraphicsContextPropertiesInfo *)malloc(sizeof(GraphicsContextPropertiesInfo)); 
	
#if defined(SOLARIS) || defined(__linux__)
    XVisualInfo *vinfo, template;
    int nitems;
    GLXContext ctx;
    int result;
    Window root;
    Window glWin; 
    XSetWindowAttributes win_attrs;
    Colormap		cmap;
    unsigned long	win_mask;
    jlong hdc;
    
    template.visualid = vid;
    vinfo = XGetVisualInfo((Display *)display, VisualIDMask, &template, &nitems);
    if (nitems != 1) {
	fprintf(stderr, "Warning Canvas3D_createQueryContext got unexpected number of matching visuals %d\n", nitems);
    }

    ctx = glXCreateContext((Display *)display, vinfo, NULL, True);
    if (ctx == NULL) {
	fprintf(stderr, "Error Canvas3D_createQueryContext: couldn't create context.\n");
    }
   
   
    /* create window if window == 0 and offscreen == true */
    if(window == 0 && !offScreen) {
     
	root = RootWindow((Display *)display, vinfo->screen);
    
	/* Create a colormap */
	cmap = XCreateColormap((Display *)display, root, vinfo->visual, AllocNone);

	/* Create a window */
	win_attrs.colormap = cmap;
	win_attrs.border_pixel = 0;
	win_attrs.event_mask = KeyPressMask | ExposureMask | StructureNotifyMask;
	win_mask = CWColormap | CWBorderPixel | CWEventMask;
	glWin = XCreateWindow((Display *)display, root, 0, 0, width, height, 0, vinfo->depth,
			      InputOutput, vinfo->visual, win_mask, &win_attrs);
	newWin = (unsigned long)glWin; 
    }
    else if(window == 0 && offScreen){
	newWin = Java_javax_media_j3d_Canvas3D_createOffScreenBuffer( env, obj, 0, display, vid, width, height);
    }
    else if(window != 0) {
	newWin = window;
    }

    result = glXMakeCurrent((Display *)display, (GLXDrawable)newWin, (GLXContext)ctx);
    if (result == GL_FALSE)
	fprintf(stderr, "glXMakeCurrent fails\n");
    gctx = (jlong)ctx;
#endif

#ifdef WIN32
    HGLRC hrc;        /* HW Rendering Context */
    HDC hdc;          /* HW Device Context */
    DWORD err;
    LPTSTR errString;
    HWND hWnd;
    static char szAppName[] = "OpenGL";
    jlong vinfo = 0;
    
    static PIXELFORMATDESCRIPTOR pfd = {
	sizeof(PIXELFORMATDESCRIPTOR),
	1,                      /* Version number */
	PFD_DRAW_TO_WINDOW |
	PFD_SUPPORT_OPENGL|
	PFD_DOUBLEBUFFER,
	PFD_TYPE_RGBA,
	24,                     /* 24 bit color depth */
	0, 0, 0,                /* RGB bits and pixel sizes */
	0, 0, 0,                /* Donnot care about them  */
	0, 0,                   /* no alpha buffer info */
	0, 0, 0, 0, 0,          /* no accumulation buffer */
	32,                     /* 16 bit depth buffer */
	0,                      /* no stencil buffer */
	0,                      /* no auxiliary buffers */
	PFD_MAIN_PLANE,         /* layer type */
	0,                      /* reserved, must be 0 */
	0,                      /* no layer mask */
	0,                      /* no visible mask */
	0                       /* no damage mask */
    };

    jboolean result;

    /* onscreen rendering and window is 0 now */
    if(window == 0 && !offScreen){
	hWnd = createDummyWindow((const char *)szAppName);
	if (!hWnd)
	    return; 
	hdc =  GetDC(hWnd);
    }
    else if(window == 0 && offScreen){
	hdc = (HDC)Java_javax_media_j3d_Canvas3D_createOffScreenBuffer( env, obj, 0, display, vid, width, height);
	pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL |
	    PFD_SUPPORT_GDI;
	vid = -1;
    }
    else if(window != 0 && offScreen){
	pfd.dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_OPENGL |
	    PFD_SUPPORT_GDI;
	vid = -1;
	hdc =  (HDC) window;
    }
    else if(window !=0 && !offScreen){
	hdc =  (HDC) window;
    }

    newWin = (int)hdc;
   
    /* vid of -1 means no vid was specified - do the old way */
    if (vid == -1) {
	/*
	 * choose the "pixel format", terminology is equivalent
	 * to UNIX "visual"
	 */
	PixelFormatID = ChoosePixelFormat(hdc, &pfd);

	if(PixelFormatID == 0) {
	    fprintf(stderr,"\nERROR: pixel format ID = 0");
	    return; 
	}
    }
    else
	PixelFormatID = vid;

    SetPixelFormat(hdc, PixelFormatID, &pfd);

    hrc = wglCreateContext( hdc );
    
    if (!hrc) {
	err = GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		      FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL, err, 0, (LPTSTR)&errString, 0, NULL);

	fprintf(stderr, "wglCreateContext Failed: %s\n", errString);
    }


    result = wglMakeCurrent(hdc, hrc);

    if (!result) {
	err = GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		      FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL, err, 0, (LPTSTR)&errString, 0, NULL);
	fprintf(stderr, "wglMakeCurrent Failed: %s\n", errString);
    }

    gctx = (jlong)hrc;

#endif

    initializeCtxInfo(env, ctxInfo);
    ctxInfo->context = gctx;
    
    /* get current context properties */
    if (getPropertiesFromCurrentContext(env, obj, ctxInfo, (jlong) hdc, PixelFormatID, display, (jlong) vinfo)) {
	/* put the properties to the Java side */
	setupCanvasProperties(env, obj, ctxInfo);
    }


    /* clear up the context , colormap and window if appropriate */
    if(window == 0 && !offScreen){
#if defined(SOLARIS) || defined(__linux__)
	Java_javax_media_j3d_Canvas3D_destroyContext(env, obj, display, newWin, (jlong)ctxInfo); 
	XDestroyWindow((Display *)display, glWin);
	XFreeColormap((Display *)display, cmap);
#endif /* SOLARIS */
#ifdef WIN32
	/* Release DC */
	ReleaseDC(hWnd, hdc);
	/* Destroy context */
	/* This will free ctxInfo also */
	Java_javax_media_j3d_Canvas3D_destroyContext(env, obj, display,newWin, (jlong)ctxInfo);
	DestroyWindow(hWnd);
	UnregisterClass(szAppName, (HINSTANCE)NULL);
#endif /* WIN32 */
    }
    else if(window == 0 && offScreen) {
	Java_javax_media_j3d_Canvas3D_destroyOffScreenBuffer(env, obj, gctx, display, newWin);
	Java_javax_media_j3d_Canvas3D_destroyContext(env, obj, display, newWin, (jlong)ctxInfo);
    }
    else if(window != 0){
	Java_javax_media_j3d_Canvas3D_destroyContext(env, obj, display, newWin, (jlong)ctxInfo);
    }
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_beginScene(
       JNIEnv *env,
       jobject obj, 
       jlong ctxInfo)
{
 /* Not used by OGL version */
}


JNIEXPORT
void JNICALL Java_javax_media_j3d_Canvas3D_endScene(
       JNIEnv *env,
       jobject obj, 
       jlong ctxInfo)
{
    /* This function is a no-op */
    /*
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    */
}

/* Setup the multisampling for full scene antialiasing */
JNIEXPORT void JNICALL Java_javax_media_j3d_Canvas3D_setFullSceneAntialiasing
(JNIEnv *env, jobject obj, jlong ctxInfo, jboolean enable)
{
    GraphicsContextPropertiesInfo *ctxProperties = (GraphicsContextPropertiesInfo *)ctxInfo;
    jlong ctx = ctxProperties->context;

    if (ctxProperties->arb_multisample && !ctxProperties->implicit_multisample) {
	if(enable == JNI_TRUE) {
	    glEnable(MULTISAMPLE_ARB);
	}
	else {
	    glDisable(MULTISAMPLE_ARB);

	}
    }
    
}


/*
 * Return false if <= 8 bit color under windows
 */
JNIEXPORT
jboolean JNICALL Java_javax_media_j3d_Canvas3D_validGraphicsMode(
       JNIEnv *env,
       jobject obj) 
{
#ifdef WIN32
    DEVMODE devMode;
    
    EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode);
    return (devMode.dmBitsPerPel > 8);
#endif

#if defined(SOLARIS) || defined(__linux__)
    return TRUE;
#endif
}