2 * Context and render target management in wined3d
4 * Copyright 2007-2008 Stefan Dösinger for CodeWeavers
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.
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.
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
26 #include "wined3d_private.h"
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
30 #define GLINFO_LOCATION This->adapter->gl_info
32 /* The last used device.
34 * If the application creates multiple devices and switches between them, ActivateContext has to
35 * change the opengl context. This flag allows to keep track which device is active
37 static IWineD3DDeviceImpl *last_device;
39 /* FBO helper functions */
41 void context_bind_fbo(IWineD3DDevice *iface, GLenum target, GLuint *fbo)
43 const IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
47 GL_EXTCALL(glGenFramebuffersEXT(1, fbo));
48 checkGLcall("glGenFramebuffersEXT()");
49 TRACE("Created FBO %d\n", *fbo);
52 GL_EXTCALL(glBindFramebufferEXT(target, *fbo));
53 checkGLcall("glBindFramebuffer()");
56 static void context_destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
60 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
61 checkGLcall("glBindFramebuffer()");
62 for (i = 0; i < GL_LIMITS(buffers); ++i)
64 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
65 checkGLcall("glFramebufferTexture2D()");
67 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
68 checkGLcall("glFramebufferTexture2D()");
69 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
70 checkGLcall("glBindFramebuffer()");
71 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
72 checkGLcall("glDeleteFramebuffers()");
75 static void context_apply_attachment_filter_states(IWineD3DDevice *iface, IWineD3DSurface *surface, BOOL force_preload)
77 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
78 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
79 IWineD3DBaseTextureImpl *texture_impl;
80 BOOL update_minfilter = FALSE;
81 BOOL update_magfilter = FALSE;
83 /* Update base texture states array */
84 if (SUCCEEDED(IWineD3DSurface_GetContainer(surface, &IID_IWineD3DBaseTexture, (void **)&texture_impl)))
86 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] != WINED3DTEXF_POINT
87 || texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] != WINED3DTEXF_NONE)
89 texture_impl->baseTexture.states[WINED3DTEXSTA_MINFILTER] = WINED3DTEXF_POINT;
90 texture_impl->baseTexture.states[WINED3DTEXSTA_MIPFILTER] = WINED3DTEXF_NONE;
91 update_minfilter = TRUE;
94 if (texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] != WINED3DTEXF_POINT)
96 texture_impl->baseTexture.states[WINED3DTEXSTA_MAGFILTER] = WINED3DTEXF_POINT;
97 update_magfilter = TRUE;
100 if (texture_impl->baseTexture.bindCount)
102 WARN("Render targets should not be bound to a sampler\n");
103 IWineD3DDeviceImpl_MarkStateDirty(This, STATE_SAMPLER(texture_impl->baseTexture.sampler));
106 IWineD3DBaseTexture_Release((IWineD3DBaseTexture *)texture_impl);
109 if (update_minfilter || update_magfilter || force_preload)
111 GLenum target, bind_target;
114 target = surface_impl->glDescription.target;
115 if (target == GL_TEXTURE_2D)
117 bind_target = GL_TEXTURE_2D;
118 glGetIntegerv(GL_TEXTURE_BINDING_2D, &old_binding);
119 } else if (target == GL_TEXTURE_RECTANGLE_ARB) {
120 bind_target = GL_TEXTURE_RECTANGLE_ARB;
121 glGetIntegerv(GL_TEXTURE_BINDING_RECTANGLE_ARB, &old_binding);
123 bind_target = GL_TEXTURE_CUBE_MAP_ARB;
124 glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP_ARB, &old_binding);
127 surface_internal_preload(surface, SRGB_RGB);
129 glBindTexture(bind_target, surface_impl->glDescription.textureName);
130 if (update_minfilter) glTexParameteri(bind_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
131 if (update_magfilter) glTexParameteri(bind_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
132 glBindTexture(bind_target, old_binding);
135 checkGLcall("apply_attachment_filter_states()");
138 /* TODO: Handle stencil attachments */
139 void context_attach_depth_stencil_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, IWineD3DSurface *depth_stencil, BOOL use_render_buffer)
141 IWineD3DSurfaceImpl *depth_stencil_impl = (IWineD3DSurfaceImpl *)depth_stencil;
143 TRACE("Attach depth stencil %p\n", depth_stencil);
147 if (use_render_buffer && depth_stencil_impl->current_renderbuffer)
149 GL_EXTCALL(glFramebufferRenderbufferEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_impl->current_renderbuffer->id));
150 checkGLcall("glFramebufferRenderbufferEXT()");
152 context_apply_attachment_filter_states((IWineD3DDevice *)This, depth_stencil, TRUE);
154 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, depth_stencil_impl->glDescription.target,
155 depth_stencil_impl->glDescription.textureName, depth_stencil_impl->glDescription.level));
156 checkGLcall("glFramebufferTexture2DEXT()");
159 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
160 checkGLcall("glFramebufferTexture2DEXT()");
164 void context_attach_surface_fbo(IWineD3DDeviceImpl *This, GLenum fbo_target, DWORD idx, IWineD3DSurface *surface)
166 const IWineD3DSurfaceImpl *surface_impl = (IWineD3DSurfaceImpl *)surface;
168 TRACE("Attach surface %p to %u\n", surface, idx);
172 context_apply_attachment_filter_states((IWineD3DDevice *)This, surface, TRUE);
174 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, surface_impl->glDescription.target,
175 surface_impl->glDescription.textureName, surface_impl->glDescription.level));
176 checkGLcall("glFramebufferTexture2DEXT()");
178 GL_EXTCALL(glFramebufferTexture2DEXT(fbo_target, GL_COLOR_ATTACHMENT0_EXT + idx, GL_TEXTURE_2D, 0, 0));
179 checkGLcall("glFramebufferTexture2DEXT()");
183 static void context_check_fbo_status(IWineD3DDevice *iface)
185 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
188 status = GL_EXTCALL(glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT));
189 if (status == GL_FRAMEBUFFER_COMPLETE_EXT)
191 TRACE("FBO complete\n");
193 IWineD3DSurfaceImpl *attachment;
195 FIXME("FBO status %s (%#x)\n", debug_fbostatus(status), status);
197 /* Dump the FBO attachments */
198 for (i = 0; i < GL_LIMITS(buffers); ++i)
200 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->render_targets[i];
203 FIXME("\tColor attachment %d: (%p) %s %ux%u\n",
204 i, attachment, debug_d3dformat(attachment->resource.format_desc->format),
205 attachment->pow2Width, attachment->pow2Height);
208 attachment = (IWineD3DSurfaceImpl *)This->activeContext->current_fbo->depth_stencil;
211 FIXME("\tDepth attachment: (%p) %s %ux%u\n",
212 attachment, debug_d3dformat(attachment->resource.format_desc->format),
213 attachment->pow2Width, attachment->pow2Height);
218 static struct fbo_entry *context_create_fbo_entry(IWineD3DDevice *iface)
220 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
221 struct fbo_entry *entry;
223 entry = HeapAlloc(GetProcessHeap(), 0, sizeof(*entry));
224 entry->render_targets = HeapAlloc(GetProcessHeap(), 0, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
225 memcpy(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets));
226 entry->depth_stencil = This->stencilBufferTarget;
227 entry->attached = FALSE;
233 static void context_destroy_fbo_entry(IWineD3DDeviceImpl *This, struct fbo_entry *entry)
237 TRACE("Destroy FBO %d\n", entry->id);
238 context_destroy_fbo(This, &entry->id);
240 list_remove(&entry->entry);
241 HeapFree(GetProcessHeap(), 0, entry->render_targets);
242 HeapFree(GetProcessHeap(), 0, entry);
246 static struct fbo_entry *context_find_fbo_entry(IWineD3DDevice *iface, WineD3DContext *context)
248 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
249 struct fbo_entry *entry;
251 LIST_FOR_EACH_ENTRY(entry, &context->fbo_list, struct fbo_entry, entry)
253 if (!memcmp(entry->render_targets, This->render_targets, GL_LIMITS(buffers) * sizeof(*entry->render_targets))
254 && entry->depth_stencil == This->stencilBufferTarget)
260 entry = context_create_fbo_entry(iface);
261 list_add_head(&context->fbo_list, &entry->entry);
265 static void context_apply_fbo_entry(IWineD3DDevice *iface, struct fbo_entry *entry)
267 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
270 context_bind_fbo(iface, GL_FRAMEBUFFER_EXT, &entry->id);
272 if (!entry->attached)
274 /* Apply render targets */
275 for (i = 0; i < GL_LIMITS(buffers); ++i)
277 IWineD3DSurface *render_target = This->render_targets[i];
278 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, i, render_target);
281 /* Apply depth targets */
282 if (This->stencilBufferTarget) {
283 unsigned int w = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Width;
284 unsigned int h = ((IWineD3DSurfaceImpl *)This->render_targets[0])->pow2Height;
286 surface_set_compatible_renderbuffer(This->stencilBufferTarget, w, h);
288 context_attach_depth_stencil_fbo(This, GL_FRAMEBUFFER_EXT, This->stencilBufferTarget, TRUE);
290 entry->attached = TRUE;
292 for (i = 0; i < GL_LIMITS(buffers); ++i)
294 if (This->render_targets[i])
295 context_apply_attachment_filter_states(iface, This->render_targets[i], FALSE);
297 if (This->stencilBufferTarget)
298 context_apply_attachment_filter_states(iface, This->stencilBufferTarget, FALSE);
301 for (i = 0; i < GL_LIMITS(buffers); ++i)
303 if (This->render_targets[i])
304 This->draw_buffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
306 This->draw_buffers[i] = GL_NONE;
310 static void context_apply_fbo_state(IWineD3DDevice *iface)
312 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
313 WineD3DContext *context = This->activeContext;
315 if (This->render_offscreen)
317 context->current_fbo = context_find_fbo_entry(iface, context);
318 context_apply_fbo_entry(iface, context->current_fbo);
320 context->current_fbo = NULL;
321 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
324 context_check_fbo_status(iface);
327 void context_resource_released(IWineD3DDevice *iface, IWineD3DResource *resource, WINED3DRESOURCETYPE type)
329 IWineD3DDeviceImpl *This = (IWineD3DDeviceImpl *)iface;
334 case WINED3DRTYPE_SURFACE:
336 for (i = 0; i < This->numContexts; ++i)
338 struct fbo_entry *entry, *entry2;
340 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &This->contexts[i]->fbo_list, struct fbo_entry, entry)
342 BOOL destroyed = FALSE;
345 for (j = 0; !destroyed && j < GL_LIMITS(buffers); ++j)
347 if (entry->render_targets[j] == (IWineD3DSurface *)resource)
349 context_destroy_fbo_entry(This, entry);
354 if (!destroyed && entry->depth_stencil == (IWineD3DSurface *)resource)
355 context_destroy_fbo_entry(This, entry);
367 /*****************************************************************************
368 * Context_MarkStateDirty
370 * Marks a state in a context dirty. Only one context, opposed to
371 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
375 * context: Context to mark the state dirty in
376 * state: State to mark dirty
377 * StateTable: Pointer to the state table in use(for state grouping)
379 *****************************************************************************/
380 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
381 DWORD rep = StateTable[state].representative;
385 if(!rep || isStateDirty(context, rep)) return;
387 context->dirtyArray[context->numDirtyEntries++] = rep;
390 context->isStateDirty[idx] |= (1 << shift);
393 /*****************************************************************************
396 * Adds a context to the context array. Helper function for CreateContext
398 * This method is not called in performance-critical code paths, only when a
399 * new render target or swapchain is created. Thus performance is not an issue
403 * This: Device to add the context for
404 * hdc: device context
405 * glCtx: WGL context to add
406 * pbuffer: optional pbuffer used with this context
408 *****************************************************************************/
409 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
410 WineD3DContext **oldArray = This->contexts;
413 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
414 if(This->contexts == NULL) {
415 ERR("Unable to grow the context array\n");
416 This->contexts = oldArray;
420 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
423 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
424 if(This->contexts[This->numContexts] == NULL) {
425 ERR("Unable to allocate a new context\n");
426 HeapFree(GetProcessHeap(), 0, This->contexts);
427 This->contexts = oldArray;
431 This->contexts[This->numContexts]->hdc = hdc;
432 This->contexts[This->numContexts]->glCtx = glCtx;
433 This->contexts[This->numContexts]->pbuffer = pbuffer;
434 This->contexts[This->numContexts]->win_handle = win_handle;
435 HeapFree(GetProcessHeap(), 0, oldArray);
437 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
439 for(state = 0; state <= STATE_HIGHEST; state++) {
440 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
444 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
445 return This->contexts[This->numContexts - 1];
448 /* This function takes care of WineD3D pixel format selection. */
449 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
452 unsigned int matchtry;
453 short redBits, greenBits, blueBits, alphaBits, colorBits;
454 short depthBits=0, stencilBits=0;
461 /* First, try without alpha match buffers. MacOS supports aux buffers only
462 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
463 * Then try without aux buffers - this is the most common cause for not
464 * finding a pixel format. Also some drivers(the open source ones)
465 * only offer 32 bit ARB pixel formats. First try without an exact alpha
466 * match, then try without an exact alpha and color match.
468 { TRUE, TRUE, TRUE },
469 { TRUE, FALSE, TRUE },
470 { FALSE, TRUE, TRUE },
471 { FALSE, FALSE, TRUE },
472 { TRUE, FALSE, FALSE },
473 { FALSE, FALSE, FALSE },
477 int nCfgs = This->adapter->nCfgs;
479 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
480 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
482 if (!getColorBits(&This->adapter->gl_info, ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits))
484 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
488 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
489 * You are able to add a depth + stencil surface at a later stage when you need it.
490 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
491 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
492 * context, need torecreate shaders, textures and other resources.
494 * The context manager already takes care of the state problem and for the other tasks code from Reset
495 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
496 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
497 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
498 * issue needs to be fixed. */
499 if(DepthStencilFormat != WINED3DFMT_D24S8)
500 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
502 DepthStencilFormat = WINED3DFMT_D24S8;
504 if(DepthStencilFormat) {
505 getDepthStencilBits(&This->adapter->gl_info, DepthStencilFormat, &depthBits, &stencilBits);
508 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
509 for(i=0; i<nCfgs; i++) {
510 BOOL exactDepthMatch = TRUE;
511 WineD3D_PixelFormat *cfg = &This->adapter->cfgs[i];
513 /* For now only accept RGBA formats. Perhaps some day we will
514 * allow floating point formats for pbuffers. */
515 if(cfg->iPixelType != WGL_TYPE_RGBA_ARB)
518 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
519 if(!pbuffer && !(cfg->windowDrawable && cfg->doubleBuffer))
522 /* We like to have aux buffers in backbuffer mode */
523 if(auxBuffers && !cfg->auxBuffers && matches[matchtry].require_aux)
526 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
527 if(pbuffer && (!cfg->pbufferDrawable || cfg->doubleBuffer))
530 if(matches[matchtry].exact_color) {
531 if(cfg->redSize != redBits)
533 if(cfg->greenSize != greenBits)
535 if(cfg->blueSize != blueBits)
538 if(cfg->redSize < redBits)
540 if(cfg->greenSize < greenBits)
542 if(cfg->blueSize < blueBits)
545 if(matches[matchtry].exact_alpha) {
546 if(cfg->alphaSize != alphaBits)
549 if(cfg->alphaSize < alphaBits)
553 /* We try to locate a format which matches our requirements exactly. In case of
554 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
555 if(cfg->depthSize < depthBits)
557 else if(cfg->depthSize > depthBits)
558 exactDepthMatch = FALSE;
560 /* In all cases make sure the number of stencil bits matches our requirements
561 * even when we don't need stencil because it could affect performance EXCEPT
562 * on cards which don't offer depth formats without stencil like the i915 drivers
564 if(stencilBits != cfg->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfg->stencilSize))
567 /* Check multisampling support */
568 if(cfg->numSamples != numSamples)
571 /* When we have passed all the checks then we have found a format which matches our
572 * requirements. Note that we only check for a limit number of capabilities right now,
573 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
574 * can still differ in things like multisampling, stereo, SRGB and other flags.
577 /* Exit the loop as we have found a format :) */
578 if(exactDepthMatch) {
579 iPixelFormat = cfg->iPixelFormat;
581 } else if(!iPixelFormat) {
582 /* In the end we might end up with a format which doesn't exactly match our depth
583 * requirements. Accept the first format we found because formats with higher iPixelFormat
584 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
585 iPixelFormat = cfg->iPixelFormat;
590 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
591 if(!iPixelFormat && !findCompatible) {
592 ERR("Can't find a suitable iPixelFormat\n");
594 } else if(!iPixelFormat) {
595 PIXELFORMATDESCRIPTOR pfd;
597 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
598 /* PixelFormat selection */
599 ZeroMemory(&pfd, sizeof(pfd));
600 pfd.nSize = sizeof(pfd);
602 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
603 pfd.iPixelType = PFD_TYPE_RGBA;
604 pfd.cAlphaBits = alphaBits;
605 pfd.cColorBits = colorBits;
606 pfd.cDepthBits = depthBits;
607 pfd.cStencilBits = stencilBits;
608 pfd.iLayerType = PFD_MAIN_PLANE;
610 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
612 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
613 ERR("Can't find a suitable iPixelFormat\n");
618 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
622 /*****************************************************************************
625 * Creates a new context for a window, or a pbuffer context.
628 * This: Device to activate the context for
629 * target: Surface this context will render to
630 * win_handle: handle to the window which we are drawing to
631 * create_pbuffer: tells whether to create a pbuffer or not
632 * pPresentParameters: contains the pixelformats to use for onscreen rendering
634 *****************************************************************************/
635 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
636 HDC oldDrawable, hdc;
637 HPBUFFERARB pbuffer = NULL;
638 HGLRC ctx = NULL, oldCtx;
639 WineD3DContext *ret = NULL;
642 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
645 HDC hdc_parent = GetDC(win_handle);
646 int iPixelFormat = 0;
648 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
649 WINED3DFORMAT StencilBufferFormat = StencilSurface ?
650 ((IWineD3DSurfaceImpl *)StencilSurface)->resource.format_desc->format : 0;
652 /* Try to find a pixel format with pbuffer support. */
653 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc->format,
654 StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */,
655 FALSE /* findCompatible */);
657 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
659 /* For some reason we weren't able to find a format, try to find something instead of crashing.
660 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
661 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format_desc->format,
662 StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */,
663 TRUE /* findCompatible */);
666 /* This shouldn't happen as ChoosePixelFormat always returns something */
668 ERR("Unable to locate a pixel format for a pbuffer\n");
669 ReleaseDC(win_handle, hdc_parent);
673 TRACE("Creating a pBuffer drawable for the new context\n");
674 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
676 ERR("Cannot create a pbuffer\n");
677 ReleaseDC(win_handle, hdc_parent);
681 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
682 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
684 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
685 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
686 ReleaseDC(win_handle, hdc_parent);
689 ReleaseDC(win_handle, hdc_parent);
691 PIXELFORMATDESCRIPTOR pfd;
694 WINED3DFORMAT ColorFormat = target->resource.format_desc->format;
695 WINED3DFORMAT DepthStencilFormat = 0;
696 BOOL auxBuffers = FALSE;
699 hdc = GetDC(win_handle);
701 ERR("Cannot retrieve a device context!\n");
705 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
706 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
709 if (target->resource.format_desc->format == WINED3DFMT_X4R4G4B4)
710 ColorFormat = WINED3DFMT_A4R4G4B4;
711 else if(target->resource.format_desc->format == WINED3DFMT_X8R8G8B8)
712 ColorFormat = WINED3DFMT_A8R8G8B8;
715 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
716 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
717 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
718 * a format with 8bit alpha, so request A8R8G8B8. */
719 if(ColorFormat == WINED3DFMT_P8)
720 ColorFormat = WINED3DFMT_A8R8G8B8;
722 /* Retrieve the depth stencil format from the present parameters.
723 * The choice of the proper format can give a nice performance boost
724 * in case of GPU limited programs. */
725 if(pPresentParms->EnableAutoDepthStencil) {
726 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
727 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
730 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
731 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
732 if(!GL_SUPPORT(ARB_MULTISAMPLE))
733 ERR("The program is requesting multisampling without support!\n");
735 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
736 numSamples = pPresentParms->MultiSampleType;
740 /* Try to find a pixel format which matches our requirements */
741 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
743 /* Try to locate a compatible format if we weren't able to find anything */
745 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
746 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
749 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
751 ERR("Can't find a suitable iPixelFormat\n");
755 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
756 res = SetPixelFormat(hdc, iPixelFormat, NULL);
758 int oldPixelFormat = GetPixelFormat(hdc);
760 /* By default WGL doesn't allow pixel format adjustments but we need it here.
761 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
762 * set the pixel format multiple times. Only use it when it is really needed. */
764 if(oldPixelFormat == iPixelFormat) {
765 /* We don't have to do anything as the formats are the same :) */
766 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
767 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
770 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
773 } else if(oldPixelFormat) {
774 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
775 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
776 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
778 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
784 ctx = pwglCreateContext(hdc);
785 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
788 ERR("Failed to create a WGL context\n");
790 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
791 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
795 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
797 ERR("Failed to add the newly created context to the context list\n");
798 pwglDeleteContext(ctx);
800 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
801 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
805 ret->surface = (IWineD3DSurface *) target;
806 ret->isPBuffer = create_pbuffer;
807 ret->tid = GetCurrentThreadId();
808 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
809 /* Create the dirty constants array and initialize them to dirty */
810 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
811 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
812 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
813 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
814 memset(ret->vshader_const_dirty, 1,
815 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
816 memset(ret->pshader_const_dirty, 1,
817 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
820 TRACE("Successfully created new context %p\n", ret);
822 list_init(&ret->fbo_list);
824 /* Set up the context defaults */
825 oldCtx = pwglGetCurrentContext();
826 oldDrawable = pwglGetCurrentDC();
827 if(oldCtx && oldDrawable) {
828 /* See comment in ActivateContext context switching */
829 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
831 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
832 ERR("Cannot activate context to set up defaults\n");
838 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
840 TRACE("Setting up the screen\n");
841 /* Clear the screen */
842 glClearColor(1.0, 0.0, 0.0, 0.0);
843 checkGLcall("glClearColor");
846 glClearStencil(0xffff);
848 checkGLcall("glClear");
850 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
851 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
853 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
854 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
856 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
857 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
859 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
860 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
861 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
862 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
864 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
865 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
866 * and textures in DIB sections(due to the memory protection).
868 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
869 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
871 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
872 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
873 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
874 * GL_VERTEX_BLEND_ARB isn't enabled too
876 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
877 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
879 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
880 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
881 * the previous texture where to source the offset from is always unit - 1.
883 for(s = 1; s < GL_LIMITS(textures); s++) {
884 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
885 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
886 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
890 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
891 for(s = 0; s < GL_LIMITS(textures); s++) {
892 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
893 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
894 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
899 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
900 * but enable it for the first context we create, and reenable it on the old context
902 if(oldDrawable && oldCtx) {
903 pwglMakeCurrent(oldDrawable, oldCtx);
907 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
915 /*****************************************************************************
916 * RemoveContextFromArray
918 * Removes a context from the context manager. The opengl context is not
919 * destroyed or unset. context is not a valid pointer after that call.
921 * Similar to the former call this isn't a performance critical function. A
922 * helper function for DestroyContext.
925 * This: Device to activate the context for
926 * context: Context to remove
928 *****************************************************************************/
929 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
930 WineD3DContext **new_array;
934 TRACE("Removing ctx %p\n", context);
936 for (i = 0; i < This->numContexts; ++i)
938 if (This->contexts[i] == context)
940 HeapFree(GetProcessHeap(), 0, context);
948 ERR("Context %p doesn't exist in context array\n", context);
952 while (i < This->numContexts - 1)
954 This->contexts[i] = This->contexts[i + 1];
959 if (!This->numContexts)
961 HeapFree(GetProcessHeap(), 0, This->contexts);
962 This->contexts = NULL;
966 new_array = HeapReAlloc(GetProcessHeap(), 0, This->contexts, This->numContexts * sizeof(*This->contexts));
969 ERR("Failed to shrink context array. Oh well.\n");
973 This->contexts = new_array;
976 /*****************************************************************************
979 * Destroys a wineD3DContext
982 * This: Device to activate the context for
983 * context: Context to destroy
985 *****************************************************************************/
986 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
987 struct fbo_entry *entry, *entry2;
989 TRACE("Destroying ctx %p\n", context);
991 /* The correct GL context needs to be active to cleanup the GL resources below */
992 if(pwglGetCurrentContext() != context->glCtx){
993 pwglMakeCurrent(context->hdc, context->glCtx);
999 LIST_FOR_EACH_ENTRY_SAFE(entry, entry2, &context->fbo_list, struct fbo_entry, entry) {
1000 context_destroy_fbo_entry(This, entry);
1002 if (context->src_fbo) {
1003 TRACE("Destroy src FBO %d\n", context->src_fbo);
1004 context_destroy_fbo(This, &context->src_fbo);
1006 if (context->dst_fbo) {
1007 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
1008 context_destroy_fbo(This, &context->dst_fbo);
1013 /* Cleanup the GL context */
1014 pwglMakeCurrent(NULL, NULL);
1015 if(context->isPBuffer) {
1016 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
1017 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
1018 } else ReleaseDC(context->win_handle, context->hdc);
1019 pwglDeleteContext(context->glCtx);
1021 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
1022 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
1023 RemoveContextFromArray(This, context);
1026 static inline void set_blit_dimension(UINT width, UINT height) {
1027 glMatrixMode(GL_PROJECTION);
1028 checkGLcall("glMatrixMode(GL_PROJECTION)");
1030 checkGLcall("glLoadIdentity()");
1031 glOrtho(0, width, height, 0, 0.0, -1.0);
1032 checkGLcall("glOrtho");
1033 glViewport(0, 0, width, height);
1034 checkGLcall("glViewport");
1037 /*****************************************************************************
1040 * Sets up a context for DirectDraw blitting.
1041 * All texture units are disabled, texture unit 0 is set as current unit
1042 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
1043 * color writing enabled for all channels
1044 * register combiners disabled, shaders disabled
1045 * world matrix is set to identity, texture matrix 0 too
1046 * projection matrix is setup for drawing screen coordinates
1049 * This: Device to activate the context for
1050 * context: Context to setup
1051 * width: render target width
1052 * height: render target height
1054 *****************************************************************************/
1055 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
1057 const struct StateEntry *StateTable = This->StateTable;
1059 TRACE("Setting up context %p for blitting\n", context);
1060 if(context->last_was_blit) {
1061 if(context->blit_w != width || context->blit_h != height) {
1062 set_blit_dimension(width, height);
1063 context->blit_w = width; context->blit_h = height;
1064 /* No need to dirtify here, the states are still dirtified because they weren't
1065 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
1069 TRACE("Context is already set up for blitting, nothing to do\n");
1072 context->last_was_blit = TRUE;
1074 /* TODO: Use a display list */
1076 /* Disable shaders */
1077 This->shader_backend->shader_select((IWineD3DDevice *)This, FALSE, FALSE);
1078 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
1079 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
1081 /* Call ENTER_GL() once for all gl calls below. In theory we should not call
1082 * helper functions in between gl calls. This function is full of Context_MarkStateDirty
1083 * which can safely be called from here, we only lock once instead locking/unlocking
1084 * after each GL call.
1088 /* Disable all textures. The caller can then bind a texture it wants to blit
1091 * The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
1092 * function texture unit. No need to care for higher samplers
1094 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
1095 sampler = This->rev_tex_unit_map[i];
1096 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
1097 checkGLcall("glActiveTextureARB");
1099 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1100 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1101 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1103 glDisable(GL_TEXTURE_3D);
1104 checkGLcall("glDisable GL_TEXTURE_3D");
1105 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1106 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1107 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1109 glDisable(GL_TEXTURE_2D);
1110 checkGLcall("glDisable GL_TEXTURE_2D");
1112 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1113 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
1115 if (sampler != -1) {
1116 if (sampler < MAX_TEXTURES) {
1117 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1119 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1122 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
1123 checkGLcall("glActiveTextureARB");
1125 sampler = This->rev_tex_unit_map[0];
1127 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
1128 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1129 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
1131 glDisable(GL_TEXTURE_3D);
1132 checkGLcall("glDisable GL_TEXTURE_3D");
1133 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
1134 glDisable(GL_TEXTURE_RECTANGLE_ARB);
1135 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
1137 glDisable(GL_TEXTURE_2D);
1138 checkGLcall("glDisable GL_TEXTURE_2D");
1140 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1142 glMatrixMode(GL_TEXTURE);
1143 checkGLcall("glMatrixMode(GL_TEXTURE)");
1145 checkGLcall("glLoadIdentity()");
1147 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
1148 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
1149 GL_TEXTURE_LOD_BIAS_EXT,
1151 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
1154 if (sampler != -1) {
1155 if (sampler < MAX_TEXTURES) {
1156 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
1157 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
1159 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
1162 /* Other misc states */
1163 glDisable(GL_ALPHA_TEST);
1164 checkGLcall("glDisable(GL_ALPHA_TEST)");
1165 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
1166 glDisable(GL_LIGHTING);
1167 checkGLcall("glDisable GL_LIGHTING");
1168 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
1169 glDisable(GL_DEPTH_TEST);
1170 checkGLcall("glDisable GL_DEPTH_TEST");
1171 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
1172 glDisableWINE(GL_FOG);
1173 checkGLcall("glDisable GL_FOG");
1174 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
1175 glDisable(GL_BLEND);
1176 checkGLcall("glDisable GL_BLEND");
1177 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1178 glDisable(GL_CULL_FACE);
1179 checkGLcall("glDisable GL_CULL_FACE");
1180 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
1181 glDisable(GL_STENCIL_TEST);
1182 checkGLcall("glDisable GL_STENCIL_TEST");
1183 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
1184 glDisable(GL_SCISSOR_TEST);
1185 checkGLcall("glDisable GL_SCISSOR_TEST");
1186 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1187 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
1188 glDisable(GL_POINT_SPRITE_ARB);
1189 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
1190 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
1192 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
1193 checkGLcall("glColorMask");
1194 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1195 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
1196 glDisable(GL_COLOR_SUM_EXT);
1197 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
1198 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
1201 /* Setup transforms */
1202 glMatrixMode(GL_MODELVIEW);
1203 checkGLcall("glMatrixMode(GL_MODELVIEW)");
1205 checkGLcall("glLoadIdentity()");
1206 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
1208 context->last_was_rhw = TRUE;
1209 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
1211 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
1212 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
1213 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
1214 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
1215 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
1216 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
1217 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
1220 set_blit_dimension(width, height);
1221 context->blit_w = width; context->blit_h = height;
1222 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1223 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
1226 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1229 /*****************************************************************************
1230 * findThreadContextForSwapChain
1232 * Searches a swapchain for all contexts and picks one for the thread tid.
1233 * If none can be found the swapchain is requested to create a new context
1235 *****************************************************************************/
1236 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
1239 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
1240 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
1241 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
1246 /* Create a new context for the thread */
1247 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
1250 /*****************************************************************************
1253 * Finds a context for the current render target and thread
1256 * target: Render target to find the context for
1257 * tid: Thread to activate the context for
1259 * Returns: The needed context
1261 *****************************************************************************/
1262 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
1263 IWineD3DSwapChain *swapchain = NULL;
1264 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
1265 WineD3DContext *context = This->activeContext;
1266 BOOL oldRenderOffscreen = This->render_offscreen;
1267 const struct GlPixelFormatDesc *old = ((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->resource.format_desc;
1268 const struct GlPixelFormatDesc *new = ((IWineD3DSurfaceImpl *)target)->resource.format_desc;
1269 const struct StateEntry *StateTable = This->StateTable;
1271 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
1272 * the alpha blend state changes with different render target formats
1274 if (old->format != new->format)
1276 /* Disable blending when the alpha mask has changed and when a format doesn't support blending */
1277 if ((old->alpha_mask && !new->alpha_mask) || (!old->alpha_mask && new->alpha_mask)
1278 || !(new->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING))
1280 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1284 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain))) {
1285 TRACE("Rendering onscreen\n");
1287 context = findThreadContextForSwapChain(swapchain, tid);
1289 This->render_offscreen = FALSE;
1290 /* The context != This->activeContext will catch a NOP context change. This can occur
1291 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
1292 * rendering. No context change is needed in that case
1295 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
1296 if(This->pbufferContext && tid == This->pbufferContext->tid) {
1297 This->pbufferContext->tid = 0;
1300 IWineD3DSwapChain_Release(swapchain);
1302 if(oldRenderOffscreen) {
1303 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1304 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1305 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1306 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1307 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1311 TRACE("Rendering offscreen\n");
1312 This->render_offscreen = TRUE;
1314 switch(wined3d_settings.offscreen_rendering_mode) {
1316 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
1317 if(This->activeContext && tid == This->lastThread) {
1318 context = This->activeContext;
1320 /* This may happen if the app jumps straight into offscreen rendering
1321 * Start using the context of the primary swapchain. tid == 0 is no problem
1322 * for findThreadContextForSwapChain.
1324 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1325 * is perfect to call.
1327 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1333 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1334 if(This->pbufferContext == NULL ||
1335 This->pbufferWidth < targetimpl->currentDesc.Width ||
1336 This->pbufferHeight < targetimpl->currentDesc.Height) {
1337 if(This->pbufferContext) {
1338 DestroyContext(This, This->pbufferContext);
1341 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1342 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1344 This->pbufferContext = CreateContext(This, targetimpl,
1345 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1346 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1347 This->pbufferWidth = targetimpl->currentDesc.Width;
1348 This->pbufferHeight = targetimpl->currentDesc.Height;
1351 if(This->pbufferContext) {
1352 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1353 FIXME("The PBuffr context is only supported for one thread for now!\n");
1355 This->pbufferContext->tid = tid;
1356 context = This->pbufferContext;
1359 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1360 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1364 case ORM_BACKBUFFER:
1365 /* Stay with the currently active context for back buffer rendering */
1366 if(This->activeContext && tid == This->lastThread) {
1367 context = This->activeContext;
1369 /* This may happen if the app jumps straight into offscreen rendering
1370 * Start using the context of the primary swapchain. tid == 0 is no problem
1371 * for findThreadContextForSwapChain.
1373 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1374 * is perfect to call.
1376 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1381 if(!oldRenderOffscreen) {
1382 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1383 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1384 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1385 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1386 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1390 /* When switching away from an offscreen render target, and we're not using FBOs,
1391 * we have to read the drawable into the texture. This is done via PreLoad(and
1392 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1393 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1394 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1395 * is read. This leads to these possible situations:
1397 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1398 * Nothing to do, we don't even reach this code in this case...
1400 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1401 * The currently active context is OK for readback. Call PreLoad, and it
1404 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1405 * Nothing to do - the drawable is unchanged
1407 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1408 * This is tricky. We have to get a context with the old drawable from somewhere
1409 * before we can switch to the new context. In this case, PreLoad calls
1410 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1411 * is case (2) then. The old drawable is activated for the new thread, and the
1412 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1413 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1414 * target for the new thread
1416 if (readTexture && This->lastActiveRenderTarget != target) {
1417 BOOL oldInDraw = This->isInDraw;
1419 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1420 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1421 * when using offscreen rendering with multithreading
1423 This->isInDraw = TRUE;
1425 /* Do that before switching the context:
1426 * Read the back buffer of the old drawable into the destination texture
1428 if(((IWineD3DSurfaceImpl *)This->lastActiveRenderTarget)->glDescription.srgbTextureName) {
1429 surface_internal_preload(This->lastActiveRenderTarget, SRGB_BOTH);
1431 surface_internal_preload(This->lastActiveRenderTarget, SRGB_RGB);
1434 /* Assume that the drawable will be modified by some other things now */
1435 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1437 This->isInDraw = oldInDraw;
1443 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1445 IWineD3DSwapChain *swapchain;
1447 if (SUCCEEDED(IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain)))
1449 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1451 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1452 checkGLcall("glDrawBuffers()");
1458 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1462 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1464 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1465 checkGLcall("glDrawBuffers()");
1469 glDrawBuffer(This->draw_buffers[0]);
1470 checkGLcall("glDrawBuffer()");
1473 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1474 checkGLcall("glDrawBuffer()");
1479 glDrawBuffer(This->offscreenBuffer);
1480 checkGLcall("glDrawBuffer()");
1486 /*****************************************************************************
1489 * Finds a rendering context and drawable matching the device and render
1490 * target for the current thread, activates them and puts them into the
1494 * This: Device to activate the context for
1495 * target: Requested render target
1496 * usage: Prepares the context for blitting, drawing or other actions
1498 *****************************************************************************/
1499 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1500 DWORD tid = GetCurrentThreadId();
1501 DWORD i, dirtyState, idx;
1503 WineD3DContext *context;
1504 const struct StateEntry *StateTable = This->StateTable;
1506 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1507 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1508 context = FindContext(This, target, tid);
1509 context->draw_buffer_dirty = TRUE;
1510 This->lastActiveRenderTarget = target;
1511 This->lastThread = tid;
1513 /* Stick to the old context */
1514 context = This->activeContext;
1517 /* Activate the opengl context */
1518 if(last_device != This || context != This->activeContext) {
1521 /* Prevent an unneeded context switch as those are expensive */
1522 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1523 TRACE("Already using gl context %p\n", context->glCtx);
1526 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1528 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1530 ERR("Failed to activate the new context\n");
1531 } else if(!context->last_was_blit) {
1532 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1534 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1537 if(This->activeContext->vshader_const_dirty) {
1538 memset(This->activeContext->vshader_const_dirty, 1,
1539 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1541 if(This->activeContext->pshader_const_dirty) {
1542 memset(This->activeContext->pshader_const_dirty, 1,
1543 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1545 This->activeContext = context;
1550 case CTXUSAGE_CLEAR:
1551 case CTXUSAGE_DRAWPRIM:
1552 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1553 context_apply_fbo_state((IWineD3DDevice *)This);
1555 if (context->draw_buffer_dirty) {
1556 apply_draw_buffer(This, target, FALSE);
1557 context->draw_buffer_dirty = FALSE;
1562 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1563 if (This->render_offscreen) {
1564 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1565 context_bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1566 context_attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1569 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1570 checkGLcall("glFramebufferRenderbufferEXT");
1574 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1575 checkGLcall("glFramebufferRenderbufferEXT");
1578 context->draw_buffer_dirty = TRUE;
1580 if (context->draw_buffer_dirty) {
1581 apply_draw_buffer(This, target, TRUE);
1582 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1583 context->draw_buffer_dirty = FALSE;
1593 case CTXUSAGE_RESOURCELOAD:
1594 /* This does not require any special states to be set up */
1597 case CTXUSAGE_CLEAR:
1598 if(context->last_was_blit) {
1599 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1602 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1603 * blending when clearing improves the clearing performance incredibly.
1606 glDisable(GL_BLEND);
1608 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1611 glEnable(GL_SCISSOR_TEST);
1612 checkGLcall("glEnable GL_SCISSOR_TEST");
1614 context->last_was_blit = FALSE;
1615 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1616 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1619 case CTXUSAGE_DRAWPRIM:
1620 /* This needs all dirty states applied */
1621 if(context->last_was_blit) {
1622 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1625 IWineD3DDeviceImpl_FindTexUnitMap(This);
1627 for(i=0; i < context->numDirtyEntries; i++) {
1628 dirtyState = context->dirtyArray[i];
1629 idx = dirtyState >> 5;
1630 shift = dirtyState & 0x1f;
1631 context->isStateDirty[idx] &= ~(1 << shift);
1632 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1634 context->numDirtyEntries = 0; /* This makes the whole list clean */
1635 context->last_was_blit = FALSE;
1639 SetupForBlit(This, context,
1640 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1641 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1645 FIXME("Unexpected context usage requested\n");
1649 WineD3DContext *getActiveContext(void) {
1650 return last_device->activeContext;