wined3d: Simplify pixel format selection.
[wine.git] / dlls / wined3d / context.c
blob59a1367630cfa1f955dc7581a5bd2af08894177e
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 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
122 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
124 const struct wined3d_gl_info *gl_info = context->gl_info;
126 if (!resource)
128 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
129 checkGLcall("glFramebufferTexture2D()");
131 else if (resource->target == GL_TEXTURE_2D_ARRAY)
133 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
135 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
136 return;
139 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
140 resource->object, resource->level, resource->layer);
141 checkGLcall("glFramebufferTextureLayer()");
143 else
145 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
146 resource->target, resource->object, resource->level);
147 checkGLcall("glFramebufferTexture2D()");
151 /* Context activation is done by the caller. */
152 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
153 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
154 DWORD flags)
156 const struct wined3d_gl_info *gl_info = context->gl_info;
158 if (resource->object)
160 TRACE("Attach depth stencil %u.\n", resource->object);
162 if (rb_namespace)
164 context_attach_depth_stencil_rb(gl_info, fbo_target,
165 flags, resource->object);
167 else
169 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
170 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
172 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
173 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
176 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
177 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
179 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
180 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
182 else
184 TRACE("Attach depth stencil 0.\n");
186 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
187 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
191 /* Context activation is done by the caller. */
192 static void context_attach_surface_fbo(struct wined3d_context *context,
193 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
195 const struct wined3d_gl_info *gl_info = context->gl_info;
197 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
199 if (resource->object)
202 if (rb_namespace)
204 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
205 GL_RENDERBUFFER, resource->object);
206 checkGLcall("glFramebufferRenderbuffer()");
208 else
210 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
213 else
215 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
219 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
220 GLenum attachment)
222 static const struct
224 GLenum target;
225 GLenum binding;
226 const char *str;
227 enum wined3d_gl_extension extension;
229 texture_type[] =
231 {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D, "2d", WINED3D_GL_EXT_NONE},
232 {GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_BINDING_RECTANGLE_ARB, "rectangle", ARB_TEXTURE_RECTANGLE},
233 {GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BINDING_2D_ARRAY, "2d-array", EXT_TEXTURE_ARRAY},
236 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
238 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
239 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
240 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
241 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
243 if (type == GL_RENDERBUFFER)
245 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
246 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
247 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
248 if (gl_info->limits.samples > 1)
249 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
250 else
251 samples = 1;
252 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
253 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
254 debug_fboattachment(attachment), name, width, height, samples, fmt);
256 else if (type == GL_TEXTURE)
258 const char *tex_type_str;
260 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
261 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
262 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
263 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
265 if (face)
267 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
269 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, name);
270 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
271 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
272 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
274 tex_target = GL_TEXTURE_CUBE_MAP;
275 tex_type_str = "cube";
277 else
279 unsigned int i;
281 tex_type_str = NULL;
282 for (i = 0; i < sizeof(texture_type) / sizeof(*texture_type); ++i)
284 if (!gl_info->supported[texture_type[i].extension])
285 continue;
287 gl_info->gl_ops.gl.p_glGetIntegerv(texture_type[i].binding, &old_texture);
288 while (gl_info->gl_ops.gl.p_glGetError());
290 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, name);
291 if (!gl_info->gl_ops.gl.p_glGetError())
293 tex_target = texture_type[i].target;
294 tex_type_str = texture_type[i].str;
295 break;
297 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, old_texture);
299 if (!tex_type_str)
301 FIXME("Cannot find type of texture %d.\n", name);
302 return;
305 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
306 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
307 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
310 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
311 tex_type_str, name, width, height, fmt);
313 gl_info->gl_ops.gl.p_glBindTexture(tex_target, old_texture);
314 checkGLcall("Guess texture type");
316 else if (type == GL_NONE)
318 FIXME(" %s: NONE.\n", debug_fboattachment(attachment));
320 else
322 ERR(" %s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
326 /* Context activation is done by the caller. */
327 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
329 const struct wined3d_gl_info *gl_info = context->gl_info;
330 GLenum status;
332 if (!FIXME_ON(d3d)) return;
334 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
335 if (status == GL_FRAMEBUFFER_COMPLETE)
337 TRACE("FBO complete\n");
339 else
341 unsigned int i;
343 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
345 if (!context->current_fbo)
347 ERR("FBO 0 is incomplete, driver bug?\n");
348 return;
351 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
352 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
354 for (i = 0; i < gl_info->limits.buffers; ++i)
355 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
356 checkGLcall("Dump FBO attachments");
360 static inline DWORD context_generate_rt_mask(GLenum buffer)
362 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
363 return buffer ? (1u << 31) | buffer : 0;
366 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
368 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
370 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
371 return 0;
374 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
377 static inline void context_set_fbo_key_for_surface(const struct wined3d_context *context,
378 struct wined3d_fbo_entry_key *key, UINT idx, struct wined3d_surface *surface,
379 DWORD location)
381 if (!surface || surface->container->resource.format->id == WINED3DFMT_NULL)
383 key->objects[idx].object = 0;
384 key->objects[idx].target = 0;
385 key->objects[idx].level = key->objects[idx].layer = 0;
387 else if (surface->current_renderbuffer)
389 key->objects[idx].object = surface->current_renderbuffer->id;
390 key->objects[idx].target = 0;
391 key->objects[idx].level = key->objects[idx].layer = 0;
392 key->rb_namespace |= 1 << idx;
394 else
396 switch (location)
398 case WINED3D_LOCATION_TEXTURE_RGB:
399 key->objects[idx].object = surface_get_texture_name(surface, context, FALSE);
400 key->objects[idx].target = surface->texture_target;
401 key->objects[idx].level = surface->texture_level;
402 key->objects[idx].layer = surface->texture_layer;
403 break;
405 case WINED3D_LOCATION_TEXTURE_SRGB:
406 key->objects[idx].object = surface_get_texture_name(surface, context, TRUE);
407 key->objects[idx].target = surface->texture_target;
408 key->objects[idx].level = surface->texture_level;
409 key->objects[idx].layer = surface->texture_layer;
410 break;
412 case WINED3D_LOCATION_RB_MULTISAMPLE:
413 key->objects[idx].object = surface->container->rb_multisample;
414 key->objects[idx].target = 0;
415 key->objects[idx].level = key->objects[idx].layer = 0;
416 key->rb_namespace |= 1 << idx;
417 break;
419 case WINED3D_LOCATION_RB_RESOLVED:
420 key->objects[idx].object = surface->container->rb_resolved;
421 key->objects[idx].target = 0;
422 key->objects[idx].level = key->objects[idx].layer = 0;
423 key->rb_namespace |= 1 << idx;
424 break;
429 static void context_generate_fbo_key(const struct wined3d_context *context,
430 struct wined3d_fbo_entry_key *key, struct wined3d_surface **render_targets,
431 struct wined3d_surface *depth_stencil, DWORD color_location,
432 DWORD ds_location)
434 UINT i;
436 key->rb_namespace = 0;
437 context_set_fbo_key_for_surface(context, key, 0, depth_stencil, ds_location);
439 for (i = 0; i < context->gl_info->limits.buffers; ++i)
440 context_set_fbo_key_for_surface(context, key, i + 1, render_targets[i], color_location);
443 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
444 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
445 DWORD color_location, DWORD ds_location)
447 const struct wined3d_gl_info *gl_info = context->gl_info;
448 struct fbo_entry *entry;
449 UINT object_count = gl_info->limits.buffers + 1;
451 entry = HeapAlloc(GetProcessHeap(), 0,
452 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
453 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
454 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
455 entry->flags = 0;
456 if (depth_stencil)
458 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
459 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
460 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
461 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
463 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
464 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
465 checkGLcall("glGenFramebuffers()");
466 TRACE("Created FBO %u.\n", entry->id);
468 return entry;
471 /* Context activation is done by the caller. */
472 static void context_reuse_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, struct fbo_entry *entry)
476 const struct wined3d_gl_info *gl_info = context->gl_info;
478 context_bind_fbo(context, target, entry->id);
479 context_clean_fbo_attachments(gl_info, target);
481 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
482 entry->flags = 0;
483 if (depth_stencil)
485 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
486 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
487 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
488 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
492 /* Context activation is done by the caller. */
493 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
495 if (entry->id)
497 TRACE("Destroy FBO %u.\n", entry->id);
498 context_destroy_fbo(context, entry->id);
500 --context->fbo_entry_count;
501 list_remove(&entry->entry);
502 HeapFree(GetProcessHeap(), 0, entry);
505 /* Context activation is done by the caller. */
506 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
507 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
508 DWORD color_location, DWORD ds_location)
510 const struct wined3d_gl_info *gl_info = context->gl_info;
511 unsigned int object_count = gl_info->limits.buffers + 1;
512 struct wined3d_texture *rt_texture, *ds_texture;
513 struct fbo_entry *entry;
514 unsigned int i;
516 if (depth_stencil && render_targets[0])
518 rt_texture = render_targets[0]->container;
519 ds_texture = depth_stencil->container;
521 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
522 < wined3d_texture_get_level_width(rt_texture, render_targets[0]->texture_level)
523 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
524 < wined3d_texture_get_level_height(rt_texture, render_targets[0]->texture_level))
526 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
527 depth_stencil = NULL;
529 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
530 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
532 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
533 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
534 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
535 depth_stencil = NULL;
537 else
538 surface_set_compatible_renderbuffer(depth_stencil, render_targets[0]);
541 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
542 ds_location);
544 if (TRACE_ON(d3d))
546 TRACE("Dumping FBO attachments:\n");
547 for (i = 0; i < gl_info->limits.buffers; ++i)
549 if (render_targets[i])
551 rt_texture = render_targets[i]->container;
552 TRACE(" Color attachment %u: %p format %s, %s %u, %ux%u, %u samples.\n",
553 i, render_targets[i], debug_d3dformat(rt_texture->resource.format->id),
554 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : "texture",
555 context->fbo_key->objects[i + 1].object,
556 wined3d_texture_get_level_pow2_width(rt_texture, render_targets[i]->texture_level),
557 wined3d_texture_get_level_pow2_height(rt_texture, render_targets[i]->texture_level),
558 rt_texture->resource.multisample_type);
561 if (depth_stencil)
563 ds_texture = depth_stencil->container;
564 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
565 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
566 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texture",
567 context->fbo_key->objects[0].object,
568 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
569 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
570 ds_texture->resource.multisample_type);
574 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
576 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
577 continue;
579 list_remove(&entry->entry);
580 list_add_head(&context->fbo_list, &entry->entry);
581 return entry;
584 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
586 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
587 list_add_head(&context->fbo_list, &entry->entry);
588 ++context->fbo_entry_count;
590 else
592 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
593 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
594 list_remove(&entry->entry);
595 list_add_head(&context->fbo_list, &entry->entry);
598 return entry;
601 /* Context activation is done by the caller. */
602 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
604 const struct wined3d_gl_info *gl_info = context->gl_info;
605 unsigned int i;
606 GLuint read_binding, draw_binding;
608 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
610 context_bind_fbo(context, target, entry->id);
611 return;
614 read_binding = context->fbo_read_binding;
615 draw_binding = context->fbo_draw_binding;
616 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
618 /* Apply render targets */
619 for (i = 0; i < gl_info->limits.buffers; ++i)
621 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
622 entry->key.rb_namespace & (1 << (i + 1)));
625 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
626 entry->key.rb_namespace & 0x1, entry->flags);
628 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
629 * GL contexts requirements. */
630 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
631 context_set_draw_buffer(context, GL_NONE);
632 if (target != GL_FRAMEBUFFER)
634 if (target == GL_READ_FRAMEBUFFER)
635 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
636 else
637 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
640 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
643 /* Context activation is done by the caller. */
644 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
645 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
646 DWORD color_location, DWORD ds_location)
648 struct fbo_entry *entry, *entry2;
650 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
652 context_destroy_fbo_entry(context, entry);
655 if (context->rebind_fbo)
657 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
658 context->rebind_fbo = FALSE;
661 if (color_location == WINED3D_LOCATION_DRAWABLE)
663 context->current_fbo = NULL;
664 context_bind_fbo(context, target, 0);
666 else
668 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
669 color_location, ds_location);
670 context_apply_fbo_entry(context, target, context->current_fbo);
674 /* Context activation is done by the caller. */
675 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
676 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
678 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
680 context->blit_targets[0] = render_target;
681 if (clear_size)
682 memset(&context->blit_targets[1], 0, clear_size);
683 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
686 /* Context activation is done by the caller. */
687 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
689 const struct wined3d_gl_info *gl_info = context->gl_info;
691 if (context->free_occlusion_query_count)
693 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
695 else
697 if (gl_info->supported[ARB_OCCLUSION_QUERY])
699 GL_EXTCALL(glGenQueries(1, &query->id));
700 checkGLcall("glGenQueries");
702 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
704 else
706 WARN("Occlusion queries not supported, not allocating query id.\n");
707 query->id = 0;
711 query->context = context;
712 list_add_head(&context->occlusion_queries, &query->entry);
715 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
717 struct wined3d_context *context = query->context;
719 list_remove(&query->entry);
720 query->context = NULL;
722 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
724 UINT new_size = context->free_occlusion_query_size << 1;
725 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
726 new_size * sizeof(*context->free_occlusion_queries));
728 if (!new_data)
730 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
731 return;
734 context->free_occlusion_query_size = new_size;
735 context->free_occlusion_queries = new_data;
738 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
741 /* Context activation is done by the caller. */
742 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
744 const struct wined3d_gl_info *gl_info = context->gl_info;
746 if (context->free_event_query_count)
748 query->object = context->free_event_queries[--context->free_event_query_count];
750 else
752 if (gl_info->supported[ARB_SYNC])
754 /* Using ARB_sync, not much to do here. */
755 query->object.sync = NULL;
756 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
758 else if (gl_info->supported[APPLE_FENCE])
760 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
761 checkGLcall("glGenFencesAPPLE");
763 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
765 else if(gl_info->supported[NV_FENCE])
767 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
768 checkGLcall("glGenFencesNV");
770 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
772 else
774 WARN("Event queries not supported, not allocating query id.\n");
775 query->object.id = 0;
779 query->context = context;
780 list_add_head(&context->event_queries, &query->entry);
783 void context_free_event_query(struct wined3d_event_query *query)
785 struct wined3d_context *context = query->context;
787 list_remove(&query->entry);
788 query->context = NULL;
790 if (context->free_event_query_count >= context->free_event_query_size - 1)
792 UINT new_size = context->free_event_query_size << 1;
793 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
794 new_size * sizeof(*context->free_event_queries));
796 if (!new_data)
798 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
799 return;
802 context->free_event_query_size = new_size;
803 context->free_event_queries = new_data;
806 context->free_event_queries[context->free_event_query_count++] = query->object;
809 /* Context activation is done by the caller. */
810 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
812 const struct wined3d_gl_info *gl_info = context->gl_info;
814 if (context->free_timestamp_query_count)
816 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
818 else
820 GL_EXTCALL(glGenQueries(1, &query->id));
821 checkGLcall("glGenQueries");
823 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
826 query->context = context;
827 list_add_head(&context->timestamp_queries, &query->entry);
830 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
832 struct wined3d_context *context = query->context;
834 list_remove(&query->entry);
835 query->context = NULL;
837 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
839 UINT new_size = context->free_timestamp_query_size << 1;
840 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
841 new_size * sizeof(*context->free_timestamp_queries));
843 if (!new_data)
845 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
846 return;
849 context->free_timestamp_query_size = new_size;
850 context->free_timestamp_queries = new_data;
853 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
856 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
858 static void context_enum_fbo_entries(const struct wined3d_device *device,
859 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
861 UINT i;
863 for (i = 0; i < device->context_count; ++i)
865 struct wined3d_context *context = device->contexts[i];
866 const struct wined3d_gl_info *gl_info = context->gl_info;
867 struct fbo_entry *entry, *entry2;
869 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
871 UINT j;
873 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
875 if (entry->key.objects[j].object == name
876 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
878 callback(context, entry);
879 break;
886 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
888 list_remove(&entry->entry);
889 list_add_head(&context->fbo_destroy_list, &entry->entry);
892 void context_resource_released(const struct wined3d_device *device,
893 struct wined3d_resource *resource, enum wined3d_resource_type type)
895 struct wined3d_texture *texture;
896 UINT i;
898 if (!device->d3d_initialized)
899 return;
901 switch (type)
903 case WINED3D_RTYPE_TEXTURE_2D:
904 case WINED3D_RTYPE_TEXTURE_3D:
905 texture = texture_from_resource(resource);
907 for (i = 0; i < device->context_count; ++i)
909 struct wined3d_context *context = device->contexts[i];
910 if (context->current_rt.texture == texture)
912 context->current_rt.texture = NULL;
913 context->current_rt.sub_resource_idx = 0;
916 break;
918 default:
919 break;
923 void context_gl_resource_released(struct wined3d_device *device,
924 GLuint name, BOOL rb_namespace)
926 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
929 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
931 const struct wined3d_gl_info *gl_info = context->gl_info;
932 struct fbo_entry *entry = context->current_fbo;
933 unsigned int i;
935 if (!entry || context->rebind_fbo) return;
937 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
939 if (surface->container->texture_rgb.name == entry->key.objects[i].object
940 || surface->container->texture_srgb.name == entry->key.objects[i].object)
942 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
943 context->rebind_fbo = TRUE;
944 return;
949 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
951 const struct wined3d_gl_info *gl_info = ctx->gl_info;
952 BOOL ret = FALSE;
954 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
956 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
958 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
959 if (dc)
961 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
963 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
964 ctx->restore_pf, ctx->restore_pf_win);
966 ReleaseDC(ctx->restore_pf_win, dc);
969 else
971 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
975 ctx->restore_pf = 0;
976 ctx->restore_pf_win = NULL;
977 return ret;
980 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
982 const struct wined3d_gl_info *gl_info = context->gl_info;
983 int current;
985 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
986 return TRUE;
988 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
989 if (current == format) goto success;
991 if (!current)
993 if (!SetPixelFormat(dc, format, NULL))
995 /* This may also happen if the dc belongs to a destroyed window. */
996 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
997 format, dc, GetLastError());
998 return FALSE;
1001 context->restore_pf = 0;
1002 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
1003 goto success;
1006 /* By default WGL doesn't allow pixel format adjustments but we need it
1007 * here. For this reason there's a Wine specific wglSetPixelFormat()
1008 * which allows us to set the pixel format multiple times. Only use it
1009 * when really needed. */
1010 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1012 HWND win;
1014 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
1016 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
1017 format, dc);
1018 return FALSE;
1021 win = private ? NULL : WindowFromDC(dc);
1022 if (win != context->restore_pf_win)
1024 context_restore_pixel_format(context);
1026 context->restore_pf = private ? 0 : current;
1027 context->restore_pf_win = win;
1030 goto success;
1033 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1034 * continue using the old format. There's a big chance that the old
1035 * format works although with a performance hit and perhaps rendering
1036 * errors. */
1037 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1038 format, dc, current);
1039 return TRUE;
1041 success:
1042 if (dc == context->hdc && context->hdc_is_private)
1043 context->hdc_has_format = TRUE;
1044 return TRUE;
1047 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1049 struct wined3d_swapchain *swapchain = ctx->swapchain;
1050 BOOL backup = FALSE;
1052 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
1054 WARN("Failed to set pixel format %d on device context %p.\n",
1055 ctx->pixel_format, ctx->hdc);
1056 backup = TRUE;
1059 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1061 HDC dc;
1063 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1064 ctx->glCtx, ctx->hdc, GetLastError());
1065 ctx->valid = 0;
1066 WARN("Trying fallback to the backup window.\n");
1068 /* FIXME: If the context is destroyed it's no longer associated with
1069 * a swapchain, so we can't use the swapchain to get a backup dc. To
1070 * make this work windowless contexts would need to be handled by the
1071 * device. */
1072 if (ctx->destroyed || !swapchain)
1074 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1075 context_set_current(NULL);
1076 return FALSE;
1079 if (!(dc = swapchain_get_backup_dc(swapchain)))
1081 context_set_current(NULL);
1082 return FALSE;
1085 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
1087 ERR("Failed to set pixel format %d on device context %p.\n",
1088 ctx->pixel_format, dc);
1089 context_set_current(NULL);
1090 return FALSE;
1093 if (!wglMakeCurrent(dc, ctx->glCtx))
1095 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1096 dc, GetLastError());
1097 context_set_current(NULL);
1098 return FALSE;
1101 ctx->valid = 1;
1103 ctx->needs_set = 0;
1104 return TRUE;
1107 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1109 if (!wglMakeCurrent(dc, gl_ctx))
1111 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1112 gl_ctx, dc, GetLastError());
1113 context_set_current(NULL);
1117 static void context_update_window(struct wined3d_context *context)
1119 if (!context->swapchain)
1120 return;
1122 if (context->win_handle == context->swapchain->win_handle)
1123 return;
1125 TRACE("Updating context %p window from %p to %p.\n",
1126 context, context->win_handle, context->swapchain->win_handle);
1128 if (context->hdc)
1129 wined3d_release_dc(context->win_handle, context->hdc);
1131 context->win_handle = context->swapchain->win_handle;
1132 context->hdc_is_private = FALSE;
1133 context->hdc_has_format = FALSE;
1134 context->needs_set = 1;
1135 context->valid = 1;
1137 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1139 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1140 context->valid = 0;
1144 static void context_destroy_gl_resources(struct wined3d_context *context)
1146 const struct wined3d_gl_info *gl_info = context->gl_info;
1147 struct wined3d_timestamp_query *timestamp_query;
1148 struct wined3d_occlusion_query *occlusion_query;
1149 struct wined3d_event_query *event_query;
1150 struct fbo_entry *entry, *entry2;
1151 HGLRC restore_ctx;
1152 HDC restore_dc;
1153 unsigned int i;
1155 restore_ctx = wglGetCurrentContext();
1156 restore_dc = wglGetCurrentDC();
1158 if (restore_ctx == context->glCtx)
1159 restore_ctx = NULL;
1160 else if (context->valid)
1161 context_set_gl_context(context);
1163 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1165 if (context->valid)
1166 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1167 timestamp_query->context = NULL;
1170 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1172 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1173 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1174 occlusion_query->context = NULL;
1177 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1179 if (context->valid)
1181 if (gl_info->supported[ARB_SYNC])
1183 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1185 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1186 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1188 event_query->context = NULL;
1191 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1193 if (!context->valid) entry->id = 0;
1194 context_destroy_fbo_entry(context, entry);
1197 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1199 if (!context->valid) entry->id = 0;
1200 context_destroy_fbo_entry(context, entry);
1203 if (context->valid)
1205 if (context->dummy_arbfp_prog)
1207 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1210 if (gl_info->supported[ARB_TIMER_QUERY])
1211 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1213 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1214 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1216 if (gl_info->supported[ARB_SYNC])
1218 for (i = 0; i < context->free_event_query_count; ++i)
1220 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1223 else if (gl_info->supported[APPLE_FENCE])
1225 for (i = 0; i < context->free_event_query_count; ++i)
1227 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1230 else if (gl_info->supported[NV_FENCE])
1232 for (i = 0; i < context->free_event_query_count; ++i)
1234 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1238 checkGLcall("context cleanup");
1241 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1242 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1243 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1245 context_restore_pixel_format(context);
1246 if (restore_ctx)
1248 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1250 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1252 ERR("Failed to disable GL context.\n");
1255 wined3d_release_dc(context->win_handle, context->hdc);
1257 if (!wglDeleteContext(context->glCtx))
1259 DWORD err = GetLastError();
1260 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1264 DWORD context_get_tls_idx(void)
1266 return wined3d_context_tls_idx;
1269 void context_set_tls_idx(DWORD idx)
1271 wined3d_context_tls_idx = idx;
1274 struct wined3d_context *context_get_current(void)
1276 return TlsGetValue(wined3d_context_tls_idx);
1279 BOOL context_set_current(struct wined3d_context *ctx)
1281 struct wined3d_context *old = context_get_current();
1283 if (old == ctx)
1285 TRACE("Already using D3D context %p.\n", ctx);
1286 return TRUE;
1289 if (old)
1291 if (old->destroyed)
1293 TRACE("Switching away from destroyed context %p.\n", old);
1294 context_destroy_gl_resources(old);
1295 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1296 HeapFree(GetProcessHeap(), 0, old);
1298 else
1300 if (wglGetCurrentContext())
1302 const struct wined3d_gl_info *gl_info = old->gl_info;
1303 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1304 gl_info->gl_ops.gl.p_glFlush();
1306 old->current = 0;
1310 if (ctx)
1312 if (!ctx->valid)
1314 ERR("Trying to make invalid context %p current\n", ctx);
1315 return FALSE;
1318 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1319 if (!context_set_gl_context(ctx))
1320 return FALSE;
1321 ctx->current = 1;
1323 else if (wglGetCurrentContext())
1325 TRACE("Clearing current D3D context.\n");
1326 if (!wglMakeCurrent(NULL, NULL))
1328 DWORD err = GetLastError();
1329 ERR("Failed to clear current GL context, last error %#x.\n", err);
1330 TlsSetValue(wined3d_context_tls_idx, NULL);
1331 return FALSE;
1335 return TlsSetValue(wined3d_context_tls_idx, ctx);
1338 void context_release(struct wined3d_context *context)
1340 TRACE("Releasing context %p, level %u.\n", context, context->level);
1342 if (WARN_ON(d3d))
1344 if (!context->level)
1345 WARN("Context %p is not active.\n", context);
1346 else if (context != context_get_current())
1347 WARN("Context %p is not the current context.\n", context);
1350 if (!--context->level)
1352 if (context_restore_pixel_format(context))
1353 context->needs_set = 1;
1354 if (context->restore_ctx)
1356 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1357 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1358 context->restore_ctx = NULL;
1359 context->restore_dc = NULL;
1362 if (context->destroy_delayed)
1364 TRACE("Destroying context %p.\n", context);
1365 context_destroy(context->device, context);
1370 /* This is used when a context for render target A is active, but a separate context is
1371 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1372 * A to avoid breaking caller code. */
1373 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1375 if (context->current_rt.texture != restore->container
1376 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1378 context_release(context);
1379 context = context_acquire(restore->container->resource.device, restore);
1382 context_release(context);
1385 static void context_enter(struct wined3d_context *context)
1387 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1389 if (!context->level++)
1391 const struct wined3d_context *current_context = context_get_current();
1392 HGLRC current_gl = wglGetCurrentContext();
1394 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1396 TRACE("Another GL context (%p on device context %p) is already current.\n",
1397 current_gl, wglGetCurrentDC());
1398 context->restore_ctx = current_gl;
1399 context->restore_dc = wglGetCurrentDC();
1400 context->needs_set = 1;
1402 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1403 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1404 context->needs_set = 1;
1408 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1410 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1411 unsigned int index, shift;
1413 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1414 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1415 context->dirty_compute_states[index] |= (1u << shift);
1418 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1420 DWORD rep = context->state_table[state].representative;
1421 DWORD idx;
1422 BYTE shift;
1424 if (isStateDirty(context, rep)) return;
1426 context->dirtyArray[context->numDirtyEntries++] = rep;
1427 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1428 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1429 context->isStateDirty[idx] |= (1u << shift);
1432 /* This function takes care of wined3d pixel format selection. */
1433 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1434 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1435 BOOL auxBuffers)
1437 unsigned int cfg_count = device->adapter->cfg_count;
1438 unsigned int current_value;
1439 PIXELFORMATDESCRIPTOR pfd;
1440 int iPixelFormat = 0;
1441 unsigned int i;
1443 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1444 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1445 auxBuffers);
1447 current_value = 0;
1448 for (i = 0; i < cfg_count; ++i)
1450 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1451 unsigned int value;
1453 /* For now only accept RGBA formats. Perhaps some day we will
1454 * allow floating point formats for pbuffers. */
1455 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1456 continue;
1457 /* In window mode we need a window drawable format and double buffering. */
1458 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1459 continue;
1460 if (cfg->redSize < color_format->red_size)
1461 continue;
1462 if (cfg->greenSize < color_format->green_size)
1463 continue;
1464 if (cfg->blueSize < color_format->blue_size)
1465 continue;
1466 if (cfg->alphaSize < color_format->alpha_size)
1467 continue;
1468 if (cfg->depthSize < ds_format->depth_size)
1469 continue;
1470 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1471 continue;
1472 /* Check multisampling support. */
1473 if (cfg->numSamples)
1474 continue;
1476 value = 1;
1477 /* We try to locate a format which matches our requirements exactly. In case of
1478 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1479 if (cfg->depthSize == ds_format->depth_size)
1480 value += 1;
1481 if (cfg->stencilSize == ds_format->stencil_size)
1482 value += 2;
1483 if (cfg->alphaSize == color_format->alpha_size)
1484 value += 4;
1485 /* We like to have aux buffers in backbuffer mode */
1486 if (auxBuffers && cfg->auxBuffers)
1487 value += 8;
1488 if (cfg->redSize == color_format->red_size
1489 && cfg->greenSize == color_format->green_size
1490 && cfg->blueSize == color_format->blue_size)
1491 value += 16;
1493 if (value > current_value)
1495 iPixelFormat = cfg->iPixelFormat;
1496 current_value = value;
1500 if (!iPixelFormat)
1502 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1504 memset(&pfd, 0, sizeof(pfd));
1505 pfd.nSize = sizeof(pfd);
1506 pfd.nVersion = 1;
1507 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1508 pfd.iPixelType = PFD_TYPE_RGBA;
1509 pfd.cAlphaBits = color_format->alpha_size;
1510 pfd.cColorBits = color_format->red_size + color_format->green_size
1511 + color_format->blue_size + color_format->alpha_size;
1512 pfd.cDepthBits = ds_format->depth_size;
1513 pfd.cStencilBits = ds_format->stencil_size;
1514 pfd.iLayerType = PFD_MAIN_PLANE;
1516 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1518 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1519 ERR("Can't find a suitable pixel format.\n");
1520 return 0;
1524 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1525 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1526 return iPixelFormat;
1529 /* Context activation is done by the caller. */
1530 void context_bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1532 const struct wined3d_gl_info *gl_info = context->gl_info;
1533 unsigned int i;
1535 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1537 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1538 checkGLcall("glActiveTexture");
1540 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
1542 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1543 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
1545 if (gl_info->supported[EXT_TEXTURE3D])
1546 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
1548 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1549 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
1551 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1552 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
1554 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1555 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
1557 checkGLcall("Bind dummy textures");
1561 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1562 const char *file, unsigned int line, const char *name)
1564 GLint err;
1566 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1568 TRACE("%s call ok %s / %u.\n", name, file, line);
1569 return;
1574 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1575 debug_glerror(err), err, name, file,line);
1576 err = gl_info->gl_ops.gl.p_glGetError();
1577 } while (err != GL_NO_ERROR);
1580 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1582 return gl_info->supported[ARB_DEBUG_OUTPUT]
1583 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1586 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1587 GLenum severity, GLsizei length, const char *message, void *ctx)
1589 switch (type)
1591 case GL_DEBUG_TYPE_ERROR_ARB:
1592 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1593 break;
1595 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1596 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1597 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1598 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1599 break;
1601 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1602 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1603 break;
1605 default:
1606 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1607 break;
1611 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1613 HGLRC ctx;
1614 unsigned int ctx_attrib_idx = 0;
1615 GLint ctx_attribs[7], ctx_flags = 0;
1617 if (context_debug_output_enabled(gl_info))
1618 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1619 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1620 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1621 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1622 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1623 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1624 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1625 if (ctx_flags)
1627 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1628 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1630 ctx_attribs[ctx_attrib_idx] = 0;
1632 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1634 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1636 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1637 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1638 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1639 GetLastError());
1642 return ctx;
1645 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1646 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1648 struct wined3d_device *device = swapchain->device;
1649 const struct wined3d_d3d_info *d3d_info = &device->adapter->d3d_info;
1650 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1651 const struct wined3d_format *color_format;
1652 struct wined3d_context *ret;
1653 BOOL hdc_is_private = FALSE;
1654 BOOL auxBuffers = FALSE;
1655 HGLRC ctx, share_ctx;
1656 DWORD target_usage;
1657 int pixel_format;
1658 unsigned int s;
1659 DWORD state;
1660 HDC hdc = 0;
1662 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1664 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1665 if (!ret)
1666 return NULL;
1668 if (!(ret->blit_targets = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->blit_targets))))
1669 goto out;
1671 if (!(ret->draw_buffers = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->draw_buffers))))
1672 goto out;
1674 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1675 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1676 if (!ret->fbo_key)
1677 goto out;
1679 ret->free_timestamp_query_size = 4;
1680 if (!(ret->free_timestamp_queries = wined3d_calloc(ret->free_timestamp_query_size,
1681 sizeof(*ret->free_timestamp_queries))))
1682 goto out;
1683 list_init(&ret->timestamp_queries);
1685 ret->free_occlusion_query_size = 4;
1686 if (!(ret->free_occlusion_queries = wined3d_calloc(ret->free_occlusion_query_size,
1687 sizeof(*ret->free_occlusion_queries))))
1688 goto out;
1690 list_init(&ret->occlusion_queries);
1692 ret->free_event_query_size = 4;
1693 if (!(ret->free_event_queries = wined3d_calloc(ret->free_event_query_size,
1694 sizeof(*ret->free_event_queries))))
1695 goto out;
1697 list_init(&ret->event_queries);
1698 list_init(&ret->fbo_list);
1699 list_init(&ret->fbo_destroy_list);
1701 if (!device->shader_backend->shader_allocate_context_data(ret))
1703 ERR("Failed to allocate shader backend context data.\n");
1704 goto out;
1706 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1708 ERR("Failed to allocate fragment pipeline context data.\n");
1709 goto out;
1712 /* Initialize the texture unit mapping to a 1:1 mapping */
1713 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1715 if (s < gl_info->limits.combined_samplers)
1717 ret->tex_unit_map[s] = s;
1718 ret->rev_tex_unit_map[s] = s;
1720 else
1722 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1723 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1727 if (!(hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1729 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1731 if ((hdc = swapchain_get_backup_dc(swapchain)))
1732 hdc_is_private = TRUE;
1733 else
1735 ERR("Failed to retrieve a device context.\n");
1736 goto out;
1740 color_format = target->resource.format;
1741 target_usage = target->resource.usage;
1743 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1744 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1745 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1747 auxBuffers = TRUE;
1749 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1750 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM, target_usage);
1751 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1752 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1755 /* DirectDraw supports 8bit paletted render targets and these are used by
1756 * old games like StarCraft and C&C. Most modern hardware doesn't support
1757 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1758 * conversion (ab)uses the alpha component for storing the palette index.
1759 * For this reason we require a format with 8bit alpha, so request
1760 * A8R8G8B8. */
1761 if (color_format->id == WINED3DFMT_P8_UINT)
1762 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1764 /* When using FBOs for off-screen rendering, we only use the drawable for
1765 * presentation blits, and don't do any rendering to it. That means we
1766 * don't need depth or stencil buffers, and can mostly ignore the render
1767 * target format. This wouldn't necessarily be quite correct for 10bpc
1768 * display modes, but we don't currently support those.
1769 * Using the same format regardless of the color/depth/stencil targets
1770 * makes it much less likely that different wined3d instances will set
1771 * conflicting pixel formats. */
1772 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
1774 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1775 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN, WINED3DUSAGE_DEPTHSTENCIL);
1778 /* Try to find a pixel format which matches our requirements. */
1779 if (!(pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers)))
1780 goto out;
1782 ret->gl_info = gl_info;
1784 context_enter(ret);
1786 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1788 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1789 context_release(ret);
1790 goto out;
1793 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1794 if (gl_info->p_wglCreateContextAttribsARB)
1796 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1797 goto out;
1799 else
1801 if (!(ctx = wglCreateContext(hdc)))
1803 ERR("Failed to create a WGL context.\n");
1804 context_release(ret);
1805 goto out;
1808 if (share_ctx && !wglShareLists(share_ctx, ctx))
1810 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1811 context_release(ret);
1812 if (!wglDeleteContext(ctx))
1813 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1814 goto out;
1818 if (!device_context_add(device, ret))
1820 ERR("Failed to add the newly created context to the context list\n");
1821 context_release(ret);
1822 if (!wglDeleteContext(ctx))
1823 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1824 goto out;
1827 ret->d3d_info = d3d_info;
1828 ret->state_table = device->StateTable;
1830 /* Mark all states dirty to force a proper initialization of the states
1831 * on the first use of the context. */
1832 for (state = 0; state <= STATE_HIGHEST; ++state)
1834 if (ret->state_table[state].representative)
1835 context_invalidate_state(ret, state);
1838 ret->device = device;
1839 ret->swapchain = swapchain;
1840 ret->current_rt.texture = target;
1841 ret->current_rt.sub_resource_idx = 0;
1842 ret->tid = GetCurrentThreadId();
1844 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
1845 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1846 ret->valid = 1;
1848 ret->glCtx = ctx;
1849 ret->win_handle = swapchain->win_handle;
1850 ret->hdc = hdc;
1851 ret->hdc_is_private = hdc_is_private;
1852 ret->hdc_has_format = TRUE;
1853 ret->pixel_format = pixel_format;
1854 ret->needs_set = 1;
1856 /* Set up the context defaults */
1857 if (!context_set_current(ret))
1859 ERR("Cannot activate context to set up defaults.\n");
1860 device_context_remove(device, ret);
1861 context_release(ret);
1862 if (!wglDeleteContext(ctx))
1863 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1864 goto out;
1867 if (context_debug_output_enabled(gl_info))
1869 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1870 if (TRACE_ON(d3d_synchronous))
1871 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1872 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1873 if (ERR_ON(d3d))
1875 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1876 GL_DONT_CARE, 0, NULL, GL_TRUE));
1878 if (FIXME_ON(d3d))
1880 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1881 GL_DONT_CARE, 0, NULL, GL_TRUE));
1882 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1883 GL_DONT_CARE, 0, NULL, GL_TRUE));
1884 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1885 GL_DONT_CARE, 0, NULL, GL_TRUE));
1887 if (WARN_ON(d3d_perf))
1889 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1890 GL_DONT_CARE, 0, NULL, GL_TRUE));
1894 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1895 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1897 TRACE("Setting up the screen\n");
1899 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1901 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1902 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1904 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1905 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1907 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1908 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1910 else
1912 GLuint vao;
1914 GL_EXTCALL(glGenVertexArrays(1, &vao));
1915 GL_EXTCALL(glBindVertexArray(vao));
1916 checkGLcall("creating VAO");
1919 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1920 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1921 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1922 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
1924 if (gl_info->supported[ARB_VERTEX_BLEND])
1926 /* Direct3D always uses n-1 weights for n world matrices and uses
1927 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1928 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1929 * enabled as well. */
1930 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1931 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1933 if (gl_info->supported[NV_TEXTURE_SHADER2])
1935 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1936 * the previous texture where to source the offset from is always unit - 1.
1938 for (s = 1; s < gl_info->limits.textures; ++s)
1940 context_active_texture(ret, gl_info, s);
1941 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1942 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1943 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1946 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1948 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1949 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1950 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1951 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1952 * is ever assigned.
1954 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1955 * program and the dummy program is destroyed when the context is destroyed.
1957 static const char dummy_program[] =
1958 "!!ARBfp1.0\n"
1959 "MOV result.color, fragment.color.primary;\n"
1960 "END\n";
1961 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1962 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1963 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1966 if (gl_info->supported[ARB_POINT_SPRITE])
1968 for (s = 0; s < gl_info->limits.textures; ++s)
1970 context_active_texture(ret, gl_info, s);
1971 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1972 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1976 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1978 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1980 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1982 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1984 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
1986 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
1988 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
1989 checkGLcall("Enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
1991 else
1993 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
1996 if (gl_info->supported[ARB_CLIP_CONTROL])
1997 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
1998 device->shader_backend->shader_init_context_state(ret);
1999 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
2000 | (1u << WINED3D_SHADER_TYPE_VERTEX)
2001 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
2002 | (1u << WINED3D_SHADER_TYPE_HULL)
2003 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
2004 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
2006 /* If this happens to be the first context for the device, dummy textures
2007 * are not created yet. In that case, they will be created (and bound) by
2008 * create_dummy_textures right after this context is initialized. */
2009 if (device->dummy_textures.tex_2d)
2010 context_bind_dummy_textures(device, ret);
2012 TRACE("Created context %p.\n", ret);
2014 return ret;
2016 out:
2017 if (hdc) wined3d_release_dc(swapchain->win_handle, hdc);
2018 device->shader_backend->shader_free_context_data(ret);
2019 device->adapter->fragment_pipe->free_context_data(ret);
2020 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
2021 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
2022 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
2023 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
2024 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
2025 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
2026 HeapFree(GetProcessHeap(), 0, ret);
2027 return NULL;
2030 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2032 BOOL destroy;
2034 TRACE("Destroying ctx %p\n", context);
2036 /* We delay destroying a context when it is active. The context_release()
2037 * function invokes context_destroy() again while leaving the last level. */
2038 if (context->level)
2040 TRACE("Delaying destruction of context %p.\n", context);
2041 context->destroy_delayed = 1;
2042 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2043 context->swapchain = NULL;
2044 return;
2047 if (context->tid == GetCurrentThreadId() || !context->current)
2049 context_destroy_gl_resources(context);
2050 TlsSetValue(wined3d_context_tls_idx, NULL);
2051 destroy = TRUE;
2053 else
2055 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2056 in wined3d_adapter may go away in the meantime */
2057 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2058 *gl_info = *context->gl_info;
2059 context->gl_info = gl_info;
2060 context->destroyed = 1;
2061 destroy = FALSE;
2064 device->shader_backend->shader_free_context_data(context);
2065 device->adapter->fragment_pipe->free_context_data(context);
2066 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2067 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2068 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2069 device_context_remove(device, context);
2070 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2073 /* Context activation is done by the caller. */
2074 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2076 const GLdouble projection[] =
2078 2.0 / width, 0.0, 0.0, 0.0,
2079 0.0, 2.0 / height, 0.0, 0.0,
2080 0.0, 0.0, 2.0, 0.0,
2081 -1.0, -1.0, -1.0, 1.0,
2084 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2085 checkGLcall("glMatrixMode(GL_PROJECTION)");
2086 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2087 checkGLcall("glLoadMatrixd");
2088 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2089 checkGLcall("glViewport");
2092 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2094 const struct wined3d_texture *rt = context->current_rt.texture;
2095 unsigned int level;
2097 if (rt->swapchain && rt->swapchain->front_buffer == rt)
2099 RECT window_size;
2101 GetClientRect(context->win_handle, &window_size);
2102 size->cx = window_size.right - window_size.left;
2103 size->cy = window_size.bottom - window_size.top;
2105 return;
2108 level = context->current_rt.sub_resource_idx % rt->level_count;
2109 size->cx = wined3d_texture_get_level_width(rt, level);
2110 size->cy = wined3d_texture_get_level_height(rt, level);
2113 /*****************************************************************************
2114 * SetupForBlit
2116 * Sets up a context for DirectDraw blitting.
2117 * All texture units are disabled, texture unit 0 is set as current unit
2118 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2119 * color writing enabled for all channels
2120 * register combiners disabled, shaders disabled
2121 * world matrix is set to identity, texture matrix 0 too
2122 * projection matrix is setup for drawing screen coordinates
2124 * Params:
2125 * This: Device to activate the context for
2126 * context: Context to setup
2128 *****************************************************************************/
2129 /* Context activation is done by the caller. */
2130 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2132 int i;
2133 const struct wined3d_gl_info *gl_info = context->gl_info;
2134 DWORD sampler;
2135 SIZE rt_size;
2137 TRACE("Setting up context %p for blitting\n", context);
2139 context_get_rt_size(context, &rt_size);
2141 if (context->last_was_blit)
2143 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2145 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2146 context->blit_w = rt_size.cx;
2147 context->blit_h = rt_size.cy;
2148 /* No need to dirtify here, the states are still dirtified because
2149 * they weren't applied since the last SetupForBlit() call. */
2151 TRACE("Context is already set up for blitting, nothing to do\n");
2152 return;
2154 context->last_was_blit = TRUE;
2156 /* Disable all textures. The caller can then bind a texture it wants to blit
2157 * from
2159 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2160 * function texture unit. No need to care for higher samplers
2162 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2164 sampler = context->rev_tex_unit_map[i];
2165 context_active_texture(context, gl_info, i);
2167 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2169 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2170 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2172 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2173 checkGLcall("glDisable GL_TEXTURE_3D");
2174 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2176 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2177 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2179 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2180 checkGLcall("glDisable GL_TEXTURE_2D");
2182 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2183 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2185 if (sampler != WINED3D_UNMAPPED_STAGE)
2187 if (sampler < MAX_TEXTURES)
2188 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2189 context_invalidate_state(context, STATE_SAMPLER(sampler));
2192 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2193 GL_EXTCALL(glBindSampler(0, 0));
2194 context_active_texture(context, gl_info, 0);
2196 sampler = context->rev_tex_unit_map[0];
2198 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2200 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2201 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2203 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2204 checkGLcall("glDisable GL_TEXTURE_3D");
2205 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2207 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2208 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2210 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2211 checkGLcall("glDisable GL_TEXTURE_2D");
2213 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2215 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2216 checkGLcall("glMatrixMode(GL_TEXTURE)");
2217 gl_info->gl_ops.gl.p_glLoadIdentity();
2218 checkGLcall("glLoadIdentity()");
2220 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2222 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2223 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2224 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2227 if (sampler != WINED3D_UNMAPPED_STAGE)
2229 if (sampler < MAX_TEXTURES)
2231 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2232 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2234 context_invalidate_state(context, STATE_SAMPLER(sampler));
2237 /* Other misc states */
2238 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2239 checkGLcall("glDisable(GL_ALPHA_TEST)");
2240 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2241 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2242 checkGLcall("glDisable GL_LIGHTING");
2243 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2244 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2245 checkGLcall("glDisable GL_DEPTH_TEST");
2246 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2247 glDisableWINE(GL_FOG);
2248 checkGLcall("glDisable GL_FOG");
2249 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2250 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2251 checkGLcall("glDisable GL_BLEND");
2252 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2253 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2254 checkGLcall("glDisable GL_CULL_FACE");
2255 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2256 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2257 checkGLcall("glDisable GL_STENCIL_TEST");
2258 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2259 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2260 checkGLcall("glDisable GL_SCISSOR_TEST");
2261 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2262 if (gl_info->supported[ARB_POINT_SPRITE])
2264 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2265 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2266 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2268 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2269 checkGLcall("glColorMask");
2270 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2271 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2272 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2273 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2274 if (gl_info->supported[EXT_SECONDARY_COLOR])
2276 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2277 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2278 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2281 /* Setup transforms */
2282 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2283 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2284 gl_info->gl_ops.gl.p_glLoadIdentity();
2285 checkGLcall("glLoadIdentity()");
2286 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2288 context->last_was_rhw = TRUE;
2289 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2291 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2292 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2293 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2294 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2295 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2296 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2297 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2299 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2300 if (gl_info->supported[ARB_CLIP_CONTROL])
2301 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2303 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2305 /* Disable shaders */
2306 device->shader_backend->shader_disable(device->shader_priv, context);
2308 context->blit_w = rt_size.cx;
2309 context->blit_h = rt_size.cy;
2310 context_invalidate_state(context, STATE_VIEWPORT);
2311 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2314 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2316 return rt_mask & (1u << 31);
2319 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2321 return rt_mask & ~(1u << 31);
2324 /* Context activation is done by the caller. */
2325 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2327 const struct wined3d_gl_info *gl_info = context->gl_info;
2329 if (!rt_mask)
2331 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2332 checkGLcall("glDrawBuffer()");
2334 else if (is_rt_mask_onscreen(rt_mask))
2336 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2337 checkGLcall("glDrawBuffer()");
2339 else
2341 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2343 unsigned int i = 0;
2345 while (rt_mask)
2347 if (rt_mask & 1)
2348 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2349 else
2350 context->draw_buffers[i] = GL_NONE;
2352 rt_mask >>= 1;
2353 ++i;
2356 if (gl_info->supported[ARB_DRAW_BUFFERS])
2358 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2359 checkGLcall("glDrawBuffers()");
2361 else
2363 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2364 checkGLcall("glDrawBuffer()");
2367 else
2369 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2374 /* Context activation is done by the caller. */
2375 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2377 const struct wined3d_gl_info *gl_info = context->gl_info;
2378 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2379 DWORD new_mask = context_generate_rt_mask(buffer);
2381 if (new_mask == *current_mask)
2382 return;
2384 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2385 checkGLcall("glDrawBuffer()");
2387 *current_mask = new_mask;
2390 /* Context activation is done by the caller. */
2391 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2393 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2394 checkGLcall("glActiveTexture");
2395 context->active_texture = unit;
2398 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2400 const struct wined3d_gl_info *gl_info = context->gl_info;
2401 DWORD unit = context->active_texture;
2402 DWORD old_texture_type = context->texture_type[unit];
2404 if (name)
2406 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2407 checkGLcall("glBindTexture");
2409 else
2411 target = GL_NONE;
2414 if (old_texture_type != target)
2416 const struct wined3d_device *device = context->device;
2418 switch (old_texture_type)
2420 case GL_NONE:
2421 /* nothing to do */
2422 break;
2423 case GL_TEXTURE_2D:
2424 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
2425 checkGLcall("glBindTexture");
2426 break;
2427 case GL_TEXTURE_2D_ARRAY:
2428 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
2429 checkGLcall("glBindTexture");
2430 break;
2431 case GL_TEXTURE_RECTANGLE_ARB:
2432 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
2433 checkGLcall("glBindTexture");
2434 break;
2435 case GL_TEXTURE_CUBE_MAP:
2436 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
2437 checkGLcall("glBindTexture");
2438 break;
2439 case GL_TEXTURE_CUBE_MAP_ARRAY:
2440 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, 0);
2441 checkGLcall("glBindTexture");
2442 break;
2443 case GL_TEXTURE_3D:
2444 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
2445 checkGLcall("glBindTexture");
2446 break;
2447 case GL_TEXTURE_BUFFER:
2448 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
2449 checkGLcall("glBindTexture");
2450 break;
2451 default:
2452 ERR("Unexpected texture target %#x.\n", old_texture_type);
2455 context->texture_type[unit] = target;
2459 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2461 if (context->render_offscreen == offscreen) return;
2463 context_invalidate_state(context, STATE_VIEWPORT);
2464 context_invalidate_state(context, STATE_SCISSORRECT);
2465 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2467 context_invalidate_state(context, STATE_FRONTFACE);
2468 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2469 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2471 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2472 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2473 context->render_offscreen = offscreen;
2476 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2477 const struct wined3d_format *required)
2479 if (existing == required)
2480 return TRUE;
2481 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2482 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2483 return FALSE;
2484 if (existing->depth_size < required->depth_size)
2485 return FALSE;
2486 /* If stencil bits are used the exact amount is required - otherwise
2487 * wrapping won't work correctly. */
2488 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2489 return FALSE;
2490 return TRUE;
2493 /* Context activation is done by the caller. */
2494 static void context_validate_onscreen_formats(struct wined3d_context *context,
2495 const struct wined3d_rendertarget_view *depth_stencil)
2497 /* Onscreen surfaces are always in a swapchain */
2498 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2500 if (context->render_offscreen || !depth_stencil) return;
2501 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2503 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2504 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2505 * format. */
2506 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2508 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2509 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2510 context, WINED3D_LOCATION_TEXTURE_RGB)))
2511 ERR("Failed to load location.\n");
2512 swapchain->render_to_fbo = TRUE;
2513 swapchain_update_draw_bindings(swapchain);
2514 context_set_render_offscreen(context, TRUE);
2517 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2519 switch (wined3d_settings.offscreen_rendering_mode)
2521 case ORM_FBO:
2522 return GL_COLOR_ATTACHMENT0;
2524 case ORM_BACKBUFFER:
2525 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2527 default:
2528 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2529 return GL_BACK;
2533 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2535 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2536 return 0;
2537 else if (rt->swapchain)
2538 return context_generate_rt_mask_from_resource(&rt->resource);
2539 else
2540 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2543 /* Context activation is done by the caller. */
2544 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2546 struct wined3d_texture *rt = context->current_rt.texture;
2547 struct wined3d_surface *surface;
2548 DWORD rt_mask, *cur_mask;
2550 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2552 context_validate_onscreen_formats(context, NULL);
2554 if (context->render_offscreen)
2556 wined3d_texture_load(rt, context, FALSE);
2558 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2559 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2560 if (rt->resource.format->id != WINED3DFMT_NULL)
2561 rt_mask = 1;
2562 else
2563 rt_mask = 0;
2565 else
2567 context->current_fbo = NULL;
2568 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2569 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2572 else
2574 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2577 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2579 if (rt_mask != *cur_mask)
2581 context_apply_draw_buffers(context, rt_mask);
2582 *cur_mask = rt_mask;
2585 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2587 context_check_fbo_status(context, GL_FRAMEBUFFER);
2590 SetupForBlit(device, context);
2591 context_invalidate_state(context, STATE_FRAMEBUFFER);
2594 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2595 const struct wined3d_rendertarget_view *ds)
2597 unsigned int i;
2599 if (ds) return TRUE;
2601 for (i = 0; i < rt_count; ++i)
2603 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2604 return TRUE;
2607 WARN("Invalid render target config, need at least one attachment.\n");
2608 return FALSE;
2611 /* Context activation is done by the caller. */
2612 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2613 UINT rt_count, const struct wined3d_fb_state *fb)
2615 struct wined3d_rendertarget_view **rts = fb->render_targets;
2616 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2617 const struct wined3d_gl_info *gl_info = context->gl_info;
2618 DWORD rt_mask = 0, *cur_mask;
2619 UINT i;
2621 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2622 || rt_count != gl_info->limits.buffers)
2624 if (!context_validate_rt_config(rt_count, rts, dsv))
2625 return FALSE;
2627 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2629 context_validate_onscreen_formats(context, dsv);
2631 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2633 for (i = 0; i < rt_count; ++i)
2635 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2636 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2637 rt_mask |= (1u << i);
2639 while (i < gl_info->limits.buffers)
2641 context->blit_targets[i] = NULL;
2642 ++i;
2644 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2645 wined3d_rendertarget_view_get_surface(dsv),
2646 rt_count ? rts[0]->resource->draw_binding : 0,
2647 dsv ? dsv->resource->draw_binding : 0);
2649 else
2651 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2652 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2653 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
2656 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2657 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2658 * state management allows this */
2659 context_invalidate_state(context, STATE_FRAMEBUFFER);
2661 else
2663 rt_mask = context_generate_rt_mask_no_fbo(context,
2664 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2667 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2668 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2670 for (i = 0; i < rt_count; ++i)
2672 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2673 rt_mask |= (1u << i);
2676 else
2678 rt_mask = context_generate_rt_mask_no_fbo(context,
2679 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
2682 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2684 if (rt_mask != *cur_mask)
2686 context_apply_draw_buffers(context, rt_mask);
2687 *cur_mask = rt_mask;
2688 context_invalidate_state(context, STATE_FRAMEBUFFER);
2691 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2693 context_check_fbo_status(context, GL_FRAMEBUFFER);
2696 context->last_was_blit = FALSE;
2698 /* Blending and clearing should be orthogonal, but tests on the nvidia
2699 * driver show that disabling blending when clearing improves the clearing
2700 * performance incredibly. */
2701 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2702 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2703 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2705 if (needs_srgb_write(context, state, fb))
2706 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2707 else
2708 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2709 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2711 checkGLcall("setting up state for clear");
2713 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2714 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2715 context_invalidate_state(context, STATE_SCISSORRECT);
2717 return TRUE;
2720 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2722 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2723 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2724 DWORD rt_mask, rt_mask_bits;
2725 unsigned int i;
2727 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2728 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
2729 else if (!context->render_offscreen)
2730 return context_generate_rt_mask_from_resource(rts[0]->resource);
2732 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2733 rt_mask &= context->d3d_info->valid_rt_mask;
2734 rt_mask_bits = rt_mask;
2735 i = 0;
2736 while (rt_mask_bits)
2738 rt_mask_bits &= ~(1u << i);
2739 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2740 rt_mask &= ~(1u << i);
2742 i++;
2745 return rt_mask;
2748 /* Context activation is done by the caller. */
2749 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2751 DWORD rt_mask = find_draw_buffers_mask(context, state);
2752 const struct wined3d_fb_state *fb = state->fb;
2753 DWORD *cur_mask;
2755 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2757 if (!context->render_offscreen)
2759 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2760 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2762 else
2764 unsigned int i;
2766 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2768 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2770 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2771 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2772 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
2773 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2777 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2778 if (rt_mask != *cur_mask)
2780 context_apply_draw_buffers(context, rt_mask);
2781 *cur_mask = rt_mask;
2783 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
2786 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2788 DWORD i = context->rev_tex_unit_map[unit];
2789 DWORD j = context->tex_unit_map[stage];
2791 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2792 context->tex_unit_map[stage] = unit;
2793 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2794 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2796 context->rev_tex_unit_map[unit] = stage;
2797 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2798 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2801 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2803 DWORD i;
2805 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2806 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2809 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2810 const struct wined3d_state *state)
2812 UINT i, start, end;
2814 context->fixed_function_usage_map = 0;
2815 for (i = 0; i < MAX_TEXTURES; ++i)
2817 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2818 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2819 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2820 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2821 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2822 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2823 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2824 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2826 /* Not used, and disable higher stages. */
2827 if (color_op == WINED3D_TOP_DISABLE)
2828 break;
2830 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2831 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2832 || ((color_arg3 == WINED3DTA_TEXTURE)
2833 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2834 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2835 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2836 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2837 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2838 context->fixed_function_usage_map |= (1u << i);
2840 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2841 && i < MAX_TEXTURES - 1)
2842 context->fixed_function_usage_map |= (1u << (i + 1));
2845 if (i < context->lowest_disabled_stage)
2847 start = i;
2848 end = context->lowest_disabled_stage;
2850 else
2852 start = context->lowest_disabled_stage;
2853 end = i;
2856 context->lowest_disabled_stage = i;
2857 for (i = start + 1; i < end; ++i)
2859 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2863 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2864 const struct wined3d_state *state)
2866 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2867 const struct wined3d_gl_info *gl_info = context->gl_info;
2868 unsigned int i, tex;
2869 WORD ffu_map;
2871 context_update_fixed_function_usage_map(context, state);
2873 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2874 return;
2876 ffu_map = context->fixed_function_usage_map;
2878 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2879 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2881 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2883 if (!(ffu_map & 1))
2884 continue;
2886 if (context->tex_unit_map[i] != i)
2888 context_map_stage(context, i, i);
2889 context_invalidate_state(context, STATE_SAMPLER(i));
2890 context_invalidate_texture_stage(context, i);
2893 return;
2896 /* Now work out the mapping */
2897 tex = 0;
2898 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2900 if (!(ffu_map & 1))
2901 continue;
2903 if (context->tex_unit_map[i] != tex)
2905 context_map_stage(context, i, tex);
2906 context_invalidate_state(context, STATE_SAMPLER(i));
2907 context_invalidate_texture_stage(context, i);
2910 ++tex;
2914 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2916 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2917 const struct wined3d_gl_info *gl_info = context->gl_info;
2918 const struct wined3d_shader_resource_info *resource_info =
2919 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2920 unsigned int i;
2922 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2923 return;
2925 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2927 if (resource_info[i].type && context->tex_unit_map[i] != i)
2929 context_map_stage(context, i, i);
2930 context_invalidate_state(context, STATE_SAMPLER(i));
2931 if (i < d3d_info->limits.ffp_blend_stages)
2932 context_invalidate_texture_stage(context, i);
2937 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2938 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2940 DWORD current_mapping = context->rev_tex_unit_map[unit];
2942 /* Not currently used */
2943 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2944 return TRUE;
2946 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2948 /* Used by a fragment sampler */
2950 if (!ps_resource_info)
2952 /* No pixel shader, check fixed function */
2953 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2956 /* Pixel shader, check the shader's sampler map */
2957 return !ps_resource_info[current_mapping].type;
2960 return TRUE;
2963 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2965 const struct wined3d_shader_resource_info *vs_resource_info =
2966 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2967 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2968 const struct wined3d_gl_info *gl_info = context->gl_info;
2969 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2970 int i;
2972 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2973 return;
2975 /* Note that we only care if a resource is used or not, not the
2976 * resource's specific type. Otherwise we'd need to call
2977 * shader_update_samplers() here for 1.x pixelshaders. */
2978 if (ps)
2979 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2981 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2983 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2984 if (vs_resource_info[i].type)
2986 while (start >= 0)
2988 if (context_unit_free_for_vs(context, ps_resource_info, start))
2990 if (context->tex_unit_map[vsampler_idx] != start)
2992 context_map_stage(context, vsampler_idx, start);
2993 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2996 --start;
2997 break;
3000 --start;
3002 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3003 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3008 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3010 BOOL vs = use_vs(state);
3011 BOOL ps = use_ps(state);
3013 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3014 * need a 1:1 map at the moment.
3015 * When the mapping of a stage is changed, sampler and ALL texture stage
3016 * states have to be reset. */
3018 if (ps)
3019 context_map_psamplers(context, state);
3020 else
3021 context_map_fixed_function_samplers(context, state);
3023 if (vs)
3024 context_map_vsamplers(context, ps, state);
3027 /* Context activation is done by the caller. */
3028 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3030 DWORD rt_mask, *cur_mask;
3032 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3034 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3035 rt_mask = find_draw_buffers_mask(context, state);
3036 if (rt_mask != *cur_mask)
3038 context_apply_draw_buffers(context, rt_mask);
3039 *cur_mask = rt_mask;
3043 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3045 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3046 *regnum = WINED3D_FFP_POSITION;
3047 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3048 *regnum = WINED3D_FFP_BLENDWEIGHT;
3049 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3050 *regnum = WINED3D_FFP_BLENDINDICES;
3051 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3052 *regnum = WINED3D_FFP_NORMAL;
3053 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3054 *regnum = WINED3D_FFP_PSIZE;
3055 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3056 *regnum = WINED3D_FFP_DIFFUSE;
3057 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3058 *regnum = WINED3D_FFP_SPECULAR;
3059 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3060 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3061 else
3063 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3064 *regnum = ~0U;
3065 return FALSE;
3068 return TRUE;
3071 /* Context activation is done by the caller. */
3072 void context_stream_info_from_declaration(struct wined3d_context *context,
3073 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
3075 /* We need to deal with frequency data! */
3076 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3077 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
3078 BOOL use_vshader = use_vs(state);
3079 unsigned int i;
3081 stream_info->use_map = 0;
3082 stream_info->swizzle_map = 0;
3083 stream_info->position_transformed = 0;
3085 if (!declaration)
3086 return;
3088 stream_info->position_transformed = declaration->position_transformed;
3090 /* Translate the declaration into strided data. */
3091 for (i = 0; i < declaration->element_count; ++i)
3093 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3094 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3095 BOOL stride_used;
3096 unsigned int idx;
3098 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3099 element, i + 1, declaration->element_count);
3101 if (!stream->buffer)
3102 continue;
3104 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3106 if (use_vshader)
3108 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3110 stride_used = FALSE;
3112 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3114 /* TODO: Assuming vertexdeclarations are usually used with the
3115 * same or a similar shader, it might be worth it to store the
3116 * last used output slot and try that one first. */
3117 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3118 element->usage, element->usage_idx, &idx);
3120 else
3122 idx = element->output_slot;
3123 stride_used = TRUE;
3126 else
3128 if (!generic_attributes && !element->ffp_valid)
3130 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3131 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3132 stride_used = FALSE;
3134 else
3136 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3140 if (stride_used)
3142 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3143 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3144 use_vshader ? "shader": "fixed function", idx,
3145 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3146 element->offset, stream->stride, debug_d3dformat(element->format->id),
3147 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3149 stream_info->elements[idx].format = element->format;
3150 stream_info->elements[idx].data.buffer_object = 0;
3151 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3152 stream_info->elements[idx].stride = stream->stride;
3153 stream_info->elements[idx].stream_idx = element->input_slot;
3154 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3156 stream_info->elements[idx].divisor = 1;
3158 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3160 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3161 if (!element->instance_data_step_rate)
3162 FIXME("Instance step rate 0 not implemented.\n");
3164 else
3166 stream_info->elements[idx].divisor = 0;
3169 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3170 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3172 stream_info->swizzle_map |= 1u << idx;
3174 stream_info->use_map |= 1u << idx;
3179 /* Context activation is done by the caller. */
3180 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3182 struct wined3d_stream_info *stream_info = &context->stream_info;
3183 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3184 const struct wined3d_gl_info *gl_info = context->gl_info;
3185 DWORD prev_all_vbo = stream_info->all_vbo;
3186 unsigned int i;
3187 WORD map;
3189 context_stream_info_from_declaration(context, state, stream_info);
3191 stream_info->all_vbo = 1;
3192 context->num_buffer_queries = 0;
3193 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3195 struct wined3d_stream_info_element *element;
3196 struct wined3d_bo_address data;
3197 struct wined3d_buffer *buffer;
3199 if (!(map & 1))
3200 continue;
3202 element = &stream_info->elements[i];
3203 buffer = state->streams[element->stream_idx].buffer;
3205 /* We can't use VBOs if the base vertex index is negative. OpenGL
3206 * doesn't accept negative offsets (or rather offsets bigger than the
3207 * VBO, because the pointer is unsigned), so use system memory
3208 * sources. In most sane cases the pointer - offset will still be > 0,
3209 * otherwise it will wrap around to some big value. Hope that with the
3210 * indices the driver wraps it back internally. If not,
3211 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3212 * path. */
3213 if (state->load_base_vertex_index < 0)
3215 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3216 state->load_base_vertex_index);
3217 element->data.buffer_object = 0;
3218 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3219 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3220 FIXME("System memory vertex data load offset is negative!\n");
3222 else
3224 wined3d_buffer_load(buffer, context, state);
3225 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3226 element->data.buffer_object = data.buffer_object;
3227 element->data.addr += (ULONG_PTR)data.addr;
3230 if (!element->data.buffer_object)
3231 stream_info->all_vbo = 0;
3233 if (buffer->query)
3234 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
3236 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3239 if (prev_all_vbo != stream_info->all_vbo)
3240 context_invalidate_state(context, STATE_INDEXBUFFER);
3242 context->use_immediate_mode_draw = FALSE;
3244 if (stream_info->all_vbo)
3245 return;
3247 if (use_vs(state))
3249 if (state->vertex_declaration->half_float_conv_needed)
3251 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3252 context->use_immediate_mode_draw = TRUE;
3255 else
3257 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3258 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3259 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3261 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3262 || (stream_info->use_map & slow_mask))
3263 context->use_immediate_mode_draw = TRUE;
3267 /* Context activation is done by the caller. */
3268 static void context_preload_texture(struct wined3d_context *context,
3269 const struct wined3d_state *state, unsigned int idx)
3271 struct wined3d_texture *texture;
3273 if (!(texture = state->textures[idx]))
3274 return;
3276 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3279 /* Context activation is done by the caller. */
3280 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3282 unsigned int i;
3284 if (use_vs(state))
3286 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3288 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3289 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3293 if (use_ps(state))
3295 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3297 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3298 context_preload_texture(context, state, i);
3301 else
3303 WORD ffu_map = context->fixed_function_usage_map;
3305 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3307 if (ffu_map & 1)
3308 context_preload_texture(context, state, i);
3313 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3314 unsigned int shader_mask)
3316 struct wined3d_shader_sampler_map_entry *entry;
3317 struct wined3d_shader_resource_view *view;
3318 struct wined3d_shader *shader;
3319 unsigned int i, j;
3321 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3323 if (!(shader_mask & (1u << i)))
3324 continue;
3326 if (!(shader = state->shader[i]))
3327 continue;
3329 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3331 if (state->cb[i][j])
3332 wined3d_buffer_load(state->cb[i][j], context, state);
3335 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3337 entry = &shader->reg_maps.sampler_map.entries[j];
3339 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3341 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3342 continue;
3345 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3346 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3347 else
3348 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3353 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3355 const struct wined3d_gl_info *gl_info = context->gl_info;
3356 const struct wined3d_device *device = context->device;
3357 struct wined3d_shader_sampler_map_entry *entry;
3358 struct wined3d_shader_resource_view *view;
3359 struct wined3d_sampler *sampler;
3360 struct wined3d_shader *shader;
3361 unsigned int i, j, count;
3362 GLuint sampler_name;
3364 static const struct
3366 enum wined3d_shader_type type;
3367 unsigned int base_idx;
3368 unsigned int count;
3370 shader_types[] =
3372 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3373 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3376 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3378 if (!(shader = state->shader[shader_types[i].type]))
3379 continue;
3381 count = shader->reg_maps.sampler_map.count;
3382 if (count > shader_types[i].count)
3384 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3385 shader, count, shader_types[i].count);
3386 count = shader_types[i].count;
3389 for (j = 0; j < count; ++j)
3391 entry = &shader->reg_maps.sampler_map.entries[j];
3393 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3395 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3396 continue;
3399 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3400 sampler_name = device->default_sampler;
3401 else if ((sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3402 sampler_name = sampler->name;
3403 else
3404 sampler_name = device->null_sampler;
3406 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3407 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler_name));
3408 checkGLcall("glBindSampler");
3409 wined3d_shader_resource_view_bind(view, context);
3414 static void context_bind_unordered_access_views(struct wined3d_context *context,
3415 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3417 const struct wined3d_gl_info *gl_info = context->gl_info;
3418 struct wined3d_unordered_access_view *view;
3419 struct wined3d_texture *texture;
3420 GLuint texture_name;
3421 unsigned int i;
3422 GLint level;
3424 context->uses_uavs = 0;
3426 if (!shader)
3427 return;
3429 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3431 if (!shader->reg_maps.uav_resource_info[i].type)
3432 continue;
3434 if (!(view = views[i]))
3436 WARN("No unordered access view bound at index %u.\n", i);
3437 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3438 continue;
3441 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3443 FIXME("Buffer unordered access views not implemented.\n");
3444 continue;
3447 context->uses_uavs = 1;
3449 texture = texture_from_resource(view->resource);
3450 wined3d_texture_load(texture, context, FALSE);
3451 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3453 if (view->gl_view.name)
3455 texture_name = view->gl_view.name;
3456 level = 0;
3458 else
3460 texture_name = wined3d_texture_get_gl_texture(texture, FALSE)->name;
3461 level = view->level_idx;
3464 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3465 view->format->glInternal));
3467 checkGLcall("Bind unordered access views");
3470 /* Context activation is done by the caller. */
3471 BOOL context_apply_draw_state(struct wined3d_context *context,
3472 const struct wined3d_device *device, const struct wined3d_state *state)
3474 const struct StateEntry *state_table = context->state_table;
3475 const struct wined3d_fb_state *fb = state->fb;
3476 unsigned int i;
3477 WORD map;
3479 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3480 fb->render_targets, fb->depth_stencil))
3481 return FALSE;
3483 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3485 context_validate_onscreen_formats(context, fb->depth_stencil);
3488 /* Preload resources before FBO setup. Texture preload in particular may
3489 * result in changes to the current FBO, due to using e.g. FBO blits for
3490 * updating a resource location. */
3491 context_update_tex_unit_map(context, state);
3492 context_preload_textures(context, state);
3493 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3494 /* TODO: Right now the dependency on the vertex shader is necessary
3495 * since context_stream_info_from_declaration depends on the reg_maps of
3496 * the current VS but maybe it's possible to relax the coupling in some
3497 * situations at least. */
3498 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3499 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3501 context_update_stream_info(context, state);
3503 else
3505 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3507 if (map & 1)
3508 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3509 context, state);
3511 /* Loading the buffers above may have invalidated the stream info. */
3512 if (isStateDirty(context, STATE_STREAMSRC))
3513 context_update_stream_info(context, state);
3515 if (state->index_buffer)
3517 if (context->stream_info.all_vbo)
3518 wined3d_buffer_load(state->index_buffer, context, state);
3519 else
3520 wined3d_buffer_load_sysmem(state->index_buffer, context);
3523 for (i = 0; i < context->numDirtyEntries; ++i)
3525 DWORD rep = context->dirtyArray[i];
3526 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3527 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3528 context->isStateDirty[idx] &= ~(1u << shift);
3529 state_table[rep].apply(context, state, rep);
3532 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
3534 device->shader_backend->shader_select(device->shader_priv, context, state);
3535 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
3538 if (context->constant_update_mask)
3540 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3541 context->constant_update_mask = 0;
3544 if (context->update_shader_resource_bindings)
3546 context_bind_shader_resources(context, state);
3547 context->update_shader_resource_bindings = 0;
3550 if (context->update_unordered_access_view_bindings)
3552 context_bind_unordered_access_views(context,
3553 state->shader[WINED3D_SHADER_TYPE_PIXEL],
3554 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3555 context->update_unordered_access_view_bindings = 0;
3556 context->update_compute_unordered_access_view_bindings = 1;
3559 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3561 context_check_fbo_status(context, GL_FRAMEBUFFER);
3564 context->numDirtyEntries = 0; /* This makes the whole list clean */
3565 context->last_was_blit = FALSE;
3567 return TRUE;
3570 void context_apply_compute_state(struct wined3d_context *context,
3571 const struct wined3d_device *device, const struct wined3d_state *state)
3573 const struct StateEntry *state_table = context->state_table;
3574 unsigned int state_id, i, j;
3576 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
3578 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
3580 for (j = 0; j < sizeof(*context->dirty_compute_states) * CHAR_BIT; ++j, ++state_id)
3582 if (context->dirty_compute_states[i] & (1u << j))
3583 state_table[state_id].apply(context, state, state_id);
3586 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
3588 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
3590 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
3591 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
3594 if (context->update_compute_unordered_access_view_bindings)
3596 context_bind_unordered_access_views(context,
3597 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3598 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3599 context->update_compute_unordered_access_view_bindings = 0;
3600 context->update_unordered_access_view_bindings = 1;
3603 context->last_was_blit = FALSE;
3606 static void context_setup_target(struct wined3d_context *context,
3607 struct wined3d_texture *texture, unsigned int sub_resource_idx)
3609 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3611 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
3612 if (context->current_rt.texture == texture
3613 && context->current_rt.sub_resource_idx == sub_resource_idx
3614 && render_offscreen == old_render_offscreen)
3615 return;
3617 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3618 * the alpha blend state changes with different render target formats. */
3619 if (!context->current_rt.texture)
3621 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3623 else
3625 const struct wined3d_format *old = context->current_rt.texture->resource.format;
3626 const struct wined3d_format *new = texture->resource.format;
3628 if (old->id != new->id)
3630 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3631 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3632 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3633 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3635 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3636 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3637 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3638 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3641 /* When switching away from an offscreen render target, and we're not
3642 * using FBOs, we have to read the drawable into the texture. This is
3643 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3644 * There are some things that need care though. PreLoad needs a GL context,
3645 * and FindContext is called before the context is activated. It also
3646 * has to be called with the old rendertarget active, otherwise a
3647 * wrong drawable is read. */
3648 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3649 && old_render_offscreen && (context->current_rt.texture != texture
3650 || context->current_rt.sub_resource_idx != sub_resource_idx))
3652 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
3653 struct wined3d_texture *prev_texture = context->current_rt.texture;
3655 /* Read the back buffer of the old drawable into the destination texture. */
3656 if (prev_texture->texture_srgb.name)
3657 wined3d_texture_load(prev_texture, context, TRUE);
3658 wined3d_texture_load(prev_texture, context, FALSE);
3659 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
3663 context->current_rt.texture = texture;
3664 context->current_rt.sub_resource_idx = sub_resource_idx;
3665 context_set_render_offscreen(context, render_offscreen);
3668 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3670 struct wined3d_context *current_context = context_get_current();
3671 struct wined3d_texture *target_texture;
3672 unsigned int target_sub_resource_idx;
3673 struct wined3d_context *context;
3675 TRACE("device %p, target %p.\n", device, target);
3677 if (current_context && current_context->destroyed)
3678 current_context = NULL;
3680 if (target)
3682 target_texture = target->container;
3683 target_sub_resource_idx = surface_get_sub_resource_idx(target);
3685 else
3687 if (current_context
3688 && current_context->current_rt.texture
3689 && current_context->device == device)
3691 target_texture = current_context->current_rt.texture;
3692 target_sub_resource_idx = current_context->current_rt.sub_resource_idx;
3694 else
3696 struct wined3d_swapchain *swapchain = device->swapchains[0];
3698 if (swapchain->back_buffers)
3699 target_texture = swapchain->back_buffers[0];
3700 else
3701 target_texture = swapchain->front_buffer;
3702 target_sub_resource_idx = 0;
3706 if (current_context && current_context->current_rt.texture == target_texture)
3708 context = current_context;
3710 else if (target_texture->swapchain)
3712 TRACE("Rendering onscreen.\n");
3714 context = swapchain_get_context(target_texture->swapchain);
3716 else
3718 TRACE("Rendering offscreen.\n");
3720 /* Stay with the current context if possible. Otherwise use the
3721 * context for the primary swapchain. */
3722 if (current_context && current_context->device == device)
3723 context = current_context;
3724 else
3725 context = swapchain_get_context(device->swapchains[0]);
3728 context_enter(context);
3729 context_update_window(context);
3730 context_setup_target(context, target_texture, target_sub_resource_idx);
3731 if (!context->valid) return context;
3733 if (context != current_context)
3735 if (!context_set_current(context))
3736 ERR("Failed to activate the new context.\n");
3738 else if (context->needs_set)
3740 context_set_gl_context(context);
3743 return context;