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 /*****************************************************************************
33 * Context_MarkStateDirty
35 * Marks a state in a context dirty. Only one context, opposed to
36 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
40 * context: Context to mark the state dirty in
41 * state: State to mark dirty
42 * StateTable: Pointer to the state table in use(for state grouping)
44 *****************************************************************************/
45 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
46 DWORD rep = StateTable[state].representative;
50 if(!rep || isStateDirty(context, rep)) return;
52 context->dirtyArray[context->numDirtyEntries++] = rep;
55 context->isStateDirty[idx] |= (1 << shift);
58 /*****************************************************************************
61 * Adds a context to the context array. Helper function for CreateContext
63 * This method is not called in performance-critical code paths, only when a
64 * new render target or swapchain is created. Thus performance is not an issue
68 * This: Device to add the context for
70 * glCtx: WGL context to add
71 * pbuffer: optional pbuffer used with this context
73 *****************************************************************************/
74 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
75 WineD3DContext **oldArray = This->contexts;
78 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
79 if(This->contexts == NULL) {
80 ERR("Unable to grow the context array\n");
81 This->contexts = oldArray;
85 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
88 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
89 if(This->contexts[This->numContexts] == NULL) {
90 ERR("Unable to allocate a new context\n");
91 HeapFree(GetProcessHeap(), 0, This->contexts);
92 This->contexts = oldArray;
96 This->contexts[This->numContexts]->hdc = hdc;
97 This->contexts[This->numContexts]->glCtx = glCtx;
98 This->contexts[This->numContexts]->pbuffer = pbuffer;
99 This->contexts[This->numContexts]->win_handle = win_handle;
100 HeapFree(GetProcessHeap(), 0, oldArray);
102 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
104 for(state = 0; state <= STATE_HIGHEST; state++) {
105 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->shader_backend->StateTable);
109 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
110 return This->contexts[This->numContexts - 1];
113 /* This function takes care of WineD3D pixel format selection. */
114 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
117 short redBits, greenBits, blueBits, alphaBits, colorBits;
118 short depthBits=0, stencilBits=0;
121 int nCfgs = This->adapter->nCfgs;
122 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
124 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
125 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
129 if(DepthStencilFormat) {
130 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
133 /* Find a pixel format which EXACTLY matches our requirements (except for depth) */
134 for(i=0; i<nCfgs; i++) {
135 BOOL exactDepthMatch = TRUE;
136 cfgs = &This->adapter->cfgs[i];
138 /* For now only accept RGBA formats. Perhaps some day we will
139 * allow floating point formats for pbuffers. */
140 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
143 /* In all cases except when we are in pbuffer-mode we need a window drawable format with double buffering. */
144 if(!pbuffer && !cfgs->windowDrawable && !cfgs->doubleBuffer)
147 /* We like to have aux buffers in backbuffer mode */
148 if(auxBuffers && !cfgs->auxBuffers)
151 /* In pbuffer-mode we need a pbuffer-capable format */
152 if(pbuffer && !cfgs->pbufferDrawable)
155 if(cfgs->redSize != redBits)
157 if(cfgs->greenSize != greenBits)
159 if(cfgs->blueSize != blueBits)
161 if(cfgs->alphaSize != alphaBits)
164 /* We try to locate a format which matches our requirements exactly. In case of
165 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
166 if(cfgs->depthSize < depthBits)
168 else if(cfgs->depthSize > depthBits)
169 exactDepthMatch = FALSE;
171 /* In all cases make sure the number of stencil bits matches our requirements
172 * even when we don't need stencil because it could affect performance */
173 if(!(cfgs->stencilSize == stencilBits))
176 /* Check multisampling support */
177 if(cfgs->numSamples != numSamples)
180 /* When we have passed all the checks then we have found a format which matches our
181 * requirements. Note that we only check for a limit number of capabilities right now,
182 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
183 * can still differ in things like multisampling, stereo, SRGB and other flags.
186 /* Exit the loop as we have found a format :) */
187 if(exactDepthMatch) {
188 iPixelFormat = cfgs->iPixelFormat;
190 } else if(!iPixelFormat) {
191 /* In the end we might end up with a format which doesn't exactly match our depth
192 * requirements. Accept the first format we found because formats with higher iPixelFormat
193 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
194 iPixelFormat = cfgs->iPixelFormat;
198 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
199 if(!iPixelFormat && !findCompatible) {
200 ERR("Can't find a suitable iPixelFormat\n");
202 } else if(!iPixelFormat) {
203 PIXELFORMATDESCRIPTOR pfd;
205 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
206 /* PixelFormat selection */
207 ZeroMemory(&pfd, sizeof(pfd));
208 pfd.nSize = sizeof(pfd);
210 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
211 pfd.iPixelType = PFD_TYPE_RGBA;
212 pfd.cAlphaBits = alphaBits;
213 pfd.cColorBits = colorBits;
214 pfd.cDepthBits = depthBits;
215 pfd.cStencilBits = stencilBits;
216 pfd.iLayerType = PFD_MAIN_PLANE;
218 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
220 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
221 ERR("Can't find a suitable iPixelFormat\n");
226 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
230 /*****************************************************************************
233 * Creates a new context for a window, or a pbuffer context.
236 * This: Device to activate the context for
237 * target: Surface this context will render to
238 * win_handle: handle to the window which we are drawing to
239 * create_pbuffer: tells whether to create a pbuffer or not
240 * pPresentParameters: contains the pixelformats to use for onscreen rendering
242 *****************************************************************************/
243 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
244 HDC oldDrawable, hdc;
245 HPBUFFERARB pbuffer = NULL;
246 HGLRC ctx = NULL, oldCtx;
247 WineD3DContext *ret = NULL;
250 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
253 HDC hdc_parent = GetDC(win_handle);
254 int iPixelFormat = 0;
256 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
257 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
259 /* Try to find a pixel format with pbuffer support. */
260 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
262 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
264 /* For some reason we weren't able to find a format, try to find something instead of crashing.
265 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
266 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
269 /* This shouldn't happen as ChoosePixelFormat always returns something */
271 ERR("Unable to locate a pixel format for a pbuffer\n");
272 ReleaseDC(win_handle, hdc_parent);
276 TRACE("Creating a pBuffer drawable for the new context\n");
277 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
279 ERR("Cannot create a pbuffer\n");
280 ReleaseDC(win_handle, hdc_parent);
284 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
285 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
287 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
288 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
289 ReleaseDC(win_handle, hdc_parent);
292 ReleaseDC(win_handle, hdc_parent);
294 PIXELFORMATDESCRIPTOR pfd;
297 WINED3DFORMAT ColorFormat = target->resource.format;
298 WINED3DFORMAT DepthStencilFormat = 0;
299 BOOL auxBuffers = FALSE;
302 hdc = GetDC(win_handle);
304 ERR("Cannot retrieve a device context!\n");
308 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
309 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
312 if(target->resource.format == WINED3DFMT_X4R4G4B4)
313 ColorFormat = WINED3DFMT_A4R4G4B4;
314 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
315 ColorFormat = WINED3DFMT_A8R8G8B8;
318 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
319 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
320 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
321 * a format with 8bit alpha, so request A8R8G8B8. */
322 if(ColorFormat == WINED3DFMT_P8)
323 ColorFormat = WINED3DFMT_A8R8G8B8;
325 /* Retrieve the depth stencil format from the present parameters.
326 * The choice of the proper format can give a nice performance boost
327 * in case of GPU limited programs. */
328 if(pPresentParms->EnableAutoDepthStencil) {
329 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
330 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
333 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
334 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
335 if(!GL_SUPPORT(ARB_MULTISAMPLE))
336 ERR("The program is requesting multisampling without support!\n");
338 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
339 numSamples = pPresentParms->MultiSampleType;
343 /* Try to find a pixel format which matches our requirements */
344 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
346 /* Try to locate a compatible format if we weren't able to find anything */
348 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
349 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
352 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
354 ERR("Can't find a suitable iPixelFormat\n");
358 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
359 res = SetPixelFormat(hdc, iPixelFormat, NULL);
361 int oldPixelFormat = GetPixelFormat(hdc);
363 /* By default WGL doesn't allow pixel format adjustments but we need it here.
364 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
365 * set the pixel format multiple times. Only use it when it is really needed. */
367 if(oldPixelFormat == iPixelFormat) {
368 /* We don't have to do anything as the formats are the same :) */
369 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
370 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
373 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
376 } else if(oldPixelFormat) {
377 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
378 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
379 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
381 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
387 ctx = pwglCreateContext(hdc);
388 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
391 ERR("Failed to create a WGL context\n");
393 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
394 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
398 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
400 ERR("Failed to add the newly created context to the context list\n");
401 pwglDeleteContext(ctx);
403 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
404 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
408 ret->surface = (IWineD3DSurface *) target;
409 ret->isPBuffer = create_pbuffer;
410 ret->tid = GetCurrentThreadId();
411 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
412 /* Create the dirty constants array and initialize them to dirty */
413 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
414 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
415 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
416 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
417 memset(ret->vshader_const_dirty, 1,
418 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
419 memset(ret->pshader_const_dirty, 1,
420 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
423 TRACE("Successfully created new context %p\n", ret);
425 /* Set up the context defaults */
426 oldCtx = pwglGetCurrentContext();
427 oldDrawable = pwglGetCurrentDC();
428 if(oldCtx && oldDrawable) {
429 /* See comment in ActivateContext context switching */
430 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, FALSE);
432 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
433 ERR("Cannot activate context to set up defaults\n");
439 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
441 TRACE("Setting up the screen\n");
442 /* Clear the screen */
443 glClearColor(1.0, 0.0, 0.0, 0.0);
444 checkGLcall("glClearColor");
447 glClearStencil(0xffff);
449 checkGLcall("glClear");
451 glColor3f(1.0, 1.0, 1.0);
452 checkGLcall("glColor3f");
454 glEnable(GL_LIGHTING);
455 checkGLcall("glEnable");
457 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
458 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
460 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
461 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
463 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
464 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
466 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
467 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
468 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
469 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
471 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
472 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
473 * and textures in DIB sections(due to the memory protection).
475 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
476 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
478 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
479 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
480 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
481 * GL_VERTEX_BLEND_ARB isn't enabled too
483 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
484 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
486 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
487 glEnable(GL_TEXTURE_SHADER_NV);
488 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
490 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
491 * the previous texture where to source the offset from is always unit - 1.
493 for(s = 1; s < GL_LIMITS(textures); s++) {
494 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
495 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
496 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
500 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
501 for(s = 0; s < GL_LIMITS(textures); s++) {
502 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
503 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
504 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
509 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
510 * but enable it for the first context we create, and reenable it on the old context
512 if(oldDrawable && oldCtx) {
513 pwglMakeCurrent(oldDrawable, oldCtx);
515 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, TRUE);
521 /*****************************************************************************
522 * RemoveContextFromArray
524 * Removes a context from the context manager. The opengl context is not
525 * destroyed or unset. context is not a valid pointer after that call.
527 * Similar to the former call this isn't a performance critical function. A
528 * helper function for DestroyContext.
531 * This: Device to activate the context for
532 * context: Context to remove
534 *****************************************************************************/
535 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
537 WineD3DContext **oldArray = This->contexts;
539 TRACE("Removing ctx %p\n", context);
543 if(This->numContexts) {
544 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
545 if(!This->contexts) {
546 ERR("Cannot allocate a new context array, PANIC!!!\n");
549 for(s = 0; s < This->numContexts; s++) {
550 if(oldArray[s] == context) continue;
551 This->contexts[t] = oldArray[s];
555 This->contexts = NULL;
558 HeapFree(GetProcessHeap(), 0, context);
559 HeapFree(GetProcessHeap(), 0, oldArray);
562 /*****************************************************************************
565 * Destroys a wineD3DContext
568 * This: Device to activate the context for
569 * context: Context to destroy
571 *****************************************************************************/
572 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
574 /* check that we are the current context first */
575 TRACE("Destroying ctx %p\n", context);
576 if(pwglGetCurrentContext() == context->glCtx){
577 pwglMakeCurrent(NULL, NULL);
580 if(context->isPBuffer) {
581 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
582 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
583 } else ReleaseDC(context->win_handle, context->hdc);
584 pwglDeleteContext(context->glCtx);
586 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
587 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
588 RemoveContextFromArray(This, context);
591 /*****************************************************************************
594 * Sets up a context for DirectDraw blitting.
595 * All texture units are disabled, texture unit 0 is set as current unit
596 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
597 * color writing enabled for all channels
598 * register combiners disabled, shaders disabled
599 * world matrix is set to identity, texture matrix 0 too
600 * projection matrix is setup for drawing screen coordinates
603 * This: Device to activate the context for
604 * context: Context to setup
605 * width: render target width
606 * height: render target height
608 *****************************************************************************/
609 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
611 const struct StateEntry *StateTable = This->shader_backend->StateTable;
613 TRACE("Setting up context %p for blitting\n", context);
614 if(context->last_was_blit) {
615 TRACE("Context is already set up for blitting, nothing to do\n");
618 context->last_was_blit = TRUE;
620 /* TODO: Use a display list */
622 /* Disable shaders */
623 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
624 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
625 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
627 /* Disable all textures. The caller can then bind a texture it wants to blit
630 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
631 glDisable(GL_REGISTER_COMBINERS_NV);
632 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
634 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
635 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
636 * function texture unit. No need to care for higher samplers
638 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
639 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
640 checkGLcall("glActiveTextureARB");
642 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
643 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
644 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
646 glDisable(GL_TEXTURE_3D);
647 checkGLcall("glDisable GL_TEXTURE_3D");
648 glDisable(GL_TEXTURE_2D);
649 checkGLcall("glDisable GL_TEXTURE_2D");
651 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
652 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
654 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP), StateTable);
655 Context_MarkStateDirty(context, STATE_SAMPLER(i), StateTable);
657 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
658 checkGLcall("glActiveTextureARB");
660 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
661 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
662 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
664 glDisable(GL_TEXTURE_3D);
665 checkGLcall("glDisable GL_TEXTURE_3D");
666 glDisable(GL_TEXTURE_2D);
667 checkGLcall("glDisable GL_TEXTURE_2D");
669 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
671 glMatrixMode(GL_TEXTURE);
672 checkGLcall("glMatrixMode(GL_TEXTURE)");
674 checkGLcall("glLoadIdentity()");
675 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0), StateTable);
677 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
678 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
679 GL_TEXTURE_LOD_BIAS_EXT,
681 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
683 Context_MarkStateDirty(context, STATE_SAMPLER(0), StateTable);
684 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP), StateTable);
686 /* Other misc states */
687 glDisable(GL_ALPHA_TEST);
688 checkGLcall("glDisable(GL_ALPHA_TEST)");
689 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
690 glDisable(GL_LIGHTING);
691 checkGLcall("glDisable GL_LIGHTING");
692 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
693 glDisable(GL_DEPTH_TEST);
694 checkGLcall("glDisable GL_DEPTH_TEST");
695 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
697 checkGLcall("glDisable GL_FOG");
698 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
700 checkGLcall("glDisable GL_BLEND");
701 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
702 glDisable(GL_CULL_FACE);
703 checkGLcall("glDisable GL_CULL_FACE");
704 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
705 glDisable(GL_STENCIL_TEST);
706 checkGLcall("glDisable GL_STENCIL_TEST");
707 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
708 glDisable(GL_SCISSOR_TEST);
709 checkGLcall("glDisable GL_SCISSOR_TEST");
710 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
711 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
712 glDisable(GL_POINT_SPRITE_ARB);
713 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
714 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
716 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
717 checkGLcall("glColorMask");
718 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
719 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
720 glDisable(GL_COLOR_SUM_EXT);
721 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
722 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
724 if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
725 GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
726 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
727 checkGLcall("glFinalCombinerInputNV");
730 /* Setup transforms */
731 glMatrixMode(GL_MODELVIEW);
732 checkGLcall("glMatrixMode(GL_MODELVIEW)");
734 checkGLcall("glLoadIdentity()");
735 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
737 glMatrixMode(GL_PROJECTION);
738 checkGLcall("glMatrixMode(GL_PROJECTION)");
740 checkGLcall("glLoadIdentity()");
741 glOrtho(0, width, height, 0, 0.0, -1.0);
742 checkGLcall("glOrtho");
743 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
745 context->last_was_rhw = TRUE;
746 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
748 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
749 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
750 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
751 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
752 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
753 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
754 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
756 glViewport(0, 0, width, height);
757 checkGLcall("glViewport");
758 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
760 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, FALSE);
763 /*****************************************************************************
764 * findThreadContextForSwapChain
766 * Searches a swapchain for all contexts and picks one for the thread tid.
767 * If none can be found the swapchain is requested to create a new context
769 *****************************************************************************/
770 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
773 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
774 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
775 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
780 /* Create a new context for the thread */
781 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
784 /*****************************************************************************
787 * Finds a context for the current render target and thread
790 * target: Render target to find the context for
791 * tid: Thread to activate the context for
793 * Returns: The needed context
795 *****************************************************************************/
796 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
797 IWineD3DSwapChain *swapchain = NULL;
799 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
800 WineD3DContext *context = This->activeContext;
801 BOOL oldRenderOffscreen = This->render_offscreen;
802 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
803 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
804 const struct StateEntry *StateTable = This->shader_backend->StateTable;
806 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
807 * the alpha blend state changes with different render target formats
809 if(oldFmt != newFmt) {
810 const GlPixelFormatDesc *glDesc;
811 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
812 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
814 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
815 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
816 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
820 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
821 if(hr == WINED3D_OK && swapchain) {
822 TRACE("Rendering onscreen\n");
824 context = findThreadContextForSwapChain(swapchain, tid);
826 This->render_offscreen = FALSE;
827 /* The context != This->activeContext will catch a NOP context change. This can occur
828 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
829 * rendering. No context change is needed in that case
832 if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
837 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
838 if(This->pbufferContext && tid == This->pbufferContext->tid) {
839 This->pbufferContext->tid = 0;
842 IWineD3DSwapChain_Release(swapchain);
844 if(oldRenderOffscreen) {
845 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
846 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
847 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
848 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
849 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
853 TRACE("Rendering offscreen\n");
854 This->render_offscreen = TRUE;
855 *buffer = This->offscreenBuffer;
857 switch(wined3d_settings.offscreen_rendering_mode) {
859 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
860 if(This->activeContext && tid == This->lastThread) {
861 context = This->activeContext;
863 /* This may happen if the app jumps straight into offscreen rendering
864 * Start using the context of the primary swapchain. tid == 0 is no problem
865 * for findThreadContextForSwapChain.
867 * Can also happen on thread switches - in that case findThreadContextForSwapChain
868 * is perfect to call.
870 context = findThreadContextForSwapChain(This->swapchains[0], tid);
876 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
877 if(This->pbufferContext == NULL ||
878 This->pbufferWidth < targetimpl->currentDesc.Width ||
879 This->pbufferHeight < targetimpl->currentDesc.Height) {
880 if(This->pbufferContext) {
881 DestroyContext(This, This->pbufferContext);
884 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
885 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
887 This->pbufferContext = CreateContext(This, targetimpl,
888 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
889 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
890 This->pbufferWidth = targetimpl->currentDesc.Width;
891 This->pbufferHeight = targetimpl->currentDesc.Height;
894 if(This->pbufferContext) {
895 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
896 FIXME("The PBuffr context is only supported for one thread for now!\n");
898 This->pbufferContext->tid = tid;
899 context = This->pbufferContext;
902 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
903 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
908 /* Stay with the currently active context for back buffer rendering */
909 if(This->activeContext && tid == This->lastThread) {
910 context = This->activeContext;
912 /* This may happen if the app jumps straight into offscreen rendering
913 * Start using the context of the primary swapchain. tid == 0 is no problem
914 * for findThreadContextForSwapChain.
916 * Can also happen on thread switches - in that case findThreadContextForSwapChain
917 * is perfect to call.
919 context = findThreadContextForSwapChain(This->swapchains[0], tid);
924 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
925 /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
926 * back when we are done won't mark us dirty.
928 IWineD3DSurface_PreLoad(target);
931 if(!oldRenderOffscreen) {
932 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
933 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
934 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
935 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
936 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
940 BOOL oldInDraw = This->isInDraw;
942 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
943 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
944 * when using offscreen rendering with multithreading
946 This->isInDraw = TRUE;
948 /* Do that before switching the context:
949 * Read the back buffer of the old drawable into the destination texture
951 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
953 /* Assume that the drawable will be modified by some other things now */
954 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
956 This->isInDraw = oldInDraw;
959 if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
960 This->depth_copy_state = WINED3D_DCS_COPY;
965 /*****************************************************************************
968 * Finds a rendering context and drawable matching the device and render
969 * target for the current thread, activates them and puts them into the
973 * This: Device to activate the context for
974 * target: Requested render target
975 * usage: Prepares the context for blitting, drawing or other actions
977 *****************************************************************************/
978 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
979 DWORD tid = GetCurrentThreadId();
981 DWORD dirtyState, idx;
983 WineD3DContext *context;
985 const struct StateEntry *StateTable = This->shader_backend->StateTable;
987 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
988 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
989 context = FindContext(This, target, tid, &drawBuffer);
990 This->lastActiveRenderTarget = target;
991 This->lastThread = tid;
993 /* Stick to the old context */
994 context = This->activeContext;
997 /* Activate the opengl context */
998 if(context != This->activeContext) {
1001 /* Prevent an unneeded context switch as those are expensive */
1002 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1003 TRACE("Already using gl context %p\n", context->glCtx);
1006 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1008 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, FALSE);
1009 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1011 ERR("Failed to activate the new context\n");
1012 } else if(!context->last_was_blit) {
1013 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, TRUE);
1016 if(This->activeContext->vshader_const_dirty) {
1017 memset(This->activeContext->vshader_const_dirty, 1,
1018 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1020 if(This->activeContext->pshader_const_dirty) {
1021 memset(This->activeContext->pshader_const_dirty, 1,
1022 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1024 This->activeContext = context;
1027 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1029 /* Select the right draw buffer. It is selected in FindContext. */
1030 if(drawBuffer && context->last_draw_buffer != drawBuffer) {
1031 TRACE("Drawing to buffer: %#x\n", drawBuffer);
1032 context->last_draw_buffer = drawBuffer;
1034 glDrawBuffer(drawBuffer);
1035 checkGLcall("glDrawBuffer");
1039 case CTXUSAGE_RESOURCELOAD:
1040 /* This does not require any special states to be set up */
1043 case CTXUSAGE_CLEAR:
1044 if(context->last_was_blit) {
1045 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, TRUE);
1048 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1049 * blending when clearing improves the clearing performance incredibly.
1051 glDisable(GL_BLEND);
1052 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1054 glEnable(GL_SCISSOR_TEST);
1055 checkGLcall("glEnable GL_SCISSOR_TEST");
1056 context->last_was_blit = FALSE;
1057 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1058 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1061 case CTXUSAGE_DRAWPRIM:
1062 /* This needs all dirty states applied */
1063 if(context->last_was_blit) {
1064 This->shader_backend->shader_fragment_enable((IWineD3DDevice *) This, TRUE);
1067 IWineD3DDeviceImpl_FindTexUnitMap(This);
1069 for(i=0; i < context->numDirtyEntries; i++) {
1070 dirtyState = context->dirtyArray[i];
1071 idx = dirtyState >> 5;
1072 shift = dirtyState & 0x1f;
1073 context->isStateDirty[idx] &= ~(1 << shift);
1074 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1076 context->numDirtyEntries = 0; /* This makes the whole list clean */
1077 context->last_was_blit = FALSE;
1081 SetupForBlit(This, context,
1082 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1083 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1087 FIXME("Unexpected context usage requested\n");