OSDN Git Service

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