VirtualBox

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

Last change on this file since 22596 was 22596, checked in by vboxsync, 16 years ago

crOpenGL: fix non updating windows for certain d3d apps

  • Property svn:eol-style set to native
File size: 80.4 KB
Line 
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 * Sun LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
23 * other than GPL or LGPL is available it will apply instead, Sun elects to use only
24 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
25 * a choice of LGPL license versions is made available with the language indicating
26 * that LGPLv2 or any later version may be used, or where a choice of which version
27 * of the LGPL is applied is otherwise unspecified.
28 */
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_EXTCALL(glGenFramebuffersEXT(1, fbo));
61 checkGLcall("glGenFramebuffersEXT()");
62 TRACE("Created FBO %u.\n", *fbo);
63 }
64 f = *fbo;
65 }
66
67 switch (target)
68 {
69 case GL_READ_FRAMEBUFFER_EXT:
70 if (context->fbo_read_binding == f) return;
71 context->fbo_read_binding = f;
72 break;
73
74 case GL_DRAW_FRAMEBUFFER_EXT:
75 if (context->fbo_draw_binding == f) return;
76 context->fbo_draw_binding = f;
77 break;
78
79 case GL_FRAMEBUFFER_EXT:
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_EXTCALL(glBindFramebufferEXT(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_LIMITS(buffers); ++i)
101 {
102 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
103 checkGLcall("glFramebufferTexture2D()");
104 }
105 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
106 checkGLcall("glFramebufferTexture2D()");
107
108 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, 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_EXT, fbo);
118 context_clean_fbo_attachments(gl_info);
119 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
120
121 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
122 checkGLcall("glDeleteFramebuffers()");
123}
124
125/* GL locking is done by the caller */
126static void context_apply_attachment_filter_states(IWineD3DSurface *surface, BOOL force_preload)
127{
128 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
129 IWineD3DDeviceImpl *device = surface_impl->resource.wineD3DDevice;
130 IWineD3DBaseTextureImpl *texture_impl;
131 BOOL update_minfilter = FALSE;
132 BOOL update_magfilter = FALSE;
133
134 /* Update base texture states array */
135 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
136 {
137 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
138 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
139 {
140 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
141 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
142 update_minfilter = TRUE;
143 }
144
145 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
146 {
147 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
148 update_magfilter = TRUE;
149 }
150
151 if (texture_impl->baseTexture.bindCount)
152 {
153 WARN("Render targets should not be bound to a sampler\n");
154 IWineD3DDeviceImpl_MarkStateDirty(device, STATE_SAMPLER(texture_impl->baseTexture.sampler));
155 }
156
157 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
158 }
159
160 if (update_minfilter || update_magfilter || force_preload)
161 {
162 GLenum target, bind_target;
163 GLint old_binding;
164
165 target = surface_impl->texture_target;
166 if (target == GL_TEXTURE_2D)
167 {
168 bind_target = GL_TEXTURE_2D;
169 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
170 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
171 bind_target = GL_TEXTURE_RECTANGLE_ARB;
172 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
173 } else {
174 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
175 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
176 }
177
178 surface_internal_preload(surface, SRGB_RGB);
179
180 glBindTexture(bind_target, surface_impl->texture_name);
181 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
182 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
183 glBindTexture(bind_target, old_binding);
184 }
185
186 checkGLcall("apply_attachment_filter_states()");
187}
188
189/* GL locking is done by the caller */
190void context_attach_depth_stencil_fbo(struct wined3d_context *context,
191 GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
192{
193 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
194 const struct wined3d_gl_info *gl_info = context->gl_info;
195
196 TRACE("Attach depth stencil %p\n", depth_stencil);
197
198 if (depth_stencil)
199 {
200 DWORD format_flags = depth_stencil_impl->resource.format_desc->Flags;
201
202 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
203 {
204 if (format_flags & WINED3DFMT_FLAG_DEPTH)
205 {
206 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
207 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
208 checkGLcall("glFramebufferRenderbufferEXT()");
209 }
210
211 if (format_flags & WINED3DFMT_FLAG_STENCIL)
212 {
213 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
214 GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
215 checkGLcall("glFramebufferRenderbufferEXT()");
216 }
217 }
218 else
219 {
220 context_apply_attachment_filter_states(depth_stencil, TRUE);
221
222 if (format_flags & WINED3DFMT_FLAG_DEPTH)
223 {
224 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT,
225 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
226 depth_stencil_impl->texture_level));
227 checkGLcall("glFramebufferTexture2DEXT()");
228 }
229
230 if (format_flags & WINED3DFMT_FLAG_STENCIL)
231 {
232 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT,
233 depth_stencil_impl->texture_target, depth_stencil_impl->texture_name,
234 depth_stencil_impl->texture_level));
235 checkGLcall("glFramebufferTexture2DEXT()");
236 }
237 }
238
239 if (!(format_flags & WINED3DFMT_FLAG_DEPTH))
240 {
241 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
242 checkGLcall("glFramebufferTexture2DEXT()");
243 }
244
245 if (!(format_flags & WINED3DFMT_FLAG_STENCIL))
246 {
247 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
248 checkGLcall("glFramebufferTexture2DEXT()");
249 }
250 }
251 else
252 {
253 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
254 checkGLcall("glFramebufferTexture2DEXT()");
255
256 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
257 checkGLcall("glFramebufferTexture2DEXT()");
258 }
259}
260
261/* GL locking is done by the caller */
262void context_attach_surface_fbo(const struct wined3d_context *context,
263 GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
264{
265 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
266 const struct wined3d_gl_info *gl_info = context->gl_info;
267
268 TRACE("Attach surface %p to %u\n", surface, idx);
269
270 if (surface)
271 {
272 context_apply_attachment_filter_states(surface, TRUE);
273
274 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->texture_target,
275 surface_impl->texture_name, surface_impl->texture_level));
276 checkGLcall("glFramebufferTexture2DEXT()");
277 } else {
278 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
279 checkGLcall("glFramebufferTexture2DEXT()");
280 }
281}
282
283/* GL locking is done by the caller */
284static void context_check_fbo_status(struct wined3d_context *context)
285{
286 const struct wined3d_gl_info *gl_info = context->gl_info;
287 GLenum status;
288
289 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
290 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
291 {
292 TRACE("FBO complete\n");
293 } else {
294 IWineD3DSurfaceImpl *attachment;
295 unsigned int i;
296 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
297
298
299 if (context->current_fbo)
300 {
301 /* Dump the FBO attachments */
302 for (i = 0; i < GL_LIMITS(buffers); ++i)
303 {
304 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->render_targets[i];
305 if (attachment)
306 {
307 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
308 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
309 attachment->pow2Width, attachment->pow2Height);
310
311 }
312 }
313 attachment = (IWineD3DSurfaceImpl *)context->current_fbo->depth_stencil;
314 if (attachment)
315 {
316 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
317 attachment, debug_d3dformat(attachment->resource.format_desc->format),
318 attachment->pow2Width, attachment->pow2Height);
319 }
320 }
321 }
322}
323
324static struct fbo_entry *context_create_fbo_entry(struct wined3d_context *context)
325{
326 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
327 const struct wined3d_gl_info *gl_info = context->gl_info;
328 struct fbo_entry *entry;
329
330 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
331 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
332 memcpy(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
333 entry->depth_stencil = device->stencilBufferTarget;
334 entry->attached = FALSE;
335 entry->id = 0;
336
337 return entry;
338}
339
340/* GL locking is done by the caller */
341static void context_reuse_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
342{
343 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
344 const struct wined3d_gl_info *gl_info = context->gl_info;
345
346 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &entry->id);
347 context_clean_fbo_attachments(gl_info);
348
349 memcpy(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
350 entry->depth_stencil = device->stencilBufferTarget;
351 entry->attached = FALSE;
352}
353
354/* GL locking is done by the caller */
355static void context_destroy_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
356{
357 if (entry->id)
358 {
359 TRACE("Destroy FBO %d\n", entry->id);
360 context_destroy_fbo(context, &entry->id);
361 }
362 --context->fbo_entry_count;
363 list_remove(&entry->entry);
364 HeapFree(GetProcessHeap(), 0, entry->render_targets);
365 HeapFree(GetProcessHeap(), 0, entry);
366}
367
368
369/* GL locking is done by the caller */
370static struct fbo_entry *context_find_fbo_entry(struct wined3d_context *context)
371{
372 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
373 const struct wined3d_gl_info *gl_info = context->gl_info;
374 struct fbo_entry *entry;
375
376 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
377 {
378 if (!memcmp(entry->render_targets, device->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
379 && entry->depth_stencil == device->stencilBufferTarget)
380 {
381 list_remove(&entry->entry);
382 list_add_head(&context->fbo_list, &entry->entry);
383 return entry;
384 }
385 }
386
387 if (context->fbo_entry_count < WINED3D_MAX_FBO_ENTRIES)
388 {
389 entry = context_create_fbo_entry(context);
390 list_add_head(&context->fbo_list, &entry->entry);
391 ++context->fbo_entry_count;
392 }
393 else
394 {
395 entry = LIST_ENTRY(list_tail(&context->fbo_list), struct fbo_entry, entry);
396 context_reuse_fbo_entry(context, entry);
397 list_remove(&entry->entry);
398 list_add_head(&context->fbo_list, &entry->entry);
399 }
400
401 return entry;
402}
403
404/* GL locking is done by the caller */
405static void context_apply_fbo_entry(struct wined3d_context *context, struct fbo_entry *entry)
406{
407 IWineD3DDeviceImpl *device = ((IWineD3DSurfaceImpl *)context->surface)->resource.wineD3DDevice;
408 const struct wined3d_gl_info *gl_info = context->gl_info;
409 unsigned int i;
410
411 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &entry->id);
412
413 if (!entry->attached)
414 {
415 /* Apply render targets */
416 for (i = 0; i < GL_LIMITS(buffers); ++i)
417 {
418 IWineD3DSurface *render_target = device->render_targets[i];
419 context_attach_surface_fbo(context, GL_FRAMEBUFFER_EXT, i, render_target);
420 }
421
422 /* Apply depth targets */
423 if (device->stencilBufferTarget)
424 {
425 unsigned int w = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Width;
426 unsigned int h = ((IWineD3DSurfaceImpl *)device->render_targets[0])->pow2Height;
427
428 surface_set_compatible_renderbuffer(device->stencilBufferTarget, w, h);
429 }
430 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, device->stencilBufferTarget, TRUE);
431
432 entry->attached = TRUE;
433 } else {
434 for (i = 0; i < GL_LIMITS(buffers); ++i)
435 {
436 if (device->render_targets[i])
437 context_apply_attachment_filter_states(device->render_targets[i], FALSE);
438 }
439 if (device->stencilBufferTarget)
440 context_apply_attachment_filter_states(device->stencilBufferTarget, FALSE);
441 }
442
443 for (i = 0; i < GL_LIMITS(buffers); ++i)
444 {
445 if (device->render_targets[i])
446 device->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
447 else
448 device->draw_buffers[i] = GL_NONE;
449 }
450}
451
452/* GL locking is done by the caller */
453static void context_apply_fbo_state(struct wined3d_context *context)
454{
455 if (context->render_offscreen)
456 {
457 context->current_fbo = context_find_fbo_entry(context);
458 context_apply_fbo_entry(context, context->current_fbo);
459 } else {
460 context->current_fbo = NULL;
461 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
462 }
463
464 context_check_fbo_status(context);
465}
466
467/* Context activation is done by the caller. */
468void context_alloc_occlusion_query(struct wined3d_context *context, struct wined3d_occlusion_query *query)
469{
470 const struct wined3d_gl_info *gl_info = context->gl_info;
471
472 if (context->free_occlusion_query_count)
473 {
474 query->id = context->free_occlusion_queries[--context->free_occlusion_query_count];
475 }
476 else
477 {
478 if (GL_SUPPORT(ARB_OCCLUSION_QUERY))
479 {
480 ENTER_GL();
481 GL_EXTCALL(glGenQueriesARB(1, &query->id));
482 checkGLcall("glGenQueriesARB");
483 LEAVE_GL();
484
485 TRACE("Allocated occlusion query %u in context %p.\n", query->id, context);
486 }
487 else
488 {
489 WARN("Occlusion queries not supported, not allocating query id.\n");
490 query->id = 0;
491 }
492 }
493
494 query->context = context;
495 list_add_head(&context->occlusion_queries, &query->entry);
496}
497
498void context_free_occlusion_query(struct wined3d_occlusion_query *query)
499{
500 struct wined3d_context *context = query->context;
501
502 list_remove(&query->entry);
503 query->context = NULL;
504
505 if (context->free_occlusion_query_count >= context->free_occlusion_query_size - 1)
506 {
507 UINT new_size = context->free_occlusion_query_size << 1;
508 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_occlusion_queries,
509 new_size * sizeof(*context->free_occlusion_queries));
510
511 if (!new_data)
512 {
513 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
514 return;
515 }
516
517 context->free_occlusion_query_size = new_size;
518 context->free_occlusion_queries = new_data;
519 }
520
521 context->free_occlusion_queries[context->free_occlusion_query_count++] = query->id;
522}
523
524/* Context activation is done by the caller. */
525void context_alloc_event_query(struct wined3d_context *context, struct wined3d_event_query *query)
526{
527 const struct wined3d_gl_info *gl_info = context->gl_info;
528
529 if (context->free_event_query_count)
530 {
531 query->id = context->free_event_queries[--context->free_event_query_count];
532 }
533 else
534 {
535 if (GL_SUPPORT(APPLE_FENCE))
536 {
537 ENTER_GL();
538 GL_EXTCALL(glGenFencesAPPLE(1, &query->id));
539 checkGLcall("glGenFencesAPPLE");
540 LEAVE_GL();
541
542 TRACE("Allocated event query %u in context %p.\n", query->id, context);
543 }
544 else if(GL_SUPPORT(NV_FENCE))
545 {
546 ENTER_GL();
547 GL_EXTCALL(glGenFencesNV(1, &query->id));
548 checkGLcall("glGenFencesNV");
549 LEAVE_GL();
550
551 TRACE("Allocated event query %u in context %p.\n", query->id, context);
552 }
553 else
554 {
555 WARN("Event queries not supported, not allocating query id.\n");
556 query->id = 0;
557 }
558 }
559
560 query->context = context;
561 list_add_head(&context->event_queries, &query->entry);
562}
563
564void context_free_event_query(struct wined3d_event_query *query)
565{
566 struct wined3d_context *context = query->context;
567
568 list_remove(&query->entry);
569 query->context = NULL;
570
571 if (context->free_event_query_count >= context->free_event_query_size - 1)
572 {
573 UINT new_size = context->free_event_query_size << 1;
574 GLuint *new_data = HeapReAlloc(GetProcessHeap(), 0, context->free_event_queries,
575 new_size * sizeof(*context->free_event_queries));
576
577 if (!new_data)
578 {
579 ERR("Failed to grow free list, leaking query %u in context %p.\n", query->id, context);
580 return;
581 }
582
583 context->free_event_query_size = new_size;
584 context->free_event_queries = new_data;
585 }
586
587 context->free_event_queries[context->free_event_query_count++] = query->id;
588}
589
590void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
591{
592 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
593 UINT i;
594
595 if (!This->d3d_initialized) return;
596
597 switch(type)
598 {
599 case WINED3DRTYPE_SURFACE:
600 {
601 ActivateContext(This, NULL, CTXUSAGE_RESOURCELOAD);
602
603 for (i = 0; i < This->numContexts; ++i)
604 {
605 struct wined3d_context *context = This->contexts[i];
606 const struct wined3d_gl_info *gl_info = context->gl_info;
607 struct fbo_entry *entry, *entry2;
608
609 if (context->current_rt == (IWineD3DSurface *)resource) context->current_rt = NULL;
610
611 ENTER_GL();
612
613 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry)
614 {
615 BOOL destroyed = FALSE;
616 UINT j;
617
618 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
619 {
620 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
621 {
622 context_destroy_fbo_entry(context, entry);
623 destroyed = TRUE;
624 }
625 }
626
627 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
628 context_destroy_fbo_entry(context, entry);
629 }
630
631 LEAVE_GL();
632 }
633
634 break;
635 }
636
637 default:
638 break;
639 }
640}
641
642static void context_destroy_gl_resources(struct wined3d_context *context)
643{
644 const struct wined3d_gl_info *gl_info = context->gl_info;
645 struct wined3d_occlusion_query *occlusion_query;
646 struct wined3d_event_query *event_query;
647 struct fbo_entry *entry, *entry2;
648 BOOL has_glctx;
649
650 has_glctx = pwglMakeCurrent(context->hdc, context->glCtx);
651 if (!has_glctx) WARN("Failed to activate context. Window already destroyed?\n");
652
653 ENTER_GL();
654
655 LIST_FOR_EACH_ENTRY(occlusion_query, &context->occlusion_queries, struct wined3d_occlusion_query, entry)
656 {
657 if (has_glctx && GL_SUPPORT(ARB_OCCLUSION_QUERY)) GL_EXTCALL(glDeleteQueriesARB(1, &occlusion_query->id));
658 occlusion_query->context = NULL;
659 }
660
661 LIST_FOR_EACH_ENTRY(event_query, &context->event_queries, struct wined3d_event_query, entry)
662 {
663 if (has_glctx)
664 {
665 if (GL_SUPPORT(APPLE_FENCE)) GL_EXTCALL(glDeleteFencesAPPLE(1, &event_query->id));
666 else if (GL_SUPPORT(NV_FENCE)) GL_EXTCALL(glDeleteFencesNV(1, &event_query->id));
667 }
668 event_query->context = NULL;
669 }
670
671 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
672 if (!has_glctx) entry->id = 0;
673 context_destroy_fbo_entry(context, entry);
674 }
675 if (has_glctx)
676 {
677 if (context->src_fbo)
678 {
679 TRACE("Destroy src FBO %d\n", context->src_fbo);
680 context_destroy_fbo(context, &context->src_fbo);
681 }
682 if (context->dst_fbo)
683 {
684 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
685 context_destroy_fbo(context, &context->dst_fbo);
686 }
687 if (context->dummy_arbfp_prog)
688 {
689 GL_EXTCALL(glDeleteProgramsARB(1, &context->dummy_arbfp_prog));
690 }
691
692 GL_EXTCALL(glDeleteQueriesARB(context->free_occlusion_query_count, context->free_occlusion_queries));
693
694 if (GL_SUPPORT(APPLE_FENCE))
695 GL_EXTCALL(glDeleteFencesAPPLE(context->free_event_query_count, context->free_event_queries));
696 else if (GL_SUPPORT(NV_FENCE))
697 GL_EXTCALL(glDeleteFencesNV(context->free_event_query_count, context->free_event_queries));
698
699 checkGLcall("context cleanup");
700 }
701
702 LEAVE_GL();
703
704 HeapFree(GetProcessHeap(), 0, context->free_occlusion_queries);
705 HeapFree(GetProcessHeap(), 0, context->free_event_queries);
706
707 if (!pwglMakeCurrent(NULL, NULL))
708 {
709 ERR("Failed to disable GL context.\n");
710 }
711
712 if (context->isPBuffer)
713 {
714 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
715 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
716 }
717 else
718 {
719 ReleaseDC(context->win_handle, context->hdc);
720 }
721
722 if (!pwglDeleteContext(context->glCtx))
723 {
724 DWORD err = GetLastError();
725 ERR("wglDeleteContext(%p) failed, last error %#x.\n", context->glCtx, err);
726 }
727}
728
729DWORD context_get_tls_idx(void)
730{
731 return wined3d_context_tls_idx;
732}
733
734void context_set_tls_idx(DWORD idx)
735{
736 wined3d_context_tls_idx = idx;
737}
738
739struct wined3d_context *context_get_current(void)
740{
741 return TlsGetValue(wined3d_context_tls_idx);
742}
743
744BOOL context_set_current(struct wined3d_context *ctx)
745{
746 struct wined3d_context *old = context_get_current();
747
748 if (old == ctx)
749 {
750 TRACE("Already using D3D context %p.\n", ctx);
751 return TRUE;
752 }
753
754 if (old)
755 {
756 if (old->destroyed)
757 {
758 TRACE("Switching away from destroyed context %p.\n", old);
759 context_destroy_gl_resources(old);
760 HeapFree(GetProcessHeap(), 0, old);
761 }
762 else
763 {
764 old->current = 0;
765 }
766 }
767
768 if (ctx)
769 {
770 TRACE("Switching to D3D context %p, GL context %p, device context %p.\n", ctx, ctx->glCtx, ctx->hdc);
771 if (!pwglMakeCurrent(ctx->hdc, ctx->glCtx))
772 {
773 ERR("Failed to make GL context %p current on device context %p.\n", ctx->glCtx, ctx->hdc);
774 return FALSE;
775 }
776 ctx->current = 1;
777 }
778 else
779 {
780 TRACE("Clearing current D3D context.\n");
781 if (!pwglMakeCurrent(NULL, NULL))
782 {
783 ERR("Failed to clear current GL context.\n");
784 /*In case of failure, wglMakeCurrent makes current GLRC not current anyway.*/
785 TlsSetValue(wined3d_context_tls_idx, NULL);
786 return FALSE;
787 }
788 }
789
790 return TlsSetValue(wined3d_context_tls_idx, ctx);
791}
792
793/*****************************************************************************
794 * Context_MarkStateDirty
795 *
796 * Marks a state in a context dirty. Only one context, opposed to
797 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
798 * contexts
799 *
800 * Params:
801 * context: Context to mark the state dirty in
802 * state: State to mark dirty
803 * StateTable: Pointer to the state table in use(for state grouping)
804 *
805 *****************************************************************************/
806static void Context_MarkStateDirty(struct wined3d_context *context, DWORD state, const struct StateEntry *StateTable)
807{
808 DWORD rep = StateTable[state].representative;
809 DWORD idx;
810 BYTE shift;
811
812 if(!rep || isStateDirty(context, rep)) return;
813
814 context->dirtyArray[context->numDirtyEntries++] = rep;
815 idx = rep >> 5;
816 shift = rep & 0x1f;
817 context->isStateDirty[idx] |= (1 << shift);
818}
819
820/*****************************************************************************
821 * AddContextToArray
822 *
823 * Adds a context to the context array. Helper function for CreateContext
824 *
825 * This method is not called in performance-critical code paths, only when a
826 * new render target or swapchain is created. Thus performance is not an issue
827 * here.
828 *
829 * Params:
830 * This: Device to add the context for
831 * hdc: device context
832 * glCtx: WGL context to add
833 * pbuffer: optional pbuffer used with this context
834 *
835 *****************************************************************************/
836static struct wined3d_context *AddContextToArray(IWineD3DDeviceImpl *This,
837 HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer)
838{
839 struct wined3d_context **oldArray = This->contexts;
840 DWORD state;
841
842 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
843 if(This->contexts == NULL) {
844 ERR("Unable to grow the context array\n");
845 This->contexts = oldArray;
846 return NULL;
847 }
848 if(oldArray) {
849 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
850 }
851
852 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(**This->contexts));
853 if(This->contexts[This->numContexts] == NULL) {
854 ERR("Unable to allocate a new context\n");
855 HeapFree(GetProcessHeap(), 0, This->contexts);
856 This->contexts = oldArray;
857 return NULL;
858 }
859
860 This->contexts[This->numContexts]->hdc = hdc;
861 This->contexts[This->numContexts]->glCtx = glCtx;
862 This->contexts[This->numContexts]->pbuffer = pbuffer;
863 This->contexts[This->numContexts]->win_handle = win_handle;
864 HeapFree(GetProcessHeap(), 0, oldArray);
865
866 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
867 */
868 for(state = 0; state <= STATE_HIGHEST; state++) {
869 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
870 }
871
872 This->numContexts++;
873 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
874 return This->contexts[This->numContexts - 1];
875}
876
877/* This function takes care of WineD3D pixel format selection. */
878static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc,
879 const struct GlPixelFormatDesc *color_format_desc, const struct GlPixelFormatDesc *ds_format_desc,
880 BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
881{
882 int iPixelFormat=0;
883 unsigned int matchtry;
884 short redBits, greenBits, blueBits, alphaBits, colorBits;
885 short depthBits=0, stencilBits=0;
886
887 struct match_type {
888 BOOL require_aux;
889 BOOL exact_alpha;
890 BOOL exact_color;
891 } matches[] = {
892 /* First, try without alpha match buffers. MacOS supports aux buffers only
893 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
894 * Then try without aux buffers - this is the most common cause for not
895 * finding a pixel format. Also some drivers(the open source ones)
896 * only offer 32 bit ARB pixel formats. First try without an exact alpha
897 * match, then try without an exact alpha and color match.
898 */
899 { TRUE, TRUE, TRUE },
900 { TRUE, FALSE, TRUE },
901 { FALSE, TRUE, TRUE },
902 { FALSE, FALSE, TRUE },
903 { TRUE, FALSE, FALSE },
904 { FALSE, FALSE, FALSE },
905 };
906
907 int i = 0;
908 int nCfgs = This->adapter->nCfgs;
909
910 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
911 debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format),
912 auxBuffers, numSamples, pbuffer, findCompatible);
913
914 if (!getColorBits(color_format_desc, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
915 {
916 ERR("Unable to get color bits for format %s (%#x)!\n",
917 debug_d3dformat(color_format_desc->format), color_format_desc->format);
918 return 0;
919 }
920
921 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
922 * You are able to add a depth + stencil surface at a later stage when you need it.
923 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
924 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
925 * context, need torecreate shaders, textures and other resources.
926 *
927 * The context manager already takes care of the state problem and for the other tasks code from Reset
928 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
929 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
930 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
931 * issue needs to be fixed. */
932 if (ds_format_desc->format != WINED3DFMT_D24S8)
933 {
934 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
935 ds_format_desc = getFormatDescEntry(WINED3DFMT_D24S8, &This->adapter->gl_info);
936 }
937
938 getDepthStencilBits(ds_format_desc, &depthBits, &stencilBits);
939
940 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
941 for(i=0; i<nCfgs; i++) {
942 BOOL exactDepthMatch = TRUE;
943 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
944
945 /* For now only accept RGBA formats. Perhaps some day we will
946 * allow floating point formats for pbuffers. */
947 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
948 continue;
949
950 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
951 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
952 continue;
953
954 /* We like to have aux buffers in backbuffer mode */
955 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
956 continue;
957
958 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
959 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
960 continue;
961
962 if(matches[matchtry].exact_color) {
963 if(cfg->redSize != redBits)
964 continue;
965 if(cfg->greenSize != greenBits)
966 continue;
967 if(cfg->blueSize != blueBits)
968 continue;
969 } else {
970 if(cfg->redSize < redBits)
971 continue;
972 if(cfg->greenSize < greenBits)
973 continue;
974 if(cfg->blueSize < blueBits)
975 continue;
976 }
977 if(matches[matchtry].exact_alpha) {
978 if(cfg->alphaSize != alphaBits)
979 continue;
980 } else {
981 if(cfg->alphaSize < alphaBits)
982 continue;
983 }
984
985 /* We try to locate a format which matches our requirements exactly. In case of
986 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
987 if(cfg->depthSize < depthBits)
988 continue;
989 else if(cfg->depthSize > depthBits)
990 exactDepthMatch = FALSE;
991
992 /* In all cases make sure the number of stencil bits matches our requirements
993 * even when we don't need stencil because it could affect performance EXCEPT
994 * on cards which don't offer depth formats without stencil like the i915 drivers
995 * on Linux. */
996 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
997 continue;
998
999 /* Check multisampling support */
1000 if(cfg->numSamples != numSamples)
1001 continue;
1002
1003 /* When we have passed all the checks then we have found a format which matches our
1004 * requirements. Note that we only check for a limit number of capabilities right now,
1005 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
1006 * can still differ in things like multisampling, stereo, SRGB and other flags.
1007 */
1008
1009 /* Exit the loop as we have found a format :) */
1010 if(exactDepthMatch) {
1011 iPixelFormat = cfg->iPixelFormat;
1012 break;
1013 } else if(!iPixelFormat) {
1014 /* In the end we might end up with a format which doesn't exactly match our depth
1015 * requirements. Accept the first format we found because formats with higher iPixelFormat
1016 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
1017 iPixelFormat = cfg->iPixelFormat;
1018 }
1019 }
1020 }
1021
1022 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
1023 if(!iPixelFormat && !findCompatible) {
1024 ERR("Can't find a suitable iPixelFormat\n");
1025 return FALSE;
1026 } else if(!iPixelFormat) {
1027 PIXELFORMATDESCRIPTOR pfd;
1028
1029 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
1030 /* PixelFormat selection */
1031 ZeroMemory(&pfd, sizeof(pfd));
1032 pfd.nSize = sizeof(pfd);
1033 pfd.nVersion = 1;
1034 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
1035 pfd.iPixelType = PFD_TYPE_RGBA;
1036 pfd.cAlphaBits = alphaBits;
1037 pfd.cColorBits = colorBits;
1038 pfd.cDepthBits = depthBits;
1039 pfd.cStencilBits = stencilBits;
1040 pfd.iLayerType = PFD_MAIN_PLANE;
1041
1042 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
1043 if(!iPixelFormat) {
1044 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
1045 ERR("Can't find a suitable iPixelFormat\n");
1046 return FALSE;
1047 }
1048 }
1049
1050 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n",
1051 iPixelFormat, debug_d3dformat(color_format_desc->format), debug_d3dformat(ds_format_desc->format));
1052 return iPixelFormat;
1053}
1054
1055/*****************************************************************************
1056 * CreateContext
1057 *
1058 * Creates a new context for a window, or a pbuffer context.
1059 *
1060 * * Params:
1061 * This: Device to activate the context for
1062 * target: Surface this context will render to
1063 * win_handle: handle to the window which we are drawing to
1064 * create_pbuffer: tells whether to create a pbuffer or not
1065 * pPresentParameters: contains the pixelformats to use for onscreen rendering
1066 *
1067 *****************************************************************************/
1068struct wined3d_context *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target,
1069 HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms)
1070{
1071 const struct wined3d_gl_info *gl_info = &This->adapter->gl_info;
1072 struct wined3d_context *ret = NULL;
1073 HPBUFFERARB pbuffer = NULL;
1074 unsigned int s;
1075 HGLRC ctx;
1076 HDC hdc;
1077
1078 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
1079
1080 if(create_pbuffer) {
1081 HDC hdc_parent = GetDC(win_handle);
1082 int iPixelFormat = 0;
1083
1084 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
1085 const struct GlPixelFormatDesc *ds_format_desc = StencilSurface
1086 ? ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc
1087 : getFormatDescEntry(WINED3DFMT_UNKNOWN, &This->adapter->gl_info);
1088
1089 /* Try to find a pixel format with pbuffer support. */
1090 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
1091 ds_format_desc, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
1092 FALSE /* findCompatible */);
1093 if(!iPixelFormat) {
1094 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1095
1096 /* For some reason we weren't able to find a format, try to find something instead of crashing.
1097 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
1098 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc,
1099 ds_format_desc, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
1100 TRUE /* findCompatible */);
1101 }
1102
1103 /* This shouldn't happen as ChoosePixelFormat always returns something */
1104 if(!iPixelFormat) {
1105 ERR("Unable to locate a pixel format for a pbuffer\n");
1106 ReleaseDC(win_handle, hdc_parent);
1107 goto out;
1108 }
1109
1110 TRACE("Creating a pBuffer drawable for the new context\n");
1111 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
1112 if(!pbuffer) {
1113 ERR("Cannot create a pbuffer\n");
1114 ReleaseDC(win_handle, hdc_parent);
1115 goto out;
1116 }
1117
1118 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
1119 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
1120 if(!hdc) {
1121 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
1122 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1123 ReleaseDC(win_handle, hdc_parent);
1124 goto out;
1125 }
1126 ReleaseDC(win_handle, hdc_parent);
1127 } else {
1128 PIXELFORMATDESCRIPTOR pfd;
1129 int iPixelFormat;
1130 int res;
1131 const struct GlPixelFormatDesc *color_format_desc = target->resource.format_desc;
1132 const struct GlPixelFormatDesc *ds_format_desc = getFormatDescEntry(WINED3DFMT_UNKNOWN,
1133 &This->adapter->gl_info);
1134 BOOL auxBuffers = FALSE;
1135 int numSamples = 0;
1136
1137 hdc = GetDC(win_handle);
1138 if(hdc == NULL) {
1139 ERR("Cannot retrieve a device context!\n");
1140 goto out;
1141 }
1142
1143 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
1144 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
1145 auxBuffers = TRUE;
1146
1147 if (color_format_desc->format == WINED3DFMT_X4R4G4B4)
1148 color_format_desc = getFormatDescEntry(WINED3DFMT_A4R4G4B4, &This->adapter->gl_info);
1149 else if (color_format_desc->format == WINED3DFMT_X8R8G8B8)
1150 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
1151 }
1152
1153 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
1154 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
1155 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
1156 * a format with 8bit alpha, so request A8R8G8B8. */
1157 if (color_format_desc->format == WINED3DFMT_P8)
1158 color_format_desc = getFormatDescEntry(WINED3DFMT_A8R8G8B8, &This->adapter->gl_info);
1159
1160 /* Retrieve the depth stencil format from the present parameters.
1161 * The choice of the proper format can give a nice performance boost
1162 * in case of GPU limited programs. */
1163 if(pPresentParms->EnableAutoDepthStencil) {
1164 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
1165 ds_format_desc = getFormatDescEntry(pPresentParms->AutoDepthStencilFormat, &This->adapter->gl_info);
1166 }
1167
1168 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
1169 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
1170 if(!GL_SUPPORT(ARB_MULTISAMPLE))
1171 ERR("The program is requesting multisampling without support!\n");
1172 else {
1173 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
1174 numSamples = pPresentParms->MultiSampleType;
1175 }
1176 }
1177
1178 /* Try to find a pixel format which matches our requirements */
1179 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
1180 auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
1181
1182 /* Try to locate a compatible format if we weren't able to find anything */
1183 if(!iPixelFormat) {
1184 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
1185 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, color_format_desc, ds_format_desc,
1186 auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
1187 }
1188
1189 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
1190 if(!iPixelFormat) {
1191 ERR("Can't find a suitable iPixelFormat\n");
1192 return NULL;
1193 }
1194
1195 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
1196 res = SetPixelFormat(hdc, iPixelFormat, NULL);
1197 if(!res) {
1198 int oldPixelFormat = GetPixelFormat(hdc);
1199
1200 /* By default WGL doesn't allow pixel format adjustments but we need it here.
1201 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
1202 * set the pixel format multiple times. Only use it when it is really needed. */
1203
1204 if(oldPixelFormat == iPixelFormat) {
1205 /* We don't have to do anything as the formats are the same :) */
1206 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
1207 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
1208
1209 if(!res) {
1210 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
1211 return NULL;
1212 }
1213 } else if(oldPixelFormat) {
1214 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
1215 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
1216 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
1217 } else {
1218 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
1219 return NULL;
1220 }
1221 }
1222 }
1223
1224 ctx = pwglCreateContext(hdc);
1225 if (This->numContexts)
1226 {
1227 if (!pwglShareLists(This->contexts[0]->glCtx, ctx))
1228 {
1229 DWORD err = GetLastError();
1230 ERR("wglShareLists(%p, %p) failed, last error %#x.\n",
1231 This->contexts[0]->glCtx, ctx, err);
1232 }
1233 }
1234
1235 if(!ctx) {
1236 ERR("Failed to create a WGL context\n");
1237 if(create_pbuffer) {
1238 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1239 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1240 }
1241 goto out;
1242 }
1243 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
1244 if(!ret) {
1245 ERR("Failed to add the newly created context to the context list\n");
1246 if (!pwglDeleteContext(ctx))
1247 {
1248 DWORD err = GetLastError();
1249 ERR("wglDeleteContext(%p) failed, last error %#x.\n", ctx, err);
1250 }
1251 if(create_pbuffer) {
1252 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
1253 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
1254 }
1255 goto out;
1256 }
1257 ret->gl_info = &This->adapter->gl_info;
1258 ret->surface = (IWineD3DSurface *) target;
1259 ret->current_rt = (IWineD3DSurface *)target;
1260 ret->isPBuffer = create_pbuffer;
1261 ret->tid = GetCurrentThreadId();
1262 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
1263 /* Create the dirty constants array and initialize them to dirty */
1264 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1265 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1266 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
1267 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1268 memset(ret->vshader_const_dirty, 1,
1269 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1270 memset(ret->pshader_const_dirty, 1,
1271 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1272 }
1273
1274 ret->free_occlusion_query_size = 4;
1275 ret->free_occlusion_queries = HeapAlloc(GetProcessHeap(), 0,
1276 ret->free_occlusion_query_size * sizeof(*ret->free_occlusion_queries));
1277 if (!ret->free_occlusion_queries) goto out;
1278
1279 list_init(&ret->occlusion_queries);
1280
1281 ret->free_event_query_size = 4;
1282 ret->free_event_queries = HeapAlloc(GetProcessHeap(), 0,
1283 ret->free_event_query_size * sizeof(*ret->free_event_queries));
1284 if (!ret->free_event_queries) goto out;
1285
1286 list_init(&ret->event_queries);
1287
1288 TRACE("Successfully created new context %p\n", ret);
1289
1290 list_init(&ret->fbo_list);
1291
1292 /* Set up the context defaults */
1293 if (!context_set_current(ret))
1294 {
1295 ERR("Cannot activate context to set up defaults\n");
1296 goto out;
1297 }
1298
1299 ENTER_GL();
1300
1301 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
1302
1303 TRACE("Setting up the screen\n");
1304 /* Clear the screen */
1305 glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
1306 checkGLcall("glClearColor");
1307 glClearIndex(0);
1308 glClearDepth(1);
1309 glClearStencil(0xffff);
1310
1311 checkGLcall("glClear");
1312
1313 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
1314 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
1315
1316 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
1317 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
1318
1319 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1320 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
1321
1322 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
1323 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
1324 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
1325 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
1326
1327 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
1328 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
1329 * and textures in DIB sections(due to the memory protection).
1330 */
1331 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
1332 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
1333 }
1334 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
1335 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
1336 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
1337 * GL_VERTEX_BLEND_ARB isn't enabled too
1338 */
1339 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
1340 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
1341 }
1342 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
1343 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
1344 * the previous texture where to source the offset from is always unit - 1.
1345 */
1346 for(s = 1; s < GL_LIMITS(textures); s++) {
1347 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1348 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
1349 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...");
1350 }
1351 }
1352 if(GL_SUPPORT(ARB_FRAGMENT_PROGRAM)) {
1353 /* MacOS(radeon X1600 at least, but most likely others too) refuses to draw if GLSL and ARBFP are
1354 * enabled, but the currently bound arbfp program is 0. Enabling ARBFP with prog 0 is invalid, but
1355 * GLSL should bypass this. This causes problems in programs that never use the fixed function pipeline,
1356 * because the ARBFP extension is enabled by the ARBFP pipeline at context creation, but no program
1357 * is ever assigned.
1358 *
1359 * So make sure a program is assigned to each context. The first real ARBFP use will set a different
1360 * program and the dummy program is destroyed when the context is destroyed.
1361 */
1362 const char *dummy_program =
1363 "!!ARBfp1.0\n"
1364 "MOV result.color, fragment.color.primary;\n"
1365 "END\n";
1366 GL_EXTCALL(glGenProgramsARB(1, &ret->dummy_arbfp_prog));
1367 GL_EXTCALL(glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, ret->dummy_arbfp_prog));
1368 GL_EXTCALL(glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(dummy_program), dummy_program));
1369 }
1370
1371 for(s = 0; s < GL_LIMITS(point_sprite_units); s++) {
1372 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
1373 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
1374 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)");
1375 }
1376 LEAVE_GL();
1377
1378 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1379
1380 return ret;
1381
1382out:
1383 if (ret)
1384 {
1385 HeapFree(GetProcessHeap(), 0, ret->free_event_queries);
1386 HeapFree(GetProcessHeap(), 0, ret->free_occlusion_queries);
1387 HeapFree(GetProcessHeap(), 0, ret->pshader_const_dirty);
1388 HeapFree(GetProcessHeap(), 0, ret->vshader_const_dirty);
1389 HeapFree(GetProcessHeap(), 0, ret);
1390 }
1391 return NULL;
1392}
1393
1394/*****************************************************************************
1395 * RemoveContextFromArray
1396 *
1397 * Removes a context from the context manager. The opengl context is not
1398 * destroyed or unset. context is not a valid pointer after that call.
1399 *
1400 * Similar to the former call this isn't a performance critical function. A
1401 * helper function for DestroyContext.
1402 *
1403 * Params:
1404 * This: Device to activate the context for
1405 * context: Context to remove
1406 *
1407 *****************************************************************************/
1408static void RemoveContextFromArray(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1409{
1410 struct wined3d_context **new_array;
1411 BOOL found = FALSE;
1412 UINT i;
1413
1414 TRACE("Removing ctx %p\n", context);
1415
1416 for (i = 0; i < This->numContexts; ++i)
1417 {
1418 if (This->contexts[i] == context)
1419 {
1420 found = TRUE;
1421 break;
1422 }
1423 }
1424
1425 if (!found)
1426 {
1427 ERR("Context %p doesn't exist in context array\n", context);
1428 return;
1429 }
1430
1431 while (i < This->numContexts - 1)
1432 {
1433 This->contexts[i] = This->contexts[i + 1];
1434 ++i;
1435 }
1436
1437 --This->numContexts;
1438 if (!This->numContexts)
1439 {
1440 HeapFree(GetProcessHeap(), 0, This->contexts);
1441 This->contexts = NULL;
1442 return;
1443 }
1444
1445 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
1446 if (!new_array)
1447 {
1448 ERR("Failed to shrink context array. Oh well.\n");
1449 return;
1450 }
1451
1452 This->contexts = new_array;
1453}
1454
1455/*****************************************************************************
1456 * DestroyContext
1457 *
1458 * Destroys a wineD3DContext
1459 *
1460 * Params:
1461 * This: Device to activate the context for
1462 * context: Context to destroy
1463 *
1464 *****************************************************************************/
1465void DestroyContext(IWineD3DDeviceImpl *This, struct wined3d_context *context)
1466{
1467 BOOL destroy;
1468
1469 TRACE("Destroying ctx %p\n", context);
1470
1471 if (context->tid == GetCurrentThreadId() || !context->current)
1472 {
1473 context_destroy_gl_resources(context);
1474 destroy = TRUE;
1475
1476 if (!context_set_current(NULL))
1477 {
1478 ERR("Failed to clear current D3D context.\n");
1479 }
1480 }
1481 else
1482 {
1483 context->destroyed = 1;
1484 destroy = FALSE;
1485 }
1486
1487 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1488 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1489 RemoveContextFromArray(This, context);
1490 if (destroy) HeapFree(GetProcessHeap(), 0, context);
1491}
1492
1493/* GL locking is done by the caller */
1494static inline void set_blit_dimension(UINT width, UINT height) {
1495 glMatrixMode(GL_PROJECTION);
1496 checkGLcall("glMatrixMode(GL_PROJECTION)");
1497 glLoadIdentity();
1498 checkGLcall("glLoadIdentity()");
1499 glOrtho(0, width, height, 0, 0.0, -1.0);
1500 checkGLcall("glOrtho");
1501 glViewport(0, 0, width, height);
1502 checkGLcall("glViewport");
1503}
1504
1505/*****************************************************************************
1506 * SetupForBlit
1507 *
1508 * Sets up a context for DirectDraw blitting.
1509 * All texture units are disabled, texture unit 0 is set as current unit
1510 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1511 * color writing enabled for all channels
1512 * register combiners disabled, shaders disabled
1513 * world matrix is set to identity, texture matrix 0 too
1514 * projection matrix is setup for drawing screen coordinates
1515 *
1516 * Params:
1517 * This: Device to activate the context for
1518 * context: Context to setup
1519 * width: render target width
1520 * height: render target height
1521 *
1522 *****************************************************************************/
1523/* Context activation is done by the caller. */
1524static inline void SetupForBlit(IWineD3DDeviceImpl *This, struct wined3d_context *context, UINT width, UINT height)
1525{
1526 int i, sampler;
1527 const struct StateEntry *StateTable = This->StateTable;
1528 const struct wined3d_gl_info *gl_info = context->gl_info;
1529
1530 TRACE("Setting up context %p for blitting\n", context);
1531 if(context->last_was_blit) {
1532 if(context->blit_w != width || context->blit_h != height) {
1533 ENTER_GL();
1534 set_blit_dimension(width, height);
1535 LEAVE_GL();
1536 context->blit_w = width; context->blit_h = height;
1537 /* No need to dirtify here, the states are still dirtified because they weren't
1538 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1539 * be set
1540 */
1541 }
1542 TRACE("Context is already set up for blitting, nothing to do\n");
1543 return;
1544 }
1545 context->last_was_blit = TRUE;
1546
1547 /* TODO: Use a display list */
1548
1549 /* Disable shaders */
1550 ENTER_GL();
1551 This->shader_backend->shader_select(context, FALSE, FALSE);
1552 LEAVE_GL();
1553
1554 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1555 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1556
1557 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1558 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1559 * which can safely be called from here, we only lock once instead locking/unlocking
1560 * after each GL call.
1561 */
1562 ENTER_GL();
1563
1564 /* Disable all textures. The caller can then bind a texture it wants to blit
1565 * from
1566 *
1567 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1568 * function texture unit. No need to care for higher samplers
1569 */
1570 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1571 sampler = This->rev_tex_unit_map[i];
1572 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1573 checkGLcall("glActiveTextureARB");
1574
1575 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1576 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1577 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1578 }
1579 glDisable(GL_TEXTURE_3D);
1580 checkGLcall("glDisable GL_TEXTURE_3D");
1581 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1582 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1583 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1584 }
1585 glDisable(GL_TEXTURE_2D);
1586 checkGLcall("glDisable GL_TEXTURE_2D");
1587
1588 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1589 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1590
1591 if (sampler != -1) {
1592 if (sampler < MAX_TEXTURES) {
1593 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1594 }
1595 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1596 }
1597 }
1598 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1599 checkGLcall("glActiveTextureARB");
1600
1601 sampler = This->rev_tex_unit_map[0];
1602
1603 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1604 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1605 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1606 }
1607 glDisable(GL_TEXTURE_3D);
1608 checkGLcall("glDisable GL_TEXTURE_3D");
1609 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1610 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1611 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1612 }
1613 glDisable(GL_TEXTURE_2D);
1614 checkGLcall("glDisable GL_TEXTURE_2D");
1615
1616 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1617
1618 glMatrixMode(GL_TEXTURE);
1619 checkGLcall("glMatrixMode(GL_TEXTURE)");
1620 glLoadIdentity();
1621 checkGLcall("glLoadIdentity()");
1622
1623 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1624 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1625 GL_TEXTURE_LOD_BIAS_EXT,
1626 0.0f);
1627 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1628 }
1629
1630 if (sampler != -1) {
1631 if (sampler < MAX_TEXTURES) {
1632 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1633 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1634 }
1635 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1636 }
1637
1638 /* Other misc states */
1639 glDisable(GL_ALPHA_TEST);
1640 checkGLcall("glDisable(GL_ALPHA_TEST)");
1641 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1642 glDisable(GL_LIGHTING);
1643 checkGLcall("glDisable GL_LIGHTING");
1644 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1645 glDisable(GL_DEPTH_TEST);
1646 checkGLcall("glDisable GL_DEPTH_TEST");
1647 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1648 glDisableWINE(GL_FOG);
1649 checkGLcall("glDisable GL_FOG");
1650 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1651 glDisable(GL_BLEND);
1652 checkGLcall("glDisable GL_BLEND");
1653 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1654 glDisable(GL_CULL_FACE);
1655 checkGLcall("glDisable GL_CULL_FACE");
1656 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1657 glDisable(GL_STENCIL_TEST);
1658 checkGLcall("glDisable GL_STENCIL_TEST");
1659 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1660 glDisable(GL_SCISSOR_TEST);
1661 checkGLcall("glDisable GL_SCISSOR_TEST");
1662 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1663 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1664 glDisable(GL_POINT_SPRITE_ARB);
1665 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1666 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1667 }
1668 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1669 checkGLcall("glColorMask");
1670 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_COLORWRITEENABLE), StateTable);
1671 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1672 glDisable(GL_COLOR_SUM_EXT);
1673 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1674 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1675 }
1676
1677 /* Setup transforms */
1678 glMatrixMode(GL_MODELVIEW);
1679 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1680 glLoadIdentity();
1681 checkGLcall("glLoadIdentity()");
1682 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1683
1684 context->last_was_rhw = TRUE;
1685 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1686
1687 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1688 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1689 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1690 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1691 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1692 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1693 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1694
1695 set_blit_dimension(width, height);
1696
1697 LEAVE_GL();
1698
1699 context->blit_w = width; context->blit_h = height;
1700 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1701 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1702
1703
1704 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1705}
1706
1707/*****************************************************************************
1708 * findThreadContextForSwapChain
1709 *
1710 * Searches a swapchain for all contexts and picks one for the thread tid.
1711 * If none can be found the swapchain is requested to create a new context
1712 *
1713 *****************************************************************************/
1714static struct wined3d_context *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid)
1715{
1716 unsigned int i;
1717
1718 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1719 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1720 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1721 }
1722
1723 }
1724
1725 /* Create a new context for the thread */
1726 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1727}
1728
1729/*****************************************************************************
1730 * FindContext
1731 *
1732 * Finds a context for the current render target and thread
1733 *
1734 * Parameters:
1735 * target: Render target to find the context for
1736 * tid: Thread to activate the context for
1737 *
1738 * Returns: The needed context
1739 *
1740 *****************************************************************************/
1741static inline struct wined3d_context *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid)
1742{
1743 IWineD3DSwapChain *swapchain = NULL;
1744 struct wined3d_context *current_context = context_get_current();
1745 const struct StateEntry *StateTable = This->StateTable;
1746 struct wined3d_context *context;
1747 BOOL old_render_offscreen;
1748
1749 if (current_context && current_context->destroyed) current_context = NULL;
1750
1751 if (!target)
1752 {
1753 if (current_context
1754 && current_context->current_rt
1755 && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.wineD3DDevice == This)
1756 {
1757 target = current_context->current_rt;
1758 }
1759 else
1760 {
1761 IWineD3DSwapChainImpl *swapchain = (IWineD3DSwapChainImpl *)This->swapchains[0];
1762 if (swapchain->backBuffer) target = swapchain->backBuffer[0];
1763 else target = swapchain->frontBuffer;
1764 }
1765 }
1766
1767 if (current_context && current_context->current_rt == target)
1768 {
1769 return current_context;
1770 }
1771
1772 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1773 TRACE("Rendering onscreen\n");
1774
1775 context = findThreadContextForSwapChain(swapchain, tid);
1776
1777 old_render_offscreen = context->render_offscreen;
1778 context->render_offscreen = FALSE;
1779 /* The context != This->activeContext will catch a NOP context change. This can occur
1780 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1781 * rendering. No context change is needed in that case
1782 */
1783
1784 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1785 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1786 This->pbufferContext->tid = 0;
1787 }
1788 }
1789 IWineD3DSwapChain_Release(swapchain);
1790 }
1791 else
1792 {
1793 TRACE("Rendering offscreen\n");
1794
1795retry:
1796 if (wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER)
1797 {
1798 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *)target;
1799 if (!This->pbufferContext
1800 || This->pbufferWidth < targetimpl->currentDesc.Width
1801 || This->pbufferHeight < targetimpl->currentDesc.Height)
1802 {
1803 if (This->pbufferContext) DestroyContext(This, This->pbufferContext);
1804
1805 /* The display is irrelevant here, the window is 0. But
1806 * CreateContext needs a valid X connection. Create the context
1807 * on the same server as the primary swapchain. The primary
1808 * swapchain is exists at this point. */
1809 This->pbufferContext = CreateContext(This, targetimpl,
1810 ((IWineD3DSwapChainImpl *)This->swapchains[0])->context[0]->win_handle,
1811 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1812 This->pbufferWidth = targetimpl->currentDesc.Width;
1813 This->pbufferHeight = targetimpl->currentDesc.Height;
1814 }
1815
1816 if (This->pbufferContext)
1817 {
1818 if (This->pbufferContext->tid && This->pbufferContext->tid != tid)
1819 {
1820 FIXME("The PBuffer context is only supported for one thread for now!\n");
1821 }
1822 This->pbufferContext->tid = tid;
1823 context = This->pbufferContext;
1824 }
1825 else
1826 {
1827 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering.\n");
1828 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1829 goto retry;
1830 }
1831 }
1832 else
1833 {
1834 /* Stay with the currently active context. */
1835 if (current_context
1836 && ((IWineD3DSurfaceImpl *)current_context->surface)->resource.wineD3DDevice == This)
1837 {
1838 context = current_context;
1839 }
1840 else
1841 {
1842 /* This may happen if the app jumps straight into offscreen rendering
1843 * Start using the context of the primary swapchain. tid == 0 is no problem
1844 * for findThreadContextForSwapChain.
1845 *
1846 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1847 * is perfect to call. */
1848 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1849 }
1850 }
1851
1852 old_render_offscreen = context->render_offscreen;
1853 context->render_offscreen = TRUE;
1854 }
1855
1856 if (context->render_offscreen != old_render_offscreen)
1857 {
1858 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1859 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1860 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1861 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1862 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1863 }
1864
1865 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1866 * the alpha blend state changes with different render target formats. */
1867 if (!context->current_rt)
1868 {
1869 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1870 }
1871 else
1872 {
1873 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)context->current_rt)->resource.format_desc;
1874 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1875
1876 if (old->format != new->format)
1877 {
1878 /* Disable blending when the alpha mask has changed and when a format doesn't support blending. */
1879 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1880 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1881 {
1882 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1883 }
1884 }
1885
1886 /* When switching away from an offscreen render target, and we're not
1887 * using FBOs, we have to read the drawable into the texture. This is
1888 * done via PreLoad (and SFLAG_INDRAWABLE set on the surface). There
1889 * are some things that need care though. PreLoad needs a GL context,
1890 * and FindContext is called before the context is activated. It also
1891 * has to be called with the old rendertarget active, otherwise a
1892 * wrong drawable is read. */
1893 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO
1894 && old_render_offscreen && context->current_rt != target)
1895 {
1896 BOOL oldInDraw = This->isInDraw;
1897
1898 /* surface_internal_preload() requires a context to load the
1899 * texture, so it will call ActivateContext. Set isInDraw to true
1900 * to signal surface_internal_preload() that it has a context. */
1901
1902 /* FIXME: This is just broken. There's no guarantee whatsoever
1903 * that the currently active context, if any, is appropriate for
1904 * reading back the render target. We should probably call
1905 * context_set_current(context) here and then rely on
1906 * ActivateContext() doing the right thing. */
1907 This->isInDraw = TRUE;
1908
1909 /* Read the back buffer of the old drawable into the destination texture. */
1910 if (((IWineD3DSurfaceImpl *)context->current_rt)->texture_name_srgb)
1911 {
1912 surface_internal_preload(context->current_rt, SRGB_BOTH);
1913 }
1914 else
1915 {
1916 surface_internal_preload(context->current_rt, SRGB_RGB);
1917 }
1918
1919 IWineD3DSurface_ModifyLocation(context->current_rt, SFLAG_INDRAWABLE, FALSE);
1920
1921 This->isInDraw = oldInDraw;
1922 }
1923 }
1924
1925 context->draw_buffer_dirty = TRUE;
1926 context->current_rt = target;
1927
1928 return context;
1929}
1930
1931/* Context activation is done by the caller. */
1932static void context_apply_draw_buffer(struct wined3d_context *context, BOOL blit)
1933{
1934 const struct wined3d_gl_info *gl_info = context->gl_info;
1935 IWineD3DSurface *rt = context->current_rt;
1936 IWineD3DSwapChain *swapchain;
1937 IWineD3DDeviceImpl *device;
1938
1939 device = ((IWineD3DSurfaceImpl *)rt)->resource.wineD3DDevice;
1940 if (SUCCEEDED(IWineD3DSurface_GetContainer(rt, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1941 {
1942 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1943 ENTER_GL();
1944 glDrawBuffer(surface_get_gl_buffer(rt, swapchain));
1945 checkGLcall("glDrawBuffers()");
1946 LEAVE_GL();
1947 }
1948 else
1949 {
1950 ENTER_GL();
1951 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1952 {
1953 if (!blit)
1954 {
1955 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1956 {
1957 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), device->draw_buffers));
1958 checkGLcall("glDrawBuffers()");
1959 }
1960 else
1961 {
1962 glDrawBuffer(device->draw_buffers[0]);
1963 checkGLcall("glDrawBuffer()");
1964 }
1965 } else {
1966 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1967 checkGLcall("glDrawBuffer()");
1968 }
1969 }
1970 else
1971 {
1972 glDrawBuffer(device->offscreenBuffer);
1973 checkGLcall("glDrawBuffer()");
1974 }
1975 LEAVE_GL();
1976 }
1977}
1978
1979/*****************************************************************************
1980 * ActivateContext
1981 *
1982 * Finds a rendering context and drawable matching the device and render
1983 * target for the current thread, activates them and puts them into the
1984 * requested state.
1985 *
1986 * Params:
1987 * This: Device to activate the context for
1988 * target: Requested render target
1989 * usage: Prepares the context for blitting, drawing or other actions
1990 *
1991 *****************************************************************************/
1992struct wined3d_context *ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, enum ContextUsage usage)
1993{
1994 struct wined3d_context *current_context = context_get_current();
1995 DWORD tid = GetCurrentThreadId();
1996 DWORD i, dirtyState, idx;
1997 BYTE shift;
1998 const struct StateEntry *StateTable = This->StateTable;
1999 const struct wined3d_gl_info *gl_info;
2000 struct wined3d_context *context;
2001
2002 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
2003
2004 context = FindContext(This, target, tid);
2005
2006 gl_info = context->gl_info;
2007
2008 /* Activate the opengl context */
2009 if (context != current_context)
2010 {
2011 if (!context_set_current(context)) ERR("Failed to activate the new context.\n");
2012 else This->frag_pipe->enable_extension((IWineD3DDevice *)This, !context->last_was_blit);
2013
2014 if (context->vshader_const_dirty)
2015 {
2016 memset(context->vshader_const_dirty, 1,
2017 sizeof(*context->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
2018 This->highest_dirty_vs_const = GL_LIMITS(vshader_constantsF);
2019 }
2020 if (context->pshader_const_dirty)
2021 {
2022 memset(context->pshader_const_dirty, 1,
2023 sizeof(*context->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
2024 This->highest_dirty_ps_const = GL_LIMITS(pshader_constantsF);
2025 }
2026 }
2027
2028 switch (usage) {
2029 case CTXUSAGE_CLEAR:
2030 case CTXUSAGE_DRAWPRIM:
2031 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2032 ENTER_GL();
2033 context_apply_fbo_state(context);
2034 LEAVE_GL();
2035 }
2036 if (context->draw_buffer_dirty) {
2037 context_apply_draw_buffer(context, FALSE);
2038 context->draw_buffer_dirty = FALSE;
2039 }
2040 break;
2041
2042 case CTXUSAGE_BLIT:
2043 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
2044 if (context->render_offscreen)
2045 {
2046 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
2047 ENTER_GL();
2048 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
2049 context_attach_surface_fbo(context, GL_FRAMEBUFFER_EXT, 0, target);
2050 context_attach_depth_stencil_fbo(context, GL_FRAMEBUFFER_EXT, NULL, FALSE);
2051 LEAVE_GL();
2052 } else {
2053 ENTER_GL();
2054 context_bind_fbo(context, GL_FRAMEBUFFER_EXT, NULL);
2055 LEAVE_GL();
2056 }
2057 context->draw_buffer_dirty = TRUE;
2058 }
2059 if (context->draw_buffer_dirty) {
2060 context_apply_draw_buffer(context, TRUE);
2061 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
2062 context->draw_buffer_dirty = FALSE;
2063 }
2064 }
2065 break;
2066
2067 default:
2068 break;
2069 }
2070
2071 switch(usage) {
2072 case CTXUSAGE_RESOURCELOAD:
2073 /* This does not require any special states to be set up */
2074 break;
2075
2076 case CTXUSAGE_CLEAR:
2077 if(context->last_was_blit) {
2078 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
2079 }
2080
2081 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
2082 * blending when clearing improves the clearing performance incredibly.
2083 */
2084 ENTER_GL();
2085 glDisable(GL_BLEND);
2086 LEAVE_GL();
2087 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
2088
2089 ENTER_GL();
2090 glEnable(GL_SCISSOR_TEST);
2091 checkGLcall("glEnable GL_SCISSOR_TEST");
2092 LEAVE_GL();
2093 context->last_was_blit = FALSE;
2094 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
2095 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
2096 break;
2097
2098 case CTXUSAGE_DRAWPRIM:
2099 /* This needs all dirty states applied */
2100 if(context->last_was_blit) {
2101 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
2102 }
2103
2104 IWineD3DDeviceImpl_FindTexUnitMap(This);
2105
2106 ENTER_GL();
2107 for(i=0; i < context->numDirtyEntries; i++) {
2108 dirtyState = context->dirtyArray[i];
2109 idx = dirtyState >> 5;
2110 shift = dirtyState & 0x1f;
2111 context->isStateDirty[idx] &= ~(1 << shift);
2112 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
2113 }
2114 LEAVE_GL();
2115 context->numDirtyEntries = 0; /* This makes the whole list clean */
2116 context->last_was_blit = FALSE;
2117 break;
2118
2119 case CTXUSAGE_BLIT:
2120 SetupForBlit(This, context,
2121 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
2122 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
2123 break;
2124
2125 default:
2126 FIXME("Unexpected context usage requested\n");
2127 }
2128
2129 return context;
2130}
Note: See TracBrowser for help on using the repository browser.

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