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