aboutsummaryrefslogtreecommitdiffstats
path: root/src/mesa/drivers/osmesa/osmesa.c
blob: b93683ae2a72fe69b1c2b8e26d8358a51580999b (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
/* $Id: osmesa.c,v 1.59 2001/06/27 13:56:17 brianp Exp $ */

/*
 * Mesa 3-D graphics library
 * Version:  3.5
 *
 * Copyright (C) 1999-2001  Brian Paul   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
 * BRIAN PAUL 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.
 */


/*
 * Off-Screen Mesa rendering / Rendering into client memory space
 *
 * Note on thread safety:  this driver is thread safe.  All
 * functions are reentrant.  The notion of current context is
 * managed by the core _mesa_make_current() and _mesa_get_current_context()
 * functions.  Those functions are thread-safe.
 */


#include "glheader.h"
#include "GL/osmesa.h"
#include "context.h"
#include "colormac.h"
#include "depth.h"
#include "extensions.h"
#include "macros.h"
#include "matrix.h"
#include "mem.h"
#include "mmath.h"
#include "mtypes.h"
#include "texformat.h"
#include "texstore.h"
#include "array_cache/acache.h"
#include "swrast/swrast.h"
#include "swrast_setup/swrast_setup.h"
#include "swrast/s_context.h"
#include "swrast/s_depth.h"
#include "swrast/s_lines.h"
#include "swrast/s_triangle.h"
#include "swrast/s_trispan.h"
#include "tnl/tnl.h"
#include "tnl/t_context.h"
#include "tnl/t_pipeline.h"



/*
 * This is the OS/Mesa context struct.
 * Notice how it includes a GLcontext.  By doing this we're mimicking
 * C++ inheritance/derivation.
 * Later, we can cast a GLcontext pointer into an OSMesaContext pointer
 * or vice versa.
 */
struct osmesa_context {
   GLcontext gl_ctx;		/* The core GL/Mesa context */
   GLvisual *gl_visual;		/* Describes the buffers */
   GLframebuffer *gl_buffer;	/* Depth, stencil, accum, etc buffers */
   GLenum format;		/* either GL_RGBA or GL_COLOR_INDEX */
   void *buffer;		/* the image buffer */
   GLint width, height;		/* size of image buffer */
   GLint rowlength;		/* number of pixels per row */
   GLint userRowLength;		/* user-specified number of pixels per row */
   GLint rshift, gshift;	/* bit shifts for RGBA formats */
   GLint bshift, ashift;
   GLint rInd, gInd, bInd, aInd;/* index offsets for RGBA formats */
   GLchan *rowaddr[MAX_HEIGHT];	/* address of first pixel in each image row */
   GLboolean yup;		/* TRUE  -> Y increases upward */
				/* FALSE -> Y increases downward */
};



/* A forward declaration: */
static void osmesa_update_state( GLcontext *ctx, GLuint newstate );
static void osmesa_register_swrast_functions( GLcontext *ctx );



#define OSMESA_CONTEXT(ctx)  ((OSMesaContext) (ctx->DriverCtx))



/**********************************************************************/
/*****                    Public Functions                        *****/
/**********************************************************************/


/*
 * Create an Off-Screen Mesa rendering context.  The only attribute needed is
 * an RGBA vs Color-Index mode flag.
 *
 * Input:  format - either GL_RGBA or GL_COLOR_INDEX
 *         sharelist - specifies another OSMesaContext with which to share
 *                     display lists.  NULL indicates no sharing.
 * Return:  an OSMesaContext or 0 if error
 */
OSMesaContext GLAPIENTRY
OSMesaCreateContext( GLenum format, OSMesaContext sharelist )
{
   return OSMesaCreateContextExt(format, DEFAULT_SOFTWARE_DEPTH_BITS,
                                 8, 16, sharelist);
}



/*
 * New in Mesa 3.5
 *
 * Create context and specify size of ancillary buffers.
 */
OSMesaContext GLAPIENTRY
OSMesaCreateContextExt( GLenum format, GLint depthBits, GLint stencilBits,
                        GLint accumBits, OSMesaContext sharelist )
{
   OSMesaContext osmesa;
   GLint rshift, gshift, bshift, ashift;
   GLint rind, gind, bind, aind;
   GLint indexBits = 0, redBits = 0, greenBits = 0, blueBits = 0, alphaBits =0;
   GLboolean rgbmode;
   GLboolean swalpha;
   const GLuint i4 = 1;
   const GLubyte *i1 = (GLubyte *) &i4;
   const GLint little_endian = *i1;

   swalpha = GL_FALSE;
   rind = gind = bind = aind = 0;
   if (format==OSMESA_COLOR_INDEX) {
      indexBits = 8;
      rshift = gshift = bshift = ashift = 0;
      rgbmode = GL_FALSE;
   }
   else if (format==OSMESA_RGBA) {
      indexBits = 0;
      redBits = CHAN_BITS;
      greenBits = CHAN_BITS;
      blueBits = CHAN_BITS;
      alphaBits = CHAN_BITS;
      rind = 0;
      gind = 1;
      bind = 2;
      aind = 3;
      if (little_endian) {
         rshift = 0;
         gshift = 8;
         bshift = 16;
         ashift = 24;
      }
      else {
         rshift = 24;
         gshift = 16;
         bshift = 8;
         ashift = 0;
      }
      rgbmode = GL_TRUE;
   }
   else if (format==OSMESA_BGRA) {
      indexBits = 0;
      redBits = CHAN_BITS;
      greenBits = CHAN_BITS;
      blueBits = CHAN_BITS;
      alphaBits = CHAN_BITS;
      rind = 2;
      gind = 1;
      bind = 0;
      aind = 3;
      if (little_endian) {
         ashift = 0;
         rshift = 8;
         gshift = 16;
         bshift = 24;
      }
      else {
         bshift = 24;
         gshift = 16;
         rshift = 8;
         ashift = 0;
      }
      rgbmode = GL_TRUE;
   }
   else if (format==OSMESA_ARGB) {
      indexBits = 0;
      redBits = CHAN_BITS;
      greenBits = CHAN_BITS;
      blueBits = CHAN_BITS;
      alphaBits = CHAN_BITS;
      rind = 1;
      gind = 2;
      bind = 3;
      aind = 0;
      if (little_endian) {
         bshift = 0;
         gshift = 8;
         rshift = 16;
         ashift = 24;
      }
      else {
         ashift = 24;
         rshift = 16;
         gshift = 8;
         bshift = 0;
      }
      rgbmode = GL_TRUE;
   }
   else if (format==OSMESA_RGB) {
      indexBits = 0;
      redBits = CHAN_BITS;
      greenBits = CHAN_BITS;
      blueBits = CHAN_BITS;
      alphaBits = 0;
      bshift = 0;
      gshift = 8;
      rshift = 16;
      ashift = 24;
      rind = 0;
      gind = 1;
      bind = 2;
      rgbmode = GL_TRUE;
      swalpha = GL_TRUE;
   }
   else if (format==OSMESA_BGR) {
      indexBits = 0;
      redBits = CHAN_BITS;
      greenBits = CHAN_BITS;
      blueBits = CHAN_BITS;
      alphaBits = 0;
      bshift = 0;
      gshift = 8;
      rshift = 16;
      ashift = 24;
      rind = 2;
      gind = 1;
      bind = 0;
      rgbmode = GL_TRUE;
      swalpha = GL_TRUE;
   }
   else if (format==OSMESA_RGB_565) {
      indexBits = 0;
      redBits = 5;
      greenBits = 6;
      blueBits = 5;
      alphaBits = 0;
      rshift = 11;
      gshift = 5;
      bshift = 0;
      ashift = 0;
      rind = 0; /* not used */
      gind = 0;
      bind = 0;
      rgbmode = GL_TRUE;
      swalpha = GL_FALSE;
   }
   else {
      return NULL;
   }


   osmesa = (OSMesaContext) CALLOC_STRUCT(osmesa_context);
   if (osmesa) {
      osmesa->gl_visual = _mesa_create_visual( rgbmode,
                                               GL_FALSE,    /* double buffer */
                                               GL_FALSE,    /* stereo */
                                               redBits,
                                               greenBits,
                                               blueBits,
                                               alphaBits,
                                               indexBits,
                                               depthBits,
                                               stencilBits,
                                               accumBits,
                                               accumBits,
                                               accumBits,
                                               alphaBits ? accumBits : 0,
                                               1            /* num samples */
                                               );
      if (!osmesa->gl_visual) {
         FREE(osmesa);
         return NULL;
      }

      if (!_mesa_initialize_context(&osmesa->gl_ctx,
                                    osmesa->gl_visual,
                                    sharelist ? &sharelist->gl_ctx
                                              : (GLcontext *) NULL,
                                    (void *) osmesa, GL_TRUE )) {
         _mesa_destroy_visual( osmesa->gl_visual );
         FREE(osmesa);
         return NULL;
      }

      _mesa_enable_sw_extensions(&(osmesa->gl_ctx));

      osmesa->gl_buffer = _mesa_create_framebuffer( osmesa->gl_visual,
                                          osmesa->gl_visual->depthBits > 0,
                                          osmesa->gl_visual->stencilBits > 0,
                                          osmesa->gl_visual->accumRedBits > 0,
                                          swalpha );

      if (!osmesa->gl_buffer) {
         _mesa_destroy_visual( osmesa->gl_visual );
         _mesa_free_context_data( &osmesa->gl_ctx );
         FREE(osmesa);
         return NULL;
      }
      osmesa->format = format;
      osmesa->buffer = NULL;
      osmesa->width = 0;
      osmesa->height = 0;
      osmesa->userRowLength = 0;
      osmesa->rowlength = 0;
      osmesa->yup = GL_TRUE;
      osmesa->rshift = rshift;
      osmesa->gshift = gshift;
      osmesa->bshift = bshift;
      osmesa->ashift = ashift;
      osmesa->rInd = rind;
      osmesa->gInd = gind;
      osmesa->bInd = bind;
      osmesa->aInd = aind;


      /* Initialize the software rasterizer and helper modules.
       */
      {
	 GLcontext *ctx = &osmesa->gl_ctx;

	 _swrast_CreateContext( ctx );
	 _ac_CreateContext( ctx );
	 _tnl_CreateContext( ctx );
	 _swsetup_CreateContext( ctx );
	
	 osmesa_register_swrast_functions( ctx );
      }
   }
   return osmesa;
}




/*
 * Destroy an Off-Screen Mesa rendering context.
 *
 * Input:  ctx - the context to destroy
 */
void GLAPIENTRY OSMesaDestroyContext( OSMesaContext ctx )
{
   if (ctx) {
      _swsetup_DestroyContext( &ctx->gl_ctx );
      _tnl_DestroyContext( &ctx->gl_ctx );
      _ac_DestroyContext( &ctx->gl_ctx );
      _swrast_DestroyContext( &ctx->gl_ctx );

      _mesa_destroy_visual( ctx->gl_visual );
      _mesa_destroy_framebuffer( ctx->gl_buffer );
      _mesa_free_context_data( &ctx->gl_ctx );
      FREE( ctx );
   }
}



/*
 * Recompute the values of the context's rowaddr array.
 */
static void compute_row_addresses( OSMesaContext ctx )
{
   GLint bytesPerPixel, bytesPerRow, i;
   GLubyte *origin = (GLubyte *) ctx->buffer;

   if (ctx->format == OSMESA_COLOR_INDEX) {
      /* CI mode */
      bytesPerPixel = 1 * sizeof(GLchan);
   }
   else if ((ctx->format == OSMESA_RGB) || (ctx->format == OSMESA_BGR)) {
      /* RGB mode */
      bytesPerPixel = 3 * sizeof(GLchan);
   }
   else if (ctx->format == OSMESA_RGB_565) {
      /* 5/6/5 RGB pixel in 16 bits */
      bytesPerPixel = 2;
   }
   else {
      /* RGBA mode */
      bytesPerPixel = 4 * sizeof(GLchan);
   }

   bytesPerRow = ctx->rowlength * bytesPerPixel;

   if (ctx->yup) {
      /* Y=0 is bottom line of window */
      for (i = 0; i < MAX_HEIGHT; i++) {
         ctx->rowaddr[i] = (GLchan *) ((GLubyte *) origin + i * bytesPerRow);
      }
   }
   else {
      /* Y=0 is top line of window */
      for (i = 0; i < MAX_HEIGHT; i++) {
         GLint j = ctx->height - i - 1;
         ctx->rowaddr[i] = (GLchan *) ((GLubyte *) origin + j * bytesPerRow);
      }
   }
}


/*
 * Bind an OSMesaContext to an image buffer.  The image buffer is just a
 * block of memory which the client provides.  Its size must be at least
 * as large as width*height*sizeof(type).  Its address should be a multiple
 * of 4 if using RGBA mode.
 *
 * Image data is stored in the order of glDrawPixels:  row-major order
 * with the lower-left image pixel stored in the first array position
 * (ie. bottom-to-top).
 *
 * Since the only type initially supported is GL_UNSIGNED_BYTE, if the
 * context is in RGBA mode, each pixel will be stored as a 4-byte RGBA
 * value.  If the context is in color indexed mode, each pixel will be
 * stored as a 1-byte value.
 *
 * If the context's viewport hasn't been initialized yet, it will now be
 * initialized to (0,0,width,height).
 *
 * Input:  ctx - the rendering context
 *         buffer - the image buffer memory
 *         type - data type for pixel components, only GL_UNSIGNED_BYTE
 *                and GL_UNSIGNED_SHORT_5_6_5 supported now.
 *         width, height - size of image buffer in pixels, at least 1
 * Return:  GL_TRUE if success, GL_FALSE if error because of invalid ctx,
 *          invalid buffer address, type!=GL_UNSIGNED_BYTE, width<1, height<1,
 *          width>internal limit or height>internal limit.
 */
GLboolean GLAPIENTRY
OSMesaMakeCurrent( OSMesaContext ctx, void *buffer, GLenum type,
                   GLsizei width, GLsizei height )
{
   if (!ctx || !buffer ||
       width < 1 || height < 1 ||
       width > MAX_WIDTH || height > MAX_HEIGHT) {
      return GL_FALSE;
   }

   if (ctx->format == OSMESA_RGB_565 && type != GL_UNSIGNED_SHORT_5_6_5) {
      return GL_FALSE;
   }
   else if (type != CHAN_TYPE) {
      return GL_FALSE;
   }

   osmesa_update_state( &ctx->gl_ctx, 0 );
   _mesa_make_current( &ctx->gl_ctx, ctx->gl_buffer );

   ctx->buffer = buffer;
   ctx->width = width;
   ctx->height = height;
   if (ctx->userRowLength)
      ctx->rowlength = ctx->userRowLength;
   else
      ctx->rowlength = width;

   compute_row_addresses( ctx );

   /* init viewport */
   if (ctx->gl_ctx.Viewport.Width==0) {
      /* initialize viewport and scissor box to buffer size */
      _mesa_Viewport( 0, 0, width, height );
      ctx->gl_ctx.Scissor.Width = width;
      ctx->gl_ctx.Scissor.Height = height;
   }

   return GL_TRUE;
}



OSMesaContext GLAPIENTRY OSMesaGetCurrentContext( void )
{
   GLcontext *ctx = _mesa_get_current_context();
   if (ctx)
      return (OSMesaContext) ctx;
   else
      return NULL;
}



void GLAPIENTRY OSMesaPixelStore( GLint pname, GLint value )
{
   OSMesaContext ctx = OSMesaGetCurrentContext();

   switch (pname) {
      case OSMESA_ROW_LENGTH:
         if (value<0) {
            _mesa_error( &ctx->gl_ctx, GL_INVALID_VALUE,
                      "OSMesaPixelStore(value)" );
            return;
         }
         ctx->userRowLength = value;
         ctx->rowlength = value;
         break;
      case OSMESA_Y_UP:
         ctx->yup = value ? GL_TRUE : GL_FALSE;
         break;
      default:
         _mesa_error( &ctx->gl_ctx, GL_INVALID_ENUM, "OSMesaPixelStore(pname)" );
         return;
   }

   compute_row_addresses( ctx );
}


void GLAPIENTRY OSMesaGetIntegerv( GLint pname, GLint *value )
{
   OSMesaContext ctx = OSMesaGetCurrentContext();

   switch (pname) {
      case OSMESA_WIDTH:
         *value = ctx->width;
         return;
      case OSMESA_HEIGHT:
         *value = ctx->height;
         return;
      case OSMESA_FORMAT:
         *value = ctx->format;
         return;
      case OSMESA_TYPE:
         *value = CHAN_TYPE;
         return;
      case OSMESA_ROW_LENGTH:
         *value = ctx->rowlength;
         return;
      case OSMESA_Y_UP:
         *value = ctx->yup;
         return;
      default:
         _mesa_error(&ctx->gl_ctx, GL_INVALID_ENUM, "OSMesaGetIntergerv(pname)");
         return;
   }
}

/*
 * Return the depth buffer associated with an OSMesa context.
 * Input:  c - the OSMesa context
 * Output:  width, height - size of buffer in pixels
 *          bytesPerValue - bytes per depth value (2 or 4)
 *          buffer - pointer to depth buffer values
 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
 */
GLboolean GLAPIENTRY
OSMesaGetDepthBuffer( OSMesaContext c, GLint *width, GLint *height,
                      GLint *bytesPerValue, void **buffer )
{
   if ((!c->gl_buffer) || (!c->gl_buffer->DepthBuffer)) {
      *width = 0;
      *height = 0;
      *bytesPerValue = 0;
      *buffer = 0;
      return GL_FALSE;
   }
   else {
      *width = c->gl_buffer->Width;
      *height = c->gl_buffer->Height;
      if (c->gl_visual->depthBits <= 16)
         *bytesPerValue = sizeof(GLushort);
      else
         *bytesPerValue = sizeof(GLuint);
      *buffer = c->gl_buffer->DepthBuffer;
      return GL_TRUE;
   }
}

/*
 * Return the color buffer associated with an OSMesa context.
 * Input:  c - the OSMesa context
 * Output:  width, height - size of buffer in pixels
 *          format - the pixel format (OSMESA_FORMAT)
 *          buffer - pointer to color buffer values
 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
 */
GLboolean GLAPIENTRY
OSMesaGetColorBuffer( OSMesaContext c, GLint *width,
                      GLint *height, GLint *format, void **buffer )
{
   if (!c->buffer) {
      *width = 0;
      *height = 0;
      *format = 0;
      *buffer = 0;
      return GL_FALSE;
   }
   else {
      *width = c->width;
      *height = c->height;
      *format = c->format;
      *buffer = c->buffer;
      return GL_TRUE;
   }
}

/**********************************************************************/
/*** Device Driver Functions                                        ***/
/**********************************************************************/


/*
 * Useful macros:
 */

#define PACK_RGBA(DST, R, G, B, A)	\
do {					\
   (DST)[osmesa->rInd] = R;		\
   (DST)[osmesa->gInd] = G;		\
   (DST)[osmesa->bInd] = B;		\
   (DST)[osmesa->aInd] = A;		\
} while (0)

#define PACK_RGB(DST, R, G, B)  \
do {				\
   (DST)[0] = R;		\
   (DST)[1] = G;		\
   (DST)[2] = B;		\
} while (0)

#define PACK_BGR(DST, R, G, B)  \
do {				\
   (DST)[0] = B;		\
   (DST)[1] = G;		\
   (DST)[2] = R;		\
} while (0)

#define PACK_RGB_565(DST, R, G, B)					\
do {									\
   (DST) = (((R) << 8) & 0xf800) | (((G) << 3) & 0x7e0) | ((B) >> 3);\
} while (0)


#define UNPACK_RED(P)      ( (P)[osmesa->rInd] )
#define UNPACK_GREEN(P)    ( (P)[osmesa->gInd] )
#define UNPACK_BLUE(P)     ( (P)[osmesa->bInd] )
#define UNPACK_ALPHA(P)    ( (P)[osmesa->aInd] )


#define PIXELADDR1(X,Y)  (osmesa->rowaddr[Y] + (X))
#define PIXELADDR2(X,Y)  (osmesa->rowaddr[Y] + 2 * (X))
#define PIXELADDR3(X,Y)  (osmesa->rowaddr[Y] + 3 * (X))
#define PIXELADDR4(X,Y)  (osmesa->rowaddr[Y] + 4 * (X))



static GLboolean set_draw_buffer( GLcontext *ctx, GLenum mode )
{
   (void) ctx;
   if (mode==GL_FRONT_LEFT) {
      return GL_TRUE;
   }
   else {
      return GL_FALSE;
   }
}


static void set_read_buffer( GLcontext *ctx, GLframebuffer *buffer, GLenum mode )
{
   /* separate read buffer not supported */
   ASSERT(buffer == ctx->DrawBuffer);
   ASSERT(mode == GL_FRONT_LEFT);
}


static void clear( GLcontext *ctx, GLbitfield mask, GLboolean all,
		   GLint x, GLint y, GLint width, GLint height )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLuint *colorMask = (GLuint *) &ctx->Color.ColorMask;

   /* sanity check - we only have a front-left buffer */
   ASSERT((mask & (DD_FRONT_RIGHT_BIT | DD_BACK_LEFT_BIT | DD_BACK_RIGHT_BIT)) == 0);
   if (*colorMask == 0xffffffff && ctx->Color.IndexMask == 0xffffffff) {
      if (mask & DD_FRONT_LEFT_BIT) {
	 if (osmesa->format == OSMESA_COLOR_INDEX) {
	    if (all) {
	       /* Clear whole CI buffer */
#if CHAN_TYPE == GL_UNSIGNED_BYTE
	       MEMSET(osmesa->buffer, ctx->Color.ClearIndex,
		      osmesa->rowlength * osmesa->height);
#else
	       const GLint n = osmesa->rowlength * osmesa->height;
	       GLchan *buffer = (GLchan *) osmesa->buffer;
	       GLint i;
	       for (i = 0; i < n; i ++) {
		  buffer[i] = ctx->Color.ClearIndex;
	       }
#endif
	    }
	    else {
	       /* Clear part of CI buffer */
	       const GLchan clearIndex = (GLchan) ctx->Color.ClearIndex;
	       GLint i, j;
	       for (i = 0; i < height; i++) {
		  GLchan *ptr1 = PIXELADDR1(x, (y + i));
		  for (j = 0; j < width; j++) {
		     *ptr1++ = clearIndex;
		  }
	       }
	    }
	 }
	 else if (osmesa->format == OSMESA_RGB) {
	    const GLchan r = ctx->Color.ClearColor[0];
	    const GLchan g = ctx->Color.ClearColor[1];
	    const GLchan b = ctx->Color.ClearColor[2];
	    if (all) {
	       /* Clear whole RGB buffer */
	       GLuint n = osmesa->rowlength * osmesa->height;
	       GLchan *ptr3 = (GLchan *) osmesa->buffer;
	       GLuint i;
	       for (i = 0; i < n; i++) {
		  PACK_RGB(ptr3, r, g, b);
		  ptr3 += 3;
	       }
	    }
	    else {
	       /* Clear part of RGB buffer */
	       GLint i, j;
	       for (i = 0; i < height; i++) {
		  GLchan *ptr3 = PIXELADDR3(x, (y + i));
		  for (j = 0; j < width; j++) {
		     PACK_RGB(ptr3, r, g, b);
		     ptr3 += 3;
		  }
	       }
	    }
	 }
	 else if (osmesa->format == OSMESA_BGR) {
	    const GLchan r = ctx->Color.ClearColor[0];
	    const GLchan g = ctx->Color.ClearColor[1];
	    const GLchan b = ctx->Color.ClearColor[2];
	    if (all) {
	       /* Clear whole RGB buffer */
	       const GLint n = osmesa->rowlength * osmesa->height;
	       GLchan *ptr3 = (GLchan *) osmesa->buffer;
	       GLint i;
	       for (i = 0; i < n; i++) {
		  PACK_BGR(ptr3, r, g, b);
		  ptr3 += 3;
	       }
	    }
	    else {
	       /* Clear part of RGB buffer */
	       GLint i, j;
	       for (i = 0; i < height; i++) {
		  GLchan *ptr3 = PIXELADDR3(x, (y + i));
		  for (j = 0; j < width; j++) {
		     PACK_BGR(ptr3, r, g, b);
		     ptr3 += 3;
		  }
	       }
	    }
	 }
         else if (osmesa->format == OSMESA_RGB_565) {
	    const GLchan r = ctx->Color.ClearColor[0];
	    const GLchan g = ctx->Color.ClearColor[1];
	    const GLchan b = ctx->Color.ClearColor[2];
            GLushort clearPixel;
            PACK_RGB_565(clearPixel, r, g, b);
            if (all) {
               /* Clear whole RGB buffer */
	       const GLint n = osmesa->rowlength * osmesa->height;
               GLushort *ptr2 = (GLushort *) osmesa->buffer;
               GLuint  i;
               for (i = 0; i < n; i++) {
                  *ptr2 = clearPixel;
                  ptr2++;
               }
            }
            else {
               /* clear scissored region */
               GLint i, j;
               for (i = 0; i < height; i++) {
                  GLushort *ptr2 = (GLushort *) PIXELADDR2(x, (y + i));
                  for (j = 0; j < width; j++) {
                     *ptr2 = clearPixel;
                     ptr2++;
                  }
               }
            }
         }
	 else {
#if CHAN_TYPE == GL_UNSIGNED_BYTE
	    /* 4-byte pixel value */
	    GLuint clearPixel;
	    GLchan *clr = (GLchan *) &clearPixel;
	    clr[osmesa->rInd] = ctx->Color.ClearColor[0];
	    clr[osmesa->gInd] = ctx->Color.ClearColor[1];
	    clr[osmesa->bInd] = ctx->Color.ClearColor[2];
	    clr[osmesa->aInd] = ctx->Color.ClearColor[3];
	    if (all) {
	       /* Clear whole RGBA buffer */
	       const GLuint n = osmesa->rowlength * osmesa->height;
	       GLuint *ptr4 = (GLuint *) osmesa->buffer;
	       GLuint i;
	       if (clearPixel) {
		  for (i = 0; i < n; i++) {
		     *ptr4++ = clearPixel;
		  }
	       }
	       else {
		  BZERO(ptr4, n * sizeof(GLuint));
	       }
	    }
	    else {
	       /* Clear part of RGBA buffer */
	       GLint i, j;
	       for (i = 0; i < height; i++) {
		  GLuint *ptr4 = (GLuint *) PIXELADDR4(x, (y + i));
		  for (j = 0; j < width; j++) {
		     *ptr4++ = clearPixel;
		  }
	       }
	    }
#else
	    const GLchan r = ctx->Color.ClearColor[0];
	    const GLchan g = ctx->Color.ClearColor[1];
	    const GLchan b = ctx->Color.ClearColor[2];
	    const GLchan a = ctx->Color.ClearColor[3];
	    if (all) {
	       /* Clear whole RGBA buffer */
	       const GLuint n = osmesa->rowlength * osmesa->height;
	       GLchan *p = (GLchan *) osmesa->buffer;
	       GLuint i;
	       for (i = 0; i < n; i++) {
		  PACK_RGBA(p, r, g, b, a);
		  p += 4;
	       }
	    }
	    else {
	       /* Clear part of RGBA buffer */
	       GLint i, j;
	       for (i = 0; i < height; i++) {
		  GLchan *p = PIXELADDR4(x, (y + i));
		  for (j = 0; j < width; j++) {
		     PACK_RGBA(p, r, g, b, a);
		     p += 4;
		  }
	       }
	    }

#endif
	 }
	 mask &= ~DD_FRONT_LEFT_BIT;
      }
   }
   
   if (mask)
      _swrast_Clear( ctx, mask, all, x, y, width, height );
}



static void buffer_size( GLcontext *ctx, GLuint *width, GLuint *height )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   *width = osmesa->width;
   *height = osmesa->height;
}


/**********************************************************************/
/*****        Read/write spans/arrays of RGBA pixels              *****/
/**********************************************************************/

/* Write RGBA pixels to an RGBA (or permuted) buffer. */
static void
write_rgba_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                 CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR4(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p += 4) {
         if (mask[i]) {
            PACK_RGBA(p, rgba[i][RCOMP], rgba[i][GCOMP],
                         rgba[i][BCOMP], rgba[i][ACOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p += 4) {
         PACK_RGBA(p, rgba[i][RCOMP], rgba[i][GCOMP],
                      rgba[i][BCOMP], rgba[i][ACOMP]);
      }
   }
}


/* Write RGBA pixels to an RGBA buffer.  This is the fastest span-writer. */
static void
write_rgba_span_rgba( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                      CONST GLchan rgba[][4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint *ptr4 = (GLuint *) PIXELADDR4(x, y);
   const GLuint *rgba4 = (const GLuint *) rgba;
   GLuint i;
   ASSERT(CHAN_TYPE == GL_UNSIGNED_BYTE);
   if (mask) {
      for (i = 0; i < n; i++) {
         if (mask[i]) {
            ptr4[i] = rgba4[i];
         }
      }
   }
   else {
      MEMCPY( ptr4, rgba4, n * 4 );
   }
}


/* Write RGB pixels to an RGBA (or permuted) buffer. */
static void
write_rgb_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                CONST GLchan rgb[][3], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR4(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p+=4) {
         if (mask[i]) {
            PACK_RGBA(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP], CHAN_MAX);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p+=4) {
         PACK_RGBA(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP], CHAN_MAX);
      }
   }
}



static void
write_monocolor_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                      const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR4(x, y);
   GLuint i;
   for (i = 0; i < n; i++, p += 4) {
      if (mask[i]) {
         PACK_RGBA(p, color[RCOMP], color[GCOMP], color[BCOMP], color[ACOMP]);
      }
   }
}



static void
write_rgba_pixels( const GLcontext *ctx, GLuint n,
                   const GLint x[], const GLint y[],
                   CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR4(x[i], y[i]);
         PACK_RGBA(p, rgba[i][RCOMP], rgba[i][GCOMP],
                      rgba[i][BCOMP], rgba[i][ACOMP]);
      }
   }
}



static void
write_monocolor_pixels( const GLcontext *ctx, GLuint n,
                        const GLint x[], const GLint y[],
                        const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR4(x[i], y[i]);
         PACK_RGBA(p, color[RCOMP], color[GCOMP], color[BCOMP], color[ACOMP]);
      }
   }
}


static void
read_rgba_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                GLchan rgba[][4] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   GLchan *p = PIXELADDR4(x, y);
   for (i = 0; i < n; i++, p += 4) {
      rgba[i][RCOMP] = UNPACK_RED(p);
      rgba[i][GCOMP] = UNPACK_GREEN(p);
      rgba[i][BCOMP] = UNPACK_BLUE(p);
      rgba[i][ACOMP] = UNPACK_ALPHA(p);
   }
}


/* Read RGBA pixels from an RGBA buffer */
static void
read_rgba_span_rgba( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                     GLchan rgba[][4] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint *ptr4 = (GLuint *) PIXELADDR4(x, y);
   MEMCPY( rgba, ptr4, n * 4 * sizeof(GLchan) );
}


static void
read_rgba_pixels( const GLcontext *ctx,
                  GLuint n, const GLint x[], const GLint y[],
                  GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         const GLchan *p = PIXELADDR4(x[i], y[i]);
         rgba[i][RCOMP] = UNPACK_RED(p);
         rgba[i][GCOMP] = UNPACK_GREEN(p);
         rgba[i][BCOMP] = UNPACK_BLUE(p);
         rgba[i][ACOMP] = UNPACK_ALPHA(p);
      }
   }
}

/**********************************************************************/
/*****                3 byte RGB pixel support funcs              *****/
/**********************************************************************/

/* Write RGBA pixels to an RGB buffer. */
static void
write_rgba_span_RGB( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                     CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p += 3) {
         if (mask[i]) {
            PACK_RGB(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p += 3) {
         PACK_RGB(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}

/* Write RGBA pixels to an BGR buffer. */
static void
write_rgba_span_BGR( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                     CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p += 3) {
         if (mask[i]) {
            PACK_BGR(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p += 3) {
         PACK_BGR(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}

/* Write RGB pixels to an RGB buffer. */
static void
write_rgb_span_RGB( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                    CONST GLchan rgb[][3], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p += 3) {
         if (mask[i]) {
            PACK_RGB(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p += 3) {
         PACK_RGB(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
      }
   }
}

/* Write RGB pixels to an BGR buffer. */
static void
write_rgb_span_BGR( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                    CONST GLchan rgb[][3], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, p += 3) {
         if (mask[i]) {
            PACK_BGR(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, p += 3) {
         PACK_BGR(p, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
      }
   }
}


static void
write_monocolor_span_RGB( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                          const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   for (i = 0; i < n; i++, p += 3) {
      if (mask[i]) {
         PACK_RGB(p, color[RCOMP], color[GCOMP], color[BCOMP]);
      }
   }
}

static void
write_monocolor_span_BGR( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                          const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *p = PIXELADDR3(x, y);
   GLuint i;
   for (i = 0; i < n; i++, p += 3) {
      if (mask[i]) {
         PACK_BGR(p, color[RCOMP], color[GCOMP], color[BCOMP]);
      }
   }
}

static void
write_rgba_pixels_RGB( const GLcontext *ctx, GLuint n,
                       const GLint x[], const GLint y[],
                       CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = (const OSMesaContext) ctx;
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR3(x[i], y[i]);
         PACK_RGB(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}

static void
write_rgba_pixels_BGR( const GLcontext *ctx, GLuint n,
                       const GLint x[], const GLint y[],
                       CONST GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = (const OSMesaContext) ctx;
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR3(x[i], y[i]);
         PACK_BGR(p, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}

static void
write_monocolor_pixels_RGB( const GLcontext *ctx,
                            GLuint n, const GLint x[], const GLint y[],
                            const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR3(x[i], y[i]);
         PACK_RGB(p, color[RCOMP], color[GCOMP], color[BCOMP]);
      }
   }
}

static void
write_monocolor_pixels_BGR( const GLcontext *ctx,
                            GLuint n, const GLint x[], const GLint y[],
                            const GLchan color[4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLchan *p = PIXELADDR3(x[i], y[i]);
         PACK_BGR(p, color[RCOMP], color[GCOMP], color[BCOMP]);
      }
   }
}

static void
read_rgba_span3( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                 GLchan rgba[][4] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   const GLchan *p = PIXELADDR3(x, y);
   for (i = 0; i < n; i++, p += 3) {
      rgba[i][RCOMP] = UNPACK_RED(p);
      rgba[i][GCOMP] = UNPACK_GREEN(p);
      rgba[i][BCOMP] = UNPACK_BLUE(p);
      rgba[i][ACOMP] = CHAN_MAX;
   }
}

static void
read_rgba_pixels3( const GLcontext *ctx,
                   GLuint n, const GLint x[], const GLint y[],
                   GLchan rgba[][4], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         const GLchan *p = PIXELADDR3(x[i], y[i]);
         rgba[i][RCOMP] = UNPACK_RED(p);
         rgba[i][GCOMP] = UNPACK_GREEN(p);
         rgba[i][BCOMP] = UNPACK_BLUE(p);
         rgba[i][ACOMP] = CHAN_MAX;
      }
   }
}


/**********************************************************************/
/*****                2 byte RGB pixel support funcs              *****/
/**********************************************************************/

/* Write RGBA pixels to an RGB_565 buffer. */
static void
write_rgba_span2( const GLcontext *ctx,
                  GLuint n, GLint x, GLint y,
                  CONST GLubyte rgba[][4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLushort *ptr2 = (GLushort *) PIXELADDR2(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, ptr2++) {
         if (mask[i]) {
            PACK_RGB_565(*ptr2, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, ptr2++) {
         PACK_RGB_565(*ptr2, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}


/* Write RGB pixels to an RGB_565 buffer. */
static void
write_rgb_span2( const GLcontext *ctx,
                 GLuint n, GLint x, GLint y,
                 CONST GLubyte rgb[][3], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLushort *ptr2 = (GLushort *) PIXELADDR2(x, y);
   GLuint i;
   if (mask) {
      for (i = 0; i < n; i++, ptr2++) {
         if (mask[i]) {
            PACK_RGB_565(*ptr2, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
         }
      }
   }
   else {
      for (i = 0; i < n; i++, ptr2++) {
         PACK_RGB_565(*ptr2, rgb[i][RCOMP], rgb[i][GCOMP], rgb[i][BCOMP]);
      }
   }
}


static void
write_monocolor_span2( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                       const GLchan color[4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLushort pixel;
   GLushort *ptr2 = (GLushort *) PIXELADDR2(x, y);
   GLuint i;
   PACK_RGB_565(pixel, color[RCOMP], color[GCOMP], color[BCOMP]);
   for (i = 0; i < n; i++, ptr2++) {
      if (mask[i]) {
         *ptr2 = pixel;
      }
   }
}


static void
write_rgba_pixels2( const GLcontext *ctx,
                    GLuint n, const GLint x[], const GLint y[],
                    CONST GLubyte rgba[][4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLushort *ptr2 = (GLushort *) PIXELADDR2(x[i],y[i]);
         PACK_RGB_565(*ptr2, rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
      }
   }
}

static void
write_monocolor_pixels2( const GLcontext *ctx,
                         GLuint n, const GLint x[], const GLint y[],
                         const GLchan color[4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   GLushort pixel;
   PACK_RGB_565(pixel, color[RCOMP], color[GCOMP], color[BCOMP]);
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         GLushort *ptr2 = (GLushort *) PIXELADDR2(x[i],y[i]);
         *ptr2 = pixel;
      }
   }
}

static void
read_rgba_span2( const GLcontext *ctx,
                 GLuint n, GLint x, GLint y,
                 GLubyte rgba[][4] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   const GLushort *ptr2 = (const GLushort *) PIXELADDR2(x, y);
   for (i = 0; i < n; i++, ptr2++) {
      /* This should be fixed to get the low bits right */
      rgba[i][RCOMP] = (*ptr2 >> 8) & 0xFe;
      rgba[i][GCOMP] = (*ptr2 >> 3) & 0xFc;
      rgba[i][BCOMP] = (*ptr2 << 3) & 0xFe;
      rgba[i][ACOMP] = 0;
   }
}

static void
read_rgba_pixels2( const GLcontext *ctx,
                   GLuint n, const GLint x[], const GLint y[],
                   GLubyte rgba[][4], const GLubyte mask[] )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i = 0; i < n; i++) {
      if (mask[i]) {
         /* This should be fixed to get the low bits right */
         const GLushort *ptr2 = (const GLushort *) PIXELADDR2(x[i],y[i]);
         rgba[i][RCOMP] = (*ptr2 >> 8) & 0xFE;
         rgba[i][GCOMP] = (*ptr2 >> 3) & 0xFC;
         rgba[i][BCOMP] = (*ptr2 << 3) & 0xFE;
         rgba[i][ACOMP] = 0;
      }
   }
}



/**********************************************************************/
/*****        Read/write spans/arrays of CI pixels                *****/
/**********************************************************************/

/* Write 32-bit color index to buffer */
static void
write_index32_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                    const GLuint index[], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *ptr1 = PIXELADDR1(x, y);
   GLuint i;
   if (mask) {
      for (i=0;i<n;i++,ptr1++) {
         if (mask[i]) {
            *ptr1 = (GLchan) index[i];
         }
      }
   }
   else {
      for (i=0;i<n;i++,ptr1++) {
         *ptr1 = (GLchan) index[i];
      }
   }
}


/* Write 8-bit color index to buffer */
static void
write_index8_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                   const GLubyte index[], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *ptr1 = PIXELADDR1(x, y);
   GLuint i;
   if (mask) {
      for (i=0;i<n;i++,ptr1++) {
         if (mask[i]) {
            *ptr1 = (GLchan) index[i];
         }
      }
   }
   else {
      MEMCPY(ptr1, index, n * sizeof(GLchan));
   }
}


static void
write_monoindex_span( const GLcontext *ctx, GLuint n, GLint x, GLint y,
                      GLuint colorIndex, const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLchan *ptr1 = PIXELADDR1(x, y);
   GLuint i;
   for (i=0;i<n;i++,ptr1++) {
      if (mask[i]) {
         *ptr1 = (GLchan) colorIndex;
      }
   }
}


static void
write_index_pixels( const GLcontext *ctx,
                    GLuint n, const GLint x[], const GLint y[],
                    const GLuint index[], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i=0;i<n;i++) {
      if (mask[i]) {
         GLchan *ptr1 = PIXELADDR1(x[i], y[i]);
         *ptr1 = (GLchan) index[i];
      }
   }
}


static void
write_monoindex_pixels( const GLcontext *ctx,
                        GLuint n, const GLint x[], const GLint y[],
                        GLuint colorIndex, const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i=0;i<n;i++) {
      if (mask[i]) {
         GLchan *ptr1 = PIXELADDR1(x[i], y[i]);
         *ptr1 = (GLchan) colorIndex;
      }
   }
}


static void
read_index_span( const GLcontext *ctx,
                 GLuint n, GLint x, GLint y, GLuint index[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   const GLchan *ptr1 = (const GLchan *) PIXELADDR1(x, y);
   for (i=0;i<n;i++,ptr1++) {
      index[i] = (GLuint) *ptr1;
   }
}


static void
read_index_pixels( const GLcontext *ctx,
                   GLuint n, const GLint x[], const GLint y[],
                   GLuint index[], const GLubyte mask[] )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   GLuint i;
   for (i=0;i<n;i++) {
      if (mask[i] ) {
         const GLchan *ptr1 = PIXELADDR1(x[i], y[i]);
         index[i] = (GLuint) *ptr1;
      }
   }
}



/**********************************************************************/
/*****                   Optimized line rendering                 *****/
/**********************************************************************/


/*
 * Draw a flat-shaded, RGB line into an osmesa buffer.
 */
static void
flat_rgba_line( GLcontext *ctx, const SWvertex *vert0, const SWvertex *vert1 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLchan *color = vert0->color;

#define INTERP_XY 1
#define CLIP_HACK 1
#define PLOT(X, Y)						\
do {								\
   GLchan *p = PIXELADDR4(X, Y);				\
   PACK_RGBA(p, color[0], color[1], color[2], color[3]);	\
} while (0)

#ifdef WIN32
#include "..\swrast\s_linetemp.h"
#else
#include "swrast/s_linetemp.h"
#endif
}


/*
 * Draw a flat-shaded, Z-less, RGB line into an osmesa buffer.
 */
static void
flat_rgba_z_line(GLcontext *ctx, const SWvertex *vert0, const SWvertex *vert1)
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLchan *color = vert0->color;

#define INTERP_XY 1
#define INTERP_Z 1
#define DEPTH_TYPE DEFAULT_SOFTWARE_DEPTH_TYPE
#define CLIP_HACK 1
#define PLOT(X, Y)					\
do {							\
   if (Z < *zPtr) {					\
      GLchan *p = PIXELADDR4(X, Y);			\
      PACK_RGBA(p, color[RCOMP], color[GCOMP],		\
                   color[BCOMP], color[ACOMP]);		\
      *zPtr = Z;					\
   }							\
} while (0)


#ifdef WIN32
#include "..\swrast\s_linetemp.h"
#else
#include "swrast/s_linetemp.h"
#endif
}


/*
 * Draw a flat-shaded, alpha-blended, RGB line into an osmesa buffer.
 * XXX update for GLchan
 */
static void
flat_blend_rgba_line( GLcontext *ctx,
                      const SWvertex *vert0, const SWvertex *vert1 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLint rshift = osmesa->rshift;
   const GLint gshift = osmesa->gshift;
   const GLint bshift = osmesa->bshift;
   const GLint avalue = vert0->color[3];
   const GLint msavalue = CHAN_MAX - avalue;
   const GLint rvalue = vert0->color[0]*avalue;
   const GLint gvalue = vert0->color[1]*avalue;
   const GLint bvalue = vert0->color[2]*avalue;

#define INTERP_XY 1
#define CLIP_HACK 1
#define PLOT(X,Y)					\
   { GLuint *ptr4 = (GLuint *) PIXELADDR4(X, Y);	\
     GLuint  pixel = 0;					\
     pixel |=((((((*ptr4) >> rshift) & 0xff)*msavalue+rvalue)>>8) << rshift);\
     pixel |=((((((*ptr4) >> gshift) & 0xff)*msavalue+gvalue)>>8) << gshift);\
     pixel |=((((((*ptr4) >> bshift) & 0xff)*msavalue+bvalue)>>8) << bshift);\
     *ptr4 = pixel;					\
   }

#ifdef WIN32
#include "..\swrast\s_linetemp.h"
#else
#include "swrast/s_linetemp.h"
#endif
}


/*
 * Draw a flat-shaded, Z-less, alpha-blended, RGB line into an osmesa buffer.
 * XXX update for GLchan
 */
static void
flat_blend_rgba_z_line( GLcontext *ctx,
                        const SWvertex *vert0, const SWvertex *vert1 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLint rshift = osmesa->rshift;
   const GLint gshift = osmesa->gshift;
   const GLint bshift = osmesa->bshift;
   const GLint avalue = vert0->color[3];
   const GLint msavalue = 256 - avalue;
   const GLint rvalue = vert0->color[0]*avalue;
   const GLint gvalue = vert0->color[1]*avalue;
   const GLint bvalue = vert0->color[2]*avalue;

#define INTERP_XY 1
#define INTERP_Z 1
#define DEPTH_TYPE DEFAULT_SOFTWARE_DEPTH_TYPE
#define CLIP_HACK 1
#define PLOT(X,Y)							\
	if (Z < *zPtr) {						\
	   GLuint *ptr4 = (GLuint *) PIXELADDR4(X, Y);			\
	   GLuint  pixel = 0;						\
	   pixel |=((((((*ptr4) >> rshift) & 0xff)*msavalue+rvalue)>>8) << rshift);	\
	   pixel |=((((((*ptr4) >> gshift) & 0xff)*msavalue+gvalue)>>8) << gshift);	\
	   pixel |=((((((*ptr4) >> bshift) & 0xff)*msavalue+bvalue)>>8) << bshift);	\
	   *ptr4 = pixel; 						\
	}

#ifdef WIN32
#include "..\swrast\s_linetemp.h"
#else
#include "swrast/s_linetemp.h"
#endif
}


/*
 * Draw a flat-shaded, Z-less, alpha-blended, RGB line into an osmesa buffer.
 * XXX update for GLchan
 */
static void
flat_blend_rgba_z_line_write( GLcontext *ctx,
                              const SWvertex *vert0, const SWvertex *vert1 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const GLint rshift = osmesa->rshift;
   const GLint gshift = osmesa->gshift;
   const GLint bshift = osmesa->bshift;
   const GLint avalue = vert0->color[3];
   const GLint msavalue = 256 - avalue;
   const GLint rvalue = vert0->color[0]*avalue;
   const GLint gvalue = vert0->color[1]*avalue;
   const GLint bvalue = vert0->color[2]*avalue;

#define INTERP_XY 1
#define INTERP_Z 1
#define DEPTH_TYPE DEFAULT_SOFTWARE_DEPTH_TYPE
#define CLIP_HACK 1
#define PLOT(X,Y)							\
	if (Z < *zPtr) {						\
	   GLuint *ptr4 = (GLuint *) PIXELADDR4(X, Y);			\
	   GLuint  pixel = 0;						\
	   pixel |=((((((*ptr4) >> rshift) & 0xff)*msavalue+rvalue)>>8) << rshift);	\
	   pixel |=((((((*ptr4) >> gshift) & 0xff)*msavalue+gvalue)>>8) << gshift);	\
	   pixel |=((((((*ptr4) >> bshift) & 0xff)*msavalue+bvalue)>>8) << bshift);	\
	   *ptr4 = pixel;						\
	   *zPtr = Z;							\
	}

#ifdef WIN32
#include "..\swrast\s_linetemp.h"
#else
#include "swrast/s_linetemp.h"
#endif
}


/*
 * Analyze context state to see if we can provide a fast line drawing
 * function, like those in lines.c.  Otherwise, return NULL.
 */
static swrast_line_func
osmesa_choose_line_function( GLcontext *ctx )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const SWcontext *swrast = SWRAST_CONTEXT(ctx);

   if (CHAN_BITS != 8)                    return NULL;
   if (ctx->RenderMode != GL_RENDER)      return NULL;
   if (ctx->Line.SmoothFlag)              return NULL;
   if (ctx->Texture._ReallyEnabled)       return NULL;
   if (ctx->Light.ShadeModel != GL_FLAT)  return NULL;
   if (ctx->Line.Width != 1.0F)           return NULL;
   if (ctx->Line.StippleFlag)             return NULL;
   if (ctx->Line.SmoothFlag)              return NULL;
   if (osmesa->format != OSMESA_RGBA &&
       osmesa->format != OSMESA_BGRA &&
       osmesa->format != OSMESA_ARGB)     return NULL;

   if (swrast->_RasterMask==DEPTH_BIT
       && ctx->Depth.Func==GL_LESS
       && ctx->Depth.Mask==GL_TRUE
       && ctx->Visual.depthBits == DEFAULT_SOFTWARE_DEPTH_BITS) {
      return flat_rgba_z_line;
   }

   if (swrast->_RasterMask == 0) {
      return flat_rgba_line;
   }

   if (swrast->_RasterMask==(DEPTH_BIT|BLEND_BIT)
       && ctx->Depth.Func==GL_LESS
       && ctx->Depth.Mask==GL_TRUE
       && ctx->Visual.depthBits == DEFAULT_SOFTWARE_DEPTH_BITS
       && ctx->Color.BlendSrcRGB==GL_SRC_ALPHA
       && ctx->Color.BlendDstRGB==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendSrcA==GL_SRC_ALPHA
       && ctx->Color.BlendDstA==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendEquation==GL_FUNC_ADD_EXT) {
      return flat_blend_rgba_z_line_write;
   }

   if (swrast->_RasterMask==(DEPTH_BIT|BLEND_BIT)
       && ctx->Depth.Func==GL_LESS
       && ctx->Depth.Mask==GL_FALSE
       && ctx->Visual.depthBits == DEFAULT_SOFTWARE_DEPTH_BITS
       && ctx->Color.BlendSrcRGB==GL_SRC_ALPHA
       && ctx->Color.BlendDstRGB==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendSrcA==GL_SRC_ALPHA
       && ctx->Color.BlendDstA==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendEquation==GL_FUNC_ADD_EXT) {
      return flat_blend_rgba_z_line;
   }

   if (swrast->_RasterMask==BLEND_BIT
       && ctx->Color.BlendSrcRGB==GL_SRC_ALPHA
       && ctx->Color.BlendDstRGB==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendSrcA==GL_SRC_ALPHA
       && ctx->Color.BlendDstA==GL_ONE_MINUS_SRC_ALPHA
       && ctx->Color.BlendEquation==GL_FUNC_ADD_EXT) {
      return flat_blend_rgba_line;
   }

   return NULL;
}


/**********************************************************************/
/*****                 Optimized triangle rendering               *****/
/**********************************************************************/


/*
 * Smooth-shaded, z-less triangle, RGBA color.
 */
static void smooth_rgba_z_triangle( GLcontext *ctx,
				    const SWvertex *v0,
                                    const SWvertex *v1,
                                    const SWvertex *v2 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);

#define INTERP_Z 1
#define DEPTH_TYPE DEFAULT_SOFTWARE_DEPTH_TYPE
#define INTERP_RGB 1
#define INTERP_ALPHA 1
#define RENDER_SPAN( span )					\
   GLuint i;							\
   GLchan *img = PIXELADDR4(span.x, span.y); 			\
   for (i = 0; i < span.count; i++, img += 4) {			\
      const GLdepth z = FixedToDepth(span.z);			\
      if (z < zRow[i]) {					\
         PACK_RGBA(img, FixedToInt(span.red),			\
            FixedToInt(span.green), FixedToInt(span.blue),	\
            FixedToInt(span.alpha));				\
         zRow[i] = z;						\
      }								\
      span.red += span.redStep;					\
      span.green += span.greenStep;				\
      span.blue += span.blueStep;				\
      span.alpha += span.alphaStep;				\
      span.z += span.zStep;					\
   }

#ifdef WIN32
#include "..\swrast\s_tritemp.h"
#else
#include "swrast/s_tritemp.h"
#endif
}




/*
 * Flat-shaded, z-less triangle, RGBA color.
 */
static void flat_rgba_z_triangle( GLcontext *ctx,
				  const SWvertex *v0,
                                  const SWvertex *v1,
                                  const SWvertex *v2 )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
#define INTERP_Z 1
#define DEPTH_TYPE DEFAULT_SOFTWARE_DEPTH_TYPE
#define SETUP_CODE						\
   GLuint pixel;						\
   PACK_RGBA((GLchan *) &pixel, v0->color[0], v0->color[1],	\
                                v0->color[2], v0->color[3]);

#define RENDER_SPAN( span )				\
   GLuint i;						\
   GLuint *img = (GLuint *) PIXELADDR4(span.x, span.y);	\
   for (i = 0; i < span.count; i++) {			\
      const GLdepth z = FixedToDepth(span.z);		\
      if (z < zRow[i]) {				\
         img[i] = pixel;				\
         zRow[i] = z;					\
      }							\
      span.z += span.zStep;				\
   }

#ifdef WIN32
#include "..\swrast\s_tritemp.h"
#else
#include "swrast/s_tritemp.h"
#endif
}



/*
 * Return pointer to an accelerated triangle function if possible.
 */
static swrast_tri_func
osmesa_choose_triangle_function( GLcontext *ctx )
{
   const OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   const SWcontext *swrast = SWRAST_CONTEXT(ctx);

   if (CHAN_BITS != 8)                  return (swrast_tri_func) NULL;
   if (ctx->RenderMode != GL_RENDER)    return (swrast_tri_func) NULL;
   if (ctx->Polygon.SmoothFlag)         return (swrast_tri_func) NULL;
   if (ctx->Polygon.StippleFlag)        return (swrast_tri_func) NULL;
   if (ctx->Texture._ReallyEnabled)     return (swrast_tri_func) NULL;
   if (osmesa->format != OSMESA_RGBA &&
       osmesa->format != OSMESA_BGRA &&
       osmesa->format != OSMESA_ARGB)   return (swrast_tri_func) NULL;

   if (swrast->_RasterMask == DEPTH_BIT &&
       ctx->Depth.Func == GL_LESS &&
       ctx->Depth.Mask == GL_TRUE &&
       ctx->Visual.depthBits == DEFAULT_SOFTWARE_DEPTH_BITS) {
      if (ctx->Light.ShadeModel == GL_SMOOTH) {
         return smooth_rgba_z_triangle;
      }
      else {
         return flat_rgba_z_triangle;
      }
   }
   return (swrast_tri_func) NULL;
}



/* Override for the swrast triangle-selection function.  Try to use one
 * of our internal triangle functions, otherwise fall back to the
 * standard swrast functions.
 */
static void osmesa_choose_triangle( GLcontext *ctx )
{
   SWcontext *swrast = SWRAST_CONTEXT(ctx);

   swrast->Triangle = osmesa_choose_triangle_function( ctx );
   if (!swrast->Triangle)
      _swrast_choose_triangle( ctx );
}

static void osmesa_choose_line( GLcontext *ctx )
{
   SWcontext *swrast = SWRAST_CONTEXT(ctx);

   swrast->Line = osmesa_choose_line_function( ctx );
   if (!swrast->Line)
      _swrast_choose_line( ctx );
}


#define OSMESA_NEW_LINE   (_NEW_LINE | \
                           _NEW_TEXTURE | \
                           _NEW_LIGHT | \
                           _NEW_DEPTH | \
                           _NEW_RENDERMODE | \
                           _SWRAST_NEW_RASTERMASK)

#define OSMESA_NEW_TRIANGLE (_NEW_POLYGON | \
                             _NEW_TEXTURE | \
                             _NEW_LIGHT | \
                             _NEW_DEPTH | \
                             _NEW_RENDERMODE | \
                             _SWRAST_NEW_RASTERMASK)


/* Extend the software rasterizer with our line and triangle
 * functions.
 */
static void osmesa_register_swrast_functions( GLcontext *ctx )
{
   SWcontext *swrast = SWRAST_CONTEXT( ctx );

   swrast->choose_line = osmesa_choose_line;
   swrast->choose_triangle = osmesa_choose_triangle;

   swrast->invalidate_line |= OSMESA_NEW_LINE;
   swrast->invalidate_triangle |= OSMESA_NEW_TRIANGLE;
}


static const GLubyte *get_string( GLcontext *ctx, GLenum name )
{
   (void) ctx;
   switch (name) {
      case GL_RENDERER:
         return (const GLubyte *) "Mesa OffScreen";
      default:
         return NULL;
   }
}


static void osmesa_update_state( GLcontext *ctx, GLuint new_state )
{
   OSMesaContext osmesa = OSMESA_CONTEXT(ctx);
   struct swrast_device_driver *swdd = _swrast_GetDeviceDriverReference( ctx );
   TNLcontext *tnl = TNL_CONTEXT(ctx);

   ASSERT((void *) osmesa == (void *) ctx->DriverCtx);

   /*
    * XXX these function pointers could be initialized just once during
    * context creation since they don't depend on any state changes.
    */

   ctx->Driver.GetString = get_string;
   ctx->Driver.UpdateState = osmesa_update_state;
   ctx->Driver.SetDrawBuffer = set_draw_buffer;
   ctx->Driver.ResizeBuffersMESA = _swrast_alloc_buffers;
   ctx->Driver.GetBufferSize = buffer_size;

   ctx->Driver.Accum = _swrast_Accum;
   ctx->Driver.Bitmap = _swrast_Bitmap;
   ctx->Driver.Clear = clear;
   ctx->Driver.CopyPixels = _swrast_CopyPixels;
   ctx->Driver.DrawPixels = _swrast_DrawPixels;
   ctx->Driver.ReadPixels = _swrast_ReadPixels;

   ctx->Driver.ChooseTextureFormat = _mesa_choose_tex_format;
   ctx->Driver.TexImage1D = _mesa_store_teximage1d;
   ctx->Driver.TexImage2D = _mesa_store_teximage2d;
   ctx->Driver.TexImage3D = _mesa_store_teximage3d;
   ctx->Driver.TexSubImage1D = _mesa_store_texsubimage1d;
   ctx->Driver.TexSubImage2D = _mesa_store_texsubimage2d;
   ctx->Driver.TexSubImage3D = _mesa_store_texsubimage3d;
   ctx->Driver.TestProxyTexImage = _mesa_test_proxy_teximage;

   ctx->Driver.CopyTexImage1D = _swrast_copy_teximage1d;
   ctx->Driver.CopyTexImage2D = _swrast_copy_teximage2d;
   ctx->Driver.CopyTexSubImage1D = _swrast_copy_texsubimage1d;
   ctx->Driver.CopyTexSubImage2D = _swrast_copy_texsubimage2d;
   ctx->Driver.CopyTexSubImage3D = _swrast_copy_texsubimage3d;
   ctx->Driver.CopyColorTable = _swrast_CopyColorTable;
   ctx->Driver.CopyColorSubTable = _swrast_CopyColorSubTable;
   ctx->Driver.CopyConvolutionFilter1D = _swrast_CopyConvolutionFilter1D;
   ctx->Driver.CopyConvolutionFilter2D = _swrast_CopyConvolutionFilter2D;


   /* RGB(A) span/pixel functions */
   if (osmesa->format == OSMESA_RGB) {
      swdd->WriteRGBASpan = write_rgba_span_RGB;
      swdd->WriteRGBSpan = write_rgb_span_RGB;
      swdd->WriteMonoRGBASpan = write_monocolor_span_RGB;
      swdd->WriteRGBAPixels = write_rgba_pixels_RGB;
      swdd->WriteMonoRGBAPixels = write_monocolor_pixels_RGB;
      swdd->ReadRGBASpan = read_rgba_span3;
      swdd->ReadRGBAPixels = read_rgba_pixels3;
   }
   else if (osmesa->format == OSMESA_BGR) {
      swdd->WriteRGBASpan = write_rgba_span_BGR;
      swdd->WriteRGBSpan = write_rgb_span_BGR;
      swdd->WriteMonoRGBASpan = write_monocolor_span_BGR;
      swdd->WriteRGBAPixels = write_rgba_pixels_BGR;
      swdd->WriteMonoRGBAPixels = write_monocolor_pixels_BGR;
      swdd->ReadRGBASpan = read_rgba_span3;
      swdd->ReadRGBAPixels = read_rgba_pixels3;
   }
   else if (osmesa->format == OSMESA_RGB_565) {
      swdd->WriteRGBASpan = write_rgba_span2;
      swdd->WriteRGBSpan = write_rgb_span2;
      swdd->WriteMonoRGBASpan = write_monocolor_span2;
      swdd->WriteRGBAPixels = write_rgba_pixels2;
      swdd->WriteMonoRGBAPixels = write_monocolor_pixels2;
      swdd->ReadRGBASpan = read_rgba_span2;
      swdd->ReadRGBAPixels = read_rgba_pixels2;
   }
   else {
      /* 4 GLchan / pixel in frame buffer */
      swdd->WriteRGBSpan = write_rgb_span;
      swdd->WriteRGBAPixels = write_rgba_pixels;
      swdd->WriteMonoRGBASpan = write_monocolor_span;
      swdd->WriteMonoRGBAPixels = write_monocolor_pixels;
      if (osmesa->format == OSMESA_RGBA &&
          CHAN_TYPE == GL_UNSIGNED_BYTE &&
          RCOMP==0 && GCOMP==1 && BCOMP==2 && ACOMP==3) {
         /* special, fast case */
         swdd->WriteRGBASpan = write_rgba_span_rgba;
         swdd->ReadRGBASpan = read_rgba_span_rgba;
      }
      else {
         swdd->WriteRGBASpan = write_rgba_span;
         swdd->ReadRGBASpan = read_rgba_span;
      }
      swdd->ReadRGBAPixels = read_rgba_pixels;
   }

   /* CI span/pixel functions */
   swdd->WriteCI32Span = write_index32_span;
   swdd->WriteCI8Span = write_index8_span;
   swdd->WriteMonoCISpan = write_monoindex_span;
   swdd->WriteCI32Pixels = write_index_pixels;
   swdd->WriteMonoCIPixels = write_monoindex_pixels;
   swdd->ReadCI32Span = read_index_span;
   swdd->ReadCI32Pixels = read_index_pixels;

   swdd->SetReadBuffer = set_read_buffer;

   tnl->Driver.RunPipeline = _tnl_run_pipeline;
   tnl->Driver.RenderStart = _swsetup_RenderStart;
   tnl->Driver.RenderFinish = _swsetup_RenderFinish;
   tnl->Driver.BuildProjectedVertices = _swsetup_BuildProjectedVertices;
   tnl->Driver.RenderPrimitive = _swsetup_RenderPrimitive;
   tnl->Driver.PointsFunc = _swsetup_Points;
   tnl->Driver.LineFunc = _swsetup_Line;
   tnl->Driver.TriangleFunc = _swsetup_Triangle;
   tnl->Driver.QuadFunc = _swsetup_Quad;
   tnl->Driver.ResetLineStipple = _swrast_ResetLineStipple;
   tnl->Driver.RenderInterp = _swsetup_RenderInterp;
   tnl->Driver.RenderCopyPV = _swsetup_RenderCopyPV;
   tnl->Driver.RenderClippedLine = _swsetup_RenderClippedLine;
   tnl->Driver.RenderClippedPolygon = _swsetup_RenderClippedPolygon;


   _swrast_InvalidateState( ctx, new_state );
   _swsetup_InvalidateState( ctx, new_state );
   _ac_InvalidateState( ctx, new_state );
   _tnl_InvalidateState( ctx, new_state );
}