• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 1999-2007  Brian Paul   All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * 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 <stdio.h>
66 #include "glxheader.h"
67 #include "xmesaP.h"
68 #include "main/api_exec.h"
69 #include "main/context.h"
70 #include "main/extensions.h"
71 #include "main/framebuffer.h"
72 #include "main/macros.h"
73 #include "main/renderbuffer.h"
74 #include "main/teximage.h"
75 #include "main/version.h"
76 #include "main/vtxfmt.h"
77 #include "swrast/swrast.h"
78 #include "swrast/s_renderbuffer.h"
79 #include "swrast_setup/swrast_setup.h"
80 #include "vbo/vbo.h"
81 #include "tnl/tnl.h"
82 #include "tnl/t_context.h"
83 #include "tnl/t_pipeline.h"
84 #include "drivers/common/driverfuncs.h"
85 #include "drivers/common/meta.h"
86 #include "util/u_memory.h"
87 
88 /**
89  * Global X driver lock
90  */
91 mtx_t _xmesa_lock;
92 
93 
94 
95 /**********************************************************************/
96 /*****                     X Utility Functions                    *****/
97 /**********************************************************************/
98 
99 
100 /**
101  * Return the host's byte order as LSBFirst or MSBFirst ala X.
102  */
host_byte_order(void)103 static int host_byte_order( void )
104 {
105    int i = 1;
106    char *cptr = (char *) &i;
107    return (*cptr==1) ? LSBFirst : MSBFirst;
108 }
109 
110 
111 /**
112  * Check if the X Shared Memory extension is available.
113  * Return:  0 = not available
114  *          1 = shared XImage support available
115  *          2 = shared Pixmap support available also
116  */
check_for_xshm(XMesaDisplay * display)117 static int check_for_xshm( XMesaDisplay *display )
118 {
119 #if defined(USE_XSHM)
120    int ignore;
121 
122    if (XQueryExtension( display, "MIT-SHM", &ignore, &ignore, &ignore )) {
123       /* Note: we're no longer calling XShmQueryVersion() here.  It seems
124        * to be flakey (triggers a spurious X protocol error when we close
125        * one display connection and start using a new one.  XShm has been
126        * around a long time and hasn't changed so if MIT_SHM is supported
127        * we assume we're good to go.
128        */
129       return 2;
130    }
131    else {
132       return 0;
133    }
134 #else
135    /* No  XSHM support */
136    return 0;
137 #endif
138 }
139 
140 
141 /**
142  * Apply gamma correction to an intensity value in [0..max].  Return the
143  * new intensity value.
144  */
145 static GLint
gamma_adjust(GLfloat gamma,GLint value,GLint max)146 gamma_adjust( GLfloat gamma, GLint value, GLint max )
147 {
148    if (gamma == 1.0) {
149       return value;
150    }
151    else {
152       double x = (double) value / (double) max;
153       return lroundf((GLfloat) max * pow(x, 1.0F/gamma));
154    }
155 }
156 
157 
158 
159 /**
160  * Return the true number of bits per pixel for XImages.
161  * For example, if we request a 24-bit deep visual we may actually need/get
162  * 32bpp XImages.  This function returns the appropriate bpp.
163  * Input:  dpy - the X display
164  *         visinfo - desribes the visual to be used for XImages
165  * Return:  true number of bits per pixel for XImages
166  */
167 static int
bits_per_pixel(XMesaVisual xmv)168 bits_per_pixel( XMesaVisual xmv )
169 {
170    XMesaDisplay *dpy = xmv->display;
171    XMesaVisualInfo visinfo = xmv->visinfo;
172    XMesaImage *img;
173    int bitsPerPixel;
174    /* Create a temporary XImage */
175    img = XCreateImage( dpy, visinfo->visual, visinfo->depth,
176 		       ZPixmap, 0,           /*format, offset*/
177 		       malloc(8),    /*data*/
178 		       1, 1,                 /*width, height*/
179 		       32,                   /*bitmap_pad*/
180 		       0                     /*bytes_per_line*/
181                      );
182    assert(img);
183    /* grab the bits/pixel value */
184    bitsPerPixel = img->bits_per_pixel;
185    /* free the XImage */
186    free( img->data );
187    img->data = NULL;
188    XMesaDestroyImage( img );
189    return bitsPerPixel;
190 }
191 
192 
193 
194 /*
195  * Determine if a given X window ID is valid (window exists).
196  * Do this by calling XGetWindowAttributes() for the window and
197  * checking if we catch an X error.
198  * Input:  dpy - the display
199  *         win - the window to check for existence
200  * Return:  GL_TRUE - window exists
201  *          GL_FALSE - window doesn't exist
202  */
203 static GLboolean WindowExistsFlag;
204 
window_exists_err_handler(XMesaDisplay * dpy,XErrorEvent * xerr)205 static int window_exists_err_handler( XMesaDisplay* dpy, XErrorEvent* xerr )
206 {
207    (void) dpy;
208    if (xerr->error_code == BadWindow) {
209       WindowExistsFlag = GL_FALSE;
210    }
211    return 0;
212 }
213 
window_exists(XMesaDisplay * dpy,Window win)214 static GLboolean window_exists( XMesaDisplay *dpy, Window win )
215 {
216    XWindowAttributes wa;
217    int (*old_handler)( XMesaDisplay*, XErrorEvent* );
218    WindowExistsFlag = GL_TRUE;
219    old_handler = XSetErrorHandler(window_exists_err_handler);
220    XGetWindowAttributes( dpy, win, &wa ); /* dummy request */
221    XSetErrorHandler(old_handler);
222    return WindowExistsFlag;
223 }
224 
225 static Status
get_drawable_size(XMesaDisplay * dpy,Drawable d,GLuint * width,GLuint * height)226 get_drawable_size( XMesaDisplay *dpy, Drawable d, GLuint *width, GLuint *height )
227 {
228    Window root;
229    Status stat;
230    int xpos, ypos;
231    unsigned int w, h, bw, depth;
232    stat = XGetGeometry(dpy, d, &root, &xpos, &ypos, &w, &h, &bw, &depth);
233    *width = w;
234    *height = h;
235    return stat;
236 }
237 
238 
239 /**
240  * Return the size of the window (or pixmap) that corresponds to the
241  * given XMesaBuffer.
242  * \param width  returns width in pixels
243  * \param height  returns height in pixels
244  */
245 void
xmesa_get_window_size(XMesaDisplay * dpy,XMesaBuffer b,GLuint * width,GLuint * height)246 xmesa_get_window_size(XMesaDisplay *dpy, XMesaBuffer b,
247                       GLuint *width, GLuint *height)
248 {
249    Status stat;
250 
251    mtx_lock(&_xmesa_lock);
252    XSync(b->xm_visual->display, 0); /* added for Chromium */
253    stat = get_drawable_size(dpy, b->frontxrb->pixmap, width, height);
254    mtx_unlock(&_xmesa_lock);
255 
256    if (!stat) {
257       /* probably querying a window that's recently been destroyed */
258       _mesa_warning(NULL, "XGetGeometry failed!\n");
259       *width = *height = 1;
260    }
261 }
262 
263 
264 
265 /**********************************************************************/
266 /*****                Linked list of XMesaBuffers                 *****/
267 /**********************************************************************/
268 
269 XMesaBuffer XMesaBufferList = NULL;
270 
271 
272 /**
273  * Allocate a new XMesaBuffer object which corresponds to the given drawable.
274  * Note that XMesaBuffer is derived from struct gl_framebuffer.
275  * The new XMesaBuffer will not have any size (Width=Height=0).
276  *
277  * \param d  the corresponding X drawable (window or pixmap)
278  * \param type  either WINDOW, PIXMAP or PBUFFER, describing d
279  * \param vis  the buffer's visual
280  * \param cmap  the window's colormap, if known.
281  * \return new XMesaBuffer or NULL if any problem
282  */
283 static XMesaBuffer
create_xmesa_buffer(XMesaDrawable d,BufferType type,XMesaVisual vis,XMesaColormap cmap)284 create_xmesa_buffer(XMesaDrawable d, BufferType type,
285                     XMesaVisual vis, XMesaColormap cmap)
286 {
287    XMesaBuffer b;
288 
289    assert(type == WINDOW || type == PIXMAP || type == PBUFFER);
290 
291    b = (XMesaBuffer) CALLOC_STRUCT(xmesa_buffer);
292    if (!b)
293       return NULL;
294 
295    b->display = vis->display;
296    b->xm_visual = vis;
297    b->type = type;
298    b->cmap = cmap;
299 
300    _mesa_initialize_window_framebuffer(&b->mesa_buffer, &vis->mesa_visual);
301    b->mesa_buffer.Delete = xmesa_delete_framebuffer;
302 
303    /*
304     * Front renderbuffer
305     */
306    b->frontxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_FALSE);
307    if (!b->frontxrb) {
308       free(b);
309       return NULL;
310    }
311    b->frontxrb->Parent = b;
312    b->frontxrb->drawable = d;
313    b->frontxrb->pixmap = (XMesaPixmap) d;
314    _mesa_attach_and_own_rb(&b->mesa_buffer, BUFFER_FRONT_LEFT,
315                            &b->frontxrb->Base.Base);
316 
317    /*
318     * Back renderbuffer
319     */
320    if (vis->mesa_visual.doubleBufferMode) {
321       b->backxrb = xmesa_new_renderbuffer(NULL, 0, vis, GL_TRUE);
322       if (!b->backxrb) {
323          /* XXX free front xrb too */
324          free(b);
325          return NULL;
326       }
327       b->backxrb->Parent = b;
328       /* determine back buffer implementation */
329       b->db_mode = vis->ximage_flag ? BACK_XIMAGE : BACK_PIXMAP;
330 
331       _mesa_attach_and_own_rb(&b->mesa_buffer, BUFFER_BACK_LEFT,
332                               &b->backxrb->Base.Base);
333    }
334 
335    /*
336     * Other renderbuffer (depth, stencil, etc)
337     */
338    _swrast_add_soft_renderbuffers(&b->mesa_buffer,
339                                   GL_FALSE,  /* color */
340                                   vis->mesa_visual.depthBits > 0,
341                                   vis->mesa_visual.stencilBits > 0,
342                                   vis->mesa_visual.accumRedBits > 0,
343                                   GL_FALSE,  /* software alpha buffer */
344                                   vis->mesa_visual.numAuxBuffers > 0 );
345 
346    /* GLX_EXT_texture_from_pixmap */
347    b->TextureTarget = 0;
348    b->TextureFormat = GLX_TEXTURE_FORMAT_NONE_EXT;
349    b->TextureMipmap = 0;
350 
351    /* insert buffer into linked list */
352    b->Next = XMesaBufferList;
353    XMesaBufferList = b;
354 
355    return b;
356 }
357 
358 
359 /**
360  * Find an XMesaBuffer by matching X display and colormap but NOT matching
361  * the notThis buffer.
362  */
363 XMesaBuffer
xmesa_find_buffer(XMesaDisplay * dpy,XMesaColormap cmap,XMesaBuffer notThis)364 xmesa_find_buffer(XMesaDisplay *dpy, XMesaColormap cmap, XMesaBuffer notThis)
365 {
366    XMesaBuffer b;
367    for (b=XMesaBufferList; b; b=b->Next) {
368       if (b->display==dpy && b->cmap==cmap && b!=notThis) {
369          return b;
370       }
371    }
372    return NULL;
373 }
374 
375 
376 /**
377  * Remove buffer from linked list, delete if no longer referenced.
378  */
379 static void
xmesa_free_buffer(XMesaBuffer buffer)380 xmesa_free_buffer(XMesaBuffer buffer)
381 {
382    XMesaBuffer prev = NULL, b;
383 
384    for (b = XMesaBufferList; b; b = b->Next) {
385       if (b == buffer) {
386          struct gl_framebuffer *fb = &buffer->mesa_buffer;
387 
388          /* unlink buffer from list */
389          if (prev)
390             prev->Next = buffer->Next;
391          else
392             XMesaBufferList = buffer->Next;
393 
394          /* mark as delete pending */
395          fb->DeletePending = GL_TRUE;
396 
397          /* Since the X window for the XMesaBuffer is going away, we don't
398           * want to dereference this pointer in the future.
399           */
400          b->frontxrb->drawable = 0;
401 
402          /* Unreference.  If count = zero we'll really delete the buffer */
403          _mesa_reference_framebuffer(&fb, NULL);
404 
405          return;
406       }
407       /* continue search */
408       prev = b;
409    }
410    /* buffer not found in XMesaBufferList */
411    _mesa_problem(NULL,"xmesa_free_buffer() - buffer not found\n");
412 }
413 
414 
415 
416 
417 /**********************************************************************/
418 /*****                   Misc Private Functions                   *****/
419 /**********************************************************************/
420 
421 
422 /**
423  * Setup RGB rendering for a window with a True/DirectColor visual.
424  */
425 static void
setup_truecolor(XMesaVisual v,XMesaBuffer buffer,XMesaColormap cmap)426 setup_truecolor(XMesaVisual v, XMesaBuffer buffer, XMesaColormap cmap)
427 {
428    unsigned long rmask, gmask, bmask;
429    (void) buffer;
430    (void) cmap;
431 
432    /* Compute red multiplier (mask) and bit shift */
433    v->rshift = 0;
434    rmask = GET_REDMASK(v);
435    while ((rmask & 1)==0) {
436       v->rshift++;
437       rmask = rmask >> 1;
438    }
439 
440    /* Compute green multiplier (mask) and bit shift */
441    v->gshift = 0;
442    gmask = GET_GREENMASK(v);
443    while ((gmask & 1)==0) {
444       v->gshift++;
445       gmask = gmask >> 1;
446    }
447 
448    /* Compute blue multiplier (mask) and bit shift */
449    v->bshift = 0;
450    bmask = GET_BLUEMASK(v);
451    while ((bmask & 1)==0) {
452       v->bshift++;
453       bmask = bmask >> 1;
454    }
455 
456    /*
457     * Compute component-to-pixel lookup tables and dithering kernel
458     */
459    {
460       static GLubyte kernel[16] = {
461           0*16,  8*16,  2*16, 10*16,
462          12*16,  4*16, 14*16,  6*16,
463           3*16, 11*16,  1*16,  9*16,
464          15*16,  7*16, 13*16,  5*16,
465       };
466       GLint rBits = util_bitcount(rmask);
467       GLint gBits = util_bitcount(gmask);
468       GLint bBits = util_bitcount(bmask);
469       GLint maxBits;
470       GLuint i;
471 
472       /* convert pixel components in [0,_mask] to RGB values in [0,255] */
473       for (i=0; i<=rmask; i++)
474          v->PixelToR[i] = (unsigned char) ((i * 255) / rmask);
475       for (i=0; i<=gmask; i++)
476          v->PixelToG[i] = (unsigned char) ((i * 255) / gmask);
477       for (i=0; i<=bmask; i++)
478          v->PixelToB[i] = (unsigned char) ((i * 255) / bmask);
479 
480       /* convert RGB values from [0,255] to pixel components */
481 
482       for (i=0;i<256;i++) {
483          GLint r = gamma_adjust(v->RedGamma,   i, 255);
484          GLint g = gamma_adjust(v->GreenGamma, i, 255);
485          GLint b = gamma_adjust(v->BlueGamma,  i, 255);
486          v->RtoPixel[i] = (r >> (8-rBits)) << v->rshift;
487          v->GtoPixel[i] = (g >> (8-gBits)) << v->gshift;
488          v->BtoPixel[i] = (b >> (8-bBits)) << v->bshift;
489       }
490       /* overflow protection */
491       for (i=256;i<512;i++) {
492          v->RtoPixel[i] = v->RtoPixel[255];
493          v->GtoPixel[i] = v->GtoPixel[255];
494          v->BtoPixel[i] = v->BtoPixel[255];
495       }
496 
497       /* setup dithering kernel */
498       maxBits = rBits;
499       if (gBits > maxBits)  maxBits = gBits;
500       if (bBits > maxBits)  maxBits = bBits;
501       for (i=0;i<16;i++) {
502          v->Kernel[i] = kernel[i] >> maxBits;
503       }
504 
505       v->undithered_pf = PF_Truecolor;
506       v->dithered_pf = (GET_VISUAL_DEPTH(v)<24) ? PF_Dither_True : PF_Truecolor;
507    }
508 
509    /*
510     * Now check for TrueColor visuals which we can optimize.
511     */
512    if (   GET_REDMASK(v)  ==0x0000ff
513        && GET_GREENMASK(v)==0x00ff00
514        && GET_BLUEMASK(v) ==0xff0000
515        && CHECK_BYTE_ORDER(v)
516        && v->BitsPerPixel==32
517        && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
518       /* common 32 bpp config used on SGI, Sun */
519       v->undithered_pf = v->dithered_pf = PF_8A8B8G8R; /* ABGR */
520    }
521    else if (GET_REDMASK(v)  == 0xff0000
522          && GET_GREENMASK(v)== 0x00ff00
523          && GET_BLUEMASK(v) == 0x0000ff
524          && CHECK_BYTE_ORDER(v)
525          && v->RedGamma == 1.0 && v->GreenGamma == 1.0 && v->BlueGamma == 1.0){
526       if (v->BitsPerPixel==32) {
527          /* if 32 bpp, and visual indicates 8 bpp alpha channel */
528          if (GET_VISUAL_DEPTH(v) == 32 && v->mesa_visual.alphaBits == 8)
529             v->undithered_pf = v->dithered_pf = PF_8A8R8G8B; /* ARGB */
530          else
531             v->undithered_pf = v->dithered_pf = PF_8R8G8B; /* xRGB */
532       }
533       else if (v->BitsPerPixel == 24) {
534          v->undithered_pf = v->dithered_pf = PF_8R8G8B24; /* RGB */
535       }
536    }
537    else if (GET_REDMASK(v)  ==0xf800
538        &&   GET_GREENMASK(v)==0x07e0
539        &&   GET_BLUEMASK(v) ==0x001f
540        && CHECK_BYTE_ORDER(v)
541        && v->BitsPerPixel==16
542        && v->RedGamma==1.0 && v->GreenGamma==1.0 && v->BlueGamma==1.0) {
543       /* 5-6-5 RGB */
544       v->undithered_pf = PF_5R6G5B;
545       v->dithered_pf = PF_Dither_5R6G5B;
546    }
547 }
548 
549 
550 /**
551  * When a context is bound for the first time, we can finally finish
552  * initializing the context's visual and buffer information.
553  * \param v  the XMesaVisual to initialize
554  * \param b  the XMesaBuffer to initialize (may be NULL)
555  * \param rgb_flag  TRUE = RGBA mode, FALSE = color index mode
556  * \param window  the window/pixmap we're rendering into
557  * \param cmap  the colormap associated with the window/pixmap
558  * \return GL_TRUE=success, GL_FALSE=failure
559  */
560 static GLboolean
initialize_visual_and_buffer(XMesaVisual v,XMesaBuffer b,XMesaDrawable window,XMesaColormap cmap)561 initialize_visual_and_buffer(XMesaVisual v, XMesaBuffer b,
562                              XMesaDrawable window,
563                              XMesaColormap cmap)
564 {
565    const int xclass = v->visualType;
566 
567 
568    assert(!b || b->xm_visual == v);
569 
570    /* Save true bits/pixel */
571    v->BitsPerPixel = bits_per_pixel(v);
572    assert(v->BitsPerPixel > 0);
573 
574    /* RGB WINDOW:
575     * We support RGB rendering into almost any kind of visual.
576     */
577    if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
578       setup_truecolor( v, b, cmap );
579    }
580    else {
581       _mesa_warning(NULL, "XMesa: RGB mode rendering not supported in given visual.\n");
582       return GL_FALSE;
583    }
584 
585    if (getenv("MESA_NO_DITHER")) {
586       v->dithered_pf = v->undithered_pf;
587    }
588 
589 
590    /*
591     * If MESA_INFO env var is set print out some debugging info
592     * which can help Brian figure out what's going on when a user
593     * reports bugs.
594     */
595    if (getenv("MESA_INFO")) {
596       printf("X/Mesa visual = %p\n", (void *) v);
597       printf("X/Mesa dithered pf = %u\n", v->dithered_pf);
598       printf("X/Mesa undithered pf = %u\n", v->undithered_pf);
599       printf("X/Mesa level = %d\n", v->mesa_visual.level);
600       printf("X/Mesa depth = %d\n", GET_VISUAL_DEPTH(v));
601       printf("X/Mesa bits per pixel = %d\n", v->BitsPerPixel);
602    }
603 
604    if (b && window) {
605       /* Do window-specific initializations */
606 
607       /* these should have been set in create_xmesa_buffer */
608       assert(b->frontxrb->drawable == window);
609       assert(b->frontxrb->pixmap == (XMesaPixmap) window);
610 
611       /* Setup for single/double buffering */
612       if (v->mesa_visual.doubleBufferMode) {
613          /* Double buffered */
614          b->shm = check_for_xshm( v->display );
615       }
616 
617       /* X11 graphics contexts */
618       b->gc = XCreateGC( v->display, window, 0, NULL );
619       XMesaSetFunction( v->display, b->gc, GXcopy );
620 
621       /* cleargc - for glClear() */
622       b->cleargc = XCreateGC( v->display, window, 0, NULL );
623       XMesaSetFunction( v->display, b->cleargc, GXcopy );
624 
625       /*
626        * Don't generate Graphics Expose/NoExpose events in swapbuffers().
627        * Patch contributed by Michael Pichler May 15, 1995.
628        */
629       {
630          XGCValues gcvalues;
631          gcvalues.graphics_exposures = False;
632          b->swapgc = XCreateGC(v->display, window,
633                                GCGraphicsExposures, &gcvalues);
634       }
635       XMesaSetFunction( v->display, b->swapgc, GXcopy );
636    }
637 
638    return GL_TRUE;
639 }
640 
641 
642 
643 /*
644  * Convert an RGBA color to a pixel value.
645  */
646 unsigned long
xmesa_color_to_pixel(struct gl_context * ctx,GLubyte r,GLubyte g,GLubyte b,GLubyte a,GLuint pixelFormat)647 xmesa_color_to_pixel(struct gl_context *ctx,
648                      GLubyte r, GLubyte g, GLubyte b, GLubyte a,
649                      GLuint pixelFormat)
650 {
651    XMesaContext xmesa = XMESA_CONTEXT(ctx);
652    switch (pixelFormat) {
653       case PF_Truecolor:
654          {
655             unsigned long p;
656             PACK_TRUECOLOR( p, r, g, b );
657             return p;
658          }
659       case PF_8A8B8G8R:
660          return PACK_8A8B8G8R( r, g, b, a );
661       case PF_8A8R8G8B:
662          return PACK_8A8R8G8B( r, g, b, a );
663       case PF_8R8G8B:
664          /* fall through */
665       case PF_8R8G8B24:
666          return PACK_8R8G8B( r, g, b );
667       case PF_5R6G5B:
668          return PACK_5R6G5B( r, g, b );
669       case PF_Dither_True:
670          /* fall through */
671       case PF_Dither_5R6G5B:
672          {
673             unsigned long p;
674             PACK_TRUEDITHER(p, 1, 0, r, g, b);
675             return p;
676          }
677       default:
678          _mesa_problem(ctx, "Bad pixel format in xmesa_color_to_pixel");
679    }
680    return 0;
681 }
682 
683 
684 #define NUM_VISUAL_TYPES   6
685 
686 /**
687  * Convert an X visual type to a GLX visual type.
688  *
689  * \param visualType X visual type (i.e., \c TrueColor, \c StaticGray, etc.)
690  *        to be converted.
691  * \return If \c visualType is a valid X visual type, a GLX visual type will
692  *         be returned.  Otherwise \c GLX_NONE will be returned.
693  *
694  * \note
695  * This code was lifted directly from lib/GL/glx/glcontextmodes.c in the
696  * DRI CVS tree.
697  */
698 static GLint
xmesa_convert_from_x_visual_type(int visualType)699 xmesa_convert_from_x_visual_type( int visualType )
700 {
701     static const int glx_visual_types[ NUM_VISUAL_TYPES ] = {
702 	GLX_STATIC_GRAY,  GLX_GRAY_SCALE,
703 	GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
704 	GLX_TRUE_COLOR,   GLX_DIRECT_COLOR
705     };
706 
707     return ( (unsigned) visualType < NUM_VISUAL_TYPES )
708 	? glx_visual_types[ visualType ] : GLX_NONE;
709 }
710 
711 
712 /**********************************************************************/
713 /*****                       Public Functions                     *****/
714 /**********************************************************************/
715 
716 
717 /*
718  * Create a new X/Mesa visual.
719  * Input:  display - X11 display
720  *         visinfo - an XVisualInfo pointer
721  *         rgb_flag - GL_TRUE = RGB mode,
722  *                    GL_FALSE = color index mode
723  *         alpha_flag - alpha buffer requested?
724  *         db_flag - GL_TRUE = double-buffered,
725  *                   GL_FALSE = single buffered
726  *         stereo_flag - stereo visual?
727  *         ximage_flag - GL_TRUE = use an XImage for back buffer,
728  *                       GL_FALSE = use an off-screen pixmap for back buffer
729  *         depth_size - requested bits/depth values, or zero
730  *         stencil_size - requested bits/stencil values, or zero
731  *         accum_red_size - requested bits/red accum values, or zero
732  *         accum_green_size - requested bits/green accum values, or zero
733  *         accum_blue_size - requested bits/blue accum values, or zero
734  *         accum_alpha_size - requested bits/alpha accum values, or zero
735  *         num_samples - number of samples/pixel if multisampling, or zero
736  *         level - visual level, usually 0
737  *         visualCaveat - ala the GLX extension, usually GLX_NONE
738  * Return;  a new XMesaVisual or 0 if error.
739  */
740 PUBLIC
XMesaCreateVisual(XMesaDisplay * display,XMesaVisualInfo visinfo,GLboolean rgb_flag,GLboolean alpha_flag,GLboolean db_flag,GLboolean stereo_flag,GLboolean ximage_flag,GLint depth_size,GLint stencil_size,GLint accum_red_size,GLint accum_green_size,GLint accum_blue_size,GLint accum_alpha_size,GLint num_samples,GLint level,GLint visualCaveat)741 XMesaVisual XMesaCreateVisual( XMesaDisplay *display,
742                                XMesaVisualInfo visinfo,
743                                GLboolean rgb_flag,
744                                GLboolean alpha_flag,
745                                GLboolean db_flag,
746                                GLboolean stereo_flag,
747                                GLboolean ximage_flag,
748                                GLint depth_size,
749                                GLint stencil_size,
750                                GLint accum_red_size,
751                                GLint accum_green_size,
752                                GLint accum_blue_size,
753                                GLint accum_alpha_size,
754                                GLint num_samples,
755                                GLint level,
756                                GLint visualCaveat )
757 {
758    char *gamma;
759    XMesaVisual v;
760    GLint red_bits, green_bits, blue_bits, alpha_bits;
761 
762    /* For debugging only */
763    if (getenv("MESA_XSYNC")) {
764       /* This makes debugging X easier.
765        * In your debugger, set a breakpoint on _XError to stop when an
766        * X protocol error is generated.
767        */
768       XSynchronize( display, 1 );
769    }
770 
771    /* Color-index rendering not supported. */
772    if (!rgb_flag)
773       return NULL;
774 
775    v = (XMesaVisual) CALLOC_STRUCT(xmesa_visual);
776    if (!v) {
777       return NULL;
778    }
779 
780    v->display = display;
781 
782    /* Save a copy of the XVisualInfo struct because the user may Xfree()
783     * the struct but we may need some of the information contained in it
784     * at a later time.
785     */
786    v->visinfo = malloc(sizeof(*visinfo));
787    if(!v->visinfo) {
788       free(v);
789       return NULL;
790    }
791    memcpy(v->visinfo, visinfo, sizeof(*visinfo));
792 
793    /* check for MESA_GAMMA environment variable */
794    gamma = getenv("MESA_GAMMA");
795    if (gamma) {
796       v->RedGamma = v->GreenGamma = v->BlueGamma = 0.0;
797       sscanf( gamma, "%f %f %f", &v->RedGamma, &v->GreenGamma, &v->BlueGamma );
798       if (v->RedGamma<=0.0)    v->RedGamma = 1.0;
799       if (v->GreenGamma<=0.0)  v->GreenGamma = v->RedGamma;
800       if (v->BlueGamma<=0.0)   v->BlueGamma = v->RedGamma;
801    }
802    else {
803       v->RedGamma = v->GreenGamma = v->BlueGamma = 1.0;
804    }
805 
806    v->ximage_flag = ximage_flag;
807 
808    v->mesa_visual.redMask = visinfo->red_mask;
809    v->mesa_visual.greenMask = visinfo->green_mask;
810    v->mesa_visual.blueMask = visinfo->blue_mask;
811    v->visualID = visinfo->visualid;
812    v->screen = visinfo->screen;
813 
814 #if !(defined(__cplusplus) || defined(c_plusplus))
815    v->visualType = xmesa_convert_from_x_visual_type(visinfo->class);
816 #else
817    v->visualType = xmesa_convert_from_x_visual_type(visinfo->c_class);
818 #endif
819 
820    v->mesa_visual.visualRating = visualCaveat;
821 
822    if (alpha_flag)
823       v->mesa_visual.alphaBits = 8;
824 
825    (void) initialize_visual_and_buffer( v, NULL, 0, 0 );
826 
827    {
828       const int xclass = v->visualType;
829       if (xclass == GLX_TRUE_COLOR || xclass == GLX_DIRECT_COLOR) {
830          red_bits   = util_bitcount(GET_REDMASK(v));
831          green_bits = util_bitcount(GET_GREENMASK(v));
832          blue_bits  = util_bitcount(GET_BLUEMASK(v));
833       }
834       else {
835          /* this is an approximation */
836          int depth;
837          depth = GET_VISUAL_DEPTH(v);
838          red_bits = depth / 3;
839          depth -= red_bits;
840          green_bits = depth / 2;
841          depth -= green_bits;
842          blue_bits = depth;
843          alpha_bits = 0;
844          assert( red_bits + green_bits + blue_bits == GET_VISUAL_DEPTH(v) );
845       }
846       alpha_bits = v->mesa_visual.alphaBits;
847    }
848 
849    if (!_mesa_initialize_visual(&v->mesa_visual,
850                                 db_flag, stereo_flag,
851                                 red_bits, green_bits,
852                                 blue_bits, alpha_bits,
853                                 depth_size,
854                                 stencil_size,
855                                 accum_red_size, accum_green_size,
856                                 accum_blue_size, accum_alpha_size,
857                                 0)) {
858       free(v->visinfo);
859       free(v);
860       return NULL;
861    }
862 
863    /* XXX minor hack */
864    v->mesa_visual.level = level;
865    return v;
866 }
867 
868 
869 PUBLIC
XMesaDestroyVisual(XMesaVisual v)870 void XMesaDestroyVisual( XMesaVisual v )
871 {
872    free(v->visinfo);
873    free(v);
874 }
875 
876 
877 
878 /**
879  * Create a new XMesaContext.
880  * \param v  the XMesaVisual
881  * \param share_list  another XMesaContext with which to share display
882  *                    lists or NULL if no sharing is wanted.
883  * \return an XMesaContext or NULL if error.
884  */
885 PUBLIC
XMesaCreateContext(XMesaVisual v,XMesaContext share_list)886 XMesaContext XMesaCreateContext( XMesaVisual v, XMesaContext share_list )
887 {
888    static GLboolean firstTime = GL_TRUE;
889    XMesaContext c;
890    struct gl_context *mesaCtx;
891    struct dd_function_table functions;
892    TNLcontext *tnl;
893 
894    if (firstTime) {
895       mtx_init(&_xmesa_lock, mtx_plain);
896       firstTime = GL_FALSE;
897    }
898 
899    /* Note: the XMesaContext contains a Mesa struct gl_context struct (inheritance) */
900    c = (XMesaContext) CALLOC_STRUCT(xmesa_context);
901    if (!c)
902       return NULL;
903 
904    mesaCtx = &(c->mesa);
905 
906    /* initialize with default driver functions, then plug in XMesa funcs */
907    _mesa_init_driver_functions(&functions);
908    _tnl_init_driver_draw_function(&functions);
909    xmesa_init_driver_functions(v, &functions);
910    if (!_mesa_initialize_context(mesaCtx, API_OPENGL_COMPAT, &v->mesa_visual,
911                       share_list ? &(share_list->mesa) : (struct gl_context *) NULL,
912                       &functions)) {
913       free(c);
914       return NULL;
915    }
916 
917    /* Enable this to exercise fixed function -> shader translation
918     * with software rendering.
919     */
920    if (0) {
921       mesaCtx->VertexProgram._MaintainTnlProgram = GL_TRUE;
922       mesaCtx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
923    }
924 
925    _mesa_enable_sw_extensions(mesaCtx);
926 
927 #if ENABLE_EXT_timer_query
928     mesaCtx->Extensions.EXT_timer_query = GL_TRUE;
929 #endif
930 
931 
932    /* finish up xmesa context initializations */
933    c->direct = GL_TRUE;
934    c->swapbytes = CHECK_BYTE_ORDER(v) ? GL_FALSE : GL_TRUE;
935    c->xm_visual = v;
936    c->xm_buffer = NULL;   /* set later by XMesaMakeCurrent */
937    c->display = v->display;
938    c->pixelformat = v->dithered_pf;      /* Dithering is enabled by default */
939 
940    /* Initialize the software rasterizer and helper modules.
941     */
942    if (!_swrast_CreateContext( mesaCtx ) ||
943        !_vbo_CreateContext( mesaCtx, false ) ||
944        !_tnl_CreateContext( mesaCtx ) ||
945        !_swsetup_CreateContext( mesaCtx )) {
946       _mesa_free_context_data(&c->mesa, true);
947       free(c);
948       return NULL;
949    }
950 
951    /* tnl setup */
952    tnl = TNL_CONTEXT(mesaCtx);
953    tnl->Driver.RunPipeline = _tnl_run_pipeline;
954    /* swrast setup */
955    xmesa_register_swrast_functions( mesaCtx );
956    _swsetup_Wakeup(mesaCtx);
957 
958    _mesa_meta_init(mesaCtx);
959 
960    _mesa_override_extensions(mesaCtx);
961    _mesa_compute_version(mesaCtx);
962 
963     /* Exec table initialization requires the version to be computed */
964    _mesa_initialize_dispatch_tables(mesaCtx);
965    _mesa_initialize_vbo_vtxfmt(mesaCtx);
966 
967    return c;
968 }
969 
970 
971 
972 PUBLIC
XMesaDestroyContext(XMesaContext c)973 void XMesaDestroyContext( XMesaContext c )
974 {
975    struct gl_context *mesaCtx = &c->mesa;
976 
977    _mesa_meta_free( mesaCtx );
978 
979    _swsetup_DestroyContext( mesaCtx );
980    _swrast_DestroyContext( mesaCtx );
981    _tnl_DestroyContext( mesaCtx );
982    _vbo_DestroyContext( mesaCtx );
983    _mesa_free_context_data(mesaCtx, true);
984    free( c );
985 }
986 
987 
988 
989 /**
990  * Private function for creating an XMesaBuffer which corresponds to an
991  * X window or pixmap.
992  * \param v  the window's XMesaVisual
993  * \param w  the window we're wrapping
994  * \return  new XMesaBuffer or NULL if error
995  */
996 PUBLIC XMesaBuffer
XMesaCreateWindowBuffer(XMesaVisual v,XMesaWindow w)997 XMesaCreateWindowBuffer(XMesaVisual v, XMesaWindow w)
998 {
999    XWindowAttributes attr;
1000    XMesaBuffer b;
1001    XMesaColormap cmap;
1002    int depth;
1003 
1004    assert(v);
1005    assert(w);
1006 
1007    /* Check that window depth matches visual depth */
1008    XGetWindowAttributes( v->display, w, &attr );
1009    depth = attr.depth;
1010    if (GET_VISUAL_DEPTH(v) != depth) {
1011       _mesa_warning(NULL, "XMesaCreateWindowBuffer: depth mismatch between visual (%d) and window (%d)!\n",
1012                     GET_VISUAL_DEPTH(v), depth);
1013       return NULL;
1014    }
1015 
1016    /* Find colormap */
1017    if (attr.colormap) {
1018       cmap = attr.colormap;
1019    }
1020    else {
1021       _mesa_warning(NULL, "Window %u has no colormap!\n", (unsigned int) w);
1022       /* this is weird, a window w/out a colormap!? */
1023       /* OK, let's just allocate a new one and hope for the best */
1024       cmap = XCreateColormap(v->display, w, attr.visual, AllocNone);
1025    }
1026 
1027    b = create_xmesa_buffer((XMesaDrawable) w, WINDOW, v, cmap);
1028    if (!b)
1029       return NULL;
1030 
1031    if (!initialize_visual_and_buffer( v, b, (XMesaDrawable) w, cmap )) {
1032       xmesa_free_buffer(b);
1033       return NULL;
1034    }
1035 
1036    return b;
1037 }
1038 
1039 
1040 
1041 /**
1042  * Create a new XMesaBuffer from an X pixmap.
1043  *
1044  * \param v    the XMesaVisual
1045  * \param p    the pixmap
1046  * \param cmap the colormap, may be 0 if using a \c GLX_TRUE_COLOR or
1047  *             \c GLX_DIRECT_COLOR visual for the pixmap
1048  * \returns new XMesaBuffer or NULL if error
1049  */
1050 PUBLIC XMesaBuffer
XMesaCreatePixmapBuffer(XMesaVisual v,XMesaPixmap p,XMesaColormap cmap)1051 XMesaCreatePixmapBuffer(XMesaVisual v, XMesaPixmap p, XMesaColormap cmap)
1052 {
1053    XMesaBuffer b;
1054 
1055    assert(v);
1056 
1057    b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1058    if (!b)
1059       return NULL;
1060 
1061    if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1062       xmesa_free_buffer(b);
1063       return NULL;
1064    }
1065 
1066    return b;
1067 }
1068 
1069 
1070 /**
1071  * For GLX_EXT_texture_from_pixmap
1072  */
1073 XMesaBuffer
XMesaCreatePixmapTextureBuffer(XMesaVisual v,XMesaPixmap p,XMesaColormap cmap,int format,int target,int mipmap)1074 XMesaCreatePixmapTextureBuffer(XMesaVisual v, XMesaPixmap p,
1075                                XMesaColormap cmap,
1076                                int format, int target, int mipmap)
1077 {
1078    GET_CURRENT_CONTEXT(ctx);
1079    XMesaBuffer b;
1080    GLuint width, height;
1081 
1082    assert(v);
1083 
1084    b = create_xmesa_buffer((XMesaDrawable) p, PIXMAP, v, cmap);
1085    if (!b)
1086       return NULL;
1087 
1088    /* get pixmap size, update framebuffer/renderbuffer dims */
1089    xmesa_get_window_size(v->display, b, &width, &height);
1090    _mesa_resize_framebuffer(NULL, &(b->mesa_buffer), width, height);
1091 
1092    if (target == 0) {
1093       /* examine dims */
1094       if (ctx->Extensions.ARB_texture_non_power_of_two) {
1095          target = GLX_TEXTURE_2D_EXT;
1096       }
1097       else if (   util_bitcount(width)  == 1
1098                && util_bitcount(height) == 1) {
1099          /* power of two size */
1100          if (height == 1) {
1101             target = GLX_TEXTURE_1D_EXT;
1102          }
1103          else {
1104             target = GLX_TEXTURE_2D_EXT;
1105          }
1106       }
1107       else if (ctx->Extensions.NV_texture_rectangle) {
1108          target = GLX_TEXTURE_RECTANGLE_EXT;
1109       }
1110       else {
1111          /* non power of two textures not supported */
1112          XMesaDestroyBuffer(b);
1113          return 0;
1114       }
1115    }
1116 
1117    b->TextureTarget = target;
1118    b->TextureFormat = format;
1119    b->TextureMipmap = mipmap;
1120 
1121    if (!initialize_visual_and_buffer(v, b, (XMesaDrawable) p, cmap)) {
1122       xmesa_free_buffer(b);
1123       return NULL;
1124    }
1125 
1126    return b;
1127 }
1128 
1129 
1130 
1131 XMesaBuffer
XMesaCreatePBuffer(XMesaVisual v,XMesaColormap cmap,unsigned int width,unsigned int height)1132 XMesaCreatePBuffer(XMesaVisual v, XMesaColormap cmap,
1133                    unsigned int width, unsigned int height)
1134 {
1135    XMesaWindow root;
1136    XMesaDrawable drawable;  /* X Pixmap Drawable */
1137    XMesaBuffer b;
1138 
1139    /* allocate pixmap for front buffer */
1140    root = RootWindow( v->display, v->visinfo->screen );
1141    drawable = XCreatePixmap(v->display, root, width, height,
1142                             v->visinfo->depth);
1143    if (!drawable)
1144       return NULL;
1145 
1146    b = create_xmesa_buffer(drawable, PBUFFER, v, cmap);
1147    if (!b)
1148       return NULL;
1149 
1150    if (!initialize_visual_and_buffer(v, b, drawable, cmap)) {
1151       xmesa_free_buffer(b);
1152       return NULL;
1153    }
1154 
1155    return b;
1156 }
1157 
1158 
1159 
1160 /*
1161  * Deallocate an XMesaBuffer structure and all related info.
1162  */
1163 PUBLIC void
XMesaDestroyBuffer(XMesaBuffer b)1164 XMesaDestroyBuffer(XMesaBuffer b)
1165 {
1166    xmesa_free_buffer(b);
1167 }
1168 
1169 
1170 /**
1171  * Query the current window size and update the corresponding struct gl_framebuffer
1172  * and all attached renderbuffers.
1173  * Called when:
1174  *  1. the first time a buffer is bound to a context.
1175  *  2. from glViewport to poll for window size changes
1176  *  3. from the XMesaResizeBuffers() API function.
1177  * Note: it's possible (and legal) for xmctx to be NULL.  That can happen
1178  * when resizing a buffer when no rendering context is bound.
1179  */
1180 void
xmesa_check_and_update_buffer_size(XMesaContext xmctx,XMesaBuffer drawBuffer)1181 xmesa_check_and_update_buffer_size(XMesaContext xmctx, XMesaBuffer drawBuffer)
1182 {
1183    GLuint width, height;
1184    xmesa_get_window_size(drawBuffer->display, drawBuffer, &width, &height);
1185    if (drawBuffer->mesa_buffer.Width != width ||
1186        drawBuffer->mesa_buffer.Height != height) {
1187       struct gl_context *ctx = xmctx ? &xmctx->mesa : NULL;
1188       _mesa_resize_framebuffer(ctx, &(drawBuffer->mesa_buffer), width, height);
1189    }
1190 }
1191 
1192 
1193 /*
1194  * Bind buffer b to context c and make c the current rendering context.
1195  */
XMesaMakeCurrent(XMesaContext c,XMesaBuffer b)1196 GLboolean XMesaMakeCurrent( XMesaContext c, XMesaBuffer b )
1197 {
1198    return XMesaMakeCurrent2( c, b, b );
1199 }
1200 
1201 
1202 /*
1203  * Bind buffer b to context c and make c the current rendering context.
1204  */
1205 PUBLIC
XMesaMakeCurrent2(XMesaContext c,XMesaBuffer drawBuffer,XMesaBuffer readBuffer)1206 GLboolean XMesaMakeCurrent2( XMesaContext c, XMesaBuffer drawBuffer,
1207                              XMesaBuffer readBuffer )
1208 {
1209    if (c) {
1210       if (!drawBuffer || !readBuffer)
1211          return GL_FALSE;  /* must specify buffers! */
1212 
1213       if (&(c->mesa) == _mesa_get_current_context()
1214           && c->mesa.DrawBuffer == &drawBuffer->mesa_buffer
1215           && c->mesa.ReadBuffer == &readBuffer->mesa_buffer
1216           && XMESA_BUFFER(c->mesa.DrawBuffer)->wasCurrent) {
1217          /* same context and buffer, do nothing */
1218          return GL_TRUE;
1219       }
1220 
1221       c->xm_buffer = drawBuffer;
1222 
1223       xmesa_check_and_update_buffer_size(c, drawBuffer);
1224       if (readBuffer != drawBuffer)
1225          xmesa_check_and_update_buffer_size(c, readBuffer);
1226 
1227       _mesa_make_current(&(c->mesa),
1228                          &drawBuffer->mesa_buffer,
1229                          &readBuffer->mesa_buffer);
1230 
1231       /*
1232        * Must recompute and set these pixel values because colormap
1233        * can be different for different windows.
1234        */
1235       c->clearpixel = xmesa_color_to_pixel( &c->mesa,
1236 					    c->clearcolor[0],
1237 					    c->clearcolor[1],
1238 					    c->clearcolor[2],
1239 					    c->clearcolor[3],
1240 					    c->xm_visual->undithered_pf);
1241       XMesaSetForeground(c->display, drawBuffer->cleargc, c->clearpixel);
1242 
1243       /* Solution to Stephane Rehel's problem with glXReleaseBuffersMESA(): */
1244       drawBuffer->wasCurrent = GL_TRUE;
1245    }
1246    else {
1247       /* Detach */
1248       _mesa_make_current( NULL, NULL, NULL );
1249    }
1250    return GL_TRUE;
1251 }
1252 
1253 
1254 /*
1255  * Unbind the context c from its buffer.
1256  */
XMesaUnbindContext(XMesaContext c)1257 GLboolean XMesaUnbindContext( XMesaContext c )
1258 {
1259    /* A no-op for XFree86 integration purposes */
1260    return GL_TRUE;
1261 }
1262 
1263 
XMesaGetCurrentContext(void)1264 XMesaContext XMesaGetCurrentContext( void )
1265 {
1266    GET_CURRENT_CONTEXT(ctx);
1267    if (ctx) {
1268       XMesaContext xmesa = XMESA_CONTEXT(ctx);
1269       return xmesa;
1270    }
1271    else {
1272       return 0;
1273    }
1274 }
1275 
1276 
XMesaGetCurrentBuffer(void)1277 XMesaBuffer XMesaGetCurrentBuffer( void )
1278 {
1279    GET_CURRENT_CONTEXT(ctx);
1280    if (ctx) {
1281       XMesaBuffer xmbuf = XMESA_BUFFER(ctx->DrawBuffer);
1282       return xmbuf;
1283    }
1284    else {
1285       return 0;
1286    }
1287 }
1288 
1289 
1290 /* New in Mesa 3.1 */
XMesaGetCurrentReadBuffer(void)1291 XMesaBuffer XMesaGetCurrentReadBuffer( void )
1292 {
1293    GET_CURRENT_CONTEXT(ctx);
1294    if (ctx) {
1295       return XMESA_BUFFER(ctx->ReadBuffer);
1296    }
1297    else {
1298       return 0;
1299    }
1300 }
1301 
1302 
XMesaGetCurrentDisplay(void)1303 Display *XMesaGetCurrentDisplay(void)
1304 {
1305    GET_CURRENT_CONTEXT(ctx);
1306    XMesaContext xmctx = XMESA_CONTEXT(ctx);
1307    return xmctx ? xmctx->display : NULL;
1308 }
1309 
1310 
1311 
1312 /*
1313  * Copy the back buffer to the front buffer.  If there's no back buffer
1314  * this is a no-op.
1315  */
1316 PUBLIC
XMesaSwapBuffers(XMesaBuffer b)1317 void XMesaSwapBuffers( XMesaBuffer b )
1318 {
1319    GET_CURRENT_CONTEXT(ctx);
1320 
1321    if (!b->backxrb) {
1322       /* single buffered */
1323       return;
1324    }
1325 
1326    /* If we're swapping the buffer associated with the current context
1327     * we have to flush any pending rendering commands first.
1328     */
1329    if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1330       _mesa_notifySwapBuffers(ctx);
1331 
1332    if (b->db_mode) {
1333       if (b->backxrb->ximage) {
1334 	 /* Copy Ximage (back buf) from client memory to server window */
1335 #if defined(USE_XSHM)
1336 	 if (b->shm) {
1337             /*mtx_lock(&_xmesa_lock);*/
1338 	    XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1339 			  b->swapgc,
1340 			  b->backxrb->ximage, 0, 0,
1341 			  0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1342                           False );
1343             /*mtx_unlock(&_xmesa_lock);*/
1344 	 }
1345 	 else
1346 #endif
1347          {
1348             /*mtx_lock(&_xmesa_lock);*/
1349             XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1350 			   b->swapgc,
1351 			   b->backxrb->ximage, 0, 0,
1352 			   0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height );
1353             /*mtx_unlock(&_xmesa_lock);*/
1354          }
1355       }
1356       else if (b->backxrb->pixmap) {
1357 	 /* Copy pixmap (back buf) to window (front buf) on server */
1358          /*mtx_lock(&_xmesa_lock);*/
1359 	 XMesaCopyArea( b->xm_visual->display,
1360 			b->backxrb->pixmap,   /* source drawable */
1361 			b->frontxrb->drawable,  /* dest. drawable */
1362 			b->swapgc,
1363 			0, 0, b->mesa_buffer.Width, b->mesa_buffer.Height,
1364 			0, 0                 /* dest region */
1365 		      );
1366          /*mtx_unlock(&_xmesa_lock);*/
1367       }
1368    }
1369    XSync( b->xm_visual->display, False );
1370 }
1371 
1372 
1373 
1374 /*
1375  * Copy sub-region of back buffer to front buffer
1376  */
XMesaCopySubBuffer(XMesaBuffer b,int x,int y,int width,int height)1377 void XMesaCopySubBuffer( XMesaBuffer b, int x, int y, int width, int height )
1378 {
1379    GET_CURRENT_CONTEXT(ctx);
1380 
1381    /* If we're swapping the buffer associated with the current context
1382     * we have to flush any pending rendering commands first.
1383     */
1384    if (ctx && ctx->DrawBuffer == &(b->mesa_buffer))
1385       _mesa_notifySwapBuffers(ctx);
1386 
1387    if (!b->backxrb) {
1388       /* single buffered */
1389       return;
1390    }
1391 
1392    if (b->db_mode) {
1393       int yTop = b->mesa_buffer.Height - y - height;
1394       if (b->backxrb->ximage) {
1395          /* Copy Ximage from host's memory to server's window */
1396 #if defined(USE_XSHM)
1397          if (b->shm) {
1398             /* XXX assuming width and height aren't too large! */
1399             XShmPutImage( b->xm_visual->display, b->frontxrb->drawable,
1400                           b->swapgc,
1401                           b->backxrb->ximage, x, yTop,
1402                           x, yTop, width, height, False );
1403             /* wait for finished event??? */
1404          }
1405          else
1406 #endif
1407          {
1408             /* XXX assuming width and height aren't too large! */
1409             XMesaPutImage( b->xm_visual->display, b->frontxrb->drawable,
1410 			   b->swapgc,
1411 			   b->backxrb->ximage, x, yTop,
1412 			   x, yTop, width, height );
1413          }
1414       }
1415       else {
1416          /* Copy pixmap to window on server */
1417          XMesaCopyArea( b->xm_visual->display,
1418 			b->backxrb->pixmap,           /* source drawable */
1419 			b->frontxrb->drawable,        /* dest. drawable */
1420 			b->swapgc,
1421 			x, yTop, width, height,  /* source region */
1422 			x, yTop                  /* dest region */
1423                       );
1424       }
1425    }
1426 }
1427 
1428 
1429 /*
1430  * Return a pointer to the XMesa backbuffer Pixmap or XImage.  This function
1431  * is a way to get "under the hood" of X/Mesa so one can manipulate the
1432  * back buffer directly.
1433  * Output:  pixmap - pointer to back buffer's Pixmap, or 0
1434  *          ximage - pointer to back buffer's XImage, or NULL
1435  * Return:  GL_TRUE = context is double buffered
1436  *          GL_FALSE = context is single buffered
1437  */
XMesaGetBackBuffer(XMesaBuffer b,XMesaPixmap * pixmap,XMesaImage ** ximage)1438 GLboolean XMesaGetBackBuffer( XMesaBuffer b,
1439                               XMesaPixmap *pixmap,
1440                               XMesaImage **ximage )
1441 {
1442    if (b->db_mode) {
1443       if (pixmap)
1444          *pixmap = b->backxrb->pixmap;
1445       if (ximage)
1446          *ximage = b->backxrb->ximage;
1447       return GL_TRUE;
1448    }
1449    else {
1450       *pixmap = 0;
1451       *ximage = NULL;
1452       return GL_FALSE;
1453    }
1454 }
1455 
1456 
1457 /*
1458  * Return the depth buffer associated with an XMesaBuffer.
1459  * Input:  b - the XMesa buffer handle
1460  * Output:  width, height - size of buffer in pixels
1461  *          bytesPerValue - bytes per depth value (2 or 4)
1462  *          buffer - pointer to depth buffer values
1463  * Return:  GL_TRUE or GL_FALSE to indicate success or failure.
1464  */
XMesaGetDepthBuffer(XMesaBuffer b,GLint * width,GLint * height,GLint * bytesPerValue,void ** buffer)1465 GLboolean XMesaGetDepthBuffer( XMesaBuffer b, GLint *width, GLint *height,
1466                                GLint *bytesPerValue, void **buffer )
1467 {
1468    struct gl_renderbuffer *rb
1469       = b->mesa_buffer.Attachment[BUFFER_DEPTH].Renderbuffer;
1470    struct xmesa_renderbuffer *xrb = xmesa_renderbuffer(rb);
1471 
1472    if (!xrb || !xrb->Base.Buffer) {
1473       *width = 0;
1474       *height = 0;
1475       *bytesPerValue = 0;
1476       *buffer = 0;
1477       return GL_FALSE;
1478    }
1479    else {
1480       *width = b->mesa_buffer.Width;
1481       *height = b->mesa_buffer.Height;
1482       *bytesPerValue = b->mesa_buffer.Visual.depthBits <= 16
1483          ? sizeof(GLushort) : sizeof(GLuint);
1484       *buffer = (void *) xrb->Base.Buffer;
1485       return GL_TRUE;
1486    }
1487 }
1488 
1489 
XMesaFlush(XMesaContext c)1490 void XMesaFlush( XMesaContext c )
1491 {
1492    if (c && c->xm_visual) {
1493       XSync( c->xm_visual->display, False );
1494    }
1495 }
1496 
1497 
1498 
XMesaGetString(XMesaContext c,int name)1499 const char *XMesaGetString( XMesaContext c, int name )
1500 {
1501    (void) c;
1502    if (name==XMESA_VERSION) {
1503       return "5.0";
1504    }
1505    else if (name==XMESA_EXTENSIONS) {
1506       return "";
1507    }
1508    else {
1509       return NULL;
1510    }
1511 }
1512 
1513 
1514 
XMesaFindBuffer(XMesaDisplay * dpy,XMesaDrawable d)1515 XMesaBuffer XMesaFindBuffer( XMesaDisplay *dpy, XMesaDrawable d )
1516 {
1517    XMesaBuffer b;
1518    for (b=XMesaBufferList; b; b=b->Next) {
1519       if (b->frontxrb->drawable == d && b->display == dpy) {
1520          return b;
1521       }
1522    }
1523    return NULL;
1524 }
1525 
1526 
1527 /**
1528  * Free/destroy all XMesaBuffers associated with given display.
1529  */
xmesa_destroy_buffers_on_display(XMesaDisplay * dpy)1530 void xmesa_destroy_buffers_on_display(XMesaDisplay *dpy)
1531 {
1532    XMesaBuffer b, next;
1533    for (b = XMesaBufferList; b; b = next) {
1534       next = b->Next;
1535       if (b->display == dpy) {
1536          xmesa_free_buffer(b);
1537       }
1538    }
1539 }
1540 
1541 
1542 /*
1543  * Look for XMesaBuffers whose X window has been destroyed.
1544  * Deallocate any such XMesaBuffers.
1545  */
XMesaGarbageCollect(XMesaDisplay * dpy)1546 void XMesaGarbageCollect( XMesaDisplay* dpy )
1547 {
1548    XMesaBuffer b, next;
1549    for (b=XMesaBufferList; b; b=next) {
1550       next = b->Next;
1551       if (b->display && b->display == dpy && b->frontxrb->drawable && b->type == WINDOW) {
1552          XSync(b->display, False);
1553          if (!window_exists( b->display, b->frontxrb->drawable )) {
1554             /* found a dead window, free the ancillary info */
1555             XMesaDestroyBuffer( b );
1556          }
1557       }
1558    }
1559 }
1560 
1561 
XMesaDitherColor(XMesaContext xmesa,GLint x,GLint y,GLfloat red,GLfloat green,GLfloat blue,GLfloat alpha)1562 unsigned long XMesaDitherColor( XMesaContext xmesa, GLint x, GLint y,
1563                                 GLfloat red, GLfloat green,
1564                                 GLfloat blue, GLfloat alpha )
1565 {
1566    GLint r = (GLint) (red   * 255.0F);
1567    GLint g = (GLint) (green * 255.0F);
1568    GLint b = (GLint) (blue  * 255.0F);
1569    GLint a = (GLint) (alpha * 255.0F);
1570 
1571    switch (xmesa->pixelformat) {
1572       case PF_Truecolor:
1573          {
1574             unsigned long p;
1575             PACK_TRUECOLOR( p, r, g, b );
1576             return p;
1577          }
1578       case PF_8A8B8G8R:
1579          return PACK_8A8B8G8R( r, g, b, a );
1580       case PF_8A8R8G8B:
1581          return PACK_8A8R8G8B( r, g, b, a );
1582       case PF_8R8G8B:
1583          return PACK_8R8G8B( r, g, b );
1584       case PF_5R6G5B:
1585          return PACK_5R6G5B( r, g, b );
1586       case PF_Dither_5R6G5B:
1587          /* fall through */
1588       case PF_Dither_True:
1589          {
1590             unsigned long p;
1591             PACK_TRUEDITHER(p, x, y, r, g, b);
1592             return p;
1593          }
1594       default:
1595          _mesa_problem(NULL, "Bad pixel format in XMesaDitherColor");
1596    }
1597    return 0;
1598 }
1599 
1600 
1601 /*
1602  * This is typically called when the window size changes and we need
1603  * to reallocate the buffer's back/depth/stencil/accum buffers.
1604  */
1605 PUBLIC void
XMesaResizeBuffers(XMesaBuffer b)1606 XMesaResizeBuffers( XMesaBuffer b )
1607 {
1608    GET_CURRENT_CONTEXT(ctx);
1609    XMesaContext xmctx = XMESA_CONTEXT(ctx);
1610    if (!xmctx)
1611       return;
1612    xmesa_check_and_update_buffer_size(xmctx, b);
1613 }
1614 
1615 
1616 static GLint
xbuffer_to_renderbuffer(int buffer)1617 xbuffer_to_renderbuffer(int buffer)
1618 {
1619    assert(MAX_AUX_BUFFERS <= 4);
1620 
1621    switch (buffer) {
1622    case GLX_FRONT_LEFT_EXT:
1623       return BUFFER_FRONT_LEFT;
1624    case GLX_FRONT_RIGHT_EXT:
1625       return BUFFER_FRONT_RIGHT;
1626    case GLX_BACK_LEFT_EXT:
1627       return BUFFER_BACK_LEFT;
1628    case GLX_BACK_RIGHT_EXT:
1629       return BUFFER_BACK_RIGHT;
1630    case GLX_AUX0_EXT:
1631       return BUFFER_AUX0;
1632    case GLX_AUX1_EXT:
1633    case GLX_AUX2_EXT:
1634    case GLX_AUX3_EXT:
1635    case GLX_AUX4_EXT:
1636    case GLX_AUX5_EXT:
1637    case GLX_AUX6_EXT:
1638    case GLX_AUX7_EXT:
1639    case GLX_AUX8_EXT:
1640    case GLX_AUX9_EXT:
1641    default:
1642       /* BadValue error */
1643       return -1;
1644    }
1645 }
1646 
1647 
1648 PUBLIC void
XMesaBindTexImage(XMesaDisplay * dpy,XMesaBuffer drawable,int buffer,const int * attrib_list)1649 XMesaBindTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer,
1650                   const int *attrib_list)
1651 {
1652 #if 0
1653    GET_CURRENT_CONTEXT(ctx);
1654    const GLuint unit = ctx->Texture.CurrentUnit;
1655    struct gl_texture_unit *texUnit = &ctx->Texture.Unit[unit];
1656    struct gl_texture_object *texObj;
1657 #endif
1658    struct gl_renderbuffer *rb;
1659    struct xmesa_renderbuffer *xrb;
1660    GLint b;
1661    XMesaImage *img = NULL;
1662    GLboolean freeImg = GL_FALSE;
1663 
1664    b = xbuffer_to_renderbuffer(buffer);
1665    if (b < 0)
1666       return;
1667 
1668    if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_NONE_EXT)
1669       return; /* BadMatch error */
1670 
1671    rb = drawable->mesa_buffer.Attachment[b].Renderbuffer;
1672    if (!rb) {
1673       /* invalid buffer */
1674       return;
1675    }
1676    xrb = xmesa_renderbuffer(rb);
1677 
1678 #if 0
1679    switch (drawable->TextureTarget) {
1680    case GLX_TEXTURE_1D_EXT:
1681       texObj = texUnit->CurrentTex[TEXTURE_1D_INDEX];
1682       break;
1683    case GLX_TEXTURE_2D_EXT:
1684       texObj = texUnit->CurrentTex[TEXTURE_2D_INDEX];
1685       break;
1686    case GLX_TEXTURE_RECTANGLE_EXT:
1687       texObj = texUnit->CurrentTex[TEXTURE_RECT_INDEX];
1688       break;
1689    default:
1690       return; /* BadMatch error */
1691    }
1692 #endif
1693 
1694    /*
1695     * The following is a quick and simple way to implement
1696     * BindTexImage.  The better way is to write some new FetchTexel()
1697     * functions which would extract texels from XImages.  We'd still
1698     * need to use GetImage when texturing from a Pixmap (front buffer)
1699     * but texturing from a back buffer (XImage) would avoid an image
1700     * copy.
1701     */
1702 
1703    /* get XImage */
1704    if (xrb->pixmap) {
1705       img = XMesaGetImage(dpy, xrb->pixmap, 0, 0, rb->Width, rb->Height, ~0L,
1706 			  ZPixmap);
1707       freeImg = GL_TRUE;
1708    }
1709    else if (xrb->ximage) {
1710       img = xrb->ximage;
1711    }
1712 
1713    /* store the XImage as a new texture image */
1714    if (img) {
1715       GLenum format, type, intFormat;
1716       if (img->bits_per_pixel == 32) {
1717          format = GL_BGRA;
1718          type = GL_UNSIGNED_BYTE;
1719          intFormat = GL_RGBA;
1720       }
1721       else if (img->bits_per_pixel == 24) {
1722          format = GL_BGR;
1723          type = GL_UNSIGNED_BYTE;
1724          intFormat = GL_RGB;
1725       }
1726       else if (img->bits_per_pixel == 16) {
1727          format = GL_BGR;
1728          type = GL_UNSIGNED_SHORT_5_6_5;
1729          intFormat = GL_RGB;
1730       }
1731       else {
1732          _mesa_problem(NULL, "Unexpected XImage format in XMesaBindTexImage");
1733          return;
1734       }
1735       if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGBA_EXT) {
1736          intFormat = GL_RGBA;
1737       }
1738       else if (drawable->TextureFormat == GLX_TEXTURE_FORMAT_RGB_EXT) {
1739          intFormat = GL_RGB;
1740       }
1741 
1742       _mesa_TexImage2D(GL_TEXTURE_2D, 0, intFormat, rb->Width, rb->Height, 0,
1743                        format, type, img->data);
1744 
1745       if (freeImg) {
1746 	 XMesaDestroyImage(img);
1747       }
1748    }
1749 }
1750 
1751 
1752 
1753 PUBLIC void
XMesaReleaseTexImage(XMesaDisplay * dpy,XMesaBuffer drawable,int buffer)1754 XMesaReleaseTexImage(XMesaDisplay *dpy, XMesaBuffer drawable, int buffer)
1755 {
1756    const GLint b = xbuffer_to_renderbuffer(buffer);
1757    if (b < 0)
1758       return;
1759 
1760    /* no-op for now */
1761 }
1762 
1763