TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / dlls / wined3d / context.c
blob1e357e706612d1b6ad6f7feb783b498c5ca9f8a6
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007-2011, 2013 Stefan Dösinger for CodeWeavers
5 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <stdio.h>
26 #ifdef HAVE_FLOAT_H
27 # include <float.h>
28 #endif
30 #include "wined3d_private.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
33 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
34 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
36 #define WINED3D_MAX_FBO_ENTRIES 64
38 static DWORD wined3d_context_tls_idx;
40 /* FBO helper functions */
42 /* Context activation is done by the caller. */
43 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
45 const struct wined3d_gl_info *gl_info = context->gl_info;
47 switch (target)
49 case GL_READ_FRAMEBUFFER:
50 if (context->fbo_read_binding == fbo) return;
51 context->fbo_read_binding = fbo;
52 break;
54 case GL_DRAW_FRAMEBUFFER:
55 if (context->fbo_draw_binding == fbo) return;
56 context->fbo_draw_binding = fbo;
57 break;
59 case GL_FRAMEBUFFER:
60 if (context->fbo_read_binding == fbo
61 && context->fbo_draw_binding == fbo) return;
62 context->fbo_read_binding = fbo;
63 context->fbo_draw_binding = fbo;
64 break;
66 default:
67 FIXME("Unhandled target %#x.\n", target);
68 break;
71 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
72 checkGLcall("glBindFramebuffer()");
75 /* Context activation is done by the caller. */
76 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
78 unsigned int i;
80 for (i = 0; i < gl_info->limits.buffers; ++i)
82 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
83 checkGLcall("glFramebufferTexture2D()");
85 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
86 checkGLcall("glFramebufferTexture2D()");
88 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
89 checkGLcall("glFramebufferTexture2D()");
92 /* Context activation is done by the caller. */
93 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
95 const struct wined3d_gl_info *gl_info = context->gl_info;
97 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
98 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
99 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
101 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
102 checkGLcall("glDeleteFramebuffers()");
105 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
106 GLenum fbo_target, DWORD format_flags, GLuint rb)
108 if (format_flags & WINED3DFMT_FLAG_DEPTH)
110 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
111 checkGLcall("glFramebufferRenderbuffer()");
114 if (format_flags & WINED3DFMT_FLAG_STENCIL)
116 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
117 checkGLcall("glFramebufferRenderbuffer()");
121 /* Context activation is done by the caller. */
122 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
123 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
125 const struct wined3d_gl_info *gl_info = context->gl_info;
127 TRACE("Attach depth stencil %p\n", depth_stencil);
129 if (depth_stencil)
131 DWORD format_flags = depth_stencil->container->resource.format_flags;
133 if (depth_stencil->current_renderbuffer)
135 context_attach_depth_stencil_rb(gl_info, fbo_target,
136 format_flags, depth_stencil->current_renderbuffer->id);
138 else
140 switch (location)
142 case WINED3D_LOCATION_TEXTURE_RGB:
143 case WINED3D_LOCATION_TEXTURE_SRGB:
144 if (format_flags & WINED3DFMT_FLAG_DEPTH)
146 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
147 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
148 depth_stencil->texture_level);
149 checkGLcall("glFramebufferTexture2D()");
152 if (format_flags & WINED3DFMT_FLAG_STENCIL)
154 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
155 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
156 depth_stencil->texture_level);
157 checkGLcall("glFramebufferTexture2D()");
159 break;
161 case WINED3D_LOCATION_RB_MULTISAMPLE:
162 context_attach_depth_stencil_rb(gl_info, fbo_target,
163 format_flags, depth_stencil->rb_multisample);
164 break;
166 case WINED3D_LOCATION_RB_RESOLVED:
167 context_attach_depth_stencil_rb(gl_info, fbo_target,
168 format_flags, depth_stencil->rb_resolved);
169 break;
171 default:
172 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
173 break;
177 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
179 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
180 checkGLcall("glFramebufferTexture2D()");
183 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
185 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
186 checkGLcall("glFramebufferTexture2D()");
189 else
191 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
192 checkGLcall("glFramebufferTexture2D()");
194 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
195 checkGLcall("glFramebufferTexture2D()");
199 /* Context activation is done by the caller. */
200 static void context_attach_surface_fbo(struct wined3d_context *context,
201 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
203 const struct wined3d_gl_info *gl_info = context->gl_info;
205 TRACE("Attach surface %p to %u\n", surface, idx);
207 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
209 BOOL srgb;
211 switch (location)
213 case WINED3D_LOCATION_TEXTURE_RGB:
214 case WINED3D_LOCATION_TEXTURE_SRGB:
215 srgb = location == WINED3D_LOCATION_TEXTURE_SRGB;
216 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
217 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
218 surface->texture_level);
219 checkGLcall("glFramebufferTexture2D()");
220 break;
222 case WINED3D_LOCATION_RB_MULTISAMPLE:
223 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
224 GL_RENDERBUFFER, surface->rb_multisample);
225 checkGLcall("glFramebufferRenderbuffer()");
226 break;
228 case WINED3D_LOCATION_RB_RESOLVED:
229 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
230 GL_RENDERBUFFER, surface->rb_resolved);
231 checkGLcall("glFramebufferRenderbuffer()");
232 break;
234 default:
235 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
236 break;
239 else
241 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
242 checkGLcall("glFramebufferTexture2D()");
246 /* Context activation is done by the caller. */
247 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
249 const struct wined3d_gl_info *gl_info = context->gl_info;
250 GLenum status;
252 if (!FIXME_ON(d3d)) return;
254 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
255 if (status == GL_FRAMEBUFFER_COMPLETE)
257 TRACE("FBO complete\n");
259 else
261 const struct wined3d_surface *attachment;
262 unsigned int i;
264 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
266 if (!context->current_fbo)
268 ERR("FBO 0 is incomplete, driver bug?\n");
269 return;
272 FIXME("\tColor Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->color_location),
273 context->current_fbo->color_location);
274 FIXME("\tDepth Stencil Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->ds_location),
275 context->current_fbo->ds_location);
277 /* Dump the FBO attachments */
278 for (i = 0; i < gl_info->limits.buffers; ++i)
280 attachment = context->current_fbo->render_targets[i];
281 if (attachment)
283 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
284 i, attachment, debug_d3dformat(attachment->resource.format->id),
285 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
288 attachment = context->current_fbo->depth_stencil;
289 if (attachment)
291 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
292 attachment, debug_d3dformat(attachment->resource.format->id),
293 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
298 static inline DWORD context_generate_rt_mask(GLenum buffer)
300 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
301 return buffer ? (1u << 31) | buffer : 0;
304 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
306 return (1u << 31) | surface_get_gl_buffer(target);
309 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
310 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
311 DWORD color_location, DWORD ds_location)
313 const struct wined3d_gl_info *gl_info = context->gl_info;
314 struct fbo_entry *entry;
316 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
317 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
318 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
319 entry->depth_stencil = depth_stencil;
320 entry->color_location = color_location;
321 entry->ds_location = ds_location;
322 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
323 entry->attached = FALSE;
324 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
325 checkGLcall("glGenFramebuffers()");
326 TRACE("Created FBO %u.\n", entry->id);
328 return entry;
331 /* Context activation is done by the caller. */
332 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
333 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
334 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
336 const struct wined3d_gl_info *gl_info = context->gl_info;
338 context_bind_fbo(context, target, entry->id);
339 context_clean_fbo_attachments(gl_info, target);
341 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
342 entry->depth_stencil = depth_stencil;
343 entry->color_location = color_location;
344 entry->ds_location = ds_location;
345 entry->attached = FALSE;
348 /* Context activation is done by the caller. */
349 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
351 if (entry->id)
353 TRACE("Destroy FBO %u.\n", entry->id);
354 context_destroy_fbo(context, entry->id);
356 --context->fbo_entry_count;
357 list_remove(&entry->entry);
358 HeapFree(GetProcessHeap(), 0, entry->render_targets);
359 HeapFree(GetProcessHeap(), 0, entry);
362 /* Context activation is done by the caller. */
363 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
364 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
365 DWORD color_location, DWORD ds_location)
367 const struct wined3d_gl_info *gl_info = context->gl_info;
368 struct fbo_entry *entry;
370 if (depth_stencil && render_targets && render_targets[0])
372 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
373 depth_stencil->resource.height < render_targets[0]->resource.height)
375 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
376 depth_stencil = NULL;
380 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
382 if (!memcmp(entry->render_targets,
383 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
384 && entry->depth_stencil == depth_stencil && entry->color_location == color_location
385 && entry->ds_location == ds_location)
387 list_remove(&entry->entry);
388 list_add_head(&context->fbo_list, &entry->entry);
389 return entry;
393 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
395 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
396 list_add_head(&context->fbo_list, &entry->entry);
397 ++context->fbo_entry_count;
399 else
401 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
402 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
403 list_remove(&entry->entry);
404 list_add_head(&context->fbo_list, &entry->entry);
407 return entry;
410 /* Context activation is done by the caller. */
411 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
413 const struct wined3d_gl_info *gl_info = context->gl_info;
414 unsigned int i;
415 GLuint read_binding, draw_binding;
416 struct wined3d_surface *depth_stencil = entry->depth_stencil;
418 if (entry->attached)
420 context_bind_fbo(context, target, entry->id);
421 return;
424 read_binding = context->fbo_read_binding;
425 draw_binding = context->fbo_draw_binding;
426 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
428 /* Apply render targets */
429 for (i = 0; i < gl_info->limits.buffers; ++i)
431 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->color_location);
434 if (depth_stencil && entry->render_targets[0]
435 && (depth_stencil->resource.multisample_type
436 != entry->render_targets[0]->resource.multisample_type
437 || depth_stencil->resource.multisample_quality
438 != entry->render_targets[0]->resource.multisample_quality))
440 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
441 entry->render_targets[0]->resource.multisample_quality,
442 entry->render_targets[0]->resource.multisample_type,
443 depth_stencil->resource.multisample_quality, depth_stencil->resource.multisample_type);
444 depth_stencil = NULL;
447 if (depth_stencil)
448 surface_set_compatible_renderbuffer(depth_stencil, entry->render_targets[0]);
449 context_attach_depth_stencil_fbo(context, target, depth_stencil, entry->ds_location);
451 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
452 * GL contexts requirements. */
453 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
454 context_set_draw_buffer(context, GL_NONE);
455 if (target != GL_FRAMEBUFFER)
457 if (target == GL_READ_FRAMEBUFFER)
458 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
459 else
460 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
463 entry->attached = TRUE;
466 /* Context activation is done by the caller. */
467 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
468 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
469 DWORD color_location, DWORD ds_location)
471 struct fbo_entry *entry, *entry2;
473 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
475 context_destroy_fbo_entry(context, entry);
478 if (context->rebind_fbo)
480 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
481 context->rebind_fbo = FALSE;
484 if (color_location == WINED3D_LOCATION_DRAWABLE)
486 context->current_fbo = NULL;
487 context_bind_fbo(context, target, 0);
489 else
491 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
492 color_location, ds_location);
493 context_apply_fbo_entry(context, target, context->current_fbo);
497 /* Context activation is done by the caller. */
498 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
499 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
501 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
503 context->blit_targets[0] = render_target;
504 if (clear_size)
505 memset(&context->blit_targets[1], 0, clear_size);
506 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
509 /* Context activation is done by the caller. */
510 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
512 const struct wined3d_gl_info *gl_info = context->gl_info;
514 if (context->free_occlusion_query_count)
516 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
518 else
520 if (gl_info->supported[ARB_OCCLUSION_QUERY])
522 GL_EXTCALL(glGenQueries(1, &query->id));
523 checkGLcall("glGenQueries");
525 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
527 else
529 WARN("Occlusion queries not supported, not allocating query id.\n");
530 query->id = 0;
534 query->context = context;
535 list_add_head(&context->occlusion_queries, &query->entry);
538 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
540 struct wined3d_context *context = query->context;
542 list_remove(&query->entry);
543 query->context = NULL;
545 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
547 UINT new_size = context->free_occlusion_query_size << 1;
548 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
549 new_size * sizeof(*context->free_occlusion_queries));
551 if (!new_data)
553 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
554 return;
557 context->free_occlusion_query_size = new_size;
558 context->free_occlusion_queries = new_data;
561 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
564 /* Context activation is done by the caller. */
565 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
567 const struct wined3d_gl_info *gl_info = context->gl_info;
569 if (context->free_event_query_count)
571 query->object = context->free_event_queries[--context->free_event_query_count];
573 else
575 if (gl_info->supported[ARB_SYNC])
577 /* Using ARB_sync, not much to do here. */
578 query->object.sync = NULL;
579 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
581 else if (gl_info->supported[APPLE_FENCE])
583 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
584 checkGLcall("glGenFencesAPPLE");
586 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
588 else if(gl_info->supported[NV_FENCE])
590 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
591 checkGLcall("glGenFencesNV");
593 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
595 else
597 WARN("Event queries not supported, not allocating query id.\n");
598 query->object.id = 0;
602 query->context = context;
603 list_add_head(&context->event_queries, &query->entry);
606 void context_free_event_query(struct wined3d_event_query *query)
608 struct wined3d_context *context = query->context;
610 list_remove(&query->entry);
611 query->context = NULL;
613 if (context->free_event_query_count >= context->free_event_query_size - 1)
615 UINT new_size = context->free_event_query_size << 1;
616 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
617 new_size * sizeof(*context->free_event_queries));
619 if (!new_data)
621 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
622 return;
625 context->free_event_query_size = new_size;
626 context->free_event_queries = new_data;
629 context->free_event_queries[context->free_event_query_count++] = query->object;
632 /* Context activation is done by the caller. */
633 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
635 const struct wined3d_gl_info *gl_info = context->gl_info;
637 if (context->free_timestamp_query_count)
639 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
641 else
643 GL_EXTCALL(glGenQueries(1, &query->id));
644 checkGLcall("glGenQueries");
646 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
649 query->context = context;
650 list_add_head(&context->timestamp_queries, &query->entry);
653 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
655 struct wined3d_context *context = query->context;
657 list_remove(&query->entry);
658 query->context = NULL;
660 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
662 UINT new_size = context->free_timestamp_query_size << 1;
663 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
664 new_size * sizeof(*context->free_timestamp_queries));
666 if (!new_data)
668 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
669 return;
672 context->free_timestamp_query_size = new_size;
673 context->free_timestamp_queries = new_data;
676 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
679 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
681 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
682 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
684 UINT i;
686 for (i = 0; i < device->context_count; ++i)
688 struct wined3d_context *context = device->contexts[i];
689 const struct wined3d_gl_info *gl_info = context->gl_info;
690 struct fbo_entry *entry, *entry2;
692 if (context->current_rt == surface) context->current_rt = NULL;
694 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
696 UINT j;
698 if (entry->depth_stencil == surface)
700 callback(context, entry);
701 continue;
704 for (j = 0; j < gl_info->limits.buffers; ++j)
706 if (entry->render_targets[j] == surface)
708 callback(context, entry);
709 break;
716 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
718 list_remove(&entry->entry);
719 list_add_head(&context->fbo_destroy_list, &entry->entry);
722 void context_resource_released(const struct wined3d_device *device,
723 struct wined3d_resource *resource, enum wined3d_resource_type type)
725 if (!device->d3d_initialized) return;
727 switch (type)
729 case WINED3D_RTYPE_SURFACE:
730 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
731 context_queue_fbo_entry_destruction);
732 break;
734 default:
735 break;
739 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
741 entry->attached = FALSE;
744 void context_resource_unloaded(const struct wined3d_device *device,
745 struct wined3d_resource *resource, enum wined3d_resource_type type)
747 switch (type)
749 case WINED3D_RTYPE_SURFACE:
750 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
751 context_detach_fbo_entry);
752 break;
754 default:
755 break;
759 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
761 const struct wined3d_gl_info *gl_info = context->gl_info;
762 struct fbo_entry *entry = context->current_fbo;
763 unsigned int i;
765 if (!entry || context->rebind_fbo) return;
767 for (i = 0; i < gl_info->limits.buffers; ++i)
769 if (surface == entry->render_targets[i])
771 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
772 context->rebind_fbo = TRUE;
773 return;
777 if (surface == entry->depth_stencil)
779 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
780 context->rebind_fbo = TRUE;
784 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
786 const struct wined3d_gl_info *gl_info = ctx->gl_info;
787 BOOL ret = FALSE;
789 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
791 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
793 HDC dc = GetDC(ctx->restore_pf_win);
794 if (dc)
796 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
798 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
799 ctx->restore_pf, ctx->restore_pf_win);
801 ReleaseDC(ctx->restore_pf_win, dc);
804 else
806 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
810 ctx->restore_pf = 0;
811 ctx->restore_pf_win = NULL;
812 return ret;
815 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
817 const struct wined3d_gl_info *gl_info = context->gl_info;
818 int current;
820 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
821 return TRUE;
823 current = gl_info->gl_ops.wgl.p_wglGetPixelFormat(dc);
824 if (current == format) goto success;
826 if (!current)
828 if (!SetPixelFormat(dc, format, NULL))
830 /* This may also happen if the dc belongs to a destroyed window. */
831 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
832 format, dc, GetLastError());
833 return FALSE;
836 context->restore_pf = 0;
837 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
838 goto success;
841 /* By default WGL doesn't allow pixel format adjustments but we need it
842 * here. For this reason there's a Wine specific wglSetPixelFormat()
843 * which allows us to set the pixel format multiple times. Only use it
844 * when really needed. */
845 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
847 HWND win;
849 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
851 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
852 format, dc);
853 return FALSE;
856 win = private ? NULL : WindowFromDC(dc);
857 if (win != context->restore_pf_win)
859 context_restore_pixel_format(context);
861 context->restore_pf = private ? 0 : current;
862 context->restore_pf_win = win;
865 goto success;
868 /* OpenGL doesn't allow pixel format adjustments. Print an error and
869 * continue using the old format. There's a big chance that the old
870 * format works although with a performance hit and perhaps rendering
871 * errors. */
872 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
873 format, dc, current);
874 return TRUE;
876 success:
877 if (dc == context->hdc && context->hdc_is_private)
878 context->hdc_has_format = TRUE;
879 return TRUE;
882 static BOOL context_set_gl_context(struct wined3d_context *ctx)
884 struct wined3d_swapchain *swapchain = ctx->swapchain;
885 BOOL backup = FALSE;
887 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
889 WARN("Failed to set pixel format %d on device context %p.\n",
890 ctx->pixel_format, ctx->hdc);
891 backup = TRUE;
894 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
896 HDC dc;
898 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
899 ctx->glCtx, ctx->hdc, GetLastError());
900 ctx->valid = 0;
901 WARN("Trying fallback to the backup window.\n");
903 /* FIXME: If the context is destroyed it's no longer associated with
904 * a swapchain, so we can't use the swapchain to get a backup dc. To
905 * make this work windowless contexts would need to be handled by the
906 * device. */
907 if (ctx->destroyed)
909 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
910 context_set_current(NULL);
911 return FALSE;
914 if (!(dc = swapchain_get_backup_dc(swapchain)))
916 context_set_current(NULL);
917 return FALSE;
920 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
922 ERR("Failed to set pixel format %d on device context %p.\n",
923 ctx->pixel_format, dc);
924 context_set_current(NULL);
925 return FALSE;
928 if (!wglMakeCurrent(dc, ctx->glCtx))
930 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
931 dc, GetLastError());
932 context_set_current(NULL);
933 return FALSE;
936 ctx->valid = 1;
938 ctx->needs_set = 0;
939 return TRUE;
942 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
944 if (!wglMakeCurrent(dc, gl_ctx))
946 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
947 gl_ctx, dc, GetLastError());
948 context_set_current(NULL);
952 static void context_update_window(struct wined3d_context *context)
954 if (context->win_handle == context->swapchain->win_handle)
955 return;
957 TRACE("Updating context %p window from %p to %p.\n",
958 context, context->win_handle, context->swapchain->win_handle);
960 if (context->hdc)
961 wined3d_release_dc(context->win_handle, context->hdc);
963 context->win_handle = context->swapchain->win_handle;
964 context->hdc_is_private = FALSE;
965 context->hdc_has_format = FALSE;
966 context->needs_set = 1;
967 context->valid = 1;
969 if (!(context->hdc = GetDC(context->win_handle)))
971 ERR("Failed to get a device context for window %p.\n", context->win_handle);
972 context->valid = 0;
976 static void context_destroy_gl_resources(struct wined3d_context *context)
978 const struct wined3d_gl_info *gl_info = context->gl_info;
979 struct wined3d_timestamp_query *timestamp_query;
980 struct wined3d_occlusion_query *occlusion_query;
981 struct wined3d_event_query *event_query;
982 struct fbo_entry *entry, *entry2;
983 HGLRC restore_ctx;
984 HDC restore_dc;
985 unsigned int i;
987 restore_ctx = wglGetCurrentContext();
988 restore_dc = wglGetCurrentDC();
990 if (restore_ctx == context->glCtx)
991 restore_ctx = NULL;
992 else if (context->valid)
993 context_set_gl_context(context);
995 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
997 if (context->valid)
998 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
999 timestamp_query->context = NULL;
1002 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1004 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1005 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1006 occlusion_query->context = NULL;
1009 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1011 if (context->valid)
1013 if (gl_info->supported[ARB_SYNC])
1015 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1017 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1018 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1020 event_query->context = NULL;
1023 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1025 if (!context->valid) entry->id = 0;
1026 context_destroy_fbo_entry(context, entry);
1029 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1031 if (!context->valid) entry->id = 0;
1032 context_destroy_fbo_entry(context, entry);
1035 if (context->valid)
1037 if (context->dummy_arbfp_prog)
1039 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1042 if (gl_info->supported[ARB_TIMER_QUERY])
1043 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1045 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1046 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1048 if (gl_info->supported[ARB_SYNC])
1050 for (i = 0; i < context->free_event_query_count; ++i)
1052 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1055 else if (gl_info->supported[APPLE_FENCE])
1057 for (i = 0; i < context->free_event_query_count; ++i)
1059 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1062 else if (gl_info->supported[NV_FENCE])
1064 for (i = 0; i < context->free_event_query_count; ++i)
1066 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1070 checkGLcall("context cleanup");
1073 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1074 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1075 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1077 context_restore_pixel_format(context);
1078 if (restore_ctx)
1080 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1082 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1084 ERR("Failed to disable GL context.\n");
1087 wined3d_release_dc(context->win_handle, context->hdc);
1089 if (!wglDeleteContext(context->glCtx))
1091 DWORD err = GetLastError();
1092 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1096 DWORD context_get_tls_idx(void)
1098 return wined3d_context_tls_idx;
1101 void context_set_tls_idx(DWORD idx)
1103 wined3d_context_tls_idx = idx;
1106 struct wined3d_context *context_get_current(void)
1108 return TlsGetValue(wined3d_context_tls_idx);
1111 BOOL context_set_current(struct wined3d_context *ctx)
1113 struct wined3d_context *old = context_get_current();
1115 if (old == ctx)
1117 TRACE("Already using D3D context %p.\n", ctx);
1118 return TRUE;
1121 if (old)
1123 if (old->destroyed)
1125 TRACE("Switching away from destroyed context %p.\n", old);
1126 context_destroy_gl_resources(old);
1127 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1128 HeapFree(GetProcessHeap(), 0, old);
1130 else
1132 if (wglGetCurrentContext())
1134 TRACE("Flushing context %p before switching to %p.\n", old, ctx);
1135 glFlush();
1137 old->current = 0;
1141 if (ctx)
1143 if (!ctx->valid)
1145 ERR("Trying to make invalid context %p current\n", ctx);
1146 return FALSE;
1149 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1150 if (!context_set_gl_context(ctx))
1151 return FALSE;
1152 ctx->current = 1;
1154 else if(wglGetCurrentContext())
1156 TRACE("Clearing current D3D context.\n");
1157 if (!wglMakeCurrent(NULL, NULL))
1159 DWORD err = GetLastError();
1160 ERR("Failed to clear current GL context, last error %#x.\n", err);
1161 TlsSetValue(wined3d_context_tls_idx, NULL);
1162 return FALSE;
1166 return TlsSetValue(wined3d_context_tls_idx, ctx);
1169 void context_release(struct wined3d_context *context)
1171 TRACE("Releasing context %p, level %u.\n", context, context->level);
1173 if (WARN_ON(d3d))
1175 if (!context->level)
1176 WARN("Context %p is not active.\n", context);
1177 else if (context != context_get_current())
1178 WARN("Context %p is not the current context.\n", context);
1181 if (!--context->level)
1183 if (context_restore_pixel_format(context))
1184 context->needs_set = 1;
1185 if (context->restore_ctx)
1187 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1188 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1189 context->restore_ctx = NULL;
1190 context->restore_dc = NULL;
1195 /* This is used when a context for render target A is active, but a separate context is
1196 * needed to access the WGL framebuffer for render target B. Re-acquire a context for rt
1197 * A to avoid breaking caller code. */
1198 void context_restore(struct wined3d_context *context, struct wined3d_surface *restore)
1200 if (context->current_rt != restore)
1202 context_release(context);
1203 context = context_acquire(restore->resource.device, restore);
1206 context_release(context);
1209 static void context_enter(struct wined3d_context *context)
1211 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1213 if (!context->level++)
1215 const struct wined3d_context *current_context = context_get_current();
1216 HGLRC current_gl = wglGetCurrentContext();
1218 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1220 TRACE("Another GL context (%p on device context %p) is already current.\n",
1221 current_gl, wglGetCurrentDC());
1222 context->restore_ctx = current_gl;
1223 context->restore_dc = wglGetCurrentDC();
1224 context->needs_set = 1;
1226 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1227 && context->pixel_format != context->gl_info->gl_ops.wgl.p_wglGetPixelFormat(context->hdc))
1228 context->needs_set = 1;
1232 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1234 DWORD rep = context->state_table[state].representative;
1235 DWORD idx;
1236 BYTE shift;
1238 if (isStateDirty(context, rep)) return;
1240 context->dirtyArray[context->numDirtyEntries++] = rep;
1241 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1242 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1243 context->isStateDirty[idx] |= (1u << shift);
1246 /* This function takes care of wined3d pixel format selection. */
1247 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1248 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1249 BOOL auxBuffers, BOOL findCompatible)
1251 int iPixelFormat=0;
1252 unsigned int current_value;
1253 unsigned int cfg_count = device->adapter->cfg_count;
1254 unsigned int i;
1256 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1257 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1258 auxBuffers, findCompatible);
1260 current_value = 0;
1261 for (i = 0; i < cfg_count; ++i)
1263 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1264 unsigned int value;
1266 /* For now only accept RGBA formats. Perhaps some day we will
1267 * allow floating point formats for pbuffers. */
1268 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1269 continue;
1270 /* In window mode we need a window drawable format and double buffering. */
1271 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1272 continue;
1273 if (cfg->redSize < color_format->red_size)
1274 continue;
1275 if (cfg->greenSize < color_format->green_size)
1276 continue;
1277 if (cfg->blueSize < color_format->blue_size)
1278 continue;
1279 if (cfg->alphaSize < color_format->alpha_size)
1280 continue;
1281 if (cfg->depthSize < ds_format->depth_size)
1282 continue;
1283 if (ds_format->stencil_size && cfg->stencilSize != ds_format->stencil_size)
1284 continue;
1285 /* Check multisampling support. */
1286 if (cfg->numSamples)
1287 continue;
1289 value = 1;
1290 /* We try to locate a format which matches our requirements exactly. In case of
1291 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1292 if (cfg->depthSize == ds_format->depth_size)
1293 value += 1;
1294 if (cfg->stencilSize == ds_format->stencil_size)
1295 value += 2;
1296 if (cfg->alphaSize == color_format->alpha_size)
1297 value += 4;
1298 /* We like to have aux buffers in backbuffer mode */
1299 if (auxBuffers && cfg->auxBuffers)
1300 value += 8;
1301 if (cfg->redSize == color_format->red_size
1302 && cfg->greenSize == color_format->green_size
1303 && cfg->blueSize == color_format->blue_size)
1304 value += 16;
1306 if (value > current_value)
1308 iPixelFormat = cfg->iPixelFormat;
1309 current_value = value;
1313 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1314 if(!iPixelFormat && !findCompatible) {
1315 ERR("Can't find a suitable iPixelFormat\n");
1316 return FALSE;
1317 } else if(!iPixelFormat) {
1318 PIXELFORMATDESCRIPTOR pfd;
1320 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1321 /* PixelFormat selection */
1322 ZeroMemory(&pfd, sizeof(pfd));
1323 pfd.nSize = sizeof(pfd);
1324 pfd.nVersion = 1;
1325 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1326 pfd.iPixelType = PFD_TYPE_RGBA;
1327 pfd.cAlphaBits = color_format->alpha_size;
1328 pfd.cColorBits = color_format->red_size + color_format->green_size
1329 + color_format->blue_size + color_format->alpha_size;
1330 pfd.cDepthBits = ds_format->depth_size;
1331 pfd.cStencilBits = ds_format->stencil_size;
1332 pfd.iLayerType = PFD_MAIN_PLANE;
1334 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1335 if(!iPixelFormat) {
1336 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1337 ERR("Can't find a suitable iPixelFormat\n");
1338 return FALSE;
1342 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1343 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1344 return iPixelFormat;
1347 /* Context activation is done by the caller. */
1348 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1350 const struct wined3d_gl_info *gl_info = context->gl_info;
1351 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1353 for (i = 0; i < count; ++i)
1355 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1356 checkGLcall("glActiveTexture");
1358 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1359 checkGLcall("glBindTexture");
1361 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1363 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1364 checkGLcall("glBindTexture");
1367 if (gl_info->supported[EXT_TEXTURE3D])
1369 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1370 checkGLcall("glBindTexture");
1373 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1375 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1376 checkGLcall("glBindTexture");
1381 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1383 return gl_info->supported[ARB_DEBUG_OUTPUT]
1384 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1387 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1388 GLenum severity, GLsizei length, const char *message, void *ctx)
1390 switch (type)
1392 case GL_DEBUG_TYPE_ERROR_ARB:
1393 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1394 break;
1396 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1397 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1398 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1399 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1400 break;
1402 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1403 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1404 break;
1406 default:
1407 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1408 break;
1412 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1414 HGLRC ctx;
1415 unsigned int ctx_attrib_idx = 0;
1416 GLint ctx_attribs[7], ctx_flags = 0;
1418 if (context_debug_output_enabled(gl_info))
1419 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1420 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1421 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1422 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1423 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1424 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1425 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1426 if (ctx_flags)
1428 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1429 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1431 ctx_attribs[ctx_attrib_idx] = 0;
1433 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1435 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1437 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1438 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1439 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1440 GetLastError());
1443 return ctx;
1446 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1447 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1449 struct wined3d_device *device = swapchain->device;
1450 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1451 const struct wined3d_format *color_format;
1452 struct wined3d_context *ret;
1453 BOOL auxBuffers = FALSE;
1454 HGLRC ctx, share_ctx;
1455 int pixel_format;
1456 unsigned int s;
1457 int swap_interval;
1458 DWORD state;
1459 HDC hdc;
1460 BOOL hdc_is_private = FALSE;
1462 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1464 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1465 if (!ret)
1466 return NULL;
1468 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1469 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1470 if (!ret->blit_targets)
1471 goto out;
1473 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1474 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1475 if (!ret->draw_buffers)
1476 goto out;
1478 ret->free_timestamp_query_size = 4;
1479 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1480 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1481 if (!ret->free_timestamp_queries)
1482 goto out;
1483 list_init(&ret->timestamp_queries);
1485 ret->free_occlusion_query_size = 4;
1486 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1487 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1488 if (!ret->free_occlusion_queries)
1489 goto out;
1491 list_init(&ret->occlusion_queries);
1493 ret->free_event_query_size = 4;
1494 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1495 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1496 if (!ret->free_event_queries)
1497 goto out;
1499 list_init(&ret->event_queries);
1500 list_init(&ret->fbo_list);
1501 list_init(&ret->fbo_destroy_list);
1503 if (!device->shader_backend->shader_allocate_context_data(ret))
1505 ERR("Failed to allocate shader backend context data.\n");
1506 goto out;
1508 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1510 ERR("Failed to allocate fragment pipeline context data.\n");
1511 goto out;
1514 /* Initialize the texture unit mapping to a 1:1 mapping */
1515 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1517 if (s < gl_info->limits.combined_samplers)
1519 ret->tex_unit_map[s] = s;
1520 ret->rev_tex_unit_map[s] = s;
1522 else
1524 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1525 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1529 if (!(hdc = GetDC(swapchain->win_handle)))
1531 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1533 if ((hdc = swapchain_get_backup_dc(swapchain)))
1534 hdc_is_private = TRUE;
1535 else
1537 ERR("Failed to retrieve a device context.\n");
1538 goto out;
1542 color_format = target->resource.format;
1544 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1545 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1546 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1548 auxBuffers = TRUE;
1550 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1551 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1552 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1553 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1556 /* DirectDraw supports 8bit paletted render targets and these are used by
1557 * old games like StarCraft and C&C. Most modern hardware doesn't support
1558 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1559 * conversion (ab)uses the alpha component for storing the palette index.
1560 * For this reason we require a format with 8bit alpha, so request
1561 * A8R8G8B8. */
1562 if (color_format->id == WINED3DFMT_P8_UINT)
1563 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1565 /* When "always_offscreen" is enabled, we only use the drawable for
1566 * presentation blits, and don't do any rendering to it. That means we
1567 * don't need depth or stencil buffers, and can mostly ignore the render
1568 * target format. This wouldn't necessarily be quite correct for 10bpc
1569 * display modes, but we don't currently support those.
1570 * Using the same format regardless of the color/depth/stencil targets
1571 * makes it much less likely that different wined3d instances will set
1572 * conflicting pixel formats. */
1573 if (wined3d_settings.offscreen_rendering_mode != ORM_BACKBUFFER
1574 && wined3d_settings.always_offscreen)
1576 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1577 ds_format = wined3d_get_format(gl_info, WINED3DFMT_UNKNOWN);
1580 /* Try to find a pixel format which matches our requirements. */
1581 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1583 /* Try to locate a compatible format if we weren't able to find anything. */
1584 if (!pixel_format)
1586 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1587 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1590 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1591 if (!pixel_format)
1593 ERR("Can't find a suitable pixel format.\n");
1594 goto out;
1597 ret->gl_info = gl_info;
1599 context_enter(ret);
1601 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1603 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1604 context_release(ret);
1605 goto out;
1608 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1609 if (gl_info->p_wglCreateContextAttribsARB)
1611 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1612 goto out;
1614 else
1616 if (!(ctx = wglCreateContext(hdc)))
1618 ERR("Failed to create a WGL context.\n");
1619 context_release(ret);
1620 goto out;
1623 if (share_ctx && !wglShareLists(share_ctx, ctx))
1625 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1626 context_release(ret);
1627 if (!wglDeleteContext(ctx))
1628 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1629 goto out;
1633 if (!device_context_add(device, ret))
1635 ERR("Failed to add the newly created context to the context list\n");
1636 context_release(ret);
1637 if (!wglDeleteContext(ctx))
1638 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1639 goto out;
1642 ret->d3d_info = &device->adapter->d3d_info;
1643 ret->state_table = device->StateTable;
1645 /* Mark all states dirty to force a proper initialization of the states
1646 * on the first use of the context. */
1647 for (state = 0; state <= STATE_HIGHEST; ++state)
1649 if (ret->state_table[state].representative)
1650 context_invalidate_state(ret, state);
1653 ret->swapchain = swapchain;
1654 ret->current_rt = target;
1655 ret->tid = GetCurrentThreadId();
1657 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1658 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1659 ret->valid = 1;
1661 ret->glCtx = ctx;
1662 ret->win_handle = swapchain->win_handle;
1663 ret->hdc = hdc;
1664 ret->hdc_is_private = hdc_is_private;
1665 ret->hdc_has_format = TRUE;
1666 ret->pixel_format = pixel_format;
1667 ret->needs_set = 1;
1669 /* Set up the context defaults */
1670 if (!context_set_current(ret))
1672 ERR("Cannot activate context to set up defaults.\n");
1673 device_context_remove(device, ret);
1674 context_release(ret);
1675 if (!wglDeleteContext(ctx))
1676 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1677 goto out;
1680 if (context_debug_output_enabled(gl_info))
1682 GL_EXTCALL(glDebugMessageCallback(wined3d_debug_callback, ret));
1683 if (TRACE_ON(d3d_synchronous))
1684 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
1685 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1686 if (ERR_ON(d3d))
1688 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR,
1689 GL_DONT_CARE, 0, NULL, GL_TRUE));
1691 if (FIXME_ON(d3d))
1693 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
1694 GL_DONT_CARE, 0, NULL, GL_TRUE));
1695 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
1696 GL_DONT_CARE, 0, NULL, GL_TRUE));
1697 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY,
1698 GL_DONT_CARE, 0, NULL, GL_TRUE));
1700 if (WARN_ON(d3d_perf))
1702 GL_EXTCALL(glDebugMessageControl(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE,
1703 GL_DONT_CARE, 0, NULL, GL_TRUE));
1707 switch (swapchain->desc.swap_interval)
1709 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1710 swap_interval = 0;
1711 break;
1712 case WINED3DPRESENT_INTERVAL_DEFAULT:
1713 case WINED3DPRESENT_INTERVAL_ONE:
1714 swap_interval = 1;
1715 break;
1716 case WINED3DPRESENT_INTERVAL_TWO:
1717 swap_interval = 2;
1718 break;
1719 case WINED3DPRESENT_INTERVAL_THREE:
1720 swap_interval = 3;
1721 break;
1722 case WINED3DPRESENT_INTERVAL_FOUR:
1723 swap_interval = 4;
1724 break;
1725 default:
1726 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1727 swap_interval = 1;
1730 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1732 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1733 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1734 swap_interval, ret, GetLastError());
1737 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1739 TRACE("Setting up the screen\n");
1741 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1742 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1744 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1745 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1747 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1748 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1750 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1751 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1752 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1753 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1755 if (!gl_info->supported[WINED3D_GL_LEGACY_CONTEXT])
1757 GLuint vao;
1759 GL_EXTCALL(glGenVertexArrays(1, &vao));
1760 GL_EXTCALL(glBindVertexArray(vao));
1761 checkGLcall("creating VAO");
1764 if (gl_info->supported[ARB_VERTEX_BLEND])
1766 /* Direct3D always uses n-1 weights for n world matrices and uses
1767 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1768 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1769 * enabled as well. */
1770 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1771 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1773 if (gl_info->supported[NV_TEXTURE_SHADER2])
1775 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1776 * the previous texture where to source the offset from is always unit - 1.
1778 for (s = 1; s < gl_info->limits.textures; ++s)
1780 context_active_texture(ret, gl_info, s);
1781 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1782 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1783 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1786 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1788 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1789 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1790 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1791 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1792 * is ever assigned.
1794 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1795 * program and the dummy program is destroyed when the context is destroyed.
1797 static const char dummy_program[] =
1798 "!!ARBfp1.0\n"
1799 "MOV result.color, fragment.color.primary;\n"
1800 "END\n";
1801 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1802 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1803 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1806 if (gl_info->supported[ARB_POINT_SPRITE])
1808 for (s = 0; s < gl_info->limits.textures; ++s)
1810 context_active_texture(ret, gl_info, s);
1811 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1812 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1816 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1818 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1820 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1822 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1824 device->shader_backend->shader_init_context_state(ret);
1825 ret->shader_update_mask = (1u << WINED3D_SHADER_TYPE_PIXEL)
1826 | (1u << WINED3D_SHADER_TYPE_VERTEX)
1827 | (1u << WINED3D_SHADER_TYPE_GEOMETRY);
1829 /* If this happens to be the first context for the device, dummy textures
1830 * are not created yet. In that case, they will be created (and bound) by
1831 * create_dummy_textures right after this context is initialized. */
1832 if (device->dummy_texture_2d[0])
1833 bind_dummy_textures(device, ret);
1835 TRACE("Created context %p.\n", ret);
1837 return ret;
1839 out:
1840 device->shader_backend->shader_free_context_data(ret);
1841 device->adapter->fragment_pipe->free_context_data(ret);
1842 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1843 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1844 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1845 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1846 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1847 HeapFree(GetProcessHeap(), 0, ret);
1848 return NULL;
1851 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1853 BOOL destroy;
1855 TRACE("Destroying ctx %p\n", context);
1857 if (context->tid == GetCurrentThreadId() || !context->current)
1859 context_destroy_gl_resources(context);
1860 TlsSetValue(wined3d_context_tls_idx, NULL);
1861 destroy = TRUE;
1863 else
1865 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1866 in wined3d_adapter may go away in the meantime */
1867 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1868 *gl_info = *context->gl_info;
1869 context->gl_info = gl_info;
1870 context->destroyed = 1;
1871 destroy = FALSE;
1874 device->shader_backend->shader_free_context_data(context);
1875 device->adapter->fragment_pipe->free_context_data(context);
1876 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1877 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1878 device_context_remove(device, context);
1879 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1882 /* Context activation is done by the caller. */
1883 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1885 const GLdouble projection[] =
1887 2.0 / width, 0.0, 0.0, 0.0,
1888 0.0, 2.0 / height, 0.0, 0.0,
1889 0.0, 0.0, 2.0, 0.0,
1890 -1.0, -1.0, -1.0, 1.0,
1893 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1894 checkGLcall("glMatrixMode(GL_PROJECTION)");
1895 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1896 checkGLcall("glLoadMatrixd");
1897 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1898 checkGLcall("glViewport");
1901 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1903 const struct wined3d_surface *rt = context->current_rt;
1905 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
1907 RECT window_size;
1909 GetClientRect(context->win_handle, &window_size);
1910 size->cx = window_size.right - window_size.left;
1911 size->cy = window_size.bottom - window_size.top;
1913 return;
1916 size->cx = rt->resource.width;
1917 size->cy = rt->resource.height;
1920 /*****************************************************************************
1921 * SetupForBlit
1923 * Sets up a context for DirectDraw blitting.
1924 * All texture units are disabled, texture unit 0 is set as current unit
1925 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1926 * color writing enabled for all channels
1927 * register combiners disabled, shaders disabled
1928 * world matrix is set to identity, texture matrix 0 too
1929 * projection matrix is setup for drawing screen coordinates
1931 * Params:
1932 * This: Device to activate the context for
1933 * context: Context to setup
1935 *****************************************************************************/
1936 /* Context activation is done by the caller. */
1937 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1939 int i;
1940 const struct wined3d_gl_info *gl_info = context->gl_info;
1941 DWORD sampler;
1942 SIZE rt_size;
1944 TRACE("Setting up context %p for blitting\n", context);
1946 context_get_rt_size(context, &rt_size);
1948 if (context->last_was_blit)
1950 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1952 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1953 context->blit_w = rt_size.cx;
1954 context->blit_h = rt_size.cy;
1955 /* No need to dirtify here, the states are still dirtified because
1956 * they weren't applied since the last SetupForBlit() call. */
1958 TRACE("Context is already set up for blitting, nothing to do\n");
1959 return;
1961 context->last_was_blit = TRUE;
1963 /* Disable all textures. The caller can then bind a texture it wants to blit
1964 * from
1966 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1967 * function texture unit. No need to care for higher samplers
1969 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1971 sampler = context->rev_tex_unit_map[i];
1972 context_active_texture(context, gl_info, i);
1974 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1976 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1977 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1979 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1980 checkGLcall("glDisable GL_TEXTURE_3D");
1981 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1983 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1984 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1986 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1987 checkGLcall("glDisable GL_TEXTURE_2D");
1989 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1990 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1992 if (sampler != WINED3D_UNMAPPED_STAGE)
1994 if (sampler < MAX_TEXTURES)
1995 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1996 context_invalidate_state(context, STATE_SAMPLER(sampler));
1999 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
2000 GL_EXTCALL(glBindSampler(0, 0));
2001 context_active_texture(context, gl_info, 0);
2003 sampler = context->rev_tex_unit_map[0];
2005 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2007 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2008 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2010 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
2011 checkGLcall("glDisable GL_TEXTURE_3D");
2012 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2014 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
2015 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2017 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
2018 checkGLcall("glDisable GL_TEXTURE_2D");
2020 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2022 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
2023 checkGLcall("glMatrixMode(GL_TEXTURE)");
2024 gl_info->gl_ops.gl.p_glLoadIdentity();
2025 checkGLcall("glLoadIdentity()");
2027 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2029 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2030 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
2031 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
2034 if (sampler != WINED3D_UNMAPPED_STAGE)
2036 if (sampler < MAX_TEXTURES)
2038 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
2039 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
2041 context_invalidate_state(context, STATE_SAMPLER(sampler));
2044 /* Other misc states */
2045 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2046 checkGLcall("glDisable(GL_ALPHA_TEST)");
2047 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2048 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2049 checkGLcall("glDisable GL_LIGHTING");
2050 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2051 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2052 checkGLcall("glDisable GL_DEPTH_TEST");
2053 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2054 glDisableWINE(GL_FOG);
2055 checkGLcall("glDisable GL_FOG");
2056 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2057 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2058 checkGLcall("glDisable GL_BLEND");
2059 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2060 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2061 checkGLcall("glDisable GL_CULL_FACE");
2062 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2063 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2064 checkGLcall("glDisable GL_STENCIL_TEST");
2065 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2066 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2067 checkGLcall("glDisable GL_SCISSOR_TEST");
2068 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2069 if (gl_info->supported[ARB_POINT_SPRITE])
2071 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2072 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2073 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2075 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2076 checkGLcall("glColorMask");
2077 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2078 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2079 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2080 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2081 if (gl_info->supported[EXT_SECONDARY_COLOR])
2083 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2084 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2085 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2088 /* Setup transforms */
2089 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2090 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2091 gl_info->gl_ops.gl.p_glLoadIdentity();
2092 checkGLcall("glLoadIdentity()");
2093 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2095 context->last_was_rhw = TRUE;
2096 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2098 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2099 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2100 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2101 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2102 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2103 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2104 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2106 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2108 /* Disable shaders */
2109 device->shader_backend->shader_disable(device->shader_priv, context);
2111 context->blit_w = rt_size.cx;
2112 context->blit_h = rt_size.cy;
2113 context_invalidate_state(context, STATE_VIEWPORT);
2114 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2117 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2119 return rt_mask & (1u << 31);
2122 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2124 return rt_mask & ~(1u << 31);
2127 /* Context activation is done by the caller. */
2128 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2130 const struct wined3d_gl_info *gl_info = context->gl_info;
2132 if (!rt_mask)
2134 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2135 checkGLcall("glDrawBuffer()");
2137 else if (is_rt_mask_onscreen(rt_mask))
2139 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2140 checkGLcall("glDrawBuffer()");
2142 else
2144 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2146 unsigned int i = 0;
2148 while (rt_mask)
2150 if (rt_mask & 1)
2151 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2152 else
2153 context->draw_buffers[i] = GL_NONE;
2155 rt_mask >>= 1;
2156 ++i;
2159 if (gl_info->supported[ARB_DRAW_BUFFERS])
2161 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2162 checkGLcall("glDrawBuffers()");
2164 else
2166 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2167 checkGLcall("glDrawBuffer()");
2170 else
2172 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2177 /* Context activation is done by the caller. */
2178 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2180 const struct wined3d_gl_info *gl_info = context->gl_info;
2181 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2182 DWORD new_mask = context_generate_rt_mask(buffer);
2184 if (new_mask == *current_mask)
2185 return;
2187 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2188 checkGLcall("glDrawBuffer()");
2190 *current_mask = new_mask;
2193 /* Context activation is done by the caller. */
2194 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2196 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2197 checkGLcall("glActiveTexture");
2198 context->active_texture = unit;
2201 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2203 const struct wined3d_gl_info *gl_info = context->gl_info;
2204 DWORD unit = context->active_texture;
2205 DWORD old_texture_type = context->texture_type[unit];
2207 if (name)
2209 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2210 checkGLcall("glBindTexture");
2212 else
2214 target = GL_NONE;
2217 if (old_texture_type != target)
2219 const struct wined3d_device *device = context->swapchain->device;
2221 switch (old_texture_type)
2223 case GL_NONE:
2224 /* nothing to do */
2225 break;
2226 case GL_TEXTURE_2D:
2227 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2228 checkGLcall("glBindTexture");
2229 break;
2230 case GL_TEXTURE_RECTANGLE_ARB:
2231 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2232 checkGLcall("glBindTexture");
2233 break;
2234 case GL_TEXTURE_CUBE_MAP:
2235 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2236 checkGLcall("glBindTexture");
2237 break;
2238 case GL_TEXTURE_3D:
2239 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2240 checkGLcall("glBindTexture");
2241 break;
2242 default:
2243 ERR("Unexpected texture target %#x\n", old_texture_type);
2246 context->texture_type[unit] = target;
2250 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2252 if (context->render_offscreen == offscreen) return;
2254 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2255 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2256 context_invalidate_state(context, STATE_VIEWPORT);
2257 context_invalidate_state(context, STATE_SCISSORRECT);
2258 context_invalidate_state(context, STATE_FRONTFACE);
2259 context->render_offscreen = offscreen;
2262 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2263 const struct wined3d_format *required)
2265 if (existing == required)
2266 return TRUE;
2267 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2268 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2269 return FALSE;
2270 if (existing->depth_size < required->depth_size)
2271 return FALSE;
2272 /* If stencil bits are used the exact amount is required - otherwise
2273 * wrapping won't work correctly. */
2274 if (required->stencil_size && required->stencil_size != existing->stencil_size)
2275 return FALSE;
2276 return TRUE;
2279 /* Context activation is done by the caller. */
2280 static void context_validate_onscreen_formats(struct wined3d_context *context,
2281 const struct wined3d_rendertarget_view *depth_stencil)
2283 /* Onscreen surfaces are always in a swapchain */
2284 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2286 if (context->render_offscreen || !depth_stencil) return;
2287 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2289 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2290 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2291 * format. */
2292 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2294 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2295 surface_load_location(context->current_rt, context, WINED3D_LOCATION_TEXTURE_RGB);
2296 swapchain->render_to_fbo = TRUE;
2297 swapchain_update_draw_bindings(swapchain);
2298 context_set_render_offscreen(context, TRUE);
2301 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2303 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2304 return 0;
2305 else if (rt->container->swapchain)
2306 return context_generate_rt_mask_from_surface(rt);
2307 else
2308 return context_generate_rt_mask(device->offscreenBuffer);
2311 /* Context activation is done by the caller. */
2312 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2314 struct wined3d_surface *rt = context->current_rt;
2315 DWORD rt_mask, *cur_mask;
2317 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2319 context_validate_onscreen_formats(context, NULL);
2321 if (context->render_offscreen)
2323 wined3d_texture_load(rt->container, context, FALSE);
2325 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2326 if (rt->resource.format->id != WINED3DFMT_NULL)
2327 rt_mask = 1;
2328 else
2329 rt_mask = 0;
2331 else
2333 context->current_fbo = NULL;
2334 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2335 rt_mask = context_generate_rt_mask_from_surface(rt);
2338 else
2340 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2343 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2345 if (rt_mask != *cur_mask)
2347 context_apply_draw_buffers(context, rt_mask);
2348 *cur_mask = rt_mask;
2351 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2353 context_check_fbo_status(context, GL_FRAMEBUFFER);
2356 SetupForBlit(device, context);
2357 context_invalidate_state(context, STATE_FRAMEBUFFER);
2360 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2361 const struct wined3d_rendertarget_view *ds)
2363 unsigned int i;
2365 if (ds) return TRUE;
2367 for (i = 0; i < rt_count; ++i)
2369 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2370 return TRUE;
2373 WARN("Invalid render target config, need at least one attachment.\n");
2374 return FALSE;
2377 /* Context activation is done by the caller. */
2378 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2379 UINT rt_count, const struct wined3d_fb_state *fb)
2381 struct wined3d_rendertarget_view **rts = fb->render_targets;
2382 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2383 const struct wined3d_gl_info *gl_info = context->gl_info;
2384 DWORD rt_mask = 0, *cur_mask;
2385 UINT i;
2387 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2388 || rt_count != context->gl_info->limits.buffers)
2390 if (!context_validate_rt_config(rt_count, rts, dsv))
2391 return FALSE;
2393 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2395 context_validate_onscreen_formats(context, dsv);
2397 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2399 for (i = 0; i < rt_count; ++i)
2401 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2402 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2403 rt_mask |= (1u << i);
2405 while (i < context->gl_info->limits.buffers)
2407 context->blit_targets[i] = NULL;
2408 ++i;
2410 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2411 wined3d_rendertarget_view_get_surface(dsv),
2412 rt_count ? rts[0]->resource->draw_binding : 0,
2413 dsv ? dsv->resource->draw_binding : 0);
2415 else
2417 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2418 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2419 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2422 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2423 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2424 * state management allows this */
2425 context_invalidate_state(context, STATE_FRAMEBUFFER);
2427 else
2429 rt_mask = context_generate_rt_mask_no_fbo(device,
2430 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2433 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2434 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2436 for (i = 0; i < rt_count; ++i)
2438 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2439 rt_mask |= (1u << i);
2442 else
2444 rt_mask = context_generate_rt_mask_no_fbo(device,
2445 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2448 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2450 if (rt_mask != *cur_mask)
2452 context_apply_draw_buffers(context, rt_mask);
2453 *cur_mask = rt_mask;
2454 context_invalidate_state(context, STATE_FRAMEBUFFER);
2457 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2459 context_check_fbo_status(context, GL_FRAMEBUFFER);
2462 if (context->last_was_blit)
2463 context->last_was_blit = FALSE;
2465 /* Blending and clearing should be orthogonal, but tests on the nvidia
2466 * driver show that disabling blending when clearing improves the clearing
2467 * performance incredibly. */
2468 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2469 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2470 if (gl_info->supported[ARB_FRAMEBUFFER_SRGB])
2472 if (device->state.render_states[WINED3D_RS_SRGBWRITEENABLE])
2473 gl_info->gl_ops.gl.p_glEnable(GL_FRAMEBUFFER_SRGB);
2474 else
2475 gl_info->gl_ops.gl.p_glDisable(GL_FRAMEBUFFER_SRGB);
2476 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
2478 checkGLcall("setting up state for clear");
2480 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2481 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2482 context_invalidate_state(context, STATE_SCISSORRECT);
2484 return TRUE;
2487 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2489 const struct wined3d_state *state = &device->state;
2490 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2491 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2492 DWORD rt_mask, rt_mask_bits;
2493 unsigned int i;
2495 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2496 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2497 else if (!context->render_offscreen)
2498 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2500 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2501 rt_mask &= context->d3d_info->valid_rt_mask;
2502 rt_mask_bits = rt_mask;
2503 i = 0;
2504 while (rt_mask_bits)
2506 rt_mask_bits &= ~(1u << i);
2507 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2508 rt_mask &= ~(1u << i);
2510 i++;
2513 return rt_mask;
2516 /* Context activation is done by the caller. */
2517 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2519 const struct wined3d_device *device = context->swapchain->device;
2520 const struct wined3d_fb_state *fb = state->fb;
2521 DWORD rt_mask = find_draw_buffers_mask(context, device);
2522 DWORD *cur_mask;
2524 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2526 if (!context->render_offscreen)
2528 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2529 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2531 else
2533 unsigned int i;
2535 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2537 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2539 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2540 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2541 fb->render_targets[0]->resource->draw_binding,
2542 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2546 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2547 if (rt_mask != *cur_mask)
2549 context_apply_draw_buffers(context, rt_mask);
2550 *cur_mask = rt_mask;
2554 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2556 DWORD i = context->rev_tex_unit_map[unit];
2557 DWORD j = context->tex_unit_map[stage];
2559 TRACE("Mapping stage %u to unit %u.\n", stage, unit);
2560 context->tex_unit_map[stage] = unit;
2561 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2562 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2564 context->rev_tex_unit_map[unit] = stage;
2565 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2566 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2569 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2571 DWORD i;
2573 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2574 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2577 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2578 const struct wined3d_state *state)
2580 UINT i, start, end;
2582 context->fixed_function_usage_map = 0;
2583 for (i = 0; i < MAX_TEXTURES; ++i)
2585 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2586 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2587 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2588 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2589 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2590 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2591 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2592 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2594 /* Not used, and disable higher stages. */
2595 if (color_op == WINED3D_TOP_DISABLE)
2596 break;
2598 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2599 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2600 || ((color_arg3 == WINED3DTA_TEXTURE)
2601 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2602 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2603 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2604 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2605 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2606 context->fixed_function_usage_map |= (1u << i);
2608 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2609 && i < MAX_TEXTURES - 1)
2610 context->fixed_function_usage_map |= (1u << (i + 1));
2613 if (i < context->lowest_disabled_stage)
2615 start = i;
2616 end = context->lowest_disabled_stage;
2618 else
2620 start = context->lowest_disabled_stage;
2621 end = i;
2624 context->lowest_disabled_stage = i;
2625 for (i = start + 1; i < end; ++i)
2627 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2631 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2632 const struct wined3d_state *state)
2634 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2635 const struct wined3d_gl_info *gl_info = context->gl_info;
2636 unsigned int i, tex;
2637 WORD ffu_map;
2639 context_update_fixed_function_usage_map(context, state);
2641 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2642 return;
2644 ffu_map = context->fixed_function_usage_map;
2646 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2647 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2649 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2651 if (!(ffu_map & 1))
2652 continue;
2654 if (context->tex_unit_map[i] != i)
2656 context_map_stage(context, i, i);
2657 context_invalidate_state(context, STATE_SAMPLER(i));
2658 context_invalidate_texture_stage(context, i);
2661 return;
2664 /* Now work out the mapping */
2665 tex = 0;
2666 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2668 if (!(ffu_map & 1))
2669 continue;
2671 if (context->tex_unit_map[i] != tex)
2673 context_map_stage(context, i, tex);
2674 context_invalidate_state(context, STATE_SAMPLER(i));
2675 context_invalidate_texture_stage(context, i);
2678 ++tex;
2682 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2684 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2685 const struct wined3d_gl_info *gl_info = context->gl_info;
2686 const struct wined3d_shader_resource_info *resource_info =
2687 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2688 unsigned int i;
2690 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2691 return;
2693 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2695 if (resource_info[i].type && context->tex_unit_map[i] != i)
2697 context_map_stage(context, i, i);
2698 context_invalidate_state(context, STATE_SAMPLER(i));
2699 if (i < d3d_info->limits.ffp_blend_stages)
2700 context_invalidate_texture_stage(context, i);
2705 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2706 const struct wined3d_shader_resource_info *ps_resource_info, DWORD unit)
2708 DWORD current_mapping = context->rev_tex_unit_map[unit];
2710 /* Not currently used */
2711 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2712 return TRUE;
2714 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2716 /* Used by a fragment sampler */
2718 if (!ps_resource_info)
2720 /* No pixel shader, check fixed function */
2721 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1u << current_mapping));
2724 /* Pixel shader, check the shader's sampler map */
2725 return !ps_resource_info[current_mapping].type;
2728 return TRUE;
2731 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2733 const struct wined3d_shader_resource_info *vs_resource_info =
2734 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2735 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2736 const struct wined3d_gl_info *gl_info = context->gl_info;
2737 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2738 int i;
2740 if (gl_info->limits.combined_samplers >= MAX_COMBINED_SAMPLERS)
2741 return;
2743 /* Note that we only care if a resource is used or not, not the
2744 * resource's specific type. Otherwise we'd need to call
2745 * shader_update_samplers() here for 1.x pixelshaders. */
2746 if (ps)
2747 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2749 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2751 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2752 if (vs_resource_info[i].type)
2754 while (start >= 0)
2756 if (context_unit_free_for_vs(context, ps_resource_info, start))
2758 if (context->tex_unit_map[vsampler_idx] != start)
2760 context_map_stage(context, vsampler_idx, start);
2761 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2764 --start;
2765 break;
2768 --start;
2770 if (context->tex_unit_map[vsampler_idx] == WINED3D_UNMAPPED_STAGE)
2771 WARN("Couldn't find a free texture unit for vertex sampler %u.\n", i);
2776 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2778 BOOL vs = use_vs(state);
2779 BOOL ps = use_ps(state);
2781 /* Try to go for a 1:1 mapping of the samplers when possible. Pixel shaders
2782 * need a 1:1 map at the moment.
2783 * When the mapping of a stage is changed, sampler and ALL texture stage
2784 * states have to be reset. */
2786 if (ps)
2787 context_map_psamplers(context, state);
2788 else
2789 context_map_fixed_function_samplers(context, state);
2791 if (vs)
2792 context_map_vsamplers(context, ps, state);
2795 /* Context activation is done by the caller. */
2796 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2798 const struct wined3d_device *device = context->swapchain->device;
2799 DWORD rt_mask, *cur_mask;
2801 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2803 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2804 rt_mask = find_draw_buffers_mask(context, device);
2805 if (rt_mask != *cur_mask)
2807 context_apply_draw_buffers(context, rt_mask);
2808 *cur_mask = rt_mask;
2812 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2814 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2815 *regnum = WINED3D_FFP_POSITION;
2816 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2817 *regnum = WINED3D_FFP_BLENDWEIGHT;
2818 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2819 *regnum = WINED3D_FFP_BLENDINDICES;
2820 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2821 *regnum = WINED3D_FFP_NORMAL;
2822 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2823 *regnum = WINED3D_FFP_PSIZE;
2824 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2825 *regnum = WINED3D_FFP_DIFFUSE;
2826 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2827 *regnum = WINED3D_FFP_SPECULAR;
2828 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2829 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2830 else
2832 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2833 *regnum = ~0U;
2834 return FALSE;
2837 return TRUE;
2840 /* Context activation is done by the caller. */
2841 void context_stream_info_from_declaration(struct wined3d_context *context,
2842 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2844 /* We need to deal with frequency data! */
2845 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2846 BOOL use_vshader = use_vs(state);
2847 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2848 unsigned int i;
2850 stream_info->use_map = 0;
2851 stream_info->swizzle_map = 0;
2852 stream_info->position_transformed = declaration->position_transformed;
2854 /* Translate the declaration into strided data. */
2855 for (i = 0; i < declaration->element_count; ++i)
2857 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2858 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2859 BOOL stride_used;
2860 unsigned int idx;
2862 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2863 element, i + 1, declaration->element_count);
2865 if (!stream->buffer)
2866 continue;
2868 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2870 if (use_vshader)
2872 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2874 stride_used = FALSE;
2876 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2878 /* TODO: Assuming vertexdeclarations are usually used with the
2879 * same or a similar shader, it might be worth it to store the
2880 * last used output slot and try that one first. */
2881 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2882 element->usage, element->usage_idx, &idx);
2884 else
2886 idx = element->output_slot;
2887 stride_used = TRUE;
2890 else
2892 if (!generic_attributes && !element->ffp_valid)
2894 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2895 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2896 stride_used = FALSE;
2898 else
2900 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2904 if (stride_used)
2906 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2907 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
2908 use_vshader ? "shader": "fixed function", idx,
2909 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2910 element->offset, stream->stride, debug_d3dformat(element->format->id),
2911 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
2913 stream_info->elements[idx].format = element->format;
2914 stream_info->elements[idx].data.buffer_object = 0;
2915 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
2916 stream_info->elements[idx].stride = stream->stride;
2917 stream_info->elements[idx].stream_idx = element->input_slot;
2918 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
2920 stream_info->elements[idx].divisor = 1;
2922 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
2924 stream_info->elements[idx].divisor = element->instance_data_step_rate;
2925 if (!element->instance_data_step_rate)
2926 FIXME("Instance step rate 0 not implemented.\n");
2928 else
2930 stream_info->elements[idx].divisor = 0;
2933 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2934 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2936 stream_info->swizzle_map |= 1u << idx;
2938 stream_info->use_map |= 1u << idx;
2943 /* Context activation is done by the caller. */
2944 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2946 const struct wined3d_gl_info *gl_info = context->gl_info;
2947 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2948 struct wined3d_stream_info *stream_info = &context->stream_info;
2949 DWORD prev_all_vbo = stream_info->all_vbo;
2950 unsigned int i;
2951 WORD map;
2953 context_stream_info_from_declaration(context, state, stream_info);
2955 stream_info->all_vbo = 1;
2956 context->num_buffer_queries = 0;
2957 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2959 struct wined3d_stream_info_element *element;
2960 struct wined3d_bo_address data;
2961 struct wined3d_buffer *buffer;
2963 if (!(map & 1))
2964 continue;
2966 element = &stream_info->elements[i];
2967 buffer = state->streams[element->stream_idx].buffer;
2969 /* We can't use VBOs if the base vertex index is negative. OpenGL
2970 * doesn't accept negative offsets (or rather offsets bigger than the
2971 * VBO, because the pointer is unsigned), so use system memory
2972 * sources. In most sane cases the pointer - offset will still be > 0,
2973 * otherwise it will wrap around to some big value. Hope that with the
2974 * indices the driver wraps it back internally. If not,
2975 * drawStridedSlow is needed, including a vertex buffer path. */
2976 if (state->load_base_vertex_index < 0)
2978 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2979 state->load_base_vertex_index);
2980 element->data.buffer_object = 0;
2981 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
2982 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
2983 FIXME("System memory vertex data load offset is negative!\n");
2985 else
2987 buffer_internal_preload(buffer, context, state);
2988 buffer_get_memory(buffer, context, &data);
2989 element->data.buffer_object = data.buffer_object;
2990 element->data.addr += (ULONG_PTR)data.addr;
2993 if (!element->data.buffer_object)
2994 stream_info->all_vbo = 0;
2996 if (buffer->query)
2997 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2999 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
3002 if (use_vs(state))
3004 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
3006 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
3007 context->use_immediate_mode_draw = TRUE;
3009 else
3011 context->use_immediate_mode_draw = FALSE;
3014 else
3016 WORD slow_mask = -!d3d_info->ffp_generic_attributes & (1u << WINED3D_FFP_PSIZE);
3017 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
3018 & ((1u << WINED3D_FFP_DIFFUSE) | (1u << WINED3D_FFP_SPECULAR));
3020 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3021 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3022 context->use_immediate_mode_draw = TRUE;
3023 else
3024 context->use_immediate_mode_draw = FALSE;
3027 if (prev_all_vbo != stream_info->all_vbo)
3028 context_invalidate_state(context, STATE_INDEXBUFFER);
3031 /* Context activation is done by the caller. */
3032 static void context_preload_texture(struct wined3d_context *context,
3033 const struct wined3d_state *state, unsigned int idx)
3035 struct wined3d_texture *texture;
3037 if (!(texture = state->textures[idx]))
3038 return;
3040 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3043 /* Context activation is done by the caller. */
3044 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3046 unsigned int i;
3048 if (use_vs(state))
3050 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3052 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3053 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3057 if (use_ps(state))
3059 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3061 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3062 context_preload_texture(context, state, i);
3065 else
3067 WORD ffu_map = context->fixed_function_usage_map;
3069 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3071 if (ffu_map & 1)
3072 context_preload_texture(context, state, i);
3077 static void context_load_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3079 struct wined3d_shader_sampler_map_entry *entry;
3080 struct wined3d_shader_resource_view *view;
3081 struct wined3d_shader *shader;
3082 unsigned int i, j;
3084 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3086 if (!(shader = state->shader[i]))
3087 continue;
3089 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3091 if (state->cb[i][j])
3092 buffer_internal_preload(state->cb[i][j], context, state);
3095 for (j = 0; j < shader->reg_maps.sampler_map.count; ++j)
3097 entry = &shader->reg_maps.sampler_map.entries[j];
3099 if (!(view = state->shader_resource_view[i][entry->resource_idx]))
3101 WARN("No resource view bound at index %u, %u.\n", i, entry->resource_idx);
3102 continue;
3105 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3106 buffer_internal_preload(buffer_from_resource(view->resource), context, state);
3107 else
3108 wined3d_texture_load(wined3d_texture_from_resource(view->resource), context, FALSE);
3113 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3115 const struct wined3d_gl_info *gl_info = context->gl_info;
3116 struct wined3d_shader_sampler_map_entry *entry;
3117 struct wined3d_shader_resource_view *view;
3118 struct wined3d_sampler *sampler;
3119 struct wined3d_texture *texture;
3120 struct wined3d_shader *shader;
3121 unsigned int i, j, count;
3123 static const struct
3125 enum wined3d_shader_type type;
3126 unsigned int base_idx;
3127 unsigned int count;
3129 shader_types[] =
3131 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3132 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3135 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3137 if (!(shader = state->shader[shader_types[i].type]))
3138 continue;
3140 count = shader->reg_maps.sampler_map.count;
3141 if (count > shader_types[i].count)
3143 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3144 shader, count, shader_types[i].count);
3145 count = shader_types[i].count;
3148 for (j = 0; j < count; ++j)
3150 entry = &shader->reg_maps.sampler_map.entries[j];
3152 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3154 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3155 continue;
3158 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3160 FIXME("Buffer shader resources not supported.\n");
3161 continue;
3164 if (!(sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3166 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3167 continue;
3170 texture = wined3d_texture_from_resource(view->resource);
3171 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3172 wined3d_texture_bind(texture, context, FALSE);
3174 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler->name));
3175 checkGLcall("glBindSampler");
3180 /* Context activation is done by the caller. */
3181 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3183 const struct wined3d_state *state = &device->state;
3184 const struct StateEntry *state_table = context->state_table;
3185 const struct wined3d_fb_state *fb = state->fb;
3186 unsigned int i;
3187 WORD map;
3189 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3190 fb->render_targets, fb->depth_stencil))
3191 return FALSE;
3193 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3195 context_validate_onscreen_formats(context, fb->depth_stencil);
3198 /* Preload resources before FBO setup. Texture preload in particular may
3199 * result in changes to the current FBO, due to using e.g. FBO blits for
3200 * updating a resource location. */
3201 context_update_tex_unit_map(context, state);
3202 context_preload_textures(context, state);
3203 context_load_shader_resources(context, state);
3204 /* TODO: Right now the dependency on the vertex shader is necessary
3205 * since context_stream_info_from_declaration depends on the reg_maps of
3206 * the current VS but maybe it's possible to relax the coupling in some
3207 * situations at least. */
3208 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3209 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3211 context_update_stream_info(context, state);
3213 else
3215 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3217 if (map & 1)
3218 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3221 if (state->index_buffer)
3223 if (context->stream_info.all_vbo)
3224 buffer_internal_preload(state->index_buffer, context, state);
3225 else
3226 buffer_get_sysmem(state->index_buffer, context);
3229 for (i = 0; i < context->numDirtyEntries; ++i)
3231 DWORD rep = context->dirtyArray[i];
3232 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3233 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3234 context->isStateDirty[idx] &= ~(1u << shift);
3235 state_table[rep].apply(context, state, rep);
3238 if (context->shader_update_mask)
3240 device->shader_backend->shader_select(device->shader_priv, context, state);
3241 context->shader_update_mask = 0;
3244 if (context->constant_update_mask)
3246 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3247 context->constant_update_mask = 0;
3250 if (context->update_shader_resource_bindings)
3252 context_bind_shader_resources(context, state);
3253 context->update_shader_resource_bindings = 0;
3256 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3258 context_check_fbo_status(context, GL_FRAMEBUFFER);
3261 context->numDirtyEntries = 0; /* This makes the whole list clean */
3262 context->last_was_blit = FALSE;
3264 return TRUE;
3267 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3269 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3271 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3272 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3274 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3275 * the alpha blend state changes with different render target formats. */
3276 if (!context->current_rt)
3278 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3280 else
3282 const struct wined3d_format *old = context->current_rt->resource.format;
3283 const struct wined3d_format *new = target->resource.format;
3285 if (old->id != new->id)
3287 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3288 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3289 || !(target->container->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3290 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3292 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3293 if ((context->current_rt->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3294 != (target->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3295 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3298 /* When switching away from an offscreen render target, and we're not
3299 * using FBOs, we have to read the drawable into the texture. This is
3300 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3301 * There are some things that need care though. PreLoad needs a GL context,
3302 * and FindContext is called before the context is activated. It also
3303 * has to be called with the old rendertarget active, otherwise a
3304 * wrong drawable is read. */
3305 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3306 && old_render_offscreen && context->current_rt != target)
3308 struct wined3d_texture *texture = context->current_rt->container;
3310 /* Read the back buffer of the old drawable into the destination texture. */
3311 if (texture->texture_srgb.name)
3312 wined3d_texture_load(texture, context, TRUE);
3313 wined3d_texture_load(texture, context, FALSE);
3314 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3318 context->current_rt = target;
3319 context_set_render_offscreen(context, render_offscreen);
3322 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3324 struct wined3d_context *current_context = context_get_current();
3325 struct wined3d_context *context;
3327 TRACE("device %p, target %p.\n", device, target);
3329 if (current_context && current_context->destroyed)
3330 current_context = NULL;
3332 if (!target)
3334 if (current_context
3335 && current_context->current_rt
3336 && current_context->swapchain->device == device)
3338 target = current_context->current_rt;
3340 else
3342 struct wined3d_swapchain *swapchain = device->swapchains[0];
3343 if (swapchain->back_buffers)
3344 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3345 else
3346 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3350 if (current_context && current_context->current_rt == target)
3352 context = current_context;
3354 else if (target->container->swapchain)
3356 TRACE("Rendering onscreen.\n");
3358 context = swapchain_get_context(target->container->swapchain);
3360 else
3362 TRACE("Rendering offscreen.\n");
3364 /* Stay with the current context if possible. Otherwise use the
3365 * context for the primary swapchain. */
3366 if (current_context && current_context->swapchain->device == device)
3367 context = current_context;
3368 else
3369 context = swapchain_get_context(device->swapchains[0]);
3372 context_enter(context);
3373 context_update_window(context);
3374 context_setup_target(context, target);
3375 if (!context->valid) return context;
3377 if (context != current_context)
3379 if (!context_set_current(context))
3380 ERR("Failed to activate the new context.\n");
3382 else if (context->needs_set)
3384 context_set_gl_context(context);
3387 return context;