msi: Set all folders' source paths to the root directory if the source type is compre...
[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->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 /* This function takes care of WineD3D pixel format selection. */
114 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
115 {
116     int iPixelFormat=0, matchtry;
117     short redBits, greenBits, blueBits, alphaBits, colorBits;
118     short depthBits=0, stencilBits=0;
119
120     struct match_type {
121         BOOL require_aux;
122         BOOL exact_alpha;
123         BOOL exact_color;
124     } matches[] = {
125         /* First, try without aux buffers - this is the most common cause
126          * for not finding a pixel format. Also some drivers(the open source ones)
127          * only offer 32 bit ARB pixel formats. First try without an exact alpha
128          * match, then try without an exact alpha and color match.
129          */
130         { TRUE,  TRUE,  TRUE  },
131         { FALSE, TRUE,  TRUE  },
132         { TRUE,  FALSE, TRUE  },
133         { TRUE,  FALSE, FALSE },
134         { FALSE, FALSE, TRUE  },
135         { FALSE, FALSE, FALSE },
136     };
137
138     int i = 0;
139     int nCfgs = This->adapter->nCfgs;
140     WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
141
142     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
143           debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
144
145     if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
146         ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
147         return 0;
148     }
149
150     /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
151      * You are able to add a depth + stencil surface at a later stage when you need it.
152      * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
153      * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
154      * context, need torecreate shaders, textures and other resources.
155      *
156      * The context manager already takes care of the state problem and for the other tasks code from Reset
157      * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
158      * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
159      * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
160      * issue needs to be fixed. */
161     if(DepthStencilFormat != WINED3DFMT_D24S8)
162         FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
163
164     DepthStencilFormat = WINED3DFMT_D24S8;
165
166     if(DepthStencilFormat) {
167         getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
168     }
169
170     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])); matchtry++) {
171         for(i=0; i<nCfgs; i++) {
172             BOOL exactDepthMatch = TRUE;
173             cfgs = &This->adapter->cfgs[i];
174
175             /* For now only accept RGBA formats. Perhaps some day we will
176              * allow floating point formats for pbuffers. */
177             if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
178                 continue;
179
180             /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
181             if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
182                 continue;
183
184             /* We like to have aux buffers in backbuffer mode */
185             if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
186                 continue;
187
188             /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
189             if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
190                 continue;
191
192             if(matches[matchtry].exact_color) {
193                 if(cfgs->redSize != redBits)
194                     continue;
195                 if(cfgs->greenSize != greenBits)
196                     continue;
197                 if(cfgs->blueSize != blueBits)
198                     continue;
199             } else {
200                 if(cfgs->redSize < redBits)
201                     continue;
202                 if(cfgs->greenSize < greenBits)
203                     continue;
204                 if(cfgs->blueSize < blueBits)
205                     continue;
206             }
207             if(matches[matchtry].exact_alpha) {
208                 if(cfgs->alphaSize != alphaBits)
209                     continue;
210             } else {
211                 if(cfgs->alphaSize < alphaBits)
212                     continue;
213             }
214
215             /* We try to locate a format which matches our requirements exactly. In case of
216              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
217             if(cfgs->depthSize < depthBits)
218                 continue;
219             else if(cfgs->depthSize > depthBits)
220                 exactDepthMatch = FALSE;
221
222             /* In all cases make sure the number of stencil bits matches our requirements
223              * even when we don't need stencil because it could affect performance EXCEPT
224              * on cards which don't offer depth formats without stencil like the i915 drivers
225              * on Linux. */
226             if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
227                 continue;
228
229             /* Check multisampling support */
230             if(cfgs->numSamples != numSamples)
231                 continue;
232
233             /* When we have passed all the checks then we have found a format which matches our
234              * requirements. Note that we only check for a limit number of capabilities right now,
235              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
236              * can still differ in things like multisampling, stereo, SRGB and other flags.
237              */
238
239             /* Exit the loop as we have found a format :) */
240             if(exactDepthMatch) {
241                 iPixelFormat = cfgs->iPixelFormat;
242                 break;
243             } else if(!iPixelFormat) {
244                 /* In the end we might end up with a format which doesn't exactly match our depth
245                  * requirements. Accept the first format we found because formats with higher iPixelFormat
246                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
247                 iPixelFormat = cfgs->iPixelFormat;
248             }
249         }
250     }
251
252     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
253     if(!iPixelFormat && !findCompatible) {
254         ERR("Can't find a suitable iPixelFormat\n");
255         return FALSE;
256     } else if(!iPixelFormat) {
257         PIXELFORMATDESCRIPTOR pfd;
258
259         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
260         /* PixelFormat selection */
261         ZeroMemory(&pfd, sizeof(pfd));
262         pfd.nSize      = sizeof(pfd);
263         pfd.nVersion   = 1;
264         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
265         pfd.iPixelType = PFD_TYPE_RGBA;
266         pfd.cAlphaBits = alphaBits;
267         pfd.cColorBits = colorBits;
268         pfd.cDepthBits = depthBits;
269         pfd.cStencilBits = stencilBits;
270         pfd.iLayerType = PFD_MAIN_PLANE;
271
272         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
273         if(!iPixelFormat) {
274             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
275             ERR("Can't find a suitable iPixelFormat\n");
276             return FALSE;
277         }
278     }
279
280     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
281     return iPixelFormat;
282 }
283
284 /*****************************************************************************
285  * CreateContext
286  *
287  * Creates a new context for a window, or a pbuffer context.
288  *
289  * * Params:
290  *  This: Device to activate the context for
291  *  target: Surface this context will render to
292  *  win_handle: handle to the window which we are drawing to
293  *  create_pbuffer: tells whether to create a pbuffer or not
294  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
295  *
296  *****************************************************************************/
297 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
298     HDC oldDrawable, hdc;
299     HPBUFFERARB pbuffer = NULL;
300     HGLRC ctx = NULL, oldCtx;
301     WineD3DContext *ret = NULL;
302     int s;
303
304     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
305
306     if(create_pbuffer) {
307         HDC hdc_parent = GetDC(win_handle);
308         int iPixelFormat = 0;
309
310         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
311         WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
312
313         /* Try to find a pixel format with pbuffer support. */
314         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
315         if(!iPixelFormat) {
316             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
317
318             /* For some reason we weren't able to find a format, try to find something instead of crashing.
319              * A reason for failure could have been wglChoosePixelFormatARB strictness. */
320             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
321         }
322
323         /* This shouldn't happen as ChoosePixelFormat always returns something */
324         if(!iPixelFormat) {
325             ERR("Unable to locate a pixel format for a pbuffer\n");
326             ReleaseDC(win_handle, hdc_parent);
327             goto out;
328         }
329
330         TRACE("Creating a pBuffer drawable for the new context\n");
331         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
332         if(!pbuffer) {
333             ERR("Cannot create a pbuffer\n");
334             ReleaseDC(win_handle, hdc_parent);
335             goto out;
336         }
337
338         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
339         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
340         if(!hdc) {
341             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
342             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
343             ReleaseDC(win_handle, hdc_parent);
344             goto out;
345         }
346         ReleaseDC(win_handle, hdc_parent);
347     } else {
348         PIXELFORMATDESCRIPTOR pfd;
349         int iPixelFormat;
350         int res;
351         WINED3DFORMAT ColorFormat = target->resource.format;
352         WINED3DFORMAT DepthStencilFormat = 0;
353         BOOL auxBuffers = FALSE;
354         int numSamples = 0;
355
356         hdc = GetDC(win_handle);
357         if(hdc == NULL) {
358             ERR("Cannot retrieve a device context!\n");
359             goto out;
360         }
361
362         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
363         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
364             auxBuffers = TRUE;
365
366             if(target->resource.format == WINED3DFMT_X4R4G4B4)
367                 ColorFormat = WINED3DFMT_A4R4G4B4;
368             else if(target->resource.format == WINED3DFMT_X8R8G8B8)
369                 ColorFormat = WINED3DFMT_A8R8G8B8;
370         }
371
372         /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
373          * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
374          * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
375          * a format with 8bit alpha, so request A8R8G8B8. */
376         if(ColorFormat == WINED3DFMT_P8)
377             ColorFormat = WINED3DFMT_A8R8G8B8;
378
379         /* Retrieve the depth stencil format from the present parameters.
380          * The choice of the proper format can give a nice performance boost
381          * in case of GPU limited programs. */
382         if(pPresentParms->EnableAutoDepthStencil) {
383             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
384             DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
385         }
386
387         /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
388         if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
389             if(!GL_SUPPORT(ARB_MULTISAMPLE))
390                 ERR("The program is requesting multisampling without support!\n");
391             else {
392                 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
393                 numSamples = pPresentParms->MultiSampleType;
394             }
395         }
396
397         /* Try to find a pixel format which matches our requirements */
398         iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
399
400         /* Try to locate a compatible format if we weren't able to find anything */
401         if(!iPixelFormat) {
402             TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
403             iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
404         }
405
406         /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
407         if(!iPixelFormat) {
408             ERR("Can't find a suitable iPixelFormat\n");
409             return FALSE;
410         }
411
412         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
413         res = SetPixelFormat(hdc, iPixelFormat, NULL);
414         if(!res) {
415             int oldPixelFormat = GetPixelFormat(hdc);
416
417             /* By default WGL doesn't allow pixel format adjustments but we need it here.
418              * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
419              * set the pixel format multiple times. Only use it when it is really needed. */
420
421             if(oldPixelFormat == iPixelFormat) {
422                 /* We don't have to do anything as the formats are the same :) */
423             } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
424                 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
425
426                 if(!res) {
427                     ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
428                     return FALSE;
429                 }
430             } else if(oldPixelFormat) {
431                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
432                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
433                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
434             } else {
435                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
436                 return FALSE;
437             }
438         }
439     }
440
441     ctx = pwglCreateContext(hdc);
442     if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
443
444     if(!ctx) {
445         ERR("Failed to create a WGL context\n");
446         if(create_pbuffer) {
447             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
448             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
449         }
450         goto out;
451     }
452     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
453     if(!ret) {
454         ERR("Failed to add the newly created context to the context list\n");
455         pwglDeleteContext(ctx);
456         if(create_pbuffer) {
457             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
458             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
459         }
460         goto out;
461     }
462     ret->surface = (IWineD3DSurface *) target;
463     ret->isPBuffer = create_pbuffer;
464     ret->tid = GetCurrentThreadId();
465     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
466         /* Create the dirty constants array and initialize them to dirty */
467         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
468                 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
469         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
470                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
471         memset(ret->vshader_const_dirty, 1,
472                sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
473         memset(ret->pshader_const_dirty, 1,
474                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
475     }
476
477     TRACE("Successfully created new context %p\n", ret);
478
479     /* Set up the context defaults */
480     oldCtx  = pwglGetCurrentContext();
481     oldDrawable = pwglGetCurrentDC();
482     if(oldCtx && oldDrawable) {
483         /* See comment in ActivateContext context switching */
484         This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
485     }
486     if(pwglMakeCurrent(hdc, ctx) == FALSE) {
487         ERR("Cannot activate context to set up defaults\n");
488         goto out;
489     }
490
491     ENTER_GL();
492
493     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
494
495     TRACE("Setting up the screen\n");
496     /* Clear the screen */
497     glClearColor(1.0, 0.0, 0.0, 0.0);
498     checkGLcall("glClearColor");
499     glClearIndex(0);
500     glClearDepth(1);
501     glClearStencil(0xffff);
502
503     checkGLcall("glClear");
504
505     glColor3f(1.0, 1.0, 1.0);
506     checkGLcall("glColor3f");
507
508     glEnable(GL_LIGHTING);
509     checkGLcall("glEnable");
510
511     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
512     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
513
514     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
515     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
516
517     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
518     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
519
520     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
521     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
522     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
523     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
524
525     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
526         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
527          * and textures in DIB sections(due to the memory protection).
528          */
529         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
530         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
531     }
532     if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
533         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
534          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
535          * GL_VERTEX_BLEND_ARB isn't enabled too
536          */
537         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
538         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
539     }
540     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
541         glEnable(GL_TEXTURE_SHADER_NV);
542         checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
543
544         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
545          * the previous texture where to source the offset from is always unit - 1.
546          */
547         for(s = 1; s < GL_LIMITS(textures); s++) {
548             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
549             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
550             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
551         }
552     }
553
554     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
555         for(s = 0; s < GL_LIMITS(textures); s++) {
556             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
557             glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
558             checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
559         }
560     }
561     LEAVE_GL();
562
563     /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
564      * but enable it for the first context we create, and reenable it on the old context
565      */
566     if(oldDrawable && oldCtx) {
567         pwglMakeCurrent(oldDrawable, oldCtx);
568     }
569     This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
570
571 out:
572     return ret;
573 }
574
575 /*****************************************************************************
576  * RemoveContextFromArray
577  *
578  * Removes a context from the context manager. The opengl context is not
579  * destroyed or unset. context is not a valid pointer after that call.
580  *
581  * Similar to the former call this isn't a performance critical function. A
582  * helper function for DestroyContext.
583  *
584  * Params:
585  *  This: Device to activate the context for
586  *  context: Context to remove
587  *
588  *****************************************************************************/
589 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
590     UINT t, s;
591     WineD3DContext **oldArray = This->contexts;
592
593     TRACE("Removing ctx %p\n", context);
594
595     This->numContexts--;
596
597     if(This->numContexts) {
598         This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
599         if(!This->contexts) {
600             ERR("Cannot allocate a new context array, PANIC!!!\n");
601         }
602         t = 0;
603         /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
604         for(s = 0; s <= This->numContexts; s++) {
605             if(oldArray[s] == context) continue;
606             This->contexts[t] = oldArray[s];
607             t++;
608         }
609     } else {
610         This->contexts = NULL;
611     }
612
613     HeapFree(GetProcessHeap(), 0, context);
614     HeapFree(GetProcessHeap(), 0, oldArray);
615 }
616
617 /*****************************************************************************
618  * DestroyContext
619  *
620  * Destroys a wineD3DContext
621  *
622  * Params:
623  *  This: Device to activate the context for
624  *  context: Context to destroy
625  *
626  *****************************************************************************/
627 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
628
629     /* check that we are the current context first */
630     TRACE("Destroying ctx %p\n", context);
631     if(pwglGetCurrentContext() == context->glCtx){
632         pwglMakeCurrent(NULL, NULL);
633     }
634
635     if(context->isPBuffer) {
636         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
637         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
638     } else ReleaseDC(context->win_handle, context->hdc);
639     pwglDeleteContext(context->glCtx);
640
641     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
642     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
643     RemoveContextFromArray(This, context);
644 }
645
646 static inline void set_blit_dimension(UINT width, UINT height) {
647     glMatrixMode(GL_PROJECTION);
648     checkGLcall("glMatrixMode(GL_PROJECTION)");
649     glLoadIdentity();
650     checkGLcall("glLoadIdentity()");
651     glOrtho(0, width, height, 0, 0.0, -1.0);
652     checkGLcall("glOrtho");
653     glViewport(0, 0, width, height);
654     checkGLcall("glViewport");
655 }
656
657 /*****************************************************************************
658  * SetupForBlit
659  *
660  * Sets up a context for DirectDraw blitting.
661  * All texture units are disabled, texture unit 0 is set as current unit
662  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
663  * color writing enabled for all channels
664  * register combiners disabled, shaders disabled
665  * world matrix is set to identity, texture matrix 0 too
666  * projection matrix is setup for drawing screen coordinates
667  *
668  * Params:
669  *  This: Device to activate the context for
670  *  context: Context to setup
671  *  width: render target width
672  *  height: render target height
673  *
674  *****************************************************************************/
675 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
676     int i, sampler;
677     const struct StateEntry *StateTable = This->StateTable;
678
679     TRACE("Setting up context %p for blitting\n", context);
680     if(context->last_was_blit) {
681         if(context->blit_w != width || context->blit_h != height) {
682             set_blit_dimension(width, height);
683             context->blit_w = width; context->blit_h = height;
684             /* No need to dirtify here, the states are still dirtified because they weren't
685              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
686              * be set
687              */
688         }
689         TRACE("Context is already set up for blitting, nothing to do\n");
690         return;
691     }
692     context->last_was_blit = TRUE;
693
694     /* TODO: Use a display list */
695
696     /* Disable shaders */
697     This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
698     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
699     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
700
701     /* Disable all textures. The caller can then bind a texture it wants to blit
702      * from
703      */
704     if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
705         glDisable(GL_REGISTER_COMBINERS_NV);
706         checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
707     }
708     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
709         /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
710          * function texture unit. No need to care for higher samplers
711          */
712         for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
713             sampler = This->rev_tex_unit_map[i];
714             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
715             checkGLcall("glActiveTextureARB");
716
717             if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
718                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
719                 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
720             }
721             glDisable(GL_TEXTURE_3D);
722             checkGLcall("glDisable GL_TEXTURE_3D");
723             glDisable(GL_TEXTURE_2D);
724             checkGLcall("glDisable GL_TEXTURE_2D");
725
726             glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
727             checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
728
729             if (sampler != -1) {
730                 if (sampler < MAX_TEXTURES) {
731                     Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
732                 }
733                 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
734             }
735         }
736         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
737         checkGLcall("glActiveTextureARB");
738     }
739
740     sampler = This->rev_tex_unit_map[0];
741
742     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
743         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
744         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
745     }
746     glDisable(GL_TEXTURE_3D);
747     checkGLcall("glDisable GL_TEXTURE_3D");
748     glDisable(GL_TEXTURE_2D);
749     checkGLcall("glDisable GL_TEXTURE_2D");
750
751     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
752
753     glMatrixMode(GL_TEXTURE);
754     checkGLcall("glMatrixMode(GL_TEXTURE)");
755     glLoadIdentity();
756     checkGLcall("glLoadIdentity()");
757
758     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
759         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
760                   GL_TEXTURE_LOD_BIAS_EXT,
761                   0.0);
762         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
763     }
764
765     if (sampler != -1) {
766         if (sampler < MAX_TEXTURES) {
767             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
768             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
769         }
770         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
771     }
772
773     /* Other misc states */
774     glDisable(GL_ALPHA_TEST);
775     checkGLcall("glDisable(GL_ALPHA_TEST)");
776     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
777     glDisable(GL_LIGHTING);
778     checkGLcall("glDisable GL_LIGHTING");
779     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
780     glDisable(GL_DEPTH_TEST);
781     checkGLcall("glDisable GL_DEPTH_TEST");
782     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
783     glDisable(GL_FOG);
784     checkGLcall("glDisable GL_FOG");
785     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
786     glDisable(GL_BLEND);
787     checkGLcall("glDisable GL_BLEND");
788     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
789     glDisable(GL_CULL_FACE);
790     checkGLcall("glDisable GL_CULL_FACE");
791     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
792     glDisable(GL_STENCIL_TEST);
793     checkGLcall("glDisable GL_STENCIL_TEST");
794     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
795     glDisable(GL_SCISSOR_TEST);
796     checkGLcall("glDisable GL_SCISSOR_TEST");
797     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
798     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
799         glDisable(GL_POINT_SPRITE_ARB);
800         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
801         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
802     }
803     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
804     checkGLcall("glColorMask");
805     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
806     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
807         glDisable(GL_COLOR_SUM_EXT);
808         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
809         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
810     }
811     if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
812         GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
813         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
814         checkGLcall("glFinalCombinerInputNV");
815     }
816
817     /* Setup transforms */
818     glMatrixMode(GL_MODELVIEW);
819     checkGLcall("glMatrixMode(GL_MODELVIEW)");
820     glLoadIdentity();
821     checkGLcall("glLoadIdentity()");
822     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
823
824     context->last_was_rhw = TRUE;
825     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
826
827     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
828     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
829     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
830     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
831     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
832     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
833     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
834
835     set_blit_dimension(width, height);
836     context->blit_w = width; context->blit_h = height;
837     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
838     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
839
840
841     This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
842 }
843
844 /*****************************************************************************
845  * findThreadContextForSwapChain
846  *
847  * Searches a swapchain for all contexts and picks one for the thread tid.
848  * If none can be found the swapchain is requested to create a new context
849  *
850  *****************************************************************************/
851 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
852     int i;
853
854     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
855         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
856             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
857         }
858
859     }
860
861     /* Create a new context for the thread */
862     return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
863 }
864
865 /*****************************************************************************
866  * FindContext
867  *
868  * Finds a context for the current render target and thread
869  *
870  * Parameters:
871  *  target: Render target to find the context for
872  *  tid: Thread to activate the context for
873  *
874  * Returns: The needed context
875  *
876  *****************************************************************************/
877 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
878     IWineD3DSwapChain *swapchain = NULL;
879     HRESULT hr;
880     BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
881     WineD3DContext *context = This->activeContext;
882     BOOL oldRenderOffscreen = This->render_offscreen;
883     const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
884     const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
885     const struct StateEntry *StateTable = This->StateTable;
886
887     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
888      * the alpha blend state changes with different render target formats
889      */
890     if(oldFmt != newFmt) {
891         const GlPixelFormatDesc *glDesc;
892         const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
893         const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
894
895         /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
896         if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
897             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
898         }
899     }
900
901     hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
902     if(hr == WINED3D_OK && swapchain) {
903         TRACE("Rendering onscreen\n");
904
905         context = findThreadContextForSwapChain(swapchain, tid);
906
907         This->render_offscreen = FALSE;
908         /* The context != This->activeContext will catch a NOP context change. This can occur
909          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
910          * rendering. No context change is needed in that case
911          */
912
913         if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
914             *buffer = GL_FRONT;
915         } else {
916             *buffer = GL_BACK;
917         }
918         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
919             if(This->pbufferContext && tid == This->pbufferContext->tid) {
920                 This->pbufferContext->tid = 0;
921             }
922         }
923         IWineD3DSwapChain_Release(swapchain);
924
925         if(oldRenderOffscreen) {
926             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
927             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
928             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
929             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
930             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
931         }
932
933     } else {
934         TRACE("Rendering offscreen\n");
935         This->render_offscreen = TRUE;
936         *buffer = This->offscreenBuffer;
937
938         switch(wined3d_settings.offscreen_rendering_mode) {
939             case ORM_FBO:
940                 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
941                 if(This->activeContext && tid == This->lastThread) {
942                     context = This->activeContext;
943                 } else {
944                     /* This may happen if the app jumps straight into offscreen rendering
945                      * Start using the context of the primary swapchain. tid == 0 is no problem
946                      * for findThreadContextForSwapChain.
947                      *
948                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
949                      * is perfect to call.
950                      */
951                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
952                 }
953                 break;
954
955             case ORM_PBUFFER:
956             {
957                 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
958                 if(This->pbufferContext == NULL ||
959                    This->pbufferWidth < targetimpl->currentDesc.Width ||
960                    This->pbufferHeight < targetimpl->currentDesc.Height) {
961                     if(This->pbufferContext) {
962                         DestroyContext(This, This->pbufferContext);
963                     }
964
965                     /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
966                      * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
967                      */
968                     This->pbufferContext = CreateContext(This, targetimpl,
969                             ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
970                             TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
971                     This->pbufferWidth = targetimpl->currentDesc.Width;
972                     This->pbufferHeight = targetimpl->currentDesc.Height;
973                    }
974
975                    if(This->pbufferContext) {
976                        if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
977                            FIXME("The PBuffr context is only supported for one thread for now!\n");
978                        }
979                        This->pbufferContext->tid = tid;
980                        context = This->pbufferContext;
981                        break;
982                    } else {
983                        ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
984                        wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
985                    }
986             }
987
988             case ORM_BACKBUFFER:
989                 /* Stay with the currently active context for back buffer rendering */
990                 if(This->activeContext && tid == This->lastThread) {
991                     context = This->activeContext;
992                 } else {
993                     /* This may happen if the app jumps straight into offscreen rendering
994                      * Start using the context of the primary swapchain. tid == 0 is no problem
995                      * for findThreadContextForSwapChain.
996                      *
997                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
998                      * is perfect to call.
999                      */
1000                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
1001                 }
1002                 break;
1003         }
1004
1005         if(!oldRenderOffscreen) {
1006             Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1007             Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1008             Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1009             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1010             Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1011         }
1012     }
1013
1014     /* When switching away from an offscreen render target, and we're not using FBOs,
1015      * we have to read the drawable into the texture. This is done via PreLoad(and
1016      * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1017      * PreLoad needs a GL context, and FindContext is called before the context is activated.
1018      * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1019      * is read. This leads to these possible situations:
1020      *
1021      * 0) lastActiveRenderTarget == target && oldTid == newTid:
1022      *    Nothing to do, we don't even reach this code in this case...
1023      *
1024      * 1) lastActiveRenderTarget != target && oldTid == newTid:
1025      *    The currently active context is OK for readback. Call PreLoad, and it
1026      *    performs the read
1027      *
1028      * 2) lastActiveRenderTarget == target && oldTid != newTid:
1029      *    Nothing to do - the drawable is unchanged
1030      *
1031      * 3) lastActiveRenderTarget != target && oldTid != newTid:
1032      *    This is tricky. We have to get a context with the old drawable from somewhere
1033      *    before we can switch to the new context. In this case, PreLoad calls
1034      *    ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1035      *    is case (2) then. The old drawable is activated for the new thread, and the
1036      *    readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1037      *    After that, the outer ActivateContext(which calls PreLoad) can activate the new
1038      *    target for the new thread
1039      */
1040     if (readTexture && This->lastActiveRenderTarget != target) {
1041         BOOL oldInDraw = This->isInDraw;
1042
1043         /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1044          * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1045          * when using offscreen rendering with multithreading
1046          */
1047         This->isInDraw = TRUE;
1048
1049         /* Do that before switching the context:
1050          * Read the back buffer of the old drawable into the destination texture
1051          */
1052         IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1053
1054         /* Assume that the drawable will be modified by some other things now */
1055         IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1056
1057         This->isInDraw = oldInDraw;
1058     }
1059
1060     return context;
1061 }
1062
1063 /*****************************************************************************
1064  * ActivateContext
1065  *
1066  * Finds a rendering context and drawable matching the device and render
1067  * target for the current thread, activates them and puts them into the
1068  * requested state.
1069  *
1070  * Params:
1071  *  This: Device to activate the context for
1072  *  target: Requested render target
1073  *  usage: Prepares the context for blitting, drawing or other actions
1074  *
1075  *****************************************************************************/
1076 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1077     DWORD                         tid = GetCurrentThreadId();
1078     int                           i;
1079     DWORD                         dirtyState, idx;
1080     BYTE                          shift;
1081     WineD3DContext                *context;
1082     GLint                         drawBuffer=0;
1083     const struct StateEntry       *StateTable = This->StateTable;
1084
1085     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1086     if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1087         context = FindContext(This, target, tid, &drawBuffer);
1088         This->lastActiveRenderTarget = target;
1089         This->lastThread = tid;
1090     } else {
1091         /* Stick to the old context */
1092         context = This->activeContext;
1093     }
1094
1095     /* Activate the opengl context */
1096     if(context != This->activeContext) {
1097         BOOL ret;
1098
1099         /* Prevent an unneeded context switch as those are expensive */
1100         if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1101             TRACE("Already using gl context %p\n", context->glCtx);
1102         }
1103         else {
1104             TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1105
1106             This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1107             ret = pwglMakeCurrent(context->hdc, context->glCtx);
1108             if(ret == FALSE) {
1109                 ERR("Failed to activate the new context\n");
1110             } else if(!context->last_was_blit) {
1111                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1112             }
1113         }
1114         if(This->activeContext->vshader_const_dirty) {
1115             memset(This->activeContext->vshader_const_dirty, 1,
1116                    sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1117         }
1118         if(This->activeContext->pshader_const_dirty) {
1119             memset(This->activeContext->pshader_const_dirty, 1,
1120                    sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1121         }
1122         This->activeContext = context;
1123     }
1124
1125     /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1126     ENTER_GL();
1127     /* Select the right draw buffer. It is selected in FindContext. */
1128     if(drawBuffer && context->last_draw_buffer != drawBuffer) {
1129         TRACE("Drawing to buffer: %#x\n", drawBuffer);
1130         context->last_draw_buffer = drawBuffer;
1131
1132         glDrawBuffer(drawBuffer);
1133         checkGLcall("glDrawBuffer");
1134     }
1135
1136     switch(usage) {
1137         case CTXUSAGE_RESOURCELOAD:
1138             /* This does not require any special states to be set up */
1139             break;
1140
1141         case CTXUSAGE_CLEAR:
1142             if(context->last_was_blit) {
1143                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1144             }
1145
1146             /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1147              * blending when clearing improves the clearing performance incredibly.
1148              */
1149             glDisable(GL_BLEND);
1150             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1151
1152             glEnable(GL_SCISSOR_TEST);
1153             checkGLcall("glEnable GL_SCISSOR_TEST");
1154             context->last_was_blit = FALSE;
1155             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1156             Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1157             break;
1158
1159         case CTXUSAGE_DRAWPRIM:
1160             /* This needs all dirty states applied */
1161             if(context->last_was_blit) {
1162                 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1163             }
1164
1165             IWineD3DDeviceImpl_FindTexUnitMap(This);
1166
1167             for(i=0; i < context->numDirtyEntries; i++) {
1168                 dirtyState = context->dirtyArray[i];
1169                 idx = dirtyState >> 5;
1170                 shift = dirtyState & 0x1f;
1171                 context->isStateDirty[idx] &= ~(1 << shift);
1172                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1173             }
1174             context->numDirtyEntries = 0; /* This makes the whole list clean */
1175             context->last_was_blit = FALSE;
1176             break;
1177
1178         case CTXUSAGE_BLIT:
1179             SetupForBlit(This, context,
1180                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1181                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1182             break;
1183
1184         default:
1185             FIXME("Unexpected context usage requested\n");
1186     }
1187     LEAVE_GL();
1188 }