loader: We now have a preloader on ARM64.
[wine.git] / dlls / wined3d / context.c
blobba9e19c06ec687b4149b26d4756ed83ca4c3bf90
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
37 #define WINED3D_ALL_LAYERS (~0u)
39 static DWORD wined3d_context_tls_idx;
41 /* FBO helper functions */
43 /* Context activation is done by the caller. */
44 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
46 const struct wined3d_gl_info *gl_info = context->gl_info;
48 switch (target)
50 case GL_READ_FRAMEBUFFER:
51 if (context->fbo_read_binding == fbo) return;
52 context->fbo_read_binding = fbo;
53 break;
55 case GL_DRAW_FRAMEBUFFER:
56 if (context->fbo_draw_binding == fbo) return;
57 context->fbo_draw_binding = fbo;
58 break;
60 case GL_FRAMEBUFFER:
61 if (context->fbo_read_binding == fbo
62 && context->fbo_draw_binding == fbo) return;
63 context->fbo_read_binding = fbo;
64 context->fbo_draw_binding = fbo;
65 break;
67 default:
68 FIXME("Unhandled target %#x.\n", target);
69 break;
72 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
73 checkGLcall("glBindFramebuffer()");
76 /* Context activation is done by the caller. */
77 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
79 unsigned int i;
81 for (i = 0; i < gl_info->limits.buffers; ++i)
83 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
84 checkGLcall("glFramebufferTexture2D()");
86 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
87 checkGLcall("glFramebufferTexture2D()");
89 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
90 checkGLcall("glFramebufferTexture2D()");
93 /* Context activation is done by the caller. */
94 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
96 const struct wined3d_gl_info *gl_info = context->gl_info;
98 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
99 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
100 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
102 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
103 checkGLcall("glDeleteFramebuffers()");
106 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
107 GLenum fbo_target, DWORD flags, GLuint rb)
109 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
111 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
112 checkGLcall("glFramebufferRenderbuffer()");
115 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
117 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
118 checkGLcall("glFramebufferRenderbuffer()");
122 static void context_attach_gl_texture_fbo(struct wined3d_context *context,
123 GLenum fbo_target, GLenum attachment, const struct wined3d_fbo_resource *resource)
125 const struct wined3d_gl_info *gl_info = context->gl_info;
127 if (!resource)
129 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment, GL_TEXTURE_2D, 0, 0);
131 else if (resource->layer == WINED3D_ALL_LAYERS)
133 if (!gl_info->fbo_ops.glFramebufferTexture)
135 FIXME("OpenGL implementation doesn't support glFramebufferTexture().\n");
136 return;
139 gl_info->fbo_ops.glFramebufferTexture(fbo_target, attachment,
140 resource->object, resource->level);
142 else if (resource->target == GL_TEXTURE_2D_ARRAY || resource->target == GL_TEXTURE_3D)
144 if (!gl_info->fbo_ops.glFramebufferTextureLayer)
146 FIXME("OpenGL implementation doesn't support glFramebufferTextureLayer().\n");
147 return;
150 gl_info->fbo_ops.glFramebufferTextureLayer(fbo_target, attachment,
151 resource->object, resource->level, resource->layer);
153 else
155 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, attachment,
156 resource->target, resource->object, resource->level);
158 checkGLcall("attach texture to fbo");
161 /* Context activation is done by the caller. */
162 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
163 GLenum fbo_target, const struct wined3d_fbo_resource *resource, BOOL rb_namespace,
164 DWORD flags)
166 const struct wined3d_gl_info *gl_info = context->gl_info;
168 if (resource->object)
170 TRACE("Attach depth stencil %u.\n", resource->object);
172 if (rb_namespace)
174 context_attach_depth_stencil_rb(gl_info, fbo_target,
175 flags, resource->object);
177 else
179 if (flags & WINED3D_FBO_ENTRY_FLAG_DEPTH)
180 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, resource);
182 if (flags & WINED3D_FBO_ENTRY_FLAG_STENCIL)
183 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, resource);
186 if (!(flags & WINED3D_FBO_ENTRY_FLAG_DEPTH))
187 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
189 if (!(flags & WINED3D_FBO_ENTRY_FLAG_STENCIL))
190 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
192 else
194 TRACE("Attach depth stencil 0.\n");
196 context_attach_gl_texture_fbo(context, fbo_target, GL_DEPTH_ATTACHMENT, NULL);
197 context_attach_gl_texture_fbo(context, fbo_target, GL_STENCIL_ATTACHMENT, NULL);
201 /* Context activation is done by the caller. */
202 static void context_attach_surface_fbo(struct wined3d_context *context,
203 GLenum fbo_target, DWORD idx, const struct wined3d_fbo_resource *resource, BOOL rb_namespace)
205 const struct wined3d_gl_info *gl_info = context->gl_info;
207 TRACE("Attach GL object %u to %u.\n", resource->object, idx);
209 if (resource->object)
212 if (rb_namespace)
214 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
215 GL_RENDERBUFFER, resource->object);
216 checkGLcall("glFramebufferRenderbuffer()");
218 else
220 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, resource);
223 else
225 context_attach_gl_texture_fbo(context, fbo_target, GL_COLOR_ATTACHMENT0 + idx, NULL);
229 static void context_dump_fbo_attachment(const struct wined3d_gl_info *gl_info, GLenum target,
230 GLenum attachment)
232 static const struct
234 GLenum target;
235 GLenum binding;
236 const char *str;
237 enum wined3d_gl_extension extension;
239 texture_type[] =
241 {GL_TEXTURE_2D, GL_TEXTURE_BINDING_2D, "2d", WINED3D_GL_EXT_NONE},
242 {GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_BINDING_RECTANGLE_ARB, "rectangle", ARB_TEXTURE_RECTANGLE},
243 {GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BINDING_2D_ARRAY, "2d-array", EXT_TEXTURE_ARRAY},
246 GLint type, name, samples, width, height, old_texture, level, face, fmt, tex_target;
248 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
249 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &name);
250 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
251 GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &type);
253 if (type == GL_RENDERBUFFER)
255 gl_info->fbo_ops.glBindRenderbuffer(GL_RENDERBUFFER, name);
256 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
257 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);
258 if (gl_info->limits.samples > 1)
259 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
260 else
261 samples = 1;
262 gl_info->fbo_ops.glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_INTERNAL_FORMAT, &fmt);
263 FIXME(" %s: renderbuffer %d, %dx%d, %d samples, format %#x.\n",
264 debug_fboattachment(attachment), name, width, height, samples, fmt);
266 else if (type == GL_TEXTURE)
268 const char *tex_type_str;
270 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
271 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &level);
272 gl_info->fbo_ops.glGetFramebufferAttachmentParameteriv(target, attachment,
273 GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE, &face);
275 if (face)
277 gl_info->gl_ops.gl.p_glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP, &old_texture);
279 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, name);
280 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
281 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_WIDTH, &width);
282 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(face, level, GL_TEXTURE_HEIGHT, &height);
284 tex_target = GL_TEXTURE_CUBE_MAP;
285 tex_type_str = "cube";
287 else
289 unsigned int i;
291 tex_type_str = NULL;
292 for (i = 0; i < ARRAY_SIZE(texture_type); ++i)
294 if (!gl_info->supported[texture_type[i].extension])
295 continue;
297 gl_info->gl_ops.gl.p_glGetIntegerv(texture_type[i].binding, &old_texture);
298 while (gl_info->gl_ops.gl.p_glGetError());
300 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, name);
301 if (!gl_info->gl_ops.gl.p_glGetError())
303 tex_target = texture_type[i].target;
304 tex_type_str = texture_type[i].str;
305 break;
307 gl_info->gl_ops.gl.p_glBindTexture(texture_type[i].target, old_texture);
309 if (!tex_type_str)
311 FIXME("Cannot find type of texture %d.\n", name);
312 return;
315 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
316 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_WIDTH, &width);
317 gl_info->gl_ops.gl.p_glGetTexLevelParameteriv(tex_target, level, GL_TEXTURE_HEIGHT, &height);
320 FIXME(" %s: %s texture %d, %dx%d, format %#x.\n", debug_fboattachment(attachment),
321 tex_type_str, name, width, height, fmt);
323 gl_info->gl_ops.gl.p_glBindTexture(tex_target, old_texture);
324 checkGLcall("Guess texture type");
326 else if (type == GL_NONE)
328 FIXME(" %s: NONE.\n", debug_fboattachment(attachment));
330 else
332 ERR(" %s: Unknown attachment %#x.\n", debug_fboattachment(attachment), type);
336 /* Context activation is done by the caller. */
337 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
339 const struct wined3d_gl_info *gl_info = context->gl_info;
340 GLenum status;
342 if (!FIXME_ON(d3d)) return;
344 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
345 if (status == GL_FRAMEBUFFER_COMPLETE)
347 TRACE("FBO complete\n");
349 else
351 unsigned int i;
353 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
355 if (!context->current_fbo)
357 ERR("FBO 0 is incomplete, driver bug?\n");
358 return;
361 context_dump_fbo_attachment(gl_info, target, GL_DEPTH_ATTACHMENT);
362 context_dump_fbo_attachment(gl_info, target, GL_STENCIL_ATTACHMENT);
364 for (i = 0; i < gl_info->limits.buffers; ++i)
365 context_dump_fbo_attachment(gl_info, target, GL_COLOR_ATTACHMENT0 + i);
366 checkGLcall("Dump FBO attachments");
370 static inline DWORD context_generate_rt_mask(GLenum buffer)
372 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
373 return buffer ? (1u << 31) | buffer : 0;
376 static inline DWORD context_generate_rt_mask_from_resource(struct wined3d_resource *resource)
378 if (resource->type != WINED3D_RTYPE_TEXTURE_2D)
380 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
381 return 0;
384 return (1u << 31) | wined3d_texture_get_gl_buffer(texture_from_resource(resource));
387 static inline void context_set_fbo_key_for_render_target(const struct wined3d_context *context,
388 struct wined3d_fbo_entry_key *key, unsigned int idx, struct wined3d_rendertarget_info *render_target,
389 DWORD location)
391 unsigned int sub_resource_idx = render_target->sub_resource_idx;
392 struct wined3d_resource *resource = render_target->resource;
393 struct wined3d_texture *texture;
395 if (!resource || resource->format->id == WINED3DFMT_NULL || resource->type == WINED3D_RTYPE_BUFFER)
397 if (resource && resource->type == WINED3D_RTYPE_BUFFER)
398 FIXME("Not implemented for %s resources.\n", debug_d3dresourcetype(resource->type));
399 key->objects[idx].object = 0;
400 key->objects[idx].target = 0;
401 key->objects[idx].level = key->objects[idx].layer = 0;
402 return;
405 if (render_target->gl_view.name)
407 key->objects[idx].object = render_target->gl_view.name;
408 key->objects[idx].target = render_target->gl_view.target;
409 key->objects[idx].level = 0;
410 key->objects[idx].layer = WINED3D_ALL_LAYERS;
411 return;
414 texture = wined3d_texture_from_resource(resource);
415 if (resource->type == WINED3D_RTYPE_TEXTURE_2D)
417 struct wined3d_surface *surface = texture->sub_resources[sub_resource_idx].u.surface;
419 if (surface->current_renderbuffer)
421 key->objects[idx].object = surface->current_renderbuffer->id;
422 key->objects[idx].target = 0;
423 key->objects[idx].level = key->objects[idx].layer = 0;
424 key->rb_namespace |= 1 << idx;
425 return;
428 key->objects[idx].target = surface->texture_target;
429 key->objects[idx].level = surface->texture_level;
430 key->objects[idx].layer = surface->texture_layer;
432 else
434 key->objects[idx].target = texture->target;
435 key->objects[idx].level = sub_resource_idx % texture->level_count;
436 key->objects[idx].layer = sub_resource_idx / texture->level_count;
438 if (render_target->layer_count != 1)
439 key->objects[idx].layer = WINED3D_ALL_LAYERS;
441 switch (location)
443 case WINED3D_LOCATION_TEXTURE_RGB:
444 key->objects[idx].object = wined3d_texture_get_texture_name(texture, context, FALSE);
445 break;
447 case WINED3D_LOCATION_TEXTURE_SRGB:
448 key->objects[idx].object = wined3d_texture_get_texture_name(texture, context, TRUE);
449 break;
451 case WINED3D_LOCATION_RB_MULTISAMPLE:
452 key->objects[idx].object = texture->rb_multisample;
453 key->objects[idx].target = 0;
454 key->objects[idx].level = key->objects[idx].layer = 0;
455 key->rb_namespace |= 1 << idx;
456 break;
458 case WINED3D_LOCATION_RB_RESOLVED:
459 key->objects[idx].object = texture->rb_resolved;
460 key->objects[idx].target = 0;
461 key->objects[idx].level = key->objects[idx].layer = 0;
462 key->rb_namespace |= 1 << idx;
463 break;
467 static void context_generate_fbo_key(const struct wined3d_context *context,
468 struct wined3d_fbo_entry_key *key, struct wined3d_rendertarget_info *render_targets,
469 struct wined3d_surface *depth_stencil_surface, DWORD color_location,
470 DWORD ds_location)
472 struct wined3d_rendertarget_info depth_stencil = {{0}};
473 unsigned int i;
475 key->rb_namespace = 0;
476 if (depth_stencil_surface)
478 depth_stencil.resource = &depth_stencil_surface->container->resource;
479 depth_stencil.sub_resource_idx = surface_get_sub_resource_idx(depth_stencil_surface);
480 depth_stencil.layer_count = 1;
482 context_set_fbo_key_for_render_target(context, key, 0, &depth_stencil, ds_location);
484 for (i = 0; i < context->gl_info->limits.buffers; ++i)
485 context_set_fbo_key_for_render_target(context, key, i + 1, &render_targets[i], color_location);
488 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
489 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
490 DWORD color_location, DWORD ds_location)
492 const struct wined3d_gl_info *gl_info = context->gl_info;
493 unsigned int object_count = gl_info->limits.buffers + 1;
494 struct fbo_entry *entry;
496 entry = HeapAlloc(GetProcessHeap(), 0,
497 FIELD_OFFSET(struct fbo_entry, key.objects[object_count]));
498 memset(&entry->key, 0, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count]));
499 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
500 entry->flags = 0;
501 if (depth_stencil)
503 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
504 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
505 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
506 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
508 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
509 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
510 checkGLcall("glGenFramebuffers()");
511 TRACE("Created FBO %u.\n", entry->id);
513 return entry;
516 /* Context activation is done by the caller. */
517 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
518 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
519 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
521 const struct wined3d_gl_info *gl_info = context->gl_info;
523 context_bind_fbo(context, target, entry->id);
524 context_clean_fbo_attachments(gl_info, target);
526 context_generate_fbo_key(context, &entry->key, render_targets, depth_stencil, color_location, ds_location);
527 entry->flags = 0;
528 if (depth_stencil)
530 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_DEPTH)
531 entry->flags |= WINED3D_FBO_ENTRY_FLAG_DEPTH;
532 if (depth_stencil->container->resource.format_flags & WINED3DFMT_FLAG_STENCIL)
533 entry->flags |= WINED3D_FBO_ENTRY_FLAG_STENCIL;
537 /* Context activation is done by the caller. */
538 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
540 if (entry->id)
542 TRACE("Destroy FBO %u.\n", entry->id);
543 context_destroy_fbo(context, entry->id);
545 --context->fbo_entry_count;
546 list_remove(&entry->entry);
547 HeapFree(GetProcessHeap(), 0, entry);
550 /* Context activation is done by the caller. */
551 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
552 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
553 DWORD color_location, DWORD ds_location)
555 const struct wined3d_gl_info *gl_info = context->gl_info;
556 unsigned int object_count = gl_info->limits.buffers + 1;
557 struct wined3d_texture *rt_texture, *ds_texture;
558 struct fbo_entry *entry;
559 unsigned int i, level;
561 if (depth_stencil && render_targets[0].resource && render_targets[0].resource->type != WINED3D_RTYPE_BUFFER)
563 rt_texture = wined3d_texture_from_resource(render_targets[0].resource);
564 level = render_targets[0].sub_resource_idx % rt_texture->level_count;
565 ds_texture = depth_stencil->container;
567 if (wined3d_texture_get_level_width(ds_texture, depth_stencil->texture_level)
568 < wined3d_texture_get_level_width(rt_texture, level)
569 || wined3d_texture_get_level_height(ds_texture, depth_stencil->texture_level)
570 < wined3d_texture_get_level_height(rt_texture, level))
572 WARN("Depth stencil is smaller than the primary color buffer, disabling.\n");
573 depth_stencil = NULL;
575 else if (ds_texture->resource.multisample_type != rt_texture->resource.multisample_type
576 || ds_texture->resource.multisample_quality != rt_texture->resource.multisample_quality)
578 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
579 rt_texture->resource.multisample_type, rt_texture->resource.multisample_quality,
580 ds_texture->resource.multisample_type, ds_texture->resource.multisample_quality);
581 depth_stencil = NULL;
583 else
584 surface_set_compatible_renderbuffer(depth_stencil, &render_targets[0]);
587 context_generate_fbo_key(context, context->fbo_key, render_targets, depth_stencil, color_location,
588 ds_location);
590 if (TRACE_ON(d3d))
592 TRACE("Dumping FBO attachments:\n");
593 for (i = 0; i < gl_info->limits.buffers; ++i)
595 struct wined3d_resource *resource;
596 if ((resource = render_targets[i].resource))
598 unsigned int width, height;
599 const char *resource_type;
601 if (resource->type == WINED3D_RTYPE_BUFFER)
603 width = resource->size;
604 height = 1;
605 resource_type = "buffer";
607 else
609 rt_texture = wined3d_texture_from_resource(resource);
610 level = render_targets[i].sub_resource_idx % rt_texture->level_count;
611 width = wined3d_texture_get_level_pow2_width(rt_texture, level);
612 height = wined3d_texture_get_level_pow2_height(rt_texture, level);
613 resource_type = "texture";
616 TRACE(" Color attachment %u: %p, %u format %s, %s %u, %ux%u, %u samples.\n",
617 i, resource, render_targets[i].sub_resource_idx, debug_d3dformat(resource->format->id),
618 context->fbo_key->rb_namespace & (1 << (i + 1)) ? "renderbuffer" : resource_type,
619 context->fbo_key->objects[i + 1].object, width, height, resource->multisample_type);
622 if (depth_stencil)
624 ds_texture = depth_stencil->container;
625 TRACE(" Depth attachment: %p format %s, %s %u, %ux%u, %u samples.\n",
626 depth_stencil, debug_d3dformat(ds_texture->resource.format->id),
627 context->fbo_key->rb_namespace & (1 << 0) ? "renderbuffer" : "texture",
628 context->fbo_key->objects[0].object,
629 wined3d_texture_get_level_pow2_width(ds_texture, depth_stencil->texture_level),
630 wined3d_texture_get_level_pow2_height(ds_texture, depth_stencil->texture_level),
631 ds_texture->resource.multisample_type);
635 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
637 if (memcmp(context->fbo_key, &entry->key, FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[object_count])))
638 continue;
640 list_remove(&entry->entry);
641 list_add_head(&context->fbo_list, &entry->entry);
642 return entry;
645 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
647 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
648 list_add_head(&context->fbo_list, &entry->entry);
649 ++context->fbo_entry_count;
651 else
653 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
654 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
655 list_remove(&entry->entry);
656 list_add_head(&context->fbo_list, &entry->entry);
659 return entry;
662 /* Context activation is done by the caller. */
663 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
665 const struct wined3d_gl_info *gl_info = context->gl_info;
666 unsigned int i;
667 GLuint read_binding, draw_binding;
669 if (entry->flags & WINED3D_FBO_ENTRY_FLAG_ATTACHED)
671 context_bind_fbo(context, target, entry->id);
672 return;
675 read_binding = context->fbo_read_binding;
676 draw_binding = context->fbo_draw_binding;
677 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
679 /* Apply render targets */
680 for (i = 0; i < gl_info->limits.buffers; ++i)
682 context_attach_surface_fbo(context, target, i, &entry->key.objects[i + 1],
683 entry->key.rb_namespace & (1 << (i + 1)));
686 context_attach_depth_stencil_fbo(context, target, &entry->key.objects[0],
687 entry->key.rb_namespace & 0x1, entry->flags);
689 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
690 * GL contexts requirements. */
691 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
692 context_set_draw_buffer(context, GL_NONE);
693 if (target != GL_FRAMEBUFFER)
695 if (target == GL_READ_FRAMEBUFFER)
696 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
697 else
698 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
701 entry->flags |= WINED3D_FBO_ENTRY_FLAG_ATTACHED;
704 /* Context activation is done by the caller. */
705 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
706 struct wined3d_rendertarget_info *render_targets, struct wined3d_surface *depth_stencil,
707 DWORD color_location, DWORD ds_location)
709 struct fbo_entry *entry, *entry2;
711 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
713 context_destroy_fbo_entry(context, entry);
716 if (context->rebind_fbo)
718 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
719 context->rebind_fbo = FALSE;
722 if (color_location == WINED3D_LOCATION_DRAWABLE)
724 context->current_fbo = NULL;
725 context_bind_fbo(context, target, 0);
727 else
729 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
730 color_location, ds_location);
731 context_apply_fbo_entry(context, target, context->current_fbo);
735 /* Context activation is done by the caller. */
736 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
737 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
739 memset(context->blit_targets, 0, context->gl_info->limits.buffers * sizeof(*context->blit_targets));
740 if (render_target)
742 context->blit_targets[0].resource = &render_target->container->resource;
743 context->blit_targets[0].sub_resource_idx = surface_get_sub_resource_idx(render_target);
744 context->blit_targets[0].layer_count = 1;
746 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
749 /* Context activation is done by the caller. */
750 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
752 const struct wined3d_gl_info *gl_info = context->gl_info;
754 if (context->free_occlusion_query_count)
756 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
758 else
760 if (gl_info->supported[ARB_OCCLUSION_QUERY])
762 GL_EXTCALL(glGenQueries(1, &query->id));
763 checkGLcall("glGenQueries");
765 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
767 else
769 WARN("Occlusion queries not supported, not allocating query id.\n");
770 query->id = 0;
774 query->context = context;
775 list_add_head(&context->occlusion_queries, &query->entry);
778 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
780 struct wined3d_context *context = query->context;
782 list_remove(&query->entry);
783 query->context = NULL;
785 if (!wined3d_array_reserve((void **)&context->free_occlusion_queries,
786 &context->free_occlusion_query_size, context->free_occlusion_query_count + 1,
787 sizeof(*context->free_occlusion_queries)))
789 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
790 return;
793 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
796 /* Context activation is done by the caller. */
797 void context_alloc_fence(struct wined3d_context *context, struct wined3d_fence *fence)
799 const struct wined3d_gl_info *gl_info = context->gl_info;
801 if (context->free_fence_count)
803 fence->object = context->free_fences[--context->free_fence_count];
805 else
807 if (gl_info->supported[ARB_SYNC])
809 /* Using ARB_sync, not much to do here. */
810 fence->object.sync = NULL;
811 TRACE("Allocated sync object in context %p.\n", context);
813 else if (gl_info->supported[APPLE_FENCE])
815 GL_EXTCALL(glGenFencesAPPLE(1, &fence->object.id));
816 checkGLcall("glGenFencesAPPLE");
818 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
820 else if(gl_info->supported[NV_FENCE])
822 GL_EXTCALL(glGenFencesNV(1, &fence->object.id));
823 checkGLcall("glGenFencesNV");
825 TRACE("Allocated fence %u in context %p.\n", fence->object.id, context);
827 else
829 WARN("Fences not supported, not allocating fence.\n");
830 fence->object.id = 0;
834 fence->context = context;
835 list_add_head(&context->fences, &fence->entry);
838 void context_free_fence(struct wined3d_fence *fence)
840 struct wined3d_context *context = fence->context;
842 list_remove(&fence->entry);
843 fence->context = NULL;
845 if (!wined3d_array_reserve((void **)&context->free_fences,
846 &context->free_fence_size, context->free_fence_count + 1,
847 sizeof(*context->free_fences)))
849 ERR("Failed to grow free list, leaking fence %u in context %p.\n", fence->object.id, context);
850 return;
853 context->free_fences[context->free_fence_count++] = fence->object;
856 /* Context activation is done by the caller. */
857 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
859 const struct wined3d_gl_info *gl_info = context->gl_info;
861 if (context->free_timestamp_query_count)
863 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
865 else
867 GL_EXTCALL(glGenQueries(1, &query->id));
868 checkGLcall("glGenQueries");
870 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
873 query->context = context;
874 list_add_head(&context->timestamp_queries, &query->entry);
877 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
879 struct wined3d_context *context = query->context;
881 list_remove(&query->entry);
882 query->context = NULL;
884 if (!wined3d_array_reserve((void **)&context->free_timestamp_queries,
885 &context->free_timestamp_query_size, context->free_timestamp_query_count + 1,
886 sizeof(*context->free_timestamp_queries)))
888 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
889 return;
892 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
895 void context_alloc_so_statistics_query(struct wined3d_context *context,
896 struct wined3d_so_statistics_query *query)
898 const struct wined3d_gl_info *gl_info = context->gl_info;
900 if (context->free_so_statistics_query_count)
902 query->u = context->free_so_statistics_queries[--context->free_so_statistics_query_count];
904 else
906 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
907 checkGLcall("glGenQueries");
909 TRACE("Allocated SO statistics queries %u, %u in context %p.\n",
910 query->u.id[0], query->u.id[1], context);
913 query->context = context;
914 list_add_head(&context->so_statistics_queries, &query->entry);
917 void context_free_so_statistics_query(struct wined3d_so_statistics_query *query)
919 struct wined3d_context *context = query->context;
921 list_remove(&query->entry);
922 query->context = NULL;
924 if (!wined3d_array_reserve((void **)&context->free_so_statistics_queries,
925 &context->free_so_statistics_query_size, context->free_so_statistics_query_count + 1,
926 sizeof(*context->free_so_statistics_queries)))
928 ERR("Failed to grow free list, leaking GL queries %u, %u in context %p.\n",
929 query->u.id[0], query->u.id[1], context);
930 return;
933 context->free_so_statistics_queries[context->free_so_statistics_query_count++] = query->u;
936 void context_alloc_pipeline_statistics_query(struct wined3d_context *context,
937 struct wined3d_pipeline_statistics_query *query)
939 const struct wined3d_gl_info *gl_info = context->gl_info;
941 if (context->free_pipeline_statistics_query_count)
943 query->u = context->free_pipeline_statistics_queries[--context->free_pipeline_statistics_query_count];
945 else
947 GL_EXTCALL(glGenQueries(ARRAY_SIZE(query->u.id), query->u.id));
948 checkGLcall("glGenQueries");
951 query->context = context;
952 list_add_head(&context->pipeline_statistics_queries, &query->entry);
955 void context_free_pipeline_statistics_query(struct wined3d_pipeline_statistics_query *query)
957 struct wined3d_context *context = query->context;
959 list_remove(&query->entry);
960 query->context = NULL;
962 if (!wined3d_array_reserve((void **)&context->free_pipeline_statistics_queries,
963 &context->free_pipeline_statistics_query_size, context->free_pipeline_statistics_query_count + 1,
964 sizeof(*context->free_pipeline_statistics_queries)))
966 ERR("Failed to grow free list, leaking GL queries in context %p.\n", context);
967 return;
970 context->free_pipeline_statistics_queries[context->free_pipeline_statistics_query_count++] = query->u;
973 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
975 static void context_enum_fbo_entries(const struct wined3d_device *device,
976 GLuint name, BOOL rb_namespace, context_fbo_entry_func_t *callback)
978 UINT i;
980 for (i = 0; i < device->context_count; ++i)
982 struct wined3d_context *context = device->contexts[i];
983 const struct wined3d_gl_info *gl_info = context->gl_info;
984 struct fbo_entry *entry, *entry2;
986 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
988 UINT j;
990 for (j = 0; j < gl_info->limits.buffers + 1; ++j)
992 if (entry->key.objects[j].object == name
993 && !(entry->key.rb_namespace & (1 << j)) == !rb_namespace)
995 callback(context, entry);
996 break;
1003 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
1005 list_remove(&entry->entry);
1006 list_add_head(&context->fbo_destroy_list, &entry->entry);
1009 void context_resource_released(const struct wined3d_device *device,
1010 struct wined3d_resource *resource, enum wined3d_resource_type type)
1012 struct wined3d_texture *texture;
1013 UINT i;
1015 if (!device->d3d_initialized)
1016 return;
1018 switch (type)
1020 case WINED3D_RTYPE_TEXTURE_2D:
1021 case WINED3D_RTYPE_TEXTURE_3D:
1022 texture = texture_from_resource(resource);
1024 for (i = 0; i < device->context_count; ++i)
1026 struct wined3d_context *context = device->contexts[i];
1027 if (context->current_rt.texture == texture)
1029 context->current_rt.texture = NULL;
1030 context->current_rt.sub_resource_idx = 0;
1033 break;
1035 default:
1036 break;
1040 void context_gl_resource_released(struct wined3d_device *device,
1041 GLuint name, BOOL rb_namespace)
1043 context_enum_fbo_entries(device, name, rb_namespace, context_queue_fbo_entry_destruction);
1046 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
1048 const struct wined3d_gl_info *gl_info = context->gl_info;
1049 struct fbo_entry *entry = context->current_fbo;
1050 unsigned int i;
1052 if (!entry || context->rebind_fbo) return;
1054 for (i = 0; i < gl_info->limits.buffers + 1; ++i)
1056 if (surface->container->texture_rgb.name == entry->key.objects[i].object
1057 || surface->container->texture_srgb.name == entry->key.objects[i].object)
1059 TRACE("Updated surface %p is bound as attachment %u to the current FBO.\n", surface, i);
1060 context->rebind_fbo = TRUE;
1061 return;
1066 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
1068 const struct wined3d_gl_info *gl_info = ctx->gl_info;
1069 BOOL ret = FALSE;
1071 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
1073 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1075 HDC dc = GetDCEx(ctx->restore_pf_win, 0, DCX_USESTYLE | DCX_CACHE);
1076 if (dc)
1078 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
1080 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
1081 ctx->restore_pf, ctx->restore_pf_win);
1083 ReleaseDC(ctx->restore_pf_win, dc);
1086 else
1088 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
1092 ctx->restore_pf = 0;
1093 ctx->restore_pf_win = NULL;
1094 return ret;
1097 static BOOL context_set_pixel_format(struct wined3d_context *context)
1099 const struct wined3d_gl_info *gl_info = context->gl_info;
1100 BOOL private = context->hdc_is_private;
1101 int format = context->pixel_format;
1102 HDC dc = context->hdc;
1103 int current;
1105 if (private && context->hdc_has_format)
1106 return TRUE;
1108 if (!private && WindowFromDC(dc) != context->win_handle)
1109 return FALSE;
1111 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
1112 if (current == format) goto success;
1114 if (!current)
1116 if (!SetPixelFormat(dc, format, NULL))
1118 /* This may also happen if the dc belongs to a destroyed window. */
1119 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
1120 format, dc, GetLastError());
1121 return FALSE;
1124 context->restore_pf = 0;
1125 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
1126 goto success;
1129 /* By default WGL doesn't allow pixel format adjustments but we need it
1130 * here. For this reason there's a Wine specific wglSetPixelFormat()
1131 * which allows us to set the pixel format multiple times. Only use it
1132 * when really needed. */
1133 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
1135 HWND win;
1137 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
1139 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
1140 format, dc);
1141 return FALSE;
1144 win = private ? NULL : WindowFromDC(dc);
1145 if (win != context->restore_pf_win)
1147 context_restore_pixel_format(context);
1149 context->restore_pf = private ? 0 : current;
1150 context->restore_pf_win = win;
1153 goto success;
1156 /* OpenGL doesn't allow pixel format adjustments. Print an error and
1157 * continue using the old format. There's a big chance that the old
1158 * format works although with a performance hit and perhaps rendering
1159 * errors. */
1160 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
1161 format, dc, current);
1162 return TRUE;
1164 success:
1165 if (private)
1166 context->hdc_has_format = TRUE;
1167 return TRUE;
1170 static BOOL context_set_gl_context(struct wined3d_context *ctx)
1172 struct wined3d_swapchain *swapchain = ctx->swapchain;
1173 BOOL backup = FALSE;
1175 if (!context_set_pixel_format(ctx))
1177 WARN("Failed to set pixel format %d on device context %p.\n",
1178 ctx->pixel_format, ctx->hdc);
1179 backup = TRUE;
1182 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
1184 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
1185 ctx->glCtx, ctx->hdc, GetLastError());
1186 ctx->valid = 0;
1187 WARN("Trying fallback to the backup window.\n");
1189 /* FIXME: If the context is destroyed it's no longer associated with
1190 * a swapchain, so we can't use the swapchain to get a backup dc. To
1191 * make this work windowless contexts would need to be handled by the
1192 * device. */
1193 if (ctx->destroyed || !swapchain)
1195 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
1196 context_set_current(NULL);
1197 return FALSE;
1200 if (!(ctx->hdc = swapchain_get_backup_dc(swapchain)))
1202 context_set_current(NULL);
1203 return FALSE;
1206 ctx->hdc_is_private = TRUE;
1207 ctx->hdc_has_format = FALSE;
1209 if (!context_set_pixel_format(ctx))
1211 ERR("Failed to set pixel format %d on device context %p.\n",
1212 ctx->pixel_format, ctx->hdc);
1213 context_set_current(NULL);
1214 return FALSE;
1217 if (!wglMakeCurrent(ctx->hdc, ctx->glCtx))
1219 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
1220 ctx->hdc, GetLastError());
1221 context_set_current(NULL);
1222 return FALSE;
1225 ctx->valid = 1;
1227 ctx->needs_set = 0;
1228 return TRUE;
1231 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
1233 if (!wglMakeCurrent(dc, gl_ctx))
1235 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1236 gl_ctx, dc, GetLastError());
1237 context_set_current(NULL);
1241 static void context_update_window(struct wined3d_context *context)
1243 if (!context->swapchain)
1244 return;
1246 if (context->win_handle == context->swapchain->win_handle)
1247 return;
1249 TRACE("Updating context %p window from %p to %p.\n",
1250 context, context->win_handle, context->swapchain->win_handle);
1252 if (context->hdc)
1253 wined3d_release_dc(context->win_handle, context->hdc);
1255 context->win_handle = context->swapchain->win_handle;
1256 context->hdc_is_private = FALSE;
1257 context->hdc_has_format = FALSE;
1258 context->needs_set = 1;
1259 context->valid = 1;
1261 if (!(context->hdc = GetDCEx(context->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1263 ERR("Failed to get a device context for window %p.\n", context->win_handle);
1264 context->valid = 0;
1268 static void context_destroy_gl_resources(struct wined3d_context *context)
1270 struct wined3d_pipeline_statistics_query *pipeline_statistics_query;
1271 const struct wined3d_gl_info *gl_info = context->gl_info;
1272 struct wined3d_so_statistics_query *so_statistics_query;
1273 struct wined3d_timestamp_query *timestamp_query;
1274 struct wined3d_occlusion_query *occlusion_query;
1275 struct fbo_entry *entry, *entry2;
1276 struct wined3d_fence *fence;
1277 HGLRC restore_ctx;
1278 HDC restore_dc;
1279 unsigned int i;
1281 restore_ctx = wglGetCurrentContext();
1282 restore_dc = wglGetCurrentDC();
1284 if (restore_ctx == context->glCtx)
1285 restore_ctx = NULL;
1286 else if (context->valid)
1287 context_set_gl_context(context);
1289 LIST_FOR_EACH_ENTRY(so_statistics_query, &context->so_statistics_queries,
1290 struct wined3d_so_statistics_query, entry)
1292 if (context->valid)
1293 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(so_statistics_query->u.id), so_statistics_query->u.id));
1294 so_statistics_query->context = NULL;
1297 LIST_FOR_EACH_ENTRY(pipeline_statistics_query, &context->pipeline_statistics_queries,
1298 struct wined3d_pipeline_statistics_query, entry)
1300 if (context->valid)
1301 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(pipeline_statistics_query->u.id), pipeline_statistics_query->u.id));
1302 pipeline_statistics_query->context = NULL;
1305 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1307 if (context->valid)
1308 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1309 timestamp_query->context = NULL;
1312 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1314 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1315 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1316 occlusion_query->context = NULL;
1319 LIST_FOR_EACH_ENTRY(fence, &context->fences, struct wined3d_fence, entry)
1321 if (context->valid)
1323 if (gl_info->supported[ARB_SYNC])
1325 if (fence->object.sync)
1326 GL_EXTCALL(glDeleteSync(fence->object.sync));
1328 else if (gl_info->supported[APPLE_FENCE])
1330 GL_EXTCALL(glDeleteFencesAPPLE(1, &fence->object.id));
1332 else if (gl_info->supported[NV_FENCE])
1334 GL_EXTCALL(glDeleteFencesNV(1, &fence->object.id));
1337 fence->context = NULL;
1340 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1342 if (!context->valid) entry->id = 0;
1343 context_destroy_fbo_entry(context, entry);
1346 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1348 if (!context->valid) entry->id = 0;
1349 context_destroy_fbo_entry(context, entry);
1352 if (context->valid)
1354 if (context->dummy_arbfp_prog)
1356 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1359 if (gl_info->supported[WINED3D_GL_PRIMITIVE_QUERY])
1361 for (i = 0; i < context->free_so_statistics_query_count; ++i)
1363 union wined3d_gl_so_statistics_query *q = &context->free_so_statistics_queries[i];
1364 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1368 if (gl_info->supported[ARB_PIPELINE_STATISTICS_QUERY])
1370 for (i = 0; i < context->free_pipeline_statistics_query_count; ++i)
1372 union wined3d_gl_pipeline_statistics_query *q = &context->free_pipeline_statistics_queries[i];
1373 GL_EXTCALL(glDeleteQueries(ARRAY_SIZE(q->id), q->id));
1377 if (gl_info->supported[ARB_TIMER_QUERY])
1378 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1380 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1381 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1383 if (gl_info->supported[ARB_SYNC])
1385 for (i = 0; i < context->free_fence_count; ++i)
1387 GL_EXTCALL(glDeleteSync(context->free_fences[i].sync));
1390 else if (gl_info->supported[APPLE_FENCE])
1392 for (i = 0; i < context->free_fence_count; ++i)
1394 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_fences[i].id));
1397 else if (gl_info->supported[NV_FENCE])
1399 for (i = 0; i < context->free_fence_count; ++i)
1401 GL_EXTCALL(glDeleteFencesNV(1, &context->free_fences[i].id));
1405 checkGLcall("context cleanup");
1408 HeapFree(GetProcessHeap(), 0, context->free_so_statistics_queries);
1409 HeapFree(GetProcessHeap(), 0, context->free_pipeline_statistics_queries);
1410 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1411 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1412 HeapFree(GetProcessHeap(), 0, context->free_fences);
1414 context_restore_pixel_format(context);
1415 if (restore_ctx)
1417 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1419 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1421 ERR("Failed to disable GL context.\n");
1424 wined3d_release_dc(context->win_handle, context->hdc);
1426 if (!wglDeleteContext(context->glCtx))
1428 DWORD err = GetLastError();
1429 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1433 DWORD context_get_tls_idx(void)
1435 return wined3d_context_tls_idx;
1438 void context_set_tls_idx(DWORD idx)
1440 wined3d_context_tls_idx = idx;
1443 struct wined3d_context *context_get_current(void)
1445 return TlsGetValue(wined3d_context_tls_idx);
1448 BOOL context_set_current(struct wined3d_context *ctx)
1450 struct wined3d_context *old = context_get_current();
1452 if (old == ctx)
1454 TRACE("Already using D3D context %p.\n", ctx);
1455 return TRUE;
1458 if (old)
1460 if (old->destroyed)
1462 TRACE("Switching away from destroyed context %p.\n", old);
1463 context_destroy_gl_resources(old);
1464 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1465 HeapFree(GetProcessHeap(), 0, old);
1467 else
1469 if (wglGetCurrentContext())
1471 const struct wined3d_gl_info *gl_info = old->gl_info;
1472 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1473 gl_info->gl_ops.gl.p_glFlush();
1475 old->current = 0;
1479 if (ctx)
1481 if (!ctx->valid)
1483 ERR("Trying to make invalid context %p current\n", ctx);
1484 return FALSE;
1487 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1488 if (!context_set_gl_context(ctx))
1489 return FALSE;
1490 ctx->current = 1;
1492 else if (wglGetCurrentContext())
1494 TRACE("Clearing current D3D context.\n");
1495 if (!wglMakeCurrent(NULL, NULL))
1497 DWORD err = GetLastError();
1498 ERR("Failed to clear current GL context, last error %#x.\n", err);
1499 TlsSetValue(wined3d_context_tls_idx, NULL);
1500 return FALSE;
1504 return TlsSetValue(wined3d_context_tls_idx, ctx);
1507 void context_release(struct wined3d_context *context)
1509 TRACE("Releasing context %p, level %u.\n", context, context->level);
1511 if (WARN_ON(d3d))
1513 if (!context->level)
1514 WARN("Context %p is not active.\n", context);
1515 else if (context != context_get_current())
1516 WARN("Context %p is not the current context.\n", context);
1519 if (!--context->level)
1521 if (context_restore_pixel_format(context))
1522 context->needs_set = 1;
1523 if (context->restore_ctx)
1525 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1526 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1527 context->restore_ctx = NULL;
1528 context->restore_dc = NULL;
1531 if (context->destroy_delayed)
1533 TRACE("Destroying context %p.\n", context);
1534 context_destroy(context->device, context);
1539 /* This is used when a context for render target A is active, but a separate context is
1540 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1541 * A to avoid breaking caller code. */
1542 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1544 if (context->current_rt.texture != restore->container
1545 || context->current_rt.sub_resource_idx != surface_get_sub_resource_idx(restore))
1547 context_release(context);
1548 context = context_acquire(restore->container->resource.device,
1549 restore->container, surface_get_sub_resource_idx(restore));
1552 context_release(context);
1555 static void context_enter(struct wined3d_context *context)
1557 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1559 if (!context->level++)
1561 const struct wined3d_context *current_context = context_get_current();
1562 HGLRC current_gl = wglGetCurrentContext();
1564 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1566 TRACE("Another GL context (%p on device context %p) is already current.\n",
1567 current_gl, wglGetCurrentDC());
1568 context->restore_ctx = current_gl;
1569 context->restore_dc = wglGetCurrentDC();
1570 context->needs_set = 1;
1572 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1573 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1574 context->needs_set = 1;
1578 void context_invalidate_compute_state(struct wined3d_context *context, DWORD state_id)
1580 DWORD representative = context->state_table[state_id].representative - STATE_COMPUTE_OFFSET;
1581 unsigned int index, shift;
1583 index = representative / (sizeof(*context->dirty_compute_states) * CHAR_BIT);
1584 shift = representative & (sizeof(*context->dirty_compute_states) * CHAR_BIT - 1);
1585 context->dirty_compute_states[index] |= (1u << shift);
1588 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1590 DWORD rep = context->state_table[state].representative;
1591 DWORD idx;
1592 BYTE shift;
1594 if (isStateDirty(context, rep)) return;
1596 context->dirtyArray[context->numDirtyEntries++] = rep;
1597 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1598 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1599 context->isStateDirty[idx] |= (1u << shift);
1602 /* This function takes care of wined3d pixel format selection. */
1603 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1604 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1605 BOOL auxBuffers)
1607 unsigned int cfg_count = device->adapter->cfg_count;
1608 unsigned int current_value;
1609 PIXELFORMATDESCRIPTOR pfd;
1610 int iPixelFormat = 0;
1611 unsigned int i;
1613 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x.\n",
1614 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1615 auxBuffers);
1617 current_value = 0;
1618 for (i = 0; i < cfg_count; ++i)
1620 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1621 unsigned int value;
1623 /* For now only accept RGBA formats. Perhaps some day we will
1624 * allow floating point formats for pbuffers. */
1625 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1626 continue;
1627 /* In window mode we need a window drawable format and double buffering. */
1628 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1629 continue;
1630 if (cfg->redSize < color_format->red_size)
1631 continue;
1632 if (cfg->greenSize < color_format->green_size)
1633 continue;
1634 if (cfg->blueSize < color_format->blue_size)
1635 continue;
1636 if (cfg->alphaSize < color_format->alpha_size)
1637 continue;
1638 if (cfg->depthSize < ds_format->depth_size)
1639 continue;
1640 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1641 continue;
1642 /* Check multisampling support. */
1643 if (cfg->numSamples)
1644 continue;
1646 value = 1;
1647 /* We try to locate a format which matches our requirements exactly. In case of
1648 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1649 if (cfg->depthSize == ds_format->depth_size)
1650 value += 1;
1651 if (cfg->stencilSize == ds_format->stencil_size)
1652 value += 2;
1653 if (cfg->alphaSize == color_format->alpha_size)
1654 value += 4;
1655 /* We like to have aux buffers in backbuffer mode */
1656 if (auxBuffers && cfg->auxBuffers)
1657 value += 8;
1658 if (cfg->redSize == color_format->red_size
1659 && cfg->greenSize == color_format->green_size
1660 && cfg->blueSize == color_format->blue_size)
1661 value += 16;
1663 if (value > current_value)
1665 iPixelFormat = cfg->iPixelFormat;
1666 current_value = value;
1670 if (!iPixelFormat)
1672 ERR("Trying to locate a compatible pixel format because an exact match failed.\n");
1674 memset(&pfd, 0, sizeof(pfd));
1675 pfd.nSize = sizeof(pfd);
1676 pfd.nVersion = 1;
1677 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1678 pfd.iPixelType = PFD_TYPE_RGBA;
1679 pfd.cAlphaBits = color_format->alpha_size;
1680 pfd.cColorBits = color_format->red_size + color_format->green_size
1681 + color_format->blue_size + color_format->alpha_size;
1682 pfd.cDepthBits = ds_format->depth_size;
1683 pfd.cStencilBits = ds_format->stencil_size;
1684 pfd.iLayerType = PFD_MAIN_PLANE;
1686 if (!(iPixelFormat = ChoosePixelFormat(hdc, &pfd)))
1688 /* Something is very wrong as ChoosePixelFormat() barely fails. */
1689 ERR("Can't find a suitable pixel format.\n");
1690 return 0;
1694 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s.\n",
1695 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1696 return iPixelFormat;
1699 /* Context activation is done by the caller. */
1700 void context_bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1702 const struct wined3d_gl_info *gl_info = context->gl_info;
1703 unsigned int i;
1705 for (i = 0; i < gl_info->limits.combined_samplers; ++i)
1707 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1708 checkGLcall("glActiveTexture");
1710 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
1712 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1713 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
1715 if (gl_info->supported[EXT_TEXTURE3D])
1716 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
1718 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1719 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
1721 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP_ARRAY])
1722 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
1724 if (gl_info->supported[EXT_TEXTURE_ARRAY])
1725 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
1727 if (gl_info->supported[ARB_TEXTURE_BUFFER_OBJECT])
1728 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
1730 checkGLcall("Bind dummy textures");
1734 void wined3d_check_gl_call(const struct wined3d_gl_info *gl_info,
1735 const char *file, unsigned int line, const char *name)
1737 GLint err;
1739 if (gl_info->supported[ARB_DEBUG_OUTPUT] || (err = gl_info->gl_ops.gl.p_glGetError()) == GL_NO_ERROR)
1741 TRACE("%s call ok %s / %u.\n", name, file, line);
1742 return;
1747 ERR(">>>>>>> %s (%#x) from %s @ %s / %u.\n",
1748 debug_glerror(err), err, name, file,line);
1749 err = gl_info->gl_ops.gl.p_glGetError();
1750 } while (err != GL_NO_ERROR);
1753 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1755 return gl_info->supported[ARB_DEBUG_OUTPUT]
1756 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1759 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1760 GLenum severity, GLsizei length, const char *message, void *ctx)
1762 switch (type)
1764 case GL_DEBUG_TYPE_ERROR_ARB:
1765 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1766 break;
1768 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1769 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1770 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1771 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1772 break;
1774 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1775 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1776 break;
1778 default:
1779 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1780 break;
1784 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1786 HGLRC ctx;
1787 unsigned int ctx_attrib_idx = 0;
1788 GLint ctx_attribs[7], ctx_flags = 0;
1790 if (context_debug_output_enabled(gl_info))
1791 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1792 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1793 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1794 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1795 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1796 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1797 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1798 if (ctx_flags)
1800 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1801 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1803 ctx_attribs[ctx_attrib_idx] = 0;
1805 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1807 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1809 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1810 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1811 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1812 GetLastError());
1815 return ctx;
1818 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1819 struct wined3d_texture *target, const struct wined3d_format *ds_format)
1821 struct wined3d_device *device = swapchain->device;
1822 const struct wined3d_d3d_info *d3d_info = &device->adapter->d3d_info;
1823 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1824 const struct wined3d_format *color_format;
1825 struct wined3d_context *ret;
1826 BOOL auxBuffers = FALSE;
1827 HGLRC ctx, share_ctx;
1828 DWORD target_usage;
1829 unsigned int i;
1830 DWORD state;
1832 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1834 wined3d_from_cs(device->cs);
1836 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1837 if (!ret)
1838 return NULL;
1840 if (!(ret->blit_targets = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->blit_targets))))
1841 goto out;
1843 if (!(ret->draw_buffers = wined3d_calloc(gl_info->limits.buffers, sizeof(*ret->draw_buffers))))
1844 goto out;
1846 ret->fbo_key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1847 FIELD_OFFSET(struct wined3d_fbo_entry_key, objects[gl_info->limits.buffers + 1]));
1848 if (!ret->fbo_key)
1849 goto out;
1851 ret->free_timestamp_query_size = 4;
1852 if (!(ret->free_timestamp_queries = wined3d_calloc(ret->free_timestamp_query_size,
1853 sizeof(*ret->free_timestamp_queries))))
1854 goto out;
1855 list_init(&ret->timestamp_queries);
1857 ret->free_occlusion_query_size = 4;
1858 if (!(ret->free_occlusion_queries = wined3d_calloc(ret->free_occlusion_query_size,
1859 sizeof(*ret->free_occlusion_queries))))
1860 goto out;
1861 list_init(&ret->occlusion_queries);
1863 ret->free_fence_size = 4;
1864 if (!(ret->free_fences = wined3d_calloc(ret->free_fence_size, sizeof(*ret->free_fences))))
1865 goto out;
1866 list_init(&ret->fences);
1868 list_init(&ret->so_statistics_queries);
1870 list_init(&ret->pipeline_statistics_queries);
1872 list_init(&ret->fbo_list);
1873 list_init(&ret->fbo_destroy_list);
1875 if (!device->shader_backend->shader_allocate_context_data(ret))
1877 ERR("Failed to allocate shader backend context data.\n");
1878 goto out;
1880 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1882 ERR("Failed to allocate fragment pipeline context data.\n");
1883 goto out;
1886 for (i = 0; i < ARRAY_SIZE(ret->tex_unit_map); ++i)
1887 ret->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1888 for (i = 0; i < ARRAY_SIZE(ret->rev_tex_unit_map); ++i)
1889 ret->rev_tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
1890 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
1892 /* Initialize the texture unit mapping to a 1:1 mapping. */
1893 unsigned int base, count;
1895 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_PIXEL, &base, &count);
1896 if (base + MAX_FRAGMENT_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1898 ERR("Unexpected texture unit base index %u.\n", base);
1899 goto out;
1901 for (i = 0; i < min(count, MAX_FRAGMENT_SAMPLERS); ++i)
1903 ret->tex_unit_map[i] = base + i;
1904 ret->rev_tex_unit_map[base + i] = i;
1907 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, WINED3D_SHADER_TYPE_VERTEX, &base, &count);
1908 if (base + MAX_VERTEX_SAMPLERS > ARRAY_SIZE(ret->rev_tex_unit_map))
1910 ERR("Unexpected texture unit base index %u.\n", base);
1911 goto out;
1913 for (i = 0; i < min(count, MAX_VERTEX_SAMPLERS); ++i)
1915 ret->tex_unit_map[MAX_FRAGMENT_SAMPLERS + i] = base + i;
1916 ret->rev_tex_unit_map[base + i] = MAX_FRAGMENT_SAMPLERS + i;
1920 if (!(ret->texture_type = wined3d_calloc(gl_info->limits.combined_samplers,
1921 sizeof(*ret->texture_type))))
1922 goto out;
1924 if (!(ret->hdc = GetDCEx(swapchain->win_handle, 0, DCX_USESTYLE | DCX_CACHE)))
1926 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1928 if ((ret->hdc = swapchain_get_backup_dc(swapchain)))
1929 ret->hdc_is_private = TRUE;
1930 else
1932 ERR("Failed to retrieve a device context.\n");
1933 goto out;
1937 color_format = target->resource.format;
1938 target_usage = target->resource.usage;
1940 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1941 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1942 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1944 auxBuffers = TRUE;
1946 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1947 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM, target_usage);
1948 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1949 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1952 /* DirectDraw supports 8bit paletted render targets and these are used by
1953 * old games like StarCraft and C&C. Most modern hardware doesn't support
1954 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1955 * conversion (ab)uses the alpha component for storing the palette index.
1956 * For this reason we require a format with 8bit alpha, so request
1957 * A8R8G8B8. */
1958 if (color_format->id == WINED3DFMT_P8_UINT)
1959 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1961 /* When using FBOs for off-screen rendering, we only use the drawable for
1962 * presentation blits, and don't do any rendering to it. That means we
1963 * don't need depth or stencil buffers, and can mostly ignore the render
1964 * target format. This wouldn't necessarily be quite correct for 10bpc
1965 * display modes, but we don't currently support those.
1966 * Using the same format regardless of the color/depth/stencil targets
1967 * makes it much less likely that different wined3d instances will set
1968 * conflicting pixel formats. */
1969 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER)
1971 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM, target_usage);
1972 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN, WINED3DUSAGE_DEPTHSTENCIL);
1975 /* Try to find a pixel format which matches our requirements. */
1976 if (!(ret->pixel_format = context_choose_pixel_format(device, ret->hdc, color_format, ds_format, auxBuffers)))
1977 goto out;
1979 ret->gl_info = gl_info;
1980 ret->win_handle = swapchain->win_handle;
1982 context_enter(ret);
1984 if (!context_set_pixel_format(ret))
1986 ERR("Failed to set pixel format %d on device context %p.\n", ret->pixel_format, ret->hdc);
1987 context_release(ret);
1988 goto out;
1991 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1992 if (gl_info->p_wglCreateContextAttribsARB)
1994 if (!(ctx = context_create_wgl_attribs(gl_info, ret->hdc, share_ctx)))
1995 goto out;
1997 else
1999 if (!(ctx = wglCreateContext(ret->hdc)))
2001 ERR("Failed to create a WGL context.\n");
2002 context_release(ret);
2003 goto out;
2006 if (share_ctx && !wglShareLists(share_ctx, ctx))
2008 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
2009 context_release(ret);
2010 if (!wglDeleteContext(ctx))
2011 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2012 goto out;
2016 if (!device_context_add(device, ret))
2018 ERR("Failed to add the newly created context to the context list\n");
2019 context_release(ret);
2020 if (!wglDeleteContext(ctx))
2021 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2022 goto out;
2025 ret->d3d_info = d3d_info;
2026 ret->state_table = device->StateTable;
2028 /* Mark all states dirty to force a proper initialization of the states on
2029 * the first use of the context. Compute states do not need initialization. */
2030 for (state = 0; state <= STATE_HIGHEST; ++state)
2032 if (ret->state_table[state].representative && !STATE_IS_COMPUTE(state))
2033 context_invalidate_state(ret, state);
2036 ret->device = device;
2037 ret->swapchain = swapchain;
2038 ret->current_rt.texture = target;
2039 ret->current_rt.sub_resource_idx = 0;
2040 ret->tid = GetCurrentThreadId();
2042 ret->render_offscreen = wined3d_resource_is_offscreen(&target->resource);
2043 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
2044 ret->valid = 1;
2046 ret->glCtx = ctx;
2047 ret->hdc_has_format = TRUE;
2048 ret->needs_set = 1;
2050 /* Set up the context defaults */
2051 if (!context_set_current(ret))
2053 ERR("Cannot activate context to set up defaults.\n");
2054 device_context_remove(device, ret);
2055 context_release(ret);
2056 if (!wglDeleteContext(ctx))
2057 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
2058 goto out;
2061 if (context_debug_output_enabled(gl_info))
2063 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
2064 if (TRACE_ON(d3d_synchronous))
2065 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
2066 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
2067 if (ERR_ON(d3d))
2069 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
2070 GL_DONT_CARE, 0, NULL, GL_TRUE));
2072 if (FIXME_ON(d3d))
2074 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
2075 GL_DONT_CARE, 0, NULL, GL_TRUE));
2076 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
2077 GL_DONT_CARE, 0, NULL, GL_TRUE));
2078 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
2079 GL_DONT_CARE, 0, NULL, GL_TRUE));
2081 if (WARN_ON(d3d_perf))
2083 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
2084 GL_DONT_CARE, 0, NULL, GL_TRUE));
2088 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2089 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
2091 TRACE("Setting up the screen\n");
2093 if (gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
2095 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
2096 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
2098 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
2099 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
2101 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
2102 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
2104 else
2106 GLuint vao;
2108 GL_EXTCALL(glGenVertexArrays(1, &vao));
2109 GL_EXTCALL(glBindVertexArray(vao));
2110 checkGLcall("creating VAO");
2113 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
2114 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
2115 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
2116 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, 1);");
2118 if (gl_info->supported[ARB_VERTEX_BLEND])
2120 /* Direct3D always uses n-1 weights for n world matrices and uses
2121 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
2122 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
2123 * enabled as well. */
2124 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
2125 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
2127 if (gl_info->supported[NV_TEXTURE_SHADER2])
2129 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
2130 * the previous texture where to source the offset from is always unit - 1.
2132 for (i = 1; i < gl_info->limits.textures; ++i)
2134 context_active_texture(ret, gl_info, i);
2135 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
2136 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + i - 1);
2137 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
2140 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
2142 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
2143 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
2144 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
2145 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
2146 * is ever assigned.
2148 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
2149 * program and the dummy program is destroyed when the context is destroyed.
2151 static const char dummy_program[] =
2152 "!!ARBfp1.0\n"
2153 "MOV result.color, fragment.color.primary;\n"
2154 "END\n";
2155 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
2156 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
2157 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
2160 if (gl_info->supported[ARB_POINT_SPRITE])
2162 for (i = 0; i < gl_info->limits.textures; ++i)
2164 context_active_texture(ret, gl_info, i);
2165 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
2166 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
2170 if (gl_info->supported[ARB_PROVOKING_VERTEX])
2172 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
2174 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
2176 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
2178 if (!(d3d_info->wined3d_creation_flags & WINED3D_NO_PRIMITIVE_RESTART))
2180 if (gl_info->supported[ARB_ES3_COMPATIBILITY])
2182 gl_info->gl_ops.gl.p_glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
2183 checkGLcall("enable GL_PRIMITIVE_RESTART_FIXED_INDEX");
2185 else
2187 FIXME("OpenGL implementation does not support GL_PRIMITIVE_RESTART_FIXED_INDEX.\n");
2190 if (!(d3d_info->wined3d_creation_flags & WINED3D_LEGACY_CUBEMAP_FILTERING)
2191 && gl_info->supported[ARB_SEAMLESS_CUBE_MAP])
2193 gl_info->gl_ops.gl.p_glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
2194 checkGLcall("enable seamless cube map filtering");
2196 if (gl_info->supported[ARB_CLIP_CONTROL])
2197 GL_EXTCALL(glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT));
2198 device->shader_backend->shader_init_context_state(ret);
2199 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
2200 | (1u << WINED3D_SHADER_TYPE_VERTEX)
2201 | (1u << WINED3D_SHADER_TYPE_GEOMETRY)
2202 | (1u << WINED3D_SHADER_TYPE_HULL)
2203 | (1u << WINED3D_SHADER_TYPE_DOMAIN)
2204 | (1u << WINED3D_SHADER_TYPE_COMPUTE);
2206 /* If this happens to be the first context for the device, dummy textures
2207 * are not created yet. In that case, they will be created (and bound) by
2208 * create_dummy_textures right after this context is initialized. */
2209 if (device->dummy_textures.tex_2d)
2210 context_bind_dummy_textures(device, ret);
2212 TRACE("Created context %p.\n", ret);
2214 return ret;
2216 out:
2217 if (ret->hdc)
2218 wined3d_release_dc(swapchain->win_handle, ret->hdc);
2219 device->shader_backend->shader_free_context_data(ret);
2220 device->adapter->fragment_pipe->free_context_data(ret);
2221 HeapFree(GetProcessHeap(), 0, ret->texture_type);
2222 HeapFree(GetProcessHeap(), 0, ret->free_fences);
2223 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
2224 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
2225 HeapFree(GetProcessHeap(), 0, ret->fbo_key);
2226 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
2227 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
2228 HeapFree(GetProcessHeap(), 0, ret);
2229 return NULL;
2232 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
2234 BOOL destroy;
2236 TRACE("Destroying ctx %p\n", context);
2238 wined3d_from_cs(device->cs);
2240 /* We delay destroying a context when it is active. The context_release()
2241 * function invokes context_destroy() again while leaving the last level. */
2242 if (context->level)
2244 TRACE("Delaying destruction of context %p.\n", context);
2245 context->destroy_delayed = 1;
2246 /* FIXME: Get rid of a pointer to swapchain from wined3d_context. */
2247 context->swapchain = NULL;
2248 return;
2251 if (context->tid == GetCurrentThreadId() || !context->current)
2253 context_destroy_gl_resources(context);
2254 TlsSetValue(wined3d_context_tls_idx, NULL);
2255 destroy = TRUE;
2257 else
2259 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
2260 in wined3d_adapter may go away in the meantime */
2261 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
2262 *gl_info = *context->gl_info;
2263 context->gl_info = gl_info;
2264 context->destroyed = 1;
2265 destroy = FALSE;
2268 device->shader_backend->shader_free_context_data(context);
2269 device->adapter->fragment_pipe->free_context_data(context);
2270 HeapFree(GetProcessHeap(), 0, context->texture_type);
2271 HeapFree(GetProcessHeap(), 0, context->fbo_key);
2272 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
2273 HeapFree(GetProcessHeap(), 0, context->blit_targets);
2274 device_context_remove(device, context);
2275 if (destroy) HeapFree(GetProcessHeap(), 0, context);
2278 const DWORD *context_get_tex_unit_mapping(const struct wined3d_context *context,
2279 const struct wined3d_shader_version *shader_version, unsigned int *base, unsigned int *count)
2281 const struct wined3d_gl_info *gl_info = context->gl_info;
2283 if (!shader_version)
2285 *base = 0;
2286 *count = MAX_TEXTURES;
2287 return context->tex_unit_map;
2290 if (shader_version->major >= 4)
2292 wined3d_gl_limits_get_texture_unit_range(&gl_info->limits, shader_version->type, base, count);
2293 return NULL;
2296 switch (shader_version->type)
2298 case WINED3D_SHADER_TYPE_PIXEL:
2299 *base = 0;
2300 *count = MAX_FRAGMENT_SAMPLERS;
2301 break;
2302 case WINED3D_SHADER_TYPE_VERTEX:
2303 *base = MAX_FRAGMENT_SAMPLERS;
2304 *count = MAX_VERTEX_SAMPLERS;
2305 break;
2306 default:
2307 ERR("Unhandled shader type %#x.\n", shader_version->type);
2308 *base = 0;
2309 *count = 0;
2312 return context->tex_unit_map;
2315 /* Context activation is done by the caller. */
2316 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
2318 const GLdouble projection[] =
2320 2.0 / width, 0.0, 0.0, 0.0,
2321 0.0, 2.0 / height, 0.0, 0.0,
2322 0.0, 0.0, 2.0, 0.0,
2323 -1.0, -1.0, -1.0, 1.0,
2326 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
2327 checkGLcall("glMatrixMode(GL_PROJECTION)");
2328 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
2329 checkGLcall("glLoadMatrixd");
2330 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
2331 checkGLcall("glViewport");
2334 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
2336 const struct wined3d_texture *rt = context->current_rt.texture;
2337 unsigned int level;
2339 if (rt->swapchain)
2341 RECT window_size;
2343 GetClientRect(context->win_handle, &window_size);
2344 size->cx = window_size.right - window_size.left;
2345 size->cy = window_size.bottom - window_size.top;
2347 return;
2350 level = context->current_rt.sub_resource_idx % rt->level_count;
2351 size->cx = wined3d_texture_get_level_width(rt, level);
2352 size->cy = wined3d_texture_get_level_height(rt, level);
2355 /*****************************************************************************
2356 * SetupForBlit
2358 * Sets up a context for DirectDraw blitting.
2359 * All texture units are disabled, texture unit 0 is set as current unit
2360 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
2361 * color writing enabled for all channels
2362 * register combiners disabled, shaders disabled
2363 * world matrix is set to identity, texture matrix 0 too
2364 * projection matrix is setup for drawing screen coordinates
2366 * Params:
2367 * This: Device to activate the context for
2368 * context: Context to setup
2370 *****************************************************************************/
2371 /* Context activation is done by the caller. */
2372 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
2374 int i;
2375 const struct wined3d_gl_info *gl_info = context->gl_info;
2376 DWORD sampler;
2377 SIZE rt_size;
2379 TRACE("Setting up context %p for blitting\n", context);
2381 context_get_rt_size(context, &rt_size);
2383 if (context->last_was_blit)
2385 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
2387 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2388 context->blit_w = rt_size.cx;
2389 context->blit_h = rt_size.cy;
2390 /* No need to dirtify here, the states are still dirtified because
2391 * they weren't applied since the last SetupForBlit() call. */
2393 TRACE("Context is already set up for blitting, nothing to do\n");
2394 return;
2396 context->last_was_blit = TRUE;
2398 /* Disable all textures. The caller can then bind a texture it wants to blit
2399 * from
2401 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2402 * function texture unit. No need to care for higher samplers
2404 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2406 sampler = context->rev_tex_unit_map[i];
2407 context_active_texture(context, gl_info, i);
2409 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2411 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2412 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2414 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2415 checkGLcall("glDisable GL_TEXTURE_3D");
2416 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2418 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2419 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2421 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2422 checkGLcall("glDisable GL_TEXTURE_2D");
2424 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2425 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2427 if (sampler != WINED3D_UNMAPPED_STAGE)
2429 if (sampler < MAX_TEXTURES)
2430 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2431 context_invalidate_state(context, STATE_SAMPLER(sampler));
2434 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2435 GL_EXTCALL(glBindSampler(0, 0));
2436 context_active_texture(context, gl_info, 0);
2438 sampler = context->rev_tex_unit_map[0];
2440 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2442 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2443 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2445 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2446 checkGLcall("glDisable GL_TEXTURE_3D");
2447 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2449 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2450 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2452 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2453 checkGLcall("glDisable GL_TEXTURE_2D");
2455 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2457 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2458 checkGLcall("glMatrixMode(GL_TEXTURE)");
2459 gl_info->gl_ops.gl.p_glLoadIdentity();
2460 checkGLcall("glLoadIdentity()");
2462 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2464 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2465 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2466 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2469 if (sampler != WINED3D_UNMAPPED_STAGE)
2471 if (sampler < MAX_TEXTURES)
2473 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2474 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2476 context_invalidate_state(context, STATE_SAMPLER(sampler));
2479 /* Other misc states */
2480 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2481 checkGLcall("glDisable(GL_ALPHA_TEST)");
2482 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2483 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2484 checkGLcall("glDisable GL_LIGHTING");
2485 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2486 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2487 checkGLcall("glDisable GL_DEPTH_TEST");
2488 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2489 glDisableWINE(GL_FOG);
2490 checkGLcall("glDisable GL_FOG");
2491 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2492 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2493 checkGLcall("glDisable GL_BLEND");
2494 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2495 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2496 checkGLcall("glDisable GL_CULL_FACE");
2497 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2498 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2499 checkGLcall("glDisable GL_STENCIL_TEST");
2500 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2501 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2502 checkGLcall("glDisable GL_SCISSOR_TEST");
2503 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2504 if (gl_info->supported[ARB_POINT_SPRITE])
2506 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2507 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2508 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2510 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2511 checkGLcall("glColorMask");
2512 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2513 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2514 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2515 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2516 if (gl_info->supported[EXT_SECONDARY_COLOR])
2518 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2519 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2520 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2523 /* Setup transforms */
2524 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2525 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2526 gl_info->gl_ops.gl.p_glLoadIdentity();
2527 checkGLcall("glLoadIdentity()");
2528 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2530 context->last_was_rhw = TRUE;
2531 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2533 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2534 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2535 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2536 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2537 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2538 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2539 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2541 /* FIXME: Make draw_textured_quad() able to work with a upper left origin. */
2542 if (gl_info->supported[ARB_CLIP_CONTROL])
2543 GL_EXTCALL(glClipControl(GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE));
2545 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2547 /* Disable shaders */
2548 device->shader_backend->shader_disable(device->shader_priv, context);
2550 context->blit_w = rt_size.cx;
2551 context->blit_h = rt_size.cy;
2552 context_invalidate_state(context, STATE_VIEWPORT);
2553 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2556 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2558 return rt_mask & (1u << 31);
2561 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2563 return rt_mask & ~(1u << 31);
2566 /* Context activation is done by the caller. */
2567 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2569 const struct wined3d_gl_info *gl_info = context->gl_info;
2571 if (!rt_mask)
2573 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2574 checkGLcall("glDrawBuffer()");
2576 else if (is_rt_mask_onscreen(rt_mask))
2578 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2579 checkGLcall("glDrawBuffer()");
2581 else
2583 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2585 unsigned int i = 0;
2587 while (rt_mask)
2589 if (rt_mask & 1)
2590 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2591 else
2592 context->draw_buffers[i] = GL_NONE;
2594 rt_mask >>= 1;
2595 ++i;
2598 if (gl_info->supported[ARB_DRAW_BUFFERS])
2600 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2601 checkGLcall("glDrawBuffers()");
2603 else
2605 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2606 checkGLcall("glDrawBuffer()");
2609 else
2611 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2616 /* Context activation is done by the caller. */
2617 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2619 const struct wined3d_gl_info *gl_info = context->gl_info;
2620 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2621 DWORD new_mask = context_generate_rt_mask(buffer);
2623 if (new_mask == *current_mask)
2624 return;
2626 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2627 checkGLcall("glDrawBuffer()");
2629 *current_mask = new_mask;
2632 /* Context activation is done by the caller. */
2633 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2635 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2636 checkGLcall("glActiveTexture");
2637 context->active_texture = unit;
2640 void context_bind_bo(struct wined3d_context *context, GLenum binding, GLuint name)
2642 const struct wined3d_gl_info *gl_info = context->gl_info;
2644 if (binding == GL_ELEMENT_ARRAY_BUFFER)
2645 context_invalidate_state(context, STATE_INDEXBUFFER);
2647 GL_EXTCALL(glBindBuffer(binding, name));
2650 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2652 const struct wined3d_gl_info *gl_info = context->gl_info;
2653 DWORD unit = context->active_texture;
2654 DWORD old_texture_type = context->texture_type[unit];
2656 if (name)
2658 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2659 checkGLcall("glBindTexture");
2661 else
2663 target = GL_NONE;
2666 if (old_texture_type != target)
2668 const struct wined3d_device *device = context->device;
2670 switch (old_texture_type)
2672 case GL_NONE:
2673 /* nothing to do */
2674 break;
2675 case GL_TEXTURE_2D:
2676 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_textures.tex_2d);
2677 checkGLcall("glBindTexture");
2678 break;
2679 case GL_TEXTURE_2D_ARRAY:
2680 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D_ARRAY, device->dummy_textures.tex_2d_array);
2681 checkGLcall("glBindTexture");
2682 break;
2683 case GL_TEXTURE_RECTANGLE_ARB:
2684 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_textures.tex_rect);
2685 checkGLcall("glBindTexture");
2686 break;
2687 case GL_TEXTURE_CUBE_MAP:
2688 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_textures.tex_cube);
2689 checkGLcall("glBindTexture");
2690 break;
2691 case GL_TEXTURE_CUBE_MAP_ARRAY:
2692 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, device->dummy_textures.tex_cube_array);
2693 checkGLcall("glBindTexture");
2694 break;
2695 case GL_TEXTURE_3D:
2696 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_textures.tex_3d);
2697 checkGLcall("glBindTexture");
2698 break;
2699 case GL_TEXTURE_BUFFER:
2700 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_BUFFER, device->dummy_textures.tex_buffer);
2701 checkGLcall("glBindTexture");
2702 break;
2703 default:
2704 ERR("Unexpected texture target %#x.\n", old_texture_type);
2707 context->texture_type[unit] = target;
2711 void *context_map_bo_address(struct wined3d_context *context,
2712 const struct wined3d_bo_address *data, size_t size, GLenum binding, DWORD flags)
2714 const struct wined3d_gl_info *gl_info;
2715 BYTE *memory;
2717 if (!data->buffer_object)
2718 return data->addr;
2720 gl_info = context->gl_info;
2721 context_bind_bo(context, binding, data->buffer_object);
2723 if (gl_info->supported[ARB_MAP_BUFFER_RANGE])
2725 GLbitfield map_flags = wined3d_resource_gl_map_flags(flags) & ~GL_MAP_FLUSH_EXPLICIT_BIT;
2726 memory = GL_EXTCALL(glMapBufferRange(binding, (INT_PTR)data->addr, size, map_flags));
2728 else
2730 memory = GL_EXTCALL(glMapBuffer(binding, wined3d_resource_gl_legacy_map_flags(flags)));
2731 memory += (INT_PTR)data->addr;
2734 context_bind_bo(context, binding, 0);
2735 checkGLcall("Map buffer object");
2737 return memory;
2740 void context_unmap_bo_address(struct wined3d_context *context,
2741 const struct wined3d_bo_address *data, GLenum binding)
2743 const struct wined3d_gl_info *gl_info;
2745 if (!data->buffer_object)
2746 return;
2748 gl_info = context->gl_info;
2749 context_bind_bo(context, binding, data->buffer_object);
2750 GL_EXTCALL(glUnmapBuffer(binding));
2751 context_bind_bo(context, binding, 0);
2752 checkGLcall("Unmap buffer object");
2755 void context_copy_bo_address(struct wined3d_context *context,
2756 const struct wined3d_bo_address *dst, GLenum dst_binding,
2757 const struct wined3d_bo_address *src, GLenum src_binding, size_t size)
2759 const struct wined3d_gl_info *gl_info;
2760 BYTE *dst_ptr, *src_ptr;
2762 gl_info = context->gl_info;
2764 if (dst->buffer_object && src->buffer_object)
2766 if (gl_info->supported[ARB_COPY_BUFFER])
2768 GL_EXTCALL(glBindBuffer(GL_COPY_READ_BUFFER, src->buffer_object));
2769 GL_EXTCALL(glBindBuffer(GL_COPY_WRITE_BUFFER, dst->buffer_object));
2770 GL_EXTCALL(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER,
2771 (GLintptr)src->addr, (GLintptr)dst->addr, size));
2772 checkGLcall("direct buffer copy");
2774 else
2776 src_ptr = context_map_bo_address(context, src, size, src_binding, WINED3D_MAP_READONLY);
2777 dst_ptr = context_map_bo_address(context, dst, size, dst_binding, 0);
2779 memcpy(dst_ptr, src_ptr, size);
2781 context_unmap_bo_address(context, dst, dst_binding);
2782 context_unmap_bo_address(context, src, src_binding);
2785 else if (!dst->buffer_object && src->buffer_object)
2787 context_bind_bo(context, src_binding, src->buffer_object);
2788 GL_EXTCALL(glGetBufferSubData(src_binding, (GLintptr)src->addr, size, dst->addr));
2789 checkGLcall("buffer download");
2791 else if (dst->buffer_object && !src->buffer_object)
2793 context_bind_bo(context, dst_binding, dst->buffer_object);
2794 GL_EXTCALL(glBufferSubData(dst_binding, (GLintptr)dst->addr, size, src->addr));
2795 checkGLcall("buffer upload");
2797 else
2799 memcpy(dst->addr, src->addr, size);
2803 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2805 if (context->render_offscreen == offscreen)
2806 return;
2808 context_invalidate_state(context, STATE_VIEWPORT);
2809 context_invalidate_state(context, STATE_SCISSORRECT);
2810 if (!context->gl_info->supported[ARB_CLIP_CONTROL])
2812 context_invalidate_state(context, STATE_FRONTFACE);
2813 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2814 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2816 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_DOMAIN));
2817 if (context->gl_info->supported[ARB_FRAGMENT_COORD_CONVENTIONS])
2818 context_invalidate_state(context, STATE_SHADER(WINED3D_SHADER_TYPE_PIXEL));
2819 context->render_offscreen = offscreen;
2822 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2823 const struct wined3d_format *required)
2825 if (existing == required)
2826 return TRUE;
2827 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2828 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2829 return FALSE;
2830 if (existing->depth_size < required->depth_size)
2831 return FALSE;
2832 /* If stencil bits are used the exact amount is required - otherwise
2833 * wrapping won't work correctly. */
2834 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2835 return FALSE;
2836 return TRUE;
2839 /* Context activation is done by the caller. */
2840 static void context_validate_onscreen_formats(struct wined3d_context *context,
2841 const struct wined3d_rendertarget_view *depth_stencil)
2843 /* Onscreen surfaces are always in a swapchain */
2844 struct wined3d_swapchain *swapchain = context->current_rt.texture->swapchain;
2846 if (context->render_offscreen || !depth_stencil) return;
2847 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2849 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2850 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2851 * format. */
2852 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2854 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2855 if (!(wined3d_texture_load_location(context->current_rt.texture, context->current_rt.sub_resource_idx,
2856 context, WINED3D_LOCATION_TEXTURE_RGB)))
2857 ERR("Failed to load location.\n");
2858 swapchain->render_to_fbo = TRUE;
2859 swapchain_update_draw_bindings(swapchain);
2860 context_set_render_offscreen(context, TRUE);
2863 GLenum context_get_offscreen_gl_buffer(const struct wined3d_context *context)
2865 switch (wined3d_settings.offscreen_rendering_mode)
2867 case ORM_FBO:
2868 return GL_COLOR_ATTACHMENT0;
2870 case ORM_BACKBUFFER:
2871 return context->aux_buffers > 0 ? GL_AUX0 : GL_BACK;
2873 default:
2874 FIXME("Unhandled offscreen rendering mode %#x.\n", wined3d_settings.offscreen_rendering_mode);
2875 return GL_BACK;
2879 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, struct wined3d_texture *rt)
2881 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2882 return 0;
2883 else if (rt->swapchain)
2884 return context_generate_rt_mask_from_resource(&rt->resource);
2885 else
2886 return context_generate_rt_mask(context_get_offscreen_gl_buffer(context));
2889 /* Context activation is done by the caller. */
2890 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2892 struct wined3d_texture *rt = context->current_rt.texture;
2893 struct wined3d_surface *surface;
2894 DWORD rt_mask, *cur_mask;
2896 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2898 context_validate_onscreen_formats(context, NULL);
2900 if (context->render_offscreen)
2902 wined3d_texture_load(rt, context, FALSE);
2904 surface = rt->sub_resources[context->current_rt.sub_resource_idx].u.surface;
2905 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, surface, NULL, rt->resource.draw_binding);
2906 if (rt->resource.format->id != WINED3DFMT_NULL)
2907 rt_mask = 1;
2908 else
2909 rt_mask = 0;
2911 else
2913 context->current_fbo = NULL;
2914 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2915 rt_mask = context_generate_rt_mask_from_resource(&rt->resource);
2918 else
2920 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2923 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2925 if (rt_mask != *cur_mask)
2927 context_apply_draw_buffers(context, rt_mask);
2928 *cur_mask = rt_mask;
2931 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2933 context_check_fbo_status(context, GL_FRAMEBUFFER);
2936 SetupForBlit(device, context);
2937 context_invalidate_state(context, STATE_FRAMEBUFFER);
2940 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2941 const struct wined3d_rendertarget_view *ds)
2943 unsigned int i;
2945 if (ds) return TRUE;
2947 for (i = 0; i < rt_count; ++i)
2949 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2950 return TRUE;
2953 WARN("Invalid render target config, need at least one attachment.\n");
2954 return FALSE;
2957 /* Context activation is done by the caller. */
2958 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_state *state,
2959 UINT rt_count, const struct wined3d_fb_state *fb)
2961 struct wined3d_rendertarget_view **rts = fb->render_targets;
2962 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2963 const struct wined3d_gl_info *gl_info = context->gl_info;
2964 DWORD rt_mask = 0, *cur_mask;
2965 unsigned int i;
2967 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != state->fb
2968 || rt_count != gl_info->limits.buffers)
2970 if (!context_validate_rt_config(rt_count, rts, dsv))
2971 return FALSE;
2973 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2975 context_validate_onscreen_formats(context, dsv);
2977 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2979 memset(context->blit_targets, 0, gl_info->limits.buffers * sizeof(*context->blit_targets));
2980 for (i = 0; i < rt_count; ++i)
2982 if (rts[i])
2984 context->blit_targets[i].gl_view = rts[i]->gl_view;
2985 context->blit_targets[i].resource = rts[i]->resource;
2986 context->blit_targets[i].sub_resource_idx = rts[i]->sub_resource_idx;
2987 context->blit_targets[i].layer_count = rts[i]->layer_count;
2989 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2990 rt_mask |= (1u << i);
2992 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2993 wined3d_rendertarget_view_get_surface(dsv),
2994 rt_count ? rts[0]->resource->draw_binding : 0,
2995 dsv ? dsv->resource->draw_binding : 0);
2997 else
2999 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
3000 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3001 rt_mask = context_generate_rt_mask_from_resource(rts[0]->resource);
3004 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
3005 * next draw. Otherwise we could mark the framebuffer state clean here, once the
3006 * state management allows this */
3007 context_invalidate_state(context, STATE_FRAMEBUFFER);
3009 else
3011 rt_mask = context_generate_rt_mask_no_fbo(context,
3012 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
3015 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
3016 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
3018 for (i = 0; i < rt_count; ++i)
3020 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
3021 rt_mask |= (1u << i);
3024 else
3026 rt_mask = context_generate_rt_mask_no_fbo(context,
3027 rt_count ? wined3d_rendertarget_view_get_surface(rts[0])->container : NULL);
3030 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3032 if (rt_mask != *cur_mask)
3034 context_apply_draw_buffers(context, rt_mask);
3035 *cur_mask = rt_mask;
3036 context_invalidate_state(context, STATE_FRAMEBUFFER);
3039 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3041 context_check_fbo_status(context, GL_FRAMEBUFFER);
3044 context->last_was_blit = FALSE;
3046 /* Blending and clearing should be orthogonal, but tests on the nvidia
3047 * driver show that disabling blending when clearing improves the clearing
3048 * performance incredibly. */
3049 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
3050 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
3051 if (rt_count && gl_info->supported[ARB_FRAMEBUFFER_SRGB])
3053 if (needs_srgb_write(context, state, fb))
3054 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
3055 else
3056 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
3057 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3059 checkGLcall("setting up state for clear");
3061 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3062 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
3063 context_invalidate_state(context, STATE_SCISSORRECT);
3065 return TRUE;
3068 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
3070 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
3071 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
3072 DWORD rt_mask, rt_mask_bits;
3073 unsigned int i;
3075 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
3076 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0])->container);
3077 else if (!context->render_offscreen)
3078 return context_generate_rt_mask_from_resource(rts[0]->resource);
3080 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
3081 rt_mask &= context->d3d_info->valid_rt_mask;
3082 rt_mask_bits = rt_mask;
3083 i = 0;
3084 while (rt_mask_bits)
3086 rt_mask_bits &= ~(1u << i);
3087 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
3088 rt_mask &= ~(1u << i);
3090 i++;
3093 return rt_mask;
3096 /* Context activation is done by the caller. */
3097 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3099 DWORD rt_mask = find_draw_buffers_mask(context, state);
3100 const struct wined3d_fb_state *fb = state->fb;
3101 DWORD *cur_mask;
3103 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3105 if (!context->render_offscreen)
3107 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
3108 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
3110 else
3112 unsigned int i;
3114 memset(context->blit_targets, 0, context->gl_info->limits.buffers * sizeof (*context->blit_targets));
3115 for (i = 0; i < context->gl_info->limits.buffers; ++i)
3117 if (fb->render_targets[i])
3119 context->blit_targets[i].gl_view = fb->render_targets[i]->gl_view;
3120 context->blit_targets[i].resource = fb->render_targets[i]->resource;
3121 context->blit_targets[i].sub_resource_idx = fb->render_targets[i]->sub_resource_idx;
3122 context->blit_targets[i].layer_count = fb->render_targets[i]->layer_count;
3125 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
3126 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
3127 fb->render_targets[0] ? fb->render_targets[0]->resource->draw_binding : 0,
3128 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
3132 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3133 if (rt_mask != *cur_mask)
3135 context_apply_draw_buffers(context, rt_mask);
3136 *cur_mask = rt_mask;
3138 context->constant_update_mask |= WINED3D_SHADER_CONST_PS_Y_CORR;
3141 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
3143 DWORD i = context->rev_tex_unit_map[unit];
3144 DWORD j = context->tex_unit_map[stage];
3146 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
3147 context->tex_unit_map[stage] = unit;
3148 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
3149 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
3151 context->rev_tex_unit_map[unit] = stage;
3152 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
3153 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
3156 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
3158 DWORD i;
3160 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
3161 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
3164 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
3165 const struct wined3d_state *state)
3167 UINT i, start, end;
3169 context->fixed_function_usage_map = 0;
3170 for (i = 0; i < MAX_TEXTURES; ++i)
3172 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
3173 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
3174 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
3175 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
3176 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
3177 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
3178 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
3179 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
3181 /* Not used, and disable higher stages. */
3182 if (color_op == WINED3D_TOP_DISABLE)
3183 break;
3185 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
3186 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
3187 || ((color_arg3 == WINED3DTA_TEXTURE)
3188 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
3189 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
3190 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
3191 || ((alpha_arg3 == WINED3DTA_TEXTURE)
3192 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
3193 context->fixed_function_usage_map |= (1u << i);
3195 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
3196 && i < MAX_TEXTURES - 1)
3197 context->fixed_function_usage_map |= (1u << (i + 1));
3200 if (i < context->lowest_disabled_stage)
3202 start = i;
3203 end = context->lowest_disabled_stage;
3205 else
3207 start = context->lowest_disabled_stage;
3208 end = i;
3211 context->lowest_disabled_stage = i;
3212 for (i = start + 1; i < end; ++i)
3214 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
3218 static void context_map_fixed_function_samplers(struct wined3d_context *context,
3219 const struct wined3d_state *state)
3221 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3222 unsigned int i, tex;
3223 WORD ffu_map;
3225 ffu_map = context->fixed_function_usage_map;
3227 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
3228 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
3230 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3232 if (!(ffu_map & 1))
3233 continue;
3235 if (context->tex_unit_map[i] != i)
3237 context_map_stage(context, i, i);
3238 context_invalidate_state(context, STATE_SAMPLER(i));
3239 context_invalidate_texture_stage(context, i);
3242 return;
3245 /* Now work out the mapping */
3246 tex = 0;
3247 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3249 if (!(ffu_map & 1))
3250 continue;
3252 if (context->tex_unit_map[i] != tex)
3254 context_map_stage(context, i, tex);
3255 context_invalidate_state(context, STATE_SAMPLER(i));
3256 context_invalidate_texture_stage(context, i);
3259 ++tex;
3263 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
3265 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3266 const struct wined3d_shader_resource_info *resource_info =
3267 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3268 unsigned int i;
3270 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3272 if (resource_info[i].type && context->tex_unit_map[i] != i)
3274 context_map_stage(context, i, i);
3275 context_invalidate_state(context, STATE_SAMPLER(i));
3276 if (i < d3d_info->limits.ffp_blend_stages)
3277 context_invalidate_texture_stage(context, i);
3282 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
3283 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
3285 DWORD current_mapping = context->rev_tex_unit_map[unit];
3287 /* Not currently used */
3288 if (current_mapping == WINED3D_UNMAPPED_STAGE)
3289 return TRUE;
3291 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
3293 /* Used by a fragment sampler */
3295 if (!ps_resource_info)
3297 /* No pixel shader, check fixed function */
3298 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
3301 /* Pixel shader, check the shader's sampler map */
3302 return !ps_resource_info[current_mapping].type;
3305 return TRUE;
3308 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
3310 const struct wined3d_shader_resource_info *vs_resource_info =
3311 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
3312 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
3313 const struct wined3d_gl_info *gl_info = context->gl_info;
3314 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.graphics_samplers) - 1;
3315 int i;
3317 /* Note that we only care if a resource is used or not, not the
3318 * resource's specific type. Otherwise we'd need to call
3319 * shader_update_samplers() here for 1.x pixelshaders. */
3320 if (ps)
3321 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
3323 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3325 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
3326 if (vs_resource_info[i].type)
3328 while (start >= 0)
3330 if (context_unit_free_for_vs(context, ps_resource_info, start))
3332 if (context->tex_unit_map[vsampler_idx] != start)
3334 context_map_stage(context, vsampler_idx, start);
3335 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
3338 --start;
3339 break;
3342 --start;
3344 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
3345 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
3350 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
3352 const struct wined3d_gl_info *gl_info = context->gl_info;
3353 BOOL vs = use_vs(state);
3354 BOOL ps = use_ps(state);
3356 if (!ps)
3357 context_update_fixed_function_usage_map(context, state);
3359 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
3360 * need a 1:1 map at the moment.
3361 * When the mapping of a stage is changed, sampler and ALL texture stage
3362 * states have to be reset. */
3364 if (gl_info->limits.graphics_samplers >= MAX_COMBINED_SAMPLERS)
3365 return;
3367 if (ps)
3368 context_map_psamplers(context, state);
3369 else
3370 context_map_fixed_function_samplers(context, state);
3372 if (vs)
3373 context_map_vsamplers(context, ps, state);
3376 /* Context activation is done by the caller. */
3377 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
3379 DWORD rt_mask, *cur_mask;
3381 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
3383 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
3384 rt_mask = find_draw_buffers_mask(context, state);
3385 if (rt_mask != *cur_mask)
3387 context_apply_draw_buffers(context, rt_mask);
3388 *cur_mask = rt_mask;
3392 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
3394 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
3395 *regnum = WINED3D_FFP_POSITION;
3396 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
3397 *regnum = WINED3D_FFP_BLENDWEIGHT;
3398 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
3399 *regnum = WINED3D_FFP_BLENDINDICES;
3400 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
3401 *regnum = WINED3D_FFP_NORMAL;
3402 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
3403 *regnum = WINED3D_FFP_PSIZE;
3404 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
3405 *regnum = WINED3D_FFP_DIFFUSE;
3406 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
3407 *regnum = WINED3D_FFP_SPECULAR;
3408 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
3409 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
3410 else
3412 WARN("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
3413 *regnum = ~0u;
3414 return FALSE;
3417 return TRUE;
3420 /* Context activation is done by the caller. */
3421 void wined3d_stream_info_from_declaration(struct wined3d_stream_info *stream_info,
3422 const struct wined3d_state *state, const struct wined3d_gl_info *gl_info,
3423 const struct wined3d_d3d_info *d3d_info)
3425 /* We need to deal with frequency data! */
3426 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
3427 BOOL generic_attributes = d3d_info->ffp_generic_attributes;
3428 BOOL use_vshader = use_vs(state);
3429 unsigned int i;
3431 stream_info->use_map = 0;
3432 stream_info->swizzle_map = 0;
3433 stream_info->position_transformed = 0;
3435 if (!declaration)
3436 return;
3438 stream_info->position_transformed = declaration->position_transformed;
3440 /* Translate the declaration into strided data. */
3441 for (i = 0; i < declaration->element_count; ++i)
3443 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
3444 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
3445 BOOL stride_used;
3446 unsigned int idx;
3448 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
3449 element, i + 1, declaration->element_count);
3451 if (!stream->buffer)
3452 continue;
3454 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
3456 if (use_vshader)
3458 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
3460 stride_used = FALSE;
3462 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
3464 /* TODO: Assuming vertexdeclarations are usually used with the
3465 * same or a similar shader, it might be worth it to store the
3466 * last used output slot and try that one first. */
3467 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
3468 element->usage, element->usage_idx, &idx);
3470 else
3472 idx = element->output_slot;
3473 stride_used = TRUE;
3476 else
3478 if (!generic_attributes && !element->ffp_valid)
3480 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
3481 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
3482 stride_used = FALSE;
3484 else
3486 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
3490 if (stride_used)
3492 TRACE("Load %s array %u [usage %s, usage_idx %u, "
3493 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
3494 use_vshader ? "shader": "fixed function", idx,
3495 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
3496 element->offset, stream->stride, debug_d3dformat(element->format->id),
3497 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
3499 stream_info->elements[idx].format = element->format;
3500 stream_info->elements[idx].data.buffer_object = 0;
3501 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
3502 stream_info->elements[idx].stride = stream->stride;
3503 stream_info->elements[idx].stream_idx = element->input_slot;
3504 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
3506 stream_info->elements[idx].divisor = 1;
3508 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
3510 stream_info->elements[idx].divisor = element->instance_data_step_rate;
3511 if (!element->instance_data_step_rate)
3512 FIXME("Instance step rate 0 not implemented.\n");
3514 else
3516 stream_info->elements[idx].divisor = 0;
3519 if (!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3520 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
3522 stream_info->swizzle_map |= 1u << idx;
3524 stream_info->use_map |= 1u << idx;
3529 /* Context activation is done by the caller. */
3530 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
3532 struct wined3d_stream_info *stream_info = &context->stream_info;
3533 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
3534 const struct wined3d_gl_info *gl_info = context->gl_info;
3535 DWORD prev_all_vbo = stream_info->all_vbo;
3536 unsigned int i;
3537 WORD map;
3539 wined3d_stream_info_from_declaration(stream_info, state, gl_info, d3d_info);
3541 stream_info->all_vbo = 1;
3542 context->buffer_fence_count = 0;
3543 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
3545 struct wined3d_stream_info_element *element;
3546 struct wined3d_bo_address data;
3547 struct wined3d_buffer *buffer;
3549 if (!(map & 1))
3550 continue;
3552 element = &stream_info->elements[i];
3553 buffer = state->streams[element->stream_idx].buffer;
3555 /* We can't use VBOs if the base vertex index is negative. OpenGL
3556 * doesn't accept negative offsets (or rather offsets bigger than the
3557 * VBO, because the pointer is unsigned), so use system memory
3558 * sources. In most sane cases the pointer - offset will still be > 0,
3559 * otherwise it will wrap around to some big value. Hope that with the
3560 * indices the driver wraps it back internally. If not,
3561 * draw_primitive_immediate_mode() is needed, including a vertex buffer
3562 * path. */
3563 if (state->load_base_vertex_index < 0)
3565 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
3566 state->load_base_vertex_index);
3567 element->data.buffer_object = 0;
3568 element->data.addr += (ULONG_PTR)wined3d_buffer_load_sysmem(buffer, context);
3569 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
3570 FIXME("System memory vertex data load offset is negative!\n");
3572 else
3574 wined3d_buffer_load(buffer, context, state);
3575 wined3d_buffer_get_memory(buffer, &data, buffer->locations);
3576 element->data.buffer_object = data.buffer_object;
3577 element->data.addr += (ULONG_PTR)data.addr;
3580 if (!element->data.buffer_object)
3581 stream_info->all_vbo = 0;
3583 if (buffer->fence)
3584 context->buffer_fences[context->buffer_fence_count++] = buffer->fence;
3586 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3589 if (prev_all_vbo != stream_info->all_vbo)
3590 context_invalidate_state(context, STATE_INDEXBUFFER);
3592 context->use_immediate_mode_draw = FALSE;
3594 if (stream_info->all_vbo)
3595 return;
3597 if (use_vs(state))
3599 if (state->vertex_declaration->half_float_conv_needed)
3601 TRACE("Using immediate mode draw with vertex shaders for FLOAT16 conversion.\n");
3602 context->use_immediate_mode_draw = TRUE;
3605 else
3607 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3608 slow_mask |= -(!gl_info->supported[ARB_VERTEX_ARRAY_BGRA] && !d3d_info->ffp_generic_attributes)
3609 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR) | (1u << WINED3D_FFP_BLENDWEIGHT));
3611 if ((stream_info->position_transformed && !d3d_info->xyzrhw)
3612 || (stream_info->use_map & slow_mask))
3613 context->use_immediate_mode_draw = TRUE;
3617 /* Context activation is done by the caller. */
3618 static void context_preload_texture(struct wined3d_context *context,
3619 const struct wined3d_state *state, unsigned int idx)
3621 struct wined3d_texture *texture;
3623 if (!(texture = state->textures[idx]))
3624 return;
3626 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3629 /* Context activation is done by the caller. */
3630 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3632 unsigned int i;
3634 if (use_vs(state))
3636 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3638 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3639 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3643 if (use_ps(state))
3645 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3647 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3648 context_preload_texture(context, state, i);
3651 else
3653 WORD ffu_map = context->fixed_function_usage_map;
3655 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3657 if (ffu_map & 1)
3658 context_preload_texture(context, state, i);
3663 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state,
3664 unsigned int shader_mask)
3666 struct wined3d_shader_sampler_map_entry *entry;
3667 struct wined3d_shader_resource_view *view;
3668 struct wined3d_shader *shader;
3669 unsigned int i, j;
3671 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3673 if (!(shader_mask & (1u << i)))
3674 continue;
3676 if (!(shader = state->shader[i]))
3677 continue;
3679 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3681 if (state->cb[i][j])
3682 wined3d_buffer_load(state->cb[i][j], context, state);
3685 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3687 entry = &shader->reg_maps.sampler_map.entries[j];
3689 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3690 continue;
3692 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3693 wined3d_buffer_load(buffer_from_resource(view->resource), context, state);
3694 else
3695 wined3d_texture_load(texture_from_resource(view->resource), context, FALSE);
3700 static void context_bind_shader_resources(struct wined3d_context *context,
3701 const struct wined3d_state *state, enum wined3d_shader_type shader_type)
3703 unsigned int bind_idx, shader_sampler_count, base, count, i;
3704 const struct wined3d_device *device = context->device;
3705 struct wined3d_shader_sampler_map_entry *entry;
3706 struct wined3d_shader_resource_view *view;
3707 const struct wined3d_shader *shader;
3708 struct wined3d_sampler *sampler;
3709 const DWORD *tex_unit_map;
3711 if (!(shader = state->shader[shader_type]))
3712 return;
3714 tex_unit_map = context_get_tex_unit_mapping(context,
3715 &shader->reg_maps.shader_version, &base, &count);
3717 shader_sampler_count = shader->reg_maps.sampler_map.count;
3718 if (shader_sampler_count > count)
3719 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3720 shader, shader_sampler_count, count);
3721 count = min(shader_sampler_count, count);
3723 for (i = 0; i < count; ++i)
3725 entry = &shader->reg_maps.sampler_map.entries[i];
3726 bind_idx = base + entry->bind_idx;
3727 if (tex_unit_map)
3728 bind_idx = tex_unit_map[bind_idx];
3730 if (!(view = state->shader_resource_view[shader_type][entry->resource_idx]))
3732 WARN("No resource view bound at index %u, %u.\n", shader_type, entry->resource_idx);
3733 continue;
3736 if (entry->sampler_idx == WINED3D_SAMPLER_DEFAULT)
3737 sampler = device->default_sampler;
3738 else if (!(sampler = state->sampler[shader_type][entry->sampler_idx]))
3739 sampler = device->null_sampler;
3740 wined3d_shader_resource_view_bind(view, bind_idx, sampler, context);
3744 static void context_load_unordered_access_resources(struct wined3d_context *context,
3745 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3747 struct wined3d_unordered_access_view *view;
3748 struct wined3d_texture *texture;
3749 struct wined3d_buffer *buffer;
3750 unsigned int i;
3752 context->uses_uavs = 0;
3754 if (!shader)
3755 return;
3757 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3759 if (!(view = views[i]))
3760 continue;
3762 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3764 buffer = buffer_from_resource(view->resource);
3765 wined3d_buffer_load_location(buffer, context, WINED3D_LOCATION_BUFFER);
3766 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_BUFFER);
3768 else
3770 texture = texture_from_resource(view->resource);
3771 wined3d_texture_load(texture, context, FALSE);
3772 wined3d_unordered_access_view_invalidate_location(view, ~WINED3D_LOCATION_TEXTURE_RGB);
3775 context->uses_uavs = 1;
3779 static void context_bind_unordered_access_views(struct wined3d_context *context,
3780 const struct wined3d_shader *shader, struct wined3d_unordered_access_view * const *views)
3782 const struct wined3d_gl_info *gl_info = context->gl_info;
3783 struct wined3d_unordered_access_view *view;
3784 GLuint texture_name;
3785 unsigned int i;
3786 GLint level;
3788 if (!shader)
3789 return;
3791 for (i = 0; i < MAX_UNORDERED_ACCESS_VIEWS; ++i)
3793 if (!(view = views[i]))
3795 if (shader->reg_maps.uav_resource_info[i].type)
3796 WARN("No unordered access view bound at index %u.\n", i);
3797 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3798 continue;
3801 if (view->gl_view.name)
3803 texture_name = view->gl_view.name;
3804 level = 0;
3806 else if (view->resource->type != WINED3D_RTYPE_BUFFER)
3808 struct wined3d_texture *texture = texture_from_resource(view->resource);
3809 texture_name = wined3d_texture_get_texture_name(texture, context, FALSE);
3810 level = view->desc.u.texture.level_idx;
3812 else
3814 FIXME("Unsupported buffer unordered access view.\n");
3815 GL_EXTCALL(glBindImageTexture(i, 0, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R8));
3816 continue;
3819 GL_EXTCALL(glBindImageTexture(i, texture_name, level, GL_TRUE, 0, GL_READ_WRITE,
3820 view->format->glInternal));
3822 if (view->counter_bo)
3823 GL_EXTCALL(glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, i, view->counter_bo));
3825 checkGLcall("Bind unordered access views");
3828 static void context_load_stream_output_buffers(struct wined3d_context *context,
3829 const struct wined3d_state *state)
3831 unsigned int i;
3833 for (i = 0; i < ARRAY_SIZE(state->stream_output); ++i)
3835 struct wined3d_buffer *buffer;
3836 if (!(buffer = state->stream_output[i].buffer))
3837 continue;
3839 wined3d_buffer_load(buffer, context, state);
3840 wined3d_buffer_invalidate_location(buffer, ~WINED3D_LOCATION_BUFFER);
3844 /* Context activation is done by the caller. */
3845 BOOL context_apply_draw_state(struct wined3d_context *context,
3846 const struct wined3d_device *device, const struct wined3d_state *state)
3848 const struct StateEntry *state_table = context->state_table;
3849 const struct wined3d_gl_info *gl_info = context->gl_info;
3850 const struct wined3d_fb_state *fb = state->fb;
3851 unsigned int i;
3852 WORD map;
3854 if (!context_validate_rt_config(gl_info->limits.buffers, fb->render_targets, fb->depth_stencil))
3855 return FALSE;
3857 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3859 context_validate_onscreen_formats(context, fb->depth_stencil);
3862 /* Preload resources before FBO setup. Texture preload in particular may
3863 * result in changes to the current FBO, due to using e.g. FBO blits for
3864 * updating a resource location. */
3865 context_update_tex_unit_map(context, state);
3866 context_preload_textures(context, state);
3867 context_load_shader_resources(context, state, ~(1u << WINED3D_SHADER_TYPE_COMPUTE));
3868 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_PIXEL],
3869 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3870 context_load_stream_output_buffers(context, state);
3871 /* TODO: Right now the dependency on the vertex shader is necessary
3872 * since wined3d_stream_info_from_declaration() depends on the reg_maps of
3873 * the current VS but maybe it's possible to relax the coupling in some
3874 * situations at least. */
3875 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3876 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3878 context_update_stream_info(context, state);
3880 else
3882 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3884 if (map & 1)
3885 wined3d_buffer_load(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3886 context, state);
3888 /* Loading the buffers above may have invalidated the stream info. */
3889 if (isStateDirty(context, STATE_STREAMSRC))
3890 context_update_stream_info(context, state);
3892 if (state->index_buffer)
3894 if (context->stream_info.all_vbo)
3895 wined3d_buffer_load(state->index_buffer, context, state);
3896 else
3897 wined3d_buffer_load_sysmem(state->index_buffer, context);
3900 for (i = 0; i < context->numDirtyEntries; ++i)
3902 DWORD rep = context->dirtyArray[i];
3903 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3904 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3905 context->isStateDirty[idx] &= ~(1u << shift);
3906 state_table[rep].apply(context, state, rep);
3909 if (context->shader_update_mask & ~(1u << WINED3D_SHADER_TYPE_COMPUTE))
3911 device->shader_backend->shader_select(device->shader_priv, context, state);
3912 context->shader_update_mask &= 1u << WINED3D_SHADER_TYPE_COMPUTE;
3915 if (context->constant_update_mask)
3917 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3918 context->constant_update_mask = 0;
3921 if (context->update_shader_resource_bindings)
3923 for (i = 0; i < WINED3D_SHADER_TYPE_GRAPHICS_COUNT; ++i)
3924 context_bind_shader_resources(context, state, i);
3925 context->update_shader_resource_bindings = 0;
3926 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3927 context->update_compute_shader_resource_bindings = 1;
3930 if (context->update_unordered_access_view_bindings)
3932 context_bind_unordered_access_views(context,
3933 state->shader[WINED3D_SHADER_TYPE_PIXEL],
3934 state->unordered_access_view[WINED3D_PIPELINE_GRAPHICS]);
3935 context->update_unordered_access_view_bindings = 0;
3936 context->update_compute_unordered_access_view_bindings = 1;
3939 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3941 context_check_fbo_status(context, GL_FRAMEBUFFER);
3944 context->numDirtyEntries = 0; /* This makes the whole list clean */
3945 context->last_was_blit = FALSE;
3947 return TRUE;
3950 void context_apply_compute_state(struct wined3d_context *context,
3951 const struct wined3d_device *device, const struct wined3d_state *state)
3953 const struct StateEntry *state_table = context->state_table;
3954 const struct wined3d_gl_info *gl_info = context->gl_info;
3955 unsigned int state_id, i, j;
3957 context_load_shader_resources(context, state, 1u << WINED3D_SHADER_TYPE_COMPUTE);
3958 context_load_unordered_access_resources(context, state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3959 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3961 for (i = 0, state_id = STATE_COMPUTE_OFFSET; i < ARRAY_SIZE(context->dirty_compute_states); ++i)
3963 for (j = 0; j < sizeof(*context->dirty_compute_states) * CHAR_BIT; ++j, ++state_id)
3965 if (context->dirty_compute_states[i] & (1u << j))
3966 state_table[state_id].apply(context, state, state_id);
3969 memset(context->dirty_compute_states, 0, sizeof(*context->dirty_compute_states));
3971 if (context->shader_update_mask & (1u << WINED3D_SHADER_TYPE_COMPUTE))
3973 device->shader_backend->shader_select_compute(device->shader_priv, context, state);
3974 context->shader_update_mask &= ~(1u << WINED3D_SHADER_TYPE_COMPUTE);
3977 if (context->update_compute_shader_resource_bindings)
3979 context_bind_shader_resources(context, state, WINED3D_SHADER_TYPE_COMPUTE);
3980 context->update_compute_shader_resource_bindings = 0;
3981 if (gl_info->limits.combined_samplers == gl_info->limits.graphics_samplers)
3982 context->update_shader_resource_bindings = 1;
3985 if (context->update_compute_unordered_access_view_bindings)
3987 context_bind_unordered_access_views(context,
3988 state->shader[WINED3D_SHADER_TYPE_COMPUTE],
3989 state->unordered_access_view[WINED3D_PIPELINE_COMPUTE]);
3990 context->update_compute_unordered_access_view_bindings = 0;
3991 context->update_unordered_access_view_bindings = 1;
3994 context->last_was_blit = FALSE;
3997 void context_end_transform_feedback(struct wined3d_context *context)
3999 const struct wined3d_gl_info *gl_info = context->gl_info;
4000 if (context->transform_feedback_active)
4002 GL_EXTCALL(glEndTransformFeedback());
4003 checkGLcall("glEndTransformFeedback");
4004 context->transform_feedback_active = 0;
4005 context->transform_feedback_paused = 0;
4009 static void context_setup_target(struct wined3d_context *context,
4010 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4012 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
4014 render_offscreen = wined3d_resource_is_offscreen(&texture->resource);
4015 if (context->current_rt.texture == texture
4016 && context->current_rt.sub_resource_idx == sub_resource_idx
4017 && render_offscreen == old_render_offscreen)
4018 return;
4020 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
4021 * the alpha blend state changes with different render target formats. */
4022 if (!context->current_rt.texture)
4024 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4026 else
4028 const struct wined3d_format *old = context->current_rt.texture->resource.format;
4029 const struct wined3d_format *new = texture->resource.format;
4031 if (old->id != new->id)
4033 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
4034 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
4035 || !(texture->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
4036 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
4038 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
4039 if ((context->current_rt.texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
4040 != (texture->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
4041 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
4044 /* When switching away from an offscreen render target, and we're not
4045 * using FBOs, we have to read the drawable into the texture. This is
4046 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
4047 * There are some things that need care though. PreLoad needs a GL context,
4048 * and FindContext is called before the context is activated. It also
4049 * has to be called with the old rendertarget active, otherwise a
4050 * wrong drawable is read. */
4051 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
4052 && old_render_offscreen && (context->current_rt.texture != texture
4053 || context->current_rt.sub_resource_idx != sub_resource_idx))
4055 unsigned int prev_sub_resource_idx = context->current_rt.sub_resource_idx;
4056 struct wined3d_texture *prev_texture = context->current_rt.texture;
4058 /* Read the back buffer of the old drawable into the destination texture. */
4059 if (prev_texture->texture_srgb.name)
4060 wined3d_texture_load(prev_texture, context, TRUE);
4061 wined3d_texture_load(prev_texture, context, FALSE);
4062 wined3d_texture_invalidate_location(prev_texture, prev_sub_resource_idx, WINED3D_LOCATION_DRAWABLE);
4066 context->current_rt.texture = texture;
4067 context->current_rt.sub_resource_idx = sub_resource_idx;
4068 context_set_render_offscreen(context, render_offscreen);
4071 struct wined3d_context *context_acquire(const struct wined3d_device *device,
4072 struct wined3d_texture *texture, unsigned int sub_resource_idx)
4074 struct wined3d_context *current_context = context_get_current();
4075 struct wined3d_context *context;
4076 BOOL swapchain_texture;
4078 TRACE("device %p, texture %p, sub_resource_idx %u.\n", device, texture, sub_resource_idx);
4080 wined3d_from_cs(device->cs);
4082 if (current_context && current_context->destroyed)
4083 current_context = NULL;
4085 swapchain_texture = texture && texture->swapchain;
4086 if (!texture)
4088 if (current_context
4089 && current_context->current_rt.texture
4090 && current_context->device == device)
4092 texture = current_context->current_rt.texture;
4093 sub_resource_idx = current_context->current_rt.sub_resource_idx;
4095 else
4097 struct wined3d_swapchain *swapchain = device->swapchains[0];
4099 if (swapchain->back_buffers)
4100 texture = swapchain->back_buffers[0];
4101 else
4102 texture = swapchain->front_buffer;
4103 sub_resource_idx = 0;
4107 if (current_context && current_context->current_rt.texture == texture)
4109 context = current_context;
4111 else if (swapchain_texture)
4113 TRACE("Rendering onscreen.\n");
4115 context = swapchain_get_context(texture->swapchain);
4117 else
4119 TRACE("Rendering offscreen.\n");
4121 /* Stay with the current context if possible. Otherwise use the
4122 * context for the primary swapchain. */
4123 if (current_context && current_context->device == device)
4124 context = current_context;
4125 else
4126 context = swapchain_get_context(device->swapchains[0]);
4129 context_enter(context);
4130 context_update_window(context);
4131 context_setup_target(context, texture, sub_resource_idx);
4132 if (!context->valid)
4133 return context;
4135 if (context != current_context)
4137 if (!context_set_current(context))
4138 ERR("Failed to activate the new context.\n");
4140 else if (context->needs_set)
4142 context_set_gl_context(context);
4145 return context;
4148 struct wined3d_context *context_reacquire(const struct wined3d_device *device,
4149 struct wined3d_context *context)
4151 struct wined3d_context *current_context;
4153 if (!context || context->tid != GetCurrentThreadId())
4154 return NULL;
4156 current_context = context_acquire(device, context->current_rt.texture,
4157 context->current_rt.sub_resource_idx);
4158 if (current_context != context)
4159 ERR("Acquired context %p instead of %p.\n", current_context, context);
4160 return current_context;