summaryrefslogtreecommitdiffstats
path: root/src/mesa/drivers/windows/gldirect/dglwgl.c
blob: c46cfe162f95d32cd96ac5b8f5244c989ba94a49 (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
/****************************************************************************
*
*                        Mesa 3-D graphics library
*                        Direct3D Driver Interface
*
*  ========================================================================
*
*   Copyright (C) 1991-2004 SciTech Software, Inc. All rights reserved.
*
*   Permission is hereby granted, free of charge, to any person obtaining a
*   copy of this software and associated documentation files (the "Software"),
*   to deal in the Software without restriction, including without limitation
*   the rights to use, copy, modify, merge, publish, distribute, sublicense,
*   and/or sell copies of the Software, and to permit persons to whom the
*   Software is furnished to do so, subject to the following conditions:
*
*   The above copyright notice and this permission notice shall be included
*   in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
*   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
*   SCITECH SOFTWARE INC BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
*   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
*   OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*   SOFTWARE.
*
*  ======================================================================
*
* Language:     ANSI C
* Environment:  Windows 9x (Win32)
*
* Description:  OpenGL window  functions (wgl*).
*
****************************************************************************/

#include "dglwgl.h"
#ifdef _USE_GLD3_WGL
#include "gld_driver.h"
#endif

#include "gl/glu.h"	// MUST USE MICROSOFT'S GLU32!

#ifndef _USE_GLD3_WGL
extern DGL_mesaFuncs mesaFuncs;
#endif

// Need to export wgl* functions if using GLD3,
// otherwise export GLD2 DGL_* functions.
#ifdef _USE_GLD3_WGL
#define _GLD_WGL_EXPORT(a) wgl##a
#else
#define _GLD_WGL_EXPORT(a) DGL_##a
#endif

// Calls into Mesa 4.x are different
#ifdef _USE_GLD3_WGL
#include "dlist.h"
#include "drawpix.h"
#include "get.h"
#include "matrix.h"
// NOTE: All the _GLD* macros now call the gl* functions direct.
//       This ensures that the correct internal pathway is taken. KeithH
#define _GLD_glNewList		glNewList
#define _GLD_glBitmap		glBitmap
#define _GLD_glEndList		glEndList
#define _GLD_glDeleteLists	glDeleteLists
#define _GLD_glGetError		glGetError
#define _GLD_glTranslatef	glTranslatef
#define _GLD_glBegin		glBegin
#define _GLD_glVertex2fv	glVertex2fv
#define _GLD_glEnd			glEnd
#define _GLD_glNormal3f		glNormal3f
#define _GLD_glVertex3f		glVertex3f
#define _GLD_glVertex3fv	glVertex3fv
#else // _USE_GLD3_WGL
#define _GLD_glNewList		(*mesaFuncs.glNewList)
#define _GLD_glBitmap		(*mesaFuncs.glBitmap)
#define _GLD_glEndList		(*mesaFuncs.glEndList)
#define _GLD_glDeleteLists	(*mesaFuncs.glDeleteLists)
#define _GLD_glGetError		(*mesaFuncs.glGetError)
#define _GLD_glTranslatef	(*mesaFuncs.glTranslatef)
#define _GLD_glBegin		(*mesaFuncs.glBegin)
#define _GLD_glVertex2fv	(*mesaFuncs.glVertex2fv)
#define _GLD_glEnd			(*mesaFuncs.glEnd)
#define _GLD_glNormal3f		(*mesaFuncs.glNormal3f)
#define _GLD_glVertex3f		(*mesaFuncs.glVertex3f)
#define _GLD_glVertex3fv	(*mesaFuncs.glVertex3fv)
#endif // _USE_GLD3_WGL

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

// Emulate SGI DDK calls.
#define __wglMalloc(a) GlobalAlloc(GPTR, (a))
#define __wglFree(a) GlobalFree((a))

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

// Mesa glu.h and MS glu.h call these different things...
//#define GLUtesselator GLUtriangulatorObj
//#define GLU_TESS_VERTEX_DATA GLU_VERTEX_DATA

// For wglFontOutlines

typedef GLUtesselator *(APIENTRY *gluNewTessProto)(void);
typedef void (APIENTRY *gluDeleteTessProto)(GLUtesselator *tess);
typedef void (APIENTRY *gluTessBeginPolygonProto)(GLUtesselator *tess, void *polygon_data);
typedef void (APIENTRY *gluTessBeginContourProto)(GLUtesselator *tess);
typedef void (APIENTRY *gluTessVertexProto)(GLUtesselator *tess, GLdouble coords[3], void *data);
typedef void (APIENTRY *gluTessEndContourProto)(GLUtesselator *tess);
typedef void (APIENTRY *gluTessEndPolygonProto)(GLUtesselator *tess);
typedef void (APIENTRY *gluTessPropertyProto)(GLUtesselator *tess, GLenum which, GLdouble value);
typedef void (APIENTRY *gluTessNormalProto)(GLUtesselator *tess, GLdouble x, GLdouble y, GLdouble z);
typedef void (APIENTRY *gluTessCallbackProto)(GLUtesselator *tess, GLenum which, void (CALLBACK *)());

static HINSTANCE		gluModuleHandle;
static gluNewTessProto		gluNewTessProc;
static gluDeleteTessProto	gluDeleteTessProc;
static gluTessBeginPolygonProto	gluTessBeginPolygonProc;
static gluTessBeginContourProto	gluTessBeginContourProc;
static gluTessVertexProto	gluTessVertexProc;
static gluTessEndContourProto	gluTessEndContourProc;
static gluTessEndPolygonProto	gluTessEndPolygonProc;
static gluTessPropertyProto	gluTessPropertyProc;
static gluTessNormalProto	gluTessNormalProc;
static gluTessCallbackProto	gluTessCallbackProc;

static HFONT	hNewFont, hOldFont;
static FLOAT	ScaleFactor;

#define LINE_BUF_QUANT 4000
#define VERT_BUF_QUANT 4000

static FLOAT*	LineBuf;
static DWORD	LineBufSize;
static DWORD	LineBufIndex;
static FLOAT*	VertBuf;
static DWORD	VertBufSize;
static DWORD	VertBufIndex;
static GLenum	TessErrorOccurred;

static int AppendToLineBuf(
	FLOAT value);

static int AppendToVertBuf(
	FLOAT value);

static int DrawGlyph(
	UCHAR*		glyphBuf,
	DWORD		glyphSize,
	FLOAT		chordalDeviation,
	FLOAT		extrusion,
	INT		format);

static void FreeLineBuf(void);

static void FreeVertBuf(void);

static long GetWord(
	UCHAR**		p);

static long GetDWord(
	UCHAR**		p);

static double GetFixed(
	UCHAR**		p);

static int InitLineBuf(void);

static int InitVertBuf(void);

static HFONT CreateHighResolutionFont(
	HDC		hDC);

static int MakeDisplayListFromGlyph(
	DWORD			listName,
	UCHAR*			glyphBuf,
	DWORD			glyphSize,
	LPGLYPHMETRICSFLOAT	glyphMetricsFloat,
	FLOAT			chordalDeviation,
	FLOAT			extrusion,
	INT			format);

static BOOL LoadGLUTesselator(void);
static BOOL UnloadGLUTesselator(void);

static int MakeLinesFromArc(
	FLOAT		x0,
	FLOAT		y0,
	FLOAT		x1,
	FLOAT		y1,
	FLOAT		x2,
	FLOAT		y2,
	DWORD		vertexCountIndex,
	FLOAT		chordalDeviationSquared);

static int MakeLinesFromGlyph(		UCHAR*		glyphBuf,
					DWORD		glyphSize,
					FLOAT		chordalDeviation);

static int MakeLinesFromTTLine(		UCHAR**		pp,
					DWORD		vertexCountIndex,
					WORD		pointCount);

static int MakeLinesFromTTPolycurve(	UCHAR**		pp,
					DWORD		vertexCountIndex,
					FLOAT		chordalDeviation);

static int MakeLinesFromTTPolygon(	UCHAR**		pp,
					FLOAT		chordalDeviation);

static int MakeLinesFromTTQSpline(	UCHAR**		pp,
					DWORD		vertexCountIndex,
					WORD		pointCount,
					FLOAT		chordalDeviation);

static void CALLBACK TessCombine(	double		coords[3],
					void*		vertex_data[4],
					FLOAT		weight[4],
					void**		outData);

static void CALLBACK TessError(		GLenum		error);

static void CALLBACK TessVertexOutData(	FLOAT		p[3],
					GLfloat 	z);

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

#ifdef GLD_THREADS
#pragma message("compiling DGLWGL.C vars for multi-threaded support")
extern CRITICAL_SECTION CriticalSection;
extern DWORD dwTLSPixelFormat;			// TLS index for current pixel format
#endif
int curPFD = 0;							// Current PFD (static)

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

int dglGetPixelFormat(void)
{
#ifdef GLD_THREADS
	int iPixelFormat;
	// get thread-specific instance
	if (glb.bMultiThreaded) {
		__try {
			iPixelFormat = (int)TlsGetValue(dwTLSPixelFormat);
		}
		__except(EXCEPTION_EXECUTE_HANDLER) {
			iPixelFormat = curPFD;
		}
	}
	// get global static var
	else {
		iPixelFormat = curPFD;
	}
	return iPixelFormat;
#else
	return curPFD;
#endif
}

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

void dglSetPixelFormat(int iPixelFormat)
{
#ifdef GLD_THREADS
	// set thread-specific instance
	if (glb.bMultiThreaded) {
		__try {
			TlsSetValue(dwTLSPixelFormat, (LPVOID)iPixelFormat);
		}
		__except(EXCEPTION_EXECUTE_HANDLER) {
			curPFD = iPixelFormat;
		}
	}
	// set global static var
	else {
		curPFD = iPixelFormat;
	}
#else
	curPFD = iPixelFormat;
#endif
}

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

int APIENTRY _GLD_WGL_EXPORT(ChoosePixelFormat)(
	HDC a,
	CONST PIXELFORMATDESCRIPTOR *ppfd)
{
	DGL_pixelFormat			*lpPF = glb.lpPF;

    PIXELFORMATDESCRIPTOR	ppfdBest;
    int						i;
	int						bestIndex = -1;
    int						numPixelFormats;
	DWORD					dwFlags;

	char					buf[128];
	char					cat[8];

	DWORD dwAllFlags = 
					PFD_DRAW_TO_WINDOW |
					PFD_DRAW_TO_BITMAP |
					PFD_SUPPORT_GDI |
					PFD_SUPPORT_OPENGL |
					PFD_GENERIC_FORMAT |
					PFD_NEED_PALETTE |
					PFD_NEED_SYSTEM_PALETTE |
					PFD_DOUBLEBUFFER |
					PFD_STEREO |
					/*PFD_SWAP_LAYER_BUFFERS |*/
					PFD_DOUBLEBUFFER_DONTCARE |
					PFD_STEREO_DONTCARE |
					PFD_SWAP_COPY |
					PFD_SWAP_EXCHANGE |
					PFD_GENERIC_ACCELERATED |
					0;

	// Validate license
	if (!dglValidate())
		return 0;

	// List may not be built until dglValidate() is called! KeithH
	lpPF = glb.lpPF;

	//
	// Lets print the input pixel format to the log
	// ** Based on "wglinfo" by Nate Robins **
	//
	ddlogMessage(DDLOG_SYSTEM, "ChoosePixelFormat:\n");
	ddlogMessage(DDLOG_INFO, "Input pixel format for ChoosePixelFormat:\n");
	ddlogMessage(DDLOG_INFO,
		"   visual  x  bf lv rg d st  r  g  b a  ax dp st accum buffs  ms\n");
	ddlogMessage(DDLOG_INFO,
		" id dep cl sp sz l  ci b ro sz sz sz sz bf th cl  r  g  b  a ns b\n");
	ddlogMessage(DDLOG_INFO,
		"-----------------------------------------------------------------\n");
	sprintf(buf, "  .  ");

	sprintf(cat, "%2d ", ppfd->cColorBits);
	strcat(buf, cat);
	if(ppfd->dwFlags & PFD_DRAW_TO_WINDOW)      sprintf(cat, "wn ");
	else if(ppfd->dwFlags & PFD_DRAW_TO_BITMAP) sprintf(cat, "bm ");
	else sprintf(cat, ".  ");
	strcat(buf, cat);

	/* should find transparent pixel from LAYERPLANEDESCRIPTOR */
	sprintf(cat, " . "); 
	strcat(buf, cat);

	sprintf(cat, "%2d ", ppfd->cColorBits);
	strcat(buf, cat);

	/* bReserved field indicates number of over/underlays */
	if(ppfd->bReserved) sprintf(cat, " %d ", ppfd->bReserved);
	else sprintf(cat, " . "); 
	strcat(buf, cat);

	sprintf(cat, " %c ", ppfd->iPixelType == PFD_TYPE_RGBA ? 'r' : 'c');
	strcat(buf, cat);

	sprintf(cat, "%c ", ppfd->dwFlags & PFD_DOUBLEBUFFER ? 'y' : '.');
	strcat(buf, cat);

	sprintf(cat, " %c ", ppfd->dwFlags & PFD_STEREO ? 'y' : '.');
	strcat(buf, cat);

	if(ppfd->cRedBits && ppfd->iPixelType == PFD_TYPE_RGBA) 
	    sprintf(cat, "%2d ", ppfd->cRedBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);

	if(ppfd->cGreenBits && ppfd->iPixelType == PFD_TYPE_RGBA) 
	    sprintf(cat, "%2d ", ppfd->cGreenBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);

	if(ppfd->cBlueBits && ppfd->iPixelType == PFD_TYPE_RGBA) 
	    sprintf(cat, "%2d ", ppfd->cBlueBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cAlphaBits && ppfd->iPixelType == PFD_TYPE_RGBA) 
		sprintf(cat, "%2d ", ppfd->cAlphaBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cAuxBuffers)     sprintf(cat, "%2d ", ppfd->cAuxBuffers);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cDepthBits)      sprintf(cat, "%2d ", ppfd->cDepthBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cStencilBits)    sprintf(cat, "%2d ", ppfd->cStencilBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cAccumRedBits)   sprintf(cat, "%2d ", ppfd->cAccumRedBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);

	if(ppfd->cAccumGreenBits) sprintf(cat, "%2d ", ppfd->cAccumGreenBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cAccumBlueBits)  sprintf(cat, "%2d ", ppfd->cAccumBlueBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	if(ppfd->cAccumAlphaBits) sprintf(cat, "%2d ", ppfd->cAccumAlphaBits);
	else sprintf(cat, " . ");
	strcat(buf, cat);
	
	/* no multisample in Win32 */
	sprintf(cat, " . .\n");
	strcat(buf, cat);

	ddlogMessage(DDLOG_INFO, buf);
	ddlogMessage(DDLOG_INFO,
		"-----------------------------------------------------------------\n");
	ddlogMessage(DDLOG_INFO, "\n");

	//
	// Examine the flags for correctness
	//
	dwFlags = ppfd->dwFlags;
    if (dwFlags != (dwFlags & dwAllFlags))
    {
		/* error: bad dwFlags */
		ddlogPrintf(DDLOG_WARN,
					"ChoosePixelFormat: bad flags (0x%x)",
					dwFlags & (~dwAllFlags));
		// Mask illegal flags and continue
		dwFlags = dwFlags & dwAllFlags;
    }
	
    switch (ppfd->iPixelType) {
    case PFD_TYPE_RGBA:
    case PFD_TYPE_COLORINDEX:
		break;
    default:
		/* error: bad iPixelType */
		ddlogMessage(DDLOG_WARN, "ChoosePixelFormat: bad pixel type\n");
		return 0;
    }
	
    switch (ppfd->iLayerType) {
    case PFD_MAIN_PLANE:
    case PFD_OVERLAY_PLANE:
    case PFD_UNDERLAY_PLANE:
		break;
    default:
		/* error: bad iLayerType */
		ddlogMessage(DDLOG_WARN, "ChoosePixelFormat: bad layer type\n");
		return 0;
    }
	
    numPixelFormats = glb.nPixelFormatCount;
	
    /* loop through candidate pixel format descriptors */
    for (i=0; i<numPixelFormats; ++i) {
		PIXELFORMATDESCRIPTOR ppfdCandidate;
		
		memcpy(&ppfdCandidate, &lpPF[i].pfd, sizeof(PIXELFORMATDESCRIPTOR));
		
		/*
		** Check attributes which must match
		*/
		if (ppfd->iPixelType != ppfdCandidate.iPixelType) {
			continue;
		}

		if (ppfd->iLayerType != ppfdCandidate.iLayerType) {
			continue;
		}
		
		if (((dwFlags ^ ppfdCandidate.dwFlags) & dwFlags) &
			(PFD_DRAW_TO_WINDOW | PFD_DRAW_TO_BITMAP |
			PFD_SUPPORT_GDI | PFD_SUPPORT_OPENGL))
		{
			continue;
		}
		
		if (!(dwFlags & PFD_DOUBLEBUFFER_DONTCARE)) {
			if ((dwFlags & PFD_DOUBLEBUFFER) !=
				(ppfdCandidate.dwFlags & PFD_DOUBLEBUFFER))
			{
				continue;
			}
		}
		
//		if (!(dwFlags & PFD_STEREO_DONTCARE)) {
			if ((dwFlags & PFD_STEREO) !=
				(ppfdCandidate.dwFlags & PFD_STEREO))
			{
				continue;
			}
//		}
		
        if (ppfd->iPixelType==PFD_TYPE_RGBA
            && ppfd->cAlphaBits && !ppfdCandidate.cAlphaBits) {
            continue;
		}
		
        if (ppfd->iPixelType==PFD_TYPE_RGBA
			&& ppfd->cAccumBits && !ppfdCandidate.cAccumBits) {
			continue;
        }
		
        if (ppfd->cDepthBits && !ppfdCandidate.cDepthBits) {
			continue;
        }
		
        if (ppfd->cStencilBits && !ppfdCandidate.cStencilBits) {
            continue;
        }

		if (ppfd->cAuxBuffers && !ppfdCandidate.cAuxBuffers) {
			continue;
		}
		
		/*
		** See if candidate is better than the previous best choice
		*/
		if (bestIndex == -1) {
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if ((ppfd->cColorBits > ppfdBest.cColorBits &&
			ppfdCandidate.cColorBits > ppfdBest.cColorBits) ||
			(ppfd->cColorBits <= ppfdCandidate.cColorBits &&
			ppfdCandidate.cColorBits < ppfdBest.cColorBits))
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if (ppfd->iPixelType==PFD_TYPE_RGBA
            && ppfd->cAlphaBits
            && ppfdCandidate.cAlphaBits > ppfdBest.cAlphaBits)
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if (ppfd->iPixelType==PFD_TYPE_RGBA
			&& ppfd->cAccumBits
            && ppfdCandidate.cAccumBits > ppfdBest.cAccumBits)
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if ((ppfd->cDepthBits > ppfdBest.cDepthBits &&
			ppfdCandidate.cDepthBits > ppfdBest.cDepthBits) ||
			(ppfd->cDepthBits <= ppfdCandidate.cDepthBits &&
			ppfdCandidate.cDepthBits < ppfdBest.cDepthBits))
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if (ppfd->cStencilBits &&
			ppfdCandidate.cStencilBits > ppfdBest.cStencilBits)
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
		
		if (ppfd->cAuxBuffers &&
			ppfdCandidate.cAuxBuffers > ppfdBest.cAuxBuffers)
		{
			ppfdBest = ppfdCandidate;
			bestIndex = i;
			continue;
		}
    }

	if (bestIndex != -1) {
		ddlogPrintf(DDLOG_SYSTEM, "Pixel Format %d chosen as best match", bestIndex+1);
	    return bestIndex + 1;
	}

	// Return the pixelformat that has the most capabilities.
	// ** NOTE: This is only possible due to the way the list
	// of pixelformats is built. **
	// Now picks best pixelformat. KeithH
	bestIndex = numPixelFormats;	// most capable double buffer format
	ddlogPrintf(DDLOG_SYSTEM, "Pixel Format %d chosen by default", bestIndex);
	return (bestIndex);
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(CopyContext)(
	HGLRC a,
	HGLRC b,
	UINT c)
{
	// Validate license
	if (!dglValidate())
		return FALSE;
    UNSUPPORTED("wglCopyContext")
    return FALSE; // Failed
}

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

HGLRC APIENTRY _GLD_WGL_EXPORT(CreateContext)(
	HDC a)
{
	int ipf;

	// Validate license
	if (!dglValidate())
		return 0;

	// Check that the current PFD is valid
	ipf = dglGetPixelFormat();
	if (!IsValidPFD(ipf))
		return (HGLRC)0;

	return dglCreateContext(a, &glb.lpPF[ipf-1]);
}

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

HGLRC APIENTRY _GLD_WGL_EXPORT(CreateLayerContext)(
	HDC a,
	int b)
{
	// Validate license
	if (!dglValidate())
		return 0;

    UNSUPPORTED("wglCreateLayerContext")
    return NULL; // Failed
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(DeleteContext)(
	HGLRC a)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

    return dglDeleteContext(a);
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(DescribeLayerPlane)(
	HDC hDC,
	int iPixelFormat,
	int iLayerPlane,
	UINT nBytes,
	LPLAYERPLANEDESCRIPTOR plpd)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	UNSUPPORTED("DGL_DescribeLayerPlane")

//	gldLogPrintf(GLDLOG_INFO, "DescribeLayerPlane: %d, %d", iPixelFormat, iLayerPlane);

	return FALSE;
}

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

int APIENTRY _GLD_WGL_EXPORT(DescribePixelFormat)(
	HDC a,
	int b,
	UINT c,
	LPPIXELFORMATDESCRIPTOR d)
{
	UINT nSize;

	// Validate license
	if (!dglValidate())
		return 0;

	if (d == NULL) // Calling app requires max number of PF's
		return glb.nPixelFormatCount;

	// The supplied buffer may be larger than the info that we
	// will be copying.
	if (c > sizeof(PIXELFORMATDESCRIPTOR))
		nSize = sizeof(PIXELFORMATDESCRIPTOR);
	else
		nSize = c;

    // Setup an empty PFD before doing validation check
    memset(d, 0, nSize);
    d->nSize = nSize;
    d->nVersion = 1;

	if (!IsValidPFD(b))
		return 0; // Bail if PFD index is invalid

	memcpy(d, &glb.lpPF[b-1].pfd, nSize);

	return glb.nPixelFormatCount;
}

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

HGLRC APIENTRY _GLD_WGL_EXPORT(GetCurrentContext)(void)
{
	// Validate license
	if (!dglValidate())
		return 0;

	return dglGetCurrentContext();
}

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

HDC APIENTRY _GLD_WGL_EXPORT(GetCurrentDC)(void)
{
	// Validate license
	if (!dglValidate())
		return 0;

	return dglGetCurrentDC();
}

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

PROC APIENTRY _GLD_WGL_EXPORT(GetDefaultProcAddress)(
	LPCSTR a)
{
	// Validate license
	if (!dglValidate())
		return NULL;

    UNSUPPORTED("DGL_GetDefaultProcAddress")
    return NULL;
}

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

int APIENTRY _GLD_WGL_EXPORT(GetLayerPaletteEntries)(
	HDC a,
	int b,
	int c,
	int d,
	COLORREF *e)
{
	// Validate license
	if (!dglValidate())
		return 0;

    UNSUPPORTED("DGL_GetLayerPaletteEntries")
    return 0;
}

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

int APIENTRY _GLD_WGL_EXPORT(GetPixelFormat)(
	HDC a)
{
	// Validate license
	if (!dglValidate())
		return 0;

	return dglGetPixelFormat();
}

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

PROC APIENTRY _GLD_WGL_EXPORT(GetProcAddress)(
	LPCSTR a)
{
	PROC dglGetProcAddressD3D(LPCSTR a);

	// Validate license
	if (!dglValidate())
		return NULL;

#ifdef _USE_GLD3_WGL
	return _gldDriver.wglGetProcAddress(a);
#else
	return dglGetProcAddressD3D(a);
#endif
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(MakeCurrent)(
	HDC a,
	HGLRC b)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	return dglMakeCurrent(a, b);
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(RealizeLayerPalette)(
	HDC a,
	int b,
	BOOL c)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

    UNSUPPORTED("DGL_RealizeLayerPalette")
	return FALSE;
}

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

int APIENTRY _GLD_WGL_EXPORT(SetLayerPaletteEntries)(
	HDC a,
	int b,
	int c,
	int d,
	CONST COLORREF *e)
{
	// Validate license
	if (!dglValidate())
		return 0;

    UNSUPPORTED("DGL_SetLayerPaletteEntries")
	return 0;
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(SetPixelFormat)(
	HDC a,
	int b,
	CONST PIXELFORMATDESCRIPTOR *c)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	if (IsValidPFD(b)) {
		ddlogPrintf(DDLOG_SYSTEM, "SetPixelFormat: PixelFormat %d has been set", b);
		dglSetPixelFormat(b);
		return TRUE;
	} else {
		ddlogPrintf(DDLOG_ERROR,
					"SetPixelFormat: PixelFormat %d is invalid and cannot be set", b);
		return FALSE;
	}
}

// ***********************************************************************
/*
 * Share lists between two gl_context structures.
 * This was added for WIN32 WGL function support, since wglShareLists()
 * must be called *after* wglCreateContext() with valid GLRCs. (DaveM)
 */
//
// Copied from GLD2.x. KeithH
//
static GLboolean _gldShareLists(
	struct gl_context *ctx1,
	struct gl_context *ctx2)
{
	/* Sanity check context pointers */
	if (ctx1 == NULL || ctx2 == NULL)
		return GL_FALSE;
	/* Sanity check shared list pointers */
	if (ctx1->Shared == NULL || ctx2->Shared == NULL)
		return GL_FALSE;
	/* Decrement reference count on sharee to release previous list */
	ctx2->Shared->RefCount--;
#if 0	/* 3DStudio exits on this memory release */
	if (ctx2->Shared->RefCount == 0)
		free_shared_state(ctx2, ctx2->Shared);
#endif
	/* Re-assign list from sharer to sharee and increment reference count */
	ctx2->Shared = ctx1->Shared;
	ctx1->Shared->RefCount++;
	return GL_TRUE;
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(ShareLists)(
	HGLRC a,
	HGLRC b)
{
	DGL_ctx *dgl1, *dgl2;

	// Validate license
	if (!dglValidate())
		return FALSE;

	// Mesa supports shared lists, but you need to supply the shared
	// GL context info when calling gl_create_context(). An auxiliary
	// function gl_share_lists() has been added to update the shared
	// list info after the GL contexts have been created. (DaveM)
	dgl1 = dglGetContextAddress(a);
	dgl2 = dglGetContextAddress(b);
	if (dgl1->bAllocated && dgl2->bAllocated) {
#ifdef _USE_GLD3_WGL
		return _gldShareLists(dgl1->glCtx, dgl2->glCtx);
#else
		return (*mesaFuncs.gl_share_lists)(dgl1->glCtx, dgl2->glCtx);
#endif
	}
	return FALSE;
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(SwapBuffers)(
	HDC a)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	return dglSwapBuffers(a);
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(SwapLayerBuffers)(
	HDC a,
	UINT b)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	return dglSwapBuffers(a);
}

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

// ***********************************************************************
// Note: This ResizeBuffers() function may be called from
// either MESA glViewport() or GLD wglMakeCurrent().

BOOL dglWglResizeBuffers(
	struct gl_context *ctx,
	BOOL bDefaultDriver)
{
	DGL_ctx						*dgl = NULL;
	RECT						rcScreenRect;
	DWORD						dwWidth;
	DWORD						dwHeight;
	DDSURFACEDESC2				ddsd2;
	DDSCAPS2					ddscaps2;
	IDirectDrawClipper			*lpddClipper = NULL;
	DWORD						dwFlags;
	HRESULT						hResult;

	DWORD						dwMemoryType;

	int							i;
	struct gl_texture_object	*tObj;
	struct gl_texture_image		*image;

	BOOL						bWasFullscreen;
	BOOL						bSaveDesktop;
	BOOL						bFullScrnWin = FALSE;
	DDSURFACEDESC2 				ddsd2DisplayMode;

	DDBLTFX						ddbltfx;
	POINT						pt;
	RECT						rcDst;
#ifdef _USE_GLD3_WGL
	GLD_displayMode				glddm;
#endif

#define DDLOG_CRITICAL_OR_WARN	(bDefaultDriver ? DDLOG_WARN : DDLOG_CRITICAL)

	// Validate license
	if (!dglValidate())
		return FALSE;

	// Sanity checks
	if (ctx == NULL)
		return FALSE;
	dgl = ctx->DriverCtx;
	if (dgl == NULL)
		return FALSE;

	// Get the window size and calculate its dimensions
	if (dgl->hWnd == NULL) {
		// Check for non-window DC = memory DC ?
		if (GetClipBox(dgl->hDC, &rcScreenRect) == ERROR)
			SetRect(&rcScreenRect, 0, 0, 0, 0);
	}
	else if (!GetClientRect(dgl->hWnd, &rcScreenRect))
		SetRect(&rcScreenRect, 0, 0, 0, 0);
	dwWidth = rcScreenRect.right - rcScreenRect.left;
	dwHeight = rcScreenRect.bottom - rcScreenRect.top;
    CopyRect(&dgl->rcScreenRect, &rcScreenRect);

	// This will occur on Alt-Tab
	if ((dwWidth == 0) && (dwHeight == 0)) {
		//dgl->bCanRender = FALSE;
		return TRUE; // No resize possible!
	}

	// Some apps zero only 1 dimension for non-visible window... (DaveM)
	if ((dwWidth == 0) || (dwHeight == 0)) {
		dwWidth = 8;
		dwHeight = 8;
	}

	// Test to see if a resize is required.
	// Note that the dimensions will be the same if a prior resize attempt failed.
	if ((dwWidth == dgl->dwWidth) && (dwHeight == dgl->dwHeight) && bDefaultDriver) {
		return TRUE; // No resize required
	}

	ddlogPrintf(DDLOG_SYSTEM, "dglResize: %dx%d", dwWidth, dwHeight);
#ifndef _USE_GLD3_WGL
	// Work out where we want our surfaces created
	dwMemoryType = (bDefaultDriver) ? glb.dwMemoryType : DDSCAPS_SYSTEMMEMORY;
#endif // _USE_GLD3_WGL

	// Note previous fullscreen vs window display status
	bWasFullscreen = dgl->bFullscreen;

#ifdef _USE_GLD3_WGL
	if (_gldDriver.GetDisplayMode(dgl, &glddm)) {
		if ( (dwWidth == glddm.Width) &&
				 (dwHeight == glddm.Height) ) {
			bFullScrnWin = TRUE;
		}
		if (bFullScrnWin && glb.bPrimary && !glb.bFullscreenBlit && !glb.bDirectDrawPersistant) {
			dgl->bFullscreen = TRUE;
			ddlogMessage(DDLOG_INFO, "Fullscreen window after resize.\n");
		}
		else {
			dgl->bFullscreen = FALSE;
			ddlogMessage(DDLOG_INFO, "Non-Fullscreen window after resize.\n");
		}
		// Cache the display mode dimensions
		dgl->dwModeWidth = glddm.Width;
		dgl->dwModeHeight = glddm.Height;
	}

	// Clamp the effective window dimensions to primary surface.
	// We need to do this for D3D viewport dimensions even if wide
	// surfaces are supported. This also is a good idea for handling
	// whacked-out window dimensions passed for non-drawable windows
	// like Solid Edge. (DaveM)
	if (dgl->dwWidth > glddm.Width)
		dgl->dwWidth = glddm.Width;
	if (dgl->dwHeight > glddm.Height)
		dgl->dwHeight = glddm.Height;
#else // _USE_GLD3_WGL
	// Window resize may have changed to fullscreen
	ZeroMemory(&ddsd2DisplayMode, sizeof(ddsd2DisplayMode));
	ddsd2DisplayMode.dwSize = sizeof(ddsd2DisplayMode);
	hResult = IDirectDraw4_GetDisplayMode(
					dgl->lpDD4,
					&ddsd2DisplayMode);
	if (SUCCEEDED(hResult)) {
		if ( (dwWidth == ddsd2DisplayMode.dwWidth) &&
				 (dwHeight == ddsd2DisplayMode.dwHeight) ) {
			bFullScrnWin = TRUE;
		}
		if (bFullScrnWin && glb.bPrimary && !glb.bFullscreenBlit && !glb.bDirectDrawPersistant) {
			dgl->bFullscreen = TRUE;
			ddlogMessage(DDLOG_INFO, "Fullscreen window after resize.\n");
		}
		else {
			dgl->bFullscreen = FALSE;
			ddlogMessage(DDLOG_INFO, "Non-Fullscreen window after resize.\n");
		}
		// Cache the display mode dimensions
		dgl->dwModeWidth = ddsd2DisplayMode.dwWidth;
		dgl->dwModeHeight = ddsd2DisplayMode.dwHeight;
	}

	// Clamp the effective window dimensions to primary surface.
	// We need to do this for D3D viewport dimensions even if wide
	// surfaces are supported. This also is a good idea for handling
	// whacked-out window dimensions passed for non-drawable windows
	// like Solid Edge. (DaveM)
	if (dgl->dwWidth > ddsd2DisplayMode.dwWidth)
		dgl->dwWidth = ddsd2DisplayMode.dwWidth;
	if (dgl->dwHeight > ddsd2DisplayMode.dwHeight)
		dgl->dwHeight = ddsd2DisplayMode.dwHeight;
#endif // _USE_GLD3_WGL

	// Note if fullscreen vs window display has changed?
	bSaveDesktop = (!bWasFullscreen && !dgl->bFullscreen) ? TRUE : FALSE;
	// Save the desktop primary surface from being destroyed
	// whenever remaining in windowed mode, since the stereo mode
	// switches are expensive...

#ifndef _USE_GLD3_WGL
	// Don't need to re-allocate persistant buffers. (DaveM)
	// Though we should clear the back buffers to hide artifacts.
	if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
		dgl->dwWidth = dwWidth;
		dgl->dwHeight = dwHeight;
		ZeroMemory(&ddbltfx, sizeof(ddbltfx));
		ddbltfx.dwSize = sizeof(ddbltfx);
		ddbltfx.dwFillColor = dgl->dwClearColorPF;
		IDirectDrawSurface4_Blt(dgl->lpBack4, &rcScreenRect, NULL, NULL,
			DDBLT_WAIT | DDBLT_COLORFILL, &ddbltfx);
		return TRUE;
	}

	// Ensure all rendering is complete
	if (ctx->Driver.Finish)
		(*ctx->Driver.Finish)(ctx);
	if (dgl->bSceneStarted == TRUE) {
		IDirect3DDevice3_EndScene(dgl->lpDev3);
		dgl->bSceneStarted = FALSE;
	}
#endif // _USE_GLD3_WGL
	dgl->bCanRender = FALSE;

#ifdef GLD_THREADS
	// Serialize access to DirectDraw and DDS operations
	if (glb.bMultiThreaded)
		EnterCriticalSection(&CriticalSection);
#endif

#ifndef _USE_GLD3_WGL
	// Release existing surfaces
	RELEASE(dgl->lpDev3);
	RELEASE(dgl->lpDepth4);
	RELEASE(dgl->lpBack4);
	if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary)
        ;
	else
	RELEASE(dgl->lpFront4);
#endif // _USE_GLD3_WGL
	dgl->dwWidth = dwWidth;
	dgl->dwHeight = dwHeight;

	// Set defaults
	dgl->dwModeWidth = dgl->dwWidth;
	dgl->dwModeHeight = dgl->dwHeight;

#ifdef _USE_GLD3_WGL
	if (!_gldDriver.ResizeDrawable(dgl, bDefaultDriver, glb.bDirectDrawPersistant, glb.bPersistantBuffers))
		goto cleanup_and_return_with_error;
#else // _USE_GLD3_WGL

	if (dgl->bFullscreen) {
		//
		// FULLSCREEN
		//

        // Disable warning popups when in fullscreen mode
        ddlogWarnOption(FALSE);

		// Have to release the persistant DirectDraw primary surface
		// if switching to fullscreen mode. So if application wants
		// persistant display in fullscreen mode, a fullscreen-size
		// window should be used instead via fullscreen-blit option.
		if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
			RELEASE(glb.lpPrimary4);
			glb.bDirectDrawPrimary = FALSE;
		}

		dwFlags = DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT;
		if (glb.bFastFPU)
			dwFlags |= DDSCL_FPUSETUP;	// optional
		hResult = IDirectDraw4_SetCooperativeLevel(dgl->lpDD4, dgl->hWnd, dwFlags);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: Unable to set Exclusive Fullscreen mode", hResult);
			goto cleanup_and_return_with_error;
		}

		hResult = IDirectDraw4_SetDisplayMode(dgl->lpDD4,
											  dgl->dwModeWidth,
											  dgl->dwModeHeight,
											  dgl->dwBPP,
											  0,
											  0);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: SetDisplayMode failed", hResult);
			goto cleanup_and_return_with_error;
		}

		// ** The display mode has changed, so dont use MessageBox! **

		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);

		if (dgl->bDoubleBuffer) {
			// Double buffered
			// Primary surface
			ddsd2.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
								   DDSCAPS_FLIP |
								   DDSCAPS_COMPLEX |
								   DDSCAPS_3DDEVICE |
								   dwMemoryType;
			ddsd2.dwBackBufferCount = 1;
			hResult = IDirectDraw4_CreateSurface(dgl->lpDD4, &ddsd2, &dgl->lpFront4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: CreateSurface (primary) failed", hResult);
				goto cleanup_and_return_with_error;
			}
			// Render target surface
			ZeroMemory(&ddscaps2, sizeof(ddscaps2)); // Clear the entire struct.
			ddscaps2.dwCaps = DDSCAPS_BACKBUFFER;
			hResult = IDirectDrawSurface4_GetAttachedSurface(dgl->lpFront4, &ddscaps2, &dgl->lpBack4);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: GetAttachedSurface failed", hResult);
				goto cleanup_and_return_with_error;
			}
		} else {
			// Single buffered
			// Primary surface
			ddsd2.dwFlags = DDSD_CAPS;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
								   //DDSCAPS_3DDEVICE |
								   dwMemoryType;

			hResult = IDirectDraw4_CreateSurface(dgl->lpDD4, &ddsd2, &dgl->lpFront4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: CreateSurface (primary) failed", hResult);
				goto cleanup_and_return_with_error;
			}

			dgl->lpBack4 = NULL;
		}
	} else {
		// WINDOWED

        // OK to enable warning popups in windowed mode
        ddlogWarnOption(glb.bMessageBoxWarnings);

		// Ditto if persistant DirectDraw primary
		if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary)
			goto DoClipperOnly;

		// WINDOWED
		dwFlags = DDSCL_NORMAL;
		if (glb.bMultiThreaded)
			dwFlags |= DDSCL_MULTITHREADED;
		if (glb.bFastFPU)
			dwFlags |= DDSCL_FPUSETUP;	// optional
		hResult = IDirectDraw4_SetCooperativeLevel(dgl->lpDD4,
												  dgl->hWnd,
												  dwFlags);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: Unable to set Normal coop level", hResult);
			goto cleanup_and_return_with_error;
		}
		// Primary surface
		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);
		ddsd2.dwFlags = DDSD_CAPS;
		ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
		hResult = IDirectDraw4_CreateSurface(dgl->lpDD4, &ddsd2, &dgl->lpFront4, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: CreateSurface (primary) failed", hResult);
			goto cleanup_and_return_with_error;
		}

		// Cache the primary surface for persistant DirectDraw state
		if (glb.bDirectDrawPersistant && !glb.bDirectDrawPrimary) {
			glb.lpPrimary4 = dgl->lpFront4;
			IDirectDrawSurface4_AddRef(glb.lpPrimary4);
			glb.bDirectDrawPrimary = TRUE;
		}

		// Clipper object
		hResult = DirectDrawCreateClipper(0, &lpddClipper, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: CreateClipper failed", hResult);
			goto cleanup_and_return_with_error;
		}
		hResult = IDirectDrawClipper_SetHWnd(lpddClipper, 0, dgl->hWnd);
		if (FAILED(hResult)) {
			RELEASE(lpddClipper);
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: SetHWnd failed", hResult);
			goto cleanup_and_return_with_error;
		}
		hResult = IDirectDrawSurface4_SetClipper(dgl->lpFront4, lpddClipper);
		RELEASE(lpddClipper); // We have finished with it.
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: SetClipper failed", hResult);
			goto cleanup_and_return_with_error;
		}
DoClipperOnly:
		// Update the window for the original clipper
		if ((glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) || bSaveDesktop) {
			IDirectDrawSurface4_GetClipper(dgl->lpFront4, &lpddClipper);
			IDirectDrawClipper_SetHWnd(lpddClipper, 0, dgl->hWnd);
			RELEASE(lpddClipper);
		}

		if (dgl->bDoubleBuffer) {
			// Render target surface
			ZeroMemory(&ddsd2, sizeof(ddsd2));
			ddsd2.dwSize = sizeof(ddsd2);
			ddsd2.dwFlags        = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
			ddsd2.dwWidth        = dgl->dwWidth;
			ddsd2.dwHeight       = dgl->dwHeight;
			ddsd2.ddsCaps.dwCaps = DDSCAPS_3DDEVICE |
								   DDSCAPS_OFFSCREENPLAIN |
								   dwMemoryType;
			hResult = IDirectDraw4_CreateSurface(dgl->lpDD4, &ddsd2, &dgl->lpBack4, NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: Create Backbuffer failed", hResult);
				goto cleanup_and_return_with_error;
			}

		} else {
			dgl->lpBack4 = NULL;
		}
	}

	//
	// Now create the Zbuffer
	//
	if (dgl->bDepthBuffer) {
		// Get z-buffer dimensions from the render target
		// Setup the surface desc for the z-buffer.
		ZeroMemory(&ddsd2, sizeof(ddsd2));
		ddsd2.dwSize = sizeof(ddsd2);
		ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
		ddsd2.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | dwMemoryType;
		ddsd2.dwWidth = dgl->dwWidth;
		ddsd2.dwHeight = dgl->dwHeight;
		memcpy(&ddsd2.ddpfPixelFormat,
			   &glb.lpZBufferPF[dgl->iZBufferPF],
			   sizeof(DDPIXELFORMAT) );

		// Create a z-buffer
		hResult = IDirectDraw4_CreateSurface(dgl->lpDD4, &ddsd2, &dgl->lpDepth4, NULL);
		if (FAILED(hResult)) {
			ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: CreateSurface (ZBuffer) failed", hResult);
			goto cleanup_and_return_with_error;
		}

		// Attach Zbuffer to render target
		TRY(IDirectDrawSurface4_AddAttachedSurface(
			dgl->bDoubleBuffer ? dgl->lpBack4 : dgl->lpFront4,
			dgl->lpDepth4),
			"dglResize: Attach Zbuffer");

	}

	// Clear the newly resized back buffers for the window client area.
	ZeroMemory(&ddbltfx, sizeof(ddbltfx));
	ddbltfx.dwSize = sizeof(ddbltfx);
	ddbltfx.dwFillColor = dgl->dwClearColorPF;
	IDirectDrawSurface4_Blt(dgl->lpBack4, &rcScreenRect, NULL, NULL,
		DDBLT_WAIT | DDBLT_COLORFILL, &ddbltfx);

	//
	// Now that we have a zbuffer we can create the 3D device
	//
	hResult = IDirect3D3_CreateDevice(dgl->lpD3D3,
									  bDefaultDriver ? &glb.d3dGuid : &IID_IDirect3DRGBDevice,
									  dgl->bDoubleBuffer ? dgl->lpBack4 : dgl->lpFront4,
									  &dgl->lpDev3,
									  NULL);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: Could not create Direct3D device", hResult);
		goto cleanup_and_return_with_error;
	}

	// We must do this as soon as the device is created
	dglInitStateCaches(dgl);

	//
	// Viewport
	//
	hResult = IDirect3DDevice3_AddViewport(dgl->lpDev3, dgl->lpViewport3);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: AddViewport failed", hResult);
		goto cleanup_and_return_with_error;
	}

	// Initialise the viewport
	dgl->d3dViewport.dwSize = sizeof(dgl->d3dViewport);
	dgl->d3dViewport.dwX = 0;
	dgl->d3dViewport.dwY = 0;
	dgl->d3dViewport.dwWidth = dgl->dwWidth;
	dgl->d3dViewport.dwHeight = dgl->dwHeight;
	dgl->d3dViewport.dvClipX = 0;
	dgl->d3dViewport.dvClipY = 0;
	dgl->d3dViewport.dvClipWidth = dgl->dwWidth;
	dgl->d3dViewport.dvClipHeight = dgl->dwHeight;
//	dgl->d3dViewport.dvMinZ = 0.0f;
//	dgl->d3dViewport.dvMaxZ = 1.0f;
	TRY(IDirect3DViewport3_SetViewport2(dgl->lpViewport3, &dgl->d3dViewport),
		"dglResize: SetViewport2");

	hResult = IDirect3DDevice3_SetCurrentViewport(dgl->lpDev3, dgl->lpViewport3);
	if (FAILED(hResult)) {
		ddlogError(DDLOG_CRITICAL_OR_WARN, "dglResize: SetCurrentViewport failed", hResult);
		goto cleanup_and_return_with_error;
	}

	// (Re)Initialise all the Direct3D renderstates
	dglInitStateD3D(ctx);

	// Now we have to recreate all of our textures (+ mipmaps).
	// Walk over all textures in hash table
	// XXX what about the default texture objects (id=0)?
	{
		struct _mesa_HashTable *textures = ctx->Shared->TexObjects;
		GLuint id;
		for (id = _mesa_HashFirstEntry(textures);
				 id;
				 id = _mesa_HashNextEntry(textures, id)) {
			tObj = (struct gl_texture_object *) _mesa_HashLookup(textures, id);
			if (tObj->DriverData) {
				// We could call our TexImage function directly, but it's
				// safer to use the driver pointer.
				for (i=0; i<MAX_TEXTURE_LEVELS; i++) {
					image = tObj->Image[i];
					if (image) {
						switch (tObj->Dimensions){
						case 1:
							if (ctx->Driver.TexImage)
								(*ctx->Driver.TexImage)(ctx, GL_TEXTURE_1D, tObj, i, image->Format, image);
							break;
						case 2:
							if (ctx->Driver.TexImage)
								(*ctx->Driver.TexImage)(ctx, GL_TEXTURE_2D, tObj, i, image->Format, image);
							break;
						default:
							break;
						}
					}
				}
			}
		}
	}

	// Re-Bind each texture Unit
	for (i=0; i<glb.wMaxSimultaneousTextures; i++) {
		tObj = ctx->Texture.Unit[i].Current;
		if (tObj) {
			DGL_texture *lpTex = (DGL_texture *)tObj->DriverData;
			hResult = dglSetTexture(dgl, i, lpTex ? lpTex->lpTexture : NULL);
			if (FAILED(hResult)) {
				ddlogError(DDLOG_ERROR, "dglResize: SetTexture failed", hResult);
			}
		}
	}
#endif // _USE_GLD3_WGL

	dgl->bCanRender = TRUE;

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	// SUCCESS.
	return TRUE;

cleanup_and_return_with_error:
	// Relase all interfaces before returning.
#ifdef _USE_GLD3_WGL
	_gldDriver.DestroyDrawable(dgl);
#else // _USE_GLD3_WGL
	RELEASE(dgl->lpDev3);
	RELEASE(dgl->lpDepth4);
	RELEASE(dgl->lpBack4);
	if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary)
		;
	else
	RELEASE(dgl->lpFront4);

#undef DDLOG_CRITICAL_OR_WARN
#endif // _USE_GLD3_WGL

	// Mark context as not being able to render
	dgl->bCanRender = FALSE;

#ifdef GLD_THREADS
	// Release serialized access
	if (glb.bMultiThreaded)
		LeaveCriticalSection(&CriticalSection);
#endif

	return FALSE;
}

// ***********************************************************************
// ***********************************************************************
// Support for bitmap fonts.
// ***********************************************************************
// ***********************************************************************

/*****************************************************************************
**
** InvertGlyphBitmap.
**
** Invert the bitmap so that it suits OpenGL's representation.
** Each row starts on a double word boundary.
**
*****************************************************************************/

static void InvertGlyphBitmap(
	int w,
	int h,
	DWORD *fptr,
	DWORD *tptr)
{
	int dWordsInRow = (w+31)/32;
	int i, j;
	DWORD *tmp = tptr;

	if (w <= 0 || h <= 0) {
	return;
	}

	tptr += ((h-1)*dWordsInRow);
	for (i = 0; i < h; i++) {
	for (j = 0; j < dWordsInRow; j++) {
		*(tptr + j) = *(fptr + j);
	}
	tptr -= dWordsInRow;
	fptr += dWordsInRow;
	}
}

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

/*****************************************************************************
 * wglUseFontBitmaps
 *
 * Converts a subrange of the glyphs in a GDI font to OpenGL display
 * lists.
 *
 * Extended to support any GDI font, not just TrueType fonts. (DaveM)
 *
 *****************************************************************************/

BOOL APIENTRY _GLD_WGL_EXPORT(UseFontBitmapsA)(
	HDC hDC,
	DWORD first,
	DWORD count,
	DWORD listBase)
{
	int					i, ox, oy, ix, iy;
	int					w, h;
	int					iBufSize, iCurBufSize = 0;
	DWORD				*bitmapBuffer = NULL;
	DWORD				*invertedBitmapBuffer = NULL;
	BOOL				bSuccessOrFail = TRUE;
	BOOL				bTrueType = FALSE;
	TEXTMETRIC			tm;
	GLYPHMETRICS		gm;
	RASTERIZER_STATUS	rs;
	MAT2				mat;
	SIZE				size;
	RECT				rect;
	HDC					hDCMem;
	HBITMAP				hBitmap;
	BITMAPINFO			bmi;
	HFONT				hFont;

	// Validate SciTech DirectGL license
	if (!dglValidate())
		return FALSE;

	// Set up a unity matrix.
	ZeroMemory(&mat, sizeof(mat));
	mat.eM11.value = 1;
	mat.eM22.value = 1;

	// Test to see if selected font is TrueType or not
	ZeroMemory(&tm, sizeof(tm));
	if (!GetTextMetrics(hDC, &tm)) {
		ddlogMessage(DDLOG_ERROR, "DGL_UseFontBitmaps: Font metrics error\n");
		return (FALSE);
	}
	bTrueType = (tm.tmPitchAndFamily & TMPF_TRUETYPE) ? TRUE : FALSE;

	// Test to see if TRUE-TYPE capabilities are installed
	// (only necessary if TrueType font selected)
	ZeroMemory(&rs, sizeof(rs));
	if (bTrueType) {
		if (!GetRasterizerCaps (&rs, sizeof (RASTERIZER_STATUS))) {
			ddlogMessage(DDLOG_ERROR, "DGL_UseFontBitmaps: Raster caps error\n");
			return (FALSE);
		}
		if (!(rs.wFlags & TT_ENABLED)) {
			ddlogMessage(DDLOG_ERROR, "DGL_UseFontBitmaps: No TrueType caps\n");
			return (FALSE);
		}
	}

	// Trick to get the current font handle
	hFont = SelectObject(hDC, GetStockObject(SYSTEM_FONT));
	SelectObject(hDC, hFont);

	// Have memory device context available for holding bitmaps of font glyphs
	hDCMem = CreateCompatibleDC(hDC);
	SelectObject(hDCMem, hFont);
	SetTextColor(hDCMem, RGB(0xFF, 0xFF, 0xFF));
	SetBkColor(hDCMem, 0);

	for (i = first; (DWORD) i < (first + count); i++) {
		// Find out how much space is needed for the bitmap so we can
		// Set the buffer size correctly.
		if (bTrueType) {
			// Use TrueType support to get bitmap size of glyph
			iBufSize = GetGlyphOutline(hDC, i, GGO_BITMAP, &gm,
				0, NULL, &mat);
			if (iBufSize == GDI_ERROR) {
				bSuccessOrFail = FALSE;
				break;
			}
		}
		else {
			// Use generic GDI support to compute bitmap size of glyph
			w = tm.tmMaxCharWidth;
			h = tm.tmHeight;
			if (GetTextExtentPoint32(hDC, (LPCTSTR)&i, 1, &size)) {
				w = size.cx;
				h = size.cy;
			}
			iBufSize = w * h;
			// Use DWORD multiple for compatibility
			iBufSize += 3;
			iBufSize /= 4;
			iBufSize *= 4;
		}

		// If we need to allocate Larger Buffers, then do so - but allocate
		// An extra 50 % so that we don't do too many mallocs !
		if (iBufSize > iCurBufSize) {
			if (bitmapBuffer) {
				__wglFree(bitmapBuffer);
			}
			if (invertedBitmapBuffer) {
				__wglFree(invertedBitmapBuffer);
			}

			iCurBufSize = iBufSize * 2;
			bitmapBuffer = (DWORD *) __wglMalloc(iCurBufSize);
			invertedBitmapBuffer = (DWORD *) __wglMalloc(iCurBufSize);

			if (bitmapBuffer == NULL || invertedBitmapBuffer == NULL) {
				bSuccessOrFail = FALSE;
				break;
			}
		}

		// If we fail to get the Glyph data, delete the display lists
		// Created so far and return FALSE.
		if (bTrueType) {
			// Use TrueType support to get bitmap of glyph
			if (GetGlyphOutline(hDC, i, GGO_BITMAP, &gm,
					iBufSize, bitmapBuffer, &mat) == GDI_ERROR) {
				bSuccessOrFail = FALSE;
				break;
			}

			// Setup glBitmap parameters for current font glyph
			w  = gm.gmBlackBoxX;
			h  = gm.gmBlackBoxY;
			ox = gm.gmptGlyphOrigin.x;
			oy = gm.gmptGlyphOrigin.y;
			ix = gm.gmCellIncX;
			iy = gm.gmCellIncY;
		}
		else {
			// Use generic GDI support to create bitmap of glyph
			ZeroMemory(bitmapBuffer, iBufSize);

			if (i >= tm.tmFirstChar && i <= tm.tmLastChar) {
				// Only create bitmaps for actual font glyphs
				hBitmap = CreateBitmap(w, h, 1, 1, NULL);
				SelectObject(hDCMem, hBitmap);
				// Make bitmap of current font glyph
				SetRect(&rect, 0, 0, w, h);
				DrawText(hDCMem, (LPCTSTR)&i, 1, &rect,
					DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_NOCLIP);
				// Make copy of bitmap in our local buffer
				ZeroMemory(&bmi, sizeof(bmi));
				bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
				bmi.bmiHeader.biWidth = w;
				bmi.bmiHeader.biHeight = -h;
				bmi.bmiHeader.biPlanes = 1;
				bmi.bmiHeader.biBitCount = 1;
				bmi.bmiHeader.biCompression = BI_RGB;
				GetDIBits(hDCMem, hBitmap, 0, h, bitmapBuffer, &bmi, 0);
				DeleteObject(hBitmap);
			}
			else {
				// Otherwise use empty display list for non-existing glyph
				iBufSize = 0;
			}

			// Setup glBitmap parameters for current font glyph
			ox = 0;
			oy = tm.tmDescent;
			ix = w;
			iy = 0;
		}

		// Create an OpenGL display list.
		_GLD_glNewList((listBase + i), GL_COMPILE);

		// Some fonts have no data for the space character, yet advertise
		// a non-zero size.
		if (0 == iBufSize) {
			_GLD_glBitmap(0, 0, 0.0f, 0.0f, (GLfloat) ix, (GLfloat) iy, NULL);
		} else {
			// Invert the Glyph data.
			InvertGlyphBitmap(w, h, bitmapBuffer, invertedBitmapBuffer);

			// Render an OpenGL bitmap and invert the origin.
			_GLD_glBitmap(w, h,
				(GLfloat) ox, (GLfloat) (h-oy),
				(GLfloat) ix, (GLfloat) iy,
				(GLubyte *) invertedBitmapBuffer);
		}

		// Close this display list.
		_GLD_glEndList();
	}

	if (bSuccessOrFail == FALSE) {
		ddlogMessage(DDLOG_ERROR, "DGL_UseFontBitmaps: Get glyph failed\n");
		_GLD_glDeleteLists((i+listBase), (i-first));
	}

	// Release resources used
	DeleteObject(hFont);
	DeleteDC(hDCMem);

	if (bitmapBuffer)
		__wglFree(bitmapBuffer);
	if (invertedBitmapBuffer)
		__wglFree(invertedBitmapBuffer);

	return(bSuccessOrFail);
}

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

BOOL APIENTRY _GLD_WGL_EXPORT(UseFontBitmapsW)(
	HDC a,
	DWORD b,
	DWORD c,
	DWORD d)
{
	// Validate license
	if (!dglValidate())
		return FALSE;

	return _GLD_WGL_EXPORT(UseFontBitmapsA)(a, b, c, d);
}

// ***********************************************************************
// ***********************************************************************
// Support for outline TrueType fonts.
// ***********************************************************************
// ***********************************************************************

void * __wglRealloc(
	void *oldPtr,
	size_t newSize)
{
    void *newPtr = NULL;
	
    if (newSize != 0) {
		newPtr = (void *) GlobalAlloc(GPTR, newSize);
		if (oldPtr && newPtr) {
			DWORD oldSize = GlobalSize(oldPtr);
			
			memcpy(newPtr, oldPtr, (oldSize <= newSize ? oldSize : newSize));
			GlobalFree(oldPtr);
		}
    } else if (oldPtr) {
		GlobalFree(oldPtr);
    }
    if (newPtr == NULL) {
		return NULL;	/* XXX out of memory error */
    }
    return newPtr;
}

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


/*****************************************************************************
 * wglUseFontOutlinesW
 *
 * Converts a subrange of the glyphs in a TrueType font to OpenGL display
 * lists.
 *****************************************************************************/

BOOL APIENTRY _GLD_WGL_EXPORT(UseFontOutlinesW)(
	IN	HDC			hDC,
	IN	DWORD			first,
	IN	DWORD			count,
	IN	DWORD			listBase,
	IN	FLOAT			chordalDeviation,
	IN	FLOAT			extrusion,
	IN	INT			format,
	OUT	LPGLYPHMETRICSFLOAT	lpgmf)
{
	return _GLD_WGL_EXPORT(UseFontOutlinesA)(hDC, first, count, listBase,
		chordalDeviation, extrusion, format, lpgmf);
}

/*****************************************************************************
 * wglUseFontOutlinesA
 *
 * Converts a subrange of the glyphs in a TrueType font to OpenGL display
 * lists.
 *****************************************************************************/

BOOL APIENTRY _GLD_WGL_EXPORT(UseFontOutlinesA)(
	IN	HDC			hDC,
			IN	DWORD			first,
			IN	DWORD			count,
			IN	DWORD			listBase,
			IN	FLOAT			chordalDeviation,
			IN	FLOAT			extrusion,
			IN	INT			format,
			OUT	LPGLYPHMETRICSFLOAT	glyphMetricsFloatArray)
	{
	DWORD	glyphIndex;
	UCHAR*	glyphBuf;
	DWORD	glyphBufSize;


	/*
	 * Flush any previous OpenGL errors.  This allows us to check for
	 * new errors so they can be reported via the function return value.
	 */
	while (_GLD_glGetError() != GL_NO_ERROR)
		;

	/*
	 * Make sure that the current font can be sampled accurately.
	 */
	hNewFont = CreateHighResolutionFont(hDC);
	if (!hNewFont)
		return FALSE;

	hOldFont = SelectObject(hDC, hNewFont);
	if (!hOldFont)
		return FALSE;

	/*
	 * Preallocate a buffer for the outline data, and track its size:
	 */
	glyphBuf = (UCHAR*) __wglMalloc(glyphBufSize = 10240);
	if (!glyphBuf)
		return FALSE; /*WGL_STATUS_NOT_ENOUGH_MEMORY*/

	/*
	 * Process each glyph in the given range:
	 */
	for (glyphIndex = first; glyphIndex - first < count; ++glyphIndex)
		{
		GLYPHMETRICS	glyphMetrics;
		DWORD		glyphSize;
		static MAT2	matrix =
			{
			{0, 1},		{0, 0},
			{0, 0},		{0, 1}
			};
		LPGLYPHMETRICSFLOAT glyphMetricsFloat =
			&glyphMetricsFloatArray[glyphIndex - first];


		/*
		 * Determine how much space is needed to store the glyph's
		 * outlines.  If our glyph buffer isn't large enough,
		 * resize it.
		 */
		glyphSize = GetGlyphOutline(	hDC,
						glyphIndex,
						GGO_NATIVE,
						&glyphMetrics,
						0,
						NULL,
						&matrix
						);
		if (glyphSize < 0)
			return FALSE; /*WGL_STATUS_FAILURE*/
		if (glyphSize > glyphBufSize)
			{
			__wglFree(glyphBuf);
			glyphBuf = (UCHAR*) __wglMalloc(glyphBufSize = glyphSize);
			if (!glyphBuf)
				return FALSE; /*WGL_STATUS_NOT_ENOUGH_MEMORY*/
			}


		/*
		 * Get the glyph's outlines.
		 */
		if (GetGlyphOutline(	hDC,
					glyphIndex,
					GGO_NATIVE,
					&glyphMetrics,
					glyphBufSize,
					glyphBuf,
					&matrix
					) < 0)
			{
			__wglFree(glyphBuf);
			return FALSE; /*WGL_STATUS_FAILURE*/
			}
		
		glyphMetricsFloat->gmfBlackBoxX =
			(FLOAT) glyphMetrics.gmBlackBoxX * ScaleFactor;
		glyphMetricsFloat->gmfBlackBoxY =
			(FLOAT) glyphMetrics.gmBlackBoxY * ScaleFactor;
		glyphMetricsFloat->gmfptGlyphOrigin.x =
			(FLOAT) glyphMetrics.gmptGlyphOrigin.x * ScaleFactor;
		glyphMetricsFloat->gmfptGlyphOrigin.y =
			(FLOAT) glyphMetrics.gmptGlyphOrigin.y * ScaleFactor;
		glyphMetricsFloat->gmfCellIncX =
			(FLOAT) glyphMetrics.gmCellIncX * ScaleFactor;
		glyphMetricsFloat->gmfCellIncY =
			(FLOAT) glyphMetrics.gmCellIncY * ScaleFactor;
		
		/*
		 * Turn the glyph into a display list:
		 */
		if (!MakeDisplayListFromGlyph(	(glyphIndex - first) + listBase,
						glyphBuf,
						glyphSize,
						glyphMetricsFloat,
						chordalDeviation + ScaleFactor,
						extrusion,
						format))
			{
			__wglFree(glyphBuf);
			return FALSE; /*WGL_STATUS_FAILURE*/
			}
		}


	/*
	 * Clean up temporary storage and return.  If an error occurred,
	 * clear all OpenGL error flags and return FAILURE status;
	 * otherwise just return SUCCESS.
	 */
	__wglFree(glyphBuf);

	SelectObject(hDC, hOldFont);

	if (_GLD_glGetError() == GL_NO_ERROR)
		return TRUE; /*WGL_STATUS_SUCCESS*/
	else
		{
		while (_GLD_glGetError() != GL_NO_ERROR)
			;
		return FALSE; /*WGL_STATUS_FAILURE*/
		}
	}



/*****************************************************************************
 * CreateHighResolutionFont
 *
 * Gets metrics for the current font and creates an equivalent font
 * scaled to the design units of the font.
 * 
 *****************************************************************************/

static HFONT
CreateHighResolutionFont(HDC hDC)
	{
	UINT otmSize;
	OUTLINETEXTMETRIC *otm;
	LONG fontHeight, fontWidth, fontUnits;
	LOGFONT logFont;

	otmSize = GetOutlineTextMetrics(hDC, 0, NULL);
	if (otmSize == 0) 
		return NULL;

	otm = (OUTLINETEXTMETRIC *) __wglMalloc(otmSize);
	if (otm == NULL)
		return NULL;

	otm->otmSize = otmSize;
	if (GetOutlineTextMetrics(hDC, otmSize, otm) == 0) 
		return NULL;
	
	fontHeight = otm->otmTextMetrics.tmHeight -
			otm->otmTextMetrics.tmInternalLeading;
	fontWidth = otm->otmTextMetrics.tmAveCharWidth;
	fontUnits = (LONG) otm->otmEMSquare;
	
	ScaleFactor = 1.0F / (FLOAT) fontUnits;

	logFont.lfHeight = - ((LONG) fontUnits);
	logFont.lfWidth = (LONG)
		((FLOAT) (fontWidth * fontUnits) / (FLOAT) fontHeight);
	logFont.lfEscapement = 0;
	logFont.lfOrientation = 0;
	logFont.lfWeight = otm->otmTextMetrics.tmWeight;
	logFont.lfItalic = otm->otmTextMetrics.tmItalic;
	logFont.lfUnderline = otm->otmTextMetrics.tmUnderlined;
	logFont.lfStrikeOut = otm->otmTextMetrics.tmStruckOut;
	logFont.lfCharSet = otm->otmTextMetrics.tmCharSet;
	logFont.lfOutPrecision = OUT_OUTLINE_PRECIS;
	logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
	logFont.lfQuality = DEFAULT_QUALITY;
	logFont.lfPitchAndFamily =
		otm->otmTextMetrics.tmPitchAndFamily & 0xf0;
	strcpy(logFont.lfFaceName,
	       (char *)otm + (int)otm->otmpFaceName);

	hNewFont = CreateFontIndirect(&logFont);
	if (hNewFont == NULL)
		return NULL;

	__wglFree(otm);

	return hNewFont;
	}



/*****************************************************************************
 * MakeDisplayListFromGlyph
 * 
 * Converts the outline of a glyph to an OpenGL display list.
 *
 * Return value is nonzero for success, zero for failure.
 *
 * Does not check for OpenGL errors, so if the caller needs to know about them,
 * it should call glGetError().
 *****************************************************************************/

static int
MakeDisplayListFromGlyph(	IN  DWORD		listName,
				IN  UCHAR*		glyphBuf,
				IN  DWORD		glyphSize,
				IN  LPGLYPHMETRICSFLOAT	glyphMetricsFloat,
				IN  FLOAT		chordalDeviation,
				IN  FLOAT		extrusion,
				IN  INT			format)
	{
	int status;

	_GLD_glNewList(listName, GL_COMPILE);
		status = DrawGlyph(	glyphBuf,
					glyphSize,
					chordalDeviation,
					extrusion,
					format);
		
	_GLD_glTranslatef(glyphMetricsFloat->gmfCellIncX,
		     glyphMetricsFloat->gmfCellIncY,
		     0.0F);
	_GLD_glEndList();

	return status;
	}



/*****************************************************************************
 * DrawGlyph
 * 
 * Converts the outline of a glyph to OpenGL drawing primitives, tessellating
 * as needed, and then draws the glyph.  Tessellation of the quadratic splines
 * in the outline is controlled by "chordalDeviation", and the drawing
 * primitives (lines or polygons) are selected by "format".
 *
 * Return value is nonzero for success, zero for failure.
 *
 * Does not check for OpenGL errors, so if the caller needs to know about them,
 * it should call glGetError().
 *****************************************************************************/

static int
DrawGlyph(	IN  UCHAR*	glyphBuf,
		IN  DWORD	glyphSize,
		IN  FLOAT	chordalDeviation,
		IN  FLOAT	extrusion,
		IN  INT		format)
	{
	INT			status = 0;
	FLOAT*			p;
	DWORD			loop;
	DWORD			point;
	GLUtesselator*		tess = NULL;


	/*
	 * Initialize the global buffer into which we place the outlines:
	 */
	if (!InitLineBuf())
		goto exit;


	/*
	 * Convert the glyph outlines to a set of polyline loops.
	 * (See MakeLinesFromGlyph() for the format of the loop data
	 * structure.)
	 */
	if (!MakeLinesFromGlyph(glyphBuf, glyphSize, chordalDeviation))
		goto exit;
	p = LineBuf;


	/*
	 * Now draw the loops in the appropriate format:
	 */
	if (format == WGL_FONT_LINES)
		{
		/*
		 * This is the easy case.  Just draw the outlines.
		 */
		for (loop = (DWORD) *p++; loop; --loop)
			{
			_GLD_glBegin(GL_LINE_LOOP);
				for (point = (DWORD) *p++; point; --point)
					{
					_GLD_glVertex2fv(p);
					p += 2;
					}
			_GLD_glEnd();
			}
		status = 1;
		}

	else if (format == WGL_FONT_POLYGONS)
		{
		double v[3];
		FLOAT *save_p = p;
		GLfloat z_value;
		
		/*
		 * This is the hard case.  We have to set up a tessellator
		 * to convert the outlines into a set of polygonal
		 * primitives, which the tessellator passes to some
		 * auxiliary routines for drawing.
		 */
		if (!LoadGLUTesselator())
			goto exit;
		if (!InitVertBuf())
			goto exit;
		if (!(tess = gluNewTessProc()))
			goto exit;
		gluTessCallbackProc(tess,	GLU_BEGIN,	(void(CALLBACK *)()) _GLD_glBegin);
		gluTessCallbackProc(tess,	GLU_TESS_VERTEX_DATA,
				    (void(CALLBACK *)()) TessVertexOutData);
		gluTessCallbackProc(tess,	GLU_END,	(void(CALLBACK *)()) _GLD_glEnd);
		gluTessCallbackProc(tess,	GLU_ERROR,	(void(CALLBACK *)()) TessError);
		gluTessCallbackProc(tess,	GLU_TESS_COMBINE, (void(CALLBACK *)()) TessCombine);
		gluTessNormalProc(tess,	0.0F, 0.0F, 1.0F);

		TessErrorOccurred = 0;
		_GLD_glNormal3f(0.0f, 0.0f, 1.0f);
		v[2] = 0.0;
		z_value = 0.0f;

		gluTessBeginPolygonProc(tess, (void *)*(int *)&z_value);
			for (loop = (DWORD) *p++; loop; --loop)
				{
				gluTessBeginContourProc(tess);
				
				for (point = (DWORD) *p++; point; --point)
					{
					v[0] = p[0];
					v[1] = p[1];
					gluTessVertexProc(tess, v, p);
					p += 2;
					}

				gluTessEndContourProc(tess);
				}
		gluTessEndPolygonProc(tess);

		status = !TessErrorOccurred;

		/* Extrusion code */
		if (extrusion) {
			DWORD loops;
			GLfloat thickness = (GLfloat) -extrusion;
			FLOAT *vert, *vert2;
			DWORD count;

			p = save_p;
			loops = (DWORD) *p++;

			for (loop = 0; loop < loops; loop++) {
				GLfloat dx, dy, len;
				DWORD last;

				count = (DWORD) *p++;
				_GLD_glBegin(GL_QUAD_STRIP);

				/* Check if the first and last vertex are identical
				 * so we don't draw the same quad twice.
				 */
				vert = p + (count-1)*2;
				last = (p[0] == vert[0] && p[1] == vert[1]) ? count-1 : count;

				for (point = 0; point <= last; point++) {
					vert  = p + 2 * (point % last);
					vert2 = p + 2 * ((point+1) % last);

					dx = vert[0] - vert2[0];
					dy = vert[1] - vert2[1];
					len = (GLfloat)sqrt(dx * dx + dy * dy);

					_GLD_glNormal3f(dy / len, -dx / len, 0.0f);
					_GLD_glVertex3f((GLfloat) vert[0],
							   (GLfloat) vert[1], thickness);
					_GLD_glVertex3f((GLfloat) vert[0],
							   (GLfloat) vert[1], 0.0f);
				}

				_GLD_glEnd();
				p += count*2;
			}

			/* Draw the back face */
			p = save_p;
			v[2] = thickness;
			_GLD_glNormal3f(0.0f, 0.0f, -1.0f);
			gluTessNormalProc(tess,	0.0F, 0.0F, -1.0F);

			gluTessBeginPolygonProc(tess, (void *)*(int *)&thickness);

			for (loop = (DWORD) *p++; loop; --loop)
			{
				count = (DWORD) *p++;

				gluTessBeginContourProc(tess);
				
				for (point = 0; point < count; point++)
				{
					vert = p + ((count-point-1)<<1);
					v[0] = vert[0];
					v[1] = vert[1];
					gluTessVertexProc(tess, v, vert);
				}
				p += count*2;

				gluTessEndContourProc(tess);
			}
			gluTessEndPolygonProc(tess);
		}

#if DEBUG
	if (TessErrorOccurred)
		printf("Tessellation error %s\n",
			gluErrorString(TessErrorOccurred));
#endif
		}


exit:
	FreeLineBuf();
	if (tess)
		gluDeleteTessProc(tess);
	// UnloadGLUTesselator();
	FreeVertBuf();
	return status;
	}



/*****************************************************************************
 * LoadGLUTesselator
 *
 * Maps the glu32.dll module and gets function pointers for the 
 * tesselator functions.
 *****************************************************************************/

static BOOL
LoadGLUTesselator(void)
	{
	if (gluModuleHandle != NULL)
		return TRUE;

	{
		extern HINSTANCE hInstanceOpenGL;
		char *gluName = "GLU32.DLL";
//		char name[256];
//		char *ptr;
//		int len;

/*
		len = GetModuleFileName(hInstanceOpenGL, name, 255);
		if (len != 0)
			{
			ptr = name+len-1;
			while (ptr > name && *ptr != '\\')
				ptr--;
			if (*ptr == '\\')
				ptr++;
			if (!stricmp(ptr, "cosmogl.dll"))
				{
				gluName = "COSMOGLU.DLL";
				}
			else if (!stricmp(ptr, "opengl32.dll"))
				{
				gluName = "GLU32.DLL";
				}
			}
*/
		if ((gluModuleHandle = LoadLibrary(gluName)) == NULL)
			return FALSE;
	}

	if ((gluNewTessProc = (gluNewTessProto)
		GetProcAddress(gluModuleHandle, "gluNewTess")) == NULL)
		return FALSE;
	
	if ((gluDeleteTessProc = (gluDeleteTessProto)
		GetProcAddress(gluModuleHandle, "gluDeleteTess")) == NULL)
		return FALSE;
	
	if ((gluTessBeginPolygonProc = (gluTessBeginPolygonProto)
		GetProcAddress(gluModuleHandle, "gluTessBeginPolygon")) == NULL)
		return FALSE;
	
	if ((gluTessBeginContourProc = (gluTessBeginContourProto)
		GetProcAddress(gluModuleHandle, "gluTessBeginContour")) == NULL)
		return FALSE;
	
	if ((gluTessVertexProc = (gluTessVertexProto)
		GetProcAddress(gluModuleHandle, "gluTessVertex")) == NULL)
		return FALSE;
	
	if ((gluTessEndContourProc = (gluTessEndContourProto)
		GetProcAddress(gluModuleHandle, "gluTessEndContour")) == NULL)
		return FALSE;
	
	if ((gluTessEndPolygonProc = (gluTessEndPolygonProto)
		GetProcAddress(gluModuleHandle, "gluTessEndPolygon")) == NULL)
		return FALSE;
	
	if ((gluTessPropertyProc = (gluTessPropertyProto)
		GetProcAddress(gluModuleHandle, "gluTessProperty")) == NULL)
		return FALSE;

	if ((gluTessNormalProc = (gluTessNormalProto)
		GetProcAddress(gluModuleHandle, "gluTessNormal")) == NULL)
		return FALSE;
	
	if ((gluTessCallbackProc = (gluTessCallbackProto)
		GetProcAddress(gluModuleHandle, "gluTessCallback")) == NULL)
		return FALSE;

	return TRUE;
	}



/*****************************************************************************
 * UnloadGLUTesselator
 *
 * Unmaps the glu32.dll module.
 *****************************************************************************/

static BOOL
UnloadGLUTesselator(void)
	{
	if (gluModuleHandle != NULL)
	    if (FreeLibrary(gluModuleHandle) == FALSE)
		return FALSE;
	gluModuleHandle = NULL;
	}



/*****************************************************************************
 * TessVertexOut
 *
 * Used by tessellator to handle output vertexes.
 *****************************************************************************/
 
static void CALLBACK
TessVertexOut(FLOAT	p[3])
	{
	    GLfloat v[2];

	    v[0] = p[0] * ScaleFactor;
	    v[1] = p[1] * ScaleFactor;
	    _GLD_glVertex2fv(v);
	}

static void CALLBACK
TessVertexOutData(FLOAT	p[3], GLfloat z)
{
    GLfloat v[3];

    v[0] = (GLfloat) p[0];
    v[1] = (GLfloat) p[1];
    v[2] = z;
    _GLD_glVertex3fv(v);
}


/*****************************************************************************
 * TessCombine
 *
 * Used by tessellator to handle self-intersecting contours and degenerate
 * geometry.
 *****************************************************************************/
 
static void CALLBACK
TessCombine(double	coords[3],
	    void*	vertex_data[4],
	    FLOAT	weight[4],
	    void**	outData)
	{
	if (!AppendToVertBuf((FLOAT) coords[0])
	 || !AppendToVertBuf((FLOAT) coords[1])
	 || !AppendToVertBuf((FLOAT) coords[2]))
		TessErrorOccurred = GL_OUT_OF_MEMORY;
	*outData = VertBuf + (VertBufIndex - 3);
	}



/*****************************************************************************
 * TessError
 *
 * Saves the last tessellator error code in the global TessErrorOccurred.
 *****************************************************************************/
 
static void CALLBACK
TessError(GLenum error)
	{
	TessErrorOccurred = error;
	}



/*****************************************************************************
 * MakeLinesFromGlyph
 * 
 * Converts the outline of a glyph from the TTPOLYGON format to a simple
 * array of floating-point values containing one or more loops.
 *
 * The first element of the output array is a count of the number of loops.
 * The loop data follows this count.  Each loop consists of a count of the
 * number of vertices it contains, followed by the vertices.  Each vertex
 * is an X and Y coordinate.  For example, a single triangle might be
 * described by this array:
 *
 *	1.,	3.,	0., 0.,		1., 0.,		0., 1.
 *       ^	 ^	 ^    ^		 ^    ^		 ^    ^
 *     #loops	#verts	 x1   y1	 x2   y2	 x3   y3
 *
 * A two-loop glyph would look like this:
 *
 *	2.,	3.,  0.,0.,  1.,0.,  0.,1.,	3.,  .2,.2,  .4,.2,  .2,.4
 *
 * Line segments from the TTPOLYGON are transferred to the output array in
 * the obvious way.  Quadratic splines in the TTPOLYGON are converted to
 * collections of line segments
 *****************************************************************************/

static int
MakeLinesFromGlyph(IN  UCHAR*	glyphBuf,
		   IN  DWORD	glyphSize,
		   IN  FLOAT	chordalDeviation)
	{
	UCHAR*	p;
	int	status = 0;


	/*
	 * Pick up all the polygons (aka loops) that make up the glyph:
	 */
	if (!AppendToLineBuf(0.0F))	/* loop count at LineBuf[0] */
		goto exit;

	p = glyphBuf;
	while (p < glyphBuf + glyphSize)
		{
		if (!MakeLinesFromTTPolygon(&p, chordalDeviation))
			goto exit;
		LineBuf[0] += 1.0F;	/* increment loop count */
		}

	status = 1;

exit:
	return status;
	}



/*****************************************************************************
 * MakeLinesFromTTPolygon
 *
 * Converts a TTPOLYGONHEADER and its associated curve structures into a
 * single polyline loop in the global LineBuf.
 *****************************************************************************/

static int
MakeLinesFromTTPolygon(	IN OUT	UCHAR**	pp,
			IN	FLOAT	chordalDeviation)
	{
	DWORD	polySize;
	UCHAR*	polyStart;
	DWORD	vertexCountIndex;

	/*
	 * Record where the polygon data begins, and where the loop's
	 * vertex count resides:
	 */
	polyStart = *pp;
	vertexCountIndex = LineBufIndex;
	if (!AppendToLineBuf(0.0F))
		return 0;

	/*
	 * Extract relevant data from the TTPOLYGONHEADER:
	 */
	polySize = GetDWord(pp);
	if (GetDWord(pp) != TT_POLYGON_TYPE)	/* polygon type */
		return 0;
	if (!AppendToLineBuf((FLOAT) GetFixed(pp)))	/* first X coord */
		return 0;
	if (!AppendToLineBuf((FLOAT) GetFixed(pp)))	/* first Y coord */
		return 0;
	LineBuf[vertexCountIndex] += 1.0F;

	/*
	 * Process each of the TTPOLYCURVE structures in the polygon:
	 */
	while (*pp < polyStart + polySize)
		if (!MakeLinesFromTTPolycurve(	pp,
						vertexCountIndex,
						chordalDeviation))
		return 0;

	return 1;
	}



/*****************************************************************************
 * MakeLinesFromTTPolyCurve
 *
 * Converts the lines and splines in a single TTPOLYCURVE structure to points
 * in the global LineBuf.
 *****************************************************************************/

static int
MakeLinesFromTTPolycurve(	IN OUT	UCHAR**	pp,
				IN	DWORD	vertexCountIndex,
				IN	FLOAT	chordalDeviation)
	{
	WORD type;
	WORD pointCount;


	/*
	 * Pick up the relevant fields of the TTPOLYCURVE structure:
	 */
	type = (WORD) GetWord(pp);
	pointCount = (WORD) GetWord(pp);

	/*
	 * Convert the "curve" to line segments:
	 */
	if (type == TT_PRIM_LINE)
		return MakeLinesFromTTLine(	pp,
						vertexCountIndex,
						pointCount);
	else if (type == TT_PRIM_QSPLINE)
		return MakeLinesFromTTQSpline(	pp,
						vertexCountIndex,
						pointCount,
						chordalDeviation);
	else
		return 0;
	}



/*****************************************************************************
 * MakeLinesFromTTLine
 *
 * Converts points from the polyline in a TT_PRIM_LINE structure to
 * equivalent points in the global LineBuf.
 *****************************************************************************/
static int
MakeLinesFromTTLine(	IN OUT	UCHAR**	pp,
			IN	DWORD	vertexCountIndex,
			IN	WORD	pointCount)
	{
	/*
	 * Just copy the line segments into the line buffer (converting
	 * type as we go):
	 */
	LineBuf[vertexCountIndex] += pointCount;
	while (pointCount--)
		{
		if (!AppendToLineBuf((FLOAT) GetFixed(pp))	/* X coord */
		 || !AppendToLineBuf((FLOAT) GetFixed(pp)))	/* Y coord */
			return 0;
		}

	return 1;
	}



/*****************************************************************************
 * MakeLinesFromTTQSpline
 *
 * Converts points from the poly quadratic spline in a TT_PRIM_QSPLINE
 * structure to polyline points in the global LineBuf.
 *****************************************************************************/

static int
MakeLinesFromTTQSpline(	IN OUT	UCHAR**	pp,
			IN	DWORD	vertexCountIndex,
			IN	WORD	pointCount,
			IN	FLOAT	chordalDeviation)
	{
	FLOAT x0, y0, x1, y1, x2, y2;
	WORD point;

	/*
	 * Process each of the non-interpolated points in the outline.
	 * To do this, we need to generate two interpolated points (the
	 * start and end of the arc) for each non-interpolated point.
	 * The first interpolated point is always the one most recently
	 * stored in LineBuf, so we just extract it from there.  The
	 * second interpolated point is either the average of the next
	 * two points in the QSpline, or the last point in the QSpline
	 * if only one remains.
	 */
	for (point = 0; point < pointCount - 1; ++point)
		{
		x0 = LineBuf[LineBufIndex - 2];
		y0 = LineBuf[LineBufIndex - 1];

		x1 = (FLOAT) GetFixed(pp);
		y1 = (FLOAT) GetFixed(pp);

		if (point == pointCount - 2)
			{
			/*
			 * This is the last arc in the QSpline.  The final
			 * point is the end of the arc.
			 */
			x2 = (FLOAT) GetFixed(pp);
			y2 = (FLOAT) GetFixed(pp);
			}
		else
			{
			/*
			 * Peek at the next point in the input to compute
			 * the end of the arc:
			 */
			x2 = 0.5F * (x1 + (FLOAT) GetFixed(pp));
			y2 = 0.5F * (y1 + (FLOAT) GetFixed(pp));
			/*
			 * Push the point back onto the input so it will
			 * be reused as the next off-curve point:
			 */
			*pp -= 8;
			}

		if (!MakeLinesFromArc(	x0, y0,
					x1, y1,
					x2, y2,
					vertexCountIndex,
					chordalDeviation * chordalDeviation))
			return 0;
		}

	return 1;
	}



/*****************************************************************************
 * MakeLinesFromArc
 *
 * Subdivides one arc of a quadratic spline until the chordal deviation
 * tolerance requirement is met, then places the resulting set of line
 * segments in the global LineBuf.
 *****************************************************************************/

static int
MakeLinesFromArc(	IN	FLOAT	x0,
			IN	FLOAT	y0,
			IN	FLOAT	x1,
			IN	FLOAT	y1,
			IN	FLOAT	x2,
			IN	FLOAT	y2,
			IN	DWORD	vertexCountIndex,
			IN	FLOAT	chordalDeviationSquared)
	{
	FLOAT	x01;
	FLOAT	y01;
	FLOAT	x12;
	FLOAT	y12;
	FLOAT	midPointX;
	FLOAT	midPointY;
	FLOAT	deltaX;
	FLOAT	deltaY;

	/*
	 * Calculate midpoint of the curve by de Casteljau:
	 */
	x01 = 0.5F * (x0 + x1);
	y01 = 0.5F * (y0 + y1);
	x12 = 0.5F * (x1 + x2);
	y12 = 0.5F * (y1 + y2);
	midPointX = 0.5F * (x01 + x12);
	midPointY = 0.5F * (y01 + y12);


	/*
	 * Estimate chordal deviation by the distance from the midpoint
	 * of the curve to its non-interpolated control point.  If this
	 * distance is greater than the specified chordal deviation
	 * constraint, then subdivide.  Otherwise, generate polylines
	 * from the three control points.
	 */
	deltaX = midPointX - x1;
	deltaY = midPointY - y1;
	if (deltaX * deltaX + deltaY * deltaY > chordalDeviationSquared)
		{
		MakeLinesFromArc(	x0, y0,
					x01, y01,
					midPointX, midPointY,
					vertexCountIndex,
					chordalDeviationSquared);
		
		MakeLinesFromArc(	midPointX, midPointY,
					x12, y12,
					x2, y2,
					vertexCountIndex,
					chordalDeviationSquared);
		}
	else
		{
		/*
		 * The "pen" is already at (x0, y0), so we don't need to
		 * add that point to the LineBuf.
		 */
		if (!AppendToLineBuf(x1)
		 || !AppendToLineBuf(y1)
		 || !AppendToLineBuf(x2)
		 || !AppendToLineBuf(y2))
			return 0;
		LineBuf[vertexCountIndex] += 2.0F;
		}

	return 1;
	}



/*****************************************************************************
 * InitLineBuf
 *
 * Initializes the global LineBuf and its associated size and current-element
 * counters.
 *****************************************************************************/

static int
InitLineBuf(void)
	{
	if (!(LineBuf = (FLOAT*)
		__wglMalloc((LineBufSize = LINE_BUF_QUANT) * sizeof(FLOAT))))
			return 0;
	LineBufIndex = 0;
	return 1;
	}



/*****************************************************************************
 * InitVertBuf
 *
 * Initializes the global VertBuf and its associated size and current-element
 * counters.
 *****************************************************************************/

static int
InitVertBuf(void)
	{
	if (!(VertBuf = (FLOAT*)
		__wglMalloc((VertBufSize = VERT_BUF_QUANT) * sizeof(FLOAT))))
			return 0;
	VertBufIndex = 0;
	return 1;
	}



/*****************************************************************************
 * AppendToLineBuf
 *
 * Appends one floating-point value to the global LineBuf array.  Return value
 * is non-zero for success, zero for failure.
 *****************************************************************************/

static int
AppendToLineBuf(FLOAT value)
	{
	if (LineBufIndex >= LineBufSize)
		{
		FLOAT* f;
		
		f = (FLOAT*) __wglRealloc(LineBuf,
			(LineBufSize += LINE_BUF_QUANT) * sizeof(FLOAT));
		if (!f)
			return 0;
		LineBuf = f;
		}
	LineBuf[LineBufIndex++] = value;
	return 1;
	}



/*****************************************************************************
 * AppendToVertBuf
 *
 * Appends one floating-point value to the global VertBuf array.  Return value
 * is non-zero for success, zero for failure.
 *
 * Note that we can't realloc this one, because the tessellator is using
 * pointers into it.
 *****************************************************************************/

static int
AppendToVertBuf(FLOAT value)
	{
	if (VertBufIndex >= VertBufSize)
		return 0;
	VertBuf[VertBufIndex++] = value;
	return 1;
	}



/*****************************************************************************
 * FreeLineBuf
 *
 * Cleans up vertex buffer structure.
 *****************************************************************************/

static void
FreeLineBuf(void)
	{
	if (LineBuf)
		{
		__wglFree(LineBuf);
		LineBuf = NULL;
		}
	}



/*****************************************************************************
 * FreeVertBuf
 *
 * Cleans up vertex buffer structure.
 *****************************************************************************/

static void
FreeVertBuf(void)
	{
	if (VertBuf)
		{
		__wglFree(VertBuf);
		VertBuf = NULL;
		}
	}



/*****************************************************************************
 * GetWord
 *
 * Fetch the next 16-bit word from a little-endian byte stream, and increment
 * the stream pointer to the next unscanned byte.
 *****************************************************************************/

static long GetWord(UCHAR** p)
	{
	long value;

	value = ((*p)[1] << 8) + (*p)[0];
	*p += 2;
	return value;
	}



/*****************************************************************************
 * GetDWord
 *
 * Fetch the next 32-bit word from a little-endian byte stream, and increment
 * the stream pointer to the next unscanned byte.
 *****************************************************************************/

static long GetDWord(UCHAR** p)
	{
	long value;

	value = ((*p)[3] << 24) + ((*p)[2] << 16) + ((*p)[1] << 8) + (*p)[0];
	*p += 4;
	return value;
	}




/*****************************************************************************
 * GetFixed
 *
 * Fetch the next 32-bit fixed-point value from a little-endian byte stream,
 * convert it to floating-point, and increment the stream pointer to the next
 * unscanned byte.
 *****************************************************************************/

static double GetFixed(
	UCHAR** p)
{
	long hiBits, loBits;
	double value;

	loBits = GetWord(p);
	hiBits = GetWord(p);
	value = (double) ((hiBits << 16) | loBits) / 65536.0;

	return value * ScaleFactor;
}

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