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