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