xm_api.c revision 462183fe4cb6df6d90632d9e2cee881c8d26b1cb
1/*
2 * Mesa 3-D graphics library
3 * Version:  6.1
4 *
5 * Copyright (C) 1999-2004  Brian Paul   All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25/*
26 * This file contains the implementations of all the XMesa* functions.
27 *
28 *
29 * NOTES:
30 *
31 * The window coordinate system origin (0,0) is in the lower-left corner
32 * of the window.  X11's window coordinate origin is in the upper-left
33 * corner of the window.  Therefore, most drawing functions in this
34 * file have to flip Y coordinates.
35 *
36 * Define USE_XSHM in the Makefile with -DUSE_XSHM if you want to compile
37 * in support for the MIT Shared Memory extension.  If enabled, when you
38 * use an Ximage for the back buffer in double buffered mode, the "swap"
39 * operation will be faster.  You must also link with -lXext.
40 *
41 * Byte swapping:  If the Mesa host and the X display use a different
42 * byte order then there's some trickiness to be aware of when using
43 * XImages.  The byte ordering used for the XImage is that of the X
44 * display, not the Mesa host.
45 * The color-to-pixel encoding for True/DirectColor must be done
46 * according to the display's visual red_mask, green_mask, and blue_mask.
47 * If XPutPixel is used to put a pixel into an XImage then XPutPixel will
48 * do byte swapping if needed.  If one wants to directly "poke" the pixel
49 * into the XImage's buffer then the pixel must be byte swapped first.  In
50 * Mesa, when byte swapping is needed we use the PF_TRUECOLOR pixel format
51 * and use XPutPixel everywhere except in the implementation of
52 * glClear(GL_COLOR_BUFFER_BIT).  We want this function to be fast so
53 * instead of using XPutPixel we "poke" our values after byte-swapping
54 * the clear pixel value if needed.
55 *
56 */
57
58#ifdef __CYGWIN__
59#undef WIN32
60#undef __WIN32__
61#endif
62
63#include "glxheader.h"
64#include "GL/xmesa.h"
65#include "xmesaP.h"
66#include "context.h"
67#include "extensions.h"
68#include "glthread.h"
69#include "imports.h"
70#include "matrix.h"
71#include "mtypes.h"
72#include "macros.h"
73#include "texformat.h"
74#include "texobj.h"
75#include "texstore.h"
76#include "swrast/swrast.h"
77#include "swrast_setup/swrast_setup.h"
78#include "array_cache/acache.h"
79#include "tnl/tnl.h"
80#include "tnl/t_context.h"
81#include "tnl/t_pipeline.h"
82#include "drivers/common/driverfuncs.h"
83
84#ifdef XFree86Server
85#include <GL/glxtokens.h>
86#endif
87
88/*
89 * Global X driver lock
90 */
91_glthread_Mutex _xmesa_lock;
92
93
94
95/*
96 * Lookup tables for HPCR pixel format:
97 */
98static short hpcr_rgbTbl[3][256] = {
99{
100 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
101 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
102 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
103 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
104 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
105 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
106 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
107 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
108112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
109128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
110144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
111160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
112176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
113192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
114208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
115224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
116},
117{
118 16,  16,  17,  17,  18,  18,  19,  19,  20,  20,  21,  21,  22,  22,  23,  23,
119 24,  24,  25,  25,  26,  26,  27,  27,  28,  28,  29,  29,  30,  30,  31,  31,
120 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
121 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,
122 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63,
123 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79,
124 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
125 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
126112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
127128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
128144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
129160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
130176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
131192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
132208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
133224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239
134},
135{
136 32,  32,  33,  33,  34,  34,  35,  35,  36,  36,  37,  37,  38,  38,  39,  39,
137 40,  40,  41,  41,  42,  42,  43,  43,  44,  44,  45,  45,  46,  46,  47,  47,
138 48,  48,  49,  49,  50,  50,  51,  51,  52,  52,  53,  53,  54,  54,  55,  55,
139 56,  56,  57,  57,  58,  58,  59,  59,  60,  60,  61,  61,  62,  62,  63,  63,
140 64,  64,  65,  65,  66,  66,  67,  67,  68,  68,  69,  69,  70,  70,  71,  71,
141 72,  72,  73,  73,  74,  74,  75,  75,  76,  76,  77,  77,  78,  78,  79,  79,
142 80,  80,  81,  81,  82,  82,  83,  83,  84,  84,  85,  85,  86,  86,  87,  87,
143 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95,
144 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
145112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
146128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
147144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
148160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
149176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
150192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
151208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223
152}
153};
154
155
156
157/**********************************************************************/
158/*****                     X Utility Functions                    *****/
159/**********************************************************************/
160
161
162/*
163 * Return the host's byte order as LSBFirst or MSBFirst ala X.
164 */
165#ifndef XFree86Server
166static int host_byte_order( void )
167{
168   int i = 1;
169   char *cptr = (char *) &i;
170   return (*cptr==1) ? LSBFirst : MSBFirst;
171}
172#endif
173
174
175/*
176 * Error handling.
177 */
178#ifndef XFree86Server
179static volatile int mesaXErrorFlag = 0;
180
181static int mesaHandleXError( XMesaDisplay *dpy, XErrorEvent *event )
182{
183   (void) dpy;
184   (void) event;
185   mesaXErrorFlag = 1;
186   return 0;
187}
188#endif
189
190
191/*
192 * Check if the X Shared Memory extension is available.
193 * Return:  0 = not available
194 *          1 = shared XImage support available
195 *          2 = shared Pixmap support available also
196 */
197#ifndef XFree86Server
198static int check_for_xshm( XMesaDisplay *display )
199{
200#ifdef USE_XSHM
201   int major, minor, ignore;
202   Bool pixmaps;
203
204   if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
205      if (XShmQueryVersion( display, &major, &minor, &pixmaps )==True) {
206	 return (pixmaps==True) ? 2 : 1;
207      }
208      else {
209	 return 0;
210      }
211   }
212   else {
213      return 0;
214   }
215#else
216   /* Can't compile XSHM support */
217   return 0;
218#endif
219}
220#endif
221
222
223/*
224 * Return the width and height of the given drawable.
225 */
226static void get_drawable_size( XMesaDisplay *dpy, XMesaDrawable d,
227                               unsigned int *width, unsigned int *height)
228{
229#ifdef XFree86Server
230    (void) dpy;
231    *width = d->width;
232    *height = d->height;
233#else
234   Window root;
235   int x, y;
236   unsigned int bw, depth;
237
238   _glthread_LOCK_MUTEX(_xmesa_lock);
239   XGetGeometry( dpy, d, &root, &x, &y, width, height, &bw, &depth );
240   _glthread_UNLOCK_MUTEX(_xmesa_lock);
241#endif
242}
243
244
245/*
246 * Apply gamma correction to an intensity value in [0..max].  Return the
247 * new intensity value.
248 */
249static GLint gamma_adjust( GLfloat gamma, GLint value, GLint max )
250{
251   if (gamma == 1.0) {
252      return value;
253   }
254   else {
255      double x = (double) value / (double) max;
256      return IROUND_POS((GLfloat) max * _mesa_pow(x, 1.0F/gamma));
257   }
258}
259
260
261
262/*
263 * Return the true number of bits per pixel for XImages.
264 * For example, if we request a 24-bit deep visual we may actually need/get
265 * 32bpp XImages.  This function returns the appropriate bpp.
266 * Input:  dpy - the X display
267 *         visinfo - desribes the visual to be used for XImages
268 * Return:  true number of bits per pixel for XImages
269 */
270#ifdef XFree86Server
271
272static int bits_per_pixel( XMesaVisual xmv )
273{
274   const int depth = xmv->nplanes;
275   int i;
276   for (i = 0; i < screenInfo.numPixmapFormats; i++) {
277      if (screenInfo.formats[i].depth == depth)
278         return screenInfo.formats[i].bitsPerPixel;
279   }
280   return depth;  /* should never get here, but this should be safe */
281}
282
283#else
284
285static int bits_per_pixel( XMesaVisual xmv )
286{
287   XMesaDisplay *dpy = xmv->display;
288   XMesaVisualInfo visinfo = xmv->visinfo;
289   XMesaImage *img;
290   int bitsPerPixel;
291   /* Create a temporary XImage */
292   img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
293		       ZPixmap, 0,           /*format, offset*/
294		       (char*) MALLOC(8),    /*data*/
295		       1, 1,                 /*width, height*/
296		       32,                   /*bitmap_pad*/
297		       0                     /*bytes_per_line*/
298                     );
299   assert(img);
300   /* grab the bits/pixel value */
301   bitsPerPixel = img->bits_per_pixel;
302   /* free the XImage */
303   FREE( img->data );
304   img->data = NULL;
305   XMesaDestroyImage( img );
306   return bitsPerPixel;
307}
308#endif
309
310
311
312/*
313 * Determine if a given X window ID is valid (window exists).
314 * Do this by calling XGetWindowAttributes() for the window and
315 * checking if we catch an X error.
316 * Input:  dpy - the display
317 *         win - the window to check for existance
318 * Return:  GL_TRUE - window exists
319 *          GL_FALSE - window doesn't exist
320 */
321#ifndef XFree86Server
322static GLboolean WindowExistsFlag;
323
324static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
325{
326   (void) dpy;
327   if (xerr->error_code == BadWindow) {
328      WindowExistsFlag = GL_FALSE;
329   }
330   return 0;
331}
332
333static GLboolean window_exists( XMesaDisplay *dpy, Window win )
334{
335   XWindowAttributes wa;
336   int (*old_handler)( XMesaDisplay*, XErrorEvent* );
337   WindowExistsFlag = GL_TRUE;
338   old_handler = XSetErrorHandler(window_exists_err_handler);
339   XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
340   XSetErrorHandler(old_handler);
341   return WindowExistsFlag;
342}
343#endif
344
345
346
347/**********************************************************************/
348/*****                Linked list of XMesaBuffers                 *****/
349/**********************************************************************/
350
351static XMesaBuffer XMesaBufferList = NULL;
352
353
354/* Allocate a new XMesaBuffer, add to linked list */
355static XMesaBuffer alloc_xmesa_buffer(void)
356{
357   XMesaBuffer b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
358   if (b) {
359      b->Next = XMesaBufferList;
360      XMesaBufferList = b;
361   }
362   return b;
363}
364
365
366/*
367 * Find an XMesaBuffer by matching X display and colormap but NOT matching
368 * the notThis buffer.
369 */
370static XMesaBuffer find_xmesa_buffer(XMesaDisplay *dpy,
371                                     XMesaColormap cmap,
372                                     XMesaBuffer notThis)
373{
374   XMesaBuffer b;
375   for (b=XMesaBufferList; b; b=b->Next) {
376      if (b->display==dpy && b->cmap==cmap && b!=notThis) {
377         return b;
378      }
379   }
380   return NULL;
381}
382
383
384/*
385 * Free an XMesaBuffer, remove from linked list, perhaps free X colormap
386 * entries.
387 */
388static void free_xmesa_buffer(int client, XMesaBuffer buffer)
389{
390   XMesaBuffer prev = NULL, b;
391   (void) client;
392   for (b=XMesaBufferList; b; b=b->Next) {
393      if (b==buffer) {
394         /* unlink bufer from list */
395         if (prev)
396            prev->Next = buffer->Next;
397         else
398            XMesaBufferList = buffer->Next;
399         /* Check to free X colors */
400         if (buffer->num_alloced>0) {
401            /* If no other buffer uses this X colormap then free the colors. */
402            if (!find_xmesa_buffer(buffer->display, buffer->cmap, buffer)) {
403#ifdef XFree86Server
404               (void)FreeColors(buffer->cmap, client,
405				buffer->num_alloced, buffer->alloced_colors,
406				0);
407#else
408               XFreeColors(buffer->display, buffer->cmap,
409                           buffer->alloced_colors, buffer->num_alloced, 0);
410#endif
411            }
412         }
413
414         _mesa_free_framebuffer_data(&buffer->mesa_buffer);
415         FREE(buffer);
416
417         return;
418      }
419      /* continue search */
420      prev = b;
421   }
422   /* buffer not found in XMesaBufferList */
423   _mesa_problem(NULL,"free_xmesa_buffer() - buffer not found\n");
424}
425
426
427/* Copy X color table stuff from one XMesaBuffer to another. */
428static void copy_colortable_info(XMesaBuffer dst, const XMesaBuffer src)
429{
430   MEMCPY(dst->color_table, src->color_table, sizeof(src->color_table));
431   MEMCPY(dst->pixel_to_r, src->pixel_to_r, sizeof(src->pixel_to_r));
432   MEMCPY(dst->pixel_to_g, src->pixel_to_g, sizeof(src->pixel_to_g));
433   MEMCPY(dst->pixel_to_b, src->pixel_to_b, sizeof(src->pixel_to_b));
434   dst->num_alloced = src->num_alloced;
435   MEMCPY(dst->alloced_colors, src->alloced_colors,
436          sizeof(src->alloced_colors));
437}
438
439
440
441/**********************************************************************/
442/*****                   Misc Private Functions                   *****/
443/**********************************************************************/
444
445
446/*
447 * Return number of bits set in n.
448 */
449static int bitcount( unsigned long n )
450{
451   int bits;
452   for (bits=0; n>0; n=n>>1) {
453      if (n&1) {
454         bits++;
455      }
456   }
457   return bits;
458}
459
460
461
462/*
463 * Allocate a shared memory XImage back buffer for the given XMesaBuffer.
464 * Return:  GL_TRUE if success, GL_FALSE if error
465 */
466#ifndef XFree86Server
467static GLboolean alloc_shm_back_buffer( XMesaBuffer b )
468{
469#ifdef USE_XSHM
470   /*
471    * We have to do a _lot_ of error checking here to be sure we can
472    * really use the XSHM extension.  It seems different servers trigger
473    * errors at different points if the extension won't work.  Therefore
474    * we have to be very careful...
475    */
476   GC gc;
477   int (*old_handler)( XMesaDisplay *, XErrorEvent * );
478
479   b->backimage = XShmCreateImage( b->xm_visual->display,
480                                   b->xm_visual->visinfo->visual,
481                                   b->xm_visual->visinfo->depth,
482				   ZPixmap, NULL, &b->shminfo,
483				   b->width, b->height );
484   if (b->backimage == NULL) {
485      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (XShmCreateImage), disabling.");
486      b->shm = 0;
487      return GL_FALSE;
488   }
489
490   b->shminfo.shmid = shmget( IPC_PRIVATE, b->backimage->bytes_per_line
491			     * b->backimage->height, IPC_CREAT|0777 );
492   if (b->shminfo.shmid < 0) {
493      _mesa_warning(NULL, "shmget failed while allocating back buffer");
494      XDestroyImage( b->backimage );
495      b->backimage = NULL;
496      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (shmget), disabling.");
497      b->shm = 0;
498      return GL_FALSE;
499   }
500
501   b->shminfo.shmaddr = b->backimage->data
502                      = (char*)shmat( b->shminfo.shmid, 0, 0 );
503   if (b->shminfo.shmaddr == (char *) -1) {
504      _mesa_warning(NULL, "shmat() failed while allocating back buffer");
505      XDestroyImage( b->backimage );
506      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
507      b->backimage = NULL;
508      _mesa_warning(NULL, "alloc_back_buffer: Shared memory error (shmat), disabling.");
509      b->shm = 0;
510      return GL_FALSE;
511   }
512
513   b->shminfo.readOnly = False;
514   mesaXErrorFlag = 0;
515   old_handler = XSetErrorHandler( mesaHandleXError );
516   /* This may trigger the X protocol error we're ready to catch: */
517   XShmAttach( b->xm_visual->display, &b->shminfo );
518   XSync( b->xm_visual->display, False );
519
520   if (mesaXErrorFlag) {
521      /* we are on a remote display, this error is normal, don't print it */
522      XFlush( b->xm_visual->display );
523      mesaXErrorFlag = 0;
524      XDestroyImage( b->backimage );
525      shmdt( b->shminfo.shmaddr );
526      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
527      b->backimage = NULL;
528      b->shm = 0;
529      (void) XSetErrorHandler( old_handler );
530      return GL_FALSE;
531   }
532
533   shmctl( b->shminfo.shmid, IPC_RMID, 0 ); /* nobody else needs it */
534
535   /* Finally, try an XShmPutImage to be really sure the extension works */
536   gc = XCreateGC( b->xm_visual->display, b->frontbuffer, 0, NULL );
537   XShmPutImage( b->xm_visual->display, b->frontbuffer, gc,
538		 b->backimage, 0, 0, 0, 0, 1, 1 /*one pixel*/, False );
539   XSync( b->xm_visual->display, False );
540   XFreeGC( b->xm_visual->display, gc );
541   (void) XSetErrorHandler( old_handler );
542   if (mesaXErrorFlag) {
543      XFlush( b->xm_visual->display );
544      mesaXErrorFlag = 0;
545      XDestroyImage( b->backimage );
546      shmdt( b->shminfo.shmaddr );
547      shmctl( b->shminfo.shmid, IPC_RMID, 0 );
548      b->backimage = NULL;
549      b->shm = 0;
550      return GL_FALSE;
551   }
552
553   if (b->backimage) {
554      int height = b->backimage->height;
555      /* Needed by PIXELADDR1 macro */
556      b->ximage_width1 = b->backimage->bytes_per_line;
557      b->ximage_origin1 = (GLubyte *) b->backimage->data
558                        + b->ximage_width1 * (height-1);
559      /* Needed by PIXELADDR2 macro */
560      b->ximage_width2 = b->backimage->bytes_per_line / 2;
561      b->ximage_origin2 = (GLushort *) b->backimage->data
562                        + b->ximage_width2 * (height-1);
563      /* Needed by PIXELADDR3 macro */
564      b->ximage_width3 = b->backimage->bytes_per_line;
565      b->ximage_origin3 = (GLubyte *) b->backimage->data
566                        + b->ximage_width3 * (height-1);
567      /* Needed by PIXELADDR4 macro */
568      b->ximage_width4 = b->backimage->width;
569      b->ximage_origin4 = (GLuint *) b->backimage->data
570                        + b->ximage_width4 * (height-1);
571   }
572
573   return GL_TRUE;
574#else
575   /* Can't compile XSHM support */
576   return GL_FALSE;
577#endif
578}
579#endif
580
581
582
583/*
584 * Setup an off-screen pixmap or Ximage to use as the back buffer.
585 * Input:  b - the X/Mesa buffer
586 */
587void xmesa_alloc_back_buffer( XMesaBuffer b )
588{
589   if (b->db_state==BACK_XIMAGE) {
590      /* Deallocate the old backimage, if any */
591      if (b->backimage) {
592#if defined(USE_XSHM) && !defined(XFree86Server)
593	 if (b->shm) {
594	    XShmDetach( b->xm_visual->display, &b->shminfo );
595	    XDestroyImage( b->backimage );
596	    shmdt( b->shminfo.shmaddr );
597	 }
598	 else
599#endif
600	   XMesaDestroyImage( b->backimage );
601	 b->backimage = NULL;
602      }
603
604      /* Allocate new back buffer */
605#ifdef XFree86Server
606      {
607	 /* Allocate a regular XImage for the back buffer. */
608	 b->backimage = XMesaCreateImage(b->xm_visual->BitsPerPixel,
609					 b->width, b->height, NULL);
610#else
611      if (b->shm==0 || alloc_shm_back_buffer(b)==GL_FALSE) {
612	 /* Allocate a regular XImage for the back buffer. */
613	 b->backimage = XCreateImage( b->xm_visual->display,
614                                      b->xm_visual->visinfo->visual,
615                                      GET_VISUAL_DEPTH(b->xm_visual),
616				      ZPixmap, 0,   /* format, offset */
617				      NULL, b->width, b->height,
618				      8, 0 );  /* pad, bytes_per_line */
619#endif
620	 if (!b->backimage) {
621	    _mesa_warning(NULL, "alloc_back_buffer: XCreateImage failed.");
622	 }
623         b->backimage->data = (char *) MALLOC( b->backimage->height
624                                             * b->backimage->bytes_per_line );
625         if (!b->backimage->data) {
626            _mesa_warning(NULL, "alloc_back_buffer: MALLOC failed.");
627            XMesaDestroyImage( b->backimage );
628            b->backimage = NULL;
629         }
630      }
631      b->backpixmap = None;
632   }
633   else if (b->db_state==BACK_PIXMAP) {
634      XMesaPixmap old_pixmap = b->backpixmap;
635      /* Free the old back pixmap */
636      if (b->backpixmap) {
637	 XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
638      }
639      /* Allocate new back pixmap */
640      b->backpixmap = XMesaCreatePixmap( b->xm_visual->display, b->frontbuffer,
641					 b->width, b->height,
642					 GET_VISUAL_DEPTH(b->xm_visual) );
643      b->backimage = NULL;
644      /* update other references to backpixmap */
645      if (b->buffer==(XMesaDrawable)old_pixmap) {
646	 b->buffer = (XMesaDrawable)b->backpixmap;
647      }
648   }
649}
650
651
652
653/*
654 * A replacement for XAllocColor.  This function should never
655 * fail to allocate a color.  When XAllocColor fails, we return
656 * the nearest matching color.  If we have to allocate many colors
657 * this function isn't too efficient; the XQueryColors() could be
658 * done just once.
659 * Written by Michael Pichler, Brian Paul, Mark Kilgard
660 * Input:  dpy - X display
661 *         cmap - X colormap
662 *         cmapSize - size of colormap
663 * In/Out: color - the XColor struct
664 * Output:  exact - 1=exact color match, 0=closest match
665 *          alloced - 1=XAlloc worked, 0=XAlloc failed
666 */
667static void
668noFaultXAllocColor( int client,
669                    XMesaDisplay *dpy,
670                    XMesaColormap cmap,
671                    int cmapSize,
672                    XMesaColor *color,
673                    int *exact, int *alloced )
674{
675#ifdef XFree86Server
676   Pixel *ppixIn;
677   xrgb *ctable;
678#else
679   /* we'll try to cache ctable for better remote display performance */
680   static Display *prevDisplay = NULL;
681   static XMesaColormap prevCmap = 0;
682   static int prevCmapSize = 0;
683   static XMesaColor *ctable = NULL;
684#endif
685   XMesaColor subColor;
686   int i, bestmatch;
687   double mindist;       /* 3*2^16^2 exceeds long int precision. */
688
689   (void) client;
690
691   /* First try just using XAllocColor. */
692#ifdef XFree86Server
693   if (AllocColor(cmap,
694		  &color->red, &color->green, &color->blue,
695		  &color->pixel,
696		  client) == Success) {
697#else
698   if (XAllocColor(dpy, cmap, color)) {
699#endif
700      *exact = 1;
701      *alloced = 1;
702      return;
703   }
704
705   /* Alloc failed, search for closest match */
706
707   /* Retrieve color table entries. */
708   /* XXX alloca candidate. */
709#ifdef XFree86Server
710   ppixIn = (Pixel *) MALLOC(cmapSize * sizeof(Pixel));
711   ctable = (xrgb *) MALLOC(cmapSize * sizeof(xrgb));
712   for (i = 0; i < cmapSize; i++) {
713      ppixIn[i] = i;
714   }
715   QueryColors(cmap, cmapSize, ppixIn, ctable);
716#else
717   if (prevDisplay != dpy || prevCmap != cmap
718       || prevCmapSize != cmapSize || !ctable) {
719      /* free previously cached color table */
720      if (ctable)
721         FREE(ctable);
722      /* Get the color table from X */
723      ctable = (XMesaColor *) MALLOC(cmapSize * sizeof(XMesaColor));
724      assert(ctable);
725      for (i = 0; i < cmapSize; i++) {
726         ctable[i].pixel = i;
727      }
728      XQueryColors(dpy, cmap, ctable, cmapSize);
729      prevDisplay = dpy;
730      prevCmap = cmap;
731      prevCmapSize = cmapSize;
732   }
733#endif
734
735   /* Find best match. */
736   bestmatch = -1;
737   mindist = 0.0;
738   for (i = 0; i < cmapSize; i++) {
739      double dr = 0.30 * ((double) color->red - (double) ctable[i].red);
740      double dg = 0.59 * ((double) color->green - (double) ctable[i].green);
741      double db = 0.11 * ((double) color->blue - (double) ctable[i].blue);
742      double dist = dr * dr + dg * dg + db * db;
743      if (bestmatch < 0 || dist < mindist) {
744         bestmatch = i;
745         mindist = dist;
746      }
747   }
748
749   /* Return result. */
750   subColor.red   = ctable[bestmatch].red;
751   subColor.green = ctable[bestmatch].green;
752   subColor.blue  = ctable[bestmatch].blue;
753   /* Try to allocate the closest match color.  This should only
754    * fail if the cell is read/write.  Otherwise, we're incrementing
755    * the cell's reference count.
756    */
757#ifdef XFree86Server
758   if (AllocColor(cmap,
759		  &subColor.red, &subColor.green, &subColor.blue,
760		  &subColor.pixel,
761		  client) == Success) {
762#else
763   if (XAllocColor(dpy, cmap, &subColor)) {
764#endif
765      *alloced = 1;
766   }
767   else {
768      /* do this to work around a problem reported by Frank Ortega */
769      subColor.pixel = (unsigned long) bestmatch;
770      subColor.red   = ctable[bestmatch].red;
771      subColor.green = ctable[bestmatch].green;
772      subColor.blue  = ctable[bestmatch].blue;
773      subColor.flags = DoRed | DoGreen | DoBlue;
774      *alloced = 0;
775   }
776#ifdef XFree86Server
777   FREE(ppixIn);
778   FREE(ctable);
779#else
780   /* don't free table, save it for next time */
781#endif
782
783   *color = subColor;
784   *exact = 0;
785}
786
787
788
789
790/*
791 * Do setup for PF_GRAYSCALE pixel format.
792 * Note that buffer may be NULL.
793 */
794static GLboolean setup_grayscale( int client, XMesaVisual v,
795                                  XMesaBuffer buffer, XMesaColormap cmap )
796{
797   (void) DitherValues;		/* Muffle compiler */
798
799   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
800      return GL_FALSE;
801   }
802
803   if (buffer) {
804      XMesaBuffer prevBuffer;
805
806      if (!cmap) {
807         return GL_FALSE;
808      }
809
810      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
811      if (prevBuffer &&
812          (buffer->xm_visual->mesa_visual.rgbMode ==
813           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
814         /* Copy colormap stuff from previous XMesaBuffer which uses same
815          * X colormap.  Do this to avoid time spent in noFaultXAllocColor.
816          */
817         copy_colortable_info(buffer, prevBuffer);
818      }
819      else {
820         /* Allocate 256 shades of gray */
821         int gray;
822         int colorsfailed = 0;
823         for (gray=0;gray<256;gray++) {
824            GLint r = gamma_adjust( v->RedGamma,   gray, 255 );
825            GLint g = gamma_adjust( v->GreenGamma, gray, 255 );
826            GLint b = gamma_adjust( v->BlueGamma,  gray, 255 );
827            int exact, alloced;
828            XMesaColor xcol;
829            xcol.red   = (r << 8) | r;
830            xcol.green = (g << 8) | g;
831            xcol.blue  = (b << 8) | b;
832            noFaultXAllocColor( client, v->display,
833                                cmap, GET_COLORMAP_SIZE(v),
834                                &xcol, &exact, &alloced );
835            if (!exact) {
836               colorsfailed++;
837            }
838            if (alloced) {
839               assert(buffer->num_alloced<256);
840               buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
841               buffer->num_alloced++;
842            }
843
844            /*OLD
845            assert(gray < 576);
846            buffer->color_table[gray*3+0] = xcol.pixel;
847            buffer->color_table[gray*3+1] = xcol.pixel;
848            buffer->color_table[gray*3+2] = xcol.pixel;
849            assert(xcol.pixel < 65536);
850            buffer->pixel_to_r[xcol.pixel] = gray * 30 / 100;
851            buffer->pixel_to_g[xcol.pixel] = gray * 59 / 100;
852            buffer->pixel_to_b[xcol.pixel] = gray * 11 / 100;
853            */
854            buffer->color_table[gray] = xcol.pixel;
855            assert(xcol.pixel < 65536);
856            buffer->pixel_to_r[xcol.pixel] = gray;
857            buffer->pixel_to_g[xcol.pixel] = gray;
858            buffer->pixel_to_b[xcol.pixel] = gray;
859         }
860
861         if (colorsfailed && _mesa_getenv("MESA_DEBUG")) {
862            _mesa_warning(NULL,
863                  "Note: %d out of 256 needed colors do not match exactly.\n",
864                  colorsfailed );
865         }
866      }
867   }
868
869   v->dithered_pf = PF_Grayscale;
870   v->undithered_pf = PF_Grayscale;
871   return GL_TRUE;
872}
873
874
875
876/*
877 * Setup RGB rendering for a window with a PseudoColor, StaticColor,
878 * or 8-bit TrueColor visual visual.  We try to allocate a palette of 225
879 * colors (5 red, 9 green, 5 blue) and dither to approximate a 24-bit RGB
880 * color.  While this function was originally designed just for 8-bit
881 * visuals, it has also proven to work from 4-bit up to 16-bit visuals.
882 * Dithering code contributed by Bob Mercier.
883 */
884static GLboolean setup_dithered_color( int client, XMesaVisual v,
885                                       XMesaBuffer buffer, XMesaColormap cmap )
886{
887   if (GET_VISUAL_DEPTH(v)<4 || GET_VISUAL_DEPTH(v)>16) {
888      return GL_FALSE;
889   }
890
891   if (buffer) {
892      XMesaBuffer prevBuffer;
893
894      if (!cmap) {
895         return GL_FALSE;
896      }
897
898      prevBuffer = find_xmesa_buffer(v->display, cmap, buffer);
899      if (prevBuffer &&
900          (buffer->xm_visual->mesa_visual.rgbMode ==
901           prevBuffer->xm_visual->mesa_visual.rgbMode)) {
902         /* Copy colormap stuff from previous, matching XMesaBuffer.
903          * Do this to avoid time spent in noFaultXAllocColor.
904          */
905         copy_colortable_info(buffer, prevBuffer);
906      }
907      else {
908         /* Allocate X colors and initialize color_table[], red_table[], etc */
909         int r, g, b, i;
910         int colorsfailed = 0;
911         for (r = 0; r < DITH_R; r++) {
912            for (g = 0; g < DITH_G; g++) {
913               for (b = 0; b < DITH_B; b++) {
914                  XMesaColor xcol;
915                  int exact, alloced;
916                  xcol.red  =gamma_adjust(v->RedGamma,   r*65535/(DITH_R-1),65535);
917                  xcol.green=gamma_adjust(v->GreenGamma, g*65535/(DITH_G-1),65535);
918                  xcol.blue =gamma_adjust(v->BlueGamma,  b*65535/(DITH_B-1),65535);
919                  noFaultXAllocColor( client, v->display,
920                                      cmap, GET_COLORMAP_SIZE(v),
921                                      &xcol, &exact, &alloced );
922                  if (!exact) {
923                     colorsfailed++;
924                  }
925                  if (alloced) {
926                     assert(buffer->num_alloced<256);
927                     buffer->alloced_colors[buffer->num_alloced] = xcol.pixel;
928                     buffer->num_alloced++;
929                  }
930                  i = DITH_MIX( r, g, b );
931                  assert(i < 576);
932                  buffer->color_table[i] = xcol.pixel;
933                  assert(xcol.pixel < 65536);
934                  buffer->pixel_to_r[xcol.pixel] = r * 255 / (DITH_R-1);
935                  buffer->pixel_to_g[xcol.pixel] = g * 255 / (DITH_G-1);
936                  buffer->pixel_to_b[xcol.pixel] = b * 255 / (DITH_B-1);
937               }
938            }
939         }
940
941         if (colorsfailed && _mesa_getenv("MESA_DEBUG")) {
942            _mesa_warning(NULL,
943                  "Note: %d out of %d needed colors do not match exactly.\n",
944                  colorsfailed, DITH_R * DITH_G * DITH_B );
945         }
946      }
947   }
948
949   v->dithered_pf = PF_Dither;
950   v->undithered_pf = PF_Lookup;
951   return GL_TRUE;
952}
953
954
955/*
956 * Setup for Hewlett Packard Color Recovery 8-bit TrueColor mode.
957 * HPCR simulates 24-bit color fidelity with an 8-bit frame buffer.
958 * Special dithering tables have to be initialized.
959 */
960static void setup_8bit_hpcr( XMesaVisual v )
961{
962   /* HP Color Recovery contributed by:  Alex De Bruyn (ad@lms.be)
963    * To work properly, the atom _HP_RGB_SMOOTH_MAP_LIST must be defined
964    * on the root window AND the colormap obtainable by XGetRGBColormaps
965    * for that atom must be set on the window.  (see also tkInitWindow)
966    * If that colormap is not set, the output will look stripy.
967    */
968
969   /* Setup color tables with gamma correction */
970   int i;
971   double g;
972
973   g = 1.0 / v->RedGamma;
974   for (i=0; i<256; i++) {
975      GLint red = IROUND_POS(255.0 * _mesa_pow( hpcr_rgbTbl[0][i]/255.0, g ));
976      v->hpcr_rgbTbl[0][i] = CLAMP( red, 16, 239 );
977   }
978
979   g = 1.0 / v->GreenGamma;
980   for (i=0; i<256; i++) {
981      GLint green = IROUND_POS(255.0 * _mesa_pow( hpcr_rgbTbl[1][i]/255.0, g ));
982      v->hpcr_rgbTbl[1][i] = CLAMP( green, 16, 239 );
983   }
984
985   g = 1.0 / v->BlueGamma;
986   for (i=0; i<256; i++) {
987      GLint blue = IROUND_POS(255.0 * _mesa_pow( hpcr_rgbTbl[2][i]/255.0, g ));
988      v->hpcr_rgbTbl[2][i] = CLAMP( blue, 32, 223 );
989   }
990   v->undithered_pf = PF_HPCR;  /* can't really disable dithering for now */
991   v->dithered_pf = PF_HPCR;
992
993   /* which method should I use to clear */
994   /* GL_FALSE: keep the ordinary method  */
995   /* GL_TRUE : clear with dither pattern */
996   v->hpcr_clear_flag = _mesa_getenv("MESA_HPCR_CLEAR") ? GL_TRUE : GL_FALSE;
997
998   if (v->hpcr_clear_flag) {
999      v->hpcr_clear_pixmap = XMesaCreatePixmap(v->display,
1000                                               DefaultRootWindow(v->display),
1001                                               16, 2, 8);
1002#ifndef XFree86Server
1003      v->hpcr_clear_ximage = XGetImage(v->display, v->hpcr_clear_pixmap,
1004                                       0, 0, 16, 2, AllPlanes, ZPixmap);
1005#endif
1006   }
1007}
1008
1009
1010/*
1011 * Setup RGB rendering for a window with a True/DirectColor visual.
1012 */
1013static void setup_truecolor( XMesaVisual v, XMesaBuffer buffer,
1014                             XMesaColormap cmap )
1015{
1016   unsigned long rmask, gmask, bmask;
1017   (void) buffer;
1018   (void) cmap;
1019
1020   /* Compute red multiplier (mask) and bit shift */
1021   v->rshift = 0;
1022   rmask = GET_REDMASK(v);
1023   while ((rmask & 1)==0) {
1024      v->rshift++;
1025      rmask = rmask >> 1;
1026   }
1027
1028   /* Compute green multiplier (mask) and bit shift */
1029   v->gshift = 0;
1030   gmask = GET_GREENMASK(v);
1031   while ((gmask & 1)==0) {
1032      v->gshift++;
1033      gmask = gmask >> 1;
1034   }
1035
1036   /* Compute blue multiplier (mask) and bit shift */
1037   v->bshift = 0;
1038   bmask = GET_BLUEMASK(v);
1039   while ((bmask & 1)==0) {
1040      v->bshift++;
1041      bmask = bmask >> 1;
1042   }
1043
1044   /*
1045    * Compute component-to-pixel lookup tables and dithering kernel
1046    */
1047   {
1048      static GLubyte kernel[16] = {
1049          0*16,  8*16,  2*16, 10*16,
1050         12*16,  4*16, 14*16,  6*16,
1051          3*16, 11*16,  1*16,  9*16,
1052         15*16,  7*16, 13*16,  5*16,
1053      };
1054      GLint rBits = bitcount(rmask);
1055      GLint gBits = bitcount(gmask);
1056      GLint bBits = bitcount(bmask);
1057      GLint maxBits;
1058      GLuint i;
1059
1060      /* convert pixel components in [0,_mask] to RGB values in [0,255] */
1061      for (i=0; i<=rmask; i++)
1062         v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
1063      for (i=0; i<=gmask; i++)
1064         v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
1065      for (i=0; i<=bmask; i++)
1066         v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
1067
1068      /* convert RGB values from [0,255] to pixel components */
1069
1070      for (i=0;i<256;i++) {
1071         GLint r = gamma_adjust(v->RedGamma,   i, 255);
1072         GLint g = gamma_adjust(v->GreenGamma, i, 255);
1073         GLint b = gamma_adjust(v->BlueGamma,  i, 255);
1074         v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
1075         v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
1076         v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
1077      }
1078      /* overflow protection */
1079      for (i=256;i<512;i++) {
1080         v->RtoPixel[i] = v->RtoPixel[255];
1081         v->GtoPixel[i] = v->GtoPixel[255];
1082         v->BtoPixel[i] = v->BtoPixel[255];
1083      }
1084
1085      /* setup dithering kernel */
1086      maxBits = rBits;
1087      if (gBits > maxBits)  maxBits = gBits;
1088      if (bBits > maxBits)  maxBits = bBits;
1089      for (i=0;i<16;i++) {
1090         v->Kernel[i] = kernel[i] >> maxBits;
1091      }
1092
1093      v->undithered_pf = PF_Truecolor;
1094      v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_Dither_True : PF_Truecolor;
1095   }
1096
1097   /*
1098    * Now check for TrueColor visuals which we can optimize.
1099    */
1100   if (   GET_REDMASK(v)  ==0x0000ff
1101       && GET_GREENMASK(v)==0x00ff00
1102       && GET_BLUEMASK(v) ==0xff0000
1103       && CHECK_BYTE_ORDER(v)
1104       && v->BitsPerPixel==32
1105       && sizeof(GLuint)==4
1106       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1107      /* common 32 bpp config used on SGI, Sun */
1108      v->undithered_pf = v->dithered_pf = PF_8A8B8G8R;
1109   }
1110   else if (GET_REDMASK(v)  ==0xff0000
1111       &&   GET_GREENMASK(v)==0x00ff00
1112       &&   GET_BLUEMASK(v) ==0x0000ff
1113       && CHECK_BYTE_ORDER(v)
1114       && v->BitsPerPixel==32
1115       && sizeof(GLuint)==4
1116       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1117      /* common 32 bpp config used on Linux, HP, IBM */
1118      v->undithered_pf = v->dithered_pf = PF_8R8G8B;
1119   }
1120   else if (GET_REDMASK(v)  ==0xff0000
1121       &&   GET_GREENMASK(v)==0x00ff00
1122       &&   GET_BLUEMASK(v) ==0x0000ff
1123       && CHECK_BYTE_ORDER(v)
1124       && v->BitsPerPixel==24
1125       && sizeof(GLuint)==4
1126       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1127      /* common packed 24 bpp config used on Linux */
1128      v->undithered_pf = v->dithered_pf = PF_8R8G8B24;
1129   }
1130   else if (GET_REDMASK(v)  ==0xf800
1131       &&   GET_GREENMASK(v)==0x07e0
1132       &&   GET_BLUEMASK(v) ==0x001f
1133       && CHECK_BYTE_ORDER(v)
1134       && v->BitsPerPixel==16
1135       && sizeof(GLushort)==2
1136       && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
1137      /* 5-6-5 color weight on common PC VGA boards */
1138      v->undithered_pf = PF_5R6G5B;
1139      v->dithered_pf = PF_Dither_5R6G5B;
1140   }
1141   else if (GET_REDMASK(v)  ==0xe0
1142       &&   GET_GREENMASK(v)==0x1c
1143       &&   GET_BLUEMASK(v) ==0x03
1144       && CHECK_FOR_HPCR(v)) {
1145      setup_8bit_hpcr( v );
1146   }
1147}
1148
1149
1150
1151/*
1152 * Setup RGB rendering for a window with a monochrome visual.
1153 */
1154static void setup_monochrome( XMesaVisual v, XMesaBuffer b )
1155{
1156   (void) b;
1157   v->dithered_pf = v->undithered_pf = PF_1Bit;
1158   /* if black=1 then we must flip pixel values */
1159   v->bitFlip = (GET_BLACK_PIXEL(v) != 0);
1160}
1161
1162
1163
1164/*
1165 * When a context is "made current" for the first time, we can finally
1166 * finish initializing the context's visual and buffer information.
1167 * Input:  v - the XMesaVisual to initialize
1168 *         b - the XMesaBuffer to initialize (may be NULL)
1169 *         rgb_flag - TRUE = RGBA mode, FALSE = color index mode
1170 *         window - the window/pixmap we're rendering into
1171 *         cmap - the colormap associated with the window/pixmap
1172 * Return:  GL_TRUE=success, GL_FALSE=failure
1173 */
1174static GLboolean initialize_visual_and_buffer( int client,
1175                                               XMesaVisual v,
1176                                               XMesaBuffer b,
1177                                               GLboolean rgb_flag,
1178                                               XMesaDrawable window,
1179                                               XMesaColormap cmap )
1180{
1181#ifndef XFree86Server
1182   XGCValues gcvalues;
1183#endif
1184
1185   if (b) {
1186      assert(b->xm_visual == v);
1187   }
1188
1189   /* Save true bits/pixel */
1190   v->BitsPerPixel = bits_per_pixel(v);
1191   assert(v->BitsPerPixel > 0);
1192
1193
1194   if (rgb_flag==GL_FALSE) {
1195      /* COLOR-INDEXED WINDOW:
1196       * Even if the visual is TrueColor or DirectColor we treat it as
1197       * being color indexed.  This is weird but might be useful to someone.
1198       */
1199      v->dithered_pf = v->undithered_pf = PF_Index;
1200      v->mesa_visual.indexBits = GET_VISUAL_DEPTH(v);
1201   }
1202   else {
1203      /* RGB WINDOW:
1204       * We support RGB rendering into almost any kind of visual.
1205       */
1206      const int xclass = v->mesa_visual.visualType;
1207      if (xclass==GLX_TRUE_COLOR || xclass==GLX_DIRECT_COLOR) {
1208	 setup_truecolor( v, b, cmap );
1209      }
1210      else if (xclass==GLX_STATIC_GRAY && GET_VISUAL_DEPTH(v)==1) {
1211	 setup_monochrome( v, b );
1212      }
1213      else if (xclass==GLX_GRAY_SCALE || xclass==GLX_STATIC_GRAY) {
1214         if (!setup_grayscale( client, v, b, cmap )) {
1215            return GL_FALSE;
1216         }
1217      }
1218      else if ((xclass==GLX_PSEUDO_COLOR || xclass==GLX_STATIC_COLOR)
1219               && GET_VISUAL_DEPTH(v)>=4 && GET_VISUAL_DEPTH(v)<=16) {
1220	 if (!setup_dithered_color( client, v, b, cmap )) {
1221            return GL_FALSE;
1222         }
1223      }
1224      else {
1225	 _mesa_warning(NULL, "XMesa: RGB mode rendering not supported in given visual.");
1226	 return GL_FALSE;
1227      }
1228      v->mesa_visual.indexBits = 0;
1229
1230      if (_mesa_getenv("MESA_NO_DITHER")) {
1231	 v->dithered_pf = v->undithered_pf;
1232      }
1233   }
1234
1235
1236   /*
1237    * If MESA_INFO env var is set print out some debugging info
1238    * which can help Brian figure out what's going on when a user
1239    * reports bugs.
1240    */
1241   if (_mesa_getenv("MESA_INFO")) {
1242      _mesa_printf("X/Mesa visual = %p\n", (void *) v);
1243      _mesa_printf("X/Mesa dithered pf = %u\n", v->dithered_pf);
1244      _mesa_printf("X/Mesa undithered pf = %u\n", v->undithered_pf);
1245      _mesa_printf("X/Mesa level = %d\n", v->mesa_visual.level);
1246      _mesa_printf("X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
1247      _mesa_printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
1248   }
1249
1250   if (b && window) {
1251      /* Do window-specific initializations */
1252
1253      /* Window dimensions */
1254      unsigned int w, h;
1255      get_drawable_size( v->display, window, &w, &h );
1256      b->width = w;
1257      b->height = h;
1258
1259      b->frontbuffer = window;
1260
1261      /* Setup for single/double buffering */
1262      if (v->mesa_visual.doubleBufferMode) {
1263         /* Double buffered */
1264#ifndef XFree86Server
1265         b->shm = check_for_xshm( v->display );
1266#endif
1267         xmesa_alloc_back_buffer( b );
1268         if (b->db_state==BACK_PIXMAP) {
1269            b->buffer = (XMesaDrawable)b->backpixmap;
1270         }
1271         else {
1272            b->buffer = XIMAGE;
1273         }
1274      }
1275      else {
1276         /* Single Buffered */
1277         b->buffer = b->frontbuffer;
1278      }
1279
1280      /* X11 graphics contexts */
1281#ifdef XFree86Server
1282      b->gc = CreateScratchGC(v->display, window->depth);
1283#else
1284      b->gc = XCreateGC( v->display, window, 0, NULL );
1285#endif
1286      XMesaSetFunction( v->display, b->gc, GXcopy );
1287
1288      /* cleargc - for glClear() */
1289#ifdef XFree86Server
1290      b->cleargc = CreateScratchGC(v->display, window->depth);
1291#else
1292      b->cleargc = XCreateGC( v->display, window, 0, NULL );
1293#endif
1294      XMesaSetFunction( v->display, b->cleargc, GXcopy );
1295
1296      /*
1297       * Don't generate Graphics Expose/NoExpose events in swapbuffers().
1298       * Patch contributed by Michael Pichler May 15, 1995.
1299       */
1300#ifdef XFree86Server
1301      b->swapgc = CreateScratchGC(v->display, window->depth);
1302      {
1303	  CARD32 v[1];
1304	  v[0] = FALSE;
1305	  dixChangeGC(NullClient, b->swapgc, GCGraphicsExposures, v, NULL);
1306      }
1307#else
1308      gcvalues.graphics_exposures = False;
1309      b->swapgc = XCreateGC( v->display, window,
1310                              GCGraphicsExposures, &gcvalues);
1311#endif
1312      XMesaSetFunction( v->display, b->swapgc, GXcopy );
1313      /*
1314       * Set fill style and tile pixmap once for all for HPCR stuff
1315       * (instead of doing it each time in clear_color_HPCR_pixmap())
1316       * Initialize whole stuff
1317       * Patch contributed by Jacques Leroy March 8, 1998.
1318       */
1319      if (v->hpcr_clear_flag && b->buffer!=XIMAGE) {
1320	int i;
1321	for (i=0; i<16; i++)
1322        {
1323	   XMesaPutPixel(v->hpcr_clear_ximage, i, 0, 0);
1324	   XMesaPutPixel(v->hpcr_clear_ximage, i, 1, 0);
1325        }
1326        XMesaPutImage(b->display, (XMesaDrawable)v->hpcr_clear_pixmap,
1327		      b->cleargc, v->hpcr_clear_ximage, 0, 0, 0, 0, 16, 2);
1328	XMesaSetFillStyle( v->display, b->cleargc, FillTiled);
1329	XMesaSetTile( v->display, b->cleargc, v->hpcr_clear_pixmap );
1330      }
1331
1332      /* Initialize the row buffer XImage for use in write_color_span() */
1333#ifdef XFree86Server
1334      b->rowimage = XMesaCreateImage(GET_VISUAL_DEPTH(v), MAX_WIDTH, 1,
1335				     (char *)MALLOC(MAX_WIDTH*4));
1336#else
1337      b->rowimage = XCreateImage( v->display,
1338                                  v->visinfo->visual,
1339                                  v->visinfo->depth,
1340                                  ZPixmap, 0,           /*format, offset*/
1341                                  (char*) MALLOC(MAX_WIDTH*4),  /*data*/
1342                                  MAX_WIDTH, 1,         /*width, height*/
1343                                  32,                   /*bitmap_pad*/
1344                                  0                     /*bytes_per_line*/ );
1345#endif
1346   }
1347
1348   return GL_TRUE;
1349}
1350
1351
1352
1353/*
1354 * Convert an RGBA color to a pixel value.
1355 */
1356unsigned long
1357xmesa_color_to_pixel( XMesaContext xmesa, GLubyte r, GLubyte g, GLubyte b, GLubyte a,
1358                      GLuint pixelFormat)
1359{
1360   switch (pixelFormat) {
1361      case PF_Index:
1362         return 0;
1363      case PF_Truecolor:
1364         {
1365            unsigned long p;
1366            PACK_TRUECOLOR( p, r, g, b );
1367            return p;
1368         }
1369      case PF_8A8B8G8R:
1370         return PACK_8A8B8G8R( r, g, b, a );
1371      case PF_8R8G8B:
1372         /* fall through */
1373      case PF_8R8G8B24:
1374         return PACK_8R8G8B( r, g, b );
1375      case PF_5R6G5B:
1376         return PACK_5R6G5B( r, g, b );
1377      case PF_Dither:
1378         {
1379            DITHER_SETUP;
1380            return DITHER( 1, 0, r, g, b );
1381         }
1382      case PF_1Bit:
1383         /* 382 = (3*255)/2 */
1384         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
1385      case PF_HPCR:
1386         return DITHER_HPCR(1, 1, r, g, b);
1387      case PF_Lookup:
1388         {
1389            LOOKUP_SETUP;
1390            return LOOKUP( r, g, b );
1391         }
1392      case PF_Grayscale:
1393         return GRAY_RGB( r, g, b );
1394      case PF_Dither_True:
1395         /* fall through */
1396      case PF_Dither_5R6G5B:
1397         {
1398            unsigned long p;
1399            PACK_TRUEDITHER(p, 1, 0, r, g, b);
1400            return p;
1401         }
1402      default:
1403         _mesa_problem(NULL, "Bad pixel format in xmesa_color_to_pixel");
1404   }
1405   return 0;
1406}
1407
1408
1409#define NUM_VISUAL_TYPES   6
1410
1411/**
1412 * Convert an X visual type to a GLX visual type.
1413 *
1414 * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
1415 *        to be converted.
1416 * \return If \c visualType is a valid X visual type, a GLX visual type will
1417 *         be returned.  Otherwise \c GLX_NONE will be returned.
1418 *
1419 * \note
1420 * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
1421 * DRI CVS tree.
1422 */
1423static GLint
1424xmesa_convert_from_x_visual_type( int visualType )
1425{
1426    static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
1427	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
1428	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
1429	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
1430    };
1431
1432    return ( (unsigned) visualType < NUM_VISUAL_TYPES )
1433	? glx_visual_types[ visualType ] : GLX_NONE;
1434}
1435
1436
1437/**********************************************************************/
1438/*****                       Public Functions                     *****/
1439/**********************************************************************/
1440
1441
1442/*
1443 * Create a new X/Mesa visual.
1444 * Input:  display - X11 display
1445 *         visinfo - an XVisualInfo pointer
1446 *         rgb_flag - GL_TRUE = RGB mode,
1447 *                    GL_FALSE = color index mode
1448 *         alpha_flag - alpha buffer requested?
1449 *         db_flag - GL_TRUE = double-buffered,
1450 *                   GL_FALSE = single buffered
1451 *         stereo_flag - stereo visual?
1452 *         ximage_flag - GL_TRUE = use an XImage for back buffer,
1453 *                       GL_FALSE = use an off-screen pixmap for back buffer
1454 *         depth_size - requested bits/depth values, or zero
1455 *         stencil_size - requested bits/stencil values, or zero
1456 *         accum_red_size - requested bits/red accum values, or zero
1457 *         accum_green_size - requested bits/green accum values, or zero
1458 *         accum_blue_size - requested bits/blue accum values, or zero
1459 *         accum_alpha_size - requested bits/alpha accum values, or zero
1460 *         num_samples - number of samples/pixel if multisampling, or zero
1461 *         level - visual level, usually 0
1462 *         visualCaveat - ala the GLX extension, usually GLX_NONE
1463 * Return;  a new XMesaVisual or 0 if error.
1464 */
1465XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
1466                               XMesaVisualInfo visinfo,
1467                               GLboolean rgb_flag,
1468                               GLboolean alpha_flag,
1469                               GLboolean db_flag,
1470                               GLboolean stereo_flag,
1471                               GLboolean ximage_flag,
1472                               GLint depth_size,
1473                               GLint stencil_size,
1474                               GLint accum_red_size,
1475                               GLint accum_green_size,
1476                               GLint accum_blue_size,
1477                               GLint accum_alpha_size,
1478                               GLint num_samples,
1479                               GLint level,
1480                               GLint visualCaveat )
1481{
1482   char *gamma;
1483   XMesaVisual v;
1484   GLint red_bits, green_bits, blue_bits, alpha_bits;
1485
1486   /* For debugging only */
1487   if (_mesa_getenv("MESA_XSYNC")) {
1488      /* This makes debugging X easier.
1489       * In your debugger, set a breakpoint on _XError to stop when an
1490       * X protocol error is generated.
1491       */
1492#ifdef XFree86Server
1493      /* NOT_NEEDED */
1494#else
1495      XSynchronize( display, 1 );
1496#endif
1497   }
1498
1499   v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
1500   if (!v) {
1501      return NULL;
1502   }
1503
1504   /*
1505    * In the X server, NULL is passed in for the display.  It will have
1506    * to be set before using this visual.  See XMesaSetVisualDisplay()
1507    * below.
1508    */
1509   v->display = display;
1510
1511   /* Save a copy of the XVisualInfo struct because the user may XFREE()
1512    * the struct but we may need some of the information contained in it
1513    * at a later time.
1514    */
1515#ifndef XFree86Server
1516   v->visinfo = (XVisualInfo *) MALLOC(sizeof(*visinfo));
1517   if(!v->visinfo) {
1518      FREE(v);
1519      return NULL;
1520   }
1521   MEMCPY(v->visinfo, visinfo, sizeof(*visinfo));
1522#endif
1523
1524   /* check for MESA_GAMMA environment variable */
1525   gamma = _mesa_getenv("MESA_GAMMA");
1526   if (gamma) {
1527      v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
1528      sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
1529      if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
1530      if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
1531      if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
1532   }
1533   else {
1534      v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
1535   }
1536
1537   v->ximage_flag = ximage_flag;
1538
1539#ifdef XFree86Server
1540   /* We could calculate these values by ourselves.  nplanes is either the sum
1541    * of the red, green, and blue bits or the number index bits.
1542    * ColormapEntries is either (1U << index_bits) or
1543    * (1U << max(redBits, greenBits, blueBits)).
1544    */
1545   v->nplanes = visinfo->nplanes;
1546   v->ColormapEntries = visinfo->ColormapEntries;
1547
1548   v->mesa_visual.redMask = visinfo->redMask;
1549   v->mesa_visual.greenMask = visinfo->greenMask;
1550   v->mesa_visual.blueMask = visinfo->blueMask;
1551   v->mesa_visual.visualID = visinfo->vid;
1552   v->mesa_visual.screen = 0; /* FIXME: What should be done here? */
1553#else
1554   v->mesa_visual.redMask = visinfo->red_mask;
1555   v->mesa_visual.greenMask = visinfo->green_mask;
1556   v->mesa_visual.blueMask = visinfo->blue_mask;
1557   v->mesa_visual.visualID = visinfo->visualid;
1558   v->mesa_visual.screen = visinfo->screen;
1559#endif
1560
1561#if defined(XFree86Server) || !(defined(__cplusplus) || defined(c_plusplus))
1562   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->class);
1563#else
1564   v->mesa_visual.visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
1565#endif
1566
1567   v->mesa_visual.visualRating = visualCaveat;
1568
1569   (void) initialize_visual_and_buffer( 0, v, NULL, rgb_flag, 0, 0 );
1570
1571   {
1572      const int xclass = v->mesa_visual.visualType;
1573      if (xclass==GLX_TRUE_COLOR || xclass==GLX_DIRECT_COLOR) {
1574         red_bits   = bitcount(GET_REDMASK(v));
1575         green_bits = bitcount(GET_GREENMASK(v));
1576         blue_bits  = bitcount(GET_BLUEMASK(v));
1577         alpha_bits = 0;
1578      }
1579      else {
1580         /* this is an approximation */
1581         int depth;
1582         depth = GET_VISUAL_DEPTH(v);
1583         red_bits = depth / 3;
1584         depth -= red_bits;
1585         green_bits = depth / 2;
1586         depth -= green_bits;
1587         blue_bits = depth;
1588         alpha_bits = 0;
1589         assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
1590      }
1591   }
1592
1593   if (alpha_flag && alpha_bits == 0)
1594      alpha_bits = 8;
1595
1596   _mesa_initialize_visual( &v->mesa_visual,
1597                            rgb_flag, db_flag, stereo_flag,
1598                            red_bits, green_bits,
1599                            blue_bits, alpha_bits,
1600                            v->mesa_visual.indexBits,
1601                            depth_size,
1602                            stencil_size,
1603                            accum_red_size, accum_green_size,
1604                            accum_blue_size, accum_alpha_size,
1605                            0 );
1606
1607   /* XXX minor hack */
1608   v->mesa_visual.level = level;
1609   return v;
1610}
1611
1612
1613void XMesaSetVisualDisplay( XMesaDisplay *dpy, XMesaVisual v )
1614{
1615    v->display = dpy;
1616}
1617
1618
1619void XMesaDestroyVisual( XMesaVisual v )
1620{
1621#ifndef XFree86Server
1622   FREE(v->visinfo);
1623#endif
1624   FREE(v);
1625}
1626
1627
1628
1629/**
1630 * Create a new XMesaContext.
1631 * \param v  the XMesaVisual
1632 * \param share_list  another XMesaContext with which to share display
1633 *                    lists or NULL if no sharing is wanted.
1634 * \return an XMesaContext or NULL if error.
1635 */
1636XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
1637{
1638   static GLboolean firstTime = GL_TRUE;
1639   XMesaContext c;
1640   GLcontext *mesaCtx;
1641   struct dd_function_table functions;
1642   TNLcontext *tnl;
1643
1644   if (firstTime) {
1645      _glthread_INIT_MUTEX(_xmesa_lock);
1646      firstTime = GL_FALSE;
1647   }
1648
1649   /* Note: the XMesaContext contains a Mesa GLcontext struct (inheritance) */
1650   c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
1651   if (!c)
1652      return NULL;
1653
1654   mesaCtx = &(c->mesa);
1655
1656   /* initialize with default driver functions, then plug in XMesa funcs */
1657   _mesa_init_driver_functions(&functions);
1658   xmesa_init_driver_functions(v, &functions);
1659   if (!_mesa_initialize_context(mesaCtx, &v->mesa_visual,
1660                      share_list ? &(share_list->mesa) : (GLcontext *) NULL,
1661                      &functions, (void *) c)) {
1662      FREE(c);
1663      return NULL;
1664   }
1665
1666   _mesa_enable_sw_extensions(mesaCtx);
1667   _mesa_enable_1_3_extensions(mesaCtx);
1668   _mesa_enable_1_4_extensions(mesaCtx);
1669   _mesa_enable_1_5_extensions(mesaCtx);
1670
1671   /* finish up xmesa context initializations */
1672   c->swapbytes = CHECK_BYTE_ORDER(v) ? GL_FALSE : GL_TRUE;
1673   c->xm_visual = v;
1674   c->xm_draw_buffer = NULL;   /* set later by XMesaMakeCurrent */
1675   c->xm_read_buffer = NULL;   /* set later by XMesaMakeCurrent */
1676   c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
1677   c->display = v->display;
1678   c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
1679
1680   /* Initialize the software rasterizer and helper modules.
1681    */
1682   if (!_swrast_CreateContext( mesaCtx ) ||
1683       !_ac_CreateContext( mesaCtx ) ||
1684       !_tnl_CreateContext( mesaCtx ) ||
1685       !_swsetup_CreateContext( mesaCtx )) {
1686      _mesa_free_context_data(&c->mesa);
1687      _mesa_free(c);
1688      return NULL;
1689   }
1690
1691   /* tnl setup */
1692   tnl = TNL_CONTEXT(mesaCtx);
1693   tnl->Driver.RunPipeline = _tnl_run_pipeline;
1694   /* swrast setup */
1695   xmesa_register_swrast_functions( mesaCtx );
1696   _swsetup_Wakeup(mesaCtx);
1697
1698   return c;
1699}
1700
1701
1702
1703void XMesaDestroyContext( XMesaContext c )
1704{
1705   GLcontext *mesaCtx = &c->mesa;
1706#ifdef FX
1707   if (c->xm_draw_buffer && c->xm_buffer->FXctx)
1708      fxMesaDestroyContext(c->xm_draw_buffer->FXctx);
1709#endif
1710   _swsetup_DestroyContext( mesaCtx );
1711   _swrast_DestroyContext( mesaCtx );
1712   _tnl_DestroyContext( mesaCtx );
1713   _ac_DestroyContext( mesaCtx );
1714   _mesa_free_context_data( mesaCtx );
1715   _mesa_free( c );
1716}
1717
1718
1719
1720/*
1721 * XXX this isn't a public function!  It's a hack for the 3Dfx driver.
1722 * Create a new XMesaBuffer from an X window.
1723 * Input:  v - the XMesaVisual
1724 *         w - the window
1725 *         c - the context
1726 * Return:  new XMesaBuffer or NULL if error
1727 */
1728XMesaBuffer XMesaCreateWindowBuffer2( XMesaVisual v, XMesaWindow w,
1729                                      XMesaContext c )
1730{
1731#ifndef XFree86Server
1732   XWindowAttributes attr;
1733#endif
1734#ifdef FX
1735   char *fxEnvVar;
1736#endif
1737   int client = 0;
1738
1739   XMesaBuffer b = alloc_xmesa_buffer();
1740   if (!b) {
1741      return NULL;
1742   }
1743
1744   (void) c;
1745
1746#ifdef XFree86Server
1747   client = CLIENT_ID(((XMesaDrawable)w)->id);
1748#endif
1749
1750   assert(v);
1751
1752#ifdef XFree86Server
1753   if (GET_VISUAL_DEPTH(v) != ((XMesaDrawable)w)->depth) {
1754#else
1755   XGetWindowAttributes( v->display, w, &attr );
1756
1757   if (GET_VISUAL_DEPTH(v) != attr.depth) {
1758#endif
1759      _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual and window!\n");
1760      return NULL;
1761   }
1762
1763   b->xm_visual = v;
1764   b->type = WINDOW;
1765   b->display = v->display;
1766#ifdef XFree86Server
1767   b->cmap = (ColormapPtr)LookupIDByType(wColormap(w), RT_COLORMAP);
1768#else
1769   if (attr.colormap) {
1770      b->cmap = attr.colormap;
1771   }
1772   else {
1773      _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
1774      /* this is weird, a window w/out a colormap!? */
1775      /* OK, let's just allocate a new one and hope for the best */
1776      b->cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1777   }
1778#endif
1779
1780   /* determine back buffer implementation */
1781   if (v->mesa_visual.doubleBufferMode) {
1782      if (v->ximage_flag) {
1783	 b->db_state = BACK_XIMAGE;
1784      }
1785      else {
1786	 b->db_state = BACK_PIXMAP;
1787      }
1788   }
1789   else {
1790      b->db_state = 0;
1791   }
1792
1793   _mesa_initialize_framebuffer(&b->mesa_buffer,
1794                                &v->mesa_visual,
1795                                v->mesa_visual.depthBits > 0,
1796                                v->mesa_visual.stencilBits > 0,
1797                                v->mesa_visual.accumRedBits > 0,
1798                                v->mesa_visual.alphaBits > 0 );
1799   /* XXX hack */
1800   b->mesa_buffer.UseSoftwareAuxBuffers = GL_TRUE;
1801
1802   if (!initialize_visual_and_buffer( client, v, b, v->mesa_visual.rgbMode,
1803                                      (XMesaDrawable)w, b->cmap )) {
1804      free_xmesa_buffer(client, b);
1805      return NULL;
1806   }
1807
1808#ifdef FX
1809   fxEnvVar = _mesa_getenv("MESA_GLX_FX");
1810   if (fxEnvVar) {
1811     if (fxEnvVar[0]!='d') {
1812       int attribs[100];
1813       int numAttribs = 0;
1814       int hw;
1815       if (v->mesa_visual.depthBits > 0) {
1816	 attribs[numAttribs++] = FXMESA_DEPTH_SIZE;
1817	 attribs[numAttribs++] = v->mesa_visual.depthBits;
1818       }
1819       if (v->mesa_visual.doubleBufferMode) {
1820	 attribs[numAttribs++] = FXMESA_DOUBLEBUFFER;
1821       }
1822       if (v->mesa_visual.accumRedBits > 0) {
1823	 attribs[numAttribs++] = FXMESA_ACCUM_SIZE;
1824	 attribs[numAttribs++] = v->mesa_visual.accumRedBits;
1825       }
1826       if (v->mesa_visual.stencilBits > 0) {
1827         attribs[numAttribs++] = FXMESA_STENCIL_SIZE;
1828         attribs[numAttribs++] = v->mesa_visual.stencilBits;
1829       }
1830       if (v->mesa_visual.alphaBits > 0) {
1831         attribs[numAttribs++] = FXMESA_ALPHA_SIZE;
1832         attribs[numAttribs++] = v->mesa_visual.alphaBits;
1833       }
1834       if (1) {
1835         attribs[numAttribs++] = FXMESA_SHARE_CONTEXT;
1836         attribs[numAttribs++] = (int) &(c->mesa);
1837       }
1838       attribs[numAttribs++] = FXMESA_NONE;
1839
1840       /* [dBorca] we should take an envvar for `fxMesaSelectCurrentBoard'!!! */
1841       hw = fxMesaSelectCurrentBoard(0);
1842       if ((hw == GR_SSTTYPE_VOODOO) || (hw == GR_SSTTYPE_Voodoo2)) {
1843         b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1844         if ((v->undithered_pf!=PF_Index) && (b->backimage)) {
1845	   b->FXisHackUsable = b->FXctx ? GL_TRUE : GL_FALSE;
1846	   if (b->FXctx && (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')) {
1847	     b->FXwindowHack = GL_TRUE;
1848	     FX_grSstControl(GR_CONTROL_DEACTIVATE);
1849	   }
1850           else {
1851	     b->FXwindowHack = GL_FALSE;
1852	   }
1853         }
1854       }
1855       else {
1856         if (fxEnvVar[0]=='w' || fxEnvVar[0]=='W')
1857	   b->FXctx = fxMesaCreateContext(w, GR_RESOLUTION_NONE,
1858					  GR_REFRESH_75Hz, attribs);
1859         else
1860	   b->FXctx = fxMesaCreateBestContext(0, b->width, b->height, attribs);
1861         b->FXisHackUsable = GL_FALSE;
1862         b->FXwindowHack = GL_FALSE;
1863       }
1864       /*
1865       fprintf(stderr,
1866               "voodoo %d, wid %d height %d hack: usable %d active %d\n",
1867               hw, b->width, b->height, b->FXisHackUsable, b->FXwindowHack);
1868       */
1869     }
1870   }
1871   else {
1872      _mesa_warning(NULL, "WARNING: This Mesa Library includes the Glide driver but\n");
1873      _mesa_warning(NULL, "         you have not defined the MESA_GLX_FX env. var.\n");
1874      _mesa_warning(NULL, "         (check the README.3DFX file for more information).\n\n");
1875      _mesa_warning(NULL, "         you can disable this message with a 'export MESA_GLX_FX=disable'.\n");
1876   }
1877#endif
1878
1879   return b;
1880}
1881
1882
1883XMesaBuffer XMesaCreateWindowBuffer( XMesaVisual v, XMesaWindow w )
1884{
1885   return XMesaCreateWindowBuffer2( v, w, NULL );
1886}
1887
1888
1889/**
1890 * Create a new XMesaBuffer from an X pixmap.
1891 *
1892 * \param v    the XMesaVisual
1893 * \param p    the pixmap
1894 * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
1895 *             \c GLX_DIRECT_COLOR visual for the pixmap
1896 * \returns new XMesaBuffer or NULL if error
1897 */
1898XMesaBuffer XMesaCreatePixmapBuffer( XMesaVisual v,
1899				     XMesaPixmap p, XMesaColormap cmap )
1900{
1901   int client = 0;
1902   XMesaBuffer b = alloc_xmesa_buffer();
1903   if (!b) {
1904      return NULL;
1905   }
1906
1907
1908#ifdef XFree86Server
1909   client = CLIENT_ID(((XMesaDrawable)p)->id);
1910#endif
1911
1912   assert(v);
1913
1914   b->xm_visual = v;
1915   b->type = PIXMAP;
1916   b->display = v->display;
1917   b->cmap = cmap;
1918
1919   /* determine back buffer implementation */
1920   if (v->mesa_visual.doubleBufferMode) {
1921      if (v->ximage_flag) {
1922	 b->db_state = BACK_XIMAGE;
1923      }
1924      else {
1925	 b->db_state = BACK_PIXMAP;
1926      }
1927   }
1928   else {
1929      b->db_state = 0;
1930   }
1931
1932   _mesa_initialize_framebuffer(&b->mesa_buffer,
1933                                &v->mesa_visual,
1934                                v->mesa_visual.depthBits > 0,
1935                                v->mesa_visual.stencilBits > 0,
1936                                v->mesa_visual.accumRedBits +
1937                                v->mesa_visual.accumGreenBits +
1938                                v->mesa_visual.accumBlueBits > 0,
1939                                v->mesa_visual.alphaBits > 0 );
1940
1941   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1942				     (XMesaDrawable)p, cmap)) {
1943      free_xmesa_buffer(client, b);
1944      return NULL;
1945   }
1946
1947   return b;
1948}
1949
1950
1951
1952XMesaBuffer XMesaCreatePBuffer( XMesaVisual v, XMesaColormap cmap,
1953                                unsigned int width, unsigned int height )
1954{
1955#ifdef XFree86Server
1956   return 0;
1957#else
1958   int client = 0;
1959   XMesaWindow root;
1960   XMesaDrawable drawable;  /* X Pixmap Drawable */
1961   XMesaBuffer b = alloc_xmesa_buffer();
1962   if (!b) {
1963      return NULL;
1964   }
1965
1966   b->xm_visual = v;
1967   b->type = PBUFFER;
1968   b->display = v->display;
1969   b->cmap = cmap;
1970
1971   /* allocate pixmap for front buffer */
1972   root = RootWindow( v->display, v->visinfo->screen );
1973   drawable = XCreatePixmap( v->display, root, width, height, v->visinfo->depth );
1974
1975   /* determine back buffer implementation */
1976   if (v->mesa_visual.doubleBufferMode) {
1977      if (v->ximage_flag) {
1978	 b->db_state = BACK_XIMAGE;
1979      }
1980      else {
1981	 b->db_state = BACK_PIXMAP;
1982      }
1983   }
1984   else {
1985      b->db_state = 0;
1986   }
1987
1988   _mesa_initialize_framebuffer(&b->mesa_buffer,
1989                                &v->mesa_visual,
1990                                v->mesa_visual.depthBits > 0,
1991                                v->mesa_visual.stencilBits > 0,
1992                                v->mesa_visual.accumRedBits +
1993                                v->mesa_visual.accumGreenBits +
1994                                v->mesa_visual.accumBlueBits > 0,
1995                                v->mesa_visual.alphaBits > 0 );
1996
1997   if (!initialize_visual_and_buffer(client, v, b, v->mesa_visual.rgbMode,
1998				     drawable, cmap)) {
1999      free_xmesa_buffer(client, b);
2000      return NULL;
2001   }
2002
2003   return b;
2004#endif
2005}
2006
2007
2008
2009/*
2010 * Deallocate an XMesaBuffer structure and all related info.
2011 */
2012void XMesaDestroyBuffer( XMesaBuffer b )
2013{
2014   int client = 0;
2015
2016#ifdef XFree86Server
2017   if (b->frontbuffer)
2018       client = CLIENT_ID(b->frontbuffer->id);
2019#endif
2020
2021   if (b->gc)  XMesaFreeGC( b->xm_visual->display, b->gc );
2022   if (b->cleargc)  XMesaFreeGC( b->xm_visual->display, b->cleargc );
2023   if (b->swapgc)  XMesaFreeGC( b->xm_visual->display, b->swapgc );
2024
2025   if (b->backimage) {
2026#if defined(USE_XSHM) && !defined(XFree86Server)
2027       if (b->shm) {
2028	   XShmDetach( b->xm_visual->display, &b->shminfo );
2029	   XDestroyImage( b->backimage );
2030	   shmdt( b->shminfo.shmaddr );
2031       }
2032       else
2033#endif
2034	   XMesaDestroyImage( b->backimage );
2035   }
2036   if (b->backpixmap) {
2037      XMesaFreePixmap( b->xm_visual->display, b->backpixmap );
2038      if (b->xm_visual->hpcr_clear_flag) {
2039	XMesaFreePixmap( b->xm_visual->display,
2040			 b->xm_visual->hpcr_clear_pixmap );
2041	XMesaDestroyImage( b->xm_visual->hpcr_clear_ximage );
2042      }
2043   }
2044   if (b->rowimage) {
2045      FREE( b->rowimage->data );
2046      b->rowimage->data = NULL;
2047      XMesaDestroyImage( b->rowimage );
2048   }
2049
2050   free_xmesa_buffer(client, b);
2051}
2052
2053
2054
2055/*
2056 * Bind buffer b to context c and make c the current rendering context.
2057 */
2058GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
2059{
2060   return XMesaMakeCurrent2( c, b, b );
2061}
2062
2063
2064/*
2065 * Bind buffer b to context c and make c the current rendering context.
2066 */
2067GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
2068                             XMesaBuffer readBuffer )
2069{
2070   if (c) {
2071      if (!drawBuffer || !readBuffer)
2072         return GL_FALSE;  /* must specify buffers! */
2073
2074#ifdef FX
2075      if (drawBuffer->FXctx) {
2076         fxMesaMakeCurrent(drawBuffer->FXctx);
2077
2078         c->xm_draw_buffer = drawBuffer;
2079         c->xm_read_buffer = readBuffer;
2080         c->xm_buffer = drawBuffer;
2081
2082         return GL_TRUE;
2083      }
2084#endif
2085      if (&(c->mesa) == _mesa_get_current_context()
2086          && c->xm_draw_buffer == drawBuffer
2087          && c->xm_read_buffer == readBuffer
2088          && c->xm_draw_buffer->wasCurrent) {
2089         /* same context and buffer, do nothing */
2090         return GL_TRUE;
2091      }
2092
2093      c->xm_draw_buffer = drawBuffer;
2094      c->xm_read_buffer = readBuffer;
2095      c->xm_buffer = drawBuffer;
2096
2097      _mesa_make_current2(&(c->mesa),
2098                          &drawBuffer->mesa_buffer,
2099                          &readBuffer->mesa_buffer);
2100
2101      if (c->mesa.Viewport.Width == 0) {
2102	 /* initialize viewport to window size */
2103	 _mesa_Viewport( 0, 0, drawBuffer->width, drawBuffer->height );
2104	 c->mesa.Scissor.Width = drawBuffer->width;
2105	 c->mesa.Scissor.Height = drawBuffer->height;
2106      }
2107
2108      if (c->xm_visual->mesa_visual.rgbMode) {
2109         /*
2110          * Must recompute and set these pixel values because colormap
2111          * can be different for different windows.
2112          */
2113         c->clearpixel = xmesa_color_to_pixel( c,
2114                                               c->clearcolor[0],
2115                                               c->clearcolor[1],
2116                                               c->clearcolor[2],
2117                                               c->clearcolor[3],
2118                                               c->xm_visual->undithered_pf);
2119         XMesaSetForeground(c->display, c->xm_draw_buffer->cleargc, c->clearpixel);
2120      }
2121
2122      /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
2123      c->xm_draw_buffer->wasCurrent = GL_TRUE;
2124   }
2125   else {
2126      /* Detach */
2127      _mesa_make_current2( NULL, NULL, NULL );
2128   }
2129   return GL_TRUE;
2130}
2131
2132
2133/*
2134 * Unbind the context c from its buffer.
2135 */
2136GLboolean XMesaUnbindContext( XMesaContext c )
2137{
2138   /* A no-op for XFree86 integration purposes */
2139   return GL_TRUE;
2140}
2141
2142
2143XMesaContext XMesaGetCurrentContext( void )
2144{
2145   GET_CURRENT_CONTEXT(ctx);
2146   if (ctx) {
2147      XMesaContext xmesa = XMESA_CONTEXT(ctx);
2148      return xmesa;
2149   }
2150   else {
2151      return 0;
2152   }
2153}
2154
2155
2156XMesaBuffer XMesaGetCurrentBuffer( void )
2157{
2158   GET_CURRENT_CONTEXT(ctx);
2159   if (ctx) {
2160      XMesaContext xmesa = XMESA_CONTEXT(ctx);
2161      return xmesa->xm_draw_buffer;
2162   }
2163   else {
2164      return 0;
2165   }
2166}
2167
2168
2169/* New in Mesa 3.1 */
2170XMesaBuffer XMesaGetCurrentReadBuffer( void )
2171{
2172   GET_CURRENT_CONTEXT(ctx);
2173   if (ctx) {
2174      XMesaContext xmesa = XMESA_CONTEXT(ctx);
2175      return xmesa->xm_read_buffer;
2176   }
2177   else {
2178      return 0;
2179   }
2180}
2181
2182
2183GLboolean XMesaForceCurrent(XMesaContext c)
2184{
2185   if (c) {
2186      if (&(c->mesa) != _mesa_get_current_context()) {
2187	 _mesa_make_current(&(c->mesa), &c->xm_draw_buffer->mesa_buffer);
2188      }
2189   }
2190   else {
2191      _mesa_make_current(NULL, NULL);
2192   }
2193   return GL_TRUE;
2194}
2195
2196
2197GLboolean XMesaLoseCurrent(XMesaContext c)
2198{
2199   (void) c;
2200   _mesa_make_current(NULL, NULL);
2201   return GL_TRUE;
2202}
2203
2204
2205/*
2206 * Switch 3Dfx support hack between window and full-screen mode.
2207 */
2208GLboolean XMesaSetFXmode( GLint mode )
2209{
2210#ifdef FX
2211   const char *fx = _mesa_getenv("MESA_GLX_FX");
2212   if (fx && fx[0] != 'd') {
2213      GET_CURRENT_CONTEXT(ctx);
2214      GrHwConfiguration hw;
2215      if (!FX_grSstQueryHardware(&hw)) {
2216         /*fprintf(stderr, "!grSstQueryHardware\n");*/
2217         return GL_FALSE;
2218      }
2219      if (hw.num_sst < 1) {
2220         /*fprintf(stderr, "hw.num_sst < 1\n");*/
2221         return GL_FALSE;
2222      }
2223      if (ctx) {
2224         /* [dBorca] Hack alert:
2225	  * oh, this is sooo wrong: ctx above is
2226	  * really an fxMesaContext, not an XMesaContext
2227	  */
2228         XMesaContext xmesa = XMESA_CONTEXT(ctx);
2229         if (mode == XMESA_FX_WINDOW) {
2230	    if (xmesa->xm_draw_buffer->FXisHackUsable) {
2231	       FX_grSstControl(GR_CONTROL_DEACTIVATE);
2232	       xmesa->xm_draw_buffer->FXwindowHack = GL_TRUE;
2233	       return GL_TRUE;
2234	    }
2235	 }
2236	 else if (mode == XMESA_FX_FULLSCREEN) {
2237	    FX_grSstControl(GR_CONTROL_ACTIVATE);
2238	    xmesa->xm_draw_buffer->FXwindowHack = GL_FALSE;
2239	    return GL_TRUE;
2240	 }
2241	 else {
2242	    /* Error: Bad mode value */
2243	 }
2244      }
2245   }
2246   /*fprintf(stderr, "fallthrough\n");*/
2247#else
2248   (void) mode;
2249#endif
2250   return GL_FALSE;
2251}
2252
2253
2254
2255#ifdef FX
2256/*
2257 * Read image from VooDoo frame buffer into X/Mesa's back XImage.
2258 */
2259static void FXgetImage( XMesaBuffer b )
2260{
2261   GET_CURRENT_CONTEXT(ctx);
2262   static unsigned short pixbuf[MAX_WIDTH];
2263   GLuint x, y;
2264   int xpos, ypos;
2265   XMesaWindow root;
2266   unsigned int bw, depth, width, height;
2267   XMesaContext xmesa = XMESA_CONTEXT(ctx);
2268
2269#ifdef XFree86Server
2270   x = b->frontbuffer->x;
2271   y = b->frontbuffer->y;
2272   width = b->frontbuffer->width;
2273   height = b->frontbuffer->height;
2274   depth = b->frontbuffer->depth;
2275#else
2276   XGetGeometry( b->xm_visual->display, b->frontbuffer,
2277                 &root, &xpos, &ypos, &width, &height, &bw, &depth);
2278#endif
2279   if (b->width != width || b->height != height) {
2280      b->width = MIN2((int)width, b->FXctx->width);
2281      b->height = MIN2((int)height, b->FXctx->height);
2282      if (b->width & 1)
2283         b->width--;  /* prevent odd width */
2284      xmesa_alloc_back_buffer( b );
2285   }
2286
2287   /* [dBorca] we're always in the right GR_COLORFORMAT... aren't we? */
2288   /* grLfbWriteColorFormat(GR_COLORFORMAT_ARGB); */
2289   if (b->xm_visual->undithered_pf==PF_5R6G5B) {
2290      /* Special case: 16bpp RGB */
2291      grLfbReadRegion( GR_BUFFER_FRONTBUFFER,       /* src buffer */
2292                       0, b->FXctx->height - b->height,  /*pos*/
2293                       b->width, b->height,         /* size */
2294                       b->width * sizeof(GLushort), /* stride */
2295                       b->backimage->data);         /* dest buffer */
2296   }
2297   else if (b->xm_visual->dithered_pf==PF_Dither
2298	    && GET_VISUAL_DEPTH(b->xm_visual)==8) {
2299      /* Special case: 8bpp RGB */
2300      for (y=0;y<b->height;y++) {
2301         GLubyte *ptr = (GLubyte*) b->backimage->data
2302                        + b->backimage->bytes_per_line * y;
2303         XDITHER_SETUP(y);
2304
2305         /* read row from 3Dfx frame buffer */
2306         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2307                          0, b->FXctx->height-(b->height-y),
2308                          b->width, 1,
2309                          0,
2310                          pixbuf );
2311
2312         /* write to XImage back buffer */
2313         for (x=0;x<b->width;x++) {
2314            GLubyte r = (pixbuf[x] & 0xf800) >> 8;
2315            GLubyte g = (pixbuf[x] & 0x07e0) >> 3;
2316            GLubyte b = (pixbuf[x] & 0x001f) << 3;
2317            *ptr++ = XDITHER( x, r, g, b);
2318         }
2319      }
2320   }
2321   else {
2322      /* General case: slow! */
2323      for (y=0;y<b->height;y++) {
2324         /* read row from 3Dfx frame buffer */
2325         grLfbReadRegion( GR_BUFFER_FRONTBUFFER,
2326                          0, b->FXctx->height-(b->height-y),
2327                          b->width, 1,
2328                          0,
2329                          pixbuf );
2330
2331         /* write to XImage back buffer */
2332         for (x=0;x<b->width;x++) {
2333            XMesaPutPixel(b->backimage,x,y,
2334			  xmesa_color_to_pixel(xmesa,
2335					       (pixbuf[x] & 0xf800) >> 8,
2336					       (pixbuf[x] & 0x07e0) >> 3,
2337					       (pixbuf[x] & 0x001f) << 3,
2338					       0xff,
2339                                               b->xm_visual->undithered_pf));
2340         }
2341      }
2342   }
2343   /* grLfbWriteColorFormat(GR_COLORFORMAT_ABGR); */
2344}
2345#endif
2346
2347
2348/*
2349 * Copy the back buffer to the front buffer.  If there's no back buffer
2350 * this is a no-op.
2351 */
2352void XMesaSwapBuffers( XMesaBuffer b )
2353{
2354   GET_CURRENT_CONTEXT(ctx);
2355
2356   /* If we're swapping the buffer associated with the current context
2357    * we have to flush any pending rendering commands first.
2358    */
2359   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
2360      _mesa_notifySwapBuffers(ctx);
2361
2362   if (b->db_state) {
2363#ifdef FX
2364      if (b->FXctx) {
2365         fxMesaSwapBuffers();
2366
2367         if (b->FXwindowHack)
2368            FXgetImage(b);
2369         else
2370            return;
2371      }
2372#endif
2373     if (b->backimage) {
2374	 /* Copy Ximage from host's memory to server's window */
2375#if defined(USE_XSHM) && !defined(XFree86Server)
2376	 if (b->shm) {
2377            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2378	    XShmPutImage( b->xm_visual->display, b->frontbuffer,
2379			  b->swapgc,
2380			  b->backimage, 0, 0,
2381			  0, 0, b->width, b->height, False );
2382            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2383	 }
2384	 else
2385#endif
2386         {
2387            /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2388            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2389			   b->swapgc,
2390			   b->backimage, 0, 0,
2391			   0, 0, b->width, b->height );
2392            /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2393         }
2394      }
2395      else {
2396	 /* Copy pixmap to window on server */
2397         /*_glthread_LOCK_MUTEX(_xmesa_lock);*/
2398	 XMesaCopyArea( b->xm_visual->display,
2399			b->backpixmap,   /* source drawable */
2400			b->frontbuffer,  /* dest. drawable */
2401			b->swapgc,
2402			0, 0, b->width, b->height,  /* source region */
2403			0, 0                 /* dest region */
2404		      );
2405         /*_glthread_UNLOCK_MUTEX(_xmesa_lock);*/
2406      }
2407   }
2408#if !defined(XFree86Server)
2409   XSync( b->xm_visual->display, False );
2410#endif
2411}
2412
2413
2414
2415/*
2416 * Copy sub-region of back buffer to front buffer
2417 */
2418void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
2419{
2420   GET_CURRENT_CONTEXT(ctx);
2421
2422   /* If we're swapping the buffer associated with the current context
2423    * we have to flush any pending rendering commands first.
2424    */
2425   if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
2426      _mesa_notifySwapBuffers(ctx);
2427
2428   if (b->db_state) {
2429      int yTop = b->height - y - height;
2430#ifdef FX
2431      if (b->FXctx) {
2432         fxMesaSwapBuffers();
2433         if (b->FXwindowHack)
2434            FXgetImage(b);
2435         else
2436            return;
2437      }
2438#endif
2439      if (b->backimage) {
2440         /* Copy Ximage from host's memory to server's window */
2441#if defined(USE_XSHM) && !defined(XFree86Server)
2442         if (b->shm) {
2443            /* XXX assuming width and height aren't too large! */
2444            XShmPutImage( b->xm_visual->display, b->frontbuffer,
2445                          b->swapgc,
2446                          b->backimage, x, yTop,
2447                          x, yTop, width, height, False );
2448            /* wait for finished event??? */
2449         }
2450         else
2451#endif
2452         {
2453            /* XXX assuming width and height aren't too large! */
2454            XMesaPutImage( b->xm_visual->display, b->frontbuffer,
2455			   b->swapgc,
2456			   b->backimage, x, yTop,
2457			   x, yTop, width, height );
2458         }
2459      }
2460      else {
2461         /* Copy pixmap to window on server */
2462         XMesaCopyArea( b->xm_visual->display,
2463			b->backpixmap,           /* source drawable */
2464			b->frontbuffer,          /* dest. drawable */
2465			b->swapgc,
2466			x, yTop, width, height,  /* source region */
2467			x, yTop                  /* dest region */
2468                      );
2469      }
2470   }
2471}
2472
2473
2474/*
2475 * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
2476 * is a way to get "under the hood" of X/Mesa so one can manipulate the
2477 * back buffer directly.
2478 * Output:  pixmap - pointer to back buffer's Pixmap, or 0
2479 *          ximage - pointer to back buffer's XImage, or NULL
2480 * Return:  GL_TRUE = context is double buffered
2481 *          GL_FALSE = context is single buffered
2482 */
2483GLboolean XMesaGetBackBuffer( XMesaBuffer b,
2484                              XMesaPixmap *pixmap,
2485                              XMesaImage **ximage )
2486{
2487   if (b->db_state) {
2488      if (pixmap)  *pixmap = b->backpixmap;
2489      if (ximage)  *ximage = b->backimage;
2490      return GL_TRUE;
2491   }
2492   else {
2493      *pixmap = 0;
2494      *ximage = NULL;
2495      return GL_FALSE;
2496   }
2497}
2498
2499
2500/*
2501 * Return the depth buffer associated with an XMesaBuffer.
2502 * Input:  b - the XMesa buffer handle
2503 * Output:  width, height - size of buffer in pixels
2504 *          bytesPerValue - bytes per depth value (2 or 4)
2505 *          buffer - pointer to depth buffer values
2506 * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
2507 */
2508GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
2509                               GLint *bytesPerValue, void **buffer )
2510{
2511   if (!b->mesa_buffer.DepthBuffer) {
2512      *width = 0;
2513      *height = 0;
2514      *bytesPerValue = 0;
2515      *buffer = 0;
2516      return GL_FALSE;
2517   }
2518   else {
2519      *width = b->mesa_buffer.Width;
2520      *height = b->mesa_buffer.Height;
2521      *bytesPerValue = sizeof(GLdepth);
2522      *buffer = b->mesa_buffer.DepthBuffer;
2523      return GL_TRUE;
2524   }
2525}
2526
2527
2528void XMesaFlush( XMesaContext c )
2529{
2530   if (c && c->xm_visual) {
2531#ifdef XFree86Server
2532      /* NOT_NEEDED */
2533#else
2534      XSync( c->xm_visual->display, False );
2535#endif
2536   }
2537}
2538
2539
2540
2541const char *XMesaGetString( XMesaContext c, int name )
2542{
2543   (void) c;
2544   if (name==XMESA_VERSION) {
2545      return "5.0";
2546   }
2547   else if (name==XMESA_EXTENSIONS) {
2548      return "";
2549   }
2550   else {
2551      return NULL;
2552   }
2553}
2554
2555
2556
2557XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
2558{
2559   XMesaBuffer b;
2560   for (b=XMesaBufferList; b; b=b->Next) {
2561      if (b->frontbuffer==d && b->display==dpy) {
2562         return b;
2563      }
2564   }
2565   return NULL;
2566}
2567
2568
2569
2570/*
2571 * Look for XMesaBuffers whose X window has been destroyed.
2572 * Deallocate any such XMesaBuffers.
2573 */
2574void XMesaGarbageCollect( void )
2575{
2576   XMesaBuffer b, next;
2577   for (b=XMesaBufferList; b; b=next) {
2578      next = b->Next;
2579      if (b->display && b->frontbuffer && b->type == WINDOW) {
2580#ifdef XFree86Server
2581	 /* NOT_NEEDED */
2582#else
2583         XSync(b->display, False);
2584         if (!window_exists( b->display, b->frontbuffer )) {
2585            /* found a dead window, free the ancillary info */
2586            XMesaDestroyBuffer( b );
2587         }
2588#endif
2589      }
2590   }
2591}
2592
2593
2594void XMesaReset( void )
2595{
2596    while (XMesaBufferList)
2597	XMesaDestroyBuffer(XMesaBufferList);
2598
2599    XMesaBufferList = NULL;
2600}
2601
2602
2603unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
2604                                GLfloat red, GLfloat green,
2605                                GLfloat blue, GLfloat alpha )
2606{
2607   GLint r = (GLint) (red   * 255.0F);
2608   GLint g = (GLint) (green * 255.0F);
2609   GLint b = (GLint) (blue  * 255.0F);
2610   GLint a = (GLint) (alpha * 255.0F);
2611
2612   switch (xmesa->pixelformat) {
2613      case PF_Index:
2614         return 0;
2615      case PF_Truecolor:
2616         {
2617            unsigned long p;
2618            PACK_TRUECOLOR( p, r, g, b );
2619            return p;
2620         }
2621      case PF_8A8B8G8R:
2622         return PACK_8A8B8G8R( r, g, b, a );
2623      case PF_8R8G8B:
2624         return PACK_8R8G8B( r, g, b );
2625      case PF_5R6G5B:
2626         return PACK_5R6G5B( r, g, b );
2627      case PF_Dither:
2628         {
2629            DITHER_SETUP;
2630            return DITHER( x, y, r, g, b );
2631         }
2632      case PF_1Bit:
2633         /* 382 = (3*255)/2 */
2634         return ((r+g+b) > 382) ^ xmesa->xm_visual->bitFlip;
2635      case PF_HPCR:
2636         return DITHER_HPCR(x, y, r, g, b);
2637      case PF_Lookup:
2638         {
2639            LOOKUP_SETUP;
2640            return LOOKUP( r, g, b );
2641         }
2642      case PF_Grayscale:
2643         return GRAY_RGB( r, g, b );
2644      case PF_Dither_5R6G5B:
2645         /* fall through */
2646      case PF_Dither_True:
2647         {
2648            unsigned long p;
2649            PACK_TRUEDITHER(p, x, y, r, g, b);
2650            return p;
2651         }
2652      default:
2653         _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
2654   }
2655   return 0;
2656}
2657
2658
2659/*
2660 * This is typically called when the window size changes and we need
2661 * to reallocate the buffer's back/depth/stencil/accum buffers.
2662 */
2663void XMesaResizeBuffers( XMesaBuffer b )
2664{
2665   xmesa_resize_buffers( &(b->mesa_buffer) );
2666
2667}
2668
2669