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