wined3d: Fix the EXT_blend_minmax extension definitions.
[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-2010 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         IWineD3DSurfaceImpl *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         IWineD3DDeviceImpl *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             IWineD3DDeviceImpl_MarkStateDirty(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, IWineD3DSurfaceImpl *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, IWineD3DSurfaceImpl *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 static 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     status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
308     if (status == GL_FRAMEBUFFER_COMPLETE)
309     {
310         TRACE("FBO complete\n");
311     } else {
312         IWineD3DSurfaceImpl *attachment;
313         unsigned int i;
314         FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
315
316         if (!context->current_fbo)
317         {
318             ERR("FBO 0 is incomplete, driver bug?\n");
319             return;
320         }
321
322         FIXME("\tLocation %s (%#x).\n", debug_surflocation(context->current_fbo->location),
323                 context->current_fbo->location);
324
325         /* Dump the FBO attachments */
326         for (i = 0; i < gl_info->limits.buffers; ++i)
327         {
328             attachment = context->current_fbo->render_targets[i];
329             if (attachment)
330             {
331                 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
332                         i, attachment, debug_d3dformat(attachment->resource.format->id),
333                         attachment->pow2Width, attachment->pow2Height);
334             }
335         }
336         attachment = context->current_fbo->depth_stencil;
337         if (attachment)
338         {
339             FIXME("\tDepth attachment: (%p) %s %ux%u\n",
340                     attachment, debug_d3dformat(attachment->resource.format->id),
341                     attachment->pow2Width, attachment->pow2Height);
342         }
343     }
344 }
345
346 static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context,
347         IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
348 {
349     const struct wined3d_gl_info *gl_info = context->gl_info;
350     struct fbo_entry *entry;
351
352     entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
353     entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
354     memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
355     entry->depth_stencil = depth_stencil;
356     entry->location = location;
357     entry->attached = FALSE;
358     entry->id = 0;
359
360     return entry;
361 }
362
363 /* GL locking is done by the caller */
364 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
365         IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil,
366         DWORD location, struct fbo_entry *entry)
367 {
368     const struct wined3d_gl_info *gl_info = context->gl_info;
369
370     context_bind_fbo(context, target, &entry->id);
371     context_clean_fbo_attachments(gl_info, target);
372
373     memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
374     entry->depth_stencil = depth_stencil;
375     entry->location = location;
376     entry->attached = FALSE;
377 }
378
379 /* GL locking is done by the caller */
380 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
381 {
382     if (entry->id)
383     {
384         TRACE("Destroy FBO %d\n", entry->id);
385         context_destroy_fbo(context, &entry->id);
386     }
387     --context->fbo_entry_count;
388     list_remove(&entry->entry);
389     HeapFree(GetProcessHeap(), 0, entry->render_targets);
390     HeapFree(GetProcessHeap(), 0, entry);
391 }
392
393
394 /* GL locking is done by the caller */
395 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
396         IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
397 {
398     const struct wined3d_gl_info *gl_info = context->gl_info;
399     struct fbo_entry *entry;
400
401     if (depth_stencil && render_targets && render_targets[0])
402     {
403         if (depth_stencil->resource.width < render_targets[0]->resource.width ||
404             depth_stencil->resource.height < render_targets[0]->resource.height)
405         {
406             WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
407             depth_stencil = NULL;
408         }
409     }
410
411     LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
412     {
413         if (!memcmp(entry->render_targets,
414                 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
415                 && entry->depth_stencil == depth_stencil && entry->location == location)
416         {
417             list_remove(&entry->entry);
418             list_add_head(&context->fbo_list, &entry->entry);
419             return entry;
420         }
421     }
422
423     if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
424     {
425         entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
426         list_add_head(&context->fbo_list, &entry->entry);
427         ++context->fbo_entry_count;
428     }
429     else
430     {
431         entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
432         context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
433         list_remove(&entry->entry);
434         list_add_head(&context->fbo_list, &entry->entry);
435     }
436
437     return entry;
438 }
439
440 /* GL locking is done by the caller */
441 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
442 {
443     const struct wined3d_gl_info *gl_info = context->gl_info;
444     unsigned int i;
445
446     context_bind_fbo(context, target, &entry->id);
447
448     if (!entry->attached)
449     {
450         /* Apply render targets */
451         for (i = 0; i < gl_info->limits.buffers; ++i)
452         {
453             context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
454         }
455
456         /* Apply depth targets */
457         if (entry->depth_stencil)
458         {
459             surface_set_compatible_renderbuffer(entry->depth_stencil,
460                     entry->render_targets[0]->pow2Width, entry->render_targets[0]->pow2Height);
461         }
462         context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, TRUE);
463
464         entry->attached = TRUE;
465     }
466     else
467     {
468         for (i = 0; i < gl_info->limits.buffers; ++i)
469         {
470             if (entry->render_targets[i])
471                 context_apply_attachment_filter_states(context, entry->render_targets[i], entry->location);
472         }
473         if (entry->depth_stencil)
474             context_apply_attachment_filter_states(context, entry->depth_stencil, SFLAG_INTEXTURE);
475     }
476 }
477
478 /* GL locking is done by the caller */
479 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
480         IWineD3DSurfaceImpl **render_targets, IWineD3DSurfaceImpl *depth_stencil, DWORD location)
481 {
482     struct fbo_entry *entry, *entry2;
483
484     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
485     {
486         context_destroy_fbo_entry(context, entry);
487     }
488
489     if (context->rebind_fbo)
490     {
491         context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
492         context->rebind_fbo = FALSE;
493     }
494
495     if (render_targets)
496     {
497         context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
498         context_apply_fbo_entry(context, target, context->current_fbo);
499     }
500     else
501     {
502         context->current_fbo = NULL;
503         context_bind_fbo(context, target, NULL);
504     }
505
506     context_check_fbo_status(context, target);
507 }
508
509 /* GL locking is done by the caller */
510 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
511         IWineD3DSurfaceImpl *render_target, IWineD3DSurfaceImpl *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(IWineD3DDeviceImpl *device,
658         IWineD3DSurfaceImpl *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 IWineD3DDeviceImpl *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 IWineD3DDeviceImpl *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, IWineD3DSurfaceImpl *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 void context_update_window(struct wined3d_context *context)
802 {
803     TRACE("Updating context %p window from %p to %p.\n",
804             context, context->win_handle, context->swapchain->win_handle);
805
806     if (context->valid)
807     {
808         if (!ReleaseDC(context->win_handle, context->hdc))
809         {
810             ERR("Failed to release device context %p, last error %#x.\n",
811                     context->hdc, GetLastError());
812         }
813     }
814     else context->valid = 1;
815
816     context->win_handle = context->swapchain->win_handle;
817
818     if (!(context->hdc = GetDC(context->win_handle)))
819     {
820         ERR("Failed to get a device context for window %p.\n", context->win_handle);
821         goto err;
822     }
823
824     if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
825     {
826         ERR("Failed to set pixel format %d on device context %p.\n",
827                 context->pixel_format, context->hdc);
828         goto err;
829     }
830
831     if (!pwglMakeCurrent(context->hdc, context->glCtx))
832     {
833         ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
834                 context->glCtx, context->hdc, GetLastError());
835         goto err;
836     }
837
838     return;
839
840 err:
841     context->valid = 0;
842 }
843
844 /* Do not call while under the GL lock. */
845 static void context_validate(struct wined3d_context *context)
846 {
847     HWND wnd = WindowFromDC(context->hdc);
848
849     if (wnd != context->win_handle)
850     {
851         WARN("DC %p belongs to window %p instead of %p.\n",
852                 context->hdc, wnd, context->win_handle);
853         context->valid = 0;
854     }
855
856     if (context->win_handle != context->swapchain->win_handle)
857         context_update_window(context);
858 }
859
860 /* Do not call while under the GL lock. */
861 static void context_destroy_gl_resources(struct wined3d_context *context)
862 {
863     const struct wined3d_gl_info *gl_info = context->gl_info;
864     struct wined3d_occlusion_query *occlusion_query;
865     struct wined3d_event_query *event_query;
866     struct fbo_entry *entry, *entry2;
867     HGLRC restore_ctx;
868     HDC restore_dc;
869     unsigned int i;
870
871     restore_ctx = pwglGetCurrentContext();
872     restore_dc = pwglGetCurrentDC();
873
874     context_validate(context);
875     if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
876     else restore_ctx = NULL;
877
878     ENTER_GL();
879
880     LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
881     {
882         if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
883             GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
884         occlusion_query->context = NULL;
885     }
886
887     LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
888     {
889         if (context->valid)
890         {
891             if (gl_info->supported[ARB_SYNC])
892             {
893                 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
894             }
895             else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
896             else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
897         }
898         event_query->context = NULL;
899     }
900
901     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
902     {
903         if (!context->valid) entry->id = 0;
904         context_destroy_fbo_entry(context, entry);
905     }
906
907     LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
908     {
909         if (!context->valid) entry->id = 0;
910         context_destroy_fbo_entry(context, entry);
911     }
912
913     if (context->valid)
914     {
915         if (context->dst_fbo)
916         {
917             TRACE("Destroy dst FBO %d\n", context->dst_fbo);
918             context_destroy_fbo(context, &context->dst_fbo);
919         }
920         if (context->dummy_arbfp_prog)
921         {
922             GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
923         }
924
925         if (gl_info->supported[ARB_OCCLUSION_QUERY])
926             GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
927
928         if (gl_info->supported[ARB_SYNC])
929         {
930             if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
931         }
932         else if (gl_info->supported[APPLE_FENCE])
933         {
934             for (i = 0; i < context->free_event_query_count; ++i)
935             {
936                 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
937             }
938         }
939         else if (gl_info->supported[NV_FENCE])
940         {
941             for (i = 0; i < context->free_event_query_count; ++i)
942             {
943                 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
944             }
945         }
946
947         checkGLcall("context cleanup");
948     }
949
950     LEAVE_GL();
951
952     HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
953     HeapFree(GetProcessHeap(), 0, context->free_event_queries);
954
955     if (restore_ctx)
956     {
957         if (!pwglMakeCurrent(restore_dc, restore_ctx))
958         {
959             DWORD err = GetLastError();
960             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
961                     restore_ctx, restore_dc, err);
962         }
963     }
964     else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
965     {
966         ERR("Failed to disable GL context.\n");
967     }
968
969     ReleaseDC(context->win_handle, context->hdc);
970
971     if (!pwglDeleteContext(context->glCtx))
972     {
973         DWORD err = GetLastError();
974         ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
975     }
976 }
977
978 DWORD context_get_tls_idx(void)
979 {
980     return wined3d_context_tls_idx;
981 }
982
983 void context_set_tls_idx(DWORD idx)
984 {
985     wined3d_context_tls_idx = idx;
986 }
987
988 struct wined3d_context *context_get_current(void)
989 {
990     return TlsGetValue(wined3d_context_tls_idx);
991 }
992
993 /* Do not call while under the GL lock. */
994 BOOL context_set_current(struct wined3d_context *ctx)
995 {
996     struct wined3d_context *old = context_get_current();
997
998     if (old == ctx)
999     {
1000         TRACE("Already using D3D context %p.\n", ctx);
1001         return TRUE;
1002     }
1003
1004     if (old)
1005     {
1006         if (old->destroyed)
1007         {
1008             TRACE("Switching away from destroyed context %p.\n", old);
1009             context_destroy_gl_resources(old);
1010             HeapFree(GetProcessHeap(), 0, old);
1011         }
1012         else
1013         {
1014             old->current = 0;
1015         }
1016     }
1017
1018     if (ctx)
1019     {
1020         TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1021         if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
1022         {
1023             DWORD err = GetLastError();
1024             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
1025                     ctx->glCtx, ctx->hdc, err);
1026             TlsSetValue(wined3d_context_tls_idx, NULL);
1027             return FALSE;
1028         }
1029         ctx->current = 1;
1030     }
1031     else if(pwglGetCurrentContext())
1032     {
1033         TRACE("Clearing current D3D context.\n");
1034         if (!pwglMakeCurrent(NULL, NULL))
1035         {
1036             DWORD err = GetLastError();
1037             ERR("Failed to clear current GL context, last error %#x.\n", err);
1038             TlsSetValue(wined3d_context_tls_idx, NULL);
1039             return FALSE;
1040         }
1041     }
1042
1043     return TlsSetValue(wined3d_context_tls_idx, ctx);
1044 }
1045
1046 void context_release(struct wined3d_context *context)
1047 {
1048     TRACE("Releasing context %p, level %u.\n", context, context->level);
1049
1050     if (WARN_ON(d3d))
1051     {
1052         if (!context->level)
1053             WARN("Context %p is not active.\n", context);
1054         else if (context != context_get_current())
1055             WARN("Context %p is not the current context.\n", context);
1056     }
1057
1058     if (!--context->level && context->restore_ctx)
1059     {
1060         TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1061         if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
1062         {
1063             DWORD err = GetLastError();
1064             ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1065                     context->restore_ctx, context->restore_dc, err);
1066         }
1067         context->restore_ctx = NULL;
1068         context->restore_dc = NULL;
1069     }
1070 }
1071
1072 static void context_enter(struct wined3d_context *context)
1073 {
1074     TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1075
1076     if (!context->level++)
1077     {
1078         const struct wined3d_context *current_context = context_get_current();
1079         HGLRC current_gl = pwglGetCurrentContext();
1080
1081         if (current_gl && (!current_context || current_context->glCtx != current_gl))
1082         {
1083             TRACE("Another GL context (%p on device context %p) is already current.\n",
1084                     current_gl, pwglGetCurrentDC());
1085             context->restore_ctx = current_gl;
1086             context->restore_dc = pwglGetCurrentDC();
1087         }
1088     }
1089 }
1090
1091 /*****************************************************************************
1092  * Context_MarkStateDirty
1093  *
1094  * Marks a state in a context dirty. Only one context, opposed to
1095  * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1096  * contexts
1097  *
1098  * Params:
1099  *  context: Context to mark the state dirty in
1100  *  state: State to mark dirty
1101  *  StateTable: Pointer to the state table in use(for state grouping)
1102  *
1103  *****************************************************************************/
1104 static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1105 {
1106     DWORD rep = StateTable[state].representative;
1107     DWORD idx;
1108     BYTE shift;
1109
1110     if (isStateDirty(context, rep)) return;
1111
1112     context->dirtyArray[context->numDirtyEntries++] = rep;
1113     idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1114     shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1115     context->isStateDirty[idx] |= (1 << shift);
1116 }
1117
1118 /* This function takes care of WineD3D pixel format selection. */
1119 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1120         const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1121         BOOL auxBuffers, int numSamples, BOOL findCompatible)
1122 {
1123     int iPixelFormat=0;
1124     unsigned int matchtry;
1125     short redBits, greenBits, blueBits, alphaBits, colorBits;
1126     short depthBits=0, stencilBits=0;
1127
1128     static const struct
1129     {
1130         BOOL require_aux;
1131         BOOL exact_alpha;
1132         BOOL exact_color;
1133     }
1134     matches[] =
1135     {
1136         /* First, try without alpha match buffers. MacOS supports aux buffers only
1137          * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1138          * Then try without aux buffers - this is the most common cause for not
1139          * finding a pixel format. Also some drivers(the open source ones)
1140          * only offer 32 bit ARB pixel formats. First try without an exact alpha
1141          * match, then try without an exact alpha and color match.
1142          */
1143         { TRUE,  TRUE,  TRUE  },
1144         { TRUE,  FALSE, TRUE  },
1145         { FALSE, TRUE,  TRUE  },
1146         { FALSE, FALSE, TRUE  },
1147         { TRUE,  FALSE, FALSE },
1148         { FALSE, FALSE, FALSE },
1149     };
1150
1151     int i = 0;
1152     int nCfgs = This->adapter->nCfgs;
1153
1154     TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1155           debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1156           auxBuffers, numSamples, findCompatible);
1157
1158     if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1159     {
1160         ERR("Unable to get color bits for format %s (%#x)!\n",
1161                 debug_d3dformat(color_format->id), color_format->id);
1162         return 0;
1163     }
1164
1165     getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1166
1167     for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1168         for(i=0; i<nCfgs; i++) {
1169             BOOL exactDepthMatch = TRUE;
1170             WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1171
1172             /* For now only accept RGBA formats. Perhaps some day we will
1173              * allow floating point formats for pbuffers. */
1174             if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1175                 continue;
1176
1177             /* In window mode we need a window drawable format and double buffering. */
1178             if(!(cfg->windowDrawable && cfg->doubleBuffer))
1179                 continue;
1180
1181             /* We like to have aux buffers in backbuffer mode */
1182             if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1183                 continue;
1184
1185             if(matches[matchtry].exact_color) {
1186                 if(cfg->redSize != redBits)
1187                     continue;
1188                 if(cfg->greenSize != greenBits)
1189                     continue;
1190                 if(cfg->blueSize != blueBits)
1191                     continue;
1192             } else {
1193                 if(cfg->redSize < redBits)
1194                     continue;
1195                 if(cfg->greenSize < greenBits)
1196                     continue;
1197                 if(cfg->blueSize < blueBits)
1198                     continue;
1199             }
1200             if(matches[matchtry].exact_alpha) {
1201                 if(cfg->alphaSize != alphaBits)
1202                     continue;
1203             } else {
1204                 if(cfg->alphaSize < alphaBits)
1205                     continue;
1206             }
1207
1208             /* We try to locate a format which matches our requirements exactly. In case of
1209              * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1210             if(cfg->depthSize < depthBits)
1211                 continue;
1212             else if(cfg->depthSize > depthBits)
1213                 exactDepthMatch = FALSE;
1214
1215             /* In all cases make sure the number of stencil bits matches our requirements
1216              * even when we don't need stencil because it could affect performance EXCEPT
1217              * on cards which don't offer depth formats without stencil like the i915 drivers
1218              * on Linux. */
1219             if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1220                 continue;
1221
1222             /* Check multisampling support */
1223             if(cfg->numSamples != numSamples)
1224                 continue;
1225
1226             /* When we have passed all the checks then we have found a format which matches our
1227              * requirements. Note that we only check for a limit number of capabilities right now,
1228              * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1229              * can still differ in things like multisampling, stereo, SRGB and other flags.
1230              */
1231
1232             /* Exit the loop as we have found a format :) */
1233             if(exactDepthMatch) {
1234                 iPixelFormat = cfg->iPixelFormat;
1235                 break;
1236             } else if(!iPixelFormat) {
1237                 /* In the end we might end up with a format which doesn't exactly match our depth
1238                  * requirements. Accept the first format we found because formats with higher iPixelFormat
1239                  * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1240                 iPixelFormat = cfg->iPixelFormat;
1241             }
1242         }
1243     }
1244
1245     /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1246     if(!iPixelFormat && !findCompatible) {
1247         ERR("Can't find a suitable iPixelFormat\n");
1248         return FALSE;
1249     } else if(!iPixelFormat) {
1250         PIXELFORMATDESCRIPTOR pfd;
1251
1252         TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1253         /* PixelFormat selection */
1254         ZeroMemory(&pfd, sizeof(pfd));
1255         pfd.nSize      = sizeof(pfd);
1256         pfd.nVersion   = 1;
1257         pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1258         pfd.iPixelType = PFD_TYPE_RGBA;
1259         pfd.cAlphaBits = alphaBits;
1260         pfd.cColorBits = colorBits;
1261         pfd.cDepthBits = depthBits;
1262         pfd.cStencilBits = stencilBits;
1263         pfd.iLayerType = PFD_MAIN_PLANE;
1264
1265         iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1266         if(!iPixelFormat) {
1267             /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1268             ERR("Can't find a suitable iPixelFormat\n");
1269             return FALSE;
1270         }
1271     }
1272
1273     TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1274             iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1275     return iPixelFormat;
1276 }
1277
1278 /* Do not call while under the GL lock. */
1279 struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain,
1280         IWineD3DSurfaceImpl *target, const struct wined3d_format *ds_format)
1281 {
1282     IWineD3DDeviceImpl *device = swapchain->device;
1283     const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1284     const struct wined3d_format *color_format;
1285     struct wined3d_context *ret;
1286     PIXELFORMATDESCRIPTOR pfd;
1287     BOOL auxBuffers = FALSE;
1288     int numSamples = 0;
1289     int pixel_format;
1290     unsigned int s;
1291     int swap_interval;
1292     DWORD state;
1293     HGLRC ctx;
1294     HDC hdc;
1295
1296     TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1297
1298     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1299     if (!ret)
1300     {
1301         ERR("Failed to allocate context memory.\n");
1302         return NULL;
1303     }
1304
1305     if (!(hdc = GetDC(swapchain->win_handle)))
1306     {
1307         ERR("Failed to retrieve a device context.\n");
1308         goto out;
1309     }
1310
1311     color_format = target->resource.format;
1312
1313     /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1314      * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1315     if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1316     {
1317         auxBuffers = TRUE;
1318
1319         if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1320             color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1321         else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1322             color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1323     }
1324
1325     /* DirectDraw supports 8bit paletted render targets and these are used by
1326      * old games like Starcraft and C&C. Most modern hardware doesn't support
1327      * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1328      * conversion (ab)uses the alpha component for storing the palette index.
1329      * For this reason we require a format with 8bit alpha, so request
1330      * A8R8G8B8. */
1331     if (color_format->id == WINED3DFMT_P8_UINT)
1332         color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1333
1334     /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1335     if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1336     {
1337         if (!gl_info->supported[ARB_MULTISAMPLE])
1338             WARN("The application is requesting multisampling without support.\n");
1339         else
1340         {
1341             TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1342             numSamples = swapchain->presentParms.MultiSampleType;
1343         }
1344     }
1345
1346     /* Try to find a pixel format which matches our requirements. */
1347     pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format, ds_format,
1348             auxBuffers, numSamples, FALSE /* findCompatible */);
1349
1350     /* Try to locate a compatible format if we weren't able to find anything. */
1351     if (!pixel_format)
1352     {
1353         TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1354         pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format, ds_format,
1355                 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1356     }
1357
1358     /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1359     if (!pixel_format)
1360     {
1361         ERR("Can't find a suitable pixel format.\n");
1362         goto out;
1363     }
1364
1365     DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1366     if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1367     {
1368         ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1369         goto out;
1370     }
1371
1372     ctx = pwglCreateContext(hdc);
1373     if (device->context_count)
1374     {
1375         if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1376         {
1377             DWORD err = GetLastError();
1378             ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1379                     device->contexts[0]->glCtx, ctx, err);
1380         }
1381     }
1382
1383     if(!ctx) {
1384         ERR("Failed to create a WGL context\n");
1385         goto out;
1386     }
1387
1388     if (!device_context_add(device, ret))
1389     {
1390         ERR("Failed to add the newly created context to the context list\n");
1391         if (!pwglDeleteContext(ctx))
1392         {
1393             DWORD err = GetLastError();
1394             ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1395         }
1396         goto out;
1397     }
1398
1399     ret->gl_info = gl_info;
1400
1401     /* Mark all states dirty to force a proper initialization of the states
1402      * on the first use of the context. */
1403     for (state = 0; state <= STATE_HIGHEST; ++state)
1404     {
1405         if (device->StateTable[state].representative)
1406             Context_MarkStateDirty(ret, state, device->StateTable);
1407     }
1408
1409     ret->swapchain = swapchain;
1410     ret->current_rt = target;
1411     ret->tid = GetCurrentThreadId();
1412
1413     ret->render_offscreen = surface_is_offscreen(target);
1414     ret->draw_buffer_dirty = TRUE;
1415     ret->valid = 1;
1416
1417     ret->glCtx = ctx;
1418     ret->win_handle = swapchain->win_handle;
1419     ret->hdc = hdc;
1420     ret->pixel_format = pixel_format;
1421
1422     if (device->shader_backend->shader_dirtifyable_constants())
1423     {
1424         /* Create the dirty constants array and initialize them to dirty */
1425         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1426                 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1427         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1428                 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1429         memset(ret->vshader_const_dirty, 1,
1430                sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1431         memset(ret->pshader_const_dirty, 1,
1432                 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1433     }
1434
1435     ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1436             gl_info->limits.buffers * sizeof(*ret->blit_targets));
1437     if (!ret->blit_targets) goto out;
1438
1439     ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1440             gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1441     if (!ret->draw_buffers) goto out;
1442
1443     ret->free_occlusion_query_size = 4;
1444     ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1445             ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1446     if (!ret->free_occlusion_queries) goto out;
1447
1448     list_init(&ret->occlusion_queries);
1449
1450     ret->free_event_query_size = 4;
1451     ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1452             ret->free_event_query_size * sizeof(*ret->free_event_queries));
1453     if (!ret->free_event_queries) goto out;
1454
1455     list_init(&ret->event_queries);
1456
1457     TRACE("Successfully created new context %p\n", ret);
1458
1459     list_init(&ret->fbo_list);
1460     list_init(&ret->fbo_destroy_list);
1461
1462     context_enter(ret);
1463
1464     /* Set up the context defaults */
1465     if (!context_set_current(ret))
1466     {
1467         ERR("Cannot activate context to set up defaults\n");
1468         context_release(ret);
1469         goto out;
1470     }
1471
1472     switch (swapchain->presentParms.PresentationInterval)
1473     {
1474         case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1475             swap_interval = 0;
1476             break;
1477         case WINED3DPRESENT_INTERVAL_DEFAULT:
1478         case WINED3DPRESENT_INTERVAL_ONE:
1479             swap_interval = 1;
1480             break;
1481         case WINED3DPRESENT_INTERVAL_TWO:
1482             swap_interval = 2;
1483             break;
1484         case WINED3DPRESENT_INTERVAL_THREE:
1485             swap_interval = 3;
1486             break;
1487         case WINED3DPRESENT_INTERVAL_FOUR:
1488             swap_interval = 4;
1489             break;
1490         default:
1491             FIXME("Unknown presentation interval %08x\n", swapchain->presentParms.PresentationInterval);
1492             swap_interval = 1;
1493     }
1494
1495     if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1496     {
1497         if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1498             ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1499                 swap_interval, ret, GetLastError());
1500     }
1501
1502     ENTER_GL();
1503
1504     glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1505
1506     TRACE("Setting up the screen\n");
1507     /* Clear the screen */
1508     glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1509     checkGLcall("glClearColor");
1510     glClearIndex(0);
1511     glClearDepth(1);
1512     glClearStencil(0xffff);
1513
1514     checkGLcall("glClear");
1515
1516     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1517     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1518
1519     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1520     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1521
1522     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1523     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1524
1525     glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1526     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1527     glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1528     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1529
1530     if (gl_info->supported[APPLE_CLIENT_STORAGE])
1531     {
1532         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1533          * and textures in DIB sections(due to the memory protection).
1534          */
1535         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1536         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1537     }
1538     if (gl_info->supported[ARB_VERTEX_BLEND])
1539     {
1540         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1541          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1542          * GL_VERTEX_BLEND_ARB isn't enabled too
1543          */
1544         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1545         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1546     }
1547     if (gl_info->supported[NV_TEXTURE_SHADER2])
1548     {
1549         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1550          * the previous texture where to source the offset from is always unit - 1.
1551          */
1552         for (s = 1; s < gl_info->limits.textures; ++s)
1553         {
1554             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1555             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1556             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1557         }
1558     }
1559     if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1560     {
1561         /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1562          * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1563          * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1564          * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1565          * is ever assigned.
1566          *
1567          * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1568          * program and the dummy program is destroyed when the context is destroyed.
1569          */
1570         const char *dummy_program =
1571                 "!!ARBfp1.0\n"
1572                 "MOV result.color, fragment.color.primary;\n"
1573                 "END\n";
1574         GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1575         GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1576         GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1577     }
1578
1579     for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1580     {
1581         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1582         glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1583         checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1584     }
1585
1586     if (gl_info->supported[ARB_PROVOKING_VERTEX])
1587     {
1588         GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1589     }
1590     else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1591     {
1592         GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1593     }
1594
1595     LEAVE_GL();
1596
1597     device->frag_pipe->enable_extension(TRUE);
1598
1599     TRACE("Created context %p.\n", ret);
1600
1601     return ret;
1602
1603 out:
1604     HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1605     HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1606     HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1607     HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1608     HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1609     HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1610     HeapFree(GetProcessHeap(), 0, ret);
1611     return NULL;
1612 }
1613
1614 /* Do not call while under the GL lock. */
1615 void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1616 {
1617     BOOL destroy;
1618
1619     TRACE("Destroying ctx %p\n", context);
1620
1621     if (context->tid == GetCurrentThreadId() || !context->current)
1622     {
1623         context_destroy_gl_resources(context);
1624         TlsSetValue(wined3d_context_tls_idx, NULL);
1625         destroy = TRUE;
1626     }
1627     else
1628     {
1629         context->destroyed = 1;
1630         destroy = FALSE;
1631     }
1632
1633     HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1634     HeapFree(GetProcessHeap(), 0, context->blit_targets);
1635     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1636     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1637     device_context_remove(This, context);
1638     if (destroy) HeapFree(GetProcessHeap(), 0, context);
1639 }
1640
1641 /* GL locking is done by the caller */
1642 static inline void set_blit_dimension(UINT width, UINT height) {
1643     glMatrixMode(GL_PROJECTION);
1644     checkGLcall("glMatrixMode(GL_PROJECTION)");
1645     glLoadIdentity();
1646     checkGLcall("glLoadIdentity()");
1647     glOrtho(0, width, 0, height, 0.0, -1.0);
1648     checkGLcall("glOrtho");
1649     glViewport(0, 0, width, height);
1650     checkGLcall("glViewport");
1651 }
1652
1653 /*****************************************************************************
1654  * SetupForBlit
1655  *
1656  * Sets up a context for DirectDraw blitting.
1657  * All texture units are disabled, texture unit 0 is set as current unit
1658  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1659  * color writing enabled for all channels
1660  * register combiners disabled, shaders disabled
1661  * world matrix is set to identity, texture matrix 0 too
1662  * projection matrix is setup for drawing screen coordinates
1663  *
1664  * Params:
1665  *  This: Device to activate the context for
1666  *  context: Context to setup
1667  *
1668  *****************************************************************************/
1669 /* Context activation is done by the caller. */
1670 static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1671 {
1672     int i;
1673     const struct StateEntry *StateTable = This->StateTable;
1674     const struct wined3d_gl_info *gl_info = context->gl_info;
1675     UINT width = context->current_rt->resource.width;
1676     UINT height = context->current_rt->resource.height;
1677     DWORD sampler;
1678
1679     TRACE("Setting up context %p for blitting\n", context);
1680     if(context->last_was_blit) {
1681         if(context->blit_w != width || context->blit_h != height) {
1682             ENTER_GL();
1683             set_blit_dimension(width, height);
1684             LEAVE_GL();
1685             context->blit_w = width; context->blit_h = height;
1686             /* No need to dirtify here, the states are still dirtified because they weren't
1687              * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1688              * be set
1689              */
1690         }
1691         TRACE("Context is already set up for blitting, nothing to do\n");
1692         return;
1693     }
1694     context->last_was_blit = TRUE;
1695
1696     /* TODO: Use a display list */
1697
1698     /* Disable shaders */
1699     ENTER_GL();
1700     This->shader_backend->shader_select(context, FALSE, FALSE);
1701     LEAVE_GL();
1702
1703     Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1704     Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1705
1706     /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1707      * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1708      * which can safely be called from here, we only lock once instead locking/unlocking
1709      * after each GL call.
1710      */
1711     ENTER_GL();
1712
1713     /* Disable all textures. The caller can then bind a texture it wants to blit
1714      * from
1715      *
1716      * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1717      * function texture unit. No need to care for higher samplers
1718      */
1719     for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1720     {
1721         sampler = This->rev_tex_unit_map[i];
1722         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1723         checkGLcall("glActiveTextureARB");
1724
1725         if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1726         {
1727             glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1728             checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1729         }
1730         glDisable(GL_TEXTURE_3D);
1731         checkGLcall("glDisable GL_TEXTURE_3D");
1732         if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1733         {
1734             glDisable(GL_TEXTURE_RECTANGLE_ARB);
1735             checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1736         }
1737         glDisable(GL_TEXTURE_2D);
1738         checkGLcall("glDisable GL_TEXTURE_2D");
1739
1740         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1741         checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1742
1743         if (sampler != WINED3D_UNMAPPED_STAGE)
1744         {
1745             if (sampler < MAX_TEXTURES) {
1746                 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1747             }
1748             Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1749         }
1750     }
1751     GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1752     checkGLcall("glActiveTextureARB");
1753
1754     sampler = This->rev_tex_unit_map[0];
1755
1756     if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1757     {
1758         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1759         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1760     }
1761     glDisable(GL_TEXTURE_3D);
1762     checkGLcall("glDisable GL_TEXTURE_3D");
1763     if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1764     {
1765         glDisable(GL_TEXTURE_RECTANGLE_ARB);
1766         checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1767     }
1768     glDisable(GL_TEXTURE_2D);
1769     checkGLcall("glDisable GL_TEXTURE_2D");
1770
1771     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1772
1773     glMatrixMode(GL_TEXTURE);
1774     checkGLcall("glMatrixMode(GL_TEXTURE)");
1775     glLoadIdentity();
1776     checkGLcall("glLoadIdentity()");
1777
1778     if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1779     {
1780         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1781                   GL_TEXTURE_LOD_BIAS_EXT,
1782                   0.0f);
1783         checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1784     }
1785
1786     if (sampler != WINED3D_UNMAPPED_STAGE)
1787     {
1788         if (sampler < MAX_TEXTURES) {
1789             Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1790             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1791         }
1792         Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1793     }
1794
1795     /* Other misc states */
1796     glDisable(GL_ALPHA_TEST);
1797     checkGLcall("glDisable(GL_ALPHA_TEST)");
1798     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1799     glDisable(GL_LIGHTING);
1800     checkGLcall("glDisable GL_LIGHTING");
1801     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1802     glDisable(GL_DEPTH_TEST);
1803     checkGLcall("glDisable GL_DEPTH_TEST");
1804     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1805     glDisableWINE(GL_FOG);
1806     checkGLcall("glDisable GL_FOG");
1807     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1808     glDisable(GL_BLEND);
1809     checkGLcall("glDisable GL_BLEND");
1810     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1811     glDisable(GL_CULL_FACE);
1812     checkGLcall("glDisable GL_CULL_FACE");
1813     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1814     glDisable(GL_STENCIL_TEST);
1815     checkGLcall("glDisable GL_STENCIL_TEST");
1816     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1817     glDisable(GL_SCISSOR_TEST);
1818     checkGLcall("glDisable GL_SCISSOR_TEST");
1819     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1820     if (gl_info->supported[ARB_POINT_SPRITE])
1821     {
1822         glDisable(GL_POINT_SPRITE_ARB);
1823         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1824         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1825     }
1826     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1827     checkGLcall("glColorMask");
1828     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1829     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
1830     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
1831     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
1832     if (gl_info->supported[EXT_SECONDARY_COLOR])
1833     {
1834         glDisable(GL_COLOR_SUM_EXT);
1835         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1836         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1837     }
1838
1839     /* Setup transforms */
1840     glMatrixMode(GL_MODELVIEW);
1841     checkGLcall("glMatrixMode(GL_MODELVIEW)");
1842     glLoadIdentity();
1843     checkGLcall("glLoadIdentity()");
1844     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1845
1846     context->last_was_rhw = TRUE;
1847     Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1848
1849     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1850     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1851     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1852     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1853     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1854     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1855     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1856
1857     set_blit_dimension(width, height);
1858
1859     LEAVE_GL();
1860
1861     context->blit_w = width; context->blit_h = height;
1862     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1863     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1864
1865     This->frag_pipe->enable_extension(FALSE);
1866 }
1867
1868 /* Do not call while under the GL lock. */
1869 static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target)
1870 {
1871     struct wined3d_context *current_context = context_get_current();
1872     struct wined3d_context *context;
1873
1874     if (current_context && current_context->destroyed) current_context = NULL;
1875
1876     if (!target)
1877     {
1878         if (current_context
1879                 && current_context->current_rt
1880                 && current_context->swapchain->device == This)
1881         {
1882             target = current_context->current_rt;
1883         }
1884         else
1885         {
1886             IWineD3DSwapChainImpl *swapchain = This->swapchains[0];
1887             if (swapchain->back_buffers) target = swapchain->back_buffers[0];
1888             else target = swapchain->front_buffer;
1889         }
1890     }
1891
1892     if (current_context && current_context->current_rt == target)
1893     {
1894         context_validate(current_context);
1895         return current_context;
1896     }
1897
1898     if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
1899     {
1900         TRACE("Rendering onscreen\n");
1901
1902         context = swapchain_get_context(target->container.u.swapchain);
1903     }
1904     else
1905     {
1906         TRACE("Rendering offscreen\n");
1907
1908         /* Stay with the current context if possible. Otherwise use the
1909          * context for the primary swapchain. */
1910         if (current_context && current_context->swapchain->device == This)
1911             context = current_context;
1912         else
1913             context = swapchain_get_context(This->swapchains[0]);
1914     }
1915
1916     context_validate(context);
1917
1918     return context;
1919 }
1920
1921 /* Context activation is done by the caller. */
1922 static void context_apply_draw_buffers(struct wined3d_context *context, UINT rt_count, IWineD3DSurfaceImpl **rts)
1923 {
1924     if (!surface_is_offscreen(rts[0]))
1925     {
1926         ENTER_GL();
1927         glDrawBuffer(surface_get_gl_buffer(rts[0]));
1928         checkGLcall("glDrawBuffer()");
1929         LEAVE_GL();
1930     }
1931     else
1932     {
1933         ENTER_GL();
1934         if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1935         {
1936             const struct wined3d_gl_info *gl_info = context->gl_info;
1937             unsigned int i;
1938
1939             for (i = 0; i < gl_info->limits.buffers; ++i)
1940             {
1941                 if (i < rt_count && rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
1942                     context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1943                 else
1944                     context->draw_buffers[i] = GL_NONE;
1945             }
1946
1947             if (gl_info->supported[ARB_DRAW_BUFFERS])
1948             {
1949                 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, context->draw_buffers));
1950                 checkGLcall("glDrawBuffers()");
1951             }
1952             else
1953             {
1954                 glDrawBuffer(context->draw_buffers[0]);
1955                 checkGLcall("glDrawBuffer()");
1956             }
1957         }
1958         else
1959         {
1960             glDrawBuffer(rts[0]->resource.device->offscreenBuffer);
1961             checkGLcall("glDrawBuffer()");
1962         }
1963         LEAVE_GL();
1964     }
1965 }
1966
1967 /* GL locking is done by the caller. */
1968 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1969 {
1970     glDrawBuffer(buffer);
1971     checkGLcall("glDrawBuffer()");
1972     context->draw_buffer_dirty = TRUE;
1973 }
1974
1975 static inline void context_set_render_offscreen(struct wined3d_context *context, const struct StateEntry *StateTable,
1976         BOOL offscreen)
1977 {
1978     if (context->render_offscreen == offscreen) return;
1979
1980     Context_MarkStateDirty(context, STATE_POINTSPRITECOORDORIGIN, StateTable);
1981     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1982     Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1983     Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1984     Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1985     context->render_offscreen = offscreen;
1986 }
1987
1988 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
1989         const struct wined3d_format *required)
1990 {
1991     short existing_depth, existing_stencil, required_depth, required_stencil;
1992
1993     if (existing == required) return TRUE;
1994     if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1995
1996     getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1997     getDepthStencilBits(required, &required_depth, &required_stencil);
1998
1999     if(existing_depth < required_depth) return FALSE;
2000     /* If stencil bits are used the exact amount is required - otherwise wrapping
2001      * won't work correctly */
2002     if(required_stencil && required_stencil != existing_stencil) return FALSE;
2003     return TRUE;
2004 }
2005 /* The caller provides a context */
2006 static void context_validate_onscreen_formats(IWineD3DDeviceImpl *device,
2007         struct wined3d_context *context, IWineD3DSurfaceImpl *depth_stencil)
2008 {
2009     /* Onscreen surfaces are always in a swapchain */
2010     IWineD3DSwapChainImpl *swapchain = context->current_rt->container.u.swapchain;
2011
2012     if (context->render_offscreen || !depth_stencil) return;
2013     if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2014
2015     /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2016      * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2017      * format. */
2018     WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2019
2020     /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2021     surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2022     swapchain->render_to_fbo = TRUE;
2023     context_set_render_offscreen(context, device->StateTable, TRUE);
2024 }
2025
2026 /* Context activation is done by the caller. */
2027 void context_apply_blit_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2028 {
2029     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2030     {
2031         context_validate_onscreen_formats(device, context, NULL);
2032
2033         if (context->render_offscreen)
2034         {
2035             surface_internal_preload(context->current_rt, SRGB_RGB);
2036
2037             ENTER_GL();
2038             context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, context->current_rt, NULL, SFLAG_INTEXTURE);
2039             LEAVE_GL();
2040         }
2041         else
2042         {
2043             ENTER_GL();
2044             context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2045             LEAVE_GL();
2046         }
2047
2048         context->draw_buffer_dirty = TRUE;
2049     }
2050
2051     if (context->draw_buffer_dirty)
2052     {
2053         context_apply_draw_buffers(context, 1, &context->current_rt);
2054         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2055             context->draw_buffer_dirty = FALSE;
2056     }
2057
2058     SetupForBlit(device, context);
2059 }
2060
2061 static BOOL context_validate_rt_config(UINT rt_count,
2062         IWineD3DSurfaceImpl **rts, IWineD3DSurfaceImpl *ds)
2063 {
2064     unsigned int i;
2065
2066     if (ds) return TRUE;
2067
2068     for (i = 0; i < rt_count; ++i)
2069     {
2070         if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2071             return TRUE;
2072     }
2073
2074     WARN("Invalid render target config, need at least one attachment.\n");
2075     return FALSE;
2076 }
2077
2078 /* Context activation is done by the caller. */
2079 BOOL context_apply_clear_state(struct wined3d_context *context, IWineD3DDeviceImpl *device,
2080         UINT rt_count, IWineD3DSurfaceImpl **rts, IWineD3DSurfaceImpl *depth_stencil)
2081 {
2082     const struct StateEntry *state_table = device->StateTable;
2083     UINT i;
2084
2085     if (!context_validate_rt_config(rt_count, rts, depth_stencil))
2086         return FALSE;
2087
2088
2089     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2090     {
2091         context_validate_onscreen_formats(device, context, depth_stencil);
2092
2093         ENTER_GL();
2094
2095         if (surface_is_offscreen(rts[0]))
2096         {
2097             for (i = 0; i < rt_count; ++i)
2098             {
2099                 context->blit_targets[i] = rts[i];
2100             }
2101             while (i < context->gl_info->limits.buffers)
2102             {
2103                 context->blit_targets[i] = NULL;
2104                 ++i;
2105             }
2106             context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, depth_stencil, SFLAG_INTEXTURE);
2107         }
2108         else
2109         {
2110             context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2111         }
2112
2113         LEAVE_GL();
2114     }
2115
2116     context_apply_draw_buffers(context, rt_count, rts);
2117     context->draw_buffer_dirty = TRUE;
2118
2119     if (context->last_was_blit)
2120     {
2121         device->frag_pipe->enable_extension(TRUE);
2122     }
2123
2124     /* Blending and clearing should be orthogonal, but tests on the nvidia
2125      * driver show that disabling blending when clearing improves the clearing
2126      * performance incredibly. */
2127     ENTER_GL();
2128     glDisable(GL_BLEND);
2129     glEnable(GL_SCISSOR_TEST);
2130     checkGLcall("glEnable GL_SCISSOR_TEST");
2131     LEAVE_GL();
2132
2133     context->last_was_blit = FALSE;
2134     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2135     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2136     Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2137
2138     return TRUE;
2139 }
2140
2141 /* Context activation is done by the caller. */
2142 BOOL context_apply_draw_state(struct wined3d_context *context, IWineD3DDeviceImpl *device)
2143 {
2144     const struct StateEntry *state_table = device->StateTable;
2145     unsigned int i;
2146
2147     if (!context_validate_rt_config(context->gl_info->limits.buffers,
2148             device->render_targets, device->depth_stencil))
2149         return FALSE;
2150
2151     /* Preload resources before FBO setup. Texture preload in particular may
2152      * result in changes to the current FBO, due to using e.g. FBO blits for
2153      * updating a resource location. */
2154     IWineD3DDeviceImpl_FindTexUnitMap(device);
2155     device_preload_textures(device);
2156     if (isStateDirty(context, STATE_VDECL))
2157         device_update_stream_info(device, context->gl_info);
2158
2159     if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2160     {
2161         context_validate_onscreen_formats(device, context, device->depth_stencil);
2162
2163         if (!context->render_offscreen)
2164         {
2165             ENTER_GL();
2166             context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2167             LEAVE_GL();
2168         }
2169         else
2170         {
2171             ENTER_GL();
2172             context_apply_fbo_state(context, GL_FRAMEBUFFER, device->render_targets,
2173                     device->depth_stencil, SFLAG_INTEXTURE);
2174             LEAVE_GL();
2175         }
2176     }
2177
2178     if (context->draw_buffer_dirty)
2179     {
2180         context_apply_draw_buffers(context, context->gl_info->limits.buffers, device->render_targets);
2181         context->draw_buffer_dirty = FALSE;
2182     }
2183
2184     if (context->last_was_blit)
2185     {
2186         device->frag_pipe->enable_extension(TRUE);
2187     }
2188
2189     ENTER_GL();
2190     for (i = 0; i < context->numDirtyEntries; ++i)
2191     {
2192         DWORD rep = context->dirtyArray[i];
2193         DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2194         BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2195         context->isStateDirty[idx] &= ~(1 << shift);
2196         state_table[rep].apply(rep, device->stateBlock, context);
2197     }
2198     LEAVE_GL();
2199     context->numDirtyEntries = 0; /* This makes the whole list clean */
2200     context->last_was_blit = FALSE;
2201
2202     return TRUE;
2203 }
2204
2205 static void context_setup_target(IWineD3DDeviceImpl *device,
2206         struct wined3d_context *context, IWineD3DSurfaceImpl *target)
2207 {
2208     BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2209     const struct StateEntry *StateTable = device->StateTable;
2210
2211     if (!target) return;
2212     render_offscreen = surface_is_offscreen(target);
2213     if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2214
2215     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2216      * the alpha blend state changes with different render target formats. */
2217     if (!context->current_rt)
2218     {
2219         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2220     }
2221     else
2222     {
2223         const struct wined3d_format *old = context->current_rt->resource.format;
2224         const struct wined3d_format *new = target->resource.format;
2225
2226         if (old->id != new->id)
2227         {
2228             /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2229             if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2230                     || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2231             {
2232                 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2233             }
2234             /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2235             if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2236             {
2237                 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SRGBWRITEENABLE), StateTable);
2238             }
2239         }
2240
2241         /* When switching away from an offscreen render target, and we're not
2242          * using FBOs, we have to read the drawable into the texture. This is
2243          * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2244          * are some things that need care though. PreLoad needs a GL context,
2245          * and FindContext is called before the context is activated. It also
2246          * has to be called with the old rendertarget active, otherwise a
2247          * wrong drawable is read. */
2248         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2249                 && old_render_offscreen && context->current_rt != target)
2250         {
2251             /* Read the back buffer of the old drawable into the destination texture. */
2252             if (context->current_rt->texture_name_srgb)
2253             {
2254                 surface_internal_preload(context->current_rt, SRGB_BOTH);
2255             }
2256             else
2257             {
2258                 surface_internal_preload(context->current_rt, SRGB_RGB);
2259             }
2260
2261             surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2262         }
2263     }
2264
2265     context->draw_buffer_dirty = TRUE;
2266     context->current_rt = target;
2267     context_set_render_offscreen(context, StateTable, render_offscreen);
2268 }
2269
2270 /* Do not call while under the GL lock. */
2271 struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurfaceImpl *target)
2272 {
2273     struct wined3d_context *current_context = context_get_current();
2274     struct wined3d_context *context;
2275
2276     TRACE("device %p, target %p.\n", device, target);
2277
2278     context = FindContext(device, target);
2279     context_setup_target(device, context, target);
2280     context_enter(context);
2281     if (!context->valid) return context;
2282
2283     if (context != current_context)
2284     {
2285         if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2286         else device->frag_pipe->enable_extension(!context->last_was_blit);
2287
2288         if (context->vshader_const_dirty)
2289         {
2290             memset(context->vshader_const_dirty, 1,
2291                     sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2292             device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2293         }
2294         if (context->pshader_const_dirty)
2295         {
2296             memset(context->pshader_const_dirty, 1,
2297                    sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2298             device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2299         }
2300     }
2301     else if (context->restore_ctx)
2302     {
2303         if (!pwglMakeCurrent(context->hdc, context->glCtx))
2304         {
2305             DWORD err = GetLastError();
2306             ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2307                     context->hdc, context->glCtx, err);
2308         }
2309     }
2310
2311     return context;
2312 }