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