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