quartz: Fix discontinuities in wave parser.
[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 /*****************************************************************************
33  * Context_MarkStateDirty
34  *
35  * Marks a state in a context dirty. Only one context, opposed to
36  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
37  * contexts
38  *
39  * Params:
40  *  context: Context to mark the state dirty in
41  *  state: State to mark dirty
42  *  StateTable: Pointer to the state table in use(for state grouping)
43  *
44  *****************************************************************************/
45 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
46     DWORD rep = StateTable[state].representative;
47     DWORD idx;
48     BYTE shift;
49
50     if(!rep || isStateDirty(context, rep)) return;
51
52     context->dirtyArray[context->numDirtyEntries++] = rep;
53     idx = rep >> 5;
54     shift = rep & 0x1f;
55     context->isStateDirty[idx] |= (1 << shift);
56 }
57
58 /*****************************************************************************
59  * AddContextToArray
60  *
61  * Adds a context to the context array. Helper function for CreateContext
62  *
63  * This method is not called in performance-critical code paths, only when a
64  * new render target or swapchain is created. Thus performance is not an issue
65  * here.
66  *
67  * Params:
68  *  This: Device to add the context for
69  *  hdc: device context
70  *  glCtx: WGL context to add
71  *  pbuffer: optional pbuffer used with this context
72  *
73  *****************************************************************************/
74 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
75     WineD3DContext **oldArray = This->contexts;
76     DWORD state;
77
78     This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
79     if(This->contexts == NULL) {
80         ERR("Unable to grow the context array\n");
81         This->contexts = oldArray;
82         return NULL;
83     }
84     if(oldArray) {
85         memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
86     }
87
88     This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
89     if(This->contexts[This->numContexts] == NULL) {
90         ERR("Unable to allocate a new context\n");
91         HeapFree(GetProcessHeap(), 0, This->contexts);
92         This->contexts = oldArray;
93         return NULL;
94     }
95
96     This->contexts[This->numContexts]->hdc = hdc;
97     This->contexts[This->numContexts]->glCtx = glCtx;
98     This->contexts[This->numContexts]->pbuffer = pbuffer;
99     This->contexts[This->numContexts]->win_handle = win_handle;
100     HeapFree(GetProcessHeap(), 0, oldArray);
101
102     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
103      */
104     for(state = 0; state <= STATE_HIGHEST; state++) {
105         Context_MarkStateDirty(This->contexts[This->numContexts], state, This->shader_backend->StateTable);
106     }
107
108     This->numContexts++;
109     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
110     return This->contexts[This->numContexts - 1];
111 }
112
113 /*****************************************************************************
114  * CreateContext
115  *
116  * Creates a new context for a window, or a pbuffer context.
117  *
118  * * Params:
119  *  This: Device to activate the context for
120  *  target: Surface this context will render to
121  *  win_handle: handle to the window which we are drawing to
122  *  create_pbuffer: tells whether to create a pbuffer or not
123  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
124  *
125  *****************************************************************************/
126 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
127     HDC oldDrawable, hdc;
128     HPBUFFERARB pbuffer = NULL;
129     HGLRC ctx = NULL, oldCtx;
130     WineD3DContext *ret = NULL;
131     int s;
132
133     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
134
135 #define PUSH1(att)        attribs[nAttribs++] = (att);
136 #define PUSH2(att,value)  attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);
137     if(create_pbuffer) {
138         HDC hdc_parent = GetDC(win_handle);
139         int iPixelFormat = 0;
140         short redBits, greenBits, blueBits, alphaBits, colorBits;
141         short depthBits, stencilBits;
142
143         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
144         WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
145
146         int attribs[256];
147         int nAttribs = 0;
148         unsigned int nFormats;
149
150         /* Retrieve the specifications for the pixelformat from the backbuffer / stencilbuffer */
151         getColorBits(target->resource.format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits);
152         getDepthStencilBits(StencilBufferFormat, &depthBits, &stencilBits);
153         PUSH2(WGL_DRAW_TO_PBUFFER_ARB, 1); /* We need pbuffer support; doublebuffering isn't needed */
154         PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
155         PUSH2(WGL_COLOR_BITS_ARB, colorBits);
156         PUSH2(WGL_RED_BITS_ARB, redBits);
157         PUSH2(WGL_GREEN_BITS_ARB, greenBits);
158         PUSH2(WGL_BLUE_BITS_ARB, blueBits);
159         PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
160         PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
161         PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
162         PUSH1(0); /* end the list */
163
164         /* Try to find a pixelformat that matches exactly. If that fails let ChoosePixelFormat try to find a close match */
165         if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc_parent, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
166         {
167             PIXELFORMATDESCRIPTOR pfd;
168
169             TRACE("Falling back to ChoosePixelFormat as wglChoosePixelFormatARB failed\n");
170
171             ZeroMemory(&pfd, sizeof(pfd));
172             pfd.nSize      = sizeof(pfd);
173             pfd.nVersion   = 1;
174             pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER_DONTCARE | PFD_DRAW_TO_WINDOW;
175             pfd.iPixelType = PFD_TYPE_RGBA;
176             pfd.cColorBits = colorBits;
177             pfd.cDepthBits = depthBits;
178             pfd.cStencilBits = stencilBits;
179             pfd.iLayerType = PFD_MAIN_PLANE;
180
181             iPixelFormat = ChoosePixelFormat(hdc_parent, &pfd);
182             if(!iPixelFormat) {
183                 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
184                 ERR("Can't find a suitable iPixelFormat for the pbuffer\n");
185             }
186         }
187
188         TRACE("Creating a pBuffer drawable for the new context\n");
189         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
190         if(!pbuffer) {
191             ERR("Cannot create a pbuffer\n");
192             ReleaseDC(win_handle, hdc_parent);
193             goto out;
194         }
195
196         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
197         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
198         if(!hdc) {
199             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
200             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
201             ReleaseDC(win_handle, hdc_parent);
202             goto out;
203         }
204         ReleaseDC(win_handle, hdc_parent);
205     } else {
206         PIXELFORMATDESCRIPTOR pfd;
207         int iPixelFormat;
208         short redBits, greenBits, blueBits, alphaBits, colorBits;
209         short depthBits=0, stencilBits=0;
210         int res;
211         int attribs[256];
212         int nAttribs = 0;
213         unsigned int nFormats;
214         WINED3DFORMAT fmt = target->resource.format;
215
216         hdc = GetDC(win_handle);
217         if(hdc == NULL) {
218             ERR("Cannot retrieve a device context!\n");
219             goto out;
220         }
221
222         /* PixelFormat selection */
223         PUSH2(WGL_DRAW_TO_WINDOW_ARB, GL_TRUE); /* We want to draw to a window */
224         PUSH2(WGL_DOUBLE_BUFFER_ARB, GL_TRUE);
225         PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
226         PUSH2(WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
227         PUSH2(WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB); /* Make sure we receive an accelerated format. On windows (at least on ATI) this is not always the case */
228
229         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
230         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
231             if(target->resource.format == WINED3DFMT_X4R4G4B4)
232                 fmt = WINED3DFMT_A4R4G4B4;
233             else if(target->resource.format == WINED3DFMT_X8R8G8B8)
234                 fmt = WINED3DFMT_A8R8G8B8;
235
236             /* We like to have two aux buffers in backbuffer mode */
237             PUSH2(WGL_AUX_BUFFERS_ARB, 2);
238         }
239
240         /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
241          * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
242          * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
243          * a format with 8bit alpha, so request A8R8G8B8. */
244         if(fmt == WINED3DFMT_P8)
245             fmt = WINED3DFMT_A8R8G8B8;
246
247         if(!getColorBits(fmt, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
248             ERR("Unable to get color bits for format %#x!\n", target->resource.format);
249             return FALSE;
250         }
251         PUSH2(WGL_COLOR_BITS_ARB, colorBits);
252         PUSH2(WGL_RED_BITS_ARB, redBits);
253         PUSH2(WGL_GREEN_BITS_ARB, greenBits);
254         PUSH2(WGL_BLUE_BITS_ARB, blueBits);
255         PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
256
257         /* Retrieve the depth stencil format from the present parameters.
258          * The choice of the proper format can give a nice performance boost
259          * in case of GPU limited programs. */
260         if(pPresentParms->EnableAutoDepthStencil) {
261             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
262             if(!getDepthStencilBits(pPresentParms->AutoDepthStencilFormat, &depthBits, &stencilBits)) {
263                 ERR("Unable to get depth / stencil bits for AutoDepthStencilFormat %#x!\n", pPresentParms->AutoDepthStencilFormat);
264                 return FALSE;
265             }
266             PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
267             PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
268         }
269
270         PUSH1(0); /* end the list */
271
272         /* In case of failure hope that standard ChoosePixelFormat will find something suitable */
273         if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
274         {
275             /* PixelFormat selection */
276             ZeroMemory(&pfd, sizeof(pfd));
277             pfd.nSize      = sizeof(pfd);
278             pfd.nVersion   = 1;
279             pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
280             pfd.iPixelType = PFD_TYPE_RGBA;
281             pfd.cAlphaBits = alphaBits;
282             pfd.cColorBits = colorBits;
283             pfd.cDepthBits = depthBits;
284             pfd.cStencilBits = stencilBits;
285             pfd.iLayerType = PFD_MAIN_PLANE;
286
287             iPixelFormat = ChoosePixelFormat(hdc, &pfd);
288             if(!iPixelFormat) {
289                 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
290                 ERR("Can't find a suitable iPixelFormat\n");
291             }
292         }
293
294         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
295         res = SetPixelFormat(hdc, iPixelFormat, NULL);
296         if(!res) {
297             int oldPixelFormat = GetPixelFormat(hdc);
298
299             if(oldPixelFormat) {
300                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
301                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
302                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
303             }
304             else {
305                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
306                 return FALSE;
307             }
308         }
309     }
310 #undef PUSH1
311 #undef PUSH2
312
313     ctx = pwglCreateContext(hdc);
314     if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
315
316     if(!ctx) {
317         ERR("Failed to create a WGL context\n");
318         if(create_pbuffer) {
319             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
320             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
321         }
322         goto out;
323     }
324     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
325     if(!ret) {
326         ERR("Failed to add the newly created context to the context list\n");
327         pwglDeleteContext(ctx);
328         if(create_pbuffer) {
329             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
330             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
331         }
332         goto out;
333     }
334     ret->surface = (IWineD3DSurface *) target;
335     ret->isPBuffer = create_pbuffer;
336     ret->tid = GetCurrentThreadId();
337     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
338         /* Create the dirty constants array and initialize them to dirty */
339         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
340                 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
341         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
342                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
343         memset(ret->vshader_const_dirty, 1,
344                sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
345         memset(ret->pshader_const_dirty, 1,
346                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
347     }
348
349     TRACE("Successfully created new context %p\n", ret);
350
351     /* Set up the context defaults */
352     oldCtx  = pwglGetCurrentContext();
353     oldDrawable = pwglGetCurrentDC();
354     if(oldCtx && oldDrawable && GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
355         /* See comment in ActivateContext context switching */
356         glDisable(GL_FRAGMENT_SHADER_ATI);
357         checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
358     }
359     if(pwglMakeCurrent(hdc, ctx) == FALSE) {
360         ERR("Cannot activate context to set up defaults\n");
361         goto out;
362     }
363
364     ENTER_GL();
365
366     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
367
368     TRACE("Setting up the screen\n");
369     /* Clear the screen */
370     glClearColor(1.0, 0.0, 0.0, 0.0);
371     checkGLcall("glClearColor");
372     glClearIndex(0);
373     glClearDepth(1);
374     glClearStencil(0xffff);
375
376     checkGLcall("glClear");
377
378     glColor3f(1.0, 1.0, 1.0);
379     checkGLcall("glColor3f");
380
381     glEnable(GL_LIGHTING);
382     checkGLcall("glEnable");
383
384     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
385     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
386
387     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
388     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
389
390     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
391     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
392
393     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
394     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
395     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
396     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
397
398     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
399         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
400          * and textures in DIB sections(due to the memory protection).
401          */
402         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
403         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
404     }
405     if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
406         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
407          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
408          * GL_VERTEX_BLEND_ARB isn't enabled too
409          */
410         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
411         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
412     }
413     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
414         glEnable(GL_TEXTURE_SHADER_NV);
415         checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
416
417         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
418          * the previous texture where to source the offset from is always unit - 1.
419          */
420         for(s = 1; s < GL_LIMITS(textures); s++) {
421             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
422             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
423             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
424         }
425     }
426
427     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
428         for(s = 0; s < GL_LIMITS(textures); s++) {
429             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
430             glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
431             checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
432         }
433     }
434     LEAVE_GL();
435
436     /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
437      * but enable it for the first context we create, and reenable it on the old context
438      */
439     if(oldDrawable && oldCtx) {
440         pwglMakeCurrent(oldDrawable, oldCtx);
441     }
442     if(GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
443         glEnable(GL_FRAGMENT_SHADER_ATI);
444         checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
445     }
446
447 out:
448     return ret;
449 }
450
451 /*****************************************************************************
452  * RemoveContextFromArray
453  *
454  * Removes a context from the context manager. The opengl context is not
455  * destroyed or unset. context is not a valid pointer after that call.
456  *
457  * Similar to the former call this isn't a performance critical function. A
458  * helper function for DestroyContext.
459  *
460  * Params:
461  *  This: Device to activate the context for
462  *  context: Context to remove
463  *
464  *****************************************************************************/
465 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
466     UINT t, s;
467     WineD3DContext **oldArray = This->contexts;
468
469     TRACE("Removing ctx %p\n", context);
470
471     This->numContexts--;
472
473     if(This->numContexts) {
474         This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
475         if(!This->contexts) {
476             ERR("Cannot allocate a new context array, PANIC!!!\n");
477         }
478         t = 0;
479         for(s = 0; s < This->numContexts; s++) {
480             if(oldArray[s] == context) continue;
481             This->contexts[t] = oldArray[s];
482             t++;
483         }
484     } else {
485         This->contexts = NULL;
486     }
487
488     HeapFree(GetProcessHeap(), 0, context);
489     HeapFree(GetProcessHeap(), 0, oldArray);
490 }
491
492 /*****************************************************************************
493  * DestroyContext
494  *
495  * Destroys a wineD3DContext
496  *
497  * Params:
498  *  This: Device to activate the context for
499  *  context: Context to destroy
500  *
501  *****************************************************************************/
502 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
503
504     /* check that we are the current context first */
505     TRACE("Destroying ctx %p\n", context);
506     if(pwglGetCurrentContext() == context->glCtx){
507         pwglMakeCurrent(NULL, NULL);
508     }
509
510     if(context->isPBuffer) {
511         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
512         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
513     } else ReleaseDC(context->win_handle, context->hdc);
514     pwglDeleteContext(context->glCtx);
515
516     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
517     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
518     RemoveContextFromArray(This, context);
519 }
520
521 /*****************************************************************************
522  * SetupForBlit
523  *
524  * Sets up a context for DirectDraw blitting.
525  * All texture units are disabled, texture unit 0 is set as current unit
526  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
527  * color writing enabled for all channels
528  * register combiners disabled, shaders disabled
529  * world matrix is set to identity, texture matrix 0 too
530  * projection matrix is setup for drawing screen coordinates
531  *
532  * Params:
533  *  This: Device to activate the context for
534  *  context: Context to setup
535  *  width: render target width
536  *  height: render target height
537  *
538  *****************************************************************************/
539 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
540     int i;
541     const struct StateEntry *StateTable = This->shader_backend->StateTable;
542
543     TRACE("Setting up context %p for blitting\n", context);
544     if(context->last_was_blit) {
545         TRACE("Context is already set up for blitting, nothing to do\n");
546         return;
547     }
548     context->last_was_blit = TRUE;
549
550     /* TODO: Use a display list */
551
552     /* Disable shaders */
553     This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
554     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
555     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
556
557     /* Disable all textures. The caller can then bind a texture it wants to blit
558      * from
559      */
560     if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
561         glDisable(GL_REGISTER_COMBINERS_NV);
562         checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
563     }
564     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
565         /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
566          * function texture unit. No need to care for higher samplers
567          */
568         for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
569             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
570             checkGLcall("glActiveTextureARB");
571
572             if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
573                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
574                 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
575             }
576             glDisable(GL_TEXTURE_3D);
577             checkGLcall("glDisable GL_TEXTURE_3D");
578             glDisable(GL_TEXTURE_2D);
579             checkGLcall("glDisable GL_TEXTURE_2D");
580
581             glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
582             checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
583
584             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP), StateTable);
585             Context_MarkStateDirty(context, STATE_SAMPLER(i), StateTable);
586         }
587         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
588         checkGLcall("glActiveTextureARB");
589     }
590     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
591         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
592         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
593     }
594     glDisable(GL_TEXTURE_3D);
595     checkGLcall("glDisable GL_TEXTURE_3D");
596     glDisable(GL_TEXTURE_2D);
597     checkGLcall("glDisable GL_TEXTURE_2D");
598
599     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
600
601     glMatrixMode(GL_TEXTURE);
602     checkGLcall("glMatrixMode(GL_TEXTURE)");
603     glLoadIdentity();
604     checkGLcall("glLoadIdentity()");
605     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0), StateTable);
606
607     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
608         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
609                   GL_TEXTURE_LOD_BIAS_EXT,
610                   0.0);
611         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
612     }
613     Context_MarkStateDirty(context, STATE_SAMPLER(0), StateTable);
614     Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP), StateTable);
615
616     /* Other misc states */
617     glDisable(GL_ALPHA_TEST);
618     checkGLcall("glDisable(GL_ALPHA_TEST)");
619     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
620     glDisable(GL_LIGHTING);
621     checkGLcall("glDisable GL_LIGHTING");
622     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
623     glDisable(GL_DEPTH_TEST);
624     checkGLcall("glDisable GL_DEPTH_TEST");
625     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
626     glDisable(GL_FOG);
627     checkGLcall("glDisable GL_FOG");
628     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
629     glDisable(GL_BLEND);
630     checkGLcall("glDisable GL_BLEND");
631     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
632     glDisable(GL_CULL_FACE);
633     checkGLcall("glDisable GL_CULL_FACE");
634     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
635     glDisable(GL_STENCIL_TEST);
636     checkGLcall("glDisable GL_STENCIL_TEST");
637     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
638     glDisable(GL_SCISSOR_TEST);
639     checkGLcall("glDisable GL_SCISSOR_TEST");
640     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
641     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
642         glDisable(GL_POINT_SPRITE_ARB);
643         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
644         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
645     }
646     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
647     checkGLcall("glColorMask");
648     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
649     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
650         glDisable(GL_COLOR_SUM_EXT);
651         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
652         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
653     }
654     if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
655         GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
656         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
657         checkGLcall("glFinalCombinerInputNV");
658     }
659
660     /* Setup transforms */
661     glMatrixMode(GL_MODELVIEW);
662     checkGLcall("glMatrixMode(GL_MODELVIEW)");
663     glLoadIdentity();
664     checkGLcall("glLoadIdentity()");
665     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
666
667     glMatrixMode(GL_PROJECTION);
668     checkGLcall("glMatrixMode(GL_PROJECTION)");
669     glLoadIdentity();
670     checkGLcall("glLoadIdentity()");
671     glOrtho(0, width, height, 0, 0.0, -1.0);
672     checkGLcall("glOrtho");
673     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
674
675     context->last_was_rhw = TRUE;
676     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
677
678     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
679     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
680     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
681     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
682     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
683     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
684     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
685
686     glViewport(0, 0, width, height);
687     checkGLcall("glViewport");
688     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
689
690     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
691         glDisable(GL_TEXTURE_SHADER_NV);
692         checkGLcall("glDisable(GL_TEXTURE_SHADER_NV)");
693     } else if(GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
694         glDisable(GL_FRAGMENT_SHADER_ATI);
695         checkGLcall("glDisable(GL_FRAGMENT_SHADER_ATI)");
696     }
697 }
698
699 /*****************************************************************************
700  * findThreadContextForSwapChain
701  *
702  * Searches a swapchain for all contexts and picks one for the thread tid.
703  * If none can be found the swapchain is requested to create a new context
704  *
705  *****************************************************************************/
706 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
707     int i;
708
709     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
710         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
711             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
712         }
713
714     }
715
716     /* Create a new context for the thread */
717     return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
718 }
719
720 /*****************************************************************************
721  * FindContext
722  *
723  * Finds a context for the current render target and thread
724  *
725  * Parameters:
726  *  target: Render target to find the context for
727  *  tid: Thread to activate the context for
728  *
729  * Returns: The needed context
730  *
731  *****************************************************************************/
732 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
733     IWineD3DSwapChain *swapchain = NULL;
734     HRESULT hr;
735     BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
736     WineD3DContext *context = This->activeContext;
737     BOOL oldRenderOffscreen = This->render_offscreen;
738     const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
739     const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
740     const struct StateEntry *StateTable = This->shader_backend->StateTable;
741
742     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
743      * the alpha blend state changes with different render target formats
744      */
745     if(oldFmt != newFmt) {
746         const GlPixelFormatDesc *glDesc;
747         const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
748         const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
749
750         /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
751         if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
752             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
753         }
754     }
755
756     hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
757     if(hr == WINED3D_OK && swapchain) {
758         TRACE("Rendering onscreen\n");
759
760         context = findThreadContextForSwapChain(swapchain, tid);
761
762         This->render_offscreen = FALSE;
763         /* The context != This->activeContext will catch a NOP context change. This can occur
764          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
765          * rendering. No context change is needed in that case
766          */
767
768         if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
769             *buffer = GL_FRONT;
770         } else {
771             *buffer = GL_BACK;
772         }
773         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
774             if(This->pbufferContext && tid == This->pbufferContext->tid) {
775                 This->pbufferContext->tid = 0;
776             }
777         }
778         IWineD3DSwapChain_Release(swapchain);
779
780         if(oldRenderOffscreen) {
781             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
782             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
783             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
784             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
785             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
786         }
787
788     } else {
789         TRACE("Rendering offscreen\n");
790         This->render_offscreen = TRUE;
791         *buffer = This->offscreenBuffer;
792
793         switch(wined3d_settings.offscreen_rendering_mode) {
794             case ORM_FBO:
795                 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
796                 if(This->activeContext && tid == This->lastThread) {
797                     context = This->activeContext;
798                 } else {
799                     /* This may happen if the app jumps straight into offscreen rendering
800                      * Start using the context of the primary swapchain. tid == 0 is no problem
801                      * for findThreadContextForSwapChain.
802                      *
803                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
804                      * is perfect to call.
805                      */
806                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
807                 }
808                 break;
809
810             case ORM_PBUFFER:
811             {
812                 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
813                 if(This->pbufferContext == NULL ||
814                    This->pbufferWidth < targetimpl->currentDesc.Width ||
815                    This->pbufferHeight < targetimpl->currentDesc.Height) {
816                     if(This->pbufferContext) {
817                         DestroyContext(This, This->pbufferContext);
818                     }
819
820                     /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
821                      * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
822                      */
823                     This->pbufferContext = CreateContext(This, targetimpl,
824                             ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
825                             TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
826                     This->pbufferWidth = targetimpl->currentDesc.Width;
827                     This->pbufferHeight = targetimpl->currentDesc.Height;
828                    }
829
830                    if(This->pbufferContext) {
831                        if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
832                            FIXME("The PBuffr context is only supported for one thread for now!\n");
833                        }
834                        This->pbufferContext->tid = tid;
835                        context = This->pbufferContext;
836                        break;
837                    } else {
838                        ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
839                        wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
840                    }
841             }
842
843             case ORM_BACKBUFFER:
844                 /* Stay with the currently active context for back buffer rendering */
845                 if(This->activeContext && tid == This->lastThread) {
846                     context = This->activeContext;
847                 } else {
848                     /* This may happen if the app jumps straight into offscreen rendering
849                      * Start using the context of the primary swapchain. tid == 0 is no problem
850                      * for findThreadContextForSwapChain.
851                      *
852                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
853                      * is perfect to call.
854                      */
855                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
856                 }
857                 break;
858         }
859
860         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
861             /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
862              * back when we are done won't mark us dirty.
863              */
864             IWineD3DSurface_PreLoad(target);
865         }
866
867         if(!oldRenderOffscreen) {
868             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
869             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
870             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
871             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
872             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
873         }
874     }
875     if (readTexture) {
876         BOOL oldInDraw = This->isInDraw;
877
878         /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
879          * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
880          * when using offscreen rendering with multithreading
881          */
882         This->isInDraw = TRUE;
883
884         /* Do that before switching the context:
885          * Read the back buffer of the old drawable into the destination texture
886          */
887         IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
888
889         /* Assume that the drawable will be modified by some other things now */
890         IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
891
892         This->isInDraw = oldInDraw;
893     }
894
895     if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
896         This->depth_copy_state = WINED3D_DCS_COPY;
897     }
898     return context;
899 }
900
901 /*****************************************************************************
902  * ActivateContext
903  *
904  * Finds a rendering context and drawable matching the device and render
905  * target for the current thread, activates them and puts them into the
906  * requested state.
907  *
908  * Params:
909  *  This: Device to activate the context for
910  *  target: Requested render target
911  *  usage: Prepares the context for blitting, drawing or other actions
912  *
913  *****************************************************************************/
914 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
915     DWORD                         tid = GetCurrentThreadId();
916     int                           i;
917     DWORD                         dirtyState, idx;
918     BYTE                          shift;
919     WineD3DContext                *context;
920     GLint                         drawBuffer=0;
921     const struct StateEntry       *StateTable = This->shader_backend->StateTable;
922
923     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
924     if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
925         context = FindContext(This, target, tid, &drawBuffer);
926         This->lastActiveRenderTarget = target;
927         This->lastThread = tid;
928     } else {
929         /* Stick to the old context */
930         context = This->activeContext;
931     }
932
933     /* Activate the opengl context */
934     if(context != This->activeContext) {
935         BOOL ret;
936
937         /* Prevent an unneeded context switch as those are expensive */
938         if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
939             TRACE("Already using gl context %p\n", context->glCtx);
940         }
941         else {
942             TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
943
944             if(GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
945                 /* Mesa crashes when enabling a context with GL_FRAGMENT_SHADER_ATI enabled.
946                  * Thus we disable it before deactivating any context, and re-enable it afterwards.
947                  *
948                  * This bug is filed as bug #15269 on bugs.freedesktop.org
949                  */
950                 glDisable(GL_FRAGMENT_SHADER_ATI);
951                 checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
952             }
953
954             ret = pwglMakeCurrent(context->hdc, context->glCtx);
955             if(ret == FALSE) {
956                 ERR("Failed to activate the new context\n");
957             } else if(GL_SUPPORT(ATI_FRAGMENT_SHADER) && !context->last_was_blit) {
958                 glEnable(GL_FRAGMENT_SHADER_ATI);
959                 checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
960             }
961         }
962         if(This->activeContext->vshader_const_dirty) {
963             memset(This->activeContext->vshader_const_dirty, 1,
964                    sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
965         }
966         if(This->activeContext->pshader_const_dirty) {
967             memset(This->activeContext->pshader_const_dirty, 1,
968                    sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
969         }
970         This->activeContext = context;
971     }
972
973     /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
974     ENTER_GL();
975     /* Select the right draw buffer. It is selected in FindContext. */
976     if(drawBuffer && context->last_draw_buffer != drawBuffer) {
977         TRACE("Drawing to buffer: %#x\n", drawBuffer);
978         context->last_draw_buffer = drawBuffer;
979
980         glDrawBuffer(drawBuffer);
981         checkGLcall("glDrawBuffer");
982     }
983
984     switch(usage) {
985         case CTXUSAGE_RESOURCELOAD:
986             /* This does not require any special states to be set up */
987             break;
988
989         case CTXUSAGE_CLEAR:
990             if(context->last_was_blit) {
991                 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
992                     glEnable(GL_TEXTURE_SHADER_NV);
993                     checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
994                 } else if(GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
995                     glEnable(GL_FRAGMENT_SHADER_ATI);
996                     checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
997                 }
998             }
999
1000             /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1001              * blending when clearing improves the clearing performance increadibly
1002              */
1003             glDisable(GL_BLEND);
1004             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1005
1006             glEnable(GL_SCISSOR_TEST);
1007             checkGLcall("glEnable GL_SCISSOR_TEST");
1008             context->last_was_blit = FALSE;
1009             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1010             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1011             break;
1012
1013         case CTXUSAGE_DRAWPRIM:
1014             /* This needs all dirty states applied */
1015             if(context->last_was_blit) {
1016                 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
1017                     glEnable(GL_TEXTURE_SHADER_NV);
1018                     checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
1019                 } else if(GL_SUPPORT(ATI_FRAGMENT_SHADER)) {
1020                     glEnable(GL_FRAGMENT_SHADER_ATI);
1021                     checkGLcall("glEnable(GL_FRAGMENT_SHADER_ATI)");
1022                 }
1023             }
1024
1025             IWineD3DDeviceImpl_FindTexUnitMap(This);
1026
1027             for(i=0; i < context->numDirtyEntries; i++) {
1028                 dirtyState = context->dirtyArray[i];
1029                 idx = dirtyState >> 5;
1030                 shift = dirtyState & 0x1f;
1031                 context->isStateDirty[idx] &= ~(1 << shift);
1032                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1033             }
1034             context->numDirtyEntries = 0; /* This makes the whole list clean */
1035             context->last_was_blit = FALSE;
1036             break;
1037
1038         case CTXUSAGE_BLIT:
1039             SetupForBlit(This, context,
1040                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1041                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1042             break;
1043
1044         default:
1045             FIXME("Unexpected context usage requested\n");
1046     }
1047     LEAVE_GL();
1048 }