msvcirt: Add implementation of streambuf::sputbackc.
[wine.git] / dlls / wined3d / context.c
blob9cc7c11b4dd8de44ee35a1e40c94ace762313570
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 wined3d_texture_prepare_texture(depth_stencil->container, context, FALSE);
146 if (format_flags & WINED3DFMT_FLAG_DEPTH)
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
149 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
150 depth_stencil->texture_level);
151 checkGLcall("glFramebufferTexture2D()");
154 if (format_flags & WINED3DFMT_FLAG_STENCIL)
156 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
157 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
158 depth_stencil->texture_level);
159 checkGLcall("glFramebufferTexture2D()");
161 break;
163 case WINED3D_LOCATION_RB_MULTISAMPLE:
164 surface_prepare_rb(depth_stencil, gl_info, TRUE);
165 context_attach_depth_stencil_rb(gl_info, fbo_target,
166 format_flags, depth_stencil->rb_multisample);
167 break;
169 case WINED3D_LOCATION_RB_RESOLVED:
170 surface_prepare_rb(depth_stencil, gl_info, FALSE);
171 context_attach_depth_stencil_rb(gl_info, fbo_target,
172 format_flags, depth_stencil->rb_resolved);
173 break;
175 default:
176 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
177 break;
181 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
183 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
184 checkGLcall("glFramebufferTexture2D()");
187 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
189 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
190 checkGLcall("glFramebufferTexture2D()");
193 else
195 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
196 checkGLcall("glFramebufferTexture2D()");
198 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
199 checkGLcall("glFramebufferTexture2D()");
203 /* Context activation is done by the caller. */
204 static void context_attach_surface_fbo(struct wined3d_context *context,
205 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
207 const struct wined3d_gl_info *gl_info = context->gl_info;
209 TRACE("Attach surface %p to %u\n", surface, idx);
211 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
213 BOOL srgb;
215 switch (location)
217 case WINED3D_LOCATION_TEXTURE_RGB:
218 case WINED3D_LOCATION_TEXTURE_SRGB:
219 srgb = location == WINED3D_LOCATION_TEXTURE_SRGB;
220 wined3d_texture_prepare_texture(surface->container, context, srgb);
221 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
222 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
223 surface->texture_level);
224 checkGLcall("glFramebufferTexture2D()");
225 break;
227 case WINED3D_LOCATION_RB_MULTISAMPLE:
228 surface_prepare_rb(surface, gl_info, TRUE);
229 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
230 GL_RENDERBUFFER, surface->rb_multisample);
231 checkGLcall("glFramebufferRenderbuffer()");
232 break;
234 case WINED3D_LOCATION_RB_RESOLVED:
235 surface_prepare_rb(surface, gl_info, FALSE);
236 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
237 GL_RENDERBUFFER, surface->rb_resolved);
238 checkGLcall("glFramebufferRenderbuffer()");
239 break;
241 default:
242 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
243 break;
246 else
248 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
249 checkGLcall("glFramebufferTexture2D()");
253 /* Context activation is done by the caller. */
254 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
256 const struct wined3d_gl_info *gl_info = context->gl_info;
257 GLenum status;
259 if (!FIXME_ON(d3d)) return;
261 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
262 if (status == GL_FRAMEBUFFER_COMPLETE)
264 TRACE("FBO complete\n");
266 else
268 const struct wined3d_surface *attachment;
269 unsigned int i;
271 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
273 if (!context->current_fbo)
275 ERR("FBO 0 is incomplete, driver bug?\n");
276 return;
279 FIXME("\tColor Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->color_location),
280 context->current_fbo->color_location);
281 FIXME("\tDepth Stencil Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->ds_location),
282 context->current_fbo->ds_location);
284 /* Dump the FBO attachments */
285 for (i = 0; i < gl_info->limits.buffers; ++i)
287 attachment = context->current_fbo->render_targets[i];
288 if (attachment)
290 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
291 i, attachment, debug_d3dformat(attachment->resource.format->id),
292 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
295 attachment = context->current_fbo->depth_stencil;
296 if (attachment)
298 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
299 attachment, debug_d3dformat(attachment->resource.format->id),
300 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
305 static inline DWORD context_generate_rt_mask(GLenum buffer)
307 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
308 return buffer ? (1 << 31) | buffer : 0;
311 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
313 return (1 << 31) | surface_get_gl_buffer(target);
316 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
317 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
318 DWORD color_location, DWORD ds_location)
320 const struct wined3d_gl_info *gl_info = context->gl_info;
321 struct fbo_entry *entry;
323 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
324 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
325 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
326 entry->depth_stencil = depth_stencil;
327 entry->color_location = color_location;
328 entry->ds_location = ds_location;
329 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
330 entry->attached = FALSE;
331 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
332 checkGLcall("glGenFramebuffers()");
333 TRACE("Created FBO %u.\n", entry->id);
335 return entry;
338 /* Context activation is done by the caller. */
339 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
340 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
341 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
343 const struct wined3d_gl_info *gl_info = context->gl_info;
345 context_bind_fbo(context, target, entry->id);
346 context_clean_fbo_attachments(gl_info, target);
348 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
349 entry->depth_stencil = depth_stencil;
350 entry->color_location = color_location;
351 entry->ds_location = ds_location;
352 entry->attached = FALSE;
355 /* Context activation is done by the caller. */
356 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
358 if (entry->id)
360 TRACE("Destroy FBO %u.\n", entry->id);
361 context_destroy_fbo(context, entry->id);
363 --context->fbo_entry_count;
364 list_remove(&entry->entry);
365 HeapFree(GetProcessHeap(), 0, entry->render_targets);
366 HeapFree(GetProcessHeap(), 0, entry);
369 /* Context activation is done by the caller. */
370 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
371 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
372 DWORD color_location, DWORD ds_location)
374 const struct wined3d_gl_info *gl_info = context->gl_info;
375 struct fbo_entry *entry;
377 if (depth_stencil && render_targets && render_targets[0])
379 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
380 depth_stencil->resource.height < render_targets[0]->resource.height)
382 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
383 depth_stencil = NULL;
387 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
389 if (!memcmp(entry->render_targets,
390 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
391 && entry->depth_stencil == depth_stencil && entry->color_location == color_location
392 && entry->ds_location == ds_location)
394 list_remove(&entry->entry);
395 list_add_head(&context->fbo_list, &entry->entry);
396 return entry;
400 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
402 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
403 list_add_head(&context->fbo_list, &entry->entry);
404 ++context->fbo_entry_count;
406 else
408 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
409 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
410 list_remove(&entry->entry);
411 list_add_head(&context->fbo_list, &entry->entry);
414 return entry;
417 /* Context activation is done by the caller. */
418 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
420 const struct wined3d_gl_info *gl_info = context->gl_info;
421 unsigned int i;
422 GLuint read_binding, draw_binding;
423 struct wined3d_surface *depth_stencil = entry->depth_stencil;
425 if (entry->attached)
427 context_bind_fbo(context, target, entry->id);
428 return;
431 read_binding = context->fbo_read_binding;
432 draw_binding = context->fbo_draw_binding;
433 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
435 /* Apply render targets */
436 for (i = 0; i < gl_info->limits.buffers; ++i)
438 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->color_location);
441 if (depth_stencil && entry->render_targets[0]
442 && (depth_stencil->resource.multisample_type
443 != entry->render_targets[0]->resource.multisample_type
444 || depth_stencil->resource.multisample_quality
445 != entry->render_targets[0]->resource.multisample_quality))
447 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
448 entry->render_targets[0]->resource.multisample_quality,
449 entry->render_targets[0]->resource.multisample_type,
450 depth_stencil->resource.multisample_quality, depth_stencil->resource.multisample_type);
451 depth_stencil = NULL;
454 if (depth_stencil)
455 surface_set_compatible_renderbuffer(depth_stencil, entry->render_targets[0]);
456 context_attach_depth_stencil_fbo(context, target, depth_stencil, entry->ds_location);
458 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
459 * GL contexts requirements. */
460 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
461 context_set_draw_buffer(context, GL_NONE);
462 if (target != GL_FRAMEBUFFER)
464 if (target == GL_READ_FRAMEBUFFER)
465 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
466 else
467 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
470 entry->attached = TRUE;
473 /* Context activation is done by the caller. */
474 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
475 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
476 DWORD color_location, DWORD ds_location)
478 struct fbo_entry *entry, *entry2;
480 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
482 context_destroy_fbo_entry(context, entry);
485 if (context->rebind_fbo)
487 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
488 context->rebind_fbo = FALSE;
491 if (color_location == WINED3D_LOCATION_DRAWABLE)
493 context->current_fbo = NULL;
494 context_bind_fbo(context, target, 0);
496 else
498 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
499 color_location, ds_location);
500 context_apply_fbo_entry(context, target, context->current_fbo);
504 /* Context activation is done by the caller. */
505 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
506 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
508 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
510 context->blit_targets[0] = render_target;
511 if (clear_size)
512 memset(&context->blit_targets[1], 0, clear_size);
513 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
516 /* Context activation is done by the caller. */
517 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
519 const struct wined3d_gl_info *gl_info = context->gl_info;
521 if (context->free_occlusion_query_count)
523 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
525 else
527 if (gl_info->supported[ARB_OCCLUSION_QUERY])
529 GL_EXTCALL(glGenQueries(1, &query->id));
530 checkGLcall("glGenQueries");
532 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
534 else
536 WARN("Occlusion queries not supported, not allocating query id.\n");
537 query->id = 0;
541 query->context = context;
542 list_add_head(&context->occlusion_queries, &query->entry);
545 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
547 struct wined3d_context *context = query->context;
549 list_remove(&query->entry);
550 query->context = NULL;
552 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
554 UINT new_size = context->free_occlusion_query_size << 1;
555 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
556 new_size * sizeof(*context->free_occlusion_queries));
558 if (!new_data)
560 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
561 return;
564 context->free_occlusion_query_size = new_size;
565 context->free_occlusion_queries = new_data;
568 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
571 /* Context activation is done by the caller. */
572 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
574 const struct wined3d_gl_info *gl_info = context->gl_info;
576 if (context->free_event_query_count)
578 query->object = context->free_event_queries[--context->free_event_query_count];
580 else
582 if (gl_info->supported[ARB_SYNC])
584 /* Using ARB_sync, not much to do here. */
585 query->object.sync = NULL;
586 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
588 else if (gl_info->supported[APPLE_FENCE])
590 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
591 checkGLcall("glGenFencesAPPLE");
593 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
595 else if(gl_info->supported[NV_FENCE])
597 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
598 checkGLcall("glGenFencesNV");
600 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
602 else
604 WARN("Event queries not supported, not allocating query id.\n");
605 query->object.id = 0;
609 query->context = context;
610 list_add_head(&context->event_queries, &query->entry);
613 void context_free_event_query(struct wined3d_event_query *query)
615 struct wined3d_context *context = query->context;
617 list_remove(&query->entry);
618 query->context = NULL;
620 if (context->free_event_query_count >= context->free_event_query_size - 1)
622 UINT new_size = context->free_event_query_size << 1;
623 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
624 new_size * sizeof(*context->free_event_queries));
626 if (!new_data)
628 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
629 return;
632 context->free_event_query_size = new_size;
633 context->free_event_queries = new_data;
636 context->free_event_queries[context->free_event_query_count++] = query->object;
639 /* Context activation is done by the caller. */
640 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
642 const struct wined3d_gl_info *gl_info = context->gl_info;
644 if (context->free_timestamp_query_count)
646 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
648 else
650 GL_EXTCALL(glGenQueries(1, &query->id));
651 checkGLcall("glGenQueries");
653 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
656 query->context = context;
657 list_add_head(&context->timestamp_queries, &query->entry);
660 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
662 struct wined3d_context *context = query->context;
664 list_remove(&query->entry);
665 query->context = NULL;
667 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
669 UINT new_size = context->free_timestamp_query_size << 1;
670 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
671 new_size * sizeof(*context->free_timestamp_queries));
673 if (!new_data)
675 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
676 return;
679 context->free_timestamp_query_size = new_size;
680 context->free_timestamp_queries = new_data;
683 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
686 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
688 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
689 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
691 UINT i;
693 for (i = 0; i < device->context_count; ++i)
695 struct wined3d_context *context = device->contexts[i];
696 const struct wined3d_gl_info *gl_info = context->gl_info;
697 struct fbo_entry *entry, *entry2;
699 if (context->current_rt == surface) context->current_rt = NULL;
701 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
703 UINT j;
705 if (entry->depth_stencil == surface)
707 callback(context, entry);
708 continue;
711 for (j = 0; j < gl_info->limits.buffers; ++j)
713 if (entry->render_targets[j] == surface)
715 callback(context, entry);
716 break;
723 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
725 list_remove(&entry->entry);
726 list_add_head(&context->fbo_destroy_list, &entry->entry);
729 void context_resource_released(const struct wined3d_device *device,
730 struct wined3d_resource *resource, enum wined3d_resource_type type)
732 if (!device->d3d_initialized) return;
734 switch (type)
736 case WINED3D_RTYPE_SURFACE:
737 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
738 context_queue_fbo_entry_destruction);
739 break;
741 default:
742 break;
746 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
748 entry->attached = FALSE;
751 void context_resource_unloaded(const struct wined3d_device *device,
752 struct wined3d_resource *resource, enum wined3d_resource_type type)
754 switch (type)
756 case WINED3D_RTYPE_SURFACE:
757 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
758 context_detach_fbo_entry);
759 break;
761 default:
762 break;
766 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
768 const struct wined3d_gl_info *gl_info = context->gl_info;
769 struct fbo_entry *entry = context->current_fbo;
770 unsigned int i;
772 if (!entry || context->rebind_fbo) return;
774 for (i = 0; i < gl_info->limits.buffers; ++i)
776 if (surface == entry->render_targets[i])
778 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
779 context->rebind_fbo = TRUE;
780 return;
784 if (surface == entry->depth_stencil)
786 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
787 context->rebind_fbo = TRUE;
791 static BOOL context_restore_pixel_format(struct wined3d_context *ctx)
793 const struct wined3d_gl_info *gl_info = ctx->gl_info;
794 BOOL ret = FALSE;
796 if (ctx->restore_pf && IsWindow(ctx->restore_pf_win))
798 if (ctx->gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
800 HDC dc = GetDC(ctx->restore_pf_win);
801 if (dc)
803 if (!(ret = GL_EXTCALL(wglSetPixelFormatWINE(dc, ctx->restore_pf))))
805 ERR("wglSetPixelFormatWINE failed to restore pixel format %d on window %p.\n",
806 ctx->restore_pf, ctx->restore_pf_win);
808 ReleaseDC(ctx->restore_pf_win, dc);
811 else
813 ERR("can't restore pixel format %d on window %p\n", ctx->restore_pf, ctx->restore_pf_win);
817 ctx->restore_pf = 0;
818 ctx->restore_pf_win = NULL;
819 return ret;
822 static BOOL context_set_pixel_format(struct wined3d_context *context, HDC dc, BOOL private, int format)
824 const struct wined3d_gl_info *gl_info = context->gl_info;
825 int current;
827 if (dc == context->hdc && context->hdc_is_private && context->hdc_has_format)
828 return TRUE;
830 current = GetPixelFormat(dc);
831 if (current == format) goto success;
833 if (!current)
835 if (!SetPixelFormat(dc, format, NULL))
837 /* This may also happen if the dc belongs to a destroyed window. */
838 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
839 format, dc, GetLastError());
840 return FALSE;
843 context->restore_pf = 0;
844 context->restore_pf_win = private ? NULL : WindowFromDC(dc);
845 goto success;
848 /* By default WGL doesn't allow pixel format adjustments but we need it
849 * here. For this reason there's a Wine specific wglSetPixelFormat()
850 * which allows us to set the pixel format multiple times. Only use it
851 * when really needed. */
852 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
854 HWND win;
856 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
858 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
859 format, dc);
860 return FALSE;
863 win = private ? NULL : WindowFromDC(dc);
864 if (win != context->restore_pf_win)
866 context_restore_pixel_format(context);
868 context->restore_pf = private ? 0 : current;
869 context->restore_pf_win = win;
872 goto success;
875 /* OpenGL doesn't allow pixel format adjustments. Print an error and
876 * continue using the old format. There's a big chance that the old
877 * format works although with a performance hit and perhaps rendering
878 * errors. */
879 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
880 format, dc, current);
881 return TRUE;
883 success:
884 if (dc == context->hdc && context->hdc_is_private)
885 context->hdc_has_format = TRUE;
886 return TRUE;
889 static BOOL context_set_gl_context(struct wined3d_context *ctx)
891 struct wined3d_swapchain *swapchain = ctx->swapchain;
892 BOOL backup = FALSE;
894 if (!context_set_pixel_format(ctx, ctx->hdc, ctx->hdc_is_private, ctx->pixel_format))
896 WARN("Failed to set pixel format %d on device context %p.\n",
897 ctx->pixel_format, ctx->hdc);
898 backup = TRUE;
901 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
903 HDC dc;
905 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
906 ctx->glCtx, ctx->hdc, GetLastError());
907 ctx->valid = 0;
908 WARN("Trying fallback to the backup window.\n");
910 /* FIXME: If the context is destroyed it's no longer associated with
911 * a swapchain, so we can't use the swapchain to get a backup dc. To
912 * make this work windowless contexts would need to be handled by the
913 * device. */
914 if (ctx->destroyed)
916 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
917 context_set_current(NULL);
918 return FALSE;
921 if (!(dc = swapchain_get_backup_dc(swapchain)))
923 context_set_current(NULL);
924 return FALSE;
927 if (!context_set_pixel_format(ctx, dc, TRUE, ctx->pixel_format))
929 ERR("Failed to set pixel format %d on device context %p.\n",
930 ctx->pixel_format, dc);
931 context_set_current(NULL);
932 return FALSE;
935 if (!wglMakeCurrent(dc, ctx->glCtx))
937 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
938 dc, GetLastError());
939 context_set_current(NULL);
940 return FALSE;
943 ctx->valid = 1;
945 ctx->needs_set = 0;
946 return TRUE;
949 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx)
951 if (!wglMakeCurrent(dc, gl_ctx))
953 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
954 gl_ctx, dc, GetLastError());
955 context_set_current(NULL);
959 static void context_update_window(struct wined3d_context *context)
961 if (context->win_handle == context->swapchain->win_handle)
962 return;
964 TRACE("Updating context %p window from %p to %p.\n",
965 context, context->win_handle, context->swapchain->win_handle);
967 if (context->hdc)
968 wined3d_release_dc(context->win_handle, context->hdc);
970 context->win_handle = context->swapchain->win_handle;
971 context->hdc_is_private = FALSE;
972 context->hdc_has_format = FALSE;
973 context->needs_set = 1;
974 context->valid = 1;
976 if (!(context->hdc = GetDC(context->win_handle)))
978 ERR("Failed to get a device context for window %p.\n", context->win_handle);
979 context->valid = 0;
983 static void context_destroy_gl_resources(struct wined3d_context *context)
985 const struct wined3d_gl_info *gl_info = context->gl_info;
986 struct wined3d_timestamp_query *timestamp_query;
987 struct wined3d_occlusion_query *occlusion_query;
988 struct wined3d_event_query *event_query;
989 struct fbo_entry *entry, *entry2;
990 HGLRC restore_ctx;
991 HDC restore_dc;
992 unsigned int i;
994 restore_ctx = wglGetCurrentContext();
995 restore_dc = wglGetCurrentDC();
997 if (restore_ctx == context->glCtx)
998 restore_ctx = NULL;
999 else if (context->valid)
1000 context_set_gl_context(context);
1002 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
1004 if (context->valid)
1005 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
1006 timestamp_query->context = NULL;
1009 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
1011 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
1012 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
1013 occlusion_query->context = NULL;
1016 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
1018 if (context->valid)
1020 if (gl_info->supported[ARB_SYNC])
1022 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1024 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
1025 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
1027 event_query->context = NULL;
1030 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
1032 if (!context->valid) entry->id = 0;
1033 context_destroy_fbo_entry(context, entry);
1036 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
1038 if (!context->valid) entry->id = 0;
1039 context_destroy_fbo_entry(context, entry);
1042 if (context->valid)
1044 if (context->dummy_arbfp_prog)
1046 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1049 if (gl_info->supported[ARB_TIMER_QUERY])
1050 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
1052 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1053 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
1055 if (gl_info->supported[ARB_SYNC])
1057 for (i = 0; i < context->free_event_query_count; ++i)
1059 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1062 else if (gl_info->supported[APPLE_FENCE])
1064 for (i = 0; i < context->free_event_query_count; ++i)
1066 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1069 else if (gl_info->supported[NV_FENCE])
1071 for (i = 0; i < context->free_event_query_count; ++i)
1073 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1077 checkGLcall("context cleanup");
1080 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1081 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1082 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1084 context_restore_pixel_format(context);
1085 if (restore_ctx)
1087 context_restore_gl_context(gl_info, restore_dc, restore_ctx);
1089 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1091 ERR("Failed to disable GL context.\n");
1094 wined3d_release_dc(context->win_handle, context->hdc);
1096 if (!wglDeleteContext(context->glCtx))
1098 DWORD err = GetLastError();
1099 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1103 DWORD context_get_tls_idx(void)
1105 return wined3d_context_tls_idx;
1108 void context_set_tls_idx(DWORD idx)
1110 wined3d_context_tls_idx = idx;
1113 struct wined3d_context *context_get_current(void)
1115 return TlsGetValue(wined3d_context_tls_idx);
1118 BOOL context_set_current(struct wined3d_context *ctx)
1120 struct wined3d_context *old = context_get_current();
1122 if (old == ctx)
1124 TRACE("Already using D3D context %p.\n", ctx);
1125 return TRUE;
1128 if (old)
1130 if (old->destroyed)
1132 TRACE("Switching away from destroyed context %p.\n", old);
1133 context_destroy_gl_resources(old);
1134 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1135 HeapFree(GetProcessHeap(), 0, old);
1137 else
1139 old->current = 0;
1143 if (ctx)
1145 if (!ctx->valid)
1147 ERR("Trying to make invalid context %p current\n", ctx);
1148 return FALSE;
1151 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1152 if (!context_set_gl_context(ctx))
1153 return FALSE;
1154 ctx->current = 1;
1156 else if(wglGetCurrentContext())
1158 TRACE("Clearing current D3D context.\n");
1159 if (!wglMakeCurrent(NULL, NULL))
1161 DWORD err = GetLastError();
1162 ERR("Failed to clear current GL context, last error %#x.\n", err);
1163 TlsSetValue(wined3d_context_tls_idx, NULL);
1164 return FALSE;
1168 return TlsSetValue(wined3d_context_tls_idx, ctx);
1171 void context_release(struct wined3d_context *context)
1173 TRACE("Releasing context %p, level %u.\n", context, context->level);
1175 if (WARN_ON(d3d))
1177 if (!context->level)
1178 WARN("Context %p is not active.\n", context);
1179 else if (context != context_get_current())
1180 WARN("Context %p is not the current context.\n", context);
1183 if (!--context->level)
1185 if (context_restore_pixel_format(context))
1186 context->needs_set = 1;
1187 if (context->restore_ctx)
1189 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1190 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx);
1191 context->restore_ctx = NULL;
1192 context->restore_dc = NULL;
1197 static void context_enter(struct wined3d_context *context)
1199 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1201 if (!context->level++)
1203 const struct wined3d_context *current_context = context_get_current();
1204 HGLRC current_gl = wglGetCurrentContext();
1206 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1208 TRACE("Another GL context (%p on device context %p) is already current.\n",
1209 current_gl, wglGetCurrentDC());
1210 context->restore_ctx = current_gl;
1211 context->restore_dc = wglGetCurrentDC();
1212 context->needs_set = 1;
1214 else if (!context->needs_set && !(context->hdc_is_private && context->hdc_has_format)
1215 && context->pixel_format != GetPixelFormat(context->hdc))
1216 context->needs_set = 1;
1220 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1222 DWORD rep = context->state_table[state].representative;
1223 DWORD idx;
1224 BYTE shift;
1226 if (isStateDirty(context, rep)) return;
1228 context->dirtyArray[context->numDirtyEntries++] = rep;
1229 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1230 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1231 context->isStateDirty[idx] |= (1 << shift);
1234 /* This function takes care of wined3d pixel format selection. */
1235 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1236 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1237 BOOL auxBuffers, BOOL findCompatible)
1239 int iPixelFormat=0;
1240 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1241 BYTE depthBits=0, stencilBits=0;
1242 unsigned int current_value;
1243 unsigned int cfg_count = device->adapter->cfg_count;
1244 unsigned int i;
1246 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1247 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1248 auxBuffers, findCompatible);
1250 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1252 ERR("Unable to get color bits for format %s (%#x)!\n",
1253 debug_d3dformat(color_format->id), color_format->id);
1254 return 0;
1257 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1259 current_value = 0;
1260 for (i = 0; i < cfg_count; ++i)
1262 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1263 unsigned int value;
1265 /* For now only accept RGBA formats. Perhaps some day we will
1266 * allow floating point formats for pbuffers. */
1267 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1268 continue;
1269 /* In window mode we need a window drawable format and double buffering. */
1270 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1271 continue;
1272 if (cfg->redSize < redBits)
1273 continue;
1274 if (cfg->greenSize < greenBits)
1275 continue;
1276 if (cfg->blueSize < blueBits)
1277 continue;
1278 if (cfg->alphaSize < alphaBits)
1279 continue;
1280 if (cfg->depthSize < depthBits)
1281 continue;
1282 if (stencilBits && cfg->stencilSize != stencilBits)
1283 continue;
1284 /* Check multisampling support. */
1285 if (cfg->numSamples)
1286 continue;
1288 value = 1;
1289 /* We try to locate a format which matches our requirements exactly. In case of
1290 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1291 if (cfg->depthSize == depthBits)
1292 value += 1;
1293 if (cfg->stencilSize == stencilBits)
1294 value += 2;
1295 if (cfg->alphaSize == alphaBits)
1296 value += 4;
1297 /* We like to have aux buffers in backbuffer mode */
1298 if (auxBuffers && cfg->auxBuffers)
1299 value += 8;
1300 if (cfg->redSize == redBits
1301 && cfg->greenSize == greenBits
1302 && cfg->blueSize == blueBits)
1303 value += 16;
1305 if (value > current_value)
1307 iPixelFormat = cfg->iPixelFormat;
1308 current_value = value;
1312 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1313 if(!iPixelFormat && !findCompatible) {
1314 ERR("Can't find a suitable iPixelFormat\n");
1315 return FALSE;
1316 } else if(!iPixelFormat) {
1317 PIXELFORMATDESCRIPTOR pfd;
1319 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1320 /* PixelFormat selection */
1321 ZeroMemory(&pfd, sizeof(pfd));
1322 pfd.nSize = sizeof(pfd);
1323 pfd.nVersion = 1;
1324 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1325 pfd.iPixelType = PFD_TYPE_RGBA;
1326 pfd.cAlphaBits = alphaBits;
1327 pfd.cColorBits = colorBits;
1328 pfd.cDepthBits = depthBits;
1329 pfd.cStencilBits = stencilBits;
1330 pfd.iLayerType = PFD_MAIN_PLANE;
1332 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1333 if(!iPixelFormat) {
1334 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1335 ERR("Can't find a suitable iPixelFormat\n");
1336 return FALSE;
1340 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1341 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1342 return iPixelFormat;
1345 /* Context activation is done by the caller. */
1346 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1348 const struct wined3d_gl_info *gl_info = context->gl_info;
1349 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1351 for (i = 0; i < count; ++i)
1353 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1354 checkGLcall("glActiveTexture");
1356 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1357 checkGLcall("glBindTexture");
1359 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1361 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1362 checkGLcall("glBindTexture");
1365 if (gl_info->supported[EXT_TEXTURE3D])
1367 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1368 checkGLcall("glBindTexture");
1371 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1373 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1374 checkGLcall("glBindTexture");
1379 BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1381 return gl_info->supported[ARB_DEBUG_OUTPUT]
1382 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1385 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1386 GLenum severity, GLsizei length, const char *message, void *ctx)
1388 switch (type)
1390 case GL_DEBUG_TYPE_ERROR_ARB:
1391 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1392 break;
1394 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1395 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1396 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1397 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1398 break;
1400 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1401 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1402 break;
1404 default:
1405 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1406 break;
1410 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1411 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1413 struct wined3d_device *device = swapchain->device;
1414 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1415 const struct wined3d_format *color_format;
1416 struct wined3d_context *ret;
1417 BOOL auxBuffers = FALSE;
1418 HGLRC ctx, share_ctx;
1419 int pixel_format;
1420 unsigned int s;
1421 int swap_interval;
1422 DWORD state;
1423 HDC hdc;
1424 BOOL hdc_is_private = FALSE;
1426 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1428 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1429 if (!ret)
1430 return NULL;
1432 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1433 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1434 if (!ret->blit_targets)
1435 goto out;
1437 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1438 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1439 if (!ret->draw_buffers)
1440 goto out;
1442 ret->free_timestamp_query_size = 4;
1443 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1444 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1445 if (!ret->free_timestamp_queries)
1446 goto out;
1447 list_init(&ret->timestamp_queries);
1449 ret->free_occlusion_query_size = 4;
1450 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1451 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1452 if (!ret->free_occlusion_queries)
1453 goto out;
1455 list_init(&ret->occlusion_queries);
1457 ret->free_event_query_size = 4;
1458 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1459 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1460 if (!ret->free_event_queries)
1461 goto out;
1463 list_init(&ret->event_queries);
1464 list_init(&ret->fbo_list);
1465 list_init(&ret->fbo_destroy_list);
1467 if (!device->shader_backend->shader_allocate_context_data(ret))
1469 ERR("Failed to allocate shader backend context data.\n");
1470 goto out;
1472 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1474 ERR("Failed to allocate fragment pipeline context data.\n");
1475 goto out;
1478 /* Initialize the texture unit mapping to a 1:1 mapping */
1479 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1481 if (s < gl_info->limits.fragment_samplers)
1483 ret->tex_unit_map[s] = s;
1484 ret->rev_tex_unit_map[s] = s;
1486 else
1488 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1489 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1493 if (!(hdc = GetDC(swapchain->win_handle)))
1495 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1497 if ((hdc = swapchain_get_backup_dc(swapchain)))
1498 hdc_is_private = TRUE;
1499 else
1501 ERR("Failed to retrieve a device context.\n");
1502 goto out;
1506 color_format = target->resource.format;
1508 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1509 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1510 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1512 auxBuffers = TRUE;
1514 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1515 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1516 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1517 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1520 /* DirectDraw supports 8bit paletted render targets and these are used by
1521 * old games like StarCraft and C&C. Most modern hardware doesn't support
1522 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1523 * conversion (ab)uses the alpha component for storing the palette index.
1524 * For this reason we require a format with 8bit alpha, so request
1525 * A8R8G8B8. */
1526 if (color_format->id == WINED3DFMT_P8_UINT)
1527 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1529 /* Try to find a pixel format which matches our requirements. */
1530 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1532 /* Try to locate a compatible format if we weren't able to find anything. */
1533 if (!pixel_format)
1535 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1536 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1539 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1540 if (!pixel_format)
1542 ERR("Can't find a suitable pixel format.\n");
1543 goto out;
1546 context_enter(ret);
1548 ret->gl_info = gl_info;
1550 if (!context_set_pixel_format(ret, hdc, hdc_is_private, pixel_format))
1552 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1553 context_release(ret);
1554 goto out;
1557 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1558 if (gl_info->p_wglCreateContextAttribsARB)
1560 unsigned int ctx_attrib_idx = 0;
1561 GLint ctx_attribs[3];
1563 if (context_debug_output_enabled(gl_info))
1565 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1566 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_DEBUG_BIT_ARB;
1568 ctx_attribs[ctx_attrib_idx] = 0;
1570 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1572 ERR("Failed to create a WGL context.\n");
1573 context_release(ret);
1574 goto out;
1577 else
1579 if (!(ctx = wglCreateContext(hdc)))
1581 ERR("Failed to create a WGL context.\n");
1582 context_release(ret);
1583 goto out;
1586 if (share_ctx && !wglShareLists(share_ctx, ctx))
1588 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1589 context_release(ret);
1590 if (!wglDeleteContext(ctx))
1591 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1592 goto out;
1596 if (!device_context_add(device, ret))
1598 ERR("Failed to add the newly created context to the context list\n");
1599 context_release(ret);
1600 if (!wglDeleteContext(ctx))
1601 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1602 goto out;
1605 ret->d3d_info = &device->adapter->d3d_info;
1606 ret->state_table = device->StateTable;
1608 /* Mark all states dirty to force a proper initialization of the states
1609 * on the first use of the context. */
1610 for (state = 0; state <= STATE_HIGHEST; ++state)
1612 if (ret->state_table[state].representative)
1613 context_invalidate_state(ret, state);
1616 ret->swapchain = swapchain;
1617 ret->current_rt = target;
1618 ret->tid = GetCurrentThreadId();
1620 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1621 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1622 ret->valid = 1;
1624 ret->glCtx = ctx;
1625 ret->win_handle = swapchain->win_handle;
1626 ret->hdc = hdc;
1627 ret->hdc_is_private = hdc_is_private;
1628 ret->hdc_has_format = TRUE;
1629 ret->pixel_format = pixel_format;
1630 ret->needs_set = 1;
1632 /* Set up the context defaults */
1633 if (!context_set_current(ret))
1635 ERR("Cannot activate context to set up defaults.\n");
1636 device_context_remove(device, ret);
1637 context_release(ret);
1638 if (!wglDeleteContext(ctx))
1639 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1640 goto out;
1643 if (context_debug_output_enabled(gl_info))
1645 GL_EXTCALL(glDebugMessageCallbackARB(wined3d_debug_callback, ret));
1646 if (TRACE_ON(d3d_synchronous))
1647 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
1648 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1649 if (ERR_ON(d3d))
1651 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB,
1652 GL_DONT_CARE, 0, NULL, GL_TRUE));
1654 if (FIXME_ON(d3d))
1656 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,
1657 GL_DONT_CARE, 0, NULL, GL_TRUE));
1658 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,
1659 GL_DONT_CARE, 0, NULL, GL_TRUE));
1660 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB,
1661 GL_DONT_CARE, 0, NULL, GL_TRUE));
1663 if (WARN_ON(d3d_perf))
1665 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB,
1666 GL_DONT_CARE, 0, NULL, GL_TRUE));
1670 switch (swapchain->desc.swap_interval)
1672 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1673 swap_interval = 0;
1674 break;
1675 case WINED3DPRESENT_INTERVAL_DEFAULT:
1676 case WINED3DPRESENT_INTERVAL_ONE:
1677 swap_interval = 1;
1678 break;
1679 case WINED3DPRESENT_INTERVAL_TWO:
1680 swap_interval = 2;
1681 break;
1682 case WINED3DPRESENT_INTERVAL_THREE:
1683 swap_interval = 3;
1684 break;
1685 case WINED3DPRESENT_INTERVAL_FOUR:
1686 swap_interval = 4;
1687 break;
1688 default:
1689 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1690 swap_interval = 1;
1693 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1695 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1696 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1697 swap_interval, ret, GetLastError());
1700 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1702 TRACE("Setting up the screen\n");
1704 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1705 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1707 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1708 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1710 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1711 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1713 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1714 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1715 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1716 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1718 if (gl_info->supported[ARB_VERTEX_BLEND])
1720 /* Direct3D always uses n-1 weights for n world matrices and uses
1721 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1722 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1723 * enabled as well. */
1724 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1725 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1727 if (gl_info->supported[NV_TEXTURE_SHADER2])
1729 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1730 * the previous texture where to source the offset from is always unit - 1.
1732 for (s = 1; s < gl_info->limits.textures; ++s)
1734 context_active_texture(ret, gl_info, s);
1735 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1736 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1737 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1740 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1742 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1743 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1744 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1745 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1746 * is ever assigned.
1748 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1749 * program and the dummy program is destroyed when the context is destroyed.
1751 static const char dummy_program[] =
1752 "!!ARBfp1.0\n"
1753 "MOV result.color, fragment.color.primary;\n"
1754 "END\n";
1755 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1756 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1757 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1760 if (gl_info->supported[ARB_POINT_SPRITE])
1762 for (s = 0; s < gl_info->limits.textures; ++s)
1764 context_active_texture(ret, gl_info, s);
1765 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1766 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1770 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1772 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1774 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1776 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1778 device->shader_backend->shader_init_context_state(ret);
1779 ret->shader_update_mask = (1 << WINED3D_SHADER_TYPE_PIXEL)
1780 | (1 << WINED3D_SHADER_TYPE_VERTEX)
1781 | (1 << WINED3D_SHADER_TYPE_GEOMETRY);
1783 /* If this happens to be the first context for the device, dummy textures
1784 * are not created yet. In that case, they will be created (and bound) by
1785 * create_dummy_textures right after this context is initialized. */
1786 if (device->dummy_texture_2d[0])
1787 bind_dummy_textures(device, ret);
1789 TRACE("Created context %p.\n", ret);
1791 return ret;
1793 out:
1794 device->shader_backend->shader_free_context_data(ret);
1795 device->adapter->fragment_pipe->free_context_data(ret);
1796 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1797 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1798 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1799 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1800 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1801 HeapFree(GetProcessHeap(), 0, ret);
1802 return NULL;
1805 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1807 BOOL destroy;
1809 TRACE("Destroying ctx %p\n", context);
1811 if (context->tid == GetCurrentThreadId() || !context->current)
1813 context_destroy_gl_resources(context);
1814 TlsSetValue(wined3d_context_tls_idx, NULL);
1815 destroy = TRUE;
1817 else
1819 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1820 in wined3d_adapter may go away in the meantime */
1821 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1822 *gl_info = *context->gl_info;
1823 context->gl_info = gl_info;
1824 context->destroyed = 1;
1825 destroy = FALSE;
1828 device->shader_backend->shader_free_context_data(context);
1829 device->adapter->fragment_pipe->free_context_data(context);
1830 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1831 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1832 device_context_remove(device, context);
1833 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1836 /* Context activation is done by the caller. */
1837 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1839 const GLdouble projection[] =
1841 2.0 / width, 0.0, 0.0, 0.0,
1842 0.0, 2.0 / height, 0.0, 0.0,
1843 0.0, 0.0, 2.0, 0.0,
1844 -1.0, -1.0, -1.0, 1.0,
1847 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1848 checkGLcall("glMatrixMode(GL_PROJECTION)");
1849 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1850 checkGLcall("glLoadMatrixd");
1851 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1852 checkGLcall("glViewport");
1855 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1857 const struct wined3d_surface *rt = context->current_rt;
1859 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
1861 RECT window_size;
1863 GetClientRect(context->win_handle, &window_size);
1864 size->cx = window_size.right - window_size.left;
1865 size->cy = window_size.bottom - window_size.top;
1867 return;
1870 size->cx = rt->resource.width;
1871 size->cy = rt->resource.height;
1874 /*****************************************************************************
1875 * SetupForBlit
1877 * Sets up a context for DirectDraw blitting.
1878 * All texture units are disabled, texture unit 0 is set as current unit
1879 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1880 * color writing enabled for all channels
1881 * register combiners disabled, shaders disabled
1882 * world matrix is set to identity, texture matrix 0 too
1883 * projection matrix is setup for drawing screen coordinates
1885 * Params:
1886 * This: Device to activate the context for
1887 * context: Context to setup
1889 *****************************************************************************/
1890 /* Context activation is done by the caller. */
1891 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1893 int i;
1894 const struct wined3d_gl_info *gl_info = context->gl_info;
1895 DWORD sampler;
1896 SIZE rt_size;
1898 TRACE("Setting up context %p for blitting\n", context);
1900 context_get_rt_size(context, &rt_size);
1902 if (context->last_was_blit)
1904 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1906 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1907 context->blit_w = rt_size.cx;
1908 context->blit_h = rt_size.cy;
1909 /* No need to dirtify here, the states are still dirtified because
1910 * they weren't applied since the last SetupForBlit() call. */
1912 TRACE("Context is already set up for blitting, nothing to do\n");
1913 return;
1915 context->last_was_blit = TRUE;
1917 /* Disable all textures. The caller can then bind a texture it wants to blit
1918 * from
1920 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1921 * function texture unit. No need to care for higher samplers
1923 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1925 sampler = context->rev_tex_unit_map[i];
1926 context_active_texture(context, gl_info, i);
1928 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1930 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1931 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1933 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1934 checkGLcall("glDisable GL_TEXTURE_3D");
1935 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1937 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1938 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1940 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1941 checkGLcall("glDisable GL_TEXTURE_2D");
1943 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1944 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1946 if (sampler != WINED3D_UNMAPPED_STAGE)
1948 if (sampler < MAX_TEXTURES)
1949 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1950 context_invalidate_state(context, STATE_SAMPLER(sampler));
1953 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
1954 GL_EXTCALL(glBindSampler(0, 0));
1955 context_active_texture(context, gl_info, 0);
1957 sampler = context->rev_tex_unit_map[0];
1959 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1961 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1962 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1964 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1965 checkGLcall("glDisable GL_TEXTURE_3D");
1966 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1968 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1969 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1971 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1972 checkGLcall("glDisable GL_TEXTURE_2D");
1974 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1976 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1977 checkGLcall("glMatrixMode(GL_TEXTURE)");
1978 gl_info->gl_ops.gl.p_glLoadIdentity();
1979 checkGLcall("glLoadIdentity()");
1981 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1983 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1984 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1985 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1988 if (sampler != WINED3D_UNMAPPED_STAGE)
1990 if (sampler < MAX_TEXTURES)
1992 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1993 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1995 context_invalidate_state(context, STATE_SAMPLER(sampler));
1998 /* Other misc states */
1999 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
2000 checkGLcall("glDisable(GL_ALPHA_TEST)");
2001 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
2002 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
2003 checkGLcall("glDisable GL_LIGHTING");
2004 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
2005 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
2006 checkGLcall("glDisable GL_DEPTH_TEST");
2007 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
2008 glDisableWINE(GL_FOG);
2009 checkGLcall("glDisable GL_FOG");
2010 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
2011 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2012 checkGLcall("glDisable GL_BLEND");
2013 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2014 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
2015 checkGLcall("glDisable GL_CULL_FACE");
2016 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
2017 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
2018 checkGLcall("glDisable GL_STENCIL_TEST");
2019 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
2020 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
2021 checkGLcall("glDisable GL_SCISSOR_TEST");
2022 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2023 if (gl_info->supported[ARB_POINT_SPRITE])
2025 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
2026 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2027 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
2029 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2030 checkGLcall("glColorMask");
2031 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
2032 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
2033 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
2034 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2035 if (gl_info->supported[EXT_SECONDARY_COLOR])
2037 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2038 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2039 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2042 /* Setup transforms */
2043 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2044 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2045 gl_info->gl_ops.gl.p_glLoadIdentity();
2046 checkGLcall("glLoadIdentity()");
2047 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2049 context->last_was_rhw = TRUE;
2050 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2052 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2053 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2054 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2055 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2056 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2057 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2058 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2060 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2062 /* Disable shaders */
2063 device->shader_backend->shader_disable(device->shader_priv, context);
2065 context->blit_w = rt_size.cx;
2066 context->blit_h = rt_size.cy;
2067 context_invalidate_state(context, STATE_VIEWPORT);
2068 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2071 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2073 return rt_mask & (1 << 31);
2076 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2078 return rt_mask & ~(1 << 31);
2081 /* Context activation is done by the caller. */
2082 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2084 const struct wined3d_gl_info *gl_info = context->gl_info;
2086 if (!rt_mask)
2088 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2089 checkGLcall("glDrawBuffer()");
2091 else if (is_rt_mask_onscreen(rt_mask))
2093 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2094 checkGLcall("glDrawBuffer()");
2096 else
2098 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2100 unsigned int i = 0;
2102 while (rt_mask)
2104 if (rt_mask & 1)
2105 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2106 else
2107 context->draw_buffers[i] = GL_NONE;
2109 rt_mask >>= 1;
2110 ++i;
2113 if (gl_info->supported[ARB_DRAW_BUFFERS])
2115 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2116 checkGLcall("glDrawBuffers()");
2118 else
2120 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2121 checkGLcall("glDrawBuffer()");
2124 else
2126 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2131 /* Context activation is done by the caller. */
2132 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2134 const struct wined3d_gl_info *gl_info = context->gl_info;
2135 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2136 DWORD new_mask = context_generate_rt_mask(buffer);
2138 if (new_mask == *current_mask)
2139 return;
2141 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2142 checkGLcall("glDrawBuffer()");
2144 *current_mask = new_mask;
2147 /* Context activation is done by the caller. */
2148 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2150 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2151 checkGLcall("glActiveTexture");
2152 context->active_texture = unit;
2155 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2157 const struct wined3d_gl_info *gl_info = context->gl_info;
2158 DWORD unit = context->active_texture;
2159 DWORD old_texture_type = context->texture_type[unit];
2161 if (name)
2163 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2164 checkGLcall("glBindTexture");
2166 else
2168 target = GL_NONE;
2171 if (old_texture_type != target)
2173 const struct wined3d_device *device = context->swapchain->device;
2175 switch (old_texture_type)
2177 case GL_NONE:
2178 /* nothing to do */
2179 break;
2180 case GL_TEXTURE_2D:
2181 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2182 checkGLcall("glBindTexture");
2183 break;
2184 case GL_TEXTURE_RECTANGLE_ARB:
2185 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2186 checkGLcall("glBindTexture");
2187 break;
2188 case GL_TEXTURE_CUBE_MAP:
2189 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2190 checkGLcall("glBindTexture");
2191 break;
2192 case GL_TEXTURE_3D:
2193 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2194 checkGLcall("glBindTexture");
2195 break;
2196 default:
2197 ERR("Unexpected texture target %#x\n", old_texture_type);
2200 context->texture_type[unit] = target;
2204 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2206 if (context->render_offscreen == offscreen) return;
2208 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2209 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2210 context_invalidate_state(context, STATE_VIEWPORT);
2211 context_invalidate_state(context, STATE_SCISSORRECT);
2212 context_invalidate_state(context, STATE_FRONTFACE);
2213 context->render_offscreen = offscreen;
2216 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2217 const struct wined3d_format *required)
2219 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
2221 if (existing == required)
2222 return TRUE;
2223 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2224 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2225 return FALSE;
2227 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2228 getDepthStencilBits(required, &required_depth, &required_stencil);
2230 if(existing_depth < required_depth) return FALSE;
2231 /* If stencil bits are used the exact amount is required - otherwise wrapping
2232 * won't work correctly */
2233 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2234 return TRUE;
2237 /* The caller provides a context */
2238 static void context_validate_onscreen_formats(struct wined3d_context *context,
2239 const struct wined3d_rendertarget_view *depth_stencil)
2241 /* Onscreen surfaces are always in a swapchain */
2242 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2244 if (context->render_offscreen || !depth_stencil) return;
2245 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2247 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2248 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2249 * format. */
2250 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2252 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2253 surface_load_location(context->current_rt, WINED3D_LOCATION_TEXTURE_RGB);
2254 swapchain->render_to_fbo = TRUE;
2255 swapchain_update_draw_bindings(swapchain);
2256 context_set_render_offscreen(context, TRUE);
2259 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2261 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2262 return 0;
2263 else if (rt->container->swapchain)
2264 return context_generate_rt_mask_from_surface(rt);
2265 else
2266 return context_generate_rt_mask(device->offscreenBuffer);
2269 /* Context activation is done by the caller. */
2270 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2272 struct wined3d_surface *rt = context->current_rt;
2273 DWORD rt_mask, *cur_mask;
2275 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2277 context_validate_onscreen_formats(context, NULL);
2279 if (context->render_offscreen)
2281 wined3d_texture_load(rt->container, context, FALSE);
2283 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2284 if (rt->resource.format->id != WINED3DFMT_NULL)
2285 rt_mask = 1;
2286 else
2287 rt_mask = 0;
2289 else
2291 context->current_fbo = NULL;
2292 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2293 rt_mask = context_generate_rt_mask_from_surface(rt);
2296 else
2298 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2301 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2303 if (rt_mask != *cur_mask)
2305 context_apply_draw_buffers(context, rt_mask);
2306 *cur_mask = rt_mask;
2309 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2311 context_check_fbo_status(context, GL_FRAMEBUFFER);
2314 SetupForBlit(device, context);
2315 context_invalidate_state(context, STATE_FRAMEBUFFER);
2318 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2319 const struct wined3d_rendertarget_view *ds)
2321 unsigned int i;
2323 if (ds) return TRUE;
2325 for (i = 0; i < rt_count; ++i)
2327 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2328 return TRUE;
2331 WARN("Invalid render target config, need at least one attachment.\n");
2332 return FALSE;
2335 /* Context activation is done by the caller. */
2336 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2337 UINT rt_count, const struct wined3d_fb_state *fb)
2339 struct wined3d_rendertarget_view **rts = fb->render_targets;
2340 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2341 const struct wined3d_gl_info *gl_info = context->gl_info;
2342 DWORD rt_mask = 0, *cur_mask;
2343 UINT i;
2345 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2346 || rt_count != context->gl_info->limits.buffers)
2348 if (!context_validate_rt_config(rt_count, rts, dsv))
2349 return FALSE;
2351 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2353 context_validate_onscreen_formats(context, dsv);
2355 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2357 for (i = 0; i < rt_count; ++i)
2359 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2360 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2361 rt_mask |= (1 << i);
2363 while (i < context->gl_info->limits.buffers)
2365 context->blit_targets[i] = NULL;
2366 ++i;
2368 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2369 wined3d_rendertarget_view_get_surface(dsv),
2370 rt_count ? rts[0]->resource->draw_binding : 0,
2371 dsv ? dsv->resource->draw_binding : 0);
2373 else
2375 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2376 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2377 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2380 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2381 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2382 * state management allows this */
2383 context_invalidate_state(context, STATE_FRAMEBUFFER);
2385 else
2387 rt_mask = context_generate_rt_mask_no_fbo(device,
2388 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2391 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2392 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2394 for (i = 0; i < rt_count; ++i)
2396 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2397 rt_mask |= (1 << i);
2400 else
2402 rt_mask = context_generate_rt_mask_no_fbo(device,
2403 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2406 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2408 if (rt_mask != *cur_mask)
2410 context_apply_draw_buffers(context, rt_mask);
2411 *cur_mask = rt_mask;
2412 context_invalidate_state(context, STATE_FRAMEBUFFER);
2415 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2417 context_check_fbo_status(context, GL_FRAMEBUFFER);
2420 if (context->last_was_blit)
2421 context->last_was_blit = FALSE;
2423 /* Blending and clearing should be orthogonal, but tests on the nvidia
2424 * driver show that disabling blending when clearing improves the clearing
2425 * performance incredibly. */
2426 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2427 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2428 checkGLcall("glEnable GL_SCISSOR_TEST");
2430 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2431 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2432 context_invalidate_state(context, STATE_SCISSORRECT);
2434 return TRUE;
2437 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2439 const struct wined3d_state *state = &device->state;
2440 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2441 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2442 DWORD rt_mask, rt_mask_bits;
2443 unsigned int i;
2445 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2446 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2447 else if (!context->render_offscreen)
2448 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2450 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2451 rt_mask &= context->d3d_info->valid_rt_mask;
2452 rt_mask_bits = rt_mask;
2453 i = 0;
2454 while (rt_mask_bits)
2456 rt_mask_bits &= ~(1 << i);
2457 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2458 rt_mask &= ~(1 << i);
2460 i++;
2463 return rt_mask;
2466 /* Context activation is done by the caller. */
2467 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2469 const struct wined3d_device *device = context->swapchain->device;
2470 const struct wined3d_fb_state *fb = state->fb;
2471 DWORD rt_mask = find_draw_buffers_mask(context, device);
2472 DWORD *cur_mask;
2474 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2476 if (!context->render_offscreen)
2478 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2479 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2481 else
2483 unsigned int i;
2485 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2487 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2489 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2490 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2491 fb->render_targets[0]->resource->draw_binding,
2492 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2496 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2497 if (rt_mask != *cur_mask)
2499 context_apply_draw_buffers(context, rt_mask);
2500 *cur_mask = rt_mask;
2504 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2506 DWORD i = context->rev_tex_unit_map[unit];
2507 DWORD j = context->tex_unit_map[stage];
2509 context->tex_unit_map[stage] = unit;
2510 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2511 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2513 context->rev_tex_unit_map[unit] = stage;
2514 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2515 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2518 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2520 DWORD i;
2522 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2523 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2526 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2527 const struct wined3d_state *state)
2529 UINT i, start, end;
2531 context->fixed_function_usage_map = 0;
2532 for (i = 0; i < MAX_TEXTURES; ++i)
2534 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2535 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2536 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2537 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2538 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2539 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2540 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2541 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2543 /* Not used, and disable higher stages. */
2544 if (color_op == WINED3D_TOP_DISABLE)
2545 break;
2547 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2548 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2549 || ((color_arg3 == WINED3DTA_TEXTURE)
2550 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2551 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2552 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2553 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2554 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2555 context->fixed_function_usage_map |= (1 << i);
2557 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2558 && i < MAX_TEXTURES - 1)
2559 context->fixed_function_usage_map |= (1 << (i + 1));
2562 if (i < context->lowest_disabled_stage)
2564 start = i;
2565 end = context->lowest_disabled_stage;
2567 else
2569 start = context->lowest_disabled_stage;
2570 end = i;
2573 context->lowest_disabled_stage = i;
2574 for (i = start + 1; i < end; ++i)
2576 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2580 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2581 const struct wined3d_state *state)
2583 unsigned int i, tex;
2584 WORD ffu_map;
2585 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2587 context_update_fixed_function_usage_map(context, state);
2588 ffu_map = context->fixed_function_usage_map;
2590 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2591 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2593 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2595 if (!(ffu_map & 1))
2596 continue;
2598 if (context->tex_unit_map[i] != i)
2600 context_map_stage(context, i, i);
2601 context_invalidate_state(context, STATE_SAMPLER(i));
2602 context_invalidate_texture_stage(context, i);
2605 return;
2608 /* Now work out the mapping */
2609 tex = 0;
2610 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2612 if (!(ffu_map & 1))
2613 continue;
2615 if (context->tex_unit_map[i] != tex)
2617 context_map_stage(context, i, tex);
2618 context_invalidate_state(context, STATE_SAMPLER(i));
2619 context_invalidate_texture_stage(context, i);
2622 ++tex;
2626 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2628 const struct wined3d_shader_resource_info *resource_info =
2629 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2630 unsigned int i;
2631 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2633 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2635 if (resource_info[i].type && context->tex_unit_map[i] != i)
2637 context_map_stage(context, i, i);
2638 context_invalidate_state(context, STATE_SAMPLER(i));
2639 if (i < d3d_info->limits.ffp_blend_stages)
2640 context_invalidate_texture_stage(context, i);
2645 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2646 const struct wined3d_shader_resource_info *ps_resource_info,
2647 const struct wined3d_shader_resource_info *vs_resource_info, DWORD unit)
2649 DWORD current_mapping = context->rev_tex_unit_map[unit];
2651 /* Not currently used */
2652 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2653 return TRUE;
2655 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2657 /* Used by a fragment sampler */
2659 if (!ps_resource_info)
2661 /* No pixel shader, check fixed function */
2662 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1 << current_mapping));
2665 /* Pixel shader, check the shader's sampler map */
2666 return !ps_resource_info[current_mapping].type;
2669 /* Used by a vertex sampler */
2670 return !vs_resource_info[current_mapping - MAX_FRAGMENT_SAMPLERS].type;
2673 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2675 const struct wined3d_shader_resource_info *vs_resource_info =
2676 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2677 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2678 const struct wined3d_gl_info *gl_info = context->gl_info;
2679 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2680 int i;
2682 /* Note that we only care if a resource is used or not, not the
2683 * resource's specific type. Otherwise we'd need to call
2684 * shader_update_samplers() here for 1.x pixelshaders. */
2685 if (ps)
2686 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2688 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2690 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2691 if (vs_resource_info[i].type)
2693 if (context->tex_unit_map[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2695 /* Already mapped somewhere */
2696 continue;
2699 while (start >= 0)
2701 if (context_unit_free_for_vs(context, ps_resource_info, vs_resource_info, start))
2703 context_map_stage(context, vsampler_idx, start);
2704 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2706 --start;
2707 break;
2710 --start;
2716 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2718 BOOL vs = use_vs(state);
2719 BOOL ps = use_ps(state);
2721 * Rules are:
2722 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2723 * that would be really messy and require shader recompilation
2724 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2725 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2727 if (ps)
2728 context_map_psamplers(context, state);
2729 else
2730 context_map_fixed_function_samplers(context, state);
2732 if (vs)
2733 context_map_vsamplers(context, ps, state);
2736 /* Context activation is done by the caller. */
2737 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2739 const struct wined3d_device *device = context->swapchain->device;
2740 DWORD rt_mask, *cur_mask;
2742 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2744 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2745 rt_mask = find_draw_buffers_mask(context, device);
2746 if (rt_mask != *cur_mask)
2748 context_apply_draw_buffers(context, rt_mask);
2749 *cur_mask = rt_mask;
2753 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2755 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2756 *regnum = WINED3D_FFP_POSITION;
2757 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2758 *regnum = WINED3D_FFP_BLENDWEIGHT;
2759 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2760 *regnum = WINED3D_FFP_BLENDINDICES;
2761 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2762 *regnum = WINED3D_FFP_NORMAL;
2763 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2764 *regnum = WINED3D_FFP_PSIZE;
2765 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2766 *regnum = WINED3D_FFP_DIFFUSE;
2767 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2768 *regnum = WINED3D_FFP_SPECULAR;
2769 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2770 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2771 else
2773 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2774 *regnum = ~0U;
2775 return FALSE;
2778 return TRUE;
2781 /* Context activation is done by the caller. */
2782 void context_stream_info_from_declaration(struct wined3d_context *context,
2783 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2785 /* We need to deal with frequency data! */
2786 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2787 BOOL use_vshader = use_vs(state);
2788 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2789 unsigned int i;
2791 stream_info->use_map = 0;
2792 stream_info->swizzle_map = 0;
2793 stream_info->position_transformed = declaration->position_transformed;
2795 /* Translate the declaration into strided data. */
2796 for (i = 0; i < declaration->element_count; ++i)
2798 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2799 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2800 BOOL stride_used;
2801 unsigned int idx;
2803 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2804 element, i + 1, declaration->element_count);
2806 if (!stream->buffer)
2807 continue;
2809 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2811 if (use_vshader)
2813 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2815 stride_used = FALSE;
2817 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2819 /* TODO: Assuming vertexdeclarations are usually used with the
2820 * same or a similar shader, it might be worth it to store the
2821 * last used output slot and try that one first. */
2822 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2823 element->usage, element->usage_idx, &idx);
2825 else
2827 idx = element->output_slot;
2828 stride_used = TRUE;
2831 else
2833 if (!generic_attributes && !element->ffp_valid)
2835 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2836 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2837 stride_used = FALSE;
2839 else
2841 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2845 if (stride_used)
2847 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2848 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
2849 use_vshader ? "shader": "fixed function", idx,
2850 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2851 element->offset, stream->stride, debug_d3dformat(element->format->id),
2852 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
2854 stream_info->elements[idx].format = element->format;
2855 stream_info->elements[idx].data.buffer_object = 0;
2856 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
2857 stream_info->elements[idx].stride = stream->stride;
2858 stream_info->elements[idx].stream_idx = element->input_slot;
2859 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
2861 stream_info->elements[idx].divisor = 1;
2863 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
2865 stream_info->elements[idx].divisor = element->instance_data_step_rate;
2866 if (!element->instance_data_step_rate)
2867 FIXME("Instance step rate 0 not implemented.\n");
2869 else
2871 stream_info->elements[idx].divisor = 0;
2874 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2875 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2877 stream_info->swizzle_map |= 1 << idx;
2879 stream_info->use_map |= 1 << idx;
2884 /* Context activation is done by the caller. */
2885 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2887 const struct wined3d_gl_info *gl_info = context->gl_info;
2888 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2889 struct wined3d_stream_info *stream_info = &context->stream_info;
2890 DWORD prev_all_vbo = stream_info->all_vbo;
2891 unsigned int i;
2892 WORD map;
2894 context_stream_info_from_declaration(context, state, stream_info);
2896 stream_info->all_vbo = 1;
2897 context->num_buffer_queries = 0;
2898 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2900 struct wined3d_stream_info_element *element;
2901 struct wined3d_bo_address data;
2902 struct wined3d_buffer *buffer;
2904 if (!(map & 1))
2905 continue;
2907 element = &stream_info->elements[i];
2908 buffer = state->streams[element->stream_idx].buffer;
2910 /* We can't use VBOs if the base vertex index is negative. OpenGL
2911 * doesn't accept negative offsets (or rather offsets bigger than the
2912 * VBO, because the pointer is unsigned), so use system memory
2913 * sources. In most sane cases the pointer - offset will still be > 0,
2914 * otherwise it will wrap around to some big value. Hope that with the
2915 * indices the driver wraps it back internally. If not,
2916 * drawStridedSlow is needed, including a vertex buffer path. */
2917 if (state->load_base_vertex_index < 0)
2919 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2920 state->load_base_vertex_index);
2921 element->data.buffer_object = 0;
2922 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
2923 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
2924 FIXME("System memory vertex data load offset is negative!\n");
2926 else
2928 buffer_internal_preload(buffer, context, state);
2929 buffer_get_memory(buffer, context, &data);
2930 element->data.buffer_object = data.buffer_object;
2931 element->data.addr += (ULONG_PTR)data.addr;
2934 if (!element->data.buffer_object)
2935 stream_info->all_vbo = 0;
2937 if (buffer->query)
2938 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2940 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
2943 if (use_vs(state))
2945 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
2947 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
2948 context->use_immediate_mode_draw = TRUE;
2950 else
2952 context->use_immediate_mode_draw = FALSE;
2955 else
2957 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
2958 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2959 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
2961 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
2962 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
2963 context->use_immediate_mode_draw = TRUE;
2964 else
2965 context->use_immediate_mode_draw = FALSE;
2968 if (prev_all_vbo != stream_info->all_vbo)
2969 context_invalidate_state(context, STATE_INDEXBUFFER);
2972 /* Context activation is done by the caller. */
2973 static void context_preload_texture(struct wined3d_context *context,
2974 const struct wined3d_state *state, unsigned int idx)
2976 struct wined3d_texture *texture;
2978 if (!(texture = state->textures[idx]))
2979 return;
2981 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
2984 /* Context activation is done by the caller. */
2985 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
2987 unsigned int i;
2989 if (use_vs(state))
2991 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2993 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
2994 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
2998 if (use_ps(state))
3000 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3002 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3003 context_preload_texture(context, state, i);
3006 else
3008 WORD ffu_map = context->fixed_function_usage_map;
3010 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3012 if (ffu_map & 1)
3013 context_preload_texture(context, state, i);
3018 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3020 const struct wined3d_gl_info *gl_info = context->gl_info;
3021 struct wined3d_shader_sampler_map_entry *entry;
3022 struct wined3d_shader_resource_view *view;
3023 struct wined3d_sampler *sampler;
3024 struct wined3d_texture *texture;
3025 struct wined3d_shader *shader;
3026 unsigned int i, j, count;
3028 static const struct
3030 enum wined3d_shader_type type;
3031 unsigned int base_idx;
3032 unsigned int count;
3034 shader_types[] =
3036 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3037 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3040 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3042 if (!(shader = state->shader[shader_types[i].type]))
3043 continue;
3045 count = shader->reg_maps.sampler_map.count;
3046 if (count > shader_types[i].count)
3048 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3049 shader, count, shader_types[i].count);
3050 count = shader_types[i].count;
3053 for (j = 0; j < count; ++j)
3055 entry = &shader->reg_maps.sampler_map.entries[j];
3057 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3059 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3060 continue;
3063 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3065 FIXME("Buffer shader resources not supported.\n");
3066 continue;
3069 if (!(sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3071 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3072 continue;
3075 texture = wined3d_texture_from_resource(view->resource);
3076 wined3d_texture_load(texture, context, FALSE);
3077 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3078 wined3d_texture_bind(texture, context, FALSE);
3080 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler->name));
3081 checkGLcall("glBindSampler");
3086 /* Context activation is done by the caller. */
3087 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3089 const struct wined3d_state *state = &device->state;
3090 const struct StateEntry *state_table = context->state_table;
3091 const struct wined3d_fb_state *fb = state->fb;
3092 unsigned int i, j;
3093 WORD map;
3095 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3096 fb->render_targets, fb->depth_stencil))
3097 return FALSE;
3099 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3101 context_validate_onscreen_formats(context, fb->depth_stencil);
3104 /* Preload resources before FBO setup. Texture preload in particular may
3105 * result in changes to the current FBO, due to using e.g. FBO blits for
3106 * updating a resource location. */
3107 context_update_tex_unit_map(context, state);
3108 context_preload_textures(context, state);
3109 /* TODO: Right now the dependency on the vertex shader is necessary
3110 * since context_stream_info_from_declaration depends on the reg_maps of
3111 * the current VS but maybe it's possible to relax the coupling in some
3112 * situations at least. */
3113 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3114 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3116 context_update_stream_info(context, state);
3118 else
3120 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3122 if (map & 1)
3123 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3126 if (state->index_buffer)
3128 if (context->stream_info.all_vbo)
3129 buffer_internal_preload(state->index_buffer, context, state);
3130 else
3131 buffer_get_sysmem(state->index_buffer, context);
3134 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3136 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3138 if (state->cb[i][j])
3139 buffer_internal_preload(state->cb[i][j], context, state);
3143 for (i = 0; i < context->numDirtyEntries; ++i)
3145 DWORD rep = context->dirtyArray[i];
3146 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3147 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3148 context->isStateDirty[idx] &= ~(1 << shift);
3149 state_table[rep].apply(context, state, rep);
3152 if (context->shader_update_mask)
3154 device->shader_backend->shader_select(device->shader_priv, context, state);
3155 context->shader_update_mask = 0;
3158 if (context->constant_update_mask)
3160 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3161 context->constant_update_mask = 0;
3164 if (context->update_shader_resource_bindings)
3166 context_bind_shader_resources(context, state);
3167 context->update_shader_resource_bindings = 0;
3170 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3172 context_check_fbo_status(context, GL_FRAMEBUFFER);
3175 context->numDirtyEntries = 0; /* This makes the whole list clean */
3176 context->last_was_blit = FALSE;
3178 return TRUE;
3181 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3183 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3185 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3186 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3188 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3189 * the alpha blend state changes with different render target formats. */
3190 if (!context->current_rt)
3192 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3194 else
3196 const struct wined3d_format *old = context->current_rt->resource.format;
3197 const struct wined3d_format *new = target->resource.format;
3199 if (old->id != new->id)
3201 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3202 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3203 || !(target->container->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3204 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3206 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3207 if ((context->current_rt->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3208 != (target->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3209 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3212 /* When switching away from an offscreen render target, and we're not
3213 * using FBOs, we have to read the drawable into the texture. This is
3214 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3215 * There are some things that need care though. PreLoad needs a GL context,
3216 * and FindContext is called before the context is activated. It also
3217 * has to be called with the old rendertarget active, otherwise a
3218 * wrong drawable is read. */
3219 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3220 && old_render_offscreen && context->current_rt != target)
3222 struct wined3d_texture *texture = context->current_rt->container;
3224 /* Read the back buffer of the old drawable into the destination texture. */
3225 if (texture->texture_srgb.name)
3226 wined3d_texture_load(texture, context, TRUE);
3227 wined3d_texture_load(texture, context, FALSE);
3228 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3232 context->current_rt = target;
3233 context_set_render_offscreen(context, render_offscreen);
3236 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3238 struct wined3d_context *current_context = context_get_current();
3239 struct wined3d_context *context;
3241 TRACE("device %p, target %p.\n", device, target);
3243 if (current_context && current_context->destroyed)
3244 current_context = NULL;
3246 if (!target)
3248 if (current_context
3249 && current_context->current_rt
3250 && current_context->swapchain->device == device)
3252 target = current_context->current_rt;
3254 else
3256 struct wined3d_swapchain *swapchain = device->swapchains[0];
3257 if (swapchain->back_buffers)
3258 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3259 else
3260 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3264 if (current_context && current_context->current_rt == target)
3266 context = current_context;
3268 else if (target->container->swapchain)
3270 TRACE("Rendering onscreen.\n");
3272 context = swapchain_get_context(target->container->swapchain);
3274 else
3276 TRACE("Rendering offscreen.\n");
3278 /* Stay with the current context if possible. Otherwise use the
3279 * context for the primary swapchain. */
3280 if (current_context && current_context->swapchain->device == device)
3281 context = current_context;
3282 else
3283 context = swapchain_get_context(device->swapchains[0]);
3286 context_enter(context);
3287 context_update_window(context);
3288 context_setup_target(context, target);
3289 if (!context->valid) return context;
3291 if (context != current_context)
3293 if (!context_set_current(context))
3294 ERR("Failed to activate the new context.\n");
3296 else if (context->needs_set)
3298 context_set_gl_context(context);
3301 return context;