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