msdaps: Add server side stubs for IAccessor.
[wine] / dlls / wined3d / directx.c
1 /*
2  * IWineD3D implementation
3  *
4  * Copyright 2002-2004 Jason Edmeades
5  * Copyright 2003-2004 Raphael Junqueira
6  * Copyright 2004 Christian Costa
7  * Copyright 2005 Oliver Stieber
8  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
9  * Copyright 2009 Henri Verbeet for CodeWeavers
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wined3d_private.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 WINE_DECLARE_DEBUG_CHANNEL(d3d_caps);
31
32 #define GLINFO_LOCATION (*gl_info)
33 #define WINE_DEFAULT_VIDMEM (64 * 1024 * 1024)
34 #define MAKEDWORD_VERSION(maj, min)  ((maj & 0xffff) << 16) | (min & 0xffff)
35
36 /* The d3d device ID */
37 static const GUID IID_D3DDEVICE_D3DUID = { 0xaeb2cdd4, 0x6e41, 0x43ea, { 0x94,0x1c,0x83,0x61,0xcc,0x76,0x07,0x81 } };
38
39 /* Extension detection */
40 static const struct {
41     const char *extension_string;
42     GL_SupportedExt extension;
43     DWORD version;
44 } EXTENSION_MAP[] = {
45     /* APPLE */
46     {"GL_APPLE_client_storage",             APPLE_CLIENT_STORAGE,           0                           },
47     {"GL_APPLE_fence",                      APPLE_FENCE,                    0                           },
48     {"GL_APPLE_float_pixels",               APPLE_FLOAT_PIXELS,             0                           },
49     {"GL_APPLE_flush_buffer_range",         APPLE_FLUSH_BUFFER_RANGE,       0                           },
50     {"GL_APPLE_flush_render",               APPLE_FLUSH_RENDER,             0                           },
51     {"GL_APPLE_ycbcr_422",                  APPLE_YCBCR_422,                0                           },
52
53     /* ARB */
54     {"GL_ARB_color_buffer_float",           ARB_COLOR_BUFFER_FLOAT,         0                           },
55     {"GL_ARB_depth_buffer_float",           ARB_DEPTH_BUFFER_FLOAT,         0                           },
56     {"GL_ARB_depth_clamp",                  ARB_DEPTH_CLAMP,                0                           },
57     {"GL_ARB_depth_texture",                ARB_DEPTH_TEXTURE,              0                           },
58     {"GL_ARB_draw_buffers",                 ARB_DRAW_BUFFERS,               0                           },
59     {"GL_ARB_fragment_program",             ARB_FRAGMENT_PROGRAM,           0                           },
60     {"GL_ARB_fragment_shader",              ARB_FRAGMENT_SHADER,            0                           },
61     {"GL_ARB_framebuffer_object",           ARB_FRAMEBUFFER_OBJECT,         0                           },
62     {"GL_ARB_geometry_shader4",             ARB_GEOMETRY_SHADER4,           0                           },
63     {"GL_ARB_half_float_pixel",             ARB_HALF_FLOAT_PIXEL,           0                           },
64     {"GL_ARB_half_float_vertex",            ARB_HALF_FLOAT_VERTEX,          0                           },
65     {"GL_ARB_imaging",                      ARB_IMAGING,                    0                           },
66     {"GL_ARB_map_buffer_range",             ARB_MAP_BUFFER_RANGE,           0                           },
67     {"GL_ARB_multisample",                  ARB_MULTISAMPLE,                0                           }, /* needs GLX_ARB_MULTISAMPLE as well */
68     {"GL_ARB_multitexture",                 ARB_MULTITEXTURE,               0                           },
69     {"GL_ARB_occlusion_query",              ARB_OCCLUSION_QUERY,            0                           },
70     {"GL_ARB_pixel_buffer_object",          ARB_PIXEL_BUFFER_OBJECT,        0                           },
71     {"GL_ARB_point_parameters",             ARB_POINT_PARAMETERS,           0                           },
72     {"GL_ARB_point_sprite",                 ARB_POINT_SPRITE,               0                           },
73     {"GL_ARB_provoking_vertex",             ARB_PROVOKING_VERTEX,           0                           },
74     {"GL_ARB_shader_objects",               ARB_SHADER_OBJECTS,             0                           },
75     {"GL_ARB_shader_texture_lod",           ARB_SHADER_TEXTURE_LOD,         0                           },
76     {"GL_ARB_shading_language_100",         ARB_SHADING_LANGUAGE_100,       0                           },
77     {"GL_ARB_sync",                         ARB_SYNC,                       0                           },
78     {"GL_ARB_texture_border_clamp",         ARB_TEXTURE_BORDER_CLAMP,       0                           },
79     {"GL_ARB_texture_compression",          ARB_TEXTURE_COMPRESSION,        0                           },
80     {"GL_ARB_texture_cube_map",             ARB_TEXTURE_CUBE_MAP,           0                           },
81     {"GL_ARB_texture_env_add",              ARB_TEXTURE_ENV_ADD,            0                           },
82     {"GL_ARB_texture_env_combine",          ARB_TEXTURE_ENV_COMBINE,        0                           },
83     {"GL_ARB_texture_env_dot3",             ARB_TEXTURE_ENV_DOT3,           0                           },
84     {"GL_ARB_texture_float",                ARB_TEXTURE_FLOAT,              0                           },
85     {"GL_ARB_texture_mirrored_repeat",      ARB_TEXTURE_MIRRORED_REPEAT,    0                           },
86     {"GL_ARB_texture_non_power_of_two",     ARB_TEXTURE_NON_POWER_OF_TWO,   MAKEDWORD_VERSION(2, 0)     },
87     {"GL_ARB_texture_rectangle",            ARB_TEXTURE_RECTANGLE,          0                           },
88     {"GL_ARB_texture_rg",                   ARB_TEXTURE_RG,                 0                           },
89     {"GL_ARB_vertex_array_bgra",            ARB_VERTEX_ARRAY_BGRA,          0                           },
90     {"GL_ARB_vertex_blend",                 ARB_VERTEX_BLEND,               0                           },
91     {"GL_ARB_vertex_buffer_object",         ARB_VERTEX_BUFFER_OBJECT,       0                           },
92     {"GL_ARB_vertex_program",               ARB_VERTEX_PROGRAM,             0                           },
93     {"GL_ARB_vertex_shader",                ARB_VERTEX_SHADER,              0                           },
94
95     /* ATI */
96     {"GL_ATI_fragment_shader",              ATI_FRAGMENT_SHADER,            0                           },
97     {"GL_ATI_separate_stencil",             ATI_SEPARATE_STENCIL,           0                           },
98     {"GL_ATI_texture_compression_3dc",      ATI_TEXTURE_COMPRESSION_3DC,    0                           },
99     {"GL_ATI_texture_env_combine3",         ATI_TEXTURE_ENV_COMBINE3,       0                           },
100     {"GL_ATI_texture_mirror_once",          ATI_TEXTURE_MIRROR_ONCE,        0                           },
101
102     /* EXT */
103     {"GL_EXT_blend_color",                  EXT_BLEND_COLOR,                0                           },
104     {"GL_EXT_blend_equation_separate",      EXT_BLEND_EQUATION_SEPARATE,    0                           },
105     {"GL_EXT_blend_func_separate",          EXT_BLEND_FUNC_SEPARATE,        0                           },
106     {"GL_EXT_blend_minmax",                 EXT_BLEND_MINMAX,               0                           },
107     {"GL_EXT_fog_coord",                    EXT_FOG_COORD,                  0                           },
108     {"GL_EXT_framebuffer_blit",             EXT_FRAMEBUFFER_BLIT,           0                           },
109     {"GL_EXT_framebuffer_multisample",      EXT_FRAMEBUFFER_MULTISAMPLE,    0                           },
110     {"GL_EXT_framebuffer_object",           EXT_FRAMEBUFFER_OBJECT,         0                           },
111     {"GL_EXT_gpu_program_parameters",       EXT_GPU_PROGRAM_PARAMETERS,     0                           },
112     {"GL_EXT_gpu_shader4",                  EXT_GPU_SHADER4,                0                           },
113     {"GL_EXT_packed_depth_stencil",         EXT_PACKED_DEPTH_STENCIL,       0                           },
114     {"GL_EXT_paletted_texture",             EXT_PALETTED_TEXTURE,           0                           },
115     {"GL_EXT_point_parameters",             EXT_POINT_PARAMETERS,           0                           },
116     {"GL_EXT_provoking_vertex",             EXT_PROVOKING_VERTEX,           0                           },
117     {"GL_EXT_secondary_color",              EXT_SECONDARY_COLOR,            0                           },
118     {"GL_EXT_stencil_two_side",             EXT_STENCIL_TWO_SIDE,           0                           },
119     {"GL_EXT_stencil_wrap",                 EXT_STENCIL_WRAP,               0                           },
120     {"GL_EXT_texture3D",                    EXT_TEXTURE3D,                  MAKEDWORD_VERSION(1, 2)     },
121     {"GL_EXT_texture_compression_rgtc",     EXT_TEXTURE_COMPRESSION_RGTC,   0                           },
122     {"GL_EXT_texture_compression_s3tc",     EXT_TEXTURE_COMPRESSION_S3TC,   0                           },
123     {"GL_EXT_texture_env_add",              EXT_TEXTURE_ENV_ADD,            0                           },
124     {"GL_EXT_texture_env_combine",          EXT_TEXTURE_ENV_COMBINE,        0                           },
125     {"GL_EXT_texture_env_dot3",             EXT_TEXTURE_ENV_DOT3,           0                           },
126     {"GL_EXT_texture_filter_anisotropic",   EXT_TEXTURE_FILTER_ANISOTROPIC, 0                           },
127     {"GL_EXT_texture_lod",                  EXT_TEXTURE_LOD,                0                           },
128     {"GL_EXT_texture_lod_bias",             EXT_TEXTURE_LOD_BIAS,           0                           },
129     {"GL_EXT_texture_sRGB",                 EXT_TEXTURE_SRGB,               0                           },
130     {"GL_EXT_texture_swizzle",              EXT_TEXTURE_SWIZZLE,            0                           },
131     {"GL_EXT_vertex_array_bgra",            EXT_VERTEX_ARRAY_BGRA,          0                           },
132     {"GL_EXT_vertex_shader",                EXT_VERTEX_SHADER,              0                           },
133
134     /* NV */
135     {"GL_NV_depth_clamp",                   NV_DEPTH_CLAMP,                 0                           },
136     {"GL_NV_fence",                         NV_FENCE,                       0                           },
137     {"GL_NV_fog_distance",                  NV_FOG_DISTANCE,                0                           },
138     {"GL_NV_fragment_program",              NV_FRAGMENT_PROGRAM,            0                           },
139     {"GL_NV_fragment_program2",             NV_FRAGMENT_PROGRAM2,           0                           },
140     {"GL_NV_fragment_program_option",       NV_FRAGMENT_PROGRAM_OPTION,     0                           },
141     {"GL_NV_half_float",                    NV_HALF_FLOAT,                  0                           },
142     {"GL_NV_light_max_exponent",            NV_LIGHT_MAX_EXPONENT,          0                           },
143     {"GL_NV_register_combiners",            NV_REGISTER_COMBINERS,          0                           },
144     {"GL_NV_register_combiners2",           NV_REGISTER_COMBINERS2,         0                           },
145     {"GL_NV_texgen_reflection",             NV_TEXGEN_REFLECTION,           0                           },
146     {"GL_NV_texture_env_combine4",          NV_TEXTURE_ENV_COMBINE4,        0                           },
147     {"GL_NV_texture_shader",                NV_TEXTURE_SHADER,              0                           },
148     {"GL_NV_texture_shader2",               NV_TEXTURE_SHADER2,             0                           },
149     {"GL_NV_texture_shader3",               NV_TEXTURE_SHADER3,             0                           },
150     {"GL_NV_vertex_program",                NV_VERTEX_PROGRAM,              0                           },
151     {"GL_NV_vertex_program1_1",             NV_VERTEX_PROGRAM1_1,           0                           },
152     {"GL_NV_vertex_program2",               NV_VERTEX_PROGRAM2,             0                           },
153     {"GL_NV_vertex_program2_option",        NV_VERTEX_PROGRAM2_OPTION,      0                           },
154     {"GL_NV_vertex_program3",               NV_VERTEX_PROGRAM3,             0                           },
155
156     /* SGI */
157     {"GL_SGIS_generate_mipmap",             SGIS_GENERATE_MIPMAP,           0                           },
158 };
159
160 /**********************************************************
161  * Utility functions follow
162  **********************************************************/
163
164 static HRESULT WINAPI IWineD3DImpl_CheckDeviceFormat(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, WINED3DFORMAT AdapterFormat, DWORD Usage, WINED3DRESOURCETYPE RType, WINED3DFORMAT CheckFormat, WINED3DSURFTYPE SurfaceType);
165
166 const struct min_lookup minMipLookup[] =
167 {
168     /* NONE         POINT                       LINEAR */
169     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
170     {{GL_NEAREST,   GL_NEAREST_MIPMAP_NEAREST,  GL_NEAREST_MIPMAP_LINEAR}}, /* POINT*/
171     {{GL_LINEAR,    GL_LINEAR_MIPMAP_NEAREST,   GL_LINEAR_MIPMAP_LINEAR}},  /* LINEAR */
172 };
173
174 const struct min_lookup minMipLookup_noFilter[] =
175 {
176     /* NONE         POINT                       LINEAR */
177     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
178     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* POINT */
179     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* LINEAR */
180 };
181
182 const struct min_lookup minMipLookup_noMip[] =
183 {
184     /* NONE         POINT                       LINEAR */
185     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* NONE */
186     {{GL_NEAREST,   GL_NEAREST,                 GL_NEAREST}},               /* POINT */
187     {{GL_LINEAR,    GL_LINEAR,                  GL_LINEAR }},               /* LINEAR */
188 };
189
190 const GLenum magLookup[] =
191 {
192     /* NONE     POINT       LINEAR */
193     GL_NEAREST, GL_NEAREST, GL_LINEAR,
194 };
195
196 const GLenum magLookup_noFilter[] =
197 {
198     /* NONE     POINT       LINEAR */
199     GL_NEAREST, GL_NEAREST, GL_NEAREST,
200 };
201
202 /* drawStridedSlow attributes */
203 glAttribFunc position_funcs[WINED3D_FFP_EMIT_COUNT];
204 glAttribFunc diffuse_funcs[WINED3D_FFP_EMIT_COUNT];
205 glAttribFunc specular_func_3ubv;
206 glAttribFunc specular_funcs[WINED3D_FFP_EMIT_COUNT];
207 glAttribFunc normal_funcs[WINED3D_FFP_EMIT_COUNT];
208 glMultiTexCoordFunc multi_texcoord_funcs[WINED3D_FFP_EMIT_COUNT];
209
210 /**
211  * Note: GL seems to trap if GetDeviceCaps is called before any HWND's created,
212  * i.e., there is no GL Context - Get a default rendering context to enable the
213  * function query some info from GL.
214  */
215
216 struct wined3d_fake_gl_ctx
217 {
218     HDC dc;
219     HWND wnd;
220     HGLRC gl_ctx;
221     HDC restore_dc;
222     HGLRC restore_gl_ctx;
223 };
224
225 static void WineD3D_ReleaseFakeGLContext(struct wined3d_fake_gl_ctx *ctx)
226 {
227     TRACE_(d3d_caps)("Destroying fake GL context.\n");
228
229     if (!pwglMakeCurrent(NULL, NULL))
230     {
231         ERR_(d3d_caps)("Failed to disable fake GL context.\n");
232     }
233
234     if (!pwglDeleteContext(ctx->gl_ctx))
235     {
236         DWORD err = GetLastError();
237         ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx->gl_ctx, err);
238     }
239
240     ReleaseDC(ctx->wnd, ctx->dc);
241     DestroyWindow(ctx->wnd);
242
243     if (ctx->restore_gl_ctx && !pwglMakeCurrent(ctx->restore_dc, ctx->restore_gl_ctx))
244     {
245         ERR_(d3d_caps)("Failed to restore previous GL context.\n");
246     }
247 }
248
249 static BOOL WineD3D_CreateFakeGLContext(struct wined3d_fake_gl_ctx *ctx)
250 {
251     PIXELFORMATDESCRIPTOR pfd;
252     int iPixelFormat;
253
254     TRACE("getting context...\n");
255
256     ctx->restore_dc = pwglGetCurrentDC();
257     ctx->restore_gl_ctx = pwglGetCurrentContext();
258
259     /* We need a fake window as a hdc retrieved using GetDC(0) can't be used for much GL purposes. */
260     ctx->wnd = CreateWindowA(WINED3D_OPENGL_WINDOW_CLASS_NAME, "WineD3D fake window",
261             WS_OVERLAPPEDWINDOW, 10, 10, 10, 10, NULL, NULL, NULL, NULL);
262     if (!ctx->wnd)
263     {
264         ERR_(d3d_caps)("Failed to create a window.\n");
265         goto fail;
266     }
267
268     ctx->dc = GetDC(ctx->wnd);
269     if (!ctx->dc)
270     {
271         ERR_(d3d_caps)("Failed to get a DC.\n");
272         goto fail;
273     }
274
275     /* PixelFormat selection */
276     ZeroMemory(&pfd, sizeof(pfd));
277     pfd.nSize = sizeof(pfd);
278     pfd.nVersion = 1;
279     pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW; /* PFD_GENERIC_ACCELERATED */
280     pfd.iPixelType = PFD_TYPE_RGBA;
281     pfd.cColorBits = 32;
282     pfd.iLayerType = PFD_MAIN_PLANE;
283
284     iPixelFormat = ChoosePixelFormat(ctx->dc, &pfd);
285     if (!iPixelFormat)
286     {
287         /* If this happens something is very wrong as ChoosePixelFormat barely fails. */
288         ERR_(d3d_caps)("Can't find a suitable iPixelFormat.\n");
289         goto fail;
290     }
291     DescribePixelFormat(ctx->dc, iPixelFormat, sizeof(pfd), &pfd);
292     SetPixelFormat(ctx->dc, iPixelFormat, &pfd);
293
294     /* Create a GL context. */
295     ctx->gl_ctx = pwglCreateContext(ctx->dc);
296     if (!ctx->gl_ctx)
297     {
298         WARN_(d3d_caps)("Error creating default context for capabilities initialization.\n");
299         goto fail;
300     }
301
302     /* Make it the current GL context. */
303     if (!context_set_current(NULL))
304     {
305         ERR_(d3d_caps)("Failed to clear current D3D context.\n");
306     }
307
308     if (!pwglMakeCurrent(ctx->dc, ctx->gl_ctx))
309     {
310         ERR_(d3d_caps)("Failed to make fake GL context current.\n");
311         goto fail;
312     }
313
314     return TRUE;
315
316 fail:
317     if (ctx->gl_ctx) pwglDeleteContext(ctx->gl_ctx);
318     ctx->gl_ctx = NULL;
319     if (ctx->dc) ReleaseDC(ctx->wnd, ctx->dc);
320     ctx->dc = NULL;
321     if (ctx->wnd) DestroyWindow(ctx->wnd);
322     ctx->wnd = NULL;
323     if (ctx->restore_gl_ctx && !pwglMakeCurrent(ctx->restore_dc, ctx->restore_gl_ctx))
324     {
325         ERR_(d3d_caps)("Failed to restore previous GL context.\n");
326     }
327
328     return FALSE;
329 }
330
331 /* Adjust the amount of used texture memory */
332 long WineD3DAdapterChangeGLRam(IWineD3DDeviceImpl *D3DDevice, long glram)
333 {
334     struct wined3d_adapter *adapter = D3DDevice->adapter;
335
336     adapter->UsedTextureRam += glram;
337     TRACE("Adjusted gl ram by %ld to %d\n", glram, adapter->UsedTextureRam);
338     return adapter->UsedTextureRam;
339 }
340
341 static void wined3d_adapter_cleanup(struct wined3d_adapter *adapter)
342 {
343     HeapFree(GetProcessHeap(), 0, adapter->gl_info.gl_formats);
344     HeapFree(GetProcessHeap(), 0, adapter->cfgs);
345 }
346
347 /**********************************************************
348  * IUnknown parts follows
349  **********************************************************/
350
351 static HRESULT WINAPI IWineD3DImpl_QueryInterface(IWineD3D *iface,REFIID riid,LPVOID *ppobj)
352 {
353     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
354
355     TRACE("(%p)->(%s,%p)\n",This,debugstr_guid(riid),ppobj);
356     if (IsEqualGUID(riid, &IID_IUnknown)
357         || IsEqualGUID(riid, &IID_IWineD3DBase)
358         || IsEqualGUID(riid, &IID_IWineD3DDevice)) {
359         IUnknown_AddRef(iface);
360         *ppobj = This;
361         return S_OK;
362     }
363     *ppobj = NULL;
364     return E_NOINTERFACE;
365 }
366
367 static ULONG WINAPI IWineD3DImpl_AddRef(IWineD3D *iface) {
368     IWineD3DImpl *This = (IWineD3DImpl *)iface;
369     ULONG refCount = InterlockedIncrement(&This->ref);
370
371     TRACE("(%p) : AddRef increasing from %d\n", This, refCount - 1);
372     return refCount;
373 }
374
375 static ULONG WINAPI IWineD3DImpl_Release(IWineD3D *iface) {
376     IWineD3DImpl *This = (IWineD3DImpl *)iface;
377     ULONG ref;
378     TRACE("(%p) : Releasing from %d\n", This, This->ref);
379     ref = InterlockedDecrement(&This->ref);
380     if (ref == 0) {
381         unsigned int i;
382
383         for (i = 0; i < This->adapter_count; ++i)
384         {
385             wined3d_adapter_cleanup(&This->adapters[i]);
386         }
387         HeapFree(GetProcessHeap(), 0, This);
388     }
389
390     return ref;
391 }
392
393 /**********************************************************
394  * IWineD3D parts follows
395  **********************************************************/
396
397 /* GL locking is done by the caller */
398 static inline BOOL test_arb_vs_offset_limit(const struct wined3d_gl_info *gl_info)
399 {
400     GLuint prog;
401     BOOL ret = FALSE;
402     const char *testcode =
403         "!!ARBvp1.0\n"
404         "PARAM C[66] = { program.env[0..65] };\n"
405         "ADDRESS A0;"
406         "PARAM zero = {0.0, 0.0, 0.0, 0.0};\n"
407         "ARL A0.x, zero.x;\n"
408         "MOV result.position, C[A0.x + 65];\n"
409         "END\n";
410
411     while(glGetError());
412     GL_EXTCALL(glGenProgramsARB(1, &prog));
413     if(!prog) {
414         ERR("Failed to create an ARB offset limit test program\n");
415     }
416     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, prog));
417     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
418                                   strlen(testcode), testcode));
419     if(glGetError() != 0) {
420         TRACE("OpenGL implementation does not allow indirect addressing offsets > 63\n");
421         TRACE("error: %s\n", debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
422         ret = TRUE;
423     } else TRACE("OpenGL implementation allows offsets > 63\n");
424
425     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0));
426     GL_EXTCALL(glDeleteProgramsARB(1, &prog));
427     checkGLcall("ARB vp offset limit test cleanup");
428
429     return ret;
430 }
431
432 static DWORD ver_for_ext(GL_SupportedExt ext)
433 {
434     unsigned int i;
435     for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i) {
436         if(EXTENSION_MAP[i].extension == ext) {
437             return EXTENSION_MAP[i].version;
438         }
439     }
440     return 0;
441 }
442
443 static BOOL match_ati_r300_to_500(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
444         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
445 {
446     if (vendor != VENDOR_ATI) return FALSE;
447     if (device == CARD_ATI_RADEON_9500) return TRUE;
448     if (device == CARD_ATI_RADEON_X700) return TRUE;
449     if (device == CARD_ATI_RADEON_X1600) return TRUE;
450     return FALSE;
451 }
452
453 static BOOL match_geforce5(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
454         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
455 {
456     if (vendor == VENDOR_NVIDIA)
457     {
458         if (device == CARD_NVIDIA_GEFORCEFX_5800 || device == CARD_NVIDIA_GEFORCEFX_5600)
459         {
460             return TRUE;
461         }
462     }
463     return FALSE;
464 }
465
466 static BOOL match_apple(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
467         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
468 {
469     /* MacOS has various specialities in the extensions it advertises. Some have to be loaded from
470      * the opengl 1.2+ core, while other extensions are advertised, but software emulated. So try to
471      * detect the Apple OpenGL implementation to apply some extension fixups afterwards.
472      *
473      * Detecting this isn't really easy. The vendor string doesn't mention Apple. Compile-time checks
474      * aren't sufficient either because a Linux binary may display on a macos X server via remote X11.
475      * So try to detect the GL implementation by looking at certain Apple extensions. Some extensions
476      * like client storage might be supported on other implementations too, but GL_APPLE_flush_render
477      * is specific to the Mac OS X window management, and GL_APPLE_ycbcr_422 is QuickTime specific. So
478      * the chance that other implementations support them is rather small since Win32 QuickTime uses
479      * DirectDraw, not OpenGL. */
480     if (gl_info->supported[APPLE_FENCE]
481             && gl_info->supported[APPLE_CLIENT_STORAGE]
482             && gl_info->supported[APPLE_FLUSH_RENDER]
483             && gl_info->supported[APPLE_YCBCR_422])
484     {
485         return TRUE;
486     }
487     else
488     {
489         return FALSE;
490     }
491 }
492
493 /* Context activation is done by the caller. */
494 static void test_pbo_functionality(struct wined3d_gl_info *gl_info)
495 {
496     /* Some OpenGL implementations, namely Apple's Geforce 8 driver, advertises PBOs,
497      * but glTexSubImage from a PBO fails miserably, with the first line repeated over
498      * all the texture. This function detects this bug by its symptom and disables PBOs
499      * if the test fails.
500      *
501      * The test uploads a 4x4 texture via the PBO in the "native" format GL_BGRA,
502      * GL_UNSIGNED_INT_8_8_8_8_REV. This format triggers the bug, and it is what we use
503      * for D3DFMT_A8R8G8B8. Then the texture is read back without any PBO and the data
504      * read back is compared to the original. If they are equal PBOs are assumed to work,
505      * otherwise the PBO extension is disabled. */
506     GLuint texture, pbo;
507     static const unsigned int pattern[] =
508     {
509         0x00000000, 0x000000ff, 0x0000ff00, 0x40ff0000,
510         0x80ffffff, 0x40ffff00, 0x00ff00ff, 0x0000ffff,
511         0x00ffff00, 0x00ff00ff, 0x0000ffff, 0x000000ff,
512         0x80ff00ff, 0x0000ffff, 0x00ff00ff, 0x40ff00ff
513     };
514     unsigned int check[sizeof(pattern) / sizeof(pattern[0])];
515
516     /* No PBO -> No point in testing them. */
517     if (!gl_info->supported[ARB_PIXEL_BUFFER_OBJECT]) return;
518
519     ENTER_GL();
520
521     while (glGetError());
522     glGenTextures(1, &texture);
523     glBindTexture(GL_TEXTURE_2D, texture);
524
525     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
526     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 4, 4, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 0);
527     checkGLcall("Specifying the PBO test texture");
528
529     GL_EXTCALL(glGenBuffersARB(1, &pbo));
530     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo));
531     GL_EXTCALL(glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, sizeof(pattern), pattern, GL_STREAM_DRAW_ARB));
532     checkGLcall("Specifying the PBO test pbo");
533
534     glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 4, 4, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, NULL);
535     checkGLcall("Loading the PBO test texture");
536
537     GL_EXTCALL(glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0));
538     wglFinish(); /* just to be sure */
539
540     memset(check, 0, sizeof(check));
541     glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, check);
542     checkGLcall("Reading back the PBO test texture");
543
544     glDeleteTextures(1, &texture);
545     GL_EXTCALL(glDeleteBuffersARB(1, &pbo));
546     checkGLcall("PBO test cleanup");
547
548     LEAVE_GL();
549
550     if (memcmp(check, pattern, sizeof(check)))
551     {
552         WARN_(d3d_caps)("PBO test failed, read back data doesn't match original.\n");
553         WARN_(d3d_caps)("Disabling PBOs. This may result in slower performance.\n");
554         gl_info->supported[ARB_PIXEL_BUFFER_OBJECT] = FALSE;
555     }
556     else
557     {
558         TRACE_(d3d_caps)("PBO test successful.\n");
559     }
560 }
561
562 static BOOL match_apple_intel(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
563         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
564 {
565     return vendor == VENDOR_INTEL && match_apple(gl_info, gl_renderer, vendor, device);
566 }
567
568 static BOOL match_apple_nonr500ati(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
569         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
570 {
571     if (!match_apple(gl_info, gl_renderer, vendor, device)) return FALSE;
572     if (vendor != VENDOR_ATI) return FALSE;
573     if (device == CARD_ATI_RADEON_X1600) return FALSE;
574     return TRUE;
575 }
576
577 static BOOL match_fglrx(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
578         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
579 {
580     if (vendor != VENDOR_ATI) return FALSE;
581     if (match_apple(gl_info, gl_renderer, vendor, device)) return FALSE;
582     if (strstr(gl_renderer, "DRI")) return FALSE; /* Filter out Mesa DRI drivers. */
583     return TRUE;
584 }
585
586 static BOOL match_dx10_capable(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
587         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
588 {
589     /* DX9 cards support 40 single float varyings in hardware, most drivers report 32. ATI misreports
590      * 44 varyings. So assume that if we have more than 44 varyings we have a dx10 card.
591      * This detection is for the gl_ClipPos varying quirk. If a d3d9 card really supports more than 44
592      * varyings and we subtract one in dx9 shaders its not going to hurt us because the dx9 limit is
593      * hardcoded
594      *
595      * dx10 cards usually have 64 varyings */
596     return gl_info->limits.glsl_varyings > 44;
597 }
598
599 /* A GL context is provided by the caller */
600 static BOOL match_allows_spec_alpha(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
601         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
602 {
603     GLenum error;
604     DWORD data[16];
605
606     if (!gl_info->supported[EXT_SECONDARY_COLOR]) return FALSE;
607
608     ENTER_GL();
609     while(glGetError());
610     GL_EXTCALL(glSecondaryColorPointerEXT)(4, GL_UNSIGNED_BYTE, 4, data);
611     error = glGetError();
612     LEAVE_GL();
613
614     if(error == GL_NO_ERROR)
615     {
616         TRACE("GL Implementation accepts 4 component specular color pointers\n");
617         return TRUE;
618     }
619     else
620     {
621         TRACE("GL implementation does not accept 4 component specular colors, error %s\n",
622               debug_glerror(error));
623         return FALSE;
624     }
625 }
626
627 static BOOL match_apple_nvts(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
628         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
629 {
630     if (!match_apple(gl_info, gl_renderer, vendor, device)) return FALSE;
631     return gl_info->supported[NV_TEXTURE_SHADER];
632 }
633
634 /* A GL context is provided by the caller */
635 static BOOL match_broken_nv_clip(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
636         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
637 {
638     GLuint prog;
639     BOOL ret = FALSE;
640     GLint pos;
641     const char *testcode =
642         "!!ARBvp1.0\n"
643         "OPTION NV_vertex_program2;\n"
644         "MOV result.clip[0], 0.0;\n"
645         "MOV result.position, 0.0;\n"
646         "END\n";
647
648     if (!gl_info->supported[NV_VERTEX_PROGRAM2_OPTION]) return FALSE;
649
650     ENTER_GL();
651     while(glGetError());
652
653     GL_EXTCALL(glGenProgramsARB(1, &prog));
654     if(!prog)
655     {
656         ERR("Failed to create the NVvp clip test program\n");
657         LEAVE_GL();
658         return FALSE;
659     }
660     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, prog));
661     GL_EXTCALL(glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
662                                   strlen(testcode), testcode));
663     glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &pos);
664     if(pos != -1)
665     {
666         WARN("GL_NV_vertex_program2_option result.clip[] test failed\n");
667         TRACE("error: %s\n", debugstr_a((const char *)glGetString(GL_PROGRAM_ERROR_STRING_ARB)));
668         ret = TRUE;
669         while(glGetError());
670     }
671     else TRACE("GL_NV_vertex_program2_option result.clip[] test passed\n");
672
673     GL_EXTCALL(glBindProgramARB(GL_VERTEX_PROGRAM_ARB, 0));
674     GL_EXTCALL(glDeleteProgramsARB(1, &prog));
675     checkGLcall("GL_NV_vertex_program2_option result.clip[] test cleanup");
676
677     LEAVE_GL();
678     return ret;
679 }
680
681 static void quirk_arb_constants(struct wined3d_gl_info *gl_info)
682 {
683     TRACE_(d3d_caps)("Using ARB vs constant limit(=%u) for GLSL.\n", gl_info->limits.arb_vs_native_constants);
684     gl_info->limits.glsl_vs_float_constants = gl_info->limits.arb_vs_native_constants;
685     TRACE_(d3d_caps)("Using ARB ps constant limit(=%u) for GLSL.\n", gl_info->limits.arb_ps_native_constants);
686     gl_info->limits.glsl_ps_float_constants = gl_info->limits.arb_ps_native_constants;
687 }
688
689 static void quirk_apple_glsl_constants(struct wined3d_gl_info *gl_info)
690 {
691     quirk_arb_constants(gl_info);
692     /* MacOS needs uniforms for relative addressing offsets. This can accumulate to quite a few uniforms.
693      * Beyond that the general uniform isn't optimal, so reserve a number of uniforms. 12 vec4's should
694      * allow 48 different offsets or other helper immediate values. */
695     TRACE_(d3d_caps)("Reserving 12 GLSL constants for compiler private use.\n");
696     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 12);
697 }
698
699 /* fglrx crashes with a very bad kernel panic if GL_POINT_SPRITE_ARB is set to GL_COORD_REPLACE_ARB
700  * on more than one texture unit. This means that the d3d9 visual point size test will cause a
701  * kernel panic on any machine running fglrx 9.3(latest that supports r300 to r500 cards). This
702  * quirk only enables point sprites on the first texture unit. This keeps point sprites working in
703  * most games, but avoids the crash
704  *
705  * A more sophisticated way would be to find all units that need texture coordinates and enable
706  * point sprites for one if only one is found, and software emulate point sprites in drawStridedSlow
707  * if more than one unit needs texture coordinates(This requires software ffp and vertex shaders though)
708  *
709  * Note that disabling the extension entirely does not gain predictability because there is no point
710  * sprite capability flag in d3d, so the potential rendering bugs are the same if we disable the extension. */
711 static void quirk_one_point_sprite(struct wined3d_gl_info *gl_info)
712 {
713     if (gl_info->supported[ARB_POINT_SPRITE])
714     {
715         TRACE("Limiting point sprites to one texture unit.\n");
716         gl_info->limits.point_sprite_units = 1;
717     }
718 }
719
720 static void quirk_ati_dx9(struct wined3d_gl_info *gl_info)
721 {
722     quirk_arb_constants(gl_info);
723
724     /* MacOS advertises GL_ARB_texture_non_power_of_two on ATI r500 and earlier cards, although
725      * these cards only support GL_ARB_texture_rectangle(D3DPTEXTURECAPS_NONPOW2CONDITIONAL).
726      * If real NP2 textures are used, the driver falls back to software. We could just remove the
727      * extension and use GL_ARB_texture_rectangle instead, but texture_rectangle is inconventient
728      * due to the non-normalized texture coordinates. Thus set an internal extension flag,
729      * GL_WINE_normalized_texrect, which signals the code that it can use non power of two textures
730      * as per GL_ARB_texture_non_power_of_two, but has to stick to the texture_rectangle limits.
731      *
732      * fglrx doesn't advertise GL_ARB_texture_non_power_of_two, but it advertises opengl 2.0 which
733      * has this extension promoted to core. The extension loading code sets this extension supported
734      * due to that, so this code works on fglrx as well. */
735     if(gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
736     {
737         TRACE("GL_ARB_texture_non_power_of_two advertised on R500 or earlier card, removing.\n");
738         gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
739         gl_info->supported[WINE_NORMALIZED_TEXRECT] = TRUE;
740     }
741
742     /* fglrx has the same structural issues as the one described in quirk_apple_glsl_constants, although
743      * it is generally more efficient. Reserve just 8 constants. */
744     TRACE_(d3d_caps)("Reserving 8 GLSL constants for compiler private use.\n");
745     gl_info->reserved_glsl_constants = max(gl_info->reserved_glsl_constants, 8);
746 }
747
748 static void quirk_no_np2(struct wined3d_gl_info *gl_info)
749 {
750     /*  The nVidia GeForceFX series reports OpenGL 2.0 capabilities with the latest drivers versions, but
751      *  doesn't explicitly advertise the ARB_tex_npot extension in the GL extension string.
752      *  This usually means that ARB_tex_npot is supported in hardware as long as the application is staying
753      *  within the limits enforced by the ARB_texture_rectangle extension. This however is not true for the
754      *  FX series, which instantly falls back to a slower software path as soon as ARB_tex_npot is used.
755      *  We therefore completely remove ARB_tex_npot from the list of supported extensions.
756      *
757      *  Note that wine_normalized_texrect can't be used in this case because internally it uses ARB_tex_npot,
758      *  triggering the software fallback. There is not much we can do here apart from disabling the
759      *  software-emulated extension and reenable ARB_tex_rect (which was previously disabled
760      *  in IWineD3DImpl_FillGLCaps).
761      *  This fixup removes performance problems on both the FX 5900 and FX 5700 (e.g. for framebuffer
762      *  post-processing effects in the game "Max Payne 2").
763      *  The behaviour can be verified through a simple test app attached in bugreport #14724. */
764     TRACE("GL_ARB_texture_non_power_of_two advertised through OpenGL 2.0 on NV FX card, removing.\n");
765     gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO] = FALSE;
766     gl_info->supported[ARB_TEXTURE_RECTANGLE] = TRUE;
767 }
768
769 static void quirk_texcoord_w(struct wined3d_gl_info *gl_info)
770 {
771     /* The Intel GPUs on MacOS set the .w register of texcoords to 0.0 by default, which causes problems
772      * with fixed function fragment processing. Ideally this flag should be detected with a test shader
773      * and OpenGL feedback mode, but some GL implementations (MacOS ATI at least, probably all MacOS ones)
774      * do not like vertex shaders in feedback mode and return an error, even though it should be valid
775      * according to the spec.
776      *
777      * We don't want to enable this on all cards, as it adds an extra instruction per texcoord used. This
778      * makes the shader slower and eats instruction slots which should be available to the d3d app.
779      *
780      * ATI Radeon HD 2xxx cards on MacOS have the issue. Instead of checking for the buggy cards, blacklist
781      * all radeon cards on Macs and whitelist the good ones. That way we're prepared for the future. If
782      * this workaround is activated on cards that do not need it, it won't break things, just affect
783      * performance negatively. */
784     TRACE("Enabling vertex texture coord fixes in vertex shaders.\n");
785     gl_info->quirks |= WINED3D_QUIRK_SET_TEXCOORD_W;
786 }
787
788 static void quirk_clip_varying(struct wined3d_gl_info *gl_info)
789 {
790     gl_info->quirks |= WINED3D_QUIRK_GLSL_CLIP_VARYING;
791 }
792
793 static void quirk_allows_specular_alpha(struct wined3d_gl_info *gl_info)
794 {
795     gl_info->quirks |= WINED3D_QUIRK_ALLOWS_SPECULAR_ALPHA;
796 }
797
798 static void quirk_apple_nvts(struct wined3d_gl_info *gl_info)
799 {
800     gl_info->supported[NV_TEXTURE_SHADER] = FALSE;
801     gl_info->supported[NV_TEXTURE_SHADER2] = FALSE;
802     gl_info->supported[NV_TEXTURE_SHADER3] = FALSE;
803 }
804
805 static void quirk_disable_nvvp_clip(struct wined3d_gl_info *gl_info)
806 {
807     gl_info->quirks |= WINED3D_QUIRK_NV_CLIP_BROKEN;
808 }
809
810 struct driver_quirk
811 {
812     BOOL (*match)(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
813             enum wined3d_pci_vendor vendor, enum wined3d_pci_device device);
814     void (*apply)(struct wined3d_gl_info *gl_info);
815     const char *description;
816 };
817
818 static const struct driver_quirk quirk_table[] =
819 {
820     {
821         match_ati_r300_to_500,
822         quirk_ati_dx9,
823         "ATI GLSL constant and normalized texrect quirk"
824     },
825     /* MacOS advertises more GLSL vertex shader uniforms than supported by the hardware, and if more are
826      * used it falls back to software. While the compiler can detect if the shader uses all declared
827      * uniforms, the optimization fails if the shader uses relative addressing. So any GLSL shader
828      * using relative addressing falls back to software.
829      *
830      * ARB vp gives the correct amount of uniforms, so use it instead of GLSL. */
831     {
832         match_apple,
833         quirk_apple_glsl_constants,
834         "Apple GLSL uniform override"
835     },
836     {
837         match_geforce5,
838         quirk_no_np2,
839         "Geforce 5 NP2 disable"
840     },
841     {
842         match_apple_intel,
843         quirk_texcoord_w,
844         "Init texcoord .w for Apple Intel GPU driver"
845     },
846     {
847         match_apple_nonr500ati,
848         quirk_texcoord_w,
849         "Init texcoord .w for Apple ATI >= r600 GPU driver"
850     },
851     {
852         match_fglrx,
853         quirk_one_point_sprite,
854         "Fglrx point sprite crash workaround"
855     },
856     {
857         match_dx10_capable,
858         quirk_clip_varying,
859         "Reserved varying for gl_ClipPos"
860     },
861     {
862         /* GL_EXT_secondary_color does not allow 4 component secondary colors, but most
863          * GL implementations accept it. The Mac GL is the only implementation known to
864          * reject it.
865          *
866          * If we can pass 4 component specular colors, do it, because (a) we don't have
867          * to screw around with the data, and (b) the D3D fixed function vertex pipeline
868          * passes specular alpha to the pixel shader if any is used. Otherwise the
869          * specular alpha is used to pass the fog coordinate, which we pass to opengl
870          * via GL_EXT_fog_coord.
871          */
872         match_allows_spec_alpha,
873         quirk_allows_specular_alpha,
874         "Allow specular alpha quirk"
875     },
876     {
877         /* The pixel formats provided by GL_NV_texture_shader are broken on OSX
878          * (rdar://5682521).
879          */
880         match_apple_nvts,
881         quirk_apple_nvts,
882         "Apple NV_texture_shader disable"
883     },
884     {
885         match_broken_nv_clip,
886         quirk_disable_nvvp_clip,
887         "Apple NV_vertex_program clip bug quirk"
888     },
889 };
890
891 /* Certain applications (Steam) complain if we report an outdated driver version. In general,
892  * reporting a driver version is moot because we are not the Windows driver, and we have different
893  * bugs, features, etc.
894  *
895  * The driver version has the form "x.y.z.w".
896  *
897  * "x" is the Windows version the driver is meant for:
898  * 4 -> 95/98/NT4
899  * 5 -> 2000
900  * 6 -> 2000/XP
901  * 7 -> Vista
902  * 8 -> Win 7
903  *
904  * "y" is the Direct3D level the driver supports:
905  * 11 -> d3d6
906  * 12 -> d3d7
907  * 13 -> d3d8
908  * 14 -> d3d9
909  * 15 -> d3d10
910  *
911  * "z" is unknown, possibly vendor specific.
912  *
913  * "w" is the vendor specific driver version.
914  */
915 struct driver_version_information
916 {
917     WORD vendor;                    /* reported PCI card vendor ID  */
918     WORD card;                      /* reported PCI card device ID  */
919     const char *description;        /* Description of the card e.g. NVIDIA RIVA TNT */
920     WORD d3d_level;                 /* driver hiword to report      */
921     WORD lopart_hi, lopart_lo;      /* driver loword to report      */
922 };
923
924 static const struct driver_version_information driver_version_table[] =
925 {
926     /* Nvidia drivers. Geforce6 and newer cards are supported by the current driver (180.x)
927      * GeforceFX support is up to 173.x, - driver uses numbering x.y.11.7341 for 173.41 where x is the windows revision (6=2000/xp, 7=vista), y is unknown
928      * Geforce2MX/3/4 up to 96.x - driver uses numbering 9.6.8.9 for 96.89
929      * TNT/Geforce1/2 up to 71.x - driver uses numbering 7.1.8.6 for 71.86
930      *
931      * All version numbers used below are from the Linux nvidia drivers. */
932     {VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT,           "NVIDIA RIVA TNT",                  1,  8,  6      },
933     {VENDOR_NVIDIA,     CARD_NVIDIA_RIVA_TNT2,          "NVIDIA RIVA TNT2/TNT2 Pro",        1,  8,  6      },
934     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE,            "NVIDIA GeForce 256",               1,  8,  6      },
935     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2_MX,        "NVIDIA GeForce2 MX/MX 400",        6,  4,  3      },
936     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE2,           "NVIDIA GeForce2 GTS/GeForce2 Pro", 1,  8,  6      },
937     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE3,           "NVIDIA GeForce3",                  6,  10, 9371   },
938     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_MX,        "NVIDIA GeForce4 MX 460",           6,  10, 9371   },
939     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE4_TI4200,    "NVIDIA GeForce4 Ti 4200",          6,  10, 9371   },
940     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5200,     "NVIDIA GeForce FX 5200",           15, 11, 7516   },
941     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5600,     "NVIDIA GeForce FX 5600",           15, 11, 7516   },
942     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCEFX_5800,     "NVIDIA GeForce FX 5800",           15, 11, 7516   },
943     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6200,       "NVIDIA GeForce 6200",              15, 11, 8618   },
944     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6600GT,     "NVIDIA GeForce 6600 GT",           15, 11, 8618   },
945     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_6800,       "NVIDIA GeForce 6800",              15, 11, 8618   },
946     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7300,       "NVIDIA GeForce Go 7300",           15, 11, 8585   },
947     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7400,       "NVIDIA GeForce Go 7400",           15, 11, 8585   },
948     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7600,       "NVIDIA GeForce 7600 GT",           15, 11, 8618   },
949     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_7800GT,     "NVIDIA GeForce 7800 GT",           15, 11, 8618   },
950     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8300GS,     "NVIDIA GeForce 8300 GS",           15, 11, 8618   },
951     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600GT,     "NVIDIA GeForce 8600 GT",           15, 11, 8618   },
952     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8600MGT,    "NVIDIA GeForce 8600M GT",          15, 11, 8585   },
953     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_8800GTS,    "NVIDIA GeForce 8800 GTS",          15, 11, 8618   },
954     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9200,       "NVIDIA GeForce 9200",              15, 11, 8618   },
955     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9400GT,     "NVIDIA GeForce 9400 GT",           15, 11, 8618   },
956     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9500GT,     "NVIDIA GeForce 9500 GT",           15, 11, 8618   },
957     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9600GT,     "NVIDIA GeForce 9600 GT",           15, 11, 8618   },
958     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_9800GT,     "NVIDIA GeForce 9800 GT",           15, 11, 8618   },
959     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX260,     "NVIDIA GeForce GTX 260",           15, 11, 8618   },
960     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX275,     "NVIDIA GeForce GTX 275",           15, 11, 8618   },
961     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GTX280,     "NVIDIA GeForce GTX 280",           15, 11, 8618   },
962     {VENDOR_NVIDIA,     CARD_NVIDIA_GEFORCE_GT240,      "NVIDIA GeForce GT 240",            15, 11, 8618   },
963
964     /* ATI cards. The driver versions are somewhat similar, but not quite the same. Let's hardcode. */
965     {VENDOR_ATI,        CARD_ATI_RADEON_9500,           "ATI Radeon 9500",                  14, 10, 6764    },
966     {VENDOR_ATI,        CARD_ATI_RADEON_X700,           "ATI Radeon X700 SE",               14, 10, 6764    },
967     {VENDOR_ATI,        CARD_ATI_RADEON_X1600,          "ATI Radeon X1600 Series",          14, 10, 6764    },
968     {VENDOR_ATI,        CARD_ATI_RADEON_HD2300,         "ATI Mobility Radeon HD 2300",      14, 10, 6764    },
969     {VENDOR_ATI,        CARD_ATI_RADEON_HD2600,         "ATI Mobility Radeon HD 2600",      14, 10, 6764    },
970     {VENDOR_ATI,        CARD_ATI_RADEON_HD2900,         "ATI Radeon HD 2900 XT",            14, 10, 6764    },
971     {VENDOR_ATI,        CARD_ATI_RADEON_HD4350,         "ATI Radeon HD 4350",               14, 10, 6764    },
972     {VENDOR_ATI,        CARD_ATI_RADEON_HD4600,         "ATI Radeon HD 4600 Series",        14, 10, 6764    },
973     {VENDOR_ATI,        CARD_ATI_RADEON_HD4700,         "ATI Radeon HD 4700 Series",        14, 10, 6764    },
974     {VENDOR_ATI,        CARD_ATI_RADEON_HD4800,         "ATI Radeon HD 4800 Series",        14, 10, 6764    },
975     {VENDOR_ATI,        CARD_ATI_RADEON_HD5700,         "ATI Radeon HD 5700 Series",        14, 10, 8681    },
976     {VENDOR_ATI,        CARD_ATI_RADEON_HD5800,         "ATI Radeon HD 5800 Series",        14, 10, 8681    },
977
978     /* TODO: Add information about legacy ATI hardware, Intel and other cards. */
979 };
980
981 static void init_driver_info(struct wined3d_driver_info *driver_info,
982         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
983 {
984     OSVERSIONINFOW os_version;
985     WORD driver_os_version;
986     unsigned int i;
987
988     if (wined3d_settings.pci_vendor_id != PCI_VENDOR_NONE)
989     {
990         TRACE_(d3d_caps)("Overriding PCI vendor ID with: %04x\n", wined3d_settings.pci_vendor_id);
991         vendor = wined3d_settings.pci_vendor_id;
992     }
993     driver_info->vendor = vendor;
994
995     if (wined3d_settings.pci_device_id != PCI_DEVICE_NONE)
996     {
997         TRACE_(d3d_caps)("Overriding PCI device ID with: %04x\n", wined3d_settings.pci_device_id);
998         device = wined3d_settings.pci_device_id;
999     }
1000     driver_info->device = device;
1001
1002     switch (vendor)
1003     {
1004         case VENDOR_ATI:
1005             driver_info->name = "ati2dvag.dll";
1006             break;
1007
1008         case VENDOR_NVIDIA:
1009             driver_info->name = "nv4_disp.dll";
1010             break;
1011
1012         default:
1013             FIXME_(d3d_caps)("Unhandled vendor %04x.\n", vendor);
1014             driver_info->name = "Display";
1015             break;
1016     }
1017
1018     memset(&os_version, 0, sizeof(os_version));
1019     os_version.dwOSVersionInfoSize = sizeof(os_version);
1020     if (!GetVersionExW(&os_version))
1021     {
1022         ERR("Failed to get OS version, reporting 2000/XP.\n");
1023         driver_os_version = 6;
1024     }
1025     else
1026     {
1027         TRACE("OS version %u.%u.\n", os_version.dwMajorVersion, os_version.dwMinorVersion);
1028         switch (os_version.dwMajorVersion)
1029         {
1030             case 4:
1031                 driver_os_version = 4;
1032                 break;
1033
1034             case 5:
1035                 driver_os_version = 6;
1036                 break;
1037
1038             case 6:
1039                 if (os_version.dwMinorVersion == 0)
1040                 {
1041                     driver_os_version = 7;
1042                 }
1043                 else
1044                 {
1045                     if (os_version.dwMinorVersion > 1)
1046                     {
1047                         FIXME("Unhandled OS version %u.%u, reporting Win 7.\n",
1048                                 os_version.dwMajorVersion, os_version.dwMinorVersion);
1049                     }
1050                     driver_os_version = 8;
1051                 }
1052                 break;
1053
1054             default:
1055                 FIXME("Unhandled OS version %u.%u, reporting 2000/XP.\n",
1056                         os_version.dwMajorVersion, os_version.dwMinorVersion);
1057                 driver_os_version = 6;
1058                 break;
1059         }
1060     }
1061
1062     driver_info->description = "Direct3D HAL";
1063     driver_info->version_high = MAKEDWORD_VERSION(driver_os_version, 15);
1064     driver_info->version_low = MAKEDWORD_VERSION(8, 6); /* Nvidia RIVA TNT, arbitrary */
1065
1066     for (i = 0; i < (sizeof(driver_version_table) / sizeof(driver_version_table[0])); ++i)
1067     {
1068         if (vendor == driver_version_table[i].vendor && device == driver_version_table[i].card)
1069         {
1070             TRACE_(d3d_caps)("Found card %04x:%04x in driver DB.\n", vendor, device);
1071
1072             driver_info->description = driver_version_table[i].description;
1073             driver_info->version_high = MAKEDWORD_VERSION(driver_os_version, driver_version_table[i].d3d_level);
1074             driver_info->version_low = MAKEDWORD_VERSION(driver_version_table[i].lopart_hi,
1075                     driver_version_table[i].lopart_lo);
1076             break;
1077         }
1078     }
1079
1080     TRACE_(d3d_caps)("Reporting (fake) driver version 0x%08x-0x%08x.\n",
1081             driver_info->version_high, driver_info->version_low);
1082 }
1083
1084 /* Context activation is done by the caller. */
1085 static void fixup_extensions(struct wined3d_gl_info *gl_info, const char *gl_renderer,
1086         enum wined3d_pci_vendor vendor, enum wined3d_pci_device device)
1087 {
1088     unsigned int i;
1089
1090     for (i = 0; i < (sizeof(quirk_table) / sizeof(*quirk_table)); ++i)
1091     {
1092         if (!quirk_table[i].match(gl_info, gl_renderer, vendor, device)) continue;
1093         TRACE_(d3d_caps)("Applying driver quirk \"%s\".\n", quirk_table[i].description);
1094         quirk_table[i].apply(gl_info);
1095     }
1096
1097     /* Find out if PBOs work as they are supposed to. */
1098     test_pbo_functionality(gl_info);
1099 }
1100
1101 static DWORD wined3d_parse_gl_version(const char *gl_version)
1102 {
1103     const char *ptr = gl_version;
1104     int major, minor;
1105
1106     major = atoi(ptr);
1107     if (major <= 0) ERR_(d3d_caps)("Invalid opengl major version: %d.\n", major);
1108
1109     while (isdigit(*ptr)) ++ptr;
1110     if (*ptr++ != '.') ERR_(d3d_caps)("Invalid opengl version string: %s.\n", debugstr_a(gl_version));
1111
1112     minor = atoi(ptr);
1113
1114     TRACE_(d3d_caps)("Found OpenGL version: %d.%d.\n", major, minor);
1115
1116     return MAKEDWORD_VERSION(major, minor);
1117 }
1118
1119 static enum wined3d_pci_vendor wined3d_guess_vendor(const char *gl_vendor, const char *gl_renderer)
1120 {
1121     if (strstr(gl_vendor, "NVIDIA"))
1122         return VENDOR_NVIDIA;
1123
1124     if (strstr(gl_vendor, "ATI"))
1125         return VENDOR_ATI;
1126
1127     if (strstr(gl_vendor, "Intel(R)")
1128             || strstr(gl_renderer, "Intel(R)")
1129             || strstr(gl_vendor, "Intel Inc."))
1130         return VENDOR_INTEL;
1131
1132     if (strstr(gl_vendor, "Mesa")
1133             || strstr(gl_vendor, "Advanced Micro Devices, Inc.")
1134             || strstr(gl_vendor, "DRI R300 Project")
1135             || strstr(gl_vendor, "Tungsten Graphics, Inc")
1136             || strstr(gl_vendor, "VMware, Inc."))
1137         return VENDOR_MESA;
1138
1139     FIXME_(d3d_caps)("Received unrecognized GL_VENDOR %s. Returning VENDOR_WINE.\n", debugstr_a(gl_vendor));
1140
1141     return VENDOR_WINE;
1142 }
1143
1144 static enum wined3d_pci_device wined3d_guess_card(const struct wined3d_gl_info *gl_info, const char *gl_renderer,
1145         enum wined3d_pci_vendor *vendor, unsigned int *vidmem)
1146 {
1147     /* Below is a list of Nvidia and ATI GPUs. Both vendors have dozens of
1148      * different GPUs with roughly the same features. In most cases GPUs from a
1149      * certain family differ in clockspeeds, the amount of video memory and the
1150      * number of shader pipelines.
1151      *
1152      * A Direct3D device object contains the PCI id (vendor + device) of the
1153      * videocard which is used for rendering. Various applications use this
1154      * information to get a rough estimation of the features of the card and
1155      * some might use it for enabling 3d effects only on certain types of
1156      * videocards. In some cases games might even use it to work around bugs
1157      * which happen on certain videocards/driver combinations. The problem is
1158      * that OpenGL only exposes a rendering string containing the name of the
1159      * videocard and not the PCI id.
1160      *
1161      * Various games depend on the PCI id, so somehow we need to provide one.
1162      * A simple option is to parse the renderer string and translate this to
1163      * the right PCI id. This is a lot of work because there are more than 200
1164      * GPUs just for Nvidia. Various cards share the same renderer string, so
1165      * the amount of code might be 'small' but there are quite a number of
1166      * exceptions which would make this a pain to maintain. Another way would
1167      * be to query the PCI id from the operating system (assuming this is the
1168      * videocard which is used for rendering which is not always the case).
1169      * This would work but it is not very portable. Second it would not work
1170      * well in, let's say, a remote X situation in which the amount of 3d
1171      * features which can be used is limited.
1172      *
1173      * As said most games only use the PCI id to get an indication of the
1174      * capabilities of the card. It doesn't really matter if the given id is
1175      * the correct one if we return the id of a card with similar 3d features.
1176      *
1177      * The code below checks the OpenGL capabilities of a videocard and matches
1178      * that to a certain level of Direct3D functionality. Once a card passes
1179      * the Direct3D9 check, we know that the card (in case of Nvidia) is at
1180      * least a GeforceFX. To give a better estimate we do a basic check on the
1181      * renderer string but if that won't pass we return a default card. This
1182      * way is better than maintaining a full card database as even without a
1183      * full database we can return a card with similar features. Second the
1184      * size of the database can be made quite small because when you know what
1185      * type of 3d functionality a card has, you know to which GPU family the
1186      * GPU must belong. Because of this you only have to check a small part of
1187      * the renderer string to distinguishes between different models from that
1188      * family.
1189      *
1190      * The code also selects a default amount of video memory which we will
1191      * use for an estimation of the amount of free texture memory. In case of
1192      * real D3D the amount of texture memory includes video memory and system
1193      * memory (to be specific AGP memory or in case of PCIE TurboCache /
1194      * HyperMemory). We don't know how much system memory can be addressed by
1195      * the system but we can make a reasonable estimation about the amount of
1196      * video memory. If the value is slightly wrong it doesn't matter as we
1197      * didn't include AGP-like memory which makes the amount of addressable
1198      * memory higher and second OpenGL isn't that critical it moves to system
1199      * memory behind our backs if really needed. Note that the amount of video
1200      * memory can be overruled using a registry setting. */
1201
1202     switch (*vendor)
1203     {
1204         case VENDOR_NVIDIA:
1205             /* Both the GeforceFX, 6xxx and 7xxx series support D3D9. The last two types have more
1206              * shader capabilities, so we use the shader capabilities to distinguish between FX and 6xxx/7xxx.
1207              */
1208             if (WINE_D3D9_CAPABLE(gl_info) && gl_info->supported[NV_VERTEX_PROGRAM3])
1209             {
1210                 /* Geforce 200 - highend */
1211                 if (strstr(gl_renderer, "GTX 280")
1212                         || strstr(gl_renderer, "GTX 285")
1213                         || strstr(gl_renderer, "GTX 295"))
1214                 {
1215                     *vidmem = 1024;
1216                     return CARD_NVIDIA_GEFORCE_GTX280;
1217                 }
1218
1219                 /* Geforce 200 - midend high */
1220                 if (strstr(gl_renderer, "GTX 275"))
1221                 {
1222                     *vidmem = 896;
1223                     return CARD_NVIDIA_GEFORCE_GTX275;
1224                 }
1225
1226                 /* Geforce 200 - midend */
1227                 if (strstr(gl_renderer, "GTX 260"))
1228                 {
1229                     *vidmem = 1024;
1230                     return CARD_NVIDIA_GEFORCE_GTX260;
1231                 }
1232                 /* Geforce 200 - midend */
1233                 if (strstr(gl_renderer, "GT 240"))
1234                 {
1235                    *vidmem = 512;
1236                    return CARD_NVIDIA_GEFORCE_GT240;
1237                 }
1238
1239                 /* Geforce9 - highend / Geforce 200 - midend (GTS 150/250 are based on the same core) */
1240                 if (strstr(gl_renderer, "9800")
1241                         || strstr(gl_renderer, "GTS 150")
1242                         || strstr(gl_renderer, "GTS 250"))
1243                 {
1244                     *vidmem = 512;
1245                     return CARD_NVIDIA_GEFORCE_9800GT;
1246                 }
1247
1248                 /* Geforce9 - midend */
1249                 if (strstr(gl_renderer, "9600"))
1250                 {
1251                     *vidmem = 384; /* The 9600GSO has 384MB, the 9600GT has 512-1024MB */
1252                     return CARD_NVIDIA_GEFORCE_9600GT;
1253                 }
1254
1255                 /* Geforce9 - midend low / Geforce 200 - low */
1256                 if (strstr(gl_renderer, "9500")
1257                         || strstr(gl_renderer, "GT 120")
1258                         || strstr(gl_renderer, "GT 130"))
1259                 {
1260                     *vidmem = 256; /* The 9500GT has 256-1024MB */
1261                     return CARD_NVIDIA_GEFORCE_9500GT;
1262                 }
1263
1264                 /* Geforce9 - lowend */
1265                 if (strstr(gl_renderer, "9400"))
1266                 {
1267                     *vidmem = 256; /* The 9400GT has 256-1024MB */
1268                     return CARD_NVIDIA_GEFORCE_9400GT;
1269                 }
1270
1271                 /* Geforce9 - lowend low */
1272                 if (strstr(gl_renderer, "9100")
1273                         || strstr(gl_renderer, "9200")
1274                         || strstr(gl_renderer, "9300")
1275                         || strstr(gl_renderer, "G 100"))
1276                 {
1277                     *vidmem = 256; /* The 9100-9300 cards have 256MB */
1278                     return CARD_NVIDIA_GEFORCE_9200;
1279                 }
1280
1281                 /* Geforce8 - highend */
1282                 if (strstr(gl_renderer, "8800"))
1283                 {
1284                     *vidmem = 320; /* The 8800GTS uses 320MB, a 8800GTX can have 768MB */
1285                     return CARD_NVIDIA_GEFORCE_8800GTS;
1286                 }
1287
1288                 /* Geforce8 - midend mobile */
1289                 if (strstr(gl_renderer, "8600 M"))
1290                 {
1291                     *vidmem = 512;
1292                     return CARD_NVIDIA_GEFORCE_8600MGT;
1293                 }
1294
1295                 /* Geforce8 - midend */
1296                 if (strstr(gl_renderer, "8600")
1297                         || strstr(gl_renderer, "8700"))
1298                 {
1299                     *vidmem = 256;
1300                     return CARD_NVIDIA_GEFORCE_8600GT;
1301                 }
1302
1303                 /* Geforce8 - lowend */
1304                 if (strstr(gl_renderer, "8100")
1305                         || strstr(gl_renderer, "8200")
1306                         || strstr(gl_renderer, "8300")
1307                         || strstr(gl_renderer, "8400")
1308                         || strstr(gl_renderer, "8500"))
1309                 {
1310                     *vidmem = 128; /* 128-256MB for a 8300, 256-512MB for a 8400 */
1311                     return CARD_NVIDIA_GEFORCE_8300GS;
1312                 }
1313
1314                 /* Geforce7 - highend */
1315                 if (strstr(gl_renderer, "7800")
1316                         || strstr(gl_renderer, "7900")
1317                         || strstr(gl_renderer, "7950")
1318                         || strstr(gl_renderer, "Quadro FX 4")
1319                         || strstr(gl_renderer, "Quadro FX 5"))
1320                 {
1321                     *vidmem = 256; /* A 7800GT uses 256MB while highend 7900 cards can use 512MB */
1322                     return CARD_NVIDIA_GEFORCE_7800GT;
1323                 }
1324
1325                 /* Geforce7 midend */
1326                 if (strstr(gl_renderer, "7600")
1327                         || strstr(gl_renderer, "7700"))
1328                 {
1329                     *vidmem = 256; /* The 7600 uses 256-512MB */
1330                     return CARD_NVIDIA_GEFORCE_7600;
1331                 }
1332
1333                 /* Geforce7 lower medium */
1334                 if (strstr(gl_renderer, "7400"))
1335                 {
1336                     *vidmem = 256; /* The 7400 uses 256-512MB */
1337                     return CARD_NVIDIA_GEFORCE_7400;
1338                 }
1339
1340                 /* Geforce7 lowend */
1341                 if (strstr(gl_renderer, "7300"))
1342                 {
1343                     *vidmem = 256; /* Mac Pros with this card have 256 MB */
1344                     return CARD_NVIDIA_GEFORCE_7300;
1345                 }
1346
1347                 /* Geforce6 highend */
1348                 if (strstr(gl_renderer, "6800"))
1349                 {
1350                     *vidmem = 128; /* The 6800 uses 128-256MB, the 7600 uses 256-512MB */
1351                     return CARD_NVIDIA_GEFORCE_6800;
1352                 }
1353
1354                 /* Geforce6 - midend */
1355                 if (strstr(gl_renderer, "6600")
1356                         || strstr(gl_renderer, "6610")
1357                         || strstr(gl_renderer, "6700"))
1358                 {
1359                     *vidmem = 128; /* A 6600GT has 128-256MB */
1360                     return CARD_NVIDIA_GEFORCE_6600GT;
1361                 }
1362
1363                 /* Geforce6/7 lowend */
1364                 *vidmem = 64; /* */
1365                 return CARD_NVIDIA_GEFORCE_6200; /* Geforce 6100/6150/6200/7300/7400/7500 */
1366             }
1367
1368             if (WINE_D3D9_CAPABLE(gl_info))
1369             {
1370                 /* GeforceFX - highend */
1371                 if (strstr(gl_renderer, "5800")
1372                         || strstr(gl_renderer, "5900")
1373                         || strstr(gl_renderer, "5950")
1374                         || strstr(gl_renderer, "Quadro FX"))
1375                 {
1376                     *vidmem = 256; /* 5800-5900 cards use 256MB */
1377                     return CARD_NVIDIA_GEFORCEFX_5800;
1378                 }
1379
1380                 /* GeforceFX - midend */
1381                 if (strstr(gl_renderer, "5600")
1382                         || strstr(gl_renderer, "5650")
1383                         || strstr(gl_renderer, "5700")
1384                         || strstr(gl_renderer, "5750"))
1385                 {
1386                     *vidmem = 128; /* A 5600 uses 128-256MB */
1387                     return CARD_NVIDIA_GEFORCEFX_5600;
1388                 }
1389
1390                 /* GeforceFX - lowend */
1391                 *vidmem = 64; /* Normal FX5200 cards use 64-256MB; laptop (non-standard) can have less */
1392                 return CARD_NVIDIA_GEFORCEFX_5200; /* GeforceFX 5100/5200/5250/5300/5500 */
1393             }
1394
1395             if (WINE_D3D8_CAPABLE(gl_info))
1396             {
1397                 if (strstr(gl_renderer, "GeForce4 Ti") || strstr(gl_renderer, "Quadro4"))
1398                 {
1399                     *vidmem = 64; /* Geforce4 Ti cards have 64-128MB */
1400                     return CARD_NVIDIA_GEFORCE4_TI4200; /* Geforce4 Ti4200/Ti4400/Ti4600/Ti4800, Quadro4 */
1401                 }
1402
1403                 *vidmem = 64; /* Geforce3 cards have 64-128MB */
1404                 return CARD_NVIDIA_GEFORCE3; /* Geforce3 standard/Ti200/Ti500, Quadro DCC */
1405             }
1406
1407             if (WINE_D3D7_CAPABLE(gl_info))
1408             {
1409                 if (strstr(gl_renderer, "GeForce4 MX"))
1410                 {
1411                     /* Most Geforce4MX GPUs have at least 64MB of memory, some
1412                      * early models had 32MB but most have 64MB or even 128MB. */
1413                     *vidmem = 64;
1414                     return CARD_NVIDIA_GEFORCE4_MX; /* MX420/MX440/MX460/MX4000 */
1415                 }
1416
1417                 if (strstr(gl_renderer, "GeForce2 MX") || strstr(gl_renderer, "Quadro2 MXR"))
1418                 {
1419                     *vidmem = 32; /* Geforce2MX GPUs have 32-64MB of video memory */
1420                     return CARD_NVIDIA_GEFORCE2_MX; /* Geforce2 standard/MX100/MX200/MX400, Quadro2 MXR */
1421                 }
1422
1423                 if (strstr(gl_renderer, "GeForce2") || strstr(gl_renderer, "Quadro2"))
1424                 {
1425                     *vidmem = 32; /* Geforce2 GPUs have 32-64MB of video memory */
1426                     return CARD_NVIDIA_GEFORCE2; /* Geforce2 GTS/Pro/Ti/Ultra, Quadro2 */
1427                 }
1428
1429                 /* Most Geforce1 cards have 32MB, there are also some rare 16
1430                  * and 64MB (Dell) models. */
1431                 *vidmem = 32;
1432                 return CARD_NVIDIA_GEFORCE; /* Geforce 256/DDR, Quadro */
1433             }
1434
1435             if (strstr(gl_renderer, "TNT2"))
1436             {
1437                 *vidmem = 32; /* Most TNT2 boards have 32MB, though there are 16MB boards too */
1438                 return CARD_NVIDIA_RIVA_TNT2; /* Riva TNT2 standard/M64/Pro/Ultra */
1439             }
1440
1441             *vidmem = 16; /* Most TNT boards have 16MB, some rare models have 8MB */
1442             return CARD_NVIDIA_RIVA_TNT; /* Riva TNT, Vanta */
1443
1444         case VENDOR_ATI:
1445             /* See http://developer.amd.com/drivers/pc_vendor_id/Pages/default.aspx
1446              *
1447              * Beware: renderer string do not match exact card model,
1448              * eg HD 4800 is returned for multiple cards, even for RV790 based ones. */
1449             if (WINE_D3D9_CAPABLE(gl_info))
1450             {
1451                 /* Radeon EG CYPRESS XT / PRO HD5800 - highend */
1452                 if (strstr(gl_renderer, "HD 5800")          /* Radeon EG CYPRESS HD58xx generic renderer string */
1453                         || strstr(gl_renderer, "HD 5850")   /* Radeon EG CYPRESS XT */
1454                         || strstr(gl_renderer, "HD 5870"))  /* Radeon EG CYPRESS PRO */
1455                 {
1456                     *vidmem = 1024; /* note: HD58xx cards use 1024MB  */
1457                     return CARD_ATI_RADEON_HD5800;
1458                 }
1459
1460                 /* Radeon EG JUNIPER XT / LE HD5700 - midend */
1461                 if (strstr(gl_renderer, "HD 5700")          /* Radeon EG JUNIPER HD57xx generic renderer string */
1462                         || strstr(gl_renderer, "HD 5750")   /* Radeon EG JUNIPER LE */
1463                         || strstr(gl_renderer, "HD 5770"))  /* Radeon EG JUNIPER XT */
1464                 {
1465                     *vidmem = 512; /* note: HD5770 cards use 1024MB and HD5750 cards use 512MB or 1024MB  */
1466                     return CARD_ATI_RADEON_HD5700;
1467                 }
1468
1469                 /* Radeon R7xx HD4800 - highend */
1470                 if (strstr(gl_renderer, "HD 4800")          /* Radeon RV7xx HD48xx generic renderer string */
1471                         || strstr(gl_renderer, "HD 4830")   /* Radeon RV770 */
1472                         || strstr(gl_renderer, "HD 4850")   /* Radeon RV770 */
1473                         || strstr(gl_renderer, "HD 4870")   /* Radeon RV770 */
1474                         || strstr(gl_renderer, "HD 4890"))  /* Radeon RV790 */
1475                 {
1476                     *vidmem = 512; /* note: HD4890 cards use 1024MB */
1477                     return CARD_ATI_RADEON_HD4800;
1478                 }
1479
1480                 /* Radeon R740 HD4700 - midend */
1481                 if (strstr(gl_renderer, "HD 4700")          /* Radeon RV770 */
1482                         || strstr(gl_renderer, "HD 4770"))  /* Radeon RV740 */
1483                 {
1484                     *vidmem = 512;
1485                     return CARD_ATI_RADEON_HD4700;
1486                 }
1487
1488                 /* Radeon R730 HD4600 - midend */
1489                 if (strstr(gl_renderer, "HD 4600")          /* Radeon RV730 */
1490                         || strstr(gl_renderer, "HD 4650")   /* Radeon RV730 */
1491                         || strstr(gl_renderer, "HD 4670"))  /* Radeon RV730 */
1492                 {
1493                     *vidmem = 512;
1494                     return CARD_ATI_RADEON_HD4600;
1495                 }
1496
1497                 /* Radeon R710 HD4500/HD4350 - lowend */
1498                 if (strstr(gl_renderer, "HD 4350")          /* Radeon RV710 */
1499                         || strstr(gl_renderer, "HD 4550"))  /* Radeon RV710 */
1500                 {
1501                     *vidmem = 256;
1502                     return CARD_ATI_RADEON_HD4350;
1503                 }
1504
1505                 /* Radeon R6xx HD2900/HD3800 - highend */
1506                 if (strstr(gl_renderer, "HD 2900")
1507                         || strstr(gl_renderer, "HD 3870")
1508                         || strstr(gl_renderer, "HD 3850"))
1509                 {
1510                     *vidmem = 512; /* HD2900/HD3800 uses 256-1024MB */
1511                     return CARD_ATI_RADEON_HD2900;
1512                 }
1513
1514                 /* Radeon R6xx HD2600/HD3600 - midend; HD3830 is China-only midend */
1515                 if (strstr(gl_renderer, "HD 2600")
1516                         || strstr(gl_renderer, "HD 3830")
1517                         || strstr(gl_renderer, "HD 3690")
1518                         || strstr(gl_renderer, "HD 3650"))
1519                 {
1520                     *vidmem = 256; /* HD2600/HD3600 uses 256-512MB */
1521                     return CARD_ATI_RADEON_HD2600;
1522                 }
1523
1524                 /* Radeon R6xx HD2300/HD2400/HD3400 - lowend */
1525                 if (strstr(gl_renderer, "HD 2300")
1526                         || strstr(gl_renderer, "HD 2400")
1527                         || strstr(gl_renderer, "HD 3470")
1528                         || strstr(gl_renderer, "HD 3450")
1529                         || strstr(gl_renderer, "HD 3430")
1530                         || strstr(gl_renderer, "HD 3400"))
1531                 {
1532                     *vidmem = 128; /* HD2300 uses at least 128MB, HD2400 uses 256MB */
1533                     return CARD_ATI_RADEON_HD2300;
1534                 }
1535
1536                 /* Radeon R6xx/R7xx integrated */
1537                 if (strstr(gl_renderer, "HD 3100")
1538                         || strstr(gl_renderer, "HD 3200")
1539                         || strstr(gl_renderer, "HD 3300"))
1540                 {
1541                     *vidmem = 128; /* 128MB */
1542                     return CARD_ATI_RADEON_HD3200;
1543                 }
1544
1545                 /* Radeon R5xx */
1546                 if (strstr(gl_renderer, "X1600")
1547                         || strstr(gl_renderer, "X1650")
1548                         || strstr(gl_renderer, "X1800")
1549                         || strstr(gl_renderer, "X1900")
1550                         || strstr(gl_renderer, "X1950"))
1551                 {
1552                     *vidmem = 128; /* X1600 uses 128-256MB, >=X1800 uses 256MB */
1553                     return CARD_ATI_RADEON_X1600;
1554                 }
1555
1556                 /* Radeon R4xx + X1300/X1400/X1450/X1550/X2300 (lowend R5xx) */
1557                 if (strstr(gl_renderer, "X700")
1558                         || strstr(gl_renderer, "X800")
1559                         || strstr(gl_renderer, "X850")
1560                         || strstr(gl_renderer, "X1300")
1561                         || strstr(gl_renderer, "X1400")
1562                         || strstr(gl_renderer, "X1450")
1563                         || strstr(gl_renderer, "X1550"))
1564                 {
1565                     *vidmem = 128; /* x700/x8*0 use 128-256MB, >=x1300 128-512MB */
1566                     return CARD_ATI_RADEON_X700;
1567                 }
1568
1569                 /* Radeon Xpress Series - onboard, DX9b, Shader 2.0, 300-400MHz */
1570                 if (strstr(gl_renderer, "Radeon Xpress"))
1571                 {
1572                     *vidmem = 64; /* Shared RAM, BIOS configurable, 64-256M */
1573                     return CARD_ATI_RADEON_XPRESS_200M;
1574                 }
1575
1576                 /* Radeon R3xx */
1577                 *vidmem = 64; /* Radeon 9500 uses 64MB, higher models use up to 256MB */
1578                 return CARD_ATI_RADEON_9500; /* Radeon 9500/9550/9600/9700/9800/X300/X550/X600 */
1579             }
1580
1581             if (WINE_D3D8_CAPABLE(gl_info))
1582             {
1583                 *vidmem = 64; /* 8500/9000 cards use mostly 64MB, though there are 32MB and 128MB models */
1584                 return CARD_ATI_RADEON_8500; /* Radeon 8500/9000/9100/9200/9300 */
1585             }
1586
1587             if (WINE_D3D7_CAPABLE(gl_info))
1588             {
1589                 *vidmem = 32; /* There are models with up to 64MB */
1590                 return CARD_ATI_RADEON_7200; /* Radeon 7000/7100/7200/7500 */
1591             }
1592
1593             *vidmem = 16; /* There are 16-32MB models */
1594             return CARD_ATI_RAGE_128PRO;
1595
1596         case VENDOR_INTEL:
1597             if (strstr(gl_renderer, "X3100"))
1598             {
1599                 /* MacOS calls the card GMA X3100, Google findings also suggest the name GM965 */
1600                 *vidmem = 128;
1601                 return CARD_INTEL_X3100;
1602             }
1603
1604             if (strstr(gl_renderer, "GMA 950") || strstr(gl_renderer, "945GM"))
1605             {
1606                 /* MacOS calls the card GMA 950, but everywhere else the PCI ID is named 945GM */
1607                 *vidmem = 64;
1608                 return CARD_INTEL_I945GM;
1609             }
1610
1611             if (strstr(gl_renderer, "915GM")) return CARD_INTEL_I915GM;
1612             if (strstr(gl_renderer, "915G")) return CARD_INTEL_I915G;
1613             if (strstr(gl_renderer, "865G")) return CARD_INTEL_I865G;
1614             if (strstr(gl_renderer, "855G")) return CARD_INTEL_I855G;
1615             if (strstr(gl_renderer, "830G")) return CARD_INTEL_I830G;
1616             return CARD_INTEL_I915G;
1617
1618         case VENDOR_MESA:
1619         case VENDOR_WINE:
1620         default:
1621             /* Default to generic Nvidia hardware based on the supported OpenGL extensions. The choice
1622              * for Nvidia was because the hardware and drivers they make are of good quality. This makes
1623              * them a good generic choice. */
1624             *vendor = VENDOR_NVIDIA;
1625             if (WINE_D3D9_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCEFX_5600;
1626             if (WINE_D3D8_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE3;
1627             if (WINE_D3D7_CAPABLE(gl_info)) return CARD_NVIDIA_GEFORCE;
1628             if (WINE_D3D6_CAPABLE(gl_info)) return CARD_NVIDIA_RIVA_TNT;
1629             return CARD_NVIDIA_RIVA_128;
1630     }
1631 }
1632
1633 static const struct fragment_pipeline *select_fragment_implementation(struct wined3d_adapter *adapter)
1634 {
1635     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
1636     int vs_selected_mode, ps_selected_mode;
1637
1638     select_shader_mode(gl_info, &ps_selected_mode, &vs_selected_mode);
1639     if ((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL)
1640             && gl_info->supported[ARB_FRAGMENT_PROGRAM]) return &arbfp_fragment_pipeline;
1641     else if (ps_selected_mode == SHADER_ATI) return &atifs_fragment_pipeline;
1642     else if (gl_info->supported[NV_REGISTER_COMBINERS]
1643             && gl_info->supported[NV_TEXTURE_SHADER2]) return &nvts_fragment_pipeline;
1644     else if (gl_info->supported[NV_REGISTER_COMBINERS]) return &nvrc_fragment_pipeline;
1645     else return &ffp_fragment_pipeline;
1646 }
1647
1648 static const shader_backend_t *select_shader_backend(struct wined3d_adapter *adapter)
1649 {
1650     int vs_selected_mode, ps_selected_mode;
1651
1652     select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
1653     if (vs_selected_mode == SHADER_GLSL || ps_selected_mode == SHADER_GLSL) return &glsl_shader_backend;
1654     if (vs_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_ARB) return &arb_program_shader_backend;
1655     return &none_shader_backend;
1656 }
1657
1658 static const struct blit_shader *select_blit_implementation(struct wined3d_adapter *adapter)
1659 {
1660     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
1661     int vs_selected_mode, ps_selected_mode;
1662
1663     select_shader_mode(gl_info, &ps_selected_mode, &vs_selected_mode);
1664     if ((ps_selected_mode == SHADER_ARB || ps_selected_mode == SHADER_GLSL)
1665             && gl_info->supported[ARB_FRAGMENT_PROGRAM]) return &arbfp_blit;
1666     else return &ffp_blit;
1667 }
1668
1669 /* Context activation is done by the caller. */
1670 static BOOL IWineD3DImpl_FillGLCaps(struct wined3d_adapter *adapter)
1671 {
1672     struct wined3d_driver_info *driver_info = &adapter->driver_info;
1673     struct wined3d_gl_info *gl_info = &adapter->gl_info;
1674     const char *GL_Extensions    = NULL;
1675     const char *WGL_Extensions   = NULL;
1676     const char *gl_string        = NULL;
1677     enum wined3d_pci_vendor vendor;
1678     enum wined3d_pci_device device;
1679     GLint       gl_max;
1680     GLfloat     gl_floatv[2];
1681     unsigned    i;
1682     HDC         hdc;
1683     unsigned int vidmem=0;
1684     char *gl_renderer;
1685     DWORD gl_version;
1686     size_t len;
1687
1688     TRACE_(d3d_caps)("(%p)\n", gl_info);
1689
1690     ENTER_GL();
1691
1692     gl_string = (const char *)glGetString(GL_RENDERER);
1693     TRACE_(d3d_caps)("GL_RENDERER: %s.\n", debugstr_a(gl_string));
1694     if (!gl_string)
1695     {
1696         LEAVE_GL();
1697         ERR_(d3d_caps)("Received a NULL GL_RENDERER.\n");
1698         return FALSE;
1699     }
1700
1701     len = strlen(gl_string) + 1;
1702     gl_renderer = HeapAlloc(GetProcessHeap(), 0, len);
1703     if (!gl_renderer)
1704     {
1705         LEAVE_GL();
1706         ERR_(d3d_caps)("Failed to allocate gl_renderer memory.\n");
1707         return FALSE;
1708     }
1709     memcpy(gl_renderer, gl_string, len);
1710
1711     gl_string = (const char *)glGetString(GL_VENDOR);
1712     TRACE_(d3d_caps)("GL_VENDOR: %s.\n", debugstr_a(gl_string));
1713     if (!gl_string)
1714     {
1715         LEAVE_GL();
1716         ERR_(d3d_caps)("Received a NULL GL_VENDOR.\n");
1717         HeapFree(GetProcessHeap(), 0, gl_renderer);
1718         return FALSE;
1719     }
1720     vendor = wined3d_guess_vendor(gl_string, gl_renderer);
1721     TRACE_(d3d_caps)("found GL_VENDOR (%s)->(0x%04x)\n", debugstr_a(gl_string), vendor);
1722
1723     /* Parse the GL_VERSION field into major and minor information */
1724     gl_string = (const char *)glGetString(GL_VERSION);
1725     TRACE_(d3d_caps)("GL_VERSION: %s.\n", debugstr_a(gl_string));
1726     if (!gl_string)
1727     {
1728         LEAVE_GL();
1729         ERR_(d3d_caps)("Received a NULL GL_VERSION.\n");
1730         HeapFree(GetProcessHeap(), 0, gl_renderer);
1731         return FALSE;
1732     }
1733     gl_version = wined3d_parse_gl_version(gl_string);
1734
1735     /*
1736      * Initialize openGL extension related variables
1737      *  with Default values
1738      */
1739     memset(gl_info->supported, 0, sizeof(gl_info->supported));
1740     gl_info->limits.buffers = 1;
1741     gl_info->limits.textures = 1;
1742     gl_info->limits.texture_stages = 1;
1743     gl_info->limits.fragment_samplers = 1;
1744     gl_info->limits.vertex_samplers = 0;
1745     gl_info->limits.combined_samplers = gl_info->limits.fragment_samplers + gl_info->limits.vertex_samplers;
1746     gl_info->limits.sampler_stages = 1;
1747     gl_info->limits.glsl_vs_float_constants = 0;
1748     gl_info->limits.glsl_ps_float_constants = 0;
1749     gl_info->limits.arb_vs_float_constants = 0;
1750     gl_info->limits.arb_vs_native_constants = 0;
1751     gl_info->limits.arb_vs_instructions = 0;
1752     gl_info->limits.arb_vs_temps = 0;
1753     gl_info->limits.arb_ps_float_constants = 0;
1754     gl_info->limits.arb_ps_local_constants = 0;
1755     gl_info->limits.arb_ps_instructions = 0;
1756     gl_info->limits.arb_ps_temps = 0;
1757
1758     /* Retrieve opengl defaults */
1759     glGetIntegerv(GL_MAX_CLIP_PLANES, &gl_max);
1760     gl_info->limits.clipplanes = min(WINED3DMAXUSERCLIPPLANES, gl_max);
1761     TRACE_(d3d_caps)("ClipPlanes support - num Planes=%d\n", gl_max);
1762
1763     glGetIntegerv(GL_MAX_LIGHTS, &gl_max);
1764     gl_info->limits.lights = gl_max;
1765     TRACE_(d3d_caps)("Lights support - max lights=%d\n", gl_max);
1766
1767     glGetIntegerv(GL_MAX_TEXTURE_SIZE, &gl_max);
1768     gl_info->limits.texture_size = gl_max;
1769     TRACE_(d3d_caps)("Maximum texture size support - max texture size=%d\n", gl_max);
1770
1771     glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, gl_floatv);
1772     gl_info->limits.pointsize_min = gl_floatv[0];
1773     gl_info->limits.pointsize_max = gl_floatv[1];
1774     TRACE_(d3d_caps)("Maximum point size support - max point size=%f\n", gl_floatv[1]);
1775
1776     /* Parse the gl supported features, in theory enabling parts of our code appropriately. */
1777     GL_Extensions = (const char *)glGetString(GL_EXTENSIONS);
1778     if (!GL_Extensions)
1779     {
1780         LEAVE_GL();
1781         ERR_(d3d_caps)("Received a NULL GL_EXTENSIONS.\n");
1782         HeapFree(GetProcessHeap(), 0, gl_renderer);
1783         return FALSE;
1784     }
1785
1786     LEAVE_GL();
1787
1788     TRACE_(d3d_caps)("GL_Extensions reported:\n");
1789
1790     gl_info->supported[WINED3D_GL_EXT_NONE] = TRUE;
1791
1792     while (*GL_Extensions)
1793     {
1794         const char *start;
1795         char current_ext[256];
1796
1797         while (isspace(*GL_Extensions)) ++GL_Extensions;
1798         start = GL_Extensions;
1799         while (!isspace(*GL_Extensions) && *GL_Extensions) ++GL_Extensions;
1800
1801         len = GL_Extensions - start;
1802         if (!len || len >= sizeof(current_ext)) continue;
1803
1804         memcpy(current_ext, start, len);
1805         current_ext[len] = '\0';
1806         TRACE_(d3d_caps)("- %s\n", debugstr_a(current_ext));
1807
1808         for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i)
1809         {
1810             if (!strcmp(current_ext, EXTENSION_MAP[i].extension_string))
1811             {
1812                 TRACE_(d3d_caps)(" FOUND: %s support.\n", EXTENSION_MAP[i].extension_string);
1813                 gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
1814                 break;
1815             }
1816         }
1817     }
1818
1819     /* Now work out what GL support this card really has */
1820 #define USE_GL_FUNC(type, pfn, ext, replace) \
1821 { \
1822     DWORD ver = ver_for_ext(ext); \
1823     if (gl_info->supported[ext]) gl_info->pfn = (type)pwglGetProcAddress(#pfn); \
1824     else if (ver && ver <= gl_version) gl_info->pfn = (type)pwglGetProcAddress(#replace); \
1825     else gl_info->pfn = NULL; \
1826 }
1827     GL_EXT_FUNCS_GEN;
1828 #undef USE_GL_FUNC
1829
1830 #define USE_GL_FUNC(type, pfn, ext, replace) gl_info->pfn = (type)pwglGetProcAddress(#pfn);
1831     WGL_EXT_FUNCS_GEN;
1832 #undef USE_GL_FUNC
1833
1834     ENTER_GL();
1835
1836     /* Now mark all the extensions supported which are included in the opengl core version. Do this *after*
1837      * loading the functions, otherwise the code above will load the extension entry points instead of the
1838      * core functions, which may not work. */
1839     for (i = 0; i < (sizeof(EXTENSION_MAP) / sizeof(*EXTENSION_MAP)); ++i)
1840     {
1841         if (!gl_info->supported[EXTENSION_MAP[i].extension]
1842                 && EXTENSION_MAP[i].version <= gl_version && EXTENSION_MAP[i].version)
1843         {
1844             TRACE_(d3d_caps)(" GL CORE: %s support.\n", EXTENSION_MAP[i].extension_string);
1845             gl_info->supported[EXTENSION_MAP[i].extension] = TRUE;
1846         }
1847     }
1848
1849     if (gl_info->supported[APPLE_FENCE])
1850     {
1851         /* GL_NV_fence and GL_APPLE_fence provide the same functionality basically.
1852          * The apple extension interacts with some other apple exts. Disable the NV
1853          * extension if the apple one is support to prevent confusion in other parts
1854          * of the code. */
1855         gl_info->supported[NV_FENCE] = FALSE;
1856     }
1857     if (gl_info->supported[APPLE_FLOAT_PIXELS])
1858     {
1859         /* GL_APPLE_float_pixels == GL_ARB_texture_float + GL_ARB_half_float_pixel
1860          *
1861          * The enums are the same:
1862          * GL_RGBA16F_ARB     = GL_RGBA_FLOAT16_APPLE = 0x881A
1863          * GL_RGB16F_ARB      = GL_RGB_FLOAT16_APPLE  = 0x881B
1864          * GL_RGBA32F_ARB     = GL_RGBA_FLOAT32_APPLE = 0x8814
1865          * GL_RGB32F_ARB      = GL_RGB_FLOAT32_APPLE  = 0x8815
1866          * GL_HALF_FLOAT_ARB  = GL_HALF_APPLE         = 0x140B
1867          */
1868         if (!gl_info->supported[ARB_TEXTURE_FLOAT])
1869         {
1870             TRACE_(d3d_caps)(" IMPLIED: GL_ARB_texture_float support(from GL_APPLE_float_pixels.\n");
1871             gl_info->supported[ARB_TEXTURE_FLOAT] = TRUE;
1872         }
1873         if (!gl_info->supported[ARB_HALF_FLOAT_PIXEL])
1874         {
1875             TRACE_(d3d_caps)(" IMPLIED: GL_ARB_half_float_pixel support(from GL_APPLE_float_pixels.\n");
1876             gl_info->supported[ARB_HALF_FLOAT_PIXEL] = TRUE;
1877         }
1878     }
1879     if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
1880     {
1881         /* GL_ARB_map_buffer_range and GL_APPLE_flush_buffer_range provide the same
1882          * functionality. Prefer the ARB extension */
1883         gl_info->supported[APPLE_FLUSH_BUFFER_RANGE] = FALSE;
1884     }
1885     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1886     {
1887         TRACE_(d3d_caps)(" IMPLIED: NVIDIA (NV) Texture Gen Reflection support.\n");
1888         gl_info->supported[NV_TEXGEN_REFLECTION] = TRUE;
1889     }
1890     if (!gl_info->supported[ARB_DEPTH_CLAMP] && gl_info->supported[NV_DEPTH_CLAMP])
1891     {
1892         TRACE_(d3d_caps)(" IMPLIED: ARB_depth_clamp support (by NV_depth_clamp).\n");
1893         gl_info->supported[ARB_DEPTH_CLAMP] = TRUE;
1894     }
1895     if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && gl_info->supported[EXT_VERTEX_ARRAY_BGRA])
1896     {
1897         TRACE_(d3d_caps)(" IMPLIED: ARB_vertex_array_bgra support (by EXT_vertex_array_bgra).\n");
1898         gl_info->supported[ARB_VERTEX_ARRAY_BGRA] = TRUE;
1899     }
1900     if (gl_info->supported[NV_TEXTURE_SHADER2])
1901     {
1902         if (gl_info->supported[NV_REGISTER_COMBINERS])
1903         {
1904             /* Also disable ATI_FRAGMENT_SHADER if register combiners and texture_shader2
1905              * are supported. The nv extensions provide the same functionality as the
1906              * ATI one, and a bit more(signed pixelformats). */
1907             gl_info->supported[ATI_FRAGMENT_SHADER] = FALSE;
1908         }
1909     }
1910     if (gl_info->supported[ARB_DRAW_BUFFERS])
1911     {
1912         glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &gl_max);
1913         gl_info->limits.buffers = gl_max;
1914         TRACE_(d3d_caps)("Max draw buffers: %u.\n", gl_max);
1915     }
1916     if (gl_info->supported[ARB_MULTITEXTURE])
1917     {
1918         glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &gl_max);
1919         gl_info->limits.textures = min(MAX_TEXTURES, gl_max);
1920         TRACE_(d3d_caps)("Max textures: %d.\n", gl_info->limits.textures);
1921
1922         if (gl_info->supported[NV_REGISTER_COMBINERS])
1923         {
1924             GLint tmp;
1925             glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &tmp);
1926             gl_info->limits.texture_stages = min(MAX_TEXTURES, tmp);
1927         }
1928         else
1929         {
1930             gl_info->limits.texture_stages = min(MAX_TEXTURES, gl_max);
1931         }
1932         TRACE_(d3d_caps)("Max texture stages: %d.\n", gl_info->limits.texture_stages);
1933
1934         if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1935         {
1936             GLint tmp;
1937             glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
1938             gl_info->limits.fragment_samplers = min(MAX_FRAGMENT_SAMPLERS, tmp);
1939         }
1940         else
1941         {
1942             gl_info->limits.fragment_samplers = max(gl_info->limits.fragment_samplers, gl_max);
1943         }
1944         TRACE_(d3d_caps)("Max fragment samplers: %d.\n", gl_info->limits.fragment_samplers);
1945
1946         if (gl_info->supported[ARB_VERTEX_SHADER])
1947         {
1948             GLint tmp;
1949             glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &tmp);
1950             gl_info->limits.vertex_samplers = tmp;
1951             glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &tmp);
1952             gl_info->limits.combined_samplers = tmp;
1953
1954             /* Loading GLSL sampler uniforms is much simpler if we can assume that the sampler setup
1955              * is known at shader link time. In a vertex shader + pixel shader combination this isn't
1956              * an issue because then the sampler setup only depends on the two shaders. If a pixel
1957              * shader is used with fixed function vertex processing we're fine too because fixed function
1958              * vertex processing doesn't use any samplers. If fixed function fragment processing is
1959              * used we have to make sure that all vertex sampler setups are valid together with all
1960              * possible fixed function fragment processing setups. This is true if vsamplers + MAX_TEXTURES
1961              * <= max_samplers. This is true on all d3d9 cards that support vtf(gf 6 and gf7 cards).
1962              * dx9 radeon cards do not support vertex texture fetch. DX10 cards have 128 samplers, and
1963              * dx9 is limited to 8 fixed function texture stages and 4 vertex samplers. DX10 does not have
1964              * a fixed function pipeline anymore.
1965              *
1966              * So this is just a check to check that our assumption holds true. If not, write a warning
1967              * and reduce the number of vertex samplers or probably disable vertex texture fetch. */
1968             if (gl_info->limits.vertex_samplers && gl_info->limits.combined_samplers < 12
1969                     && MAX_TEXTURES + gl_info->limits.vertex_samplers > gl_info->limits.combined_samplers)
1970             {
1971                 FIXME("OpenGL implementation supports %u vertex samplers and %u total samplers.\n",
1972                         gl_info->limits.vertex_samplers, gl_info->limits.combined_samplers);
1973                 FIXME("Expected vertex samplers + MAX_TEXTURES(=8) > combined_samplers.\n");
1974                 if (gl_info->limits.combined_samplers > MAX_TEXTURES)
1975                     gl_info->limits.vertex_samplers = gl_info->limits.combined_samplers - MAX_TEXTURES;
1976                 else
1977                     gl_info->limits.vertex_samplers = 0;
1978             }
1979         }
1980         else
1981         {
1982             gl_info->limits.combined_samplers = gl_info->limits.fragment_samplers;
1983         }
1984         TRACE_(d3d_caps)("Max vertex samplers: %u.\n", gl_info->limits.vertex_samplers);
1985         TRACE_(d3d_caps)("Max combined samplers: %u.\n", gl_info->limits.combined_samplers);
1986     }
1987     if (gl_info->supported[ARB_VERTEX_BLEND])
1988     {
1989         glGetIntegerv(GL_MAX_VERTEX_UNITS_ARB, &gl_max);
1990         gl_info->limits.blends = gl_max;
1991         TRACE_(d3d_caps)("Max blends: %u.\n", gl_info->limits.blends);
1992     }
1993     if (gl_info->supported[EXT_TEXTURE3D])
1994     {
1995         glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_EXT, &gl_max);
1996         gl_info->limits.texture3d_size = gl_max;
1997         TRACE_(d3d_caps)("Max texture3D size: %d.\n", gl_info->limits.texture3d_size);
1998     }
1999     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
2000     {
2001         glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &gl_max);
2002         gl_info->limits.anisotropy = gl_max;
2003         TRACE_(d3d_caps)("Max anisotropy: %d.\n", gl_info->limits.anisotropy);
2004     }
2005     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2006     {
2007         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
2008         gl_info->limits.arb_ps_float_constants = gl_max;
2009         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM float constants: %d.\n", gl_info->limits.arb_ps_float_constants);
2010         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, &gl_max));
2011         gl_info->limits.arb_ps_native_constants = gl_max;
2012         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native float constants: %d.\n",
2013                 gl_info->limits.arb_ps_native_constants);
2014         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
2015         gl_info->limits.arb_ps_temps = gl_max;
2016         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native temporaries: %d.\n", gl_info->limits.arb_ps_temps);
2017         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
2018         gl_info->limits.arb_ps_instructions = gl_max;
2019         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM native instructions: %d.\n", gl_info->limits.arb_ps_instructions);
2020         GL_EXTCALL(glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &gl_max));
2021         gl_info->limits.arb_ps_local_constants = gl_max;
2022         TRACE_(d3d_caps)("Max ARB_FRAGMENT_PROGRAM local parameters: %d.\n", gl_info->limits.arb_ps_instructions);
2023     }
2024     if (gl_info->supported[ARB_VERTEX_PROGRAM])
2025     {
2026         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_ENV_PARAMETERS_ARB, &gl_max));
2027         gl_info->limits.arb_vs_float_constants = gl_max;
2028         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM float constants: %d.\n", gl_info->limits.arb_vs_float_constants);
2029         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB, &gl_max));
2030         gl_info->limits.arb_vs_native_constants = gl_max;
2031         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native float constants: %d.\n",
2032                 gl_info->limits.arb_vs_native_constants);
2033         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB, &gl_max));
2034         gl_info->limits.arb_vs_temps = gl_max;
2035         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native temporaries: %d.\n", gl_info->limits.arb_vs_temps);
2036         GL_EXTCALL(glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB, &gl_max));
2037         gl_info->limits.arb_vs_instructions = gl_max;
2038         TRACE_(d3d_caps)("Max ARB_VERTEX_PROGRAM native instructions: %d.\n", gl_info->limits.arb_vs_instructions);
2039
2040         if (test_arb_vs_offset_limit(gl_info)) gl_info->quirks |= WINED3D_QUIRK_ARB_VS_OFFSET_LIMIT;
2041     }
2042     if (gl_info->supported[ARB_VERTEX_SHADER])
2043     {
2044         glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, &gl_max);
2045         gl_info->limits.glsl_vs_float_constants = gl_max / 4;
2046         TRACE_(d3d_caps)("Max ARB_VERTEX_SHADER float constants: %u.\n", gl_info->limits.glsl_vs_float_constants);
2047     }
2048     if (gl_info->supported[ARB_FRAGMENT_SHADER])
2049     {
2050         glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, &gl_max);
2051         gl_info->limits.glsl_ps_float_constants = gl_max / 4;
2052         TRACE_(d3d_caps)("Max ARB_FRAGMENT_SHADER float constants: %u.\n", gl_info->limits.glsl_ps_float_constants);
2053         glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, &gl_max);
2054         gl_info->limits.glsl_varyings = gl_max;
2055         TRACE_(d3d_caps)("Max GLSL varyings: %u (%u 4 component varyings).\n", gl_max, gl_max / 4);
2056     }
2057     if (gl_info->supported[ARB_SHADING_LANGUAGE_100])
2058     {
2059         const char *str = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION_ARB);
2060         TRACE_(d3d_caps)("GLSL version string: %s.\n", debugstr_a(str));
2061     }
2062     if (gl_info->supported[NV_LIGHT_MAX_EXPONENT])
2063     {
2064         glGetFloatv(GL_MAX_SHININESS_NV, &gl_info->limits.shininess);
2065     }
2066     else
2067     {
2068         gl_info->limits.shininess = 128.0f;
2069     }
2070     if (gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
2071     {
2072         /* If we have full NP2 texture support, disable
2073          * GL_ARB_texture_rectangle because we will never use it.
2074          * This saves a few redundant glDisable calls. */
2075         gl_info->supported[ARB_TEXTURE_RECTANGLE] = FALSE;
2076     }
2077     if (gl_info->supported[ATI_FRAGMENT_SHADER])
2078     {
2079         /* Disable NV_register_combiners and fragment shader if this is supported.
2080          * generally the NV extensions are preferred over the ATI ones, and this
2081          * extension is disabled if register_combiners and texture_shader2 are both
2082          * supported. So we reach this place only if we have incomplete NV dxlevel 8
2083          * fragment processing support. */
2084         gl_info->supported[NV_REGISTER_COMBINERS] = FALSE;
2085         gl_info->supported[NV_REGISTER_COMBINERS2] = FALSE;
2086         gl_info->supported[NV_TEXTURE_SHADER] = FALSE;
2087         gl_info->supported[NV_TEXTURE_SHADER2] = FALSE;
2088         gl_info->supported[NV_TEXTURE_SHADER3] = FALSE;
2089     }
2090     if (gl_info->supported[NV_HALF_FLOAT])
2091     {
2092         /* GL_ARB_half_float_vertex is a subset of GL_NV_half_float. */
2093         gl_info->supported[ARB_HALF_FLOAT_VERTEX] = TRUE;
2094     }
2095     if (gl_info->supported[ARB_POINT_SPRITE])
2096     {
2097         gl_info->limits.point_sprite_units = gl_info->limits.textures;
2098     }
2099     else
2100     {
2101         gl_info->limits.point_sprite_units = 0;
2102     }
2103     checkGLcall("extension detection");
2104
2105     LEAVE_GL();
2106
2107     adapter->fragment_pipe = select_fragment_implementation(adapter);
2108     adapter->shader_backend = select_shader_backend(adapter);
2109     adapter->blitter = select_blit_implementation(adapter);
2110
2111     /* In some cases the number of texture stages can be larger than the number
2112      * of samplers. The GF4 for example can use only 2 samplers (no fragment
2113      * shaders), but 8 texture stages (register combiners). */
2114     gl_info->limits.sampler_stages = max(gl_info->limits.fragment_samplers, gl_info->limits.texture_stages);
2115
2116     if (gl_info->supported[ARB_FRAMEBUFFER_OBJECT])
2117     {
2118         gl_info->fbo_ops.glIsRenderbuffer = gl_info->glIsRenderbuffer;
2119         gl_info->fbo_ops.glBindRenderbuffer = gl_info->glBindRenderbuffer;
2120         gl_info->fbo_ops.glDeleteRenderbuffers = gl_info->glDeleteRenderbuffers;
2121         gl_info->fbo_ops.glGenRenderbuffers = gl_info->glGenRenderbuffers;
2122         gl_info->fbo_ops.glRenderbufferStorage = gl_info->glRenderbufferStorage;
2123         gl_info->fbo_ops.glRenderbufferStorageMultisample = gl_info->glRenderbufferStorageMultisample;
2124         gl_info->fbo_ops.glGetRenderbufferParameteriv = gl_info->glGetRenderbufferParameteriv;
2125         gl_info->fbo_ops.glIsFramebuffer = gl_info->glIsFramebuffer;
2126         gl_info->fbo_ops.glBindFramebuffer = gl_info->glBindFramebuffer;
2127         gl_info->fbo_ops.glDeleteFramebuffers = gl_info->glDeleteFramebuffers;
2128         gl_info->fbo_ops.glGenFramebuffers = gl_info->glGenFramebuffers;
2129         gl_info->fbo_ops.glCheckFramebufferStatus = gl_info->glCheckFramebufferStatus;
2130         gl_info->fbo_ops.glFramebufferTexture1D = gl_info->glFramebufferTexture1D;
2131         gl_info->fbo_ops.glFramebufferTexture2D = gl_info->glFramebufferTexture2D;
2132         gl_info->fbo_ops.glFramebufferTexture3D = gl_info->glFramebufferTexture3D;
2133         gl_info->fbo_ops.glFramebufferRenderbuffer = gl_info->glFramebufferRenderbuffer;
2134         gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv = gl_info->glGetFramebufferAttachmentParameteriv;
2135         gl_info->fbo_ops.glBlitFramebuffer = gl_info->glBlitFramebuffer;
2136         gl_info->fbo_ops.glGenerateMipmap = gl_info->glGenerateMipmap;
2137     }
2138     else
2139     {
2140         if (gl_info->supported[EXT_FRAMEBUFFER_OBJECT])
2141         {
2142             gl_info->fbo_ops.glIsRenderbuffer = gl_info->glIsRenderbufferEXT;
2143             gl_info->fbo_ops.glBindRenderbuffer = gl_info->glBindRenderbufferEXT;
2144             gl_info->fbo_ops.glDeleteRenderbuffers = gl_info->glDeleteRenderbuffersEXT;
2145             gl_info->fbo_ops.glGenRenderbuffers = gl_info->glGenRenderbuffersEXT;
2146             gl_info->fbo_ops.glRenderbufferStorage = gl_info->glRenderbufferStorageEXT;
2147             gl_info->fbo_ops.glGetRenderbufferParameteriv = gl_info->glGetRenderbufferParameterivEXT;
2148             gl_info->fbo_ops.glIsFramebuffer = gl_info->glIsFramebufferEXT;
2149             gl_info->fbo_ops.glBindFramebuffer = gl_info->glBindFramebufferEXT;
2150             gl_info->fbo_ops.glDeleteFramebuffers = gl_info->glDeleteFramebuffersEXT;
2151             gl_info->fbo_ops.glGenFramebuffers = gl_info->glGenFramebuffersEXT;
2152             gl_info->fbo_ops.glCheckFramebufferStatus = gl_info->glCheckFramebufferStatusEXT;
2153             gl_info->fbo_ops.glFramebufferTexture1D = gl_info->glFramebufferTexture1DEXT;
2154             gl_info->fbo_ops.glFramebufferTexture2D = gl_info->glFramebufferTexture2DEXT;
2155             gl_info->fbo_ops.glFramebufferTexture3D = gl_info->glFramebufferTexture3DEXT;
2156             gl_info->fbo_ops.glFramebufferRenderbuffer = gl_info->glFramebufferRenderbufferEXT;
2157             gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv = gl_info->glGetFramebufferAttachmentParameterivEXT;
2158             gl_info->fbo_ops.glGenerateMipmap = gl_info->glGenerateMipmapEXT;
2159         }
2160         else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2161         {
2162             WARN_(d3d_caps)("Framebuffer objects not supported, falling back to backbuffer offscreen rendering mode.\n");
2163             wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
2164         }
2165         if (gl_info->supported[EXT_FRAMEBUFFER_BLIT])
2166         {
2167             gl_info->fbo_ops.glBlitFramebuffer = gl_info->glBlitFramebufferEXT;
2168         }
2169         if (gl_info->supported[EXT_FRAMEBUFFER_MULTISAMPLE])
2170         {
2171             gl_info->fbo_ops.glRenderbufferStorageMultisample = gl_info->glRenderbufferStorageMultisampleEXT;
2172         }
2173     }
2174
2175     /* MRTs are currently only supported when FBOs are used. */
2176     if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2177     {
2178         gl_info->limits.buffers = 1;
2179     }
2180
2181     device = wined3d_guess_card(gl_info, gl_renderer, &vendor, &vidmem);
2182     TRACE_(d3d_caps)("FOUND (fake) card: 0x%x (vendor id), 0x%x (device id)\n", vendor, device);
2183
2184     /* If we have an estimate use it, else default to 64MB;  */
2185     if(vidmem)
2186         gl_info->vidmem = vidmem*1024*1024; /* convert from MBs to bytes */
2187     else
2188         gl_info->vidmem = WINE_DEFAULT_VIDMEM;
2189
2190     gl_info->wrap_lookup[WINED3DTADDRESS_WRAP - WINED3DTADDRESS_WRAP] = GL_REPEAT;
2191     gl_info->wrap_lookup[WINED3DTADDRESS_MIRROR - WINED3DTADDRESS_WRAP] =
2192             gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT] ? GL_MIRRORED_REPEAT_ARB : GL_REPEAT;
2193     gl_info->wrap_lookup[WINED3DTADDRESS_CLAMP - WINED3DTADDRESS_WRAP] = GL_CLAMP_TO_EDGE;
2194     gl_info->wrap_lookup[WINED3DTADDRESS_BORDER - WINED3DTADDRESS_WRAP] =
2195             gl_info->supported[ARB_TEXTURE_BORDER_CLAMP] ? GL_CLAMP_TO_BORDER_ARB : GL_REPEAT;
2196     gl_info->wrap_lookup[WINED3DTADDRESS_MIRRORONCE - WINED3DTADDRESS_WRAP] =
2197             gl_info->supported[ATI_TEXTURE_MIRROR_ONCE] ? GL_MIRROR_CLAMP_TO_EDGE_ATI : GL_REPEAT;
2198
2199     /* Make sure there's an active HDC else the WGL extensions will fail */
2200     hdc = pwglGetCurrentDC();
2201     if (hdc) {
2202         /* Not all GL drivers might offer WGL extensions e.g. VirtualBox */
2203         if(GL_EXTCALL(wglGetExtensionsStringARB))
2204             WGL_Extensions = GL_EXTCALL(wglGetExtensionsStringARB(hdc));
2205
2206         if (NULL == WGL_Extensions) {
2207             ERR("   WGL_Extensions returns NULL\n");
2208         } else {
2209             TRACE_(d3d_caps)("WGL_Extensions reported:\n");
2210             while (*WGL_Extensions != 0x00) {
2211                 const char *Start;
2212                 char ThisExtn[256];
2213
2214                 while (isspace(*WGL_Extensions)) WGL_Extensions++;
2215                 Start = WGL_Extensions;
2216                 while (!isspace(*WGL_Extensions) && *WGL_Extensions != 0x00) {
2217                     WGL_Extensions++;
2218                 }
2219
2220                 len = WGL_Extensions - Start;
2221                 if (len == 0 || len >= sizeof(ThisExtn))
2222                     continue;
2223
2224                 memcpy(ThisExtn, Start, len);
2225                 ThisExtn[len] = '\0';
2226                 TRACE_(d3d_caps)("- %s\n", debugstr_a(ThisExtn));
2227
2228                 if (!strcmp(ThisExtn, "WGL_ARB_pbuffer")) {
2229                     gl_info->supported[WGL_ARB_PBUFFER] = TRUE;
2230                     TRACE_(d3d_caps)("FOUND: WGL_ARB_pbuffer support\n");
2231                 }
2232                 if (!strcmp(ThisExtn, "WGL_ARB_pixel_format")) {
2233                     gl_info->supported[WGL_ARB_PIXEL_FORMAT] = TRUE;
2234                     TRACE_(d3d_caps)("FOUND: WGL_ARB_pixel_format support\n");
2235                 }
2236                 if (!strcmp(ThisExtn, "WGL_WINE_pixel_format_passthrough")) {
2237                     gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH] = TRUE;
2238                     TRACE_(d3d_caps)("FOUND: WGL_WINE_pixel_format_passthrough support\n");
2239                 }
2240             }
2241         }
2242     }
2243
2244     fixup_extensions(gl_info, gl_renderer, vendor, device);
2245     init_driver_info(driver_info, vendor, device);
2246     add_gl_compat_wrappers(gl_info);
2247
2248     HeapFree(GetProcessHeap(), 0, gl_renderer);
2249     return TRUE;
2250 }
2251
2252 /**********************************************************
2253  * IWineD3D implementation follows
2254  **********************************************************/
2255
2256 static UINT     WINAPI IWineD3DImpl_GetAdapterCount (IWineD3D *iface) {
2257     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2258
2259     TRACE_(d3d_caps)("(%p): Reporting %u adapters\n", This, This->adapter_count);
2260
2261     return This->adapter_count;
2262 }
2263
2264 static HRESULT WINAPI IWineD3DImpl_RegisterSoftwareDevice(IWineD3D *iface, void *init_function)
2265 {
2266     FIXME("iface %p, init_function %p stub!\n", iface, init_function);
2267
2268     return WINED3D_OK;
2269 }
2270
2271 static HMONITOR WINAPI IWineD3DImpl_GetAdapterMonitor(IWineD3D *iface, UINT Adapter) {
2272     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2273
2274     TRACE_(d3d_caps)("(%p)->(%d)\n", This, Adapter);
2275
2276     if (Adapter >= IWineD3DImpl_GetAdapterCount(iface)) {
2277         return NULL;
2278     }
2279
2280     return MonitorFromPoint(This->adapters[Adapter].monitorPoint, MONITOR_DEFAULTTOPRIMARY);
2281 }
2282
2283 /* FIXME: GetAdapterModeCount and EnumAdapterModes currently only returns modes
2284      of the same bpp but different resolutions                                  */
2285
2286 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
2287 static UINT     WINAPI IWineD3DImpl_GetAdapterModeCount(IWineD3D *iface, UINT Adapter, WINED3DFORMAT Format) {
2288     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2289     TRACE_(d3d_caps)("(%p}->(Adapter: %d, Format: %s)\n", This, Adapter, debug_d3dformat(Format));
2290
2291     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2292         return 0;
2293     }
2294
2295     /* TODO: Store modes per adapter and read it from the adapter structure */
2296     if (Adapter == 0) { /* Display */
2297         const struct GlPixelFormatDesc *format_desc = getFormatDescEntry(Format, &This->adapters[Adapter].gl_info);
2298         UINT format_bits = format_desc->byte_count * CHAR_BIT;
2299         unsigned int i = 0;
2300         unsigned int j = 0;
2301         DEVMODEW mode;
2302
2303         memset(&mode, 0, sizeof(mode));
2304         mode.dmSize = sizeof(mode);
2305
2306         while (EnumDisplaySettingsExW(NULL, j, &mode, 0))
2307         {
2308             ++j;
2309
2310             if (Format == WINED3DFMT_UNKNOWN)
2311             {
2312                 /* This is for D3D8, do not enumerate P8 here */
2313                 if (mode.dmBitsPerPel == 32 || mode.dmBitsPerPel == 16) ++i;
2314             }
2315             else if (mode.dmBitsPerPel == format_bits)
2316             {
2317                 ++i;
2318             }
2319         }
2320
2321         TRACE_(d3d_caps)("(%p}->(Adapter: %d) => %d (out of %d)\n", This, Adapter, i, j);
2322         return i;
2323     } else {
2324         FIXME_(d3d_caps)("Adapter not primary display\n");
2325     }
2326     return 0;
2327 }
2328
2329 /* Note: dx9 supplies a format. Calls from d3d8 supply WINED3DFMT_UNKNOWN */
2330 static HRESULT WINAPI IWineD3DImpl_EnumAdapterModes(IWineD3D *iface, UINT Adapter, WINED3DFORMAT Format, UINT Mode, WINED3DDISPLAYMODE* pMode) {
2331     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2332     TRACE_(d3d_caps)("(%p}->(Adapter:%d, mode:%d, pMode:%p, format:%s)\n", This, Adapter, Mode, pMode, debug_d3dformat(Format));
2333
2334     /* Validate the parameters as much as possible */
2335     if (NULL == pMode ||
2336         Adapter >= IWineD3DImpl_GetAdapterCount(iface) ||
2337         Mode    >= IWineD3DImpl_GetAdapterModeCount(iface, Adapter, Format)) {
2338         return WINED3DERR_INVALIDCALL;
2339     }
2340
2341     /* TODO: Store modes per adapter and read it from the adapter structure */
2342     if (Adapter == 0)
2343     {
2344         const struct GlPixelFormatDesc *format_desc = getFormatDescEntry(Format, &This->adapters[Adapter].gl_info);
2345         UINT format_bits = format_desc->byte_count * CHAR_BIT;
2346         DEVMODEW DevModeW;
2347         int ModeIdx = 0;
2348         UINT i = 0;
2349         int j = 0;
2350
2351         ZeroMemory(&DevModeW, sizeof(DevModeW));
2352         DevModeW.dmSize = sizeof(DevModeW);
2353
2354         /* If we are filtering to a specific format (D3D9), then need to skip
2355            all unrelated modes, but if mode is irrelevant (D3D8), then we can
2356            just count through the ones with valid bit depths */
2357         while ((i<=Mode) && EnumDisplaySettingsExW(NULL, j++, &DevModeW, 0))
2358         {
2359             if (Format == WINED3DFMT_UNKNOWN)
2360             {
2361                 /* This is for D3D8, do not enumerate P8 here */
2362                 if (DevModeW.dmBitsPerPel == 32 || DevModeW.dmBitsPerPel == 16) ++i;
2363             }
2364             else if (DevModeW.dmBitsPerPel == format_bits)
2365             {
2366                 ++i;
2367             }
2368         }
2369
2370         if (i == 0) {
2371             TRACE_(d3d_caps)("No modes found for format (%x - %s)\n", Format, debug_d3dformat(Format));
2372             return WINED3DERR_INVALIDCALL;
2373         }
2374         ModeIdx = j - 1;
2375
2376         /* Now get the display mode via the calculated index */
2377         if (EnumDisplaySettingsExW(NULL, ModeIdx, &DevModeW, 0)) {
2378             pMode->Width        = DevModeW.dmPelsWidth;
2379             pMode->Height       = DevModeW.dmPelsHeight;
2380             pMode->RefreshRate  = DEFAULT_REFRESH_RATE;
2381             if (DevModeW.dmFields & DM_DISPLAYFREQUENCY)
2382                 pMode->RefreshRate = DevModeW.dmDisplayFrequency;
2383
2384             if (Format == WINED3DFMT_UNKNOWN) {
2385                 pMode->Format = pixelformat_for_depth(DevModeW.dmBitsPerPel);
2386             } else {
2387                 pMode->Format = Format;
2388             }
2389         } else {
2390             TRACE_(d3d_caps)("Requested mode out of range %d\n", Mode);
2391             return WINED3DERR_INVALIDCALL;
2392         }
2393
2394         TRACE_(d3d_caps)("W %d H %d rr %d fmt (%x - %s) bpp %u\n", pMode->Width, pMode->Height,
2395                 pMode->RefreshRate, pMode->Format, debug_d3dformat(pMode->Format),
2396                 DevModeW.dmBitsPerPel);
2397
2398     }
2399     else
2400     {
2401         FIXME_(d3d_caps)("Adapter not primary display\n");
2402     }
2403
2404     return WINED3D_OK;
2405 }
2406
2407 static HRESULT WINAPI IWineD3DImpl_GetAdapterDisplayMode(IWineD3D *iface, UINT Adapter, WINED3DDISPLAYMODE *pMode)
2408 {
2409     TRACE("iface %p, adapter_idx %u, display_mode %p.\n", iface, Adapter, pMode);
2410
2411     if (NULL == pMode ||
2412         Adapter >= IWineD3D_GetAdapterCount(iface)) {
2413         return WINED3DERR_INVALIDCALL;
2414     }
2415
2416     if (Adapter == 0) { /* Display */
2417         int bpp = 0;
2418         DEVMODEW DevModeW;
2419
2420         ZeroMemory(&DevModeW, sizeof(DevModeW));
2421         DevModeW.dmSize = sizeof(DevModeW);
2422
2423         EnumDisplaySettingsExW(NULL, ENUM_CURRENT_SETTINGS, &DevModeW, 0);
2424         pMode->Width        = DevModeW.dmPelsWidth;
2425         pMode->Height       = DevModeW.dmPelsHeight;
2426         bpp                 = DevModeW.dmBitsPerPel;
2427         pMode->RefreshRate  = DEFAULT_REFRESH_RATE;
2428         if (DevModeW.dmFields&DM_DISPLAYFREQUENCY)
2429         {
2430             pMode->RefreshRate = DevModeW.dmDisplayFrequency;
2431         }
2432
2433         pMode->Format = pixelformat_for_depth(bpp);
2434     } else {
2435         FIXME_(d3d_caps)("Adapter not primary display\n");
2436     }
2437
2438     TRACE_(d3d_caps)("returning w:%d, h:%d, ref:%d, fmt:%s\n", pMode->Width,
2439           pMode->Height, pMode->RefreshRate, debug_d3dformat(pMode->Format));
2440     return WINED3D_OK;
2441 }
2442
2443 /* NOTE: due to structure differences between dx8 and dx9 D3DADAPTER_IDENTIFIER,
2444    and fields being inserted in the middle, a new structure is used in place    */
2445 static HRESULT WINAPI IWineD3DImpl_GetAdapterIdentifier(IWineD3D *iface, UINT Adapter, DWORD Flags,
2446                                                    WINED3DADAPTER_IDENTIFIER* pIdentifier) {
2447     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2448     struct wined3d_adapter *adapter;
2449     size_t len;
2450
2451     TRACE_(d3d_caps)("(%p}->(Adapter: %d, Flags: %x, pId=%p)\n", This, Adapter, Flags, pIdentifier);
2452
2453     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2454         return WINED3DERR_INVALIDCALL;
2455     }
2456
2457     adapter = &This->adapters[Adapter];
2458
2459     /* Return the information requested */
2460     TRACE_(d3d_caps)("device/Vendor Name and Version detection using FillGLCaps\n");
2461
2462     if (pIdentifier->driver_size)
2463     {
2464         const char *name = adapter->driver_info.name;
2465         len = min(strlen(name), pIdentifier->driver_size - 1);
2466         memcpy(pIdentifier->driver, name, len);
2467         pIdentifier->driver[len] = '\0';
2468     }
2469
2470     if (pIdentifier->description_size)
2471     {
2472         const char *description = adapter->driver_info.description;
2473         len = min(strlen(description), pIdentifier->description_size - 1);
2474         memcpy(pIdentifier->description, description, len);
2475         pIdentifier->description[len] = '\0';
2476     }
2477
2478     /* Note that d3d8 doesn't supply a device name. */
2479     if (pIdentifier->device_name_size)
2480     {
2481         static const char *device_name = "\\\\.\\DISPLAY1"; /* FIXME: May depend on desktop? */
2482
2483         len = strlen(device_name);
2484         if (len >= pIdentifier->device_name_size)
2485         {
2486             ERR("Device name size too small.\n");
2487             return WINED3DERR_INVALIDCALL;
2488         }
2489
2490         memcpy(pIdentifier->device_name, device_name, len);
2491         pIdentifier->device_name[len] = '\0';
2492     }
2493
2494     pIdentifier->driver_version.u.HighPart = adapter->driver_info.version_high;
2495     pIdentifier->driver_version.u.LowPart = adapter->driver_info.version_low;
2496     pIdentifier->vendor_id = adapter->driver_info.vendor;
2497     pIdentifier->device_id = adapter->driver_info.device;
2498     pIdentifier->subsystem_id = 0;
2499     pIdentifier->revision = 0;
2500     memcpy(&pIdentifier->device_identifier, &IID_D3DDEVICE_D3DUID, sizeof(pIdentifier->device_identifier));
2501     pIdentifier->whql_level = (Flags & WINED3DENUM_NO_WHQL_LEVEL) ? 0 : 1;
2502     memcpy(&pIdentifier->adapter_luid, &adapter->luid, sizeof(pIdentifier->adapter_luid));
2503     pIdentifier->video_memory = adapter->TextureRam;
2504
2505     return WINED3D_OK;
2506 }
2507
2508 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(const struct wined3d_gl_info *gl_info,
2509         const WineD3D_PixelFormat *cfg, const struct GlPixelFormatDesc *format_desc)
2510 {
2511     short redSize, greenSize, blueSize, alphaSize, colorBits;
2512
2513     if(!cfg)
2514         return FALSE;
2515
2516     if(cfg->iPixelType == WGL_TYPE_RGBA_ARB) { /* Integer RGBA formats */
2517         if (!getColorBits(format_desc, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
2518         {
2519             ERR("Unable to check compatibility for Format=%s\n", debug_d3dformat(format_desc->format));
2520             return FALSE;
2521         }
2522
2523         if(cfg->redSize < redSize)
2524             return FALSE;
2525
2526         if(cfg->greenSize < greenSize)
2527             return FALSE;
2528
2529         if(cfg->blueSize < blueSize)
2530             return FALSE;
2531
2532         if(cfg->alphaSize < alphaSize)
2533             return FALSE;
2534
2535         return TRUE;
2536     } else if(cfg->iPixelType == WGL_TYPE_RGBA_FLOAT_ARB) { /* Float RGBA formats; TODO: WGL_NV_float_buffer */
2537         if (format_desc->format == WINED3DFMT_R16_FLOAT)
2538             return (cfg->redSize == 16 && cfg->greenSize == 0 && cfg->blueSize == 0 && cfg->alphaSize == 0);
2539         if (format_desc->format == WINED3DFMT_R16G16_FLOAT)
2540             return (cfg->redSize == 16 && cfg->greenSize == 16 && cfg->blueSize == 0 && cfg->alphaSize == 0);
2541         if (format_desc->format == WINED3DFMT_R16G16B16A16_FLOAT)
2542             return (cfg->redSize == 16 && cfg->greenSize == 16 && cfg->blueSize == 16 && cfg->alphaSize == 16);
2543         if (format_desc->format == WINED3DFMT_R32_FLOAT)
2544             return (cfg->redSize == 32 && cfg->greenSize == 0 && cfg->blueSize == 0 && cfg->alphaSize == 0);
2545         if (format_desc->format == WINED3DFMT_R32G32_FLOAT)
2546             return (cfg->redSize == 32 && cfg->greenSize == 32 && cfg->blueSize == 0 && cfg->alphaSize == 0);
2547         if (format_desc->format == WINED3DFMT_R32G32B32A32_FLOAT)
2548             return (cfg->redSize == 32 && cfg->greenSize == 32 && cfg->blueSize == 32 && cfg->alphaSize == 32);
2549     } else {
2550         /* Probably a color index mode */
2551         return FALSE;
2552     }
2553
2554     return FALSE;
2555 }
2556
2557 static BOOL IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(const struct wined3d_gl_info *gl_info,
2558         const WineD3D_PixelFormat *cfg, const struct GlPixelFormatDesc *format_desc)
2559 {
2560     short depthSize, stencilSize;
2561     BOOL lockable = FALSE;
2562
2563     if(!cfg)
2564         return FALSE;
2565
2566     if (!getDepthStencilBits(format_desc, &depthSize, &stencilSize))
2567     {
2568         ERR("Unable to check compatibility for Format=%s\n", debug_d3dformat(format_desc->format));
2569         return FALSE;
2570     }
2571
2572     if ((format_desc->format == WINED3DFMT_D16_LOCKABLE) || (format_desc->format == WINED3DFMT_D32_FLOAT))
2573         lockable = TRUE;
2574
2575     /* On some modern cards like the Geforce8/9 GLX doesn't offer some dephthstencil formats which D3D9 reports.
2576      * We can safely report 'compatible' formats (e.g. D24 can be used for D16) as long as we aren't dealing with
2577      * a lockable format. This also helps D3D <= 7 as they expect D16 which isn't offered without this on Geforce8 cards. */
2578     if(!(cfg->depthSize == depthSize || (!lockable && cfg->depthSize > depthSize)))
2579         return FALSE;
2580
2581     /* Some cards like Intel i915 ones only offer D24S8 but lots of games also need a format without stencil, so
2582      * allow more stencil bits than requested. */
2583     if(cfg->stencilSize < stencilSize)
2584         return FALSE;
2585
2586     return TRUE;
2587 }
2588
2589 static HRESULT WINAPI IWineD3DImpl_CheckDepthStencilMatch(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
2590                                                    WINED3DFORMAT AdapterFormat,
2591                                                    WINED3DFORMAT RenderTargetFormat,
2592                                                    WINED3DFORMAT DepthStencilFormat) {
2593     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2594     int nCfgs;
2595     const WineD3D_PixelFormat *cfgs;
2596     const struct wined3d_adapter *adapter;
2597     const struct GlPixelFormatDesc *rt_format_desc;
2598     const struct GlPixelFormatDesc *ds_format_desc;
2599     int it;
2600
2601     WARN_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, DevType:(%x,%s), AdptFmt:(%x,%s), RendrTgtFmt:(%x,%s), DepthStencilFmt:(%x,%s))\n",
2602            This, Adapter,
2603            DeviceType, debug_d3ddevicetype(DeviceType),
2604            AdapterFormat, debug_d3dformat(AdapterFormat),
2605            RenderTargetFormat, debug_d3dformat(RenderTargetFormat),
2606            DepthStencilFormat, debug_d3dformat(DepthStencilFormat));
2607
2608     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2609         TRACE("(%p) Failed: Atapter (%u) higher than supported adapters (%u) returning WINED3DERR_INVALIDCALL\n", This, Adapter, IWineD3D_GetAdapterCount(iface));
2610         return WINED3DERR_INVALIDCALL;
2611     }
2612
2613     adapter = &This->adapters[Adapter];
2614     rt_format_desc = getFormatDescEntry(RenderTargetFormat, &adapter->gl_info);
2615     ds_format_desc = getFormatDescEntry(DepthStencilFormat, &adapter->gl_info);
2616     cfgs = adapter->cfgs;
2617     nCfgs = adapter->nCfgs;
2618     for (it = 0; it < nCfgs; ++it) {
2619         if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, &cfgs[it], rt_format_desc))
2620         {
2621             if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[it], ds_format_desc))
2622             {
2623                 TRACE_(d3d_caps)("(%p) : Formats matched\n", This);
2624                 return WINED3D_OK;
2625             }
2626         }
2627     }
2628     WARN_(d3d_caps)("unsupported format pair: %s and %s\n", debug_d3dformat(RenderTargetFormat), debug_d3dformat(DepthStencilFormat));
2629
2630     return WINED3DERR_NOTAVAILABLE;
2631 }
2632
2633 static HRESULT WINAPI IWineD3DImpl_CheckDeviceMultiSampleType(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
2634         WINED3DFORMAT SurfaceFormat, BOOL Windowed, WINED3DMULTISAMPLE_TYPE MultiSampleType, DWORD *pQualityLevels)
2635 {
2636     IWineD3DImpl *This = (IWineD3DImpl *)iface;
2637     const struct GlPixelFormatDesc *glDesc;
2638     const struct wined3d_adapter *adapter;
2639
2640     TRACE_(d3d_caps)("(%p)-> (Adptr:%d, DevType:(%x,%s), SurfFmt:(%x,%s), Win?%d, MultiSamp:%x, pQual:%p)\n",
2641           This,
2642           Adapter,
2643           DeviceType, debug_d3ddevicetype(DeviceType),
2644           SurfaceFormat, debug_d3dformat(SurfaceFormat),
2645           Windowed,
2646           MultiSampleType,
2647           pQualityLevels);
2648
2649     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2650         return WINED3DERR_INVALIDCALL;
2651     }
2652
2653     /* TODO: handle Windowed, add more quality levels */
2654
2655     if (WINED3DMULTISAMPLE_NONE == MultiSampleType) {
2656         if(pQualityLevels) *pQualityLevels = 1;
2657         return WINED3D_OK;
2658     }
2659
2660     /* By default multisampling is disabled right now as it causes issues
2661      * on some Nvidia driver versions and it doesn't work well in combination
2662      * with FBOs yet. */
2663     if(!wined3d_settings.allow_multisampling)
2664         return WINED3DERR_NOTAVAILABLE;
2665
2666     adapter = &This->adapters[Adapter];
2667     glDesc = getFormatDescEntry(SurfaceFormat, &adapter->gl_info);
2668     if (!glDesc) return WINED3DERR_INVALIDCALL;
2669
2670     if(glDesc->Flags & (WINED3DFMT_FLAG_DEPTH | WINED3DFMT_FLAG_STENCIL)) {
2671         int i, nCfgs;
2672         const WineD3D_PixelFormat *cfgs;
2673
2674         cfgs = adapter->cfgs;
2675         nCfgs = adapter->nCfgs;
2676         for(i=0; i<nCfgs; i++) {
2677             if(cfgs[i].numSamples != MultiSampleType)
2678                 continue;
2679
2680             if (!IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, &cfgs[i], glDesc))
2681                 continue;
2682
2683             TRACE("Found iPixelFormat=%d to support MultiSampleType=%d for format %s\n", cfgs[i].iPixelFormat, MultiSampleType, debug_d3dformat(SurfaceFormat));
2684
2685             if(pQualityLevels)
2686                 *pQualityLevels = 1; /* Guess at a value! */
2687             return WINED3D_OK;
2688         }
2689     }
2690     else if(glDesc->Flags & WINED3DFMT_FLAG_RENDERTARGET) {
2691         short redSize, greenSize, blueSize, alphaSize, colorBits;
2692         int i, nCfgs;
2693         const WineD3D_PixelFormat *cfgs;
2694
2695         if (!getColorBits(glDesc, &redSize, &greenSize, &blueSize, &alphaSize, &colorBits))
2696         {
2697             ERR("Unable to color bits for format %#x, can't check multisampling capability!\n", SurfaceFormat);
2698             return WINED3DERR_NOTAVAILABLE;
2699         }
2700
2701         cfgs = adapter->cfgs;
2702         nCfgs = adapter->nCfgs;
2703         for(i=0; i<nCfgs; i++) {
2704             if(cfgs[i].numSamples != MultiSampleType)
2705                 continue;
2706             if(cfgs[i].redSize != redSize)
2707                 continue;
2708             if(cfgs[i].greenSize != greenSize)
2709                 continue;
2710             if(cfgs[i].blueSize != blueSize)
2711                 continue;
2712             if(cfgs[i].alphaSize != alphaSize)
2713                 continue;
2714
2715             TRACE("Found iPixelFormat=%d to support MultiSampleType=%d for format %s\n", cfgs[i].iPixelFormat, MultiSampleType, debug_d3dformat(SurfaceFormat));
2716
2717             if(pQualityLevels)
2718                 *pQualityLevels = 1; /* Guess at a value! */
2719             return WINED3D_OK;
2720         }
2721     }
2722     return WINED3DERR_NOTAVAILABLE;
2723 }
2724
2725 static HRESULT WINAPI IWineD3DImpl_CheckDeviceType(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
2726         WINED3DFORMAT DisplayFormat, WINED3DFORMAT BackBufferFormat, BOOL Windowed)
2727 {
2728     HRESULT hr = WINED3DERR_NOTAVAILABLE;
2729     UINT nmodes;
2730
2731     TRACE("iface %p, adapter_idx %u, device_type %s, display_format %s, backbuffer_format %s, windowed %#x.\n",
2732             iface, Adapter, debug_d3ddevicetype(DeviceType), debug_d3dformat(DisplayFormat),
2733             debug_d3dformat(BackBufferFormat), Windowed);
2734
2735     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
2736         WARN_(d3d_caps)("Adapter >= IWineD3D_GetAdapterCount(iface), returning WINED3DERR_INVALIDCALL\n");
2737         return WINED3DERR_INVALIDCALL;
2738     }
2739
2740     /* The task of this function is to check whether a certain display / backbuffer format
2741      * combination is available on the given adapter. In fullscreen mode microsoft specified
2742      * that the display format shouldn't provide alpha and that ignoring alpha the backbuffer
2743      * and display format should match exactly.
2744      * In windowed mode format conversion can occur and this depends on the driver. When format
2745      * conversion is done, this function should nevertheless fail and applications need to use
2746      * CheckDeviceFormatConversion.
2747      * At the moment we assume that fullscreen and windowed have the same capabilities */
2748
2749     /* There are only 4 display formats */
2750     if (!(DisplayFormat == WINED3DFMT_B5G6R5_UNORM
2751             || DisplayFormat == WINED3DFMT_B5G5R5X1_UNORM
2752             || DisplayFormat == WINED3DFMT_B8G8R8X8_UNORM
2753             || DisplayFormat == WINED3DFMT_B10G10R10A2_UNORM))
2754     {
2755         TRACE_(d3d_caps)("Format %s unsupported as display format\n", debug_d3dformat(DisplayFormat));
2756         return WINED3DERR_NOTAVAILABLE;
2757     }
2758
2759     /* If the requested DisplayFormat is not available, don't continue */
2760     nmodes = IWineD3DImpl_GetAdapterModeCount(iface, Adapter, DisplayFormat);
2761     if(!nmodes) {
2762         TRACE_(d3d_caps)("No available modes for display format %s\n", debug_d3dformat(DisplayFormat));
2763         return WINED3DERR_NOTAVAILABLE;
2764     }
2765
2766     /* Windowed mode allows you to specify WINED3DFMT_UNKNOWN for the backbufferformat, it means 'reuse' the display format for the backbuffer */
2767     if(!Windowed && BackBufferFormat == WINED3DFMT_UNKNOWN) {
2768         TRACE_(d3d_caps)("BackBufferFormat WINED3FMT_UNKNOWN not available in Windowed mode\n");
2769         return WINED3DERR_NOTAVAILABLE;
2770     }
2771
2772     /* In FULLSCREEN mode R5G6B5 can only be mixed with backbuffer format R5G6B5 */
2773     if (DisplayFormat == WINED3DFMT_B5G6R5_UNORM && BackBufferFormat != WINED3DFMT_B5G6R5_UNORM)
2774     {
2775         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2776         return WINED3DERR_NOTAVAILABLE;
2777     }
2778
2779     /* In FULLSCREEN mode X1R5G5B5 can only be mixed with backbuffer format *1R5G5B5 */
2780     if (DisplayFormat == WINED3DFMT_B5G5R5X1_UNORM
2781             && !(BackBufferFormat == WINED3DFMT_B5G5R5X1_UNORM || BackBufferFormat == WINED3DFMT_B5G5R5A1_UNORM))
2782     {
2783         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2784         return WINED3DERR_NOTAVAILABLE;
2785     }
2786
2787     /* In FULLSCREEN mode X8R8G8B8 can only be mixed with backbuffer format *8R8G8B8 */
2788     if (DisplayFormat == WINED3DFMT_B8G8R8X8_UNORM
2789             && !(BackBufferFormat == WINED3DFMT_B8G8R8X8_UNORM || BackBufferFormat == WINED3DFMT_B8G8R8A8_UNORM))
2790     {
2791         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2792         return WINED3DERR_NOTAVAILABLE;
2793     }
2794
2795     /* A2R10G10B10 is only allowed in fullscreen mode and it can only be mixed with backbuffer format A2R10G10B10 */
2796     if (DisplayFormat == WINED3DFMT_B10G10R10A2_UNORM
2797             && (BackBufferFormat != WINED3DFMT_B10G10R10A2_UNORM || Windowed))
2798     {
2799         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2800         return WINED3DERR_NOTAVAILABLE;
2801     }
2802
2803     /* Use CheckDeviceFormat to see if the BackBufferFormat is usable with the given DisplayFormat */
2804     hr = IWineD3DImpl_CheckDeviceFormat(iface, Adapter, DeviceType, DisplayFormat, WINED3DUSAGE_RENDERTARGET, WINED3DRTYPE_SURFACE, BackBufferFormat, SURFACE_OPENGL);
2805     if(FAILED(hr))
2806         TRACE_(d3d_caps)("Unsupported display/backbuffer format combination %s/%s\n", debug_d3dformat(DisplayFormat), debug_d3dformat(BackBufferFormat));
2807
2808     return hr;
2809 }
2810
2811
2812 /* Check if we support bumpmapping for a format */
2813 static BOOL CheckBumpMapCapability(struct wined3d_adapter *adapter,
2814         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
2815 {
2816     switch(format_desc->format)
2817     {
2818         case WINED3DFMT_R8G8_SNORM:
2819         case WINED3DFMT_R16G16_SNORM:
2820         case WINED3DFMT_R5G5_SNORM_L6_UNORM:
2821         case WINED3DFMT_R8G8_SNORM_L8X8_UNORM:
2822         case WINED3DFMT_R8G8B8A8_SNORM:
2823             /* Ask the fixed function pipeline implementation if it can deal
2824              * with the conversion. If we've got a GL extension giving native
2825              * support this will be an identity conversion. */
2826             if (adapter->fragment_pipe->color_fixup_supported(format_desc->color_fixup))
2827             {
2828                 TRACE_(d3d_caps)("[OK]\n");
2829                 return TRUE;
2830             }
2831             TRACE_(d3d_caps)("[FAILED]\n");
2832             return FALSE;
2833
2834         default:
2835             TRACE_(d3d_caps)("[FAILED]\n");
2836             return FALSE;
2837     }
2838 }
2839
2840 /* Check if the given DisplayFormat + DepthStencilFormat combination is valid for the Adapter */
2841 static BOOL CheckDepthStencilCapability(struct wined3d_adapter *adapter,
2842         const struct GlPixelFormatDesc *display_format_desc, const struct GlPixelFormatDesc *ds_format_desc)
2843 {
2844     int it=0;
2845
2846     /* Only allow depth/stencil formats */
2847     if (!(ds_format_desc->depth_size || ds_format_desc->stencil_size)) return FALSE;
2848
2849     /* Walk through all WGL pixel formats to find a match */
2850     for (it = 0; it < adapter->nCfgs; ++it)
2851     {
2852         WineD3D_PixelFormat *cfg = &adapter->cfgs[it];
2853         if (IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info, cfg, display_format_desc))
2854         {
2855             if (IWineD3DImpl_IsPixelFormatCompatibleWithDepthFmt(&adapter->gl_info, cfg, ds_format_desc))
2856             {
2857                 return TRUE;
2858             }
2859         }
2860     }
2861
2862     return FALSE;
2863 }
2864
2865 static BOOL CheckFilterCapability(struct wined3d_adapter *adapter, const struct GlPixelFormatDesc *format_desc)
2866 {
2867     /* The flags entry of a format contains the filtering capability */
2868     if (format_desc->Flags & WINED3DFMT_FLAG_FILTERING) return TRUE;
2869
2870     return FALSE;
2871 }
2872
2873 /* Check the render target capabilities of a format */
2874 static BOOL CheckRenderTargetCapability(struct wined3d_adapter *adapter,
2875         const struct GlPixelFormatDesc *adapter_format_desc, const struct GlPixelFormatDesc *check_format_desc)
2876 {
2877     /* Filter out non-RT formats */
2878     if (!(check_format_desc->Flags & WINED3DFMT_FLAG_RENDERTARGET)) return FALSE;
2879
2880     if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
2881         WineD3D_PixelFormat *cfgs = adapter->cfgs;
2882         int it;
2883         short AdapterRed, AdapterGreen, AdapterBlue, AdapterAlpha, AdapterTotalSize;
2884         short CheckRed, CheckGreen, CheckBlue, CheckAlpha, CheckTotalSize;
2885
2886         getColorBits(adapter_format_desc, &AdapterRed, &AdapterGreen, &AdapterBlue, &AdapterAlpha, &AdapterTotalSize);
2887         getColorBits(check_format_desc, &CheckRed, &CheckGreen, &CheckBlue, &CheckAlpha, &CheckTotalSize);
2888
2889         /* In backbuffer mode the front and backbuffer share the same WGL pixelformat.
2890          * The format must match in RGB, alpha is allowed to be different. (Only the backbuffer can have alpha) */
2891         if(!((AdapterRed == CheckRed) && (AdapterGreen == CheckGreen) && (AdapterBlue == CheckBlue))) {
2892             TRACE_(d3d_caps)("[FAILED]\n");
2893             return FALSE;
2894         }
2895
2896         /* Check if there is a WGL pixel format matching the requirements, the format should also be window
2897          * drawable (not offscreen; e.g. Nvidia offers R5G6B5 for pbuffers even when X is running at 24bit) */
2898         for (it = 0; it < adapter->nCfgs; ++it)
2899         {
2900             if (cfgs[it].windowDrawable && IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info,
2901                     &cfgs[it], check_format_desc))
2902             {
2903                 TRACE_(d3d_caps)("iPixelFormat=%d is compatible with CheckFormat=%s\n",
2904                         cfgs[it].iPixelFormat, debug_d3dformat(check_format_desc->format));
2905                 return TRUE;
2906             }
2907         }
2908     } else if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
2909         /* We can probably use this function in FBO mode too on some drivers to get some basic indication of the capabilities. */
2910         WineD3D_PixelFormat *cfgs = adapter->cfgs;
2911         int it;
2912
2913         /* Check if there is a WGL pixel format matching the requirements, the pixel format should also be usable with pbuffers */
2914         for (it = 0; it < adapter->nCfgs; ++it)
2915         {
2916             if (cfgs[it].pbufferDrawable && IWineD3DImpl_IsPixelFormatCompatibleWithRenderFmt(&adapter->gl_info,
2917                     &cfgs[it], check_format_desc))
2918             {
2919                 TRACE_(d3d_caps)("iPixelFormat=%d is compatible with CheckFormat=%s\n",
2920                         cfgs[it].iPixelFormat, debug_d3dformat(check_format_desc->format));
2921                 return TRUE;
2922             }
2923         }
2924     } else if(wined3d_settings.offscreen_rendering_mode == ORM_FBO){
2925         /* For now return TRUE for FBOs until we have some proper checks.
2926          * Note that this function will only be called when the format is around for texturing. */
2927         return TRUE;
2928     }
2929     return FALSE;
2930 }
2931
2932 static BOOL CheckSrgbReadCapability(struct wined3d_adapter *adapter, const struct GlPixelFormatDesc *format_desc)
2933 {
2934     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
2935
2936     /* Check for supported sRGB formats (Texture loading and framebuffer) */
2937     if (!gl_info->supported[EXT_TEXTURE_SRGB])
2938     {
2939         TRACE_(d3d_caps)("[FAILED] GL_EXT_texture_sRGB not supported\n");
2940         return FALSE;
2941     }
2942
2943     switch (format_desc->format)
2944     {
2945         case WINED3DFMT_B8G8R8A8_UNORM:
2946         case WINED3DFMT_B8G8R8X8_UNORM:
2947         case WINED3DFMT_B4G4R4A4_UNORM:
2948         case WINED3DFMT_L8_UNORM:
2949         case WINED3DFMT_L8A8_UNORM:
2950         case WINED3DFMT_DXT1:
2951         case WINED3DFMT_DXT2:
2952         case WINED3DFMT_DXT3:
2953         case WINED3DFMT_DXT4:
2954         case WINED3DFMT_DXT5:
2955             TRACE_(d3d_caps)("[OK]\n");
2956             return TRUE;
2957
2958         default:
2959             TRACE_(d3d_caps)("[FAILED] Gamma texture format %s not supported.\n", debug_d3dformat(format_desc->format));
2960             return FALSE;
2961     }
2962     return FALSE;
2963 }
2964
2965 static BOOL CheckSrgbWriteCapability(struct wined3d_adapter *adapter,
2966         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
2967 {
2968     /* Only offer SRGB writing on X8R8G8B8/A8R8G8B8 when we use ARB or GLSL shaders as we are
2969      * doing the color fixup in shaders.
2970      * Note Windows drivers (at least on the Geforce 8800) also offer this on R5G6B5. */
2971     if ((format_desc->format == WINED3DFMT_B8G8R8X8_UNORM) || (format_desc->format == WINED3DFMT_B8G8R8A8_UNORM))
2972     {
2973         int vs_selected_mode;
2974         int ps_selected_mode;
2975         select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
2976
2977         if((ps_selected_mode == SHADER_ARB) || (ps_selected_mode == SHADER_GLSL)) {
2978             TRACE_(d3d_caps)("[OK]\n");
2979             return TRUE;
2980         }
2981     }
2982
2983     TRACE_(d3d_caps)("[FAILED] - no SRGB writing support on format=%s\n", debug_d3dformat(format_desc->format));
2984     return FALSE;
2985 }
2986
2987 /* Check if a format support blending in combination with pixel shaders */
2988 static BOOL CheckPostPixelShaderBlendingCapability(struct wined3d_adapter *adapter,
2989         const struct GlPixelFormatDesc *format_desc)
2990 {
2991     /* The flags entry of a format contains the post pixel shader blending capability */
2992     if (format_desc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING) return TRUE;
2993
2994     return FALSE;
2995 }
2996
2997 static BOOL CheckWrapAndMipCapability(struct wined3d_adapter *adapter, const struct GlPixelFormatDesc *format_desc)
2998 {
2999     /* OpenGL supports mipmapping on all formats basically. Wrapping is unsupported,
3000      * but we have to report mipmapping so we cannot reject this flag. Tests show that
3001      * windows reports WRAPANDMIP on unfilterable surfaces as well, apparently to show
3002      * that wrapping is supported. The lack of filtering will sort out the mipmapping
3003      * capability anyway.
3004      *
3005      * For now lets report this on all formats, but in the future we may want to
3006      * restrict it to some should games need that
3007      */
3008     return TRUE;
3009 }
3010
3011 /* Check if a texture format is supported on the given adapter */
3012 static BOOL CheckTextureCapability(struct wined3d_adapter *adapter,
3013         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *format_desc)
3014 {
3015     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3016
3017     switch (format_desc->format)
3018     {
3019         /*****
3020          *  supported: RGB(A) formats
3021          */
3022         case WINED3DFMT_B8G8R8_UNORM: /* Enable for dx7, blacklisted for 8 and 9 above */
3023         case WINED3DFMT_B8G8R8A8_UNORM:
3024         case WINED3DFMT_B8G8R8X8_UNORM:
3025         case WINED3DFMT_B5G6R5_UNORM:
3026         case WINED3DFMT_B5G5R5X1_UNORM:
3027         case WINED3DFMT_B5G5R5A1_UNORM:
3028         case WINED3DFMT_B4G4R4A4_UNORM:
3029         case WINED3DFMT_A8_UNORM:
3030         case WINED3DFMT_B4G4R4X4_UNORM:
3031         case WINED3DFMT_R8G8B8A8_UNORM:
3032         case WINED3DFMT_R8G8B8X8_UNORM:
3033         case WINED3DFMT_B10G10R10A2_UNORM:
3034         case WINED3DFMT_R10G10B10A2_UNORM:
3035         case WINED3DFMT_R16G16_UNORM:
3036             TRACE_(d3d_caps)("[OK]\n");
3037             return TRUE;
3038
3039         case WINED3DFMT_B2G3R3_UNORM:
3040             TRACE_(d3d_caps)("[FAILED] - Not supported on Windows\n");
3041             return FALSE;
3042
3043         /*****
3044          *  supported: Palettized
3045          */
3046         case WINED3DFMT_P8_UINT:
3047             TRACE_(d3d_caps)("[OK]\n");
3048             return TRUE;
3049         /* No Windows driver offers WINED3DFMT_P8_UINT_A8_UNORM, so don't offer it either */
3050         case WINED3DFMT_P8_UINT_A8_UNORM:
3051             return FALSE;
3052
3053         /*****
3054          *  Supported: (Alpha)-Luminance
3055          */
3056         case WINED3DFMT_L8_UNORM:
3057         case WINED3DFMT_L8A8_UNORM:
3058         case WINED3DFMT_L16_UNORM:
3059             TRACE_(d3d_caps)("[OK]\n");
3060             return TRUE;
3061
3062         /* Not supported on Windows, thus disabled */
3063         case WINED3DFMT_L4A4_UNORM:
3064             TRACE_(d3d_caps)("[FAILED] - not supported on windows\n");
3065             return FALSE;
3066
3067         /*****
3068          *  Supported: Depth/Stencil formats
3069          */
3070         case WINED3DFMT_D16_LOCKABLE:
3071         case WINED3DFMT_D16_UNORM:
3072         case WINED3DFMT_S1_UINT_D15_UNORM:
3073         case WINED3DFMT_X8D24_UNORM:
3074         case WINED3DFMT_S4X4_UINT_D24_UNORM:
3075         case WINED3DFMT_D24_UNORM_S8_UINT:
3076         case WINED3DFMT_S8_UINT_D24_FLOAT:
3077         case WINED3DFMT_D32_UNORM:
3078         case WINED3DFMT_D32_FLOAT:
3079             return TRUE;
3080
3081         /*****
3082          *  Not supported everywhere(depends on GL_ATI_envmap_bumpmap or
3083          *  GL_NV_texture_shader). Emulated by shaders
3084          */
3085         case WINED3DFMT_R8G8_SNORM:
3086         case WINED3DFMT_R8G8_SNORM_L8X8_UNORM:
3087         case WINED3DFMT_R5G5_SNORM_L6_UNORM:
3088         case WINED3DFMT_R8G8B8A8_SNORM:
3089         case WINED3DFMT_R16G16_SNORM:
3090             /* Ask the shader backend if it can deal with the conversion. If
3091              * we've got a GL extension giving native support this will be an
3092              * identity conversion. */
3093             if (adapter->shader_backend->shader_color_fixup_supported(format_desc->color_fixup))
3094             {
3095                 TRACE_(d3d_caps)("[OK]\n");
3096                 return TRUE;
3097             }
3098             TRACE_(d3d_caps)("[FAILED]\n");
3099             return FALSE;
3100
3101         case WINED3DFMT_DXT1:
3102         case WINED3DFMT_DXT2:
3103         case WINED3DFMT_DXT3:
3104         case WINED3DFMT_DXT4:
3105         case WINED3DFMT_DXT5:
3106             if (gl_info->supported[EXT_TEXTURE_COMPRESSION_S3TC])
3107             {
3108                 TRACE_(d3d_caps)("[OK]\n");
3109                 return TRUE;
3110             }
3111             TRACE_(d3d_caps)("[FAILED]\n");
3112             return FALSE;
3113
3114
3115         /*****
3116          *  Odd formats - not supported
3117          */
3118         case WINED3DFMT_VERTEXDATA:
3119         case WINED3DFMT_R16_UINT:
3120         case WINED3DFMT_R32_UINT:
3121         case WINED3DFMT_R16G16B16A16_SNORM:
3122         case WINED3DFMT_R10G10B10_SNORM_A2_UNORM:
3123         case WINED3DFMT_R10G11B11_SNORM:
3124             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3125             return FALSE;
3126
3127         /*****
3128          *  WINED3DFMT_R8G8_SNORM_Cx: Not supported right now
3129          */
3130         case WINED3DFMT_R8G8_SNORM_Cx:
3131             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3132             return FALSE;
3133
3134         /* YUV formats */
3135         case WINED3DFMT_UYVY:
3136         case WINED3DFMT_YUY2:
3137             if (gl_info->supported[APPLE_YCBCR_422])
3138             {
3139                 TRACE_(d3d_caps)("[OK]\n");
3140                 return TRUE;
3141             }
3142             TRACE_(d3d_caps)("[FAILED]\n");
3143             return FALSE;
3144         case WINED3DFMT_YV12:
3145             TRACE_(d3d_caps)("[FAILED]\n");
3146             return FALSE;
3147
3148             /* Not supported */
3149         case WINED3DFMT_R16G16B16A16_UNORM:
3150         case WINED3DFMT_B2G3R3A8_UNORM:
3151             TRACE_(d3d_caps)("[FAILED]\n"); /* Enable when implemented */
3152             return FALSE;
3153
3154             /* Floating point formats */
3155         case WINED3DFMT_R16_FLOAT:
3156         case WINED3DFMT_R16G16_FLOAT:
3157         case WINED3DFMT_R16G16B16A16_FLOAT:
3158             if (gl_info->supported[ARB_TEXTURE_FLOAT] && gl_info->supported[ARB_HALF_FLOAT_PIXEL])
3159             {
3160                 TRACE_(d3d_caps)("[OK]\n");
3161                 return TRUE;
3162             }
3163             TRACE_(d3d_caps)("[FAILED]\n");
3164             return FALSE;
3165
3166         case WINED3DFMT_R32_FLOAT:
3167         case WINED3DFMT_R32G32_FLOAT:
3168         case WINED3DFMT_R32G32B32A32_FLOAT:
3169             if (gl_info->supported[ARB_TEXTURE_FLOAT])
3170             {
3171                 TRACE_(d3d_caps)("[OK]\n");
3172                 return TRUE;
3173             }
3174             TRACE_(d3d_caps)("[FAILED]\n");
3175             return FALSE;
3176
3177         /* ATI instancing hack: Although ATI cards do not support Shader Model 3.0, they support
3178          * instancing. To query if the card supports instancing CheckDeviceFormat with the special format
3179          * MAKEFOURCC('I','N','S','T') is used. Should a (broken) app check for this provide a proper return value.
3180          * We can do instancing with all shader versions, but we need vertex shaders.
3181          *
3182          * Additionally applications have to set the D3DRS_POINTSIZE render state to MAKEFOURCC('I','N','S','T') once
3183          * to enable instancing. WineD3D doesn't need that and just ignores it.
3184          *
3185          * With Shader Model 3.0 capable cards Instancing 'just works' in Windows.
3186          */
3187         case WINED3DFMT_INST:
3188             TRACE("ATI Instancing check hack\n");
3189             if (gl_info->supported[ARB_VERTEX_PROGRAM] || gl_info->supported[ARB_VERTEX_SHADER])
3190             {
3191                 TRACE_(d3d_caps)("[OK]\n");
3192                 return TRUE;
3193             }
3194             TRACE_(d3d_caps)("[FAILED]\n");
3195             return FALSE;
3196
3197         /* Some weird FOURCC formats */
3198         case WINED3DFMT_R8G8_B8G8:
3199         case WINED3DFMT_G8R8_G8B8:
3200         case WINED3DFMT_MULTI2_ARGB8:
3201             TRACE_(d3d_caps)("[FAILED]\n");
3202             return FALSE;
3203
3204         /* Vendor specific formats */
3205         case WINED3DFMT_ATI2N:
3206             if (gl_info->supported[ATI_TEXTURE_COMPRESSION_3DC]
3207                     || gl_info->supported[EXT_TEXTURE_COMPRESSION_RGTC])
3208             {
3209                 if (adapter->shader_backend->shader_color_fixup_supported(format_desc->color_fixup)
3210                         && adapter->fragment_pipe->color_fixup_supported(format_desc->color_fixup))
3211                 {
3212                     TRACE_(d3d_caps)("[OK]\n");
3213                     return TRUE;
3214                 }
3215
3216                 TRACE_(d3d_caps)("[OK]\n");
3217                 return TRUE;
3218             }
3219             TRACE_(d3d_caps)("[FAILED]\n");
3220             return FALSE;
3221
3222         case WINED3DFMT_NVHU:
3223         case WINED3DFMT_NVHS:
3224             /* These formats seem to be similar to the HILO formats in GL_NV_texture_shader. NVHU
3225              * is said to be GL_UNSIGNED_HILO16, NVHS GL_SIGNED_HILO16. Rumours say that d3d computes
3226              * a 3rd channel similarly to D3DFMT_CxV8U8(So NVHS could be called D3DFMT_CxV16U16).
3227              * ATI refused to support formats which can easilly be emulated with pixel shaders, so
3228              * Applications have to deal with not having NVHS and NVHU.
3229              */
3230             TRACE_(d3d_caps)("[FAILED]\n");
3231             return FALSE;
3232
3233         case WINED3DFMT_UNKNOWN:
3234             return FALSE;
3235
3236         default:
3237             ERR("Unhandled format=%s\n", debug_d3dformat(format_desc->format));
3238             break;
3239     }
3240     return FALSE;
3241 }
3242
3243 static BOOL CheckSurfaceCapability(struct wined3d_adapter *adapter, const struct GlPixelFormatDesc *adapter_format_desc,
3244         WINED3DDEVTYPE DeviceType, const struct GlPixelFormatDesc *check_format_desc, WINED3DSURFTYPE SurfaceType)
3245 {
3246     if(SurfaceType == SURFACE_GDI) {
3247         switch(check_format_desc->format)
3248         {
3249             case WINED3DFMT_B8G8R8_UNORM:
3250             case WINED3DFMT_B8G8R8A8_UNORM:
3251             case WINED3DFMT_B8G8R8X8_UNORM:
3252             case WINED3DFMT_B5G6R5_UNORM:
3253             case WINED3DFMT_B5G5R5X1_UNORM:
3254             case WINED3DFMT_B5G5R5A1_UNORM:
3255             case WINED3DFMT_B4G4R4A4_UNORM:
3256             case WINED3DFMT_B2G3R3_UNORM:
3257             case WINED3DFMT_A8_UNORM:
3258             case WINED3DFMT_B2G3R3A8_UNORM:
3259             case WINED3DFMT_B4G4R4X4_UNORM:
3260             case WINED3DFMT_R10G10B10A2_UNORM:
3261             case WINED3DFMT_R8G8B8A8_UNORM:
3262             case WINED3DFMT_R8G8B8X8_UNORM:
3263             case WINED3DFMT_R16G16_UNORM:
3264             case WINED3DFMT_B10G10R10A2_UNORM:
3265             case WINED3DFMT_R16G16B16A16_UNORM:
3266             case WINED3DFMT_P8_UINT:
3267                 TRACE_(d3d_caps)("[OK]\n");
3268                 return TRUE;
3269             default:
3270                 TRACE_(d3d_caps)("[FAILED] - not available on GDI surfaces\n");
3271                 return FALSE;
3272         }
3273     }
3274
3275     /* All format that are supported for textures are supported for surfaces as well */
3276     if (CheckTextureCapability(adapter, DeviceType, check_format_desc)) return TRUE;
3277     /* All depth stencil formats are supported on surfaces */
3278     if (CheckDepthStencilCapability(adapter, adapter_format_desc, check_format_desc)) return TRUE;
3279
3280     /* If opengl can't process the format natively, the blitter may be able to convert it */
3281     if (adapter->blitter->color_fixup_supported(check_format_desc->color_fixup))
3282     {
3283         TRACE_(d3d_caps)("[OK]\n");
3284         return TRUE;
3285     }
3286
3287     /* Reject other formats */
3288     TRACE_(d3d_caps)("[FAILED]\n");
3289     return FALSE;
3290 }
3291
3292 static BOOL CheckVertexTextureCapability(struct wined3d_adapter *adapter, const struct GlPixelFormatDesc *format_desc)
3293 {
3294     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3295
3296     if (!gl_info->limits.vertex_samplers)
3297     {
3298         TRACE_(d3d_caps)("[FAILED]\n");
3299         return FALSE;
3300     }
3301
3302     switch (format_desc->format)
3303     {
3304         case WINED3DFMT_R32G32B32A32_FLOAT:
3305             if (!gl_info->supported[ARB_TEXTURE_FLOAT])
3306             {
3307                 TRACE_(d3d_caps)("[FAILED]\n");
3308                 return FALSE;
3309             }
3310             TRACE_(d3d_caps)("[OK]\n");
3311             return TRUE;
3312
3313         default:
3314             TRACE_(d3d_caps)("[FAILED]\n");
3315             return FALSE;
3316     }
3317     return FALSE;
3318 }
3319
3320 static HRESULT WINAPI IWineD3DImpl_CheckDeviceFormat(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType,
3321         WINED3DFORMAT AdapterFormat, DWORD Usage, WINED3DRESOURCETYPE RType, WINED3DFORMAT CheckFormat,
3322         WINED3DSURFTYPE SurfaceType)
3323 {
3324     IWineD3DImpl *This = (IWineD3DImpl *)iface;
3325     struct wined3d_adapter *adapter = &This->adapters[Adapter];
3326     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3327     const struct GlPixelFormatDesc *format_desc = getFormatDescEntry(CheckFormat, gl_info);
3328     const struct GlPixelFormatDesc *adapter_format_desc = getFormatDescEntry(AdapterFormat, gl_info);
3329     DWORD UsageCaps = 0;
3330
3331     TRACE_(d3d_caps)("(%p)-> (STUB) (Adptr:%d, DevType:(%u,%s), AdptFmt:(%u,%s), Use:(%u,%s,%s), ResTyp:(%x,%s), CheckFmt:(%u,%s))\n",
3332           This,
3333           Adapter,
3334           DeviceType, debug_d3ddevicetype(DeviceType),
3335           AdapterFormat, debug_d3dformat(AdapterFormat),
3336           Usage, debug_d3dusage(Usage), debug_d3dusagequery(Usage),
3337           RType, debug_d3dresourcetype(RType),
3338           CheckFormat, debug_d3dformat(CheckFormat));
3339
3340     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
3341         return WINED3DERR_INVALIDCALL;
3342     }
3343
3344     if(RType == WINED3DRTYPE_CUBETEXTURE) {
3345
3346         if(SurfaceType != SURFACE_OPENGL) {
3347             TRACE("[FAILED]\n");
3348             return WINED3DERR_NOTAVAILABLE;
3349         }
3350
3351         /* Cubetexture allows:
3352          *                    - D3DUSAGE_AUTOGENMIPMAP
3353          *                    - D3DUSAGE_DEPTHSTENCIL
3354          *                    - D3DUSAGE_DYNAMIC
3355          *                    - D3DUSAGE_NONSECURE (d3d9ex)
3356          *                    - D3DUSAGE_RENDERTARGET
3357          *                    - D3DUSAGE_SOFTWAREPROCESSING
3358          *                    - D3DUSAGE_QUERY_WRAPANDMIP
3359          */
3360         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
3361         {
3362             /* Check if the texture format is around */
3363             if (CheckTextureCapability(adapter, DeviceType, format_desc))
3364             {
3365                 if(Usage & WINED3DUSAGE_AUTOGENMIPMAP) {
3366                     /* Check for automatic mipmap generation support */
3367                     if (gl_info->supported[SGIS_GENERATE_MIPMAP])
3368                     {
3369                         UsageCaps |= WINED3DUSAGE_AUTOGENMIPMAP;
3370                     } else {
3371                         /* When autogenmipmap isn't around continue and return WINED3DOK_NOAUTOGEN instead of D3D_OK */
3372                         TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
3373                     }
3374                 }
3375
3376                 /* Always report dynamic locking */
3377                 if(Usage & WINED3DUSAGE_DYNAMIC)
3378                     UsageCaps |= WINED3DUSAGE_DYNAMIC;
3379
3380                 if(Usage & WINED3DUSAGE_RENDERTARGET) {
3381                     if(CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
3382                     {
3383                         UsageCaps |= WINED3DUSAGE_RENDERTARGET;
3384                     } else {
3385                         TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3386                         return WINED3DERR_NOTAVAILABLE;
3387                     }
3388                 }
3389
3390                 /* Always report software processing */
3391                 if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
3392                     UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
3393
3394                 /* Check QUERY_FILTER support */
3395                 if(Usage & WINED3DUSAGE_QUERY_FILTER) {
3396                     if (CheckFilterCapability(adapter, format_desc))
3397                     {
3398                         UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
3399                     } else {
3400                         TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
3401                         return WINED3DERR_NOTAVAILABLE;
3402                     }
3403                 }
3404
3405                 /* Check QUERY_POSTPIXELSHADER_BLENDING support */
3406                 if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
3407                     if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
3408                     {
3409                         UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3410                     } else {
3411                         TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3412                         return WINED3DERR_NOTAVAILABLE;
3413                     }
3414                 }
3415
3416                 /* Check QUERY_SRGBREAD support */
3417                 if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
3418                     if (CheckSrgbReadCapability(adapter, format_desc))
3419                     {
3420                         UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
3421                     } else {
3422                         TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
3423                         return WINED3DERR_NOTAVAILABLE;
3424                     }
3425                 }
3426
3427                 /* Check QUERY_SRGBWRITE support */
3428                 if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
3429                     if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
3430                     {
3431                         UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
3432                     } else {
3433                         TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
3434                         return WINED3DERR_NOTAVAILABLE;
3435                     }
3436                 }
3437
3438                 /* Check QUERY_VERTEXTEXTURE support */
3439                 if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
3440                     if (CheckVertexTextureCapability(adapter, format_desc))
3441                     {
3442                         UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
3443                     } else {
3444                         TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
3445                         return WINED3DERR_NOTAVAILABLE;
3446                     }
3447                 }
3448
3449                 /* Check QUERY_WRAPANDMIP support */
3450                 if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
3451                     if (CheckWrapAndMipCapability(adapter, format_desc))
3452                     {
3453                         UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3454                     } else {
3455                         TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3456                         return WINED3DERR_NOTAVAILABLE;
3457                     }
3458                 }
3459             } else {
3460                 TRACE_(d3d_caps)("[FAILED] - Cube texture format not supported\n");
3461                 return WINED3DERR_NOTAVAILABLE;
3462             }
3463         } else {
3464             TRACE_(d3d_caps)("[FAILED] - No cube texture support\n");
3465             return WINED3DERR_NOTAVAILABLE;
3466         }
3467     } else if(RType == WINED3DRTYPE_SURFACE) {
3468         /* Surface allows:
3469          *                - D3DUSAGE_DEPTHSTENCIL
3470          *                - D3DUSAGE_NONSECURE (d3d9ex)
3471          *                - D3DUSAGE_RENDERTARGET
3472          */
3473
3474         if (CheckSurfaceCapability(adapter, adapter_format_desc, DeviceType, format_desc, SurfaceType))
3475         {
3476             if(Usage & WINED3DUSAGE_DEPTHSTENCIL) {
3477                 if (CheckDepthStencilCapability(adapter, adapter_format_desc, format_desc))
3478                 {
3479                     UsageCaps |= WINED3DUSAGE_DEPTHSTENCIL;
3480                 } else {
3481                     TRACE_(d3d_caps)("[FAILED] - No depthstencil support\n");
3482                     return WINED3DERR_NOTAVAILABLE;
3483                 }
3484             }
3485
3486             if(Usage & WINED3DUSAGE_RENDERTARGET) {
3487                 if (CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
3488                 {
3489                     UsageCaps |= WINED3DUSAGE_RENDERTARGET;
3490                 } else {
3491                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3492                     return WINED3DERR_NOTAVAILABLE;
3493                 }
3494             }
3495
3496             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
3497             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
3498                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
3499                 {
3500                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3501                 } else {
3502                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3503                     return WINED3DERR_NOTAVAILABLE;
3504                 }
3505             }
3506         } else {
3507             TRACE_(d3d_caps)("[FAILED] - Not supported for plain surfaces\n");
3508             return WINED3DERR_NOTAVAILABLE;
3509         }
3510
3511     } else if(RType == WINED3DRTYPE_TEXTURE) {
3512         /* Texture allows:
3513          *                - D3DUSAGE_AUTOGENMIPMAP
3514          *                - D3DUSAGE_DEPTHSTENCIL
3515          *                - D3DUSAGE_DMAP
3516          *                - D3DUSAGE_DYNAMIC
3517          *                - D3DUSAGE_NONSECURE (d3d9ex)
3518          *                - D3DUSAGE_RENDERTARGET
3519          *                - D3DUSAGE_SOFTWAREPROCESSING
3520          *                - D3DUSAGE_TEXTAPI (d3d9ex)
3521          *                - D3DUSAGE_QUERY_WRAPANDMIP
3522          */
3523
3524         if(SurfaceType != SURFACE_OPENGL) {
3525             TRACE("[FAILED]\n");
3526             return WINED3DERR_NOTAVAILABLE;
3527         }
3528
3529         /* Check if the texture format is around */
3530         if (CheckTextureCapability(adapter, DeviceType, format_desc))
3531         {
3532             if(Usage & WINED3DUSAGE_AUTOGENMIPMAP) {
3533                 /* Check for automatic mipmap generation support */
3534                 if (gl_info->supported[SGIS_GENERATE_MIPMAP])
3535                 {
3536                     UsageCaps |= WINED3DUSAGE_AUTOGENMIPMAP;
3537                 } else {
3538                     /* When autogenmipmap isn't around continue and return WINED3DOK_NOAUTOGEN instead of D3D_OK */
3539                     TRACE_(d3d_caps)("[FAILED] - No autogenmipmap support, but continuing\n");
3540                 }
3541             }
3542
3543             /* Always report dynamic locking */
3544             if(Usage & WINED3DUSAGE_DYNAMIC)
3545                 UsageCaps |= WINED3DUSAGE_DYNAMIC;
3546
3547             if(Usage & WINED3DUSAGE_RENDERTARGET) {
3548                 if (CheckRenderTargetCapability(adapter, adapter_format_desc, format_desc))
3549                 {
3550                     UsageCaps |= WINED3DUSAGE_RENDERTARGET;
3551                 } else {
3552                     TRACE_(d3d_caps)("[FAILED] - No rendertarget support\n");
3553                      return WINED3DERR_NOTAVAILABLE;
3554                  }
3555             }
3556
3557             /* Always report software processing */
3558             if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
3559                 UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
3560
3561             /* Check QUERY_FILTER support */
3562             if(Usage & WINED3DUSAGE_QUERY_FILTER) {
3563                 if (CheckFilterCapability(adapter, format_desc))
3564                 {
3565                     UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
3566                 } else {
3567                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
3568                     return WINED3DERR_NOTAVAILABLE;
3569                 }
3570             }
3571
3572             /* Check QUERY_LEGACYBUMPMAP support */
3573             if(Usage & WINED3DUSAGE_QUERY_LEGACYBUMPMAP) {
3574                 if (CheckBumpMapCapability(adapter, DeviceType, format_desc))
3575                 {
3576                     UsageCaps |= WINED3DUSAGE_QUERY_LEGACYBUMPMAP;
3577                 } else {
3578                     TRACE_(d3d_caps)("[FAILED] - No legacy bumpmap support\n");
3579                     return WINED3DERR_NOTAVAILABLE;
3580                 }
3581             }
3582
3583             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
3584             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
3585                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
3586                 {
3587                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3588                 } else {
3589                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3590                     return WINED3DERR_NOTAVAILABLE;
3591                 }
3592             }
3593
3594             /* Check QUERY_SRGBREAD support */
3595             if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
3596                 if (CheckSrgbReadCapability(adapter, format_desc))
3597                 {
3598                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
3599                 } else {
3600                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
3601                     return WINED3DERR_NOTAVAILABLE;
3602                 }
3603             }
3604
3605             /* Check QUERY_SRGBWRITE support */
3606             if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
3607                 if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
3608                 {
3609                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
3610                 } else {
3611                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
3612                     return WINED3DERR_NOTAVAILABLE;
3613                 }
3614             }
3615
3616             /* Check QUERY_VERTEXTEXTURE support */
3617             if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
3618                 if (CheckVertexTextureCapability(adapter, format_desc))
3619                 {
3620                     UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
3621                 } else {
3622                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
3623                     return WINED3DERR_NOTAVAILABLE;
3624                 }
3625             }
3626
3627             /* Check QUERY_WRAPANDMIP support */
3628             if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
3629                 if (CheckWrapAndMipCapability(adapter, format_desc))
3630                 {
3631                     UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3632                 } else {
3633                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3634                     return WINED3DERR_NOTAVAILABLE;
3635                 }
3636             }
3637
3638             if(Usage & WINED3DUSAGE_DEPTHSTENCIL) {
3639                 if (CheckDepthStencilCapability(adapter, adapter_format_desc, format_desc))
3640                 {
3641                     UsageCaps |= WINED3DUSAGE_DEPTHSTENCIL;
3642                 } else {
3643                     TRACE_(d3d_caps)("[FAILED] - No depth stencil support\n");
3644                     return WINED3DERR_NOTAVAILABLE;
3645                 }
3646             }
3647         } else {
3648             TRACE_(d3d_caps)("[FAILED] - Texture format not supported\n");
3649             return WINED3DERR_NOTAVAILABLE;
3650         }
3651     } else if((RType == WINED3DRTYPE_VOLUME) || (RType == WINED3DRTYPE_VOLUMETEXTURE)) {
3652         /* Volume is to VolumeTexture what Surface is to Texture but its usage caps are not documented.
3653          * Most driver seem to offer (nearly) the same on Volume and VolumeTexture, so do that too.
3654          *
3655          * Volumetexture allows:
3656          *                      - D3DUSAGE_DYNAMIC
3657          *                      - D3DUSAGE_NONSECURE (d3d9ex)
3658          *                      - D3DUSAGE_SOFTWAREPROCESSING
3659          *                      - D3DUSAGE_QUERY_WRAPANDMIP
3660          */
3661
3662         if(SurfaceType != SURFACE_OPENGL) {
3663             TRACE("[FAILED]\n");
3664             return WINED3DERR_NOTAVAILABLE;
3665         }
3666
3667         /* Check volume texture and volume usage caps */
3668         if (gl_info->supported[EXT_TEXTURE3D])
3669         {
3670             if (!CheckTextureCapability(adapter, DeviceType, format_desc))
3671             {
3672                 TRACE_(d3d_caps)("[FAILED] - Format not supported\n");
3673                 return WINED3DERR_NOTAVAILABLE;
3674             }
3675
3676             /* Always report dynamic locking */
3677             if(Usage & WINED3DUSAGE_DYNAMIC)
3678                 UsageCaps |= WINED3DUSAGE_DYNAMIC;
3679
3680             /* Always report software processing */
3681             if(Usage & WINED3DUSAGE_SOFTWAREPROCESSING)
3682                 UsageCaps |= WINED3DUSAGE_SOFTWAREPROCESSING;
3683
3684             /* Check QUERY_FILTER support */
3685             if(Usage & WINED3DUSAGE_QUERY_FILTER) {
3686                 if (CheckFilterCapability(adapter, format_desc))
3687                 {
3688                     UsageCaps |= WINED3DUSAGE_QUERY_FILTER;
3689                 } else {
3690                     TRACE_(d3d_caps)("[FAILED] - No query filter support\n");
3691                     return WINED3DERR_NOTAVAILABLE;
3692                 }
3693             }
3694
3695             /* Check QUERY_POSTPIXELSHADER_BLENDING support */
3696             if(Usage & WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING) {
3697                 if (CheckPostPixelShaderBlendingCapability(adapter, format_desc))
3698                 {
3699                     UsageCaps |= WINED3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING;
3700                 } else {
3701                     TRACE_(d3d_caps)("[FAILED] - No query post pixelshader blending support\n");
3702                     return WINED3DERR_NOTAVAILABLE;
3703                 }
3704             }
3705
3706             /* Check QUERY_SRGBREAD support */
3707             if(Usage & WINED3DUSAGE_QUERY_SRGBREAD) {
3708                 if (CheckSrgbReadCapability(adapter, format_desc))
3709                 {
3710                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBREAD;
3711                 } else {
3712                     TRACE_(d3d_caps)("[FAILED] - No query srgbread support\n");
3713                     return WINED3DERR_NOTAVAILABLE;
3714                 }
3715             }
3716
3717             /* Check QUERY_SRGBWRITE support */
3718             if(Usage & WINED3DUSAGE_QUERY_SRGBWRITE) {
3719                 if (CheckSrgbWriteCapability(adapter, DeviceType, format_desc))
3720                 {
3721                     UsageCaps |= WINED3DUSAGE_QUERY_SRGBWRITE;
3722                 } else {
3723                     TRACE_(d3d_caps)("[FAILED] - No query srgbwrite support\n");
3724                     return WINED3DERR_NOTAVAILABLE;
3725                 }
3726             }
3727
3728             /* Check QUERY_VERTEXTEXTURE support */
3729             if(Usage & WINED3DUSAGE_QUERY_VERTEXTEXTURE) {
3730                 if (CheckVertexTextureCapability(adapter, format_desc))
3731                 {
3732                     UsageCaps |= WINED3DUSAGE_QUERY_VERTEXTEXTURE;
3733                 } else {
3734                     TRACE_(d3d_caps)("[FAILED] - No query vertextexture support\n");
3735                     return WINED3DERR_NOTAVAILABLE;
3736                 }
3737             }
3738
3739             /* Check QUERY_WRAPANDMIP support */
3740             if(Usage & WINED3DUSAGE_QUERY_WRAPANDMIP) {
3741                 if (CheckWrapAndMipCapability(adapter, format_desc))
3742                 {
3743                     UsageCaps |= WINED3DUSAGE_QUERY_WRAPANDMIP;
3744                 } else {
3745                     TRACE_(d3d_caps)("[FAILED] - No wrapping and mipmapping support\n");
3746                     return WINED3DERR_NOTAVAILABLE;
3747                 }
3748             }
3749         } else {
3750             TRACE_(d3d_caps)("[FAILED] - No volume texture support\n");
3751             return WINED3DERR_NOTAVAILABLE;
3752         }
3753
3754         /* Filter formats that need conversion; For one part, this conversion is unimplemented,
3755          * and volume textures are huge, so it would be a big performance hit. Unless we hit an
3756          * app needing one of those formats, don't advertize them to avoid leading apps into
3757          * temptation. The windows drivers don't support most of those formats on volumes anyway,
3758          * except of R32F.
3759          */
3760         switch(CheckFormat) {
3761             case WINED3DFMT_P8_UINT:
3762             case WINED3DFMT_L4A4_UNORM:
3763             case WINED3DFMT_R32_FLOAT:
3764             case WINED3DFMT_R16_FLOAT:
3765             case WINED3DFMT_R8G8_SNORM_L8X8_UNORM:
3766             case WINED3DFMT_R5G5_SNORM_L6_UNORM:
3767             case WINED3DFMT_R16G16_UNORM:
3768                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3769                 return WINED3DERR_NOTAVAILABLE;
3770
3771             case WINED3DFMT_R8G8B8A8_SNORM:
3772             case WINED3DFMT_R16G16_SNORM:
3773             if (!gl_info->supported[NV_TEXTURE_SHADER])
3774             {
3775                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3776                 return WINED3DERR_NOTAVAILABLE;
3777             }
3778             break;
3779
3780             case WINED3DFMT_R8G8_SNORM:
3781             if (!gl_info->supported[NV_TEXTURE_SHADER])
3782             {
3783                 TRACE_(d3d_caps)("[FAILED] - No converted formats on volumes\n");
3784                 return WINED3DERR_NOTAVAILABLE;
3785             }
3786             break;
3787
3788             case WINED3DFMT_DXT1:
3789             case WINED3DFMT_DXT2:
3790             case WINED3DFMT_DXT3:
3791             case WINED3DFMT_DXT4:
3792             case WINED3DFMT_DXT5:
3793                 /* The GL_EXT_texture_compression_s3tc spec requires that loading an s3tc
3794                  * compressed texture results in an error. While the D3D refrast does
3795                  * support s3tc volumes, at least the nvidia windows driver does not, so
3796                  * we're free not to support this format.
3797                  */
3798                 TRACE_(d3d_caps)("[FAILED] - DXTn does not support 3D textures\n");
3799                 return WINED3DERR_NOTAVAILABLE;
3800
3801             default:
3802                 /* Do nothing, continue with checking the format below */
3803                 break;
3804         }
3805     } else if(RType == WINED3DRTYPE_BUFFER){
3806         /* For instance vertexbuffer/indexbuffer aren't supported yet because no Windows drivers seem to offer it */
3807         TRACE_(d3d_caps)("Unhandled resource type D3DRTYPE_INDEXBUFFER / D3DRTYPE_VERTEXBUFFER\n");
3808         return WINED3DERR_NOTAVAILABLE;
3809     }
3810
3811     /* When the UsageCaps exactly matches Usage return WINED3D_OK except for the situation in which
3812      * WINED3DUSAGE_AUTOGENMIPMAP isn't around, then WINED3DOK_NOAUTOGEN is returned if all the other
3813      * usage flags match. */
3814     if(UsageCaps == Usage) {
3815         return WINED3D_OK;
3816     } else if((UsageCaps == (Usage & ~WINED3DUSAGE_AUTOGENMIPMAP)) && (Usage & WINED3DUSAGE_AUTOGENMIPMAP)){
3817         return WINED3DOK_NOAUTOGEN;
3818     } else {
3819         TRACE_(d3d_caps)("[FAILED] - Usage=%#08x requested for CheckFormat=%s and RType=%d but only %#08x is available\n", Usage, debug_d3dformat(CheckFormat), RType, UsageCaps);
3820         return WINED3DERR_NOTAVAILABLE;
3821     }
3822 }
3823
3824 static HRESULT WINAPI IWineD3DImpl_CheckDeviceFormatConversion(IWineD3D *iface, UINT adapter_idx,
3825         WINED3DDEVTYPE device_type, WINED3DFORMAT src_format, WINED3DFORMAT dst_format)
3826 {
3827     FIXME("iface %p, adapter_idx %u, device_type %s, src_format %s, dst_format %s stub!\n",
3828             iface, adapter_idx, debug_d3ddevicetype(device_type), debug_d3dformat(src_format),
3829             debug_d3dformat(dst_format));
3830
3831     return WINED3D_OK;
3832 }
3833
3834 /* Note: d3d8 passes in a pointer to a D3DCAPS8 structure, which is a true
3835       subset of a D3DCAPS9 structure. However, it has to come via a void *
3836       as the d3d8 interface cannot import the d3d9 header                  */
3837 static HRESULT WINAPI IWineD3DImpl_GetDeviceCaps(IWineD3D *iface, UINT Adapter, WINED3DDEVTYPE DeviceType, WINED3DCAPS* pCaps) {
3838
3839     IWineD3DImpl    *This = (IWineD3DImpl *)iface;
3840     struct wined3d_adapter *adapter = &This->adapters[Adapter];
3841     const struct wined3d_gl_info *gl_info = &adapter->gl_info;
3842     int vs_selected_mode;
3843     int ps_selected_mode;
3844     struct shader_caps shader_caps;
3845     struct fragment_caps fragment_caps;
3846     DWORD ckey_caps, blit_caps, fx_caps;
3847
3848     TRACE_(d3d_caps)("(%p)->(Adptr:%d, DevType: %x, pCaps: %p)\n", This, Adapter, DeviceType, pCaps);
3849
3850     if (Adapter >= IWineD3D_GetAdapterCount(iface)) {
3851         return WINED3DERR_INVALIDCALL;
3852     }
3853
3854     select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
3855
3856     /* ------------------------------------------------
3857        The following fields apply to both d3d8 and d3d9
3858        ------------------------------------------------ */
3859     pCaps->DeviceType              = (DeviceType == WINED3DDEVTYPE_HAL) ? WINED3DDEVTYPE_HAL : WINED3DDEVTYPE_REF;  /* Not quite true, but use h/w supported by opengl I suppose */
3860     pCaps->AdapterOrdinal          = Adapter;
3861
3862     pCaps->Caps                    = 0;
3863     pCaps->Caps2                   = WINED3DCAPS2_CANRENDERWINDOWED |
3864                                      WINED3DCAPS2_FULLSCREENGAMMA |
3865                                      WINED3DCAPS2_DYNAMICTEXTURES;
3866     if (gl_info->supported[SGIS_GENERATE_MIPMAP])
3867     {
3868         pCaps->Caps2 |= WINED3DCAPS2_CANAUTOGENMIPMAP;
3869     }
3870
3871     pCaps->Caps3                   = WINED3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD |
3872                                      WINED3DCAPS3_COPY_TO_VIDMEM                   |
3873                                      WINED3DCAPS3_COPY_TO_SYSTEMMEM;
3874
3875     pCaps->PresentationIntervals   = WINED3DPRESENT_INTERVAL_IMMEDIATE  |
3876                                      WINED3DPRESENT_INTERVAL_ONE;
3877
3878     pCaps->CursorCaps              = WINED3DCURSORCAPS_COLOR            |
3879                                      WINED3DCURSORCAPS_LOWRES;
3880
3881     pCaps->DevCaps                 = WINED3DDEVCAPS_FLOATTLVERTEX       |
3882                                      WINED3DDEVCAPS_EXECUTESYSTEMMEMORY |
3883                                      WINED3DDEVCAPS_TLVERTEXSYSTEMMEMORY|
3884                                      WINED3DDEVCAPS_TLVERTEXVIDEOMEMORY |
3885                                      WINED3DDEVCAPS_DRAWPRIMTLVERTEX    |
3886                                      WINED3DDEVCAPS_HWTRANSFORMANDLIGHT |
3887                                      WINED3DDEVCAPS_EXECUTEVIDEOMEMORY  |
3888                                      WINED3DDEVCAPS_PUREDEVICE          |
3889                                      WINED3DDEVCAPS_HWRASTERIZATION     |
3890                                      WINED3DDEVCAPS_TEXTUREVIDEOMEMORY  |
3891                                      WINED3DDEVCAPS_TEXTURESYSTEMMEMORY |
3892                                      WINED3DDEVCAPS_CANRENDERAFTERFLIP  |
3893                                      WINED3DDEVCAPS_DRAWPRIMITIVES2     |
3894                                      WINED3DDEVCAPS_DRAWPRIMITIVES2EX   |
3895                                      WINED3DDEVCAPS_RTPATCHES;
3896
3897     pCaps->PrimitiveMiscCaps       = WINED3DPMISCCAPS_CULLNONE              |
3898                                      WINED3DPMISCCAPS_CULLCCW               |
3899                                      WINED3DPMISCCAPS_CULLCW                |
3900                                      WINED3DPMISCCAPS_COLORWRITEENABLE      |
3901                                      WINED3DPMISCCAPS_CLIPTLVERTS           |
3902                                      WINED3DPMISCCAPS_CLIPPLANESCALEDPOINTS |
3903                                      WINED3DPMISCCAPS_MASKZ                 |
3904                                      WINED3DPMISCCAPS_BLENDOP               |
3905                                      WINED3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING;
3906                                     /* TODO:
3907                                         WINED3DPMISCCAPS_NULLREFERENCE
3908                                         WINED3DPMISCCAPS_INDEPENDENTWRITEMASKS
3909                                         WINED3DPMISCCAPS_FOGANDSPECULARALPHA
3910                                         WINED3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS
3911                                         WINED3DPMISCCAPS_FOGVERTEXCLAMPED */
3912
3913     if (gl_info->supported[EXT_BLEND_EQUATION_SEPARATE] && gl_info->supported[EXT_BLEND_FUNC_SEPARATE])
3914         pCaps->PrimitiveMiscCaps |= WINED3DPMISCCAPS_SEPARATEALPHABLEND;
3915
3916     pCaps->RasterCaps              = WINED3DPRASTERCAPS_DITHER    |
3917                                      WINED3DPRASTERCAPS_PAT       |
3918                                      WINED3DPRASTERCAPS_WFOG      |
3919                                      WINED3DPRASTERCAPS_ZFOG      |
3920                                      WINED3DPRASTERCAPS_FOGVERTEX |
3921                                      WINED3DPRASTERCAPS_FOGTABLE  |
3922                                      WINED3DPRASTERCAPS_STIPPLE   |
3923                                      WINED3DPRASTERCAPS_SUBPIXEL  |
3924                                      WINED3DPRASTERCAPS_ZTEST     |
3925                                      WINED3DPRASTERCAPS_SCISSORTEST   |
3926                                      WINED3DPRASTERCAPS_SLOPESCALEDEPTHBIAS |
3927                                      WINED3DPRASTERCAPS_DEPTHBIAS;
3928
3929     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
3930     {
3931         pCaps->RasterCaps |= WINED3DPRASTERCAPS_ANISOTROPY    |
3932                              WINED3DPRASTERCAPS_ZBIAS         |
3933                              WINED3DPRASTERCAPS_MIPMAPLODBIAS;
3934     }
3935     if (gl_info->supported[NV_FOG_DISTANCE])
3936     {
3937         pCaps->RasterCaps         |= WINED3DPRASTERCAPS_FOGRANGE;
3938     }
3939                         /* FIXME Add:
3940                            WINED3DPRASTERCAPS_COLORPERSPECTIVE
3941                            WINED3DPRASTERCAPS_STRETCHBLTMULTISAMPLE
3942                            WINED3DPRASTERCAPS_ANTIALIASEDGES
3943                            WINED3DPRASTERCAPS_ZBUFFERLESSHSR
3944                            WINED3DPRASTERCAPS_WBUFFER */
3945
3946     pCaps->ZCmpCaps = WINED3DPCMPCAPS_ALWAYS       |
3947                       WINED3DPCMPCAPS_EQUAL        |
3948                       WINED3DPCMPCAPS_GREATER      |
3949                       WINED3DPCMPCAPS_GREATEREQUAL |
3950                       WINED3DPCMPCAPS_LESS         |
3951                       WINED3DPCMPCAPS_LESSEQUAL    |
3952                       WINED3DPCMPCAPS_NEVER        |
3953                       WINED3DPCMPCAPS_NOTEQUAL;
3954
3955     pCaps->SrcBlendCaps  = WINED3DPBLENDCAPS_BOTHINVSRCALPHA |
3956                            WINED3DPBLENDCAPS_BOTHSRCALPHA    |
3957                            WINED3DPBLENDCAPS_DESTALPHA       |
3958                            WINED3DPBLENDCAPS_DESTCOLOR       |
3959                            WINED3DPBLENDCAPS_INVDESTALPHA    |
3960                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
3961                            WINED3DPBLENDCAPS_INVSRCALPHA     |
3962                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
3963                            WINED3DPBLENDCAPS_ONE             |
3964                            WINED3DPBLENDCAPS_SRCALPHA        |
3965                            WINED3DPBLENDCAPS_SRCALPHASAT     |
3966                            WINED3DPBLENDCAPS_SRCCOLOR        |
3967                            WINED3DPBLENDCAPS_ZERO;
3968
3969     pCaps->DestBlendCaps = WINED3DPBLENDCAPS_DESTALPHA       |
3970                            WINED3DPBLENDCAPS_DESTCOLOR       |
3971                            WINED3DPBLENDCAPS_INVDESTALPHA    |
3972                            WINED3DPBLENDCAPS_INVDESTCOLOR    |
3973                            WINED3DPBLENDCAPS_INVSRCALPHA     |
3974                            WINED3DPBLENDCAPS_INVSRCCOLOR     |
3975                            WINED3DPBLENDCAPS_ONE             |
3976                            WINED3DPBLENDCAPS_SRCALPHA        |
3977                            WINED3DPBLENDCAPS_SRCCOLOR        |
3978                            WINED3DPBLENDCAPS_ZERO;
3979     /* NOTE: WINED3DPBLENDCAPS_SRCALPHASAT is not supported as dest blend factor,
3980      * according to the glBlendFunc manpage
3981      *
3982      * WINED3DPBLENDCAPS_BOTHINVSRCALPHA and WINED3DPBLENDCAPS_BOTHSRCALPHA are
3983      * legacy settings for srcblend only
3984      */
3985
3986     if (gl_info->supported[EXT_BLEND_COLOR])
3987     {
3988         pCaps->SrcBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
3989         pCaps->DestBlendCaps |= WINED3DPBLENDCAPS_BLENDFACTOR;
3990     }
3991
3992
3993     pCaps->AlphaCmpCaps = WINED3DPCMPCAPS_ALWAYS       |
3994                           WINED3DPCMPCAPS_EQUAL        |
3995                           WINED3DPCMPCAPS_GREATER      |
3996                           WINED3DPCMPCAPS_GREATEREQUAL |
3997                           WINED3DPCMPCAPS_LESS         |
3998                           WINED3DPCMPCAPS_LESSEQUAL    |
3999                           WINED3DPCMPCAPS_NEVER        |
4000                           WINED3DPCMPCAPS_NOTEQUAL;
4001
4002     pCaps->ShadeCaps     = WINED3DPSHADECAPS_SPECULARGOURAUDRGB |
4003                            WINED3DPSHADECAPS_COLORGOURAUDRGB    |
4004                            WINED3DPSHADECAPS_ALPHAFLATBLEND     |
4005                            WINED3DPSHADECAPS_ALPHAGOURAUDBLEND  |
4006                            WINED3DPSHADECAPS_COLORFLATRGB       |
4007                            WINED3DPSHADECAPS_FOGFLAT            |
4008                            WINED3DPSHADECAPS_FOGGOURAUD         |
4009                            WINED3DPSHADECAPS_SPECULARFLATRGB;
4010
4011     pCaps->TextureCaps =  WINED3DPTEXTURECAPS_ALPHA              |
4012                           WINED3DPTEXTURECAPS_ALPHAPALETTE       |
4013                           WINED3DPTEXTURECAPS_TRANSPARENCY       |
4014                           WINED3DPTEXTURECAPS_BORDER             |
4015                           WINED3DPTEXTURECAPS_MIPMAP             |
4016                           WINED3DPTEXTURECAPS_PROJECTED          |
4017                           WINED3DPTEXTURECAPS_PERSPECTIVE;
4018
4019     if (!gl_info->supported[ARB_TEXTURE_NON_POWER_OF_TWO])
4020     {
4021         pCaps->TextureCaps |= WINED3DPTEXTURECAPS_POW2 |
4022                               WINED3DPTEXTURECAPS_NONPOW2CONDITIONAL;
4023     }
4024
4025     if (gl_info->supported[EXT_TEXTURE3D])
4026     {
4027         pCaps->TextureCaps |=  WINED3DPTEXTURECAPS_VOLUMEMAP      |
4028                                WINED3DPTEXTURECAPS_MIPVOLUMEMAP   |
4029                                WINED3DPTEXTURECAPS_VOLUMEMAP_POW2;
4030     }
4031
4032     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4033     {
4034         pCaps->TextureCaps |= WINED3DPTEXTURECAPS_CUBEMAP     |
4035                               WINED3DPTEXTURECAPS_MIPCUBEMAP    |
4036                               WINED3DPTEXTURECAPS_CUBEMAP_POW2;
4037
4038     }
4039
4040     pCaps->TextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
4041                                WINED3DPTFILTERCAPS_MAGFPOINT        |
4042                                WINED3DPTFILTERCAPS_MINFLINEAR       |
4043                                WINED3DPTFILTERCAPS_MINFPOINT        |
4044                                WINED3DPTFILTERCAPS_MIPFLINEAR       |
4045                                WINED3DPTFILTERCAPS_MIPFPOINT        |
4046                                WINED3DPTFILTERCAPS_LINEAR           |
4047                                WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4048                                WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4049                                WINED3DPTFILTERCAPS_MIPLINEAR        |
4050                                WINED3DPTFILTERCAPS_MIPNEAREST       |
4051                                WINED3DPTFILTERCAPS_NEAREST;
4052
4053     if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
4054     {
4055         pCaps->TextureFilterCaps |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
4056                                     WINED3DPTFILTERCAPS_MINFANISOTROPIC;
4057     }
4058
4059     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
4060     {
4061         pCaps->CubeTextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
4062                                        WINED3DPTFILTERCAPS_MAGFPOINT        |
4063                                        WINED3DPTFILTERCAPS_MINFLINEAR       |
4064                                        WINED3DPTFILTERCAPS_MINFPOINT        |
4065                                        WINED3DPTFILTERCAPS_MIPFLINEAR       |
4066                                        WINED3DPTFILTERCAPS_MIPFPOINT        |
4067                                        WINED3DPTFILTERCAPS_LINEAR           |
4068                                        WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4069                                        WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4070                                        WINED3DPTFILTERCAPS_MIPLINEAR        |
4071                                        WINED3DPTFILTERCAPS_MIPNEAREST       |
4072                                        WINED3DPTFILTERCAPS_NEAREST;
4073
4074         if (gl_info->supported[EXT_TEXTURE_FILTER_ANISOTROPIC])
4075         {
4076             pCaps->CubeTextureFilterCaps |= WINED3DPTFILTERCAPS_MAGFANISOTROPIC |
4077                                             WINED3DPTFILTERCAPS_MINFANISOTROPIC;
4078         }
4079     } else
4080         pCaps->CubeTextureFilterCaps = 0;
4081
4082     if (gl_info->supported[EXT_TEXTURE3D])
4083     {
4084         pCaps->VolumeTextureFilterCaps = WINED3DPTFILTERCAPS_MAGFLINEAR       |
4085                                          WINED3DPTFILTERCAPS_MAGFPOINT        |
4086                                          WINED3DPTFILTERCAPS_MINFLINEAR       |
4087                                          WINED3DPTFILTERCAPS_MINFPOINT        |
4088                                          WINED3DPTFILTERCAPS_MIPFLINEAR       |
4089                                          WINED3DPTFILTERCAPS_MIPFPOINT        |
4090                                          WINED3DPTFILTERCAPS_LINEAR           |
4091                                          WINED3DPTFILTERCAPS_LINEARMIPLINEAR  |
4092                                          WINED3DPTFILTERCAPS_LINEARMIPNEAREST |
4093                                          WINED3DPTFILTERCAPS_MIPLINEAR        |
4094                                          WINED3DPTFILTERCAPS_MIPNEAREST       |
4095                                          WINED3DPTFILTERCAPS_NEAREST;
4096     } else
4097         pCaps->VolumeTextureFilterCaps = 0;
4098
4099     pCaps->TextureAddressCaps =  WINED3DPTADDRESSCAPS_INDEPENDENTUV |
4100                                  WINED3DPTADDRESSCAPS_CLAMP  |
4101                                  WINED3DPTADDRESSCAPS_WRAP;
4102
4103     if (gl_info->supported[ARB_TEXTURE_BORDER_CLAMP])
4104     {
4105         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
4106     }
4107     if (gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT])
4108     {
4109         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
4110     }
4111     if (gl_info->supported[ATI_TEXTURE_MIRROR_ONCE])
4112     {
4113         pCaps->TextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
4114     }
4115
4116     if (gl_info->supported[EXT_TEXTURE3D])
4117     {
4118         pCaps->VolumeTextureAddressCaps =  WINED3DPTADDRESSCAPS_INDEPENDENTUV |
4119                                            WINED3DPTADDRESSCAPS_CLAMP  |
4120                                            WINED3DPTADDRESSCAPS_WRAP;
4121         if (gl_info->supported[ARB_TEXTURE_BORDER_CLAMP])
4122         {
4123             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_BORDER;
4124         }
4125         if (gl_info->supported[ARB_TEXTURE_MIRRORED_REPEAT])
4126         {
4127             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRROR;
4128         }
4129         if (gl_info->supported[ATI_TEXTURE_MIRROR_ONCE])
4130         {
4131             pCaps->VolumeTextureAddressCaps |= WINED3DPTADDRESSCAPS_MIRRORONCE;
4132         }
4133     } else
4134         pCaps->VolumeTextureAddressCaps = 0;
4135
4136     pCaps->LineCaps = WINED3DLINECAPS_TEXTURE       |
4137                       WINED3DLINECAPS_ZTEST         |
4138                       WINED3DLINECAPS_BLEND         |
4139                       WINED3DLINECAPS_ALPHACMP      |
4140                       WINED3DLINECAPS_FOG;
4141     /* WINED3DLINECAPS_ANTIALIAS is not supported on Windows, and dx and gl seem to have a different
4142      * idea how generating the smoothing alpha values works; the result is different
4143      */
4144
4145     pCaps->MaxTextureWidth = gl_info->limits.texture_size;
4146     pCaps->MaxTextureHeight = gl_info->limits.texture_size;
4147
4148     if (gl_info->supported[EXT_TEXTURE3D])
4149         pCaps->MaxVolumeExtent = gl_info->limits.texture3d_size;
4150     else
4151         pCaps->MaxVolumeExtent = 0;
4152
4153     pCaps->MaxTextureRepeat = 32768;
4154     pCaps->MaxTextureAspectRatio = gl_info->limits.texture_size;
4155     pCaps->MaxVertexW = 1.0f;
4156
4157     pCaps->GuardBandLeft = 0.0f;
4158     pCaps->GuardBandTop = 0.0f;
4159     pCaps->GuardBandRight = 0.0f;
4160     pCaps->GuardBandBottom = 0.0f;
4161
4162     pCaps->ExtentsAdjust = 0.0f;
4163
4164     pCaps->StencilCaps =  WINED3DSTENCILCAPS_DECRSAT |
4165                           WINED3DSTENCILCAPS_INCRSAT |
4166                           WINED3DSTENCILCAPS_INVERT  |
4167                           WINED3DSTENCILCAPS_KEEP    |
4168                           WINED3DSTENCILCAPS_REPLACE |
4169                           WINED3DSTENCILCAPS_ZERO;
4170     if (gl_info->supported[EXT_STENCIL_WRAP])
4171     {
4172         pCaps->StencilCaps |= WINED3DSTENCILCAPS_DECR  |
4173                               WINED3DSTENCILCAPS_INCR;
4174     }
4175     if (gl_info->supported[EXT_STENCIL_TWO_SIDE] || gl_info->supported[ATI_SEPARATE_STENCIL])
4176     {
4177         pCaps->StencilCaps |= WINED3DSTENCILCAPS_TWOSIDED;
4178     }
4179
4180     pCaps->FVFCaps = WINED3DFVFCAPS_PSIZE | 0x0008; /* 8 texture coords */
4181
4182     pCaps->MaxUserClipPlanes = gl_info->limits.clipplanes;
4183     pCaps->MaxActiveLights = gl_info->limits.lights;
4184
4185     pCaps->MaxVertexBlendMatrices = gl_info->limits.blends;
4186     pCaps->MaxVertexBlendMatrixIndex   = 0;
4187
4188     pCaps->MaxAnisotropy = gl_info->limits.anisotropy;
4189     pCaps->MaxPointSize = gl_info->limits.pointsize_max;
4190
4191
4192     /* FIXME: Add D3DVTXPCAPS_TWEENING, D3DVTXPCAPS_TEXGEN_SPHEREMAP */
4193     pCaps->VertexProcessingCaps = WINED3DVTXPCAPS_DIRECTIONALLIGHTS |
4194                                   WINED3DVTXPCAPS_MATERIALSOURCE7   |
4195                                   WINED3DVTXPCAPS_POSITIONALLIGHTS  |
4196                                   WINED3DVTXPCAPS_LOCALVIEWER       |
4197                                   WINED3DVTXPCAPS_VERTEXFOG         |
4198                                   WINED3DVTXPCAPS_TEXGEN;
4199
4200     pCaps->MaxPrimitiveCount   = 0xFFFFF; /* For now set 2^20-1 which is used by most >=Geforce3/Radeon8500 cards */
4201     pCaps->MaxVertexIndex      = 0xFFFFF;
4202     pCaps->MaxStreams          = MAX_STREAMS;
4203     pCaps->MaxStreamStride     = 1024;
4204
4205     /* d3d9.dll sets D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES here because StretchRects is implemented in d3d9 */
4206     pCaps->DevCaps2                          = WINED3DDEVCAPS2_STREAMOFFSET |
4207                                                WINED3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET;
4208     pCaps->MaxNpatchTessellationLevel        = 0;
4209     pCaps->MasterAdapterOrdinal              = 0;
4210     pCaps->AdapterOrdinalInGroup             = 0;
4211     pCaps->NumberOfAdaptersInGroup           = 1;
4212
4213     pCaps->NumSimultaneousRTs = gl_info->limits.buffers;
4214
4215     pCaps->StretchRectFilterCaps             = WINED3DPTFILTERCAPS_MINFPOINT  |
4216                                                 WINED3DPTFILTERCAPS_MAGFPOINT  |
4217                                                 WINED3DPTFILTERCAPS_MINFLINEAR |
4218                                                 WINED3DPTFILTERCAPS_MAGFLINEAR;
4219     pCaps->VertexTextureFilterCaps           = 0;
4220
4221     memset(&shader_caps, 0, sizeof(shader_caps));
4222     adapter->shader_backend->shader_get_caps(&adapter->gl_info, &shader_caps);
4223
4224     memset(&fragment_caps, 0, sizeof(fragment_caps));
4225     adapter->fragment_pipe->get_caps(&adapter->gl_info, &fragment_caps);
4226
4227     /* Add shader misc caps. Only some of them belong to the shader parts of the pipeline */
4228     pCaps->PrimitiveMiscCaps |= fragment_caps.PrimitiveMiscCaps;
4229
4230     /* This takes care for disabling vertex shader or pixel shader caps while leaving the other one enabled.
4231      * Ignore shader model capabilities if disabled in config
4232      */
4233     if(vs_selected_mode == SHADER_NONE) {
4234         TRACE_(d3d_caps)("Vertex shader disabled in config, reporting version 0.0\n");
4235         pCaps->VertexShaderVersion          = WINED3DVS_VERSION(0,0);
4236         pCaps->MaxVertexShaderConst         = 0;
4237     } else {
4238         pCaps->VertexShaderVersion          = shader_caps.VertexShaderVersion;
4239         pCaps->MaxVertexShaderConst         = shader_caps.MaxVertexShaderConst;
4240     }
4241
4242     if(ps_selected_mode == SHADER_NONE) {
4243         TRACE_(d3d_caps)("Pixel shader disabled in config, reporting version 0.0\n");
4244         pCaps->PixelShaderVersion           = WINED3DPS_VERSION(0,0);
4245         pCaps->PixelShader1xMaxValue        = 0.0f;
4246     } else {
4247         pCaps->PixelShaderVersion           = shader_caps.PixelShaderVersion;
4248         pCaps->PixelShader1xMaxValue        = shader_caps.PixelShader1xMaxValue;
4249     }
4250
4251     pCaps->TextureOpCaps                    = fragment_caps.TextureOpCaps;
4252     pCaps->MaxTextureBlendStages            = fragment_caps.MaxTextureBlendStages;
4253     pCaps->MaxSimultaneousTextures          = fragment_caps.MaxSimultaneousTextures;
4254
4255     pCaps->VS20Caps                         = shader_caps.VS20Caps;
4256     pCaps->MaxVShaderInstructionsExecuted   = shader_caps.MaxVShaderInstructionsExecuted;
4257     pCaps->MaxVertexShader30InstructionSlots= shader_caps.MaxVertexShader30InstructionSlots;
4258     pCaps->PS20Caps                         = shader_caps.PS20Caps;
4259     pCaps->MaxPShaderInstructionsExecuted   = shader_caps.MaxPShaderInstructionsExecuted;
4260     pCaps->MaxPixelShader30InstructionSlots = shader_caps.MaxPixelShader30InstructionSlots;
4261
4262     /* The following caps are shader specific, but they are things we cannot detect, or which
4263      * are the same among all shader models. So to avoid code duplication set the shader version
4264      * specific, but otherwise constant caps here
4265      */
4266     if(pCaps->VertexShaderVersion == WINED3DVS_VERSION(3,0)) {
4267         /* Where possible set the caps based on OpenGL extensions and if they aren't set (in case of software rendering)
4268         use the VS 3.0 from MSDN or else if there's OpenGL spec use a hardcoded value minimum VS3.0 value. */
4269         pCaps->VS20Caps.Caps                     = WINED3DVS20CAPS_PREDICATION;
4270         pCaps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH; /* VS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
4271         pCaps->VS20Caps.NumTemps = max(32, adapter->gl_info.limits.arb_vs_temps);
4272         pCaps->VS20Caps.StaticFlowControlDepth   = WINED3DVS20_MAX_STATICFLOWCONTROLDEPTH ; /* level of nesting in loops / if-statements; VS 3.0 requires MAX (4) */
4273
4274         pCaps->MaxVShaderInstructionsExecuted    = 65535; /* VS 3.0 needs at least 65535, some cards even use 2^32-1 */
4275         pCaps->MaxVertexShader30InstructionSlots = max(512, adapter->gl_info.limits.arb_vs_instructions);
4276     }
4277     else if (pCaps->VertexShaderVersion == WINED3DVS_VERSION(2,0))
4278     {
4279         pCaps->VS20Caps.Caps                     = 0;
4280         pCaps->VS20Caps.DynamicFlowControlDepth  = WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH;
4281         pCaps->VS20Caps.NumTemps = max(12, adapter->gl_info.limits.arb_vs_temps);
4282         pCaps->VS20Caps.StaticFlowControlDepth   = 1;
4283
4284         pCaps->MaxVShaderInstructionsExecuted    = 65535;
4285         pCaps->MaxVertexShader30InstructionSlots = 0;
4286     } else { /* VS 1.x */
4287         pCaps->VS20Caps.Caps                     = 0;
4288         pCaps->VS20Caps.DynamicFlowControlDepth  = 0;
4289         pCaps->VS20Caps.NumTemps                 = 0;
4290         pCaps->VS20Caps.StaticFlowControlDepth   = 0;
4291
4292         pCaps->MaxVShaderInstructionsExecuted    = 0;
4293         pCaps->MaxVertexShader30InstructionSlots = 0;
4294     }
4295
4296     if(pCaps->PixelShaderVersion == WINED3DPS_VERSION(3,0)) {
4297         /* Where possible set the caps based on OpenGL extensions and if they aren't set (in case of software rendering)
4298         use the PS 3.0 from MSDN or else if there's OpenGL spec use a hardcoded value minimum PS 3.0 value. */
4299
4300         /* Caps is more or less undocumented on MSDN but it appears to be used for PS20Caps based on results from R9600/FX5900/Geforce6800 cards from Windows */
4301         pCaps->PS20Caps.Caps                     = WINED3DPS20CAPS_ARBITRARYSWIZZLE     |
4302                 WINED3DPS20CAPS_GRADIENTINSTRUCTIONS |
4303                 WINED3DPS20CAPS_PREDICATION          |
4304                 WINED3DPS20CAPS_NODEPENDENTREADLIMIT |
4305                 WINED3DPS20CAPS_NOTEXINSTRUCTIONLIMIT;
4306         pCaps->PS20Caps.DynamicFlowControlDepth  = WINED3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH; /* PS 3.0 requires MAX_DYNAMICFLOWCONTROLDEPTH (24) */
4307         pCaps->PS20Caps.NumTemps = max(32, adapter->gl_info.limits.arb_ps_temps);
4308         pCaps->PS20Caps.StaticFlowControlDepth   = WINED3DPS20_MAX_STATICFLOWCONTROLDEPTH; /* PS 3.0 requires MAX_STATICFLOWCONTROLDEPTH (4) */
4309         pCaps->PS20Caps.NumInstructionSlots      = WINED3DPS20_MAX_NUMINSTRUCTIONSLOTS; /* PS 3.0 requires MAX_NUMINSTRUCTIONSLOTS (512) */
4310
4311         pCaps->MaxPShaderInstructionsExecuted    = 65535;
4312         pCaps->MaxPixelShader30InstructionSlots = max(WINED3DMIN30SHADERINSTRUCTIONS,
4313                 adapter->gl_info.limits.arb_ps_instructions);
4314     }
4315     else if(pCaps->PixelShaderVersion == WINED3DPS_VERSION(2,0))
4316     {
4317         /* Below we assume PS2.0 specs, not extended 2.0a(GeforceFX)/2.0b(Radeon R3xx) ones */
4318         pCaps->PS20Caps.Caps                     = 0;
4319         pCaps->PS20Caps.DynamicFlowControlDepth  = 0; /* WINED3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH = 0 */
4320         pCaps->PS20Caps.NumTemps = max(12, adapter->gl_info.limits.arb_ps_temps);
4321         pCaps->PS20Caps.StaticFlowControlDepth   = WINED3DPS20_MIN_STATICFLOWCONTROLDEPTH; /* Minimum: 1 */
4322         pCaps->PS20Caps.NumInstructionSlots      = WINED3DPS20_MIN_NUMINSTRUCTIONSLOTS; /* Minimum number (64 ALU + 32 Texture), a GeforceFX uses 512 */
4323
4324         pCaps->MaxPShaderInstructionsExecuted    = 512; /* Minimum value, a GeforceFX uses 1024 */
4325         pCaps->MaxPixelShader30InstructionSlots  = 0;
4326     } else { /* PS 1.x */
4327         pCaps->PS20Caps.Caps                     = 0;
4328         pCaps->PS20Caps.DynamicFlowControlDepth  = 0;
4329         pCaps->PS20Caps.NumTemps                 = 0;
4330         pCaps->PS20Caps.StaticFlowControlDepth   = 0;
4331         pCaps->PS20Caps.NumInstructionSlots      = 0;
4332
4333         pCaps->MaxPShaderInstructionsExecuted    = 0;
4334         pCaps->MaxPixelShader30InstructionSlots  = 0;
4335     }
4336
4337     if(pCaps->VertexShaderVersion >= WINED3DVS_VERSION(2,0)) {
4338         /* OpenGL supports all the formats below, perhaps not always
4339          * without conversion, but it supports them.
4340          * Further GLSL doesn't seem to have an official unsigned type so
4341          * don't advertise it yet as I'm not sure how we handle it.
4342          * We might need to add some clamping in the shader engine to
4343          * support it.
4344          * TODO: WINED3DDTCAPS_USHORT2N, WINED3DDTCAPS_USHORT4N, WINED3DDTCAPS_UDEC3, WINED3DDTCAPS_DEC3N */
4345         pCaps->DeclTypes = WINED3DDTCAPS_UBYTE4    |
4346                            WINED3DDTCAPS_UBYTE4N   |
4347                            WINED3DDTCAPS_SHORT2N   |
4348                            WINED3DDTCAPS_SHORT4N;
4349         if (gl_info->supported[ARB_HALF_FLOAT_VERTEX])
4350         {
4351             pCaps->DeclTypes |= WINED3DDTCAPS_FLOAT16_2 |
4352                                 WINED3DDTCAPS_FLOAT16_4;
4353         }
4354     } else
4355         pCaps->DeclTypes                         = 0;
4356
4357     /* Set DirectDraw helper Caps */
4358     ckey_caps =                         WINEDDCKEYCAPS_DESTBLT              |
4359                                         WINEDDCKEYCAPS_SRCBLT;
4360     fx_caps =                           WINEDDFXCAPS_BLTALPHA               |
4361                                         WINEDDFXCAPS_BLTMIRRORLEFTRIGHT     |
4362                                         WINEDDFXCAPS_BLTMIRRORUPDOWN        |
4363                                         WINEDDFXCAPS_BLTROTATION90          |
4364                                         WINEDDFXCAPS_BLTSHRINKX             |
4365                                         WINEDDFXCAPS_BLTSHRINKXN            |
4366                                         WINEDDFXCAPS_BLTSHRINKY             |
4367                                         WINEDDFXCAPS_BLTSHRINKXN            |
4368                                         WINEDDFXCAPS_BLTSTRETCHX            |
4369                                         WINEDDFXCAPS_BLTSTRETCHXN           |
4370                                         WINEDDFXCAPS_BLTSTRETCHY            |
4371                                         WINEDDFXCAPS_BLTSTRETCHYN;
4372     blit_caps =                         WINEDDCAPS_BLT                      |
4373                                         WINEDDCAPS_BLTCOLORFILL             |
4374                                         WINEDDCAPS_BLTDEPTHFILL             |
4375                                         WINEDDCAPS_BLTSTRETCH               |
4376                                         WINEDDCAPS_CANBLTSYSMEM             |
4377                                         WINEDDCAPS_CANCLIP                  |
4378                                         WINEDDCAPS_CANCLIPSTRETCHED         |
4379                                         WINEDDCAPS_COLORKEY                 |
4380                                         WINEDDCAPS_COLORKEYHWASSIST         |
4381                                         WINEDDCAPS_ALIGNBOUNDARYSRC;
4382
4383     /* Fill the ddraw caps structure */
4384     pCaps->DirectDrawCaps.Caps =        WINEDDCAPS_GDI                      |
4385                                         WINEDDCAPS_PALETTE                  |
4386                                         blit_caps;
4387     pCaps->DirectDrawCaps.Caps2 =       WINEDDCAPS2_CERTIFIED                |
4388                                         WINEDDCAPS2_NOPAGELOCKREQUIRED       |
4389                                         WINEDDCAPS2_PRIMARYGAMMA             |
4390                                         WINEDDCAPS2_WIDESURFACES             |
4391                                         WINEDDCAPS2_CANRENDERWINDOWED;
4392     pCaps->DirectDrawCaps.SVBCaps =     blit_caps;
4393     pCaps->DirectDrawCaps.SVBCKeyCaps = ckey_caps;
4394     pCaps->DirectDrawCaps.SVBFXCaps =   fx_caps;
4395     pCaps->DirectDrawCaps.VSBCaps =     blit_caps;
4396     pCaps->DirectDrawCaps.VSBCKeyCaps = ckey_caps;
4397     pCaps->DirectDrawCaps.VSBFXCaps =   fx_caps;
4398     pCaps->DirectDrawCaps.SSBCaps =     blit_caps;
4399     pCaps->DirectDrawCaps.SSBCKeyCaps = ckey_caps;
4400     pCaps->DirectDrawCaps.SSBFXCaps =   fx_caps;
4401
4402     pCaps->DirectDrawCaps.ddsCaps =     WINEDDSCAPS_ALPHA                   |
4403                                         WINEDDSCAPS_BACKBUFFER              |
4404                                         WINEDDSCAPS_FLIP                    |
4405                                         WINEDDSCAPS_FRONTBUFFER             |
4406                                         WINEDDSCAPS_OFFSCREENPLAIN          |
4407                                         WINEDDSCAPS_PALETTE                 |
4408                                         WINEDDSCAPS_PRIMARYSURFACE          |
4409                                         WINEDDSCAPS_SYSTEMMEMORY            |
4410                                         WINEDDSCAPS_VIDEOMEMORY             |
4411                                         WINEDDSCAPS_VISIBLE;
4412     pCaps->DirectDrawCaps.StrideAlign = DDRAW_PITCH_ALIGNMENT;
4413
4414     /* Set D3D caps if OpenGL is available. */
4415     if (adapter->opengl)
4416     {
4417         pCaps->DirectDrawCaps.ddsCaps |=WINEDDSCAPS_3DDEVICE                |
4418                                         WINEDDSCAPS_MIPMAP                  |
4419                                         WINEDDSCAPS_TEXTURE                 |
4420                                         WINEDDSCAPS_ZBUFFER;
4421         pCaps->DirectDrawCaps.Caps |=   WINEDDCAPS_3D;
4422     }
4423
4424     return WINED3D_OK;
4425 }
4426
4427 static HRESULT WINAPI IWineD3DImpl_CreateDevice(IWineD3D *iface, UINT adapter_idx,
4428         WINED3DDEVTYPE device_type, HWND focus_window, DWORD flags, IUnknown *parent,
4429         IWineD3DDeviceParent *device_parent, IWineD3DDevice **device)
4430 {
4431     IWineD3DImpl *This = (IWineD3DImpl *)iface;
4432     IWineD3DDeviceImpl *object;
4433     HRESULT hr;
4434
4435     TRACE("iface %p, adapter_idx %u, device_type %#x, focus_window %p, flags %#x.\n"
4436             "parent %p, device_parent %p, device %p.\n",
4437             iface, adapter_idx, device_type, focus_window, flags,
4438             parent, device_parent, device);
4439
4440     /* Validate the adapter number. If no adapters are available(no GL), ignore the adapter
4441      * number and create a device without a 3D adapter for 2D only operation. */
4442     if (IWineD3D_GetAdapterCount(iface) && adapter_idx >= IWineD3D_GetAdapterCount(iface))
4443     {
4444         return WINED3DERR_INVALIDCALL;
4445     }
4446
4447     object = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*object));
4448     if (!object)
4449     {
4450         ERR("Failed to allocate device memory.\n");
4451         return E_OUTOFMEMORY;
4452     }
4453
4454     hr = device_init(object, This, adapter_idx, device_type, focus_window, flags, parent, device_parent);
4455     if (FAILED(hr))
4456     {
4457         WARN("Failed to initialize device, hr %#x.\n", hr);
4458         HeapFree(GetProcessHeap(), 0, object);
4459         return hr;
4460     }
4461
4462     TRACE("Created device %p.\n", object);
4463     *device = (IWineD3DDevice *)object;
4464
4465     IWineD3DDeviceParent_WineD3DDeviceCreated(device_parent, *device);
4466
4467     return WINED3D_OK;
4468 }
4469
4470 static HRESULT WINAPI IWineD3DImpl_GetParent(IWineD3D *iface, IUnknown **pParent) {
4471     IWineD3DImpl *This = (IWineD3DImpl *)iface;
4472     IUnknown_AddRef(This->parent);
4473     *pParent = This->parent;
4474     return WINED3D_OK;
4475 }
4476
4477 static void WINE_GLAPI invalid_func(const void *data)
4478 {
4479     ERR("Invalid vertex attribute function called\n");
4480     DebugBreak();
4481 }
4482
4483 static void WINE_GLAPI invalid_texcoord_func(GLenum unit, const void *data)
4484 {
4485     ERR("Invalid texcoord function called\n");
4486     DebugBreak();
4487 }
4488
4489 /* Helper functions for providing vertex data to opengl. The arrays are initialized based on
4490  * the extension detection and are used in drawStridedSlow
4491  */
4492 static void WINE_GLAPI position_d3dcolor(const void *data)
4493 {
4494     DWORD pos = *((const DWORD *)data);
4495
4496     FIXME("Add a test for fixed function position from d3dcolor type\n");
4497     glVertex4s(D3DCOLOR_B_R(pos),
4498                D3DCOLOR_B_G(pos),
4499                D3DCOLOR_B_B(pos),
4500                D3DCOLOR_B_A(pos));
4501 }
4502
4503 static void WINE_GLAPI position_float4(const void *data)
4504 {
4505     const GLfloat *pos = data;
4506
4507     if (pos[3] != 0.0f && pos[3] != 1.0f)
4508     {
4509         float w = 1.0f / pos[3];
4510
4511         glVertex4f(pos[0] * w, pos[1] * w, pos[2] * w, w);
4512     }
4513     else
4514     {
4515         glVertex3fv(pos);
4516     }
4517 }
4518
4519 static void WINE_GLAPI diffuse_d3dcolor(const void *data)
4520 {
4521     DWORD diffuseColor = *((const DWORD *)data);
4522
4523     glColor4ub(D3DCOLOR_B_R(diffuseColor),
4524                D3DCOLOR_B_G(diffuseColor),
4525                D3DCOLOR_B_B(diffuseColor),
4526                D3DCOLOR_B_A(diffuseColor));
4527 }
4528
4529 static void WINE_GLAPI specular_d3dcolor(const void *data)
4530 {
4531     DWORD specularColor = *((const DWORD *)data);
4532     GLbyte d[] = {D3DCOLOR_B_R(specularColor),
4533             D3DCOLOR_B_G(specularColor),
4534             D3DCOLOR_B_B(specularColor)};
4535
4536     specular_func_3ubv(d);
4537 }
4538
4539 static void WINE_GLAPI warn_no_specular_func(const void *data)
4540 {
4541     WARN("GL_EXT_secondary_color not supported\n");
4542 }
4543
4544 static void fillGLAttribFuncs(const struct wined3d_gl_info *gl_info)
4545 {
4546     position_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
4547     position_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
4548     position_funcs[WINED3D_FFP_EMIT_FLOAT3]      = (glAttribFunc)glVertex3fv;
4549     position_funcs[WINED3D_FFP_EMIT_FLOAT4]      = position_float4;
4550     position_funcs[WINED3D_FFP_EMIT_D3DCOLOR]    = position_d3dcolor;
4551     position_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
4552     position_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
4553     position_funcs[WINED3D_FFP_EMIT_SHORT4]      = (glAttribFunc)glVertex2sv;
4554     position_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
4555     position_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
4556     position_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
4557     position_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
4558     position_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
4559     position_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
4560     position_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
4561     position_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
4562     position_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
4563
4564     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT1]       = invalid_func;
4565     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT2]       = invalid_func;
4566     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT3]       = (glAttribFunc)glColor3fv;
4567     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT4]       = (glAttribFunc)glColor4fv;
4568     diffuse_funcs[WINED3D_FFP_EMIT_D3DCOLOR]     = diffuse_d3dcolor;
4569     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4]       = invalid_func;
4570     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2]       = invalid_func;
4571     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4]       = invalid_func;
4572     diffuse_funcs[WINED3D_FFP_EMIT_UBYTE4N]      = (glAttribFunc)glColor4ubv;
4573     diffuse_funcs[WINED3D_FFP_EMIT_SHORT2N]      = invalid_func;
4574     diffuse_funcs[WINED3D_FFP_EMIT_SHORT4N]      = (glAttribFunc)glColor4sv;
4575     diffuse_funcs[WINED3D_FFP_EMIT_USHORT2N]     = invalid_func;
4576     diffuse_funcs[WINED3D_FFP_EMIT_USHORT4N]     = (glAttribFunc)glColor4usv;
4577     diffuse_funcs[WINED3D_FFP_EMIT_UDEC3]        = invalid_func;
4578     diffuse_funcs[WINED3D_FFP_EMIT_DEC3N]        = invalid_func;
4579     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_2]    = invalid_func;
4580     diffuse_funcs[WINED3D_FFP_EMIT_FLOAT16_4]    = invalid_func;
4581
4582     /* No 4 component entry points here */
4583     specular_funcs[WINED3D_FFP_EMIT_FLOAT1]      = invalid_func;
4584     specular_funcs[WINED3D_FFP_EMIT_FLOAT2]      = invalid_func;
4585     if (gl_info->supported[EXT_SECONDARY_COLOR])
4586     {
4587         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = (glAttribFunc)GL_EXTCALL(glSecondaryColor3fvEXT);
4588     }
4589     else
4590     {
4591         specular_funcs[WINED3D_FFP_EMIT_FLOAT3]  = warn_no_specular_func;
4592     }
4593     specular_funcs[WINED3D_FFP_EMIT_FLOAT4]      = invalid_func;
4594     if (gl_info->supported[EXT_SECONDARY_COLOR])
4595     {
4596         specular_func_3ubv = (glAttribFunc)GL_EXTCALL(glSecondaryColor3ubvEXT);
4597         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = specular_d3dcolor;
4598     }
4599     else
4600     {
4601         specular_funcs[WINED3D_FFP_EMIT_D3DCOLOR] = warn_no_specular_func;
4602     }
4603     specular_funcs[WINED3D_FFP_EMIT_UBYTE4]      = invalid_func;
4604     specular_funcs[WINED3D_FFP_EMIT_SHORT2]      = invalid_func;
4605     specular_funcs[WINED3D_FFP_EMIT_SHORT4]      = invalid_func;
4606     specular_funcs[WINED3D_FFP_EMIT_UBYTE4N]     = invalid_func;
4607     specular_funcs[WINED3D_FFP_EMIT_SHORT2N]     = invalid_func;
4608     specular_funcs[WINED3D_FFP_EMIT_SHORT4N]     = invalid_func;
4609     specular_funcs[WINED3D_FFP_EMIT_USHORT2N]    = invalid_func;
4610     specular_funcs[WINED3D_FFP_EMIT_USHORT4N]    = invalid_func;
4611     specular_funcs[WINED3D_FFP_EMIT_UDEC3]       = invalid_func;
4612     specular_funcs[WINED3D_FFP_EMIT_DEC3N]       = invalid_func;
4613     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_2]   = invalid_func;
4614     specular_funcs[WINED3D_FFP_EMIT_FLOAT16_4]   = invalid_func;
4615
4616     /* Only 3 component entry points here. Test how others behave. Float4 normals are used
4617      * by one of our tests, trying to pass it to the pixel shader, which fails on Windows.
4618      */
4619     normal_funcs[WINED3D_FFP_EMIT_FLOAT1]         = invalid_func;
4620     normal_funcs[WINED3D_FFP_EMIT_FLOAT2]         = invalid_func;
4621     normal_funcs[WINED3D_FFP_EMIT_FLOAT3]         = (glAttribFunc)glNormal3fv;
4622     normal_funcs[WINED3D_FFP_EMIT_FLOAT4]         = (glAttribFunc)glNormal3fv; /* Just ignore the 4th value */
4623     normal_funcs[WINED3D_FFP_EMIT_D3DCOLOR]       = invalid_func;
4624     normal_funcs[WINED3D_FFP_EMIT_UBYTE4]         = invalid_func;
4625     normal_funcs[WINED3D_FFP_EMIT_SHORT2]         = invalid_func;
4626     normal_funcs[WINED3D_FFP_EMIT_SHORT4]         = invalid_func;
4627     normal_funcs[WINED3D_FFP_EMIT_UBYTE4N]        = invalid_func;
4628     normal_funcs[WINED3D_FFP_EMIT_SHORT2N]        = invalid_func;
4629     normal_funcs[WINED3D_FFP_EMIT_SHORT4N]        = invalid_func;
4630     normal_funcs[WINED3D_FFP_EMIT_USHORT2N]       = invalid_func;
4631     normal_funcs[WINED3D_FFP_EMIT_USHORT4N]       = invalid_func;
4632     normal_funcs[WINED3D_FFP_EMIT_UDEC3]          = invalid_func;
4633     normal_funcs[WINED3D_FFP_EMIT_DEC3N]          = invalid_func;
4634     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_2]      = invalid_func;
4635     normal_funcs[WINED3D_FFP_EMIT_FLOAT16_4]      = invalid_func;
4636
4637     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT1]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord1fvARB);
4638     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2fvARB);
4639     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT3]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord3fvARB);
4640     multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4fvARB);
4641     multi_texcoord_funcs[WINED3D_FFP_EMIT_D3DCOLOR]  = invalid_texcoord_func;
4642     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4]    = invalid_texcoord_func;
4643     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2svARB);
4644     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4]    = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4svARB);
4645     multi_texcoord_funcs[WINED3D_FFP_EMIT_UBYTE4N]   = invalid_texcoord_func;
4646     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT2N]   = invalid_texcoord_func;
4647     multi_texcoord_funcs[WINED3D_FFP_EMIT_SHORT4N]   = invalid_texcoord_func;
4648     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT2N]  = invalid_texcoord_func;
4649     multi_texcoord_funcs[WINED3D_FFP_EMIT_USHORT4N]  = invalid_texcoord_func;
4650     multi_texcoord_funcs[WINED3D_FFP_EMIT_UDEC3]     = invalid_texcoord_func;
4651     multi_texcoord_funcs[WINED3D_FFP_EMIT_DEC3N]     = invalid_texcoord_func;
4652     if (gl_info->supported[NV_HALF_FLOAT])
4653     {
4654         /* Not supported by ARB_HALF_FLOAT_VERTEX, so check for NV_HALF_FLOAT */
4655         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord2hvNV);
4656         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = (glMultiTexCoordFunc)GL_EXTCALL(glMultiTexCoord4hvNV);
4657     } else {
4658         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_2] = invalid_texcoord_func;
4659         multi_texcoord_funcs[WINED3D_FFP_EMIT_FLOAT16_4] = invalid_texcoord_func;
4660     }
4661 }
4662
4663 BOOL InitAdapters(IWineD3DImpl *This)
4664 {
4665     static HMODULE mod_gl;
4666     BOOL ret;
4667     int ps_selected_mode, vs_selected_mode;
4668
4669     /* No need to hold any lock. The calling library makes sure only one thread calls
4670      * wined3d simultaneously
4671      */
4672
4673     TRACE("Initializing adapters\n");
4674
4675     if(!mod_gl) {
4676 #ifdef USE_WIN32_OPENGL
4677 #define USE_GL_FUNC(pfn) pfn = (void*)GetProcAddress(mod_gl, #pfn);
4678         mod_gl = LoadLibraryA("opengl32.dll");
4679         if(!mod_gl) {
4680             ERR("Can't load opengl32.dll!\n");
4681             goto nogl_adapter;
4682         }
4683 #else
4684 #define USE_GL_FUNC(pfn) pfn = (void*)pwglGetProcAddress(#pfn);
4685         /* To bypass the opengl32 thunks load wglGetProcAddress from gdi32 (glXGetProcAddress wrapper) instead of opengl32's */
4686         mod_gl = GetModuleHandleA("gdi32.dll");
4687 #endif
4688     }
4689
4690 /* Load WGL core functions from opengl32.dll */
4691 #define USE_WGL_FUNC(pfn) p##pfn = (void*)GetProcAddress(mod_gl, #pfn);
4692     WGL_FUNCS_GEN;
4693 #undef USE_WGL_FUNC
4694
4695     if(!pwglGetProcAddress) {
4696         ERR("Unable to load wglGetProcAddress!\n");
4697         goto nogl_adapter;
4698     }
4699
4700 /* Dynamically load all GL core functions */
4701     GL_FUNCS_GEN;
4702 #undef USE_GL_FUNC
4703
4704     /* Load glFinish and glFlush from opengl32.dll even if we're not using WIN32 opengl
4705      * otherwise because we have to use winex11.drv's override
4706      */
4707 #ifdef USE_WIN32_OPENGL
4708     wglFinish = (void*)GetProcAddress(mod_gl, "glFinish");
4709     wglFlush = (void*)GetProcAddress(mod_gl, "glFlush");
4710 #else
4711     wglFinish = (void*)pwglGetProcAddress("wglFinish");
4712     wglFlush = (void*)pwglGetProcAddress("wglFlush");
4713 #endif
4714
4715     glEnableWINE = glEnable;
4716     glDisableWINE = glDisable;
4717
4718     /* For now only one default adapter */
4719     {
4720         struct wined3d_adapter *adapter = &This->adapters[0];
4721         const struct wined3d_gl_info *gl_info = &adapter->gl_info;
4722         struct wined3d_fake_gl_ctx fake_gl_ctx = {0};
4723         int iPixelFormat;
4724         int res;
4725         int i;
4726         WineD3D_PixelFormat *cfgs;
4727         DISPLAY_DEVICEW DisplayDevice;
4728         HDC hdc;
4729
4730         TRACE("Initializing default adapter\n");
4731         adapter->ordinal = 0;
4732         adapter->monitorPoint.x = -1;
4733         adapter->monitorPoint.y = -1;
4734
4735         if (!AllocateLocallyUniqueId(&adapter->luid))
4736         {
4737             DWORD err = GetLastError();
4738             ERR("Failed to set adapter LUID (%#x).\n", err);
4739             goto nogl_adapter;
4740         }
4741         TRACE("Allocated LUID %08x:%08x for adapter.\n",
4742                 adapter->luid.HighPart, adapter->luid.LowPart);
4743
4744         if (!WineD3D_CreateFakeGLContext(&fake_gl_ctx))
4745         {
4746             ERR("Failed to get a gl context for default adapter\n");
4747             goto nogl_adapter;
4748         }
4749
4750         ret = IWineD3DImpl_FillGLCaps(adapter);
4751         if(!ret) {
4752             ERR("Failed to initialize gl caps for default adapter\n");
4753             WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
4754             goto nogl_adapter;
4755         }
4756         ret = initPixelFormats(&adapter->gl_info, adapter->driver_info.vendor);
4757         if(!ret) {
4758             ERR("Failed to init gl formats\n");
4759             WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
4760             goto nogl_adapter;
4761         }
4762
4763         hdc = fake_gl_ctx.dc;
4764
4765         /* Use the VideoRamSize registry setting when set */
4766         if(wined3d_settings.emulated_textureram)
4767             adapter->TextureRam = wined3d_settings.emulated_textureram;
4768         else
4769             adapter->TextureRam = adapter->gl_info.vidmem;
4770         adapter->UsedTextureRam = 0;
4771         TRACE("Emulating %dMB of texture ram\n", adapter->TextureRam/(1024*1024));
4772
4773         /* Initialize the Adapter's DeviceName which is required for ChangeDisplaySettings and friends */
4774         DisplayDevice.cb = sizeof(DisplayDevice);
4775         EnumDisplayDevicesW(NULL, 0 /* Adapter 0 = iDevNum 0 */, &DisplayDevice, 0);
4776         TRACE("DeviceName: %s\n", debugstr_w(DisplayDevice.DeviceName));
4777         strcpyW(adapter->DeviceName, DisplayDevice.DeviceName);
4778
4779         if (gl_info->supported[WGL_ARB_PIXEL_FORMAT])
4780         {
4781             int attribute;
4782             int attribs[10];
4783             int values[10];
4784             int nAttribs = 0;
4785
4786             attribute = WGL_NUMBER_PIXEL_FORMATS_ARB;
4787             GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, 0, 0, 1, &attribute, &adapter->nCfgs));
4788
4789             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, adapter->nCfgs *sizeof(WineD3D_PixelFormat));
4790             cfgs = adapter->cfgs;
4791             attribs[nAttribs++] = WGL_RED_BITS_ARB;
4792             attribs[nAttribs++] = WGL_GREEN_BITS_ARB;
4793             attribs[nAttribs++] = WGL_BLUE_BITS_ARB;
4794             attribs[nAttribs++] = WGL_ALPHA_BITS_ARB;
4795             attribs[nAttribs++] = WGL_DEPTH_BITS_ARB;
4796             attribs[nAttribs++] = WGL_STENCIL_BITS_ARB;
4797             attribs[nAttribs++] = WGL_DRAW_TO_WINDOW_ARB;
4798             attribs[nAttribs++] = WGL_PIXEL_TYPE_ARB;
4799             attribs[nAttribs++] = WGL_DOUBLE_BUFFER_ARB;
4800             attribs[nAttribs++] = WGL_AUX_BUFFERS_ARB;
4801
4802             for (iPixelFormat=1; iPixelFormat <= adapter->nCfgs; ++iPixelFormat)
4803             {
4804                 res = GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, nAttribs, attribs, values));
4805
4806                 if(!res)
4807                     continue;
4808
4809                 /* Cache the pixel format */
4810                 cfgs->iPixelFormat = iPixelFormat;
4811                 cfgs->redSize = values[0];
4812                 cfgs->greenSize = values[1];
4813                 cfgs->blueSize = values[2];
4814                 cfgs->alphaSize = values[3];
4815                 cfgs->depthSize = values[4];
4816                 cfgs->stencilSize = values[5];
4817                 cfgs->windowDrawable = values[6];
4818                 cfgs->iPixelType = values[7];
4819                 cfgs->doubleBuffer = values[8];
4820                 cfgs->auxBuffers = values[9];
4821
4822                 cfgs->pbufferDrawable = FALSE;
4823                 /* Check for pbuffer support when it is around as
4824                  * wglGetPixelFormatAttribiv fails for unknown attributes. */
4825                 if (gl_info->supported[WGL_ARB_PBUFFER])
4826                 {
4827                     int attrib = WGL_DRAW_TO_PBUFFER_ARB;
4828                     int value;
4829                     if(GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, 1, &attrib, &value)))
4830                         cfgs->pbufferDrawable = value;
4831                 }
4832
4833                 cfgs->numSamples = 0;
4834                 /* Check multisample support */
4835                 if (gl_info->supported[ARB_MULTISAMPLE])
4836                 {
4837                     int attrib[2] = {WGL_SAMPLE_BUFFERS_ARB, WGL_SAMPLES_ARB};
4838                     int value[2];
4839                     if(GL_EXTCALL(wglGetPixelFormatAttribivARB(hdc, iPixelFormat, 0, 2, attrib, value))) {
4840                         /* value[0] = WGL_SAMPLE_BUFFERS_ARB which tells whether multisampling is supported.
4841                         * value[1] = number of multi sample buffers*/
4842                         if(value[0])
4843                             cfgs->numSamples = value[1];
4844                     }
4845                 }
4846
4847                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, depth=%d, stencil=%d, windowDrawable=%d, pbufferDrawable=%d\n", cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer, cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize, cfgs->depthSize, cfgs->stencilSize, cfgs->windowDrawable, cfgs->pbufferDrawable);
4848                 cfgs++;
4849             }
4850         }
4851         else
4852         {
4853             int nCfgs = DescribePixelFormat(hdc, 0, 0, 0);
4854             adapter->cfgs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, nCfgs*sizeof(WineD3D_PixelFormat));
4855             adapter->nCfgs = 0; /* We won't accept all formats e.g. software accelerated ones will be skipped */
4856
4857             cfgs = adapter->cfgs;
4858             for(iPixelFormat=1; iPixelFormat<=nCfgs; iPixelFormat++)
4859             {
4860                 PIXELFORMATDESCRIPTOR ppfd;
4861
4862                 res = DescribePixelFormat(hdc, iPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &ppfd);
4863                 if(!res)
4864                     continue;
4865
4866                 /* We only want HW acceleration using an OpenGL ICD driver.
4867                  * PFD_GENERIC_FORMAT = slow opengl 1.1 gdi software rendering
4868                  * PFD_GENERIC_ACCELERATED = partial hw acceleration using a MCD driver (e.g. 3dfx minigl)
4869                  */
4870                 if(ppfd.dwFlags & (PFD_GENERIC_FORMAT | PFD_GENERIC_ACCELERATED))
4871                 {
4872                     TRACE("Skipping iPixelFormat=%d because it isn't ICD accelerated\n", iPixelFormat);
4873                     continue;
4874                 }
4875
4876                 cfgs->iPixelFormat = iPixelFormat;
4877                 cfgs->redSize = ppfd.cRedBits;
4878                 cfgs->greenSize = ppfd.cGreenBits;
4879                 cfgs->blueSize = ppfd.cBlueBits;
4880                 cfgs->alphaSize = ppfd.cAlphaBits;
4881                 cfgs->depthSize = ppfd.cDepthBits;
4882                 cfgs->stencilSize = ppfd.cStencilBits;
4883                 cfgs->pbufferDrawable = 0;
4884                 cfgs->windowDrawable = (ppfd.dwFlags & PFD_DRAW_TO_WINDOW) ? 1 : 0;
4885                 cfgs->iPixelType = (ppfd.iPixelType == PFD_TYPE_RGBA) ? WGL_TYPE_RGBA_ARB : WGL_TYPE_COLORINDEX_ARB;
4886                 cfgs->doubleBuffer = (ppfd.dwFlags & PFD_DOUBLEBUFFER) ? 1 : 0;
4887                 cfgs->auxBuffers = ppfd.cAuxBuffers;
4888                 cfgs->numSamples = 0;
4889
4890                 TRACE("iPixelFormat=%d, iPixelType=%#x, doubleBuffer=%d, RGBA=%d/%d/%d/%d, depth=%d, stencil=%d, windowDrawable=%d, pbufferDrawable=%d\n", cfgs->iPixelFormat, cfgs->iPixelType, cfgs->doubleBuffer, cfgs->redSize, cfgs->greenSize, cfgs->blueSize, cfgs->alphaSize, cfgs->depthSize, cfgs->stencilSize, cfgs->windowDrawable, cfgs->pbufferDrawable);
4891                 cfgs++;
4892                 adapter->nCfgs++;
4893             }
4894
4895             /* Yikes we haven't found any suitable formats. This should only happen in case of GDI software rendering which we can't use anyway as its 3D functionality is very, very limited */
4896             if(!adapter->nCfgs)
4897             {
4898                 ERR("Disabling Direct3D because no hardware accelerated pixel formats have been found!\n");
4899
4900                 WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
4901                 HeapFree(GetProcessHeap(), 0, adapter->cfgs);
4902                 goto nogl_adapter;
4903             }
4904         }
4905
4906         /* D16, D24X8 and D24S8 are common depth / depth+stencil formats. All drivers support them though this doesn't
4907          * mean that the format is offered in hardware. For instance Geforce8 cards don't have offer D16 in hardware
4908          * but just fake it using D24(X8?) which is fine. D3D also allows that.
4909          * Some display drivers (i915 on Linux) only report mixed depth+stencil formats like D24S8. MSDN clearly mentions
4910          * that only on lockable formats (e.g. D16_locked) the bit order is guaranteed and that on other formats the
4911          * driver is allowed to consume more bits EXCEPT for stencil bits.
4912          *
4913          * Mark an adapter with this broken stencil behavior.
4914          */
4915         adapter->brokenStencil = TRUE;
4916         for (i = 0, cfgs = adapter->cfgs; i < adapter->nCfgs; ++i)
4917         {
4918             /* Nearly all drivers offer depth formats without stencil, only on i915 this if-statement won't be entered. */
4919             if(cfgs[i].depthSize && !cfgs[i].stencilSize) {
4920                 adapter->brokenStencil = FALSE;
4921                 break;
4922             }
4923         }
4924
4925         WineD3D_ReleaseFakeGLContext(&fake_gl_ctx);
4926
4927         select_shader_mode(&adapter->gl_info, &ps_selected_mode, &vs_selected_mode);
4928         fillGLAttribFuncs(&adapter->gl_info);
4929         adapter->opengl = TRUE;
4930     }
4931     This->adapter_count = 1;
4932     TRACE("%u adapters successfully initialized\n", This->adapter_count);
4933
4934     return TRUE;
4935
4936 nogl_adapter:
4937     /* Initialize an adapter for ddraw-only memory counting */
4938     memset(This->adapters, 0, sizeof(This->adapters));
4939     This->adapters[0].ordinal = 0;
4940     This->adapters[0].opengl = FALSE;
4941     This->adapters[0].monitorPoint.x = -1;
4942     This->adapters[0].monitorPoint.y = -1;
4943
4944     This->adapters[0].driver_info.name = "Display";
4945     This->adapters[0].driver_info.description = "WineD3D DirectDraw Emulation";
4946     if(wined3d_settings.emulated_textureram) {
4947         This->adapters[0].TextureRam = wined3d_settings.emulated_textureram;
4948     } else {
4949         This->adapters[0].TextureRam = 8 * 1024 * 1024; /* This is plenty for a DDraw-only card */
4950     }
4951
4952     initPixelFormatsNoGL(&This->adapters[0].gl_info);
4953
4954     This->adapter_count = 1;
4955     return FALSE;
4956 }
4957
4958 /**********************************************************
4959  * IWineD3D VTbl follows
4960  **********************************************************/
4961
4962 const IWineD3DVtbl IWineD3D_Vtbl =
4963 {
4964     /* IUnknown */
4965     IWineD3DImpl_QueryInterface,
4966     IWineD3DImpl_AddRef,
4967     IWineD3DImpl_Release,
4968     /* IWineD3D */
4969     IWineD3DImpl_GetParent,
4970     IWineD3DImpl_GetAdapterCount,
4971     IWineD3DImpl_RegisterSoftwareDevice,
4972     IWineD3DImpl_GetAdapterMonitor,
4973     IWineD3DImpl_GetAdapterModeCount,
4974     IWineD3DImpl_EnumAdapterModes,
4975     IWineD3DImpl_GetAdapterDisplayMode,
4976     IWineD3DImpl_GetAdapterIdentifier,
4977     IWineD3DImpl_CheckDeviceMultiSampleType,
4978     IWineD3DImpl_CheckDepthStencilMatch,
4979     IWineD3DImpl_CheckDeviceType,
4980     IWineD3DImpl_CheckDeviceFormat,
4981     IWineD3DImpl_CheckDeviceFormatConversion,
4982     IWineD3DImpl_GetDeviceCaps,
4983     IWineD3DImpl_CreateDevice
4984 };
4985
4986 static void STDMETHODCALLTYPE wined3d_null_wined3d_object_destroyed(void *parent) {}
4987
4988 const struct wined3d_parent_ops wined3d_null_parent_ops =
4989 {
4990     wined3d_null_wined3d_object_destroyed,
4991 };