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