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