msxml3: Block ::add() if collection is read-only.
[wine/multimedia.git] / dlls / wined3d / context.c
blobfe26549179c54f997c7f8431a9fba9fa752c6cbd
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009-2011 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 static DWORD wined3d_context_tls_idx;
33 /* FBO helper functions */
35 /* GL locking is done by the caller */
36 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
38 const struct wined3d_gl_info *gl_info = context->gl_info;
39 GLuint f;
41 if (!fbo)
43 f = 0;
45 else
47 if (!*fbo)
49 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
50 checkGLcall("glGenFramebuffers()");
51 TRACE("Created FBO %u.\n", *fbo);
53 f = *fbo;
56 switch (target)
58 case GL_READ_FRAMEBUFFER:
59 if (context->fbo_read_binding == f) return;
60 context->fbo_read_binding = f;
61 break;
63 case GL_DRAW_FRAMEBUFFER:
64 if (context->fbo_draw_binding == f) return;
65 context->fbo_draw_binding = f;
66 break;
68 case GL_FRAMEBUFFER:
69 if (context->fbo_read_binding == f
70 && context->fbo_draw_binding == f) return;
71 context->fbo_read_binding = f;
72 context->fbo_draw_binding = f;
73 break;
75 default:
76 FIXME("Unhandled target %#x.\n", target);
77 break;
80 gl_info->fbo_ops.glBindFramebuffer(target, f);
81 checkGLcall("glBindFramebuffer()");
84 /* GL locking is done by the caller */
85 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
87 unsigned int i;
89 for (i = 0; i < gl_info->limits.buffers; ++i)
91 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
92 checkGLcall("glFramebufferTexture2D()");
94 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
95 checkGLcall("glFramebufferTexture2D()");
97 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
98 checkGLcall("glFramebufferTexture2D()");
101 /* GL locking is done by the caller */
102 static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
104 const struct wined3d_gl_info *gl_info = context->gl_info;
106 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
107 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
108 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
110 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
111 checkGLcall("glDeleteFramebuffers()");
114 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
115 GLenum fbo_target, DWORD format_flags, GLuint rb)
117 if (format_flags & WINED3DFMT_FLAG_DEPTH)
119 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
120 checkGLcall("glFramebufferRenderbuffer()");
123 if (format_flags & WINED3DFMT_FLAG_STENCIL)
125 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
126 checkGLcall("glFramebufferRenderbuffer()");
130 /* GL locking is done by the caller */
131 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
132 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
134 const struct wined3d_gl_info *gl_info = context->gl_info;
136 TRACE("Attach depth stencil %p\n", depth_stencil);
138 if (depth_stencil)
140 DWORD format_flags = depth_stencil->resource.format->flags;
142 if (depth_stencil->current_renderbuffer)
144 context_attach_depth_stencil_rb(gl_info, fbo_target,
145 format_flags, depth_stencil->current_renderbuffer->id);
147 else
149 switch (location)
151 case SFLAG_INTEXTURE:
152 case SFLAG_INSRGBTEX:
153 surface_prepare_texture(depth_stencil, context, FALSE);
155 if (format_flags & WINED3DFMT_FLAG_DEPTH)
157 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
158 depth_stencil->texture_target, depth_stencil->texture_name,
159 depth_stencil->texture_level);
160 checkGLcall("glFramebufferTexture2D()");
163 if (format_flags & WINED3DFMT_FLAG_STENCIL)
165 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
166 depth_stencil->texture_target, depth_stencil->texture_name,
167 depth_stencil->texture_level);
168 checkGLcall("glFramebufferTexture2D()");
170 break;
172 case SFLAG_INRB_MULTISAMPLE:
173 surface_prepare_rb(depth_stencil, gl_info, TRUE);
174 context_attach_depth_stencil_rb(gl_info, fbo_target,
175 format_flags, depth_stencil->rb_multisample);
176 break;
178 case SFLAG_INRB_RESOLVED:
179 surface_prepare_rb(depth_stencil, gl_info, FALSE);
180 context_attach_depth_stencil_rb(gl_info, fbo_target,
181 format_flags, depth_stencil->rb_resolved);
182 break;
184 default:
185 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
186 break;
190 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
192 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
193 checkGLcall("glFramebufferTexture2D()");
196 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
198 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
199 checkGLcall("glFramebufferTexture2D()");
202 else
204 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
205 checkGLcall("glFramebufferTexture2D()");
207 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
208 checkGLcall("glFramebufferTexture2D()");
212 /* GL locking is done by the caller */
213 static void context_attach_surface_fbo(struct wined3d_context *context,
214 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
216 const struct wined3d_gl_info *gl_info = context->gl_info;
218 TRACE("Attach surface %p to %u\n", surface, idx);
220 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
222 BOOL srgb;
224 switch (location)
226 case SFLAG_INTEXTURE:
227 case SFLAG_INSRGBTEX:
228 srgb = location == SFLAG_INSRGBTEX;
229 surface_prepare_texture(surface, context, srgb);
230 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
231 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
232 surface->texture_level);
233 checkGLcall("glFramebufferTexture2D()");
234 break;
236 case SFLAG_INRB_MULTISAMPLE:
237 surface_prepare_rb(surface, gl_info, TRUE);
238 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
239 GL_RENDERBUFFER, surface->rb_multisample);
240 checkGLcall("glFramebufferRenderbuffer()");
241 break;
243 case SFLAG_INRB_RESOLVED:
244 surface_prepare_rb(surface, gl_info, FALSE);
245 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
246 GL_RENDERBUFFER, surface->rb_resolved);
247 checkGLcall("glFramebufferRenderbuffer()");
248 break;
250 default:
251 ERR("Unsupported location %s (%#x).\n", debug_surflocation(location), location);
252 break;
255 else
257 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
258 checkGLcall("glFramebufferTexture2D()");
262 /* GL locking is done by the caller */
263 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
265 const struct wined3d_gl_info *gl_info = context->gl_info;
266 GLenum status;
268 if (!FIXME_ON(d3d)) return;
270 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
271 if (status == GL_FRAMEBUFFER_COMPLETE)
273 TRACE("FBO complete\n");
275 else
277 const struct wined3d_surface *attachment;
278 unsigned int i;
280 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
282 if (!context->current_fbo)
284 ERR("FBO 0 is incomplete, driver bug?\n");
285 return;
288 FIXME("\tLocation %s (%#x).\n", debug_surflocation(context->current_fbo->location),
289 context->current_fbo->location);
291 /* Dump the FBO attachments */
292 for (i = 0; i < gl_info->limits.buffers; ++i)
294 attachment = context->current_fbo->render_targets[i];
295 if (attachment)
297 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
298 i, attachment, debug_d3dformat(attachment->resource.format->id),
299 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
302 attachment = context->current_fbo->depth_stencil;
303 if (attachment)
305 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
306 attachment, debug_d3dformat(attachment->resource.format->id),
307 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
312 static inline DWORD context_generate_rt_mask(GLenum buffer)
314 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
315 return buffer ? (1 << 31) | buffer : 0;
318 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
320 return (1 << 31) | surface_get_gl_buffer(target);
323 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
324 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
326 const struct wined3d_gl_info *gl_info = context->gl_info;
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, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
332 entry->depth_stencil = depth_stencil;
333 entry->location = location;
334 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
335 entry->attached = FALSE;
336 entry->id = 0;
338 return entry;
341 /* GL locking is done by the caller */
342 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
343 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
344 DWORD location, struct fbo_entry *entry)
346 const struct wined3d_gl_info *gl_info = context->gl_info;
348 context_bind_fbo(context, target, &entry->id);
349 context_clean_fbo_attachments(gl_info, target);
351 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
352 entry->depth_stencil = depth_stencil;
353 entry->location = location;
354 entry->attached = FALSE;
357 /* GL locking is done by the caller */
358 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
360 if (entry->id)
362 TRACE("Destroy FBO %d\n", entry->id);
363 context_destroy_fbo(context, &entry->id);
365 --context->fbo_entry_count;
366 list_remove(&entry->entry);
367 HeapFree(GetProcessHeap(), 0, entry->render_targets);
368 HeapFree(GetProcessHeap(), 0, entry);
372 /* GL locking is done by the caller */
373 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
374 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
376 const struct wined3d_gl_info *gl_info = context->gl_info;
377 struct fbo_entry *entry;
379 if (depth_stencil && render_targets && render_targets[0])
381 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
382 depth_stencil->resource.height < render_targets[0]->resource.height)
384 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
385 depth_stencil = NULL;
389 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
391 if (!memcmp(entry->render_targets,
392 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
393 && entry->depth_stencil == depth_stencil && entry->location == location)
395 list_remove(&entry->entry);
396 list_add_head(&context->fbo_list, &entry->entry);
397 return entry;
401 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
403 entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
404 list_add_head(&context->fbo_list, &entry->entry);
405 ++context->fbo_entry_count;
407 else
409 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
410 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
411 list_remove(&entry->entry);
412 list_add_head(&context->fbo_list, &entry->entry);
415 return entry;
418 /* GL locking is done by the caller */
419 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
421 const struct wined3d_gl_info *gl_info = context->gl_info;
422 unsigned int i;
424 context_bind_fbo(context, target, &entry->id);
426 if (entry->attached) return;
428 /* Apply render targets */
429 for (i = 0; i < gl_info->limits.buffers; ++i)
431 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
434 /* Apply depth targets */
435 if (entry->depth_stencil)
436 surface_set_compatible_renderbuffer(entry->depth_stencil, entry->render_targets[0]);
437 context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, entry->location);
439 entry->attached = TRUE;
442 /* GL locking is done by the caller */
443 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
444 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
446 struct fbo_entry *entry, *entry2;
448 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
450 context_destroy_fbo_entry(context, entry);
453 if (context->rebind_fbo)
455 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
456 context->rebind_fbo = FALSE;
459 if (location == SFLAG_INDRAWABLE)
461 context->current_fbo = NULL;
462 context_bind_fbo(context, target, NULL);
464 else
466 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
467 context_apply_fbo_entry(context, target, context->current_fbo);
471 /* GL locking is done by the caller */
472 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
473 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
475 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
477 context->blit_targets[0] = render_target;
478 if (clear_size)
479 memset(&context->blit_targets[1], 0, clear_size);
480 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location);
483 /* Context activation is done by the caller. */
484 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
486 const struct wined3d_gl_info *gl_info = context->gl_info;
488 if (context->free_occlusion_query_count)
490 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
492 else
494 if (gl_info->supported[ARB_OCCLUSION_QUERY])
496 ENTER_GL();
497 GL_EXTCALL(glGenQueriesARB(1, &query->id));
498 checkGLcall("glGenQueriesARB");
499 LEAVE_GL();
501 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
503 else
505 WARN("Occlusion queries not supported, not allocating query id.\n");
506 query->id = 0;
510 query->context = context;
511 list_add_head(&context->occlusion_queries, &query->entry);
514 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
516 struct wined3d_context *context = query->context;
518 list_remove(&query->entry);
519 query->context = NULL;
521 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
523 UINT new_size = context->free_occlusion_query_size << 1;
524 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
525 new_size * sizeof(*context->free_occlusion_queries));
527 if (!new_data)
529 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
530 return;
533 context->free_occlusion_query_size = new_size;
534 context->free_occlusion_queries = new_data;
537 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
540 /* Context activation is done by the caller. */
541 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
543 const struct wined3d_gl_info *gl_info = context->gl_info;
545 if (context->free_event_query_count)
547 query->object = context->free_event_queries[--context->free_event_query_count];
549 else
551 if (gl_info->supported[ARB_SYNC])
553 /* Using ARB_sync, not much to do here. */
554 query->object.sync = NULL;
555 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
557 else if (gl_info->supported[APPLE_FENCE])
559 ENTER_GL();
560 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
561 checkGLcall("glGenFencesAPPLE");
562 LEAVE_GL();
564 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
566 else if(gl_info->supported[NV_FENCE])
568 ENTER_GL();
569 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
570 checkGLcall("glGenFencesNV");
571 LEAVE_GL();
573 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
575 else
577 WARN("Event queries not supported, not allocating query id.\n");
578 query->object.id = 0;
582 query->context = context;
583 list_add_head(&context->event_queries, &query->entry);
586 void context_free_event_query(struct wined3d_event_query *query)
588 struct wined3d_context *context = query->context;
590 list_remove(&query->entry);
591 query->context = NULL;
593 if (context->free_event_query_count >= context->free_event_query_size - 1)
595 UINT new_size = context->free_event_query_size << 1;
596 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
597 new_size * sizeof(*context->free_event_queries));
599 if (!new_data)
601 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
602 return;
605 context->free_event_query_size = new_size;
606 context->free_event_queries = new_data;
609 context->free_event_queries[context->free_event_query_count++] = query->object;
612 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
614 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
615 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
617 UINT i;
619 for (i = 0; i < device->context_count; ++i)
621 struct wined3d_context *context = device->contexts[i];
622 const struct wined3d_gl_info *gl_info = context->gl_info;
623 struct fbo_entry *entry, *entry2;
625 if (context->current_rt == surface) context->current_rt = NULL;
627 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
629 UINT j;
631 if (entry->depth_stencil == surface)
633 callback(context, entry);
634 continue;
637 for (j = 0; j < gl_info->limits.buffers; ++j)
639 if (entry->render_targets[j] == surface)
641 callback(context, entry);
642 break;
649 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
651 list_remove(&entry->entry);
652 list_add_head(&context->fbo_destroy_list, &entry->entry);
655 void context_resource_released(const struct wined3d_device *device,
656 struct wined3d_resource *resource, enum wined3d_resource_type type)
658 if (!device->d3d_initialized) return;
660 switch (type)
662 case WINED3D_RTYPE_SURFACE:
663 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
664 context_queue_fbo_entry_destruction);
665 break;
667 default:
668 break;
672 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
674 entry->attached = FALSE;
677 void context_resource_unloaded(const struct wined3d_device *device,
678 struct wined3d_resource *resource, enum wined3d_resource_type type)
680 switch (type)
682 case WINED3D_RTYPE_SURFACE:
683 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
684 context_detach_fbo_entry);
685 break;
687 default:
688 break;
692 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
694 const struct wined3d_gl_info *gl_info = context->gl_info;
695 struct fbo_entry *entry = context->current_fbo;
696 unsigned int i;
698 if (!entry || context->rebind_fbo) return;
700 for (i = 0; i < gl_info->limits.buffers; ++i)
702 if (surface == entry->render_targets[i])
704 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
705 context->rebind_fbo = TRUE;
706 return;
710 if (surface == entry->depth_stencil)
712 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
713 context->rebind_fbo = TRUE;
717 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
719 int current = GetPixelFormat(dc);
721 if (current == format) return TRUE;
723 if (!current)
725 if (!SetPixelFormat(dc, format, NULL))
727 /* This may also happen if the dc belongs to a destroyed window. */
728 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
729 format, dc, GetLastError());
730 return FALSE;
732 return TRUE;
735 /* By default WGL doesn't allow pixel format adjustments but we need it
736 * here. For this reason there's a Wine specific wglSetPixelFormat()
737 * which allows us to set the pixel format multiple times. Only use it
738 * when really needed. */
739 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
741 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
743 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
744 format, dc);
745 return FALSE;
747 return TRUE;
750 /* OpenGL doesn't allow pixel format adjustments. Print an error and
751 * continue using the old format. There's a big chance that the old
752 * format works although with a performance hit and perhaps rendering
753 * errors. */
754 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
755 format, dc, current);
756 return TRUE;
759 static BOOL context_set_gl_context(struct wined3d_context *ctx)
761 struct wined3d_swapchain *swapchain = ctx->swapchain;
762 BOOL backup = FALSE;
764 if (!context_set_pixel_format(ctx->gl_info, ctx->hdc, ctx->pixel_format))
766 WARN("Failed to set pixel format %d on device context %p.\n",
767 ctx->pixel_format, ctx->hdc);
768 backup = TRUE;
771 if (backup || !pwglMakeCurrent(ctx->hdc, ctx->glCtx))
773 HDC dc;
775 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
776 ctx->glCtx, ctx->hdc, GetLastError());
777 ctx->valid = 0;
778 WARN("Trying fallback to the backup window.\n");
780 /* FIXME: If the context is destroyed it's no longer associated with
781 * a swapchain, so we can't use the swapchain to get a backup dc. To
782 * make this work windowless contexts would need to be handled by the
783 * device. */
784 if (ctx->destroyed)
786 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
787 context_set_current(NULL);
788 return FALSE;
791 if (!(dc = swapchain_get_backup_dc(swapchain)))
793 context_set_current(NULL);
794 return FALSE;
797 if (!context_set_pixel_format(ctx->gl_info, dc, ctx->pixel_format))
799 ERR("Failed to set pixel format %d on device context %p.\n",
800 ctx->pixel_format, dc);
801 context_set_current(NULL);
802 return FALSE;
805 if (!pwglMakeCurrent(dc, ctx->glCtx))
807 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
808 dc, GetLastError());
809 context_set_current(NULL);
810 return FALSE;
813 return TRUE;
816 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx, int pf)
818 if (!context_set_pixel_format(gl_info, dc, pf))
820 ERR("Failed to restore pixel format %d on device context %p.\n", pf, dc);
821 context_set_current(NULL);
822 return;
825 if (!pwglMakeCurrent(dc, gl_ctx))
827 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
828 gl_ctx, dc, GetLastError());
829 context_set_current(NULL);
833 static void context_update_window(struct wined3d_context *context)
835 if (context->win_handle == context->swapchain->win_handle)
836 return;
838 TRACE("Updating context %p window from %p to %p.\n",
839 context, context->win_handle, context->swapchain->win_handle);
841 if (context->valid)
843 /* You'd figure ReleaseDC() would fail if the DC doesn't match the
844 * window. However, that's not what actually happens, and there are
845 * user32 tests that confirm ReleaseDC() with the wrong window is
846 * supposed to succeed. So explicitly check that the DC belongs to
847 * the window, since we want to avoid releasing a DC that belongs to
848 * some other window if the original window was already destroyed. */
849 if (WindowFromDC(context->hdc) != context->win_handle)
851 WARN("DC %p does not belong to window %p.\n",
852 context->hdc, context->win_handle);
854 else if (!ReleaseDC(context->win_handle, context->hdc))
856 ERR("Failed to release device context %p, last error %#x.\n",
857 context->hdc, GetLastError());
860 else context->valid = 1;
862 context->win_handle = context->swapchain->win_handle;
864 if (!(context->hdc = GetDC(context->win_handle)))
866 ERR("Failed to get a device context for window %p.\n", context->win_handle);
867 goto err;
870 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
872 ERR("Failed to set pixel format %d on device context %p.\n",
873 context->pixel_format, context->hdc);
874 goto err;
877 context_set_gl_context(context);
879 return;
881 err:
882 context->valid = 0;
885 /* Do not call while under the GL lock. */
886 static void context_destroy_gl_resources(struct wined3d_context *context)
888 const struct wined3d_gl_info *gl_info = context->gl_info;
889 struct wined3d_occlusion_query *occlusion_query;
890 struct wined3d_event_query *event_query;
891 struct fbo_entry *entry, *entry2;
892 HGLRC restore_ctx;
893 HDC restore_dc;
894 unsigned int i;
895 int restore_pf;
897 restore_ctx = pwglGetCurrentContext();
898 restore_dc = pwglGetCurrentDC();
899 restore_pf = GetPixelFormat(restore_dc);
901 if (context->valid && restore_ctx != context->glCtx)
902 context_set_gl_context(context);
903 else restore_ctx = NULL;
905 ENTER_GL();
907 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
909 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
910 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
911 occlusion_query->context = NULL;
914 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
916 if (context->valid)
918 if (gl_info->supported[ARB_SYNC])
920 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
922 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
923 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
925 event_query->context = NULL;
928 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
930 if (!context->valid) entry->id = 0;
931 context_destroy_fbo_entry(context, entry);
934 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
936 if (!context->valid) entry->id = 0;
937 context_destroy_fbo_entry(context, entry);
940 if (context->valid)
942 if (context->dummy_arbfp_prog)
944 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
947 if (gl_info->supported[ARB_OCCLUSION_QUERY])
948 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
950 if (gl_info->supported[ARB_SYNC])
952 for (i = 0; i < context->free_event_query_count; ++i)
954 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
957 else if (gl_info->supported[APPLE_FENCE])
959 for (i = 0; i < context->free_event_query_count; ++i)
961 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
964 else if (gl_info->supported[NV_FENCE])
966 for (i = 0; i < context->free_event_query_count; ++i)
968 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
972 checkGLcall("context cleanup");
975 LEAVE_GL();
977 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
978 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
980 if (restore_ctx)
982 context_restore_gl_context(gl_info, restore_dc, restore_ctx, restore_pf);
984 else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
986 ERR("Failed to disable GL context.\n");
989 ReleaseDC(context->win_handle, context->hdc);
991 if (!pwglDeleteContext(context->glCtx))
993 DWORD err = GetLastError();
994 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
998 DWORD context_get_tls_idx(void)
1000 return wined3d_context_tls_idx;
1003 void context_set_tls_idx(DWORD idx)
1005 wined3d_context_tls_idx = idx;
1008 struct wined3d_context *context_get_current(void)
1010 return TlsGetValue(wined3d_context_tls_idx);
1013 /* Do not call while under the GL lock. */
1014 BOOL context_set_current(struct wined3d_context *ctx)
1016 struct wined3d_context *old = context_get_current();
1018 if (old == ctx)
1020 TRACE("Already using D3D context %p.\n", ctx);
1021 return TRUE;
1024 if (old)
1026 if (old->destroyed)
1028 TRACE("Switching away from destroyed context %p.\n", old);
1029 context_destroy_gl_resources(old);
1030 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1031 HeapFree(GetProcessHeap(), 0, old);
1033 else
1035 old->current = 0;
1039 if (ctx)
1041 if (!ctx->valid)
1043 ERR("Trying to make invalid context %p current\n", ctx);
1044 return FALSE;
1047 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1048 if (!context_set_gl_context(ctx))
1049 return FALSE;
1050 ctx->current = 1;
1052 else if(pwglGetCurrentContext())
1054 TRACE("Clearing current D3D context.\n");
1055 if (!pwglMakeCurrent(NULL, NULL))
1057 DWORD err = GetLastError();
1058 ERR("Failed to clear current GL context, last error %#x.\n", err);
1059 TlsSetValue(wined3d_context_tls_idx, NULL);
1060 return FALSE;
1064 return TlsSetValue(wined3d_context_tls_idx, ctx);
1067 void context_release(struct wined3d_context *context)
1069 TRACE("Releasing context %p, level %u.\n", context, context->level);
1071 if (WARN_ON(d3d))
1073 if (!context->level)
1074 WARN("Context %p is not active.\n", context);
1075 else if (context != context_get_current())
1076 WARN("Context %p is not the current context.\n", context);
1079 if (!--context->level && context->restore_ctx)
1081 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1082 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx, context->restore_pf);
1083 context->restore_ctx = NULL;
1084 context->restore_dc = NULL;
1088 static void context_enter(struct wined3d_context *context)
1090 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1092 if (!context->level++)
1094 const struct wined3d_context *current_context = context_get_current();
1095 HGLRC current_gl = pwglGetCurrentContext();
1097 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1099 TRACE("Another GL context (%p on device context %p) is already current.\n",
1100 current_gl, pwglGetCurrentDC());
1101 context->restore_ctx = current_gl;
1102 context->restore_dc = pwglGetCurrentDC();
1103 context->restore_pf = GetPixelFormat(context->restore_dc);
1108 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1110 DWORD rep = context->state_table[state].representative;
1111 DWORD idx;
1112 BYTE shift;
1114 if (isStateDirty(context, rep)) return;
1116 context->dirtyArray[context->numDirtyEntries++] = rep;
1117 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1118 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1119 context->isStateDirty[idx] |= (1 << shift);
1122 /* This function takes care of wined3d pixel format selection. */
1123 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1124 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1125 BOOL auxBuffers, BOOL findCompatible)
1127 int iPixelFormat=0;
1128 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1129 BYTE depthBits=0, stencilBits=0;
1130 unsigned int current_value;
1131 unsigned int cfg_count = device->adapter->cfg_count;
1132 unsigned int i;
1134 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1135 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1136 auxBuffers, findCompatible);
1138 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1140 ERR("Unable to get color bits for format %s (%#x)!\n",
1141 debug_d3dformat(color_format->id), color_format->id);
1142 return 0;
1145 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1147 current_value = 0;
1148 for (i = 0; i < cfg_count; ++i)
1150 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1151 unsigned int value;
1153 /* For now only accept RGBA formats. Perhaps some day we will
1154 * allow floating point formats for pbuffers. */
1155 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1156 continue;
1157 /* In window mode we need a window drawable format and double buffering. */
1158 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1159 continue;
1160 if (cfg->redSize < redBits)
1161 continue;
1162 if (cfg->greenSize < greenBits)
1163 continue;
1164 if (cfg->blueSize < blueBits)
1165 continue;
1166 if (cfg->alphaSize < alphaBits)
1167 continue;
1168 if (cfg->depthSize < depthBits)
1169 continue;
1170 if (stencilBits && cfg->stencilSize != stencilBits)
1171 continue;
1172 /* Check multisampling support. */
1173 if (cfg->numSamples)
1174 continue;
1176 value = 1;
1177 /* We try to locate a format which matches our requirements exactly. In case of
1178 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1179 if (cfg->depthSize == depthBits)
1180 value += 1;
1181 if (cfg->stencilSize == stencilBits)
1182 value += 2;
1183 if (cfg->alphaSize == alphaBits)
1184 value += 4;
1185 /* We like to have aux buffers in backbuffer mode */
1186 if (auxBuffers && cfg->auxBuffers)
1187 value += 8;
1188 if (cfg->redSize == redBits
1189 && cfg->greenSize == greenBits
1190 && cfg->blueSize == blueBits)
1191 value += 16;
1193 if (value > current_value)
1195 iPixelFormat = cfg->iPixelFormat;
1196 current_value = value;
1200 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1201 if(!iPixelFormat && !findCompatible) {
1202 ERR("Can't find a suitable iPixelFormat\n");
1203 return FALSE;
1204 } else if(!iPixelFormat) {
1205 PIXELFORMATDESCRIPTOR pfd;
1207 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1208 /* PixelFormat selection */
1209 ZeroMemory(&pfd, sizeof(pfd));
1210 pfd.nSize = sizeof(pfd);
1211 pfd.nVersion = 1;
1212 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1213 pfd.iPixelType = PFD_TYPE_RGBA;
1214 pfd.cAlphaBits = alphaBits;
1215 pfd.cColorBits = colorBits;
1216 pfd.cDepthBits = depthBits;
1217 pfd.cStencilBits = stencilBits;
1218 pfd.iLayerType = PFD_MAIN_PLANE;
1220 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1221 if(!iPixelFormat) {
1222 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1223 ERR("Can't find a suitable iPixelFormat\n");
1224 return FALSE;
1228 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1229 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1230 return iPixelFormat;
1233 /* GL locking is done by the caller */
1234 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1236 const struct wined3d_gl_info *gl_info = context->gl_info;
1237 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1239 for (i = 0; i < count; ++i)
1241 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1242 checkGLcall("glActiveTextureARB");
1244 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1245 checkGLcall("glBindTexture");
1247 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1249 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1250 checkGLcall("glBindTexture");
1253 if (gl_info->supported[EXT_TEXTURE3D])
1255 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1256 checkGLcall("glBindTexture");
1259 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1261 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1262 checkGLcall("glBindTexture");
1267 /* Do not call while under the GL lock. */
1268 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1269 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1271 struct wined3d_device *device = swapchain->device;
1272 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1273 const struct wined3d_format *color_format;
1274 struct wined3d_context *ret;
1275 BOOL auxBuffers = FALSE;
1276 int pixel_format;
1277 unsigned int s;
1278 int swap_interval;
1279 DWORD state;
1280 HGLRC ctx;
1281 HDC hdc;
1283 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1285 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1286 if (!ret)
1288 ERR("Failed to allocate context memory.\n");
1289 return NULL;
1292 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1293 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1294 if (!ret->blit_targets)
1295 goto out;
1297 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1298 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1299 if (!ret->draw_buffers)
1300 goto out;
1302 ret->free_occlusion_query_size = 4;
1303 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1304 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1305 if (!ret->free_occlusion_queries)
1306 goto out;
1308 list_init(&ret->occlusion_queries);
1310 ret->free_event_query_size = 4;
1311 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1312 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1313 if (!ret->free_event_queries)
1314 goto out;
1316 list_init(&ret->event_queries);
1317 list_init(&ret->fbo_list);
1318 list_init(&ret->fbo_destroy_list);
1320 if (!(hdc = GetDC(swapchain->win_handle)))
1322 WARN("Failed to retireve device context, trying swapchain backup.\n");
1324 if (!(hdc = swapchain_get_backup_dc(swapchain)))
1326 ERR("Failed to retrieve a device context.\n");
1327 goto out;
1331 color_format = target->resource.format;
1333 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1334 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1335 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1337 auxBuffers = TRUE;
1339 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1340 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1341 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1342 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1345 /* DirectDraw supports 8bit paletted render targets and these are used by
1346 * old games like StarCraft and C&C. Most modern hardware doesn't support
1347 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1348 * conversion (ab)uses the alpha component for storing the palette index.
1349 * For this reason we require a format with 8bit alpha, so request
1350 * A8R8G8B8. */
1351 if (color_format->id == WINED3DFMT_P8_UINT)
1352 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1354 /* Try to find a pixel format which matches our requirements. */
1355 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1357 /* Try to locate a compatible format if we weren't able to find anything. */
1358 if (!pixel_format)
1360 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1361 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1364 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1365 if (!pixel_format)
1367 ERR("Can't find a suitable pixel format.\n");
1368 goto out;
1371 context_enter(ret);
1373 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1375 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1376 context_release(ret);
1377 goto out;
1380 if (!(ctx = pwglCreateContext(hdc)))
1382 ERR("Failed to create a WGL context.\n");
1383 context_release(ret);
1384 goto out;
1387 if (device->context_count)
1389 if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1391 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1392 device->contexts[0]->glCtx, ctx, GetLastError());
1393 context_release(ret);
1394 if (!pwglDeleteContext(ctx))
1395 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1396 goto out;
1400 if (!device_context_add(device, ret))
1402 ERR("Failed to add the newly created context to the context list\n");
1403 context_release(ret);
1404 if (!pwglDeleteContext(ctx))
1405 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1406 goto out;
1409 ret->gl_info = gl_info;
1410 ret->state_table = device->StateTable;
1412 /* Mark all states dirty to force a proper initialization of the states
1413 * on the first use of the context. */
1414 for (state = 0; state <= STATE_HIGHEST; ++state)
1416 if (ret->state_table[state].representative)
1417 context_invalidate_state(ret, state);
1420 ret->swapchain = swapchain;
1421 ret->current_rt = target;
1422 ret->tid = GetCurrentThreadId();
1424 ret->render_offscreen = surface_is_offscreen(target);
1425 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1426 ret->valid = 1;
1428 ret->glCtx = ctx;
1429 ret->win_handle = swapchain->win_handle;
1430 ret->hdc = hdc;
1431 ret->pixel_format = pixel_format;
1433 /* Set up the context defaults */
1434 if (!context_set_current(ret))
1436 ERR("Cannot activate context to set up defaults.\n");
1437 device_context_remove(device, ret);
1438 context_release(ret);
1439 if (!pwglDeleteContext(ctx))
1440 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1441 goto out;
1444 switch (swapchain->desc.swap_interval)
1446 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1447 swap_interval = 0;
1448 break;
1449 case WINED3DPRESENT_INTERVAL_DEFAULT:
1450 case WINED3DPRESENT_INTERVAL_ONE:
1451 swap_interval = 1;
1452 break;
1453 case WINED3DPRESENT_INTERVAL_TWO:
1454 swap_interval = 2;
1455 break;
1456 case WINED3DPRESENT_INTERVAL_THREE:
1457 swap_interval = 3;
1458 break;
1459 case WINED3DPRESENT_INTERVAL_FOUR:
1460 swap_interval = 4;
1461 break;
1462 default:
1463 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1464 swap_interval = 1;
1467 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1469 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1470 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1471 swap_interval, ret, GetLastError());
1474 ENTER_GL();
1476 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1478 TRACE("Setting up the screen\n");
1479 /* Clear the screen */
1480 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1481 checkGLcall("glClearColor");
1482 glClearIndex(0);
1483 glClearDepth(1);
1484 glClearStencil(0xffff);
1486 checkGLcall("glClear");
1488 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1489 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1491 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1492 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1494 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1495 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1497 glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1498 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1499 glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1500 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1502 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1504 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1505 * and textures in DIB sections(due to the memory protection).
1507 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1508 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1510 if (gl_info->supported[ARB_VERTEX_BLEND])
1512 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1513 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1514 * GL_VERTEX_BLEND_ARB isn't enabled too
1516 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1517 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1519 if (gl_info->supported[NV_TEXTURE_SHADER2])
1521 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1522 * the previous texture where to source the offset from is always unit - 1.
1524 for (s = 1; s < gl_info->limits.textures; ++s)
1526 context_active_texture(ret, gl_info, s);
1527 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1528 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1531 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1533 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1534 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1535 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1536 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1537 * is ever assigned.
1539 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1540 * program and the dummy program is destroyed when the context is destroyed.
1542 const char *dummy_program =
1543 "!!ARBfp1.0\n"
1544 "MOV result.color, fragment.color.primary;\n"
1545 "END\n";
1546 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1547 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1548 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1551 if (gl_info->supported[ARB_POINT_SPRITE])
1553 for (s = 0; s < gl_info->limits.textures; ++s)
1555 context_active_texture(ret, gl_info, s);
1556 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1557 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1561 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1563 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1565 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1567 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1569 device->frag_pipe->enable_extension(TRUE);
1571 /* If this happens to be the first context for the device, dummy textures
1572 * are not created yet. In that case, they will be created (and bound) by
1573 * create_dummy_textures right after this context is initialized. */
1574 if (device->dummy_texture_2d[0])
1575 bind_dummy_textures(device, ret);
1577 LEAVE_GL();
1579 TRACE("Created context %p.\n", ret);
1581 return ret;
1583 out:
1584 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1585 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1586 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1587 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1588 HeapFree(GetProcessHeap(), 0, ret);
1589 return NULL;
1592 /* Do not call while under the GL lock. */
1593 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1595 BOOL destroy;
1597 TRACE("Destroying ctx %p\n", context);
1599 if (context->tid == GetCurrentThreadId() || !context->current)
1601 context_destroy_gl_resources(context);
1602 TlsSetValue(wined3d_context_tls_idx, NULL);
1603 destroy = TRUE;
1605 else
1607 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1608 in wined3d_adapter may go away in the meantime */
1609 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1610 *gl_info = *context->gl_info;
1611 context->gl_info = gl_info;
1612 context->destroyed = 1;
1613 destroy = FALSE;
1616 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1617 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1618 device_context_remove(device, context);
1619 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1622 /* GL locking is done by the caller */
1623 static void set_blit_dimension(UINT width, UINT height)
1625 const GLdouble projection[] =
1627 2.0 / width, 0.0, 0.0, 0.0,
1628 0.0, 2.0 / height, 0.0, 0.0,
1629 0.0, 0.0, 2.0, 0.0,
1630 -1.0, -1.0, -1.0, 1.0,
1633 glMatrixMode(GL_PROJECTION);
1634 checkGLcall("glMatrixMode(GL_PROJECTION)");
1635 glLoadMatrixd(projection);
1636 checkGLcall("glLoadMatrixd");
1637 glViewport(0, 0, width, height);
1638 checkGLcall("glViewport");
1641 /*****************************************************************************
1642 * SetupForBlit
1644 * Sets up a context for DirectDraw blitting.
1645 * All texture units are disabled, texture unit 0 is set as current unit
1646 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1647 * color writing enabled for all channels
1648 * register combiners disabled, shaders disabled
1649 * world matrix is set to identity, texture matrix 0 too
1650 * projection matrix is setup for drawing screen coordinates
1652 * Params:
1653 * This: Device to activate the context for
1654 * context: Context to setup
1656 *****************************************************************************/
1657 /* Context activation is done by the caller. */
1658 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1660 int i;
1661 const struct wined3d_gl_info *gl_info = context->gl_info;
1662 UINT width = context->current_rt->resource.width;
1663 UINT height = context->current_rt->resource.height;
1664 DWORD sampler;
1666 TRACE("Setting up context %p for blitting\n", context);
1667 if(context->last_was_blit) {
1668 if(context->blit_w != width || context->blit_h != height) {
1669 ENTER_GL();
1670 set_blit_dimension(width, height);
1671 LEAVE_GL();
1672 context->blit_w = width; context->blit_h = height;
1673 /* No need to dirtify here, the states are still dirtified because they weren't
1674 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1675 * be set
1678 TRACE("Context is already set up for blitting, nothing to do\n");
1679 return;
1681 context->last_was_blit = TRUE;
1683 /* TODO: Use a display list */
1685 /* Disable shaders */
1686 ENTER_GL();
1687 device->shader_backend->shader_select(context, FALSE, FALSE);
1688 LEAVE_GL();
1690 context_invalidate_state(context, STATE_VSHADER);
1691 context_invalidate_state(context, STATE_PIXELSHADER);
1693 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1694 * helper functions in between gl calls. This function is full of context_invalidate_state
1695 * which can safely be called from here, we only lock once instead locking/unlocking
1696 * after each GL call.
1698 ENTER_GL();
1700 /* Disable all textures. The caller can then bind a texture it wants to blit
1701 * from
1703 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1704 * function texture unit. No need to care for higher samplers
1706 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1708 sampler = device->rev_tex_unit_map[i];
1709 context_active_texture(context, gl_info, i);
1711 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1713 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1714 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1716 glDisable(GL_TEXTURE_3D);
1717 checkGLcall("glDisable GL_TEXTURE_3D");
1718 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1720 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1721 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1723 glDisable(GL_TEXTURE_2D);
1724 checkGLcall("glDisable GL_TEXTURE_2D");
1726 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1727 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1729 if (sampler != WINED3D_UNMAPPED_STAGE)
1731 if (sampler < MAX_TEXTURES)
1732 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1733 context_invalidate_state(context, STATE_SAMPLER(sampler));
1736 context_active_texture(context, gl_info, 0);
1738 sampler = device->rev_tex_unit_map[0];
1740 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1742 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1743 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1745 glDisable(GL_TEXTURE_3D);
1746 checkGLcall("glDisable GL_TEXTURE_3D");
1747 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1749 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1750 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1752 glDisable(GL_TEXTURE_2D);
1753 checkGLcall("glDisable GL_TEXTURE_2D");
1755 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1757 glMatrixMode(GL_TEXTURE);
1758 checkGLcall("glMatrixMode(GL_TEXTURE)");
1759 glLoadIdentity();
1760 checkGLcall("glLoadIdentity()");
1762 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1764 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1765 GL_TEXTURE_LOD_BIAS_EXT,
1766 0.0f);
1767 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1770 if (sampler != WINED3D_UNMAPPED_STAGE)
1772 if (sampler < MAX_TEXTURES)
1774 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1775 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1777 context_invalidate_state(context, STATE_SAMPLER(sampler));
1780 /* Other misc states */
1781 glDisable(GL_ALPHA_TEST);
1782 checkGLcall("glDisable(GL_ALPHA_TEST)");
1783 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1784 glDisable(GL_LIGHTING);
1785 checkGLcall("glDisable GL_LIGHTING");
1786 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1787 glDisable(GL_DEPTH_TEST);
1788 checkGLcall("glDisable GL_DEPTH_TEST");
1789 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1790 glDisableWINE(GL_FOG);
1791 checkGLcall("glDisable GL_FOG");
1792 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1793 glDisable(GL_BLEND);
1794 checkGLcall("glDisable GL_BLEND");
1795 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1796 glDisable(GL_CULL_FACE);
1797 checkGLcall("glDisable GL_CULL_FACE");
1798 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1799 glDisable(GL_STENCIL_TEST);
1800 checkGLcall("glDisable GL_STENCIL_TEST");
1801 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1802 glDisable(GL_SCISSOR_TEST);
1803 checkGLcall("glDisable GL_SCISSOR_TEST");
1804 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1805 if (gl_info->supported[ARB_POINT_SPRITE])
1807 glDisable(GL_POINT_SPRITE_ARB);
1808 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1809 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1811 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1812 checkGLcall("glColorMask");
1813 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1814 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1815 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1816 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
1817 if (gl_info->supported[EXT_SECONDARY_COLOR])
1819 glDisable(GL_COLOR_SUM_EXT);
1820 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
1821 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1824 /* Setup transforms */
1825 glMatrixMode(GL_MODELVIEW);
1826 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1827 glLoadIdentity();
1828 checkGLcall("glLoadIdentity()");
1829 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
1831 context->last_was_rhw = TRUE;
1832 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
1834 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1835 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1836 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1837 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1838 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1839 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1840 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
1842 set_blit_dimension(width, height);
1843 device->frag_pipe->enable_extension(FALSE);
1845 LEAVE_GL();
1847 context->blit_w = width; context->blit_h = height;
1848 context_invalidate_state(context, STATE_VIEWPORT);
1849 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1852 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
1854 return rt_mask & (1 << 31);
1857 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
1859 return rt_mask & ~(1 << 31);
1862 /* Context activation and GL locking are done by the caller. */
1863 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
1865 if (!rt_mask)
1867 glDrawBuffer(GL_NONE);
1868 checkGLcall("glDrawBuffer()");
1870 else if (is_rt_mask_onscreen(rt_mask))
1872 glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
1873 checkGLcall("glDrawBuffer()");
1875 else
1877 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1879 const struct wined3d_gl_info *gl_info = context->gl_info;
1880 unsigned int i = 0;
1882 while (rt_mask)
1884 if (rt_mask & 1)
1885 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1886 else
1887 context->draw_buffers[i] = GL_NONE;
1889 rt_mask >>= 1;
1890 ++i;
1893 if (gl_info->supported[ARB_DRAW_BUFFERS])
1895 GL_EXTCALL(glDrawBuffersARB(i, context->draw_buffers));
1896 checkGLcall("glDrawBuffers()");
1898 else
1900 glDrawBuffer(context->draw_buffers[0]);
1901 checkGLcall("glDrawBuffer()");
1904 else
1906 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
1911 /* GL locking is done by the caller. */
1912 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
1914 glDrawBuffer(buffer);
1915 checkGLcall("glDrawBuffer()");
1916 if (context->current_fbo)
1917 context->current_fbo->rt_mask = context_generate_rt_mask(buffer);
1918 else
1919 context->draw_buffers_mask = context_generate_rt_mask(buffer);
1922 /* GL locking is done by the caller. */
1923 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
1925 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0 + unit));
1926 checkGLcall("glActiveTextureARB");
1927 context->active_texture = unit;
1930 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
1932 DWORD unit = context->active_texture;
1933 DWORD old_texture_type = context->texture_type[unit];
1935 if (name)
1937 glBindTexture(target, name);
1938 checkGLcall("glBindTexture");
1940 else
1942 target = GL_NONE;
1945 if (old_texture_type != target)
1947 const struct wined3d_device *device = context->swapchain->device;
1949 switch (old_texture_type)
1951 case GL_NONE:
1952 /* nothing to do */
1953 break;
1954 case GL_TEXTURE_2D:
1955 glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
1956 checkGLcall("glBindTexture");
1957 break;
1958 case GL_TEXTURE_RECTANGLE_ARB:
1959 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
1960 checkGLcall("glBindTexture");
1961 break;
1962 case GL_TEXTURE_CUBE_MAP:
1963 glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
1964 checkGLcall("glBindTexture");
1965 break;
1966 case GL_TEXTURE_3D:
1967 glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
1968 checkGLcall("glBindTexture");
1969 break;
1970 default:
1971 ERR("Unexpected texture target %#x\n", old_texture_type);
1974 context->texture_type[unit] = target;
1978 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
1980 if (context->render_offscreen == offscreen) return;
1982 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
1983 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1984 context_invalidate_state(context, STATE_VIEWPORT);
1985 context_invalidate_state(context, STATE_SCISSORRECT);
1986 context_invalidate_state(context, STATE_FRONTFACE);
1987 context->render_offscreen = offscreen;
1990 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
1991 const struct wined3d_format *required)
1993 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
1995 if (existing == required) return TRUE;
1996 if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
1998 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
1999 getDepthStencilBits(required, &required_depth, &required_stencil);
2001 if(existing_depth < required_depth) return FALSE;
2002 /* If stencil bits are used the exact amount is required - otherwise wrapping
2003 * won't work correctly */
2004 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2005 return TRUE;
2008 /* The caller provides a context */
2009 static void context_validate_onscreen_formats(struct wined3d_context *context,
2010 const struct wined3d_surface *depth_stencil)
2012 /* Onscreen surfaces are always in a swapchain */
2013 struct wined3d_swapchain *swapchain = context->current_rt->container.u.swapchain;
2015 if (context->render_offscreen || !depth_stencil) return;
2016 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2018 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2019 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2020 * format. */
2021 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2023 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2024 surface_load_location(context->current_rt, SFLAG_INTEXTURE, NULL);
2025 swapchain->render_to_fbo = TRUE;
2026 swapchain_update_draw_bindings(swapchain);
2027 context_set_render_offscreen(context, TRUE);
2030 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2032 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2033 return 0;
2034 else if (rt->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2035 return context_generate_rt_mask_from_surface(rt);
2036 else
2037 return context_generate_rt_mask(device->offscreenBuffer);
2040 /* Context activation is done by the caller. */
2041 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2043 struct wined3d_surface *rt = context->current_rt;
2044 DWORD rt_mask, old_mask;
2046 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2048 context_validate_onscreen_formats(context, NULL);
2050 if (context->render_offscreen)
2052 surface_internal_preload(rt, SRGB_RGB);
2054 ENTER_GL();
2055 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->draw_binding);
2056 LEAVE_GL();
2057 if (rt->resource.format->id != WINED3DFMT_NULL)
2058 rt_mask = 1;
2059 else
2060 rt_mask = 0;
2062 else
2064 ENTER_GL();
2065 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2066 LEAVE_GL();
2067 rt_mask = context_generate_rt_mask_from_surface(rt);
2070 else
2072 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2075 old_mask = context->current_fbo ? context->current_fbo->rt_mask : context->draw_buffers_mask;
2077 ENTER_GL();
2078 if (rt_mask != old_mask)
2080 context_apply_draw_buffers(context, rt_mask);
2081 context->draw_buffers_mask = rt_mask;
2084 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2086 context_check_fbo_status(context, GL_FRAMEBUFFER);
2088 LEAVE_GL();
2090 SetupForBlit(device, context);
2091 context_invalidate_state(context, STATE_FRAMEBUFFER);
2094 static BOOL context_validate_rt_config(UINT rt_count,
2095 struct wined3d_surface * const *rts, const struct wined3d_surface *ds)
2097 unsigned int i;
2099 if (ds) return TRUE;
2101 for (i = 0; i < rt_count; ++i)
2103 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2104 return TRUE;
2107 WARN("Invalid render target config, need at least one attachment.\n");
2108 return FALSE;
2111 /* Context activation is done by the caller. */
2112 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2113 UINT rt_count, const struct wined3d_fb_state *fb)
2115 DWORD rt_mask = 0, old_mask;
2116 UINT i;
2117 struct wined3d_surface **rts = fb->render_targets;
2119 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2120 || rt_count != context->gl_info->limits.buffers)
2122 if (!context_validate_rt_config(rt_count, rts, fb->depth_stencil))
2123 return FALSE;
2125 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2127 context_validate_onscreen_formats(context, fb->depth_stencil);
2129 ENTER_GL();
2131 if (!rt_count || surface_is_offscreen(rts[0]))
2133 for (i = 0; i < rt_count; ++i)
2135 context->blit_targets[i] = rts[i];
2136 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2137 rt_mask |= (1 << i);
2139 while (i < context->gl_info->limits.buffers)
2141 context->blit_targets[i] = NULL;
2142 ++i;
2144 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, fb->depth_stencil,
2145 rt_count ? rts[0]->draw_binding : SFLAG_INTEXTURE);
2146 glReadBuffer(GL_NONE);
2147 checkGLcall("glReadBuffer");
2149 else
2151 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2152 rt_mask = context_generate_rt_mask_from_surface(rts[0]);
2155 LEAVE_GL();
2157 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2158 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2159 * state management allows this */
2160 context_invalidate_state(context, STATE_FRAMEBUFFER);
2162 else
2164 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2167 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2168 && (!rt_count || surface_is_offscreen(rts[0])))
2170 for (i = 0; i < rt_count; ++i)
2172 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL) rt_mask |= (1 << i);
2175 else
2177 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2180 old_mask = context->current_fbo ? context->current_fbo->rt_mask : context->draw_buffers_mask;
2182 ENTER_GL();
2183 if (rt_mask != old_mask)
2185 context_apply_draw_buffers(context, rt_mask);
2186 context->draw_buffers_mask = rt_mask;
2187 context_invalidate_state(context, STATE_FRAMEBUFFER);
2190 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2192 context_check_fbo_status(context, GL_FRAMEBUFFER);
2195 if (context->last_was_blit)
2197 device->frag_pipe->enable_extension(TRUE);
2198 context->last_was_blit = FALSE;
2201 /* Blending and clearing should be orthogonal, but tests on the nvidia
2202 * driver show that disabling blending when clearing improves the clearing
2203 * performance incredibly. */
2204 glDisable(GL_BLEND);
2205 glEnable(GL_SCISSOR_TEST);
2206 checkGLcall("glEnable GL_SCISSOR_TEST");
2207 LEAVE_GL();
2209 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2210 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2211 context_invalidate_state(context, STATE_SCISSORRECT);
2213 return TRUE;
2216 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2218 const struct wined3d_state *state = &device->stateBlock->state;
2219 struct wined3d_surface **rts = state->fb->render_targets;
2220 struct wined3d_shader *ps = state->pixel_shader;
2221 DWORD rt_mask, rt_mask_bits;
2222 unsigned int i;
2224 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return context_generate_rt_mask_no_fbo(device, rts[0]);
2225 else if (!context->render_offscreen) return context_generate_rt_mask_from_surface(rts[0]);
2227 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2228 rt_mask &= device->valid_rt_mask;
2229 rt_mask_bits = rt_mask;
2230 i = 0;
2231 while (rt_mask_bits)
2233 rt_mask_bits &= ~(1 << i);
2234 if (!rts[i] || rts[i]->resource.format->id == WINED3DFMT_NULL)
2235 rt_mask &= ~(1 << i);
2237 i++;
2240 return rt_mask;
2243 /* GL locking and context activation are done by the caller */
2244 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2246 const struct wined3d_device *device = context->swapchain->device;
2247 const struct wined3d_fb_state *fb = state->fb;
2248 DWORD rt_mask = find_draw_buffers_mask(context, device);
2249 DWORD old_mask;
2251 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2253 if (!context->render_offscreen)
2255 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, SFLAG_INDRAWABLE);
2257 else
2259 context_apply_fbo_state(context, GL_FRAMEBUFFER, fb->render_targets, fb->depth_stencil,
2260 fb->render_targets[0]->draw_binding);
2261 glReadBuffer(GL_NONE);
2262 checkGLcall("glReadBuffer");
2266 old_mask = context->current_fbo ? context->current_fbo->rt_mask : context->draw_buffers_mask;
2267 if (rt_mask != old_mask)
2269 context_apply_draw_buffers(context, rt_mask);
2270 context->draw_buffers_mask = rt_mask;
2274 /* GL locking and context activation are done by the caller */
2275 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2277 const struct wined3d_device *device = context->swapchain->device;
2278 DWORD rt_mask, old_mask;
2280 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2282 old_mask = context->current_fbo ? context->current_fbo->rt_mask : context->draw_buffers_mask;
2283 rt_mask = find_draw_buffers_mask(context, device);
2284 if (rt_mask != old_mask)
2286 context_apply_draw_buffers(context, rt_mask);
2287 context->draw_buffers_mask = rt_mask;
2291 /* Context activation is done by the caller. */
2292 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
2294 const struct wined3d_state *state = &device->stateBlock->state;
2295 const struct StateEntry *state_table = context->state_table;
2296 const struct wined3d_fb_state *fb = state->fb;
2297 unsigned int i;
2299 if (!context_validate_rt_config(context->gl_info->limits.buffers,
2300 fb->render_targets, fb->depth_stencil))
2301 return FALSE;
2303 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
2305 context_validate_onscreen_formats(context, fb->depth_stencil);
2308 /* Preload resources before FBO setup. Texture preload in particular may
2309 * result in changes to the current FBO, due to using e.g. FBO blits for
2310 * updating a resource location. */
2311 device_update_tex_unit_map(device);
2312 device_preload_textures(device);
2313 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC))
2314 device_update_stream_info(device, context->gl_info);
2316 ENTER_GL();
2317 if (context->last_was_blit)
2319 device->frag_pipe->enable_extension(TRUE);
2322 for (i = 0; i < context->numDirtyEntries; ++i)
2324 DWORD rep = context->dirtyArray[i];
2325 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2326 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2327 context->isStateDirty[idx] &= ~(1 << shift);
2328 state_table[rep].apply(context, state, rep);
2331 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2333 context_check_fbo_status(context, GL_FRAMEBUFFER);
2336 LEAVE_GL();
2337 context->numDirtyEntries = 0; /* This makes the whole list clean */
2338 context->last_was_blit = FALSE;
2340 return TRUE;
2343 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
2345 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2347 render_offscreen = surface_is_offscreen(target);
2348 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2350 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2351 * the alpha blend state changes with different render target formats. */
2352 if (!context->current_rt)
2354 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2356 else
2358 const struct wined3d_format *old = context->current_rt->resource.format;
2359 const struct wined3d_format *new = target->resource.format;
2361 if (old->id != new->id)
2363 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2364 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2365 || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2366 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2368 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2369 if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2370 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2373 /* When switching away from an offscreen render target, and we're not
2374 * using FBOs, we have to read the drawable into the texture. This is
2375 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2376 * are some things that need care though. PreLoad needs a GL context,
2377 * and FindContext is called before the context is activated. It also
2378 * has to be called with the old rendertarget active, otherwise a
2379 * wrong drawable is read. */
2380 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2381 && old_render_offscreen && context->current_rt != target)
2383 /* Read the back buffer of the old drawable into the destination texture. */
2384 if (context->current_rt->texture_name_srgb)
2385 surface_internal_preload(context->current_rt, SRGB_SRGB);
2386 surface_internal_preload(context->current_rt, SRGB_RGB);
2387 surface_modify_location(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2391 context->current_rt = target;
2392 context_set_render_offscreen(context, render_offscreen);
2395 /* Do not call while under the GL lock. */
2396 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
2398 struct wined3d_context *current_context = context_get_current();
2399 struct wined3d_context *context;
2401 TRACE("device %p, target %p.\n", device, target);
2403 if (current_context && current_context->destroyed)
2404 current_context = NULL;
2406 if (!target)
2408 if (current_context
2409 && current_context->current_rt
2410 && current_context->swapchain->device == device)
2412 target = current_context->current_rt;
2414 else
2416 struct wined3d_swapchain *swapchain = device->swapchains[0];
2417 if (swapchain->back_buffers)
2418 target = swapchain->back_buffers[0];
2419 else
2420 target = swapchain->front_buffer;
2424 if (current_context && current_context->current_rt == target)
2426 context = current_context;
2428 else if (target->container.type == WINED3D_CONTAINER_SWAPCHAIN)
2430 TRACE("Rendering onscreen.\n");
2432 context = swapchain_get_context(target->container.u.swapchain);
2434 else
2436 TRACE("Rendering offscreen.\n");
2438 /* Stay with the current context if possible. Otherwise use the
2439 * context for the primary swapchain. */
2440 if (current_context && current_context->swapchain->device == device)
2441 context = current_context;
2442 else
2443 context = swapchain_get_context(device->swapchains[0]);
2446 context_update_window(context);
2447 context_setup_target(context, target);
2448 context_enter(context);
2449 if (!context->valid) return context;
2451 if (context != current_context)
2453 if (!context_set_current(context))
2455 ERR("Failed to activate the new context.\n");
2457 else
2459 ENTER_GL();
2460 device->frag_pipe->enable_extension(!context->last_was_blit);
2461 LEAVE_GL();
2464 else if (context->restore_ctx)
2466 context_set_gl_context(context);
2469 return context;