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