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