wined3d: Tidy up pshader_hw_cnd.
[wine] / dlls / wined3d / context.c
1 /*
2  * Context and render target management in wined3d
3  *
4  * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
29
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 /* The last used device.
33  *
34  * If the application creates multiple devices and switches between them, ActivateContext has to
35  * change the opengl context. This flag allows to keep track which device is active
36  */
37 static IWineD3DDeviceImpl *last_device;
38
39 /* FBO helper functions */
40
41 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
42 {
43     const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
44
45     if (!*fbo)
46     {
47         GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48         checkGLcall("glGenFramebuffersEXT()");
49         TRACE("Created FBO %d\n", *fbo);
50     }
51
52     GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53     checkGLcall("glBindFramebuffer()");
54 }
55
56 static void context_clean_fbo_attachments(IWineD3DDeviceImpl *This)
57 {
58     unsigned int i;
59
60     for (i = 0; i < GL_LIMITS(buffers); ++i)
61     {
62         GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
63         checkGLcall("glFramebufferTexture2D()");
64     }
65     GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
66     checkGLcall("glFramebufferTexture2D()");
67 }
68
69 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
70 {
71     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
72     checkGLcall("glBindFramebuffer()");
73
74     context_clean_fbo_attachments(This);
75
76     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
77     checkGLcall("glBindFramebuffer()");
78     GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
79     checkGLcall("glDeleteFramebuffers()");
80 }
81
82 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
83 {
84     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
85     const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
86     IWineD3DBaseTextureImpl *texture_impl;
87     BOOL update_minfilter = FALSE;
88     BOOL update_magfilter = FALSE;
89
90     /* Update base texture states array */
91     if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
92     {
93         if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
94             || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
95         {
96             texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
97             texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
98             update_minfilter = TRUE;
99         }
100
101         if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
102         {
103             texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
104             update_magfilter = TRUE;
105         }
106
107         if (texture_impl->baseTexture.bindCount)
108         {
109             WARN("Render targets should not be bound to a sampler\n");
110             IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
111         }
112
113         IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
114     }
115
116     if (update_minfilter || update_magfilter || force_preload)
117     {
118         GLenum target, bind_target;
119         GLint old_binding;
120
121         target = surface_impl->glDescription.target;
122         if (target == GL_TEXTURE_2D)
123         {
124             bind_target = GL_TEXTURE_2D;
125             glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
126         } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
127             bind_target = GL_TEXTURE_RECTANGLE_ARB;
128             glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
129         } else {
130             bind_target = GL_TEXTURE_CUBE_MAP_ARB;
131             glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
132         }
133
134         surface_internal_preload(surface, SRGB_RGB);
135
136         glBindTexture(bind_target, surface_impl->glDescription.textureName);
137         if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
138         if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
139         glBindTexture(bind_target, old_binding);
140     }
141
142     checkGLcall("apply_attachment_filter_states()");
143 }
144
145 /* TODO: Handle stencil attachments */
146 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
147 {
148     IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
149
150     TRACE("Attach depth stencil %p\n", depth_stencil);
151
152     if (depth_stencil)
153     {
154         if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
155         {
156             GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
157             checkGLcall("glFramebufferRenderbufferEXT()");
158         } else {
159             context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
160
161             GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
162                         depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
163             checkGLcall("glFramebufferTexture2DEXT()");
164         }
165     } else {
166         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
167         checkGLcall("glFramebufferTexture2DEXT()");
168     }
169 }
170
171 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
172 {
173     const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
174
175     TRACE("Attach surface %p to %u\n", surface, idx);
176
177     if (surface)
178     {
179         context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
180
181         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
182                 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
183         checkGLcall("glFramebufferTexture2DEXT()");
184     } else {
185         GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
186         checkGLcall("glFramebufferTexture2DEXT()");
187     }
188 }
189
190 static void context_check_fbo_status(IWineD3DDevice *iface)
191 {
192     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
193     GLenum status;
194
195     status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
196     if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
197     {
198         TRACE("FBO complete\n");
199     } else {
200         IWineD3DSurfaceImpl *attachment;
201         unsigned int i;
202         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
203
204         /* Dump the FBO attachments */
205         for (i = 0; i < GL_LIMITS(buffers); ++i)
206         {
207             attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
208             if (attachment)
209             {
210                 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
211                         i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
212                         attachment->pow2Width, attachment->pow2Height);
213             }
214         }
215         attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
216         if (attachment)
217         {
218             FIXME("\tDepth attachment: (%p) %s %ux%u\n",
219                     attachment, debug_d3dformat(attachment->resource.format_desc->format),
220                     attachment->pow2Width, attachment->pow2Height);
221         }
222     }
223 }
224
225 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
226 {
227     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
228     struct fbo_entry *entry;
229
230     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
231     entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
232     memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
233     entry->depth_stencil = This->stencilBufferTarget;
234     entry->attached = FALSE;
235     entry->id = 0;
236
237     return entry;
238 }
239
240 static void context_reuse_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
241 {
242     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
243
244     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, entry->id));
245     checkGLcall("glBindFramebuffer()");
246     context_clean_fbo_attachments(This);
247
248     memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
249     entry->depth_stencil = This->stencilBufferTarget;
250     entry->attached = FALSE;
251 }
252
253 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
254 {
255     if (entry->id)
256     {
257         TRACE("Destroy FBO %d\n", entry->id);
258         context_destroy_fbo(This, &entry->id);
259     }
260     list_remove(&entry->entry);
261     HeapFree(GetProcessHeap(), 0, entry->render_targets);
262     HeapFree(GetProcessHeap(), 0, entry);
263 }
264
265
266 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
267 {
268     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
269     struct fbo_entry *entry;
270
271     LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
272     {
273         if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
274                 && entry->depth_stencil == This->stencilBufferTarget)
275         {
276             list_remove(&entry->entry);
277             list_add_head(&context->fbo_list, &entry->entry);
278             return entry;
279         }
280     }
281
282     if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
283     {
284         entry = context_create_fbo_entry(iface);
285         list_add_head(&context->fbo_list, &entry->entry);
286         ++context->fbo_entry_count;
287     }
288     else
289     {
290         entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
291         context_reuse_fbo_entry(iface, entry);
292         list_remove(&entry->entry);
293         list_add_head(&context->fbo_list, &entry->entry);
294     }
295
296     return entry;
297 }
298
299 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
300 {
301     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
302     unsigned int i;
303
304     context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
305
306     if (!entry->attached)
307     {
308         /* Apply render targets */
309         for (i = 0; i < GL_LIMITS(buffers); ++i)
310         {
311             IWineD3DSurface *render_target = This->render_targets[i];
312             context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
313         }
314
315         /* Apply depth targets */
316         if (This->stencilBufferTarget) {
317             unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
318             unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
319
320             surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
321         }
322         context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
323
324         entry->attached = TRUE;
325     } else {
326         for (i = 0; i < GL_LIMITS(buffers); ++i)
327         {
328             if (This->render_targets[i])
329                 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
330         }
331         if (This->stencilBufferTarget)
332             context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
333     }
334
335     for (i = 0; i < GL_LIMITS(buffers); ++i)
336     {
337         if (This->render_targets[i])
338             This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
339         else
340             This->draw_buffers[i] = GL_NONE;
341     }
342 }
343
344 static void context_apply_fbo_state(IWineD3DDevice *iface)
345 {
346     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
347     WineD3DContext *context = This->activeContext;
348
349     if (This->render_offscreen)
350     {
351         context->current_fbo = context_find_fbo_entry(iface, context);
352         context_apply_fbo_entry(iface, context->current_fbo);
353     } else {
354         context->current_fbo = NULL;
355         GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
356     }
357
358     context_check_fbo_status(iface);
359 }
360
361 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
362 {
363     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
364     UINT i;
365
366     switch(type)
367     {
368         case WINED3DRTYPE_SURFACE:
369         {
370             for (i = 0; i < This->numContexts; ++i)
371             {
372                 struct fbo_entry *entry, *entry2;
373
374                 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
375                 {
376                     BOOL destroyed = FALSE;
377                     UINT j;
378
379                     for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
380                     {
381                         if (entry->render_targets[j] == (IWineD3DSurface *)resource)
382                         {
383                             context_destroy_fbo_entry(This, entry);
384                             destroyed = TRUE;
385                         }
386                     }
387
388                     if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
389                         context_destroy_fbo_entry(This, entry);
390                 }
391             }
392
393             break;
394         }
395
396         default:
397             break;
398     }
399 }
400
401 /*****************************************************************************
402  * Context_MarkStateDirty
403  *
404  * Marks a state in a context dirty. Only one context, opposed to
405  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
406  * contexts
407  *
408  * Params:
409  *  context: Context to mark the state dirty in
410  *  state: State to mark dirty
411  *  StateTable: Pointer to the state table in use(for state grouping)
412  *
413  *****************************************************************************/
414 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
415     DWORD rep = StateTable[state].representative;
416     DWORD idx;
417     BYTE shift;
418
419     if(!rep || isStateDirty(context, rep)) return;
420
421     context->dirtyArray[context->numDirtyEntries++] = rep;
422     idx = rep >> 5;
423     shift = rep & 0x1f;
424     context->isStateDirty[idx] |= (1 << shift);
425 }
426
427 /*****************************************************************************
428  * AddContextToArray
429  *
430  * Adds a context to the context array. Helper function for CreateContext
431  *
432  * This method is not called in performance-critical code paths, only when a
433  * new render target or swapchain is created. Thus performance is not an issue
434  * here.
435  *
436  * Params:
437  *  This: Device to add the context for
438  *  hdc: device context
439  *  glCtx: WGL context to add
440  *  pbuffer: optional pbuffer used with this context
441  *
442  *****************************************************************************/
443 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
444     WineD3DContext **oldArray = This->contexts;
445     DWORD state;
446
447     This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
448     if(This->contexts == NULL) {
449         ERR("Unable to grow the context array\n");
450         This->contexts = oldArray;
451         return NULL;
452     }
453     if(oldArray) {
454         memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
455     }
456
457     This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
458     if(This->contexts[This->numContexts] == NULL) {
459         ERR("Unable to allocate a new context\n");
460         HeapFree(GetProcessHeap(), 0, This->contexts);
461         This->contexts = oldArray;
462         return NULL;
463     }
464
465     This->contexts[This->numContexts]->hdc = hdc;
466     This->contexts[This->numContexts]->glCtx = glCtx;
467     This->contexts[This->numContexts]->pbuffer = pbuffer;
468     This->contexts[This->numContexts]->win_handle = win_handle;
469     HeapFree(GetProcessHeap(), 0, oldArray);
470
471     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
472      */
473     for(state = 0; state <= STATE_HIGHEST; state++) {
474         Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
475     }
476
477     This->numContexts++;
478     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
479     return This->contexts[This->numContexts - 1];
480 }
481
482 /* This function takes care of WineD3D pixel format selection. */
483 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
484         const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
485         BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
486 {
487     int iPixelFormat=0;
488     unsigned int matchtry;
489     short redBits, greenBits, blueBits, alphaBits, colorBits;
490     short depthBits=0, stencilBits=0;
491
492     struct match_type {
493         BOOL require_aux;
494         BOOL exact_alpha;
495         BOOL exact_color;
496     } matches[] = {
497         /* First, try without alpha match buffers. MacOS supports aux buffers only
498          * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
499          * Then try without aux buffers - this is the most common cause for not
500          * finding a pixel format. Also some drivers(the open source ones)
501          * only offer 32 bit ARB pixel formats. First try without an exact alpha
502          * match, then try without an exact alpha and color match.
503          */
504         { TRUE,  TRUE,  TRUE  },
505         { TRUE,  FALSE, TRUE  },
506         { FALSE, TRUE,  TRUE  },
507         { FALSE, FALSE, TRUE  },
508         { TRUE,  FALSE, FALSE },
509         { FALSE, FALSE, FALSE },
510     };
511
512     int i = 0;
513     int nCfgs = This->adapter->nCfgs;
514
515     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
516           debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
517           auxBuffers, numSamples, pbuffer, findCompatible);
518
519     if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
520     {
521         ERR("Unable to get color bits for format %s (%#x)!\n",
522                 debug_d3dformat(color_format_desc->format), color_format_desc->format);
523         return 0;
524     }
525
526     /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
527      * You are able to add a depth + stencil surface at a later stage when you need it.
528      * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
529      * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
530      * context, need torecreate shaders, textures and other resources.
531      *
532      * The context manager already takes care of the state problem and for the other tasks code from Reset
533      * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
534      * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
535      * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
536      * issue needs to be fixed. */
537     if (ds_format_desc->format != WINED3DFMT_D24S8)
538     {
539         FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
540         ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
541     }
542
543     getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
544
545     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
546         for(i=0; i<nCfgs; i++) {
547             BOOL exactDepthMatch = TRUE;
548             WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
549
550             /* For now only accept RGBA formats. Perhaps some day we will
551              * allow floating point formats for pbuffers. */
552             if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
553                 continue;
554
555             /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
556             if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
557                 continue;
558
559             /* We like to have aux buffers in backbuffer mode */
560             if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
561                 continue;
562
563             /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
564             if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
565                 continue;
566
567             if(matches[matchtry].exact_color) {
568                 if(cfg->redSize != redBits)
569                     continue;
570                 if(cfg->greenSize != greenBits)
571                     continue;
572                 if(cfg->blueSize != blueBits)
573                     continue;
574             } else {
575                 if(cfg->redSize < redBits)
576                     continue;
577                 if(cfg->greenSize < greenBits)
578                     continue;
579                 if(cfg->blueSize < blueBits)
580                     continue;
581             }
582             if(matches[matchtry].exact_alpha) {
583                 if(cfg->alphaSize != alphaBits)
584                     continue;
585             } else {
586                 if(cfg->alphaSize < alphaBits)
587                     continue;
588             }
589
590             /* We try to locate a format which matches our requirements exactly. In case of
591              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
592             if(cfg->depthSize < depthBits)
593                 continue;
594             else if(cfg->depthSize > depthBits)
595                 exactDepthMatch = FALSE;
596
597             /* In all cases make sure the number of stencil bits matches our requirements
598              * even when we don't need stencil because it could affect performance EXCEPT
599              * on cards which don't offer depth formats without stencil like the i915 drivers
600              * on Linux. */
601             if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
602                 continue;
603
604             /* Check multisampling support */
605             if(cfg->numSamples != numSamples)
606                 continue;
607
608             /* When we have passed all the checks then we have found a format which matches our
609              * requirements. Note that we only check for a limit number of capabilities right now,
610              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
611              * can still differ in things like multisampling, stereo, SRGB and other flags.
612              */
613
614             /* Exit the loop as we have found a format :) */
615             if(exactDepthMatch) {
616                 iPixelFormat = cfg->iPixelFormat;
617                 break;
618             } else if(!iPixelFormat) {
619                 /* In the end we might end up with a format which doesn't exactly match our depth
620                  * requirements. Accept the first format we found because formats with higher iPixelFormat
621                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
622                 iPixelFormat = cfg->iPixelFormat;
623             }
624         }
625     }
626
627     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
628     if(!iPixelFormat && !findCompatible) {
629         ERR("Can't find a suitable iPixelFormat\n");
630         return FALSE;
631     } else if(!iPixelFormat) {
632         PIXELFORMATDESCRIPTOR pfd;
633
634         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
635         /* PixelFormat selection */
636         ZeroMemory(&pfd, sizeof(pfd));
637         pfd.nSize      = sizeof(pfd);
638         pfd.nVersion   = 1;
639         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
640         pfd.iPixelType = PFD_TYPE_RGBA;
641         pfd.cAlphaBits = alphaBits;
642         pfd.cColorBits = colorBits;
643         pfd.cDepthBits = depthBits;
644         pfd.cStencilBits = stencilBits;
645         pfd.iLayerType = PFD_MAIN_PLANE;
646
647         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
648         if(!iPixelFormat) {
649             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
650             ERR("Can't find a suitable iPixelFormat\n");
651             return FALSE;
652         }
653     }
654
655     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
656             iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
657     return iPixelFormat;
658 }
659
660 /*****************************************************************************
661  * CreateContext
662  *
663  * Creates a new context for a window, or a pbuffer context.
664  *
665  * * Params:
666  *  This: Device to activate the context for
667  *  target: Surface this context will render to
668  *  win_handle: handle to the window which we are drawing to
669  *  create_pbuffer: tells whether to create a pbuffer or not
670  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
671  *
672  *****************************************************************************/
673 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
674     HDC oldDrawable, hdc;
675     HPBUFFERARB pbuffer = NULL;
676     HGLRC ctx = NULL, oldCtx;
677     WineD3DContext *ret = NULL;
678     unsigned int s;
679
680     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
681
682     if(create_pbuffer) {
683         HDC hdc_parent = GetDC(win_handle);
684         int iPixelFormat = 0;
685
686         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
687         const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
688                 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
689                 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
690
691         /* Try to find a pixel format with pbuffer support. */
692         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
693                 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
694                 FALSE /* findCompatible */);
695         if(!iPixelFormat) {
696             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
697
698             /* For some reason we weren't able to find a format, try to find something instead of crashing.
699              * A reason for failure could have been wglChoosePixelFormatARB strictness. */
700             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
701                     ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
702                     TRUE /* findCompatible */);
703         }
704
705         /* This shouldn't happen as ChoosePixelFormat always returns something */
706         if(!iPixelFormat) {
707             ERR("Unable to locate a pixel format for a pbuffer\n");
708             ReleaseDC(win_handle, hdc_parent);
709             goto out;
710         }
711
712         TRACE("Creating a pBuffer drawable for the new context\n");
713         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
714         if(!pbuffer) {
715             ERR("Cannot create a pbuffer\n");
716             ReleaseDC(win_handle, hdc_parent);
717             goto out;
718         }
719
720         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
721         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
722         if(!hdc) {
723             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
724             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
725             ReleaseDC(win_handle, hdc_parent);
726             goto out;
727         }
728         ReleaseDC(win_handle, hdc_parent);
729     } else {
730         PIXELFORMATDESCRIPTOR pfd;
731         int iPixelFormat;
732         int res;
733         const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
734         const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
735                 &This->adapter->gl_info);
736         BOOL auxBuffers = FALSE;
737         int numSamples = 0;
738
739         hdc = GetDC(win_handle);
740         if(hdc == NULL) {
741             ERR("Cannot retrieve a device context!\n");
742             goto out;
743         }
744
745         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
746         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
747             auxBuffers = TRUE;
748
749             if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
750                 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
751             else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
752                 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
753         }
754
755         /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
756          * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
757          * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
758          * a format with 8bit alpha, so request A8R8G8B8. */
759         if (color_format_desc->format == WINED3DFMT_P8)
760             color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
761
762         /* Retrieve the depth stencil format from the present parameters.
763          * The choice of the proper format can give a nice performance boost
764          * in case of GPU limited programs. */
765         if(pPresentParms->EnableAutoDepthStencil) {
766             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
767             ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
768         }
769
770         /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
771         if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
772             if(!GL_SUPPORT(ARB_MULTISAMPLE))
773                 ERR("The program is requesting multisampling without support!\n");
774             else {
775                 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
776                 numSamples = pPresentParms->MultiSampleType;
777             }
778         }
779
780         /* Try to find a pixel format which matches our requirements */
781         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
782                 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
783
784         /* Try to locate a compatible format if we weren't able to find anything */
785         if(!iPixelFormat) {
786             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
787             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
788                     auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
789         }
790
791         /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
792         if(!iPixelFormat) {
793             ERR("Can't find a suitable iPixelFormat\n");
794             return FALSE;
795         }
796
797         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
798         res = SetPixelFormat(hdc, iPixelFormat, NULL);
799         if(!res) {
800             int oldPixelFormat = GetPixelFormat(hdc);
801
802             /* By default WGL doesn't allow pixel format adjustments but we need it here.
803              * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
804              * set the pixel format multiple times. Only use it when it is really needed. */
805
806             if(oldPixelFormat == iPixelFormat) {
807                 /* We don't have to do anything as the formats are the same :) */
808             } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
809                 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
810
811                 if(!res) {
812                     ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
813                     return FALSE;
814                 }
815             } else if(oldPixelFormat) {
816                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
817                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
818                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
819             } else {
820                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
821                 return FALSE;
822             }
823         }
824     }
825
826     ctx = pwglCreateContext(hdc);
827     if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
828
829     if(!ctx) {
830         ERR("Failed to create a WGL context\n");
831         if(create_pbuffer) {
832             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
833             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
834         }
835         goto out;
836     }
837     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
838     if(!ret) {
839         ERR("Failed to add the newly created context to the context list\n");
840         pwglDeleteContext(ctx);
841         if(create_pbuffer) {
842             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
843             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
844         }
845         goto out;
846     }
847     ret->surface = (IWineD3DSurface *) target;
848     ret->isPBuffer = create_pbuffer;
849     ret->tid = GetCurrentThreadId();
850     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
851         /* Create the dirty constants array and initialize them to dirty */
852         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
853                 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
854         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
855                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
856         memset(ret->vshader_const_dirty, 1,
857                sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
858         memset(ret->pshader_const_dirty, 1,
859                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
860     }
861
862     TRACE("Successfully created new context %p\n", ret);
863
864     list_init(&ret->fbo_list);
865
866     /* Set up the context defaults */
867     oldCtx  = pwglGetCurrentContext();
868     oldDrawable = pwglGetCurrentDC();
869     if(oldCtx && oldDrawable) {
870         /* See comment in ActivateContext context switching */
871         This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
872     }
873     if(pwglMakeCurrent(hdc, ctx) == FALSE) {
874         ERR("Cannot activate context to set up defaults\n");
875         goto out;
876     }
877
878     ENTER_GL();
879
880     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
881
882     TRACE("Setting up the screen\n");
883     /* Clear the screen */
884     glClearColor(1.0, 0.0, 0.0, 0.0);
885     checkGLcall("glClearColor");
886     glClearIndex(0);
887     glClearDepth(1);
888     glClearStencil(0xffff);
889
890     checkGLcall("glClear");
891
892     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
893     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
894
895     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
896     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
897
898     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
899     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
900
901     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
902     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
903     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
904     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
905
906     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
907         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
908          * and textures in DIB sections(due to the memory protection).
909          */
910         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
911         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
912     }
913     if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
914         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
915          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
916          * GL_VERTEX_BLEND_ARB isn't enabled too
917          */
918         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
919         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
920     }
921     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
922         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
923          * the previous texture where to source the offset from is always unit - 1.
924          */
925         for(s = 1; s < GL_LIMITS(textures); s++) {
926             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
927             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
928             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
929         }
930     }
931
932     for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
933         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
934         glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
935         checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
936     }
937     LEAVE_GL();
938
939     /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
940      * but enable it for the first context we create, and reenable it on the old context
941      */
942     if(oldDrawable && oldCtx) {
943         pwglMakeCurrent(oldDrawable, oldCtx);
944     } else {
945         last_device = This;
946     }
947     This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
948
949     return ret;
950
951 out:
952     return NULL;
953 }
954
955 /*****************************************************************************
956  * RemoveContextFromArray
957  *
958  * Removes a context from the context manager. The opengl context is not
959  * destroyed or unset. context is not a valid pointer after that call.
960  *
961  * Similar to the former call this isn't a performance critical function. A
962  * helper function for DestroyContext.
963  *
964  * Params:
965  *  This: Device to activate the context for
966  *  context: Context to remove
967  *
968  *****************************************************************************/
969 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
970     WineD3DContext **new_array;
971     BOOL found = FALSE;
972     UINT i;
973
974     TRACE("Removing ctx %p\n", context);
975
976     for (i = 0; i < This->numContexts; ++i)
977     {
978         if (This->contexts[i] == context)
979         {
980             HeapFree(GetProcessHeap(), 0, context);
981             found = TRUE;
982             break;
983         }
984     }
985
986     if (!found)
987     {
988         ERR("Context %p doesn't exist in context array\n", context);
989         return;
990     }
991
992     while (i < This->numContexts - 1)
993     {
994         This->contexts[i] = This->contexts[i + 1];
995         ++i;
996     }
997
998     --This->numContexts;
999     if (!This->numContexts)
1000     {
1001         HeapFree(GetProcessHeap(), 0, This->contexts);
1002         This->contexts = NULL;
1003         return;
1004     }
1005
1006     new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1007     if (!new_array)
1008     {
1009         ERR("Failed to shrink context array. Oh well.\n");
1010         return;
1011     }
1012
1013     This->contexts = new_array;
1014 }
1015
1016 /*****************************************************************************
1017  * DestroyContext
1018  *
1019  * Destroys a wineD3DContext
1020  *
1021  * Params:
1022  *  This: Device to activate the context for
1023  *  context: Context to destroy
1024  *
1025  *****************************************************************************/
1026 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
1027     struct fbo_entry *entry, *entry2;
1028
1029     TRACE("Destroying ctx %p\n", context);
1030
1031     /* The correct GL context needs to be active to cleanup the GL resources below */
1032     if(pwglGetCurrentContext() != context->glCtx){
1033         pwglMakeCurrent(context->hdc, context->glCtx);
1034         last_device = NULL;
1035     }
1036
1037     ENTER_GL();
1038
1039     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1040         context_destroy_fbo_entry(This, entry);
1041     }
1042     if (context->src_fbo) {
1043         TRACE("Destroy src FBO %d\n", context->src_fbo);
1044         context_destroy_fbo(This, &context->src_fbo);
1045     }
1046     if (context->dst_fbo) {
1047         TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1048         context_destroy_fbo(This, &context->dst_fbo);
1049     }
1050
1051     LEAVE_GL();
1052
1053     if (This->activeContext == context)
1054     {
1055         This->activeContext = NULL;
1056         TRACE("Destroying the active context.\n");
1057     }
1058
1059     /* Cleanup the GL context */
1060     pwglMakeCurrent(NULL, NULL);
1061     if(context->isPBuffer) {
1062         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1063         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1064     } else ReleaseDC(context->win_handle, context->hdc);
1065     pwglDeleteContext(context->glCtx);
1066
1067     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1068     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1069     RemoveContextFromArray(This, context);
1070 }
1071
1072 static inline void set_blit_dimension(UINT width, UINT height) {
1073     glMatrixMode(GL_PROJECTION);
1074     checkGLcall("glMatrixMode(GL_PROJECTION)");
1075     glLoadIdentity();
1076     checkGLcall("glLoadIdentity()");
1077     glOrtho(0, width, height, 0, 0.0, -1.0);
1078     checkGLcall("glOrtho");
1079     glViewport(0, 0, width, height);
1080     checkGLcall("glViewport");
1081 }
1082
1083 /*****************************************************************************
1084  * SetupForBlit
1085  *
1086  * Sets up a context for DirectDraw blitting.
1087  * All texture units are disabled, texture unit 0 is set as current unit
1088  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1089  * color writing enabled for all channels
1090  * register combiners disabled, shaders disabled
1091  * world matrix is set to identity, texture matrix 0 too
1092  * projection matrix is setup for drawing screen coordinates
1093  *
1094  * Params:
1095  *  This: Device to activate the context for
1096  *  context: Context to setup
1097  *  width: render target width
1098  *  height: render target height
1099  *
1100  *****************************************************************************/
1101 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1102     int i, sampler;
1103     const struct StateEntry *StateTable = This->StateTable;
1104
1105     TRACE("Setting up context %p for blitting\n", context);
1106     if(context->last_was_blit) {
1107         if(context->blit_w != width || context->blit_h != height) {
1108             set_blit_dimension(width, height);
1109             context->blit_w = width; context->blit_h = height;
1110             /* No need to dirtify here, the states are still dirtified because they weren't
1111              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1112              * be set
1113              */
1114         }
1115         TRACE("Context is already set up for blitting, nothing to do\n");
1116         return;
1117     }
1118     context->last_was_blit = TRUE;
1119
1120     /* TODO: Use a display list */
1121
1122     /* Disable shaders */
1123     ENTER_GL();
1124     This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1125     LEAVE_GL();
1126
1127     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1128     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1129
1130     /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1131      * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1132      * which can safely be called from here, we only lock once instead locking/unlocking
1133      * after each GL call.
1134      */
1135     ENTER_GL();
1136
1137     /* Disable all textures. The caller can then bind a texture it wants to blit
1138      * from
1139      *
1140      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1141      * function texture unit. No need to care for higher samplers
1142      */
1143     for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1144         sampler = This->rev_tex_unit_map[i];
1145         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1146         checkGLcall("glActiveTextureARB");
1147
1148         if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1149             glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1150             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1151         }
1152         glDisable(GL_TEXTURE_3D);
1153         checkGLcall("glDisable GL_TEXTURE_3D");
1154         if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1155             glDisable(GL_TEXTURE_RECTANGLE_ARB);
1156             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1157         }
1158         glDisable(GL_TEXTURE_2D);
1159         checkGLcall("glDisable GL_TEXTURE_2D");
1160
1161         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1162         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1163
1164         if (sampler != -1) {
1165             if (sampler < MAX_TEXTURES) {
1166                 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1167             }
1168             Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1169         }
1170     }
1171     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1172     checkGLcall("glActiveTextureARB");
1173
1174     sampler = This->rev_tex_unit_map[0];
1175
1176     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1177         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1178         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1179     }
1180     glDisable(GL_TEXTURE_3D);
1181     checkGLcall("glDisable GL_TEXTURE_3D");
1182     if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1183         glDisable(GL_TEXTURE_RECTANGLE_ARB);
1184         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1185     }
1186     glDisable(GL_TEXTURE_2D);
1187     checkGLcall("glDisable GL_TEXTURE_2D");
1188
1189     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1190
1191     glMatrixMode(GL_TEXTURE);
1192     checkGLcall("glMatrixMode(GL_TEXTURE)");
1193     glLoadIdentity();
1194     checkGLcall("glLoadIdentity()");
1195
1196     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1197         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1198                   GL_TEXTURE_LOD_BIAS_EXT,
1199                   0.0);
1200         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1201     }
1202
1203     if (sampler != -1) {
1204         if (sampler < MAX_TEXTURES) {
1205             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1206             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1207         }
1208         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1209     }
1210
1211     /* Other misc states */
1212     glDisable(GL_ALPHA_TEST);
1213     checkGLcall("glDisable(GL_ALPHA_TEST)");
1214     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1215     glDisable(GL_LIGHTING);
1216     checkGLcall("glDisable GL_LIGHTING");
1217     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1218     glDisable(GL_DEPTH_TEST);
1219     checkGLcall("glDisable GL_DEPTH_TEST");
1220     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1221     glDisableWINE(GL_FOG);
1222     checkGLcall("glDisable GL_FOG");
1223     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1224     glDisable(GL_BLEND);
1225     checkGLcall("glDisable GL_BLEND");
1226     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1227     glDisable(GL_CULL_FACE);
1228     checkGLcall("glDisable GL_CULL_FACE");
1229     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1230     glDisable(GL_STENCIL_TEST);
1231     checkGLcall("glDisable GL_STENCIL_TEST");
1232     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1233     glDisable(GL_SCISSOR_TEST);
1234     checkGLcall("glDisable GL_SCISSOR_TEST");
1235     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1236     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1237         glDisable(GL_POINT_SPRITE_ARB);
1238         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1239         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1240     }
1241     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1242     checkGLcall("glColorMask");
1243     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1244     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1245         glDisable(GL_COLOR_SUM_EXT);
1246         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1247         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1248     }
1249
1250     /* Setup transforms */
1251     glMatrixMode(GL_MODELVIEW);
1252     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1253     glLoadIdentity();
1254     checkGLcall("glLoadIdentity()");
1255     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1256
1257     context->last_was_rhw = TRUE;
1258     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1259
1260     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1261     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1262     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1263     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1264     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1265     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1266     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1267     LEAVE_GL();
1268
1269     set_blit_dimension(width, height);
1270     context->blit_w = width; context->blit_h = height;
1271     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1272     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1273
1274
1275     This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1276 }
1277
1278 /*****************************************************************************
1279  * findThreadContextForSwapChain
1280  *
1281  * Searches a swapchain for all contexts and picks one for the thread tid.
1282  * If none can be found the swapchain is requested to create a new context
1283  *
1284  *****************************************************************************/
1285 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1286     unsigned int i;
1287
1288     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1289         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1290             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1291         }
1292
1293     }
1294
1295     /* Create a new context for the thread */
1296     return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1297 }
1298
1299 /*****************************************************************************
1300  * FindContext
1301  *
1302  * Finds a context for the current render target and thread
1303  *
1304  * Parameters:
1305  *  target: Render target to find the context for
1306  *  tid: Thread to activate the context for
1307  *
1308  * Returns: The needed context
1309  *
1310  *****************************************************************************/
1311 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1312     IWineD3DSwapChain *swapchain = NULL;
1313     BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1314     WineD3DContext *context = This->activeContext;
1315     BOOL oldRenderOffscreen = This->render_offscreen;
1316     const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1317     const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1318     const struct StateEntry *StateTable = This->StateTable;
1319
1320     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1321      * the alpha blend state changes with different render target formats
1322      */
1323     if (old->format != new->format)
1324     {
1325         /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1326         if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1327                 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1328         {
1329             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1330         }
1331     }
1332
1333     if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1334         TRACE("Rendering onscreen\n");
1335
1336         context = findThreadContextForSwapChain(swapchain, tid);
1337
1338         This->render_offscreen = FALSE;
1339         /* The context != This->activeContext will catch a NOP context change. This can occur
1340          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1341          * rendering. No context change is needed in that case
1342          */
1343
1344         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1345             if(This->pbufferContext && tid == This->pbufferContext->tid) {
1346                 This->pbufferContext->tid = 0;
1347             }
1348         }
1349         IWineD3DSwapChain_Release(swapchain);
1350
1351         if(oldRenderOffscreen) {
1352             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1353             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1354             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1355             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1356             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1357         }
1358
1359     } else {
1360         TRACE("Rendering offscreen\n");
1361         This->render_offscreen = TRUE;
1362
1363         switch(wined3d_settings.offscreen_rendering_mode) {
1364             case ORM_FBO:
1365                 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1366                 if(This->activeContext && tid == This->lastThread) {
1367                     context = This->activeContext;
1368                 } else {
1369                     /* This may happen if the app jumps straight into offscreen rendering
1370                      * Start using the context of the primary swapchain. tid == 0 is no problem
1371                      * for findThreadContextForSwapChain.
1372                      *
1373                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
1374                      * is perfect to call.
1375                      */
1376                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
1377                 }
1378                 break;
1379
1380             case ORM_PBUFFER:
1381             {
1382                 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1383                 if(This->pbufferContext == NULL ||
1384                    This->pbufferWidth < targetimpl->currentDesc.Width ||
1385                    This->pbufferHeight < targetimpl->currentDesc.Height) {
1386                     if(This->pbufferContext) {
1387                         DestroyContext(This, This->pbufferContext);
1388                     }
1389
1390                     /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1391                      * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1392                      */
1393                     This->pbufferContext = CreateContext(This, targetimpl,
1394                             ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1395                             TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1396                     This->pbufferWidth = targetimpl->currentDesc.Width;
1397                     This->pbufferHeight = targetimpl->currentDesc.Height;
1398                    }
1399
1400                    if(This->pbufferContext) {
1401                        if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1402                            FIXME("The PBuffr context is only supported for one thread for now!\n");
1403                        }
1404                        This->pbufferContext->tid = tid;
1405                        context = This->pbufferContext;
1406                        break;
1407                    } else {
1408                        ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1409                        wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1410                    }
1411             }
1412
1413             case ORM_BACKBUFFER:
1414                 /* Stay with the currently active context for back buffer rendering */
1415                 if(This->activeContext && tid == This->lastThread) {
1416                     context = This->activeContext;
1417                 } else {
1418                     /* This may happen if the app jumps straight into offscreen rendering
1419                      * Start using the context of the primary swapchain. tid == 0 is no problem
1420                      * for findThreadContextForSwapChain.
1421                      *
1422                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
1423                      * is perfect to call.
1424                      */
1425                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
1426                 }
1427                 break;
1428         }
1429
1430         if(!oldRenderOffscreen) {
1431             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1432             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1433             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1434             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1435             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1436         }
1437     }
1438
1439     /* When switching away from an offscreen render target, and we're not using FBOs,
1440      * we have to read the drawable into the texture. This is done via PreLoad(and
1441      * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1442      * PreLoad needs a GL context, and FindContext is called before the context is activated.
1443      * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1444      * is read. This leads to these possible situations:
1445      *
1446      * 0) lastActiveRenderTarget == target && oldTid == newTid:
1447      *    Nothing to do, we don't even reach this code in this case...
1448      *
1449      * 1) lastActiveRenderTarget != target && oldTid == newTid:
1450      *    The currently active context is OK for readback. Call PreLoad, and it
1451      *    performs the read
1452      *
1453      * 2) lastActiveRenderTarget == target && oldTid != newTid:
1454      *    Nothing to do - the drawable is unchanged
1455      *
1456      * 3) lastActiveRenderTarget != target && oldTid != newTid:
1457      *    This is tricky. We have to get a context with the old drawable from somewhere
1458      *    before we can switch to the new context. In this case, PreLoad calls
1459      *    ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1460      *    is case (2) then. The old drawable is activated for the new thread, and the
1461      *    readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1462      *    After that, the outer ActivateContext(which calls PreLoad) can activate the new
1463      *    target for the new thread
1464      */
1465     if (readTexture && This->lastActiveRenderTarget != target) {
1466         BOOL oldInDraw = This->isInDraw;
1467
1468         /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1469          * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1470          * when using offscreen rendering with multithreading
1471          */
1472         This->isInDraw = TRUE;
1473
1474         /* Do that before switching the context:
1475          * Read the back buffer of the old drawable into the destination texture
1476          */
1477         if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1478             surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1479         } else {
1480             surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1481         }
1482
1483         /* Assume that the drawable will be modified by some other things now */
1484         IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1485
1486         This->isInDraw = oldInDraw;
1487     }
1488
1489     return context;
1490 }
1491
1492 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1493 {
1494     IWineD3DSwapChain *swapchain;
1495
1496     if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1497     {
1498         IWineD3DSwapChain_Release((IUnknown *)swapchain);
1499         ENTER_GL();
1500         glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1501         checkGLcall("glDrawBuffers()");
1502         LEAVE_GL();
1503     }
1504     else
1505     {
1506         ENTER_GL();
1507         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1508         {
1509             if (!blit)
1510             {
1511                 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1512                 {
1513                     GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1514                     checkGLcall("glDrawBuffers()");
1515                 }
1516                 else
1517                 {
1518                     glDrawBuffer(This->draw_buffers[0]);
1519                     checkGLcall("glDrawBuffer()");
1520                 }
1521             } else {
1522                 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1523                 checkGLcall("glDrawBuffer()");
1524             }
1525         }
1526         else
1527         {
1528             glDrawBuffer(This->offscreenBuffer);
1529             checkGLcall("glDrawBuffer()");
1530         }
1531         LEAVE_GL();
1532     }
1533 }
1534
1535 /*****************************************************************************
1536  * ActivateContext
1537  *
1538  * Finds a rendering context and drawable matching the device and render
1539  * target for the current thread, activates them and puts them into the
1540  * requested state.
1541  *
1542  * Params:
1543  *  This: Device to activate the context for
1544  *  target: Requested render target
1545  *  usage: Prepares the context for blitting, drawing or other actions
1546  *
1547  *****************************************************************************/
1548 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1549     DWORD                         tid = GetCurrentThreadId();
1550     DWORD                         i, dirtyState, idx;
1551     BYTE                          shift;
1552     WineD3DContext                *context;
1553     const struct StateEntry       *StateTable = This->StateTable;
1554
1555     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1556     if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1557         context = FindContext(This, target, tid);
1558         context->draw_buffer_dirty = TRUE;
1559         This->lastActiveRenderTarget = target;
1560         This->lastThread = tid;
1561     } else {
1562         /* Stick to the old context */
1563         context = This->activeContext;
1564     }
1565
1566     /* Activate the opengl context */
1567     if(last_device != This || context != This->activeContext) {
1568         BOOL ret;
1569
1570         /* Prevent an unneeded context switch as those are expensive */
1571         if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1572             TRACE("Already using gl context %p\n", context->glCtx);
1573         }
1574         else {
1575             TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1576
1577             ret = pwglMakeCurrent(context->hdc, context->glCtx);
1578             if(ret == FALSE) {
1579                 ERR("Failed to activate the new context\n");
1580             } else if(!context->last_was_blit) {
1581                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1582             } else {
1583                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1584             }
1585         }
1586         if(This->activeContext->vshader_const_dirty) {
1587             memset(This->activeContext->vshader_const_dirty, 1,
1588                    sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1589         }
1590         if(This->activeContext->pshader_const_dirty) {
1591             memset(This->activeContext->pshader_const_dirty, 1,
1592                    sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1593         }
1594         This->activeContext = context;
1595         last_device = This;
1596     }
1597
1598     switch (usage) {
1599         case CTXUSAGE_CLEAR:
1600         case CTXUSAGE_DRAWPRIM:
1601             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1602                 context_apply_fbo_state((IWineD3DDevice *)This);
1603             }
1604             if (context->draw_buffer_dirty) {
1605                 apply_draw_buffer(This, target, FALSE);
1606                 context->draw_buffer_dirty = FALSE;
1607             }
1608             break;
1609
1610         case CTXUSAGE_BLIT:
1611             if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1612                 if (This->render_offscreen) {
1613                     FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1614                     context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1615                     context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1616
1617                     ENTER_GL();
1618                     GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1619                     checkGLcall("glFramebufferRenderbufferEXT");
1620                     LEAVE_GL();
1621                 } else {
1622                     ENTER_GL();
1623                     GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1624                     checkGLcall("glFramebufferRenderbufferEXT");
1625                     LEAVE_GL();
1626                 }
1627                 context->draw_buffer_dirty = TRUE;
1628             }
1629             if (context->draw_buffer_dirty) {
1630                 apply_draw_buffer(This, target, TRUE);
1631                 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1632                     context->draw_buffer_dirty = FALSE;
1633                 }
1634             }
1635             break;
1636
1637         default:
1638             break;
1639     }
1640
1641     switch(usage) {
1642         case CTXUSAGE_RESOURCELOAD:
1643             /* This does not require any special states to be set up */
1644             break;
1645
1646         case CTXUSAGE_CLEAR:
1647             if(context->last_was_blit) {
1648                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1649             }
1650
1651             /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1652              * blending when clearing improves the clearing performance incredibly.
1653              */
1654             ENTER_GL();
1655             glDisable(GL_BLEND);
1656             LEAVE_GL();
1657             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1658
1659             ENTER_GL();
1660             glEnable(GL_SCISSOR_TEST);
1661             checkGLcall("glEnable GL_SCISSOR_TEST");
1662             LEAVE_GL();
1663             context->last_was_blit = FALSE;
1664             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1665             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1666             break;
1667
1668         case CTXUSAGE_DRAWPRIM:
1669             /* This needs all dirty states applied */
1670             if(context->last_was_blit) {
1671                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1672             }
1673
1674             IWineD3DDeviceImpl_FindTexUnitMap(This);
1675
1676             ENTER_GL();
1677             for(i=0; i < context->numDirtyEntries; i++) {
1678                 dirtyState = context->dirtyArray[i];
1679                 idx = dirtyState >> 5;
1680                 shift = dirtyState & 0x1f;
1681                 context->isStateDirty[idx] &= ~(1 << shift);
1682                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1683             }
1684             LEAVE_GL();
1685             context->numDirtyEntries = 0; /* This makes the whole list clean */
1686             context->last_was_blit = FALSE;
1687             break;
1688
1689         case CTXUSAGE_BLIT:
1690             SetupForBlit(This, context,
1691                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1692                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1693             break;
1694
1695         default:
1696             FIXME("Unexpected context usage requested\n");
1697     }
1698 }
1699
1700 WineD3DContext *getActiveContext(void) {
1701     return last_device->activeContext;
1702 }