OSDN Git Service

glx: Handle a null reply in QueryVersion.
[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;
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          *prev = priv->next;
270          break;
271       }
272    }
273    _XUnlockMutex(_Xglobal_lock);
274
275    glx_display_free(priv);
276
277    return 1;
278 }
279
280 /*
281 ** Query the version of the GLX extension.  This procedure works even if
282 ** the client extension is not completely set up.
283 */
284 static Bool
285 QueryVersion(Display * dpy, int opcode, int *major, int *minor)
286 {
287 #ifdef USE_XCB
288    xcb_connection_t *c = XGetXCBConnection(dpy);
289    xcb_glx_query_version_reply_t *reply = xcb_glx_query_version_reply(c,
290                                                                       xcb_glx_query_version
291                                                                       (c,
292                                                                        GLX_MAJOR_VERSION,
293                                                                        GLX_MINOR_VERSION),
294                                                                       NULL);
295
296    if (!reply)
297      return GL_FALSE;
298
299    if (reply->major_version != GLX_MAJOR_VERSION) {
300       free(reply);
301       return GL_FALSE;
302    }
303    *major = reply->major_version;
304    *minor = min(reply->minor_version, GLX_MINOR_VERSION);
305    free(reply);
306    return GL_TRUE;
307 #else
308    xGLXQueryVersionReq *req;
309    xGLXQueryVersionReply reply;
310
311    /* Send the glXQueryVersion request */
312    LockDisplay(dpy);
313    GetReq(GLXQueryVersion, req);
314    req->reqType = opcode;
315    req->glxCode = X_GLXQueryVersion;
316    req->majorVersion = GLX_MAJOR_VERSION;
317    req->minorVersion = GLX_MINOR_VERSION;
318    _XReply(dpy, (xReply *) & reply, 0, False);
319    UnlockDisplay(dpy);
320    SyncHandle();
321
322    if (reply.majorVersion != GLX_MAJOR_VERSION) {
323       /*
324        ** The server does not support the same major release as this
325        ** client.
326        */
327       return GL_FALSE;
328    }
329    *major = reply.majorVersion;
330    *minor = min(reply.minorVersion, GLX_MINOR_VERSION);
331    return GL_TRUE;
332 #endif /* USE_XCB */
333 }
334
335 /* 
336  * We don't want to enable this GLX_OML_swap_method in glxext.h, 
337  * because we can't support it.  The X server writes it out though,
338  * so we should handle it somehow, to avoid false warnings.
339  */
340 enum {
341     IGNORE_GLX_SWAP_METHOD_OML = 0x8060
342 };
343
344
345 static GLint
346 convert_from_x_visual_type(int visualType)
347 {
348    static const int glx_visual_types[] = {
349       GLX_STATIC_GRAY, GLX_GRAY_SCALE,
350       GLX_STATIC_COLOR, GLX_PSEUDO_COLOR,
351       GLX_TRUE_COLOR, GLX_DIRECT_COLOR
352    };
353
354    if (visualType < ARRAY_SIZE(glx_visual_types))
355       return glx_visual_types[visualType];
356
357    return GLX_NONE;
358 }
359
360 /*
361  * getVisualConfigs uses the !tagged_only path.
362  * getFBConfigs uses the tagged_only path.
363  */
364 _X_HIDDEN void
365 __glXInitializeVisualConfigFromTags(struct glx_config * config, int count,
366                                     const INT32 * bp, Bool tagged_only,
367                                     Bool fbconfig_style_tags)
368 {
369    int i;
370
371    if (!tagged_only) {
372       /* Copy in the first set of properties */
373       config->visualID = *bp++;
374
375       config->visualType = convert_from_x_visual_type(*bp++);
376
377       config->rgbMode = *bp++;
378
379       config->redBits = *bp++;
380       config->greenBits = *bp++;
381       config->blueBits = *bp++;
382       config->alphaBits = *bp++;
383       config->accumRedBits = *bp++;
384       config->accumGreenBits = *bp++;
385       config->accumBlueBits = *bp++;
386       config->accumAlphaBits = *bp++;
387
388       config->doubleBufferMode = *bp++;
389       config->stereoMode = *bp++;
390
391       config->rgbBits = *bp++;
392       config->depthBits = *bp++;
393       config->stencilBits = *bp++;
394       config->numAuxBuffers = *bp++;
395       config->level = *bp++;
396
397 #ifdef GLX_USE_APPLEGL
398        /* AppleSGLX supports pixmap and pbuffers with all config. */
399        config->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
400        /* Unfortunately this can create an ABI compatibility problem. */
401        count -= 18;
402 #else
403       count -= __GLX_MIN_CONFIG_PROPS;
404 #endif
405    }
406
407    /*
408     ** Additional properties may be in a list at the end
409     ** of the reply.  They are in pairs of property type
410     ** and property value.
411     */
412
413 #define FETCH_OR_SET(tag) \
414     config-> tag = ( fbconfig_style_tags ) ? *bp++ : 1
415
416    for (i = 0; i < count; i += 2) {
417       long int tag = *bp++;
418       
419       switch (tag) {
420       case GLX_RGBA:
421          FETCH_OR_SET(rgbMode);
422          break;
423       case GLX_BUFFER_SIZE:
424          config->rgbBits = *bp++;
425          break;
426       case GLX_LEVEL:
427          config->level = *bp++;
428          break;
429       case GLX_DOUBLEBUFFER:
430          FETCH_OR_SET(doubleBufferMode);
431          break;
432       case GLX_STEREO:
433          FETCH_OR_SET(stereoMode);
434          break;
435       case GLX_AUX_BUFFERS:
436          config->numAuxBuffers = *bp++;
437          break;
438       case GLX_RED_SIZE:
439          config->redBits = *bp++;
440          break;
441       case GLX_GREEN_SIZE:
442          config->greenBits = *bp++;
443          break;
444       case GLX_BLUE_SIZE:
445          config->blueBits = *bp++;
446          break;
447       case GLX_ALPHA_SIZE:
448          config->alphaBits = *bp++;
449          break;
450       case GLX_DEPTH_SIZE:
451          config->depthBits = *bp++;
452          break;
453       case GLX_STENCIL_SIZE:
454          config->stencilBits = *bp++;
455          break;
456       case GLX_ACCUM_RED_SIZE:
457          config->accumRedBits = *bp++;
458          break;
459       case GLX_ACCUM_GREEN_SIZE:
460          config->accumGreenBits = *bp++;
461          break;
462       case GLX_ACCUM_BLUE_SIZE:
463          config->accumBlueBits = *bp++;
464          break;
465       case GLX_ACCUM_ALPHA_SIZE:
466          config->accumAlphaBits = *bp++;
467          break;
468       case GLX_VISUAL_CAVEAT_EXT:
469          config->visualRating = *bp++;
470          break;
471       case GLX_X_VISUAL_TYPE:
472          config->visualType = *bp++;
473          break;
474       case GLX_TRANSPARENT_TYPE:
475          config->transparentPixel = *bp++;
476          break;
477       case GLX_TRANSPARENT_INDEX_VALUE:
478          config->transparentIndex = *bp++;
479          break;
480       case GLX_TRANSPARENT_RED_VALUE:
481          config->transparentRed = *bp++;
482          break;
483       case GLX_TRANSPARENT_GREEN_VALUE:
484          config->transparentGreen = *bp++;
485          break;
486       case GLX_TRANSPARENT_BLUE_VALUE:
487          config->transparentBlue = *bp++;
488          break;
489       case GLX_TRANSPARENT_ALPHA_VALUE:
490          config->transparentAlpha = *bp++;
491          break;
492       case GLX_VISUAL_ID:
493          config->visualID = *bp++;
494          break;
495       case GLX_DRAWABLE_TYPE:
496          config->drawableType = *bp++;
497 #ifdef GLX_USE_APPLEGL
498          /* AppleSGLX supports pixmap and pbuffers with all config. */
499          config->drawableType |= GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;              
500 #endif
501          break;
502       case GLX_RENDER_TYPE:
503          config->renderType = *bp++;
504          break;
505       case GLX_X_RENDERABLE:
506          config->xRenderable = *bp++;
507          break;
508       case GLX_FBCONFIG_ID:
509          config->fbconfigID = *bp++;
510          break;
511       case GLX_MAX_PBUFFER_WIDTH:
512          config->maxPbufferWidth = *bp++;
513          break;
514       case GLX_MAX_PBUFFER_HEIGHT:
515          config->maxPbufferHeight = *bp++;
516          break;
517       case GLX_MAX_PBUFFER_PIXELS:
518          config->maxPbufferPixels = *bp++;
519          break;
520 #ifndef GLX_USE_APPLEGL
521       case GLX_OPTIMAL_PBUFFER_WIDTH_SGIX:
522          config->optimalPbufferWidth = *bp++;
523          break;
524       case GLX_OPTIMAL_PBUFFER_HEIGHT_SGIX:
525          config->optimalPbufferHeight = *bp++;
526          break;
527       case GLX_VISUAL_SELECT_GROUP_SGIX:
528          config->visualSelectGroup = *bp++;
529          break;
530       case GLX_SWAP_METHOD_OML:
531          config->swapMethod = *bp++;
532          break;
533 #endif
534       case GLX_SAMPLE_BUFFERS_SGIS:
535          config->sampleBuffers = *bp++;
536          break;
537       case GLX_SAMPLES_SGIS:
538          config->samples = *bp++;
539          break;
540 #ifdef GLX_USE_APPLEGL
541       case IGNORE_GLX_SWAP_METHOD_OML:
542          /* We ignore this tag.  See the comment above this function. */
543          ++bp;
544          break;
545 #else
546       case GLX_BIND_TO_TEXTURE_RGB_EXT:
547          config->bindToTextureRgb = *bp++;
548          break;
549       case GLX_BIND_TO_TEXTURE_RGBA_EXT:
550          config->bindToTextureRgba = *bp++;
551          break;
552       case GLX_BIND_TO_MIPMAP_TEXTURE_EXT:
553          config->bindToMipmapTexture = *bp++;
554          break;
555       case GLX_BIND_TO_TEXTURE_TARGETS_EXT:
556          config->bindToTextureTargets = *bp++;
557          break;
558       case GLX_Y_INVERTED_EXT:
559          config->yInverted = *bp++;
560          break;
561 #endif
562       case GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT:
563          config->sRGBCapable = *bp++;
564          break;
565
566       case GLX_USE_GL:
567          if (fbconfig_style_tags)
568             bp++;
569          break;
570       case None:
571          i = count;
572          break;
573       default:
574          if(getenv("LIBGL_DIAGNOSTIC")) {
575              long int tagvalue = *bp++;
576              fprintf(stderr, "WARNING: unknown GLX tag from server: "
577                      "tag 0x%lx value 0x%lx\n", tag, tagvalue);
578          } else {
579              /* Ignore the unrecognized tag's value */
580              bp++;
581          }
582          break;
583       }
584    }
585
586    config->renderType =
587       (config->rgbMode) ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT;
588 }
589
590 static struct glx_config *
591 createConfigsFromProperties(Display * dpy, int nvisuals, int nprops,
592                             int screen, GLboolean tagged_only)
593 {
594    INT32 buf[__GLX_TOTAL_CONFIG], *props;
595    unsigned prop_size;
596    struct glx_config *modes, *m;
597    int i;
598
599    if (nprops == 0)
600       return NULL;
601
602    /* FIXME: Is the __GLX_MIN_CONFIG_PROPS test correct for FBconfigs? */
603
604    /* Check number of properties */
605    if (nprops < __GLX_MIN_CONFIG_PROPS || nprops > __GLX_MAX_CONFIG_PROPS)
606       return NULL;
607
608    /* Allocate memory for our config structure */
609    modes = glx_config_create_list(nvisuals);
610    if (!modes)
611       return NULL;
612
613    prop_size = nprops * __GLX_SIZE_INT32;
614    if (prop_size <= sizeof(buf))
615       props = buf;
616    else
617       props = Xmalloc(prop_size);
618
619    /* Read each config structure and convert it into our format */
620    m = modes;
621    for (i = 0; i < nvisuals; i++) {
622       _XRead(dpy, (char *) props, prop_size);
623 #ifdef GLX_USE_APPLEGL
624        /* Older X servers don't send this so we default it here. */
625       m->drawableType = GLX_WINDOW_BIT;
626 #else
627       /* 
628        * The XQuartz 2.3.2.1 X server doesn't set this properly, so
629        * set the proper bits here.
630        * AppleSGLX supports windows, pixmaps, and pbuffers with all config.
631        */
632       m->drawableType = GLX_WINDOW_BIT | GLX_PIXMAP_BIT | GLX_PBUFFER_BIT;
633 #endif
634        __glXInitializeVisualConfigFromTags(m, nprops, props,
635                                           tagged_only, GL_TRUE);
636       m->screen = screen;
637       m = m->next;
638    }
639
640    if (props != buf)
641       Xfree(props);
642
643    return modes;
644 }
645
646 static GLboolean
647 getVisualConfigs(struct glx_screen *psc,
648                   struct glx_display *priv, int screen)
649 {
650    xGLXGetVisualConfigsReq *req;
651    xGLXGetVisualConfigsReply reply;
652    Display *dpy = priv->dpy;
653
654    LockDisplay(dpy);
655
656    psc->visuals = NULL;
657    GetReq(GLXGetVisualConfigs, req);
658    req->reqType = priv->majorOpcode;
659    req->glxCode = X_GLXGetVisualConfigs;
660    req->screen = screen;
661
662    if (!_XReply(dpy, (xReply *) & reply, 0, False))
663       goto out;
664
665    psc->visuals = createConfigsFromProperties(dpy,
666                                               reply.numVisuals,
667                                               reply.numProps,
668                                               screen, GL_FALSE);
669
670  out:
671    UnlockDisplay(dpy);
672    return psc->visuals != NULL;
673 }
674
675 static GLboolean
676  getFBConfigs(struct glx_screen *psc, struct glx_display *priv, int screen)
677 {
678    xGLXGetFBConfigsReq *fb_req;
679    xGLXGetFBConfigsSGIXReq *sgi_req;
680    xGLXVendorPrivateWithReplyReq *vpreq;
681    xGLXGetFBConfigsReply reply;
682    Display *dpy = priv->dpy;
683
684    psc->serverGLXexts =
685       __glXQueryServerString(dpy, priv->majorOpcode, screen, GLX_EXTENSIONS);
686
687    LockDisplay(dpy);
688
689    psc->configs = NULL;
690    if (atof(priv->serverGLXversion) >= 1.3) {
691       GetReq(GLXGetFBConfigs, fb_req);
692       fb_req->reqType = priv->majorOpcode;
693       fb_req->glxCode = X_GLXGetFBConfigs;
694       fb_req->screen = screen;
695    }
696    else if (strstr(psc->serverGLXexts, "GLX_SGIX_fbconfig") != NULL) {
697       GetReqExtra(GLXVendorPrivateWithReply,
698                   sz_xGLXGetFBConfigsSGIXReq -
699                   sz_xGLXVendorPrivateWithReplyReq, vpreq);
700       sgi_req = (xGLXGetFBConfigsSGIXReq *) vpreq;
701       sgi_req->reqType = priv->majorOpcode;
702       sgi_req->glxCode = X_GLXVendorPrivateWithReply;
703       sgi_req->vendorCode = X_GLXvop_GetFBConfigsSGIX;
704       sgi_req->screen = screen;
705    }
706    else
707       goto out;
708
709    if (!_XReply(dpy, (xReply *) & reply, 0, False))
710       goto out;
711
712    psc->configs = createConfigsFromProperties(dpy,
713                                               reply.numFBConfigs,
714                                               reply.numAttribs * 2,
715                                               screen, GL_TRUE);
716
717  out:
718    UnlockDisplay(dpy);
719    return psc->configs != NULL;
720 }
721
722 _X_HIDDEN Bool
723 glx_screen_init(struct glx_screen *psc,
724                  int screen, struct glx_display * priv)
725 {
726    /* Initialize per screen dynamic client GLX extensions */
727    psc->ext_list_first_time = GL_TRUE;
728    psc->scr = screen;
729    psc->dpy = priv->dpy;
730    psc->display = priv;
731
732    getVisualConfigs(psc, priv, screen);
733    getFBConfigs(psc, priv, screen);
734
735    return GL_TRUE;
736 }
737
738 _X_HIDDEN void
739 glx_screen_cleanup(struct glx_screen *psc)
740 {
741    if (psc->configs) {
742       glx_config_destroy_list(psc->configs);
743       if (psc->effectiveGLXexts)
744           Xfree(psc->effectiveGLXexts);
745       psc->configs = NULL;   /* NOTE: just for paranoia */
746    }
747    if (psc->visuals) {
748       glx_config_destroy_list(psc->visuals);
749       psc->visuals = NULL;   /* NOTE: just for paranoia */
750    }
751    Xfree((char *) psc->serverGLXexts);
752 }
753
754 /*
755 ** Allocate the memory for the per screen configs for each screen.
756 ** If that works then fetch the per screen configs data.
757 */
758 static Bool
759 AllocAndFetchScreenConfigs(Display * dpy, struct glx_display * priv)
760 {
761    struct glx_screen *psc;
762    GLint i, screens;
763
764    /*
765     ** First allocate memory for the array of per screen configs.
766     */
767    screens = ScreenCount(dpy);
768    priv->screens = Xmalloc(screens * sizeof *priv->screens);
769    if (!priv->screens)
770       return GL_FALSE;
771
772    priv->serverGLXversion =
773       __glXQueryServerString(dpy, priv->majorOpcode, 0, GLX_VERSION);
774    if (priv->serverGLXversion == NULL) {
775       FreeScreenConfigs(priv);
776       return GL_FALSE;
777    }
778
779    for (i = 0; i < screens; i++, psc++) {
780       psc = NULL;
781 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
782       if (priv->dri2Display)
783          psc = (*priv->dri2Display->createScreen) (i, priv);
784       if (psc == NULL && priv->driDisplay)
785          psc = (*priv->driDisplay->createScreen) (i, priv);
786       if (psc == NULL && priv->driswDisplay)
787          psc = (*priv->driswDisplay->createScreen) (i, priv);
788 #endif
789 #if defined(GLX_USE_APPLEGL)
790       if (psc == NULL)
791          psc = applegl_create_screen(i, priv);
792 #else
793       if (psc == NULL)
794          psc = indirect_create_screen(i, priv);
795 #endif
796       priv->screens[i] = psc;
797    }
798    SyncHandle();
799    return GL_TRUE;
800 }
801
802 /*
803 ** Initialize the client side extension code.
804 */
805  _X_HIDDEN struct glx_display *
806 __glXInitialize(Display * dpy)
807 {
808    struct glx_display *dpyPriv, *d;
809 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
810    Bool glx_direct, glx_accel;
811 #endif
812    int i;
813
814    _XLockMutex(_Xglobal_lock);
815
816    for (dpyPriv = glx_displays; dpyPriv; dpyPriv = dpyPriv->next) {
817       if (dpyPriv->dpy == dpy) {
818          _XUnlockMutex(_Xglobal_lock);
819          return dpyPriv;
820       }
821    }
822
823    /* Drop the lock while we create the display private. */
824    _XUnlockMutex(_Xglobal_lock);
825
826    dpyPriv = Xcalloc(1, sizeof *dpyPriv);
827    if (!dpyPriv)
828       return NULL;
829
830    dpyPriv->codes = XInitExtension(dpy, __glXExtensionName);
831    if (!dpyPriv->codes) {
832       Xfree(dpyPriv);
833       _XUnlockMutex(_Xglobal_lock);
834       return NULL;
835    }
836
837    dpyPriv->dpy = dpy;
838    dpyPriv->majorOpcode = dpyPriv->codes->major_opcode;
839    dpyPriv->serverGLXvendor = 0x0;
840    dpyPriv->serverGLXversion = 0x0;
841
842    /* See if the versions are compatible.  This GLX implementation does not
843     * work with servers that only support GLX 1.0.
844     */
845    if (!QueryVersion(dpy, dpyPriv->majorOpcode,
846                      &dpyPriv->majorVersion, &dpyPriv->minorVersion)
847        || (dpyPriv->majorVersion == 1 && dpyPriv->minorVersion < 1)) {
848       Xfree(dpyPriv);
849       _XUnlockMutex(_Xglobal_lock);
850       return NULL;
851    }
852
853    for (i = 0; i < __GLX_NUMBER_EVENTS; i++) {
854       XESetWireToEvent(dpy, dpyPriv->codes->first_event + i, __glXWireToEvent);
855       XESetEventToWire(dpy, dpyPriv->codes->first_event + i, __glXEventToWire);
856    }
857
858    XESetCloseDisplay(dpy, dpyPriv->codes->extension, __glXCloseDisplay);
859    XESetErrorString (dpy, dpyPriv->codes->extension,__glXErrorString);
860
861    dpyPriv->glXDrawHash = __glxHashCreate();
862
863 #if defined(GLX_DIRECT_RENDERING) && !defined(GLX_USE_APPLEGL)
864    glx_direct = (getenv("LIBGL_ALWAYS_INDIRECT") == NULL);
865    glx_accel = (getenv("LIBGL_ALWAYS_SOFTWARE") == NULL);
866
867    dpyPriv->drawHash = __glxHashCreate();
868
869    /*
870     ** Initialize the direct rendering per display data and functions.
871     ** Note: This _must_ be done before calling any other DRI routines
872     ** (e.g., those called in AllocAndFetchScreenConfigs).
873     */
874    if (glx_direct && glx_accel) {
875       dpyPriv->dri2Display = dri2CreateDisplay(dpy);
876       dpyPriv->driDisplay = driCreateDisplay(dpy);
877    }
878    if (glx_direct)
879       dpyPriv->driswDisplay = driswCreateDisplay(dpy);
880 #endif
881
882 #ifdef GLX_USE_APPLEGL
883    if (!applegl_create_display(dpyPriv)) {
884       Xfree(dpyPriv);
885       return NULL;
886    }
887 #endif
888    if (!AllocAndFetchScreenConfigs(dpy, dpyPriv)) {
889       Xfree(dpyPriv);
890       return NULL;
891    }
892
893 #ifdef USE_XCB
894    __glX_send_client_info(dpyPriv);
895 #else
896    __glXClientInfo(dpy, dpyPriv->majorOpcode);
897 #endif
898
899    /* Grab the lock again and add the dispay private, unless somebody
900     * beat us to initializing on this display in the meantime. */
901    _XLockMutex(_Xglobal_lock);
902
903    for (d = glx_displays; d; d = d->next) {
904       if (d->dpy == dpy) {
905          _XUnlockMutex(_Xglobal_lock);
906          glx_display_free(dpyPriv);
907          return d;
908       }
909    }
910
911    dpyPriv->next = glx_displays;
912    glx_displays = dpyPriv;
913
914     _XUnlockMutex(_Xglobal_lock);
915
916    return dpyPriv;
917 }
918
919 /*
920 ** Setup for sending a GLX command on dpy.  Make sure the extension is
921 ** initialized.  Try to avoid calling __glXInitialize as its kinda slow.
922 */
923 _X_HIDDEN CARD8
924 __glXSetupForCommand(Display * dpy)
925 {
926     struct glx_context *gc;
927     struct glx_display *priv;
928
929    /* If this thread has a current context, flush its rendering commands */
930    gc = __glXGetCurrentContext();
931    if (gc->currentDpy) {
932       /* Flush rendering buffer of the current context, if any */
933       (void) __glXFlushRenderBuffer(gc, gc->pc);
934
935       if (gc->currentDpy == dpy) {
936          /* Use opcode from gc because its right */
937          return gc->majorOpcode;
938       }
939       else {
940          /*
941           ** Have to get info about argument dpy because it might be to
942           ** a different server
943           */
944       }
945    }
946
947    /* Forced to lookup extension via the slow initialize route */
948    priv = __glXInitialize(dpy);
949    if (!priv) {
950       return 0;
951    }
952    return priv->majorOpcode;
953 }
954
955 /**
956  * Flush the drawing command transport buffer.
957  *
958  * \param ctx  Context whose transport buffer is to be flushed.
959  * \param pc   Pointer to first unused buffer location.
960  *
961  * \todo
962  * Modify this function to use \c ctx->pc instead of the explicit
963  * \c pc parameter.
964  */
965 _X_HIDDEN GLubyte *
966 __glXFlushRenderBuffer(struct glx_context * ctx, GLubyte * pc)
967 {
968    Display *const dpy = ctx->currentDpy;
969 #ifdef USE_XCB
970    xcb_connection_t *c = XGetXCBConnection(dpy);
971 #else
972    xGLXRenderReq *req;
973 #endif /* USE_XCB */
974    const GLint size = pc - ctx->buf;
975
976    if ((dpy != NULL) && (size > 0)) {
977 #ifdef USE_XCB
978       xcb_glx_render(c, ctx->currentContextTag, size,
979                      (const uint8_t *) ctx->buf);
980 #else
981       /* Send the entire buffer as an X request */
982       LockDisplay(dpy);
983       GetReq(GLXRender, req);
984       req->reqType = ctx->majorOpcode;
985       req->glxCode = X_GLXRender;
986       req->contextTag = ctx->currentContextTag;
987       req->length += (size + 3) >> 2;
988       _XSend(dpy, (char *) ctx->buf, size);
989       UnlockDisplay(dpy);
990       SyncHandle();
991 #endif
992    }
993
994    /* Reset pointer and return it */
995    ctx->pc = ctx->buf;
996    return ctx->pc;
997 }
998
999
1000 /**
1001  * Send a portion of a GLXRenderLarge command to the server.  The advantage of
1002  * this function over \c __glXSendLargeCommand is that callers can use the
1003  * data buffer in the GLX context and may be able to avoid allocating an
1004  * extra buffer.  The disadvantage is the clients will have to do more
1005  * GLX protocol work (i.e., calculating \c totalRequests, etc.).
1006  *
1007  * \sa __glXSendLargeCommand
1008  *
1009  * \param gc             GLX context
1010  * \param requestNumber  Which part of the whole command is this?  The first
1011  *                       request is 1.
1012  * \param totalRequests  How many requests will there be?
1013  * \param data           Command data.
1014  * \param dataLen        Size, in bytes, of the command data.
1015  */
1016 _X_HIDDEN void
1017 __glXSendLargeChunk(struct glx_context * gc, GLint requestNumber,
1018                     GLint totalRequests, const GLvoid * data, GLint dataLen)
1019 {
1020    Display *dpy = gc->currentDpy;
1021 #ifdef USE_XCB
1022    xcb_connection_t *c = XGetXCBConnection(dpy);
1023    xcb_glx_render_large(c, gc->currentContextTag, requestNumber,
1024                         totalRequests, dataLen, data);
1025 #else
1026    xGLXRenderLargeReq *req;
1027
1028    if (requestNumber == 1) {
1029       LockDisplay(dpy);
1030    }
1031
1032    GetReq(GLXRenderLarge, req);
1033    req->reqType = gc->majorOpcode;
1034    req->glxCode = X_GLXRenderLarge;
1035    req->contextTag = gc->currentContextTag;
1036    req->length += (dataLen + 3) >> 2;
1037    req->requestNumber = requestNumber;
1038    req->requestTotal = totalRequests;
1039    req->dataBytes = dataLen;
1040    Data(dpy, data, dataLen);
1041
1042    if (requestNumber == totalRequests) {
1043       UnlockDisplay(dpy);
1044       SyncHandle();
1045    }
1046 #endif /* USE_XCB */
1047 }
1048
1049
1050 /**
1051  * Send a command that is too large for the GLXRender protocol request.
1052  *
1053  * Send a large command, one that is too large for some reason to
1054  * send using the GLXRender protocol request.  One reason to send
1055  * a large command is to avoid copying the data.
1056  *
1057  * \param ctx        GLX context
1058  * \param header     Header data.
1059  * \param headerLen  Size, in bytes, of the header data.  It is assumed that
1060  *                   the header data will always be small enough to fit in
1061  *                   a single X protocol packet.
1062  * \param data       Command data.
1063  * \param dataLen    Size, in bytes, of the command data.
1064  */
1065 _X_HIDDEN void
1066 __glXSendLargeCommand(struct glx_context * ctx,
1067                       const GLvoid * header, GLint headerLen,
1068                       const GLvoid * data, GLint dataLen)
1069 {
1070    GLint maxSize;
1071    GLint totalRequests, requestNumber;
1072
1073    /*
1074     ** Calculate the maximum amount of data can be stuffed into a single
1075     ** packet.  sz_xGLXRenderReq is added because bufSize is the maximum
1076     ** packet size minus sz_xGLXRenderReq.
1077     */
1078    maxSize = (ctx->bufSize + sz_xGLXRenderReq) - sz_xGLXRenderLargeReq;
1079    totalRequests = 1 + (dataLen / maxSize);
1080    if (dataLen % maxSize)
1081       totalRequests++;
1082
1083    /*
1084     ** Send all of the command, except the large array, as one request.
1085     */
1086    assert(headerLen <= maxSize);
1087    __glXSendLargeChunk(ctx, 1, totalRequests, header, headerLen);
1088
1089    /*
1090     ** Send enough requests until the whole array is sent.
1091     */
1092    for (requestNumber = 2; requestNumber <= (totalRequests - 1);
1093         requestNumber++) {
1094       __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, maxSize);
1095       data = (const GLvoid *) (((const GLubyte *) data) + maxSize);
1096       dataLen -= maxSize;
1097       assert(dataLen > 0);
1098    }
1099
1100    assert(dataLen <= maxSize);
1101    __glXSendLargeChunk(ctx, requestNumber, totalRequests, data, dataLen);
1102 }
1103
1104 /************************************************************************/
1105
1106 #ifdef DEBUG
1107 _X_HIDDEN void
1108 __glXDumpDrawBuffer(struct glx_context * ctx)
1109 {
1110    GLubyte *p = ctx->buf;
1111    GLubyte *end = ctx->pc;
1112    GLushort opcode, length;
1113
1114    while (p < end) {
1115       /* Fetch opcode */
1116       opcode = *((GLushort *) p);
1117       length = *((GLushort *) (p + 2));
1118       printf("%2x: %5d: ", opcode, length);
1119       length -= 4;
1120       p += 4;
1121       while (length > 0) {
1122          printf("%08x ", *((unsigned *) p));
1123          p += 4;
1124          length -= 4;
1125       }
1126       printf("\n");
1127    }
1128 }
1129 #endif