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