VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/Graphics/Wine/wined3d/context.c@ 39501

最後變更 在這個檔案從39501是 39501,由 vboxsync 提交於 13 年 前

wine/xpdm: fix refering destroyed swapchain

  • 屬性 svn:eol-style 設為 native
檔案大小: 96.4 KB
 
1/*
2 * Context and render target management in wined3d
3 *
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
5 * Copyright 2009 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/*
23 * Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
24 * other than GPL or LGPL is available it will apply instead, Oracle elects to use only
25 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
26 * a choice of LGPL license versions is made available with the language indicating
27 * that LGPLv2 or any later version may be used, or where a choice of which version
28 * of the LGPL is applied is otherwise unspecified.
29 */
30
31#include "config.h"
32#include <stdio.h>
33#ifdef HAVE_FLOAT_H
34# include <float.h>
35#endif
36#include "wined3d_private.h"
37
38WINE_DEFAULT_DEBUG_CHANNEL(d3d);
39
40#define GLINFO_LOCATION (*gl_info)
41
42static DWORD wined3d_context_tls_idx;
43
44/* FBO helper functions */
45
46/* GL locking is done by the caller */
47void context_bind_fbo(struct wined3d_context *context, GLenum target, GLuint *fbo)
48{
49 const struct wined3d_gl_info *gl_info = context->gl_info;
50 GLuint f;
51
52 if (!fbo)
53 {
54 f = 0;
55 }
56 else
57 {
58 if (!*fbo)
59 {
60 gl_info->fbo_ops.glGenFramebuffers(1, fbo);
61 checkGLcall("glGenFramebuffers()");
62 TRACE("Created FBO %u.\n", *fbo);
63 }
64 f = *fbo;
65 }
66
67 switch (target)
68 {
69 case GL_READ_FRAMEBUFFER:
70 if (context->fbo_read_binding == f) return;
71 context->fbo_read_binding = f;
72 break;
73
74 case GL_DRAW_FRAMEBUFFER:
75 if (context->fbo_draw_binding == f) return;
76 context->fbo_draw_binding = f;
77 break;
78
79 case GL_FRAMEBUFFER:
80 if (context->fbo_read_binding == f
81 && context->fbo_draw_binding == f) return;
82 context->fbo_read_binding = f;
83 context->fbo_draw_binding = f;
84 break;
85
86 default:
87 FIXME("Unhandled target %#x.\n", target);
88 break;
89 }
90
91 gl_info->fbo_ops.glBindFramebuffer(target, f);
92 checkGLcall("glBindFramebuffer()");
93}
94
95/* GL locking is done by the caller */
96static void context_clean_fbo_attachments(const struct wined3d_gl_info *gl_info)
97{
98 unsigned int i;
99
100 for (i = 0; i < gl_info->limits.buffers; ++i)
101 {
102 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, 0, 0);
103 checkGLcall("glFramebufferTexture2D()");
104 }
105 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
106 checkGLcall("glFramebufferTexture2D()");
107
108 gl_info->fbo_ops.glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
109 checkGLcall("glFramebufferTexture2D()");
110}
111
112/* GL locking is done by the caller */
113static void context_destroy_fbo(struct wined3d_context *context, GLuint *fbo)
114{
115 const struct wined3d_gl_info *gl_info = context->gl_info;
116
117 context_bind_fbo(context, GL_FRAMEBUFFER, fbo);
118 context_clean_fbo_attachments(gl_info);
119 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
120
121 gl_info->fbo_ops.glDeleteFramebuffers(1, fbo);
122 checkGLcall("glDeleteFramebuffers()");
123}
124
125/* GL locking is done by the caller */
126static void context_apply_attachment_filter_states(IWineD3DSurfaceImpl *surface)
127{
128 IWineD3DBaseTextureImpl *texture_impl;
129
130 /* Update base texture states array */
131 if (SUCCEEDED(IWineD3DSurface_GetContainer((IWineD3DSurface *)surface,
132 &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
133 {
134 IWineD3DDeviceImpl *device = surface->resource.device;
135 BOOL update_minfilter = FALSE;
136 BOOL update_magfilter = FALSE;
137
138 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
139 || texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
140 {
141 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
142 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
143 update_minfilter = TRUE;
144 }
145
146 if (texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
147 {
148 texture_impl->baseTexture.texture_rgb.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
149 update_magfilter = TRUE;
150 }
151
152 if (texture_impl->baseTexture.bindCount)
153 {
154 WARN("Render targets should not be bound to a sampler\n");
155 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
156 }
157
158 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
159
160 if (update_minfilter || update_magfilter)
161 {
162 GLenum target, bind_target;
163 GLint old_binding;
164
165 target = surface->texture_target;
166 if (target == GL_TEXTURE_2D)
167 {
168 bind_target = GL_TEXTURE_2D;
169 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
170 }
171 else if (target == GL_TEXTURE_RECTANGLE_ARB)
172 {
173 bind_target = GL_TEXTURE_RECTANGLE_ARB;
174 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
175 }
176 else
177 {
178 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
179 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
180 }
181
182 glBindTexture(bind_target, surface->texture_name);
183 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
184 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
185 glBindTexture(bind_target, old_binding);
186 }
187
188 checkGLcall("apply_attachment_filter_states()");
189 }
190}
191
192/* GL locking is done by the caller */
193void context_attach_depth_stencil_fbo(struct wined3d_context *context,
194 GLenum fbo_target, IWineD3DSurfaceImpl *depth_stencil, BOOL use_render_buffer)
195{
196 const struct wined3d_gl_info *gl_info = context->gl_info;
197
198 TRACE("Attach depth stencil %p\n", depth_stencil);
199
200 if (depth_stencil)
201 {
202 DWORD format_flags = depth_stencil->resource.format_desc->Flags;
203
204 if (use_render_buffer && depth_stencil->current_renderbuffer)
205 {
206 if (format_flags & WINED3DFMT_FLAG_DEPTH)
207 {
208 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_DEPTH_ATTACHMENT,
209 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
210 checkGLcall("glFramebufferRenderbuffer()");
211 }
212
213 if (format_flags & WINED3DFMT_FLAG_STENCIL)
214 {
215 gl_info->fbo_ops.glFramebufferRenderbuffer(fbo_target, GL_STENCIL_ATTACHMENT,
216 GL_RENDERBUFFER, depth_stencil->current_renderbuffer->id);
217 checkGLcall("glFramebufferRenderbuffer()");
218 }
219 }
220 else
221 {
222 surface_prepare_texture(depth_stencil, gl_info, FALSE);
223 context_apply_attachment_filter_states(depth_stencil);
224
225 if (format_flags & WINED3DFMT_FLAG_DEPTH)
226 {
227 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT,
228 depth_stencil->texture_target, depth_stencil->texture_name,
229 depth_stencil->texture_level);
230 checkGLcall("glFramebufferTexture2D()");
231 }
232
233 if (format_flags & WINED3DFMT_FLAG_STENCIL)
234 {
235 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT,
236 depth_stencil->texture_target, depth_stencil->texture_name,
237 depth_stencil->texture_level);
238 checkGLcall("glFramebufferTexture2D()");
239 }
240 }
241
242 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
243 {
244 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
245 checkGLcall("glFramebufferTexture2D()");
246 }
247
248 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
249 {
250 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
251 checkGLcall("glFramebufferTexture2D()");
252 }
253 }
254 else
255 {
256 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
257 checkGLcall("glFramebufferTexture2D()");
258
259 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
260 checkGLcall("glFramebufferTexture2D()");
261 }
262}
263
264/* GL locking is done by the caller */
265void context_attach_surface_fbo(const struct wined3d_context *context,
266 GLenum fbo_target, DWORD idx, IWineD3DSurfaceImpl *surface)
267{
268 const struct wined3d_gl_info *gl_info = context->gl_info;
269
270 TRACE("Attach surface %p to %u\n", surface, idx);
271
272 if (surface)
273 {
274 surface_prepare_texture(surface, gl_info, FALSE);
275 context_apply_attachment_filter_states(surface);
276
277 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, surface->texture_target,
278 surface->texture_name, surface->texture_level);
279 checkGLcall("glFramebufferTexture2D()");
280 }
281 else
282 {
283 gl_info->fbo_ops.glFramebufferTexture2D(fbo_target, GL_COLOR_ATTACHMENT0 + idx, GL_TEXTURE_2D, 0, 0);
284 checkGLcall("glFramebufferTexture2D()");
285 }
286}
287
288/* GL locking is done by the caller */
289static void context_check_fbo_status(struct wined3d_context *context)
290{
291 const struct wined3d_gl_info *gl_info = context->gl_info;
292 GLenum status;
293
294 status = gl_info->fbo_ops.glCheckFramebufferStatus(GL_FRAMEBUFFER);
295 if (status == GL_FRAMEBUFFER_COMPLETE)
296 {
297 TRACE("FBO complete\n");
298 } else {
299 IWineD3DSurfaceImpl *attachment;
300 unsigned int i;
301 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
302
303 if (!context->current_fbo)
304 {
305 ERR("FBO 0 is incomplete, driver bug?\n");
306 return;
307 }
308
309 /* Dump the FBO attachments */
310 for (i = 0; i < gl_info->limits.buffers; ++i)
311 {
312 attachment = context->current_fbo->render_targets[i];
313 if (attachment)
314 {
315 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
316 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
317 attachment->pow2Width, attachment->pow2Height);
318 }
319 }
320 attachment = context->current_fbo->depth_stencil;
321 if (attachment)
322 {
323 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
324 attachment, debug_d3dformat(attachment->resource.format_desc->format),
325 attachment->pow2Width, attachment->pow2Height);
326 }
327 }
328}
329
330static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
331{
332 const struct wined3d_gl_info *gl_info = context->gl_info;
333 IWineD3DDeviceImpl *device = context_get_device(context);
334 struct fbo_entry *entry;
335
336 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
337 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, gl_info->limits.buffers * sizeof(*entry->render_targets));
338 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
339 entry->depth_stencil = (IWineD3DSurfaceImpl *)device->stencilBufferTarget;
340 entry->attached = FALSE;
341 entry->id = 0;
342
343 return entry;
344}
345
346/* GL locking is done by the caller */
347static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
348{
349 const struct wined3d_gl_info *gl_info = context->gl_info;
350 IWineD3DDeviceImpl *device = context_get_device(context);
351
352 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
353 context_clean_fbo_attachments(gl_info);
354
355 memcpy(entry->render_targets, device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets));
356 entry->depth_stencil = (IWineD3DSurfaceImpl *)device->stencilBufferTarget;
357 entry->attached = FALSE;
358}
359
360/* GL locking is done by the caller */
361static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
362{
363 if (entry->id)
364 {
365 TRACE("Destroy FBO %d\n", entry->id);
366 context_destroy_fbo(context, &entry->id);
367 }
368 --context->fbo_entry_count;
369 list_remove(&entry->entry);
370 HeapFree(GetProcessHeap(), 0, entry->render_targets);
371 HeapFree(GetProcessHeap(), 0, entry);
372}
373
374
375/* GL locking is done by the caller */
376static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
377{
378 const struct wined3d_gl_info *gl_info = context->gl_info;
379 IWineD3DDeviceImpl *device = context_get_device(context);
380 struct fbo_entry *entry;
381
382 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
383 {
384 if (!memcmp(entry->render_targets,
385 device->render_targets, gl_info->limits.buffers * sizeof(*entry->render_targets))
386 && entry->depth_stencil == (IWineD3DSurfaceImpl *)device->stencilBufferTarget)
387 {
388 list_remove(&entry->entry);
389 list_add_head(&context->fbo_list, &entry->entry);
390 return entry;
391 }
392 }
393
394 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
395 {
396 entry = context_create_fbo_entry(context);
397 list_add_head(&context->fbo_list, &entry->entry);
398 ++context->fbo_entry_count;
399 }
400 else
401 {
402 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
403 context_reuse_fbo_entry(context, entry);
404 list_remove(&entry->entry);
405 list_add_head(&context->fbo_list, &entry->entry);
406 }
407
408 return entry;
409}
410
411/* GL locking is done by the caller */
412static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
413{
414 const struct wined3d_gl_info *gl_info = context->gl_info;
415 IWineD3DDeviceImpl *device = context_get_device(context);
416 unsigned int i;
417
418 context_bind_fbo(context, GL_FRAMEBUFFER, &entry->id);
419
420 if (!entry->attached)
421 {
422 /* Apply render targets */
423 for (i = 0; i < gl_info->limits.buffers; ++i)
424 {
425 IWineD3DSurfaceImpl *render_target = (IWineD3DSurfaceImpl *)device->render_targets[i];
426 context_attach_surface_fbo(context, GL_FRAMEBUFFER, i, render_target);
427 }
428
429 /* Apply depth targets */
430 if (device->stencilBufferTarget)
431 {
432 unsigned int w = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Width;
433 unsigned int h = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Height;
434
435 surface_set_compatible_renderbuffer(device->stencilBufferTarget, w, h);
436 }
437 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, (IWineD3DSurfaceImpl *)device->stencilBufferTarget, TRUE);
438
439 entry->attached = TRUE;
440 }
441 else
442 {
443 for (i = 0; i < gl_info->limits.buffers; ++i)
444 {
445 if (device->render_targets[i])
446 context_apply_attachment_filter_states((IWineD3DSurfaceImpl *)device->render_targets[i]);
447 }
448 if (device->stencilBufferTarget)
449 context_apply_attachment_filter_states((IWineD3DSurfaceImpl *)device->stencilBufferTarget);
450 }
451
452 for (i = 0; i < gl_info->limits.buffers; ++i)
453 {
454 if (device->render_targets[i])
455 device->draw_buffers[i] = GL_COLOR_ATTACHMENT0 + i;
456 else
457 device->draw_buffers[i] = GL_NONE;
458 }
459}
460
461/* GL locking is done by the caller */
462static void context_apply_fbo_state(struct wined3d_context *context)
463{
464 struct fbo_entry *entry, *entry2;
465
466 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
467 {
468 context_destroy_fbo_entry(context, entry);
469 }
470
471 if (context->rebind_fbo)
472 {
473 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
474 context->rebind_fbo = FALSE;
475 }
476
477 if (context->render_offscreen)
478 {
479 context->current_fbo = context_find_fbo_entry(context);
480 context_apply_fbo_entry(context, context->current_fbo);
481 } else {
482 context->current_fbo = NULL;
483 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
484 }
485
486#if defined(DEBUG) && !defined(DEBUG_misha)
487 context_check_fbo_status(context);
488#endif
489}
490
491/* Context activation is done by the caller. */
492void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
493{
494 const struct wined3d_gl_info *gl_info = context->gl_info;
495
496 if (context->free_occlusion_query_count)
497 {
498 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
499 }
500 else
501 {
502 if (gl_info->supported[ARB_OCCLUSION_QUERY])
503 {
504 ENTER_GL();
505 GL_EXTCALL(glGenQueriesARB(1, &query->id));
506 checkGLcall("glGenQueriesARB");
507 LEAVE_GL();
508
509 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
510 }
511 else
512 {
513 WARN("Occlusion queries not supported, not allocating query id.\n");
514 query->id = 0;
515 }
516 }
517
518 query->context = context;
519 list_add_head(&context->occlusion_queries, &query->entry);
520}
521
522void context_free_occlusion_query(struct wined3d_occlusion_query *query)
523{
524 struct wined3d_context *context = query->context;
525
526 list_remove(&query->entry);
527 query->context = NULL;
528
529 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
530 {
531 UINT new_size = context->free_occlusion_query_size << 1;
532 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
533 new_size * sizeof(*context->free_occlusion_queries));
534
535 if (!new_data)
536 {
537 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
538 return;
539 }
540
541 context->free_occlusion_query_size = new_size;
542 context->free_occlusion_queries = new_data;
543 }
544
545 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
546}
547
548/* Context activation is done by the caller. */
549void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
550{
551 const struct wined3d_gl_info *gl_info = context->gl_info;
552
553 if (context->free_event_query_count)
554 {
555 query->object = context->free_event_queries[--context->free_event_query_count];
556 }
557 else
558 {
559 if (gl_info->supported[ARB_SYNC])
560 {
561 /* Using ARB_sync, not much to do here. */
562 query->object.sync = NULL;
563 TRACE("Allocated event query %p in context %p.\n", query->object.sync, context);
564 }
565 else if (gl_info->supported[APPLE_FENCE])
566 {
567 ENTER_GL();
568 GL_EXTCALL(glGenFencesAPPLE(1, &query->object.id));
569 checkGLcall("glGenFencesAPPLE");
570 LEAVE_GL();
571
572 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
573 }
574 else if(gl_info->supported[NV_FENCE])
575 {
576 ENTER_GL();
577 GL_EXTCALL(glGenFencesNV(1, &query->object.id));
578 checkGLcall("glGenFencesNV");
579 LEAVE_GL();
580
581 TRACE("Allocated event query %u in context %p.\n", query->object.id, context);
582 }
583 else
584 {
585 WARN("Event queries not supported, not allocating query id.\n");
586 query->object.id = 0;
587 }
588 }
589
590 query->context = context;
591 list_add_head(&context->event_queries, &query->entry);
592}
593
594void context_free_event_query(struct wined3d_event_query *query)
595{
596 struct wined3d_context *context = query->context;
597
598 list_remove(&query->entry);
599 query->context = NULL;
600
601 if (context->free_event_query_count >= context->free_event_query_size - 1)
602 {
603 UINT new_size = context->free_event_query_size << 1;
604 union wined3d_gl_query_object *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
605 new_size * sizeof(*context->free_event_queries));
606
607 if (!new_data)
608 {
609 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->object.id, context);
610 return;
611 }
612
613 context->free_event_query_size = new_size;
614 context->free_event_queries = new_data;
615 }
616
617 context->free_event_queries[context->free_event_query_count++] = query->object;
618}
619
620void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
621{
622 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
623 UINT i;
624
625 if (!This->d3d_initialized) return;
626
627 switch(type)
628 {
629 case WINED3DRTYPE_SURFACE:
630 {
631 for (i = 0; i < This->numContexts; ++i)
632 {
633 struct wined3d_context *context = This->contexts[i];
634 const struct wined3d_gl_info *gl_info = context->gl_info;
635 struct fbo_entry *entry, *entry2;
636
637 if (context->current_rt == (IWineD3DSurface *)resource) context->current_rt = NULL;
638
639 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
640 {
641 UINT j;
642
643 if (entry->depth_stencil == (IWineD3DSurfaceImpl *)resource)
644 {
645 list_remove(&entry->entry);
646 list_add_head(&context->fbo_destroy_list, &entry->entry);
647 continue;
648 }
649
650 for (j = 0; j < gl_info->limits.buffers; ++j)
651 {
652 if (entry->render_targets[j] == (IWineD3DSurfaceImpl *)resource)
653 {
654 list_remove(&entry->entry);
655 list_add_head(&context->fbo_destroy_list, &entry->entry);
656 break;
657 }
658 }
659 }
660 }
661
662 break;
663 }
664
665 default:
666 break;
667 }
668}
669
670void context_surface_update(struct wined3d_context *context, IWineD3DSurfaceImpl *surface)
671{
672 const struct wined3d_gl_info *gl_info = context->gl_info;
673 struct fbo_entry *entry = context->current_fbo;
674 unsigned int i;
675
676 if (!entry || context->rebind_fbo) return;
677
678 for (i = 0; i < gl_info->limits.buffers; ++i)
679 {
680 if (surface == entry->render_targets[i])
681 {
682 TRACE("Updated surface %p is bound as color attachment %u to the current FBO.\n", surface, i);
683 context->rebind_fbo = TRUE;
684 return;
685 }
686 }
687
688 if (surface == entry->depth_stencil)
689 {
690 TRACE("Updated surface %p is bound as depth attachment to the current FBO.\n", surface);
691 context->rebind_fbo = TRUE;
692 }
693}
694
695static BOOL context_set_pixel_format(const struct wined3d_gl_info *gl_info, HDC dc, int format)
696{
697 int current = GetPixelFormat(dc);
698
699 if (current == format) return TRUE;
700
701 if (!current)
702 {
703 if (!SetPixelFormat(dc, format, NULL))
704 {
705 ERR("Failed to set pixel format %d on device context %p, last error %#x.\n",
706 format, dc, GetLastError());
707 return FALSE;
708 }
709 return TRUE;
710 }
711
712 /* By default WGL doesn't allow pixel format adjustments but we need it
713 * here. For this reason there's a Wine specific wglSetPixelFormat()
714 * which allows us to set the pixel format multiple times. Only use it
715 * when really needed. */
716 if (gl_info->supported[WGL_WINE_PIXEL_FORMAT_PASSTHROUGH])
717 {
718 if (!GL_EXTCALL(wglSetPixelFormatWINE(dc, format, NULL)))
719 {
720 ERR("wglSetPixelFormatWINE failed to set pixel format %d on device context %p.\n",
721 format, dc);
722 return FALSE;
723 }
724 return TRUE;
725 }
726
727 /* OpenGL doesn't allow pixel format adjustments. Print an error and
728 * continue using the old format. There's a big chance that the old
729 * format works although with a performance hit and perhaps rendering
730 * errors. */
731 ERR("Unable to set pixel format %d on device context %p. Already using format %d.\n",
732 format, dc, current);
733 return TRUE;
734}
735
736#ifdef VBOX_WITH_WDDM
737static BOOL swapchain_validate(IWineD3DSwapChainImpl *swapchain)
738{
739 if (!swapchain->hDC)
740 {
741 ERR("NULL hDC");
742 return FALSE;
743 }
744
745#ifdef DEBUG
746 {
747 HWND hWnd = WindowFromDC(swapchain->hDC);
748 if (hWnd != swapchain->win_handle)
749 {
750 ERR("Unexpected swapchain for dc %p window expected %p, but was %p.\n", swapchain->hDC, swapchain->win_handle, hWnd);
751 }
752 }
753#endif
754 return TRUE;
755}
756
757static IWineD3DSwapChainImpl * swapchain_find_valid(IWineD3DDeviceImpl *device)
758{
759 int i;
760 for (i = device->NumberOfSwapChains - 1; i >= 0 ; --i)
761 {
762 if (swapchain_validate((IWineD3DSwapChainImpl*)device->swapchains[i]))
763 {
764 return (IWineD3DSwapChainImpl*)device->swapchains[i];
765 }
766 }
767
768 return NULL;
769}
770#endif
771
772static void context_update_window(struct wined3d_context *context
773#ifdef VBOX_WITH_WDDM
774 , IWineD3DSwapChainImpl *swapchain
775#endif
776 )
777{
778#ifdef VBOX_WITH_WDDM
779 TRACE("Updating context %p swapchain from %p to %p.\n",
780 context, context->currentSwapchain, swapchain);
781
782 context->valid = 1;
783
784 if (!swapchain_validate(swapchain))
785 {
786 ERR("invalid swapchain %p\n", swapchain);
787 goto err;
788 }
789 context->currentSwapchain = swapchain;
790
791 if (!context_set_pixel_format(context->gl_info, swapchain->hDC, context->pixel_format))
792 {
793 ERR("Failed to set pixel format %d on device context %p.\n",
794 context->pixel_format, swapchain->hDC);
795 goto err;
796 }
797
798 if (!pwglMakeCurrent(swapchain->hDC, context->glCtx))
799 {
800 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
801 context->glCtx, swapchain->hDC, GetLastError());
802 goto err;
803 }
804#else
805 TRACE("Updating context %p window from %p to %p.\n",
806 context, context->win_handle, context->swapchain->win_handle);
807
808 if (context->valid)
809 {
810 if (!ReleaseDC(context->win_handle, context->hdc))
811 {
812 ERR("Failed to release device context %p, last error %#x.\n",
813 context->hdc, GetLastError());
814 }
815 }
816 else context->valid = 1;
817
818 context->win_handle = context->swapchain->win_handle;
819 if (!(context->hdc = GetDC(context->win_handle)))
820 {
821 ERR("Failed to get a device context for window %p.\n", context->win_handle);
822 goto err;
823 }
824
825 if (!context_set_pixel_format(context->gl_info, context->hdc, context->pixel_format))
826 {
827 ERR("Failed to set pixel format %d on device context %p.\n",
828 context->pixel_format, context->hdc);
829 goto err;
830 }
831
832 if (!pwglMakeCurrent(context->hdc, context->glCtx))
833 {
834 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
835 context->glCtx, context->hdc, GetLastError());
836 goto err;
837 }
838#endif
839
840 return;
841err:
842 context->valid = 0;
843}
844
845static void context_validate(struct wined3d_context *context
846#ifdef VBOX_WITH_WDDM
847 , IWineD3DSwapChainImpl *swapchain
848# ifdef DEBUG_misha
849 , BOOL fExpectedValid
850# endif
851#endif
852
853 )
854{
855#ifdef VBOX_WITH_WDDM
856 if (!swapchain)
857 {
858 swapchain = context->currentSwapchain;
859 }
860
861 if (!swapchain)
862 {
863 context->valid = FALSE;
864# ifdef DEBUG_misha
865 if (fExpectedValid)
866 {
867 ERR("no current swapchain!\n");
868 }
869# endif
870 return;
871 }
872
873 if (swapchain == context->currentSwapchain)
874 {
875 context->valid = swapchain_validate(context->currentSwapchain);
876 }
877 else
878#else
879 HWND wnd = WindowFromDC(context->hdc);
880
881 if (wnd != context->win_handle)
882 {
883 DWORD winEr = GetLastError();
884 WARN("DC %p belongs to window %p instead of %p., winEr(%d)\n",
885 context->hdc, wnd, context->win_handle, winEr);
886 context->valid = 0;
887 }
888
889 if (context->swapchain && context->win_handle != context->swapchain->win_handle)
890#endif
891 {
892 context_update_window(context
893#ifdef VBOX_WITH_WDDM
894 , swapchain
895#endif
896 );
897 }
898}
899
900#ifdef VBOX_WITH_WDDM
901static void context_validate_adjust_wnd(struct wined3d_context *context)
902{
903 IWineD3DSwapChainImpl *swapchain = NULL;
904
905 context_validate(context, NULL
906# ifdef DEBUG_misha
907 , FALSE
908# endif
909 );
910 if (context->valid)
911 return;
912
913 swapchain = swapchain_find_valid(context->device);
914 if (swapchain)
915 {
916 context_validate(context, swapchain
917# ifdef DEBUG_misha
918 , TRUE
919# endif
920 );
921 if (!context->valid)
922 {
923 ERR("unexpected\n");
924 }
925 }
926 else
927 {
928 ERR("novalid swapchain found\n");
929 }
930}
931#endif
932
933static void context_destroy_gl_resources(struct wined3d_context *context)
934{
935 const struct wined3d_gl_info *gl_info = context->gl_info;
936 struct wined3d_occlusion_query *occlusion_query;
937 struct wined3d_event_query *event_query;
938 struct fbo_entry *entry, *entry2;
939 HGLRC restore_ctx;
940 HDC restore_dc;
941 unsigned int i;
942
943 restore_ctx = pwglGetCurrentContext();
944 restore_dc = pwglGetCurrentDC();
945
946#ifdef VBOX_WITH_WDDM
947 context_validate_adjust_wnd(context);
948 if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->currentSwapchain->hDC, context->glCtx);
949 else restore_ctx = NULL;
950#else
951 context_validate(context);
952 if (context->valid && restore_ctx != context->glCtx) pwglMakeCurrent(context->hdc, context->glCtx);
953 else restore_ctx = NULL;
954#endif
955
956 ENTER_GL();
957
958 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
959 {
960 if (context->valid && gl_info->supported[ARB_OCCLUSION_QUERY])
961 GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
962 occlusion_query->context = NULL;
963 }
964
965 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
966 {
967 if (context->valid)
968 {
969 if (gl_info->supported[ARB_SYNC])
970 {
971 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
972 }
973 else if (gl_info->supported[APPLE_FENCE]) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->object.id));
974 else if (gl_info->supported[NV_FENCE]) GL_EXTCALL(glDeleteFencesNV(1, &event_query->object.id));
975 }
976 event_query->context = NULL;
977 }
978
979 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_destroy_list, struct fbo_entry, entry)
980 {
981 if (!context->valid) entry->id = 0;
982 context_destroy_fbo_entry(context, entry);
983 }
984
985 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
986 {
987 if (!context->valid) entry->id = 0;
988 context_destroy_fbo_entry(context, entry);
989 }
990
991 if (context->valid)
992 {
993 if (context->src_fbo)
994 {
995 TRACE("Destroy src FBO %d\n", context->src_fbo);
996 context_destroy_fbo(context, &context->src_fbo);
997 }
998 if (context->dst_fbo)
999 {
1000 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1001 context_destroy_fbo(context, &context->dst_fbo);
1002 }
1003 if (context->dummy_arbfp_prog)
1004 {
1005 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
1006 }
1007
1008 if (gl_info->supported[ARB_OCCLUSION_QUERY])
1009 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
1010
1011 if (gl_info->supported[ARB_SYNC])
1012 {
1013 if (event_query->object.sync) GL_EXTCALL(glDeleteSync(event_query->object.sync));
1014 }
1015 else if (gl_info->supported[APPLE_FENCE])
1016 {
1017 for (i = 0; i < context->free_event_query_count; ++i)
1018 {
1019 GL_EXTCALL(glDeleteFencesAPPLE(1, &context->free_event_queries[i].id));
1020 }
1021 }
1022 else if (gl_info->supported[NV_FENCE])
1023 {
1024 for (i = 0; i < context->free_event_query_count; ++i)
1025 {
1026 GL_EXTCALL(glDeleteFencesNV(1, &context->free_event_queries[i].id));
1027 }
1028 }
1029
1030 checkGLcall("context cleanup");
1031 }
1032
1033 LEAVE_GL();
1034
1035 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
1036 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
1037
1038 if (restore_ctx)
1039 {
1040 if (!pwglMakeCurrent(restore_dc, restore_ctx))
1041 {
1042 DWORD err = GetLastError();
1043 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1044 restore_ctx, restore_dc, err);
1045 }
1046 }
1047 else if (pwglGetCurrentContext() && !pwglMakeCurrent(NULL, NULL))
1048 {
1049 ERR("Failed to disable GL context.\n");
1050 }
1051#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1052# ifndef VBOX_WITH_WDDM
1053 ReleaseDC(context->win_handle, context->hdc);
1054# else
1055 VBoxExtReleaseDC(context->win_handle, context->hdc);
1056# endif
1057#endif
1058 if (!pwglDeleteContext(context->glCtx))
1059 {
1060 DWORD err = GetLastError();
1061 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
1062 }
1063}
1064
1065DWORD context_get_tls_idx(void)
1066{
1067 return wined3d_context_tls_idx;
1068}
1069
1070void context_set_tls_idx(DWORD idx)
1071{
1072 wined3d_context_tls_idx = idx;
1073}
1074
1075#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
1076static struct wined3d_context *context_get_current_ex(DWORD adjustTid)
1077{
1078 struct wined3d_context *ctx = TlsGetValue(wined3d_context_tls_idx);
1079 if (!adjustTid)
1080 return ctx;
1081 if (!ctx || ctx->tid == adjustTid)
1082 return ctx;
1083 if (context_set_current(ctx))
1084 {
1085 Assert(ctx->tid == adjustTid);
1086 return ctx;
1087 }
1088 ERR("context_set_current failed\n");
1089 return NULL;
1090}
1091#endif
1092
1093struct wined3d_context *context_get_current(void)
1094{
1095#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1096 return TlsGetValue(wined3d_context_tls_idx);
1097#else
1098 DWORD tid = GetCurrentThreadId();
1099 return context_get_current_ex(tid);
1100#endif
1101}
1102
1103
1104BOOL context_set_current(struct wined3d_context *ctx)
1105{
1106#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
1107 struct wined3d_context *old = context_get_current_ex(0);
1108 DWORD tid = GetCurrentThreadId();
1109#else
1110 struct wined3d_context *old = context_get_current();
1111#endif
1112 if (old == ctx)
1113 {
1114#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
1115 if (ctx && ctx->tid != tid)
1116 {
1117 old = NULL;
1118 }
1119 else
1120#endif
1121 {
1122 TRACE("Already using D3D context %p.\n", ctx);
1123 return TRUE;
1124 }
1125 }
1126
1127 if (old)
1128 {
1129#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
1130 old->tid = 0;
1131#endif
1132 if (old->destroyed)
1133 {
1134 TRACE("Switching away from destroyed context %p.\n", old);
1135 context_destroy_gl_resources(old);
1136 HeapFree(GetProcessHeap(), 0, old);
1137 }
1138 else
1139 {
1140 old->current = 0;
1141 }
1142 }
1143
1144 if (ctx)
1145 {
1146#ifdef VBOX_WITH_WDDM
1147 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->currentSwapchain->hDC);
1148 if (!pwglMakeCurrent(ctx->currentSwapchain->hDC, ctx->glCtx))
1149 {
1150 DWORD err = GetLastError();
1151 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
1152 ctx->glCtx, ctx->currentSwapchain->hDC, err);
1153 TlsSetValue(wined3d_context_tls_idx, NULL);
1154 return FALSE;
1155 }
1156#else
1157 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
1158 if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
1159 {
1160 DWORD err = GetLastError();
1161 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
1162 ctx->glCtx, ctx->hdc, err);
1163 TlsSetValue(wined3d_context_tls_idx, NULL);
1164 return FALSE;
1165 }
1166#endif
1167 ctx->current = 1;
1168 }
1169 else if(pwglGetCurrentContext())
1170 {
1171 TRACE("Clearing current D3D context.\n");
1172 if (!pwglMakeCurrent(NULL, NULL))
1173 {
1174 DWORD err = GetLastError();
1175 ERR("Failed to clear current GL context, last error %#x.\n", err);
1176 TlsSetValue(wined3d_context_tls_idx, NULL);
1177 return FALSE;
1178 }
1179 }
1180
1181#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1182 return TlsSetValue(wined3d_context_tls_idx, ctx);
1183#else
1184 if (TlsSetValue(wined3d_context_tls_idx, ctx))
1185 {
1186 if (ctx)
1187 {
1188 ctx->tid = tid;
1189 }
1190 return TRUE;
1191 }
1192 else
1193 {
1194 DWORD err = GetLastError();
1195 ERR("Failed to set tls value, last error %#x.\n", err);
1196 }
1197 return FALSE;
1198#endif
1199}
1200
1201void context_release(struct wined3d_context *context)
1202{
1203 TRACE("Releasing context %p, level %u.\n", context, context->level);
1204
1205 if (WARN_ON(d3d))
1206 {
1207 if (!context->level)
1208 WARN("Context %p is not active.\n", context);
1209 else if (context != context_get_current())
1210 WARN("Context %p is not the current context.\n", context);
1211 }
1212
1213 if (!--context->level && context->restore_ctx)
1214 {
1215 TRACE("Restoring GL context %p on device context %p.\n", context->restore_ctx, context->restore_dc);
1216 if (!pwglMakeCurrent(context->restore_dc, context->restore_ctx))
1217 {
1218 DWORD err = GetLastError();
1219 ERR("Failed to restore GL context %p on device context %p, last error %#x.\n",
1220 context->restore_ctx, context->restore_dc, err);
1221 }
1222#ifdef VBOX_WITH_WDDM
1223 else
1224 {
1225 /* success branch */
1226 /* sync back our tls with gl settings */
1227 const struct wined3d_context *current_context = context_get_current();
1228 if (current_context && current_context->glCtx != context->restore_ctx)
1229 {
1230 IWineD3DDeviceImpl *device = context->device;
1231 UINT i = 0;
1232 for (; i < device->numContexts; ++i)
1233 {
1234 struct wined3d_context *ctx = device->contexts[i];
1235 if (ctx->glCtx == context->restore_ctx)
1236 {
1237 context_set_current(ctx);
1238 break;
1239 }
1240 }
1241
1242 if (i == device->numContexts)
1243 {
1244 context_set_current(NULL);
1245 }
1246 }
1247 }
1248#endif
1249
1250 context->restore_ctx = NULL;
1251 context->restore_dc = NULL;
1252 }
1253}
1254
1255static void context_enter(struct wined3d_context *context)
1256{
1257 TRACE("Entering context %p, level %u.\n", context, context->level + 1);
1258
1259 if (!context->level++)
1260 {
1261 const struct wined3d_context *current_context = context_get_current();
1262 HGLRC current_gl = pwglGetCurrentContext();
1263
1264 if (current_gl && (!current_context || current_context->glCtx != current_gl))
1265 {
1266 TRACE("Another GL context (%p on device context %p) is already current.\n",
1267 current_gl, pwglGetCurrentDC());
1268 context->restore_ctx = current_gl;
1269 context->restore_dc = pwglGetCurrentDC();
1270 }
1271 }
1272}
1273
1274/*****************************************************************************
1275 * Context_MarkStateDirty
1276 *
1277 * Marks a state in a context dirty. Only one context, opposed to
1278 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
1279 * contexts
1280 *
1281 * Params:
1282 * context: Context to mark the state dirty in
1283 * state: State to mark dirty
1284 * StateTable: Pointer to the state table in use(for state grouping)
1285 *
1286 *****************************************************************************/
1287static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
1288{
1289 DWORD rep = StateTable[state].representative;
1290 DWORD idx;
1291 BYTE shift;
1292
1293 if (isStateDirty(context, rep)) return;
1294
1295 context->dirtyArray[context->numDirtyEntries++] = rep;
1296 idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
1297 shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
1298 context->isStateDirty[idx] |= (1 << shift);
1299}
1300
1301/* This function takes care of WineD3D pixel format selection. */
1302static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
1303 const struct wined3d_format_desc *color_format_desc, const struct wined3d_format_desc *ds_format_desc,
1304 BOOL auxBuffers, int numSamples, BOOL findCompatible)
1305{
1306 int iPixelFormat=0;
1307 unsigned int matchtry;
1308 short redBits, greenBits, blueBits, alphaBits, colorBits;
1309 short depthBits=0, stencilBits=0;
1310
1311 struct match_type {
1312 BOOL require_aux;
1313 BOOL exact_alpha;
1314 BOOL exact_color;
1315 } matches[] = {
1316 /* First, try without alpha match buffers. MacOS supports aux buffers only
1317 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
1318 * Then try without aux buffers - this is the most common cause for not
1319 * finding a pixel format. Also some drivers(the open source ones)
1320 * only offer 32 bit ARB pixel formats. First try without an exact alpha
1321 * match, then try without an exact alpha and color match.
1322 */
1323 { TRUE, TRUE, TRUE },
1324 { TRUE, FALSE, TRUE },
1325 { FALSE, TRUE, TRUE },
1326 { FALSE, FALSE, TRUE },
1327 { TRUE, FALSE, FALSE },
1328 { FALSE, FALSE, FALSE },
1329 };
1330
1331 int i = 0;
1332 int nCfgs = This->adapter->nCfgs;
1333
1334 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, findCompatible=%d\n",
1335 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
1336 auxBuffers, numSamples, findCompatible);
1337
1338 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
1339 {
1340 ERR("Unable to get color bits for format %s (%#x)!\n",
1341 debug_d3dformat(color_format_desc->format), color_format_desc->format);
1342 return 0;
1343 }
1344
1345 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
1346
1347 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
1348 for(i=0; i<nCfgs; i++) {
1349 BOOL exactDepthMatch = TRUE;
1350 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
1351
1352 /* For now only accept RGBA formats. Perhaps some day we will
1353 * allow floating point formats for pbuffers. */
1354 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
1355 continue;
1356
1357 /* In window mode we need a window drawable format and double buffering. */
1358 if(!(cfg->windowDrawable && cfg->doubleBuffer))
1359 continue;
1360
1361 /* We like to have aux buffers in backbuffer mode */
1362 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
1363 continue;
1364
1365 if(matches[matchtry].exact_color) {
1366 if(cfg->redSize != redBits)
1367 continue;
1368 if(cfg->greenSize != greenBits)
1369 continue;
1370 if(cfg->blueSize != blueBits)
1371 continue;
1372 } else {
1373 if(cfg->redSize < redBits)
1374 continue;
1375 if(cfg->greenSize < greenBits)
1376 continue;
1377 if(cfg->blueSize < blueBits)
1378 continue;
1379 }
1380 if(matches[matchtry].exact_alpha) {
1381 if(cfg->alphaSize != alphaBits)
1382 continue;
1383 } else {
1384 if(cfg->alphaSize < alphaBits)
1385 continue;
1386 }
1387
1388 /* We try to locate a format which matches our requirements exactly. In case of
1389 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
1390 if(cfg->depthSize < depthBits)
1391 continue;
1392 else if(cfg->depthSize > depthBits)
1393 exactDepthMatch = FALSE;
1394
1395 /* In all cases make sure the number of stencil bits matches our requirements
1396 * even when we don't need stencil because it could affect performance EXCEPT
1397 * on cards which don't offer depth formats without stencil like the i915 drivers
1398 * on Linux. */
1399 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
1400 continue;
1401
1402 /* Check multisampling support */
1403 if(cfg->numSamples != numSamples)
1404 continue;
1405
1406 /* When we have passed all the checks then we have found a format which matches our
1407 * requirements. Note that we only check for a limit number of capabilities right now,
1408 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1409 * can still differ in things like multisampling, stereo, SRGB and other flags.
1410 */
1411
1412 /* Exit the loop as we have found a format :) */
1413 if(exactDepthMatch) {
1414 iPixelFormat = cfg->iPixelFormat;
1415 break;
1416 } else if(!iPixelFormat) {
1417 /* In the end we might end up with a format which doesn't exactly match our depth
1418 * requirements. Accept the first format we found because formats with higher iPixelFormat
1419 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1420 iPixelFormat = cfg->iPixelFormat;
1421 }
1422 }
1423 }
1424
1425 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1426 if(!iPixelFormat && !findCompatible) {
1427#ifdef DEBUG_misha
1428 WARN("Can't find a suitable iPixelFormat\n");
1429#elif !defined(VBOX_WITH_WDDM)
1430 ERR("Can't find a suitable iPixelFormat\n");
1431#endif
1432 return FALSE;
1433 } else if(!iPixelFormat) {
1434 PIXELFORMATDESCRIPTOR pfd;
1435
1436 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1437 /* PixelFormat selection */
1438 ZeroMemory(&pfd, sizeof(pfd));
1439 pfd.nSize = sizeof(pfd);
1440 pfd.nVersion = 1;
1441 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1442 pfd.iPixelType = PFD_TYPE_RGBA;
1443 pfd.cAlphaBits = alphaBits;
1444 pfd.cColorBits = colorBits;
1445 pfd.cDepthBits = depthBits;
1446 pfd.cStencilBits = stencilBits;
1447 pfd.iLayerType = PFD_MAIN_PLANE;
1448
1449 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1450 if(!iPixelFormat) {
1451 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1452 ERR("Can't find a suitable iPixelFormat\n");
1453 return FALSE;
1454 }
1455 }
1456
1457 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1458 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1459 return iPixelFormat;
1460}
1461
1462struct IWineD3DDeviceImpl *context_get_device(const struct wined3d_context *context)
1463{
1464#ifdef VBOX_WITH_WDDM
1465 return context->device;
1466#else
1467 return context->swapchain->device;
1468#endif
1469}
1470
1471
1472/*****************************************************************************
1473 * context_create
1474 *
1475 * Creates a new context.
1476 *
1477 * * Params:
1478 * This: Device to activate the context for
1479 * target: Surface this context will render to
1480 * win_handle: handle to the window which we are drawing to
1481 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1482 *
1483 *****************************************************************************/
1484struct wined3d_context *context_create(IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target,
1485 const struct wined3d_format_desc *ds_format_desc)
1486{
1487 IWineD3DDeviceImpl *device = swapchain->device;
1488 const struct wined3d_gl_info *gl_info = &device->adapter->gl_info;
1489 const struct wined3d_format_desc *color_format_desc;
1490 struct wined3d_context *ret;
1491 PIXELFORMATDESCRIPTOR pfd;
1492 BOOL auxBuffers = FALSE;
1493 int numSamples = 0;
1494 int pixel_format;
1495 unsigned int s;
1496 DWORD state;
1497 HGLRC ctx;
1498 HDC hdc;
1499
1500 TRACE("swapchain %p, target %p, window %p.\n", swapchain, target, swapchain->win_handle);
1501
1502 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ret));
1503 if (!ret)
1504 {
1505 ERR("Failed to allocate context memory.\n");
1506 return NULL;
1507 }
1508
1509 if (!(hdc =
1510#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
1511 swapchain->hDC
1512#else
1513 GetDC(swapchain->win_handle)
1514#endif
1515 )
1516 )
1517 {
1518 ERR("Failed to retrieve a device context.\n");
1519 goto out;
1520 }
1521
1522 color_format_desc = target->resource.format_desc;
1523
1524 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for
1525 * X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1526 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER)
1527 {
1528 auxBuffers = TRUE;
1529
1530 if (color_format_desc->format == WINED3DFMT_B4G4R4X4_UNORM)
1531 color_format_desc = getFormatDescEntry(WINED3DFMT_B4G4R4A4_UNORM, gl_info);
1532 else if (color_format_desc->format == WINED3DFMT_B8G8R8X8_UNORM)
1533 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1534 }
1535
1536 /* DirectDraw supports 8bit paletted render targets and these are used by
1537 * old games like Starcraft and C&C. Most modern hardware doesn't support
1538 * 8bit natively so we perform some form of 8bit -> 32bit conversion. The
1539 * conversion (ab)uses the alpha component for storing the palette index.
1540 * For this reason we require a format with 8bit alpha, so request
1541 * A8R8G8B8. */
1542 if (color_format_desc->format == WINED3DFMT_P8_UINT)
1543 color_format_desc = getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, gl_info);
1544
1545 /* Retrieve the depth stencil format from the present parameters.
1546 * The choice of the proper format can give a nice performance boost
1547 * in case of GPU limited programs. */
1548 if (swapchain->presentParms.EnableAutoDepthStencil)
1549 {
1550 TRACE("Auto depth stencil enabled, using format %s.\n",
1551 debug_d3dformat(swapchain->presentParms.AutoDepthStencilFormat));
1552 ds_format_desc = getFormatDescEntry(swapchain->presentParms.AutoDepthStencilFormat, gl_info);
1553 }
1554
1555 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD. */
1556 if (swapchain->presentParms.MultiSampleType && (swapchain->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD))
1557 {
1558 if (!gl_info->supported[ARB_MULTISAMPLE])
1559 WARN("The application is requesting multisampling without support.\n");
1560 else
1561 {
1562 TRACE("Requesting multisample type %#x.\n", swapchain->presentParms.MultiSampleType);
1563 numSamples = swapchain->presentParms.MultiSampleType;
1564 }
1565 }
1566
1567 /* Try to find a pixel format which matches our requirements. */
1568 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1569 auxBuffers, numSamples, FALSE /* findCompatible */);
1570
1571 /* Try to locate a compatible format if we weren't able to find anything. */
1572 if (!pixel_format)
1573 {
1574 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1575 pixel_format = WineD3D_ChoosePixelFormat(device, hdc, color_format_desc, ds_format_desc,
1576 auxBuffers, 0 /* numSamples */, TRUE /* findCompatible */);
1577 }
1578
1579 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1580 if (!pixel_format)
1581 {
1582 ERR("Can't find a suitable pixel format.\n");
1583 goto out;
1584 }
1585
1586 DescribePixelFormat(hdc, pixel_format, sizeof(pfd), &pfd);
1587 if (!context_set_pixel_format(gl_info, hdc, pixel_format))
1588 {
1589 ERR("Failed to set pixel format %d on device context %p.\n", pixel_format, hdc);
1590 goto out;
1591 }
1592
1593 ctx = pwglCreateContext(hdc);
1594 if (device->numContexts)
1595 {
1596 if (!pwglShareLists(device->contexts[0]->glCtx, ctx))
1597 {
1598 DWORD err = GetLastError();
1599 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1600 device->contexts[0]->glCtx, ctx, err);
1601 }
1602 }
1603
1604 if(!ctx) {
1605 ERR("Failed to create a WGL context\n");
1606 goto out;
1607 }
1608
1609 if (!device_context_add(device, ret))
1610 {
1611 ERR("Failed to add the newly created context to the context list\n");
1612 if (!pwglDeleteContext(ctx))
1613 {
1614 DWORD err = GetLastError();
1615 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1616 }
1617 goto out;
1618 }
1619
1620 ret->gl_info = gl_info;
1621
1622 /* Mark all states dirty to force a proper initialization of the states
1623 * on the first use of the context. */
1624 for (state = 0; state <= STATE_HIGHEST; ++state)
1625 {
1626 if (device->StateTable[state].representative)
1627 Context_MarkStateDirty(ret, state, device->StateTable);
1628 }
1629
1630#ifdef VBOX_WITH_WDDM
1631 ret->device = device;
1632 ret->currentSwapchain = swapchain;
1633#else
1634 ret->swapchain = swapchain;
1635#endif
1636 ret->current_rt = (IWineD3DSurface *)target;
1637#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1638 ret->tid = GetCurrentThreadId();
1639#endif
1640
1641 ret->render_offscreen = surface_is_offscreen((IWineD3DSurface *) target);
1642 ret->draw_buffer_dirty = TRUE;
1643 ret->valid = 1;
1644
1645 ret->glCtx = ctx;
1646#ifndef VBOX_WITH_WDDM
1647 ret->win_handle = swapchain->win_handle;
1648 ret->hdc = hdc;
1649#endif
1650 ret->pixel_format = pixel_format;
1651
1652 if (device->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *)device))
1653 {
1654 /* Create the dirty constants array and initialize them to dirty */
1655 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1656 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1657 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1658 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1659 memset(ret->vshader_const_dirty, 1,
1660 sizeof(*ret->vshader_const_dirty) * device->d3d_vshader_constantF);
1661 memset(ret->pshader_const_dirty, 1,
1662 sizeof(*ret->pshader_const_dirty) * device->d3d_pshader_constantF);
1663 }
1664
1665 ret->free_occlusion_query_size = 4;
1666 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1667 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1668 if (!ret->free_occlusion_queries) goto out;
1669
1670 list_init(&ret->occlusion_queries);
1671
1672 ret->free_event_query_size = 4;
1673 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1674 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1675 if (!ret->free_event_queries) goto out;
1676
1677 list_init(&ret->event_queries);
1678
1679 TRACE("Successfully created new context %p\n", ret);
1680
1681 list_init(&ret->fbo_list);
1682 list_init(&ret->fbo_destroy_list);
1683
1684 context_enter(ret);
1685
1686 /* Set up the context defaults */
1687 if (!context_set_current(ret))
1688 {
1689 ERR("Cannot activate context to set up defaults\n");
1690 context_release(ret);
1691 goto out;
1692 }
1693
1694 ENTER_GL();
1695
1696 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1697
1698 TRACE("Setting up the screen\n");
1699 /* Clear the screen */
1700 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1701 checkGLcall("glClearColor");
1702 glClearIndex(0);
1703 glClearDepth(1);
1704 glClearStencil(0xffff);
1705
1706 checkGLcall("glClear");
1707
1708 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1709 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1710
1711 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1712 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1713
1714 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1715 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1716
1717 glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);
1718 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, device->surface_alignment);");
1719 glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);
1720 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, device->surface_alignment);");
1721
1722 if (gl_info->supported[APPLE_CLIENT_STORAGE])
1723 {
1724 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1725 * and textures in DIB sections(due to the memory protection).
1726 */
1727 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1728 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1729 }
1730 if (gl_info->supported[ARB_VERTEX_BLEND])
1731 {
1732 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1733 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1734 * GL_VERTEX_BLEND_ARB isn't enabled too
1735 */
1736 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1737 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1738 }
1739 if (gl_info->supported[NV_TEXTURE_SHADER2])
1740 {
1741 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1742 * the previous texture where to source the offset from is always unit - 1.
1743 */
1744 for (s = 1; s < gl_info->limits.textures; ++s)
1745 {
1746 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1747 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1748 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1749 }
1750 }
1751 if (gl_info->supported[ARB_FRAGMENT_PROGRAM])
1752 {
1753 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1754 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1755 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1756 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1757 * is ever assigned.
1758 *
1759 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1760 * program and the dummy program is destroyed when the context is destroyed.
1761 */
1762 const char *dummy_program =
1763 "!!ARBfp1.0\n"
1764 "MOV result.color, fragment.color.primary;\n"
1765 "END\n";
1766 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1767 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1768 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1769 }
1770
1771 for (s = 0; s < gl_info->limits.point_sprite_units; ++s)
1772 {
1773 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1774 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1775 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1776 }
1777
1778 if (gl_info->supported[ARB_PROVOKING_VERTEX])
1779 {
1780 GL_EXTCALL(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION));
1781 }
1782 else if (gl_info->supported[EXT_PROVOKING_VERTEX])
1783 {
1784 GL_EXTCALL(glProvokingVertexEXT(GL_FIRST_VERTEX_CONVENTION_EXT));
1785 }
1786
1787#ifdef VBOX_WITH_WDDM
1788 GL_EXTCALL(glChromiumParameteriCR(GL_SHARE_CONTEXT_RESOURCES_CR, GL_TRUE));
1789 GL_EXTCALL(glChromiumParameteriCR(GL_FLUSH_ON_THREAD_SWITCH_CR, GL_TRUE));
1790#endif
1791
1792 LEAVE_GL();
1793
1794 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
1795
1796 TRACE("Created context %p.\n", ret);
1797
1798 return ret;
1799
1800out:
1801 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1802 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1803 HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1804 HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1805 HeapFree(GetProcessHeap(), 0, ret);
1806 return NULL;
1807}
1808
1809#ifdef VBOX_WITH_WDDM
1810static void context_setup_target(IWineD3DDeviceImpl *device, struct wined3d_context *context, IWineD3DSurface *target);
1811static void context_apply_state(struct wined3d_context *context, IWineD3DDeviceImpl *device, enum ContextUsage usage);
1812
1813BOOL context_acquire_context(struct wined3d_context * context, IWineD3DSurface *target, enum ContextUsage usage, BOOL bReValidate)
1814{
1815 IWineD3DDeviceImpl *device = context->device;
1816 struct wined3d_context *current_context = context_get_current();
1817 if (bReValidate)
1818 {
1819 IWineD3DSwapChain *swapchain = NULL;
1820 if (target && SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1821 context_validate(context, (IWineD3DSwapChainImpl*)swapchain
1822# ifdef DEBUG_misha
1823 , TRUE
1824# endif
1825 );
1826 IWineD3DSwapChain_Release(swapchain);
1827 }
1828 else {
1829 context_validate_adjust_wnd(context);
1830 }
1831 }
1832 context_setup_target(device, context, target);
1833 context_enter(context);
1834// Assert(context->valid);
1835 if (!context->valid) return FALSE;
1836
1837 if (context != current_context)
1838 {
1839 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
1840 else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
1841
1842 if (context->vshader_const_dirty)
1843 {
1844 memset(context->vshader_const_dirty, 1,
1845 sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
1846 device->highest_dirty_vs_const = device->d3d_vshader_constantF;
1847 }
1848 if (context->pshader_const_dirty)
1849 {
1850 memset(context->pshader_const_dirty, 1,
1851 sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
1852 device->highest_dirty_ps_const = device->d3d_pshader_constantF;
1853 }
1854 }
1855 else if (context->restore_ctx)
1856 {
1857 if (!pwglMakeCurrent(context->currentSwapchain->hDC, context->glCtx))
1858 {
1859 DWORD err = GetLastError();
1860 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
1861 context->currentSwapchain->hDC, context->glCtx, err);
1862 }
1863 }
1864
1865 context_apply_state(context, device, usage);
1866
1867 return TRUE;
1868}
1869
1870struct wined3d_context *context_find_create(IWineD3DDeviceImpl *device, IWineD3DSwapChainImpl *swapchain, IWineD3DSurfaceImpl *target,
1871 const struct wined3d_format_desc *ds_format_desc)
1872{
1873#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1874 UINT i;
1875 DWORD tid = GetCurrentThreadId();
1876#endif
1877 struct wined3d_context *context = NULL;
1878
1879#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
1880 for(i = 0 ; i < device->numContexts ; i ++)
1881 {
1882 if(device->contexts[i]->tid == tid) {
1883 context = device->contexts[i];
1884 break;
1885 }
1886 }
1887#else
1888 context = device->numContexts ? device->contexts[0] : NULL;
1889#endif
1890
1891 if (!context)
1892 {
1893 Assert(!device->NumberOfSwapChains);
1894 context = context_create(swapchain, target, ds_format_desc);
1895 }
1896 else
1897 {
1898 if(!context_acquire_context(context, (IWineD3DSurface*)target, CTXUSAGE_RESOURCELOAD, TRUE))
1899 {
1900 ERR("Failed to acquire the context.\n");
1901 Assert(0);
1902 Assert(!context->valid);
1903 context = NULL;
1904 }
1905 else
1906 {
1907 Assert(context->valid);
1908 }
1909 }
1910
1911 return context;
1912}
1913#endif
1914
1915/*****************************************************************************
1916 * context_destroy
1917 *
1918 * Destroys a wined3d context
1919 *
1920 * Params:
1921 * This: Device to activate the context for
1922 * context: Context to destroy
1923 *
1924 *****************************************************************************/
1925void context_destroy(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1926{
1927 BOOL destroy;
1928
1929 TRACE("Destroying ctx %p\n", context);
1930
1931 if (context->tid == GetCurrentThreadId() || !context->current)
1932 {
1933 context_destroy_gl_resources(context);
1934 TlsSetValue(wined3d_context_tls_idx, NULL);
1935 destroy = TRUE;
1936 }
1937 else
1938 {
1939 context->destroyed = 1;
1940 destroy = FALSE;
1941 }
1942
1943 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1944 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1945 device_context_remove(This, context);
1946 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1947#ifndef VBOX_WITH_WDDM
1948 else context->swapchain = NULL;
1949#endif
1950}
1951
1952/* GL locking is done by the caller */
1953static inline void set_blit_dimension(UINT width, UINT height) {
1954 glMatrixMode(GL_PROJECTION);
1955 checkGLcall("glMatrixMode(GL_PROJECTION)");
1956 glLoadIdentity();
1957 checkGLcall("glLoadIdentity()");
1958 glOrtho(0, width, height, 0, 0.0, -1.0);
1959 checkGLcall("glOrtho");
1960 glViewport(0, 0, width, height);
1961 checkGLcall("glViewport");
1962}
1963
1964/*****************************************************************************
1965 * SetupForBlit
1966 *
1967 * Sets up a context for DirectDraw blitting.
1968 * All texture units are disabled, texture unit 0 is set as current unit
1969 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1970 * color writing enabled for all channels
1971 * register combiners disabled, shaders disabled
1972 * world matrix is set to identity, texture matrix 0 too
1973 * projection matrix is setup for drawing screen coordinates
1974 *
1975 * Params:
1976 * This: Device to activate the context for
1977 * context: Context to setup
1978 *
1979 *****************************************************************************/
1980/* Context activation is done by the caller. */
1981static void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1982{
1983 int i;
1984 const struct StateEntry *StateTable = This->StateTable;
1985 const struct wined3d_gl_info *gl_info = context->gl_info;
1986 UINT width = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Width;
1987 UINT height = ((IWineD3DSurfaceImpl *)context->current_rt)->currentDesc.Height;
1988 DWORD sampler;
1989
1990 TRACE("Setting up context %p for blitting\n", context);
1991 if(context->last_was_blit) {
1992 if(context->blit_w != width || context->blit_h != height) {
1993 ENTER_GL();
1994 set_blit_dimension(width, height);
1995 LEAVE_GL();
1996 context->blit_w = width; context->blit_h = height;
1997 /* No need to dirtify here, the states are still dirtified because they weren't
1998 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1999 * be set
2000 */
2001 }
2002 TRACE("Context is already set up for blitting, nothing to do\n");
2003 return;
2004 }
2005 context->last_was_blit = TRUE;
2006
2007 /* TODO: Use a display list */
2008
2009 /* Disable shaders */
2010 ENTER_GL();
2011 This->shader_backend->shader_select(context, FALSE, FALSE);
2012 LEAVE_GL();
2013
2014 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
2015 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
2016
2017 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
2018 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
2019 * which can safely be called from here, we only lock once instead locking/unlocking
2020 * after each GL call.
2021 */
2022 ENTER_GL();
2023
2024 /* Disable all textures. The caller can then bind a texture it wants to blit
2025 * from
2026 *
2027 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
2028 * function texture unit. No need to care for higher samplers
2029 */
2030 for (i = gl_info->limits.textures - 1; i > 0 ; --i)
2031 {
2032 sampler = This->rev_tex_unit_map[i];
2033 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
2034 checkGLcall("glActiveTextureARB");
2035
2036 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2037 {
2038 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2039 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2040 }
2041 glDisable(GL_TEXTURE_3D);
2042 checkGLcall("glDisable GL_TEXTURE_3D");
2043 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2044 {
2045 glDisable(GL_TEXTURE_RECTANGLE_ARB);
2046 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2047 }
2048 glDisable(GL_TEXTURE_2D);
2049 checkGLcall("glDisable GL_TEXTURE_2D");
2050
2051 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2052 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
2053
2054 if (sampler != WINED3D_UNMAPPED_STAGE)
2055 {
2056 if (sampler < MAX_TEXTURES) {
2057 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
2058 }
2059 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
2060 }
2061 }
2062 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
2063 checkGLcall("glActiveTextureARB");
2064
2065 sampler = This->rev_tex_unit_map[0];
2066
2067 if (gl_info->supported[ARB_TEXTURE_CUBE_MAP])
2068 {
2069 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
2070 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
2071 }
2072 glDisable(GL_TEXTURE_3D);
2073 checkGLcall("glDisable GL_TEXTURE_3D");
2074 if (gl_info->supported[ARB_TEXTURE_RECTANGLE])
2075 {
2076 glDisable(GL_TEXTURE_RECTANGLE_ARB);
2077 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
2078 }
2079 glDisable(GL_TEXTURE_2D);
2080 checkGLcall("glDisable GL_TEXTURE_2D");
2081
2082 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
2083
2084 glMatrixMode(GL_TEXTURE);
2085 checkGLcall("glMatrixMode(GL_TEXTURE)");
2086 glLoadIdentity();
2087 checkGLcall("glLoadIdentity()");
2088
2089 if (gl_info->supported[EXT_TEXTURE_LOD_BIAS])
2090 {
2091 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
2092 GL_TEXTURE_LOD_BIAS_EXT,
2093 0.0f);
2094 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
2095 }
2096
2097 if (sampler != WINED3D_UNMAPPED_STAGE)
2098 {
2099 if (sampler < MAX_TEXTURES) {
2100 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
2101 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
2102 }
2103 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
2104 }
2105
2106 /* Other misc states */
2107 glDisable(GL_ALPHA_TEST);
2108 checkGLcall("glDisable(GL_ALPHA_TEST)");
2109 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
2110 glDisable(GL_LIGHTING);
2111 checkGLcall("glDisable GL_LIGHTING");
2112 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
2113 glDisable(GL_DEPTH_TEST);
2114 checkGLcall("glDisable GL_DEPTH_TEST");
2115 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
2116 glDisableWINE(GL_FOG);
2117 checkGLcall("glDisable GL_FOG");
2118 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
2119 glDisable(GL_BLEND);
2120 checkGLcall("glDisable GL_BLEND");
2121 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2122 glDisable(GL_CULL_FACE);
2123 checkGLcall("glDisable GL_CULL_FACE");
2124 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
2125 glDisable(GL_STENCIL_TEST);
2126 checkGLcall("glDisable GL_STENCIL_TEST");
2127 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
2128 glDisable(GL_SCISSOR_TEST);
2129 checkGLcall("glDisable GL_SCISSOR_TEST");
2130 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
2131 if (gl_info->supported[ARB_POINT_SPRITE])
2132 {
2133 glDisable(GL_POINT_SPRITE_ARB);
2134 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
2135 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
2136 }
2137 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
2138 checkGLcall("glColorMask");
2139 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
2140 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE1), StateTable);
2141 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE2), StateTable);
2142 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE3), StateTable);
2143 if (gl_info->supported[EXT_SECONDARY_COLOR])
2144 {
2145 glDisable(GL_COLOR_SUM_EXT);
2146 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
2147 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
2148 }
2149
2150 /* Setup transforms */
2151 glMatrixMode(GL_MODELVIEW);
2152 checkGLcall("glMatrixMode(GL_MODELVIEW)");
2153 glLoadIdentity();
2154 checkGLcall("glLoadIdentity()");
2155 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
2156
2157 context->last_was_rhw = TRUE;
2158 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
2159
2160 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
2161 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
2162 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
2163 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
2164 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
2165 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
2166 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
2167
2168 set_blit_dimension(width, height);
2169
2170 LEAVE_GL();
2171
2172 context->blit_w = width; context->blit_h = height;
2173 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
2174 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
2175
2176
2177 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
2178}
2179
2180/*****************************************************************************
2181 * findThreadContextForSwapChain
2182 *
2183 * Searches a swapchain for all contexts and picks one for the thread tid.
2184 * If none can be found the swapchain is requested to create a new context
2185 *
2186 *****************************************************************************/
2187static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain
2188#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
2189 , DWORD tid
2190#endif
2191 )
2192{
2193#ifdef VBOX_WINE_WITH_SINGLE_CONTEXT
2194 IWineD3DDeviceImpl *device = ((IWineD3DSwapChainImpl*)swapchain)->device;
2195 if (device->numContexts)
2196 return device->contexts[0];
2197#else
2198 unsigned int i;
2199# ifdef VBOX_WITH_WDDM
2200 IWineD3DDeviceImpl *device = ((IWineD3DSwapChainImpl*)swapchain)->device;
2201 for (i = 0; i < device->numContexts; ++i)
2202 {
2203 if (device->contexts[i]->tid == tid)
2204 return device->contexts[i];
2205 }
2206# else
2207 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
2208 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
2209 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
2210 }
2211 }
2212# endif
2213#endif
2214
2215 /* Create a new context for the thread */
2216 return swapchain_create_context_for_thread(swapchain);
2217}
2218
2219#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
2220/*****************************************************************************
2221 * FindContext
2222 *
2223 * Finds a context for the current render target and thread
2224 *
2225 * Parameters:
2226 * target: Render target to find the context for
2227 * tid: Thread to activate the context for
2228 *
2229 * Returns: The needed context
2230 *
2231 *****************************************************************************/
2232static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target)
2233{
2234 IWineD3DSwapChain *swapchain = NULL;
2235 struct wined3d_context *current_context = context_get_current();
2236#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
2237 DWORD tid = GetCurrentThreadId();
2238#endif
2239 struct wined3d_context *context;
2240
2241 if (current_context && current_context->destroyed) current_context = NULL;
2242
2243 if (!target)
2244 {
2245 if (current_context
2246 && current_context->current_rt
2247 && context_get_device(current_context) == This
2248 )
2249 {
2250 target = current_context->current_rt;
2251 }
2252 else
2253 {
2254#ifdef VBOX_WITH_WDDM
2255 /* tmp work-around */
2256 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[This->NumberOfSwapChains-1];
2257#else
2258 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
2259#endif
2260 if (swapchain->backBuffer) target = swapchain->backBuffer[0];
2261 else target = swapchain->frontBuffer;
2262 }
2263 }
2264
2265 if (current_context && current_context->current_rt == target)
2266 {
2267#ifdef VBOX_WITH_WDDM
2268 IWineD3DSwapChain *swapchain = NULL;
2269 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
2270 context_validate(current_context, (IWineD3DSwapChainImpl*)swapchain);
2271 IWineD3DSwapChain_Release(swapchain);
2272 }
2273 else {
2274 /* tmp work-around */
2275 context_validate(current_context,
2276 NULL //(IWineD3DSwapChainImpl*)current_context->device->swapchains[current_context->device->NumberOfSwapChains-1]
2277 );
2278 }
2279#else
2280 context_validate(current_context);
2281#endif
2282 return current_context;
2283 }
2284
2285 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
2286 TRACE("Rendering onscreen\n");
2287
2288 context = findThreadContextForSwapChain(swapchain
2289#ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
2290 , tid
2291#endif
2292 );
2293#ifdef VBOX_WITH_WDDM
2294 context_validate(context, (IWineD3DSwapChainImpl*)swapchain);
2295#endif
2296 IWineD3DSwapChain_Release(swapchain);
2297 }
2298 else
2299 {
2300 TRACE("Rendering offscreen\n");
2301
2302 /* Stay with the currently active context. */
2303 if (current_context && context_get_device(current_context) == This)
2304 {
2305 context = current_context;
2306 }
2307 else
2308 {
2309 /* This may happen if the app jumps straight into offscreen rendering
2310 * Start using the context of the primary swapchain. tid == 0 is no problem
2311 * for findThreadContextForSwapChain.
2312 *
2313 * Can also happen on thread switches - in that case findThreadContextForSwapChain
2314 * is perfect to call. */
2315#ifdef VBOX_WITH_WDDM /* tmp work-around */
2316 context = findThreadContextForSwapChain(This->swapchains[This->NumberOfSwapChains-1]
2317# ifndef VBOX_WINE_WITH_SINGLE_CONTEXT
2318 , tid
2319# endif
2320 );
2321#else
2322 context = findThreadContextForSwapChain(This->swapchains[0], tid);
2323#endif
2324 }
2325#ifdef VBOX_WITH_WDDM
2326 context_validate(context,
2327 NULL //(IWineD3DSwapChainImpl*)This->swapchains[This->NumberOfSwapChains-1] /* tmp work-around */
2328 );
2329#endif
2330 }
2331
2332#ifndef VBOX_WITH_WDDM
2333 context_validate(context);
2334#endif
2335
2336 return context;
2337}
2338#else
2339/*****************************************************************************
2340 * FindContext
2341 *
2342 * Finds a context for the current render target and thread
2343 *
2344 * Parameters:
2345 * target: Render target to find the context for
2346 * tid: Thread to activate the context for
2347 *
2348 * Returns: The needed context
2349 *
2350 *****************************************************************************/
2351static struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target)
2352{
2353 IWineD3DSwapChain *swapchain = NULL;
2354 struct wined3d_context *context = This->numContexts ? This->contexts[0] : NULL;
2355
2356
2357 if (context && context->destroyed)
2358 {
2359 ERR("context is destroyed");
2360 }
2361
2362 if (!target)
2363 {
2364 if (context
2365 && context->current_rt
2366 && context_get_device(context) == This
2367 )
2368 {
2369 target = context->current_rt;
2370 }
2371 else
2372 {
2373 IWineD3DSwapChainImpl *swapchain = swapchain_find_valid(This);
2374 if (!swapchain)
2375 swapchain = (IWineD3DSwapChainImpl *)This->swapchains[This->NumberOfSwapChains-1]; /* just fallback to anything to avoid NPE */
2376 if (swapchain->backBuffer) target = swapchain->backBuffer[0];
2377 else if (swapchain->frontBuffer) target = swapchain->frontBuffer;
2378 else target = swapchain->presentRt;
2379 }
2380 }
2381
2382 if (context && context->current_rt == target)
2383 {
2384 IWineD3DSwapChain *swapchain = NULL;
2385 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
2386 context_validate(context, (IWineD3DSwapChainImpl*)swapchain
2387# ifdef DEBUG_misha
2388 , TRUE
2389# endif
2390 );
2391 IWineD3DSwapChain_Release(swapchain);
2392 }
2393 else {
2394 context_validate_adjust_wnd(context);
2395 }
2396 return context;
2397 }
2398
2399 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
2400 TRACE("Rendering onscreen\n");
2401
2402 context = findThreadContextForSwapChain(swapchain);
2403 context_validate(context, (IWineD3DSwapChainImpl*)swapchain
2404# ifdef DEBUG_misha
2405 , TRUE
2406# endif
2407 );
2408 IWineD3DSwapChain_Release(swapchain);
2409 }
2410 else
2411 {
2412 if (context)
2413 {
2414 context_validate_adjust_wnd(context);
2415 }
2416 else
2417 {
2418 IWineD3DSwapChainImpl *swapchain = swapchain_find_valid(This);
2419 if (!swapchain)
2420 swapchain = (IWineD3DSwapChainImpl *)This->swapchains[This->NumberOfSwapChains-1]; /* just fallback to anything to avoid NPE */
2421 context = findThreadContextForSwapChain((IWineD3DSwapChain*)swapchain);
2422 context_validate(context, swapchain
2423# ifdef DEBUG_misha
2424 , TRUE
2425# endif
2426 );
2427 }
2428
2429 TRACE("Rendering offscreen\n");
2430 }
2431
2432 return context;
2433}
2434#endif
2435
2436/* Context activation is done by the caller. */
2437static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
2438{
2439 const struct wined3d_gl_info *gl_info = context->gl_info;
2440 IWineD3DSurface *rt = context->current_rt;
2441 IWineD3DDeviceImpl *device;
2442
2443 device = ((IWineD3DSurfaceImpl *)rt)->resource.device;
2444 if (!surface_is_offscreen(rt))
2445 {
2446 ENTER_GL();
2447 glDrawBuffer(surface_get_gl_buffer(rt));
2448 checkGLcall("glDrawBuffers()");
2449 LEAVE_GL();
2450 }
2451 else
2452 {
2453 ENTER_GL();
2454 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
2455 {
2456 if (!blit)
2457 {
2458 if (gl_info->supported[ARB_DRAW_BUFFERS])
2459 {
2460 GL_EXTCALL(glDrawBuffersARB(gl_info->limits.buffers, device->draw_buffers));
2461 checkGLcall("glDrawBuffers()");
2462 }
2463 else
2464 {
2465 glDrawBuffer(device->draw_buffers[0]);
2466 checkGLcall("glDrawBuffer()");
2467 }
2468 } else {
2469 glDrawBuffer(GL_COLOR_ATTACHMENT0);
2470 checkGLcall("glDrawBuffer()");
2471 }
2472 }
2473 else
2474 {
2475 glDrawBuffer(device->offscreenBuffer);
2476 checkGLcall("glDrawBuffer()");
2477 }
2478 LEAVE_GL();
2479 }
2480}
2481
2482/* GL locking is done by the caller. */
2483void context_set_draw_buffer(struct wined3d_context *context, GLenum buffer)
2484{
2485 glDrawBuffer(buffer);
2486 checkGLcall("glDrawBuffer()");
2487 context->draw_buffer_dirty = TRUE;
2488}
2489
2490static inline void context_set_render_offscreen(struct wined3d_context *context, const struct StateEntry *StateTable,
2491 BOOL offscreen)
2492{
2493 if (context->render_offscreen == offscreen) return;
2494
2495 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
2496 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
2497 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
2498 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
2499 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
2500 context->render_offscreen = offscreen;
2501}
2502
2503static BOOL match_depth_stencil_format(const struct wined3d_format_desc *existing,
2504 const struct wined3d_format_desc *required)
2505{
2506 short existing_depth, existing_stencil, required_depth, required_stencil;
2507
2508 if(existing == required) return TRUE;
2509 if((existing->Flags & WINED3DFMT_FLAG_FLOAT) != (required->Flags & WINED3DFMT_FLAG_FLOAT)) return FALSE;
2510
2511 getDepthStencilBits(existing, &existing_depth, &existing_stencil);
2512 getDepthStencilBits(required, &required_depth, &required_stencil);
2513
2514 if(existing_depth < required_depth) return FALSE;
2515 /* If stencil bits are used the exact amount is required - otherwise wrapping
2516 * won't work correctly */
2517 if(required_stencil && required_stencil != existing_stencil) return FALSE;
2518 return TRUE;
2519}
2520/* The caller provides a context */
2521static void context_validate_onscreen_formats(IWineD3DDeviceImpl *device, struct wined3d_context *context)
2522{
2523 /* Onscreen surfaces are always in a swapchain */
2524 IWineD3DSurfaceImpl *depth_stencil = (IWineD3DSurfaceImpl *) device->stencilBufferTarget;
2525 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *) ((IWineD3DSurfaceImpl *)context->current_rt)->container;
2526
2527 if (!depth_stencil) return;
2528 if (match_depth_stencil_format(swapchain->ds_format, depth_stencil->resource.format_desc)) return;
2529
2530 /* TODO: If the requested format would satisfy the needs of the existing one(reverse match),
2531 * or no onscreen depth buffer was created, the OpenGL drawable could be changed to the new
2532 * format. */
2533 WARN("Depth stencil format is not supported by WGL, rendering the backbuffer in an FBO\n");
2534
2535 /* The currently active context is the necessary context to access the swapchain's onscreen buffers */
2536 IWineD3DSurface_LoadLocation(context->current_rt, SFLAG_INTEXTURE, NULL);
2537 swapchain->render_to_fbo = TRUE;
2538 context_set_render_offscreen(context, device->StateTable, TRUE);
2539}
2540
2541/* Context activation is done by the caller. */
2542static void context_apply_state(struct wined3d_context *context, IWineD3DDeviceImpl *device, enum ContextUsage usage)
2543{
2544 const struct StateEntry *state_table = device->StateTable;
2545 unsigned int i;
2546
2547 switch (usage) {
2548 case CTXUSAGE_CLEAR:
2549 case CTXUSAGE_DRAWPRIM:
2550 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2551 if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2552 ENTER_GL();
2553 context_apply_fbo_state(context);
2554 LEAVE_GL();
2555 }
2556 if (context->draw_buffer_dirty) {
2557 context_apply_draw_buffer(context, FALSE);
2558 context->draw_buffer_dirty = FALSE;
2559 }
2560 break;
2561
2562 case CTXUSAGE_BLIT:
2563 case CTXUSAGE_BLIT_LIGHT:
2564 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2565 if (!context->render_offscreen) context_validate_onscreen_formats(device, context);
2566 if (context->render_offscreen)
2567 {
2568 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2569 surface_internal_preload(context->current_rt, SRGB_RGB);
2570
2571 ENTER_GL();
2572 context_bind_fbo(context, GL_FRAMEBUFFER, &context->dst_fbo);
2573 context_attach_surface_fbo(context, GL_FRAMEBUFFER, 0, (IWineD3DSurfaceImpl *)context->current_rt);
2574 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER, NULL, FALSE);
2575 LEAVE_GL();
2576 } else {
2577 ENTER_GL();
2578 context_bind_fbo(context, GL_FRAMEBUFFER, NULL);
2579 LEAVE_GL();
2580 }
2581 context->draw_buffer_dirty = TRUE;
2582 }
2583 if (context->draw_buffer_dirty) {
2584 context_apply_draw_buffer(context, TRUE);
2585 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2586 context->draw_buffer_dirty = FALSE;
2587 }
2588 }
2589 break;
2590
2591 default:
2592 break;
2593 }
2594
2595 switch(usage) {
2596 case CTXUSAGE_RESOURCELOAD:
2597 case CTXUSAGE_BLIT_LIGHT:
2598 /* This does not require any special states to be set up */
2599 break;
2600
2601 case CTXUSAGE_CLEAR:
2602 if(context->last_was_blit) {
2603 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2604 }
2605
2606 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2607 * blending when clearing improves the clearing performance incredibly.
2608 */
2609 ENTER_GL();
2610 glDisable(GL_BLEND);
2611 LEAVE_GL();
2612 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), state_table);
2613
2614 ENTER_GL();
2615 glEnable(GL_SCISSOR_TEST);
2616 checkGLcall("glEnable GL_SCISSOR_TEST");
2617 LEAVE_GL();
2618 context->last_was_blit = FALSE;
2619 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), state_table);
2620 Context_MarkStateDirty(context, STATE_SCISSORRECT, state_table);
2621 break;
2622
2623 case CTXUSAGE_DRAWPRIM:
2624 /* This needs all dirty states applied */
2625 if(context->last_was_blit) {
2626 device->frag_pipe->enable_extension((IWineD3DDevice *)device, TRUE);
2627 }
2628
2629 IWineD3DDeviceImpl_FindTexUnitMap(device);
2630 device_preload_textures(device);
2631 if (isStateDirty(context, STATE_VDECL))
2632 device_update_stream_info(device, context->gl_info);
2633
2634 ENTER_GL();
2635 for (i = 0; i < context->numDirtyEntries; ++i)
2636 {
2637 DWORD rep = context->dirtyArray[i];
2638 DWORD idx = rep / (sizeof(*context->isStateDirty) * CHAR_BIT);
2639 BYTE shift = rep & ((sizeof(*context->isStateDirty) * CHAR_BIT) - 1);
2640 context->isStateDirty[idx] &= ~(1 << shift);
2641 state_table[rep].apply(rep, device->stateBlock, context);
2642 }
2643 LEAVE_GL();
2644 context->numDirtyEntries = 0; /* This makes the whole list clean */
2645 context->last_was_blit = FALSE;
2646 break;
2647
2648 case CTXUSAGE_BLIT:
2649 SetupForBlit(device, context);
2650 break;
2651
2652 default:
2653 FIXME("Unexpected context usage requested\n");
2654 }
2655}
2656
2657static void context_setup_target(IWineD3DDeviceImpl *device, struct wined3d_context *context, IWineD3DSurface *target)
2658{
2659 BOOL old_render_offscreen = context->render_offscreen, render_offscreen;
2660 const struct StateEntry *StateTable = device->StateTable;
2661
2662 if (!target) return;
2663 else if (context->current_rt == target) return;
2664 render_offscreen = surface_is_offscreen(target);
2665
2666 context_set_render_offscreen(context, StateTable, render_offscreen);
2667
2668 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
2669 * the alpha blend state changes with different render target formats. */
2670 if (!context->current_rt)
2671 {
2672 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2673 }
2674 else
2675 {
2676 const struct wined3d_format_desc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
2677 const struct wined3d_format_desc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
2678
2679 if (old->format != new->format)
2680 {
2681 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
2682 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
2683 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
2684 {
2685 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2686 }
2687 }
2688
2689 /* When switching away from an offscreen render target, and we're not
2690 * using FBOs, we have to read the drawable into the texture. This is
2691 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
2692 * are some things that need care though. PreLoad needs a GL context,
2693 * and FindContext is called before the context is activated. It also
2694 * has to be called with the old rendertarget active, otherwise a
2695 * wrong drawable is read. */
2696 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
2697 && old_render_offscreen && context->current_rt != target)
2698 {
2699 BOOL oldInDraw = device->isInDraw;
2700
2701 /* surface_internal_preload() requires a context to load the
2702 * texture, so it will call context_acquire(). Set isInDraw to true
2703 * to signal surface_internal_preload() that it has a context. */
2704
2705 /* FIXME: This is just broken. There's no guarantee whatsoever
2706 * that the currently active context, if any, is appropriate for
2707 * reading back the render target. We should probably call
2708 * context_set_current(context) here and then rely on
2709 * context_acquire() doing the right thing. */
2710 device->isInDraw = TRUE;
2711
2712 /* Read the back buffer of the old drawable into the destination texture. */
2713 if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
2714 {
2715 surface_internal_preload(context->current_rt, SRGB_BOTH);
2716 }
2717 else
2718 {
2719 surface_internal_preload(context->current_rt, SRGB_RGB);
2720 }
2721
2722 IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
2723
2724 device->isInDraw = oldInDraw;
2725 }
2726 }
2727
2728 context->draw_buffer_dirty = TRUE;
2729 context->current_rt = target;
2730}
2731
2732/*****************************************************************************
2733 * context_acquire
2734 *
2735 * Finds a rendering context and drawable matching the device and render
2736 * target for the current thread, activates them and puts them into the
2737 * requested state.
2738 *
2739 * Params:
2740 * This: Device to activate the context for
2741 * target: Requested render target
2742 * usage: Prepares the context for blitting, drawing or other actions
2743 *
2744 *****************************************************************************/
2745struct wined3d_context *context_acquire(IWineD3DDeviceImpl *device, IWineD3DSurface *target, enum ContextUsage usage)
2746{
2747 struct wined3d_context *current_context = context_get_current();
2748 struct wined3d_context *context;
2749
2750 TRACE("device %p, target %p, usage %#x.\n", device, target, usage);
2751
2752 context = FindContext(device, target);
2753 context_setup_target(device, context, target);
2754 context_enter(context);
2755 if (!context->valid) return context;
2756
2757 if (context != current_context)
2758 {
2759 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2760 else device->frag_pipe->enable_extension((IWineD3DDevice *)device, !context->last_was_blit);
2761
2762 if (context->vshader_const_dirty)
2763 {
2764 memset(context->vshader_const_dirty, 1,
2765 sizeof(*context->vshader_const_dirty) * device->d3d_vshader_constantF);
2766 device->highest_dirty_vs_const = device->d3d_vshader_constantF;
2767 }
2768 if (context->pshader_const_dirty)
2769 {
2770 memset(context->pshader_const_dirty, 1,
2771 sizeof(*context->pshader_const_dirty) * device->d3d_pshader_constantF);
2772 device->highest_dirty_ps_const = device->d3d_pshader_constantF;
2773 }
2774 }
2775 else if (context->restore_ctx)
2776 {
2777#ifdef VBOX_WITH_WDDM
2778 if (!pwglMakeCurrent(context->currentSwapchain->hDC, context->glCtx))
2779 {
2780 DWORD err = GetLastError();
2781 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2782 context->currentSwapchain->hDC, context->glCtx, err);
2783 }
2784#else
2785 if (!pwglMakeCurrent(context->hdc, context->glCtx))
2786 {
2787 DWORD err = GetLastError();
2788 ERR("Failed to make GL context %p current on device context %p, last error %#x.\n",
2789 context->hdc, context->glCtx, err);
2790 }
2791#endif
2792 }
2793
2794 context_apply_state(context, device, usage);
2795
2796 return context;
2797}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette