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