mshtml: Added IHTMLWindow2::focus implementation.
[wine] / dlls / winex11.drv / opengl.c
1 /*
2  * X11DRV OpenGL functions
3  *
4  * Copyright 2000 Lionel Ulmer
5  * Copyright 2005 Alex Woods
6  * Copyright 2005 Raphael Junqueira
7  * Copyright 2006-2009 Roderick Colenbrander
8  * Copyright 2006 Tomas Carnecky
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
34 #endif
35 #ifdef HAVE_SYS_UN_H
36 #include <sys/un.h>
37 #endif
38
39 #include "x11drv.h"
40 #include "winternl.h"
41 #include "wine/library.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(wgl);
45 WINE_DECLARE_DEBUG_CHANNEL(winediag);
46
47 #ifdef SONAME_LIBGL
48
49 #undef APIENTRY
50 #undef CALLBACK
51 #undef WINAPI
52
53 #ifdef HAVE_GL_GL_H
54 # include <GL/gl.h>
55 #endif
56 #ifdef HAVE_GL_GLX_H
57 # include <GL/glx.h>
58 #endif
59
60 #include "wine/wgl.h"
61
62 #undef APIENTRY
63 #undef CALLBACK
64 #undef WINAPI
65
66 /* Redefines the constants */
67 #define CALLBACK    __stdcall
68 #define WINAPI      __stdcall
69 #define APIENTRY    WINAPI
70
71
72 WINE_DECLARE_DEBUG_CHANNEL(fps);
73
74 typedef struct wine_glextension {
75     const char *extName;
76     struct {
77         const char *funcName;
78         void *funcAddress;
79     } extEntryPoints[9];
80 } WineGLExtension;
81
82 struct WineGLInfo {
83     const char *glVersion;
84     char *glExtensions;
85
86     int glxVersion[2];
87
88     const char *glxServerVersion;
89     const char *glxServerVendor;
90     const char *glxServerExtensions;
91
92     const char *glxClientVersion;
93     const char *glxClientVendor;
94     const char *glxClientExtensions;
95
96     const char *glxExtensions;
97
98     BOOL glxDirect;
99     char wglExtensions[4096];
100 };
101
102 typedef struct wine_glpixelformat {
103     int         iPixelFormat;
104     GLXFBConfig fbconfig;
105     int         fmt_id;
106     int         render_type;
107     BOOL        offscreenOnly;
108     DWORD       dwFlags; /* We store some PFD_* flags in here for emulated bitmap formats */
109 } WineGLPixelFormat;
110
111 typedef struct wine_glcontext {
112     HDC hdc;
113     BOOL do_escape;
114     BOOL has_been_current;
115     BOOL sharing;
116     DWORD tid;
117     BOOL gl3_context;
118     XVisualInfo *vis;
119     WineGLPixelFormat *fmt;
120     int numAttribs; /* This is needed for delaying wglCreateContextAttribsARB */
121     int attribList[16]; /* This is needed for delaying wglCreateContextAttribsARB */
122     GLXContext ctx;
123     HDC read_hdc;
124     Drawable drawables[2];
125     BOOL refresh_drawables;
126     struct wine_glcontext *next;
127     struct wine_glcontext *prev;
128 } Wine_GLContext;
129
130 typedef struct wine_glpbuffer {
131     Drawable   drawable;
132     Display*   display;
133     WineGLPixelFormat* fmt;
134     int        width;
135     int        height;
136     int*       attribList;
137     HDC        hdc;
138
139     int        use_render_texture; /* This is also the internal texture format */
140     int        texture_bind_target;
141     int        texture_bpp;
142     GLint      texture_format;
143     GLuint     texture_target;
144     GLenum     texture_type;
145     GLuint     texture;
146     int        texture_level;
147 } Wine_GLPBuffer;
148
149 static Wine_GLContext *context_list;
150 static struct WineGLInfo WineGLInfo = { 0 };
151 static int use_render_texture_emulation = 1;
152 static int use_render_texture_ati = 0;
153 static int swap_interval = 1;
154
155 #define MAX_EXTENSIONS 16
156 static const WineGLExtension *WineGLExtensionList[MAX_EXTENSIONS];
157 static int WineGLExtensionListSize;
158
159 static void X11DRV_WineGL_LoadExtensions(void);
160 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count);
161 static BOOL glxRequireVersion(int requiredVersion);
162 static BOOL glxRequireExtension(const char *requiredExtension);
163
164 static void dump_PIXELFORMATDESCRIPTOR(const PIXELFORMATDESCRIPTOR *ppfd) {
165   TRACE("  - size / version : %d / %d\n", ppfd->nSize, ppfd->nVersion);
166   TRACE("  - dwFlags : ");
167 #define TEST_AND_DUMP(t,tv) if ((t) & (tv)) TRACE(#tv " ")
168   TEST_AND_DUMP(ppfd->dwFlags, PFD_DEPTH_DONTCARE);
169   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER);
170   TEST_AND_DUMP(ppfd->dwFlags, PFD_DOUBLEBUFFER_DONTCARE);
171   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_WINDOW);
172   TEST_AND_DUMP(ppfd->dwFlags, PFD_DRAW_TO_BITMAP);
173   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_ACCELERATED);
174   TEST_AND_DUMP(ppfd->dwFlags, PFD_GENERIC_FORMAT);
175   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_PALETTE);
176   TEST_AND_DUMP(ppfd->dwFlags, PFD_NEED_SYSTEM_PALETTE);
177   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO);
178   TEST_AND_DUMP(ppfd->dwFlags, PFD_STEREO_DONTCARE);
179   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_GDI);
180   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_OPENGL);
181   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_COPY);
182   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_EXCHANGE);
183   TEST_AND_DUMP(ppfd->dwFlags, PFD_SWAP_LAYER_BUFFERS);
184   /* PFD_SUPPORT_COMPOSITION is new in Vista, it is similar to composition
185    * under X e.g. COMPOSITE + GLX_EXT_TEXTURE_FROM_PIXMAP. */
186   TEST_AND_DUMP(ppfd->dwFlags, PFD_SUPPORT_COMPOSITION);
187 #undef TEST_AND_DUMP
188   TRACE("\n");
189
190   TRACE("  - iPixelType : ");
191   switch (ppfd->iPixelType) {
192   case PFD_TYPE_RGBA: TRACE("PFD_TYPE_RGBA"); break;
193   case PFD_TYPE_COLORINDEX: TRACE("PFD_TYPE_COLORINDEX"); break;
194   }
195   TRACE("\n");
196
197   TRACE("  - Color   : %d\n", ppfd->cColorBits);
198   TRACE("  - Red     : %d\n", ppfd->cRedBits);
199   TRACE("  - Green   : %d\n", ppfd->cGreenBits);
200   TRACE("  - Blue    : %d\n", ppfd->cBlueBits);
201   TRACE("  - Alpha   : %d\n", ppfd->cAlphaBits);
202   TRACE("  - Accum   : %d\n", ppfd->cAccumBits);
203   TRACE("  - Depth   : %d\n", ppfd->cDepthBits);
204   TRACE("  - Stencil : %d\n", ppfd->cStencilBits);
205   TRACE("  - Aux     : %d\n", ppfd->cAuxBuffers);
206
207   TRACE("  - iLayerType : ");
208   switch (ppfd->iLayerType) {
209   case PFD_MAIN_PLANE: TRACE("PFD_MAIN_PLANE"); break;
210   case PFD_OVERLAY_PLANE: TRACE("PFD_OVERLAY_PLANE"); break;
211   case (BYTE)PFD_UNDERLAY_PLANE: TRACE("PFD_UNDERLAY_PLANE"); break;
212   }
213   TRACE("\n");
214 }
215
216 #define PUSH1(attribs,att)        do { attribs[nAttribs++] = (att); } while (0)
217 #define PUSH2(attribs,att,value)  do { attribs[nAttribs++] = (att); attribs[nAttribs++] = (value); } while(0)
218
219 #define MAKE_FUNCPTR(f) static typeof(f) * p##f;
220 /* GLX 1.0 */
221 MAKE_FUNCPTR(glXChooseVisual)
222 MAKE_FUNCPTR(glXCopyContext)
223 MAKE_FUNCPTR(glXCreateContext)
224 MAKE_FUNCPTR(glXCreateGLXPixmap)
225 MAKE_FUNCPTR(glXGetCurrentContext)
226 MAKE_FUNCPTR(glXGetCurrentDrawable)
227 MAKE_FUNCPTR(glXDestroyContext)
228 MAKE_FUNCPTR(glXDestroyGLXPixmap)
229 MAKE_FUNCPTR(glXGetConfig)
230 MAKE_FUNCPTR(glXIsDirect)
231 MAKE_FUNCPTR(glXMakeCurrent)
232 MAKE_FUNCPTR(glXSwapBuffers)
233 MAKE_FUNCPTR(glXQueryExtension)
234 MAKE_FUNCPTR(glXQueryVersion)
235 MAKE_FUNCPTR(glXUseXFont)
236
237 /* GLX 1.1 */
238 MAKE_FUNCPTR(glXGetClientString)
239 MAKE_FUNCPTR(glXQueryExtensionsString)
240 MAKE_FUNCPTR(glXQueryServerString)
241
242 /* GLX 1.3 */
243 MAKE_FUNCPTR(glXGetFBConfigs)
244 MAKE_FUNCPTR(glXChooseFBConfig)
245 MAKE_FUNCPTR(glXCreatePbuffer)
246 MAKE_FUNCPTR(glXCreateNewContext)
247 MAKE_FUNCPTR(glXDestroyPbuffer)
248 MAKE_FUNCPTR(glXGetFBConfigAttrib)
249 MAKE_FUNCPTR(glXGetVisualFromFBConfig)
250 MAKE_FUNCPTR(glXMakeContextCurrent)
251 MAKE_FUNCPTR(glXQueryDrawable)
252 MAKE_FUNCPTR(glXGetCurrentReadDrawable)
253
254 /* GLX Extensions */
255 static GLXContext (*pglXCreateContextAttribsARB)(Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
256 static void* (*pglXGetProcAddressARB)(const GLubyte *);
257 static int   (*pglXSwapIntervalSGI)(int);
258
259 /* ATI GLX Extensions */
260 static BOOL  (*pglXBindTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
261 static BOOL  (*pglXReleaseTexImageATI)(Display *dpy, GLXPbuffer pbuffer, int buffer);
262 static BOOL  (*pglXDrawableAttribATI)(Display *dpy, GLXDrawable draw, const int *attribList);
263
264 /* NV GLX Extension */
265 static void* (*pglXAllocateMemoryNV)(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
266 static void  (*pglXFreeMemoryNV)(GLvoid *pointer);
267
268 /* MESA GLX Extensions */
269 static void (*pglXCopySubBufferMESA)(Display *dpy, GLXDrawable drawable, int x, int y, int width, int height);
270
271 /* Standard OpenGL */
272 MAKE_FUNCPTR(glBindTexture)
273 MAKE_FUNCPTR(glBitmap)
274 MAKE_FUNCPTR(glCopyTexSubImage1D)
275 MAKE_FUNCPTR(glCopyTexImage2D)
276 MAKE_FUNCPTR(glCopyTexSubImage2D)
277 MAKE_FUNCPTR(glDrawBuffer)
278 MAKE_FUNCPTR(glEndList)
279 MAKE_FUNCPTR(glGetError)
280 MAKE_FUNCPTR(glGetIntegerv)
281 MAKE_FUNCPTR(glGetString)
282 MAKE_FUNCPTR(glNewList)
283 MAKE_FUNCPTR(glPixelStorei)
284 MAKE_FUNCPTR(glReadPixels)
285 MAKE_FUNCPTR(glTexImage2D)
286 MAKE_FUNCPTR(glFinish)
287 MAKE_FUNCPTR(glFlush)
288 #undef MAKE_FUNCPTR
289
290 static int GLXErrorHandler(Display *dpy, XErrorEvent *event, void *arg)
291 {
292     /* In the future we might want to find the exact X or GLX error to report back to the app */
293     return 1;
294 }
295
296 static BOOL infoInitialized = FALSE;
297 static BOOL X11DRV_WineGL_InitOpenglInfo(void)
298 {
299     int screen = DefaultScreen(gdi_display);
300     Window win = 0, root = 0;
301     const char* str;
302     XVisualInfo *vis;
303     GLXContext ctx = NULL;
304     XSetWindowAttributes attr;
305     BOOL ret = FALSE;
306     int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, None};
307
308     if (infoInitialized)
309         return TRUE;
310     infoInitialized = TRUE;
311
312     attr.override_redirect = True;
313     attr.colormap = None;
314
315     wine_tsx11_lock();
316
317     vis = pglXChooseVisual(gdi_display, screen, attribList);
318     if (vis) {
319 #ifdef __i386__
320         WORD old_fs = wine_get_fs();
321         /* Create a GLX Context. Without one we can't query GL information */
322         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
323         if (wine_get_fs() != old_fs)
324         {
325             wine_set_fs( old_fs );
326             ERR( "%%fs register corrupted, probably broken ATI driver, disabling OpenGL.\n" );
327             ERR( "You need to set the \"UseFastTls\" option to \"2\" in your X config file.\n" );
328             goto done;
329         }
330 #else
331         ctx = pglXCreateContext(gdi_display, vis, None, GL_TRUE);
332 #endif
333     }
334     if (!ctx) goto done;
335
336     root = RootWindow( gdi_display, vis->screen );
337     if (vis->visual != DefaultVisual( gdi_display, vis->screen ))
338         attr.colormap = XCreateColormap( gdi_display, root, vis->visual, AllocNone );
339     if ((win = XCreateWindow( gdi_display, root, -1, -1, 1, 1, 0, vis->depth, InputOutput,
340                               vis->visual, CWOverrideRedirect | CWColormap, &attr )))
341         XMapWindow( gdi_display, win );
342     else
343         win = root;
344
345     pglXMakeCurrent(gdi_display, win, ctx);
346
347     WineGLInfo.glVersion = (const char *) pglGetString(GL_VERSION);
348     str = (const char *) pglGetString(GL_EXTENSIONS);
349     WineGLInfo.glExtensions = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
350     strcpy(WineGLInfo.glExtensions, str);
351
352     /* Get the common GLX version supported by GLX client and server ( major/minor) */
353     pglXQueryVersion(gdi_display, &WineGLInfo.glxVersion[0], &WineGLInfo.glxVersion[1]);
354
355     WineGLInfo.glxServerVersion = pglXQueryServerString(gdi_display, screen, GLX_VERSION);
356     WineGLInfo.glxServerVendor = pglXQueryServerString(gdi_display, screen, GLX_VENDOR);
357     WineGLInfo.glxServerExtensions = pglXQueryServerString(gdi_display, screen, GLX_EXTENSIONS);
358
359     WineGLInfo.glxClientVersion = pglXGetClientString(gdi_display, GLX_VERSION);
360     WineGLInfo.glxClientVendor = pglXGetClientString(gdi_display, GLX_VENDOR);
361     WineGLInfo.glxClientExtensions = pglXGetClientString(gdi_display, GLX_EXTENSIONS);
362
363     WineGLInfo.glxExtensions = pglXQueryExtensionsString(gdi_display, screen);
364     WineGLInfo.glxDirect = pglXIsDirect(gdi_display, ctx);
365
366     TRACE("GL version             : %s.\n", WineGLInfo.glVersion);
367     TRACE("GL renderer            : %s.\n", pglGetString(GL_RENDERER));
368     TRACE("GLX version            : %d.%d.\n", WineGLInfo.glxVersion[0], WineGLInfo.glxVersion[1]);
369     TRACE("Server GLX version     : %s.\n", WineGLInfo.glxServerVersion);
370     TRACE("Server GLX vendor:     : %s.\n", WineGLInfo.glxServerVendor);
371     TRACE("Client GLX version     : %s.\n", WineGLInfo.glxClientVersion);
372     TRACE("Client GLX vendor:     : %s.\n", WineGLInfo.glxClientVendor);
373     TRACE("Direct rendering enabled: %s\n", WineGLInfo.glxDirect ? "True" : "False");
374
375     if(!WineGLInfo.glxDirect)
376     {
377         int fd = ConnectionNumber(gdi_display);
378         struct sockaddr_un uaddr;
379         unsigned int uaddrlen = sizeof(struct sockaddr_un);
380
381         /* In general indirect rendering on a local X11 server indicates a driver problem.
382          * Detect a local X11 server by checking whether the X11 socket is a Unix socket.
383          */
384         if(!getsockname(fd, (struct sockaddr *)&uaddr, &uaddrlen) && uaddr.sun_family == AF_UNIX)
385             ERR_(winediag)("Direct rendering is disabled, most likely your OpenGL drivers haven't been installed correctly\n");
386     }
387     else
388     {
389         /* In general you would expect that if direct rendering is returned, that you receive hardware
390          * accelerated OpenGL rendering. The definition of direct rendering is that rendering is performed
391          * client side without sending all GL commands to X using the GLX protocol. When Mesa falls back to
392          * software rendering, it shows direct rendering.
393          *
394          * Depending on the cause of software rendering a different rendering string is shown. In case Mesa fails
395          * to load a DRI module 'Software Rasterizer' is returned. When Mesa is compiled as a OpenGL reference driver
396          * it shows 'Mesa X11'.
397          */
398         const char *gl_renderer = (const char *)pglGetString(GL_RENDERER);
399         if(!strcmp(gl_renderer, "Software Rasterizer") || !strcmp(gl_renderer, "Mesa X11"))
400             ERR_(winediag)("The Mesa OpenGL driver is using software rendering, most likely your OpenGL drivers haven't been installed correctly\n");
401     }
402     ret = TRUE;
403
404 done:
405     if(vis) XFree(vis);
406     if(ctx) {
407         pglXMakeCurrent(gdi_display, None, NULL);    
408         pglXDestroyContext(gdi_display, ctx);
409     }
410     if (win != root) XDestroyWindow( gdi_display, win );
411     if (attr.colormap) XFreeColormap( gdi_display, attr.colormap );
412     wine_tsx11_unlock();
413     if (!ret) ERR(" couldn't initialize OpenGL, expect problems\n");
414     return ret;
415 }
416
417 void X11DRV_OpenGL_Cleanup(void)
418 {
419     HeapFree(GetProcessHeap(), 0, WineGLInfo.glExtensions);
420     infoInitialized = FALSE;
421 }
422
423 static BOOL has_opengl(void)
424 {
425     static int init_done;
426     static void *opengl_handle;
427
428     char buffer[200];
429     int error_base, event_base;
430
431     if (init_done) return (opengl_handle != NULL);
432     init_done = 1;
433
434     /* No need to load any other libraries as according to the ABI, libGL should be self-sufficient
435        and include all dependencies */
436     opengl_handle = wine_dlopen(SONAME_LIBGL, RTLD_NOW|RTLD_GLOBAL, buffer, sizeof(buffer));
437     if (opengl_handle == NULL)
438     {
439         ERR( "Failed to load libGL: %s\n", buffer );
440         ERR( "OpenGL support is disabled.\n");
441         return FALSE;
442     }
443
444     pglXGetProcAddressARB = wine_dlsym(opengl_handle, "glXGetProcAddressARB", NULL, 0);
445     if (pglXGetProcAddressARB == NULL) {
446         ERR("Could not find glXGetProcAddressARB in libGL, disabling OpenGL.\n");
447         goto failed;
448     }
449
450 #define LOAD_FUNCPTR(f) do if((p##f = (void*)pglXGetProcAddressARB((const unsigned char*)#f)) == NULL) \
451     { \
452         ERR( "%s not found in libGL, disabling OpenGL.\n", #f ); \
453         goto failed; \
454     } while(0)
455
456     /* GLX 1.0 */
457     LOAD_FUNCPTR(glXChooseVisual);
458     LOAD_FUNCPTR(glXCopyContext);
459     LOAD_FUNCPTR(glXCreateContext);
460     LOAD_FUNCPTR(glXCreateGLXPixmap);
461     LOAD_FUNCPTR(glXGetCurrentContext);
462     LOAD_FUNCPTR(glXGetCurrentDrawable);
463     LOAD_FUNCPTR(glXDestroyContext);
464     LOAD_FUNCPTR(glXDestroyGLXPixmap);
465     LOAD_FUNCPTR(glXGetConfig);
466     LOAD_FUNCPTR(glXIsDirect);
467     LOAD_FUNCPTR(glXMakeCurrent);
468     LOAD_FUNCPTR(glXSwapBuffers);
469     LOAD_FUNCPTR(glXQueryExtension);
470     LOAD_FUNCPTR(glXQueryVersion);
471     LOAD_FUNCPTR(glXUseXFont);
472
473     /* GLX 1.1 */
474     LOAD_FUNCPTR(glXGetClientString);
475     LOAD_FUNCPTR(glXQueryExtensionsString);
476     LOAD_FUNCPTR(glXQueryServerString);
477
478     /* GLX 1.3 */
479     LOAD_FUNCPTR(glXCreatePbuffer);
480     LOAD_FUNCPTR(glXCreateNewContext);
481     LOAD_FUNCPTR(glXDestroyPbuffer);
482     LOAD_FUNCPTR(glXMakeContextCurrent);
483     LOAD_FUNCPTR(glXGetCurrentReadDrawable);
484     LOAD_FUNCPTR(glXGetFBConfigs);
485
486     /* Standard OpenGL calls */
487     LOAD_FUNCPTR(glBindTexture);
488     LOAD_FUNCPTR(glBitmap);
489     LOAD_FUNCPTR(glCopyTexSubImage1D);
490     LOAD_FUNCPTR(glCopyTexImage2D);
491     LOAD_FUNCPTR(glCopyTexSubImage2D);
492     LOAD_FUNCPTR(glDrawBuffer);
493     LOAD_FUNCPTR(glEndList);
494     LOAD_FUNCPTR(glGetError);
495     LOAD_FUNCPTR(glGetIntegerv);
496     LOAD_FUNCPTR(glGetString);
497     LOAD_FUNCPTR(glNewList);
498     LOAD_FUNCPTR(glPixelStorei);
499     LOAD_FUNCPTR(glReadPixels);
500     LOAD_FUNCPTR(glTexImage2D);
501     LOAD_FUNCPTR(glFinish);
502     LOAD_FUNCPTR(glFlush);
503 #undef LOAD_FUNCPTR
504
505 /* It doesn't matter if these fail. They'll only be used if the driver reports
506    the associated extension is available (and if a driver reports the extension
507    is available but fails to provide the functions, it's quite broken) */
508 #define LOAD_FUNCPTR(f) p##f = pglXGetProcAddressARB((const GLubyte *)#f)
509     /* ARB GLX Extension */
510     LOAD_FUNCPTR(glXCreateContextAttribsARB);
511     /* SGI GLX Extension */
512     LOAD_FUNCPTR(glXSwapIntervalSGI);
513     /* NV GLX Extension */
514     LOAD_FUNCPTR(glXAllocateMemoryNV);
515     LOAD_FUNCPTR(glXFreeMemoryNV);
516 #undef LOAD_FUNCPTR
517
518     if(!X11DRV_WineGL_InitOpenglInfo()) goto failed;
519
520     wine_tsx11_lock();
521     if (pglXQueryExtension(gdi_display, &error_base, &event_base)) {
522         TRACE("GLX is up and running error_base = %d\n", error_base);
523     } else {
524         wine_tsx11_unlock();
525         ERR( "GLX extension is missing, disabling OpenGL.\n" );
526         goto failed;
527     }
528
529     /* In case of GLX you have direct and indirect rendering. Most of the time direct rendering is used
530      * as in general only that is hardware accelerated. In some cases like in case of remote X indirect
531      * rendering is used.
532      *
533      * The main problem for our OpenGL code is that we need certain GLX calls but their presence
534      * depends on the reported GLX client / server version and on the client / server extension list.
535      * Those don't have to be the same.
536      *
537      * In general the server GLX information lists the capabilities in case of indirect rendering.
538      * When direct rendering is used, the OpenGL client library is responsible for which GLX calls are
539      * available and in that case the client GLX informat can be used.
540      * OpenGL programs should use the 'intersection' of both sets of information which is advertised
541      * in the GLX version/extension list. When a program does this it works for certain for both
542      * direct and indirect rendering.
543      *
544      * The problem we are having in this area is that ATI's Linux drivers are broken. For some reason
545      * they haven't added some very important GLX extensions like GLX_SGIX_fbconfig to their client
546      * extension list which causes this extension not to be listed. (Wine requires this extension).
547      * ATI advertises a GLX client version of 1.3 which implies that this fbconfig extension among
548      * pbuffers is around.
549      *
550      * In order to provide users of Ati's proprietary drivers with OpenGL support, we need to detect
551      * the ATI drivers and from then on use GLX client information for them.
552      */
553
554     if(glxRequireVersion(3)) {
555         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
556         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
557         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
558         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
559     } else if(glxRequireExtension("GLX_SGIX_fbconfig")) {
560         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfigSGIX");
561         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttribSGIX");
562         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfigSGIX");
563
564         /* The mesa libGL client library seems to forward glXQueryDrawable to the Xserver, so only
565          * enable this function when the Xserver understand GLX 1.3 or newer
566          */
567         pglXQueryDrawable = NULL;
568      } else if(strcmp("ATI", WineGLInfo.glxClientVendor) == 0) {
569         TRACE("Overriding ATI GLX capabilities!\n");
570         pglXChooseFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXChooseFBConfig");
571         pglXGetFBConfigAttrib = pglXGetProcAddressARB((const GLubyte *) "glXGetFBConfigAttrib");
572         pglXGetVisualFromFBConfig = pglXGetProcAddressARB((const GLubyte *) "glXGetVisualFromFBConfig");
573         pglXQueryDrawable = pglXGetProcAddressARB((const GLubyte *) "glXQueryDrawable");
574
575         /* Use client GLX information in case of the ATI drivers. We override the
576          * capabilities over here and not somewhere else as ATI might better their
577          * life in the future. In case they release proper drivers this block of
578          * code won't be called. */
579         WineGLInfo.glxExtensions = WineGLInfo.glxClientExtensions;
580     } else {
581          ERR(" glx_version is %s and GLX_SGIX_fbconfig extension is unsupported. Expect problems.\n", WineGLInfo.glxServerVersion);
582     }
583
584     if(glxRequireExtension("GLX_ATI_render_texture")) {
585         use_render_texture_ati = 1;
586         pglXBindTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXBindTexImageATI");
587         pglXReleaseTexImageATI = pglXGetProcAddressARB((const GLubyte *) "glXReleaseTexImageATI");
588         pglXDrawableAttribATI = pglXGetProcAddressARB((const GLubyte *) "glXDrawableAttribATI");
589     }
590
591     if(glxRequireExtension("GLX_MESA_copy_sub_buffer")) {
592         pglXCopySubBufferMESA = pglXGetProcAddressARB((const GLubyte *) "glXCopySubBufferMESA");
593     }
594
595     X11DRV_WineGL_LoadExtensions();
596
597     wine_tsx11_unlock();
598     return TRUE;
599
600 failed:
601     wine_dlclose(opengl_handle, NULL, 0);
602     opengl_handle = NULL;
603     return FALSE;
604 }
605
606 static inline Wine_GLContext *alloc_context(void)
607 {
608     Wine_GLContext *ret;
609
610     if ((ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Wine_GLContext))))
611     {
612         ret->next = context_list;
613         if (context_list) context_list->prev = ret;
614         context_list = ret;
615     }
616     return ret;
617 }
618
619 static inline void free_context(Wine_GLContext *context)
620 {
621     if (context->next != NULL) context->next->prev = context->prev;
622     if (context->prev != NULL) context->prev->next = context->next;
623     else context_list = context->next;
624
625     if (context->vis) XFree(context->vis);
626     HeapFree(GetProcessHeap(), 0, context);
627 }
628
629 static inline BOOL is_valid_context( Wine_GLContext *ctx )
630 {
631     Wine_GLContext *ptr;
632     for (ptr = context_list; ptr; ptr = ptr->next) if (ptr == ctx) break;
633     return (ptr != NULL);
634 }
635
636 static int describeContext(Wine_GLContext* ctx) {
637     int tmp;
638     int ctx_vis_id;
639     TRACE(" Context %p have (vis:%p):\n", ctx, ctx->vis);
640     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_FBCONFIG_ID, &tmp);
641     TRACE(" - FBCONFIG_ID 0x%x\n", tmp);
642     pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_VISUAL_ID, &tmp);
643     TRACE(" - VISUAL_ID 0x%x\n", tmp);
644     ctx_vis_id = tmp;
645     return ctx_vis_id;
646 }
647
648 static BOOL describeDrawable(X11DRV_PDEVICE *physDev) {
649     int tmp;
650     WineGLPixelFormat *fmt;
651     int fmt_count = 0;
652
653     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE /* Offscreen */, &fmt_count);
654     if(!fmt) return FALSE;
655
656     TRACE(" HDC %p has:\n", physDev->hdc);
657     TRACE(" - iPixelFormat %d\n", fmt->iPixelFormat);
658     TRACE(" - Drawable %p\n", (void*) get_glxdrawable(physDev));
659     TRACE(" - FBCONFIG_ID 0x%x\n", fmt->fmt_id);
660
661     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &tmp);
662     TRACE(" - VISUAL_ID 0x%x\n", tmp);
663
664     return TRUE;
665 }
666
667 static int ConvertAttribWGLtoGLX(const int* iWGLAttr, int* oGLXAttr, Wine_GLPBuffer* pbuf) {
668   int nAttribs = 0;
669   unsigned cur = 0; 
670   int pop;
671   int drawattrib = 0;
672   int nvfloatattrib = GLX_DONT_CARE;
673   int pixelattrib = ~0;
674
675   /* The list of WGL attributes is allowed to be NULL. We don't return here for NULL
676    * because we need to do fixups for GLX_DRAWABLE_TYPE/GLX_RENDER_TYPE/GLX_FLOAT_COMPONENTS_NV. */
677   while (iWGLAttr && 0 != iWGLAttr[cur]) {
678     TRACE("pAttr[%d] = %x\n", cur, iWGLAttr[cur]);
679
680     switch (iWGLAttr[cur]) {
681     case WGL_AUX_BUFFERS_ARB:
682       pop = iWGLAttr[++cur];
683       PUSH2(oGLXAttr, GLX_AUX_BUFFERS, pop);
684       TRACE("pAttr[%d] = GLX_AUX_BUFFERS: %d\n", cur, pop);
685       break;
686     case WGL_COLOR_BITS_ARB:
687       pop = iWGLAttr[++cur];
688       PUSH2(oGLXAttr, GLX_BUFFER_SIZE, pop);
689       TRACE("pAttr[%d] = GLX_BUFFER_SIZE: %d\n", cur, pop);
690       break;
691     case WGL_BLUE_BITS_ARB:
692       pop = iWGLAttr[++cur];
693       PUSH2(oGLXAttr, GLX_BLUE_SIZE, pop);
694       TRACE("pAttr[%d] = GLX_BLUE_SIZE: %d\n", cur, pop);
695       break;
696     case WGL_RED_BITS_ARB:
697       pop = iWGLAttr[++cur];
698       PUSH2(oGLXAttr, GLX_RED_SIZE, pop);
699       TRACE("pAttr[%d] = GLX_RED_SIZE: %d\n", cur, pop);
700       break;
701     case WGL_GREEN_BITS_ARB:
702       pop = iWGLAttr[++cur];
703       PUSH2(oGLXAttr, GLX_GREEN_SIZE, pop);
704       TRACE("pAttr[%d] = GLX_GREEN_SIZE: %d\n", cur, pop);
705       break;
706     case WGL_ALPHA_BITS_ARB:
707       pop = iWGLAttr[++cur];
708       PUSH2(oGLXAttr, GLX_ALPHA_SIZE, pop);
709       TRACE("pAttr[%d] = GLX_ALPHA_SIZE: %d\n", cur, pop);
710       break;
711     case WGL_DEPTH_BITS_ARB:
712       pop = iWGLAttr[++cur];
713       PUSH2(oGLXAttr, GLX_DEPTH_SIZE, pop);
714       TRACE("pAttr[%d] = GLX_DEPTH_SIZE: %d\n", cur, pop);
715       break;
716     case WGL_STENCIL_BITS_ARB:
717       pop = iWGLAttr[++cur];
718       PUSH2(oGLXAttr, GLX_STENCIL_SIZE, pop);
719       TRACE("pAttr[%d] = GLX_STENCIL_SIZE: %d\n", cur, pop);
720       break;
721     case WGL_DOUBLE_BUFFER_ARB:
722       pop = iWGLAttr[++cur];
723       PUSH2(oGLXAttr, GLX_DOUBLEBUFFER, pop);
724       TRACE("pAttr[%d] = GLX_DOUBLEBUFFER: %d\n", cur, pop);
725       break;
726     case WGL_STEREO_ARB:
727       pop = iWGLAttr[++cur];
728       PUSH2(oGLXAttr, GLX_STEREO, pop);
729       TRACE("pAttr[%d] = GLX_STEREO: %d\n", cur, pop);
730       break;
731
732     case WGL_PIXEL_TYPE_ARB:
733       pop = iWGLAttr[++cur];
734       TRACE("pAttr[%d] = WGL_PIXEL_TYPE_ARB: %d\n", cur, pop);
735       switch (pop) {
736       case WGL_TYPE_COLORINDEX_ARB: pixelattrib = GLX_COLOR_INDEX_BIT; break ;
737       case WGL_TYPE_RGBA_ARB: pixelattrib = GLX_RGBA_BIT; break ;
738       /* This is the same as WGL_TYPE_RGBA_FLOAT_ATI but the GLX constants differ, only the ARB GLX one is widely supported so use that */
739       case WGL_TYPE_RGBA_FLOAT_ATI: pixelattrib = GLX_RGBA_FLOAT_BIT; break ;
740       case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT: pixelattrib = GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT; break ;
741       default:
742         ERR("unexpected PixelType(%x)\n", pop); 
743         pop = 0;
744       }
745       break;
746
747     case WGL_SUPPORT_GDI_ARB:
748       /* This flag is set in a WineGLPixelFormat */
749       pop = iWGLAttr[++cur];
750       TRACE("pAttr[%d] = WGL_SUPPORT_GDI_ARB: %d\n", cur, pop);
751       break;
752
753     case WGL_DRAW_TO_BITMAP_ARB:
754       /* This flag is set in a WineGLPixelFormat */
755       pop = iWGLAttr[++cur];
756       TRACE("pAttr[%d] = WGL_DRAW_TO_BITMAP_ARB: %d\n", cur, pop);
757       break;
758
759     case WGL_DRAW_TO_WINDOW_ARB:
760       pop = iWGLAttr[++cur];
761       TRACE("pAttr[%d] = WGL_DRAW_TO_WINDOW_ARB: %d\n", cur, pop);
762       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
763       if (pop) {
764         drawattrib |= GLX_WINDOW_BIT;
765       }
766       break;
767
768     case WGL_DRAW_TO_PBUFFER_ARB:
769       pop = iWGLAttr[++cur];
770       TRACE("pAttr[%d] = WGL_DRAW_TO_PBUFFER_ARB: %d\n", cur, pop);
771       /* GLX_DRAWABLE_TYPE flags need to be OR'd together. See below. */
772       if (pop) {
773         drawattrib |= GLX_PBUFFER_BIT;
774       }
775       break;
776
777     case WGL_ACCELERATION_ARB:
778       /* This flag is set in a WineGLPixelFormat */
779       pop = iWGLAttr[++cur];
780       TRACE("pAttr[%d] = WGL_ACCELERATION_ARB: %d\n", cur, pop);
781       break;
782
783     case WGL_SUPPORT_OPENGL_ARB:
784       pop = iWGLAttr[++cur];
785       /** nothing to do, if we are here, supposing support Accelerated OpenGL */
786       TRACE("pAttr[%d] = WGL_SUPPORT_OPENGL_ARB: %d\n", cur, pop);
787       break;
788
789     case WGL_SWAP_METHOD_ARB:
790       pop = iWGLAttr[++cur];
791       /* For now we ignore this and just return SWAP_EXCHANGE */
792       TRACE("pAttr[%d] = WGL_SWAP_METHOD_ARB: %#x\n", cur, pop);
793       break;
794
795     case WGL_PBUFFER_LARGEST_ARB:
796       pop = iWGLAttr[++cur];
797       PUSH2(oGLXAttr, GLX_LARGEST_PBUFFER, pop);
798       TRACE("pAttr[%d] = GLX_LARGEST_PBUFFER: %x\n", cur, pop);
799       break;
800
801     case WGL_SAMPLE_BUFFERS_ARB:
802       pop = iWGLAttr[++cur];
803       PUSH2(oGLXAttr, GLX_SAMPLE_BUFFERS_ARB, pop);
804       TRACE("pAttr[%d] = GLX_SAMPLE_BUFFERS_ARB: %x\n", cur, pop);
805       break;
806
807     case WGL_SAMPLES_ARB:
808       pop = iWGLAttr[++cur];
809       PUSH2(oGLXAttr, GLX_SAMPLES_ARB, pop);
810       TRACE("pAttr[%d] = GLX_SAMPLES_ARB: %x\n", cur, pop);
811       break;
812
813     case WGL_TEXTURE_FORMAT_ARB:
814     case WGL_TEXTURE_TARGET_ARB:
815     case WGL_MIPMAP_TEXTURE_ARB:
816       TRACE("WGL_render_texture Attributes: %x as %x\n", iWGLAttr[cur], iWGLAttr[cur + 1]);
817       pop = iWGLAttr[++cur];
818       if (NULL == pbuf) {
819         ERR("trying to use GLX_Pbuffer Attributes without Pbuffer (was %x)\n", iWGLAttr[cur]);
820       }
821       if (use_render_texture_ati) {
822         /** nothing to do here */
823       }
824       else if (!use_render_texture_emulation) {
825         if (WGL_NO_TEXTURE_ARB != pop) {
826           ERR("trying to use WGL_render_texture Attributes without support (was %x)\n", iWGLAttr[cur]);
827           return -1; /** error: don't support it */
828         } else {
829           drawattrib |= GLX_PBUFFER_BIT;
830         }
831       }
832       break ;
833     case WGL_FLOAT_COMPONENTS_NV:
834       nvfloatattrib = iWGLAttr[++cur];
835       TRACE("pAttr[%d] = WGL_FLOAT_COMPONENTS_NV: %x\n", cur, nvfloatattrib);
836       break ;
837     case WGL_BIND_TO_TEXTURE_DEPTH_NV:
838     case WGL_BIND_TO_TEXTURE_RGB_ARB:
839     case WGL_BIND_TO_TEXTURE_RGBA_ARB:
840     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV:
841     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV:
842     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV:
843     case WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV:
844       pop = iWGLAttr[++cur];
845       /** cannot be converted, see direct handling on 
846        *   - wglGetPixelFormatAttribivARB
847        *  TODO: wglChoosePixelFormat
848        */
849       break ;
850     case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
851       pop = iWGLAttr[++cur];
852       PUSH2(oGLXAttr, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, pop);
853       TRACE("pAttr[%d] = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT: %x\n", cur, pop);
854       break ;
855
856     case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
857       pop = iWGLAttr[++cur];
858       PUSH2(oGLXAttr, GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT, pop);
859       TRACE("pAttr[%d] = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT: %x\n", cur, pop);
860       break ;
861     default:
862       FIXME("unsupported %x WGL Attribute\n", iWGLAttr[cur]);
863       break;
864     }
865     ++cur;
866   }
867
868   /* By default glXChooseFBConfig defaults to GLX_WINDOW_BIT. wglChoosePixelFormatARB searches through
869    * all formats. Unless drawattrib is set to a non-zero value override it with ~0, so that pixmap and pbuffer
870    * formats appear as well. */
871   if(!drawattrib) drawattrib = ~0;
872   PUSH2(oGLXAttr, GLX_DRAWABLE_TYPE, drawattrib);
873   TRACE("pAttr[?] = GLX_DRAWABLE_TYPE: %#x\n", drawattrib);
874
875   /* By default glXChooseFBConfig uses GLX_RGBA_BIT as the default value. Since wglChoosePixelFormatARB
876    * searches in all formats we have to do the same. For this reason we set GLX_RENDER_TYPE to ~0 unless
877    * it is overridden. */
878   PUSH2(oGLXAttr, GLX_RENDER_TYPE, pixelattrib);
879   TRACE("pAttr[?] = GLX_RENDER_TYPE: %#x\n", pixelattrib);
880
881   /* Set GLX_FLOAT_COMPONENTS_NV all the time */
882   if(strstr(WineGLInfo.glxExtensions, "GLX_NV_float_buffer")) {
883     PUSH2(oGLXAttr, GLX_FLOAT_COMPONENTS_NV, nvfloatattrib);
884     TRACE("pAttr[?] = GLX_FLOAT_COMPONENTS_NV: %#x\n", nvfloatattrib);
885   }
886
887   return nAttribs;
888 }
889
890 static int get_render_type_from_fbconfig(Display *display, GLXFBConfig fbconfig)
891 {
892     int render_type=0, render_type_bit;
893     pglXGetFBConfigAttrib(display, fbconfig, GLX_RENDER_TYPE, &render_type_bit);
894     switch(render_type_bit)
895     {
896         case GLX_RGBA_BIT:
897             render_type = GLX_RGBA_TYPE;
898             break;
899         case GLX_COLOR_INDEX_BIT:
900             render_type = GLX_COLOR_INDEX_TYPE;
901             break;
902         case GLX_RGBA_FLOAT_BIT:
903             render_type = GLX_RGBA_FLOAT_TYPE;
904             break;
905         case GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT:
906             render_type = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
907             break;
908         default:
909             ERR("Unknown render_type: %x\n", render_type_bit);
910     }
911     return render_type;
912 }
913
914 /* Check whether a fbconfig is suitable for Windows-style bitmap rendering */
915 static BOOL check_fbconfig_bitmap_capability(Display *display, GLXFBConfig fbconfig)
916 {
917     int dbuf, value;
918     pglXGetFBConfigAttrib(display, fbconfig, GLX_DOUBLEBUFFER, &dbuf);
919     pglXGetFBConfigAttrib(gdi_display, fbconfig, GLX_DRAWABLE_TYPE, &value);
920
921     /* Windows only supports bitmap rendering on single buffered formats, further the fbconfig needs to have
922      * the GLX_PIXMAP_BIT set. */
923     return !dbuf && (value & GLX_PIXMAP_BIT);
924 }
925
926 static WineGLPixelFormat *get_formats(Display *display, int *size_ret, int *onscreen_size_ret)
927 {
928     static WineGLPixelFormat *list;
929     static int size, onscreen_size;
930
931     int fmt_id, nCfgs, i, run, bmp_formats;
932     GLXFBConfig* cfgs;
933     XVisualInfo *visinfo;
934
935     wine_tsx11_lock();
936     if (list) goto done;
937
938     cfgs = pglXGetFBConfigs(display, DefaultScreen(display), &nCfgs);
939     if (NULL == cfgs || 0 == nCfgs) {
940         if(cfgs != NULL) XFree(cfgs);
941         wine_tsx11_unlock();
942         ERR("glXChooseFBConfig returns NULL\n");
943         return NULL;
944     }
945
946     /* Bitmap rendering on Windows implies the use of the Microsoft GDI software renderer.
947      * Further most GLX drivers only offer pixmap rendering using indirect rendering (except for modern drivers which support 'AIGLX' / composite).
948      * Indirect rendering can indicate software rendering (on Nvidia it is hw accelerated)
949      * Since bitmap rendering implies the use of software rendering we can safely use indirect rendering for bitmaps.
950      *
951      * Below we count the number of formats which are suitable for bitmap rendering. Windows restricts bitmap rendering to single buffered formats.
952      */
953     for(i=0, bmp_formats=0; i<nCfgs; i++)
954     {
955         if(check_fbconfig_bitmap_capability(display, cfgs[i]))
956             bmp_formats++;
957     }
958     TRACE("Found %d bitmap capable fbconfigs\n", bmp_formats);
959
960     list = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (nCfgs + bmp_formats)*sizeof(WineGLPixelFormat));
961
962     /* Fill the pixel format list. Put onscreen formats at the top and offscreen ones at the bottom.
963      * Do this as GLX doesn't guarantee that the list is sorted */
964     for(run=0; run < 2; run++)
965     {
966         for(i=0; i<nCfgs; i++) {
967             pglXGetFBConfigAttrib(display, cfgs[i], GLX_FBCONFIG_ID, &fmt_id);
968             visinfo = pglXGetVisualFromFBConfig(display, cfgs[i]);
969
970             /* The first run we only add onscreen formats (ones which have an associated X Visual).
971              * The second run we only set offscreen formats. */
972             if(!run && visinfo)
973             {
974                 /* We implement child window rendering using offscreen buffers (using composite or an XPixmap).
975                  * The contents is copied to the destination using XCopyArea. For the copying to work
976                  * the depth of the source and destination window should be the same. In general this should
977                  * not be a problem for OpenGL as drivers only advertise formats with a similar depth (or no depth).
978                  * As of the introduction of composition managers at least Nvidia now also offers ARGB visuals
979                  * with a depth of 32 in addition to the default 24 bit. In order to prevent BadMatch errors we only
980                  * list formats with the same depth. */
981                 if(visinfo->depth != screen_depth)
982                 {
983                     XFree(visinfo);
984                     continue;
985                 }
986
987                 TRACE("Found onscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
988                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
989                 list[size].fbconfig = cfgs[i];
990                 list[size].fmt_id = fmt_id;
991                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
992                 list[size].offscreenOnly = FALSE;
993                 list[size].dwFlags = 0;
994                 size++;
995                 onscreen_size++;
996
997                 /* Clone a format if it is bitmap capable for indirect rendering to bitmaps */
998                 if(check_fbconfig_bitmap_capability(display, cfgs[i]))
999                 {
1000                     TRACE("Found bitmap capable format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1001                     list[size].iPixelFormat = size+1; /* The index starts at 1 */
1002                     list[size].fbconfig = cfgs[i];
1003                     list[size].fmt_id = fmt_id;
1004                     list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1005                     list[size].offscreenOnly = FALSE;
1006                     list[size].dwFlags = PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI | PFD_GENERIC_FORMAT;
1007                     size++;
1008                     onscreen_size++;
1009                 }
1010             } else if(run && !visinfo) {
1011                 int window_drawable=0;
1012                 pglXGetFBConfigAttrib(gdi_display, cfgs[i], GLX_DRAWABLE_TYPE, &window_drawable);
1013
1014                 /* Recent Nvidia drivers and DRI drivers offer window drawable formats without a visual.
1015                  * This are formats like 16-bit rgb on a 24-bit desktop. In order to support these formats
1016                  * onscreen we would have to use glXCreateWindow instead of XCreateWindow. Further it will
1017                  * likely make our child window opengl rendering more complicated since likely you can't use
1018                  * XCopyArea on a GLX Window.
1019                  * For now ignore fbconfigs which are window drawable but lack a visual. */
1020                 if(window_drawable & GLX_WINDOW_BIT)
1021                 {
1022                     TRACE("Skipping FBCONFIG_ID 0x%x as an offscreen format because it is window_drawable\n", fmt_id);
1023                     continue;
1024                 }
1025
1026                 TRACE("Found offscreen format FBCONFIG_ID 0x%x corresponding to iPixelFormat %d at GLX index %d\n", fmt_id, size+1, i);
1027                 list[size].iPixelFormat = size+1; /* The index starts at 1 */
1028                 list[size].fbconfig = cfgs[i];
1029                 list[size].fmt_id = fmt_id;
1030                 list[size].render_type = get_render_type_from_fbconfig(display, cfgs[i]);
1031                 list[size].offscreenOnly = TRUE;
1032                 list[size].dwFlags = 0;
1033                 size++;
1034             }
1035
1036             if (visinfo) XFree(visinfo);
1037         }
1038     }
1039
1040     XFree(cfgs);
1041
1042 done:
1043     if (size_ret) *size_ret = size;
1044     if (onscreen_size_ret) *onscreen_size_ret = onscreen_size;
1045     wine_tsx11_unlock();
1046     return list;
1047 }
1048
1049 /* GLX can advertise dozens of different pixelformats including offscreen and onscreen ones.
1050  * In our WGL implementation we only support a subset of these formats namely the format of
1051  * Wine's main visual and offscreen formats (if they are available).
1052  * This function converts a WGL format to its corresponding GLX one. It returns a WineGLPixelFormat
1053  * and it returns the number of supported WGL formats in fmt_count.
1054  */
1055 static WineGLPixelFormat* ConvertPixelFormatWGLtoGLX(Display *display, int iPixelFormat, BOOL AllowOffscreen, int *fmt_count)
1056 {
1057     WineGLPixelFormat *list, *res = NULL;
1058     int size, onscreen_size;
1059
1060     if (!(list = get_formats(display, &size, &onscreen_size ))) return NULL;
1061
1062     /* Check if the pixelformat is valid. Note that it is legal to pass an invalid
1063      * iPixelFormat in case of probing the number of pixelformats.
1064      */
1065     if((iPixelFormat > 0) && (iPixelFormat <= size) &&
1066        (!list[iPixelFormat-1].offscreenOnly || AllowOffscreen)) {
1067         res = &list[iPixelFormat-1];
1068         TRACE("Returning fmt_id=%#x for iPixelFormat=%d\n", res->fmt_id, iPixelFormat);
1069     }
1070
1071     if(AllowOffscreen)
1072         *fmt_count = size;
1073     else
1074         *fmt_count = onscreen_size;
1075
1076     TRACE("Number of returned pixelformats=%d\n", *fmt_count);
1077
1078     return res;
1079 }
1080
1081 /* Search our internal pixelformat list for the WGL format corresponding to the given fbconfig */
1082 static WineGLPixelFormat* ConvertPixelFormatGLXtoWGL(Display *display, int fmt_id, DWORD dwFlags)
1083 {
1084     WineGLPixelFormat *list;
1085     int i, size;
1086
1087     if (!(list = get_formats(display, &size, NULL ))) return NULL;
1088
1089     for(i=0; i<size; i++) {
1090         /* A GLX format can appear multiple times in the pixel format list due to fake formats for bitmap rendering.
1091          * Fake formats might get selected when the user passes the proper flags using the dwFlags parameter. */
1092         if( (list[i].fmt_id == fmt_id) && ((list[i].dwFlags & dwFlags) == dwFlags) ) {
1093             TRACE("Returning iPixelFormat %d for fmt_id 0x%x\n", list[i].iPixelFormat, fmt_id);
1094             return &list[i];
1095         }
1096     }
1097     TRACE("No compatible format found for fmt_id 0x%x\n", fmt_id);
1098     return NULL;
1099 }
1100
1101 int pixelformat_from_fbconfig_id(XID fbconfig_id)
1102 {
1103     WineGLPixelFormat *fmt;
1104
1105     if (!fbconfig_id) return 0;
1106
1107     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
1108     if(fmt)
1109         return fmt->iPixelFormat;
1110     /* This will happen on hwnds without a pixel format set; it's ok */
1111     return 0;
1112 }
1113
1114
1115 /* Mark any allocated context using the glx drawable 'old' to use 'new' */
1116 void mark_drawable_dirty(Drawable old, Drawable new)
1117 {
1118     Wine_GLContext *ctx;
1119     for (ctx = context_list; ctx; ctx = ctx->next) {
1120         if (old == ctx->drawables[0]) {
1121             ctx->drawables[0] = new;
1122             ctx->refresh_drawables = TRUE;
1123         }
1124         if (old == ctx->drawables[1]) {
1125             ctx->drawables[1] = new;
1126             ctx->refresh_drawables = TRUE;
1127         }
1128     }
1129 }
1130
1131 /* Given the current context, make sure its drawable is sync'd */
1132 static inline void sync_context(Wine_GLContext *context)
1133 {
1134     if(context && context->refresh_drawables) {
1135         if (glxRequireVersion(3))
1136             pglXMakeContextCurrent(gdi_display, context->drawables[0],
1137                                    context->drawables[1], context->ctx);
1138         else
1139             pglXMakeCurrent(gdi_display, context->drawables[0], context->ctx);
1140         context->refresh_drawables = FALSE;
1141     }
1142 }
1143
1144
1145 static GLXContext create_glxcontext(Display *display, Wine_GLContext *context, GLXContext shareList)
1146 {
1147     GLXContext ctx;
1148
1149     /* We use indirect rendering for rendering to bitmaps. See get_formats for a comment about this. */
1150     BOOL indirect = (context->fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? FALSE : TRUE;
1151
1152     if(context->gl3_context)
1153     {
1154         if(context->numAttribs)
1155             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, context->attribList);
1156         else
1157             ctx = pglXCreateContextAttribsARB(gdi_display, context->fmt->fbconfig, shareList, indirect, NULL);
1158     }
1159     else if(context->vis)
1160         ctx = pglXCreateContext(gdi_display, context->vis, shareList, indirect);
1161     else /* Create a GLX Context for a pbuffer */
1162         ctx = pglXCreateNewContext(gdi_display, context->fmt->fbconfig, context->fmt->render_type, shareList, TRUE);
1163
1164     return ctx;
1165 }
1166
1167
1168 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
1169 {
1170     return pglXCreateGLXPixmap(display, vis, parent);
1171 }
1172
1173
1174 static XID create_bitmap_glxpixmap(X11DRV_PDEVICE *physDev, WineGLPixelFormat *fmt)
1175 {
1176     GLXPixmap ret = 0;
1177     XVisualInfo *vis;
1178
1179     wine_tsx11_lock();
1180
1181     vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1182     if(vis) {
1183         if(vis->depth == physDev->bitmap->pixmap_depth)
1184             ret = pglXCreateGLXPixmap(gdi_display, vis, physDev->bitmap->pixmap);
1185         XFree(vis);
1186     }
1187     wine_tsx11_unlock();
1188     TRACE("return %lx\n", ret);
1189     return ret;
1190 }
1191
1192 /**
1193  * X11DRV_ChoosePixelFormat
1194  *
1195  * Equivalent to glXChooseVisual.
1196  */
1197 int CDECL X11DRV_ChoosePixelFormat(X11DRV_PDEVICE *physDev,
1198                              const PIXELFORMATDESCRIPTOR *ppfd) {
1199     WineGLPixelFormat *list;
1200     int onscreen_size;
1201     int ret = 0;
1202     int value = 0;
1203     int i = 0;
1204     int bestFormat = -1;
1205     int bestDBuffer = -1;
1206     int bestStereo = -1;
1207     int bestColor = -1;
1208     int bestAlpha = -1;
1209     int bestDepth = -1;
1210     int bestStencil = -1;
1211     int bestAux = -1;
1212
1213     if (!has_opengl()) return 0;
1214
1215     if (TRACE_ON(wgl)) {
1216         TRACE("(%p,%p)\n", physDev, ppfd);
1217
1218         dump_PIXELFORMATDESCRIPTOR(ppfd);
1219     }
1220
1221     if (!(list = get_formats(gdi_display, NULL, &onscreen_size ))) return 0;
1222
1223     wine_tsx11_lock();
1224     for(i=0; i<onscreen_size; i++)
1225     {
1226         int dwFlags = 0;
1227         int iPixelType = 0;
1228         int alpha=0, color=0, depth=0, stencil=0, aux=0;
1229         WineGLPixelFormat *fmt = &list[i];
1230
1231         /* Pixel type */
1232         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1233         if (value & GLX_RGBA_BIT)
1234             iPixelType = PFD_TYPE_RGBA;
1235         else
1236             iPixelType = PFD_TYPE_COLORINDEX;
1237
1238         if (ppfd->iPixelType != iPixelType)
1239         {
1240             TRACE("pixel type mismatch for iPixelFormat=%d\n", i+1);
1241             continue;
1242         }
1243
1244         /* Only use bitmap capable for formats for bitmap rendering.
1245          * See get_formats for more info. */
1246         if( (ppfd->dwFlags & PFD_DRAW_TO_BITMAP) != (fmt->dwFlags & PFD_DRAW_TO_BITMAP))
1247         {
1248             TRACE("PFD_DRAW_TO_BITMAP mismatch for iPixelFormat=%d\n", i+1);
1249             continue;
1250         }
1251
1252         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1253         if (value) dwFlags |= PFD_DOUBLEBUFFER;
1254         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value);
1255         if (value) dwFlags |= PFD_STEREO;
1256         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &color); /* cColorBits */
1257         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &alpha); /* cAlphaBits */
1258         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &depth); /* cDepthBits */
1259         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &stencil); /* cStencilBits */
1260         pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &aux); /* cAuxBuffers */
1261
1262         /* The behavior of PDF_STEREO/PFD_STEREO_DONTCARE and PFD_DOUBLEBUFFER / PFD_DOUBLEBUFFER_DONTCARE
1263          * is not very clear on MSDN. They specify that ChoosePixelFormat tries to match pixel formats
1264          * with the flag (PFD_STEREO / PFD_DOUBLEBUFFERING) set. Otherwise it says that it tries to match
1265          * formats without the given flag set.
1266          * A test on Windows using a Radeon 9500pro on WinXP (the driver doesn't support Stereo)
1267          * has indicated that a format without stereo is returned when stereo is unavailable.
1268          * So in case PFD_STEREO is set, formats that support it should have priority above formats
1269          * without. In case PFD_STEREO_DONTCARE is set, stereo is ignored.
1270          *
1271          * To summarize the following is most likely the correct behavior:
1272          * stereo not set -> prefer no-stereo formats, else also accept stereo formats
1273          * stereo set -> prefer stereo formats, else also accept no-stereo formats
1274          * stereo don't care -> it doesn't matter whether we get stereo or not
1275          *
1276          * In Wine we will treat no-stereo the same way as don't care because it makes
1277          * format selection even more complicated and second drivers with Stereo advertise
1278          * each format twice anyway.
1279          */
1280
1281         /* Doublebuffer, see the comments above */
1282         if( !(ppfd->dwFlags & PFD_DOUBLEBUFFER_DONTCARE) ) {
1283             if( ((ppfd->dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer) &&
1284                 ((dwFlags & PFD_DOUBLEBUFFER) == (ppfd->dwFlags & PFD_DOUBLEBUFFER)) )
1285             {
1286                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1287                 bestStereo = dwFlags & PFD_STEREO;
1288                 bestAlpha = alpha;
1289                 bestColor = color;
1290                 bestDepth = depth;
1291                 bestStencil = stencil;
1292                 bestAux = aux;
1293                 bestFormat = i;
1294                 continue;
1295             }
1296             if(bestDBuffer != -1 && (dwFlags & PFD_DOUBLEBUFFER) != bestDBuffer)
1297                 continue;
1298         }
1299
1300         /* Stereo, see the comments above. */
1301         if( !(ppfd->dwFlags & PFD_STEREO_DONTCARE) ) {
1302             if( ((ppfd->dwFlags & PFD_STEREO) != bestStereo) &&
1303                 ((dwFlags & PFD_STEREO) == (ppfd->dwFlags & PFD_STEREO)) )
1304             {
1305                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1306                 bestStereo = dwFlags & PFD_STEREO;
1307                 bestAlpha = alpha;
1308                 bestColor = color;
1309                 bestDepth = depth;
1310                 bestStencil = stencil;
1311                 bestAux = aux;
1312                 bestFormat = i;
1313                 continue;
1314             }
1315             if(bestStereo != -1 && (dwFlags & PFD_STEREO) != bestStereo)
1316                 continue;
1317         }
1318
1319         /* Below we will do a number of checks to select the 'best' pixelformat.
1320          * We assume the precedence cColorBits > cAlphaBits > cDepthBits > cStencilBits -> cAuxBuffers.
1321          * The code works by trying to match the most important options as close as possible.
1322          * When a reasonable format is found, we will try to match more options.
1323          * It appears (see the opengl32 test) that Windows opengl drivers ignore options
1324          * like cColorBits, cAlphaBits and friends if they are set to 0, so they are considered
1325          * as DONTCARE. At least Serious Sam TSE relies on this behavior. */
1326
1327         /* Color bits */
1328         if(ppfd->cColorBits) {
1329             if( ((ppfd->cColorBits > bestColor) && (color > bestColor)) ||
1330                 ((color >= ppfd->cColorBits) && (color < bestColor)) )
1331             {
1332                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1333                 bestStereo = dwFlags & PFD_STEREO;
1334                 bestAlpha = alpha;
1335                 bestColor = color;
1336                 bestDepth = depth;
1337                 bestStencil = stencil;
1338                 bestAux = aux;
1339                 bestFormat = i;
1340                 continue;
1341             } else if(bestColor != color) {  /* Do further checks if the format is compatible */
1342                 TRACE("color mismatch for iPixelFormat=%d\n", i+1);
1343                 continue;
1344             }
1345         }
1346
1347         /* Alpha bits */
1348         if(ppfd->cAlphaBits) {
1349             if( ((ppfd->cAlphaBits > bestAlpha) && (alpha > bestAlpha)) ||
1350                 ((alpha >= ppfd->cAlphaBits) && (alpha < bestAlpha)) )
1351             {
1352                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1353                 bestStereo = dwFlags & PFD_STEREO;
1354                 bestAlpha = alpha;
1355                 bestColor = color;
1356                 bestDepth = depth;
1357                 bestStencil = stencil;
1358                 bestAux = aux;
1359                 bestFormat = i;
1360                 continue;
1361             } else if(bestAlpha != alpha) {
1362                 TRACE("alpha mismatch for iPixelFormat=%d\n", i+1);
1363                 continue;
1364             }
1365         }
1366
1367         /* Depth bits */
1368         if(ppfd->cDepthBits) {
1369             if( ((ppfd->cDepthBits > bestDepth) && (depth > bestDepth)) ||
1370                 ((depth >= ppfd->cDepthBits) && (depth < bestDepth)) )
1371             {
1372                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1373                 bestStereo = dwFlags & PFD_STEREO;
1374                 bestAlpha = alpha;
1375                 bestColor = color;
1376                 bestDepth = depth;
1377                 bestStencil = stencil;
1378                 bestAux = aux;
1379                 bestFormat = i;
1380                 continue;
1381             } else if(bestDepth != depth) {
1382                 TRACE("depth mismatch for iPixelFormat=%d\n", i+1);
1383                 continue;
1384             }
1385         }
1386
1387         /* Stencil bits */
1388         if(ppfd->cStencilBits) {
1389             if( ((ppfd->cStencilBits > bestStencil) && (stencil > bestStencil)) ||
1390                 ((stencil >= ppfd->cStencilBits) && (stencil < bestStencil)) )
1391             {
1392                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1393                 bestStereo = dwFlags & PFD_STEREO;
1394                 bestAlpha = alpha;
1395                 bestColor = color;
1396                 bestDepth = depth;
1397                 bestStencil = stencil;
1398                 bestAux = aux;
1399                 bestFormat = i;
1400                 continue;
1401             } else if(bestStencil != stencil) {
1402                 TRACE("stencil mismatch for iPixelFormat=%d\n", i+1);
1403                 continue;
1404             }
1405         }
1406
1407         /* Aux buffers */
1408         if(ppfd->cAuxBuffers) {
1409             if( ((ppfd->cAuxBuffers > bestAux) && (aux > bestAux)) ||
1410                 ((aux >= ppfd->cAuxBuffers) && (aux < bestAux)) )
1411             {
1412                 bestDBuffer = dwFlags & PFD_DOUBLEBUFFER;
1413                 bestStereo = dwFlags & PFD_STEREO;
1414                 bestAlpha = alpha;
1415                 bestColor = color;
1416                 bestDepth = depth;
1417                 bestStencil = stencil;
1418                 bestAux = aux;
1419                 bestFormat = i;
1420                 continue;
1421             } else if(bestAux != aux) {
1422                 TRACE("aux mismatch for iPixelFormat=%d\n", i+1);
1423                 continue;
1424             }
1425         }
1426     }
1427
1428     if(bestFormat == -1) {
1429         TRACE("No matching mode was found returning 0\n");
1430         ret = 0;
1431     }
1432     else {
1433         ret = bestFormat+1; /* the return value should be a 1-based index */
1434         TRACE("Successfully found a matching mode, returning index: %d %x\n", ret, list[bestFormat].fmt_id);
1435     }
1436
1437     wine_tsx11_unlock();
1438
1439     return ret;
1440 }
1441 /**
1442  * X11DRV_DescribePixelFormat
1443  *
1444  * Get the pixel-format descriptor associated to the given id
1445  */
1446 int CDECL X11DRV_DescribePixelFormat(X11DRV_PDEVICE *physDev,
1447                                int iPixelFormat,
1448                                UINT nBytes,
1449                                PIXELFORMATDESCRIPTOR *ppfd) {
1450   /*XVisualInfo *vis;*/
1451   int value;
1452   int rb,gb,bb,ab;
1453   WineGLPixelFormat *fmt;
1454   int ret = 0;
1455   int fmt_count = 0;
1456
1457   if (!has_opengl()) return 0;
1458
1459   TRACE("(%p,%d,%d,%p)\n", physDev, iPixelFormat, nBytes, ppfd);
1460
1461   /* Look for the iPixelFormat in our list of supported formats. If it is supported we get the index in the FBConfig table and the number of supported formats back */
1462   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &fmt_count);
1463   if (ppfd == NULL) {
1464       /* The application is only querying the number of pixelformats */
1465       return fmt_count;
1466   } else if(fmt == NULL) {
1467       WARN("unexpected iPixelFormat(%d): not >=1 and <=nFormats(%d), returning NULL!\n", iPixelFormat, fmt_count);
1468       return 0;
1469   }
1470
1471   if (nBytes < sizeof(PIXELFORMATDESCRIPTOR)) {
1472     ERR("Wrong structure size !\n");
1473     /* Should set error */
1474     return 0;
1475   }
1476
1477   ret = fmt_count;
1478
1479   memset(ppfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
1480   ppfd->nSize = sizeof(PIXELFORMATDESCRIPTOR);
1481   ppfd->nVersion = 1;
1482
1483   /* These flags are always the same... */
1484   ppfd->dwFlags = PFD_SUPPORT_OPENGL;
1485   /* Now the flags extracted from the Visual */
1486
1487   wine_tsx11_lock();
1488
1489   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1490   if(value & GLX_WINDOW_BIT)
1491       ppfd->dwFlags |= PFD_DRAW_TO_WINDOW;
1492
1493   /* On Windows bitmap rendering is only offered using the GDI Software renderer. We reserve some formats (see get_formats for more info)
1494    * for bitmap rendering since we require indirect rendering for this. Further pixel format logs of a GeforceFX, Geforce8800GT, Radeon HD3400 and a
1495    * Radeon 9000 indicated that all bitmap formats have PFD_SUPPORT_GDI. Except for 2 formats on the Radeon 9000 none of the hw accelerated formats
1496    * offered the GDI bit either. */
1497   ppfd->dwFlags |= fmt->dwFlags & (PFD_DRAW_TO_BITMAP | PFD_SUPPORT_GDI);
1498
1499   /* PFD_GENERIC_FORMAT - gdi software rendering
1500    * PFD_GENERIC_ACCELERATED - some parts are accelerated by a display driver (MCD e.g. 3dfx minigl)
1501    * none set - full hardware accelerated by a ICD
1502    *
1503    * We only set PFD_GENERIC_FORMAT on bitmap formats (see get_formats) as that's what ATI and Nvidia Windows drivers do  */
1504   ppfd->dwFlags |= fmt->dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED);
1505
1506   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DOUBLEBUFFER, &value);
1507   if (value) {
1508       ppfd->dwFlags |= PFD_DOUBLEBUFFER;
1509       ppfd->dwFlags &= ~PFD_SUPPORT_GDI;
1510   }
1511   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STEREO, &value); if (value) ppfd->dwFlags |= PFD_STEREO;
1512
1513   /* Pixel type */
1514   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RENDER_TYPE, &value);
1515   if (value & GLX_RGBA_BIT)
1516     ppfd->iPixelType = PFD_TYPE_RGBA;
1517   else
1518     ppfd->iPixelType = PFD_TYPE_COLORINDEX;
1519
1520   /* Color bits */
1521   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BUFFER_SIZE, &value);
1522   ppfd->cColorBits = value;
1523
1524   /* Red, green, blue and alpha bits / shifts */
1525   if (ppfd->iPixelType == PFD_TYPE_RGBA) {
1526     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_RED_SIZE, &rb);
1527     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_GREEN_SIZE, &gb);
1528     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_BLUE_SIZE, &bb);
1529     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ALPHA_SIZE, &ab);
1530
1531     ppfd->cRedBits = rb;
1532     ppfd->cRedShift = gb + bb + ab;
1533     ppfd->cBlueBits = bb;
1534     ppfd->cBlueShift = ab;
1535     ppfd->cGreenBits = gb;
1536     ppfd->cGreenShift = bb + ab;
1537     ppfd->cAlphaBits = ab;
1538     ppfd->cAlphaShift = 0;
1539   } else {
1540     ppfd->cRedBits = 0;
1541     ppfd->cRedShift = 0;
1542     ppfd->cBlueBits = 0;
1543     ppfd->cBlueShift = 0;
1544     ppfd->cGreenBits = 0;
1545     ppfd->cGreenShift = 0;
1546     ppfd->cAlphaBits = 0;
1547     ppfd->cAlphaShift = 0;
1548   }
1549
1550   /* Accum RGBA bits */
1551   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &rb);
1552   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &gb);
1553   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &bb);
1554   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &ab);
1555
1556   ppfd->cAccumBits = rb+gb+bb+ab;
1557   ppfd->cAccumRedBits = rb;
1558   ppfd->cAccumGreenBits = gb;
1559   ppfd->cAccumBlueBits = bb;
1560   ppfd->cAccumAlphaBits = ab;
1561
1562   /* Aux bits */
1563   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_AUX_BUFFERS, &value);
1564   ppfd->cAuxBuffers = value;
1565
1566   /* Depth bits */
1567   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DEPTH_SIZE, &value);
1568   ppfd->cDepthBits = value;
1569
1570   /* stencil bits */
1571   pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_STENCIL_SIZE, &value);
1572   ppfd->cStencilBits = value;
1573
1574   wine_tsx11_unlock();
1575
1576   ppfd->iLayerType = PFD_MAIN_PLANE;
1577
1578   if (TRACE_ON(wgl)) {
1579     dump_PIXELFORMATDESCRIPTOR(ppfd);
1580   }
1581
1582   return ret;
1583 }
1584
1585 /**
1586  * X11DRV_GetPixelFormat
1587  *
1588  * Get the pixel-format id used by this DC
1589  */
1590 int CDECL X11DRV_GetPixelFormat(X11DRV_PDEVICE *physDev) {
1591   WineGLPixelFormat *fmt;
1592   int tmp;
1593   TRACE("(%p)\n", physDev);
1594
1595   if (!physDev->current_pf) return 0;  /* not set yet */
1596
1597   fmt = ConvertPixelFormatWGLtoGLX(gdi_display, physDev->current_pf, TRUE, &tmp);
1598   if(!fmt)
1599   {
1600     ERR("Unable to find a WineGLPixelFormat for iPixelFormat=%d\n", physDev->current_pf);
1601     return 0;
1602   }
1603   else if(fmt->offscreenOnly)
1604   {
1605     /* Offscreen formats can't be used with traditional WGL calls.
1606      * As has been verified on Windows GetPixelFormat doesn't fail but returns iPixelFormat=1. */
1607      TRACE("Returning iPixelFormat=1 for offscreen format: %d\n", fmt->iPixelFormat);
1608     return 1;
1609   }
1610
1611   TRACE("(%p): returns %d\n", physDev, physDev->current_pf);
1612   return physDev->current_pf;
1613 }
1614
1615 /* This function is the core of X11DRV_SetPixelFormat and X11DRV_SetPixelFormatWINE.
1616  * Both functions are the same except that X11DRV_SetPixelFormatWINE allows you to
1617  * set the pixel format multiple times. */
1618 static BOOL internal_SetPixelFormat(X11DRV_PDEVICE *physDev,
1619                            int iPixelFormat,
1620                            const PIXELFORMATDESCRIPTOR *ppfd) {
1621     WineGLPixelFormat *fmt;
1622     int value;
1623     HWND hwnd;
1624
1625     /* SetPixelFormat is not allowed on the X root_window e.g. GetDC(0) */
1626     if(get_glxdrawable(physDev) == root_window)
1627     {
1628         ERR("Invalid operation on root_window\n");
1629         return FALSE;
1630     }
1631
1632     /* Check if iPixelFormat is in our list of supported formats to see if it is supported. */
1633     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, FALSE /* Offscreen */, &value);
1634     if(!fmt) {
1635         ERR("Invalid iPixelFormat: %d\n", iPixelFormat);
1636         return FALSE;
1637     }
1638
1639     wine_tsx11_lock();
1640     pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1641     wine_tsx11_unlock();
1642
1643     hwnd = WindowFromDC(physDev->hdc);
1644     if(hwnd) {
1645         if(!(value&GLX_WINDOW_BIT)) {
1646             WARN("Pixel format %d is not compatible for window rendering\n", iPixelFormat);
1647             return FALSE;
1648         }
1649
1650         if(!SendMessageW(hwnd, WM_X11DRV_SET_WIN_FORMAT, fmt->fmt_id, 0)) {
1651             ERR("Couldn't set format of the window, returning failure\n");
1652             return FALSE;
1653         }
1654     }
1655     else if(physDev->bitmap) {
1656         if(!(value&GLX_PIXMAP_BIT)) {
1657             WARN("Pixel format %d is not compatible for bitmap rendering\n", iPixelFormat);
1658             return FALSE;
1659         }
1660
1661         physDev->bitmap->glxpixmap = create_bitmap_glxpixmap(physDev, fmt);
1662         if(!physDev->bitmap->glxpixmap) {
1663             WARN("Couldn't create glxpixmap for pixel format %d\n", iPixelFormat);
1664             return FALSE;
1665         }
1666     }
1667     else {
1668         FIXME("called on a non-window, non-bitmap object?\n");
1669     }
1670
1671     physDev->current_pf = iPixelFormat;
1672
1673     if (TRACE_ON(wgl)) {
1674         int gl_test = 0;
1675
1676         wine_tsx11_lock();
1677         gl_test = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_FBCONFIG_ID, &value);
1678         if (gl_test) {
1679            ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
1680         } else {
1681             TRACE(" FBConfig have :\n");
1682             TRACE(" - FBCONFIG_ID   0x%x\n", value);
1683             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_VISUAL_ID, &value);
1684             TRACE(" - VISUAL_ID     0x%x\n", value);
1685             pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &value);
1686             TRACE(" - DRAWABLE_TYPE 0x%x\n", value);
1687         }
1688         wine_tsx11_unlock();
1689     }
1690     return TRUE;
1691 }
1692
1693
1694 /**
1695  * X11DRV_SetPixelFormat
1696  *
1697  * Set the pixel-format id used by this DC
1698  */
1699 BOOL CDECL X11DRV_SetPixelFormat(X11DRV_PDEVICE *physDev,
1700                            int iPixelFormat,
1701                            const PIXELFORMATDESCRIPTOR *ppfd) {
1702     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
1703
1704     if (!has_opengl()) return FALSE;
1705
1706     if(physDev->current_pf)  /* cannot change it if already set */
1707         return (physDev->current_pf == iPixelFormat);
1708
1709     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
1710 }
1711
1712 /**
1713  * X11DRV_wglCopyContext
1714  *
1715  * For OpenGL32 wglCopyContext.
1716  */
1717 BOOL CDECL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask) {
1718     Wine_GLContext *src = (Wine_GLContext*)hglrcSrc;
1719     Wine_GLContext *dst = (Wine_GLContext*)hglrcDst;
1720
1721     TRACE("hglrcSrc: (%p), hglrcDst: (%p), mask: %#x\n", hglrcSrc, hglrcDst, mask);
1722
1723     wine_tsx11_lock();
1724     pglXCopyContext(gdi_display, src->ctx, dst->ctx, mask);
1725     wine_tsx11_unlock();
1726
1727     /* As opposed to wglCopyContext, glXCopyContext doesn't return anything, so hopefully we passed */
1728     return TRUE;
1729 }
1730
1731 /**
1732  * X11DRV_wglCreateContext
1733  *
1734  * For OpenGL32 wglCreateContext.
1735  */
1736 HGLRC CDECL X11DRV_wglCreateContext(X11DRV_PDEVICE *physDev)
1737 {
1738     Wine_GLContext *ret;
1739     WineGLPixelFormat *fmt;
1740     int hdcPF = physDev->current_pf;
1741     int fmt_count = 0;
1742     HDC hdc = physDev->hdc;
1743
1744     TRACE("(%p)->(PF:%d)\n", hdc, hdcPF);
1745
1746     if (!has_opengl()) return 0;
1747
1748     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
1749     /* We can render using the iPixelFormat (1) of Wine's Main visual AND using some offscreen formats.
1750      * Note that standard WGL-calls don't recognize offscreen-only formats. For that reason pbuffers
1751      * use a sort of 'proxy' HDC (wglGetPbufferDCARB).
1752      * If this fails something is very wrong on the system. */
1753     if(!fmt) {
1754         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
1755         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
1756         return NULL;
1757     }
1758
1759     wine_tsx11_lock();
1760     ret = alloc_context();
1761     ret->hdc = hdc;
1762     ret->fmt = fmt;
1763     ret->has_been_current = FALSE;
1764     ret->sharing = FALSE;
1765
1766     ret->vis = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
1767     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
1768     wine_tsx11_unlock();
1769
1770     TRACE(" creating context %p (GL context creation delayed)\n", ret);
1771     return (HGLRC) ret;
1772 }
1773
1774 /**
1775  * X11DRV_wglDeleteContext
1776  *
1777  * For OpenGL32 wglDeleteContext.
1778  */
1779 BOOL CDECL X11DRV_wglDeleteContext(HGLRC hglrc)
1780 {
1781     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1782
1783     TRACE("(%p)\n", hglrc);
1784
1785     if (!has_opengl()) return 0;
1786
1787     if (!is_valid_context(ctx))
1788     {
1789         WARN("Error deleting context !\n");
1790         SetLastError(ERROR_INVALID_HANDLE);
1791         return FALSE;
1792     }
1793
1794     /* WGL doesn't allow deletion of a context which is current in another thread */
1795     if (ctx->tid != 0 && ctx->tid != GetCurrentThreadId())
1796     {
1797         TRACE("Cannot delete context=%p because it is current in another thread.\n", ctx);
1798         SetLastError(ERROR_BUSY);
1799         return FALSE;
1800     }
1801
1802     /* WGL makes a context not current if it is active before deletion. GLX waits until the context is not current. */
1803     if (ctx == NtCurrentTeb()->glContext)
1804         wglMakeCurrent(ctx->hdc, NULL);
1805
1806     if (ctx->ctx)
1807     {
1808         wine_tsx11_lock();
1809         pglXDestroyContext(gdi_display, ctx->ctx);
1810         wine_tsx11_unlock();
1811     }
1812
1813     free_context(ctx);
1814     return TRUE;
1815 }
1816
1817 /**
1818  * X11DRV_wglGetCurrentReadDCARB
1819  *
1820  * For OpenGL32 wglGetCurrentReadDCARB.
1821  */
1822 static HDC WINAPI X11DRV_wglGetCurrentReadDCARB(void) 
1823 {
1824     HDC ret = 0;
1825     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
1826
1827     if (ctx) ret = ctx->read_hdc;
1828
1829     TRACE(" returning %p (GL drawable %lu)\n", ret, ctx ? ctx->drawables[1] : 0);
1830     return ret;
1831 }
1832
1833 /**
1834  * X11DRV_wglGetProcAddress
1835  *
1836  * For OpenGL32 wglGetProcAddress.
1837  */
1838 PROC CDECL X11DRV_wglGetProcAddress(LPCSTR lpszProc)
1839 {
1840     int i, j;
1841     const WineGLExtension *ext;
1842
1843     int padding = 32 - strlen(lpszProc);
1844     if (padding < 0)
1845         padding = 0;
1846
1847     if (!has_opengl()) return NULL;
1848
1849     /* Check the table of WGL extensions to see if we need to return a WGL extension
1850      * or a function pointer to a native OpenGL function. */
1851     if(strncmp(lpszProc, "wgl", 3) != 0) {
1852         return pglXGetProcAddressARB((const GLubyte*)lpszProc);
1853     } else {
1854         TRACE("('%s'):%*s", lpszProc, padding, " ");
1855         for (i = 0; i < WineGLExtensionListSize; ++i) {
1856             ext = WineGLExtensionList[i];
1857             for (j = 0; ext->extEntryPoints[j].funcName; ++j) {
1858                 if (strcmp(ext->extEntryPoints[j].funcName, lpszProc) == 0) {
1859                     TRACE("(%p) - WineGL\n", ext->extEntryPoints[j].funcAddress);
1860                     return ext->extEntryPoints[j].funcAddress;
1861                 }
1862             }
1863         }
1864     }
1865
1866     WARN("(%s) - not found\n", lpszProc);
1867     return NULL;
1868 }
1869
1870 /**
1871  * X11DRV_wglMakeCurrent
1872  *
1873  * For OpenGL32 wglMakeCurrent.
1874  */
1875 BOOL CDECL X11DRV_wglMakeCurrent(X11DRV_PDEVICE *physDev, HGLRC hglrc) {
1876     BOOL ret;
1877     HDC hdc = physDev->hdc;
1878     DWORD type = GetObjectType(hdc);
1879     Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1880
1881     TRACE("(%p,%p)\n", hdc, hglrc);
1882
1883     if (!has_opengl()) return FALSE;
1884
1885     wine_tsx11_lock();
1886     if (hglrc == NULL)
1887     {
1888         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1889         if (prev_ctx) prev_ctx->tid = 0;
1890
1891         ret = pglXMakeCurrent(gdi_display, None, NULL);
1892         NtCurrentTeb()->glContext = NULL;
1893     }
1894     else if (ctx->fmt->iPixelFormat != physDev->current_pf)
1895     {
1896         WARN( "mismatched pixel format hdc %p %u ctx %p %u\n",
1897               hdc, physDev->current_pf, ctx, ctx->fmt->iPixelFormat );
1898         SetLastError( ERROR_INVALID_PIXEL_FORMAT );
1899         ret = FALSE;
1900     }
1901     else
1902     {
1903         Drawable drawable = get_glxdrawable(physDev);
1904         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1905         if (prev_ctx) prev_ctx->tid = 0;
1906
1907         /* The describe lines below are for debugging purposes only */
1908         if (TRACE_ON(wgl)) {
1909             describeDrawable(physDev);
1910             describeContext(ctx);
1911         }
1912
1913         TRACE(" make current for dis %p, drawable %p, ctx %p\n", gdi_display, (void*) drawable, ctx->ctx);
1914         ret = pglXMakeCurrent(gdi_display, drawable, ctx->ctx);
1915         NtCurrentTeb()->glContext = ctx;
1916
1917         if(ret)
1918         {
1919             ctx->has_been_current = TRUE;
1920             ctx->tid = GetCurrentThreadId();
1921             ctx->hdc = hdc;
1922             ctx->read_hdc = hdc;
1923             ctx->drawables[0] = drawable;
1924             ctx->drawables[1] = drawable;
1925             ctx->refresh_drawables = FALSE;
1926
1927             if (type == OBJ_MEMDC)
1928             {
1929                 ctx->do_escape = TRUE;
1930                 pglDrawBuffer(GL_FRONT_LEFT);
1931             }
1932         }
1933     }
1934     wine_tsx11_unlock();
1935     TRACE(" returning %s\n", (ret ? "True" : "False"));
1936     return ret;
1937 }
1938
1939 /**
1940  * X11DRV_wglMakeContextCurrentARB
1941  *
1942  * For OpenGL32 wglMakeContextCurrentARB
1943  */
1944 BOOL CDECL X11DRV_wglMakeContextCurrentARB(X11DRV_PDEVICE* pDrawDev, X11DRV_PDEVICE* pReadDev, HGLRC hglrc)
1945 {
1946     BOOL ret;
1947
1948     TRACE("(%p,%p,%p)\n", pDrawDev, pReadDev, hglrc);
1949
1950     if (!has_opengl()) return 0;
1951
1952     wine_tsx11_lock();
1953     if (hglrc == NULL)
1954     {
1955         Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1956         if (prev_ctx) prev_ctx->tid = 0;
1957
1958         ret = pglXMakeCurrent(gdi_display, None, NULL);
1959         NtCurrentTeb()->glContext = NULL;
1960     }
1961     else
1962     {
1963         if (NULL == pglXMakeContextCurrent) {
1964             ret = FALSE;
1965         } else {
1966             Wine_GLContext *prev_ctx = NtCurrentTeb()->glContext;
1967             Wine_GLContext *ctx = (Wine_GLContext *) hglrc;
1968             Drawable d_draw = get_glxdrawable(pDrawDev);
1969             Drawable d_read = get_glxdrawable(pReadDev);
1970
1971             if (prev_ctx) prev_ctx->tid = 0;
1972
1973             ctx->has_been_current = TRUE;
1974             ctx->tid = GetCurrentThreadId();
1975             ctx->hdc = pDrawDev->hdc;
1976             ctx->read_hdc = pReadDev->hdc;
1977             ctx->drawables[0] = d_draw;
1978             ctx->drawables[1] = d_read;
1979             ctx->refresh_drawables = FALSE;
1980             ret = pglXMakeContextCurrent(gdi_display, d_draw, d_read, ctx->ctx);
1981             NtCurrentTeb()->glContext = ctx;
1982         }
1983     }
1984     wine_tsx11_unlock();
1985
1986     TRACE(" returning %s\n", (ret ? "True" : "False"));
1987     return ret;
1988 }
1989
1990 /**
1991  * X11DRV_wglShareLists
1992  *
1993  * For OpenGL32 wglShareLists.
1994  */
1995 BOOL CDECL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2) {
1996     Wine_GLContext *org  = (Wine_GLContext *) hglrc1;
1997     Wine_GLContext *dest = (Wine_GLContext *) hglrc2;
1998
1999     TRACE("(%p, %p)\n", org, dest);
2000
2001     if (!has_opengl()) return FALSE;
2002
2003     /* Sharing of display lists works differently in GLX and WGL. In case of GLX it is done
2004      * at context creation time but in case of WGL it is done using wglShareLists.
2005      * In the past we tried to emulate wglShareLists by delaying GLX context creation until
2006      * either a wglMakeCurrent or wglShareLists. This worked fine for most apps but it causes
2007      * issues for OpenGL 3 because there wglCreateContextAttribsARB can fail in a lot of cases,
2008      * so there delaying context creation doesn't work.
2009      *
2010      * The new approach is to create a GLX context in wglCreateContext / wglCreateContextAttribsARB
2011      * and when a program requests sharing we recreate the destination context if it hasn't been made
2012      * current or when it hasn't shared display lists before.
2013      */
2014
2015     if((org->has_been_current && dest->has_been_current) || dest->has_been_current)
2016     {
2017         ERR("Could not share display lists, one of the contexts has been current already !\n");
2018         return FALSE;
2019     }
2020     else if(dest->sharing)
2021     {
2022         ERR("Could not share display lists because hglrc2 has already shared lists before\n");
2023         return FALSE;
2024     }
2025     else
2026     {
2027         if((GetObjectType(org->hdc) == OBJ_MEMDC) ^ (GetObjectType(dest->hdc) == OBJ_MEMDC))
2028         {
2029             WARN("Attempting to share a context between a direct and indirect rendering context, expect issues!\n");
2030         }
2031
2032         wine_tsx11_lock();
2033         describeContext(org);
2034         describeContext(dest);
2035
2036         /* Re-create the GLX context and share display lists */
2037         pglXDestroyContext(gdi_display, dest->ctx);
2038         dest->ctx = create_glxcontext(gdi_display, dest, org->ctx);
2039         wine_tsx11_unlock();
2040         TRACE(" re-created an OpenGL context (%p) for Wine context %p sharing lists with OpenGL ctx %p\n", dest->ctx, dest, org->ctx);
2041
2042         org->sharing = TRUE;
2043         dest->sharing = TRUE;
2044         return TRUE;
2045     }
2046     return FALSE;
2047 }
2048
2049 static BOOL internal_wglUseFontBitmaps(HDC hdc, DWORD first, DWORD count, DWORD listBase, DWORD (WINAPI *GetGlyphOutline_ptr)(HDC,UINT,UINT,LPGLYPHMETRICS,DWORD,LPVOID,const MAT2*))
2050 {
2051      /* We are running using client-side rendering fonts... */
2052      GLYPHMETRICS gm;
2053      unsigned int glyph, size = 0;
2054      void *bitmap = NULL, *gl_bitmap = NULL;
2055      int org_alignment;
2056
2057      wine_tsx11_lock();
2058      pglGetIntegerv(GL_UNPACK_ALIGNMENT, &org_alignment);
2059      pglPixelStorei(GL_UNPACK_ALIGNMENT, 4);
2060      wine_tsx11_unlock();
2061
2062      for (glyph = first; glyph < first + count; glyph++) {
2063          static const MAT2 identity = { {0,1},{0,0},{0,0},{0,1} };
2064          unsigned int needed_size = GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, 0, NULL, &identity);
2065          unsigned int height, width_int;
2066
2067          TRACE("Glyph : %3d / List : %d\n", glyph, listBase);
2068          if (needed_size == GDI_ERROR) {
2069              TRACE("  - needed size : %d (GDI_ERROR)\n", needed_size);
2070              goto error;
2071          } else {
2072              TRACE("  - needed size : %d\n", needed_size);
2073          }
2074
2075          if (needed_size > size) {
2076              size = needed_size;
2077              HeapFree(GetProcessHeap(), 0, bitmap);
2078              HeapFree(GetProcessHeap(), 0, gl_bitmap);
2079              bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2080              gl_bitmap = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size);
2081          }
2082          if (GetGlyphOutline_ptr(hdc, glyph, GGO_BITMAP, &gm, size, bitmap, &identity) == GDI_ERROR)
2083              goto error;
2084          if (TRACE_ON(wgl)) {
2085              unsigned int height, width, bitmask;
2086              unsigned char *bitmap_ = bitmap;
2087
2088              TRACE("  - bbox : %d x %d\n", gm.gmBlackBoxX, gm.gmBlackBoxY);
2089              TRACE("  - origin : (%d , %d)\n", gm.gmptGlyphOrigin.x, gm.gmptGlyphOrigin.y);
2090              TRACE("  - increment : %d - %d\n", gm.gmCellIncX, gm.gmCellIncY);
2091              if (needed_size != 0) {
2092                  TRACE("  - bitmap :\n");
2093                  for (height = 0; height < gm.gmBlackBoxY; height++) {
2094                      TRACE("      ");
2095                      for (width = 0, bitmask = 0x80; width < gm.gmBlackBoxX; width++, bitmask >>= 1) {
2096                          if (bitmask == 0) {
2097                              bitmap_ += 1;
2098                              bitmask = 0x80;
2099                          }
2100                          if (*bitmap_ & bitmask)
2101                              TRACE("*");
2102                          else
2103                              TRACE(" ");
2104                      }
2105                      bitmap_ += (4 - ((UINT_PTR)bitmap_ & 0x03));
2106                      TRACE("\n");
2107                  }
2108              }
2109          }
2110
2111          /* In OpenGL, the bitmap is drawn from the bottom to the top... So we need to invert the
2112          * glyph for it to be drawn properly.
2113          */
2114          if (needed_size != 0) {
2115              width_int = (gm.gmBlackBoxX + 31) / 32;
2116              for (height = 0; height < gm.gmBlackBoxY; height++) {
2117                  unsigned int width;
2118                  for (width = 0; width < width_int; width++) {
2119                      ((int *) gl_bitmap)[(gm.gmBlackBoxY - height - 1) * width_int + width] =
2120                      ((int *) bitmap)[height * width_int + width];
2121                  }
2122              }
2123          }
2124
2125          wine_tsx11_lock();
2126          pglNewList(listBase++, GL_COMPILE);
2127          if (needed_size != 0) {
2128              pglBitmap(gm.gmBlackBoxX, gm.gmBlackBoxY,
2129                      0 - gm.gmptGlyphOrigin.x, (int) gm.gmBlackBoxY - gm.gmptGlyphOrigin.y,
2130                      gm.gmCellIncX, gm.gmCellIncY,
2131                      gl_bitmap);
2132          } else {
2133              /* This is the case of 'empty' glyphs like the space character */
2134              pglBitmap(0, 0, 0, 0, gm.gmCellIncX, gm.gmCellIncY, NULL);
2135          }
2136          pglEndList();
2137          wine_tsx11_unlock();
2138      }
2139
2140      wine_tsx11_lock();
2141      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2142      wine_tsx11_unlock();
2143
2144      HeapFree(GetProcessHeap(), 0, bitmap);
2145      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2146      return TRUE;
2147
2148   error:
2149      wine_tsx11_lock();
2150      pglPixelStorei(GL_UNPACK_ALIGNMENT, org_alignment);
2151      wine_tsx11_unlock();
2152
2153      HeapFree(GetProcessHeap(), 0, bitmap);
2154      HeapFree(GetProcessHeap(), 0, gl_bitmap);
2155      return FALSE;
2156 }
2157
2158 /**
2159  * X11DRV_wglUseFontBitmapsA
2160  *
2161  * For OpenGL32 wglUseFontBitmapsA.
2162  */
2163 BOOL CDECL X11DRV_wglUseFontBitmapsA(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
2164 {
2165      Font fid = physDev->font;
2166
2167      TRACE("(%p, %d, %d, %d) using font %ld\n", physDev->hdc, first, count, listBase, fid);
2168
2169      if (!has_opengl()) return FALSE;
2170
2171      if (fid == 0) {
2172          return internal_wglUseFontBitmaps(physDev->hdc, first, count, listBase, GetGlyphOutlineA);
2173      }
2174
2175      wine_tsx11_lock();
2176      /* I assume that the glyphs are at the same position for X and for Windows */
2177      pglXUseXFont(fid, first, count, listBase);
2178      wine_tsx11_unlock();
2179      return TRUE;
2180 }
2181
2182 /**
2183  * X11DRV_wglUseFontBitmapsW
2184  *
2185  * For OpenGL32 wglUseFontBitmapsW.
2186  */
2187 BOOL CDECL X11DRV_wglUseFontBitmapsW(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
2188 {
2189      Font fid = physDev->font;
2190
2191      TRACE("(%p, %d, %d, %d) using font %ld\n", physDev->hdc, first, count, listBase, fid);
2192
2193      if (!has_opengl()) return FALSE;
2194
2195      if (fid == 0) {
2196          return internal_wglUseFontBitmaps(physDev->hdc, first, count, listBase, GetGlyphOutlineW);
2197      }
2198
2199      WARN("Using the glX API for the WCHAR variant - some characters may come out incorrectly !\n");
2200
2201      wine_tsx11_lock();
2202      /* I assume that the glyphs are at the same position for X and for Windows */
2203      pglXUseXFont(fid, first, count, listBase);
2204      wine_tsx11_unlock();
2205      return TRUE;
2206 }
2207
2208 /* WGL helper function which handles differences in glGetIntegerv from WGL and GLX */
2209 static void WINAPI X11DRV_wglGetIntegerv(GLenum pname, GLint* params)
2210 {
2211     wine_tsx11_lock();
2212     switch(pname)
2213     {
2214     case GL_DEPTH_BITS:
2215         {
2216             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2217
2218             pglGetIntegerv(pname, params);
2219             /**
2220              * if we cannot find a Wine Context
2221              * we only have the default wine desktop context,
2222              * so if we have only a 24 depth say we have 32
2223              */
2224             if (!ctx && *params == 24) {
2225                 *params = 32;
2226             }
2227             TRACE("returns GL_DEPTH_BITS as '%d'\n", *params);
2228             break;
2229         }
2230     case GL_ALPHA_BITS:
2231         {
2232             Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2233
2234             pglXGetFBConfigAttrib(gdi_display, ctx->fmt->fbconfig, GLX_ALPHA_SIZE, params);
2235             TRACE("returns GL_ALPHA_BITS as '%d'\n", *params);
2236             break;
2237         }
2238     default:
2239         pglGetIntegerv(pname, params);
2240         break;
2241     }
2242     wine_tsx11_unlock();
2243 }
2244
2245 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
2246 {
2247     int w, h;
2248
2249     if (!physDev->gl_copy)
2250         return;
2251
2252     w = physDev->dc_rect.right - physDev->dc_rect.left;
2253     h = physDev->dc_rect.bottom - physDev->dc_rect.top;
2254
2255     if(w > 0 && h > 0) {
2256         Drawable src = physDev->pixmap;
2257         if(!src) src = physDev->gl_drawable;
2258
2259         /* The GL drawable may be lagged behind if we don't flush first, so
2260          * flush the display make sure we copy up-to-date data */
2261         wine_tsx11_lock();
2262         XFlush(gdi_display);
2263         XSetFunction(gdi_display, physDev->gc, GXcopy);
2264         XCopyArea(gdi_display, src, physDev->drawable, physDev->gc, 0, 0, w, h,
2265                   physDev->dc_rect.left, physDev->dc_rect.top);
2266         wine_tsx11_unlock();
2267     }
2268 }
2269
2270
2271 static void WINAPI X11DRV_wglFinish(void)
2272 {
2273     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2274     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2275
2276     wine_tsx11_lock();
2277     sync_context(ctx);
2278     pglFinish();
2279     wine_tsx11_unlock();
2280     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2281 }
2282
2283 static void WINAPI X11DRV_wglFlush(void)
2284 {
2285     Wine_GLContext *ctx = NtCurrentTeb()->glContext;
2286     enum x11drv_escape_codes code = X11DRV_FLUSH_GL_DRAWABLE;
2287
2288     wine_tsx11_lock();
2289     sync_context(ctx);
2290     pglFlush();
2291     wine_tsx11_unlock();
2292     if (ctx) ExtEscape(ctx->hdc, X11DRV_ESCAPE, sizeof(code), (LPSTR)&code, 0, NULL );
2293 }
2294
2295 /**
2296  * X11DRV_wglCreateContextAttribsARB
2297  *
2298  * WGL_ARB_create_context: wglCreateContextAttribsARB
2299  */
2300 HGLRC CDECL X11DRV_wglCreateContextAttribsARB(X11DRV_PDEVICE *physDev, HGLRC hShareContext, const int* attribList)
2301 {
2302     Wine_GLContext *ret;
2303     WineGLPixelFormat *fmt;
2304     int hdcPF = physDev->current_pf;
2305     int fmt_count = 0;
2306
2307     TRACE("(%p %p %p)\n", physDev, hShareContext, attribList);
2308
2309     if (!has_opengl()) return 0;
2310
2311     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, hdcPF, TRUE /* Offscreen */, &fmt_count);
2312     /* wglCreateContextAttribsARB supports ALL pixel formats, so also offscreen ones.
2313      * If this fails something is very wrong on the system. */
2314     if(!fmt)
2315     {
2316         ERR("Cannot get FB Config for iPixelFormat %d, expect problems!\n", hdcPF);
2317         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2318         return NULL;
2319     }
2320
2321     wine_tsx11_lock();
2322     ret = alloc_context();
2323     wine_tsx11_unlock();
2324     ret->hdc = physDev->hdc;
2325     ret->fmt = fmt;
2326     ret->vis = NULL; /* glXCreateContextAttribsARB requires a fbconfig instead of a visual */
2327     ret->gl3_context = TRUE;
2328
2329     ret->numAttribs = 0;
2330     if(attribList)
2331     {
2332         int *pAttribList = (int*)attribList;
2333         int *pContextAttribList = &ret->attribList[0];
2334         /* attribList consists of pairs {token, value] terminated with 0 */
2335         while(pAttribList[0] != 0)
2336         {
2337             TRACE("%#x %#x\n", pAttribList[0], pAttribList[1]);
2338             switch(pAttribList[0])
2339             {
2340                 case WGL_CONTEXT_MAJOR_VERSION_ARB:
2341                     pContextAttribList[0] = GLX_CONTEXT_MAJOR_VERSION_ARB;
2342                     pContextAttribList[1] = pAttribList[1];
2343                     break;
2344                 case WGL_CONTEXT_MINOR_VERSION_ARB:
2345                     pContextAttribList[0] = GLX_CONTEXT_MINOR_VERSION_ARB;
2346                     pContextAttribList[1] = pAttribList[1];
2347                     break;
2348                 case WGL_CONTEXT_LAYER_PLANE_ARB:
2349                     break;
2350                 case WGL_CONTEXT_FLAGS_ARB:
2351                     pContextAttribList[0] = GLX_CONTEXT_FLAGS_ARB;
2352                     pContextAttribList[1] = pAttribList[1];
2353                     break;
2354                 case WGL_CONTEXT_PROFILE_MASK_ARB:
2355                     pContextAttribList[0] = GLX_CONTEXT_PROFILE_MASK_ARB;
2356                     pContextAttribList[1] = pAttribList[1];
2357                     break;
2358                 default:
2359                     ERR("Unhandled attribList pair: %#x %#x\n", pAttribList[0], pAttribList[1]);
2360             }
2361
2362             ret->numAttribs++;
2363             pAttribList += 2;
2364             pContextAttribList += 2;
2365         }
2366     }
2367
2368     wine_tsx11_lock();
2369     X11DRV_expect_error(gdi_display, GLXErrorHandler, NULL);
2370     ret->ctx = create_glxcontext(gdi_display, ret, NULL);
2371
2372     XSync(gdi_display, False);
2373     if(X11DRV_check_error() || !ret->ctx)
2374     {
2375         /* In the future we should convert the GLX error to a win32 one here if needed */
2376         ERR("Context creation failed\n");
2377         free_context(ret);
2378         wine_tsx11_unlock();
2379         return NULL;
2380     }
2381
2382     wine_tsx11_unlock();
2383     TRACE(" creating context %p\n", ret);
2384     return (HGLRC) ret;
2385 }
2386
2387 /**
2388  * X11DRV_wglGetExtensionsStringARB
2389  *
2390  * WGL_ARB_extensions_string: wglGetExtensionsStringARB
2391  */
2392 static const char * WINAPI X11DRV_wglGetExtensionsStringARB(HDC hdc) {
2393     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
2394     return WineGLInfo.wglExtensions;
2395 }
2396
2397 /**
2398  * X11DRV_wglCreatePbufferARB
2399  *
2400  * WGL_ARB_pbuffer: wglCreatePbufferARB
2401  */
2402 static HPBUFFERARB WINAPI X11DRV_wglCreatePbufferARB(HDC hdc, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList)
2403 {
2404     Wine_GLPBuffer* object = NULL;
2405     WineGLPixelFormat *fmt = NULL;
2406     int nCfgs = 0;
2407     int attribs[256];
2408     int nAttribs = 0;
2409
2410     TRACE("(%p, %d, %d, %d, %p)\n", hdc, iPixelFormat, iWidth, iHeight, piAttribList);
2411
2412     if (0 >= iPixelFormat) {
2413         ERR("(%p): unexpected iPixelFormat(%d) <= 0, returns NULL\n", hdc, iPixelFormat);
2414         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2415         return NULL; /* unexpected error */
2416     }
2417
2418     /* Convert the WGL pixelformat to a GLX format, if it fails then the format is invalid */
2419     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nCfgs);
2420     if(!fmt) {
2421         ERR("(%p): unexpected iPixelFormat(%d) > nFormats(%d), returns NULL\n", hdc, iPixelFormat, nCfgs);
2422         SetLastError(ERROR_INVALID_PIXEL_FORMAT);
2423         goto create_failed; /* unexpected error */
2424     }
2425
2426     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(Wine_GLPBuffer));
2427     if (NULL == object) {
2428         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2429         goto create_failed; /* unexpected error */
2430     }
2431     object->hdc = hdc;
2432     object->display = gdi_display;
2433     object->width = iWidth;
2434     object->height = iHeight;
2435     object->fmt = fmt;
2436
2437     PUSH2(attribs, GLX_PBUFFER_WIDTH,  iWidth);
2438     PUSH2(attribs, GLX_PBUFFER_HEIGHT, iHeight); 
2439     while (piAttribList && 0 != *piAttribList) {
2440         int attr_v;
2441         switch (*piAttribList) {
2442             case WGL_PBUFFER_LARGEST_ARB: {
2443                 ++piAttribList;
2444                 attr_v = *piAttribList;
2445                 TRACE("WGL_LARGEST_PBUFFER_ARB = %d\n", attr_v);
2446                 PUSH2(attribs, GLX_LARGEST_PBUFFER, attr_v);
2447                 break;
2448             }
2449
2450             case WGL_TEXTURE_FORMAT_ARB: {
2451                 ++piAttribList;
2452                 attr_v = *piAttribList;
2453                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_FORMAT_ARB as %x\n", attr_v);
2454                 if (use_render_texture_ati) {
2455                     int type = 0;
2456                     switch (attr_v) {
2457                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2458                         case WGL_TEXTURE_RGB_ARB: type = GLX_TEXTURE_RGB_ATI; break ;
2459                         case WGL_TEXTURE_RGBA_ARB: type = GLX_TEXTURE_RGBA_ATI; break ;
2460                         default:
2461                             SetLastError(ERROR_INVALID_DATA);
2462                             goto create_failed;
2463                     }
2464                     object->use_render_texture = 1;
2465                     PUSH2(attribs, GLX_TEXTURE_FORMAT_ATI, type);
2466                 } else {
2467                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2468                         object->use_render_texture = 0;
2469                     } else {
2470                         if (!use_render_texture_emulation) {
2471                             SetLastError(ERROR_INVALID_DATA);
2472                             goto create_failed;
2473                         }
2474                         switch (attr_v) {
2475                             case WGL_TEXTURE_RGB_ARB:
2476                                 object->use_render_texture = GL_RGB;
2477                                 object->texture_bpp = 3;
2478                                 object->texture_format = GL_RGB;
2479                                 object->texture_type = GL_UNSIGNED_BYTE;
2480                                 break;
2481                             case WGL_TEXTURE_RGBA_ARB:
2482                                 object->use_render_texture = GL_RGBA;
2483                                 object->texture_bpp = 4;
2484                                 object->texture_format = GL_RGBA;
2485                                 object->texture_type = GL_UNSIGNED_BYTE;
2486                                 break;
2487
2488                             /* WGL_FLOAT_COMPONENTS_NV */
2489                             case WGL_TEXTURE_FLOAT_R_NV:
2490                                 object->use_render_texture = GL_FLOAT_R_NV;
2491                                 object->texture_bpp = 4;
2492                                 object->texture_format = GL_RED;
2493                                 object->texture_type = GL_FLOAT;
2494                                 break;
2495                             case WGL_TEXTURE_FLOAT_RG_NV:
2496                                 object->use_render_texture = GL_FLOAT_RG_NV;
2497                                 object->texture_bpp = 8;
2498                                 object->texture_format = GL_LUMINANCE_ALPHA;
2499                                 object->texture_type = GL_FLOAT;
2500                                 break;
2501                             case WGL_TEXTURE_FLOAT_RGB_NV:
2502                                 object->use_render_texture = GL_FLOAT_RGB_NV;
2503                                 object->texture_bpp = 12;
2504                                 object->texture_format = GL_RGB;
2505                                 object->texture_type = GL_FLOAT;
2506                                 break;
2507                             case WGL_TEXTURE_FLOAT_RGBA_NV:
2508                                 object->use_render_texture = GL_FLOAT_RGBA_NV;
2509                                 object->texture_bpp = 16;
2510                                 object->texture_format = GL_RGBA;
2511                                 object->texture_type = GL_FLOAT;
2512                                 break;
2513                             default:
2514                                 ERR("Unknown texture format: %x\n", attr_v);
2515                                 SetLastError(ERROR_INVALID_DATA);
2516                                 goto create_failed;
2517                         }
2518                     }
2519                 }
2520                 break;
2521             }
2522
2523             case WGL_TEXTURE_TARGET_ARB: {
2524                 ++piAttribList;
2525                 attr_v = *piAttribList;
2526                 TRACE("WGL_render_texture Attribute: WGL_TEXTURE_TARGET_ARB as %x\n", attr_v);
2527                 if (use_render_texture_ati) {
2528                     int type = 0;
2529                     switch (attr_v) {
2530                         case WGL_NO_TEXTURE_ARB: type = GLX_NO_TEXTURE_ATI; break ;
2531                         case WGL_TEXTURE_CUBE_MAP_ARB: type = GLX_TEXTURE_CUBE_MAP_ATI; break ;
2532                         case WGL_TEXTURE_1D_ARB: type = GLX_TEXTURE_1D_ATI; break ;
2533                         case WGL_TEXTURE_2D_ARB: type = GLX_TEXTURE_2D_ATI; break ;
2534                         default:
2535                             SetLastError(ERROR_INVALID_DATA);
2536                             goto create_failed;
2537                     }
2538                     PUSH2(attribs, GLX_TEXTURE_TARGET_ATI, type);
2539                 } else {
2540                     if (WGL_NO_TEXTURE_ARB == attr_v) {
2541                         object->texture_target = 0;
2542                     } else {
2543                         if (!use_render_texture_emulation) {
2544                             SetLastError(ERROR_INVALID_DATA);
2545                             goto create_failed;
2546                         }
2547                         switch (attr_v) {
2548                             case WGL_TEXTURE_CUBE_MAP_ARB: {
2549                                 if (iWidth != iHeight) {
2550                                     SetLastError(ERROR_INVALID_DATA);
2551                                     goto create_failed;
2552                                 }
2553                                 object->texture_target = GL_TEXTURE_CUBE_MAP;
2554                                 object->texture_bind_target = GL_TEXTURE_BINDING_CUBE_MAP;
2555                                break;
2556                             }
2557                             case WGL_TEXTURE_1D_ARB: {
2558                                 if (1 != iHeight) {
2559                                     SetLastError(ERROR_INVALID_DATA);
2560                                     goto create_failed;
2561                                 }
2562                                 object->texture_target = GL_TEXTURE_1D;
2563                                 object->texture_bind_target = GL_TEXTURE_BINDING_1D;
2564                                 break;
2565                             }
2566                             case WGL_TEXTURE_2D_ARB: {
2567                                 object->texture_target = GL_TEXTURE_2D;
2568                                 object->texture_bind_target = GL_TEXTURE_BINDING_2D;
2569                                 break;
2570                             }
2571                             case WGL_TEXTURE_RECTANGLE_NV: {
2572                                 object->texture_target = GL_TEXTURE_RECTANGLE_NV;
2573                                 object->texture_bind_target = GL_TEXTURE_BINDING_RECTANGLE_NV;
2574                                 break;
2575                             }
2576                             default:
2577                                 ERR("Unknown texture target: %x\n", attr_v);
2578                                 SetLastError(ERROR_INVALID_DATA);
2579                                 goto create_failed;
2580                         }
2581                     }
2582                 }
2583                 break;
2584             }
2585
2586             case WGL_MIPMAP_TEXTURE_ARB: {
2587                 ++piAttribList;
2588                 attr_v = *piAttribList;
2589                 TRACE("WGL_render_texture Attribute: WGL_MIPMAP_TEXTURE_ARB as %x\n", attr_v);
2590                 if (use_render_texture_ati) {
2591                     PUSH2(attribs, GLX_MIPMAP_TEXTURE_ATI, attr_v);
2592                 } else {
2593                     if (!use_render_texture_emulation) {
2594                         SetLastError(ERROR_INVALID_DATA);
2595                         goto create_failed;
2596                     }
2597                 }
2598                 break;
2599             }
2600         }
2601         ++piAttribList;
2602     }
2603
2604     PUSH1(attribs, None);
2605     wine_tsx11_lock();
2606     object->drawable = pglXCreatePbuffer(gdi_display, fmt->fbconfig, attribs);
2607     wine_tsx11_unlock();
2608     TRACE("new Pbuffer drawable as %p\n", (void*) object->drawable);
2609     if (!object->drawable) {
2610         SetLastError(ERROR_NO_SYSTEM_RESOURCES);
2611         goto create_failed; /* unexpected error */
2612     }
2613     TRACE("->(%p)\n", object);
2614     return object;
2615
2616 create_failed:
2617     HeapFree(GetProcessHeap(), 0, object);
2618     TRACE("->(FAILED)\n");
2619     return NULL;
2620 }
2621
2622 /**
2623  * X11DRV_wglDestroyPbufferARB
2624  *
2625  * WGL_ARB_pbuffer: wglDestroyPbufferARB
2626  */
2627 static GLboolean WINAPI X11DRV_wglDestroyPbufferARB(HPBUFFERARB hPbuffer)
2628 {
2629     Wine_GLPBuffer* object = hPbuffer;
2630     TRACE("(%p)\n", hPbuffer);
2631     if (NULL == object) {
2632         SetLastError(ERROR_INVALID_HANDLE);
2633         return GL_FALSE;
2634     }
2635     wine_tsx11_lock();
2636     pglXDestroyPbuffer(object->display, object->drawable);
2637     wine_tsx11_unlock();
2638     HeapFree(GetProcessHeap(), 0, object);
2639     return GL_TRUE;
2640 }
2641
2642 /**
2643  * X11DRV_wglGetPbufferDCARB
2644  *
2645  * WGL_ARB_pbuffer: wglGetPbufferDCARB
2646  * The function wglGetPbufferDCARB returns a device context for a pbuffer.
2647  * Gdi32 implements the part of this function which creates a device context.
2648  * This part associates the physDev with the X drawable of the pbuffer.
2649  */
2650 HDC CDECL X11DRV_wglGetPbufferDCARB(X11DRV_PDEVICE *physDev, HPBUFFERARB hPbuffer)
2651 {
2652     Wine_GLPBuffer* object = hPbuffer;
2653     if (NULL == object) {
2654         SetLastError(ERROR_INVALID_HANDLE);
2655         return NULL;
2656     }
2657
2658     /* The function wglGetPbufferDCARB returns a DC to which the pbuffer can be connected.
2659      * All formats in our pixelformat list are compatible with each other and the main drawable. */
2660     physDev->current_pf = object->fmt->iPixelFormat;
2661     physDev->drawable = object->drawable;
2662     SetRect( &physDev->drawable_rect, 0, 0, object->width, object->height );
2663     physDev->dc_rect = physDev->drawable_rect;
2664
2665     TRACE("(%p)->(%p)\n", hPbuffer, physDev->hdc);
2666     return physDev->hdc;
2667 }
2668
2669 /**
2670  * X11DRV_wglQueryPbufferARB
2671  *
2672  * WGL_ARB_pbuffer: wglQueryPbufferARB
2673  */
2674 static GLboolean WINAPI X11DRV_wglQueryPbufferARB(HPBUFFERARB hPbuffer, int iAttribute, int *piValue)
2675 {
2676     Wine_GLPBuffer* object = hPbuffer;
2677     TRACE("(%p, 0x%x, %p)\n", hPbuffer, iAttribute, piValue);
2678     if (NULL == object) {
2679         SetLastError(ERROR_INVALID_HANDLE);
2680         return GL_FALSE;
2681     }
2682     switch (iAttribute) {
2683         case WGL_PBUFFER_WIDTH_ARB:
2684             wine_tsx11_lock();
2685             pglXQueryDrawable(object->display, object->drawable, GLX_WIDTH, (unsigned int*) piValue);
2686             wine_tsx11_unlock();
2687             break;
2688         case WGL_PBUFFER_HEIGHT_ARB:
2689             wine_tsx11_lock();
2690             pglXQueryDrawable(object->display, object->drawable, GLX_HEIGHT, (unsigned int*) piValue);
2691             wine_tsx11_unlock();
2692             break;
2693
2694         case WGL_PBUFFER_LOST_ARB:
2695             /* GLX Pbuffers cannot be lost by default. We can support this by
2696              * setting GLX_PRESERVED_CONTENTS to False and using glXSelectEvent
2697              * to receive pixel buffer clobber events, however that may or may
2698              * not give any benefit */
2699             *piValue = GL_FALSE;
2700             break;
2701
2702         case WGL_TEXTURE_FORMAT_ARB:
2703             if (use_render_texture_ati) {
2704                 unsigned int tmp;
2705                 int type = WGL_NO_TEXTURE_ARB;
2706                 wine_tsx11_lock();
2707                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_FORMAT_ATI, &tmp);
2708                 wine_tsx11_unlock();
2709                 switch (tmp) {
2710                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2711                     case GLX_TEXTURE_RGB_ATI: type = WGL_TEXTURE_RGB_ARB; break ;
2712                     case GLX_TEXTURE_RGBA_ATI: type = WGL_TEXTURE_RGBA_ARB; break ;
2713                 }
2714                 *piValue = type;
2715             } else {
2716                 if (!object->use_render_texture) {
2717                     *piValue = WGL_NO_TEXTURE_ARB;
2718                 } else {
2719                     if (!use_render_texture_emulation) {
2720                         SetLastError(ERROR_INVALID_HANDLE);
2721                         return GL_FALSE;
2722                     }
2723                     switch(object->use_render_texture) {
2724                         case GL_RGB:
2725                             *piValue = WGL_TEXTURE_RGB_ARB;
2726                             break;
2727                         case GL_RGBA:
2728                             *piValue = WGL_TEXTURE_RGBA_ARB;
2729                             break;
2730                         /* WGL_FLOAT_COMPONENTS_NV */
2731                         case GL_FLOAT_R_NV:
2732                             *piValue = WGL_TEXTURE_FLOAT_R_NV;
2733                             break;
2734                         case GL_FLOAT_RG_NV:
2735                             *piValue = WGL_TEXTURE_FLOAT_RG_NV;
2736                             break;
2737                         case GL_FLOAT_RGB_NV:
2738                             *piValue = WGL_TEXTURE_FLOAT_RGB_NV;
2739                             break;
2740                         case GL_FLOAT_RGBA_NV:
2741                             *piValue = WGL_TEXTURE_FLOAT_RGBA_NV;
2742                             break;
2743                         default:
2744                             ERR("Unknown texture format: %x\n", object->use_render_texture);
2745                     }
2746                 }
2747             }
2748             break;
2749
2750         case WGL_TEXTURE_TARGET_ARB:
2751             if (use_render_texture_ati) {
2752                 unsigned int tmp;
2753                 int type = WGL_NO_TEXTURE_ARB;
2754                 wine_tsx11_lock();
2755                 pglXQueryDrawable(object->display, object->drawable, GLX_TEXTURE_TARGET_ATI, &tmp);
2756                 wine_tsx11_unlock();
2757                 switch (tmp) {
2758                     case GLX_NO_TEXTURE_ATI: type = WGL_NO_TEXTURE_ARB; break ;
2759                     case GLX_TEXTURE_CUBE_MAP_ATI: type = WGL_TEXTURE_CUBE_MAP_ARB; break ;
2760                     case GLX_TEXTURE_1D_ATI: type = WGL_TEXTURE_1D_ARB; break ;
2761                     case GLX_TEXTURE_2D_ATI: type = WGL_TEXTURE_2D_ARB; break ;
2762                 }
2763                 *piValue = type;
2764             } else {
2765             if (!object->texture_target) {
2766                 *piValue = WGL_NO_TEXTURE_ARB;
2767             } else {
2768                 if (!use_render_texture_emulation) {
2769                     SetLastError(ERROR_INVALID_DATA);      
2770                     return GL_FALSE;
2771                 }
2772                 switch (object->texture_target) {
2773                     case GL_TEXTURE_1D:       *piValue = WGL_TEXTURE_1D_ARB; break;
2774                     case GL_TEXTURE_2D:       *piValue = WGL_TEXTURE_2D_ARB; break;
2775                     case GL_TEXTURE_CUBE_MAP: *piValue = WGL_TEXTURE_CUBE_MAP_ARB; break;
2776                     case GL_TEXTURE_RECTANGLE_NV: *piValue = WGL_TEXTURE_RECTANGLE_NV; break;
2777                 }
2778             }
2779         }
2780         break;
2781
2782     case WGL_MIPMAP_TEXTURE_ARB:
2783         if (use_render_texture_ati) {
2784             wine_tsx11_lock();
2785             pglXQueryDrawable(object->display, object->drawable, GLX_MIPMAP_TEXTURE_ATI, (unsigned int*) piValue);
2786             wine_tsx11_unlock();
2787         } else {
2788             *piValue = GL_FALSE; /** don't support that */
2789             FIXME("unsupported WGL_ARB_render_texture attribute query for 0x%x\n", iAttribute);
2790         }
2791         break;
2792
2793     default:
2794         FIXME("unexpected attribute %x\n", iAttribute);
2795         break;
2796     }
2797
2798     return GL_TRUE;
2799 }
2800
2801 /**
2802  * X11DRV_wglReleasePbufferDCARB
2803  *
2804  * WGL_ARB_pbuffer: wglReleasePbufferDCARB
2805  */
2806 static int WINAPI X11DRV_wglReleasePbufferDCARB(HPBUFFERARB hPbuffer, HDC hdc)
2807 {
2808     TRACE("(%p, %p)\n", hPbuffer, hdc);
2809     return DeleteDC(hdc);
2810 }
2811
2812 /**
2813  * X11DRV_wglSetPbufferAttribARB
2814  *
2815  * WGL_ARB_pbuffer: wglSetPbufferAttribARB
2816  */
2817 static GLboolean WINAPI X11DRV_wglSetPbufferAttribARB(HPBUFFERARB hPbuffer, const int *piAttribList)
2818 {
2819     Wine_GLPBuffer* object = hPbuffer;
2820     GLboolean ret = GL_FALSE;
2821
2822     WARN("(%p, %p): alpha-testing, report any problem\n", hPbuffer, piAttribList);
2823     if (NULL == object) {
2824         SetLastError(ERROR_INVALID_HANDLE);
2825         return GL_FALSE;
2826     }
2827     if (!object->use_render_texture) {
2828         SetLastError(ERROR_INVALID_HANDLE);
2829         return GL_FALSE;
2830     }
2831     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
2832         return GL_TRUE;
2833     }
2834     if (NULL != pglXDrawableAttribATI) {
2835         if (use_render_texture_ati) {
2836             FIXME("Need conversion for GLX_ATI_render_texture\n");
2837         }
2838         wine_tsx11_lock();
2839         ret = pglXDrawableAttribATI(object->display, object->drawable, piAttribList);
2840         wine_tsx11_unlock();
2841     }
2842     return ret;
2843 }
2844
2845 /**
2846  * X11DRV_wglChoosePixelFormatARB
2847  *
2848  * WGL_ARB_pixel_format: wglChoosePixelFormatARB
2849  */
2850 static GLboolean WINAPI X11DRV_wglChoosePixelFormatARB(HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats)
2851 {
2852     int gl_test = 0;
2853     int attribs[256];
2854     int nAttribs = 0;
2855     GLXFBConfig* cfgs = NULL;
2856     int nCfgs = 0;
2857     int it;
2858     int fmt_id;
2859     WineGLPixelFormat *fmt;
2860     UINT pfmt_it = 0;
2861     int run;
2862     int i;
2863     DWORD dwFlags = 0;
2864
2865     TRACE("(%p, %p, %p, %d, %p, %p): hackish\n", hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
2866     if (NULL != pfAttribFList) {
2867         FIXME("unused pfAttribFList\n");
2868     }
2869
2870     nAttribs = ConvertAttribWGLtoGLX(piAttribIList, attribs, NULL);
2871     if (-1 == nAttribs) {
2872         WARN("Cannot convert WGL to GLX attributes\n");
2873         return GL_FALSE;
2874     }
2875     PUSH1(attribs, None);
2876
2877     /* There is no 1:1 mapping between GLX and WGL formats because we duplicate some GLX formats for bitmap rendering (see get_formats).
2878      * Flags like PFD_SUPPORT_GDI, PFD_DRAW_TO_BITMAP and others are a property of the WineGLPixelFormat. We don't query these attributes
2879      * using glXChooseFBConfig but we filter the result of glXChooseFBConfig later on by passing a dwFlags to 'ConvertPixelFormatGLXtoWGL'. */
2880     for(i=0; piAttribIList[i] != 0; i+=2)
2881     {
2882         switch(piAttribIList[i])
2883         {
2884             case WGL_DRAW_TO_BITMAP_ARB:
2885                 if(piAttribIList[i+1])
2886                     dwFlags |= PFD_DRAW_TO_BITMAP;
2887                 break;
2888             case WGL_ACCELERATION_ARB:
2889                 switch(piAttribIList[i+1])
2890                 {
2891                     case WGL_NO_ACCELERATION_ARB:
2892                         dwFlags |= PFD_GENERIC_FORMAT;
2893                         break;
2894                     case WGL_GENERIC_ACCELERATION_ARB:
2895                         dwFlags |= PFD_GENERIC_ACCELERATED;
2896                         break;
2897                     case WGL_FULL_ACCELERATION_ARB:
2898                         /* Nothing to do */
2899                         break;
2900                 }
2901                 break;
2902             case WGL_SUPPORT_GDI_ARB:
2903                 if(piAttribIList[i+1])
2904                     dwFlags |= PFD_SUPPORT_GDI;
2905                 break;
2906         }
2907     }
2908
2909     /* Search for FB configurations matching the requirements in attribs */
2910     wine_tsx11_lock();
2911     cfgs = pglXChooseFBConfig(gdi_display, DefaultScreen(gdi_display), attribs, &nCfgs);
2912     if (NULL == cfgs) {
2913         wine_tsx11_unlock();
2914         WARN("Compatible Pixel Format not found\n");
2915         return GL_FALSE;
2916     }
2917
2918     /* Loop through all matching formats and check if they are suitable.
2919     * Note that this function should at max return nMaxFormats different formats */
2920     for(run=0; run < 2; run++)
2921     {
2922         for (it = 0; it < nCfgs; ++it) {
2923             gl_test = pglXGetFBConfigAttrib(gdi_display, cfgs[it], GLX_FBCONFIG_ID, &fmt_id);
2924             if (gl_test) {
2925                 ERR("Failed to retrieve FBCONFIG_ID from GLXFBConfig, expect problems.\n");
2926                 continue;
2927             }
2928
2929             /* Search for the format in our list of compatible formats */
2930             fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fmt_id, dwFlags);
2931             if(!fmt)
2932                 continue;
2933
2934             /* During the first run we only want onscreen formats and during the second only offscreen 'XOR' */
2935             if( ((run == 0) && fmt->offscreenOnly) || ((run == 1) && !fmt->offscreenOnly) )
2936                 continue;
2937
2938             if(pfmt_it < nMaxFormats) {
2939                 piFormats[pfmt_it] = fmt->iPixelFormat;
2940                 TRACE("at %d/%d found FBCONFIG_ID 0x%x (%d)\n", it + 1, nCfgs, fmt_id, piFormats[pfmt_it]);
2941             }
2942             pfmt_it++;
2943         }
2944     }
2945
2946     *nNumFormats = pfmt_it;
2947     /** free list */
2948     XFree(cfgs);
2949     wine_tsx11_unlock();
2950     return GL_TRUE;
2951 }
2952
2953 /**
2954  * X11DRV_wglGetPixelFormatAttribivARB
2955  *
2956  * WGL_ARB_pixel_format: wglGetPixelFormatAttribivARB
2957  */
2958 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribivARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues)
2959 {
2960     UINT i;
2961     WineGLPixelFormat *fmt = NULL;
2962     int hTest;
2963     int tmp;
2964     int curGLXAttr = 0;
2965     int nWGLFormats = 0;
2966
2967     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
2968
2969     if (0 < iLayerPlane) {
2970         FIXME("unsupported iLayerPlane(%d) > 0, returns FALSE\n", iLayerPlane);
2971         return GL_FALSE;
2972     }
2973
2974     /* Convert the WGL pixelformat to a GLX one, if this fails then most likely the iPixelFormat isn't supported.
2975     * We don't have to fail yet as a program can specify an invalid iPixelFormat (lets say 0) if it wants to query
2976     * the number of supported WGL formats. Whether the iPixelFormat is valid is handled in the for-loop below. */
2977     fmt = ConvertPixelFormatWGLtoGLX(gdi_display, iPixelFormat, TRUE /* Offscreen */, &nWGLFormats);
2978     if(!fmt) {
2979         WARN("Unable to convert iPixelFormat %d to a GLX one!\n", iPixelFormat);
2980     }
2981
2982     wine_tsx11_lock();
2983     for (i = 0; i < nAttributes; ++i) {
2984         const int curWGLAttr = piAttributes[i];
2985         TRACE("pAttr[%d] = %x\n", i, curWGLAttr);
2986
2987         switch (curWGLAttr) {
2988             case WGL_NUMBER_PIXEL_FORMATS_ARB:
2989                 piValues[i] = nWGLFormats; 
2990                 continue;
2991
2992             case WGL_SUPPORT_OPENGL_ARB:
2993                 piValues[i] = GL_TRUE; 
2994                 continue;
2995
2996             case WGL_ACCELERATION_ARB:
2997                 curGLXAttr = GLX_CONFIG_CAVEAT;
2998                 if (!fmt) goto pix_error;
2999                 if(fmt->dwFlags & PFD_GENERIC_FORMAT)
3000                     piValues[i] = WGL_NO_ACCELERATION_ARB;
3001                 else if(fmt->dwFlags & PFD_GENERIC_ACCELERATED)
3002                     piValues[i] = WGL_GENERIC_ACCELERATION_ARB;
3003                 else
3004                     piValues[i] = WGL_FULL_ACCELERATION_ARB;
3005                 continue;
3006
3007             case WGL_TRANSPARENT_ARB:
3008                 curGLXAttr = GLX_TRANSPARENT_TYPE;
3009                 if (!fmt) goto pix_error;
3010                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3011                 if (hTest) goto get_error;
3012                     piValues[i] = GL_FALSE;
3013                 if (GLX_NONE != tmp) piValues[i] = GL_TRUE;
3014                     continue;
3015
3016             case WGL_PIXEL_TYPE_ARB:
3017                 curGLXAttr = GLX_RENDER_TYPE;
3018                 if (!fmt) goto pix_error;
3019                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3020                 if (hTest) goto get_error;
3021                 TRACE("WGL_PIXEL_TYPE_ARB: GLX_RENDER_TYPE = 0x%x\n", tmp);
3022                 if      (tmp & GLX_RGBA_BIT)           { piValues[i] = WGL_TYPE_RGBA_ARB; }
3023                 else if (tmp & GLX_COLOR_INDEX_BIT)    { piValues[i] = WGL_TYPE_COLORINDEX_ARB; }
3024                 else if (tmp & GLX_RGBA_FLOAT_BIT)     { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
3025                 else if (tmp & GLX_RGBA_FLOAT_ATI_BIT) { piValues[i] = WGL_TYPE_RGBA_FLOAT_ATI; }
3026                 else if (tmp & GLX_RGBA_UNSIGNED_FLOAT_BIT_EXT) { piValues[i] = WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT; }
3027                 else {
3028                     ERR("unexpected RenderType(%x)\n", tmp);
3029                     piValues[i] = WGL_TYPE_RGBA_ARB;
3030                 }
3031                 continue;
3032
3033             case WGL_COLOR_BITS_ARB:
3034                 curGLXAttr = GLX_BUFFER_SIZE;
3035                 break;
3036
3037             case WGL_BIND_TO_TEXTURE_RGB_ARB:
3038                 if (use_render_texture_ati) {
3039                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGB_ATI;
3040                     break;
3041                 }
3042             case WGL_BIND_TO_TEXTURE_RGBA_ARB:
3043                 if (use_render_texture_ati) {
3044                     curGLXAttr = GLX_BIND_TO_TEXTURE_RGBA_ATI;
3045                     break;
3046                 }
3047                 if (!use_render_texture_emulation) {
3048                     piValues[i] = GL_FALSE;
3049                     continue;   
3050                 }
3051                 curGLXAttr = GLX_RENDER_TYPE;
3052                 if (!fmt) goto pix_error;
3053                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, &tmp);
3054                 if (hTest) goto get_error;
3055                 if (GLX_COLOR_INDEX_BIT == tmp) {
3056                     piValues[i] = GL_FALSE;  
3057                     continue;
3058                 }
3059                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3060                 if (hTest) goto get_error;
3061                 piValues[i] = (tmp & GLX_PBUFFER_BIT) ? GL_TRUE : GL_FALSE;
3062                 continue;
3063
3064             case WGL_BLUE_BITS_ARB:
3065                 curGLXAttr = GLX_BLUE_SIZE;
3066                 break;
3067             case WGL_RED_BITS_ARB:
3068                 curGLXAttr = GLX_RED_SIZE;
3069                 break;
3070             case WGL_GREEN_BITS_ARB:
3071                 curGLXAttr = GLX_GREEN_SIZE;
3072                 break;
3073             case WGL_ALPHA_BITS_ARB:
3074                 curGLXAttr = GLX_ALPHA_SIZE;
3075                 break;
3076             case WGL_DEPTH_BITS_ARB:
3077                 curGLXAttr = GLX_DEPTH_SIZE;
3078                 break;
3079             case WGL_STENCIL_BITS_ARB:
3080                 curGLXAttr = GLX_STENCIL_SIZE;
3081                 break;
3082             case WGL_DOUBLE_BUFFER_ARB:
3083                 curGLXAttr = GLX_DOUBLEBUFFER;
3084                 break;
3085             case WGL_STEREO_ARB:
3086                 curGLXAttr = GLX_STEREO;
3087                 break;
3088             case WGL_AUX_BUFFERS_ARB:
3089                 curGLXAttr = GLX_AUX_BUFFERS;
3090                 break;
3091
3092             case WGL_SUPPORT_GDI_ARB:
3093                 if (!fmt) goto pix_error;
3094                 piValues[i] = (fmt->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
3095                 continue;
3096
3097             case WGL_DRAW_TO_BITMAP_ARB:
3098                 if (!fmt) goto pix_error;
3099                 piValues[i] = (fmt->dwFlags & PFD_DRAW_TO_BITMAP) ? TRUE : FALSE;
3100                 continue;
3101
3102             case WGL_DRAW_TO_WINDOW_ARB:
3103             case WGL_DRAW_TO_PBUFFER_ARB:
3104                 if (!fmt) goto pix_error;
3105                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_DRAWABLE_TYPE, &tmp);
3106                 if (hTest) goto get_error;
3107                 if((curWGLAttr == WGL_DRAW_TO_WINDOW_ARB && (tmp&GLX_WINDOW_BIT)) ||
3108                    (curWGLAttr == WGL_DRAW_TO_PBUFFER_ARB && (tmp&GLX_PBUFFER_BIT)))
3109                     piValues[i] = GL_TRUE;
3110                 else
3111                     piValues[i] = GL_FALSE;
3112                 continue;
3113
3114             case WGL_SWAP_METHOD_ARB:
3115                 /* For now return SWAP_EXCHANGE_ARB which is the best type of buffer switch available.
3116                  * Later on we can also use GLX_OML_swap_method on drivers which support this. At this
3117                  * point only ATI offers this.
3118                  */
3119                 piValues[i] = WGL_SWAP_EXCHANGE_ARB;
3120                 break;
3121
3122             case WGL_PBUFFER_LARGEST_ARB:
3123                 curGLXAttr = GLX_LARGEST_PBUFFER;
3124                 break;
3125
3126             case WGL_SAMPLE_BUFFERS_ARB:
3127                 curGLXAttr = GLX_SAMPLE_BUFFERS_ARB;
3128                 break;
3129
3130             case WGL_SAMPLES_ARB:
3131                 curGLXAttr = GLX_SAMPLES_ARB;
3132                 break;
3133
3134             case WGL_FLOAT_COMPONENTS_NV:
3135                 curGLXAttr = GLX_FLOAT_COMPONENTS_NV;
3136                 break;
3137
3138             case WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT:
3139                 curGLXAttr = GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT;
3140                 break;
3141
3142             case WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT:
3143                 curGLXAttr = GLX_RGBA_UNSIGNED_FLOAT_TYPE_EXT;
3144                 break;
3145
3146             case WGL_ACCUM_RED_BITS_ARB:
3147                 curGLXAttr = GLX_ACCUM_RED_SIZE;
3148                 break;
3149             case WGL_ACCUM_GREEN_BITS_ARB:
3150                 curGLXAttr = GLX_ACCUM_GREEN_SIZE;
3151                 break;
3152             case WGL_ACCUM_BLUE_BITS_ARB:
3153                 curGLXAttr = GLX_ACCUM_BLUE_SIZE;
3154                 break;
3155             case WGL_ACCUM_ALPHA_BITS_ARB:
3156                 curGLXAttr = GLX_ACCUM_ALPHA_SIZE;
3157                 break;
3158             case WGL_ACCUM_BITS_ARB:
3159                 if (!fmt) goto pix_error;
3160                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_RED_SIZE, &tmp);
3161                 if (hTest) goto get_error;
3162                 piValues[i] = tmp;
3163                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_GREEN_SIZE, &tmp);
3164                 if (hTest) goto get_error;
3165                 piValues[i] += tmp;
3166                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_BLUE_SIZE, &tmp);
3167                 if (hTest) goto get_error;
3168                 piValues[i] += tmp;
3169                 hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, GLX_ACCUM_ALPHA_SIZE, &tmp);
3170                 if (hTest) goto get_error;
3171                 piValues[i] += tmp;
3172                 continue;
3173
3174             default:
3175                 FIXME("unsupported %x WGL Attribute\n", curWGLAttr);
3176         }
3177
3178         /* Retrieve a GLX FBConfigAttrib when the attribute to query is valid and
3179          * iPixelFormat != 0. When iPixelFormat is 0 the only value which makes
3180          * sense to query is WGL_NUMBER_PIXEL_FORMATS_ARB.
3181          *
3182          * TODO: properly test the behavior of wglGetPixelFormatAttrib*v on Windows
3183          *       and check which options can work using iPixelFormat=0 and which not.
3184          *       A problem would be that this function is an extension. This would
3185          *       mean that the behavior could differ between different vendors (ATI, Nvidia, ..).
3186          */
3187         if (0 != curGLXAttr && iPixelFormat != 0) {
3188             if (!fmt) goto pix_error;
3189             hTest = pglXGetFBConfigAttrib(gdi_display, fmt->fbconfig, curGLXAttr, piValues + i);
3190             if (hTest) goto get_error;
3191             curGLXAttr = 0;
3192         } else { 
3193             piValues[i] = GL_FALSE; 
3194         }
3195     }
3196     wine_tsx11_unlock();
3197     return GL_TRUE;
3198
3199 get_error:
3200     wine_tsx11_unlock();
3201     ERR("(%p): unexpected failure on GetFBConfigAttrib(%x) returns FALSE\n", hdc, curGLXAttr);
3202     return GL_FALSE;
3203
3204 pix_error:
3205     wine_tsx11_unlock();
3206     ERR("(%p): unexpected iPixelFormat(%d) vs nFormats(%d), returns FALSE\n", hdc, iPixelFormat, nWGLFormats);
3207     return GL_FALSE;
3208 }
3209
3210 /**
3211  * X11DRV_wglGetPixelFormatAttribfvARB
3212  *
3213  * WGL_ARB_pixel_format: wglGetPixelFormatAttribfvARB
3214  */
3215 static GLboolean WINAPI X11DRV_wglGetPixelFormatAttribfvARB(HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues)
3216 {
3217     int *attr;
3218     int ret;
3219     UINT i;
3220
3221     TRACE("(%p, %d, %d, %d, %p, %p)\n", hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
3222
3223     /* Allocate a temporary array to store integer values */
3224     attr = HeapAlloc(GetProcessHeap(), 0, nAttributes * sizeof(int));
3225     if (!attr) {
3226         ERR("couldn't allocate %d array\n", nAttributes);
3227         return GL_FALSE;
3228     }
3229
3230     /* Piggy-back on wglGetPixelFormatAttribivARB */
3231     ret = X11DRV_wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, attr);
3232     if (ret) {
3233         /* Convert integer values to float. Should also check for attributes
3234            that can give decimal values here */
3235         for (i=0; i<nAttributes;i++) {
3236             pfValues[i] = attr[i];
3237         }
3238     }
3239
3240     HeapFree(GetProcessHeap(), 0, attr);
3241     return ret;
3242 }
3243
3244 /**
3245  * X11DRV_wglBindTexImageARB
3246  *
3247  * WGL_ARB_render_texture: wglBindTexImageARB
3248  */
3249 static GLboolean WINAPI X11DRV_wglBindTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3250 {
3251     Wine_GLPBuffer* object = hPbuffer;
3252     GLboolean ret = GL_FALSE;
3253
3254     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3255     if (NULL == object) {
3256         SetLastError(ERROR_INVALID_HANDLE);
3257         return GL_FALSE;
3258     }
3259     if (!object->use_render_texture) {
3260         SetLastError(ERROR_INVALID_HANDLE);
3261         return GL_FALSE;
3262     }
3263
3264     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3265         static int init = 0;
3266         int prev_binded_texture = 0;
3267         GLXContext prev_context;
3268         Drawable prev_drawable;
3269         GLXContext tmp_context;
3270
3271         wine_tsx11_lock();
3272         prev_context = pglXGetCurrentContext();
3273         prev_drawable = pglXGetCurrentDrawable();
3274
3275         /* Our render_texture emulation is basic and lacks some features (1D/Cube support).
3276            This is mostly due to lack of demos/games using them. Further the use of glReadPixels
3277            isn't ideal performance wise but I wasn't able to get other ways working.
3278         */
3279         if(!init) {
3280             init = 1; /* Only show the FIXME once for performance reasons */
3281             FIXME("partial stub!\n");
3282         }
3283
3284         TRACE("drawable=%p, context=%p\n", (void*)object->drawable, prev_context);
3285         tmp_context = pglXCreateNewContext(gdi_display, object->fmt->fbconfig, object->fmt->render_type, prev_context, True);
3286
3287         pglGetIntegerv(object->texture_bind_target, &prev_binded_texture);
3288
3289         /* Switch to our pbuffer */
3290         pglXMakeCurrent(gdi_display, object->drawable, tmp_context);
3291
3292         /* Make sure that the prev_binded_texture is set as the current texture state isn't shared between contexts.
3293          * After that upload the pbuffer texture data. */
3294         pglBindTexture(object->texture_target, prev_binded_texture);
3295         pglCopyTexImage2D(object->texture_target, 0, object->use_render_texture, 0, 0, object->width, object->height, 0);
3296
3297         /* Switch back to the original drawable and upload the pbuffer-texture */
3298         pglXMakeCurrent(object->display, prev_drawable, prev_context);
3299         pglXDestroyContext(gdi_display, tmp_context);
3300         wine_tsx11_unlock();
3301         return GL_TRUE;
3302     }
3303
3304     if (NULL != pglXBindTexImageATI) {
3305         int buffer;
3306
3307         switch(iBuffer)
3308         {
3309             case WGL_FRONT_LEFT_ARB:
3310                 buffer = GLX_FRONT_LEFT_ATI;
3311                 break;
3312             case WGL_FRONT_RIGHT_ARB:
3313                 buffer = GLX_FRONT_RIGHT_ATI;
3314                 break;
3315             case WGL_BACK_LEFT_ARB:
3316                 buffer = GLX_BACK_LEFT_ATI;
3317                 break;
3318             case WGL_BACK_RIGHT_ARB:
3319                 buffer = GLX_BACK_RIGHT_ATI;
3320                 break;
3321             default:
3322                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3323                 return FALSE;
3324         }
3325
3326         /* In the sample 'ogl_offscreen_rendering_3' from codesampler.net I get garbage on the screen.
3327          * I'm not sure if that's a bug in the ATI extension or in the program. I think that the program
3328          * expected a single buffering format since it didn't ask for double buffering. A buffer swap
3329          * fixed the program. I don't know what the correct behavior is. On the other hand that demo
3330          * works fine using our pbuffer emulation path.
3331          */
3332         wine_tsx11_lock();
3333         ret = pglXBindTexImageATI(object->display, object->drawable, buffer);
3334         wine_tsx11_unlock();
3335     }
3336     return ret;
3337 }
3338
3339 /**
3340  * X11DRV_wglReleaseTexImageARB
3341  *
3342  * WGL_ARB_render_texture: wglReleaseTexImageARB
3343  */
3344 static GLboolean WINAPI X11DRV_wglReleaseTexImageARB(HPBUFFERARB hPbuffer, int iBuffer)
3345 {
3346     Wine_GLPBuffer* object = hPbuffer;
3347     GLboolean ret = GL_FALSE;
3348
3349     TRACE("(%p, %d)\n", hPbuffer, iBuffer);
3350     if (NULL == object) {
3351         SetLastError(ERROR_INVALID_HANDLE);
3352         return GL_FALSE;
3353     }
3354     if (!object->use_render_texture) {
3355         SetLastError(ERROR_INVALID_HANDLE);
3356         return GL_FALSE;
3357     }
3358     if (!use_render_texture_ati && 1 == use_render_texture_emulation) {
3359         return GL_TRUE;
3360     }
3361     if (NULL != pglXReleaseTexImageATI) {
3362         int buffer;
3363
3364         switch(iBuffer)
3365         {
3366             case WGL_FRONT_LEFT_ARB:
3367                 buffer = GLX_FRONT_LEFT_ATI;
3368                 break;
3369             case WGL_FRONT_RIGHT_ARB:
3370                 buffer = GLX_FRONT_RIGHT_ATI;
3371                 break;
3372             case WGL_BACK_LEFT_ARB:
3373                 buffer = GLX_BACK_LEFT_ATI;
3374                 break;
3375             case WGL_BACK_RIGHT_ARB:
3376                 buffer = GLX_BACK_RIGHT_ATI;
3377                 break;
3378             default:
3379                 ERR("Unknown iBuffer=%#x\n", iBuffer);
3380                 return FALSE;
3381         }
3382         wine_tsx11_lock();
3383         ret = pglXReleaseTexImageATI(object->display, object->drawable, buffer);
3384         wine_tsx11_unlock();
3385     }
3386     return ret;
3387 }
3388
3389 /**
3390  * X11DRV_wglGetExtensionsStringEXT
3391  *
3392  * WGL_EXT_extensions_string: wglGetExtensionsStringEXT
3393  */
3394 static const char * WINAPI X11DRV_wglGetExtensionsStringEXT(void) {
3395     TRACE("() returning \"%s\"\n", WineGLInfo.wglExtensions);
3396     return WineGLInfo.wglExtensions;
3397 }
3398
3399 /**
3400  * X11DRV_wglGetSwapIntervalEXT
3401  *
3402  * WGL_EXT_swap_control: wglGetSwapIntervalEXT
3403  */
3404 static int WINAPI X11DRV_wglGetSwapIntervalEXT(VOID) {
3405     /* GLX_SGI_swap_control doesn't have any provisions for getting the swap
3406      * interval, so the swap interval has to be tracked. */
3407     TRACE("()\n");
3408     return swap_interval;
3409 }
3410
3411 /**
3412  * X11DRV_wglSwapIntervalEXT
3413  *
3414  * WGL_EXT_swap_control: wglSwapIntervalEXT
3415  */
3416 static BOOL WINAPI X11DRV_wglSwapIntervalEXT(int interval) {
3417     BOOL ret = TRUE;
3418
3419     TRACE("(%d)\n", interval);
3420
3421     if (interval < 0)
3422     {
3423         SetLastError(ERROR_INVALID_DATA);
3424         return FALSE;
3425     }
3426     else if (interval == 0)
3427     {
3428         /* wglSwapIntervalEXT considers an interval value of zero to mean that
3429          * vsync should be disabled, but glXSwapIntervalSGI considers such a
3430          * value to be an error. Just silently ignore the request for now. */
3431         WARN("Request to disable vertical sync is not handled\n");
3432         swap_interval = 0;
3433     }
3434     else
3435     {
3436         if (pglXSwapIntervalSGI)
3437         {
3438             wine_tsx11_lock();
3439             ret = !pglXSwapIntervalSGI(interval);
3440             wine_tsx11_unlock();
3441         }
3442         else
3443             WARN("GLX_SGI_swap_control extension is not available\n");
3444
3445         if (ret)
3446             swap_interval = interval;
3447         else
3448             SetLastError(ERROR_DC_NOT_FOUND);
3449     }
3450
3451     return ret;
3452 }
3453
3454 /**
3455  * X11DRV_wglAllocateMemoryNV
3456  *
3457  * WGL_NV_vertex_array_range: wglAllocateMemoryNV
3458  */
3459 static void* WINAPI X11DRV_wglAllocateMemoryNV(GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority) {
3460     void *ret = NULL;
3461     TRACE("(%d, %f, %f, %f)\n", size, readfreq, writefreq, priority );
3462
3463     if (pglXAllocateMemoryNV)
3464     {
3465         wine_tsx11_lock();
3466         ret = pglXAllocateMemoryNV(size, readfreq, writefreq, priority);
3467         wine_tsx11_unlock();
3468     }
3469     return ret;
3470 }
3471
3472 /**
3473  * X11DRV_wglFreeMemoryNV
3474  *
3475  * WGL_NV_vertex_array_range: wglFreeMemoryNV
3476  */
3477 static void WINAPI X11DRV_wglFreeMemoryNV(GLvoid* pointer) {
3478     TRACE("(%p)\n", pointer);
3479     if (pglXFreeMemoryNV == NULL)
3480         return;
3481
3482     wine_tsx11_lock();
3483     pglXFreeMemoryNV(pointer);
3484     wine_tsx11_unlock();
3485 }
3486
3487 /**
3488  * X11DRV_wglSetPixelFormatWINE
3489  *
3490  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
3491  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
3492  */
3493 BOOL CDECL X11DRV_wglSetPixelFormatWINE(X11DRV_PDEVICE *physDev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
3494 {
3495     TRACE("(%p,%d,%p)\n", physDev, iPixelFormat, ppfd);
3496
3497     if (!has_opengl()) return FALSE;
3498
3499     if (physDev->current_pf == iPixelFormat) return TRUE;
3500
3501     /* Relay to the core SetPixelFormat */
3502     TRACE("Changing iPixelFormat from %d to %d\n", physDev->current_pf, iPixelFormat);
3503     return internal_SetPixelFormat(physDev, iPixelFormat, ppfd);
3504 }
3505
3506 /**
3507  * glxRequireVersion (internal)
3508  *
3509  * Check if the supported GLX version matches requiredVersion.
3510  */
3511 static BOOL glxRequireVersion(int requiredVersion)
3512 {
3513     /* Both requiredVersion and glXVersion[1] contains the minor GLX version */
3514     if(requiredVersion <= WineGLInfo.glxVersion[1])
3515         return TRUE;
3516
3517     return FALSE;
3518 }
3519
3520 static BOOL glxRequireExtension(const char *requiredExtension)
3521 {
3522     if (strstr(WineGLInfo.glxExtensions, requiredExtension) == NULL) {
3523         return FALSE;
3524     }
3525
3526     return TRUE;
3527 }
3528
3529 static void register_extension_string(const char *ext)
3530 {
3531     if (WineGLInfo.wglExtensions[0])
3532         strcat(WineGLInfo.wglExtensions, " ");
3533     strcat(WineGLInfo.wglExtensions, ext);
3534
3535     TRACE("'%s'\n", ext);
3536 }
3537
3538 static BOOL register_extension(const WineGLExtension * ext)
3539 {
3540     int i;
3541
3542     assert( WineGLExtensionListSize < MAX_EXTENSIONS );
3543     WineGLExtensionList[WineGLExtensionListSize++] = ext;
3544
3545     register_extension_string(ext->extName);
3546
3547     for (i = 0; ext->extEntryPoints[i].funcName; ++i)
3548         TRACE("    - '%s'\n", ext->extEntryPoints[i].funcName);
3549
3550     return TRUE;
3551 }
3552
3553 static const WineGLExtension WGL_internal_functions =
3554 {
3555   "",
3556   {
3557     { "wglGetIntegerv", X11DRV_wglGetIntegerv },
3558     { "wglFinish", X11DRV_wglFinish },
3559     { "wglFlush", X11DRV_wglFlush },
3560   }
3561 };
3562
3563
3564 static const WineGLExtension WGL_ARB_create_context =
3565 {
3566   "WGL_ARB_create_context",
3567   {
3568     { "wglCreateContextAttribsARB", X11DRV_wglCreateContextAttribsARB },
3569   }
3570 };
3571
3572 static const WineGLExtension WGL_ARB_extensions_string =
3573 {
3574   "WGL_ARB_extensions_string",
3575   {
3576     { "wglGetExtensionsStringARB", X11DRV_wglGetExtensionsStringARB },
3577   }
3578 };
3579
3580 static const WineGLExtension WGL_ARB_make_current_read =
3581 {
3582   "WGL_ARB_make_current_read",
3583   {
3584     { "wglGetCurrentReadDCARB", X11DRV_wglGetCurrentReadDCARB },
3585     { "wglMakeContextCurrentARB", X11DRV_wglMakeContextCurrentARB },
3586   }
3587 };
3588
3589 static const WineGLExtension WGL_ARB_multisample =
3590 {
3591   "WGL_ARB_multisample",
3592 };
3593
3594 static const WineGLExtension WGL_ARB_pbuffer =
3595 {
3596   "WGL_ARB_pbuffer",
3597   {
3598     { "wglCreatePbufferARB", X11DRV_wglCreatePbufferARB },
3599     { "wglDestroyPbufferARB", X11DRV_wglDestroyPbufferARB },
3600     { "wglGetPbufferDCARB", X11DRV_wglGetPbufferDCARB },
3601     { "wglQueryPbufferARB", X11DRV_wglQueryPbufferARB },
3602     { "wglReleasePbufferDCARB", X11DRV_wglReleasePbufferDCARB },
3603     { "wglSetPbufferAttribARB", X11DRV_wglSetPbufferAttribARB },
3604   }
3605 };
3606
3607 static const WineGLExtension WGL_ARB_pixel_format =
3608 {
3609   "WGL_ARB_pixel_format",
3610   {
3611     { "wglChoosePixelFormatARB", X11DRV_wglChoosePixelFormatARB },
3612     { "wglGetPixelFormatAttribfvARB", X11DRV_wglGetPixelFormatAttribfvARB },
3613     { "wglGetPixelFormatAttribivARB", X11DRV_wglGetPixelFormatAttribivARB },
3614   }
3615 };
3616
3617 static const WineGLExtension WGL_ARB_render_texture =
3618 {
3619   "WGL_ARB_render_texture",
3620   {
3621     { "wglBindTexImageARB", X11DRV_wglBindTexImageARB },
3622     { "wglReleaseTexImageARB", X11DRV_wglReleaseTexImageARB },
3623   }
3624 };
3625
3626 static const WineGLExtension WGL_EXT_extensions_string =
3627 {
3628   "WGL_EXT_extensions_string",
3629   {
3630     { "wglGetExtensionsStringEXT", X11DRV_wglGetExtensionsStringEXT },
3631   }
3632 };
3633
3634 static const WineGLExtension WGL_EXT_swap_control =
3635 {
3636   "WGL_EXT_swap_control",
3637   {
3638     { "wglSwapIntervalEXT", X11DRV_wglSwapIntervalEXT },
3639     { "wglGetSwapIntervalEXT", X11DRV_wglGetSwapIntervalEXT },
3640   }
3641 };
3642
3643 static const WineGLExtension WGL_NV_vertex_array_range =
3644 {
3645   "WGL_NV_vertex_array_range",
3646   {
3647     { "wglAllocateMemoryNV", X11DRV_wglAllocateMemoryNV },
3648     { "wglFreeMemoryNV", X11DRV_wglFreeMemoryNV },
3649   }
3650 };
3651
3652 static const WineGLExtension WGL_WINE_pixel_format_passthrough =
3653 {
3654   "WGL_WINE_pixel_format_passthrough",
3655   {
3656     { "wglSetPixelFormatWINE", X11DRV_wglSetPixelFormatWINE },
3657   }
3658 };
3659
3660 /**
3661  * X11DRV_WineGL_LoadExtensions
3662  */
3663 static void X11DRV_WineGL_LoadExtensions(void)
3664 {
3665     WineGLInfo.wglExtensions[0] = 0;
3666
3667     /* Load Wine internal functions */
3668     register_extension(&WGL_internal_functions);
3669
3670     /* ARB Extensions */
3671
3672     if(glxRequireExtension("GLX_ARB_create_context"))
3673     {
3674         register_extension(&WGL_ARB_create_context);
3675
3676         if(glxRequireExtension("GLX_ARB_create_context_profile"))
3677             register_extension_string("WGL_ARB_create_context_profile");
3678     }
3679
3680     if(glxRequireExtension("GLX_ARB_fbconfig_float"))
3681     {
3682         register_extension_string("WGL_ARB_pixel_format_float");
3683         register_extension_string("WGL_ATI_pixel_format_float");
3684     }
3685
3686     register_extension(&WGL_ARB_extensions_string);
3687
3688     if (glxRequireVersion(3))
3689         register_extension(&WGL_ARB_make_current_read);
3690
3691     if (glxRequireExtension("GLX_ARB_multisample"))
3692         register_extension(&WGL_ARB_multisample);
3693
3694     /* In general pbuffer functionality requires support in the X-server. The functionality is
3695      * available either when the GLX_SGIX_pbuffer is present or when the GLX server version is 1.3.
3696      * All display drivers except for Nvidia's use the GLX module from Xfree86/Xorg which only
3697      * supports GLX 1.2. The endresult is that only Nvidia's drivers support pbuffers.
3698      *
3699      * The only other drive which has pbuffer support is Ati's FGLRX driver. They provide clientside GLX 1.3 support
3700      * without support in the X-server (which other Mesa based drivers require).
3701      *
3702      * Support pbuffers when the GLX version is 1.3 and GLX_SGIX_pbuffer is available. Further pbuffers can
3703      * also be supported when GLX_ATI_render_texture is available. This extension depends on pbuffers, so when it
3704      * is available pbuffers must be available too. */
3705     if ( (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer")) || glxRequireExtension("GLX_ATI_render_texture"))
3706         register_extension(&WGL_ARB_pbuffer);
3707
3708     register_extension(&WGL_ARB_pixel_format);
3709
3710     /* Support WGL_ARB_render_texture when there's support or pbuffer based emulation */
3711     if (glxRequireExtension("GLX_ATI_render_texture") ||
3712         glxRequireExtension("GLX_ARB_render_texture") ||
3713         (glxRequireVersion(3) && glxRequireExtension("GLX_SGIX_pbuffer") && use_render_texture_emulation))
3714     {
3715         register_extension(&WGL_ARB_render_texture);
3716
3717         /* The WGL version of GLX_NV_float_buffer requires render_texture */
3718         if(glxRequireExtension("GLX_NV_float_buffer"))
3719             register_extension_string("WGL_NV_float_buffer");
3720
3721         /* Again there's no GLX equivalent for this extension, so depend on the required GL extension */
3722         if(strstr(WineGLInfo.glExtensions, "GL_NV_texture_rectangle") != NULL)
3723             register_extension_string("WGL_NV_texture_rectangle");
3724     }
3725
3726     /* EXT Extensions */
3727
3728     register_extension(&WGL_EXT_extensions_string);
3729
3730     /* Load this extension even when it isn't backed by a GLX extension because it is has been around for ages.
3731      * Games like Call of Duty and K.O.T.O.R. rely on it. Further our emulation is good enough. */
3732     register_extension(&WGL_EXT_swap_control);
3733
3734     if(glxRequireExtension("GLX_EXT_framebuffer_sRGB"))
3735         register_extension_string("WGL_EXT_framebuffer_sRGB");
3736
3737     if(glxRequireExtension("GLX_EXT_fbconfig_packed_float"))
3738         register_extension_string("WGL_EXT_pixel_format_packed_float");
3739
3740     /* The OpenGL extension GL_NV_vertex_array_range adds wgl/glX functions which aren't exported as 'real' wgl/glX extensions. */
3741     if(strstr(WineGLInfo.glExtensions, "GL_NV_vertex_array_range") != NULL)
3742         register_extension(&WGL_NV_vertex_array_range);
3743
3744     /* WINE-specific WGL Extensions */
3745
3746     /* In WineD3D we need the ability to set the pixel format more than once (e.g. after a device reset).
3747      * The default wglSetPixelFormat doesn't allow this, so add our own which allows it.
3748      */
3749     register_extension(&WGL_WINE_pixel_format_passthrough);
3750 }
3751
3752
3753 Drawable get_glxdrawable(X11DRV_PDEVICE *physDev)
3754 {
3755     Drawable ret;
3756
3757     if(physDev->bitmap)
3758     {
3759         if (physDev->bitmap->hbitmap == BITMAP_stock_phys_bitmap.hbitmap)
3760             ret = physDev->drawable; /* PBuffer */
3761         else
3762             ret = physDev->bitmap->glxpixmap;
3763     }
3764     else if(physDev->gl_drawable)
3765         ret = physDev->gl_drawable;
3766     else
3767         ret = physDev->drawable;
3768     return ret;
3769 }
3770
3771 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
3772 {
3773     wine_tsx11_lock(); 
3774     pglXDestroyGLXPixmap(display, glxpixmap);
3775     wine_tsx11_unlock(); 
3776     return TRUE;
3777 }
3778
3779 /**
3780  * X11DRV_SwapBuffers
3781  *
3782  * Swap the buffers of this DC
3783  */
3784 BOOL CDECL X11DRV_SwapBuffers(X11DRV_PDEVICE *physDev)
3785 {
3786   GLXDrawable drawable;
3787   Wine_GLContext *ctx = NtCurrentTeb()->glContext;
3788
3789   if (!has_opengl()) return FALSE;
3790
3791   TRACE("(%p)\n", physDev);
3792
3793   drawable = get_glxdrawable(physDev);
3794
3795   wine_tsx11_lock();
3796   sync_context(ctx);
3797   if(physDev->pixmap) {
3798       if(pglXCopySubBufferMESA) {
3799           int w = physDev->dc_rect.right - physDev->dc_rect.left;
3800           int h = physDev->dc_rect.bottom - physDev->dc_rect.top;
3801
3802           /* (glX)SwapBuffers has an implicit glFlush effect, however
3803            * GLX_MESA_copy_sub_buffer doesn't. Make sure GL is flushed before
3804            * copying */
3805           pglFlush();
3806           if(w > 0 && h > 0)
3807               pglXCopySubBufferMESA(gdi_display, drawable, 0, 0, w, h);
3808       }
3809       else
3810           pglXSwapBuffers(gdi_display, drawable);
3811   }
3812   else
3813       pglXSwapBuffers(gdi_display, drawable);
3814
3815   flush_gl_drawable(physDev);
3816   wine_tsx11_unlock();
3817
3818   /* FPS support */
3819   if (TRACE_ON(fps))
3820   {
3821       static long prev_time, start_time;
3822       static unsigned long frames, frames_total;
3823
3824       DWORD time = GetTickCount();
3825       frames++;
3826       frames_total++;
3827       /* every 1.5 seconds */
3828       if (time - prev_time > 1500) {
3829           TRACE_(fps)("@ approx %.2ffps, total %.2ffps\n",
3830                       1000.0*frames/(time - prev_time), 1000.0*frames_total/(time - start_time));
3831           prev_time = time;
3832           frames = 0;
3833           if(start_time == 0) start_time = time;
3834       }
3835   }
3836
3837   return TRUE;
3838 }
3839
3840 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
3841 {
3842     WineGLPixelFormat *fmt;
3843     XVisualInfo *ret;
3844
3845     fmt = ConvertPixelFormatGLXtoWGL(gdi_display, fbconfig_id, 0 /* no flags */);
3846     if(fmt == NULL)
3847         return NULL;
3848
3849     wine_tsx11_lock();
3850     ret = pglXGetVisualFromFBConfig(gdi_display, fmt->fbconfig);
3851     wine_tsx11_unlock();
3852     return ret;
3853 }
3854
3855 #else  /* no OpenGL includes */
3856
3857 void X11DRV_OpenGL_Cleanup(void)
3858 {
3859 }
3860
3861 static inline void opengl_error(void)
3862 {
3863     static int warned;
3864     if (!warned++) ERR("No OpenGL support compiled in.\n");
3865 }
3866
3867 int pixelformat_from_fbconfig_id(XID fbconfig_id)
3868 {
3869     return 0;
3870 }
3871
3872 void mark_drawable_dirty(Drawable old, Drawable new)
3873 {
3874 }
3875
3876 void flush_gl_drawable(X11DRV_PDEVICE *physDev)
3877 {
3878 }
3879
3880 Drawable create_glxpixmap(Display *display, XVisualInfo *vis, Pixmap parent)
3881 {
3882     return 0;
3883 }
3884
3885 /***********************************************************************
3886  *              ChoosePixelFormat (X11DRV.@)
3887  */
3888 int CDECL X11DRV_ChoosePixelFormat(X11DRV_PDEVICE *physDev,
3889                                      const PIXELFORMATDESCRIPTOR *ppfd) {
3890   opengl_error();
3891   return 0;
3892 }
3893
3894 /***********************************************************************
3895  *              DescribePixelFormat (X11DRV.@)
3896  */
3897 int CDECL X11DRV_DescribePixelFormat(X11DRV_PDEVICE *physDev,
3898                                      int iPixelFormat,
3899                                      UINT nBytes,
3900                                      PIXELFORMATDESCRIPTOR *ppfd) {
3901   opengl_error();
3902   return 0;
3903 }
3904
3905 /***********************************************************************
3906  *              GetPixelFormat (X11DRV.@)
3907  */
3908 int CDECL X11DRV_GetPixelFormat(X11DRV_PDEVICE *physDev) {
3909   opengl_error();
3910   return 0;
3911 }
3912
3913 /***********************************************************************
3914  *              SetPixelFormat (X11DRV.@)
3915  */
3916 BOOL CDECL X11DRV_SetPixelFormat(X11DRV_PDEVICE *physDev,
3917                                    int iPixelFormat,
3918                                    const PIXELFORMATDESCRIPTOR *ppfd) {
3919   opengl_error();
3920   return FALSE;
3921 }
3922
3923 /***********************************************************************
3924  *              SwapBuffers (X11DRV.@)
3925  */
3926 BOOL CDECL X11DRV_SwapBuffers(X11DRV_PDEVICE *physDev) {
3927   opengl_error();
3928   return FALSE;
3929 }
3930
3931 /**
3932  * X11DRV_wglCopyContext
3933  *
3934  * For OpenGL32 wglCopyContext.
3935  */
3936 BOOL CDECL X11DRV_wglCopyContext(HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask) {
3937     opengl_error();
3938     return FALSE;
3939 }
3940
3941 /**
3942  * X11DRV_wglCreateContext
3943  *
3944  * For OpenGL32 wglCreateContext.
3945  */
3946 HGLRC CDECL X11DRV_wglCreateContext(X11DRV_PDEVICE *physDev) {
3947     opengl_error();
3948     return NULL;
3949 }
3950
3951 /**
3952  * X11DRV_wglCreateContextAttribsARB
3953  *
3954  * WGL_ARB_create_context: wglCreateContextAttribsARB
3955  */
3956 HGLRC CDECL X11DRV_wglCreateContextAttribsARB(X11DRV_PDEVICE *physDev, HGLRC hShareContext, const int* attribList)
3957 {
3958     opengl_error();
3959     return NULL;
3960 }
3961
3962 /**
3963  * X11DRV_wglDeleteContext
3964  *
3965  * For OpenGL32 wglDeleteContext.
3966  */
3967 BOOL CDECL X11DRV_wglDeleteContext(HGLRC hglrc) {
3968     opengl_error();
3969     return FALSE;
3970 }
3971
3972 /**
3973  * X11DRV_wglGetProcAddress
3974  *
3975  * For OpenGL32 wglGetProcAddress.
3976  */
3977 PROC CDECL X11DRV_wglGetProcAddress(LPCSTR lpszProc) {
3978     opengl_error();
3979     return NULL;
3980 }
3981
3982 HDC CDECL X11DRV_wglGetPbufferDCARB(X11DRV_PDEVICE *hDevice, void *hPbuffer)
3983 {
3984     opengl_error();
3985     return NULL;
3986 }
3987
3988 BOOL CDECL X11DRV_wglMakeContextCurrentARB(X11DRV_PDEVICE* hDrawDev, X11DRV_PDEVICE* hReadDev, HGLRC hglrc) {
3989     opengl_error();
3990     return FALSE;
3991 }
3992
3993 /**
3994  * X11DRV_wglMakeCurrent
3995  *
3996  * For OpenGL32 wglMakeCurrent.
3997  */
3998 BOOL CDECL X11DRV_wglMakeCurrent(X11DRV_PDEVICE *physDev, HGLRC hglrc) {
3999     opengl_error();
4000     return FALSE;
4001 }
4002
4003 /**
4004  * X11DRV_wglShareLists
4005  *
4006  * For OpenGL32 wglShareLists.
4007  */
4008 BOOL CDECL X11DRV_wglShareLists(HGLRC hglrc1, HGLRC hglrc2) {
4009     opengl_error();
4010     return FALSE;
4011 }
4012
4013 /**
4014  * X11DRV_wglUseFontBitmapsA
4015  *
4016  * For OpenGL32 wglUseFontBitmapsA.
4017  */
4018 BOOL CDECL X11DRV_wglUseFontBitmapsA(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
4019 {
4020     opengl_error();
4021     return FALSE;
4022 }
4023
4024 /**
4025  * X11DRV_wglUseFontBitmapsW
4026  *
4027  * For OpenGL32 wglUseFontBitmapsW.
4028  */
4029 BOOL CDECL X11DRV_wglUseFontBitmapsW(X11DRV_PDEVICE *physDev, DWORD first, DWORD count, DWORD listBase)
4030 {
4031     opengl_error();
4032     return FALSE;
4033 }
4034
4035 /**
4036  * X11DRV_wglSetPixelFormatWINE
4037  *
4038  * WGL_WINE_pixel_format_passthrough: wglSetPixelFormatWINE
4039  * This is a WINE-specific wglSetPixelFormat which can set the pixel format multiple times.
4040  */
4041 BOOL CDECL X11DRV_wglSetPixelFormatWINE(X11DRV_PDEVICE *physDev, int iPixelFormat, const PIXELFORMATDESCRIPTOR *ppfd)
4042 {
4043     opengl_error();
4044     return FALSE;
4045 }
4046
4047 Drawable get_glxdrawable(X11DRV_PDEVICE *physDev)
4048 {
4049     return 0;
4050 }
4051
4052 BOOL destroy_glxpixmap(Display *display, XID glxpixmap)
4053 {
4054     return FALSE;
4055 }
4056
4057 XVisualInfo *visual_from_fbconfig_id( XID fbconfig_id )
4058 {
4059     return NULL;
4060 }
4061
4062 #endif /* defined(SONAME_LIBGL) */