VirtualBox

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

Last change on this file since 22319 was 22319, checked in by vboxsync, 15 years ago

crOpenGL: partial fix for crashing java apps with d3d support in guest

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

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