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