wined3d: Check multisampling compatibility before finding the FBO key.
[wine.git] / dlls / wined3d / context.c
blobd04a246a761b2d10ccd36bf98258763fdddb7ae3
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, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
124 DWORD format_flags)
126 const struct wined3d_gl_info *gl_info = context->gl_info;
128 if (resource->object)
130 TRACE("Attach depth stencil %u.\n", resource->object);
132 if (rb_namespace)
134 context_attach_depth_stencil_rb(gl_info, fbo_target,
135 format_flags, resource->object);
137 else
139 if (format_flags & WINED3DFMT_FLAG_DEPTH)
141 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
142 resource->target, resource->object, resource->level);
143 checkGLcall("glFramebufferTexture2D()");
146 if (format_flags & WINED3DFMT_FLAG_STENCIL)
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
149 resource->target, resource->object, resource->level);
150 checkGLcall("glFramebufferTexture2D()");
154 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
157 checkGLcall("glFramebufferTexture2D()");
160 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
162 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
163 checkGLcall("glFramebufferTexture2D()");
166 else
168 TRACE("Attach depth stencil 0.\n");
170 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
171 checkGLcall("glFramebufferTexture2D()");
173 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
174 checkGLcall("glFramebufferTexture2D()");
178 /* Context activation is done by the caller. */
179 static void context_attach_surface_fbo(struct wined3d_context *context,
180 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
182 const struct wined3d_gl_info *gl_info = context->gl_info;
184 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
186 if (resource->object)
189 if (rb_namespace)
191 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
192 GL_RENDERBUFFER, resource->object);
193 checkGLcall("glFramebufferRenderbuffer()");
195 else
197 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
198 resource->target, resource->object, resource->level);
199 checkGLcall("glFramebufferTexture2D()");
202 else
204 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
205 checkGLcall("glFramebufferTexture2D()");
209 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
210 GLenum attachment)
212 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
214 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
215 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
216 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
217 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
219 if (type == GL_RENDERBUFFER)
221 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
222 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
223 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
224 if (gl_info->limits.samples > 1)
225 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
226 else
227 samples = 1;
228 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
229 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
230 debug_fboattachment(attachment), name, width, height, samples, fmt);
232 else if (type == GL_TEXTURE)
234 const char *tex_type_str;
236 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
237 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
238 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
239 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
241 if (face)
243 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
245 glBindTexture(GL_TEXTURE_CUBE_MAP, name);
246 glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
247 glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
248 glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
250 tex_target = GL_TEXTURE_CUBE_MAP;
251 tex_type_str = "cube";
253 else
255 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_texture);
256 while (gl_info->gl_ops.gl.p_glGetError());
258 glBindTexture(GL_TEXTURE_2D, name);
259 if (!gl_info->gl_ops.gl.p_glGetError())
261 tex_target = GL_TEXTURE_2D;
262 tex_type_str = "2d";
264 else
266 glBindTexture(GL_TEXTURE_2D, old_texture);
267 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_texture);
269 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, name);
270 if (gl_info->gl_ops.gl.p_glGetError())
272 glBindTexture(GL_TEXTURE_RECTANGLE_ARB, old_texture);
273 FIXME("Cannot find type of texture %d.\n", name);
274 return;
276 tex_target = GL_TEXTURE_RECTANGLE_ARB;
277 tex_type_str = "rectangle";
280 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
281 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
282 glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
285 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
286 tex_type_str, name, width, height, fmt);
288 glBindTexture(tex_target, old_texture);
290 else if (type == GL_NONE)
292 FIXME("\t%s: NONE.\n", debug_fboattachment(attachment));
294 else
295 ERR("\t%s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
298 /* Context activation is done by the caller. */
299 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
301 const struct wined3d_gl_info *gl_info = context->gl_info;
302 GLenum status;
304 if (!FIXME_ON(d3d)) return;
306 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
307 if (status == GL_FRAMEBUFFER_COMPLETE)
309 TRACE("FBO complete\n");
311 else
313 unsigned int i;
315 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
317 if (!context->current_fbo)
319 ERR("FBO 0 is incomplete, driver bug?\n");
320 return;
323 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
324 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
326 for (i = 0; i < gl_info->limits.buffers; ++i)
327 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
328 checkGLcall("Dump FBO attachments");
332 static inline DWORD context_generate_rt_mask(GLenum buffer)
334 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
335 return buffer ? (1u << 31) | buffer : 0;
338 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
340 return (1u << 31) | surface_get_gl_buffer(target);
343 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
344 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
345 DWORD location)
347 if (!surface)
349 key->objects[idx].object = 0;
350 key->objects[idx].level = key->objects[idx].target = 0;
352 else if (surface->current_renderbuffer)
354 key->objects[idx].object = surface->current_renderbuffer->id;
355 key->objects[idx].level = key->objects[idx].target = 0;
356 key->rb_namespace |= 1 << idx;
358 else
360 switch (location)
362 case WINED3D_LOCATION_TEXTURE_RGB:
363 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
364 key->objects[idx].level = surface->texture_level;
365 key->objects[idx].target = surface->texture_target;
366 break;
368 case WINED3D_LOCATION_TEXTURE_SRGB:
369 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
370 key->objects[idx].level = surface->texture_level;
371 key->objects[idx].target = surface->texture_target;
372 break;
374 case WINED3D_LOCATION_RB_MULTISAMPLE:
375 key->objects[idx].object = surface->rb_multisample;
376 key->objects[idx].level = key->objects[idx].target = 0;
377 key->rb_namespace |= 1 << idx;
378 break;
380 case WINED3D_LOCATION_RB_RESOLVED:
381 key->objects[idx].object = surface->rb_resolved;
382 key->objects[idx].level = key->objects[idx].target = 0;
383 key->rb_namespace |= 1 << idx;
384 break;
389 static void context_generate_fbo_key(const struct wined3d_context *context,
390 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
391 struct wined3d_surface *depth_stencil, DWORD color_location,
392 DWORD ds_location)
394 UINT i;
396 key->rb_namespace = 0;
397 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
399 for (i = 0; i < context->gl_info->limits.buffers; ++i)
400 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
403 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
404 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
405 DWORD color_location, DWORD ds_location)
407 const struct wined3d_gl_info *gl_info = context->gl_info;
408 struct fbo_entry *entry;
409 UINT object_count = gl_info->limits.buffers + 1;
411 entry = HeapAlloc(GetProcessHeap(), 0,
412 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
413 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
414 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
415 entry->d3d_depth_stencil = depth_stencil;
416 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
417 entry->attached = FALSE;
418 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
419 checkGLcall("glGenFramebuffers()");
420 TRACE("Created FBO %u.\n", entry->id);
422 return entry;
425 /* Context activation is done by the caller. */
426 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
427 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
428 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
430 const struct wined3d_gl_info *gl_info = context->gl_info;
432 context_bind_fbo(context, target, entry->id);
433 context_clean_fbo_attachments(gl_info, target);
435 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
436 entry->d3d_depth_stencil = depth_stencil;
437 entry->attached = FALSE;
440 /* Context activation is done by the caller. */
441 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
443 if (entry->id)
445 TRACE("Destroy FBO %u.\n", entry->id);
446 context_destroy_fbo(context, entry->id);
448 --context->fbo_entry_count;
449 list_remove(&entry->entry);
450 HeapFree(GetProcessHeap(), 0, entry);
453 /* Context activation is done by the caller. */
454 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
455 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
456 DWORD color_location, DWORD ds_location)
458 const struct wined3d_gl_info *gl_info = context->gl_info;
459 struct fbo_entry *entry;
460 UINT object_count = gl_info->limits.buffers + 1;
461 unsigned int i;
463 if (depth_stencil && render_targets && render_targets[0])
465 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
466 depth_stencil->resource.height < render_targets[0]->resource.height)
468 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
469 depth_stencil = NULL;
471 else if (depth_stencil->resource.multisample_type
472 != render_targets[0]->resource.multisample_type
473 || depth_stencil->resource.multisample_quality
474 != render_targets[0]->resource.multisample_quality)
476 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
477 render_targets[0]->resource.multisample_quality,
478 render_targets[0]->resource.multisample_type,
479 depth_stencil->resource.multisample_quality, depth_stencil->resource.multisample_type);
480 depth_stencil = NULL;
482 else
483 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
486 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
487 ds_location);
489 if (TRACE_ON(d3d))
491 TRACE("Dumping FBO attachments:\n");
492 for (i = 0; i < gl_info->limits.buffers; ++i)
494 if (render_targets[i])
496 TRACE("\tColor attachment %u: (%p) %s gl obj %u(%s) %ux%u %u samples.\n",
497 i, render_targets[i], debug_d3dformat(render_targets[i]->resource.format->id),
498 context->fbo_key->objects[i + 1].object,
499 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "rb" : "texure",
500 render_targets[i]->pow2Width, render_targets[i]->pow2Height,
501 render_targets[i]->resource.multisample_type);
504 if (depth_stencil)
506 TRACE("\tDepth attachment: (%p) %s gl obj %u(%s) %ux%u %u samples.\n",
507 depth_stencil, debug_d3dformat(depth_stencil->resource.format->id),
508 context->fbo_key->objects[0].object,
509 context->fbo_key->rb_namespace & (1 << 0) ? "rb" : "texure",
510 depth_stencil->pow2Width, depth_stencil->pow2Height, depth_stencil->resource.multisample_type);
514 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
516 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
517 continue;
519 list_remove(&entry->entry);
520 list_add_head(&context->fbo_list, &entry->entry);
521 return entry;
524 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
526 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
527 list_add_head(&context->fbo_list, &entry->entry);
528 ++context->fbo_entry_count;
530 else
532 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
533 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
534 list_remove(&entry->entry);
535 list_add_head(&context->fbo_list, &entry->entry);
538 return entry;
541 /* Context activation is done by the caller. */
542 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
544 const struct wined3d_gl_info *gl_info = context->gl_info;
545 unsigned int i;
546 GLuint read_binding, draw_binding;
547 struct wined3d_surface *depth_stencil = entry->d3d_depth_stencil;
549 if (entry->attached)
551 context_bind_fbo(context, target, entry->id);
552 return;
555 read_binding = context->fbo_read_binding;
556 draw_binding = context->fbo_draw_binding;
557 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
559 /* Apply render targets */
560 for (i = 0; i < gl_info->limits.buffers; ++i)
562 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
563 entry->key.rb_namespace & (1 << (i + 1)));
566 if (depth_stencil)
568 DWORD format_flags = depth_stencil->container->resource.format_flags;
569 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
570 entry->key.rb_namespace & 0x1, format_flags);
572 else
574 static const struct wined3d_fbo_resource resource = {0};
575 context_attach_depth_stencil_fbo(context, target, &resource, FALSE, 0);
578 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
579 * GL contexts requirements. */
580 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
581 context_set_draw_buffer(context, GL_NONE);
582 if (target != GL_FRAMEBUFFER)
584 if (target == GL_READ_FRAMEBUFFER)
585 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
586 else
587 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
590 entry->attached = TRUE;
593 /* Context activation is done by the caller. */
594 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
595 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
596 DWORD color_location, DWORD ds_location)
598 struct fbo_entry *entry, *entry2;
600 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
602 context_destroy_fbo_entry(context, entry);
605 if (context->rebind_fbo)
607 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
608 context->rebind_fbo = FALSE;
611 if (color_location == WINED3D_LOCATION_DRAWABLE)
613 context->current_fbo = NULL;
614 context_bind_fbo(context, target, 0);
616 else
618 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
619 color_location, ds_location);
620 context_apply_fbo_entry(context, target, context->current_fbo);
624 /* Context activation is done by the caller. */
625 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
626 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
628 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
630 context->blit_targets[0] = render_target;
631 if (clear_size)
632 memset(&context->blit_targets[1], 0, clear_size);
633 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
636 /* Context activation is done by the caller. */
637 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
639 const struct wined3d_gl_info *gl_info = context->gl_info;
641 if (context->free_occlusion_query_count)
643 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
645 else
647 if (gl_info->supported[ARB_OCCLUSION_QUERY])
649 GL_EXTCALL(glGenQueries(1, &query->id));
650 checkGLcall("glGenQueries");
652 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
654 else
656 WARN("Occlusion queries not supported, not allocating query id.\n");
657 query->id = 0;
661 query->context = context;
662 list_add_head(&context->occlusion_queries, &query->entry);
665 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
667 struct wined3d_context *context = query->context;
669 list_remove(&query->entry);
670 query->context = NULL;
672 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
674 UINT new_size = context->free_occlusion_query_size << 1;
675 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
676 new_size * sizeof(*context->free_occlusion_queries));
678 if (!new_data)
680 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
681 return;
684 context->free_occlusion_query_size = new_size;
685 context->free_occlusion_queries = new_data;
688 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
691 /* Context activation is done by the caller. */
692 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
694 const struct wined3d_gl_info *gl_info = context->gl_info;
696 if (context->free_event_query_count)
698 query->object = context->free_event_queries[--context->free_event_query_count];
700 else
702 if (gl_info->supported[ARB_SYNC])
704 /* Using ARB_sync, not much to do here. */
705 query->object.sync = NULL;
706 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
708 else if (gl_info->supported[APPLE_FENCE])
710 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
711 checkGLcall("glGenFencesAPPLE");
713 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
715 else if(gl_info->supported[NV_FENCE])
717 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
718 checkGLcall("glGenFencesNV");
720 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
722 else
724 WARN("Event queries not supported, not allocating query id.\n");
725 query->object.id = 0;
729 query->context = context;
730 list_add_head(&context->event_queries, &query->entry);
733 void context_free_event_query(struct wined3d_event_query *query)
735 struct wined3d_context *context = query->context;
737 list_remove(&query->entry);
738 query->context = NULL;
740 if (context->free_event_query_count >= context->free_event_query_size - 1)
742 UINT new_size = context->free_event_query_size << 1;
743 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
744 new_size * sizeof(*context->free_event_queries));
746 if (!new_data)
748 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
749 return;
752 context->free_event_query_size = new_size;
753 context->free_event_queries = new_data;
756 context->free_event_queries[context->free_event_query_count++] = query->object;
759 /* Context activation is done by the caller. */
760 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
762 const struct wined3d_gl_info *gl_info = context->gl_info;
764 if (context->free_timestamp_query_count)
766 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
768 else
770 GL_EXTCALL(glGenQueries(1, &query->id));
771 checkGLcall("glGenQueries");
773 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
776 query->context = context;
777 list_add_head(&context->timestamp_queries, &query->entry);
780 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
782 struct wined3d_context *context = query->context;
784 list_remove(&query->entry);
785 query->context = NULL;
787 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
789 UINT new_size = context->free_timestamp_query_size << 1;
790 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
791 new_size * sizeof(*context->free_timestamp_queries));
793 if (!new_data)
795 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
796 return;
799 context->free_timestamp_query_size = new_size;
800 context->free_timestamp_queries = new_data;
803 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
806 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
808 static void context_enum_fbo_entries(const struct wined3d_device *device,
809 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
811 UINT i;
813 for (i = 0; i < device->context_count; ++i)
815 struct wined3d_context *context = device->contexts[i];
816 const struct wined3d_gl_info *gl_info = context->gl_info;
817 struct fbo_entry *entry, *entry2;
819 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
821 UINT j;
823 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
825 if (entry->key.objects[j].object == name
826 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
828 callback(context, entry);
829 break;
836 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
838 list_remove(&entry->entry);
839 list_add_head(&context->fbo_destroy_list, &entry->entry);
842 void context_resource_released(const struct wined3d_device *device,
843 struct wined3d_resource *resource, enum wined3d_resource_type type)
845 UINT i;
846 struct wined3d_surface *surface;
848 if (!device->d3d_initialized)
849 return;
851 switch (type)
853 case WINED3D_RTYPE_SURFACE:
854 surface = surface_from_resource(resource);
856 for (i = 0; i < device->context_count; ++i)
858 struct wined3d_context *context = device->contexts[i];
859 if (context->current_rt == surface)
860 context->current_rt = NULL;
862 break;
864 default:
865 break;
869 void context_gl_resource_released(struct wined3d_device *device,
870 GLuint name, BOOL rb_namespace)
872 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
875 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
877 const struct wined3d_gl_info *gl_info = context->gl_info;
878 struct fbo_entry *entry = context->current_fbo;
879 unsigned int i;
881 if (!entry || context->rebind_fbo) return;
883 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
885 if (surface->container->texture_rgb.name == entry->key.objects[i].object
886 || surface->container->texture_srgb.name == entry->key.objects[i].object)
888 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
889 context->rebind_fbo = TRUE;
890 return;
895 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
897 const struct wined3d_gl_info *gl_info = ctx->gl_info;
898 BOOL ret = FALSE;
900 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
902 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
904 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
905 if (dc)
907 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
909 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
910 ctx->restore_pf, ctx->restore_pf_win);
912 ReleaseDC(ctx->restore_pf_win, dc);
915 else
917 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
921 ctx->restore_pf = 0;
922 ctx->restore_pf_win = NULL;
923 return ret;
926 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
928 const struct wined3d_gl_info *gl_info = context->gl_info;
929 int current;
931 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
932 return TRUE;
934 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
935 if (current == format) goto success;
937 if (!current)
939 if (!SetPixelFormat(dc, format, NULL))
941 /* This may also happen if the dc belongs to a destroyed window. */
942 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
943 format, dc, GetLastError());
944 return FALSE;
947 context->restore_pf = 0;
948 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
949 goto success;
952 /* By default WGL doesn't allow pixel format adjustments but we need it
953 * here. For this reason there's a Wine specific wglSetPixelFormat()
954 * which allows us to set the pixel format multiple times. Only use it
955 * when really needed. */
956 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
958 HWND win;
960 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
962 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
963 format, dc);
964 return FALSE;
967 win = private ? NULL : WindowFromDC(dc);
968 if (win != context->restore_pf_win)
970 context_restore_pixel_format(context);
972 context->restore_pf = private ? 0 : current;
973 context->restore_pf_win = win;
976 goto success;
979 /* OpenGL doesn't allow pixel format adjustments. Print an error and
980 * continue using the old format. There's a big chance that the old
981 * format works although with a performance hit and perhaps rendering
982 * errors. */
983 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
984 format, dc, current);
985 return TRUE;
987 success:
988 if (dc == context->hdc && context->hdc_is_private)
989 context->hdc_has_format = TRUE;
990 return TRUE;
993 static BOOL context_set_gl_context(struct wined3d_context *ctx)
995 struct wined3d_swapchain *swapchain = ctx->swapchain;
996 BOOL backup = FALSE;
998 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1000 WARN("Failed to set pixel format %d on device context %p.\n",
1001 ctx->pixel_format, ctx->hdc);
1002 backup = TRUE;
1005 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1007 HDC dc;
1009 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1010 ctx->glCtx, ctx->hdc, GetLastError());
1011 ctx->valid = 0;
1012 WARN("Trying fallback to the backup window.\n");
1014 /* FIXME: If the context is destroyed it's no longer associated with
1015 * a swapchain, so we can't use the swapchain to get a backup dc. To
1016 * make this work windowless contexts would need to be handled by the
1017 * device. */
1018 if (ctx->destroyed)
1020 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1021 context_set_current(NULL);
1022 return FALSE;
1025 if (!(dc = swapchain_get_backup_dc(swapchain)))
1027 context_set_current(NULL);
1028 return FALSE;
1031 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1033 ERR("Failed to set pixel format %d on device context %p.\n",
1034 ctx->pixel_format, dc);
1035 context_set_current(NULL);
1036 return FALSE;
1039 if (!wglMakeCurrent(dc, ctx->glCtx))
1041 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1042 dc, GetLastError());
1043 context_set_current(NULL);
1044 return FALSE;
1047 ctx->valid = 1;
1049 ctx->needs_set = 0;
1050 return TRUE;
1053 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1055 if (!wglMakeCurrent(dc, gl_ctx))
1057 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1058 gl_ctx, dc, GetLastError());
1059 context_set_current(NULL);
1063 static void context_update_window(struct wined3d_context *context)
1065 if (context->win_handle == context->swapchain->win_handle)
1066 return;
1068 TRACE("Updating context %p window from %p to %p.\n",
1069 context, context->win_handle, context->swapchain->win_handle);
1071 if (context->hdc)
1072 wined3d_release_dc(context->win_handle, context->hdc);
1074 context->win_handle = context->swapchain->win_handle;
1075 context->hdc_is_private = FALSE;
1076 context->hdc_has_format = FALSE;
1077 context->needs_set = 1;
1078 context->valid = 1;
1080 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1082 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1083 context->valid = 0;
1087 static void context_destroy_gl_resources(struct wined3d_context *context)
1089 const struct wined3d_gl_info *gl_info = context->gl_info;
1090 struct wined3d_timestamp_query *timestamp_query;
1091 struct wined3d_occlusion_query *occlusion_query;
1092 struct wined3d_event_query *event_query;
1093 struct fbo_entry *entry, *entry2;
1094 HGLRC restore_ctx;
1095 HDC restore_dc;
1096 unsigned int i;
1098 restore_ctx = wglGetCurrentContext();
1099 restore_dc = wglGetCurrentDC();
1101 if (restore_ctx == context->glCtx)
1102 restore_ctx = NULL;
1103 else if (context->valid)
1104 context_set_gl_context(context);
1106 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1108 if (context->valid)
1109 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1110 timestamp_query->context = NULL;
1113 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1115 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1116 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1117 occlusion_query->context = NULL;
1120 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1122 if (context->valid)
1124 if (gl_info->supported[ARB_SYNC])
1126 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1128 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1129 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1131 event_query->context = NULL;
1134 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1136 if (!context->valid) entry->id = 0;
1137 context_destroy_fbo_entry(context, entry);
1140 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1142 if (!context->valid) entry->id = 0;
1143 context_destroy_fbo_entry(context, entry);
1146 if (context->valid)
1148 if (context->dummy_arbfp_prog)
1150 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1153 if (gl_info->supported[ARB_TIMER_QUERY])
1154 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1156 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1157 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1159 if (gl_info->supported[ARB_SYNC])
1161 for (i = 0; i < context->free_event_query_count; ++i)
1163 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1166 else if (gl_info->supported[APPLE_FENCE])
1168 for (i = 0; i < context->free_event_query_count; ++i)
1170 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1173 else if (gl_info->supported[NV_FENCE])
1175 for (i = 0; i < context->free_event_query_count; ++i)
1177 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1181 checkGLcall("context cleanup");
1184 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1185 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1186 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1188 context_restore_pixel_format(context);
1189 if (restore_ctx)
1191 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1193 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1195 ERR("Failed to disable GL context.\n");
1198 wined3d_release_dc(context->win_handle, context->hdc);
1200 if (!wglDeleteContext(context->glCtx))
1202 DWORD err = GetLastError();
1203 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1207 DWORD context_get_tls_idx(void)
1209 return wined3d_context_tls_idx;
1212 void context_set_tls_idx(DWORD idx)
1214 wined3d_context_tls_idx = idx;
1217 struct wined3d_context *context_get_current(void)
1219 return TlsGetValue(wined3d_context_tls_idx);
1222 BOOL context_set_current(struct wined3d_context *ctx)
1224 struct wined3d_context *old = context_get_current();
1226 if (old == ctx)
1228 TRACE("Already using D3D context %p.\n", ctx);
1229 return TRUE;
1232 if (old)
1234 if (old->destroyed)
1236 TRACE("Switching away from destroyed context %p.\n", old);
1237 context_destroy_gl_resources(old);
1238 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1239 HeapFree(GetProcessHeap(), 0, old);
1241 else
1243 if (wglGetCurrentContext())
1245 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1246 glFlush();
1248 old->current = 0;
1252 if (ctx)
1254 if (!ctx->valid)
1256 ERR("Trying to make invalid context %p current\n", ctx);
1257 return FALSE;
1260 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1261 if (!context_set_gl_context(ctx))
1262 return FALSE;
1263 ctx->current = 1;
1265 else if(wglGetCurrentContext())
1267 TRACE("Clearing current D3D context.\n");
1268 if (!wglMakeCurrent(NULL, NULL))
1270 DWORD err = GetLastError();
1271 ERR("Failed to clear current GL context, last error %#x.\n", err);
1272 TlsSetValue(wined3d_context_tls_idx, NULL);
1273 return FALSE;
1277 return TlsSetValue(wined3d_context_tls_idx, ctx);
1280 void context_release(struct wined3d_context *context)
1282 TRACE("Releasing context %p, level %u.\n", context, context->level);
1284 if (WARN_ON(d3d))
1286 if (!context->level)
1287 WARN("Context %p is not active.\n", context);
1288 else if (context != context_get_current())
1289 WARN("Context %p is not the current context.\n", context);
1292 if (!--context->level)
1294 if (context_restore_pixel_format(context))
1295 context->needs_set = 1;
1296 if (context->restore_ctx)
1298 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1299 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1300 context->restore_ctx = NULL;
1301 context->restore_dc = NULL;
1306 /* This is used when a context for render target A is active, but a separate context is
1307 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1308 * A to avoid breaking caller code. */
1309 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1311 if (context->current_rt != restore)
1313 context_release(context);
1314 context = context_acquire(restore->resource.device, restore);
1317 context_release(context);
1320 static void context_enter(struct wined3d_context *context)
1322 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1324 if (!context->level++)
1326 const struct wined3d_context *current_context = context_get_current();
1327 HGLRC current_gl = wglGetCurrentContext();
1329 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1331 TRACE("Another GL context (%p on device context %p) is already current.\n",
1332 current_gl, wglGetCurrentDC());
1333 context->restore_ctx = current_gl;
1334 context->restore_dc = wglGetCurrentDC();
1335 context->needs_set = 1;
1337 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1338 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1339 context->needs_set = 1;
1343 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1345 DWORD rep = context->state_table[state].representative;
1346 DWORD idx;
1347 BYTE shift;
1349 if (isStateDirty(context, rep)) return;
1351 context->dirtyArray[context->numDirtyEntries++] = rep;
1352 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1353 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1354 context->isStateDirty[idx] |= (1u << shift);
1357 /* This function takes care of wined3d pixel format selection. */
1358 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1359 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1360 BOOL auxBuffers, BOOL findCompatible)
1362 int iPixelFormat=0;
1363 unsigned int current_value;
1364 unsigned int cfg_count = device->adapter->cfg_count;
1365 unsigned int i;
1367 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1368 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1369 auxBuffers, findCompatible);
1371 current_value = 0;
1372 for (i = 0; i < cfg_count; ++i)
1374 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1375 unsigned int value;
1377 /* For now only accept RGBA formats. Perhaps some day we will
1378 * allow floating point formats for pbuffers. */
1379 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1380 continue;
1381 /* In window mode we need a window drawable format and double buffering. */
1382 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1383 continue;
1384 if (cfg->redSize < color_format->red_size)
1385 continue;
1386 if (cfg->greenSize < color_format->green_size)
1387 continue;
1388 if (cfg->blueSize < color_format->blue_size)
1389 continue;
1390 if (cfg->alphaSize < color_format->alpha_size)
1391 continue;
1392 if (cfg->depthSize < ds_format->depth_size)
1393 continue;
1394 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1395 continue;
1396 /* Check multisampling support. */
1397 if (cfg->numSamples)
1398 continue;
1400 value = 1;
1401 /* We try to locate a format which matches our requirements exactly. In case of
1402 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1403 if (cfg->depthSize == ds_format->depth_size)
1404 value += 1;
1405 if (cfg->stencilSize == ds_format->stencil_size)
1406 value += 2;
1407 if (cfg->alphaSize == color_format->alpha_size)
1408 value += 4;
1409 /* We like to have aux buffers in backbuffer mode */
1410 if (auxBuffers && cfg->auxBuffers)
1411 value += 8;
1412 if (cfg->redSize == color_format->red_size
1413 && cfg->greenSize == color_format->green_size
1414 && cfg->blueSize == color_format->blue_size)
1415 value += 16;
1417 if (value > current_value)
1419 iPixelFormat = cfg->iPixelFormat;
1420 current_value = value;
1424 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1425 if(!iPixelFormat && !findCompatible) {
1426 ERR("Can't find a suitable iPixelFormat\n");
1427 return FALSE;
1428 } else if(!iPixelFormat) {
1429 PIXELFORMATDESCRIPTOR pfd;
1431 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1432 /* PixelFormat selection */
1433 ZeroMemory(&pfd, sizeof(pfd));
1434 pfd.nSize = sizeof(pfd);
1435 pfd.nVersion = 1;
1436 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1437 pfd.iPixelType = PFD_TYPE_RGBA;
1438 pfd.cAlphaBits = color_format->alpha_size;
1439 pfd.cColorBits = color_format->red_size + color_format->green_size
1440 + color_format->blue_size + color_format->alpha_size;
1441 pfd.cDepthBits = ds_format->depth_size;
1442 pfd.cStencilBits = ds_format->stencil_size;
1443 pfd.iLayerType = PFD_MAIN_PLANE;
1445 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1446 if(!iPixelFormat) {
1447 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1448 ERR("Can't find a suitable iPixelFormat\n");
1449 return FALSE;
1453 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1454 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1455 return iPixelFormat;
1458 /* Context activation is done by the caller. */
1459 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1461 const struct wined3d_gl_info *gl_info = context->gl_info;
1462 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1464 for (i = 0; i < count; ++i)
1466 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1467 checkGLcall("glActiveTexture");
1469 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1470 checkGLcall("glBindTexture");
1472 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1474 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1475 checkGLcall("glBindTexture");
1478 if (gl_info->supported[EXT_TEXTURE3D])
1480 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1481 checkGLcall("glBindTexture");
1484 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1486 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1487 checkGLcall("glBindTexture");
1492 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1494 return gl_info->supported[ARB_DEBUG_OUTPUT]
1495 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1498 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1499 GLenum severity, GLsizei length, const char *message, void *ctx)
1501 switch (type)
1503 case GL_DEBUG_TYPE_ERROR_ARB:
1504 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1505 break;
1507 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1508 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1509 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1510 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1511 break;
1513 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1514 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1515 break;
1517 default:
1518 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1519 break;
1523 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1525 HGLRC ctx;
1526 unsigned int ctx_attrib_idx = 0;
1527 GLint ctx_attribs[7], ctx_flags = 0;
1529 if (context_debug_output_enabled(gl_info))
1530 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1531 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1532 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1533 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1534 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1535 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1536 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1537 if (ctx_flags)
1539 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1540 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1542 ctx_attribs[ctx_attrib_idx] = 0;
1544 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1546 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1548 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1549 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1550 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1551 GetLastError());
1554 return ctx;
1557 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1558 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1560 struct wined3d_device *device = swapchain->device;
1561 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1562 const struct wined3d_format *color_format;
1563 struct wined3d_context *ret;
1564 BOOL auxBuffers = FALSE;
1565 HGLRC ctx, share_ctx;
1566 int pixel_format;
1567 unsigned int s;
1568 int swap_interval;
1569 DWORD state;
1570 HDC hdc = 0;
1571 BOOL hdc_is_private = FALSE;
1573 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1575 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1576 if (!ret)
1577 return NULL;
1579 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1580 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1581 if (!ret->blit_targets)
1582 goto out;
1584 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1585 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1586 if (!ret->draw_buffers)
1587 goto out;
1589 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1590 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1591 if (!ret->fbo_key)
1592 goto out;
1594 ret->free_timestamp_query_size = 4;
1595 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1596 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1597 if (!ret->free_timestamp_queries)
1598 goto out;
1599 list_init(&ret->timestamp_queries);
1601 ret->free_occlusion_query_size = 4;
1602 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1603 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1604 if (!ret->free_occlusion_queries)
1605 goto out;
1607 list_init(&ret->occlusion_queries);
1609 ret->free_event_query_size = 4;
1610 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1611 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1612 if (!ret->free_event_queries)
1613 goto out;
1615 list_init(&ret->event_queries);
1616 list_init(&ret->fbo_list);
1617 list_init(&ret->fbo_destroy_list);
1619 if (!device->shader_backend->shader_allocate_context_data(ret))
1621 ERR("Failed to allocate shader backend context data.\n");
1622 goto out;
1624 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1626 ERR("Failed to allocate fragment pipeline context data.\n");
1627 goto out;
1630 /* Initialize the texture unit mapping to a 1:1 mapping */
1631 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1633 if (s < gl_info->limits.combined_samplers)
1635 ret->tex_unit_map[s] = s;
1636 ret->rev_tex_unit_map[s] = s;
1638 else
1640 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1641 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1645 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1647 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1649 if ((hdc = swapchain_get_backup_dc(swapchain)))
1650 hdc_is_private = TRUE;
1651 else
1653 ERR("Failed to retrieve a device context.\n");
1654 goto out;
1658 color_format = target->resource.format;
1660 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1661 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1662 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1664 auxBuffers = TRUE;
1666 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1667 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1668 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1669 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1672 /* DirectDraw supports 8bit paletted render targets and these are used by
1673 * old games like StarCraft and C&C. Most modern hardware doesn't support
1674 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1675 * conversion (ab)uses the alpha component for storing the palette index.
1676 * For this reason we require a format with 8bit alpha, so request
1677 * A8R8G8B8. */
1678 if (color_format->id == WINED3DFMT_P8_UINT)
1679 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1681 /* When "always_offscreen" is enabled, we only use the drawable for
1682 * presentation blits, and don't do any rendering to it. That means we
1683 * don't need depth or stencil buffers, and can mostly ignore the render
1684 * target format. This wouldn't necessarily be quite correct for 10bpc
1685 * display modes, but we don't currently support those.
1686 * Using the same format regardless of the color/depth/stencil targets
1687 * makes it much less likely that different wined3d instances will set
1688 * conflicting pixel formats. */
1689 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER
1690 && wined3d_settings.always_offscreen)
1692 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1693 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN);
1696 /* Try to find a pixel format which matches our requirements. */
1697 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1699 /* Try to locate a compatible format if we weren't able to find anything. */
1700 if (!pixel_format)
1702 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1703 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1706 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1707 if (!pixel_format)
1709 ERR("Can't find a suitable pixel format.\n");
1710 goto out;
1713 ret->gl_info = gl_info;
1715 context_enter(ret);
1717 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1719 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1720 context_release(ret);
1721 goto out;
1724 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1725 if (gl_info->p_wglCreateContextAttribsARB)
1727 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1728 goto out;
1730 else
1732 if (!(ctx = wglCreateContext(hdc)))
1734 ERR("Failed to create a WGL context.\n");
1735 context_release(ret);
1736 goto out;
1739 if (share_ctx && !wglShareLists(share_ctx, ctx))
1741 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1742 context_release(ret);
1743 if (!wglDeleteContext(ctx))
1744 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1745 goto out;
1749 if (!device_context_add(device, ret))
1751 ERR("Failed to add the newly created context to the context list\n");
1752 context_release(ret);
1753 if (!wglDeleteContext(ctx))
1754 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1755 goto out;
1758 ret->d3d_info = &device->adapter->d3d_info;
1759 ret->state_table = device->StateTable;
1761 /* Mark all states dirty to force a proper initialization of the states
1762 * on the first use of the context. */
1763 for (state = 0; state <= STATE_HIGHEST; ++state)
1765 if (ret->state_table[state].representative)
1766 context_invalidate_state(ret, state);
1769 ret->swapchain = swapchain;
1770 ret->current_rt = target;
1771 ret->tid = GetCurrentThreadId();
1773 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1774 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1775 ret->valid = 1;
1777 ret->glCtx = ctx;
1778 ret->win_handle = swapchain->win_handle;
1779 ret->hdc = hdc;
1780 ret->hdc_is_private = hdc_is_private;
1781 ret->hdc_has_format = TRUE;
1782 ret->pixel_format = pixel_format;
1783 ret->needs_set = 1;
1785 /* Set up the context defaults */
1786 if (!context_set_current(ret))
1788 ERR("Cannot activate context to set up defaults.\n");
1789 device_context_remove(device, ret);
1790 context_release(ret);
1791 if (!wglDeleteContext(ctx))
1792 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1793 goto out;
1796 if (context_debug_output_enabled(gl_info))
1798 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1799 if (TRACE_ON(d3d_synchronous))
1800 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1801 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1802 if (ERR_ON(d3d))
1804 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1805 GL_DONT_CARE, 0, NULL, GL_TRUE));
1807 if (FIXME_ON(d3d))
1809 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1810 GL_DONT_CARE, 0, NULL, GL_TRUE));
1811 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1812 GL_DONT_CARE, 0, NULL, GL_TRUE));
1813 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1814 GL_DONT_CARE, 0, NULL, GL_TRUE));
1816 if (WARN_ON(d3d_perf))
1818 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1819 GL_DONT_CARE, 0, NULL, GL_TRUE));
1823 switch (swapchain->desc.swap_interval)
1825 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1826 swap_interval = 0;
1827 break;
1828 case WINED3DPRESENT_INTERVAL_DEFAULT:
1829 case WINED3DPRESENT_INTERVAL_ONE:
1830 swap_interval = 1;
1831 break;
1832 case WINED3DPRESENT_INTERVAL_TWO:
1833 swap_interval = 2;
1834 break;
1835 case WINED3DPRESENT_INTERVAL_THREE:
1836 swap_interval = 3;
1837 break;
1838 case WINED3DPRESENT_INTERVAL_FOUR:
1839 swap_interval = 4;
1840 break;
1841 default:
1842 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1843 swap_interval = 1;
1846 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1848 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1849 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1850 swap_interval, ret, GetLastError());
1853 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1855 TRACE("Setting up the screen\n");
1857 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1858 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1860 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1861 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1863 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1864 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1866 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1867 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1868 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1869 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1871 if (!gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1873 GLuint vao;
1875 GL_EXTCALL(glGenVertexArrays(1, &vao));
1876 GL_EXTCALL(glBindVertexArray(vao));
1877 checkGLcall("creating VAO");
1880 if (gl_info->supported[ARB_VERTEX_BLEND])
1882 /* Direct3D always uses n-1 weights for n world matrices and uses
1883 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1884 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1885 * enabled as well. */
1886 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1887 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1889 if (gl_info->supported[NV_TEXTURE_SHADER2])
1891 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1892 * the previous texture where to source the offset from is always unit - 1.
1894 for (s = 1; s < gl_info->limits.textures; ++s)
1896 context_active_texture(ret, gl_info, s);
1897 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1898 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1899 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1902 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1904 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1905 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1906 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1907 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1908 * is ever assigned.
1910 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1911 * program and the dummy program is destroyed when the context is destroyed.
1913 static const char dummy_program[] =
1914 "!!ARBfp1.0\n"
1915 "MOV result.color, fragment.color.primary;\n"
1916 "END\n";
1917 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1918 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1919 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1922 if (gl_info->supported[ARB_POINT_SPRITE])
1924 for (s = 0; s < gl_info->limits.textures; ++s)
1926 context_active_texture(ret, gl_info, s);
1927 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1928 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1932 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1934 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1936 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1938 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1940 device->shader_backend->shader_init_context_state(ret);
1941 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1942 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1943 | (1u << WINED3D_SHADER_TYPE_GEOMETRY);
1945 /* If this happens to be the first context for the device, dummy textures
1946 * are not created yet. In that case, they will be created (and bound) by
1947 * create_dummy_textures right after this context is initialized. */
1948 if (device->dummy_texture_2d[0])
1949 bind_dummy_textures(device, ret);
1951 TRACE("Created context %p.\n", ret);
1953 return ret;
1955 out:
1956 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
1957 device->shader_backend->shader_free_context_data(ret);
1958 device->adapter->fragment_pipe->free_context_data(ret);
1959 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1960 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1961 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1962 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
1963 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1964 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1965 HeapFree(GetProcessHeap(), 0, ret);
1966 return NULL;
1969 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1971 BOOL destroy;
1973 TRACE("Destroying ctx %p\n", context);
1975 if (context->tid == GetCurrentThreadId() || !context->current)
1977 context_destroy_gl_resources(context);
1978 TlsSetValue(wined3d_context_tls_idx, NULL);
1979 destroy = TRUE;
1981 else
1983 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1984 in wined3d_adapter may go away in the meantime */
1985 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1986 *gl_info = *context->gl_info;
1987 context->gl_info = gl_info;
1988 context->destroyed = 1;
1989 destroy = FALSE;
1992 device->shader_backend->shader_free_context_data(context);
1993 device->adapter->fragment_pipe->free_context_data(context);
1994 HeapFree(GetProcessHeap(), 0, context->fbo_key);
1995 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1996 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1997 device_context_remove(device, context);
1998 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2001 /* Context activation is done by the caller. */
2002 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2004 const GLdouble projection[] =
2006 2.0 / width, 0.0, 0.0, 0.0,
2007 0.0, 2.0 / height, 0.0, 0.0,
2008 0.0, 0.0, 2.0, 0.0,
2009 -1.0, -1.0, -1.0, 1.0,
2012 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2013 checkGLcall("glMatrixMode(GL_PROJECTION)");
2014 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2015 checkGLcall("glLoadMatrixd");
2016 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2017 checkGLcall("glViewport");
2020 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2022 const struct wined3d_surface *rt = context->current_rt;
2024 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
2026 RECT window_size;
2028 GetClientRect(context->win_handle, &window_size);
2029 size->cx = window_size.right - window_size.left;
2030 size->cy = window_size.bottom - window_size.top;
2032 return;
2035 size->cx = rt->resource.width;
2036 size->cy = rt->resource.height;
2039 /*****************************************************************************
2040 * SetupForBlit
2042 * Sets up a context for DirectDraw blitting.
2043 * All texture units are disabled, texture unit 0 is set as current unit
2044 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2045 * color writing enabled for all channels
2046 * register combiners disabled, shaders disabled
2047 * world matrix is set to identity, texture matrix 0 too
2048 * projection matrix is setup for drawing screen coordinates
2050 * Params:
2051 * This: Device to activate the context for
2052 * context: Context to setup
2054 *****************************************************************************/
2055 /* Context activation is done by the caller. */
2056 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2058 int i;
2059 const struct wined3d_gl_info *gl_info = context->gl_info;
2060 DWORD sampler;
2061 SIZE rt_size;
2063 TRACE("Setting up context %p for blitting\n", context);
2065 context_get_rt_size(context, &rt_size);
2067 if (context->last_was_blit)
2069 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2071 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2072 context->blit_w = rt_size.cx;
2073 context->blit_h = rt_size.cy;
2074 /* No need to dirtify here, the states are still dirtified because
2075 * they weren't applied since the last SetupForBlit() call. */
2077 TRACE("Context is already set up for blitting, nothing to do\n");
2078 return;
2080 context->last_was_blit = TRUE;
2082 /* Disable all textures. The caller can then bind a texture it wants to blit
2083 * from
2085 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2086 * function texture unit. No need to care for higher samplers
2088 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2090 sampler = context->rev_tex_unit_map[i];
2091 context_active_texture(context, gl_info, i);
2093 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2095 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2096 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2098 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2099 checkGLcall("glDisable GL_TEXTURE_3D");
2100 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2102 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2103 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2105 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2106 checkGLcall("glDisable GL_TEXTURE_2D");
2108 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2109 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2111 if (sampler != WINED3D_UNMAPPED_STAGE)
2113 if (sampler < MAX_TEXTURES)
2114 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2115 context_invalidate_state(context, STATE_SAMPLER(sampler));
2118 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2119 GL_EXTCALL(glBindSampler(0, 0));
2120 context_active_texture(context, gl_info, 0);
2122 sampler = context->rev_tex_unit_map[0];
2124 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2126 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2127 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2129 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2130 checkGLcall("glDisable GL_TEXTURE_3D");
2131 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2133 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2134 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2136 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2137 checkGLcall("glDisable GL_TEXTURE_2D");
2139 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2141 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2142 checkGLcall("glMatrixMode(GL_TEXTURE)");
2143 gl_info->gl_ops.gl.p_glLoadIdentity();
2144 checkGLcall("glLoadIdentity()");
2146 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2148 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2149 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2150 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2153 if (sampler != WINED3D_UNMAPPED_STAGE)
2155 if (sampler < MAX_TEXTURES)
2157 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2158 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2160 context_invalidate_state(context, STATE_SAMPLER(sampler));
2163 /* Other misc states */
2164 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2165 checkGLcall("glDisable(GL_ALPHA_TEST)");
2166 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2167 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2168 checkGLcall("glDisable GL_LIGHTING");
2169 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2170 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2171 checkGLcall("glDisable GL_DEPTH_TEST");
2172 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2173 glDisableWINE(GL_FOG);
2174 checkGLcall("glDisable GL_FOG");
2175 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2176 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2177 checkGLcall("glDisable GL_BLEND");
2178 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2179 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2180 checkGLcall("glDisable GL_CULL_FACE");
2181 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2182 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2183 checkGLcall("glDisable GL_STENCIL_TEST");
2184 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2185 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2186 checkGLcall("glDisable GL_SCISSOR_TEST");
2187 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2188 if (gl_info->supported[ARB_POINT_SPRITE])
2190 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2191 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2192 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2194 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2195 checkGLcall("glColorMask");
2196 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2197 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2198 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2199 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2200 if (gl_info->supported[EXT_SECONDARY_COLOR])
2202 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2203 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2204 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2207 /* Setup transforms */
2208 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2209 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2210 gl_info->gl_ops.gl.p_glLoadIdentity();
2211 checkGLcall("glLoadIdentity()");
2212 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2214 context->last_was_rhw = TRUE;
2215 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2217 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2218 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2219 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2220 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2221 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2222 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2223 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2225 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2227 /* Disable shaders */
2228 device->shader_backend->shader_disable(device->shader_priv, context);
2230 context->blit_w = rt_size.cx;
2231 context->blit_h = rt_size.cy;
2232 context_invalidate_state(context, STATE_VIEWPORT);
2233 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2236 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2238 return rt_mask & (1u << 31);
2241 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2243 return rt_mask & ~(1u << 31);
2246 /* Context activation is done by the caller. */
2247 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2249 const struct wined3d_gl_info *gl_info = context->gl_info;
2251 if (!rt_mask)
2253 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2254 checkGLcall("glDrawBuffer()");
2256 else if (is_rt_mask_onscreen(rt_mask))
2258 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2259 checkGLcall("glDrawBuffer()");
2261 else
2263 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2265 unsigned int i = 0;
2267 while (rt_mask)
2269 if (rt_mask & 1)
2270 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2271 else
2272 context->draw_buffers[i] = GL_NONE;
2274 rt_mask >>= 1;
2275 ++i;
2278 if (gl_info->supported[ARB_DRAW_BUFFERS])
2280 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2281 checkGLcall("glDrawBuffers()");
2283 else
2285 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2286 checkGLcall("glDrawBuffer()");
2289 else
2291 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2296 /* Context activation is done by the caller. */
2297 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2299 const struct wined3d_gl_info *gl_info = context->gl_info;
2300 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2301 DWORD new_mask = context_generate_rt_mask(buffer);
2303 if (new_mask == *current_mask)
2304 return;
2306 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2307 checkGLcall("glDrawBuffer()");
2309 *current_mask = new_mask;
2312 /* Context activation is done by the caller. */
2313 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2315 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2316 checkGLcall("glActiveTexture");
2317 context->active_texture = unit;
2320 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2322 const struct wined3d_gl_info *gl_info = context->gl_info;
2323 DWORD unit = context->active_texture;
2324 DWORD old_texture_type = context->texture_type[unit];
2326 if (name)
2328 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2329 checkGLcall("glBindTexture");
2331 else
2333 target = GL_NONE;
2336 if (old_texture_type != target)
2338 const struct wined3d_device *device = context->swapchain->device;
2340 switch (old_texture_type)
2342 case GL_NONE:
2343 /* nothing to do */
2344 break;
2345 case GL_TEXTURE_2D:
2346 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2347 checkGLcall("glBindTexture");
2348 break;
2349 case GL_TEXTURE_RECTANGLE_ARB:
2350 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2351 checkGLcall("glBindTexture");
2352 break;
2353 case GL_TEXTURE_CUBE_MAP:
2354 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2355 checkGLcall("glBindTexture");
2356 break;
2357 case GL_TEXTURE_3D:
2358 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2359 checkGLcall("glBindTexture");
2360 break;
2361 default:
2362 ERR("Unexpected texture target %#x\n", old_texture_type);
2365 context->texture_type[unit] = target;
2369 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2371 if (context->render_offscreen == offscreen) return;
2373 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2374 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2375 context_invalidate_state(context, STATE_VIEWPORT);
2376 context_invalidate_state(context, STATE_SCISSORRECT);
2377 context_invalidate_state(context, STATE_FRONTFACE);
2378 context->render_offscreen = offscreen;
2381 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2382 const struct wined3d_format *required)
2384 if (existing == required)
2385 return TRUE;
2386 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2387 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2388 return FALSE;
2389 if (existing->depth_size < required->depth_size)
2390 return FALSE;
2391 /* If stencil bits are used the exact amount is required - otherwise
2392 * wrapping won't work correctly. */
2393 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2394 return FALSE;
2395 return TRUE;
2398 /* Context activation is done by the caller. */
2399 static void context_validate_onscreen_formats(struct wined3d_context *context,
2400 const struct wined3d_rendertarget_view *depth_stencil)
2402 /* Onscreen surfaces are always in a swapchain */
2403 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2405 if (context->render_offscreen || !depth_stencil) return;
2406 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2408 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2409 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2410 * format. */
2411 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2413 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2414 surface_load_location(context->current_rt, context, WINED3D_LOCATION_TEXTURE_RGB);
2415 swapchain->render_to_fbo = TRUE;
2416 swapchain_update_draw_bindings(swapchain);
2417 context_set_render_offscreen(context, TRUE);
2420 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2422 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2423 return 0;
2424 else if (rt->container->swapchain)
2425 return context_generate_rt_mask_from_surface(rt);
2426 else
2427 return context_generate_rt_mask(device->offscreenBuffer);
2430 /* Context activation is done by the caller. */
2431 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2433 struct wined3d_surface *rt = context->current_rt;
2434 DWORD rt_mask, *cur_mask;
2436 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2438 context_validate_onscreen_formats(context, NULL);
2440 if (context->render_offscreen)
2442 wined3d_texture_load(rt->container, context, FALSE);
2444 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2445 if (rt->resource.format->id != WINED3DFMT_NULL)
2446 rt_mask = 1;
2447 else
2448 rt_mask = 0;
2450 else
2452 context->current_fbo = NULL;
2453 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2454 rt_mask = context_generate_rt_mask_from_surface(rt);
2457 else
2459 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2462 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2464 if (rt_mask != *cur_mask)
2466 context_apply_draw_buffers(context, rt_mask);
2467 *cur_mask = rt_mask;
2470 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2472 context_check_fbo_status(context, GL_FRAMEBUFFER);
2475 SetupForBlit(device, context);
2476 context_invalidate_state(context, STATE_FRAMEBUFFER);
2479 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2480 const struct wined3d_rendertarget_view *ds)
2482 unsigned int i;
2484 if (ds) return TRUE;
2486 for (i = 0; i < rt_count; ++i)
2488 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2489 return TRUE;
2492 WARN("Invalid render target config, need at least one attachment.\n");
2493 return FALSE;
2496 /* Context activation is done by the caller. */
2497 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2498 UINT rt_count, const struct wined3d_fb_state *fb)
2500 struct wined3d_rendertarget_view **rts = fb->render_targets;
2501 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2502 const struct wined3d_gl_info *gl_info = context->gl_info;
2503 DWORD rt_mask = 0, *cur_mask;
2504 UINT i;
2506 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2507 || rt_count != context->gl_info->limits.buffers)
2509 if (!context_validate_rt_config(rt_count, rts, dsv))
2510 return FALSE;
2512 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2514 context_validate_onscreen_formats(context, dsv);
2516 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2518 for (i = 0; i < rt_count; ++i)
2520 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2521 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2522 rt_mask |= (1u << i);
2524 while (i < context->gl_info->limits.buffers)
2526 context->blit_targets[i] = NULL;
2527 ++i;
2529 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2530 wined3d_rendertarget_view_get_surface(dsv),
2531 rt_count ? rts[0]->resource->draw_binding : 0,
2532 dsv ? dsv->resource->draw_binding : 0);
2534 else
2536 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2537 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2538 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2541 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2542 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2543 * state management allows this */
2544 context_invalidate_state(context, STATE_FRAMEBUFFER);
2546 else
2548 rt_mask = context_generate_rt_mask_no_fbo(device,
2549 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2552 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2553 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2555 for (i = 0; i < rt_count; ++i)
2557 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2558 rt_mask |= (1u << i);
2561 else
2563 rt_mask = context_generate_rt_mask_no_fbo(device,
2564 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2567 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2569 if (rt_mask != *cur_mask)
2571 context_apply_draw_buffers(context, rt_mask);
2572 *cur_mask = rt_mask;
2573 context_invalidate_state(context, STATE_FRAMEBUFFER);
2576 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2578 context_check_fbo_status(context, GL_FRAMEBUFFER);
2581 if (context->last_was_blit)
2582 context->last_was_blit = FALSE;
2584 /* Blending and clearing should be orthogonal, but tests on the nvidia
2585 * driver show that disabling blending when clearing improves the clearing
2586 * performance incredibly. */
2587 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2588 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2589 if (gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2591 if (!(context->d3d_info->wined3d_creation_flags & WINED3D_SRGB_READ_WRITE_CONTROL)
2592 || device->state.render_states[WINED3D_RS_SRGBWRITEENABLE])
2593 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2594 else
2595 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2596 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2598 checkGLcall("setting up state for clear");
2600 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2601 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2602 context_invalidate_state(context, STATE_SCISSORRECT);
2604 return TRUE;
2607 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2609 const struct wined3d_state *state = &device->state;
2610 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2611 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2612 DWORD rt_mask, rt_mask_bits;
2613 unsigned int i;
2615 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2616 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2617 else if (!context->render_offscreen)
2618 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2620 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2621 rt_mask &= context->d3d_info->valid_rt_mask;
2622 rt_mask_bits = rt_mask;
2623 i = 0;
2624 while (rt_mask_bits)
2626 rt_mask_bits &= ~(1u << i);
2627 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2628 rt_mask &= ~(1u << i);
2630 i++;
2633 return rt_mask;
2636 /* Context activation is done by the caller. */
2637 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2639 const struct wined3d_device *device = context->swapchain->device;
2640 const struct wined3d_fb_state *fb = state->fb;
2641 DWORD rt_mask = find_draw_buffers_mask(context, device);
2642 DWORD *cur_mask;
2644 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2646 if (!context->render_offscreen)
2648 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2649 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2651 else
2653 unsigned int i;
2655 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2657 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2659 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2660 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2661 fb->render_targets[0]->resource->draw_binding,
2662 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2666 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2667 if (rt_mask != *cur_mask)
2669 context_apply_draw_buffers(context, rt_mask);
2670 *cur_mask = rt_mask;
2674 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2676 DWORD i = context->rev_tex_unit_map[unit];
2677 DWORD j = context->tex_unit_map[stage];
2679 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2680 context->tex_unit_map[stage] = unit;
2681 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2682 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2684 context->rev_tex_unit_map[unit] = stage;
2685 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2686 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2689 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2691 DWORD i;
2693 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2694 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2697 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2698 const struct wined3d_state *state)
2700 UINT i, start, end;
2702 context->fixed_function_usage_map = 0;
2703 for (i = 0; i < MAX_TEXTURES; ++i)
2705 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2706 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2707 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2708 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2709 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2710 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2711 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2712 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2714 /* Not used, and disable higher stages. */
2715 if (color_op == WINED3D_TOP_DISABLE)
2716 break;
2718 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2719 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2720 || ((color_arg3 == WINED3DTA_TEXTURE)
2721 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2722 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2723 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2724 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2725 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2726 context->fixed_function_usage_map |= (1u << i);
2728 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2729 && i < MAX_TEXTURES - 1)
2730 context->fixed_function_usage_map |= (1u << (i + 1));
2733 if (i < context->lowest_disabled_stage)
2735 start = i;
2736 end = context->lowest_disabled_stage;
2738 else
2740 start = context->lowest_disabled_stage;
2741 end = i;
2744 context->lowest_disabled_stage = i;
2745 for (i = start + 1; i < end; ++i)
2747 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2751 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2752 const struct wined3d_state *state)
2754 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2755 const struct wined3d_gl_info *gl_info = context->gl_info;
2756 unsigned int i, tex;
2757 WORD ffu_map;
2759 context_update_fixed_function_usage_map(context, state);
2761 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2762 return;
2764 ffu_map = context->fixed_function_usage_map;
2766 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2767 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2769 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2771 if (!(ffu_map & 1))
2772 continue;
2774 if (context->tex_unit_map[i] != i)
2776 context_map_stage(context, i, i);
2777 context_invalidate_state(context, STATE_SAMPLER(i));
2778 context_invalidate_texture_stage(context, i);
2781 return;
2784 /* Now work out the mapping */
2785 tex = 0;
2786 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2788 if (!(ffu_map & 1))
2789 continue;
2791 if (context->tex_unit_map[i] != tex)
2793 context_map_stage(context, i, tex);
2794 context_invalidate_state(context, STATE_SAMPLER(i));
2795 context_invalidate_texture_stage(context, i);
2798 ++tex;
2802 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2804 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2805 const struct wined3d_gl_info *gl_info = context->gl_info;
2806 const struct wined3d_shader_resource_info *resource_info =
2807 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2808 unsigned int i;
2810 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2811 return;
2813 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2815 if (resource_info[i].type && context->tex_unit_map[i] != i)
2817 context_map_stage(context, i, i);
2818 context_invalidate_state(context, STATE_SAMPLER(i));
2819 if (i < d3d_info->limits.ffp_blend_stages)
2820 context_invalidate_texture_stage(context, i);
2825 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2826 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2828 DWORD current_mapping = context->rev_tex_unit_map[unit];
2830 /* Not currently used */
2831 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2832 return TRUE;
2834 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2836 /* Used by a fragment sampler */
2838 if (!ps_resource_info)
2840 /* No pixel shader, check fixed function */
2841 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2844 /* Pixel shader, check the shader's sampler map */
2845 return !ps_resource_info[current_mapping].type;
2848 return TRUE;
2851 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2853 const struct wined3d_shader_resource_info *vs_resource_info =
2854 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2855 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2856 const struct wined3d_gl_info *gl_info = context->gl_info;
2857 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2858 int i;
2860 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2861 return;
2863 /* Note that we only care if a resource is used or not, not the
2864 * resource's specific type. Otherwise we'd need to call
2865 * shader_update_samplers() here for 1.x pixelshaders. */
2866 if (ps)
2867 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2869 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2871 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2872 if (vs_resource_info[i].type)
2874 while (start >= 0)
2876 if (context_unit_free_for_vs(context, ps_resource_info, start))
2878 if (context->tex_unit_map[vsampler_idx] != start)
2880 context_map_stage(context, vsampler_idx, start);
2881 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2884 --start;
2885 break;
2888 --start;
2890 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
2891 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
2896 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2898 BOOL vs = use_vs(state);
2899 BOOL ps = use_ps(state);
2901 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
2902 * need a 1:1 map at the moment.
2903 * When the mapping of a stage is changed, sampler and ALL texture stage
2904 * states have to be reset. */
2906 if (ps)
2907 context_map_psamplers(context, state);
2908 else
2909 context_map_fixed_function_samplers(context, state);
2911 if (vs)
2912 context_map_vsamplers(context, ps, state);
2915 /* Context activation is done by the caller. */
2916 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2918 const struct wined3d_device *device = context->swapchain->device;
2919 DWORD rt_mask, *cur_mask;
2921 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2923 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2924 rt_mask = find_draw_buffers_mask(context, device);
2925 if (rt_mask != *cur_mask)
2927 context_apply_draw_buffers(context, rt_mask);
2928 *cur_mask = rt_mask;
2932 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2934 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2935 *regnum = WINED3D_FFP_POSITION;
2936 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2937 *regnum = WINED3D_FFP_BLENDWEIGHT;
2938 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2939 *regnum = WINED3D_FFP_BLENDINDICES;
2940 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2941 *regnum = WINED3D_FFP_NORMAL;
2942 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2943 *regnum = WINED3D_FFP_PSIZE;
2944 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2945 *regnum = WINED3D_FFP_DIFFUSE;
2946 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2947 *regnum = WINED3D_FFP_SPECULAR;
2948 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2949 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2950 else
2952 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2953 *regnum = ~0U;
2954 return FALSE;
2957 return TRUE;
2960 /* Context activation is done by the caller. */
2961 void context_stream_info_from_declaration(struct wined3d_context *context,
2962 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2964 /* We need to deal with frequency data! */
2965 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2966 BOOL use_vshader = use_vs(state);
2967 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2968 unsigned int i;
2970 stream_info->use_map = 0;
2971 stream_info->swizzle_map = 0;
2972 stream_info->position_transformed = declaration->position_transformed;
2974 /* Translate the declaration into strided data. */
2975 for (i = 0; i < declaration->element_count; ++i)
2977 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2978 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2979 BOOL stride_used;
2980 unsigned int idx;
2982 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2983 element, i + 1, declaration->element_count);
2985 if (!stream->buffer)
2986 continue;
2988 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2990 if (use_vshader)
2992 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2994 stride_used = FALSE;
2996 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2998 /* TODO: Assuming vertexdeclarations are usually used with the
2999 * same or a similar shader, it might be worth it to store the
3000 * last used output slot and try that one first. */
3001 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3002 element->usage, element->usage_idx, &idx);
3004 else
3006 idx = element->output_slot;
3007 stride_used = TRUE;
3010 else
3012 if (!generic_attributes && !element->ffp_valid)
3014 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3015 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3016 stride_used = FALSE;
3018 else
3020 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3024 if (stride_used)
3026 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3027 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3028 use_vshader ? "shader": "fixed function", idx,
3029 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3030 element->offset, stream->stride, debug_d3dformat(element->format->id),
3031 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3033 stream_info->elements[idx].format = element->format;
3034 stream_info->elements[idx].data.buffer_object = 0;
3035 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3036 stream_info->elements[idx].stride = stream->stride;
3037 stream_info->elements[idx].stream_idx = element->input_slot;
3038 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3040 stream_info->elements[idx].divisor = 1;
3042 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3044 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3045 if (!element->instance_data_step_rate)
3046 FIXME("Instance step rate 0 not implemented.\n");
3048 else
3050 stream_info->elements[idx].divisor = 0;
3053 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3054 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3056 stream_info->swizzle_map |= 1u << idx;
3058 stream_info->use_map |= 1u << idx;
3063 /* Context activation is done by the caller. */
3064 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3066 const struct wined3d_gl_info *gl_info = context->gl_info;
3067 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3068 struct wined3d_stream_info *stream_info = &context->stream_info;
3069 DWORD prev_all_vbo = stream_info->all_vbo;
3070 unsigned int i;
3071 WORD map;
3073 context_stream_info_from_declaration(context, state, stream_info);
3075 stream_info->all_vbo = 1;
3076 context->num_buffer_queries = 0;
3077 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3079 struct wined3d_stream_info_element *element;
3080 struct wined3d_bo_address data;
3081 struct wined3d_buffer *buffer;
3083 if (!(map & 1))
3084 continue;
3086 element = &stream_info->elements[i];
3087 buffer = state->streams[element->stream_idx].buffer;
3089 /* We can't use VBOs if the base vertex index is negative. OpenGL
3090 * doesn't accept negative offsets (or rather offsets bigger than the
3091 * VBO, because the pointer is unsigned), so use system memory
3092 * sources. In most sane cases the pointer - offset will still be > 0,
3093 * otherwise it will wrap around to some big value. Hope that with the
3094 * indices the driver wraps it back internally. If not,
3095 * drawStridedSlow is needed, including a vertex buffer path. */
3096 if (state->load_base_vertex_index < 0)
3098 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3099 state->load_base_vertex_index);
3100 element->data.buffer_object = 0;
3101 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
3102 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3103 FIXME("System memory vertex data load offset is negative!\n");
3105 else
3107 buffer_internal_preload(buffer, context, state);
3108 buffer_get_memory(buffer, context, &data);
3109 element->data.buffer_object = data.buffer_object;
3110 element->data.addr += (ULONG_PTR)data.addr;
3113 if (!element->data.buffer_object)
3114 stream_info->all_vbo = 0;
3116 if (buffer->query)
3117 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3119 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3122 if (use_vs(state))
3124 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
3126 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
3127 context->use_immediate_mode_draw = TRUE;
3129 else
3131 context->use_immediate_mode_draw = FALSE;
3134 else
3136 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3137 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3138 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR));
3140 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3141 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3142 context->use_immediate_mode_draw = TRUE;
3143 else
3144 context->use_immediate_mode_draw = FALSE;
3147 if (prev_all_vbo != stream_info->all_vbo)
3148 context_invalidate_state(context, STATE_INDEXBUFFER);
3151 /* Context activation is done by the caller. */
3152 static void context_preload_texture(struct wined3d_context *context,
3153 const struct wined3d_state *state, unsigned int idx)
3155 struct wined3d_texture *texture;
3157 if (!(texture = state->textures[idx]))
3158 return;
3160 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3163 /* Context activation is done by the caller. */
3164 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3166 unsigned int i;
3168 if (use_vs(state))
3170 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3172 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3173 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3177 if (use_ps(state))
3179 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3181 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3182 context_preload_texture(context, state, i);
3185 else
3187 WORD ffu_map = context->fixed_function_usage_map;
3189 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3191 if (ffu_map & 1)
3192 context_preload_texture(context, state, i);
3197 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3199 struct wined3d_shader_sampler_map_entry *entry;
3200 struct wined3d_shader_resource_view *view;
3201 struct wined3d_shader *shader;
3202 unsigned int i, j;
3204 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3206 if (!(shader = state->shader[i]))
3207 continue;
3209 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3211 if (state->cb[i][j])
3212 buffer_internal_preload(state->cb[i][j], context, state);
3215 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3217 entry = &shader->reg_maps.sampler_map.entries[j];
3219 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3221 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3222 continue;
3225 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3226 buffer_internal_preload(buffer_from_resource(view->resource), context, state);
3227 else
3228 wined3d_texture_load(wined3d_texture_from_resource(view->resource), context, FALSE);
3233 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3235 const struct wined3d_device *device = context->swapchain->device;
3236 const struct wined3d_gl_info *gl_info = context->gl_info;
3237 struct wined3d_shader_sampler_map_entry *entry;
3238 struct wined3d_shader_resource_view *view;
3239 struct wined3d_sampler *sampler;
3240 struct wined3d_texture *texture;
3241 struct wined3d_shader *shader;
3242 unsigned int i, j, count;
3243 GLuint sampler_name;
3245 static const struct
3247 enum wined3d_shader_type type;
3248 unsigned int base_idx;
3249 unsigned int count;
3251 shader_types[] =
3253 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3254 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3257 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3259 if (!(shader = state->shader[shader_types[i].type]))
3260 continue;
3262 count = shader->reg_maps.sampler_map.count;
3263 if (count > shader_types[i].count)
3265 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3266 shader, count, shader_types[i].count);
3267 count = shader_types[i].count;
3270 for (j = 0; j < count; ++j)
3272 entry = &shader->reg_maps.sampler_map.entries[j];
3274 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3276 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3277 continue;
3280 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3282 FIXME("Buffer shader resources not supported.\n");
3283 continue;
3286 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3288 sampler_name = device->default_sampler;
3290 else if ((sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3292 sampler_name = sampler->name;
3294 else
3296 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3297 continue;
3300 texture = wined3d_texture_from_resource(view->resource);
3301 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3302 wined3d_texture_bind(texture, context, FALSE);
3304 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler_name));
3305 checkGLcall("glBindSampler");
3310 /* Context activation is done by the caller. */
3311 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3313 const struct wined3d_state *state = &device->state;
3314 const struct StateEntry *state_table = context->state_table;
3315 const struct wined3d_fb_state *fb = state->fb;
3316 unsigned int i;
3317 WORD map;
3319 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3320 fb->render_targets, fb->depth_stencil))
3321 return FALSE;
3323 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3325 context_validate_onscreen_formats(context, fb->depth_stencil);
3328 /* Preload resources before FBO setup. Texture preload in particular may
3329 * result in changes to the current FBO, due to using e.g. FBO blits for
3330 * updating a resource location. */
3331 context_update_tex_unit_map(context, state);
3332 context_preload_textures(context, state);
3333 context_load_shader_resources(context, state);
3334 /* TODO: Right now the dependency on the vertex shader is necessary
3335 * since context_stream_info_from_declaration depends on the reg_maps of
3336 * the current VS but maybe it's possible to relax the coupling in some
3337 * situations at least. */
3338 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3339 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3341 context_update_stream_info(context, state);
3343 else
3345 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3347 if (map & 1)
3348 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3351 if (state->index_buffer)
3353 if (context->stream_info.all_vbo)
3354 buffer_internal_preload(state->index_buffer, context, state);
3355 else
3356 buffer_get_sysmem(state->index_buffer, context);
3359 for (i = 0; i < context->numDirtyEntries; ++i)
3361 DWORD rep = context->dirtyArray[i];
3362 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3363 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3364 context->isStateDirty[idx] &= ~(1u << shift);
3365 state_table[rep].apply(context, state, rep);
3368 if (context->shader_update_mask)
3370 device->shader_backend->shader_select(device->shader_priv, context, state);
3371 context->shader_update_mask = 0;
3374 if (context->constant_update_mask)
3376 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3377 context->constant_update_mask = 0;
3380 if (context->update_shader_resource_bindings)
3382 context_bind_shader_resources(context, state);
3383 context->update_shader_resource_bindings = 0;
3386 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3388 context_check_fbo_status(context, GL_FRAMEBUFFER);
3391 context->numDirtyEntries = 0; /* This makes the whole list clean */
3392 context->last_was_blit = FALSE;
3394 return TRUE;
3397 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3399 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3401 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3402 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3404 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3405 * the alpha blend state changes with different render target formats. */
3406 if (!context->current_rt)
3408 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3410 else
3412 const struct wined3d_format *old = context->current_rt->resource.format;
3413 const struct wined3d_format *new = target->resource.format;
3415 if (old->id != new->id)
3417 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3418 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3419 || !(target->container->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3420 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3422 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3423 if ((context->current_rt->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3424 != (target->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3425 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3428 /* When switching away from an offscreen render target, and we're not
3429 * using FBOs, we have to read the drawable into the texture. This is
3430 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3431 * There are some things that need care though. PreLoad needs a GL context,
3432 * and FindContext is called before the context is activated. It also
3433 * has to be called with the old rendertarget active, otherwise a
3434 * wrong drawable is read. */
3435 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3436 && old_render_offscreen && context->current_rt != target)
3438 struct wined3d_texture *texture = context->current_rt->container;
3440 /* Read the back buffer of the old drawable into the destination texture. */
3441 if (texture->texture_srgb.name)
3442 wined3d_texture_load(texture, context, TRUE);
3443 wined3d_texture_load(texture, context, FALSE);
3444 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3448 context->current_rt = target;
3449 context_set_render_offscreen(context, render_offscreen);
3452 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3454 struct wined3d_context *current_context = context_get_current();
3455 struct wined3d_context *context;
3457 TRACE("device %p, target %p.\n", device, target);
3459 if (current_context && current_context->destroyed)
3460 current_context = NULL;
3462 if (!target)
3464 if (current_context
3465 && current_context->current_rt
3466 && current_context->swapchain->device == device)
3468 target = current_context->current_rt;
3470 else
3472 struct wined3d_swapchain *swapchain = device->swapchains[0];
3473 if (swapchain->back_buffers)
3474 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3475 else
3476 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3480 if (current_context && current_context->current_rt == target)
3482 context = current_context;
3484 else if (target->container->swapchain)
3486 TRACE("Rendering onscreen.\n");
3488 context = swapchain_get_context(target->container->swapchain);
3490 else
3492 TRACE("Rendering offscreen.\n");
3494 /* Stay with the current context if possible. Otherwise use the
3495 * context for the primary swapchain. */
3496 if (current_context && current_context->swapchain->device == device)
3497 context = current_context;
3498 else
3499 context = swapchain_get_context(device->swapchains[0]);
3502 context_enter(context);
3503 context_update_window(context);
3504 context_setup_target(context, target);
3505 if (!context->valid) return context;
3507 if (context != current_context)
3509 if (!context_set_current(context))
3510 ERR("Failed to activate the new context.\n");
3512 else if (context->needs_set)
3514 context_set_gl_context(context);
3517 return context;