wined3d: Don't grab the implicit depth stencil format in the wrong place.
[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  * Copyright 2009 Henri Verbeet for CodeWeavers
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include <stdio.h>
24 #ifdef HAVE_FLOAT_H
25 # include <float.h>
26 #endif
27 #include "wined3d_private.h"
28
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30
31 #define GLINFO_LOCATION (*gl_info)
32
33 static DWORD wined3d_context_tls_idx;
34
35 /* FBO helper functions */
36
37 /* GL locking is done by the caller */
38 void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
39 {
40     const struct wined3d_gl_info *gl_info = context->gl_info;
41     GLuint f;
42
43     if (!fbo)
44     {
45         f = 0;
46     }
47     else
48     {
49         if (!*fbo)
50         {
51             gl_info->fbo_ops.glGenFramebuffers(1, fbo);
52             checkGLcall("glGenFramebuffers()");
53             TRACE("Created FBO %u.\n", *fbo);
54         }
55         f = *fbo;
56     }
57
58     switch (target)
59     {
60         case GL_READ_FRAMEBUFFER:
61             if (context->fbo_read_binding == f) return;
62             context->fbo_read_binding = f;
63             break;
64
65         case GL_DRAW_FRAMEBUFFER:
66             if (context->fbo_draw_binding == f) return;
67             context->fbo_draw_binding = f;
68             break;
69
70         case GL_FRAMEBUFFER:
71             if (context->fbo_read_binding == f
72                     && context->fbo_draw_binding == f) return;
73             context->fbo_read_binding = f;
74             context->fbo_draw_binding = f;
75             break;
76
77         default:
78             FIXME("Unhandled target %#x.\n", target);
79             break;
80     }
81
82     gl_info->fbo_ops.glBindFramebuffer(target, f);
83     checkGLcall("glBindFramebuffer()");
84 }
85
86 /* GL locking is done by the caller */
87 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info)
88 {
89     unsigned int i;
90
91     for (i = 0; i < gl_info->limits.buffers; ++i)
92     {
93         gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
94         checkGLcall("glFramebufferTexture2D()");
95     }
96     gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
97     checkGLcall("glFramebufferTexture2D()");
98
99     gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
100     checkGLcall("glFramebufferTexture2D()");
101 }
102
103 /* GL locking is done by the caller */
104 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
105 {
106     const struct wined3d_gl_info *gl_info = context->gl_info;
107
108     context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
109     context_clean_fbo_attachments(gl_info);
110     context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
111
112     gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
113     checkGLcall("glDeleteFramebuffers()");
114 }
115
116 /* GL locking is done by the caller */
117 static void context_apply_attachment_filter_states(IWineD3DSurfaceImpl *surface)
118 {
119     IWineD3DBaseTextureImpl *texture_impl;
120
121     /* Update base texture states array */
122     if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
123             &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
124     {
125         IWineD3DDeviceImpl *device = surface->resource.device;
126         BOOL update_minfilter = FALSE;
127         BOOL update_magfilter = FALSE;
128
129         if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
130             || texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
131         {
132             texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
133             texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
134             update_minfilter = TRUE;
135         }
136
137         if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
138         {
139             texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
140             update_magfilter = TRUE;
141         }
142
143         if (texture_impl->baseTexture.bindCount)
144         {
145             WARN("Render targets should not be bound to a sampler\n");
146             IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
147         }
148
149         IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
150
151         if (update_minfilter || update_magfilter)
152         {
153             GLenum target, bind_target;
154             GLint old_binding;
155
156             target = surface->texture_target;
157             if (target == GL_TEXTURE_2D)
158             {
159                 bind_target = GL_TEXTURE_2D;
160                 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
161             }
162             else if (target == GL_TEXTURE_RECTANGLE_ARB)
163             {
164                 bind_target = GL_TEXTURE_RECTANGLE_ARB;
165                 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
166             }
167             else
168             {
169                 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
170                 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
171             }
172
173             glBindTexture(bind_target, surface->texture_name);
174             if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
175             if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
176             glBindTexture(bind_target, old_binding);
177         }
178
179         checkGLcall("apply_attachment_filter_states()");
180     }
181 }
182
183 /* GL locking is done by the caller */
184 void context_attach_depth_stencil_fbo(struct wined3d_context *context,
185         GLenum fbo_target, IWineD3DSurfaceImpl *depth_stencil, BOOL use_render_buffer)
186 {
187     const struct wined3d_gl_info *gl_info = context->gl_info;
188
189     TRACE("Attach depth stencil %p\n", depth_stencil);
190
191     if (depth_stencil)
192     {
193         DWORD format_flags = depth_stencil->resource.format_desc->Flags;
194
195         if (use_render_buffer && depth_stencil->current_renderbuffer)
196         {
197             if (format_flags & WINED3DFMT_FLAG_DEPTH)
198             {
199                 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT,
200                         GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
201                 checkGLcall("glFramebufferRenderbuffer()");
202             }
203
204             if (format_flags & WINED3DFMT_FLAG_STENCIL)
205             {
206                 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT,
207                         GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
208                 checkGLcall("glFramebufferRenderbuffer()");
209             }
210         }
211         else
212         {
213             surface_prepare_texture(depth_stencil, gl_info, FALSE);
214             context_apply_attachment_filter_states(depth_stencil);
215
216             if (format_flags & WINED3DFMT_FLAG_DEPTH)
217             {
218                 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
219                         depth_stencil->texture_target, depth_stencil->texture_name,
220                         depth_stencil->texture_level);
221                 checkGLcall("glFramebufferTexture2D()");
222             }
223
224             if (format_flags & WINED3DFMT_FLAG_STENCIL)
225             {
226                 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
227                         depth_stencil->texture_target, depth_stencil->texture_name,
228                         depth_stencil->texture_level);
229                 checkGLcall("glFramebufferTexture2D()");
230             }
231         }
232
233         if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
234         {
235             gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
236             checkGLcall("glFramebufferTexture2D()");
237         }
238
239         if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
240         {
241             gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
242             checkGLcall("glFramebufferTexture2D()");
243         }
244     }
245     else
246     {
247         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
248         checkGLcall("glFramebufferTexture2D()");
249
250         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
251         checkGLcall("glFramebufferTexture2D()");
252     }
253 }
254
255 /* GL locking is done by the caller */
256 void context_attach_surface_fbo(const struct wined3d_context *context,
257         GLenum fbo_target, DWORD idx, IWineD3DSurfaceImpl *surface)
258 {
259     const struct wined3d_gl_info *gl_info = context->gl_info;
260
261     TRACE("Attach surface %p to %u\n", surface, idx);
262
263     if (surface)
264     {
265         surface_prepare_texture(surface, gl_info, FALSE);
266         context_apply_attachment_filter_states(surface);
267
268         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, surface->texture_target,
269                 surface->texture_name, surface->texture_level);
270         checkGLcall("glFramebufferTexture2D()");
271     }
272     else
273     {
274         gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
275         checkGLcall("glFramebufferTexture2D()");
276     }
277 }
278
279 /* GL locking is done by the caller */
280 static void context_check_fbo_status(struct wined3d_context *context)
281 {
282     const struct wined3d_gl_info *gl_info = context->gl_info;
283     GLenum status;
284
285     status = gl_info->fbo_ops.glCheckFramebufferStatus(GL_FRAMEBUFFER);
286     if (status == GL_FRAMEBUFFER_COMPLETE)
287     {
288         TRACE("FBO complete\n");
289     } else {
290         IWineD3DSurfaceImpl *attachment;
291         unsigned int i;
292         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
293
294         if (!context->current_fbo)
295         {
296             ERR("FBO 0 is incomplete, driver bug?\n");
297             return;
298         }
299
300         /* Dump the FBO attachments */
301         for (i = 0; i < gl_info->limits.buffers; ++i)
302         {
303             attachment = context->current_fbo->render_targets[i];
304             if (attachment)
305             {
306                 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
307                         i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
308                         attachment->pow2Width, attachment->pow2Height);
309             }
310         }
311         attachment = context->current_fbo->depth_stencil;
312         if (attachment)
313         {
314             FIXME("\tDepth attachment: (%p) %s %ux%u\n",
315                     attachment, debug_d3dformat(attachment->resource.format_desc->format),
316                     attachment->pow2Width, attachment->pow2Height);
317         }
318     }
319 }
320
321 static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
322 {
323     const struct wined3d_gl_info *gl_info = context->gl_info;
324     IWineD3DDeviceImpl *device = context->swapchain->device;
325     struct fbo_entry *entry;
326
327     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
328     entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
329     memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
330     entry->depth_stencil = device->depth_stencil;
331     entry->attached = FALSE;
332     entry->id = 0;
333
334     return entry;
335 }
336
337 /* GL locking is done by the caller */
338 static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
339 {
340     const struct wined3d_gl_info *gl_info = context->gl_info;
341     IWineD3DDeviceImpl *device = context->swapchain->device;
342
343     context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
344     context_clean_fbo_attachments(gl_info);
345
346     memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
347     entry->depth_stencil = device->depth_stencil;
348     entry->attached = FALSE;
349 }
350
351 /* GL locking is done by the caller */
352 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
353 {
354     if (entry->id)
355     {
356         TRACE("Destroy FBO %d\n", entry->id);
357         context_destroy_fbo(context, &entry->id);
358     }
359     --context->fbo_entry_count;
360     list_remove(&entry->entry);
361     HeapFree(GetProcessHeap(), 0, entry->render_targets);
362     HeapFree(GetProcessHeap(), 0, entry);
363 }
364
365
366 /* GL locking is done by the caller */
367 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
368 {
369     const struct wined3d_gl_info *gl_info = context->gl_info;
370     IWineD3DDeviceImpl *device = context->swapchain->device;
371     struct fbo_entry *entry;
372
373     LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
374     {
375         if (!memcmp(entry->render_targets,
376                 device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
377                 && entry->depth_stencil == device->depth_stencil)
378         {
379             list_remove(&entry->entry);
380             list_add_head(&context->fbo_list, &entry->entry);
381             return entry;
382         }
383     }
384
385     if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
386     {
387         entry = context_create_fbo_entry(context);
388         list_add_head(&context->fbo_list, &entry->entry);
389         ++context->fbo_entry_count;
390     }
391     else
392     {
393         entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
394         context_reuse_fbo_entry(context, entry);
395         list_remove(&entry->entry);
396         list_add_head(&context->fbo_list, &entry->entry);
397     }
398
399     return entry;
400 }
401
402 /* GL locking is done by the caller */
403 static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
404 {
405     const struct wined3d_gl_info *gl_info = context->gl_info;
406     IWineD3DDeviceImpl *device = context->swapchain->device;
407     unsigned int i;
408
409     context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
410
411     if (!entry->attached)
412     {
413         /* Apply render targets */
414         for (i = 0; i < gl_info->limits.buffers; ++i)
415         {
416             context_attach_surface_fbo(context, GL_FRAMEBUFFER, i, entry->render_targets[i]);
417         }
418
419         /* Apply depth targets */
420         if (entry->depth_stencil)
421         {
422             surface_set_compatible_renderbuffer(entry->depth_stencil,
423                     entry->render_targets[0]->pow2Width, entry->render_targets[0]->pow2Height);
424         }
425         context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, entry->depth_stencil, TRUE);
426
427         entry->attached = TRUE;
428     }
429     else
430     {
431         for (i = 0; i < gl_info->limits.buffers; ++i)
432         {
433             if (entry->render_targets[i])
434                 context_apply_attachment_filter_states(entry->render_targets[i]);
435         }
436         if (entry->depth_stencil)
437             context_apply_attachment_filter_states(entry->depth_stencil);
438     }
439
440     for (i = 0; i < gl_info->limits.buffers; ++i)
441     {
442         if (device->render_targets[i])
443             device->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
444         else
445             device->draw_buffers[i] = GL_NONE;
446     }
447 }
448
449 /* GL locking is done by the caller */
450 static void context_apply_fbo_state(struct wined3d_context *context)
451 {
452     struct fbo_entry *entry, *entry2;
453
454     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
455     {
456         context_destroy_fbo_entry(context, entry);
457     }
458
459     if (context->rebind_fbo)
460     {
461         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
462         context->rebind_fbo = FALSE;
463     }
464
465     if (context->render_offscreen)
466     {
467         context->current_fbo = context_find_fbo_entry(context);
468         context_apply_fbo_entry(context, context->current_fbo);
469     } else {
470         context->current_fbo = NULL;
471         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
472     }
473
474     context_check_fbo_status(context);
475 }
476
477 /* Context activation is done by the caller. */
478 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
479 {
480     const struct wined3d_gl_info *gl_info = context->gl_info;
481
482     if (context->free_occlusion_query_count)
483     {
484         query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
485     }
486     else
487     {
488         if (gl_info->supported[ARB_OCCLUSION_QUERY])
489         {
490             ENTER_GL();
491             GL_EXTCALL(glGenQueriesARB(1, &query->id));
492             checkGLcall("glGenQueriesARB");
493             LEAVE_GL();
494
495             TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
496         }
497         else
498         {
499             WARN("Occlusion queries not supported, not allocating query id.\n");
500             query->id = 0;
501         }
502     }
503
504     query->context = context;
505     list_add_head(&context->occlusion_queries, &query->entry);
506 }
507
508 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
509 {
510     struct wined3d_context *context = query->context;
511
512     list_remove(&query->entry);
513     query->context = NULL;
514
515     if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
516     {
517         UINT new_size = context->free_occlusion_query_size << 1;
518         GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
519                 new_size * sizeof(*context->free_occlusion_queries));
520
521         if (!new_data)
522         {
523             ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
524             return;
525         }
526
527         context->free_occlusion_query_size = new_size;
528         context->free_occlusion_queries = new_data;
529     }
530
531     context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
532 }
533
534 /* Context activation is done by the caller. */
535 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
536 {
537     const struct wined3d_gl_info *gl_info = context->gl_info;
538
539     if (context->free_event_query_count)
540     {
541         query->object = context->free_event_queries[--context->free_event_query_count];
542     }
543     else
544     {
545         if (gl_info->supported[ARB_SYNC])
546         {
547             /* Using ARB_sync, not much to do here. */
548             query->object.sync = NULL;
549             TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
550         }
551         else if (gl_info->supported[APPLE_FENCE])
552         {
553             ENTER_GL();
554             GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
555             checkGLcall("glGenFencesAPPLE");
556             LEAVE_GL();
557
558             TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
559         }
560         else if(gl_info->supported[NV_FENCE])
561         {
562             ENTER_GL();
563             GL_EXTCALL(glGenFencesNV(1, &query->object.id));
564             checkGLcall("glGenFencesNV");
565             LEAVE_GL();
566
567             TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
568         }
569         else
570         {
571             WARN("Event queries not supported, not allocating query id.\n");
572             query->object.id = 0;
573         }
574     }
575
576     query->context = context;
577     list_add_head(&context->event_queries, &query->entry);
578 }
579
580 void context_free_event_query(struct wined3d_event_query *query)
581 {
582     struct wined3d_context *context = query->context;
583
584     list_remove(&query->entry);
585     query->context = NULL;
586
587     if (context->free_event_query_count >= context->free_event_query_size - 1)
588     {
589         UINT new_size = context->free_event_query_size << 1;
590         union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
591                 new_size * sizeof(*context->free_event_queries));
592
593         if (!new_data)
594         {
595             ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
596             return;
597         }
598
599         context->free_event_query_size = new_size;
600         context->free_event_queries = new_data;
601     }
602
603     context->free_event_queries[context->free_event_query_count++] = query->object;
604 }
605
606 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
607 {
608     IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
609     UINT i;
610
611     if (!This->d3d_initialized) return;
612
613     switch(type)
614     {
615         case WINED3DRTYPE_SURFACE:
616         {
617             for (i = 0; i < This->numContexts; ++i)
618             {
619                 struct wined3d_context *context = This->contexts[i];
620                 const struct wined3d_gl_info *gl_info = context->gl_info;
621                 struct fbo_entry *entry, *entry2;
622
623                 if (context->current_rt == (IWineD3DSurfaceImpl *)resource) context->current_rt = NULL;
624
625                 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
626                 {
627                     UINT j;
628
629                     if (entry->depth_stencil == (IWineD3DSurfaceImpl *)resource)
630                     {
631                         list_remove(&entry->entry);
632                         list_add_head(&context->fbo_destroy_list, &entry->entry);
633                         continue;
634                     }
635
636                     for (j = 0; j < gl_info->limits.buffers; ++j)
637                     {
638                         if (entry->render_targets[j] == (IWineD3DSurfaceImpl *)resource)
639                         {
640                             list_remove(&entry->entry);
641                             list_add_head(&context->fbo_destroy_list, &entry->entry);
642                             break;
643                         }
644                     }
645                 }
646             }
647
648             break;
649         }
650
651         default:
652             break;
653     }
654 }
655
656 void context_surface_update(struct wined3d_context *context, IWineD3DSurfaceImpl *surface)
657 {
658     const struct wined3d_gl_info *gl_info = context->gl_info;
659     struct fbo_entry *entry = context->current_fbo;
660     unsigned int i;
661
662     if (!entry || context->rebind_fbo) return;
663
664     for (i = 0; i < gl_info->limits.buffers; ++i)
665     {
666         if (surface == entry->render_targets[i])
667         {
668             TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
669             context->rebind_fbo = TRUE;
670             return;
671         }
672     }
673
674     if (surface == entry->depth_stencil)
675     {
676         TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
677         context->rebind_fbo = TRUE;
678     }
679 }
680
681 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
682 {
683     int current = GetPixelFormat(dc);
684
685     if (current == format) return TRUE;
686
687     if (!current)
688     {
689         if (!SetPixelFormat(dc, format, NULL))
690         {
691             ERR("Failed to set pixel format %d on device context %p, last error %#x.\n",
692                     format, dc, GetLastError());
693             return FALSE;
694         }
695         return TRUE;
696     }
697
698     /* By default WGL doesn't allow pixel format adjustments but we need it
699      * here. For this reason there's a Wine specific wglSetPixelFormat()
700      * which allows us to set the pixel format multiple times. Only use it
701      * when really needed. */
702     if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
703     {
704         if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
705         {
706             ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
707                     format, dc);
708             return FALSE;
709         }
710         return TRUE;
711     }
712
713     /* OpenGL doesn't allow pixel format adjustments. Print an error and
714      * continue using the old format. There's a big chance that the old
715      * format works although with a performance hit and perhaps rendering
716      * errors. */
717     ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
718             format, dc, current);
719     return TRUE;
720 }
721
722 static void context_update_window(struct wined3d_context *context)
723 {
724     TRACE("Updating context %p window from %p to %p.\n",
725             context, context->win_handle, context->swapchain->win_handle);
726
727     if (context->valid)
728     {
729         if (!ReleaseDC(context->win_handle, context->hdc))
730         {
731             ERR("Failed to release device context %p, last error %#x.\n",
732                     context->hdc, GetLastError());
733         }
734     }
735     else context->valid = 1;
736
737     context->win_handle = context->swapchain->win_handle;
738
739     if (!(context->hdc = GetDC(context->win_handle)))
740     {
741         ERR("Failed to get a device context for window %p.\n", context->win_handle);
742         goto err;
743     }
744
745     if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
746     {
747         ERR("Failed to set pixel format %d on device context %p.\n",
748                 context->pixel_format, context->hdc);
749         goto err;
750     }
751
752     if (!pwglMakeCurrent(context->hdc, context->glCtx))
753     {
754         ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
755                 context->glCtx, context->hdc, GetLastError());
756         goto err;
757     }
758
759     return;
760
761 err:
762     context->valid = 0;
763 }
764
765 static void context_validate(struct wined3d_context *context)
766 {
767     HWND wnd = WindowFromDC(context->hdc);
768
769     if (wnd != context->win_handle)
770     {
771         WARN("DC %p belongs to window %p instead of %p.\n",
772                 context->hdc, wnd, context->win_handle);
773         context->valid = 0;
774     }
775
776     if (context->win_handle != context->swapchain->win_handle)
777         context_update_window(context);
778 }
779
780 static void context_destroy_gl_resources(struct wined3d_context *context)
781 {
782     const struct wined3d_gl_info *gl_info = context->gl_info;
783     struct wined3d_occlusion_query *occlusion_query;
784     struct wined3d_event_query *event_query;
785     struct fbo_entry *entry, *entry2;
786     HGLRC restore_ctx;
787     HDC restore_dc;
788     unsigned int i;
789
790     restore_ctx = pwglGetCurrentContext();
791     restore_dc = pwglGetCurrentDC();
792
793     context_validate(context);
794     if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
795     else restore_ctx = NULL;
796
797     ENTER_GL();
798
799     LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
800     {
801         if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
802             GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
803         occlusion_query->context = NULL;
804     }
805
806     LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
807     {
808         if (context->valid)
809         {
810             if (gl_info->supported[ARB_SYNC])
811             {
812                 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
813             }
814             else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
815             else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
816         }
817         event_query->context = NULL;
818     }
819
820     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
821     {
822         if (!context->valid) entry->id = 0;
823         context_destroy_fbo_entry(context, entry);
824     }
825
826     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
827     {
828         if (!context->valid) entry->id = 0;
829         context_destroy_fbo_entry(context, entry);
830     }
831
832     if (context->valid)
833     {
834         if (context->src_fbo)
835         {
836             TRACE("Destroy src FBO %d\n", context->src_fbo);
837             context_destroy_fbo(context, &context->src_fbo);
838         }
839         if (context->dst_fbo)
840         {
841             TRACE("Destroy dst FBO %d\n", context->dst_fbo);
842             context_destroy_fbo(context, &context->dst_fbo);
843         }
844         if (context->dummy_arbfp_prog)
845         {
846             GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
847         }
848
849         if (gl_info->supported[ARB_OCCLUSION_QUERY])
850             GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
851
852         if (gl_info->supported[ARB_SYNC])
853         {
854             if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
855         }
856         else if (gl_info->supported[APPLE_FENCE])
857         {
858             for (i = 0; i < context->free_event_query_count; ++i)
859             {
860                 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
861             }
862         }
863         else if (gl_info->supported[NV_FENCE])
864         {
865             for (i = 0; i < context->free_event_query_count; ++i)
866             {
867                 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
868             }
869         }
870
871         checkGLcall("context cleanup");
872     }
873
874     LEAVE_GL();
875
876     HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
877     HeapFree(GetProcessHeap(), 0, context->free_event_queries);
878
879     if (restore_ctx)
880     {
881         if (!pwglMakeCurrent(restore_dc, restore_ctx))
882         {
883             DWORD err = GetLastError();
884             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
885                     restore_ctx, restore_dc, err);
886         }
887     }
888     else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
889     {
890         ERR("Failed to disable GL context.\n");
891     }
892
893     ReleaseDC(context->win_handle, context->hdc);
894
895     if (!pwglDeleteContext(context->glCtx))
896     {
897         DWORD err = GetLastError();
898         ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
899     }
900 }
901
902 DWORD context_get_tls_idx(void)
903 {
904     return wined3d_context_tls_idx;
905 }
906
907 void context_set_tls_idx(DWORD idx)
908 {
909     wined3d_context_tls_idx = idx;
910 }
911
912 struct wined3d_context *context_get_current(void)
913 {
914     return TlsGetValue(wined3d_context_tls_idx);
915 }
916
917 BOOL context_set_current(struct wined3d_context *ctx)
918 {
919     struct wined3d_context *old = context_get_current();
920
921     if (old == ctx)
922     {
923         TRACE("Already using D3D context %p.\n", ctx);
924         return TRUE;
925     }
926
927     if (old)
928     {
929         if (old->destroyed)
930         {
931             TRACE("Switching away from destroyed context %p.\n", old);
932             context_destroy_gl_resources(old);
933             HeapFree(GetProcessHeap(), 0, old);
934         }
935         else
936         {
937             old->current = 0;
938         }
939     }
940
941     if (ctx)
942     {
943         TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
944         if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
945         {
946             DWORD err = GetLastError();
947             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
948                     ctx->glCtx, ctx->hdc, err);
949             TlsSetValue(wined3d_context_tls_idx, NULL);
950             return FALSE;
951         }
952         ctx->current = 1;
953     }
954     else if(pwglGetCurrentContext())
955     {
956         TRACE("Clearing current D3D context.\n");
957         if (!pwglMakeCurrent(NULL, NULL))
958         {
959             DWORD err = GetLastError();
960             ERR("Failed to clear current GL context, last error %#x.\n", err);
961             TlsSetValue(wined3d_context_tls_idx, NULL);
962             return FALSE;
963         }
964     }
965
966     return TlsSetValue(wined3d_context_tls_idx, ctx);
967 }
968
969 void context_release(struct wined3d_context *context)
970 {
971     TRACE("Releasing context %p, level %u.\n", context, context->level);
972
973     if (WARN_ON(d3d))
974     {
975         if (!context->level)
976             WARN("Context %p is not active.\n", context);
977         else if (context != context_get_current())
978             WARN("Context %p is not the current context.\n", context);
979     }
980
981     if (!--context->level && context->restore_ctx)
982     {
983         TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
984         if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
985         {
986             DWORD err = GetLastError();
987             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
988                     context->restore_ctx, context->restore_dc, err);
989         }
990         context->restore_ctx = NULL;
991         context->restore_dc = NULL;
992     }
993 }
994
995 static void context_enter(struct wined3d_context *context)
996 {
997     TRACE("Entering context %p, level %u.\n", context, context->level + 1);
998
999     if (!context->level++)
1000     {
1001         const struct wined3d_context *current_context = context_get_current();
1002         HGLRC current_gl = pwglGetCurrentContext();
1003
1004         if (current_gl && (!current_context || current_context->glCtx != current_gl))
1005         {
1006             TRACE("Another GL context (%p on device context %p) is already current.\n",
1007                     current_gl, pwglGetCurrentDC());
1008             context->restore_ctx = current_gl;
1009             context->restore_dc = pwglGetCurrentDC();
1010         }
1011     }
1012 }
1013
1014 /*****************************************************************************
1015  * Context_MarkStateDirty
1016  *
1017  * Marks a state in a context dirty. Only one context, opposed to
1018  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1019  * contexts
1020  *
1021  * Params:
1022  *  context: Context to mark the state dirty in
1023  *  state: State to mark dirty
1024  *  StateTable: Pointer to the state table in use(for state grouping)
1025  *
1026  *****************************************************************************/
1027 static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1028 {
1029     DWORD rep = StateTable[state].representative;
1030     DWORD idx;
1031     BYTE shift;
1032
1033     if (isStateDirty(context, rep)) return;
1034
1035     context->dirtyArray[context->numDirtyEntries++] = rep;
1036     idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1037     shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1038     context->isStateDirty[idx] |= (1 << shift);
1039 }
1040
1041 /* This function takes care of WineD3D pixel format selection. */
1042 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1043         const struct wined3d_format_desc *color_format_desc, const struct wined3d_format_desc *ds_format_desc,
1044         BOOL auxBuffers, int numSamples, BOOL findCompatible)
1045 {
1046     int iPixelFormat=0;
1047     unsigned int matchtry;
1048     short redBits, greenBits, blueBits, alphaBits, colorBits;
1049     short depthBits=0, stencilBits=0;
1050
1051     struct match_type {
1052         BOOL require_aux;
1053         BOOL exact_alpha;
1054         BOOL exact_color;
1055     } matches[] = {
1056         /* First, try without alpha match buffers. MacOS supports aux buffers only
1057          * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1058          * Then try without aux buffers - this is the most common cause for not
1059          * finding a pixel format. Also some drivers(the open source ones)
1060          * only offer 32 bit ARB pixel formats. First try without an exact alpha
1061          * match, then try without an exact alpha and color match.
1062          */
1063         { TRUE,  TRUE,  TRUE  },
1064         { TRUE,  FALSE, TRUE  },
1065         { FALSE, TRUE,  TRUE  },
1066         { FALSE, FALSE, TRUE  },
1067         { TRUE,  FALSE, FALSE },
1068         { FALSE, FALSE, FALSE },
1069     };
1070
1071     int i = 0;
1072     int nCfgs = This->adapter->nCfgs;
1073
1074     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1075           debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1076           auxBuffers, numSamples, findCompatible);
1077
1078     if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1079     {
1080         ERR("Unable to get color bits for format %s (%#x)!\n",
1081                 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1082         return 0;
1083     }
1084
1085     getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1086
1087     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1088         for(i=0; i<nCfgs; i++) {
1089             BOOL exactDepthMatch = TRUE;
1090             WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1091
1092             /* For now only accept RGBA formats. Perhaps some day we will
1093              * allow floating point formats for pbuffers. */
1094             if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1095                 continue;
1096
1097             /* In window mode we need a window drawable format and double buffering. */
1098             if(!(cfg->windowDrawable && cfg->doubleBuffer))
1099                 continue;
1100
1101             /* We like to have aux buffers in backbuffer mode */
1102             if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1103                 continue;
1104
1105             if(matches[matchtry].exact_color) {
1106                 if(cfg->redSize != redBits)
1107                     continue;
1108                 if(cfg->greenSize != greenBits)
1109                     continue;
1110                 if(cfg->blueSize != blueBits)
1111                     continue;
1112             } else {
1113                 if(cfg->redSize < redBits)
1114                     continue;
1115                 if(cfg->greenSize < greenBits)
1116                     continue;
1117                 if(cfg->blueSize < blueBits)
1118                     continue;
1119             }
1120             if(matches[matchtry].exact_alpha) {
1121                 if(cfg->alphaSize != alphaBits)
1122                     continue;
1123             } else {
1124                 if(cfg->alphaSize < alphaBits)
1125                     continue;
1126             }
1127
1128             /* We try to locate a format which matches our requirements exactly. In case of
1129              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1130             if(cfg->depthSize < depthBits)
1131                 continue;
1132             else if(cfg->depthSize > depthBits)
1133                 exactDepthMatch = FALSE;
1134
1135             /* In all cases make sure the number of stencil bits matches our requirements
1136              * even when we don't need stencil because it could affect performance EXCEPT
1137              * on cards which don't offer depth formats without stencil like the i915 drivers
1138              * on Linux. */
1139             if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1140                 continue;
1141
1142             /* Check multisampling support */
1143             if(cfg->numSamples != numSamples)
1144                 continue;
1145
1146             /* When we have passed all the checks then we have found a format which matches our
1147              * requirements. Note that we only check for a limit number of capabilities right now,
1148              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1149              * can still differ in things like multisampling, stereo, SRGB and other flags.
1150              */
1151
1152             /* Exit the loop as we have found a format :) */
1153             if(exactDepthMatch) {
1154                 iPixelFormat = cfg->iPixelFormat;
1155                 break;
1156             } else if(!iPixelFormat) {
1157                 /* In the end we might end up with a format which doesn't exactly match our depth
1158                  * requirements. Accept the first format we found because formats with higher iPixelFormat
1159                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1160                 iPixelFormat = cfg->iPixelFormat;
1161             }
1162         }
1163     }
1164
1165     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1166     if(!iPixelFormat && !findCompatible) {
1167         ERR("Can't find a suitable iPixelFormat\n");
1168         return FALSE;
1169     } else if(!iPixelFormat) {
1170         PIXELFORMATDESCRIPTOR pfd;
1171
1172         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1173         /* PixelFormat selection */
1174         ZeroMemory(&pfd, sizeof(pfd));
1175         pfd.nSize      = sizeof(pfd);
1176         pfd.nVersion   = 1;
1177         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1178         pfd.iPixelType = PFD_TYPE_RGBA;
1179         pfd.cAlphaBits = alphaBits;
1180         pfd.cColorBits = colorBits;
1181         pfd.cDepthBits = depthBits;
1182         pfd.cStencilBits = stencilBits;
1183         pfd.iLayerType = PFD_MAIN_PLANE;
1184
1185         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1186         if(!iPixelFormat) {
1187             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1188             ERR("Can't find a suitable iPixelFormat\n");
1189             return FALSE;
1190         }
1191     }
1192
1193     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1194             iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1195     return iPixelFormat;
1196 }
1197
1198 /*****************************************************************************
1199  * context_create
1200  *
1201  * Creates a new context.
1202  *
1203  * * Params:
1204  *  This: Device to activate the context for
1205  *  target: Surface this context will render to
1206  *  win_handle: handle to the window which we are drawing to
1207  *  pPresentParameters: contains the pixelformats to use for onscreen rendering
1208  *
1209  *****************************************************************************/
1210 struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target,
1211         const struct wined3d_format_desc *ds_format_desc)
1212 {
1213     IWineD3DDeviceImpl *device = swapchain->device;
1214     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1215     const struct wined3d_format_desc *color_format_desc;
1216     struct wined3d_context *ret;
1217     PIXELFORMATDESCRIPTOR pfd;
1218     BOOL auxBuffers = FALSE;
1219     int numSamples = 0;
1220     int pixel_format;
1221     unsigned int s;
1222     DWORD state;
1223     HGLRC ctx;
1224     HDC hdc;
1225
1226     TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1227
1228     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1229     if (!ret)
1230     {
1231         ERR("Failed to allocate context memory.\n");
1232         return NULL;
1233     }
1234
1235     if (!(hdc = GetDC(swapchain->win_handle)))
1236     {
1237         ERR("Failed to retrieve a device context.\n");
1238         goto out;
1239     }
1240
1241     color_format_desc = target->resource.format_desc;
1242
1243     /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1244      * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1245     if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1246     {
1247         auxBuffers = TRUE;
1248
1249         if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1250             color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, gl_info);
1251         else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1252             color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1253     }
1254
1255     /* DirectDraw supports 8bit paletted render targets and these are used by
1256      * old games like Starcraft and C&C. Most modern hardware doesn't support
1257      * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1258      * conversion (ab)uses the alpha component for storing the palette index.
1259      * For this reason we require a format with 8bit alpha, so request
1260      * A8R8G8B8. */
1261     if (color_format_desc->format == WINED3DFMT_P8_UINT)
1262         color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1263
1264     /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1265     if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1266     {
1267         if (!gl_info->supported[ARB_MULTISAMPLE])
1268             WARN("The application is requesting multisampling without support.\n");
1269         else
1270         {
1271             TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1272             numSamples = swapchain->presentParms.MultiSampleType;
1273         }
1274     }
1275
1276     /* Try to find a pixel format which matches our requirements. */
1277     pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1278             auxBuffers, numSamples, FALSE /* findCompatible */);
1279
1280     /* Try to locate a compatible format if we weren't able to find anything. */
1281     if (!pixel_format)
1282     {
1283         TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1284         pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1285                 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1286     }
1287
1288     /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1289     if (!pixel_format)
1290     {
1291         ERR("Can't find a suitable pixel format.\n");
1292         goto out;
1293     }
1294
1295     DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1296     if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1297     {
1298         ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1299         goto out;
1300     }
1301
1302     ctx = pwglCreateContext(hdc);
1303     if (device->numContexts)
1304     {
1305         if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1306         {
1307             DWORD err = GetLastError();
1308             ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1309                     device->contexts[0]->glCtx, ctx, err);
1310         }
1311     }
1312
1313     if(!ctx) {
1314         ERR("Failed to create a WGL context\n");
1315         goto out;
1316     }
1317
1318     if (!device_context_add(device, ret))
1319     {
1320         ERR("Failed to add the newly created context to the context list\n");
1321         if (!pwglDeleteContext(ctx))
1322         {
1323             DWORD err = GetLastError();
1324             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1325         }
1326         goto out;
1327     }
1328
1329     ret->gl_info = gl_info;
1330
1331     /* Mark all states dirty to force a proper initialization of the states
1332      * on the first use of the context. */
1333     for (state = 0; state <= STATE_HIGHEST; ++state)
1334     {
1335         if (device->StateTable[state].representative)
1336             Context_MarkStateDirty(ret, state, device->StateTable);
1337     }
1338
1339     ret->swapchain = swapchain;
1340     ret->current_rt = target;
1341     ret->tid = GetCurrentThreadId();
1342
1343     ret->render_offscreen = surface_is_offscreen(target);
1344     ret->draw_buffer_dirty = TRUE;
1345     ret->valid = 1;
1346
1347     ret->glCtx = ctx;
1348     ret->win_handle = swapchain->win_handle;
1349     ret->hdc = hdc;
1350     ret->pixel_format = pixel_format;
1351
1352     if (device->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *)device))
1353     {
1354         /* Create the dirty constants array and initialize them to dirty */
1355         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1356                 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1357         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1358                 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1359         memset(ret->vshader_const_dirty, 1,
1360                sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1361         memset(ret->pshader_const_dirty, 1,
1362                 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1363     }
1364
1365     ret->free_occlusion_query_size = 4;
1366     ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1367             ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1368     if (!ret->free_occlusion_queries) goto out;
1369
1370     list_init(&ret->occlusion_queries);
1371
1372     ret->free_event_query_size = 4;
1373     ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1374             ret->free_event_query_size * sizeof(*ret->free_event_queries));
1375     if (!ret->free_event_queries) goto out;
1376
1377     list_init(&ret->event_queries);
1378
1379     TRACE("Successfully created new context %p\n", ret);
1380
1381     list_init(&ret->fbo_list);
1382     list_init(&ret->fbo_destroy_list);
1383
1384     context_enter(ret);
1385
1386     /* Set up the context defaults */
1387     if (!context_set_current(ret))
1388     {
1389         ERR("Cannot activate context to set up defaults\n");
1390         context_release(ret);
1391         goto out;
1392     }
1393
1394     ENTER_GL();
1395
1396     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1397
1398     TRACE("Setting up the screen\n");
1399     /* Clear the screen */
1400     glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1401     checkGLcall("glClearColor");
1402     glClearIndex(0);
1403     glClearDepth(1);
1404     glClearStencil(0xffff);
1405
1406     checkGLcall("glClear");
1407
1408     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1409     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1410
1411     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1412     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1413
1414     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1415     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1416
1417     glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1418     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1419     glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1420     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1421
1422     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1423     {
1424         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1425          * and textures in DIB sections(due to the memory protection).
1426          */
1427         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1428         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1429     }
1430     if (gl_info->supported[ARB_VERTEX_BLEND])
1431     {
1432         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1433          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1434          * GL_VERTEX_BLEND_ARB isn't enabled too
1435          */
1436         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1437         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1438     }
1439     if (gl_info->supported[NV_TEXTURE_SHADER2])
1440     {
1441         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1442          * the previous texture where to source the offset from is always unit - 1.
1443          */
1444         for (s = 1; s < gl_info->limits.textures; ++s)
1445         {
1446             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1447             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1448             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1449         }
1450     }
1451     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1452     {
1453         /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1454          * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1455          * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1456          * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1457          * is ever assigned.
1458          *
1459          * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1460          * program and the dummy program is destroyed when the context is destroyed.
1461          */
1462         const char *dummy_program =
1463                 "!!ARBfp1.0\n"
1464                 "MOV result.color, fragment.color.primary;\n"
1465                 "END\n";
1466         GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1467         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1468         GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1469     }
1470
1471     for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1472     {
1473         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1474         glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1475         checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1476     }
1477
1478     if (gl_info->supported[ARB_PROVOKING_VERTEX])
1479     {
1480         GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1481     }
1482     else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1483     {
1484         GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1485     }
1486
1487     LEAVE_GL();
1488
1489     device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
1490
1491     TRACE("Created context %p.\n", ret);
1492
1493     return ret;
1494
1495 out:
1496     HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1497     HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1498     HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1499     HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1500     HeapFree(GetProcessHeap(), 0, ret);
1501     return NULL;
1502 }
1503
1504 /*****************************************************************************
1505  * context_destroy
1506  *
1507  * Destroys a wined3d context
1508  *
1509  * Params:
1510  *  This: Device to activate the context for
1511  *  context: Context to destroy
1512  *
1513  *****************************************************************************/
1514 void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1515 {
1516     BOOL destroy;
1517
1518     TRACE("Destroying ctx %p\n", context);
1519
1520     if (context->tid == GetCurrentThreadId() || !context->current)
1521     {
1522         context_destroy_gl_resources(context);
1523         TlsSetValue(wined3d_context_tls_idx, NULL);
1524         destroy = TRUE;
1525     }
1526     else
1527     {
1528         context->destroyed = 1;
1529         destroy = FALSE;
1530     }
1531
1532     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1533     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1534     device_context_remove(This, context);
1535     if (destroy) HeapFree(GetProcessHeap(), 0, context);
1536 }
1537
1538 /* GL locking is done by the caller */
1539 static inline void set_blit_dimension(UINT width, UINT height) {
1540     glMatrixMode(GL_PROJECTION);
1541     checkGLcall("glMatrixMode(GL_PROJECTION)");
1542     glLoadIdentity();
1543     checkGLcall("glLoadIdentity()");
1544     glOrtho(0, width, height, 0, 0.0, -1.0);
1545     checkGLcall("glOrtho");
1546     glViewport(0, 0, width, height);
1547     checkGLcall("glViewport");
1548 }
1549
1550 /*****************************************************************************
1551  * SetupForBlit
1552  *
1553  * Sets up a context for DirectDraw blitting.
1554  * All texture units are disabled, texture unit 0 is set as current unit
1555  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1556  * color writing enabled for all channels
1557  * register combiners disabled, shaders disabled
1558  * world matrix is set to identity, texture matrix 0 too
1559  * projection matrix is setup for drawing screen coordinates
1560  *
1561  * Params:
1562  *  This: Device to activate the context for
1563  *  context: Context to setup
1564  *
1565  *****************************************************************************/
1566 /* Context activation is done by the caller. */
1567 static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1568 {
1569     int i;
1570     const struct StateEntry *StateTable = This->StateTable;
1571     const struct wined3d_gl_info *gl_info = context->gl_info;
1572     UINT width = context->current_rt->currentDesc.Width;
1573     UINT height = context->current_rt->currentDesc.Height;
1574     DWORD sampler;
1575
1576     TRACE("Setting up context %p for blitting\n", context);
1577     if(context->last_was_blit) {
1578         if(context->blit_w != width || context->blit_h != height) {
1579             ENTER_GL();
1580             set_blit_dimension(width, height);
1581             LEAVE_GL();
1582             context->blit_w = width; context->blit_h = height;
1583             /* No need to dirtify here, the states are still dirtified because they weren't
1584              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1585              * be set
1586              */
1587         }
1588         TRACE("Context is already set up for blitting, nothing to do\n");
1589         return;
1590     }
1591     context->last_was_blit = TRUE;
1592
1593     /* TODO: Use a display list */
1594
1595     /* Disable shaders */
1596     ENTER_GL();
1597     This->shader_backend->shader_select(context, FALSE, FALSE);
1598     LEAVE_GL();
1599
1600     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1601     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1602
1603     /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1604      * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1605      * which can safely be called from here, we only lock once instead locking/unlocking
1606      * after each GL call.
1607      */
1608     ENTER_GL();
1609
1610     /* Disable all textures. The caller can then bind a texture it wants to blit
1611      * from
1612      *
1613      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1614      * function texture unit. No need to care for higher samplers
1615      */
1616     for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1617     {
1618         sampler = This->rev_tex_unit_map[i];
1619         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1620         checkGLcall("glActiveTextureARB");
1621
1622         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1623         {
1624             glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1625             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1626         }
1627         glDisable(GL_TEXTURE_3D);
1628         checkGLcall("glDisable GL_TEXTURE_3D");
1629         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1630         {
1631             glDisable(GL_TEXTURE_RECTANGLE_ARB);
1632             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1633         }
1634         glDisable(GL_TEXTURE_2D);
1635         checkGLcall("glDisable GL_TEXTURE_2D");
1636
1637         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1638         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1639
1640         if (sampler != WINED3D_UNMAPPED_STAGE)
1641         {
1642             if (sampler < MAX_TEXTURES) {
1643                 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1644             }
1645             Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1646         }
1647     }
1648     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1649     checkGLcall("glActiveTextureARB");
1650
1651     sampler = This->rev_tex_unit_map[0];
1652
1653     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1654     {
1655         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1656         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1657     }
1658     glDisable(GL_TEXTURE_3D);
1659     checkGLcall("glDisable GL_TEXTURE_3D");
1660     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1661     {
1662         glDisable(GL_TEXTURE_RECTANGLE_ARB);
1663         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1664     }
1665     glDisable(GL_TEXTURE_2D);
1666     checkGLcall("glDisable GL_TEXTURE_2D");
1667
1668     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1669
1670     glMatrixMode(GL_TEXTURE);
1671     checkGLcall("glMatrixMode(GL_TEXTURE)");
1672     glLoadIdentity();
1673     checkGLcall("glLoadIdentity()");
1674
1675     if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1676     {
1677         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1678                   GL_TEXTURE_LOD_BIAS_EXT,
1679                   0.0f);
1680         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1681     }
1682
1683     if (sampler != WINED3D_UNMAPPED_STAGE)
1684     {
1685         if (sampler < MAX_TEXTURES) {
1686             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1687             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1688         }
1689         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1690     }
1691
1692     /* Other misc states */
1693     glDisable(GL_ALPHA_TEST);
1694     checkGLcall("glDisable(GL_ALPHA_TEST)");
1695     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1696     glDisable(GL_LIGHTING);
1697     checkGLcall("glDisable GL_LIGHTING");
1698     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1699     glDisable(GL_DEPTH_TEST);
1700     checkGLcall("glDisable GL_DEPTH_TEST");
1701     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1702     glDisableWINE(GL_FOG);
1703     checkGLcall("glDisable GL_FOG");
1704     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1705     glDisable(GL_BLEND);
1706     checkGLcall("glDisable GL_BLEND");
1707     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1708     glDisable(GL_CULL_FACE);
1709     checkGLcall("glDisable GL_CULL_FACE");
1710     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1711     glDisable(GL_STENCIL_TEST);
1712     checkGLcall("glDisable GL_STENCIL_TEST");
1713     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1714     glDisable(GL_SCISSOR_TEST);
1715     checkGLcall("glDisable GL_SCISSOR_TEST");
1716     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1717     if (gl_info->supported[ARB_POINT_SPRITE])
1718     {
1719         glDisable(GL_POINT_SPRITE_ARB);
1720         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1721         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1722     }
1723     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1724     checkGLcall("glColorMask");
1725     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1726     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
1727     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
1728     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
1729     if (gl_info->supported[EXT_SECONDARY_COLOR])
1730     {
1731         glDisable(GL_COLOR_SUM_EXT);
1732         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1733         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1734     }
1735
1736     /* Setup transforms */
1737     glMatrixMode(GL_MODELVIEW);
1738     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1739     glLoadIdentity();
1740     checkGLcall("glLoadIdentity()");
1741     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1742
1743     context->last_was_rhw = TRUE;
1744     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1745
1746     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1747     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1748     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1749     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1750     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1751     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1752     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1753
1754     set_blit_dimension(width, height);
1755
1756     LEAVE_GL();
1757
1758     context->blit_w = width; context->blit_h = height;
1759     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1760     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1761
1762
1763     This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1764 }
1765
1766 /*****************************************************************************
1767  * findThreadContextForSwapChain
1768  *
1769  * Searches a swapchain for all contexts and picks one for the thread tid.
1770  * If none can be found the swapchain is requested to create a new context
1771  *
1772  *****************************************************************************/
1773 static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1774 {
1775     unsigned int i;
1776
1777     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1778         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1779             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1780         }
1781
1782     }
1783
1784     /* Create a new context for the thread */
1785     return swapchain_create_context_for_thread(swapchain);
1786 }
1787
1788 /*****************************************************************************
1789  * FindContext
1790  *
1791  * Finds a context for the current render target and thread
1792  *
1793  * Parameters:
1794  *  target: Render target to find the context for
1795  *  tid: Thread to activate the context for
1796  *
1797  * Returns: The needed context
1798  *
1799  *****************************************************************************/
1800 static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target)
1801 {
1802     IWineD3DSwapChain *swapchain = NULL;
1803     struct wined3d_context *current_context = context_get_current();
1804     DWORD tid = GetCurrentThreadId();
1805     struct wined3d_context *context;
1806
1807     if (current_context && current_context->destroyed) current_context = NULL;
1808
1809     if (!target)
1810     {
1811         if (current_context
1812                 && current_context->current_rt
1813                 && current_context->swapchain->device == This)
1814         {
1815             target = current_context->current_rt;
1816         }
1817         else
1818         {
1819             IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1820             if (swapchain->back_buffers) target = swapchain->back_buffers[0];
1821             else target = swapchain->front_buffer;
1822         }
1823     }
1824
1825     if (current_context && current_context->current_rt == target)
1826     {
1827         context_validate(current_context);
1828         return current_context;
1829     }
1830
1831     if (target->Flags & SFLAG_SWAPCHAIN)
1832     {
1833         TRACE("Rendering onscreen\n");
1834
1835         swapchain = (IWineD3DSwapChain *)target->container;
1836         context = findThreadContextForSwapChain(swapchain, tid);
1837     }
1838     else
1839     {
1840         TRACE("Rendering offscreen\n");
1841
1842         /* Stay with the currently active context. */
1843         if (current_context && current_context->swapchain->device == This)
1844         {
1845             context = current_context;
1846         }
1847         else
1848         {
1849             /* This may happen if the app jumps straight into offscreen rendering
1850              * Start using the context of the primary swapchain. tid == 0 is no problem
1851              * for findThreadContextForSwapChain.
1852              *
1853              * Can also happen on thread switches - in that case findThreadContextForSwapChain
1854              * is perfect to call. */
1855             context = findThreadContextForSwapChain(This->swapchains[0], tid);
1856         }
1857     }
1858
1859     context_validate(context);
1860
1861     return context;
1862 }
1863
1864 /* Context activation is done by the caller. */
1865 static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
1866 {
1867     const struct wined3d_gl_info *gl_info = context->gl_info;
1868     IWineD3DSurfaceImpl *rt = context->current_rt;
1869     IWineD3DDeviceImpl *device;
1870
1871     device = rt->resource.device;
1872     if (!surface_is_offscreen(rt))
1873     {
1874         ENTER_GL();
1875         glDrawBuffer(surface_get_gl_buffer(rt));
1876         checkGLcall("glDrawBuffers()");
1877         LEAVE_GL();
1878     }
1879     else
1880     {
1881         ENTER_GL();
1882         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1883         {
1884             if (!blit)
1885             {
1886                 if (gl_info->supported[ARB_DRAW_BUFFERS])
1887                 {
1888                     GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, device->draw_buffers));
1889                     checkGLcall("glDrawBuffers()");
1890                 }
1891                 else
1892                 {
1893                     glDrawBuffer(device->draw_buffers[0]);
1894                     checkGLcall("glDrawBuffer()");
1895                 }
1896             } else {
1897                 glDrawBuffer(GL_COLOR_ATTACHMENT0);
1898                 checkGLcall("glDrawBuffer()");
1899             }
1900         }
1901         else
1902         {
1903             glDrawBuffer(device->offscreenBuffer);
1904             checkGLcall("glDrawBuffer()");
1905         }
1906         LEAVE_GL();
1907     }
1908 }
1909
1910 /* GL locking is done by the caller. */
1911 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1912 {
1913     glDrawBuffer(buffer);
1914     checkGLcall("glDrawBuffer()");
1915     context->draw_buffer_dirty = TRUE;
1916 }
1917
1918 static inline void context_set_render_offscreen(struct wined3d_context *context, const struct StateEntry *StateTable,
1919         BOOL offscreen)
1920 {
1921     if (context->render_offscreen == offscreen) return;
1922
1923     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1924     Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1925     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1926     Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1927     Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1928     context->render_offscreen = offscreen;
1929 }
1930
1931 static BOOL match_depth_stencil_format(const struct wined3d_format_desc *existing,
1932         const struct wined3d_format_desc *required)
1933 {
1934     short existing_depth, existing_stencil, required_depth, required_stencil;
1935
1936     if(existing == required) return TRUE;
1937     if((existing->Flags & WINED3DFMT_FLAG_FLOAT) != (required->Flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1938
1939     getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1940     getDepthStencilBits(required, &required_depth, &required_stencil);
1941
1942     if(existing_depth < required_depth) return FALSE;
1943     /* If stencil bits are used the exact amount is required - otherwise wrapping
1944      * won't work correctly */
1945     if(required_stencil && required_stencil != existing_stencil) return FALSE;
1946     return TRUE;
1947 }
1948 /* The caller provides a context */
1949 static void context_validate_onscreen_formats(IWineD3DDeviceImpl *device, struct wined3d_context *context)
1950 {
1951     /* Onscreen surfaces are always in a swapchain */
1952     IWineD3DSurfaceImpl *depth_stencil = device->depth_stencil;
1953     IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)context->current_rt->container;
1954
1955     if (!depth_stencil) return;
1956     if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format_desc)) return;
1957
1958     /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
1959      * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
1960      * format. */
1961     WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
1962
1963     /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
1964     IWineD3DSurface_LoadLocation((IWineD3DSurface *)context->current_rt, SFLAG_INTEXTURE, NULL);
1965     swapchain->render_to_fbo = TRUE;
1966     context_set_render_offscreen(context, device->StateTable, TRUE);
1967 }
1968
1969 /* Context activation is done by the caller. */
1970 void context_apply_blit_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
1971 {
1972     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1973     {
1974         if (context->render_offscreen)
1975         {
1976             FIXME("Applying blit state for an offscreen target with ORM_FBO. This should be avoided.\n");
1977             surface_internal_preload(context->current_rt, SRGB_RGB);
1978
1979             ENTER_GL();
1980             context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
1981             context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, context->current_rt);
1982             context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
1983             LEAVE_GL();
1984         }
1985         else
1986         {
1987             context_validate_onscreen_formats(device, context);
1988
1989             ENTER_GL();
1990             context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
1991             LEAVE_GL();
1992         }
1993
1994         context->draw_buffer_dirty = TRUE;
1995     }
1996
1997     if (context->draw_buffer_dirty)
1998     {
1999         context_apply_draw_buffer(context, TRUE);
2000         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2001             context->draw_buffer_dirty = FALSE;
2002     }
2003
2004     SetupForBlit(device, context);
2005 }
2006
2007 /* Context activation is done by the caller. */
2008 void context_apply_clear_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2009 {
2010     const struct StateEntry *state_table = device->StateTable;
2011
2012     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2013     {
2014         if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2015         ENTER_GL();
2016         context_apply_fbo_state(context);
2017         LEAVE_GL();
2018     }
2019
2020     if (context->draw_buffer_dirty)
2021     {
2022         context_apply_draw_buffer(context, FALSE);
2023         context->draw_buffer_dirty = FALSE;
2024     }
2025
2026     if (context->last_was_blit)
2027     {
2028         device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2029     }
2030
2031     /* Blending and clearing should be orthogonal, but tests on the nvidia
2032      * driver show that disabling blending when clearing improves the clearing
2033      * performance incredibly. */
2034     ENTER_GL();
2035     glDisable(GL_BLEND);
2036     glEnable(GL_SCISSOR_TEST);
2037     checkGLcall("glEnable GL_SCISSOR_TEST");
2038     LEAVE_GL();
2039
2040     context->last_was_blit = FALSE;
2041     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2042     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2043     Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2044 }
2045
2046 /* Context activation is done by the caller. */
2047 void context_apply_draw_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2048 {
2049     const struct StateEntry *state_table = device->StateTable;
2050     unsigned int i;
2051
2052     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2053     {
2054         if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2055         ENTER_GL();
2056         context_apply_fbo_state(context);
2057         LEAVE_GL();
2058     }
2059
2060     if (context->draw_buffer_dirty)
2061     {
2062         context_apply_draw_buffer(context, FALSE);
2063         context->draw_buffer_dirty = FALSE;
2064     }
2065
2066     if (context->last_was_blit)
2067     {
2068         device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2069     }
2070
2071     IWineD3DDeviceImpl_FindTexUnitMap(device);
2072     device_preload_textures(device);
2073     if (isStateDirty(context, STATE_VDECL))
2074         device_update_stream_info(device, context->gl_info);
2075
2076     ENTER_GL();
2077     for (i = 0; i < context->numDirtyEntries; ++i)
2078     {
2079         DWORD rep = context->dirtyArray[i];
2080         DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2081         BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2082         context->isStateDirty[idx] &= ~(1 << shift);
2083         state_table[rep].apply(rep, device->stateBlock, context);
2084     }
2085     LEAVE_GL();
2086     context->numDirtyEntries = 0; /* This makes the whole list clean */
2087     context->last_was_blit = FALSE;
2088 }
2089
2090 static void context_setup_target(IWineD3DDeviceImpl *device,
2091         struct wined3d_context *context, IWineD3DSurfaceImpl *target)
2092 {
2093     BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2094     const struct StateEntry *StateTable = device->StateTable;
2095
2096     if (!target) return;
2097     else if (context->current_rt == target) return;
2098     render_offscreen = surface_is_offscreen(target);
2099
2100     context_set_render_offscreen(context, StateTable, render_offscreen);
2101
2102     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2103      * the alpha blend state changes with different render target formats. */
2104     if (!context->current_rt)
2105     {
2106         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2107     }
2108     else
2109     {
2110         const struct wined3d_format_desc *old = context->current_rt->resource.format_desc;
2111         const struct wined3d_format_desc *new = target->resource.format_desc;
2112
2113         if (old->format != new->format)
2114         {
2115             /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2116             if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2117                     || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2118             {
2119                 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2120             }
2121         }
2122
2123         /* When switching away from an offscreen render target, and we're not
2124          * using FBOs, we have to read the drawable into the texture. This is
2125          * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2126          * are some things that need care though. PreLoad needs a GL context,
2127          * and FindContext is called before the context is activated. It also
2128          * has to be called with the old rendertarget active, otherwise a
2129          * wrong drawable is read. */
2130         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2131                 && old_render_offscreen && context->current_rt != target)
2132         {
2133             BOOL oldInDraw = device->isInDraw;
2134
2135             /* surface_internal_preload() requires a context to load the
2136              * texture, so it will call context_acquire(). Set isInDraw to true
2137              * to signal surface_internal_preload() that it has a context. */
2138
2139             /* FIXME: This is just broken. There's no guarantee whatsoever
2140              * that the currently active context, if any, is appropriate for
2141              * reading back the render target. We should probably call
2142              * context_set_current(context) here and then rely on
2143              * context_acquire() doing the right thing. */
2144             device->isInDraw = TRUE;
2145
2146             /* Read the back buffer of the old drawable into the destination texture. */
2147             if (context->current_rt->texture_name_srgb)
2148             {
2149                 surface_internal_preload(context->current_rt, SRGB_BOTH);
2150             }
2151             else
2152             {
2153                 surface_internal_preload(context->current_rt, SRGB_RGB);
2154             }
2155
2156             IWineD3DSurface_ModifyLocation((IWineD3DSurface *)context->current_rt, SFLAG_INDRAWABLE, FALSE);
2157
2158             device->isInDraw = oldInDraw;
2159         }
2160     }
2161
2162     context->draw_buffer_dirty = TRUE;
2163     context->current_rt = target;
2164 }
2165
2166 /*****************************************************************************
2167  * context_acquire
2168  *
2169  * Finds a rendering context and drawable matching the device and render
2170  * target for the current thread, activates them and puts them into the
2171  * requested state.
2172  *
2173  * Params:
2174  *  This: Device to activate the context for
2175  *  target: Requested render target
2176  *  usage: Prepares the context for blitting, drawing or other actions
2177  *
2178  *****************************************************************************/
2179 struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *target)
2180 {
2181     struct wined3d_context *current_context = context_get_current();
2182     struct wined3d_context *context;
2183
2184     TRACE("device %p, target %p.\n", device, target);
2185
2186     context = FindContext(device, target);
2187     context_setup_target(device, context, target);
2188     context_enter(context);
2189     if (!context->valid) return context;
2190
2191     if (context != current_context)
2192     {
2193         if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2194         else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2195
2196         if (context->vshader_const_dirty)
2197         {
2198             memset(context->vshader_const_dirty, 1,
2199                     sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2200             device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2201         }
2202         if (context->pshader_const_dirty)
2203         {
2204             memset(context->pshader_const_dirty, 1,
2205                    sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2206             device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2207         }
2208     }
2209     else if (context->restore_ctx)
2210     {
2211         if (!pwglMakeCurrent(context->hdc, context->glCtx))
2212         {
2213             DWORD err = GetLastError();
2214             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2215                     context->hdc, context->glCtx, err);
2216         }
2217     }
2218
2219     return context;
2220 }