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