6f3d60f9ede714572ad418cf391680e0b379e4ea
[reactos.git] / reactos / dll / directx / wine / wined3d / context.c
1 /*
2 * Context and render target management in wined3d
3 *
4 * Copyright 2007-2011, 2013 Stefan Dösinger for CodeWeavers
5 * Copyright 2009-2011 Henri Verbeet for CodeWeavers
6 *
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.
11 *
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.
16 *
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
20 */
21
22 #include "wined3d_private.h"
23
24 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
25 WINE_DECLARE_DEBUG_CHANNEL(d3d_perf);
26 WINE_DECLARE_DEBUG_CHANNEL(d3d_synchronous);
27
28 #define WINED3D_MAX_FBO_ENTRIES 64
29
30 static DWORD wined3d_context_tls_idx;
31
32 /* FBO helper functions */
33
34 /* Context activation is done by the caller. */
35 static void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint fbo)
36 {
37 const struct wined3d_gl_info *gl_info = context->gl_info;
38
39 switch (target)
40 {
41 case GL_READ_FRAMEBUFFER:
42 if (context->fbo_read_binding == fbo) return;
43 context->fbo_read_binding = fbo;
44 break;
45
46 case GL_DRAW_FRAMEBUFFER:
47 if (context->fbo_draw_binding == fbo) return;
48 context->fbo_draw_binding = fbo;
49 break;
50
51 case GL_FRAMEBUFFER:
52 if (context->fbo_read_binding == fbo
53 && context->fbo_draw_binding == fbo) return;
54 context->fbo_read_binding = fbo;
55 context->fbo_draw_binding = fbo;
56 break;
57
58 default:
59 FIXME("Unhandled target %#x.\n", target);
60 break;
61 }
62
63 gl_info->fbo_ops.glBindFramebuffer(target, fbo);
64 checkGLcall("glBindFramebuffer()");
65 }
66
67 /* Context activation is done by the caller. */
68 static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info, GLenum target)
69 {
70 unsigned int i;
71
72 for (i = 0; i < gl_info->limits.buffers; ++i)
73 {
74 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
75 checkGLcall("glFramebufferTexture2D()");
76 }
77 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
78 checkGLcall("glFramebufferTexture2D()");
79
80 gl_info->fbo_ops.glFramebufferTexture2D(target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
81 checkGLcall("glFramebufferTexture2D()");
82 }
83
84 /* Context activation is done by the caller. */
85 static void context_destroy_fbo(struct wined3d_context *context, GLuint fbo)
86 {
87 const struct wined3d_gl_info *gl_info = context->gl_info;
88
89 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
90 context_clean_fbo_attachments(gl_info, GL_FRAMEBUFFER);
91 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
92
93 gl_info->fbo_ops.glDeleteFramebuffers(1, &fbo);
94 checkGLcall("glDeleteFramebuffers()");
95 }
96
97 static void context_attach_depth_stencil_rb(const struct wined3d_gl_info *gl_info,
98 GLenum fbo_target, DWORD format_flags, GLuint rb)
99 {
100 if (format_flags & WINED3DFMT_FLAG_DEPTH)
101 {
102 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rb);
103 checkGLcall("glFramebufferRenderbuffer()");
104 }
105
106 if (format_flags & WINED3DFMT_FLAG_STENCIL)
107 {
108 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rb);
109 checkGLcall("glFramebufferRenderbuffer()");
110 }
111 }
112
113 /* Context activation is done by the caller. */
114 static void context_attach_depth_stencil_fbo(struct wined3d_context *context,
115 GLenum fbo_target, struct wined3d_surface *depth_stencil, DWORD location)
116 {
117 const struct wined3d_gl_info *gl_info = context->gl_info;
118
119 TRACE("Attach depth stencil %p\n", depth_stencil);
120
121 if (depth_stencil)
122 {
123 DWORD format_flags = depth_stencil->container->resource.format_flags;
124
125 if (depth_stencil->current_renderbuffer)
126 {
127 context_attach_depth_stencil_rb(gl_info, fbo_target,
128 format_flags, depth_stencil->current_renderbuffer->id);
129 }
130 else
131 {
132 switch (location)
133 {
134 case WINED3D_LOCATION_TEXTURE_RGB:
135 case WINED3D_LOCATION_TEXTURE_SRGB:
136 wined3d_texture_prepare_texture(depth_stencil->container, context, FALSE);
137
138 if (format_flags & WINED3DFMT_FLAG_DEPTH)
139 {
140 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
141 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
142 depth_stencil->texture_level);
143 checkGLcall("glFramebufferTexture2D()");
144 }
145
146 if (format_flags & WINED3DFMT_FLAG_STENCIL)
147 {
148 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
149 depth_stencil->texture_target, depth_stencil->container->texture_rgb.name,
150 depth_stencil->texture_level);
151 checkGLcall("glFramebufferTexture2D()");
152 }
153 break;
154
155 case WINED3D_LOCATION_RB_MULTISAMPLE:
156 surface_prepare_rb(depth_stencil, gl_info, TRUE);
157 context_attach_depth_stencil_rb(gl_info, fbo_target,
158 format_flags, depth_stencil->rb_multisample);
159 break;
160
161 case WINED3D_LOCATION_RB_RESOLVED:
162 surface_prepare_rb(depth_stencil, gl_info, FALSE);
163 context_attach_depth_stencil_rb(gl_info, fbo_target,
164 format_flags, depth_stencil->rb_resolved);
165 break;
166
167 default:
168 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
169 break;
170 }
171 }
172
173 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
174 {
175 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
176 checkGLcall("glFramebufferTexture2D()");
177 }
178
179 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
180 {
181 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
182 checkGLcall("glFramebufferTexture2D()");
183 }
184 }
185 else
186 {
187 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
188 checkGLcall("glFramebufferTexture2D()");
189
190 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
191 checkGLcall("glFramebufferTexture2D()");
192 }
193 }
194
195 /* Context activation is done by the caller. */
196 static void context_attach_surface_fbo(struct wined3d_context *context,
197 GLenum fbo_target, DWORD idx, struct wined3d_surface *surface, DWORD location)
198 {
199 const struct wined3d_gl_info *gl_info = context->gl_info;
200
201 TRACE("Attach surface %p to %u\n", surface, idx);
202
203 if (surface && surface->resource.format->id != WINED3DFMT_NULL)
204 {
205 BOOL srgb;
206
207 switch (location)
208 {
209 case WINED3D_LOCATION_TEXTURE_RGB:
210 case WINED3D_LOCATION_TEXTURE_SRGB:
211 srgb = location == WINED3D_LOCATION_TEXTURE_SRGB;
212 wined3d_texture_prepare_texture(surface->container, context, srgb);
213 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
214 surface->texture_target, surface_get_texture_name(surface, gl_info, srgb),
215 surface->texture_level);
216 checkGLcall("glFramebufferTexture2D()");
217 break;
218
219 case WINED3D_LOCATION_RB_MULTISAMPLE:
220 surface_prepare_rb(surface, gl_info, TRUE);
221 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
222 GL_RENDERBUFFER, surface->rb_multisample);
223 checkGLcall("glFramebufferRenderbuffer()");
224 break;
225
226 case WINED3D_LOCATION_RB_RESOLVED:
227 surface_prepare_rb(surface, gl_info, FALSE);
228 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_COLOR_ATTACHMENT0 + idx,
229 GL_RENDERBUFFER, surface->rb_resolved);
230 checkGLcall("glFramebufferRenderbuffer()");
231 break;
232
233 default:
234 ERR("Unsupported location %s (%#x).\n", wined3d_debug_location(location), location);
235 break;
236 }
237 }
238 else
239 {
240 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
241 checkGLcall("glFramebufferTexture2D()");
242 }
243 }
244
245 /* Context activation is done by the caller. */
246 void context_check_fbo_status(const struct wined3d_context *context, GLenum target)
247 {
248 const struct wined3d_gl_info *gl_info = context->gl_info;
249 GLenum status;
250
251 if (!FIXME_ON(d3d)) return;
252
253 status = gl_info->fbo_ops.glCheckFramebufferStatus(target);
254 if (status == GL_FRAMEBUFFER_COMPLETE)
255 {
256 TRACE("FBO complete\n");
257 }
258 else
259 {
260 const struct wined3d_surface *attachment;
261 unsigned int i;
262
263 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
264
265 if (!context->current_fbo)
266 {
267 ERR("FBO 0 is incomplete, driver bug?\n");
268 return;
269 }
270
271 FIXME("\tColor Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->color_location),
272 context->current_fbo->color_location);
273 FIXME("\tDepth Stencil Location %s (%#x).\n", wined3d_debug_location(context->current_fbo->ds_location),
274 context->current_fbo->ds_location);
275
276 /* Dump the FBO attachments */
277 for (i = 0; i < gl_info->limits.buffers; ++i)
278 {
279 attachment = context->current_fbo->render_targets[i];
280 if (attachment)
281 {
282 FIXME("\tColor attachment %d: (%p) %s %ux%u %u samples.\n",
283 i, attachment, debug_d3dformat(attachment->resource.format->id),
284 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
285 }
286 }
287 attachment = context->current_fbo->depth_stencil;
288 if (attachment)
289 {
290 FIXME("\tDepth attachment: (%p) %s %ux%u %u samples.\n",
291 attachment, debug_d3dformat(attachment->resource.format->id),
292 attachment->pow2Width, attachment->pow2Height, attachment->resource.multisample_type);
293 }
294 }
295 }
296
297 static inline DWORD context_generate_rt_mask(GLenum buffer)
298 {
299 /* Should take care of all the GL_FRONT/GL_BACK/GL_AUXi/GL_NONE... cases */
300 return buffer ? (1 << 31) | buffer : 0;
301 }
302
303 static inline DWORD context_generate_rt_mask_from_surface(const struct wined3d_surface *target)
304 {
305 return (1 << 31) | surface_get_gl_buffer(target);
306 }
307
308 static struct fbo_entry *context_create_fbo_entry(const struct wined3d_context *context,
309 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
310 DWORD color_location, DWORD ds_location)
311 {
312 const struct wined3d_gl_info *gl_info = context->gl_info;
313 struct fbo_entry *entry;
314
315 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
316 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
317 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
318 entry->depth_stencil = depth_stencil;
319 entry->color_location = color_location;
320 entry->ds_location = ds_location;
321 entry->rt_mask = context_generate_rt_mask(GL_COLOR_ATTACHMENT0);
322 entry->attached = FALSE;
323 gl_info->fbo_ops.glGenFramebuffers(1, &entry->id);
324 checkGLcall("glGenFramebuffers()");
325 TRACE("Created FBO %u.\n", entry->id);
326
327 return entry;
328 }
329
330 /* Context activation is done by the caller. */
331 static void context_reuse_fbo_entry(struct wined3d_context *context, GLenum target,
332 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
333 DWORD color_location, DWORD ds_location, struct fbo_entry *entry)
334 {
335 const struct wined3d_gl_info *gl_info = context->gl_info;
336
337 context_bind_fbo(context, target, entry->id);
338 context_clean_fbo_attachments(gl_info, target);
339
340 memcpy(entry->render_targets, render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
341 entry->depth_stencil = depth_stencil;
342 entry->color_location = color_location;
343 entry->ds_location = ds_location;
344 entry->attached = FALSE;
345 }
346
347 /* Context activation is done by the caller. */
348 static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
349 {
350 if (entry->id)
351 {
352 TRACE("Destroy FBO %u.\n", entry->id);
353 context_destroy_fbo(context, entry->id);
354 }
355 --context->fbo_entry_count;
356 list_remove(&entry->entry);
357 HeapFree(GetProcessHeap(), 0, entry->render_targets);
358 HeapFree(GetProcessHeap(), 0, entry);
359 }
360
361 /* Context activation is done by the caller. */
362 static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context, GLenum target,
363 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
364 DWORD color_location, DWORD ds_location)
365 {
366 const struct wined3d_gl_info *gl_info = context->gl_info;
367 struct fbo_entry *entry;
368
369 if (depth_stencil && render_targets && render_targets[0])
370 {
371 if (depth_stencil->resource.width < render_targets[0]->resource.width ||
372 depth_stencil->resource.height < render_targets[0]->resource.height)
373 {
374 WARN("Depth stencil is smaller than the primary color buffer, disabling\n");
375 depth_stencil = NULL;
376 }
377 }
378
379 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
380 {
381 if (!memcmp(entry->render_targets,
382 render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
383 && entry->depth_stencil == depth_stencil && entry->color_location == color_location
384 && entry->ds_location == ds_location)
385 {
386 list_remove(&entry->entry);
387 list_add_head(&context->fbo_list, &entry->entry);
388 return entry;
389 }
390 }
391
392 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
393 {
394 entry = context_create_fbo_entry(context, render_targets, depth_stencil, color_location, ds_location);
395 list_add_head(&context->fbo_list, &entry->entry);
396 ++context->fbo_entry_count;
397 }
398 else
399 {
400 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
401 context_reuse_fbo_entry(context, target, render_targets, depth_stencil, color_location, ds_location, entry);
402 list_remove(&entry->entry);
403 list_add_head(&context->fbo_list, &entry->entry);
404 }
405
406 return entry;
407 }
408
409 /* Context activation is done by the caller. */
410 static void context_apply_fbo_entry(struct wined3d_context *context, GLenum target, struct fbo_entry *entry)
411 {
412 const struct wined3d_gl_info *gl_info = context->gl_info;
413 unsigned int i;
414 GLuint read_binding, draw_binding;
415 struct wined3d_surface *depth_stencil = entry->depth_stencil;
416
417 if (entry->attached)
418 {
419 context_bind_fbo(context, target, entry->id);
420 return;
421 }
422
423 read_binding = context->fbo_read_binding;
424 draw_binding = context->fbo_draw_binding;
425 context_bind_fbo(context, GL_FRAMEBUFFER, entry->id);
426
427 /* Apply render targets */
428 for (i = 0; i < gl_info->limits.buffers; ++i)
429 {
430 context_attach_surface_fbo(context, target, i, entry->render_targets[i], entry->color_location);
431 }
432
433 if (depth_stencil && entry->render_targets[0]
434 && (depth_stencil->resource.multisample_type
435 != entry->render_targets[0]->resource.multisample_type
436 || depth_stencil->resource.multisample_quality
437 != entry->render_targets[0]->resource.multisample_quality))
438 {
439 WARN("Color multisample type %u and quality %u, depth stencil has %u and %u, disabling ds buffer.\n",
440 entry->render_targets[0]->resource.multisample_quality,
441 entry->render_targets[0]->resource.multisample_type,
442 depth_stencil->resource.multisample_quality, depth_stencil->resource.multisample_type);
443 depth_stencil = NULL;
444 }
445
446 if (depth_stencil)
447 surface_set_compatible_renderbuffer(depth_stencil, entry->render_targets[0]);
448 context_attach_depth_stencil_fbo(context, target, depth_stencil, entry->ds_location);
449
450 /* Set valid read and draw buffer bindings to satisfy pedantic pre-ES2_compatibility
451 * GL contexts requirements. */
452 gl_info->gl_ops.gl.p_glReadBuffer(GL_NONE);
453 context_set_draw_buffer(context, GL_NONE);
454 if (target != GL_FRAMEBUFFER)
455 {
456 if (target == GL_READ_FRAMEBUFFER)
457 context_bind_fbo(context, GL_DRAW_FRAMEBUFFER, draw_binding);
458 else
459 context_bind_fbo(context, GL_READ_FRAMEBUFFER, read_binding);
460 }
461
462 entry->attached = TRUE;
463 }
464
465 /* Context activation is done by the caller. */
466 static void context_apply_fbo_state(struct wined3d_context *context, GLenum target,
467 struct wined3d_surface **render_targets, struct wined3d_surface *depth_stencil,
468 DWORD color_location, DWORD ds_location)
469 {
470 struct fbo_entry *entry, *entry2;
471
472 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
473 {
474 context_destroy_fbo_entry(context, entry);
475 }
476
477 if (context->rebind_fbo)
478 {
479 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
480 context->rebind_fbo = FALSE;
481 }
482
483 if (color_location == WINED3D_LOCATION_DRAWABLE)
484 {
485 context->current_fbo = NULL;
486 context_bind_fbo(context, target, 0);
487 }
488 else
489 {
490 context->current_fbo = context_find_fbo_entry(context, target, render_targets, depth_stencil,
491 color_location, ds_location);
492 context_apply_fbo_entry(context, target, context->current_fbo);
493 }
494 }
495
496 /* Context activation is done by the caller. */
497 void context_apply_fbo_state_blit(struct wined3d_context *context, GLenum target,
498 struct wined3d_surface *render_target, struct wined3d_surface *depth_stencil, DWORD location)
499 {
500 UINT clear_size = (context->gl_info->limits.buffers - 1) * sizeof(*context->blit_targets);
501
502 context->blit_targets[0] = render_target;
503 if (clear_size)
504 memset(&context->blit_targets[1], 0, clear_size);
505 context_apply_fbo_state(context, target, context->blit_targets, depth_stencil, location, location);
506 }
507
508 /* Context activation is done by the caller. */
509 void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
510 {
511 const struct wined3d_gl_info *gl_info = context->gl_info;
512
513 if (context->free_occlusion_query_count)
514 {
515 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
516 }
517 else
518 {
519 if (gl_info->supported[ARB_OCCLUSION_QUERY])
520 {
521 GL_EXTCALL(glGenQueries(1, &query->id));
522 checkGLcall("glGenQueries");
523
524 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
525 }
526 else
527 {
528 WARN("Occlusion queries not supported, not allocating query id.\n");
529 query->id = 0;
530 }
531 }
532
533 query->context = context;
534 list_add_head(&context->occlusion_queries, &query->entry);
535 }
536
537 void context_free_occlusion_query(struct wined3d_occlusion_query *query)
538 {
539 struct wined3d_context *context = query->context;
540
541 list_remove(&query->entry);
542 query->context = NULL;
543
544 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
545 {
546 UINT new_size = context->free_occlusion_query_size << 1;
547 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
548 new_size * sizeof(*context->free_occlusion_queries));
549
550 if (!new_data)
551 {
552 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
553 return;
554 }
555
556 context->free_occlusion_query_size = new_size;
557 context->free_occlusion_queries = new_data;
558 }
559
560 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
561 }
562
563 /* Context activation is done by the caller. */
564 void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
565 {
566 const struct wined3d_gl_info *gl_info = context->gl_info;
567
568 if (context->free_event_query_count)
569 {
570 query->object = context->free_event_queries[--context->free_event_query_count];
571 }
572 else
573 {
574 if (gl_info->supported[ARB_SYNC])
575 {
576 /* Using ARB_sync, not much to do here. */
577 query->object.sync = NULL;
578 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
579 }
580 else if (gl_info->supported[APPLE_FENCE])
581 {
582 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
583 checkGLcall("glGenFencesAPPLE");
584
585 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
586 }
587 else if(gl_info->supported[NV_FENCE])
588 {
589 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
590 checkGLcall("glGenFencesNV");
591
592 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
593 }
594 else
595 {
596 WARN("Event queries not supported, not allocating query id.\n");
597 query->object.id = 0;
598 }
599 }
600
601 query->context = context;
602 list_add_head(&context->event_queries, &query->entry);
603 }
604
605 void context_free_event_query(struct wined3d_event_query *query)
606 {
607 struct wined3d_context *context = query->context;
608
609 list_remove(&query->entry);
610 query->context = NULL;
611
612 if (context->free_event_query_count >= context->free_event_query_size - 1)
613 {
614 UINT new_size = context->free_event_query_size << 1;
615 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
616 new_size * sizeof(*context->free_event_queries));
617
618 if (!new_data)
619 {
620 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
621 return;
622 }
623
624 context->free_event_query_size = new_size;
625 context->free_event_queries = new_data;
626 }
627
628 context->free_event_queries[context->free_event_query_count++] = query->object;
629 }
630
631 /* Context activation is done by the caller. */
632 void context_alloc_timestamp_query(struct wined3d_context *context, struct wined3d_timestamp_query *query)
633 {
634 const struct wined3d_gl_info *gl_info = context->gl_info;
635
636 if (context->free_timestamp_query_count)
637 {
638 query->id = context->free_timestamp_queries[--context->free_timestamp_query_count];
639 }
640 else
641 {
642 GL_EXTCALL(glGenQueries(1, &query->id));
643 checkGLcall("glGenQueries");
644
645 TRACE("Allocated timestamp query %u in context %p.\n", query->id, context);
646 }
647
648 query->context = context;
649 list_add_head(&context->timestamp_queries, &query->entry);
650 }
651
652 void context_free_timestamp_query(struct wined3d_timestamp_query *query)
653 {
654 struct wined3d_context *context = query->context;
655
656 list_remove(&query->entry);
657 query->context = NULL;
658
659 if (context->free_timestamp_query_count >= context->free_timestamp_query_size - 1)
660 {
661 UINT new_size = context->free_timestamp_query_size << 1;
662 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_timestamp_queries,
663 new_size * sizeof(*context->free_timestamp_queries));
664
665 if (!new_data)
666 {
667 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
668 return;
669 }
670
671 context->free_timestamp_query_size = new_size;
672 context->free_timestamp_queries = new_data;
673 }
674
675 context->free_timestamp_queries[context->free_timestamp_query_count++] = query->id;
676 }
677
678 typedef void (context_fbo_entry_func_t)(struct wined3d_context *context, struct fbo_entry *entry);
679
680 static void context_enum_surface_fbo_entries(const struct wined3d_device *device,
681 const struct wined3d_surface *surface, context_fbo_entry_func_t *callback)
682 {
683 UINT i;
684
685 for (i = 0; i < device->context_count; ++i)
686 {
687 struct wined3d_context *context = device->contexts[i];
688 const struct wined3d_gl_info *gl_info = context->gl_info;
689 struct fbo_entry *entry, *entry2;
690
691 if (context->current_rt == surface) context->current_rt = NULL;
692
693 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
694 {
695 UINT j;
696
697 if (entry->depth_stencil == surface)
698 {
699 callback(context, entry);
700 continue;
701 }
702
703 for (j = 0; j < gl_info->limits.buffers; ++j)
704 {
705 if (entry->render_targets[j] == surface)
706 {
707 callback(context, entry);
708 break;
709 }
710 }
711 }
712 }
713 }
714
715 static void context_queue_fbo_entry_destruction(struct wined3d_context *context, struct fbo_entry *entry)
716 {
717 list_remove(&entry->entry);
718 list_add_head(&context->fbo_destroy_list, &entry->entry);
719 }
720
721 void context_resource_released(const struct wined3d_device *device,
722 struct wined3d_resource *resource, enum wined3d_resource_type type)
723 {
724 if (!device->d3d_initialized) return;
725
726 switch (type)
727 {
728 case WINED3D_RTYPE_SURFACE:
729 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
730 context_queue_fbo_entry_destruction);
731 break;
732
733 default:
734 break;
735 }
736 }
737
738 static void context_detach_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
739 {
740 entry->attached = FALSE;
741 }
742
743 void context_resource_unloaded(const struct wined3d_device *device,
744 struct wined3d_resource *resource, enum wined3d_resource_type type)
745 {
746 switch (type)
747 {
748 case WINED3D_RTYPE_SURFACE:
749 context_enum_surface_fbo_entries(device, surface_from_resource(resource),
750 context_detach_fbo_entry);
751 break;
752
753 default:
754 break;
755 }
756 }
757
758 void context_surface_update(struct wined3d_context *context, const struct wined3d_surface *surface)
759 {
760 const struct wined3d_gl_info *gl_info = context->gl_info;
761 struct fbo_entry *entry = context->current_fbo;
762 unsigned int i;
763
764 if (!entry || context->rebind_fbo) return;
765
766 for (i = 0; i < gl_info->limits.buffers; ++i)
767 {
768 if (surface == entry->render_targets[i])
769 {
770 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
771 context->rebind_fbo = TRUE;
772 return;
773 }
774 }
775
776 if (surface == entry->depth_stencil)
777 {
778 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
779 context->rebind_fbo = TRUE;
780 }
781 }
782
783 static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
784 {
785 int current = GetPixelFormat(dc);
786
787 if (current == format) return TRUE;
788
789 if (!current)
790 {
791 if (!SetPixelFormat(dc, format, NULL))
792 {
793 /* This may also happen if the dc belongs to a destroyed window. */
794 WARN("Failed to set pixel format %d on device context %p, last error %#x.\n",
795 format, dc, GetLastError());
796 return FALSE;
797 }
798 return TRUE;
799 }
800
801 /* By default WGL doesn't allow pixel format adjustments but we need it
802 * here. For this reason there's a Wine specific wglSetPixelFormat()
803 * which allows us to set the pixel format multiple times. Only use it
804 * when really needed. */
805 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
806 {
807 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format)))
808 {
809 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
810 format, dc);
811 return FALSE;
812 }
813 return TRUE;
814 }
815
816 /* OpenGL doesn't allow pixel format adjustments. Print an error and
817 * continue using the old format. There's a big chance that the old
818 * format works although with a performance hit and perhaps rendering
819 * errors. */
820 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
821 format, dc, current);
822 return TRUE;
823 }
824
825 static BOOL context_set_gl_context(struct wined3d_context *ctx)
826 {
827 struct wined3d_swapchain *swapchain = ctx->swapchain;
828 BOOL backup = FALSE;
829
830 if (!context_set_pixel_format(ctx->gl_info, ctx->hdc, ctx->pixel_format))
831 {
832 WARN("Failed to set pixel format %d on device context %p.\n",
833 ctx->pixel_format, ctx->hdc);
834 backup = TRUE;
835 }
836
837 if (backup || !wglMakeCurrent(ctx->hdc, ctx->glCtx))
838 {
839 HDC dc;
840
841 WARN("Failed to make GL context %p current on device context %p, last error %#x.\n",
842 ctx->glCtx, ctx->hdc, GetLastError());
843 ctx->valid = 0;
844 WARN("Trying fallback to the backup window.\n");
845
846 /* FIXME: If the context is destroyed it's no longer associated with
847 * a swapchain, so we can't use the swapchain to get a backup dc. To
848 * make this work windowless contexts would need to be handled by the
849 * device. */
850 if (ctx->destroyed)
851 {
852 FIXME("Unable to get backup dc for destroyed context %p.\n", ctx);
853 context_set_current(NULL);
854 return FALSE;
855 }
856
857 if (!(dc = swapchain_get_backup_dc(swapchain)))
858 {
859 context_set_current(NULL);
860 return FALSE;
861 }
862
863 if (!context_set_pixel_format(ctx->gl_info, dc, ctx->pixel_format))
864 {
865 ERR("Failed to set pixel format %d on device context %p.\n",
866 ctx->pixel_format, dc);
867 context_set_current(NULL);
868 return FALSE;
869 }
870
871 if (!wglMakeCurrent(dc, ctx->glCtx))
872 {
873 ERR("Fallback to backup window (dc %p) failed too, last error %#x.\n",
874 dc, GetLastError());
875 context_set_current(NULL);
876 return FALSE;
877 }
878
879 ctx->valid = 1;
880 }
881 ctx->needs_set = 0;
882 return TRUE;
883 }
884
885 static void context_restore_gl_context(const struct wined3d_gl_info *gl_info, HDC dc, HGLRC gl_ctx, int pf)
886 {
887 if (!context_set_pixel_format(gl_info, dc, pf))
888 {
889 ERR("Failed to restore pixel format %d on device context %p.\n", pf, dc);
890 context_set_current(NULL);
891 return;
892 }
893
894 if (!wglMakeCurrent(dc, gl_ctx))
895 {
896 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
897 gl_ctx, dc, GetLastError());
898 context_set_current(NULL);
899 }
900 }
901
902 static void context_update_window(struct wined3d_context *context)
903 {
904 if (context->win_handle == context->swapchain->win_handle)
905 return;
906
907 TRACE("Updating context %p window from %p to %p.\n",
908 context, context->win_handle, context->swapchain->win_handle);
909
910 if (context->hdc)
911 wined3d_release_dc(context->win_handle, context->hdc);
912
913 context->win_handle = context->swapchain->win_handle;
914 context->needs_set = 1;
915 context->valid = 1;
916
917 if (!(context->hdc = GetDC(context->win_handle)))
918 {
919 ERR("Failed to get a device context for window %p.\n", context->win_handle);
920 context->valid = 0;
921 }
922 }
923
924 static void context_destroy_gl_resources(struct wined3d_context *context)
925 {
926 const struct wined3d_gl_info *gl_info = context->gl_info;
927 struct wined3d_timestamp_query *timestamp_query;
928 struct wined3d_occlusion_query *occlusion_query;
929 struct wined3d_event_query *event_query;
930 struct fbo_entry *entry, *entry2;
931 HGLRC restore_ctx;
932 HDC restore_dc;
933 unsigned int i;
934 int restore_pf;
935
936 restore_ctx = wglGetCurrentContext();
937 restore_dc = wglGetCurrentDC();
938 restore_pf = GetPixelFormat(restore_dc);
939
940 if (restore_ctx == context->glCtx)
941 restore_ctx = NULL;
942 else if (context->valid)
943 context_set_gl_context(context);
944
945 LIST_FOR_EACH_ENTRY(timestamp_query, &context->timestamp_queries, struct wined3d_timestamp_query, entry)
946 {
947 if (context->valid)
948 GL_EXTCALL(glDeleteQueries(1, &timestamp_query->id));
949 timestamp_query->context = NULL;
950 }
951
952 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
953 {
954 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
955 GL_EXTCALL(glDeleteQueries(1, &occlusion_query->id));
956 occlusion_query->context = NULL;
957 }
958
959 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
960 {
961 if (context->valid)
962 {
963 if (gl_info->supported[ARB_SYNC])
964 {
965 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
966 }
967 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
968 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
969 }
970 event_query->context = NULL;
971 }
972
973 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
974 {
975 if (!context->valid) entry->id = 0;
976 context_destroy_fbo_entry(context, entry);
977 }
978
979 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
980 {
981 if (!context->valid) entry->id = 0;
982 context_destroy_fbo_entry(context, entry);
983 }
984
985 if (context->valid)
986 {
987 if (context->dummy_arbfp_prog)
988 {
989 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
990 }
991
992 if (gl_info->supported[ARB_TIMER_QUERY])
993 GL_EXTCALL(glDeleteQueries(context->free_timestamp_query_count, context->free_timestamp_queries));
994
995 if (gl_info->supported[ARB_OCCLUSION_QUERY])
996 GL_EXTCALL(glDeleteQueries(context->free_occlusion_query_count, context->free_occlusion_queries));
997
998 if (gl_info->supported[ARB_SYNC])
999 {
1000 for (i = 0; i < context->free_event_query_count; ++i)
1001 {
1002 GL_EXTCALL(glDeleteSync(context->free_event_queries[i].sync));
1003 }
1004 }
1005 else if (gl_info->supported[APPLE_FENCE])
1006 {
1007 for (i = 0; i < context->free_event_query_count; ++i)
1008 {
1009 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1010 }
1011 }
1012 else if (gl_info->supported[NV_FENCE])
1013 {
1014 for (i = 0; i < context->free_event_query_count; ++i)
1015 {
1016 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1017 }
1018 }
1019
1020 checkGLcall("context cleanup");
1021 }
1022
1023 HeapFree(GetProcessHeap(), 0, context->free_timestamp_queries);
1024 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1025 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1026
1027 if (restore_ctx)
1028 {
1029 context_restore_gl_context(gl_info, restore_dc, restore_ctx, restore_pf);
1030 }
1031 else if (wglGetCurrentContext() && !wglMakeCurrent(NULL, NULL))
1032 {
1033 ERR("Failed to disable GL context.\n");
1034 }
1035
1036 wined3d_release_dc(context->win_handle, context->hdc);
1037
1038 if (!wglDeleteContext(context->glCtx))
1039 {
1040 DWORD err = GetLastError();
1041 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1042 }
1043 }
1044
1045 DWORD context_get_tls_idx(void)
1046 {
1047 return wined3d_context_tls_idx;
1048 }
1049
1050 void context_set_tls_idx(DWORD idx)
1051 {
1052 wined3d_context_tls_idx = idx;
1053 }
1054
1055 struct wined3d_context *context_get_current(void)
1056 {
1057 return TlsGetValue(wined3d_context_tls_idx);
1058 }
1059
1060 BOOL context_set_current(struct wined3d_context *ctx)
1061 {
1062 struct wined3d_context *old = context_get_current();
1063
1064 if (old == ctx)
1065 {
1066 TRACE("Already using D3D context %p.\n", ctx);
1067 return TRUE;
1068 }
1069
1070 if (old)
1071 {
1072 if (old->destroyed)
1073 {
1074 TRACE("Switching away from destroyed context %p.\n", old);
1075 context_destroy_gl_resources(old);
1076 HeapFree(GetProcessHeap(), 0, (void *)old->gl_info);
1077 HeapFree(GetProcessHeap(), 0, old);
1078 }
1079 else
1080 {
1081 old->current = 0;
1082 }
1083 }
1084
1085 if (ctx)
1086 {
1087 if (!ctx->valid)
1088 {
1089 ERR("Trying to make invalid context %p current\n", ctx);
1090 return FALSE;
1091 }
1092
1093 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1094 if (!context_set_gl_context(ctx))
1095 return FALSE;
1096 ctx->current = 1;
1097 }
1098 else if(wglGetCurrentContext())
1099 {
1100 TRACE("Clearing current D3D context.\n");
1101 if (!wglMakeCurrent(NULL, NULL))
1102 {
1103 DWORD err = GetLastError();
1104 ERR("Failed to clear current GL context, last error %#x.\n", err);
1105 TlsSetValue(wined3d_context_tls_idx, NULL);
1106 return FALSE;
1107 }
1108 }
1109
1110 return TlsSetValue(wined3d_context_tls_idx, ctx);
1111 }
1112
1113 void context_release(struct wined3d_context *context)
1114 {
1115 TRACE("Releasing context %p, level %u.\n", context, context->level);
1116
1117 if (WARN_ON(d3d))
1118 {
1119 if (!context->level)
1120 WARN("Context %p is not active.\n", context);
1121 else if (context != context_get_current())
1122 WARN("Context %p is not the current context.\n", context);
1123 }
1124
1125 if (!--context->level && context->restore_ctx)
1126 {
1127 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1128 context_restore_gl_context(context->gl_info, context->restore_dc, context->restore_ctx, context->restore_pf);
1129 context->restore_ctx = NULL;
1130 context->restore_dc = NULL;
1131 }
1132 }
1133
1134 static void context_enter(struct wined3d_context *context)
1135 {
1136 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1137
1138 if (!context->level++)
1139 {
1140 const struct wined3d_context *current_context = context_get_current();
1141 HGLRC current_gl = wglGetCurrentContext();
1142
1143 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1144 {
1145 TRACE("Another GL context (%p on device context %p) is already current.\n",
1146 current_gl, wglGetCurrentDC());
1147 context->restore_ctx = current_gl;
1148 context->restore_dc = wglGetCurrentDC();
1149 context->restore_pf = GetPixelFormat(context->restore_dc);
1150 context->needs_set = 1;
1151 }
1152 }
1153 }
1154
1155 void context_invalidate_state(struct wined3d_context *context, DWORD state)
1156 {
1157 DWORD rep = context->state_table[state].representative;
1158 DWORD idx;
1159 BYTE shift;
1160
1161 if (isStateDirty(context, rep)) return;
1162
1163 context->dirtyArray[context->numDirtyEntries++] = rep;
1164 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1165 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1166 context->isStateDirty[idx] |= (1 << shift);
1167 }
1168
1169 /* This function takes care of wined3d pixel format selection. */
1170 static int context_choose_pixel_format(const struct wined3d_device *device, HDC hdc,
1171 const struct wined3d_format *color_format, const struct wined3d_format *ds_format,
1172 BOOL auxBuffers, BOOL findCompatible)
1173 {
1174 int iPixelFormat=0;
1175 BYTE redBits, greenBits, blueBits, alphaBits, colorBits;
1176 BYTE depthBits=0, stencilBits=0;
1177 unsigned int current_value;
1178 unsigned int cfg_count = device->adapter->cfg_count;
1179 unsigned int i;
1180
1181 TRACE("device %p, dc %p, color_format %s, ds_format %s, aux_buffers %#x, find_compatible %#x.\n",
1182 device, hdc, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id),
1183 auxBuffers, findCompatible);
1184
1185 if (!getColorBits(color_format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1186 {
1187 ERR("Unable to get color bits for format %s (%#x)!\n",
1188 debug_d3dformat(color_format->id), color_format->id);
1189 return 0;
1190 }
1191
1192 getDepthStencilBits(ds_format, &depthBits, &stencilBits);
1193
1194 current_value = 0;
1195 for (i = 0; i < cfg_count; ++i)
1196 {
1197 const struct wined3d_pixel_format *cfg = &device->adapter->cfgs[i];
1198 unsigned int value;
1199
1200 /* For now only accept RGBA formats. Perhaps some day we will
1201 * allow floating point formats for pbuffers. */
1202 if (cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1203 continue;
1204 /* In window mode we need a window drawable format and double buffering. */
1205 if (!(cfg->windowDrawable && cfg->doubleBuffer))
1206 continue;
1207 if (cfg->redSize < redBits)
1208 continue;
1209 if (cfg->greenSize < greenBits)
1210 continue;
1211 if (cfg->blueSize < blueBits)
1212 continue;
1213 if (cfg->alphaSize < alphaBits)
1214 continue;
1215 if (cfg->depthSize < depthBits)
1216 continue;
1217 if (stencilBits && cfg->stencilSize != stencilBits)
1218 continue;
1219 /* Check multisampling support. */
1220 if (cfg->numSamples)
1221 continue;
1222
1223 value = 1;
1224 /* We try to locate a format which matches our requirements exactly. In case of
1225 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1226 if (cfg->depthSize == depthBits)
1227 value += 1;
1228 if (cfg->stencilSize == stencilBits)
1229 value += 2;
1230 if (cfg->alphaSize == alphaBits)
1231 value += 4;
1232 /* We like to have aux buffers in backbuffer mode */
1233 if (auxBuffers && cfg->auxBuffers)
1234 value += 8;
1235 if (cfg->redSize == redBits
1236 && cfg->greenSize == greenBits
1237 && cfg->blueSize == blueBits)
1238 value += 16;
1239
1240 if (value > current_value)
1241 {
1242 iPixelFormat = cfg->iPixelFormat;
1243 current_value = value;
1244 }
1245 }
1246
1247 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1248 if(!iPixelFormat && !findCompatible) {
1249 ERR("Can't find a suitable iPixelFormat\n");
1250 return FALSE;
1251 } else if(!iPixelFormat) {
1252 PIXELFORMATDESCRIPTOR pfd;
1253
1254 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1255 /* PixelFormat selection */
1256 ZeroMemory(&pfd, sizeof(pfd));
1257 pfd.nSize = sizeof(pfd);
1258 pfd.nVersion = 1;
1259 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1260 pfd.iPixelType = PFD_TYPE_RGBA;
1261 pfd.cAlphaBits = alphaBits;
1262 pfd.cColorBits = colorBits;
1263 pfd.cDepthBits = depthBits;
1264 pfd.cStencilBits = stencilBits;
1265 pfd.iLayerType = PFD_MAIN_PLANE;
1266
1267 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1268 if(!iPixelFormat) {
1269 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1270 ERR("Can't find a suitable iPixelFormat\n");
1271 return FALSE;
1272 }
1273 }
1274
1275 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1276 iPixelFormat, debug_d3dformat(color_format->id), debug_d3dformat(ds_format->id));
1277 return iPixelFormat;
1278 }
1279
1280 /* Context activation is done by the caller. */
1281 static void bind_dummy_textures(const struct wined3d_device *device, const struct wined3d_context *context)
1282 {
1283 const struct wined3d_gl_info *gl_info = context->gl_info;
1284 unsigned int i, count = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers);
1285
1286 for (i = 0; i < count; ++i)
1287 {
1288 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + i));
1289 checkGLcall("glActiveTexture");
1290
1291 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[i]);
1292 checkGLcall("glBindTexture");
1293
1294 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1295 {
1296 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[i]);
1297 checkGLcall("glBindTexture");
1298 }
1299
1300 if (gl_info->supported[EXT_TEXTURE3D])
1301 {
1302 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[i]);
1303 checkGLcall("glBindTexture");
1304 }
1305
1306 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1307 {
1308 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[i]);
1309 checkGLcall("glBindTexture");
1310 }
1311 }
1312 }
1313
1314 static BOOL context_debug_output_enabled(const struct wined3d_gl_info *gl_info)
1315 {
1316 return gl_info->supported[ARB_DEBUG_OUTPUT]
1317 && (ERR_ON(d3d) || FIXME_ON(d3d) || WARN_ON(d3d_perf));
1318 }
1319
1320 static void WINE_GLAPI wined3d_debug_callback(GLenum source, GLenum type, GLuint id,
1321 GLenum severity, GLsizei length, const char *message, void *ctx)
1322 {
1323 switch (type)
1324 {
1325 case GL_DEBUG_TYPE_ERROR_ARB:
1326 ERR("%p: %s.\n", ctx, debugstr_an(message, length));
1327 break;
1328
1329 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB:
1330 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB:
1331 case GL_DEBUG_TYPE_PORTABILITY_ARB:
1332 FIXME("%p: %s.\n", ctx, debugstr_an(message, length));
1333 break;
1334
1335 case GL_DEBUG_TYPE_PERFORMANCE_ARB:
1336 WARN_(d3d_perf)("%p: %s.\n", ctx, debugstr_an(message, length));
1337 break;
1338
1339 default:
1340 FIXME("ctx %p, type %#x: %s.\n", ctx, type, debugstr_an(message, length));
1341 break;
1342 }
1343 }
1344
1345 HGLRC context_create_wgl_attribs(const struct wined3d_gl_info *gl_info, HDC hdc, HGLRC share_ctx)
1346 {
1347 HGLRC ctx;
1348 unsigned int ctx_attrib_idx = 0;
1349 GLint ctx_attribs[7], ctx_flags = 0;
1350
1351 if (context_debug_output_enabled(gl_info))
1352 ctx_flags = WGL_CONTEXT_DEBUG_BIT_ARB;
1353 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
1354 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version >> 16;
1355 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_MINOR_VERSION_ARB;
1356 ctx_attribs[ctx_attrib_idx++] = gl_info->selected_gl_version & 0xffff;
1357 if (gl_info->selected_gl_version >= MAKEDWORD_VERSION(3, 2))
1358 ctx_flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1359 if (ctx_flags)
1360 {
1361 ctx_attribs[ctx_attrib_idx++] = WGL_CONTEXT_FLAGS_ARB;
1362 ctx_attribs[ctx_attrib_idx++] = ctx_flags;
1363 }
1364 ctx_attribs[ctx_attrib_idx] = 0;
1365
1366 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1367 {
1368 if (ctx_flags & WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB)
1369 {
1370 ctx_attribs[ctx_attrib_idx - 1] &= ~WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
1371 if (!(ctx = gl_info->p_wglCreateContextAttribsARB(hdc, share_ctx, ctx_attribs)))
1372 WARN("Failed to create a WGL context with wglCreateContextAttribsARB, last error %#x.\n",
1373 GetLastError());
1374 }
1375 }
1376 return ctx;
1377 }
1378
1379 struct wined3d_context *context_create(struct wined3d_swapchain *swapchain,
1380 struct wined3d_surface *target, const struct wined3d_format *ds_format)
1381 {
1382 struct wined3d_device *device = swapchain->device;
1383 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1384 const struct wined3d_format *color_format;
1385 struct wined3d_context *ret;
1386 BOOL auxBuffers = FALSE;
1387 HGLRC ctx, share_ctx;
1388 int pixel_format;
1389 unsigned int s;
1390 int swap_interval;
1391 DWORD state;
1392 HDC hdc;
1393
1394 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1395
1396 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1397 if (!ret)
1398 return NULL;
1399
1400 ret->blit_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1401 gl_info->limits.buffers * sizeof(*ret->blit_targets));
1402 if (!ret->blit_targets)
1403 goto out;
1404
1405 ret->draw_buffers = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1406 gl_info->limits.buffers * sizeof(*ret->draw_buffers));
1407 if (!ret->draw_buffers)
1408 goto out;
1409
1410 ret->free_timestamp_query_size = 4;
1411 ret->free_timestamp_queries = HeapAlloc(GetProcessHeap(), 0,
1412 ret->free_timestamp_query_size * sizeof(*ret->free_timestamp_queries));
1413 if (!ret->free_timestamp_queries)
1414 goto out;
1415 list_init(&ret->timestamp_queries);
1416
1417 ret->free_occlusion_query_size = 4;
1418 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1419 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1420 if (!ret->free_occlusion_queries)
1421 goto out;
1422
1423 list_init(&ret->occlusion_queries);
1424
1425 ret->free_event_query_size = 4;
1426 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1427 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1428 if (!ret->free_event_queries)
1429 goto out;
1430
1431 list_init(&ret->event_queries);
1432 list_init(&ret->fbo_list);
1433 list_init(&ret->fbo_destroy_list);
1434
1435 if (!device->shader_backend->shader_allocate_context_data(ret))
1436 {
1437 ERR("Failed to allocate shader backend context data.\n");
1438 goto out;
1439 }
1440 if (!device->adapter->fragment_pipe->allocate_context_data(ret))
1441 {
1442 ERR("Failed to allocate fragment pipeline context data.\n");
1443 goto out;
1444 }
1445
1446 #if defined(STAGING_CSMT)
1447 ret->current_fb.render_targets = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1448 sizeof(*ret->current_fb.render_targets) * gl_info->limits.buffers);
1449 ret->current_fb.rt_size = gl_info->limits.buffers;
1450 if (!ret->current_fb.render_targets)
1451 goto out;
1452 if (device->context_count)
1453 ret->offscreenBuffer = device->contexts[0]->offscreenBuffer;
1454
1455 #endif /* STAGING_CSMT */
1456 /* Initialize the texture unit mapping to a 1:1 mapping */
1457 for (s = 0; s < MAX_COMBINED_SAMPLERS; ++s)
1458 {
1459 if (s < gl_info->limits.fragment_samplers)
1460 {
1461 ret->tex_unit_map[s] = s;
1462 ret->rev_tex_unit_map[s] = s;
1463 }
1464 else
1465 {
1466 ret->tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1467 ret->rev_tex_unit_map[s] = WINED3D_UNMAPPED_STAGE;
1468 }
1469 }
1470
1471 if (!(hdc = GetDC(swapchain->win_handle)))
1472 {
1473 WARN("Failed to retrieve device context, trying swapchain backup.\n");
1474
1475 if (!(hdc = swapchain_get_backup_dc(swapchain)))
1476 {
1477 ERR("Failed to retrieve a device context.\n");
1478 goto out;
1479 }
1480 }
1481
1482 color_format = target->resource.format;
1483
1484 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1485 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1486 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1487 {
1488 auxBuffers = TRUE;
1489
1490 if (color_format->id == WINED3DFMT_B4G4R4X4_UNORM)
1491 color_format = wined3d_get_format(gl_info, WINED3DFMT_B4G4R4A4_UNORM);
1492 else if (color_format->id == WINED3DFMT_B8G8R8X8_UNORM)
1493 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1494 }
1495
1496 /* DirectDraw supports 8bit paletted render targets and these are used by
1497 * old games like StarCraft and C&C. Most modern hardware doesn't support
1498 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1499 * conversion (ab)uses the alpha component for storing the palette index.
1500 * For this reason we require a format with 8bit alpha, so request
1501 * A8R8G8B8. */
1502 if (color_format->id == WINED3DFMT_P8_UINT)
1503 color_format = wined3d_get_format(gl_info, WINED3DFMT_B8G8R8A8_UNORM);
1504
1505 /* Try to find a pixel format which matches our requirements. */
1506 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, FALSE);
1507
1508 /* Try to locate a compatible format if we weren't able to find anything. */
1509 if (!pixel_format)
1510 {
1511 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1512 pixel_format = context_choose_pixel_format(device, hdc, color_format, ds_format, auxBuffers, TRUE);
1513 }
1514
1515 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1516 if (!pixel_format)
1517 {
1518 ERR("Can't find a suitable pixel format.\n");
1519 goto out;
1520 }
1521
1522 context_enter(ret);
1523
1524 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1525 {
1526 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1527 context_release(ret);
1528 goto out;
1529 }
1530
1531 share_ctx = device->context_count ? device->contexts[0]->glCtx : NULL;
1532 if (gl_info->p_wglCreateContextAttribsARB)
1533 {
1534 if (!(ctx = context_create_wgl_attribs(gl_info, hdc, share_ctx)))
1535 goto out;
1536 }
1537 else
1538 {
1539 if (!(ctx = wglCreateContext(hdc)))
1540 {
1541 ERR("Failed to create a WGL context.\n");
1542 context_release(ret);
1543 goto out;
1544 }
1545
1546 if (share_ctx && !wglShareLists(share_ctx, ctx))
1547 {
1548 ERR("wglShareLists(%p, %p) failed, last error %#x.\n", share_ctx, ctx, GetLastError());
1549 context_release(ret);
1550 if (!wglDeleteContext(ctx))
1551 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1552 goto out;
1553 }
1554 }
1555
1556 if (!device_context_add(device, ret))
1557 {
1558 ERR("Failed to add the newly created context to the context list\n");
1559 context_release(ret);
1560 if (!wglDeleteContext(ctx))
1561 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1562 goto out;
1563 }
1564
1565 ret->gl_info = gl_info;
1566 ret->d3d_info = &device->adapter->d3d_info;
1567 ret->state_table = device->StateTable;
1568
1569 /* Mark all states dirty to force a proper initialization of the states
1570 * on the first use of the context. */
1571 for (state = 0; state <= STATE_HIGHEST; ++state)
1572 {
1573 if (ret->state_table[state].representative)
1574 context_invalidate_state(ret, state);
1575 }
1576
1577 ret->swapchain = swapchain;
1578 ret->current_rt = target;
1579 ret->tid = GetCurrentThreadId();
1580
1581 ret->render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
1582 ret->draw_buffers_mask = context_generate_rt_mask(GL_BACK);
1583 ret->valid = 1;
1584
1585 ret->glCtx = ctx;
1586 ret->win_handle = swapchain->win_handle;
1587 ret->hdc = hdc;
1588 ret->pixel_format = pixel_format;
1589 ret->needs_set = 1;
1590
1591 /* Set up the context defaults */
1592 if (!context_set_current(ret))
1593 {
1594 ERR("Cannot activate context to set up defaults.\n");
1595 device_context_remove(device, ret);
1596 context_release(ret);
1597 if (!wglDeleteContext(ctx))
1598 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, GetLastError());
1599 goto out;
1600 }
1601
1602 if (context_debug_output_enabled(gl_info))
1603 {
1604 GL_EXTCALL(glDebugMessageCallbackARB(wined3d_debug_callback, ret));
1605 if (TRACE_ON(d3d_synchronous))
1606 gl_info->gl_ops.gl.p_glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
1607 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_FALSE));
1608 if (ERR_ON(d3d))
1609 {
1610 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_ERROR_ARB,
1611 GL_DONT_CARE, 0, NULL, GL_TRUE));
1612 }
1613 if (FIXME_ON(d3d))
1614 {
1615 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,
1616 GL_DONT_CARE, 0, NULL, GL_TRUE));
1617 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,
1618 GL_DONT_CARE, 0, NULL, GL_TRUE));
1619 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PORTABILITY_ARB,
1620 GL_DONT_CARE, 0, NULL, GL_TRUE));
1621 }
1622 if (WARN_ON(d3d_perf))
1623 {
1624 GL_EXTCALL(glDebugMessageControlARB(GL_DONT_CARE, GL_DEBUG_TYPE_PERFORMANCE_ARB,
1625 GL_DONT_CARE, 0, NULL, GL_TRUE));
1626 }
1627 }
1628
1629 switch (swapchain->desc.swap_interval)
1630 {
1631 case WINED3DPRESENT_INTERVAL_IMMEDIATE:
1632 swap_interval = 0;
1633 break;
1634 case WINED3DPRESENT_INTERVAL_DEFAULT:
1635 case WINED3DPRESENT_INTERVAL_ONE:
1636 swap_interval = 1;
1637 break;
1638 case WINED3DPRESENT_INTERVAL_TWO:
1639 swap_interval = 2;
1640 break;
1641 case WINED3DPRESENT_INTERVAL_THREE:
1642 swap_interval = 3;
1643 break;
1644 case WINED3DPRESENT_INTERVAL_FOUR:
1645 swap_interval = 4;
1646 break;
1647 default:
1648 FIXME("Unknown swap interval %#x.\n", swapchain->desc.swap_interval);
1649 swap_interval = 1;
1650 }
1651
1652 if (gl_info->supported[WGL_EXT_SWAP_CONTROL])
1653 {
1654 if (!GL_EXTCALL(wglSwapIntervalEXT(swap_interval)))
1655 ERR("wglSwapIntervalEXT failed to set swap interval %d for context %p, last error %#x\n",
1656 swap_interval, ret, GetLastError());
1657 }
1658
1659 gl_info->gl_ops.gl.p_glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1660
1661 TRACE("Setting up the screen\n");
1662
1663 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1664 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1665
1666 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1667 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1668
1669 gl_info->gl_ops.gl.p_glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1670 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1671
1672 gl_info->gl_ops.gl.p_glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1673 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1674 gl_info->gl_ops.gl.p_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1675 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1676
1677 if (gl_info->supported[ARB_VERTEX_BLEND])
1678 {
1679 /* Direct3D always uses n-1 weights for n world matrices and uses
1680 * 1 - sum for the last one this is equal to GL_WEIGHT_SUM_UNITY_ARB.
1681 * Enabling it doesn't do anything unless GL_VERTEX_BLEND_ARB isn't
1682 * enabled as well. */
1683 gl_info->gl_ops.gl.p_glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1684 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1685 }
1686 if (gl_info->supported[NV_TEXTURE_SHADER2])
1687 {
1688 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1689 * the previous texture where to source the offset from is always unit - 1.
1690 */
1691 for (s = 1; s < gl_info->limits.textures; ++s)
1692 {
1693 context_active_texture(ret, gl_info, s);
1694 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_SHADER_NV,
1695 GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1696 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1697 }
1698 }
1699 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1700 {
1701 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1702 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1703 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1704 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1705 * is ever assigned.
1706 *
1707 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1708 * program and the dummy program is destroyed when the context is destroyed.
1709 */
1710 static const char dummy_program[] =
1711 "!!ARBfp1.0\n"
1712 "MOV result.color, fragment.color.primary;\n"
1713 "END\n";
1714 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1715 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1716 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1717 }
1718
1719 if (gl_info->supported[ARB_POINT_SPRITE])
1720 {
1721 for (s = 0; s < gl_info->limits.textures; ++s)
1722 {
1723 context_active_texture(ret, gl_info, s);
1724 gl_info->gl_ops.gl.p_glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1725 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1726 }
1727 }
1728
1729 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1730 {
1731 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1732 }
1733 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1734 {
1735 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1736 }
1737 device->shader_backend->shader_init_context_state(ret);
1738 ret->shader_update_mask = (1 << WINED3D_SHADER_TYPE_PIXEL)
1739 | (1 << WINED3D_SHADER_TYPE_VERTEX)
1740 | (1 << WINED3D_SHADER_TYPE_GEOMETRY);
1741
1742 /* If this happens to be the first context for the device, dummy textures
1743 * are not created yet. In that case, they will be created (and bound) by
1744 * create_dummy_textures right after this context is initialized. */
1745 if (device->dummy_texture_2d[0])
1746 bind_dummy_textures(device, ret);
1747
1748 TRACE("Created context %p.\n", ret);
1749
1750 return ret;
1751
1752 out:
1753 device->shader_backend->shader_free_context_data(ret);
1754 device->adapter->fragment_pipe->free_context_data(ret);
1755 #if defined(STAGING_CSMT)
1756 HeapFree(GetProcessHeap(), 0, ret->current_fb.render_targets);
1757 #endif /* STAGING_CSMT */
1758 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1759 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1760 HeapFree(GetProcessHeap(), 0, ret->free_timestamp_queries);
1761 HeapFree(GetProcessHeap(), 0, ret->draw_buffers);
1762 HeapFree(GetProcessHeap(), 0, ret->blit_targets);
1763 HeapFree(GetProcessHeap(), 0, ret);
1764 return NULL;
1765 }
1766
1767 void context_destroy(struct wined3d_device *device, struct wined3d_context *context)
1768 {
1769 BOOL destroy;
1770
1771 TRACE("Destroying ctx %p\n", context);
1772
1773 if (context->tid == GetCurrentThreadId() || !context->current)
1774 {
1775 context_destroy_gl_resources(context);
1776 TlsSetValue(wined3d_context_tls_idx, NULL);
1777 destroy = TRUE;
1778 }
1779 else
1780 {
1781 /* Make a copy of gl_info for context_destroy_gl_resources use, the one
1782 in wined3d_adapter may go away in the meantime */
1783 struct wined3d_gl_info *gl_info = HeapAlloc(GetProcessHeap(), 0, sizeof(*gl_info));
1784 *gl_info = *context->gl_info;
1785 context->gl_info = gl_info;
1786 context->destroyed = 1;
1787 destroy = FALSE;
1788 }
1789
1790 device->shader_backend->shader_free_context_data(context);
1791 device->adapter->fragment_pipe->free_context_data(context);
1792 #if defined(STAGING_CSMT)
1793 HeapFree(GetProcessHeap(), 0, context->current_fb.render_targets);
1794 #endif /* STAGING_CSMT */
1795 HeapFree(GetProcessHeap(), 0, context->draw_buffers);
1796 HeapFree(GetProcessHeap(), 0, context->blit_targets);
1797 device_context_remove(device, context);
1798 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1799 }
1800
1801 /* Context activation is done by the caller. */
1802 static void set_blit_dimension(const struct wined3d_gl_info *gl_info, UINT width, UINT height)
1803 {
1804 const GLdouble projection[] =
1805 {
1806 2.0 / width, 0.0, 0.0, 0.0,
1807 0.0, 2.0 / height, 0.0, 0.0,
1808 0.0, 0.0, 2.0, 0.0,
1809 -1.0, -1.0, -1.0, 1.0,
1810 };
1811
1812 gl_info->gl_ops.gl.p_glMatrixMode(GL_PROJECTION);
1813 checkGLcall("glMatrixMode(GL_PROJECTION)");
1814 gl_info->gl_ops.gl.p_glLoadMatrixd(projection);
1815 checkGLcall("glLoadMatrixd");
1816 gl_info->gl_ops.gl.p_glViewport(0, 0, width, height);
1817 checkGLcall("glViewport");
1818 }
1819
1820 static void context_get_rt_size(const struct wined3d_context *context, SIZE *size)
1821 {
1822 const struct wined3d_surface *rt = context->current_rt;
1823
1824 if (rt->container->swapchain && rt->container->swapchain->front_buffer == rt->container)
1825 {
1826 RECT window_size;
1827
1828 GetClientRect(context->win_handle, &window_size);
1829 size->cx = window_size.right - window_size.left;
1830 size->cy = window_size.bottom - window_size.top;
1831
1832 return;
1833 }
1834
1835 size->cx = rt->resource.width;
1836 size->cy = rt->resource.height;
1837 }
1838
1839 /*****************************************************************************
1840 * SetupForBlit
1841 *
1842 * Sets up a context for DirectDraw blitting.
1843 * All texture units are disabled, texture unit 0 is set as current unit
1844 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1845 * color writing enabled for all channels
1846 * register combiners disabled, shaders disabled
1847 * world matrix is set to identity, texture matrix 0 too
1848 * projection matrix is setup for drawing screen coordinates
1849 *
1850 * Params:
1851 * This: Device to activate the context for
1852 * context: Context to setup
1853 *
1854 *****************************************************************************/
1855 /* Context activation is done by the caller. */
1856 static void SetupForBlit(const struct wined3d_device *device, struct wined3d_context *context)
1857 {
1858 int i;
1859 const struct wined3d_gl_info *gl_info = context->gl_info;
1860 DWORD sampler;
1861 SIZE rt_size;
1862
1863 TRACE("Setting up context %p for blitting\n", context);
1864
1865 context_get_rt_size(context, &rt_size);
1866
1867 if (context->last_was_blit)
1868 {
1869 if (context->blit_w != rt_size.cx || context->blit_h != rt_size.cy)
1870 {
1871 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
1872 context->blit_w = rt_size.cx;
1873 context->blit_h = rt_size.cy;
1874 /* No need to dirtify here, the states are still dirtified because
1875 * they weren't applied since the last SetupForBlit() call. */
1876 }
1877 TRACE("Context is already set up for blitting, nothing to do\n");
1878 return;
1879 }
1880 context->last_was_blit = TRUE;
1881
1882 /* Disable all textures. The caller can then bind a texture it wants to blit
1883 * from
1884 *
1885 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1886 * function texture unit. No need to care for higher samplers
1887 */
1888 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
1889 {
1890 sampler = context->rev_tex_unit_map[i];
1891 context_active_texture(context, gl_info, i);
1892
1893 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1894 {
1895 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1896 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1897 }
1898 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1899 checkGLcall("glDisable GL_TEXTURE_3D");
1900 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1901 {
1902 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1903 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1904 }
1905 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1906 checkGLcall("glDisable GL_TEXTURE_2D");
1907
1908 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1909 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1910
1911 if (sampler != WINED3D_UNMAPPED_STAGE)
1912 {
1913 if (sampler < MAX_TEXTURES)
1914 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1915 context_invalidate_state(context, STATE_SAMPLER(sampler));
1916 }
1917 }
1918 if (gl_info->supported[ARB_SAMPLER_OBJECTS])
1919 GL_EXTCALL(glBindSampler(0, 0));
1920 context_active_texture(context, gl_info, 0);
1921
1922 sampler = context->rev_tex_unit_map[0];
1923
1924 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
1925 {
1926 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1927 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1928 }
1929 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_3D);
1930 checkGLcall("glDisable GL_TEXTURE_3D");
1931 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
1932 {
1933 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_RECTANGLE_ARB);
1934 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1935 }
1936 gl_info->gl_ops.gl.p_glDisable(GL_TEXTURE_2D);
1937 checkGLcall("glDisable GL_TEXTURE_2D");
1938
1939 gl_info->gl_ops.gl.p_glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1940
1941 gl_info->gl_ops.gl.p_glMatrixMode(GL_TEXTURE);
1942 checkGLcall("glMatrixMode(GL_TEXTURE)");
1943 gl_info->gl_ops.gl.p_glLoadIdentity();
1944 checkGLcall("glLoadIdentity()");
1945
1946 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
1947 {
1948 gl_info->gl_ops.gl.p_glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1949 GL_TEXTURE_LOD_BIAS_EXT, 0.0f);
1950 checkGLcall("glTexEnvf GL_TEXTURE_LOD_BIAS_EXT ...");
1951 }
1952
1953 if (sampler != WINED3D_UNMAPPED_STAGE)
1954 {
1955 if (sampler < MAX_TEXTURES)
1956 {
1957 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_TEXTURE0 + sampler));
1958 context_invalidate_state(context, STATE_TEXTURESTAGE(sampler, WINED3D_TSS_COLOR_OP));
1959 }
1960 context_invalidate_state(context, STATE_SAMPLER(sampler));
1961 }
1962
1963 /* Other misc states */
1964 gl_info->gl_ops.gl.p_glDisable(GL_ALPHA_TEST);
1965 checkGLcall("glDisable(GL_ALPHA_TEST)");
1966 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHATESTENABLE));
1967 gl_info->gl_ops.gl.p_glDisable(GL_LIGHTING);
1968 checkGLcall("glDisable GL_LIGHTING");
1969 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_LIGHTING));
1970 gl_info->gl_ops.gl.p_glDisable(GL_DEPTH_TEST);
1971 checkGLcall("glDisable GL_DEPTH_TEST");
1972 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ZENABLE));
1973 glDisableWINE(GL_FOG);
1974 checkGLcall("glDisable GL_FOG");
1975 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_FOGENABLE));
1976 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
1977 checkGLcall("glDisable GL_BLEND");
1978 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
1979 gl_info->gl_ops.gl.p_glDisable(GL_CULL_FACE);
1980 checkGLcall("glDisable GL_CULL_FACE");
1981 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CULLMODE));
1982 gl_info->gl_ops.gl.p_glDisable(GL_STENCIL_TEST);
1983 checkGLcall("glDisable GL_STENCIL_TEST");
1984 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_STENCILENABLE));
1985 gl_info->gl_ops.gl.p_glDisable(GL_SCISSOR_TEST);
1986 checkGLcall("glDisable GL_SCISSOR_TEST");
1987 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
1988 if (gl_info->supported[ARB_POINT_SPRITE])
1989 {
1990 gl_info->gl_ops.gl.p_glDisable(GL_POINT_SPRITE_ARB);
1991 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1992 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_POINTSPRITEENABLE));
1993 }
1994 gl_info->gl_ops.gl.p_glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1995 checkGLcall("glColorMask");
1996 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE));
1997 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE1));
1998 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE2));
1999 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_COLORWRITEENABLE3));
2000 if (gl_info->supported[EXT_SECONDARY_COLOR])
2001 {
2002 gl_info->gl_ops.gl.p_glDisable(GL_COLOR_SUM_EXT);
2003 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SPECULARENABLE));
2004 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2005 }
2006
2007 /* Setup transforms */
2008 gl_info->gl_ops.gl.p_glMatrixMode(GL_MODELVIEW);
2009 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2010 gl_info->gl_ops.gl.p_glLoadIdentity();
2011 checkGLcall("glLoadIdentity()");
2012 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_WORLD_MATRIX(0)));
2013
2014 context->last_was_rhw = TRUE;
2015 context_invalidate_state(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
2016
2017 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2018 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2019 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2020 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2021 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2022 gl_info->gl_ops.gl.p_glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2023 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_CLIPPING));
2024
2025 set_blit_dimension(gl_info, rt_size.cx, rt_size.cy);
2026
2027 /* Disable shaders */
2028 device->shader_backend->shader_disable(device->shader_priv, context);
2029
2030 context->blit_w = rt_size.cx;
2031 context->blit_h = rt_size.cy;
2032 context_invalidate_state(context, STATE_VIEWPORT);
2033 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2034 }
2035
2036 static inline BOOL is_rt_mask_onscreen(DWORD rt_mask)
2037 {
2038 return rt_mask & (1 << 31);
2039 }
2040
2041 static inline GLenum draw_buffer_from_rt_mask(DWORD rt_mask)
2042 {
2043 return rt_mask & ~(1 << 31);
2044 }
2045
2046 /* Context activation is done by the caller. */
2047 static void context_apply_draw_buffers(struct wined3d_context *context, DWORD rt_mask)
2048 {
2049 const struct wined3d_gl_info *gl_info = context->gl_info;
2050
2051 if (!rt_mask)
2052 {
2053 gl_info->gl_ops.gl.p_glDrawBuffer(GL_NONE);
2054 checkGLcall("glDrawBuffer()");
2055 }
2056 else if (is_rt_mask_onscreen(rt_mask))
2057 {
2058 gl_info->gl_ops.gl.p_glDrawBuffer(draw_buffer_from_rt_mask(rt_mask));
2059 checkGLcall("glDrawBuffer()");
2060 }
2061 else
2062 {
2063 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2064 {
2065 unsigned int i = 0;
2066
2067 while (rt_mask)
2068 {
2069 if (rt_mask & 1)
2070 context->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
2071 else
2072 context->draw_buffers[i] = GL_NONE;
2073
2074 rt_mask >>= 1;
2075 ++i;
2076 }
2077
2078 if (gl_info->supported[ARB_DRAW_BUFFERS])
2079 {
2080 GL_EXTCALL(glDrawBuffers(i, context->draw_buffers));
2081 checkGLcall("glDrawBuffers()");
2082 }
2083 else
2084 {
2085 gl_info->gl_ops.gl.p_glDrawBuffer(context->draw_buffers[0]);
2086 checkGLcall("glDrawBuffer()");
2087 }
2088 }
2089 else
2090 {
2091 ERR("Unexpected draw buffers mask with backbuffer ORM.\n");
2092 }
2093 }
2094 }
2095
2096 /* Context activation is done by the caller. */
2097 void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2098 {
2099 const struct wined3d_gl_info *gl_info = context->gl_info;
2100 DWORD *current_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2101 DWORD new_mask = context_generate_rt_mask(buffer);
2102
2103 if (new_mask == *current_mask)
2104 return;
2105
2106 gl_info->gl_ops.gl.p_glDrawBuffer(buffer);
2107 checkGLcall("glDrawBuffer()");
2108
2109 *current_mask = new_mask;
2110 }
2111
2112 /* Context activation is done by the caller. */
2113 void context_active_texture(struct wined3d_context *context, const struct wined3d_gl_info *gl_info, unsigned int unit)
2114 {
2115 GL_EXTCALL(glActiveTexture(GL_TEXTURE0 + unit));
2116 checkGLcall("glActiveTexture");
2117 context->active_texture = unit;
2118 }
2119
2120 void context_bind_texture(struct wined3d_context *context, GLenum target, GLuint name)
2121 {
2122 const struct wined3d_gl_info *gl_info = context->gl_info;
2123 DWORD unit = context->active_texture;
2124 DWORD old_texture_type = context->texture_type[unit];
2125
2126 if (name)
2127 {
2128 gl_info->gl_ops.gl.p_glBindTexture(target, name);
2129 checkGLcall("glBindTexture");
2130 }
2131 else
2132 {
2133 target = GL_NONE;
2134 }
2135
2136 if (old_texture_type != target)
2137 {
2138 const struct wined3d_device *device = context->swapchain->device;
2139
2140 switch (old_texture_type)
2141 {
2142 case GL_NONE:
2143 /* nothing to do */
2144 break;
2145 case GL_TEXTURE_2D:
2146 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_2D, device->dummy_texture_2d[unit]);
2147 checkGLcall("glBindTexture");
2148 break;
2149 case GL_TEXTURE_RECTANGLE_ARB:
2150 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_RECTANGLE_ARB, device->dummy_texture_rect[unit]);
2151 checkGLcall("glBindTexture");
2152 break;
2153 case GL_TEXTURE_CUBE_MAP:
2154 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_CUBE_MAP, device->dummy_texture_cube[unit]);
2155 checkGLcall("glBindTexture");
2156 break;
2157 case GL_TEXTURE_3D:
2158 gl_info->gl_ops.gl.p_glBindTexture(GL_TEXTURE_3D, device->dummy_texture_3d[unit]);
2159 checkGLcall("glBindTexture");
2160 break;
2161 default:
2162 ERR("Unexpected texture target %#x\n", old_texture_type);
2163 }
2164
2165 context->texture_type[unit] = target;
2166 }
2167 }
2168
2169 static void context_set_render_offscreen(struct wined3d_context *context, BOOL offscreen)
2170 {
2171 if (context->render_offscreen == offscreen) return;
2172
2173 context_invalidate_state(context, STATE_POINTSPRITECOORDORIGIN);
2174 context_invalidate_state(context, STATE_TRANSFORM(WINED3D_TS_PROJECTION));
2175 context_invalidate_state(context, STATE_VIEWPORT);
2176 context_invalidate_state(context, STATE_SCISSORRECT);
2177 context_invalidate_state(context, STATE_FRONTFACE);
2178 context->render_offscreen = offscreen;
2179 }
2180
2181 static BOOL match_depth_stencil_format(const struct wined3d_format *existing,
2182 const struct wined3d_format *required)
2183 {
2184 BYTE existing_depth, existing_stencil, required_depth, required_stencil;
2185
2186 if (existing == required)
2187 return TRUE;
2188 if ((existing->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT)
2189 != (required->flags[WINED3D_GL_RES_TYPE_TEX_2D] & WINED3DFMT_FLAG_FLOAT))
2190 return FALSE;
2191
2192 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2193 getDepthStencilBits(required, &required_depth, &required_stencil);
2194
2195 if(existing_depth < required_depth) return FALSE;
2196 /* If stencil bits are used the exact amount is required - otherwise wrapping
2197 * won't work correctly */
2198 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2199 return TRUE;
2200 }
2201
2202 #if defined(STAGING_CSMT)
2203 /* Context activation is done by the caller. */
2204 #else /* STAGING_CSMT */
2205 /* The caller provides a context */
2206 #endif /* STAGING_CSMT */
2207 static void context_validate_onscreen_formats(struct wined3d_context *context,
2208 const struct wined3d_rendertarget_view *depth_stencil)
2209 {
2210 /* Onscreen surfaces are always in a swapchain */
2211 struct wined3d_swapchain *swapchain = context->current_rt->container->swapchain;
2212
2213 if (context->render_offscreen || !depth_stencil) return;
2214 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->format)) return;
2215
2216 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2217 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2218 * format. */
2219 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2220
2221 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2222 #if defined(STAGING_CSMT)
2223 wined3d_resource_load_location(&context->current_rt->resource, context, WINED3D_LOCATION_TEXTURE_RGB);
2224 swapchain->render_to_fbo = TRUE;
2225 swapchain_update_draw_bindings(swapchain);
2226 context_set_render_offscreen(context, TRUE);
2227 }
2228
2229 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_context *context, const struct wined3d_surface *rt)
2230 {
2231 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2232 return 0;
2233 else if (rt->container->swapchain)
2234 return context_generate_rt_mask_from_surface(rt);
2235 else
2236 return context_generate_rt_mask(context->offscreenBuffer);
2237 #else /* STAGING_CSMT */
2238 surface_load_location(context->current_rt, WINED3D_LOCATION_TEXTURE_RGB);
2239 swapchain->render_to_fbo = TRUE;
2240 swapchain_update_draw_bindings(swapchain);
2241 context_set_render_offscreen(context, TRUE);
2242 }
2243
2244 static DWORD context_generate_rt_mask_no_fbo(const struct wined3d_device *device, const struct wined3d_surface *rt)
2245 {
2246 if (!rt || rt->resource.format->id == WINED3DFMT_NULL)
2247 return 0;
2248 else if (rt->container->swapchain)
2249 return context_generate_rt_mask_from_surface(rt);
2250 else
2251 return context_generate_rt_mask(device->offscreenBuffer);
2252 #endif /* STAGING_CSMT */
2253 }
2254
2255 /* Context activation is done by the caller. */
2256 void context_apply_blit_state(struct wined3d_context *context, const struct wined3d_device *device)
2257 {
2258 struct wined3d_surface *rt = context->current_rt;
2259 DWORD rt_mask, *cur_mask;
2260
2261 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2262 {
2263 context_validate_onscreen_formats(context, NULL);
2264
2265 if (context->render_offscreen)
2266 {
2267 wined3d_texture_load(rt->container, context, FALSE);
2268
2269 context_apply_fbo_state_blit(context, GL_FRAMEBUFFER, rt, NULL, rt->container->resource.draw_binding);
2270 if (rt->resource.format->id != WINED3DFMT_NULL)
2271 rt_mask = 1;
2272 else
2273 rt_mask = 0;
2274 }
2275 else
2276 {
2277 context->current_fbo = NULL;
2278 context_bind_fbo(context, GL_FRAMEBUFFER, 0);
2279 rt_mask = context_generate_rt_mask_from_surface(rt);
2280 }
2281 }
2282 else
2283 {
2284 #if defined(STAGING_CSMT)
2285 rt_mask = context_generate_rt_mask_no_fbo(context, rt);
2286 #else /* STAGING_CSMT */
2287 rt_mask = context_generate_rt_mask_no_fbo(device, rt);
2288 #endif /* STAGING_CSMT */
2289 }
2290
2291 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2292
2293 if (rt_mask != *cur_mask)
2294 {
2295 context_apply_draw_buffers(context, rt_mask);
2296 *cur_mask = rt_mask;
2297 }
2298
2299 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2300 {
2301 context_check_fbo_status(context, GL_FRAMEBUFFER);
2302 }
2303
2304 SetupForBlit(device, context);
2305 context_invalidate_state(context, STATE_FRAMEBUFFER);
2306 }
2307
2308 static BOOL context_validate_rt_config(UINT rt_count, struct wined3d_rendertarget_view * const *rts,
2309 const struct wined3d_rendertarget_view *ds)
2310 {
2311 unsigned int i;
2312
2313 if (ds) return TRUE;
2314
2315 for (i = 0; i < rt_count; ++i)
2316 {
2317 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2318 return TRUE;
2319 }
2320
2321 WARN("Invalid render target config, need at least one attachment.\n");
2322 return FALSE;
2323 }
2324
2325 /* Context activation is done by the caller. */
2326 BOOL context_apply_clear_state(struct wined3d_context *context, const struct wined3d_device *device,
2327 UINT rt_count, const struct wined3d_fb_state *fb)
2328 {
2329 struct wined3d_rendertarget_view **rts = fb->render_targets;
2330 struct wined3d_rendertarget_view *dsv = fb->depth_stencil;
2331 const struct wined3d_gl_info *gl_info = context->gl_info;
2332 DWORD rt_mask = 0, *cur_mask;
2333 UINT i;
2334
2335 #if defined(STAGING_CSMT)
2336 if (isStateDirty(context, STATE_FRAMEBUFFER) || !wined3d_fb_equal(fb, &context->current_fb)
2337 #else /* STAGING_CSMT */
2338 if (isStateDirty(context, STATE_FRAMEBUFFER) || fb != &device->fb
2339 #endif /* STAGING_CSMT */
2340 || rt_count != context->gl_info->limits.buffers)
2341 {
2342 if (!context_validate_rt_config(rt_count, rts, dsv))
2343 return FALSE;
2344
2345 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2346 {
2347 context_validate_onscreen_formats(context, dsv);
2348
2349 if (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource))
2350 {
2351 for (i = 0; i < rt_count; ++i)
2352 {
2353 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(rts[i]);
2354 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2355 rt_mask |= (1 << i);
2356 }
2357 while (i < context->gl_info->limits.buffers)
2358 {
2359 context->blit_targets[i] = NULL;
2360 ++i;
2361 }
2362 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2363 wined3d_rendertarget_view_get_surface(dsv),
2364 rt_count ? rts[0]->resource->draw_binding : 0,
2365 dsv ? dsv->resource->draw_binding : 0);
2366 }
2367 else
2368 {
2369 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2370 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2371 rt_mask = context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2372 }
2373
2374 /* If the framebuffer is not the device's fb the device's fb has to be reapplied
2375 * next draw. Otherwise we could mark the framebuffer state clean here, once the
2376 * state management allows this */
2377 context_invalidate_state(context, STATE_FRAMEBUFFER);
2378 }
2379 else
2380 {
2381 #if defined(STAGING_CSMT)
2382 rt_mask = context_generate_rt_mask_no_fbo(context,
2383 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2384 }
2385
2386 wined3d_fb_copy(&context->current_fb, fb);
2387 #else /* STAGING_CSMT */
2388 rt_mask = context_generate_rt_mask_no_fbo(device,
2389 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2390 }
2391 #endif /* STAGING_CSMT */
2392 }
2393 else if (wined3d_settings.offscreen_rendering_mode == ORM_FBO
2394 && (!rt_count || wined3d_resource_is_offscreen(rts[0]->resource)))
2395 {
2396 for (i = 0; i < rt_count; ++i)
2397 {
2398 if (rts[i] && rts[i]->format->id != WINED3DFMT_NULL)
2399 rt_mask |= (1 << i);
2400 }
2401 }
2402 else
2403 {
2404 #if defined(STAGING_CSMT)
2405 rt_mask = context_generate_rt_mask_no_fbo(context,
2406 #else /* STAGING_CSMT */
2407 rt_mask = context_generate_rt_mask_no_fbo(device,
2408 #endif /* STAGING_CSMT */
2409 rt_count ? wined3d_rendertarget_view_get_surface(rts[0]) : NULL);
2410 }
2411
2412 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2413
2414 if (rt_mask != *cur_mask)
2415 {
2416 context_apply_draw_buffers(context, rt_mask);
2417 *cur_mask = rt_mask;
2418 context_invalidate_state(context, STATE_FRAMEBUFFER);
2419 }
2420
2421 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2422 {
2423 context_check_fbo_status(context, GL_FRAMEBUFFER);
2424 }
2425
2426 if (context->last_was_blit)
2427 context->last_was_blit = FALSE;
2428
2429 /* Blending and clearing should be orthogonal, but tests on the nvidia
2430 * driver show that disabling blending when clearing improves the clearing
2431 * performance incredibly. */
2432 gl_info->gl_ops.gl.p_glDisable(GL_BLEND);
2433 gl_info->gl_ops.gl.p_glEnable(GL_SCISSOR_TEST);
2434 checkGLcall("glEnable GL_SCISSOR_TEST");
2435
2436 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
2437 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SCISSORTESTENABLE));
2438 context_invalidate_state(context, STATE_SCISSORRECT);
2439
2440 return TRUE;
2441 }
2442
2443 #if defined(STAGING_CSMT)
2444 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_state *state)
2445 {
2446 struct wined3d_rendertarget_view **rts = state->fb.render_targets;
2447 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2448 DWORD rt_mask, rt_mask_bits;
2449 unsigned int i;
2450
2451 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2452 return context_generate_rt_mask_no_fbo(context, wined3d_rendertarget_view_get_surface(rts[0]));
2453 #else /* STAGING_CSMT */
2454 static DWORD find_draw_buffers_mask(const struct wined3d_context *context, const struct wined3d_device *device)
2455 {
2456 const struct wined3d_state *state = &device->state;
2457 struct wined3d_rendertarget_view **rts = state->fb->render_targets;
2458 struct wined3d_shader *ps = state->shader[WINED3D_SHADER_TYPE_PIXEL];
2459 DWORD rt_mask, rt_mask_bits;
2460 unsigned int i;
2461
2462 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO)
2463 return context_generate_rt_mask_no_fbo(device, wined3d_rendertarget_view_get_surface(rts[0]));
2464 #endif /* STAGING_CSMT */
2465 else if (!context->render_offscreen)
2466 return context_generate_rt_mask_from_surface(wined3d_rendertarget_view_get_surface(rts[0]));
2467
2468 rt_mask = ps ? ps->reg_maps.rt_mask : 1;
2469 rt_mask &= context->d3d_info->valid_rt_mask;
2470 rt_mask_bits = rt_mask;
2471 i = 0;
2472 while (rt_mask_bits)
2473 {
2474 rt_mask_bits &= ~(1 << i);
2475 if (!rts[i] || rts[i]->format->id == WINED3DFMT_NULL)
2476 rt_mask &= ~(1 << i);
2477
2478 i++;
2479 }
2480
2481 return rt_mask;
2482 }
2483
2484 /* Context activation is done by the caller. */
2485 void context_state_fb(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2486 {
2487 #if defined(STAGING_CSMT)
2488 const struct wined3d_fb_state *fb = &state->fb;
2489 DWORD rt_mask = find_draw_buffers_mask(context, state);
2490 #else /* STAGING_CSMT */
2491 const struct wined3d_device *device = context->swapchain->device;
2492 const struct wined3d_fb_state *fb = state->fb;
2493 DWORD rt_mask = find_draw_buffers_mask(context, device);
2494 #endif /* STAGING_CSMT */
2495 DWORD *cur_mask;
2496
2497 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2498 {
2499 if (!context->render_offscreen)
2500 {
2501 context_apply_fbo_state(context, GL_FRAMEBUFFER, NULL, NULL,
2502 WINED3D_LOCATION_DRAWABLE, WINED3D_LOCATION_DRAWABLE);
2503 }
2504 else
2505 {
2506 unsigned int i;
2507
2508 for (i = 0; i < context->gl_info->limits.buffers; ++i)
2509 {
2510 context->blit_targets[i] = wined3d_rendertarget_view_get_surface(fb->render_targets[i]);
2511 }
2512 context_apply_fbo_state(context, GL_FRAMEBUFFER, context->blit_targets,
2513 wined3d_rendertarget_view_get_surface(fb->depth_stencil),
2514 fb->render_targets[0]->resource->draw_binding,
2515 fb->depth_stencil ? fb->depth_stencil->resource->draw_binding : 0);
2516 }
2517 }
2518
2519 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2520 if (rt_mask != *cur_mask)
2521 {
2522 context_apply_draw_buffers(context, rt_mask);
2523 *cur_mask = rt_mask;
2524 }
2525 #if defined(STAGING_CSMT)
2526
2527 wined3d_fb_copy(&context->current_fb, &state->fb);
2528 #endif /* STAGING_CSMT */
2529 }
2530
2531 static void context_map_stage(struct wined3d_context *context, DWORD stage, DWORD unit)
2532 {
2533 DWORD i = context->rev_tex_unit_map[unit];
2534 DWORD j = context->tex_unit_map[stage];
2535
2536 context->tex_unit_map[stage] = unit;
2537 if (i != WINED3D_UNMAPPED_STAGE && i != stage)
2538 context->tex_unit_map[i] = WINED3D_UNMAPPED_STAGE;
2539
2540 context->rev_tex_unit_map[unit] = stage;
2541 if (j != WINED3D_UNMAPPED_STAGE && j != unit)
2542 context->rev_tex_unit_map[j] = WINED3D_UNMAPPED_STAGE;
2543 }
2544
2545 static void context_invalidate_texture_stage(struct wined3d_context *context, DWORD stage)
2546 {
2547 DWORD i;
2548
2549 for (i = 0; i <= WINED3D_HIGHEST_TEXTURE_STATE; ++i)
2550 context_invalidate_state(context, STATE_TEXTURESTAGE(stage, i));
2551 }
2552
2553 static void context_update_fixed_function_usage_map(struct wined3d_context *context,
2554 const struct wined3d_state *state)
2555 {
2556 UINT i, start, end;
2557
2558 context->fixed_function_usage_map = 0;
2559 for (i = 0; i < MAX_TEXTURES; ++i)
2560 {
2561 enum wined3d_texture_op color_op = state->texture_states[i][WINED3D_TSS_COLOR_OP];
2562 enum wined3d_texture_op alpha_op = state->texture_states[i][WINED3D_TSS_ALPHA_OP];
2563 DWORD color_arg1 = state->texture_states[i][WINED3D_TSS_COLOR_ARG1] & WINED3DTA_SELECTMASK;
2564 DWORD color_arg2 = state->texture_states[i][WINED3D_TSS_COLOR_ARG2] & WINED3DTA_SELECTMASK;
2565 DWORD color_arg3 = state->texture_states[i][WINED3D_TSS_COLOR_ARG0] & WINED3DTA_SELECTMASK;
2566 DWORD alpha_arg1 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG1] & WINED3DTA_SELECTMASK;
2567 DWORD alpha_arg2 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG2] & WINED3DTA_SELECTMASK;
2568 DWORD alpha_arg3 = state->texture_states[i][WINED3D_TSS_ALPHA_ARG0] & WINED3DTA_SELECTMASK;
2569
2570 /* Not used, and disable higher stages. */
2571 if (color_op == WINED3D_TOP_DISABLE)
2572 break;
2573
2574 if (((color_arg1 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG2)
2575 || ((color_arg2 == WINED3DTA_TEXTURE) && color_op != WINED3D_TOP_SELECT_ARG1)
2576 || ((color_arg3 == WINED3DTA_TEXTURE)
2577 && (color_op == WINED3D_TOP_MULTIPLY_ADD || color_op == WINED3D_TOP_LERP))
2578 || ((alpha_arg1 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG2)
2579 || ((alpha_arg2 == WINED3DTA_TEXTURE) && alpha_op != WINED3D_TOP_SELECT_ARG1)
2580 || ((alpha_arg3 == WINED3DTA_TEXTURE)
2581 && (alpha_op == WINED3D_TOP_MULTIPLY_ADD || alpha_op == WINED3D_TOP_LERP)))
2582 context->fixed_function_usage_map |= (1 << i);
2583
2584 if ((color_op == WINED3D_TOP_BUMPENVMAP || color_op == WINED3D_TOP_BUMPENVMAP_LUMINANCE)
2585 && i < MAX_TEXTURES - 1)
2586 context->fixed_function_usage_map |= (1 << (i + 1));
2587 }
2588
2589 if (i < context->lowest_disabled_stage)
2590 {
2591 start = i;
2592 end = context->lowest_disabled_stage;
2593 }
2594 else
2595 {
2596 start = context->lowest_disabled_stage;
2597 end = i;
2598 }
2599
2600 context->lowest_disabled_stage = i;
2601 for (i = start + 1; i < end; ++i)
2602 {
2603 context_invalidate_state(context, STATE_TEXTURESTAGE(i, WINED3D_TSS_COLOR_OP));
2604 }
2605 }
2606
2607 static void context_map_fixed_function_samplers(struct wined3d_context *context,
2608 const struct wined3d_state *state)
2609 {
2610 unsigned int i, tex;
2611 WORD ffu_map;
2612 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2613
2614 context_update_fixed_function_usage_map(context, state);
2615 ffu_map = context->fixed_function_usage_map;
2616
2617 if (d3d_info->limits.ffp_textures == d3d_info->limits.ffp_blend_stages
2618 || context->lowest_disabled_stage <= d3d_info->limits.ffp_textures)
2619 {
2620 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2621 {
2622 if (!(ffu_map & 1))
2623 continue;
2624
2625 if (context->tex_unit_map[i] != i)
2626 {
2627 context_map_stage(context, i, i);
2628 context_invalidate_state(context, STATE_SAMPLER(i));
2629 context_invalidate_texture_stage(context, i);
2630 }
2631 }
2632 return;
2633 }
2634
2635 /* Now work out the mapping */
2636 tex = 0;
2637 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
2638 {
2639 if (!(ffu_map & 1))
2640 continue;
2641
2642 if (context->tex_unit_map[i] != tex)
2643 {
2644 context_map_stage(context, i, tex);
2645 context_invalidate_state(context, STATE_SAMPLER(i));
2646 context_invalidate_texture_stage(context, i);
2647 }
2648
2649 ++tex;
2650 }
2651 }
2652
2653 static void context_map_psamplers(struct wined3d_context *context, const struct wined3d_state *state)
2654 {
2655 const struct wined3d_shader_resource_info *resource_info =
2656 state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2657 unsigned int i;
2658 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2659
2660 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
2661 {
2662 if (resource_info[i].type && context->tex_unit_map[i] != i)
2663 {
2664 context_map_stage(context, i, i);
2665 context_invalidate_state(context, STATE_SAMPLER(i));
2666 if (i < d3d_info->limits.ffp_blend_stages)
2667 context_invalidate_texture_stage(context, i);
2668 }
2669 }
2670 }
2671
2672 static BOOL context_unit_free_for_vs(const struct wined3d_context *context,
2673 const struct wined3d_shader_resource_info *ps_resource_info,
2674 const struct wined3d_shader_resource_info *vs_resource_info, DWORD unit)
2675 {
2676 DWORD current_mapping = context->rev_tex_unit_map[unit];
2677
2678 /* Not currently used */
2679 if (current_mapping == WINED3D_UNMAPPED_STAGE)
2680 return TRUE;
2681
2682 if (current_mapping < MAX_FRAGMENT_SAMPLERS)
2683 {
2684 /* Used by a fragment sampler */
2685
2686 if (!ps_resource_info)
2687 {
2688 /* No pixel shader, check fixed function */
2689 return current_mapping >= MAX_TEXTURES || !(context->fixed_function_usage_map & (1 << current_mapping));
2690 }
2691
2692 /* Pixel shader, check the shader's sampler map */
2693 return !ps_resource_info[current_mapping].type;
2694 }
2695
2696 /* Used by a vertex sampler */
2697 return !vs_resource_info[current_mapping - MAX_FRAGMENT_SAMPLERS].type;
2698 }
2699
2700 static void context_map_vsamplers(struct wined3d_context *context, BOOL ps, const struct wined3d_state *state)
2701 {
2702 const struct wined3d_shader_resource_info *vs_resource_info =
2703 state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info;
2704 const struct wined3d_shader_resource_info *ps_resource_info = NULL;
2705 const struct wined3d_gl_info *gl_info = context->gl_info;
2706 int start = min(MAX_COMBINED_SAMPLERS, gl_info->limits.combined_samplers) - 1;
2707 int i;
2708
2709 /* Note that we only care if a resource is used or not, not the
2710 * resource's specific type. Otherwise we'd need to call
2711 * shader_update_samplers() here for 1.x pixelshaders. */
2712 if (ps)
2713 ps_resource_info = state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info;
2714
2715 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
2716 {
2717 DWORD vsampler_idx = i + MAX_FRAGMENT_SAMPLERS;
2718 if (vs_resource_info[i].type)
2719 {
2720 if (context->tex_unit_map[vsampler_idx] != WINED3D_UNMAPPED_STAGE)
2721 {
2722 /* Already mapped somewhere */
2723 continue;
2724 }
2725
2726 while (start >= 0)
2727 {
2728 if (context_unit_free_for_vs(context, ps_resource_info, vs_resource_info, start))
2729 {
2730 context_map_stage(context, vsampler_idx, start);
2731 context_invalidate_state(context, STATE_SAMPLER(vsampler_idx));
2732
2733 --start;
2734 break;
2735 }
2736
2737 --start;
2738 }
2739 }
2740 }
2741 }
2742
2743 static void context_update_tex_unit_map(struct wined3d_context *context, const struct wined3d_state *state)
2744 {
2745 BOOL vs = use_vs(state);
2746 BOOL ps = use_ps(state);
2747 /*
2748 * Rules are:
2749 * -> Pixel shaders need a 1:1 map. In theory the shader input could be mapped too, but
2750 * that would be really messy and require shader recompilation
2751 * -> When the mapping of a stage is changed, sampler and ALL texture stage states have
2752 * to be reset. Because of that try to work with a 1:1 mapping as much as possible
2753 */
2754 if (ps)
2755 context_map_psamplers(context, state);
2756 else
2757 context_map_fixed_function_samplers(context, state);
2758
2759 if (vs)
2760 context_map_vsamplers(context, ps, state);
2761 }
2762
2763 /* Context activation is done by the caller. */
2764 void context_state_drawbuf(struct wined3d_context *context, const struct wined3d_state *state, DWORD state_id)
2765 {
2766 #if defined(STAGING_CSMT)
2767 DWORD rt_mask, *cur_mask;
2768
2769 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2770
2771 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2772 rt_mask = find_draw_buffers_mask(context, state);
2773 #else /* STAGING_CSMT */
2774 const struct wined3d_device *device = context->swapchain->device;
2775 DWORD rt_mask, *cur_mask;
2776
2777 if (isStateDirty(context, STATE_FRAMEBUFFER)) return;
2778
2779 cur_mask = context->current_fbo ? &context->current_fbo->rt_mask : &context->draw_buffers_mask;
2780 rt_mask = find_draw_buffers_mask(context, device);
2781 #endif /* STAGING_CSMT */
2782 if (rt_mask != *cur_mask)
2783 {
2784 context_apply_draw_buffers(context, rt_mask);
2785 *cur_mask = rt_mask;
2786 }
2787 }
2788
2789 static BOOL fixed_get_input(BYTE usage, BYTE usage_idx, unsigned int *regnum)
2790 {
2791 if ((usage == WINED3D_DECL_USAGE_POSITION || usage == WINED3D_DECL_USAGE_POSITIONT) && !usage_idx)
2792 *regnum = WINED3D_FFP_POSITION;
2793 else if (usage == WINED3D_DECL_USAGE_BLEND_WEIGHT && !usage_idx)
2794 *regnum = WINED3D_FFP_BLENDWEIGHT;
2795 else if (usage == WINED3D_DECL_USAGE_BLEND_INDICES && !usage_idx)
2796 *regnum = WINED3D_FFP_BLENDINDICES;
2797 else if (usage == WINED3D_DECL_USAGE_NORMAL && !usage_idx)
2798 *regnum = WINED3D_FFP_NORMAL;
2799 else if (usage == WINED3D_DECL_USAGE_PSIZE && !usage_idx)
2800 *regnum = WINED3D_FFP_PSIZE;
2801 else if (usage == WINED3D_DECL_USAGE_COLOR && !usage_idx)
2802 *regnum = WINED3D_FFP_DIFFUSE;
2803 else if (usage == WINED3D_DECL_USAGE_COLOR && usage_idx == 1)
2804 *regnum = WINED3D_FFP_SPECULAR;
2805 else if (usage == WINED3D_DECL_USAGE_TEXCOORD && usage_idx < WINED3DDP_MAXTEXCOORD)
2806 *regnum = WINED3D_FFP_TEXCOORD0 + usage_idx;
2807 else
2808 {
2809 FIXME("Unsupported input stream [usage=%s, usage_idx=%u].\n", debug_d3ddeclusage(usage), usage_idx);
2810 *regnum = ~0U;
2811 return FALSE;
2812 }
2813
2814 return TRUE;
2815 }
2816
2817 /* Context activation is done by the caller. */
2818 void context_stream_info_from_declaration(struct wined3d_context *context,
2819 const struct wined3d_state *state, struct wined3d_stream_info *stream_info)
2820 {
2821 /* We need to deal with frequency data! */
2822 struct wined3d_vertex_declaration *declaration = state->vertex_declaration;
2823 BOOL use_vshader = use_vs(state);
2824 BOOL generic_attributes = context->d3d_info->ffp_generic_attributes;
2825 unsigned int i;
2826
2827 stream_info->use_map = 0;
2828 stream_info->swizzle_map = 0;
2829 stream_info->position_transformed = declaration->position_transformed;
2830
2831 /* Translate the declaration into strided data. */
2832 for (i = 0; i < declaration->element_count; ++i)
2833 {
2834 const struct wined3d_vertex_declaration_element *element = &declaration->elements[i];
2835 const struct wined3d_stream_state *stream = &state->streams[element->input_slot];
2836 BOOL stride_used;
2837 unsigned int idx;
2838
2839 TRACE("%p Element %p (%u of %u).\n", declaration->elements,
2840 element, i + 1, declaration->element_count);
2841
2842 if (!stream->buffer)
2843 continue;
2844
2845 TRACE("offset %u input_slot %u usage_idx %d.\n", element->offset, element->input_slot, element->usage_idx);
2846
2847 if (use_vshader)
2848 {
2849 if (element->output_slot == WINED3D_OUTPUT_SLOT_UNUSED)
2850 {
2851 stride_used = FALSE;
2852 }
2853 else if (element->output_slot == WINED3D_OUTPUT_SLOT_SEMANTIC)
2854 {
2855 /* TODO: Assuming vertexdeclarations are usually used with the
2856 * same or a similar shader, it might be worth it to store the
2857 * last used output slot and try that one first. */
2858 stride_used = vshader_get_input(state->shader[WINED3D_SHADER_TYPE_VERTEX],
2859 element->usage, element->usage_idx, &idx);
2860 }
2861 else
2862 {
2863 idx = element->output_slot;
2864 stride_used = TRUE;
2865 }
2866 }
2867 else
2868 {
2869 if (!generic_attributes && !element->ffp_valid)
2870 {
2871 WARN("Skipping unsupported fixed function element of format %s and usage %s.\n",
2872 debug_d3dformat(element->format->id), debug_d3ddeclusage(element->usage));
2873 stride_used = FALSE;
2874 }
2875 else
2876 {
2877 stride_used = fixed_get_input(element->usage, element->usage_idx, &idx);
2878 }
2879 }
2880
2881 if (stride_used)
2882 {
2883 TRACE("Load %s array %u [usage %s, usage_idx %u, "
2884 "input_slot %u, offset %u, stride %u, format %s, class %s, step_rate %u].\n",
2885 use_vshader ? "shader": "fixed function", idx,
2886 debug_d3ddeclusage(element->usage), element->usage_idx, element->input_slot,
2887 element->offset, stream->stride, debug_d3dformat(element->format->id),
2888 debug_d3dinput_classification(element->input_slot_class), element->instance_data_step_rate);
2889
2890 stream_info->elements[idx].format = element->format;
2891 stream_info->elements[idx].data.buffer_object = 0;
2892 stream_info->elements[idx].data.addr = (BYTE *)NULL + stream->offset + element->offset;
2893 stream_info->elements[idx].stride = stream->stride;
2894 stream_info->elements[idx].stream_idx = element->input_slot;
2895 if (stream->flags & WINED3DSTREAMSOURCE_INSTANCEDATA)
2896 {
2897 stream_info->elements[idx].divisor = 1;
2898 }
2899 else if (element->input_slot_class == WINED3D_INPUT_PER_INSTANCE_DATA)
2900 {
2901 stream_info->elements[idx].divisor = element->instance_data_step_rate;
2902 if (!element->instance_data_step_rate)
2903 FIXME("Instance step rate 0 not implemented.\n");
2904 }
2905 else
2906 {
2907 stream_info->elements[idx].divisor = 0;
2908 }
2909
2910 if (!context->gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2911 && element->format->id == WINED3DFMT_B8G8R8A8_UNORM)
2912 {
2913 stream_info->swizzle_map |= 1 << idx;
2914 }
2915 stream_info->use_map |= 1 << idx;
2916 }
2917 }
2918 }
2919
2920 /* Context activation is done by the caller. */
2921 static void context_update_stream_info(struct wined3d_context *context, const struct wined3d_state *state)
2922 {
2923 const struct wined3d_gl_info *gl_info = context->gl_info;
2924 const struct wined3d_d3d_info *d3d_info = context->d3d_info;
2925 struct wined3d_stream_info *stream_info = &context->stream_info;
2926 DWORD prev_all_vbo = stream_info->all_vbo;
2927 unsigned int i;
2928 WORD map;
2929
2930 context_stream_info_from_declaration(context, state, stream_info);
2931
2932 stream_info->all_vbo = 1;
2933 context->num_buffer_queries = 0;
2934 for (i = 0, map = stream_info->use_map; map; map >>= 1, ++i)
2935 {
2936 struct wined3d_stream_info_element *element;
2937 struct wined3d_bo_address data;
2938 struct wined3d_buffer *buffer;
2939
2940 if (!(map & 1))
2941 continue;
2942
2943 element = &stream_info->elements[i];
2944 buffer = state->streams[element->stream_idx].buffer;
2945
2946 /* We can't use VBOs if the base vertex index is negative. OpenGL
2947 * doesn't accept negative offsets (or rather offsets bigger than the
2948 * VBO, because the pointer is unsigned), so use system memory
2949 * sources. In most sane cases the pointer - offset will still be > 0,
2950 * otherwise it will wrap around to some big value. Hope that with the
2951 * indices the driver wraps it back internally. If not,
2952 * drawStridedSlow is needed, including a vertex buffer path. */
2953 if (state->load_base_vertex_index < 0)
2954 {
2955 WARN_(d3d_perf)("load_base_vertex_index is < 0 (%d), not using VBOs.\n",
2956 state->load_base_vertex_index);
2957 element->data.buffer_object = 0;
2958 element->data.addr += (ULONG_PTR)buffer_get_sysmem(buffer, context);
2959 if ((UINT_PTR)element->data.addr < -state->load_base_vertex_index * element->stride)
2960 FIXME("System memory vertex data load offset is negative!\n");
2961 }
2962 else
2963 {
2964 buffer_internal_preload(buffer, context, state);
2965 buffer_get_memory(buffer, context, &data);
2966 element->data.buffer_object = data.buffer_object;
2967 element->data.addr += (ULONG_PTR)data.addr;
2968 }
2969
2970 if (!element->data.buffer_object)
2971 stream_info->all_vbo = 0;
2972
2973 if (buffer->query)
2974 context->buffer_queries[context->num_buffer_queries++] = buffer->query;
2975
2976 TRACE("Load array %u {%#x:%p}.\n", i, element->data.buffer_object, element->data.addr);
2977 }
2978
2979 if (use_vs(state))
2980 {
2981 if (state->vertex_declaration->half_float_conv_needed && !stream_info->all_vbo)
2982 {
2983 #if defined(STAGING_CSMT)
2984 TRACE("Using draw_strided_slow with vertex shaders for FLOAT16 conversion.\n");
2985 #else /* STAGING_CSMT */
2986 TRACE("Using drawStridedSlow with vertex shaders for FLOAT16 conversion.\n");
2987 #endif /* STAGING_CSMT */
2988 context->use_immediate_mode_draw = TRUE;
2989 }
2990 else
2991 {
2992 context->use_immediate_mode_draw = FALSE;
2993 }
2994 }
2995 else
2996 {
2997 WORD slow_mask = (1 << WINED3D_FFP_PSIZE);
2998 slow_mask |= -!gl_info->supported[ARB_VERTEX_ARRAY_BGRA]
2999 & ((1 << WINED3D_FFP_DIFFUSE) | (1 << WINED3D_FFP_SPECULAR));
3000
3001 if (((stream_info->position_transformed && !d3d_info->xyzrhw)
3002 || (stream_info->use_map & slow_mask)) && !stream_info->all_vbo)
3003 context->use_immediate_mode_draw = TRUE;
3004 else
3005 context->use_immediate_mode_draw = FALSE;
3006 }
3007
3008 if (prev_all_vbo != stream_info->all_vbo)
3009 context_invalidate_state(context, STATE_INDEXBUFFER);
3010 }
3011
3012 /* Context activation is done by the caller. */
3013 static void context_preload_texture(struct wined3d_context *context,
3014 const struct wined3d_state *state, unsigned int idx)
3015 {
3016 struct wined3d_texture *texture;
3017
3018 if (!(texture = state->textures[idx]))
3019 return;
3020
3021 wined3d_texture_load(texture, context, state->sampler_states[idx][WINED3D_SAMP_SRGB_TEXTURE]);
3022 }
3023
3024 /* Context activation is done by the caller. */
3025 static void context_preload_textures(struct wined3d_context *context, const struct wined3d_state *state)
3026 {
3027 unsigned int i;
3028
3029 if (use_vs(state))
3030 {
3031 for (i = 0; i < MAX_VERTEX_SAMPLERS; ++i)
3032 {
3033 if (state->shader[WINED3D_SHADER_TYPE_VERTEX]->reg_maps.resource_info[i].type)
3034 context_preload_texture(context, state, MAX_FRAGMENT_SAMPLERS + i);
3035 }
3036 }
3037
3038 if (use_ps(state))
3039 {
3040 for (i = 0; i < MAX_FRAGMENT_SAMPLERS; ++i)
3041 {
3042 if (state->shader[WINED3D_SHADER_TYPE_PIXEL]->reg_maps.resource_info[i].type)
3043 context_preload_texture(context, state, i);
3044 }
3045 }
3046 else
3047 {
3048 WORD ffu_map = context->fixed_function_usage_map;
3049
3050 for (i = 0; ffu_map; ffu_map >>= 1, ++i)
3051 {
3052 if (ffu_map & 1)
3053 context_preload_texture(context, state, i);
3054 }
3055 }
3056 }
3057
3058 static void context_bind_shader_resources(struct wined3d_context *context, const struct wined3d_state *state)
3059 {
3060 const struct wined3d_gl_info *gl_info = context->gl_info;
3061 struct wined3d_shader_sampler_map_entry *entry;
3062 struct wined3d_shader_resource_view *view;
3063 struct wined3d_sampler *sampler;
3064 struct wined3d_texture *texture;
3065 struct wined3d_shader *shader;
3066 unsigned int i, j, count;
3067
3068 static const struct
3069 {
3070 enum wined3d_shader_type type;
3071 unsigned int base_idx;
3072 unsigned int count;
3073 }
3074 shader_types[] =
3075 {
3076 {WINED3D_SHADER_TYPE_PIXEL, 0, MAX_FRAGMENT_SAMPLERS},
3077 {WINED3D_SHADER_TYPE_VERTEX, MAX_FRAGMENT_SAMPLERS, MAX_VERTEX_SAMPLERS},
3078 };
3079
3080 for (i = 0; i < ARRAY_SIZE(shader_types); ++i)
3081 {
3082 if (!(shader = state->shader[shader_types[i].type]))
3083 continue;
3084
3085 count = shader->reg_maps.sampler_map.count;
3086 if (count > shader_types[i].count)
3087 {
3088 FIXME("Shader %p needs %u samplers, but only %u are supported.\n",
3089 shader, count, shader_types[i].count);
3090 count = shader_types[i].count;
3091 }
3092
3093 for (j = 0; j < count; ++j)
3094 {
3095 entry = &shader->reg_maps.sampler_map.entries[j];
3096
3097 if (!(view = state->shader_resource_view[shader_types[i].type][entry->resource_idx]))
3098 {
3099 WARN("No resource view bound at index %u, %u.\n", shader_types[i].type, entry->resource_idx);
3100 continue;
3101 }
3102
3103 if (view->resource->type == WINED3D_RTYPE_BUFFER)
3104 {
3105 FIXME("Buffer shader resources not supported.\n");
3106 continue;
3107 }
3108
3109 if (!(sampler = state->sampler[shader_types[i].type][entry->sampler_idx]))
3110 {
3111 WARN("No sampler object bound at index %u, %u.\n", shader_types[i].type, entry->sampler_idx);
3112 continue;
3113 }
3114
3115 texture = wined3d_texture_from_resource(view->resource);
3116 wined3d_texture_load(texture, context, FALSE);
3117 context_active_texture(context, gl_info, shader_types[i].base_idx + entry->bind_idx);
3118 wined3d_texture_bind(texture, context, FALSE);
3119
3120 GL_EXTCALL(glBindSampler(shader_types[i].base_idx + entry->bind_idx, sampler->name));
3121 checkGLcall("glBindSampler");
3122 }
3123 }
3124 }
3125
3126 /* Context activation is done by the caller. */
3127 #if defined(STAGING_CSMT)
3128 BOOL context_apply_draw_state(struct wined3d_context *context, const struct wined3d_device *device,
3129 const struct wined3d_state *state)
3130 {
3131 const struct StateEntry *state_table = context->state_table;
3132 const struct wined3d_fb_state *fb = &state->fb;
3133 #else /* STAGING_CSMT */
3134 BOOL context_apply_draw_state(struct wined3d_context *context, struct wined3d_device *device)
3135 {
3136 const struct wined3d_state *state = &device->state;
3137 const struct StateEntry *state_table = context->state_table;
3138 const struct wined3d_fb_state *fb = state->fb;
3139 #endif /* STAGING_CSMT */
3140 unsigned int i, j;
3141 WORD map;
3142
3143 if (!context_validate_rt_config(context->gl_info->limits.buffers,
3144 fb->render_targets, fb->depth_stencil))
3145 return FALSE;
3146
3147 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO && isStateDirty(context, STATE_FRAMEBUFFER))
3148 {
3149 context_validate_onscreen_formats(context, fb->depth_stencil);
3150 }
3151
3152 /* Preload resources before FBO setup. Texture preload in particular may
3153 * result in changes to the current FBO, due to using e.g. FBO blits for
3154 * updating a resource location. */
3155 context_update_tex_unit_map(context, state);
3156 context_preload_textures(context, state);
3157 /* TODO: Right now the dependency on the vertex shader is necessary
3158 * since context_stream_info_from_declaration depends on the reg_maps of
3159 * the current VS but maybe it's possible to relax the coupling in some
3160 * situations at least. */
3161 if (isStateDirty(context, STATE_VDECL) || isStateDirty(context, STATE_STREAMSRC)
3162 || isStateDirty(context, STATE_SHADER(WINED3D_SHADER_TYPE_VERTEX)))
3163 {
3164 context_update_stream_info(context, state);
3165 }
3166 else
3167 {
3168 for (i = 0, map = context->stream_info.use_map; map; map >>= 1, ++i)
3169 {
3170 if (map & 1)
3171 #if defined(STAGING_CSMT)
3172 buffer_internal_preload(state->streams[context->stream_info.elements[i].stream_idx].buffer,
3173 context, state);
3174 }
3175 /* PreLoad may kick buffers out of vram. */
3176 if (isStateDirty(context, STATE_STREAMSRC))
3177 context_update_stream_info(context, state);
3178 #else /* STAGING_CSMT */
3179 buffer_mark_used(state->streams[context->stream_info.elements[i].stream_idx].buffer);
3180 }
3181 #endif /* STAGING_CSMT */
3182 }
3183 if (state->index_buffer)
3184 {
3185 if (context->stream_info.all_vbo)
3186 buffer_internal_preload(state->index_buffer, context, state);
3187 else
3188 buffer_get_sysmem(state->index_buffer, context);
3189 }
3190
3191 for (i = 0; i < WINED3D_SHADER_TYPE_COUNT; ++i)
3192 {
3193 for (j = 0; j < WINED3D_MAX_CBS; ++j)
3194 {
3195 if (state->cb[i][j])
3196 buffer_internal_preload(state->cb[i][j], context, state);
3197 }
3198 }
3199
3200 for (i = 0; i < context->numDirtyEntries; ++i)
3201 {
3202 DWORD rep = context->dirtyArray[i];
3203 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
3204 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
3205 context->isStateDirty[idx] &= ~(1 << shift);
3206 state_table[rep].apply(context, state, rep);
3207 }
3208
3209 if (context->shader_update_mask)
3210 {
3211 device->shader_backend->shader_select(device->shader_priv, context, state);
3212 context->shader_update_mask = 0;
3213 }
3214
3215 if (context->constant_update_mask)
3216 {
3217 device->shader_backend->shader_load_constants(device->shader_priv, context, state);
3218 context->constant_update_mask = 0;
3219 }
3220
3221 if (context->update_shader_resource_bindings)
3222 {
3223 context_bind_shader_resources(context, state);
3224 context->update_shader_resource_bindings = 0;
3225 }
3226
3227 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
3228 {
3229 context_check_fbo_status(context, GL_FRAMEBUFFER);
3230 }
3231
3232 context->numDirtyEntries = 0; /* This makes the whole list clean */
3233 context->last_was_blit = FALSE;
3234
3235 return TRUE;
3236 }
3237
3238 static void context_setup_target(struct wined3d_context *context, struct wined3d_surface *target)
3239 {
3240 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
3241
3242 render_offscreen = wined3d_resource_is_offscreen(&target->container->resource);
3243 if (context->current_rt == target && render_offscreen == old_render_offscreen) return;
3244
3245 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
3246 * the alpha blend state changes with different render target formats. */
3247 if (!context->current_rt)
3248 {
3249 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3250 }
3251 else
3252 {
3253 const struct wined3d_format *old = context->current_rt->resource.format;
3254 const struct wined3d_format *new = target->resource.format;
3255
3256 if (old->id != new->id)
3257 {
3258 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
3259 if ((old->alpha_size && !new->alpha_size) || (!old->alpha_size && new->alpha_size)
3260 || !(target->container->resource.format_flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
3261 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_ALPHABLENDENABLE));
3262
3263 /* Update sRGB writing when switching between formats that do/do not support sRGB writing */
3264 if ((context->current_rt->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE)
3265 != (target->container->resource.format_flags & WINED3DFMT_FLAG_SRGB_WRITE))
3266 context_invalidate_state(context, STATE_RENDER(WINED3D_RS_SRGBWRITEENABLE));
3267 }
3268
3269 /* When switching away from an offscreen render target, and we're not
3270 * using FBOs, we have to read the drawable into the texture. This is
3271 * done via PreLoad (and WINED3D_LOCATION_DRAWABLE set on the surface).
3272 * There are some things that need care though. PreLoad needs a GL context,
3273 * and FindContext is called before the context is activated. It also
3274 * has to be called with the old rendertarget active, otherwise a
3275 * wrong drawable is read. */
3276 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
3277 && old_render_offscreen && context->current_rt != target)
3278 {
3279 struct wined3d_texture *texture = context->current_rt->container;
3280
3281 /* Read the back buffer of the old drawable into the destination texture. */
3282 if (texture->texture_srgb.name)
3283 wined3d_texture_load(texture, context, TRUE);
3284 wined3d_texture_load(texture, context, FALSE);
3285 #if defined(STAGING_CSMT)
3286 wined3d_resource_invalidate_location(&context->current_rt->resource, WINED3D_LOCATION_DRAWABLE);
3287 #else /* STAGING_CSMT */
3288 surface_invalidate_location(context->current_rt, WINED3D_LOCATION_DRAWABLE);
3289 #endif /* STAGING_CSMT */
3290 }
3291 }
3292
3293 context->current_rt = target;
3294 context_set_render_offscreen(context, render_offscreen);
3295 }
3296
3297 struct wined3d_context *context_acquire(const struct wined3d_device *device, struct wined3d_surface *target)
3298 {
3299 struct wined3d_context *current_context = context_get_current();
3300 struct wined3d_context *context;
3301
3302 TRACE("device %p, target %p.\n", device, target);
3303
3304 if (current_context && current_context->destroyed)
3305 current_context = NULL;
3306
3307 if (!target)
3308 {
3309 if (current_context
3310 && current_context->current_rt
3311 && current_context->swapchain->device == device)
3312 {
3313 target = current_context->current_rt;
3314 }
3315 else
3316 {
3317 struct wined3d_swapchain *swapchain = device->swapchains[0];
3318 if (swapchain->back_buffers)
3319 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->back_buffers[0], 0));
3320 else
3321 target = surface_from_resource(wined3d_texture_get_sub_resource(swapchain->front_buffer, 0));
3322 }
3323 }
3324
3325 if (current_context && current_context->current_rt == target)
3326 {
3327 context = current_context;
3328 }
3329 else if (target->container->swapchain)
3330 {
3331 TRACE("Rendering onscreen.\n");
3332
3333 context = swapchain_get_context(target->container->swapchain);
3334 }
3335 else
3336 {
3337 TRACE("Rendering offscreen.\n");
3338
3339 /* Stay with the current context if possible. Otherwise use the
3340 * context for the primary swapchain. */
3341 if (current_context && current_context->swapchain->device == device)
3342 context = current_context;
3343 else
3344 context = swapchain_get_context(device->swapchains[0]);
3345 }
3346
3347 context_enter(context);
3348 context_update_window(context);
3349 context_setup_target(context, target);
3350 if (!context->valid) return context;
3351
3352 if (context != current_context)
3353 {
3354 if (!context_set_current(context))
3355 ERR("Failed to activate the new context.\n");
3356 }
3357 else if (context->needs_set)
3358 {
3359 context_set_gl_context(context);
3360 }
3361
3362 return context;
3363 }