OSDN Git Service

Merge remote-tracking branch 'origin/master' into pipe-video
[android-x86/external-mesa.git] / src / glx / glxext.c
1 /*
2  * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
3  * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice including the dates of first publication and
13  * either this permission notice or a reference to
14  * http://oss.sgi.com/projects/FreeB/
15  * shall be included 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  * SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
22  * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Except as contained in this notice, the name of Silicon Graphics, Inc.
26  * shall not be used in advertising or otherwise to promote the sale, use or
27  * other dealings in this Software without prior written authorization from
28  * Silicon Graphics, Inc.
29  */
30
31 /**
32  * \file glxext.c
33  * GLX protocol interface boot-strap code.
34  *
35  * Direct rendering support added by Precision Insight, Inc.
36  *
37  * \author Kevin E. Martin <kevin@precisioninsight.com>
38  */
39
40 #include <assert.h>
41 #include "glxclient.h"
42 #include <X11/extensions/Xext.h>
43 #include <X11/extensions/extutil.h>
44 #ifdef GLX_USE_APPLEGL
45 #include "apple_glx.h"
46 #include "apple_visual.h"
47 #endif
48 #include "glxextensions.h"
49
50 #ifdef USE_XCB
51 #include <X11/Xlib-xcb.h>
52 #include <xcb/xcb.h>
53 #include <xcb/glx.h>
54 #endif
55
56
57 #ifdef DEBUG
58 void __glXDumpDrawBuffer(struct glx_context * ctx);
59 #endif
60
61 /*
62 ** You can set this cell to 1 to force the gl drawing stuff to be
63 ** one command per packet
64 */
65 _X_HIDDEN int __glXDebug = 0;
66
67 /* Extension required boiler plate */
68
69 static const char __glXExtensionName[] = GLX_EXTENSION_NAME;
70   static struct glx_display *glx_displays;
71
72 static /* const */ char *error_list[] = {
73    "GLXBadContext",
74    "GLXBadContextState",
75    "GLXBadDrawable",
76    "GLXBadPixmap",
77    "GLXBadContextTag",
78    "GLXBadCurrentWindow",
79    "GLXBadRenderRequest",
80    "GLXBadLargeRequest",
81    "GLXUnsupportedPrivateRequest",
82    "GLXBadFBConfig",
83    "GLXBadPbuffer",
84    "GLXBadCurrentDrawable",
85    "GLXBadWindow",
86 };
87
88 #ifdef GLX_USE_APPLEGL
89 static char *__glXErrorString(Display *dpy, int code, XExtCodes *codes, 
90                               char *buf, int n);
91 #endif
92
93 static
94 XEXT_GENERATE_ERROR_STRING(__glXErrorString, __glXExtensionName,
95                            __GLX_NUMBER_ERRORS, error_list)
96
97 /*
98  * GLX events are a bit funky.  We don't stuff the X event code into
99  * our user exposed (via XNextEvent) structure.  Instead we use the GLX
100  * private event code namespace (and hope it doesn't conflict).  Clients
101  * have to know that bit 15 in the event type field means they're getting
102  * a GLX event, and then handle the various sub-event types there, rather
103  * than simply checking the event code and handling it directly.
104  */
105
106 static Bool
107 __glXWireToEvent(Display *dpy, XEvent *event, xEvent *wire)
108 {
109      struct glx_display *glx_dpy = __glXInitialize(dpy);
110
111    if (glx_dpy == NULL)
112       return False;
113
114    switch ((wire->u.u.type & 0x7f) - glx_dpy->codes->first_event) {
115    case GLX_PbufferClobber:
116    {
117       GLXPbufferClobberEvent *aevent = (GLXPbufferClobberEvent *)event;
118       xGLXPbufferClobberEvent *awire = (xGLXPbufferClobberEvent *)wire;
119       aevent->event_type = awire->type;
120       aevent->serial = awire->sequenceNumber;
121       aevent->event_type = awire->event_type;
122       aevent->draw_type = awire->draw_type;
123       aevent->drawable = awire->drawable;
124       aevent->buffer_mask = awire->buffer_mask;
125       aevent->aux_buffer = awire->aux_buffer;
126       aevent->x = awire->x;
127       aevent->y = awire->y;
128       aevent->width = awire->width;
129       aevent->height = awire->height;
130       aevent->count = awire->count;
131       return True;
132    }
133    case GLX_BufferSwapComplete:
134    {
135       GLXBufferSwapComplete *aevent = (GLXBufferSwapComplete *)event;
136       xGLXBufferSwapComplete2 *awire = (xGLXBufferSwapComplete2 *)wire;
137       struct glx_drawable *glxDraw = GetGLXDrawable(dpy, awire->drawable);
138       aevent->event_type = awire->event_type;
139       aevent->drawable = awire->drawable;
140       aevent->ust = ((CARD64)awire->ust_hi << 32) | awire->ust_lo;
141       aevent->msc = ((CARD64)awire->msc_hi << 32) | awire->msc_lo;
142
143       if (!glxDraw)
144          return False;
145
146       if (awire->sbc < glxDraw->lastEventSbc)
147          glxDraw->eventSbcWrap += 0x100000000;
148       glxDraw->lastEventSbc = awire->sbc;
149       aevent->sbc = awire->sbc + glxDraw->eventSbcWrap;
150       return True;
151    }
152    default:
153       /* client doesn't support server event */
154       break;
155    }
156
157    return False;
158 }
159
160 /* We don't actually support this.  It doesn't make sense for clients to
161  * send each other GLX events.
162  */
163 static Status
164 __glXEventToWire(Display *dpy, XEvent *event, xEvent *wire)
165 {
166      struct glx_display *glx_dpy = __glXInitialize(dpy);
167
168    if (glx_dpy == NULL)
169       return False;
170
171    switch (event->type) {
172    case GLX_DAMAGED:
173       break;
174    case GLX_SAVED:
175       break;
176    case GLX_EXCHANGE_COMPLETE_INTEL:
177       break;
178    case GLX_COPY_COMPLETE_INTEL:
179       break;
180    case GLX_FLIP_COMPLETE_INTEL:
181       break;
182    default:
183       /* client doesn't support server event */
184       break;
185    }
186
187    return Success;
188 }
189
190 /************************************************************************/
191 /*
192 ** Free the per screen configs data as well as the array of
193 ** __glXScreenConfigs.
194 */
195 static void
196 FreeScreenConfigs(struct glx_display * priv)
197 {
198    struct glx_screen *psc;
199    GLint i, screens;
200
201    /* Free screen configuration information */
202    screens = ScreenCount(priv->dpy);
203    for (i = 0; i < screens; i++) {
204       psc = priv->screens[i];
205       glx_screen_cleanup(psc);
206
207 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
208       if (psc->driScreen) {
209          psc->driScreen->destroyScreen(psc);
210       } else {
211          Xfree(psc);
212       }
213 #else
214       Xfree(psc);
215 #endif
216    }
217    XFree((char *) priv->screens);
218    priv->screens = NULL;
219 }
220
221 static void
222 glx_display_free(struct glx_display *priv)
223 {
224    struct glx_context *gc;
225
226    gc = __glXGetCurrentContext();
227    if (priv->dpy == gc->currentDpy) {
228       gc->vtable->destroy(gc);
229       __glXSetCurrentContextNull();
230    }
231
232    FreeScreenConfigs(priv);
233    if (priv->serverGLXvendor)
234       Xfree((char *) priv->serverGLXvendor);
235    if (priv->serverGLXversion)
236       Xfree((char *) priv->serverGLXversion);
237
238    __glxHashDestroy(priv->glXDrawHash);
239
240 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
241    __glxHashDestroy(priv->drawHash);
242
243    /* Free the direct rendering per display data */
244    if (priv->driswDisplay)
245       (*priv->driswDisplay->destroyDisplay) (priv->driswDisplay);
246    priv->driswDisplay = NULL;
247
248    if (priv->driDisplay)
249       (*priv->driDisplay->destroyDisplay) (priv->driDisplay);
250    priv->driDisplay = NULL;
251
252    if (priv->dri2Display)
253       (*priv->dri2Display->destroyDisplay) (priv->dri2Display);
254    priv->dri2Display = NULL;
255 #endif
256
257    Xfree((char *) priv);
258 }
259
260 static int
261 __glXCloseDisplay(Display * dpy, XExtCodes * codes)
262 {
263    struct glx_display *priv, **prev, *next;
264
265    _XLockMutex(_Xglobal_lock);
266    prev = &glx_displays;
267    for (priv = glx_displays; priv; prev = &priv->next, priv = priv->next) {
268       if (priv->dpy == dpy) {
269          break;
270       }
271    }
272
273    /* Only remove the display from the list after it's destroyed. The cleanup
274     * code (e.g. driReleaseDrawables()) ends up calling __glXInitialize(),
275     * which would create a new glx_display while we're trying to destroy this
276     * one. */
277    next = priv->next;
278    glx_display_free(priv);
279    *prev = next;
280    _XUnlockMutex(_Xglobal_lock);
281
282    return 1;
283 }
284
285 /*
286 ** Query the version of the GLX extension.  This procedure works even if
287 ** the client extension is not completely set up.
288 */
289 static Bool
290 QueryVersion(Display * dpy, int opcode, int *major, int *minor)
291 {
292 #ifdef USE_XCB
293    xcb_connection_t *c = XGetXCBConnection(dpy);
294    xcb_glx_query_version_reply_t *reply = xcb_glx_query_version_reply(c,
295                                                                       xcb_glx_query_version
296                                                                       (c,
297                                                                        GLX_MAJOR_VERSION,
298                                                                        GLX_MINOR_VERSION),
299                                                                       NULL);
300
301    if (reply->major_version != GLX_MAJOR_VERSION) {
302       free(reply);
303       return GL_FALSE;
304    }
305    *major = reply->major_version;
306    *minor = min(reply->minor_version, GLX_MINOR_VERSION);
307    free(reply);
308    return GL_TRUE;
309 #else
310    xGLXQueryVersionReq *req;
311    xGLXQueryVersionReply reply;
312
313    /* Send the glXQueryVersion request */
314    LockDisplay(dpy);
315    GetReq(GLXQueryVersion, req);
316    req->reqType = opcode;
317    req->glxCode = X_GLXQueryVersion;
318    req->majorVersion = GLX_MAJOR_VERSION;
319    req->minorVersion = GLX_MINOR_VERSION;
320    _XReply(dpy, (xReply *) & reply, 0, False);
321    UnlockDisplay(dpy);
322    SyncHandle();
323
324    if (reply.majorVersion != GLX_MAJOR_VERSION) {
325       /*
326        ** The server does not support the same major release as this
327        ** client.
328        */
329       return GL_FALSE;
330    }
331    *major = reply.majorVersion;
332    *minor = min(reply.minorVersion, GLX_MINOR_VERSION);
333    return GL_TRUE;
334 #endif /* USE_XCB */
335 }
336
337 /* 
338  * We don't want to enable this GLX_OML_swap_method in glxext.h, 
339  * because we can't support it.  The X server writes it out though,
340  * so we should handle it somehow, to avoid false warnings.
341  */
342 enum {
343     IGNORE_GLX_SWAP_METHOD_OML = 0x8060
344 };
345
346
347 static GLint
348 convert_from_x_visual_type(int visualType)
349 {
350    static const int glx_visual_types[] = {
351       GLX_STATIC_GRAY, GLX_GRAY_SCALE,
352       GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
353       GLX_TRUE_COLOR, GLX_DIRECT_COLOR
354    };
355
356    if (visualType < ARRAY_SIZE(glx_visual_types))
357       return glx_visual_types[visualType];
358
359    return GLX_NONE;
360 }
361
362 /*
363  * getVisualConfigs uses the !tagged_only path.
364  * getFBConfigs uses the tagged_only path.
365  */
366 _X_HIDDEN void
367 __glXInitializeVisualConfigFromTags(struct glx_config * config, int count,
368                                     const INT32 * bp, Bool tagged_only,
369                                     Bool fbconfig_style_tags)
370 {
371    int i;
372
373    if (!tagged_only) {
374       /* Copy in the first set of properties */
375       config->visualID = *bp++;
376
377       config->visualType = convert_from_x_visual_type(*bp++);
378
379       config->rgbMode = *bp++;
380
381       config->redBits = *bp++;
382       config->greenBits = *bp++;
383       config->blueBits = *bp++;
384       config->alphaBits = *bp++;
385       config->accumRedBits = *bp++;
386       config->accumGreenBits = *bp++;
387       config->accumBlueBits = *bp++;
388       config->accumAlphaBits = *bp++;
389
390       config->doubleBufferMode = *bp++;
391       config->stereoMode = *bp++;
392
393       config->rgbBits = *bp++;
394       config->depthBits = *bp++;
395       config->stencilBits = *bp++;
396       config->numAuxBuffers = *bp++;
397       config->level = *bp++;
398
399 #ifdef GLX_USE_APPLEGL
400        /* AppleSGLX supports pixmap and pbuffers with all config. */
401        config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
402        /* Unfortunately this can create an ABI compatibility problem. */
403        count -= 18;
404 #else
405       count -= __GLX_MIN_CONFIG_PROPS;
406 #endif
407    }
408
409    /*
410     ** Additional properties may be in a list at the end
411     ** of the reply.  They are in pairs of property type
412     ** and property value.
413     */
414
415 #define FETCH_OR_SET(tag) \
416     config-> tag = ( fbconfig_style_tags ) ? *bp++ : 1
417
418    for (i = 0; i < count; i += 2) {
419       long int tag = *bp++;
420       
421       switch (tag) {
422       case GLX_RGBA:
423          FETCH_OR_SET(rgbMode);
424          break;
425       case GLX_BUFFER_SIZE:
426          config->rgbBits = *bp++;
427          break;
428       case GLX_LEVEL:
429          config->level = *bp++;
430          break;
431       case GLX_DOUBLEBUFFER:
432          FETCH_OR_SET(doubleBufferMode);
433          break;
434       case GLX_STEREO:
435          FETCH_OR_SET(stereoMode);
436          break;
437       case GLX_AUX_BUFFERS:
438          config->numAuxBuffers = *bp++;
439          break;
440       case GLX_RED_SIZE:
441          config->redBits = *bp++;
442          break;
443       case GLX_GREEN_SIZE:
444          config->greenBits = *bp++;
445          break;
446       case GLX_BLUE_SIZE:
447          config->blueBits = *bp++;
448          break;
449       case GLX_ALPHA_SIZE:
450          config->alphaBits = *bp++;
451          break;
452       case GLX_DEPTH_SIZE:
453          config->depthBits = *bp++;
454          break;
455       case GLX_STENCIL_SIZE:
456          config->stencilBits = *bp++;
457          break;
458       case GLX_ACCUM_RED_SIZE:
459          config->accumRedBits = *bp++;
460          break;
461       case GLX_ACCUM_GREEN_SIZE:
462          config->accumGreenBits = *bp++;
463          break;
464       case GLX_ACCUM_BLUE_SIZE:
465          config->accumBlueBits = *bp++;
466          break;
467       case GLX_ACCUM_ALPHA_SIZE:
468          config->accumAlphaBits = *bp++;
469          break;
470       case GLX_VISUAL_CAVEAT_EXT:
471          config->visualRating = *bp++;
472          break;
473       case GLX_X_VISUAL_TYPE:
474          config->visualType = *bp++;
475          break;
476       case GLX_TRANSPARENT_TYPE:
477          config->transparentPixel = *bp++;
478          break;
479       case GLX_TRANSPARENT_INDEX_VALUE:
480          config->transparentIndex = *bp++;
481          break;
482       case GLX_TRANSPARENT_RED_VALUE:
483          config->transparentRed = *bp++;
484          break;
485       case GLX_TRANSPARENT_GREEN_VALUE:
486          config->transparentGreen = *bp++;
487          break;
488       case GLX_TRANSPARENT_BLUE_VALUE:
489          config->transparentBlue = *bp++;
490          break;
491       case GLX_TRANSPARENT_ALPHA_VALUE:
492          config->transparentAlpha = *bp++;
493          break;
494       case GLX_VISUAL_ID:
495          config->visualID = *bp++;
496          break;
497       case GLX_DRAWABLE_TYPE:
498          config->drawableType = *bp++;
499 #ifdef GLX_USE_APPLEGL
500          /* AppleSGLX supports pixmap and pbuffers with all config. */
501          config->drawableType |= GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;              
502 #endif
503          break;
504       case GLX_RENDER_TYPE:
505          config->renderType = *bp++;
506          break;
507       case GLX_X_RENDERABLE:
508          config->xRenderable = *bp++;
509          break;
510       case GLX_FBCONFIG_ID:
511          config->fbconfigID = *bp++;
512          break;
513       case GLX_MAX_PBUFFER_WIDTH:
514          config->maxPbufferWidth = *bp++;
515          break;
516       case GLX_MAX_PBUFFER_HEIGHT:
517          config->maxPbufferHeight = *bp++;
518          break;
519       case GLX_MAX_PBUFFER_PIXELS:
520          config->maxPbufferPixels = *bp++;
521          break;
522 #ifndef GLX_USE_APPLEGL
523       case GLX_OPTIMAL_PBUFFER_WIDTH_SGIX:
524          config->optimalPbufferWidth = *bp++;
525          break;
526       case GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX:
527          config->optimalPbufferHeight = *bp++;
528          break;
529       case GLX_VISUAL_SELECT_GROUP_SGIX:
530          config->visualSelectGroup = *bp++;
531          break;
532       case GLX_SWAP_METHOD_OML:
533          config->swapMethod = *bp++;
534          break;
535 #endif
536       case GLX_SAMPLE_BUFFERS_SGIS:
537          config->sampleBuffers = *bp++;
538          break;
539       case GLX_SAMPLES_SGIS:
540          config->samples = *bp++;
541          break;
542 #ifdef GLX_USE_APPLEGL
543       case IGNORE_GLX_SWAP_METHOD_OML:
544          /* We ignore this tag.  See the comment above this function. */
545          ++bp;
546          break;
547 #else
548       case GLX_BIND_TO_TEXTURE_RGB_EXT:
549          config->bindToTextureRgb = *bp++;
550          break;
551       case GLX_BIND_TO_TEXTURE_RGBA_EXT:
552          config->bindToTextureRgba = *bp++;
553          break;
554       case GLX_BIND_TO_MIPMAP_TEXTURE_EXT:
555          config->bindToMipmapTexture = *bp++;
556          break;
557       case GLX_BIND_TO_TEXTURE_TARGETS_EXT:
558          config->bindToTextureTargets = *bp++;
559          break;
560       case GLX_Y_INVERTED_EXT:
561          config->yInverted = *bp++;
562          break;
563 #endif
564       case GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT:
565          config->sRGBCapable = *bp++;
566          break;
567
568       case GLX_USE_GL:
569          if (fbconfig_style_tags)
570             bp++;
571          break;
572       case None:
573          i = count;
574          break;
575       default:
576          if(getenv("LIBGL_DIAGNOSTIC")) {
577              long int tagvalue = *bp++;
578              fprintf(stderr, "WARNING: unknown GLX tag from server: "
579                      "tag 0x%lx value 0x%lx\n", tag, tagvalue);
580          } else {
581              /* Ignore the unrecognized tag's value */
582              bp++;
583          }
584          break;
585       }
586    }
587
588    config->renderType =
589       (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
590 }
591
592 static struct glx_config *
593 createConfigsFromProperties(Display * dpy, int nvisuals, int nprops,
594                             int screen, GLboolean tagged_only)
595 {
596    INT32 buf[__GLX_TOTAL_CONFIG], *props;
597    unsigned prop_size;
598    struct glx_config *modes, *m;
599    int i;
600
601    if (nprops == 0)
602       return NULL;
603
604    /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for FBconfigs? */
605
606    /* Check number of properties */
607    if (nprops < __GLX_MIN_CONFIG_PROPS || nprops > __GLX_MAX_CONFIG_PROPS)
608       return NULL;
609
610    /* Allocate memory for our config structure */
611    modes = glx_config_create_list(nvisuals);
612    if (!modes)
613       return NULL;
614
615    prop_size = nprops * __GLX_SIZE_INT32;
616    if (prop_size <= sizeof(buf))
617       props = buf;
618    else
619       props = Xmalloc(prop_size);
620
621    /* Read each config structure and convert it into our format */
622    m = modes;
623    for (i = 0; i < nvisuals; i++) {
624       _XRead(dpy, (char *) props, prop_size);
625 #ifdef GLX_USE_APPLEGL
626        /* Older X servers don't send this so we default it here. */
627       m->drawableType = GLX_WINDOW_BIT;
628 #else
629       /* 
630        * The XQuartz 2.3.2.1 X server doesn't set this properly, so
631        * set the proper bits here.
632        * AppleSGLX supports windows, pixmaps, and pbuffers with all config.
633        */
634       m->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
635 #endif
636        __glXInitializeVisualConfigFromTags(m, nprops, props,
637                                           tagged_only, GL_TRUE);
638       m->screen = screen;
639       m = m->next;
640    }
641
642    if (props != buf)
643       Xfree(props);
644
645    return modes;
646 }
647
648 static GLboolean
649 getVisualConfigs(struct glx_screen *psc,
650                   struct glx_display *priv, int screen)
651 {
652    xGLXGetVisualConfigsReq *req;
653    xGLXGetVisualConfigsReply reply;
654    Display *dpy = priv->dpy;
655
656    LockDisplay(dpy);
657
658    psc->visuals = NULL;
659    GetReq(GLXGetVisualConfigs, req);
660    req->reqType = priv->majorOpcode;
661    req->glxCode = X_GLXGetVisualConfigs;
662    req->screen = screen;
663
664    if (!_XReply(dpy, (xReply *) & reply, 0, False))
665       goto out;
666
667    psc->visuals = createConfigsFromProperties(dpy,
668                                               reply.numVisuals,
669                                               reply.numProps,
670                                               screen, GL_FALSE);
671
672  out:
673    UnlockDisplay(dpy);
674    return psc->visuals != NULL;
675 }
676
677 static GLboolean
678  getFBConfigs(struct glx_screen *psc, struct glx_display *priv, int screen)
679 {
680    xGLXGetFBConfigsReq *fb_req;
681    xGLXGetFBConfigsSGIXReq *sgi_req;
682    xGLXVendorPrivateWithReplyReq *vpreq;
683    xGLXGetFBConfigsReply reply;
684    Display *dpy = priv->dpy;
685
686    psc->serverGLXexts =
687       __glXQueryServerString(dpy, priv->majorOpcode, screen, GLX_EXTENSIONS);
688
689    LockDisplay(dpy);
690
691    psc->configs = NULL;
692    if (atof(priv->serverGLXversion) >= 1.3) {
693       GetReq(GLXGetFBConfigs, fb_req);
694       fb_req->reqType = priv->majorOpcode;
695       fb_req->glxCode = X_GLXGetFBConfigs;
696       fb_req->screen = screen;
697    }
698    else if (strstr(psc->serverGLXexts, "GLX_SGIX_fbconfig") != NULL) {
699       GetReqExtra(GLXVendorPrivateWithReply,
700                   sz_xGLXGetFBConfigsSGIXReq -
701                   sz_xGLXVendorPrivateWithReplyReq, vpreq);
702       sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
703       sgi_req->reqType = priv->majorOpcode;
704       sgi_req->glxCode = X_GLXVendorPrivateWithReply;
705       sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
706       sgi_req->screen = screen;
707    }
708    else
709       goto out;
710
711    if (!_XReply(dpy, (xReply *) & reply, 0, False))
712       goto out;
713
714    psc->configs = createConfigsFromProperties(dpy,
715                                               reply.numFBConfigs,
716                                               reply.numAttribs * 2,
717                                               screen, GL_TRUE);
718
719  out:
720    UnlockDisplay(dpy);
721    return psc->configs != NULL;
722 }
723
724 _X_HIDDEN Bool
725 glx_screen_init(struct glx_screen *psc,
726                  int screen, struct glx_display * priv)
727 {
728    /* Initialize per screen dynamic client GLX extensions */
729    psc->ext_list_first_time = GL_TRUE;
730    psc->scr = screen;
731    psc->dpy = priv->dpy;
732    psc->display = priv;
733
734    getVisualConfigs(psc, priv, screen);
735    getFBConfigs(psc, priv, screen);
736
737    return GL_TRUE;
738 }
739
740 _X_HIDDEN void
741 glx_screen_cleanup(struct glx_screen *psc)
742 {
743    if (psc->configs) {
744       glx_config_destroy_list(psc->configs);
745       if (psc->effectiveGLXexts)
746           Xfree(psc->effectiveGLXexts);
747       psc->configs = NULL;   /* NOTE: just for paranoia */
748    }
749    if (psc->visuals) {
750       glx_config_destroy_list(psc->visuals);
751       psc->visuals = NULL;   /* NOTE: just for paranoia */
752    }
753    Xfree((char *) psc->serverGLXexts);
754 }
755
756 /*
757 ** Allocate the memory for the per screen configs for each screen.
758 ** If that works then fetch the per screen configs data.
759 */
760 static Bool
761 AllocAndFetchScreenConfigs(Display * dpy, struct glx_display * priv)
762 {
763    struct glx_screen *psc;
764    GLint i, screens;
765
766    /*
767     ** First allocate memory for the array of per screen configs.
768     */
769    screens = ScreenCount(dpy);
770    priv->screens = Xmalloc(screens * sizeof *priv->screens);
771    if (!priv->screens)
772       return GL_FALSE;
773
774    priv->serverGLXversion =
775       __glXQueryServerString(dpy, priv->majorOpcode, 0, GLX_VERSION);
776    if (priv->serverGLXversion == NULL) {
777       FreeScreenConfigs(priv);
778       return GL_FALSE;
779    }
780
781    for (i = 0; i < screens; i++, psc++) {
782       psc = NULL;
783 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
784       if (priv->dri2Display)
785          psc = (*priv->dri2Display->createScreen) (i, priv);
786       if (psc == NULL && priv->driDisplay)
787          psc = (*priv->driDisplay->createScreen) (i, priv);
788       if (psc == NULL && priv->driswDisplay)
789          psc = (*priv->driswDisplay->createScreen) (i, priv);
790 #endif
791 #if defined(GLX_USE_APPLEGL)
792       if (psc == NULL)
793          psc = applegl_create_screen(i, priv);
794 #else
795       if (psc == NULL)
796          psc = indirect_create_screen(i, priv);
797 #endif
798       priv->screens[i] = psc;
799    }
800    SyncHandle();
801    return GL_TRUE;
802 }
803
804 /*
805 ** Initialize the client side extension code.
806 */
807  _X_HIDDEN struct glx_display *
808 __glXInitialize(Display * dpy)
809 {
810    struct glx_display *dpyPriv, *d;
811 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
812    Bool glx_direct, glx_accel;
813 #endif
814    int i;
815
816    _XLockMutex(_Xglobal_lock);
817
818    for (dpyPriv = glx_displays; dpyPriv; dpyPriv = dpyPriv->next) {
819       if (dpyPriv->dpy == dpy) {
820          _XUnlockMutex(_Xglobal_lock);
821          return dpyPriv;
822       }
823    }
824
825    /* Drop the lock while we create the display private. */
826    _XUnlockMutex(_Xglobal_lock);
827
828    dpyPriv = Xcalloc(1, sizeof *dpyPriv);
829    if (!dpyPriv)
830       return NULL;
831
832    dpyPriv->codes = XInitExtension(dpy, __glXExtensionName);
833    if (!dpyPriv->codes) {
834       Xfree(dpyPriv);
835       _XUnlockMutex(_Xglobal_lock);
836       return NULL;
837    }
838
839    dpyPriv->dpy = dpy;
840    dpyPriv->majorOpcode = dpyPriv->codes->major_opcode;
841    dpyPriv->serverGLXvendor = 0x0;
842    dpyPriv->serverGLXversion = 0x0;
843
844    /* See if the versions are compatible */
845    if (!QueryVersion(dpy, dpyPriv->majorOpcode,
846                      &dpyPriv->majorVersion, &dpyPriv->minorVersion)) {
847       Xfree(dpyPriv);
848       _XUnlockMutex(_Xglobal_lock);
849       return NULL;
850    }
851
852    for (i = 0; i < __GLX_NUMBER_EVENTS; i++) {
853       XESetWireToEvent(dpy, dpyPriv->codes->first_event + i, __glXWireToEvent);
854       XESetEventToWire(dpy, dpyPriv->codes->first_event + i, __glXEventToWire);
855    }
856
857    XESetCloseDisplay(dpy, dpyPriv->codes->extension, __glXCloseDisplay);
858    XESetErrorString (dpy, dpyPriv->codes->extension,__glXErrorString);
859
860    dpyPriv->glXDrawHash = __glxHashCreate();
861
862 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
863    glx_direct = (getenv("LIBGL_ALWAYS_INDIRECT") == NULL);
864    glx_accel = (getenv("LIBGL_ALWAYS_SOFTWARE") == NULL);
865
866    dpyPriv->drawHash = __glxHashCreate();
867
868    /*
869     ** Initialize the direct rendering per display data and functions.
870     ** Note: This _must_ be done before calling any other DRI routines
871     ** (e.g., those called in AllocAndFetchScreenConfigs).
872     */
873    if (glx_direct && glx_accel) {
874       dpyPriv->dri2Display = dri2CreateDisplay(dpy);
875       dpyPriv->driDisplay = driCreateDisplay(dpy);
876    }
877    if (glx_direct)
878       dpyPriv->driswDisplay = driswCreateDisplay(dpy);
879 #endif
880
881 #ifdef GLX_USE_APPLEGL
882    if (!applegl_create_display(dpyPriv)) {
883       Xfree(dpyPriv);
884       return NULL;
885    }
886 #endif
887    if (!AllocAndFetchScreenConfigs(dpy, dpyPriv)) {
888       Xfree(dpyPriv);
889       return NULL;
890    }
891
892    if (dpyPriv->majorVersion == 1 && dpyPriv->minorVersion >= 1)
893       __glXClientInfo(dpy, dpyPriv->majorOpcode);
894
895    /* Grab the lock again and add the dispay private, unless somebody
896     * beat us to initializing on this display in the meantime. */
897    _XLockMutex(_Xglobal_lock);
898
899    for (d = glx_displays; d; d = d->next) {
900       if (d->dpy == dpy) {
901          _XUnlockMutex(_Xglobal_lock);
902          glx_display_free(dpyPriv);
903          return d;
904       }
905    }
906
907    dpyPriv->next = glx_displays;
908    glx_displays = dpyPriv;
909
910     _XUnlockMutex(_Xglobal_lock);
911
912    return dpyPriv;
913 }
914
915 /*
916 ** Setup for sending a GLX command on dpy.  Make sure the extension is
917 ** initialized.  Try to avoid calling __glXInitialize as its kinda slow.
918 */
919 _X_HIDDEN CARD8
920 __glXSetupForCommand(Display * dpy)
921 {
922     struct glx_context *gc;
923     struct glx_display *priv;
924
925    /* If this thread has a current context, flush its rendering commands */
926    gc = __glXGetCurrentContext();
927    if (gc->currentDpy) {
928       /* Flush rendering buffer of the current context, if any */
929       (void) __glXFlushRenderBuffer(gc, gc->pc);
930
931       if (gc->currentDpy == dpy) {
932          /* Use opcode from gc because its right */
933          return gc->majorOpcode;
934       }
935       else {
936          /*
937           ** Have to get info about argument dpy because it might be to
938           ** a different server
939           */
940       }
941    }
942
943    /* Forced to lookup extension via the slow initialize route */
944    priv = __glXInitialize(dpy);
945    if (!priv) {
946       return 0;
947    }
948    return priv->majorOpcode;
949 }
950
951 /**
952  * Flush the drawing command transport buffer.
953  *
954  * \param ctx  Context whose transport buffer is to be flushed.
955  * \param pc   Pointer to first unused buffer location.
956  *
957  * \todo
958  * Modify this function to use \c ctx->pc instead of the explicit
959  * \c pc parameter.
960  */
961 _X_HIDDEN GLubyte *
962 __glXFlushRenderBuffer(struct glx_context * ctx, GLubyte * pc)
963 {
964    Display *const dpy = ctx->currentDpy;
965 #ifdef USE_XCB
966    xcb_connection_t *c = XGetXCBConnection(dpy);
967 #else
968    xGLXRenderReq *req;
969 #endif /* USE_XCB */
970    const GLint size = pc - ctx->buf;
971
972    if ((dpy != NULL) && (size > 0)) {
973 #ifdef USE_XCB
974       xcb_glx_render(c, ctx->currentContextTag, size,
975                      (const uint8_t *) ctx->buf);
976 #else
977       /* Send the entire buffer as an X request */
978       LockDisplay(dpy);
979       GetReq(GLXRender, req);
980       req->reqType = ctx->majorOpcode;
981       req->glxCode = X_GLXRender;
982       req->contextTag = ctx->currentContextTag;
983       req->length += (size + 3) >> 2;
984       _XSend(dpy, (char *) ctx->buf, size);
985       UnlockDisplay(dpy);
986       SyncHandle();
987 #endif
988    }
989
990    /* Reset pointer and return it */
991    ctx->pc = ctx->buf;
992    return ctx->pc;
993 }
994
995
996 /**
997  * Send a portion of a GLXRenderLarge command to the server.  The advantage of
998  * this function over \c __glXSendLargeCommand is that callers can use the
999  * data buffer in the GLX context and may be able to avoid allocating an
1000  * extra buffer.  The disadvantage is the clients will have to do more
1001  * GLX protocol work (i.e., calculating \c totalRequests, etc.).
1002  *
1003  * \sa __glXSendLargeCommand
1004  *
1005  * \param gc             GLX context
1006  * \param requestNumber  Which part of the whole command is this?  The first
1007  *                       request is 1.
1008  * \param totalRequests  How many requests will there be?
1009  * \param data           Command data.
1010  * \param dataLen        Size, in bytes, of the command data.
1011  */
1012 _X_HIDDEN void
1013 __glXSendLargeChunk(struct glx_context * gc, GLint requestNumber,
1014                     GLint totalRequests, const GLvoid * data, GLint dataLen)
1015 {
1016    Display *dpy = gc->currentDpy;
1017 #ifdef USE_XCB
1018    xcb_connection_t *c = XGetXCBConnection(dpy);
1019    xcb_glx_render_large(c, gc->currentContextTag, requestNumber,
1020                         totalRequests, dataLen, data);
1021 #else
1022    xGLXRenderLargeReq *req;
1023
1024    if (requestNumber == 1) {
1025       LockDisplay(dpy);
1026    }
1027
1028    GetReq(GLXRenderLarge, req);
1029    req->reqType = gc->majorOpcode;
1030    req->glxCode = X_GLXRenderLarge;
1031    req->contextTag = gc->currentContextTag;
1032    req->length += (dataLen + 3) >> 2;
1033    req->requestNumber = requestNumber;
1034    req->requestTotal = totalRequests;
1035    req->dataBytes = dataLen;
1036    Data(dpy, data, dataLen);
1037
1038    if (requestNumber == totalRequests) {
1039       UnlockDisplay(dpy);
1040       SyncHandle();
1041    }
1042 #endif /* USE_XCB */
1043 }
1044
1045
1046 /**
1047  * Send a command that is too large for the GLXRender protocol request.
1048  *
1049  * Send a large command, one that is too large for some reason to
1050  * send using the GLXRender protocol request.  One reason to send
1051  * a large command is to avoid copying the data.
1052  *
1053  * \param ctx        GLX context
1054  * \param header     Header data.
1055  * \param headerLen  Size, in bytes, of the header data.  It is assumed that
1056  *                   the header data will always be small enough to fit in
1057  *                   a single X protocol packet.
1058  * \param data       Command data.
1059  * \param dataLen    Size, in bytes, of the command data.
1060  */
1061 _X_HIDDEN void
1062 __glXSendLargeCommand(struct glx_context * ctx,
1063                       const GLvoid * header, GLint headerLen,
1064                       const GLvoid * data, GLint dataLen)
1065 {
1066    GLint maxSize;
1067    GLint totalRequests, requestNumber;
1068
1069    /*
1070     ** Calculate the maximum amount of data can be stuffed into a single
1071     ** packet.  sz_xGLXRenderReq is added because bufSize is the maximum
1072     ** packet size minus sz_xGLXRenderReq.
1073     */
1074    maxSize = (ctx->bufSize + sz_xGLXRenderReq) - sz_xGLXRenderLargeReq;
1075    totalRequests = 1 + (dataLen / maxSize);
1076    if (dataLen % maxSize)
1077       totalRequests++;
1078
1079    /*
1080     ** Send all of the command, except the large array, as one request.
1081     */
1082    assert(headerLen <= maxSize);
1083    __glXSendLargeChunk(ctx, 1, totalRequests, header, headerLen);
1084
1085    /*
1086     ** Send enough requests until the whole array is sent.
1087     */
1088    for (requestNumber = 2; requestNumber <= (totalRequests - 1);
1089         requestNumber++) {
1090       __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, maxSize);
1091       data = (const GLvoid *) (((const GLubyte *) data) + maxSize);
1092       dataLen -= maxSize;
1093       assert(dataLen > 0);
1094    }
1095
1096    assert(dataLen <= maxSize);
1097    __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, dataLen);
1098 }
1099
1100 /************************************************************************/
1101
1102 #ifdef DEBUG
1103 _X_HIDDEN void
1104 __glXDumpDrawBuffer(struct glx_context * ctx)
1105 {
1106    GLubyte *p = ctx->buf;
1107    GLubyte *end = ctx->pc;
1108    GLushort opcode, length;
1109
1110    while (p < end) {
1111       /* Fetch opcode */
1112       opcode = *((GLushort *) p);
1113       length = *((GLushort *) (p + 2));
1114       printf("%2x: %5d: ", opcode, length);
1115       length -= 4;
1116       p += 4;
1117       while (length > 0) {
1118          printf("%08x ", *((unsigned *) p));
1119          p += 4;
1120          length -= 4;
1121       }
1122       printf("\n");
1123    }
1124 }
1125 #endif