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