wined3d: Don't call GetPixelFormat() to set a flag that's already set.
[wine/multimedia.git] / dlls / wined3d / context.c
blob3341ae2595a5c7d62b12a603355894c33da859b7
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2011, 2013 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 "wine/port.h"
25 #include <stdio.h>
26 #ifdef HAVE_FLOAT_H
27 # include <float.h>
28 #endif
30 #include "wined3d_private.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
33 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
36 #define WINED3D_MAX_FBO_ENTRIES 64
38 static DWORD wined3d_context_tls_idx;
40 /* FBO helper functions */
42 /* Context activation is done by the caller. */
43 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
45 const struct wined3d_gl_info *gl_info = context->gl_info;
47 switch (target)
49 case GL_READ_FRAMEBUFFER:
50 if (context->fbo_read_binding == fbo) return;
51 context->fbo_read_binding = fbo;
52 break;
54 case GL_DRAW_FRAMEBUFFER:
55 if (context->fbo_draw_binding == fbo) return;
56 context->fbo_draw_binding = fbo;
57 break;
59 case GL_FRAMEBUFFER:
60 if (context->fbo_read_binding == fbo
61 && context->fbo_draw_binding == fbo) return;
62 context->fbo_read_binding = fbo;
63 context->fbo_draw_binding = fbo;
64 break;
66 default:
67 FIXME("Unhandled target %#x.\n", target);
68 break;
71 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
72 checkGLcall("glBindFramebuffer()");
75 /* Context activation is done by the caller. */
76 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
78 unsigned int i;
80 for (i = 0; i < gl_info->limits.buffers; ++i)
82 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
83 checkGLcall("glFramebufferTexture2D()");
85 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
86 checkGLcall("glFramebufferTexture2D()");
88 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
89 checkGLcall("glFramebufferTexture2D()");
92 /* Context activation is done by the caller. */
93 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
95 const struct wined3d_gl_info *gl_info = context->gl_info;
97 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
98 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
99 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
101 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
102 checkGLcall("glDeleteFramebuffers()");
105 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
106 GLenum fbo_target, DWORD format_flags, GLuint rb)
108 if (format_flags & WINED3DFMT_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (format_flags & WINED3DFMT_FLAG_STENCIL)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
121 /* Context activation is done by the caller. */
122 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
123 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
125 const struct wined3d_gl_info *gl_info = context->gl_info;
127 TRACE("Attach depth stencil %p\n", depth_stencil);
129 if (depth_stencil)
131 DWORD format_flags = depth_stencil->resource.format->flags;
133 if (depth_stencil->current_renderbuffer)
135 context_attach_depth_stencil_rb(gl_info, fbo_target,
136 format_flags, depth_stencil->current_renderbuffer->id);
138 else
140 switch (location)
142 case WINED3D_LOCATION_TEXTURE_RGB:
143 case WINED3D_LOCATION_TEXTURE_SRGB:
144 surface_prepare_texture(depth_stencil, context, FALSE);
146 if (format_flags & WINED3DFMT_FLAG_DEPTH)
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
149 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
150 depth_stencil->texture_level);
151 checkGLcall("glFramebufferTexture2D()");
154 if (format_flags & WINED3DFMT_FLAG_STENCIL)
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
157 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
158 depth_stencil->texture_level);
159 checkGLcall("glFramebufferTexture2D()");
161 break;
163 case WINED3D_LOCATION_RB_MULTISAMPLE:
164 surface_prepare_rb(depth_stencil, gl_info, TRUE);
165 context_attach_depth_stencil_rb(gl_info, fbo_target,
166 format_flags, depth_stencil->rb_multisample);
167 break;
169 case WINED3D_LOCATION_RB_RESOLVED:
170 surface_prepare_rb(depth_stencil, gl_info, FALSE);
171 context_attach_depth_stencil_rb(gl_info, fbo_target,
172 format_flags, depth_stencil->rb_resolved);
173 break;
175 default:
176 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
177 break;
181 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
183 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
184 checkGLcall("glFramebufferTexture2D()");
187 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
189 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
190 checkGLcall("glFramebufferTexture2D()");
193 else
195 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
196 checkGLcall("glFramebufferTexture2D()");
198 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
199 checkGLcall("glFramebufferTexture2D()");
203 /* Context activation is done by the caller. */
204 static void context_attach_surface_fbo(struct wined3d_context *context,
205 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
207 const struct wined3d_gl_info *gl_info = context->gl_info;
209 TRACE("Attach surface %p to %u\n", surface, idx);
211 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
213 BOOL srgb;
215 switch (location)
217 case WINED3D_LOCATION_TEXTURE_RGB:
218 case WINED3D_LOCATION_TEXTURE_SRGB:
219 srgb = location == WINED3D_LOCATION_TEXTURE_SRGB;
220 surface_prepare_texture(surface, context, srgb);
221 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
222 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
223 surface->texture_level);
224 checkGLcall("glFramebufferTexture2D()");
225 break;
227 case WINED3D_LOCATION_RB_MULTISAMPLE:
228 surface_prepare_rb(surface, gl_info, TRUE);
229 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
230 GL_RENDERBUFFER, surface->rb_multisample);
231 checkGLcall("glFramebufferRenderbuffer()");
232 break;
234 case WINED3D_LOCATION_RB_RESOLVED:
235 surface_prepare_rb(surface, gl_info, FALSE);
236 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
237 GL_RENDERBUFFER, surface->rb_resolved);
238 checkGLcall("glFramebufferRenderbuffer()");
239 break;
241 default:
242 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
243 break;
246 else
248 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
249 checkGLcall("glFramebufferTexture2D()");
253 /* Context activation is done by the caller. */
254 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
256 const struct wined3d_gl_info *gl_info = context->gl_info;
257 GLenum status;
259 if (!FIXME_ON(d3d)) return;
261 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
262 if (status == GL_FRAMEBUFFER_COMPLETE)
264 TRACE("FBO complete\n");
266 else
268 const struct wined3d_surface *attachment;
269 unsigned int i;
271 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
273 if (!context->current_fbo)
275 ERR("FBO 0 is incomplete, driver bug?\n");
276 return;
279 FIXME("\tLocation %s (%#x).\n", wined3d_debug_location(context->current_fbo->location),
280 context->current_fbo->location);
282 /* Dump the FBO attachments */
283 for (i = 0; i < gl_info->limits.buffers; ++i)
285 attachment = context->current_fbo->render_targets[i];
286 if (attachment)
288 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
289 i, attachment, debug_d3dformat(attachment->resource.format->id),
290 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
293 attachment = context->current_fbo->depth_stencil;
294 if (attachment)
296 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
297 attachment, debug_d3dformat(attachment->resource.format->id),
298 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
303 static inline DWORD context_generate_rt_mask(GLenum buffer)
305 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
306 return buffer ? (1 << 31) | buffer : 0;
309 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
311 return (1 << 31) | surface_get_gl_buffer(target);
314 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
315 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
317 const struct wined3d_gl_info *gl_info = context->gl_info;
318 struct fbo_entry *entry;
320 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
321 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
322 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
323 entry->depth_stencil = depth_stencil;
324 entry->location = location;
325 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
326 entry->attached = FALSE;
327 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
328 checkGLcall("glGenFramebuffers()");
329 TRACE("Created FBO %u.\n", entry->id);
331 return entry;
334 /* Context activation is done by the caller. */
335 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
336 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
337 DWORD location, struct fbo_entry *entry)
339 const struct wined3d_gl_info *gl_info = context->gl_info;
341 context_bind_fbo(context, target, entry->id);
342 context_clean_fbo_attachments(gl_info, target);
344 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
345 entry->depth_stencil = depth_stencil;
346 entry->location = location;
347 entry->attached = FALSE;
350 /* Context activation is done by the caller. */
351 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
353 if (entry->id)
355 TRACE("Destroy FBO %u.\n", entry->id);
356 context_destroy_fbo(context, entry->id);
358 --context->fbo_entry_count;
359 list_remove(&entry->entry);
360 HeapFree(GetProcessHeap(), 0, entry->render_targets);
361 HeapFree(GetProcessHeap(), 0, entry);
364 /* Context activation is done by the caller. */
365 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
366 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
368 const struct wined3d_gl_info *gl_info = context->gl_info;
369 struct fbo_entry *entry;
371 if (depth_stencil && render_targets && render_targets[0])
373 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
374 depth_stencil->resource.height < render_targets[0]->resource.height)
376 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
377 depth_stencil = NULL;
381 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
383 if (!memcmp(entry->render_targets,
384 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
385 && entry->depth_stencil == depth_stencil && entry->location == location)
387 list_remove(&entry->entry);
388 list_add_head(&context->fbo_list, &entry->entry);
389 return entry;
393 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
395 entry = context_create_fbo_entry(context, render_targets, depth_stencil, location);
396 list_add_head(&context->fbo_list, &entry->entry);
397 ++context->fbo_entry_count;
399 else
401 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
402 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, location, entry);
403 list_remove(&entry->entry);
404 list_add_head(&context->fbo_list, &entry->entry);
407 return entry;
410 /* Context activation is done by the caller. */
411 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
413 const struct wined3d_gl_info *gl_info = context->gl_info;
414 unsigned int i;
415 GLuint read_binding, draw_binding;
417 if (entry->attached)
419 context_bind_fbo(context, target, entry->id);
420 return;
423 read_binding = context->fbo_read_binding;
424 draw_binding = context->fbo_draw_binding;
425 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
427 /* Apply render targets */
428 for (i = 0; i < gl_info->limits.buffers; ++i)
430 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->location);
433 /* Apply depth targets */
434 if (entry->depth_stencil)
435 surface_set_compatible_renderbuffer(entry->depth_stencil, entry->render_targets[0]);
436 context_attach_depth_stencil_fbo(context, target, entry->depth_stencil, entry->location);
438 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
439 * GL contexts requirements. */
440 glReadBuffer(GL_NONE);
441 context_set_draw_buffer(context, GL_NONE);
442 if (target != GL_FRAMEBUFFER)
444 if (target == GL_READ_FRAMEBUFFER)
445 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
446 else
447 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
450 entry->attached = TRUE;
453 /* Context activation is done by the caller. */
454 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
455 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil, DWORD location)
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, 0);
467 context->rebind_fbo = FALSE;
470 if (location == WINED3D_LOCATION_DRAWABLE)
472 context->current_fbo = NULL;
473 context_bind_fbo(context, target, 0);
475 else
477 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil, location);
478 context_apply_fbo_entry(context, target, context->current_fbo);
482 /* Context activation is done by the caller. */
483 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
484 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
486 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
488 context->blit_targets[0] = render_target;
489 if (clear_size)
490 memset(&context->blit_targets[1], 0, clear_size);
491 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location);
494 /* Context activation is done by the caller. */
495 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
497 const struct wined3d_gl_info *gl_info = context->gl_info;
499 if (context->free_occlusion_query_count)
501 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
503 else
505 if (gl_info->supported[ARB_OCCLUSION_QUERY])
507 GL_EXTCALL(glGenQueriesARB(1, &query->id));
508 checkGLcall("glGenQueriesARB");
510 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
512 else
514 WARN("Occlusion queries not supported, not allocating query id.\n");
515 query->id = 0;
519 query->context = context;
520 list_add_head(&context->occlusion_queries, &query->entry);
523 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
525 struct wined3d_context *context = query->context;
527 list_remove(&query->entry);
528 query->context = NULL;
530 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
532 UINT new_size = context->free_occlusion_query_size << 1;
533 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
534 new_size * sizeof(*context->free_occlusion_queries));
536 if (!new_data)
538 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
539 return;
542 context->free_occlusion_query_size = new_size;
543 context->free_occlusion_queries = new_data;
546 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
549 /* Context activation is done by the caller. */
550 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
552 const struct wined3d_gl_info *gl_info = context->gl_info;
554 if (context->free_event_query_count)
556 query->object = context->free_event_queries[--context->free_event_query_count];
558 else
560 if (gl_info->supported[ARB_SYNC])
562 /* Using ARB_sync, not much to do here. */
563 query->object.sync = NULL;
564 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
566 else if (gl_info->supported[APPLE_FENCE])
568 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
569 checkGLcall("glGenFencesAPPLE");
571 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
573 else if(gl_info->supported[NV_FENCE])
575 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
576 checkGLcall("glGenFencesNV");
578 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
580 else
582 WARN("Event queries not supported, not allocating query id.\n");
583 query->object.id = 0;
587 query->context = context;
588 list_add_head(&context->event_queries, &query->entry);
591 void context_free_event_query(struct wined3d_event_query *query)
593 struct wined3d_context *context = query->context;
595 list_remove(&query->entry);
596 query->context = NULL;
598 if (context->free_event_query_count >= context->free_event_query_size - 1)
600 UINT new_size = context->free_event_query_size << 1;
601 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
602 new_size * sizeof(*context->free_event_queries));
604 if (!new_data)
606 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
607 return;
610 context->free_event_query_size = new_size;
611 context->free_event_queries = new_data;
614 context->free_event_queries[context->free_event_query_count++] = query->object;
617 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
619 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
620 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
622 UINT i;
624 for (i = 0; i < device->context_count; ++i)
626 struct wined3d_context *context = device->contexts[i];
627 const struct wined3d_gl_info *gl_info = context->gl_info;
628 struct fbo_entry *entry, *entry2;
630 if (context->current_rt == surface) context->current_rt = NULL;
632 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
634 UINT j;
636 if (entry->depth_stencil == surface)
638 callback(context, entry);
639 continue;
642 for (j = 0; j < gl_info->limits.buffers; ++j)
644 if (entry->render_targets[j] == surface)
646 callback(context, entry);
647 break;
654 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
656 list_remove(&entry->entry);
657 list_add_head(&context->fbo_destroy_list, &entry->entry);
660 void context_resource_released(const struct wined3d_device *device,
661 struct wined3d_resource *resource, enum wined3d_resource_type type)
663 if (!device->d3d_initialized) return;
665 switch (type)
667 case WINED3D_RTYPE_SURFACE:
668 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
669 context_queue_fbo_entry_destruction);
670 break;
672 default:
673 break;
677 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
679 entry->attached = FALSE;
682 void context_resource_unloaded(const struct wined3d_device *device,
683 struct wined3d_resource *resource, enum wined3d_resource_type type)
685 switch (type)
687 case WINED3D_RTYPE_SURFACE:
688 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
689 context_detach_fbo_entry);
690 break;
692 default:
693 break;
697 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
699 const struct wined3d_gl_info *gl_info = context->gl_info;
700 struct fbo_entry *entry = context->current_fbo;
701 unsigned int i;
703 if (!entry || context->rebind_fbo) return;
705 for (i = 0; i < gl_info->limits.buffers; ++i)
707 if (surface == entry->render_targets[i])
709 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
710 context->rebind_fbo = TRUE;
711 return;
715 if (surface == entry->depth_stencil)
717 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
718 context->rebind_fbo = TRUE;
722 static void context_restore_pixel_format(struct wined3d_context *ctx)
724 const struct wined3d_gl_info *gl_info = ctx->gl_info;
726 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
728 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
730 HDC dc = GetDC(ctx->restore_pf_win);
731 if (dc)
733 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf)))
735 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
736 ctx->restore_pf, ctx->restore_pf_win);
738 ReleaseDC(ctx->restore_pf_win, dc);
741 else
743 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
747 ctx->restore_pf = 0;
748 ctx->restore_pf_win = NULL;
751 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, int format)
753 const struct wined3d_gl_info *gl_info = context->gl_info;
754 int current = GetPixelFormat(dc);
756 if (current == format) return TRUE;
758 if (!current)
760 if (!SetPixelFormat(dc, format, NULL))
762 /* This may also happen if the dc belongs to a destroyed window. */
763 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
764 format, dc, GetLastError());
765 return FALSE;
768 context->restore_pf = 0;
769 context->restore_pf_win = WindowFromDC(dc);
770 return TRUE;
773 /* By default WGL doesn't allow pixel format adjustments but we need it
774 * here. For this reason there's a Wine specific wglSetPixelFormat()
775 * which allows us to set the pixel format multiple times. Only use it
776 * when really needed. */
777 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
779 HWND win;
781 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
783 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
784 format, dc);
785 return FALSE;
788 win = WindowFromDC(dc);
789 if (win != context->restore_pf_win)
791 context_restore_pixel_format(context);
793 context->restore_pf = current;
794 context->restore_pf_win = win;
797 return TRUE;
800 /* OpenGL doesn't allow pixel format adjustments. Print an error and
801 * continue using the old format. There's a big chance that the old
802 * format works although with a performance hit and perhaps rendering
803 * errors. */
804 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
805 format, dc, current);
806 return TRUE;
809 static BOOL context_set_gl_context(struct wined3d_context *ctx)
811 struct wined3d_swapchain *swapchain = ctx->swapchain;
812 BOOL backup = FALSE;
814 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->pixel_format))
816 WARN("Failed to set pixel format %d on device context %p.\n",
817 ctx->pixel_format, ctx->hdc);
818 backup = TRUE;
821 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
823 HDC dc;
825 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
826 ctx->glCtx, ctx->hdc, GetLastError());
827 ctx->valid = 0;
828 WARN("Trying fallback to the backup window.\n");
830 /* FIXME: If the context is destroyed it's no longer associated with
831 * a swapchain, so we can't use the swapchain to get a backup dc. To
832 * make this work windowless contexts would need to be handled by the
833 * device. */
834 if (ctx->destroyed)
836 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
837 context_set_current(NULL);
838 return FALSE;
841 if (!(dc = swapchain_get_backup_dc(swapchain)))
843 context_set_current(NULL);
844 return FALSE;
847 if (!context_set_pixel_format(ctx, dc, ctx->pixel_format))
849 ERR("Failed to set pixel format %d on device context %p.\n",
850 ctx->pixel_format, dc);
851 context_set_current(NULL);
852 return FALSE;
855 if (!wglMakeCurrent(dc, ctx->glCtx))
857 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
858 dc, GetLastError());
859 context_set_current(NULL);
860 return FALSE;
863 ctx->valid = 1;
865 ctx->needs_set = 0;
866 return TRUE;
869 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
871 if (!wglMakeCurrent(dc, gl_ctx))
873 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
874 gl_ctx, dc, GetLastError());
875 context_set_current(NULL);
879 static void context_update_window(struct wined3d_context *context)
881 if (context->win_handle == context->swapchain->win_handle)
882 return;
884 TRACE("Updating context %p window from %p to %p.\n",
885 context, context->win_handle, context->swapchain->win_handle);
887 if (context->hdc)
888 wined3d_release_dc(context->win_handle, context->hdc);
890 context->win_handle = context->swapchain->win_handle;
891 context->needs_set = 1;
892 context->valid = 1;
894 if (!(context->hdc = GetDC(context->win_handle)))
896 ERR("Failed to get a device context for window %p.\n", context->win_handle);
897 context->valid = 0;
901 static void context_destroy_gl_resources(struct wined3d_context *context)
903 const struct wined3d_gl_info *gl_info = context->gl_info;
904 struct wined3d_occlusion_query *occlusion_query;
905 struct wined3d_event_query *event_query;
906 struct fbo_entry *entry, *entry2;
907 HGLRC restore_ctx;
908 HDC restore_dc;
909 unsigned int i;
911 restore_ctx = wglGetCurrentContext();
912 restore_dc = wglGetCurrentDC();
914 if (restore_ctx == context->glCtx)
915 restore_ctx = NULL;
916 else if (context->valid)
917 context_set_gl_context(context);
919 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
921 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
922 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
923 occlusion_query->context = NULL;
926 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
928 if (context->valid)
930 if (gl_info->supported[ARB_SYNC])
932 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
934 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
935 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
937 event_query->context = NULL;
940 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
942 if (!context->valid) entry->id = 0;
943 context_destroy_fbo_entry(context, entry);
946 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
948 if (!context->valid) entry->id = 0;
949 context_destroy_fbo_entry(context, entry);
952 if (context->valid)
954 if (context->dummy_arbfp_prog)
956 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
959 if (gl_info->supported[ARB_OCCLUSION_QUERY])
960 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
962 if (gl_info->supported[ARB_SYNC])
964 for (i = 0; i < context->free_event_query_count; ++i)
966 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
969 else if (gl_info->supported[APPLE_FENCE])
971 for (i = 0; i < context->free_event_query_count; ++i)
973 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
976 else if (gl_info->supported[NV_FENCE])
978 for (i = 0; i < context->free_event_query_count; ++i)
980 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
984 checkGLcall("context cleanup");
987 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
988 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
990 context_restore_pixel_format(context);
991 if (restore_ctx)
993 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
995 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
997 ERR("Failed to disable GL context.\n");
1000 wined3d_release_dc(context->win_handle, context->hdc);
1002 if (!wglDeleteContext(context->glCtx))
1004 DWORD err = GetLastError();
1005 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1009 DWORD context_get_tls_idx(void)
1011 return wined3d_context_tls_idx;
1014 void context_set_tls_idx(DWORD idx)
1016 wined3d_context_tls_idx = idx;
1019 struct wined3d_context *context_get_current(void)
1021 return TlsGetValue(wined3d_context_tls_idx);
1024 BOOL context_set_current(struct wined3d_context *ctx)
1026 struct wined3d_context *old = context_get_current();
1028 if (old == ctx)
1030 TRACE("Already using D3D context %p.\n", ctx);
1031 return TRUE;
1034 if (old)
1036 if (old->destroyed)
1038 TRACE("Switching away from destroyed context %p.\n", old);
1039 context_destroy_gl_resources(old);
1040 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1041 HeapFree(GetProcessHeap(), 0, old);
1043 else
1045 old->current = 0;
1049 if (ctx)
1051 if (!ctx->valid)
1053 ERR("Trying to make invalid context %p current\n", ctx);
1054 return FALSE;
1057 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1058 if (!context_set_gl_context(ctx))
1059 return FALSE;
1060 ctx->current = 1;
1062 else if(wglGetCurrentContext())
1064 TRACE("Clearing current D3D context.\n");
1065 if (!wglMakeCurrent(NULL, NULL))
1067 DWORD err = GetLastError();
1068 ERR("Failed to clear current GL context, last error %#x.\n", err);
1069 TlsSetValue(wined3d_context_tls_idx, NULL);
1070 return FALSE;
1074 return TlsSetValue(wined3d_context_tls_idx, ctx);
1077 void context_release(struct wined3d_context *context)
1079 TRACE("Releasing context %p, level %u.\n", context, context->level);
1081 if (WARN_ON(d3d))
1083 if (!context->level)
1084 WARN("Context %p is not active.\n", context);
1085 else if (context != context_get_current())
1086 WARN("Context %p is not the current context.\n", context);
1089 if (!--context->level)
1091 context_restore_pixel_format(context);
1092 if (context->restore_ctx)
1094 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1095 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1096 context->restore_ctx = NULL;
1097 context->restore_dc = NULL;
1102 static void context_enter(struct wined3d_context *context)
1104 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1106 if (!context->level++)
1108 const struct wined3d_context *current_context = context_get_current();
1109 HGLRC current_gl = wglGetCurrentContext();
1111 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1113 TRACE("Another GL context (%p on device context %p) is already current.\n",
1114 current_gl, wglGetCurrentDC());
1115 context->restore_ctx = current_gl;
1116 context->restore_dc = wglGetCurrentDC();
1117 context->needs_set = 1;
1119 else if (!context->needs_set && context->pixel_format != GetPixelFormat(context->hdc))
1120 context->needs_set = 1;
1124 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1126 DWORD rep = context->state_table[state].representative;
1127 DWORD idx;
1128 BYTE shift;
1130 if (isStateDirty(context, rep)) return;
1132 context->dirtyArray[context->numDirtyEntries++] = rep;
1133 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1134 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1135 context->isStateDirty[idx] |= (1 << shift);
1138 /* This function takes care of wined3d pixel format selection. */
1139 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1140 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1141 BOOL auxBuffers, BOOL findCompatible)
1143 int iPixelFormat=0;
1144 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1145 BYTE depthBits=0, stencilBits=0;
1146 unsigned int current_value;
1147 unsigned int cfg_count = device->adapter->cfg_count;
1148 unsigned int i;
1150 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1151 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1152 auxBuffers, findCompatible);
1154 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1156 ERR("Unable to get color bits for format %s (%#x)!\n",
1157 debug_d3dformat(color_format->id), color_format->id);
1158 return 0;
1161 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1163 current_value = 0;
1164 for (i = 0; i < cfg_count; ++i)
1166 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1167 unsigned int value;
1169 /* For now only accept RGBA formats. Perhaps some day we will
1170 * allow floating point formats for pbuffers. */
1171 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1172 continue;
1173 /* In window mode we need a window drawable format and double buffering. */
1174 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1175 continue;
1176 if (cfg->redSize < redBits)
1177 continue;
1178 if (cfg->greenSize < greenBits)
1179 continue;
1180 if (cfg->blueSize < blueBits)
1181 continue;
1182 if (cfg->alphaSize < alphaBits)
1183 continue;
1184 if (cfg->depthSize < depthBits)
1185 continue;
1186 if (stencilBits && cfg->stencilSize != stencilBits)
1187 continue;
1188 /* Check multisampling support. */
1189 if (cfg->numSamples)
1190 continue;
1192 value = 1;
1193 /* We try to locate a format which matches our requirements exactly. In case of
1194 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1195 if (cfg->depthSize == depthBits)
1196 value += 1;
1197 if (cfg->stencilSize == stencilBits)
1198 value += 2;
1199 if (cfg->alphaSize == alphaBits)
1200 value += 4;
1201 /* We like to have aux buffers in backbuffer mode */
1202 if (auxBuffers && cfg->auxBuffers)
1203 value += 8;
1204 if (cfg->redSize == redBits
1205 && cfg->greenSize == greenBits
1206 && cfg->blueSize == blueBits)
1207 value += 16;
1209 if (value > current_value)
1211 iPixelFormat = cfg->iPixelFormat;
1212 current_value = value;
1216 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1217 if(!iPixelFormat && !findCompatible) {
1218 ERR("Can't find a suitable iPixelFormat\n");
1219 return FALSE;
1220 } else if(!iPixelFormat) {
1221 PIXELFORMATDESCRIPTOR pfd;
1223 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1224 /* PixelFormat selection */
1225 ZeroMemory(&pfd, sizeof(pfd));
1226 pfd.nSize = sizeof(pfd);
1227 pfd.nVersion = 1;
1228 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1229 pfd.iPixelType = PFD_TYPE_RGBA;
1230 pfd.cAlphaBits = alphaBits;
1231 pfd.cColorBits = colorBits;
1232 pfd.cDepthBits = depthBits;
1233 pfd.cStencilBits = stencilBits;
1234 pfd.iLayerType = PFD_MAIN_PLANE;
1236 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1237 if(!iPixelFormat) {
1238 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1239 ERR("Can't find a suitable iPixelFormat\n");
1240 return FALSE;
1244 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1245 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1246 return iPixelFormat;
1249 /* Context activation is done by the caller. */
1250 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1252 const struct wined3d_gl_info *gl_info = context->gl_info;
1253 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1255 for (i = 0; i < count; ++i)
1257 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1258 checkGLcall("glActiveTextureARB");
1260 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1261 checkGLcall("glBindTexture");
1263 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1265 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1266 checkGLcall("glBindTexture");
1269 if (gl_info->supported[EXT_TEXTURE3D])
1271 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1272 checkGLcall("glBindTexture");
1275 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1277 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1278 checkGLcall("glBindTexture");
1283 BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1285 return gl_info->supported[ARB_DEBUG_OUTPUT]
1286 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1289 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1290 GLenum severity, GLsizei length, const char *message, void *ctx)
1292 switch (type)
1294 case GL_DEBUG_TYPE_ERROR_ARB:
1295 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1296 break;
1298 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1299 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1300 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1301 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1302 break;
1304 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1305 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1306 break;
1308 default:
1309 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1310 break;
1314 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1315 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1317 struct wined3d_device *device = swapchain->device;
1318 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1319 const struct wined3d_format *color_format;
1320 struct wined3d_context *ret;
1321 BOOL auxBuffers = FALSE;
1322 HGLRC ctx, share_ctx;
1323 int pixel_format;
1324 unsigned int s;
1325 int swap_interval;
1326 DWORD state;
1327 HDC hdc;
1329 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1331 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1332 if (!ret)
1333 return NULL;
1335 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1336 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1337 if (!ret->blit_targets)
1338 goto out;
1340 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1341 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1342 if (!ret->draw_buffers)
1343 goto out;
1345 ret->free_occlusion_query_size = 4;
1346 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1347 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1348 if (!ret->free_occlusion_queries)
1349 goto out;
1351 list_init(&ret->occlusion_queries);
1353 ret->free_event_query_size = 4;
1354 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1355 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1356 if (!ret->free_event_queries)
1357 goto out;
1359 list_init(&ret->event_queries);
1360 list_init(&ret->fbo_list);
1361 list_init(&ret->fbo_destroy_list);
1363 if (!device->shader_backend->shader_allocate_context_data(ret))
1365 ERR("Failed to allocate shader backend context data.\n");
1366 goto out;
1369 /* Initialize the texture unit mapping to a 1:1 mapping */
1370 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1372 if (s < gl_info->limits.fragment_samplers)
1374 ret->tex_unit_map[s] = s;
1375 ret->rev_tex_unit_map[s] = s;
1377 else
1379 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1380 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1384 if (!(hdc = GetDC(swapchain->win_handle)))
1386 WARN("Failed to retireve device context, trying swapchain backup.\n");
1388 if (!(hdc = swapchain_get_backup_dc(swapchain)))
1390 ERR("Failed to retrieve a device context.\n");
1391 goto out;
1395 color_format = target->resource.format;
1397 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1398 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1399 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1401 auxBuffers = TRUE;
1403 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1404 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1405 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1406 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1409 /* DirectDraw supports 8bit paletted render targets and these are used by
1410 * old games like StarCraft and C&C. Most modern hardware doesn't support
1411 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1412 * conversion (ab)uses the alpha component for storing the palette index.
1413 * For this reason we require a format with 8bit alpha, so request
1414 * A8R8G8B8. */
1415 if (color_format->id == WINED3DFMT_P8_UINT)
1416 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1418 /* Try to find a pixel format which matches our requirements. */
1419 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1421 /* Try to locate a compatible format if we weren't able to find anything. */
1422 if (!pixel_format)
1424 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1425 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1428 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1429 if (!pixel_format)
1431 ERR("Can't find a suitable pixel format.\n");
1432 goto out;
1435 context_enter(ret);
1437 ret->gl_info = gl_info;
1439 if (!context_set_pixel_format(ret, hdc, pixel_format))
1441 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1442 context_release(ret);
1443 goto out;
1446 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1447 if (gl_info->p_wglCreateContextAttribsARB)
1449 unsigned int ctx_attrib_idx = 0;
1450 GLint ctx_attribs[3];
1452 if (context_debug_output_enabled(gl_info))
1454 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1455 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_DEBUG_BIT_ARB;
1457 ctx_attribs[ctx_attrib_idx] = 0;
1459 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1461 ERR("Failed to create a WGL context.\n");
1462 context_release(ret);
1463 goto out;
1466 else
1468 if (!(ctx = wglCreateContext(hdc)))
1470 ERR("Failed to create a WGL context.\n");
1471 context_release(ret);
1472 goto out;
1475 if (share_ctx && !wglShareLists(share_ctx, ctx))
1477 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1478 context_release(ret);
1479 if (!wglDeleteContext(ctx))
1480 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1481 goto out;
1485 if (!device_context_add(device, ret))
1487 ERR("Failed to add the newly created context to the context list\n");
1488 context_release(ret);
1489 if (!wglDeleteContext(ctx))
1490 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1491 goto out;
1494 ret->d3d_info = &device->adapter->d3d_info;
1495 ret->state_table = device->StateTable;
1497 /* Mark all states dirty to force a proper initialization of the states
1498 * on the first use of the context. */
1499 for (state = 0; state <= STATE_HIGHEST; ++state)
1501 if (ret->state_table[state].representative)
1502 context_invalidate_state(ret, state);
1505 ret->swapchain = swapchain;
1506 ret->current_rt = target;
1507 ret->tid = GetCurrentThreadId();
1509 ret->render_offscreen = surface_is_offscreen(target);
1510 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1511 ret->valid = 1;
1513 ret->glCtx = ctx;
1514 ret->win_handle = swapchain->win_handle;
1515 ret->hdc = hdc;
1516 ret->pixel_format = pixel_format;
1517 ret->needs_set = 1;
1519 /* Set up the context defaults */
1520 if (!context_set_current(ret))
1522 ERR("Cannot activate context to set up defaults.\n");
1523 device_context_remove(device, ret);
1524 context_release(ret);
1525 if (!wglDeleteContext(ctx))
1526 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1527 goto out;
1530 if (context_debug_output_enabled(gl_info))
1532 GL_EXTCALL(glDebugMessageCallbackARB(wined3d_debug_callback, ret));
1533 if (TRACE_ON(d3d_synchronous))
1534 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
1535 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1536 if (ERR_ON(d3d))
1538 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB,
1539 GL_DONT_CARE, 0, NULL, GL_TRUE));
1541 if (FIXME_ON(d3d))
1543 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,
1544 GL_DONT_CARE, 0, NULL, GL_TRUE));
1545 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,
1546 GL_DONT_CARE, 0, NULL, GL_TRUE));
1547 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB,
1548 GL_DONT_CARE, 0, NULL, GL_TRUE));
1550 if (WARN_ON(d3d_perf))
1552 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB,
1553 GL_DONT_CARE, 0, NULL, GL_TRUE));
1557 switch (swapchain->desc.swap_interval)
1559 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1560 swap_interval = 0;
1561 break;
1562 case WINED3DPRESENT_INTERVAL_DEFAULT:
1563 case WINED3DPRESENT_INTERVAL_ONE:
1564 swap_interval = 1;
1565 break;
1566 case WINED3DPRESENT_INTERVAL_TWO:
1567 swap_interval = 2;
1568 break;
1569 case WINED3DPRESENT_INTERVAL_THREE:
1570 swap_interval = 3;
1571 break;
1572 case WINED3DPRESENT_INTERVAL_FOUR:
1573 swap_interval = 4;
1574 break;
1575 default:
1576 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1577 swap_interval = 1;
1580 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1582 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1583 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1584 swap_interval, ret, GetLastError());
1587 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1589 TRACE("Setting up the screen\n");
1591 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1592 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1594 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1595 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1597 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1598 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1600 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1601 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1602 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1603 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1605 if (gl_info->supported[ARB_VERTEX_BLEND])
1607 /* Direct3D always uses n-1 weights for n world matrices and uses
1608 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1609 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1610 * enabled as well. */
1611 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1612 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1614 if (gl_info->supported[NV_TEXTURE_SHADER2])
1616 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1617 * the previous texture where to source the offset from is always unit - 1.
1619 for (s = 1; s < gl_info->limits.textures; ++s)
1621 context_active_texture(ret, gl_info, s);
1622 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1623 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1624 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1627 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1629 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1630 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1631 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1632 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1633 * is ever assigned.
1635 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1636 * program and the dummy program is destroyed when the context is destroyed.
1638 const char *dummy_program =
1639 "!!ARBfp1.0\n"
1640 "MOV result.color, fragment.color.primary;\n"
1641 "END\n";
1642 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1643 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1644 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1647 if (gl_info->supported[ARB_POINT_SPRITE])
1649 for (s = 0; s < gl_info->limits.textures; ++s)
1651 context_active_texture(ret, gl_info, s);
1652 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1653 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1657 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1659 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1661 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1663 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1665 ret->shader_update_mask = (1 << WINED3D_SHADER_TYPE_PIXEL)
1666 | (1 << WINED3D_SHADER_TYPE_VERTEX)
1667 | (1 << WINED3D_SHADER_TYPE_GEOMETRY);
1669 /* If this happens to be the first context for the device, dummy textures
1670 * are not created yet. In that case, they will be created (and bound) by
1671 * create_dummy_textures right after this context is initialized. */
1672 if (device->dummy_texture_2d[0])
1673 bind_dummy_textures(device, ret);
1675 TRACE("Created context %p.\n", ret);
1677 return ret;
1679 out:
1680 device->shader_backend->shader_free_context_data(ret);
1681 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1682 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1683 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1684 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1685 HeapFree(GetProcessHeap(), 0, ret);
1686 return NULL;
1689 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1691 BOOL destroy;
1693 TRACE("Destroying ctx %p\n", context);
1695 if (context->tid == GetCurrentThreadId() || !context->current)
1697 context_destroy_gl_resources(context);
1698 TlsSetValue(wined3d_context_tls_idx, NULL);
1699 destroy = TRUE;
1701 else
1703 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1704 in wined3d_adapter may go away in the meantime */
1705 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1706 *gl_info = *context->gl_info;
1707 context->gl_info = gl_info;
1708 context->destroyed = 1;
1709 destroy = FALSE;
1712 device->shader_backend->shader_free_context_data(context);
1713 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1714 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1715 device_context_remove(device, context);
1716 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1719 /* Context activation is done by the caller. */
1720 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1722 const GLdouble projection[] =
1724 2.0 / width, 0.0, 0.0, 0.0,
1725 0.0, 2.0 / height, 0.0, 0.0,
1726 0.0, 0.0, 2.0, 0.0,
1727 -1.0, -1.0, -1.0, 1.0,
1730 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1731 checkGLcall("glMatrixMode(GL_PROJECTION)");
1732 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1733 checkGLcall("glLoadMatrixd");
1734 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1735 checkGLcall("glViewport");
1738 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1740 const struct wined3d_surface *rt = context->current_rt;
1742 if (rt->swapchain && rt->swapchain->front_buffer == rt)
1744 RECT window_size;
1746 GetClientRect(context->win_handle, &window_size);
1747 size->cx = window_size.right - window_size.left;
1748 size->cy = window_size.bottom - window_size.top;
1750 return;
1753 size->cx = rt->resource.width;
1754 size->cy = rt->resource.height;
1757 /*****************************************************************************
1758 * SetupForBlit
1760 * Sets up a context for DirectDraw blitting.
1761 * All texture units are disabled, texture unit 0 is set as current unit
1762 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1763 * color writing enabled for all channels
1764 * register combiners disabled, shaders disabled
1765 * world matrix is set to identity, texture matrix 0 too
1766 * projection matrix is setup for drawing screen coordinates
1768 * Params:
1769 * This: Device to activate the context for
1770 * context: Context to setup
1772 *****************************************************************************/
1773 /* Context activation is done by the caller. */
1774 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1776 int i;
1777 const struct wined3d_gl_info *gl_info = context->gl_info;
1778 DWORD sampler;
1779 SIZE rt_size;
1781 TRACE("Setting up context %p for blitting\n", context);
1783 context_get_rt_size(context, &rt_size);
1785 if (context->last_was_blit)
1787 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1789 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1790 context->blit_w = rt_size.cx;
1791 context->blit_h = rt_size.cy;
1792 /* No need to dirtify here, the states are still dirtified because
1793 * they weren't applied since the last SetupForBlit() call. */
1795 TRACE("Context is already set up for blitting, nothing to do\n");
1796 return;
1798 context->last_was_blit = TRUE;
1800 /* Disable all textures. The caller can then bind a texture it wants to blit
1801 * from
1803 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1804 * function texture unit. No need to care for higher samplers
1806 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1808 sampler = context->rev_tex_unit_map[i];
1809 context_active_texture(context, gl_info, i);
1811 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1813 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1814 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1816 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1817 checkGLcall("glDisable GL_TEXTURE_3D");
1818 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1820 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1821 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1823 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1824 checkGLcall("glDisable GL_TEXTURE_2D");
1826 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1827 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1829 if (sampler != WINED3D_UNMAPPED_STAGE)
1831 if (sampler < MAX_TEXTURES)
1832 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1833 context_invalidate_state(context, STATE_SAMPLER(sampler));
1836 context_active_texture(context, gl_info, 0);
1838 sampler = context->rev_tex_unit_map[0];
1840 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1842 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1843 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1845 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1846 checkGLcall("glDisable GL_TEXTURE_3D");
1847 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1849 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1850 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1852 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1853 checkGLcall("glDisable GL_TEXTURE_2D");
1855 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1857 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1858 checkGLcall("glMatrixMode(GL_TEXTURE)");
1859 gl_info->gl_ops.gl.p_glLoadIdentity();
1860 checkGLcall("glLoadIdentity()");
1862 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1864 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1865 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1866 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1869 if (sampler != WINED3D_UNMAPPED_STAGE)
1871 if (sampler < MAX_TEXTURES)
1873 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1874 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1876 context_invalidate_state(context, STATE_SAMPLER(sampler));
1879 /* Other misc states */
1880 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1881 checkGLcall("glDisable(GL_ALPHA_TEST)");
1882 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1883 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1884 checkGLcall("glDisable GL_LIGHTING");
1885 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1886 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1887 checkGLcall("glDisable GL_DEPTH_TEST");
1888 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1889 glDisableWINE(GL_FOG);
1890 checkGLcall("glDisable GL_FOG");
1891 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1892 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1893 checkGLcall("glDisable GL_BLEND");
1894 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1895 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
1896 checkGLcall("glDisable GL_CULL_FACE");
1897 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1898 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
1899 checkGLcall("glDisable GL_STENCIL_TEST");
1900 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1901 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
1902 checkGLcall("glDisable GL_SCISSOR_TEST");
1903 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1904 if (gl_info->supported[ARB_POINT_SPRITE])
1906 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
1907 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1908 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1910 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1911 checkGLcall("glColorMask");
1912 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1913 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1914 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1915 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
1916 if (gl_info->supported[EXT_SECONDARY_COLOR])
1918 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
1919 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
1920 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1923 /* Setup transforms */
1924 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
1925 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1926 gl_info->gl_ops.gl.p_glLoadIdentity();
1927 checkGLcall("glLoadIdentity()");
1928 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
1930 context->last_was_rhw = TRUE;
1931 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
1933 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1934 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1935 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1936 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1937 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1938 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1939 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
1941 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1943 /* Disable shaders */
1944 device->shader_backend->shader_disable(device->shader_priv, context);
1946 context->blit_w = rt_size.cx;
1947 context->blit_h = rt_size.cy;
1948 context_invalidate_state(context, STATE_VIEWPORT);
1949 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
1952 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
1954 return rt_mask & (1 << 31);
1957 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
1959 return rt_mask & ~(1 << 31);
1962 /* Context activation is done by the caller. */
1963 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
1965 const struct wined3d_gl_info *gl_info = context->gl_info;
1967 if (!rt_mask)
1969 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
1970 checkGLcall("glDrawBuffer()");
1972 else if (is_rt_mask_onscreen(rt_mask))
1974 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
1975 checkGLcall("glDrawBuffer()");
1977 else
1979 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1981 unsigned int i = 0;
1983 while (rt_mask)
1985 if (rt_mask & 1)
1986 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
1987 else
1988 context->draw_buffers[i] = GL_NONE;
1990 rt_mask >>= 1;
1991 ++i;
1994 if (gl_info->supported[ARB_DRAW_BUFFERS])
1996 GL_EXTCALL(glDrawBuffersARB(i, context->draw_buffers));
1997 checkGLcall("glDrawBuffers()");
1999 else
2001 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2002 checkGLcall("glDrawBuffer()");
2005 else
2007 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2012 /* Context activation is done by the caller. */
2013 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2015 const struct wined3d_gl_info *gl_info = context->gl_info;
2016 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2017 DWORD new_mask = context_generate_rt_mask(buffer);
2019 if (new_mask == *current_mask)
2020 return;
2022 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2023 checkGLcall("glDrawBuffer()");
2025 *current_mask = new_mask;
2028 /* Context activation is done by the caller. */
2029 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2031 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0 + unit));
2032 checkGLcall("glActiveTextureARB");
2033 context->active_texture = unit;
2036 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2038 const struct wined3d_gl_info *gl_info = context->gl_info;
2039 DWORD unit = context->active_texture;
2040 DWORD old_texture_type = context->texture_type[unit];
2042 if (name)
2044 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2045 checkGLcall("glBindTexture");
2047 else
2049 target = GL_NONE;
2052 if (old_texture_type != target)
2054 const struct wined3d_device *device = context->swapchain->device;
2056 switch (old_texture_type)
2058 case GL_NONE:
2059 /* nothing to do */
2060 break;
2061 case GL_TEXTURE_2D:
2062 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2063 checkGLcall("glBindTexture");
2064 break;
2065 case GL_TEXTURE_RECTANGLE_ARB:
2066 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2067 checkGLcall("glBindTexture");
2068 break;
2069 case GL_TEXTURE_CUBE_MAP:
2070 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2071 checkGLcall("glBindTexture");
2072 break;
2073 case GL_TEXTURE_3D:
2074 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2075 checkGLcall("glBindTexture");
2076 break;
2077 default:
2078 ERR("Unexpected texture target %#x\n", old_texture_type);
2081 context->texture_type[unit] = target;
2085 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2087 if (context->render_offscreen == offscreen) return;
2089 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2090 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2091 context_invalidate_state(context, STATE_VIEWPORT);
2092 context_invalidate_state(context, STATE_SCISSORRECT);
2093 context_invalidate_state(context, STATE_FRONTFACE);
2094 context->render_offscreen = offscreen;
2097 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2098 const struct wined3d_format *required)
2100 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
2102 if (existing == required) return TRUE;
2103 if ((existing->flags & WINED3DFMT_FLAG_FLOAT) != (required->flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
2105 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2106 getDepthStencilBits(required, &required_depth, &required_stencil);
2108 if(existing_depth < required_depth) return FALSE;
2109 /* If stencil bits are used the exact amount is required - otherwise wrapping
2110 * won't work correctly */
2111 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2112 return TRUE;
2115 /* The caller provides a context */
2116 static void context_validate_onscreen_formats(struct wined3d_context *context,
2117 const struct wined3d_surface *depth_stencil)
2119 /* Onscreen surfaces are always in a swapchain */
2120 struct wined3d_swapchain *swapchain = context->current_rt->swapchain;
2122 if (context->render_offscreen || !depth_stencil) return;
2123 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format)) return;
2125 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2126 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2127 * format. */
2128 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2130 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2131 surface_load_location(context->current_rt, WINED3D_LOCATION_TEXTURE_RGB);
2132 swapchain->render_to_fbo = TRUE;
2133 swapchain_update_draw_bindings(swapchain);
2134 context_set_render_offscreen(context, TRUE);
2137 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2139 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2140 return 0;
2141 else if (rt->swapchain)
2142 return context_generate_rt_mask_from_surface(rt);
2143 else
2144 return context_generate_rt_mask(device->offscreenBuffer);
2147 /* Context activation is done by the caller. */
2148 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2150 struct wined3d_surface *rt = context->current_rt;
2151 DWORD rt_mask, *cur_mask;
2153 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2155 context_validate_onscreen_formats(context, NULL);
2157 if (context->render_offscreen)
2159 wined3d_texture_load(rt->container, context, FALSE);
2161 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->draw_binding);
2162 if (rt->resource.format->id != WINED3DFMT_NULL)
2163 rt_mask = 1;
2164 else
2165 rt_mask = 0;
2167 else
2169 context->current_fbo = NULL;
2170 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2171 rt_mask = context_generate_rt_mask_from_surface(rt);
2174 else
2176 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2179 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2181 if (rt_mask != *cur_mask)
2183 context_apply_draw_buffers(context, rt_mask);
2184 *cur_mask = rt_mask;
2187 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2189 context_check_fbo_status(context, GL_FRAMEBUFFER);
2192 SetupForBlit(device, context);
2193 context_invalidate_state(context, STATE_FRAMEBUFFER);
2196 static BOOL context_validate_rt_config(UINT rt_count,
2197 struct wined3d_surface * const *rts, const struct wined3d_surface *ds)
2199 unsigned int i;
2201 if (ds) return TRUE;
2203 for (i = 0; i < rt_count; ++i)
2205 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2206 return TRUE;
2209 WARN("Invalid render target config, need at least one attachment.\n");
2210 return FALSE;
2213 /* Context activation is done by the caller. */
2214 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2215 UINT rt_count, const struct wined3d_fb_state *fb)
2217 const struct wined3d_gl_info *gl_info = context->gl_info;
2218 DWORD rt_mask = 0, *cur_mask;
2219 UINT i;
2220 struct wined3d_surface **rts = fb->render_targets;
2222 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2223 || rt_count != context->gl_info->limits.buffers)
2225 if (!context_validate_rt_config(rt_count, rts, fb->depth_stencil))
2226 return FALSE;
2228 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2230 context_validate_onscreen_formats(context, fb->depth_stencil);
2232 if (!rt_count || surface_is_offscreen(rts[0]))
2234 for (i = 0; i < rt_count; ++i)
2236 context->blit_targets[i] = rts[i];
2237 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL)
2238 rt_mask |= (1 << i);
2240 while (i < context->gl_info->limits.buffers)
2242 context->blit_targets[i] = NULL;
2243 ++i;
2245 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets, fb->depth_stencil,
2246 rt_count ? rts[0]->draw_binding : WINED3D_LOCATION_TEXTURE_RGB);
2248 else
2250 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, WINED3D_LOCATION_DRAWABLE);
2251 rt_mask = context_generate_rt_mask_from_surface(rts[0]);
2254 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2255 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2256 * state management allows this */
2257 context_invalidate_state(context, STATE_FRAMEBUFFER);
2259 else
2261 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2264 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2265 && (!rt_count || surface_is_offscreen(rts[0])))
2267 for (i = 0; i < rt_count; ++i)
2269 if (rts[i] && rts[i]->resource.format->id != WINED3DFMT_NULL) rt_mask |= (1 << i);
2272 else
2274 rt_mask = context_generate_rt_mask_no_fbo(device, rt_count ? rts[0] : NULL);
2277 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2279 if (rt_mask != *cur_mask)
2281 context_apply_draw_buffers(context, rt_mask);
2282 *cur_mask = rt_mask;
2283 context_invalidate_state(context, STATE_FRAMEBUFFER);
2286 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2288 context_check_fbo_status(context, GL_FRAMEBUFFER);
2291 if (context->last_was_blit)
2292 context->last_was_blit = FALSE;
2294 /* Blending and clearing should be orthogonal, but tests on the nvidia
2295 * driver show that disabling blending when clearing improves the clearing
2296 * performance incredibly. */
2297 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2298 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2299 checkGLcall("glEnable GL_SCISSOR_TEST");
2301 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2302 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2303 context_invalidate_state(context, STATE_SCISSORRECT);
2305 return TRUE;
2308 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2310 const struct wined3d_state *state = &device->state;
2311 struct wined3d_surface **rts = state->fb->render_targets;
2312 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2313 DWORD rt_mask, rt_mask_bits;
2314 unsigned int i;
2316 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) return context_generate_rt_mask_no_fbo(device, rts[0]);
2317 else if (!context->render_offscreen) return context_generate_rt_mask_from_surface(rts[0]);
2319 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2320 rt_mask &= context->d3d_info->valid_rt_mask;
2321 rt_mask_bits = rt_mask;
2322 i = 0;
2323 while (rt_mask_bits)
2325 rt_mask_bits &= ~(1 << i);
2326 if (!rts[i] || rts[i]->resource.format->id == WINED3DFMT_NULL)
2327 rt_mask &= ~(1 << i);
2329 i++;
2332 return rt_mask;
2335 /* Context activation is done by the caller. */
2336 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2338 const struct wined3d_device *device = context->swapchain->device;
2339 const struct wined3d_fb_state *fb = state->fb;
2340 DWORD rt_mask = find_draw_buffers_mask(context, device);
2341 DWORD *cur_mask;
2343 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2345 if (!context->render_offscreen)
2347 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL, WINED3D_LOCATION_DRAWABLE);
2349 else
2351 context_apply_fbo_state(context, GL_FRAMEBUFFER, fb->render_targets, fb->depth_stencil,
2352 fb->render_targets[0]->draw_binding);
2356 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2357 if (rt_mask != *cur_mask)
2359 context_apply_draw_buffers(context, rt_mask);
2360 *cur_mask = rt_mask;
2364 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2366 DWORD i = context->rev_tex_unit_map[unit];
2367 DWORD j = context->tex_unit_map[stage];
2369 context->tex_unit_map[stage] = unit;
2370 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2371 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2373 context->rev_tex_unit_map[unit] = stage;
2374 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2375 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2378 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2380 DWORD i;
2382 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2383 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2386 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2387 const struct wined3d_state *state)
2389 UINT i, start, end;
2391 context->fixed_function_usage_map = 0;
2392 for (i = 0; i < MAX_TEXTURES; ++i)
2394 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2395 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2396 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2397 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2398 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2399 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2400 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2401 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2403 /* Not used, and disable higher stages. */
2404 if (color_op == WINED3D_TOP_DISABLE)
2405 break;
2407 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2408 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2409 || ((color_arg3 == WINED3DTA_TEXTURE)
2410 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2411 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2412 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2413 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2414 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2415 context->fixed_function_usage_map |= (1 << i);
2417 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2418 && i < MAX_TEXTURES - 1)
2419 context->fixed_function_usage_map |= (1 << (i + 1));
2422 if (i < context->lowest_disabled_stage)
2424 start = i;
2425 end = context->lowest_disabled_stage;
2427 else
2429 start = context->lowest_disabled_stage;
2430 end = i;
2433 context->lowest_disabled_stage = i;
2434 for (i = start + 1; i < end; ++i)
2436 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2440 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2441 const struct wined3d_state *state)
2443 unsigned int i, tex;
2444 WORD ffu_map;
2445 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2447 context_update_fixed_function_usage_map(context, state);
2448 ffu_map = context->fixed_function_usage_map;
2450 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2451 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2453 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2455 if (!(ffu_map & 1))
2456 continue;
2458 if (context->tex_unit_map[i] != i)
2460 context_map_stage(context, i, i);
2461 context_invalidate_state(context, STATE_SAMPLER(i));
2462 context_invalidate_texture_stage(context, i);
2465 return;
2468 /* Now work out the mapping */
2469 tex = 0;
2470 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2472 if (!(ffu_map & 1))
2473 continue;
2475 if (context->tex_unit_map[i] != tex)
2477 context_map_stage(context, i, tex);
2478 context_invalidate_state(context, STATE_SAMPLER(i));
2479 context_invalidate_texture_stage(context, i);
2482 ++tex;
2486 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2488 const enum wined3d_sampler_texture_type *sampler_type =
2489 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.sampler_type;
2490 unsigned int i;
2491 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2493 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2495 if (sampler_type[i] && context->tex_unit_map[i] != i)
2497 context_map_stage(context, i, i);
2498 context_invalidate_state(context, STATE_SAMPLER(i));
2499 if (i < d3d_info->limits.ffp_blend_stages)
2500 context_invalidate_texture_stage(context, i);
2505 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2506 const enum wined3d_sampler_texture_type *pshader_sampler_tokens,
2507 const enum wined3d_sampler_texture_type *vshader_sampler_tokens, DWORD unit)
2509 DWORD current_mapping = context->rev_tex_unit_map[unit];
2511 /* Not currently used */
2512 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2513 return TRUE;
2515 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2517 /* Used by a fragment sampler */
2519 if (!pshader_sampler_tokens)
2521 /* No pixel shader, check fixed function */
2522 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1 << current_mapping));
2525 /* Pixel shader, check the shader's sampler map */
2526 return !pshader_sampler_tokens[current_mapping];
2529 /* Used by a vertex sampler */
2530 return !vshader_sampler_tokens[current_mapping - MAX_FRAGMENT_SAMPLERS];
2533 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2535 const enum wined3d_sampler_texture_type *vshader_sampler_type =
2536 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.sampler_type;
2537 const enum wined3d_sampler_texture_type *pshader_sampler_type = NULL;
2538 const struct wined3d_gl_info *gl_info = context->gl_info;
2539 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2540 int i;
2542 if (ps)
2544 /* Note that we only care if a sampler is sampled or not, not the sampler's specific type.
2545 * Otherwise we'd need to call shader_update_samplers() here for 1.x pixelshaders. */
2546 pshader_sampler_type = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.sampler_type;
2549 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i) {
2550 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2551 if (vshader_sampler_type[i])
2553 if (context->tex_unit_map[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2555 /* Already mapped somewhere */
2556 continue;
2559 while (start >= 0)
2561 if (context_unit_free_for_vs(context, pshader_sampler_type, vshader_sampler_type, start))
2563 context_map_stage(context, vsampler_idx, start);
2564 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2566 --start;
2567 break;
2570 --start;
2576 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2578 BOOL vs = use_vs(state);
2579 BOOL ps = use_ps(state);
2581 * Rules are:
2582 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2583 * that would be really messy and require shader recompilation
2584 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2585 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2587 if (ps)
2588 context_map_psamplers(context, state);
2589 else
2590 context_map_fixed_function_samplers(context, state);
2592 if (vs)
2593 context_map_vsamplers(context, ps, state);
2596 /* Context activation is done by the caller. */
2597 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2599 const struct wined3d_device *device = context->swapchain->device;
2600 DWORD rt_mask, *cur_mask;
2602 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2604 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2605 rt_mask = find_draw_buffers_mask(context, device);
2606 if (rt_mask != *cur_mask)
2608 context_apply_draw_buffers(context, rt_mask);
2609 *cur_mask = rt_mask;
2613 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2615 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2616 *regnum = WINED3D_FFP_POSITION;
2617 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2618 *regnum = WINED3D_FFP_BLENDWEIGHT;
2619 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2620 *regnum = WINED3D_FFP_BLENDINDICES;
2621 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2622 *regnum = WINED3D_FFP_NORMAL;
2623 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2624 *regnum = WINED3D_FFP_PSIZE;
2625 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2626 *regnum = WINED3D_FFP_DIFFUSE;
2627 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2628 *regnum = WINED3D_FFP_SPECULAR;
2629 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2630 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2631 else
2633 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2634 *regnum = ~0U;
2635 return FALSE;
2638 return TRUE;
2641 /* FIXME: Separate buffer loading from declaration decoding */
2642 /* Context activation is done by the caller. */
2643 void context_stream_info_from_declaration(struct wined3d_context *context,
2644 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2646 /* We need to deal with frequency data! */
2647 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2648 BOOL use_vshader = use_vs(state);
2649 unsigned int i;
2650 WORD map;
2652 stream_info->use_map = 0;
2653 stream_info->swizzle_map = 0;
2654 stream_info->all_vbo = 1;
2655 stream_info->position_transformed = declaration->position_transformed;
2657 /* Translate the declaration into strided data. */
2658 for (i = 0; i < declaration->element_count; ++i)
2660 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2661 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2662 struct wined3d_buffer *buffer = stream->buffer;
2663 struct wined3d_bo_address data;
2664 BOOL stride_used;
2665 unsigned int idx;
2666 DWORD stride;
2668 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2669 element, i + 1, declaration->element_count);
2671 if (!buffer) continue;
2673 stride = stream->stride;
2674 TRACE("Stream %u in buffer %p.\n", element->input_slot, buffer);
2675 buffer_get_memory(buffer, context, &data);
2677 /* Can't use vbo's if the base vertex index is negative. OpenGL doesn't accept negative offsets
2678 * (or rather offsets bigger than the vbo, because the pointer is unsigned), so use system memory
2679 * sources. In most sane cases the pointer - offset will still be > 0, otherwise it will wrap
2680 * around to some big value. Hope that with the indices, the driver wraps it back internally. If
2681 * not, drawStridedSlow is needed, including a vertex buffer path. */
2682 if (state->load_base_vertex_index < 0)
2684 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2685 state->load_base_vertex_index);
2686 data.buffer_object = 0;
2687 data.addr = buffer_get_sysmem(buffer, context);
2688 if ((UINT_PTR)data.addr < -state->load_base_vertex_index * stride)
2690 FIXME("System memory vertex data load offset is negative!\n");
2693 data.addr += element->offset;
2695 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2697 if (use_vshader)
2699 if (element->output_slot == ~0U)
2701 /* TODO: Assuming vertexdeclarations are usually used with the
2702 * same or a similar shader, it might be worth it to store the
2703 * last used output slot and try that one first. */
2704 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2705 element->usage, element->usage_idx, &idx);
2707 else
2709 idx = element->output_slot;
2710 stride_used = TRUE;
2713 else
2715 if (!element->ffp_valid)
2717 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2718 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2719 stride_used = FALSE;
2721 else
2723 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2727 if (stride_used)
2729 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2730 "input_slot %u, offset %u, stride %u, format %s, buffer_object %u].\n",
2731 use_vshader ? "shader": "fixed function", idx,
2732 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2733 element->offset, stride, debug_d3dformat(element->format->id), data.buffer_object);
2735 data.addr += stream->offset;
2737 stream_info->elements[idx].format = element->format;
2738 stream_info->elements[idx].data = data;
2739 stream_info->elements[idx].stride = stride;
2740 stream_info->elements[idx].stream_idx = element->input_slot;
2742 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2743 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2745 stream_info->swizzle_map |= 1 << idx;
2747 stream_info->use_map |= 1 << idx;
2751 /* Preload the vertex buffers. */
2752 context->num_buffer_queries = 0;
2753 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2755 struct wined3d_stream_info_element *element;
2756 struct wined3d_buffer *buffer;
2758 if (!(map & 1))
2759 continue;
2761 element = &stream_info->elements[i];
2762 buffer = state->streams[element->stream_idx].buffer;
2763 buffer_internal_preload(buffer, context, state);
2765 /* If the preload dropped the buffer object, update the stream info. */
2766 if (buffer->buffer_object != element->data.buffer_object)
2768 element->data.buffer_object = 0;
2769 element->data.addr = buffer_get_sysmem(buffer, context)
2770 + (ptrdiff_t)element->data.addr;
2773 if (!buffer->buffer_object)
2774 stream_info->all_vbo = 0;
2776 if (buffer->query)
2777 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2781 /* Context activation is done by the caller. */
2782 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2784 const struct wined3d_gl_info *gl_info = context->gl_info;
2785 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2786 struct wined3d_stream_info *stream_info = &context->stream_info;
2787 DWORD prev_all_vbo = stream_info->all_vbo;
2789 TRACE("============================= Vertex Declaration =============================\n");
2790 context_stream_info_from_declaration(context, state, stream_info);
2792 if (use_vs(state))
2794 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
2796 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
2797 context->use_immediate_mode_draw = TRUE;
2799 else
2801 context->use_immediate_mode_draw = FALSE;
2804 else
2806 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
2807 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2808 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
2810 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
2811 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
2812 context->use_immediate_mode_draw = TRUE;
2813 else
2814 context->use_immediate_mode_draw = FALSE;
2817 if (prev_all_vbo != stream_info->all_vbo)
2818 context_invalidate_state(context, STATE_INDEXBUFFER);
2821 /* Context activation is done by the caller. */
2822 static void context_preload_texture(struct wined3d_context *context,
2823 const struct wined3d_state *state, unsigned int idx)
2825 struct wined3d_texture *texture;
2827 if (!(texture = state->textures[idx]))
2828 return;
2830 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
2833 /* Context activation is done by the caller. */
2834 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
2836 unsigned int i;
2838 if (use_vs(state))
2840 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2842 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.sampler_type[i])
2843 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
2847 if (use_ps(state))
2849 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2851 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.sampler_type[i])
2852 context_preload_texture(context, state, i);
2855 else
2857 WORD ffu_map = context->fixed_function_usage_map;
2859 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2861 if (ffu_map & 1)
2862 context_preload_texture(context, state, i);
2867 /* Context activation is done by the caller. */
2868 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
2870 const struct wined3d_state *state = &device->state;
2871 const struct StateEntry *state_table = context->state_table;
2872 const struct wined3d_fb_state *fb = state->fb;
2873 unsigned int i;
2875 if (!context_validate_rt_config(context->gl_info->limits.buffers,
2876 fb->render_targets, fb->depth_stencil))
2877 return FALSE;
2879 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
2881 context_validate_onscreen_formats(context, fb->depth_stencil);
2884 /* Preload resources before FBO setup. Texture preload in particular may
2885 * result in changes to the current FBO, due to using e.g. FBO blits for
2886 * updating a resource location. */
2887 context_update_tex_unit_map(context, state);
2888 context_preload_textures(context, state);
2889 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC))
2890 context_update_stream_info(context, state);
2891 if (state->index_buffer)
2893 if (context->stream_info.all_vbo)
2894 buffer_internal_preload(state->index_buffer, context, state);
2895 else
2896 buffer_get_sysmem(state->index_buffer, context);
2899 for (i = 0; i < context->numDirtyEntries; ++i)
2901 DWORD rep = context->dirtyArray[i];
2902 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2903 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2904 context->isStateDirty[idx] &= ~(1 << shift);
2905 state_table[rep].apply(context, state, rep);
2908 if (context->shader_update_mask)
2910 device->shader_backend->shader_select(device->shader_priv, context, state);
2911 context->shader_update_mask = 0;
2914 if (context->constant_update_mask)
2916 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
2917 context->constant_update_mask = 0;
2920 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2922 context_check_fbo_status(context, GL_FRAMEBUFFER);
2925 context->numDirtyEntries = 0; /* This makes the whole list clean */
2926 context->last_was_blit = FALSE;
2928 return TRUE;
2931 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
2933 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2935 render_offscreen = surface_is_offscreen(target);
2936 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
2938 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2939 * the alpha blend state changes with different render target formats. */
2940 if (!context->current_rt)
2942 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2944 else
2946 const struct wined3d_format *old = context->current_rt->resource.format;
2947 const struct wined3d_format *new = target->resource.format;
2949 if (old->id != new->id)
2951 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2952 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
2953 || !(new->flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2954 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2956 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
2957 if ((old->flags & WINED3DFMT_FLAG_SRGB_WRITE) != (new->flags & WINED3DFMT_FLAG_SRGB_WRITE))
2958 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2961 /* When switching away from an offscreen render target, and we're not
2962 * using FBOs, we have to read the drawable into the texture. This is
2963 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
2964 * There are some things that need care though. PreLoad needs a GL context,
2965 * and FindContext is called before the context is activated. It also
2966 * has to be called with the old rendertarget active, otherwise a
2967 * wrong drawable is read. */
2968 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2969 && old_render_offscreen && context->current_rt != target)
2971 struct wined3d_texture *texture = context->current_rt->container;
2973 /* Read the back buffer of the old drawable into the destination texture. */
2974 if (texture->texture_srgb.name)
2975 wined3d_texture_load(texture, context, TRUE);
2976 wined3d_texture_load(texture, context, FALSE);
2977 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
2981 context->current_rt = target;
2982 context_set_render_offscreen(context, render_offscreen);
2985 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
2987 struct wined3d_context *current_context = context_get_current();
2988 struct wined3d_context *context;
2990 TRACE("device %p, target %p.\n", device, target);
2992 if (current_context && current_context->destroyed)
2993 current_context = NULL;
2995 if (!target)
2997 if (current_context
2998 && current_context->current_rt
2999 && current_context->swapchain->device == device)
3001 target = current_context->current_rt;
3003 else
3005 struct wined3d_swapchain *swapchain = device->swapchains[0];
3006 if (swapchain->back_buffers)
3007 target = swapchain->back_buffers[0];
3008 else
3009 target = swapchain->front_buffer;
3013 if (current_context && current_context->current_rt == target)
3015 context = current_context;
3017 else if (target->swapchain)
3019 TRACE("Rendering onscreen.\n");
3021 context = swapchain_get_context(target->swapchain);
3023 else
3025 TRACE("Rendering offscreen.\n");
3027 /* Stay with the current context if possible. Otherwise use the
3028 * context for the primary swapchain. */
3029 if (current_context && current_context->swapchain->device == device)
3030 context = current_context;
3031 else
3032 context = swapchain_get_context(device->swapchains[0]);
3035 context_enter(context);
3036 context_update_window(context);
3037 context_setup_target(context, target);
3038 if (!context->valid) return context;
3040 if (context != current_context)
3042 if (!context_set_current(context))
3043 ERR("Failed to activate the new context.\n");
3045 else if (context->needs_set)
3047 context_set_gl_context(context);
3050 return context;