shell32: Pack the systray data structure to allow crossing 32/64 boundaries.
[wine/multimedia.git] / dlls / wined3d / context.c
blob15a8f77be38b4a103f892d9a73cf585d547e7d24
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009 Henri Verbeet for CodeWeavers
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.
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.
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
22 #include "config.h"
23 #include <stdio.h>
24 #ifdef HAVE_FLOAT_H
25 # include <float.h>
26 #endif
27 #include "wined3d_private.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
31 #define GLINFO_LOCATION (*gl_info)
33 static DWORD wined3d_context_tls_idx;
35 /* FBO helper functions */
37 /* GL locking is done by the caller */
38 void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
40 const struct wined3d_gl_info *gl_info = context->gl_info;
41 GLuint f;
43 if (!fbo)
45 f = 0;
47 else
49 if (!*fbo)
51 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
52 checkGLcall("glGenFramebuffers()");
53 TRACE("Created FBO %u.\n", *fbo);
55 f = *fbo;
58 switch (target)
60 case GL_READ_FRAMEBUFFER:
61 if (context->fbo_read_binding == f) return;
62 context->fbo_read_binding = f;
63 break;
65 case GL_DRAW_FRAMEBUFFER:
66 if (context->fbo_draw_binding == f) return;
67 context->fbo_draw_binding = f;
68 break;
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;
77 default:
78 FIXME("Unhandled target %#x.\n", target);
79 break;
82 gl_info->fbo_ops.glBindFramebuffer(target, f);
83 checkGLcall("glBindFramebuffer()");
86 /* GL locking is done by the caller */
87 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info)
89 unsigned int i;
91 for (i = 0; i < gl_info->limits.buffers; ++i)
93 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
94 checkGLcall("glFramebufferTexture2D()");
96 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
97 checkGLcall("glFramebufferTexture2D()");
99 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
100 checkGLcall("glFramebufferTexture2D()");
103 /* GL locking is done by the caller */
104 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
106 const struct wined3d_gl_info *gl_info = context->gl_info;
108 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
109 context_clean_fbo_attachments(gl_info);
110 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
112 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
113 checkGLcall("glDeleteFramebuffers()");
116 /* GL locking is done by the caller */
117 static void context_apply_attachment_filter_states(IWineD3DSurface *surface)
119 IWineD3DBaseTextureImpl *texture_impl;
121 /* Update base texture states array */
122 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
124 IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
125 IWineD3DDeviceImpl *device = surface_impl->resource.device;
126 BOOL update_minfilter = FALSE;
127 BOOL update_magfilter = FALSE;
129 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
130 || texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
132 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
133 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
134 update_minfilter = TRUE;
137 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
139 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
140 update_magfilter = TRUE;
143 if (texture_impl->baseTexture.bindCount)
145 WARN("Render targets should not be bound to a sampler\n");
146 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
149 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
151 if (update_minfilter || update_magfilter)
153 GLenum target, bind_target;
154 GLint old_binding;
156 target = surface_impl->texture_target;
157 if (target == GL_TEXTURE_2D)
159 bind_target = GL_TEXTURE_2D;
160 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
162 else if (target == GL_TEXTURE_RECTANGLE_ARB)
164 bind_target = GL_TEXTURE_RECTANGLE_ARB;
165 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
167 else
169 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
170 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
173 glBindTexture(bind_target, surface_impl->texture_name);
174 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
175 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
176 glBindTexture(bind_target, old_binding);
179 checkGLcall("apply_attachment_filter_states()");
183 /* GL locking is done by the caller */
184 void context_attach_depth_stencil_fbo(struct wined3d_context *context,
185 GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
187 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
188 const struct wined3d_gl_info *gl_info = context->gl_info;
190 TRACE("Attach depth stencil %p\n", depth_stencil);
192 if (depth_stencil)
194 DWORD format_flags = depth_stencil_impl->resource.format_desc->Flags;
196 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
198 if (format_flags & WINED3DFMT_FLAG_DEPTH)
200 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT,
201 GL_RENDERBUFFER, depth_stencil_impl->current_renderbuffer->id);
202 checkGLcall("glFramebufferRenderbuffer()");
205 if (format_flags & WINED3DFMT_FLAG_STENCIL)
207 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT,
208 GL_RENDERBUFFER, depth_stencil_impl->current_renderbuffer->id);
209 checkGLcall("glFramebufferRenderbuffer()");
212 else
214 surface_prepare_texture(depth_stencil_impl, gl_info, FALSE);
215 context_apply_attachment_filter_states(depth_stencil);
217 if (format_flags & WINED3DFMT_FLAG_DEPTH)
219 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
220 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
221 depth_stencil_impl->texture_level);
222 checkGLcall("glFramebufferTexture2D()");
225 if (format_flags & WINED3DFMT_FLAG_STENCIL)
227 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
228 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
229 depth_stencil_impl->texture_level);
230 checkGLcall("glFramebufferTexture2D()");
234 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
236 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
237 checkGLcall("glFramebufferTexture2D()");
240 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
242 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
243 checkGLcall("glFramebufferTexture2D()");
246 else
248 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
249 checkGLcall("glFramebufferTexture2D()");
251 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
252 checkGLcall("glFramebufferTexture2D()");
256 /* GL locking is done by the caller */
257 void context_attach_surface_fbo(const struct wined3d_context *context,
258 GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
260 IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
261 const struct wined3d_gl_info *gl_info = context->gl_info;
263 TRACE("Attach surface %p to %u\n", surface, idx);
265 if (surface)
267 surface_prepare_texture(surface_impl, gl_info, FALSE);
268 context_apply_attachment_filter_states(surface);
270 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, surface_impl->texture_target,
271 surface_impl->texture_name, surface_impl->texture_level);
272 checkGLcall("glFramebufferTexture2D()");
274 else
276 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
277 checkGLcall("glFramebufferTexture2D()");
281 /* GL locking is done by the caller */
282 static void context_check_fbo_status(struct wined3d_context *context)
284 const struct wined3d_gl_info *gl_info = context->gl_info;
285 GLenum status;
287 status = gl_info->fbo_ops.glCheckFramebufferStatus(GL_FRAMEBUFFER);
288 if (status == GL_FRAMEBUFFER_COMPLETE)
290 TRACE("FBO complete\n");
291 } else {
292 IWineD3DSurfaceImpl *attachment;
293 unsigned int i;
294 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
296 if (!context->current_fbo)
298 ERR("FBO 0 is incomplete, driver bug?\n");
299 return;
302 /* Dump the FBO attachments */
303 for (i = 0; i < gl_info->limits.buffers; ++i)
305 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->render_targets[i];
306 if (attachment)
308 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
309 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
310 attachment->pow2Width, attachment->pow2Height);
313 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->depth_stencil;
314 if (attachment)
316 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
317 attachment, debug_d3dformat(attachment->resource.format_desc->format),
318 attachment->pow2Width, attachment->pow2Height);
323 static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
325 const struct wined3d_gl_info *gl_info = context->gl_info;
326 IWineD3DDeviceImpl *device = context->swapchain->device;
327 struct fbo_entry *entry;
329 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
330 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
331 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
332 entry->depth_stencil = device->stencilBufferTarget;
333 entry->attached = FALSE;
334 entry->id = 0;
336 return entry;
339 /* GL locking is done by the caller */
340 static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
342 const struct wined3d_gl_info *gl_info = context->gl_info;
343 IWineD3DDeviceImpl *device = context->swapchain->device;
345 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
346 context_clean_fbo_attachments(gl_info);
348 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
349 entry->depth_stencil = device->stencilBufferTarget;
350 entry->attached = FALSE;
353 /* GL locking is done by the caller */
354 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
356 if (entry->id)
358 TRACE("Destroy FBO %d\n", entry->id);
359 context_destroy_fbo(context, &entry->id);
361 --context->fbo_entry_count;
362 list_remove(&entry->entry);
363 HeapFree(GetProcessHeap(), 0, entry->render_targets);
364 HeapFree(GetProcessHeap(), 0, entry);
368 /* GL locking is done by the caller */
369 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
371 const struct wined3d_gl_info *gl_info = context->gl_info;
372 IWineD3DDeviceImpl *device = context->swapchain->device;
373 struct fbo_entry *entry;
375 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
377 if (!memcmp(entry->render_targets,
378 device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
379 && entry->depth_stencil == device->stencilBufferTarget)
381 list_remove(&entry->entry);
382 list_add_head(&context->fbo_list, &entry->entry);
383 return entry;
387 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
389 entry = context_create_fbo_entry(context);
390 list_add_head(&context->fbo_list, &entry->entry);
391 ++context->fbo_entry_count;
393 else
395 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
396 context_reuse_fbo_entry(context, entry);
397 list_remove(&entry->entry);
398 list_add_head(&context->fbo_list, &entry->entry);
401 return entry;
404 /* GL locking is done by the caller */
405 static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
407 const struct wined3d_gl_info *gl_info = context->gl_info;
408 IWineD3DDeviceImpl *device = context->swapchain->device;
409 unsigned int i;
411 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
413 if (!entry->attached)
415 /* Apply render targets */
416 for (i = 0; i < gl_info->limits.buffers; ++i)
418 IWineD3DSurface *render_target = device->render_targets[i];
419 context_attach_surface_fbo(context, GL_FRAMEBUFFER, i, render_target);
422 /* Apply depth targets */
423 if (device->stencilBufferTarget)
425 unsigned int w = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Width;
426 unsigned int h = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Height;
428 surface_set_compatible_renderbuffer(device->stencilBufferTarget, w, h);
430 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, device->stencilBufferTarget, TRUE);
432 entry->attached = TRUE;
434 else
436 for (i = 0; i < gl_info->limits.buffers; ++i)
438 if (device->render_targets[i])
439 context_apply_attachment_filter_states(device->render_targets[i]);
441 if (device->stencilBufferTarget)
442 context_apply_attachment_filter_states(device->stencilBufferTarget);
445 for (i = 0; i < gl_info->limits.buffers; ++i)
447 if (device->render_targets[i])
448 device->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
449 else
450 device->draw_buffers[i] = GL_NONE;
454 /* GL locking is done by the caller */
455 static void context_apply_fbo_state(struct wined3d_context *context)
457 struct fbo_entry *entry, *entry2;
459 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
461 context_destroy_fbo_entry(context, entry);
464 if (context->rebind_fbo)
466 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
467 context->rebind_fbo = FALSE;
470 if (context->render_offscreen)
472 context->current_fbo = context_find_fbo_entry(context);
473 context_apply_fbo_entry(context, context->current_fbo);
474 } else {
475 context->current_fbo = NULL;
476 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
479 context_check_fbo_status(context);
482 /* Context activation is done by the caller. */
483 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
485 const struct wined3d_gl_info *gl_info = context->gl_info;
487 if (context->free_occlusion_query_count)
489 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
491 else
493 if (gl_info->supported[ARB_OCCLUSION_QUERY])
495 ENTER_GL();
496 GL_EXTCALL(glGenQueriesARB(1, &query->id));
497 checkGLcall("glGenQueriesARB");
498 LEAVE_GL();
500 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
502 else
504 WARN("Occlusion queries not supported, not allocating query id.\n");
505 query->id = 0;
509 query->context = context;
510 list_add_head(&context->occlusion_queries, &query->entry);
513 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
515 struct wined3d_context *context = query->context;
517 list_remove(&query->entry);
518 query->context = NULL;
520 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
522 UINT new_size = context->free_occlusion_query_size << 1;
523 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
524 new_size * sizeof(*context->free_occlusion_queries));
526 if (!new_data)
528 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
529 return;
532 context->free_occlusion_query_size = new_size;
533 context->free_occlusion_queries = new_data;
536 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
539 /* Context activation is done by the caller. */
540 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
542 const struct wined3d_gl_info *gl_info = context->gl_info;
544 if (context->free_event_query_count)
546 query->object = context->free_event_queries[--context->free_event_query_count];
548 else
550 if (gl_info->supported[ARB_SYNC])
552 /* Using ARB_sync, not much to do here. */
553 query->object.sync = NULL;
554 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
556 else if (gl_info->supported[APPLE_FENCE])
558 ENTER_GL();
559 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
560 checkGLcall("glGenFencesAPPLE");
561 LEAVE_GL();
563 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
565 else if(gl_info->supported[NV_FENCE])
567 ENTER_GL();
568 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
569 checkGLcall("glGenFencesNV");
570 LEAVE_GL();
572 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
574 else
576 WARN("Event queries not supported, not allocating query id.\n");
577 query->object.id = 0;
581 query->context = context;
582 list_add_head(&context->event_queries, &query->entry);
585 void context_free_event_query(struct wined3d_event_query *query)
587 struct wined3d_context *context = query->context;
589 list_remove(&query->entry);
590 query->context = NULL;
592 if (context->free_event_query_count >= context->free_event_query_size - 1)
594 UINT new_size = context->free_event_query_size << 1;
595 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
596 new_size * sizeof(*context->free_event_queries));
598 if (!new_data)
600 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
601 return;
604 context->free_event_query_size = new_size;
605 context->free_event_queries = new_data;
608 context->free_event_queries[context->free_event_query_count++] = query->object;
611 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
613 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
614 UINT i;
616 if (!This->d3d_initialized) return;
618 switch(type)
620 case WINED3DRTYPE_SURFACE:
622 for (i = 0; i < This->numContexts; ++i)
624 struct wined3d_context *context = This->contexts[i];
625 const struct wined3d_gl_info *gl_info = context->gl_info;
626 struct fbo_entry *entry, *entry2;
628 if (context->current_rt == (IWineD3DSurface *)resource) context->current_rt = NULL;
630 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
632 UINT j;
634 if (entry->depth_stencil == (IWineD3DSurface *)resource)
636 list_remove(&entry->entry);
637 list_add_head(&context->fbo_destroy_list, &entry->entry);
638 continue;
641 for (j = 0; j < gl_info->limits.buffers; ++j)
643 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
645 list_remove(&entry->entry);
646 list_add_head(&context->fbo_destroy_list, &entry->entry);
647 break;
653 break;
656 default:
657 break;
661 void context_surface_update(struct wined3d_context *context, IWineD3DSurfaceImpl *surface)
663 const struct wined3d_gl_info *gl_info = context->gl_info;
664 struct fbo_entry *entry = context->current_fbo;
665 unsigned int i;
667 if (!entry || context->rebind_fbo) return;
669 for (i = 0; i < gl_info->limits.buffers; ++i)
671 if (surface == (IWineD3DSurfaceImpl *)entry->render_targets[i])
673 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
674 context->rebind_fbo = TRUE;
675 return;
679 if (surface == (IWineD3DSurfaceImpl *)entry->depth_stencil)
681 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
682 context->rebind_fbo = TRUE;
686 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
688 int current = GetPixelFormat(dc);
690 if (current == format) return TRUE;
692 if (!current)
694 if (!SetPixelFormat(dc, format, NULL))
696 ERR("Failed to set pixel format %d on device context %p, last error %#x.\n",
697 format, dc, GetLastError());
698 return FALSE;
700 return TRUE;
703 /* By default WGL doesn't allow pixel format adjustments but we need it
704 * here. For this reason there's a Wine specific wglSetPixelFormat()
705 * which allows us to set the pixel format multiple times. Only use it
706 * when really needed. */
707 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
709 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
711 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
712 format, dc);
713 return FALSE;
715 return TRUE;
718 /* OpenGL doesn't allow pixel format adjustments. Print an error and
719 * continue using the old format. There's a big chance that the old
720 * format works although with a performance hit and perhaps rendering
721 * errors. */
722 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
723 format, dc, current);
724 return TRUE;
727 static void context_update_window(struct wined3d_context *context)
729 TRACE("Updating context %p window from %p to %p.\n",
730 context, context->win_handle, context->swapchain->win_handle);
732 if (context->valid)
734 if (!ReleaseDC(context->win_handle, context->hdc))
736 ERR("Failed to release device context %p, last error %#x.\n",
737 context->hdc, GetLastError());
740 else context->valid = 1;
742 context->win_handle = context->swapchain->win_handle;
744 if (!(context->hdc = GetDC(context->win_handle)))
746 ERR("Failed to get a device context for window %p.\n", context->win_handle);
747 goto err;
750 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
752 ERR("Failed to set pixel format %d on device context %p.\n",
753 context->pixel_format, context->hdc);
754 goto err;
757 if (!pwglMakeCurrent(context->hdc, context->glCtx))
759 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
760 context->glCtx, context->hdc, GetLastError());
761 goto err;
764 return;
766 err:
767 context->valid = 0;
770 static void context_validate(struct wined3d_context *context)
772 HWND wnd = WindowFromDC(context->hdc);
774 if (wnd != context->win_handle)
776 WARN("DC %p belongs to window %p instead of %p.\n",
777 context->hdc, wnd, context->win_handle);
778 context->valid = 0;
781 if (context->win_handle != context->swapchain->win_handle)
782 context_update_window(context);
785 static void context_destroy_gl_resources(struct wined3d_context *context)
787 const struct wined3d_gl_info *gl_info = context->gl_info;
788 struct wined3d_occlusion_query *occlusion_query;
789 struct wined3d_event_query *event_query;
790 struct fbo_entry *entry, *entry2;
791 HGLRC restore_ctx;
792 HDC restore_dc;
793 unsigned int i;
795 restore_ctx = pwglGetCurrentContext();
796 restore_dc = pwglGetCurrentDC();
798 context_validate(context);
799 if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
800 else restore_ctx = NULL;
802 ENTER_GL();
804 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
806 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
807 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
808 occlusion_query->context = NULL;
811 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
813 if (context->valid)
815 if (gl_info->supported[ARB_SYNC])
817 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
819 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
820 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
822 event_query->context = NULL;
825 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
827 if (!context->valid) entry->id = 0;
828 context_destroy_fbo_entry(context, entry);
831 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
833 if (!context->valid) entry->id = 0;
834 context_destroy_fbo_entry(context, entry);
837 if (context->valid)
839 if (context->src_fbo)
841 TRACE("Destroy src FBO %d\n", context->src_fbo);
842 context_destroy_fbo(context, &context->src_fbo);
844 if (context->dst_fbo)
846 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
847 context_destroy_fbo(context, &context->dst_fbo);
849 if (context->dummy_arbfp_prog)
851 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
854 if (gl_info->supported[ARB_OCCLUSION_QUERY])
855 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
857 if (gl_info->supported[ARB_SYNC])
859 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
861 else if (gl_info->supported[APPLE_FENCE])
863 for (i = 0; i < context->free_event_query_count; ++i)
865 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
868 else if (gl_info->supported[NV_FENCE])
870 for (i = 0; i < context->free_event_query_count; ++i)
872 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
876 checkGLcall("context cleanup");
879 LEAVE_GL();
881 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
882 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
884 if (restore_ctx)
886 if (!pwglMakeCurrent(restore_dc, restore_ctx))
888 DWORD err = GetLastError();
889 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
890 restore_ctx, restore_dc, err);
893 else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
895 ERR("Failed to disable GL context.\n");
898 ReleaseDC(context->win_handle, context->hdc);
900 if (!pwglDeleteContext(context->glCtx))
902 DWORD err = GetLastError();
903 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
907 DWORD context_get_tls_idx(void)
909 return wined3d_context_tls_idx;
912 void context_set_tls_idx(DWORD idx)
914 wined3d_context_tls_idx = idx;
917 struct wined3d_context *context_get_current(void)
919 return TlsGetValue(wined3d_context_tls_idx);
922 BOOL context_set_current(struct wined3d_context *ctx)
924 struct wined3d_context *old = context_get_current();
926 if (old == ctx)
928 TRACE("Already using D3D context %p.\n", ctx);
929 return TRUE;
932 if (old)
934 if (old->destroyed)
936 TRACE("Switching away from destroyed context %p.\n", old);
937 context_destroy_gl_resources(old);
938 HeapFree(GetProcessHeap(), 0, old);
940 else
942 old->current = 0;
946 if (ctx)
948 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
949 if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
951 DWORD err = GetLastError();
952 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
953 ctx->glCtx, ctx->hdc, err);
954 TlsSetValue(wined3d_context_tls_idx, NULL);
955 return FALSE;
957 ctx->current = 1;
959 else if(pwglGetCurrentContext())
961 TRACE("Clearing current D3D context.\n");
962 if (!pwglMakeCurrent(NULL, NULL))
964 DWORD err = GetLastError();
965 ERR("Failed to clear current GL context, last error %#x.\n", err);
966 TlsSetValue(wined3d_context_tls_idx, NULL);
967 return FALSE;
971 return TlsSetValue(wined3d_context_tls_idx, ctx);
974 void context_release(struct wined3d_context *context)
976 TRACE("Releasing context %p, level %u.\n", context, context->level);
978 if (WARN_ON(d3d))
980 if (!context->level)
981 WARN("Context %p is not active.\n", context);
982 else if (context != context_get_current())
983 WARN("Context %p is not the current context.\n", context);
986 if (!--context->level && context->restore_ctx)
988 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
989 if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
991 DWORD err = GetLastError();
992 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
993 context->restore_ctx, context->restore_dc, err);
995 context->restore_ctx = NULL;
996 context->restore_dc = NULL;
1000 static void context_enter(struct wined3d_context *context)
1002 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1004 if (!context->level++)
1006 const struct wined3d_context *current_context = context_get_current();
1007 HGLRC current_gl = pwglGetCurrentContext();
1009 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1011 TRACE("Another GL context (%p on device context %p) is already current.\n",
1012 current_gl, pwglGetCurrentDC());
1013 context->restore_ctx = current_gl;
1014 context->restore_dc = pwglGetCurrentDC();
1019 /*****************************************************************************
1020 * Context_MarkStateDirty
1022 * Marks a state in a context dirty. Only one context, opposed to
1023 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1024 * contexts
1026 * Params:
1027 * context: Context to mark the state dirty in
1028 * state: State to mark dirty
1029 * StateTable: Pointer to the state table in use(for state grouping)
1031 *****************************************************************************/
1032 static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1034 DWORD rep = StateTable[state].representative;
1035 DWORD idx;
1036 BYTE shift;
1038 if (isStateDirty(context, rep)) return;
1040 context->dirtyArray[context->numDirtyEntries++] = rep;
1041 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1042 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1043 context->isStateDirty[idx] |= (1 << shift);
1046 /* This function takes care of WineD3D pixel format selection. */
1047 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1048 const struct wined3d_format_desc *color_format_desc, const struct wined3d_format_desc *ds_format_desc,
1049 BOOL auxBuffers, int numSamples, BOOL findCompatible)
1051 int iPixelFormat=0;
1052 unsigned int matchtry;
1053 short redBits, greenBits, blueBits, alphaBits, colorBits;
1054 short depthBits=0, stencilBits=0;
1056 struct match_type {
1057 BOOL require_aux;
1058 BOOL exact_alpha;
1059 BOOL exact_color;
1060 } matches[] = {
1061 /* First, try without alpha match buffers. MacOS supports aux buffers only
1062 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1063 * Then try without aux buffers - this is the most common cause for not
1064 * finding a pixel format. Also some drivers(the open source ones)
1065 * only offer 32 bit ARB pixel formats. First try without an exact alpha
1066 * match, then try without an exact alpha and color match.
1068 { TRUE, TRUE, TRUE },
1069 { TRUE, FALSE, TRUE },
1070 { FALSE, TRUE, TRUE },
1071 { FALSE, FALSE, TRUE },
1072 { TRUE, FALSE, FALSE },
1073 { FALSE, FALSE, FALSE },
1076 int i = 0;
1077 int nCfgs = This->adapter->nCfgs;
1079 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1080 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1081 auxBuffers, numSamples, findCompatible);
1083 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1085 ERR("Unable to get color bits for format %s (%#x)!\n",
1086 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1087 return 0;
1090 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
1091 * You are able to add a depth + stencil surface at a later stage when you need it.
1092 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
1093 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
1094 * context, need torecreate shaders, textures and other resources.
1096 * The context manager already takes care of the state problem and for the other tasks code from Reset
1097 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
1098 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
1099 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
1100 * issue needs to be fixed. */
1101 if (ds_format_desc->format != WINED3DFMT_D24_UNORM_S8_UINT)
1103 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
1104 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24_UNORM_S8_UINT, &This->adapter->gl_info);
1107 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1109 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1110 for(i=0; i<nCfgs; i++) {
1111 BOOL exactDepthMatch = TRUE;
1112 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1114 /* For now only accept RGBA formats. Perhaps some day we will
1115 * allow floating point formats for pbuffers. */
1116 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1117 continue;
1119 /* In window mode we need a window drawable format and double buffering. */
1120 if(!(cfg->windowDrawable && cfg->doubleBuffer))
1121 continue;
1123 /* We like to have aux buffers in backbuffer mode */
1124 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1125 continue;
1127 if(matches[matchtry].exact_color) {
1128 if(cfg->redSize != redBits)
1129 continue;
1130 if(cfg->greenSize != greenBits)
1131 continue;
1132 if(cfg->blueSize != blueBits)
1133 continue;
1134 } else {
1135 if(cfg->redSize < redBits)
1136 continue;
1137 if(cfg->greenSize < greenBits)
1138 continue;
1139 if(cfg->blueSize < blueBits)
1140 continue;
1142 if(matches[matchtry].exact_alpha) {
1143 if(cfg->alphaSize != alphaBits)
1144 continue;
1145 } else {
1146 if(cfg->alphaSize < alphaBits)
1147 continue;
1150 /* We try to locate a format which matches our requirements exactly. In case of
1151 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1152 if(cfg->depthSize < depthBits)
1153 continue;
1154 else if(cfg->depthSize > depthBits)
1155 exactDepthMatch = FALSE;
1157 /* In all cases make sure the number of stencil bits matches our requirements
1158 * even when we don't need stencil because it could affect performance EXCEPT
1159 * on cards which don't offer depth formats without stencil like the i915 drivers
1160 * on Linux. */
1161 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1162 continue;
1164 /* Check multisampling support */
1165 if(cfg->numSamples != numSamples)
1166 continue;
1168 /* When we have passed all the checks then we have found a format which matches our
1169 * requirements. Note that we only check for a limit number of capabilities right now,
1170 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1171 * can still differ in things like multisampling, stereo, SRGB and other flags.
1174 /* Exit the loop as we have found a format :) */
1175 if(exactDepthMatch) {
1176 iPixelFormat = cfg->iPixelFormat;
1177 break;
1178 } else if(!iPixelFormat) {
1179 /* In the end we might end up with a format which doesn't exactly match our depth
1180 * requirements. Accept the first format we found because formats with higher iPixelFormat
1181 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1182 iPixelFormat = cfg->iPixelFormat;
1187 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1188 if(!iPixelFormat && !findCompatible) {
1189 ERR("Can't find a suitable iPixelFormat\n");
1190 return FALSE;
1191 } else if(!iPixelFormat) {
1192 PIXELFORMATDESCRIPTOR pfd;
1194 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1195 /* PixelFormat selection */
1196 ZeroMemory(&pfd, sizeof(pfd));
1197 pfd.nSize = sizeof(pfd);
1198 pfd.nVersion = 1;
1199 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1200 pfd.iPixelType = PFD_TYPE_RGBA;
1201 pfd.cAlphaBits = alphaBits;
1202 pfd.cColorBits = colorBits;
1203 pfd.cDepthBits = depthBits;
1204 pfd.cStencilBits = stencilBits;
1205 pfd.iLayerType = PFD_MAIN_PLANE;
1207 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1208 if(!iPixelFormat) {
1209 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1210 ERR("Can't find a suitable iPixelFormat\n");
1211 return FALSE;
1215 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1216 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1217 return iPixelFormat;
1220 /*****************************************************************************
1221 * context_create
1223 * Creates a new context.
1225 * * Params:
1226 * This: Device to activate the context for
1227 * target: Surface this context will render to
1228 * win_handle: handle to the window which we are drawing to
1229 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1231 *****************************************************************************/
1232 struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target)
1234 IWineD3DDeviceImpl *device = swapchain->device;
1235 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1236 const struct wined3d_format_desc *color_format_desc;
1237 const struct wined3d_format_desc *ds_format_desc;
1238 struct wined3d_context *ret;
1239 PIXELFORMATDESCRIPTOR pfd;
1240 BOOL auxBuffers = FALSE;
1241 int numSamples = 0;
1242 int pixel_format;
1243 unsigned int s;
1244 DWORD state;
1245 HGLRC ctx;
1246 HDC hdc;
1248 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1250 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1251 if (!ret)
1253 ERR("Failed to allocate context memory.\n");
1254 return NULL;
1257 if (!(hdc = GetDC(swapchain->win_handle)))
1259 ERR("Failed to retrieve a device context.\n");
1260 goto out;
1263 ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN, gl_info);
1264 color_format_desc = target->resource.format_desc;
1266 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1267 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1268 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1270 auxBuffers = TRUE;
1272 if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1273 color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, gl_info);
1274 else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1275 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1278 /* DirectDraw supports 8bit paletted render targets and these are used by
1279 * old games like Starcraft and C&C. Most modern hardware doesn't support
1280 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1281 * conversion (ab)uses the alpha component for storing the palette index.
1282 * For this reason we require a format with 8bit alpha, so request
1283 * A8R8G8B8. */
1284 if (color_format_desc->format == WINED3DFMT_P8_UINT)
1285 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1287 /* Retrieve the depth stencil format from the present parameters.
1288 * The choice of the proper format can give a nice performance boost
1289 * in case of GPU limited programs. */
1290 if (swapchain->presentParms.EnableAutoDepthStencil)
1292 TRACE("Auto depth stencil enabled, using format %s.\n",
1293 debug_d3dformat(swapchain->presentParms.AutoDepthStencilFormat));
1294 ds_format_desc = getFormatDescEntry(swapchain->presentParms.AutoDepthStencilFormat, gl_info);
1297 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1298 if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1300 if (!gl_info->supported[ARB_MULTISAMPLE])
1301 WARN("The application is requesting multisampling without support.\n");
1302 else
1304 TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1305 numSamples = swapchain->presentParms.MultiSampleType;
1309 /* Try to find a pixel format which matches our requirements. */
1310 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1311 auxBuffers, numSamples, FALSE /* findCompatible */);
1313 /* Try to locate a compatible format if we weren't able to find anything. */
1314 if (!pixel_format)
1316 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1317 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1318 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1321 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1322 if (!pixel_format)
1324 ERR("Can't find a suitable pixel format.\n");
1325 goto out;
1328 DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1329 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1331 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1332 goto out;
1335 ctx = pwglCreateContext(hdc);
1336 if (device->numContexts)
1338 if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1340 DWORD err = GetLastError();
1341 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1342 device->contexts[0]->glCtx, ctx, err);
1346 if(!ctx) {
1347 ERR("Failed to create a WGL context\n");
1348 goto out;
1351 if (!device_context_add(device, ret))
1353 ERR("Failed to add the newly created context to the context list\n");
1354 if (!pwglDeleteContext(ctx))
1356 DWORD err = GetLastError();
1357 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1359 goto out;
1362 ret->gl_info = gl_info;
1364 /* Mark all states dirty to force a proper initialization of the states
1365 * on the first use of the context. */
1366 for (state = 0; state <= STATE_HIGHEST; ++state)
1368 if (device->StateTable[state].representative)
1369 Context_MarkStateDirty(ret, state, device->StateTable);
1372 ret->swapchain = swapchain;
1373 ret->current_rt = (IWineD3DSurface *)target;
1374 ret->tid = GetCurrentThreadId();
1376 ret->render_offscreen = surface_is_offscreen((IWineD3DSurface *) target);
1377 ret->draw_buffer_dirty = TRUE;
1378 ret->valid = 1;
1380 ret->glCtx = ctx;
1381 ret->win_handle = swapchain->win_handle;
1382 ret->hdc = hdc;
1383 ret->pixel_format = pixel_format;
1385 if (device->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *)device))
1387 /* Create the dirty constants array and initialize them to dirty */
1388 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1389 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1390 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1391 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1392 memset(ret->vshader_const_dirty, 1,
1393 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1394 memset(ret->pshader_const_dirty, 1,
1395 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1398 ret->free_occlusion_query_size = 4;
1399 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1400 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1401 if (!ret->free_occlusion_queries) goto out;
1403 list_init(&ret->occlusion_queries);
1405 ret->free_event_query_size = 4;
1406 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1407 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1408 if (!ret->free_event_queries) goto out;
1410 list_init(&ret->event_queries);
1412 TRACE("Successfully created new context %p\n", ret);
1414 list_init(&ret->fbo_list);
1415 list_init(&ret->fbo_destroy_list);
1417 context_enter(ret);
1419 /* Set up the context defaults */
1420 if (!context_set_current(ret))
1422 ERR("Cannot activate context to set up defaults\n");
1423 context_release(ret);
1424 goto out;
1427 ENTER_GL();
1429 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1431 TRACE("Setting up the screen\n");
1432 /* Clear the screen */
1433 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1434 checkGLcall("glClearColor");
1435 glClearIndex(0);
1436 glClearDepth(1);
1437 glClearStencil(0xffff);
1439 checkGLcall("glClear");
1441 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1442 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1444 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1445 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1447 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1448 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1450 glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1451 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1452 glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1453 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1455 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1457 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1458 * and textures in DIB sections(due to the memory protection).
1460 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1461 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1463 if (gl_info->supported[ARB_VERTEX_BLEND])
1465 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1466 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1467 * GL_VERTEX_BLEND_ARB isn't enabled too
1469 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1470 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1472 if (gl_info->supported[NV_TEXTURE_SHADER2])
1474 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1475 * the previous texture where to source the offset from is always unit - 1.
1477 for (s = 1; s < gl_info->limits.textures; ++s)
1479 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1480 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1481 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1484 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1486 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1487 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1488 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1489 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1490 * is ever assigned.
1492 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1493 * program and the dummy program is destroyed when the context is destroyed.
1495 const char *dummy_program =
1496 "!!ARBfp1.0\n"
1497 "MOV result.color, fragment.color.primary;\n"
1498 "END\n";
1499 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1500 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1501 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1504 for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1506 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1507 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1508 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1511 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1513 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1515 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1517 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1520 LEAVE_GL();
1522 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
1524 TRACE("Created context %p.\n", ret);
1526 return ret;
1528 out:
1529 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1530 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1531 HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1532 HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1533 HeapFree(GetProcessHeap(), 0, ret);
1534 return NULL;
1537 /*****************************************************************************
1538 * context_destroy
1540 * Destroys a wined3d context
1542 * Params:
1543 * This: Device to activate the context for
1544 * context: Context to destroy
1546 *****************************************************************************/
1547 void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1549 BOOL destroy;
1551 TRACE("Destroying ctx %p\n", context);
1553 if (context->tid == GetCurrentThreadId() || !context->current)
1555 context_destroy_gl_resources(context);
1556 TlsSetValue(wined3d_context_tls_idx, NULL);
1557 destroy = TRUE;
1559 else
1561 context->destroyed = 1;
1562 destroy = FALSE;
1565 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1566 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1567 device_context_remove(This, context);
1568 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1571 /* GL locking is done by the caller */
1572 static inline void set_blit_dimension(UINT width, UINT height) {
1573 glMatrixMode(GL_PROJECTION);
1574 checkGLcall("glMatrixMode(GL_PROJECTION)");
1575 glLoadIdentity();
1576 checkGLcall("glLoadIdentity()");
1577 glOrtho(0, width, height, 0, 0.0, -1.0);
1578 checkGLcall("glOrtho");
1579 glViewport(0, 0, width, height);
1580 checkGLcall("glViewport");
1583 /*****************************************************************************
1584 * SetupForBlit
1586 * Sets up a context for DirectDraw blitting.
1587 * All texture units are disabled, texture unit 0 is set as current unit
1588 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1589 * color writing enabled for all channels
1590 * register combiners disabled, shaders disabled
1591 * world matrix is set to identity, texture matrix 0 too
1592 * projection matrix is setup for drawing screen coordinates
1594 * Params:
1595 * This: Device to activate the context for
1596 * context: Context to setup
1598 *****************************************************************************/
1599 /* Context activation is done by the caller. */
1600 static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1602 int i;
1603 const struct StateEntry *StateTable = This->StateTable;
1604 const struct wined3d_gl_info *gl_info = context->gl_info;
1605 UINT width = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Width;
1606 UINT height = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
1607 DWORD sampler;
1609 TRACE("Setting up context %p for blitting\n", context);
1610 if(context->last_was_blit) {
1611 if(context->blit_w != width || context->blit_h != height) {
1612 ENTER_GL();
1613 set_blit_dimension(width, height);
1614 LEAVE_GL();
1615 context->blit_w = width; context->blit_h = height;
1616 /* No need to dirtify here, the states are still dirtified because they weren't
1617 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1618 * be set
1621 TRACE("Context is already set up for blitting, nothing to do\n");
1622 return;
1624 context->last_was_blit = TRUE;
1626 /* TODO: Use a display list */
1628 /* Disable shaders */
1629 ENTER_GL();
1630 This->shader_backend->shader_select(context, FALSE, FALSE);
1631 LEAVE_GL();
1633 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1634 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1636 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1637 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1638 * which can safely be called from here, we only lock once instead locking/unlocking
1639 * after each GL call.
1641 ENTER_GL();
1643 /* Disable all textures. The caller can then bind a texture it wants to blit
1644 * from
1646 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1647 * function texture unit. No need to care for higher samplers
1649 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1651 sampler = This->rev_tex_unit_map[i];
1652 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1653 checkGLcall("glActiveTextureARB");
1655 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1657 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1658 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1660 glDisable(GL_TEXTURE_3D);
1661 checkGLcall("glDisable GL_TEXTURE_3D");
1662 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1664 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1665 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1667 glDisable(GL_TEXTURE_2D);
1668 checkGLcall("glDisable GL_TEXTURE_2D");
1670 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1671 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1673 if (sampler != WINED3D_UNMAPPED_STAGE)
1675 if (sampler < MAX_TEXTURES) {
1676 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1678 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1681 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1682 checkGLcall("glActiveTextureARB");
1684 sampler = This->rev_tex_unit_map[0];
1686 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1688 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1689 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1691 glDisable(GL_TEXTURE_3D);
1692 checkGLcall("glDisable GL_TEXTURE_3D");
1693 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1695 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1696 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1698 glDisable(GL_TEXTURE_2D);
1699 checkGLcall("glDisable GL_TEXTURE_2D");
1701 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1703 glMatrixMode(GL_TEXTURE);
1704 checkGLcall("glMatrixMode(GL_TEXTURE)");
1705 glLoadIdentity();
1706 checkGLcall("glLoadIdentity()");
1708 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1710 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1711 GL_TEXTURE_LOD_BIAS_EXT,
1712 0.0f);
1713 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1716 if (sampler != WINED3D_UNMAPPED_STAGE)
1718 if (sampler < MAX_TEXTURES) {
1719 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1720 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1722 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1725 /* Other misc states */
1726 glDisable(GL_ALPHA_TEST);
1727 checkGLcall("glDisable(GL_ALPHA_TEST)");
1728 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1729 glDisable(GL_LIGHTING);
1730 checkGLcall("glDisable GL_LIGHTING");
1731 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1732 glDisable(GL_DEPTH_TEST);
1733 checkGLcall("glDisable GL_DEPTH_TEST");
1734 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1735 glDisableWINE(GL_FOG);
1736 checkGLcall("glDisable GL_FOG");
1737 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1738 glDisable(GL_BLEND);
1739 checkGLcall("glDisable GL_BLEND");
1740 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1741 glDisable(GL_CULL_FACE);
1742 checkGLcall("glDisable GL_CULL_FACE");
1743 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1744 glDisable(GL_STENCIL_TEST);
1745 checkGLcall("glDisable GL_STENCIL_TEST");
1746 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1747 glDisable(GL_SCISSOR_TEST);
1748 checkGLcall("glDisable GL_SCISSOR_TEST");
1749 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1750 if (gl_info->supported[ARB_POINT_SPRITE])
1752 glDisable(GL_POINT_SPRITE_ARB);
1753 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1754 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1756 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1757 checkGLcall("glColorMask");
1758 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1759 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
1760 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
1761 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
1762 if (gl_info->supported[EXT_SECONDARY_COLOR])
1764 glDisable(GL_COLOR_SUM_EXT);
1765 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1766 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1769 /* Setup transforms */
1770 glMatrixMode(GL_MODELVIEW);
1771 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1772 glLoadIdentity();
1773 checkGLcall("glLoadIdentity()");
1774 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1776 context->last_was_rhw = TRUE;
1777 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1779 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1780 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1781 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1782 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1783 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1784 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1785 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1787 set_blit_dimension(width, height);
1789 LEAVE_GL();
1791 context->blit_w = width; context->blit_h = height;
1792 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1793 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1796 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1799 /*****************************************************************************
1800 * findThreadContextForSwapChain
1802 * Searches a swapchain for all contexts and picks one for the thread tid.
1803 * If none can be found the swapchain is requested to create a new context
1805 *****************************************************************************/
1806 static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1808 unsigned int i;
1810 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1811 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1812 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1817 /* Create a new context for the thread */
1818 return swapchain_create_context_for_thread(swapchain);
1821 /*****************************************************************************
1822 * FindContext
1824 * Finds a context for the current render target and thread
1826 * Parameters:
1827 * target: Render target to find the context for
1828 * tid: Thread to activate the context for
1830 * Returns: The needed context
1832 *****************************************************************************/
1833 static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target)
1835 IWineD3DSwapChain *swapchain = NULL;
1836 struct wined3d_context *current_context = context_get_current();
1837 const struct StateEntry *StateTable = This->StateTable;
1838 DWORD tid = GetCurrentThreadId();
1839 struct wined3d_context *context;
1840 BOOL old_render_offscreen;
1842 if (current_context && current_context->destroyed) current_context = NULL;
1844 if (!target)
1846 if (current_context
1847 && current_context->current_rt
1848 && current_context->swapchain->device == This)
1850 target = current_context->current_rt;
1852 else
1854 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1855 if (swapchain->backBuffer) target = swapchain->backBuffer[0];
1856 else target = swapchain->frontBuffer;
1860 if (current_context && current_context->current_rt == target)
1862 context_validate(current_context);
1863 return current_context;
1866 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1867 TRACE("Rendering onscreen\n");
1869 context = findThreadContextForSwapChain(swapchain, tid);
1871 old_render_offscreen = context->render_offscreen;
1872 context->render_offscreen = surface_is_offscreen(target);
1873 IWineD3DSwapChain_Release(swapchain);
1875 else
1877 TRACE("Rendering offscreen\n");
1879 /* Stay with the currently active context. */
1880 if (current_context && current_context->swapchain->device == This)
1882 context = current_context;
1884 else
1886 /* This may happen if the app jumps straight into offscreen rendering
1887 * Start using the context of the primary swapchain. tid == 0 is no problem
1888 * for findThreadContextForSwapChain.
1890 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1891 * is perfect to call. */
1892 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1895 old_render_offscreen = context->render_offscreen;
1896 context->render_offscreen = TRUE;
1899 context_validate(context);
1901 if (context->render_offscreen != old_render_offscreen)
1903 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1904 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1905 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1906 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1907 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1910 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1911 * the alpha blend state changes with different render target formats. */
1912 if (!context->current_rt)
1914 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1916 else
1918 const struct wined3d_format_desc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
1919 const struct wined3d_format_desc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1921 if (old->format != new->format)
1923 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
1924 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1925 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1927 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1931 /* When switching away from an offscreen render target, and we're not
1932 * using FBOs, we have to read the drawable into the texture. This is
1933 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
1934 * are some things that need care though. PreLoad needs a GL context,
1935 * and FindContext is called before the context is activated. It also
1936 * has to be called with the old rendertarget active, otherwise a
1937 * wrong drawable is read. */
1938 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
1939 && old_render_offscreen && context->current_rt != target)
1941 BOOL oldInDraw = This->isInDraw;
1943 /* surface_internal_preload() requires a context to load the
1944 * texture, so it will call context_acquire(). Set isInDraw to true
1945 * to signal surface_internal_preload() that it has a context. */
1947 /* FIXME: This is just broken. There's no guarantee whatsoever
1948 * that the currently active context, if any, is appropriate for
1949 * reading back the render target. We should probably call
1950 * context_set_current(context) here and then rely on
1951 * context_acquire() doing the right thing. */
1952 This->isInDraw = TRUE;
1954 /* Read the back buffer of the old drawable into the destination texture. */
1955 if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
1957 surface_internal_preload(context->current_rt, SRGB_BOTH);
1959 else
1961 surface_internal_preload(context->current_rt, SRGB_RGB);
1964 IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
1966 This->isInDraw = oldInDraw;
1970 context->draw_buffer_dirty = TRUE;
1971 context->current_rt = target;
1973 return context;
1976 /* Context activation is done by the caller. */
1977 static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
1979 const struct wined3d_gl_info *gl_info = context->gl_info;
1980 IWineD3DSurface *rt = context->current_rt;
1981 IWineD3DDeviceImpl *device;
1983 device = ((IWineD3DSurfaceImpl *)rt)->resource.device;
1984 if (!surface_is_offscreen(rt))
1986 ENTER_GL();
1987 glDrawBuffer(surface_get_gl_buffer(rt));
1988 checkGLcall("glDrawBuffers()");
1989 LEAVE_GL();
1991 else
1993 ENTER_GL();
1994 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1996 if (!blit)
1998 if (gl_info->supported[ARB_DRAW_BUFFERS])
2000 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, device->draw_buffers));
2001 checkGLcall("glDrawBuffers()");
2003 else
2005 glDrawBuffer(device->draw_buffers[0]);
2006 checkGLcall("glDrawBuffer()");
2008 } else {
2009 glDrawBuffer(GL_COLOR_ATTACHMENT0);
2010 checkGLcall("glDrawBuffer()");
2013 else
2015 glDrawBuffer(device->offscreenBuffer);
2016 checkGLcall("glDrawBuffer()");
2018 LEAVE_GL();
2022 /* GL locking is done by the caller. */
2023 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2025 glDrawBuffer(buffer);
2026 checkGLcall("glDrawBuffer()");
2027 context->draw_buffer_dirty = TRUE;
2030 /* Context activation is done by the caller. */
2031 static void context_apply_state(struct wined3d_context *context, IWineD3DDeviceImpl *device, enum ContextUsage usage)
2033 const struct StateEntry *state_table = device->StateTable;
2034 unsigned int i;
2036 switch (usage) {
2037 case CTXUSAGE_CLEAR:
2038 case CTXUSAGE_DRAWPRIM:
2039 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2040 ENTER_GL();
2041 context_apply_fbo_state(context);
2042 LEAVE_GL();
2044 if (context->draw_buffer_dirty) {
2045 context_apply_draw_buffer(context, FALSE);
2046 context->draw_buffer_dirty = FALSE;
2048 break;
2050 case CTXUSAGE_BLIT:
2051 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2052 if (context->render_offscreen)
2054 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2055 surface_internal_preload(context->current_rt, SRGB_RGB);
2057 ENTER_GL();
2058 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
2059 context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, context->current_rt);
2060 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
2061 LEAVE_GL();
2062 } else {
2063 ENTER_GL();
2064 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2065 LEAVE_GL();
2067 context->draw_buffer_dirty = TRUE;
2069 if (context->draw_buffer_dirty) {
2070 context_apply_draw_buffer(context, TRUE);
2071 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2072 context->draw_buffer_dirty = FALSE;
2075 break;
2077 default:
2078 break;
2081 switch(usage) {
2082 case CTXUSAGE_RESOURCELOAD:
2083 /* This does not require any special states to be set up */
2084 break;
2086 case CTXUSAGE_CLEAR:
2087 if(context->last_was_blit) {
2088 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2091 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2092 * blending when clearing improves the clearing performance incredibly.
2094 ENTER_GL();
2095 glDisable(GL_BLEND);
2096 LEAVE_GL();
2097 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2099 ENTER_GL();
2100 glEnable(GL_SCISSOR_TEST);
2101 checkGLcall("glEnable GL_SCISSOR_TEST");
2102 LEAVE_GL();
2103 context->last_was_blit = FALSE;
2104 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2105 Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2106 break;
2108 case CTXUSAGE_DRAWPRIM:
2109 /* This needs all dirty states applied */
2110 if(context->last_was_blit) {
2111 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2114 IWineD3DDeviceImpl_FindTexUnitMap(device);
2115 device_preload_textures(device);
2116 if (isStateDirty(context, STATE_VDECL))
2117 device_update_stream_info(device, context->gl_info);
2119 ENTER_GL();
2120 for (i = 0; i < context->numDirtyEntries; ++i)
2122 DWORD rep = context->dirtyArray[i];
2123 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2124 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2125 context->isStateDirty[idx] &= ~(1 << shift);
2126 state_table[rep].apply(rep, device->stateBlock, context);
2128 LEAVE_GL();
2129 context->numDirtyEntries = 0; /* This makes the whole list clean */
2130 context->last_was_blit = FALSE;
2131 break;
2133 case CTXUSAGE_BLIT:
2134 SetupForBlit(device, context);
2135 break;
2137 default:
2138 FIXME("Unexpected context usage requested\n");
2142 /*****************************************************************************
2143 * context_acquire
2145 * Finds a rendering context and drawable matching the device and render
2146 * target for the current thread, activates them and puts them into the
2147 * requested state.
2149 * Params:
2150 * This: Device to activate the context for
2151 * target: Requested render target
2152 * usage: Prepares the context for blitting, drawing or other actions
2154 *****************************************************************************/
2155 struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurface *target, enum ContextUsage usage)
2157 struct wined3d_context *current_context = context_get_current();
2158 struct wined3d_context *context;
2160 TRACE("device %p, target %p, usage %#x.\n", device, target, usage);
2162 context = FindContext(device, target);
2163 context_enter(context);
2164 if (!context->valid) return context;
2166 if (context != current_context)
2168 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2169 else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2171 if (context->vshader_const_dirty)
2173 memset(context->vshader_const_dirty, 1,
2174 sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2175 device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2177 if (context->pshader_const_dirty)
2179 memset(context->pshader_const_dirty, 1,
2180 sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2181 device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2184 else if (context->restore_ctx)
2186 if (!pwglMakeCurrent(context->hdc, context->glCtx))
2188 DWORD err = GetLastError();
2189 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2190 context->hdc, context->glCtx, err);
2194 context_apply_state(context, device, usage);
2196 return context;