wined3d: Store renderbuffer IDs in struct wined3d_texture.
[wine.git] / dlls / wined3d / context.c
blob94522ba80e2b193b7a41176aa8a0f2d366ee6d85
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 flags, GLuint rb)
108 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (flags & WINED3D_FBO_ENTRY_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 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 flags, resource->object);
137 else
139 if (flags & WINED3D_FBO_ENTRY_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 (flags & WINED3D_FBO_ENTRY_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 (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
157 checkGLcall("glFramebufferTexture2D()");
160 if (!(flags & WINED3D_FBO_ENTRY_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_resource(struct wined3d_resource *resource)
340 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
342 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
343 return 0;
346 return (1u << 31) | wined3d_texture_get_gl_buffer(wined3d_texture_from_resource(resource));
349 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
350 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
351 DWORD location)
353 if (!surface)
355 key->objects[idx].object = 0;
356 key->objects[idx].level = key->objects[idx].target = 0;
358 else if (surface->current_renderbuffer)
360 key->objects[idx].object = surface->current_renderbuffer->id;
361 key->objects[idx].level = key->objects[idx].target = 0;
362 key->rb_namespace |= 1 << idx;
364 else
366 switch (location)
368 case WINED3D_LOCATION_TEXTURE_RGB:
369 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
370 key->objects[idx].level = surface->texture_level;
371 key->objects[idx].target = surface->texture_target;
372 break;
374 case WINED3D_LOCATION_TEXTURE_SRGB:
375 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
376 key->objects[idx].level = surface->texture_level;
377 key->objects[idx].target = surface->texture_target;
378 break;
380 case WINED3D_LOCATION_RB_MULTISAMPLE:
381 key->objects[idx].object = surface->container->rb_multisample;
382 key->objects[idx].level = key->objects[idx].target = 0;
383 key->rb_namespace |= 1 << idx;
384 break;
386 case WINED3D_LOCATION_RB_RESOLVED:
387 key->objects[idx].object = surface->container->rb_resolved;
388 key->objects[idx].level = key->objects[idx].target = 0;
389 key->rb_namespace |= 1 << idx;
390 break;
395 static void context_generate_fbo_key(const struct wined3d_context *context,
396 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
397 struct wined3d_surface *depth_stencil, DWORD color_location,
398 DWORD ds_location)
400 UINT i;
402 key->rb_namespace = 0;
403 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
405 for (i = 0; i < context->gl_info->limits.buffers; ++i)
406 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
409 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
410 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
411 DWORD color_location, DWORD ds_location)
413 const struct wined3d_gl_info *gl_info = context->gl_info;
414 struct fbo_entry *entry;
415 UINT object_count = gl_info->limits.buffers + 1;
417 entry = HeapAlloc(GetProcessHeap(), 0,
418 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
419 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
420 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
421 entry->flags = 0;
422 if (depth_stencil)
424 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
425 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
426 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
427 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
429 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
430 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
431 checkGLcall("glGenFramebuffers()");
432 TRACE("Created FBO %u.\n", entry->id);
434 return entry;
437 /* Context activation is done by the caller. */
438 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
439 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
440 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
442 const struct wined3d_gl_info *gl_info = context->gl_info;
444 context_bind_fbo(context, target, entry->id);
445 context_clean_fbo_attachments(gl_info, target);
447 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
448 entry->flags = 0;
449 if (depth_stencil)
451 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
452 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
453 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
454 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
458 /* Context activation is done by the caller. */
459 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
461 if (entry->id)
463 TRACE("Destroy FBO %u.\n", entry->id);
464 context_destroy_fbo(context, entry->id);
466 --context->fbo_entry_count;
467 list_remove(&entry->entry);
468 HeapFree(GetProcessHeap(), 0, entry);
471 /* Context activation is done by the caller. */
472 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
473 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
474 DWORD color_location, DWORD ds_location)
476 const struct wined3d_gl_info *gl_info = context->gl_info;
477 unsigned int object_count = gl_info->limits.buffers + 1;
478 struct wined3d_texture *rt_texture, *ds_texture;
479 struct fbo_entry *entry;
480 unsigned int i;
482 if (depth_stencil && render_targets[0])
484 rt_texture = render_targets[0]->container;
485 ds_texture = depth_stencil->container;
487 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
488 < wined3d_texture_get_level_width(rt_texture, render_targets[0]->texture_level)
489 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
490 < wined3d_texture_get_level_height(rt_texture, render_targets[0]->texture_level))
492 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
493 depth_stencil = NULL;
495 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
496 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
498 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
499 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
500 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
501 depth_stencil = NULL;
503 else
504 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
507 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
508 ds_location);
510 if (TRACE_ON(d3d))
512 TRACE("Dumping FBO attachments:\n");
513 for (i = 0; i < gl_info->limits.buffers; ++i)
515 if (render_targets[i])
517 rt_texture = render_targets[i]->container;
518 TRACE(" Color attachment %u: %p format %s, %s %u, %ux%u, %u samples.\n",
519 i, render_targets[i], debug_d3dformat(rt_texture->resource.format->id),
520 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : "texure",
521 context->fbo_key->objects[i + 1].object,
522 wined3d_texture_get_level_pow2_width(rt_texture, render_targets[i]->texture_level),
523 wined3d_texture_get_level_pow2_height(rt_texture, render_targets[i]->texture_level),
524 rt_texture->resource.multisample_type);
527 if (depth_stencil)
529 ds_texture = depth_stencil->container;
530 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
531 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
532 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texure",
533 context->fbo_key->objects[0].object,
534 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
535 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
536 ds_texture->resource.multisample_type);
540 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
542 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
543 continue;
545 list_remove(&entry->entry);
546 list_add_head(&context->fbo_list, &entry->entry);
547 return entry;
550 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
552 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
553 list_add_head(&context->fbo_list, &entry->entry);
554 ++context->fbo_entry_count;
556 else
558 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
559 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
560 list_remove(&entry->entry);
561 list_add_head(&context->fbo_list, &entry->entry);
564 return entry;
567 /* Context activation is done by the caller. */
568 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
570 const struct wined3d_gl_info *gl_info = context->gl_info;
571 unsigned int i;
572 GLuint read_binding, draw_binding;
574 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
576 context_bind_fbo(context, target, entry->id);
577 return;
580 read_binding = context->fbo_read_binding;
581 draw_binding = context->fbo_draw_binding;
582 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
584 /* Apply render targets */
585 for (i = 0; i < gl_info->limits.buffers; ++i)
587 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
588 entry->key.rb_namespace & (1 << (i + 1)));
591 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
592 entry->key.rb_namespace & 0x1, entry->flags);
594 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
595 * GL contexts requirements. */
596 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
597 context_set_draw_buffer(context, GL_NONE);
598 if (target != GL_FRAMEBUFFER)
600 if (target == GL_READ_FRAMEBUFFER)
601 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
602 else
603 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
606 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
609 /* Context activation is done by the caller. */
610 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
611 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
612 DWORD color_location, DWORD ds_location)
614 struct fbo_entry *entry, *entry2;
616 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
618 context_destroy_fbo_entry(context, entry);
621 if (context->rebind_fbo)
623 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
624 context->rebind_fbo = FALSE;
627 if (color_location == WINED3D_LOCATION_DRAWABLE)
629 context->current_fbo = NULL;
630 context_bind_fbo(context, target, 0);
632 else
634 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
635 color_location, ds_location);
636 context_apply_fbo_entry(context, target, context->current_fbo);
640 /* Context activation is done by the caller. */
641 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
642 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
644 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
646 context->blit_targets[0] = render_target;
647 if (clear_size)
648 memset(&context->blit_targets[1], 0, clear_size);
649 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
652 /* Context activation is done by the caller. */
653 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
655 const struct wined3d_gl_info *gl_info = context->gl_info;
657 if (context->free_occlusion_query_count)
659 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
661 else
663 if (gl_info->supported[ARB_OCCLUSION_QUERY])
665 GL_EXTCALL(glGenQueries(1, &query->id));
666 checkGLcall("glGenQueries");
668 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
670 else
672 WARN("Occlusion queries not supported, not allocating query id.\n");
673 query->id = 0;
677 query->context = context;
678 list_add_head(&context->occlusion_queries, &query->entry);
681 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
683 struct wined3d_context *context = query->context;
685 list_remove(&query->entry);
686 query->context = NULL;
688 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
690 UINT new_size = context->free_occlusion_query_size << 1;
691 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
692 new_size * sizeof(*context->free_occlusion_queries));
694 if (!new_data)
696 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
697 return;
700 context->free_occlusion_query_size = new_size;
701 context->free_occlusion_queries = new_data;
704 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
707 /* Context activation is done by the caller. */
708 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
710 const struct wined3d_gl_info *gl_info = context->gl_info;
712 if (context->free_event_query_count)
714 query->object = context->free_event_queries[--context->free_event_query_count];
716 else
718 if (gl_info->supported[ARB_SYNC])
720 /* Using ARB_sync, not much to do here. */
721 query->object.sync = NULL;
722 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
724 else if (gl_info->supported[APPLE_FENCE])
726 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
727 checkGLcall("glGenFencesAPPLE");
729 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
731 else if(gl_info->supported[NV_FENCE])
733 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
734 checkGLcall("glGenFencesNV");
736 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
738 else
740 WARN("Event queries not supported, not allocating query id.\n");
741 query->object.id = 0;
745 query->context = context;
746 list_add_head(&context->event_queries, &query->entry);
749 void context_free_event_query(struct wined3d_event_query *query)
751 struct wined3d_context *context = query->context;
753 list_remove(&query->entry);
754 query->context = NULL;
756 if (context->free_event_query_count >= context->free_event_query_size - 1)
758 UINT new_size = context->free_event_query_size << 1;
759 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
760 new_size * sizeof(*context->free_event_queries));
762 if (!new_data)
764 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
765 return;
768 context->free_event_query_size = new_size;
769 context->free_event_queries = new_data;
772 context->free_event_queries[context->free_event_query_count++] = query->object;
775 /* Context activation is done by the caller. */
776 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
778 const struct wined3d_gl_info *gl_info = context->gl_info;
780 if (context->free_timestamp_query_count)
782 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
784 else
786 GL_EXTCALL(glGenQueries(1, &query->id));
787 checkGLcall("glGenQueries");
789 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
792 query->context = context;
793 list_add_head(&context->timestamp_queries, &query->entry);
796 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
798 struct wined3d_context *context = query->context;
800 list_remove(&query->entry);
801 query->context = NULL;
803 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
805 UINT new_size = context->free_timestamp_query_size << 1;
806 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
807 new_size * sizeof(*context->free_timestamp_queries));
809 if (!new_data)
811 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
812 return;
815 context->free_timestamp_query_size = new_size;
816 context->free_timestamp_queries = new_data;
819 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
822 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
824 static void context_enum_fbo_entries(const struct wined3d_device *device,
825 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
827 UINT i;
829 for (i = 0; i < device->context_count; ++i)
831 struct wined3d_context *context = device->contexts[i];
832 const struct wined3d_gl_info *gl_info = context->gl_info;
833 struct fbo_entry *entry, *entry2;
835 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
837 UINT j;
839 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
841 if (entry->key.objects[j].object == name
842 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
844 callback(context, entry);
845 break;
852 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
854 list_remove(&entry->entry);
855 list_add_head(&context->fbo_destroy_list, &entry->entry);
858 void context_resource_released(const struct wined3d_device *device,
859 struct wined3d_resource *resource, enum wined3d_resource_type type)
861 struct wined3d_texture *texture;
862 UINT i;
864 if (!device->d3d_initialized)
865 return;
867 switch (type)
869 case WINED3D_RTYPE_TEXTURE_2D:
870 case WINED3D_RTYPE_TEXTURE_3D:
871 texture = wined3d_texture_from_resource(resource);
873 for (i = 0; i < device->context_count; ++i)
875 struct wined3d_context *context = device->contexts[i];
876 if (context->current_rt.texture == texture)
878 context->current_rt.texture = NULL;
879 context->current_rt.sub_resource_idx = 0;
882 break;
884 default:
885 break;
889 void context_gl_resource_released(struct wined3d_device *device,
890 GLuint name, BOOL rb_namespace)
892 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
895 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
897 const struct wined3d_gl_info *gl_info = context->gl_info;
898 struct fbo_entry *entry = context->current_fbo;
899 unsigned int i;
901 if (!entry || context->rebind_fbo) return;
903 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
905 if (surface->container->texture_rgb.name == entry->key.objects[i].object
906 || surface->container->texture_srgb.name == entry->key.objects[i].object)
908 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
909 context->rebind_fbo = TRUE;
910 return;
915 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
917 const struct wined3d_gl_info *gl_info = ctx->gl_info;
918 BOOL ret = FALSE;
920 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
922 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
924 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
925 if (dc)
927 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
929 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
930 ctx->restore_pf, ctx->restore_pf_win);
932 ReleaseDC(ctx->restore_pf_win, dc);
935 else
937 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
941 ctx->restore_pf = 0;
942 ctx->restore_pf_win = NULL;
943 return ret;
946 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
948 const struct wined3d_gl_info *gl_info = context->gl_info;
949 int current;
951 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
952 return TRUE;
954 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
955 if (current == format) goto success;
957 if (!current)
959 if (!SetPixelFormat(dc, format, NULL))
961 /* This may also happen if the dc belongs to a destroyed window. */
962 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
963 format, dc, GetLastError());
964 return FALSE;
967 context->restore_pf = 0;
968 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
969 goto success;
972 /* By default WGL doesn't allow pixel format adjustments but we need it
973 * here. For this reason there's a Wine specific wglSetPixelFormat()
974 * which allows us to set the pixel format multiple times. Only use it
975 * when really needed. */
976 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
978 HWND win;
980 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
982 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
983 format, dc);
984 return FALSE;
987 win = private ? NULL : WindowFromDC(dc);
988 if (win != context->restore_pf_win)
990 context_restore_pixel_format(context);
992 context->restore_pf = private ? 0 : current;
993 context->restore_pf_win = win;
996 goto success;
999 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1000 * continue using the old format. There's a big chance that the old
1001 * format works although with a performance hit and perhaps rendering
1002 * errors. */
1003 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1004 format, dc, current);
1005 return TRUE;
1007 success:
1008 if (dc == context->hdc && context->hdc_is_private)
1009 context->hdc_has_format = TRUE;
1010 return TRUE;
1013 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1015 struct wined3d_swapchain *swapchain = ctx->swapchain;
1016 BOOL backup = FALSE;
1018 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1020 WARN("Failed to set pixel format %d on device context %p.\n",
1021 ctx->pixel_format, ctx->hdc);
1022 backup = TRUE;
1025 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1027 HDC dc;
1029 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1030 ctx->glCtx, ctx->hdc, GetLastError());
1031 ctx->valid = 0;
1032 WARN("Trying fallback to the backup window.\n");
1034 /* FIXME: If the context is destroyed it's no longer associated with
1035 * a swapchain, so we can't use the swapchain to get a backup dc. To
1036 * make this work windowless contexts would need to be handled by the
1037 * device. */
1038 if (ctx->destroyed)
1040 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1041 context_set_current(NULL);
1042 return FALSE;
1045 if (!(dc = swapchain_get_backup_dc(swapchain)))
1047 context_set_current(NULL);
1048 return FALSE;
1051 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1053 ERR("Failed to set pixel format %d on device context %p.\n",
1054 ctx->pixel_format, dc);
1055 context_set_current(NULL);
1056 return FALSE;
1059 if (!wglMakeCurrent(dc, ctx->glCtx))
1061 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1062 dc, GetLastError());
1063 context_set_current(NULL);
1064 return FALSE;
1067 ctx->valid = 1;
1069 ctx->needs_set = 0;
1070 return TRUE;
1073 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1075 if (!wglMakeCurrent(dc, gl_ctx))
1077 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1078 gl_ctx, dc, GetLastError());
1079 context_set_current(NULL);
1083 static void context_update_window(struct wined3d_context *context)
1085 if (context->win_handle == context->swapchain->win_handle)
1086 return;
1088 TRACE("Updating context %p window from %p to %p.\n",
1089 context, context->win_handle, context->swapchain->win_handle);
1091 if (context->hdc)
1092 wined3d_release_dc(context->win_handle, context->hdc);
1094 context->win_handle = context->swapchain->win_handle;
1095 context->hdc_is_private = FALSE;
1096 context->hdc_has_format = FALSE;
1097 context->needs_set = 1;
1098 context->valid = 1;
1100 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1102 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1103 context->valid = 0;
1107 static void context_destroy_gl_resources(struct wined3d_context *context)
1109 const struct wined3d_gl_info *gl_info = context->gl_info;
1110 struct wined3d_timestamp_query *timestamp_query;
1111 struct wined3d_occlusion_query *occlusion_query;
1112 struct wined3d_event_query *event_query;
1113 struct fbo_entry *entry, *entry2;
1114 HGLRC restore_ctx;
1115 HDC restore_dc;
1116 unsigned int i;
1118 restore_ctx = wglGetCurrentContext();
1119 restore_dc = wglGetCurrentDC();
1121 if (restore_ctx == context->glCtx)
1122 restore_ctx = NULL;
1123 else if (context->valid)
1124 context_set_gl_context(context);
1126 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1128 if (context->valid)
1129 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1130 timestamp_query->context = NULL;
1133 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1135 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1136 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1137 occlusion_query->context = NULL;
1140 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1142 if (context->valid)
1144 if (gl_info->supported[ARB_SYNC])
1146 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1148 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1149 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1151 event_query->context = NULL;
1154 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1156 if (!context->valid) entry->id = 0;
1157 context_destroy_fbo_entry(context, entry);
1160 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1162 if (!context->valid) entry->id = 0;
1163 context_destroy_fbo_entry(context, entry);
1166 if (context->valid)
1168 if (context->dummy_arbfp_prog)
1170 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1173 if (gl_info->supported[ARB_TIMER_QUERY])
1174 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1176 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1177 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1179 if (gl_info->supported[ARB_SYNC])
1181 for (i = 0; i < context->free_event_query_count; ++i)
1183 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1186 else if (gl_info->supported[APPLE_FENCE])
1188 for (i = 0; i < context->free_event_query_count; ++i)
1190 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1193 else if (gl_info->supported[NV_FENCE])
1195 for (i = 0; i < context->free_event_query_count; ++i)
1197 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1201 checkGLcall("context cleanup");
1204 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1205 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1206 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1208 context_restore_pixel_format(context);
1209 if (restore_ctx)
1211 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1213 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1215 ERR("Failed to disable GL context.\n");
1218 wined3d_release_dc(context->win_handle, context->hdc);
1220 if (!wglDeleteContext(context->glCtx))
1222 DWORD err = GetLastError();
1223 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1227 DWORD context_get_tls_idx(void)
1229 return wined3d_context_tls_idx;
1232 void context_set_tls_idx(DWORD idx)
1234 wined3d_context_tls_idx = idx;
1237 struct wined3d_context *context_get_current(void)
1239 return TlsGetValue(wined3d_context_tls_idx);
1242 BOOL context_set_current(struct wined3d_context *ctx)
1244 struct wined3d_context *old = context_get_current();
1246 if (old == ctx)
1248 TRACE("Already using D3D context %p.\n", ctx);
1249 return TRUE;
1252 if (old)
1254 if (old->destroyed)
1256 TRACE("Switching away from destroyed context %p.\n", old);
1257 context_destroy_gl_resources(old);
1258 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1259 HeapFree(GetProcessHeap(), 0, old);
1261 else
1263 if (wglGetCurrentContext())
1265 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1266 glFlush();
1268 old->current = 0;
1272 if (ctx)
1274 if (!ctx->valid)
1276 ERR("Trying to make invalid context %p current\n", ctx);
1277 return FALSE;
1280 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1281 if (!context_set_gl_context(ctx))
1282 return FALSE;
1283 ctx->current = 1;
1285 else if(wglGetCurrentContext())
1287 TRACE("Clearing current D3D context.\n");
1288 if (!wglMakeCurrent(NULL, NULL))
1290 DWORD err = GetLastError();
1291 ERR("Failed to clear current GL context, last error %#x.\n", err);
1292 TlsSetValue(wined3d_context_tls_idx, NULL);
1293 return FALSE;
1297 return TlsSetValue(wined3d_context_tls_idx, ctx);
1300 void context_release(struct wined3d_context *context)
1302 TRACE("Releasing context %p, level %u.\n", context, context->level);
1304 if (WARN_ON(d3d))
1306 if (!context->level)
1307 WARN("Context %p is not active.\n", context);
1308 else if (context != context_get_current())
1309 WARN("Context %p is not the current context.\n", context);
1312 if (!--context->level)
1314 if (context_restore_pixel_format(context))
1315 context->needs_set = 1;
1316 if (context->restore_ctx)
1318 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1319 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1320 context->restore_ctx = NULL;
1321 context->restore_dc = NULL;
1326 /* This is used when a context for render target A is active, but a separate context is
1327 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1328 * A to avoid breaking caller code. */
1329 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1331 if (context->current_rt.texture != restore->container
1332 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1334 context_release(context);
1335 context = context_acquire(restore->container->resource.device, restore);
1338 context_release(context);
1341 static void context_enter(struct wined3d_context *context)
1343 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1345 if (!context->level++)
1347 const struct wined3d_context *current_context = context_get_current();
1348 HGLRC current_gl = wglGetCurrentContext();
1350 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1352 TRACE("Another GL context (%p on device context %p) is already current.\n",
1353 current_gl, wglGetCurrentDC());
1354 context->restore_ctx = current_gl;
1355 context->restore_dc = wglGetCurrentDC();
1356 context->needs_set = 1;
1358 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1359 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1360 context->needs_set = 1;
1364 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1366 DWORD rep = context->state_table[state].representative;
1367 DWORD idx;
1368 BYTE shift;
1370 if (isStateDirty(context, rep)) return;
1372 context->dirtyArray[context->numDirtyEntries++] = rep;
1373 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1374 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1375 context->isStateDirty[idx] |= (1u << shift);
1378 /* This function takes care of wined3d pixel format selection. */
1379 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1380 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1381 BOOL auxBuffers, BOOL findCompatible)
1383 int iPixelFormat=0;
1384 unsigned int current_value;
1385 unsigned int cfg_count = device->adapter->cfg_count;
1386 unsigned int i;
1388 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1389 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1390 auxBuffers, findCompatible);
1392 current_value = 0;
1393 for (i = 0; i < cfg_count; ++i)
1395 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1396 unsigned int value;
1398 /* For now only accept RGBA formats. Perhaps some day we will
1399 * allow floating point formats for pbuffers. */
1400 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1401 continue;
1402 /* In window mode we need a window drawable format and double buffering. */
1403 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1404 continue;
1405 if (cfg->redSize < color_format->red_size)
1406 continue;
1407 if (cfg->greenSize < color_format->green_size)
1408 continue;
1409 if (cfg->blueSize < color_format->blue_size)
1410 continue;
1411 if (cfg->alphaSize < color_format->alpha_size)
1412 continue;
1413 if (cfg->depthSize < ds_format->depth_size)
1414 continue;
1415 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1416 continue;
1417 /* Check multisampling support. */
1418 if (cfg->numSamples)
1419 continue;
1421 value = 1;
1422 /* We try to locate a format which matches our requirements exactly. In case of
1423 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1424 if (cfg->depthSize == ds_format->depth_size)
1425 value += 1;
1426 if (cfg->stencilSize == ds_format->stencil_size)
1427 value += 2;
1428 if (cfg->alphaSize == color_format->alpha_size)
1429 value += 4;
1430 /* We like to have aux buffers in backbuffer mode */
1431 if (auxBuffers && cfg->auxBuffers)
1432 value += 8;
1433 if (cfg->redSize == color_format->red_size
1434 && cfg->greenSize == color_format->green_size
1435 && cfg->blueSize == color_format->blue_size)
1436 value += 16;
1438 if (value > current_value)
1440 iPixelFormat = cfg->iPixelFormat;
1441 current_value = value;
1445 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1446 if(!iPixelFormat && !findCompatible) {
1447 ERR("Can't find a suitable iPixelFormat\n");
1448 return FALSE;
1449 } else if(!iPixelFormat) {
1450 PIXELFORMATDESCRIPTOR pfd;
1452 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1453 /* PixelFormat selection */
1454 ZeroMemory(&pfd, sizeof(pfd));
1455 pfd.nSize = sizeof(pfd);
1456 pfd.nVersion = 1;
1457 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1458 pfd.iPixelType = PFD_TYPE_RGBA;
1459 pfd.cAlphaBits = color_format->alpha_size;
1460 pfd.cColorBits = color_format->red_size + color_format->green_size
1461 + color_format->blue_size + color_format->alpha_size;
1462 pfd.cDepthBits = ds_format->depth_size;
1463 pfd.cStencilBits = ds_format->stencil_size;
1464 pfd.iLayerType = PFD_MAIN_PLANE;
1466 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1467 if(!iPixelFormat) {
1468 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1469 ERR("Can't find a suitable iPixelFormat\n");
1470 return FALSE;
1474 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1475 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1476 return iPixelFormat;
1479 /* Context activation is done by the caller. */
1480 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1482 const struct wined3d_gl_info *gl_info = context->gl_info;
1483 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1485 for (i = 0; i < count; ++i)
1487 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1488 checkGLcall("glActiveTexture");
1490 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1491 checkGLcall("glBindTexture");
1493 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1495 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1496 checkGLcall("glBindTexture");
1499 if (gl_info->supported[EXT_TEXTURE3D])
1501 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1502 checkGLcall("glBindTexture");
1505 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1507 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1508 checkGLcall("glBindTexture");
1513 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1515 return gl_info->supported[ARB_DEBUG_OUTPUT]
1516 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1519 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1520 GLenum severity, GLsizei length, const char *message, void *ctx)
1522 switch (type)
1524 case GL_DEBUG_TYPE_ERROR_ARB:
1525 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1526 break;
1528 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1529 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1530 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1531 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1532 break;
1534 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1535 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1536 break;
1538 default:
1539 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1540 break;
1544 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1546 HGLRC ctx;
1547 unsigned int ctx_attrib_idx = 0;
1548 GLint ctx_attribs[7], ctx_flags = 0;
1550 if (context_debug_output_enabled(gl_info))
1551 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1552 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1553 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1554 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1555 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1556 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1557 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1558 if (ctx_flags)
1560 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1561 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1563 ctx_attribs[ctx_attrib_idx] = 0;
1565 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1567 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1569 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1570 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1571 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1572 GetLastError());
1575 return ctx;
1578 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1579 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1581 struct wined3d_device *device = swapchain->device;
1582 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1583 const struct wined3d_format *color_format;
1584 struct wined3d_context *ret;
1585 BOOL auxBuffers = FALSE;
1586 HGLRC ctx, share_ctx;
1587 int pixel_format;
1588 unsigned int s;
1589 DWORD state;
1590 HDC hdc = 0;
1591 BOOL hdc_is_private = FALSE;
1593 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1595 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1596 if (!ret)
1597 return NULL;
1599 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1600 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1601 if (!ret->blit_targets)
1602 goto out;
1604 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1605 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1606 if (!ret->draw_buffers)
1607 goto out;
1609 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1610 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1611 if (!ret->fbo_key)
1612 goto out;
1614 ret->free_timestamp_query_size = 4;
1615 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1616 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1617 if (!ret->free_timestamp_queries)
1618 goto out;
1619 list_init(&ret->timestamp_queries);
1621 ret->free_occlusion_query_size = 4;
1622 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1623 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1624 if (!ret->free_occlusion_queries)
1625 goto out;
1627 list_init(&ret->occlusion_queries);
1629 ret->free_event_query_size = 4;
1630 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1631 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1632 if (!ret->free_event_queries)
1633 goto out;
1635 list_init(&ret->event_queries);
1636 list_init(&ret->fbo_list);
1637 list_init(&ret->fbo_destroy_list);
1639 if (!device->shader_backend->shader_allocate_context_data(ret))
1641 ERR("Failed to allocate shader backend context data.\n");
1642 goto out;
1644 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1646 ERR("Failed to allocate fragment pipeline context data.\n");
1647 goto out;
1650 /* Initialize the texture unit mapping to a 1:1 mapping */
1651 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1653 if (s < gl_info->limits.combined_samplers)
1655 ret->tex_unit_map[s] = s;
1656 ret->rev_tex_unit_map[s] = s;
1658 else
1660 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1661 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1665 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1667 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1669 if ((hdc = swapchain_get_backup_dc(swapchain)))
1670 hdc_is_private = TRUE;
1671 else
1673 ERR("Failed to retrieve a device context.\n");
1674 goto out;
1678 color_format = target->resource.format;
1680 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1681 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1682 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1684 auxBuffers = TRUE;
1686 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1687 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1688 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1689 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1692 /* DirectDraw supports 8bit paletted render targets and these are used by
1693 * old games like StarCraft and C&C. Most modern hardware doesn't support
1694 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1695 * conversion (ab)uses the alpha component for storing the palette index.
1696 * For this reason we require a format with 8bit alpha, so request
1697 * A8R8G8B8. */
1698 if (color_format->id == WINED3DFMT_P8_UINT)
1699 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1701 /* When "always_offscreen" is enabled, we only use the drawable for
1702 * presentation blits, and don't do any rendering to it. That means we
1703 * don't need depth or stencil buffers, and can mostly ignore the render
1704 * target format. This wouldn't necessarily be quite correct for 10bpc
1705 * display modes, but we don't currently support those.
1706 * Using the same format regardless of the color/depth/stencil targets
1707 * makes it much less likely that different wined3d instances will set
1708 * conflicting pixel formats. */
1709 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER
1710 && wined3d_settings.always_offscreen)
1712 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1713 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN);
1716 /* Try to find a pixel format which matches our requirements. */
1717 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1719 /* Try to locate a compatible format if we weren't able to find anything. */
1720 if (!pixel_format)
1722 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1723 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1726 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1727 if (!pixel_format)
1729 ERR("Can't find a suitable pixel format.\n");
1730 goto out;
1733 ret->gl_info = gl_info;
1735 context_enter(ret);
1737 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1739 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1740 context_release(ret);
1741 goto out;
1744 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1745 if (gl_info->p_wglCreateContextAttribsARB)
1747 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1748 goto out;
1750 else
1752 if (!(ctx = wglCreateContext(hdc)))
1754 ERR("Failed to create a WGL context.\n");
1755 context_release(ret);
1756 goto out;
1759 if (share_ctx && !wglShareLists(share_ctx, ctx))
1761 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1762 context_release(ret);
1763 if (!wglDeleteContext(ctx))
1764 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1765 goto out;
1769 if (!device_context_add(device, ret))
1771 ERR("Failed to add the newly created context to the context list\n");
1772 context_release(ret);
1773 if (!wglDeleteContext(ctx))
1774 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1775 goto out;
1778 ret->d3d_info = &device->adapter->d3d_info;
1779 ret->state_table = device->StateTable;
1781 /* Mark all states dirty to force a proper initialization of the states
1782 * on the first use of the context. */
1783 for (state = 0; state <= STATE_HIGHEST; ++state)
1785 if (ret->state_table[state].representative)
1786 context_invalidate_state(ret, state);
1789 ret->swapchain = swapchain;
1790 ret->current_rt.texture = target;
1791 ret->current_rt.sub_resource_idx = 0;
1792 ret->tid = GetCurrentThreadId();
1794 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
1795 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1796 ret->valid = 1;
1798 ret->glCtx = ctx;
1799 ret->win_handle = swapchain->win_handle;
1800 ret->hdc = hdc;
1801 ret->hdc_is_private = hdc_is_private;
1802 ret->hdc_has_format = TRUE;
1803 ret->pixel_format = pixel_format;
1804 ret->needs_set = 1;
1806 /* Set up the context defaults */
1807 if (!context_set_current(ret))
1809 ERR("Cannot activate context to set up defaults.\n");
1810 device_context_remove(device, ret);
1811 context_release(ret);
1812 if (!wglDeleteContext(ctx))
1813 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1814 goto out;
1817 if (context_debug_output_enabled(gl_info))
1819 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1820 if (TRACE_ON(d3d_synchronous))
1821 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1822 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1823 if (ERR_ON(d3d))
1825 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1826 GL_DONT_CARE, 0, NULL, GL_TRUE));
1828 if (FIXME_ON(d3d))
1830 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1831 GL_DONT_CARE, 0, NULL, GL_TRUE));
1832 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1833 GL_DONT_CARE, 0, NULL, GL_TRUE));
1834 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1835 GL_DONT_CARE, 0, NULL, GL_TRUE));
1837 if (WARN_ON(d3d_perf))
1839 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1840 GL_DONT_CARE, 0, NULL, GL_TRUE));
1844 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1846 TRACE("Setting up the screen\n");
1848 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1850 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1851 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1853 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1854 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1856 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1857 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1859 else
1861 GLuint vao;
1863 GL_EXTCALL(glGenVertexArrays(1, &vao));
1864 GL_EXTCALL(glBindVertexArray(vao));
1865 checkGLcall("creating VAO");
1868 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1869 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1870 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1871 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1873 if (gl_info->supported[ARB_VERTEX_BLEND])
1875 /* Direct3D always uses n-1 weights for n world matrices and uses
1876 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1877 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1878 * enabled as well. */
1879 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1880 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1882 if (gl_info->supported[NV_TEXTURE_SHADER2])
1884 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1885 * the previous texture where to source the offset from is always unit - 1.
1887 for (s = 1; s < gl_info->limits.textures; ++s)
1889 context_active_texture(ret, gl_info, s);
1890 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1891 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1892 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1895 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1897 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1898 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1899 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1900 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1901 * is ever assigned.
1903 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1904 * program and the dummy program is destroyed when the context is destroyed.
1906 static const char dummy_program[] =
1907 "!!ARBfp1.0\n"
1908 "MOV result.color, fragment.color.primary;\n"
1909 "END\n";
1910 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1911 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1912 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1915 if (gl_info->supported[ARB_POINT_SPRITE])
1917 for (s = 0; s < gl_info->limits.textures; ++s)
1919 context_active_texture(ret, gl_info, s);
1920 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1921 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1925 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1927 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1929 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1931 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1933 device->shader_backend->shader_init_context_state(ret);
1934 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1935 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1936 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
1937 | (1u << WINED3D_SHADER_TYPE_HULL)
1938 | (1u << WINED3D_SHADER_TYPE_DOMAIN);
1940 /* If this happens to be the first context for the device, dummy textures
1941 * are not created yet. In that case, they will be created (and bound) by
1942 * create_dummy_textures right after this context is initialized. */
1943 if (device->dummy_texture_2d[0])
1944 bind_dummy_textures(device, ret);
1946 TRACE("Created context %p.\n", ret);
1948 return ret;
1950 out:
1951 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
1952 device->shader_backend->shader_free_context_data(ret);
1953 device->adapter->fragment_pipe->free_context_data(ret);
1954 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1955 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1956 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1957 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
1958 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1959 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1960 HeapFree(GetProcessHeap(), 0, ret);
1961 return NULL;
1964 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1966 BOOL destroy;
1968 TRACE("Destroying ctx %p\n", context);
1970 if (context->tid == GetCurrentThreadId() || !context->current)
1972 context_destroy_gl_resources(context);
1973 TlsSetValue(wined3d_context_tls_idx, NULL);
1974 destroy = TRUE;
1976 else
1978 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1979 in wined3d_adapter may go away in the meantime */
1980 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1981 *gl_info = *context->gl_info;
1982 context->gl_info = gl_info;
1983 context->destroyed = 1;
1984 destroy = FALSE;
1987 device->shader_backend->shader_free_context_data(context);
1988 device->adapter->fragment_pipe->free_context_data(context);
1989 HeapFree(GetProcessHeap(), 0, context->fbo_key);
1990 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1991 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1992 device_context_remove(device, context);
1993 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1996 /* Context activation is done by the caller. */
1997 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1999 const GLdouble projection[] =
2001 2.0 / width, 0.0, 0.0, 0.0,
2002 0.0, 2.0 / height, 0.0, 0.0,
2003 0.0, 0.0, 2.0, 0.0,
2004 -1.0, -1.0, -1.0, 1.0,
2007 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2008 checkGLcall("glMatrixMode(GL_PROJECTION)");
2009 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2010 checkGLcall("glLoadMatrixd");
2011 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2012 checkGLcall("glViewport");
2015 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2017 const struct wined3d_texture *rt = context->current_rt.texture;
2018 unsigned int level;
2020 if (rt->swapchain && rt->swapchain->front_buffer == rt)
2022 RECT window_size;
2024 GetClientRect(context->win_handle, &window_size);
2025 size->cx = window_size.right - window_size.left;
2026 size->cy = window_size.bottom - window_size.top;
2028 return;
2031 level = context->current_rt.sub_resource_idx % rt->level_count;
2032 size->cx = wined3d_texture_get_level_width(rt, level);
2033 size->cy = wined3d_texture_get_level_height(rt, level);
2036 /*****************************************************************************
2037 * SetupForBlit
2039 * Sets up a context for DirectDraw blitting.
2040 * All texture units are disabled, texture unit 0 is set as current unit
2041 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2042 * color writing enabled for all channels
2043 * register combiners disabled, shaders disabled
2044 * world matrix is set to identity, texture matrix 0 too
2045 * projection matrix is setup for drawing screen coordinates
2047 * Params:
2048 * This: Device to activate the context for
2049 * context: Context to setup
2051 *****************************************************************************/
2052 /* Context activation is done by the caller. */
2053 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2055 int i;
2056 const struct wined3d_gl_info *gl_info = context->gl_info;
2057 DWORD sampler;
2058 SIZE rt_size;
2060 TRACE("Setting up context %p for blitting\n", context);
2062 context_get_rt_size(context, &rt_size);
2064 if (context->last_was_blit)
2066 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2068 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2069 context->blit_w = rt_size.cx;
2070 context->blit_h = rt_size.cy;
2071 /* No need to dirtify here, the states are still dirtified because
2072 * they weren't applied since the last SetupForBlit() call. */
2074 TRACE("Context is already set up for blitting, nothing to do\n");
2075 return;
2077 context->last_was_blit = TRUE;
2079 /* Disable all textures. The caller can then bind a texture it wants to blit
2080 * from
2082 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2083 * function texture unit. No need to care for higher samplers
2085 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2087 sampler = context->rev_tex_unit_map[i];
2088 context_active_texture(context, gl_info, i);
2090 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2092 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2093 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2095 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2096 checkGLcall("glDisable GL_TEXTURE_3D");
2097 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2099 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2100 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2102 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2103 checkGLcall("glDisable GL_TEXTURE_2D");
2105 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2106 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2108 if (sampler != WINED3D_UNMAPPED_STAGE)
2110 if (sampler < MAX_TEXTURES)
2111 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2112 context_invalidate_state(context, STATE_SAMPLER(sampler));
2115 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2116 GL_EXTCALL(glBindSampler(0, 0));
2117 context_active_texture(context, gl_info, 0);
2119 sampler = context->rev_tex_unit_map[0];
2121 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2123 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2124 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2126 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2127 checkGLcall("glDisable GL_TEXTURE_3D");
2128 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2130 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2131 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2133 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2134 checkGLcall("glDisable GL_TEXTURE_2D");
2136 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2138 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2139 checkGLcall("glMatrixMode(GL_TEXTURE)");
2140 gl_info->gl_ops.gl.p_glLoadIdentity();
2141 checkGLcall("glLoadIdentity()");
2143 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2145 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2146 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2147 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2150 if (sampler != WINED3D_UNMAPPED_STAGE)
2152 if (sampler < MAX_TEXTURES)
2154 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2155 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2157 context_invalidate_state(context, STATE_SAMPLER(sampler));
2160 /* Other misc states */
2161 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2162 checkGLcall("glDisable(GL_ALPHA_TEST)");
2163 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2164 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2165 checkGLcall("glDisable GL_LIGHTING");
2166 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2167 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2168 checkGLcall("glDisable GL_DEPTH_TEST");
2169 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2170 glDisableWINE(GL_FOG);
2171 checkGLcall("glDisable GL_FOG");
2172 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2173 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2174 checkGLcall("glDisable GL_BLEND");
2175 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2176 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2177 checkGLcall("glDisable GL_CULL_FACE");
2178 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2179 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2180 checkGLcall("glDisable GL_STENCIL_TEST");
2181 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2182 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2183 checkGLcall("glDisable GL_SCISSOR_TEST");
2184 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2185 if (gl_info->supported[ARB_POINT_SPRITE])
2187 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2188 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2189 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2191 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2192 checkGLcall("glColorMask");
2193 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2194 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2195 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2196 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2197 if (gl_info->supported[EXT_SECONDARY_COLOR])
2199 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2200 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2201 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2204 /* Setup transforms */
2205 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2206 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2207 gl_info->gl_ops.gl.p_glLoadIdentity();
2208 checkGLcall("glLoadIdentity()");
2209 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2211 context->last_was_rhw = TRUE;
2212 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2214 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2215 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2216 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2217 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2218 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2219 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2220 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2222 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2224 /* Disable shaders */
2225 device->shader_backend->shader_disable(device->shader_priv, context);
2227 context->blit_w = rt_size.cx;
2228 context->blit_h = rt_size.cy;
2229 context_invalidate_state(context, STATE_VIEWPORT);
2230 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2233 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2235 return rt_mask & (1u << 31);
2238 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2240 return rt_mask & ~(1u << 31);
2243 /* Context activation is done by the caller. */
2244 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2246 const struct wined3d_gl_info *gl_info = context->gl_info;
2248 if (!rt_mask)
2250 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2251 checkGLcall("glDrawBuffer()");
2253 else if (is_rt_mask_onscreen(rt_mask))
2255 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2256 checkGLcall("glDrawBuffer()");
2258 else
2260 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2262 unsigned int i = 0;
2264 while (rt_mask)
2266 if (rt_mask & 1)
2267 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2268 else
2269 context->draw_buffers[i] = GL_NONE;
2271 rt_mask >>= 1;
2272 ++i;
2275 if (gl_info->supported[ARB_DRAW_BUFFERS])
2277 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2278 checkGLcall("glDrawBuffers()");
2280 else
2282 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2283 checkGLcall("glDrawBuffer()");
2286 else
2288 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2293 /* Context activation is done by the caller. */
2294 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2296 const struct wined3d_gl_info *gl_info = context->gl_info;
2297 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2298 DWORD new_mask = context_generate_rt_mask(buffer);
2300 if (new_mask == *current_mask)
2301 return;
2303 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2304 checkGLcall("glDrawBuffer()");
2306 *current_mask = new_mask;
2309 /* Context activation is done by the caller. */
2310 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2312 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2313 checkGLcall("glActiveTexture");
2314 context->active_texture = unit;
2317 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2319 const struct wined3d_gl_info *gl_info = context->gl_info;
2320 DWORD unit = context->active_texture;
2321 DWORD old_texture_type = context->texture_type[unit];
2323 if (name)
2325 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2326 checkGLcall("glBindTexture");
2328 else
2330 target = GL_NONE;
2333 if (old_texture_type != target)
2335 const struct wined3d_device *device = context->swapchain->device;
2337 switch (old_texture_type)
2339 case GL_NONE:
2340 /* nothing to do */
2341 break;
2342 case GL_TEXTURE_2D:
2343 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2344 checkGLcall("glBindTexture");
2345 break;
2346 case GL_TEXTURE_RECTANGLE_ARB:
2347 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2348 checkGLcall("glBindTexture");
2349 break;
2350 case GL_TEXTURE_CUBE_MAP:
2351 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2352 checkGLcall("glBindTexture");
2353 break;
2354 case GL_TEXTURE_3D:
2355 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2356 checkGLcall("glBindTexture");
2357 break;
2358 default:
2359 ERR("Unexpected texture target %#x\n", old_texture_type);
2362 context->texture_type[unit] = target;
2366 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2368 if (context->render_offscreen == offscreen) return;
2370 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2371 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2372 context_invalidate_state(context, STATE_VIEWPORT);
2373 context_invalidate_state(context, STATE_SCISSORRECT);
2374 context_invalidate_state(context, STATE_FRONTFACE);
2375 context->render_offscreen = offscreen;
2378 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2379 const struct wined3d_format *required)
2381 if (existing == required)
2382 return TRUE;
2383 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2384 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2385 return FALSE;
2386 if (existing->depth_size < required->depth_size)
2387 return FALSE;
2388 /* If stencil bits are used the exact amount is required - otherwise
2389 * wrapping won't work correctly. */
2390 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2391 return FALSE;
2392 return TRUE;
2395 /* Context activation is done by the caller. */
2396 static void context_validate_onscreen_formats(struct wined3d_context *context,
2397 const struct wined3d_rendertarget_view *depth_stencil)
2399 /* Onscreen surfaces are always in a swapchain */
2400 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2401 struct wined3d_surface *surface;
2403 if (context->render_offscreen || !depth_stencil) return;
2404 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2406 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2407 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2408 * format. */
2409 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2411 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2412 surface = context->current_rt.texture->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2413 surface_load_location(surface, context, WINED3D_LOCATION_TEXTURE_RGB);
2414 swapchain->render_to_fbo = TRUE;
2415 swapchain_update_draw_bindings(swapchain);
2416 context_set_render_offscreen(context, TRUE);
2419 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2421 switch (wined3d_settings.offscreen_rendering_mode)
2423 case ORM_FBO:
2424 return GL_COLOR_ATTACHMENT0;
2426 case ORM_BACKBUFFER:
2427 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2429 default:
2430 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2431 return GL_BACK;
2435 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2437 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2438 return 0;
2439 else if (rt->swapchain)
2440 return context_generate_rt_mask_from_resource(&rt->resource);
2441 else
2442 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2445 /* Context activation is done by the caller. */
2446 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2448 struct wined3d_texture *rt = context->current_rt.texture;
2449 struct wined3d_surface *surface;
2450 DWORD rt_mask, *cur_mask;
2452 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2454 context_validate_onscreen_formats(context, NULL);
2456 if (context->render_offscreen)
2458 wined3d_texture_load(rt, context, FALSE);
2460 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2461 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2462 if (rt->resource.format->id != WINED3DFMT_NULL)
2463 rt_mask = 1;
2464 else
2465 rt_mask = 0;
2467 else
2469 context->current_fbo = NULL;
2470 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2471 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2474 else
2476 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2479 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2481 if (rt_mask != *cur_mask)
2483 context_apply_draw_buffers(context, rt_mask);
2484 *cur_mask = rt_mask;
2487 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2489 context_check_fbo_status(context, GL_FRAMEBUFFER);
2492 SetupForBlit(device, context);
2493 context_invalidate_state(context, STATE_FRAMEBUFFER);
2496 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2497 const struct wined3d_rendertarget_view *ds)
2499 unsigned int i;
2501 if (ds) return TRUE;
2503 for (i = 0; i < rt_count; ++i)
2505 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2506 return TRUE;
2509 WARN("Invalid render target config, need at least one attachment.\n");
2510 return FALSE;
2513 /* Context activation is done by the caller. */
2514 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2515 UINT rt_count, const struct wined3d_fb_state *fb)
2517 struct wined3d_rendertarget_view **rts = fb->render_targets;
2518 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2519 const struct wined3d_gl_info *gl_info = context->gl_info;
2520 DWORD rt_mask = 0, *cur_mask;
2521 UINT i;
2523 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2524 || rt_count != gl_info->limits.buffers)
2526 if (!context_validate_rt_config(rt_count, rts, dsv))
2527 return FALSE;
2529 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2531 context_validate_onscreen_formats(context, dsv);
2533 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2535 for (i = 0; i < rt_count; ++i)
2537 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2538 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2539 rt_mask |= (1u << i);
2541 while (i < gl_info->limits.buffers)
2543 context->blit_targets[i] = NULL;
2544 ++i;
2546 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2547 wined3d_rendertarget_view_get_surface(dsv),
2548 rt_count ? rts[0]->resource->draw_binding : 0,
2549 dsv ? dsv->resource->draw_binding : 0);
2551 else
2553 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2554 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2555 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2558 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2559 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2560 * state management allows this */
2561 context_invalidate_state(context, STATE_FRAMEBUFFER);
2563 else
2565 rt_mask = context_generate_rt_mask_no_fbo(context,
2566 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2569 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2570 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2572 for (i = 0; i < rt_count; ++i)
2574 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2575 rt_mask |= (1u << i);
2578 else
2580 rt_mask = context_generate_rt_mask_no_fbo(context,
2581 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2584 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2586 if (rt_mask != *cur_mask)
2588 context_apply_draw_buffers(context, rt_mask);
2589 *cur_mask = rt_mask;
2590 context_invalidate_state(context, STATE_FRAMEBUFFER);
2593 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2595 context_check_fbo_status(context, GL_FRAMEBUFFER);
2598 if (context->last_was_blit)
2599 context->last_was_blit = FALSE;
2601 /* Blending and clearing should be orthogonal, but tests on the nvidia
2602 * driver show that disabling blending when clearing improves the clearing
2603 * performance incredibly. */
2604 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2605 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2606 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2608 if (needs_srgb_write(context, state, fb))
2609 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2610 else
2611 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2612 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2614 checkGLcall("setting up state for clear");
2616 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2617 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2618 context_invalidate_state(context, STATE_SCISSORRECT);
2620 return TRUE;
2623 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2625 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2626 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2627 DWORD rt_mask, rt_mask_bits;
2628 unsigned int i;
2630 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2631 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
2632 else if (!context->render_offscreen)
2633 return context_generate_rt_mask_from_resource(rts[0]->resource);
2635 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2636 rt_mask &= context->d3d_info->valid_rt_mask;
2637 rt_mask_bits = rt_mask;
2638 i = 0;
2639 while (rt_mask_bits)
2641 rt_mask_bits &= ~(1u << i);
2642 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2643 rt_mask &= ~(1u << i);
2645 i++;
2648 return rt_mask;
2651 /* Context activation is done by the caller. */
2652 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2654 DWORD rt_mask = find_draw_buffers_mask(context, state);
2655 const struct wined3d_fb_state *fb = state->fb;
2656 DWORD *cur_mask;
2658 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2660 if (!context->render_offscreen)
2662 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2663 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2665 else
2667 unsigned int i;
2669 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2671 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2673 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2674 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2675 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
2676 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2680 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2681 if (rt_mask != *cur_mask)
2683 context_apply_draw_buffers(context, rt_mask);
2684 *cur_mask = rt_mask;
2688 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2690 DWORD i = context->rev_tex_unit_map[unit];
2691 DWORD j = context->tex_unit_map[stage];
2693 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2694 context->tex_unit_map[stage] = unit;
2695 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2696 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2698 context->rev_tex_unit_map[unit] = stage;
2699 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2700 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2703 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2705 DWORD i;
2707 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2708 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2711 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2712 const struct wined3d_state *state)
2714 UINT i, start, end;
2716 context->fixed_function_usage_map = 0;
2717 for (i = 0; i < MAX_TEXTURES; ++i)
2719 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2720 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2721 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2722 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2723 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2724 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2725 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2726 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2728 /* Not used, and disable higher stages. */
2729 if (color_op == WINED3D_TOP_DISABLE)
2730 break;
2732 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2733 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2734 || ((color_arg3 == WINED3DTA_TEXTURE)
2735 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2736 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2737 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2738 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2739 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2740 context->fixed_function_usage_map |= (1u << i);
2742 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2743 && i < MAX_TEXTURES - 1)
2744 context->fixed_function_usage_map |= (1u << (i + 1));
2747 if (i < context->lowest_disabled_stage)
2749 start = i;
2750 end = context->lowest_disabled_stage;
2752 else
2754 start = context->lowest_disabled_stage;
2755 end = i;
2758 context->lowest_disabled_stage = i;
2759 for (i = start + 1; i < end; ++i)
2761 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2765 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2766 const struct wined3d_state *state)
2768 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2769 const struct wined3d_gl_info *gl_info = context->gl_info;
2770 unsigned int i, tex;
2771 WORD ffu_map;
2773 context_update_fixed_function_usage_map(context, state);
2775 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2776 return;
2778 ffu_map = context->fixed_function_usage_map;
2780 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2781 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2783 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2785 if (!(ffu_map & 1))
2786 continue;
2788 if (context->tex_unit_map[i] != i)
2790 context_map_stage(context, i, i);
2791 context_invalidate_state(context, STATE_SAMPLER(i));
2792 context_invalidate_texture_stage(context, i);
2795 return;
2798 /* Now work out the mapping */
2799 tex = 0;
2800 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2802 if (!(ffu_map & 1))
2803 continue;
2805 if (context->tex_unit_map[i] != tex)
2807 context_map_stage(context, i, tex);
2808 context_invalidate_state(context, STATE_SAMPLER(i));
2809 context_invalidate_texture_stage(context, i);
2812 ++tex;
2816 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2818 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2819 const struct wined3d_gl_info *gl_info = context->gl_info;
2820 const struct wined3d_shader_resource_info *resource_info =
2821 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2822 unsigned int i;
2824 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2825 return;
2827 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2829 if (resource_info[i].type && context->tex_unit_map[i] != i)
2831 context_map_stage(context, i, i);
2832 context_invalidate_state(context, STATE_SAMPLER(i));
2833 if (i < d3d_info->limits.ffp_blend_stages)
2834 context_invalidate_texture_stage(context, i);
2839 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2840 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2842 DWORD current_mapping = context->rev_tex_unit_map[unit];
2844 /* Not currently used */
2845 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2846 return TRUE;
2848 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2850 /* Used by a fragment sampler */
2852 if (!ps_resource_info)
2854 /* No pixel shader, check fixed function */
2855 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2858 /* Pixel shader, check the shader's sampler map */
2859 return !ps_resource_info[current_mapping].type;
2862 return TRUE;
2865 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2867 const struct wined3d_shader_resource_info *vs_resource_info =
2868 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2869 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2870 const struct wined3d_gl_info *gl_info = context->gl_info;
2871 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2872 int i;
2874 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2875 return;
2877 /* Note that we only care if a resource is used or not, not the
2878 * resource's specific type. Otherwise we'd need to call
2879 * shader_update_samplers() here for 1.x pixelshaders. */
2880 if (ps)
2881 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2883 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2885 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2886 if (vs_resource_info[i].type)
2888 while (start >= 0)
2890 if (context_unit_free_for_vs(context, ps_resource_info, start))
2892 if (context->tex_unit_map[vsampler_idx] != start)
2894 context_map_stage(context, vsampler_idx, start);
2895 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2898 --start;
2899 break;
2902 --start;
2904 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
2905 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
2910 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2912 BOOL vs = use_vs(state);
2913 BOOL ps = use_ps(state);
2915 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
2916 * need a 1:1 map at the moment.
2917 * When the mapping of a stage is changed, sampler and ALL texture stage
2918 * states have to be reset. */
2920 if (ps)
2921 context_map_psamplers(context, state);
2922 else
2923 context_map_fixed_function_samplers(context, state);
2925 if (vs)
2926 context_map_vsamplers(context, ps, state);
2929 /* Context activation is done by the caller. */
2930 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2932 DWORD rt_mask, *cur_mask;
2934 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2936 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2937 rt_mask = find_draw_buffers_mask(context, state);
2938 if (rt_mask != *cur_mask)
2940 context_apply_draw_buffers(context, rt_mask);
2941 *cur_mask = rt_mask;
2945 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2947 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2948 *regnum = WINED3D_FFP_POSITION;
2949 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2950 *regnum = WINED3D_FFP_BLENDWEIGHT;
2951 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2952 *regnum = WINED3D_FFP_BLENDINDICES;
2953 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2954 *regnum = WINED3D_FFP_NORMAL;
2955 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2956 *regnum = WINED3D_FFP_PSIZE;
2957 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2958 *regnum = WINED3D_FFP_DIFFUSE;
2959 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2960 *regnum = WINED3D_FFP_SPECULAR;
2961 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2962 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2963 else
2965 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2966 *regnum = ~0U;
2967 return FALSE;
2970 return TRUE;
2973 /* Context activation is done by the caller. */
2974 void context_stream_info_from_declaration(struct wined3d_context *context,
2975 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2977 /* We need to deal with frequency data! */
2978 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2979 BOOL use_vshader = use_vs(state);
2980 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2981 unsigned int i;
2983 stream_info->use_map = 0;
2984 stream_info->swizzle_map = 0;
2985 stream_info->position_transformed = declaration->position_transformed;
2987 /* Translate the declaration into strided data. */
2988 for (i = 0; i < declaration->element_count; ++i)
2990 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2991 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2992 BOOL stride_used;
2993 unsigned int idx;
2995 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2996 element, i + 1, declaration->element_count);
2998 if (!stream->buffer)
2999 continue;
3001 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3003 if (use_vshader)
3005 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3007 stride_used = FALSE;
3009 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3011 /* TODO: Assuming vertexdeclarations are usually used with the
3012 * same or a similar shader, it might be worth it to store the
3013 * last used output slot and try that one first. */
3014 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3015 element->usage, element->usage_idx, &idx);
3017 else
3019 idx = element->output_slot;
3020 stride_used = TRUE;
3023 else
3025 if (!generic_attributes && !element->ffp_valid)
3027 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3028 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3029 stride_used = FALSE;
3031 else
3033 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3037 if (stride_used)
3039 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3040 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3041 use_vshader ? "shader": "fixed function", idx,
3042 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3043 element->offset, stream->stride, debug_d3dformat(element->format->id),
3044 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3046 stream_info->elements[idx].format = element->format;
3047 stream_info->elements[idx].data.buffer_object = 0;
3048 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3049 stream_info->elements[idx].stride = stream->stride;
3050 stream_info->elements[idx].stream_idx = element->input_slot;
3051 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3053 stream_info->elements[idx].divisor = 1;
3055 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3057 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3058 if (!element->instance_data_step_rate)
3059 FIXME("Instance step rate 0 not implemented.\n");
3061 else
3063 stream_info->elements[idx].divisor = 0;
3066 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3067 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3069 stream_info->swizzle_map |= 1u << idx;
3071 stream_info->use_map |= 1u << idx;
3076 /* Context activation is done by the caller. */
3077 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3079 const struct wined3d_gl_info *gl_info = context->gl_info;
3080 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3081 struct wined3d_stream_info *stream_info = &context->stream_info;
3082 DWORD prev_all_vbo = stream_info->all_vbo;
3083 unsigned int i;
3084 WORD map;
3086 context_stream_info_from_declaration(context, state, stream_info);
3088 stream_info->all_vbo = 1;
3089 context->num_buffer_queries = 0;
3090 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3092 struct wined3d_stream_info_element *element;
3093 struct wined3d_bo_address data;
3094 struct wined3d_buffer *buffer;
3096 if (!(map & 1))
3097 continue;
3099 element = &stream_info->elements[i];
3100 buffer = state->streams[element->stream_idx].buffer;
3102 /* We can't use VBOs if the base vertex index is negative. OpenGL
3103 * doesn't accept negative offsets (or rather offsets bigger than the
3104 * VBO, because the pointer is unsigned), so use system memory
3105 * sources. In most sane cases the pointer - offset will still be > 0,
3106 * otherwise it will wrap around to some big value. Hope that with the
3107 * indices the driver wraps it back internally. If not,
3108 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3109 * path. */
3110 if (state->load_base_vertex_index < 0)
3112 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3113 state->load_base_vertex_index);
3114 element->data.buffer_object = 0;
3115 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
3116 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3117 FIXME("System memory vertex data load offset is negative!\n");
3119 else
3121 buffer_internal_preload(buffer, context, state);
3122 buffer_get_memory(buffer, context, &data);
3123 element->data.buffer_object = data.buffer_object;
3124 element->data.addr += (ULONG_PTR)data.addr;
3127 if (!element->data.buffer_object)
3128 stream_info->all_vbo = 0;
3130 if (buffer->query)
3131 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3133 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3136 if (use_vs(state))
3138 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
3140 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3141 context->use_immediate_mode_draw = TRUE;
3143 else
3145 context->use_immediate_mode_draw = FALSE;
3148 else
3150 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3151 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3152 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR));
3154 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3155 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3156 context->use_immediate_mode_draw = TRUE;
3157 else
3158 context->use_immediate_mode_draw = FALSE;
3161 if (prev_all_vbo != stream_info->all_vbo)
3162 context_invalidate_state(context, STATE_INDEXBUFFER);
3165 /* Context activation is done by the caller. */
3166 static void context_preload_texture(struct wined3d_context *context,
3167 const struct wined3d_state *state, unsigned int idx)
3169 struct wined3d_texture *texture;
3171 if (!(texture = state->textures[idx]))
3172 return;
3174 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3177 /* Context activation is done by the caller. */
3178 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3180 unsigned int i;
3182 if (use_vs(state))
3184 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3186 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3187 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3191 if (use_ps(state))
3193 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3195 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3196 context_preload_texture(context, state, i);
3199 else
3201 WORD ffu_map = context->fixed_function_usage_map;
3203 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3205 if (ffu_map & 1)
3206 context_preload_texture(context, state, i);
3211 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3213 struct wined3d_shader_sampler_map_entry *entry;
3214 struct wined3d_shader_resource_view *view;
3215 struct wined3d_shader *shader;
3216 unsigned int i, j;
3218 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3220 if (!(shader = state->shader[i]))
3221 continue;
3223 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3225 if (state->cb[i][j])
3226 buffer_internal_preload(state->cb[i][j], context, state);
3229 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3231 entry = &shader->reg_maps.sampler_map.entries[j];
3233 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3235 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3236 continue;
3239 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3240 buffer_internal_preload(buffer_from_resource(view->resource), context, state);
3241 else
3242 wined3d_texture_load(wined3d_texture_from_resource(view->resource), context, FALSE);
3247 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3249 const struct wined3d_device *device = context->swapchain->device;
3250 const struct wined3d_gl_info *gl_info = context->gl_info;
3251 struct wined3d_shader_sampler_map_entry *entry;
3252 struct wined3d_shader_resource_view *view;
3253 struct wined3d_sampler *sampler;
3254 struct wined3d_texture *texture;
3255 struct wined3d_shader *shader;
3256 unsigned int i, j, count;
3257 GLuint sampler_name;
3259 static const struct
3261 enum wined3d_shader_type type;
3262 unsigned int base_idx;
3263 unsigned int count;
3265 shader_types[] =
3267 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3268 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3271 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3273 if (!(shader = state->shader[shader_types[i].type]))
3274 continue;
3276 count = shader->reg_maps.sampler_map.count;
3277 if (count > shader_types[i].count)
3279 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3280 shader, count, shader_types[i].count);
3281 count = shader_types[i].count;
3284 for (j = 0; j < count; ++j)
3286 entry = &shader->reg_maps.sampler_map.entries[j];
3288 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3290 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3291 continue;
3294 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3296 FIXME("Buffer shader resources not supported.\n");
3297 continue;
3300 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3302 sampler_name = device->default_sampler;
3304 else if ((sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3306 sampler_name = sampler->name;
3308 else
3310 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3311 continue;
3314 texture = wined3d_texture_from_resource(view->resource);
3315 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3316 wined3d_texture_bind(texture, context, FALSE);
3318 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler_name));
3319 checkGLcall("glBindSampler");
3324 /* Context activation is done by the caller. */
3325 BOOL context_apply_draw_state(struct wined3d_context *context,
3326 const struct wined3d_device *device, const struct wined3d_state *state)
3328 const struct StateEntry *state_table = context->state_table;
3329 const struct wined3d_fb_state *fb = state->fb;
3330 unsigned int i;
3331 WORD map;
3333 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3334 fb->render_targets, fb->depth_stencil))
3335 return FALSE;
3337 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3339 context_validate_onscreen_formats(context, fb->depth_stencil);
3342 /* Preload resources before FBO setup. Texture preload in particular may
3343 * result in changes to the current FBO, due to using e.g. FBO blits for
3344 * updating a resource location. */
3345 context_update_tex_unit_map(context, state);
3346 context_preload_textures(context, state);
3347 context_load_shader_resources(context, state);
3348 /* TODO: Right now the dependency on the vertex shader is necessary
3349 * since context_stream_info_from_declaration depends on the reg_maps of
3350 * the current VS but maybe it's possible to relax the coupling in some
3351 * situations at least. */
3352 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3353 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3355 context_update_stream_info(context, state);
3357 else
3359 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3361 if (map & 1)
3362 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3365 if (state->index_buffer)
3367 if (context->stream_info.all_vbo)
3368 buffer_internal_preload(state->index_buffer, context, state);
3369 else
3370 buffer_get_sysmem(state->index_buffer, context);
3373 for (i = 0; i < context->numDirtyEntries; ++i)
3375 DWORD rep = context->dirtyArray[i];
3376 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3377 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3378 context->isStateDirty[idx] &= ~(1u << shift);
3379 state_table[rep].apply(context, state, rep);
3382 if (context->shader_update_mask)
3384 device->shader_backend->shader_select(device->shader_priv, context, state);
3385 context->shader_update_mask = 0;
3388 if (context->constant_update_mask)
3390 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3391 context->constant_update_mask = 0;
3394 if (context->update_shader_resource_bindings)
3396 context_bind_shader_resources(context, state);
3397 context->update_shader_resource_bindings = 0;
3400 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3402 context_check_fbo_status(context, GL_FRAMEBUFFER);
3405 context->numDirtyEntries = 0; /* This makes the whole list clean */
3406 context->last_was_blit = FALSE;
3408 return TRUE;
3411 static void context_setup_target(struct wined3d_context *context,
3412 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3414 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3416 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3417 if (context->current_rt.texture == texture
3418 && context->current_rt.sub_resource_idx == sub_resource_idx
3419 && render_offscreen == old_render_offscreen)
3420 return;
3422 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3423 * the alpha blend state changes with different render target formats. */
3424 if (!context->current_rt.texture)
3426 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3428 else
3430 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3431 const struct wined3d_format *new = texture->resource.format;
3433 if (old->id != new->id)
3435 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3436 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3437 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3438 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3440 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3441 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3442 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3443 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3446 /* When switching away from an offscreen render target, and we're not
3447 * using FBOs, we have to read the drawable into the texture. This is
3448 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3449 * There are some things that need care though. PreLoad needs a GL context,
3450 * and FindContext is called before the context is activated. It also
3451 * has to be called with the old rendertarget active, otherwise a
3452 * wrong drawable is read. */
3453 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3454 && old_render_offscreen && (context->current_rt.texture != texture
3455 || context->current_rt.sub_resource_idx != sub_resource_idx))
3457 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
3458 struct wined3d_texture *prev_texture = context->current_rt.texture;
3460 /* Read the back buffer of the old drawable into the destination texture. */
3461 if (prev_texture->texture_srgb.name)
3462 wined3d_texture_load(prev_texture, context, TRUE);
3463 wined3d_texture_load(prev_texture, context, FALSE);
3464 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
3468 context->current_rt.texture = texture;
3469 context->current_rt.sub_resource_idx = sub_resource_idx;
3470 context_set_render_offscreen(context, render_offscreen);
3473 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3475 struct wined3d_context *current_context = context_get_current();
3476 struct wined3d_texture *target_texture;
3477 unsigned int target_sub_resource_idx;
3478 struct wined3d_context *context;
3480 TRACE("device %p, target %p.\n", device, target);
3482 if (current_context && current_context->destroyed)
3483 current_context = NULL;
3485 if (target)
3487 target_texture = target->container;
3488 target_sub_resource_idx = surface_get_sub_resource_idx(target);
3490 else
3492 if (current_context
3493 && current_context->current_rt.texture
3494 && current_context->swapchain->device == device)
3496 target_texture = current_context->current_rt.texture;
3497 target_sub_resource_idx = current_context->current_rt.sub_resource_idx;
3499 else
3501 struct wined3d_swapchain *swapchain = device->swapchains[0];
3503 if (swapchain->back_buffers)
3504 target_texture = swapchain->back_buffers[0];
3505 else
3506 target_texture = swapchain->front_buffer;
3507 target_sub_resource_idx = 0;
3511 if (current_context && current_context->current_rt.texture == target_texture)
3513 context = current_context;
3515 else if (target_texture->swapchain)
3517 TRACE("Rendering onscreen.\n");
3519 context = swapchain_get_context(target_texture->swapchain);
3521 else
3523 TRACE("Rendering offscreen.\n");
3525 /* Stay with the current context if possible. Otherwise use the
3526 * context for the primary swapchain. */
3527 if (current_context && current_context->swapchain->device == device)
3528 context = current_context;
3529 else
3530 context = swapchain_get_context(device->swapchains[0]);
3533 context_enter(context);
3534 context_update_window(context);
3535 context_setup_target(context, target_texture, target_sub_resource_idx);
3536 if (!context->valid) return context;
3538 if (context != current_context)
3540 if (!context_set_current(context))
3541 ERR("Failed to activate the new context.\n");
3543 else if (context->needs_set)
3545 context_set_gl_context(context);
3548 return context;