winebuild: Generate MS-style imports using the OriginalFirstThunk field.
[wine.git] / dlls / wined3d / context.c
blob2f30affdc484c171552b59ce4d5d8e783df238a7
1 /*
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
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
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 /*****************************************************************************
40 * Context_MarkStateDirty
42 * Marks a state in a context dirty. Only one context, opposed to
43 * IWineD3DDeviceImpl_MarkStateDirty, which marks the state dirty in all
44 * contexts
46 * Params:
47 * context: Context to mark the state dirty in
48 * state: State to mark dirty
49 * StateTable: Pointer to the state table in use(for state grouping)
51 *****************************************************************************/
52 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state, const struct StateEntry *StateTable) {
53 DWORD rep = StateTable[state].representative;
54 DWORD idx;
55 BYTE shift;
57 if(!rep || isStateDirty(context, rep)) return;
59 context->dirtyArray[context->numDirtyEntries++] = rep;
60 idx = rep >> 5;
61 shift = rep & 0x1f;
62 context->isStateDirty[idx] |= (1 << shift);
65 /*****************************************************************************
66 * AddContextToArray
68 * Adds a context to the context array. Helper function for CreateContext
70 * This method is not called in performance-critical code paths, only when a
71 * new render target or swapchain is created. Thus performance is not an issue
72 * here.
74 * Params:
75 * This: Device to add the context for
76 * hdc: device context
77 * glCtx: WGL context to add
78 * pbuffer: optional pbuffer used with this context
80 *****************************************************************************/
81 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
82 WineD3DContext **oldArray = This->contexts;
83 DWORD state;
85 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
86 if(This->contexts == NULL) {
87 ERR("Unable to grow the context array\n");
88 This->contexts = oldArray;
89 return NULL;
91 if(oldArray) {
92 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
95 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
96 if(This->contexts[This->numContexts] == NULL) {
97 ERR("Unable to allocate a new context\n");
98 HeapFree(GetProcessHeap(), 0, This->contexts);
99 This->contexts = oldArray;
100 return NULL;
103 This->contexts[This->numContexts]->hdc = hdc;
104 This->contexts[This->numContexts]->glCtx = glCtx;
105 This->contexts[This->numContexts]->pbuffer = pbuffer;
106 This->contexts[This->numContexts]->win_handle = win_handle;
107 HeapFree(GetProcessHeap(), 0, oldArray);
109 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
111 for(state = 0; state <= STATE_HIGHEST; state++) {
112 Context_MarkStateDirty(This->contexts[This->numContexts], state, This->StateTable);
115 This->numContexts++;
116 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
117 return This->contexts[This->numContexts - 1];
120 /* This function takes care of WineD3D pixel format selection. */
121 static int WineD3D_ChoosePixelFormat(IWineD3DDeviceImpl *This, HDC hdc, WINED3DFORMAT ColorFormat, WINED3DFORMAT DepthStencilFormat, BOOL auxBuffers, int numSamples, BOOL pbuffer, BOOL findCompatible)
123 int iPixelFormat=0, matchtry;
124 short redBits, greenBits, blueBits, alphaBits, colorBits;
125 short depthBits=0, stencilBits=0;
127 struct match_type {
128 BOOL require_aux;
129 BOOL exact_alpha;
130 BOOL exact_color;
131 } matches[] = {
132 /* First, try without alpha match buffers. MacOS supports aux buffers only
133 * on A8R8G8B8, and we prefer better offscreen rendering over an alpha match.
134 * Then try without aux buffers - this is the most common cause for not
135 * finding a pixel format. Also some drivers(the open source ones)
136 * only offer 32 bit ARB pixel formats. First try without an exact alpha
137 * match, then try without an exact alpha and color match.
139 { FALSE, TRUE, TRUE },
140 { TRUE, TRUE, TRUE },
141 { FALSE, FALSE, TRUE },
142 { FALSE, FALSE, FALSE },
143 { TRUE, FALSE, TRUE },
144 { TRUE, FALSE, FALSE },
147 int i = 0;
148 int nCfgs = This->adapter->nCfgs;
149 WineD3D_PixelFormat *cfgs = This->adapter->cfgs;
151 TRACE("ColorFormat=%s, DepthStencilFormat=%s, auxBuffers=%d, numSamples=%d, pbuffer=%d, findCompatible=%d\n",
152 debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat), auxBuffers, numSamples, pbuffer, findCompatible);
154 if(!getColorBits(ColorFormat, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
155 ERR("Unable to get color bits for format %s (%#x)!\n", debug_d3dformat(ColorFormat), ColorFormat);
156 return 0;
159 /* In WGL both color, depth and stencil are features of a pixel format. In case of D3D they are separate.
160 * You are able to add a depth + stencil surface at a later stage when you need it.
161 * In order to support this properly in WineD3D we need the ability to recreate the opengl context and
162 * drawable when this is required. This is very tricky as we need to reapply ALL opengl states for the new
163 * context, need torecreate shaders, textures and other resources.
165 * The context manager already takes care of the state problem and for the other tasks code from Reset
166 * can be used. These changes are way to risky during the 1.0 code freeze which is taking place right now.
167 * Likely a lot of other new bugs will be exposed. For that reason request a depth stencil surface all the
168 * time. It can cause a slight performance hit but fixes a lot of regressions. A fixme reminds of that this
169 * issue needs to be fixed. */
170 if(DepthStencilFormat != WINED3DFMT_D24S8)
171 FIXME("Add OpenGL context recreation support to SetDepthStencilSurface\n");
173 DepthStencilFormat = WINED3DFMT_D24S8;
175 if(DepthStencilFormat) {
176 getDepthStencilBits(DepthStencilFormat, &depthBits, &stencilBits);
179 for(matchtry = 0; matchtry < (sizeof(matches) / sizeof(matches[0])) && !iPixelFormat; matchtry++) {
180 for(i=0; i<nCfgs; i++) {
181 BOOL exactDepthMatch = TRUE;
182 cfgs = &This->adapter->cfgs[i];
184 /* For now only accept RGBA formats. Perhaps some day we will
185 * allow floating point formats for pbuffers. */
186 if(cfgs->iPixelType != WGL_TYPE_RGBA_ARB)
187 continue;
189 /* In window mode (!pbuffer) we need a window drawable format and double buffering. */
190 if(!pbuffer && !(cfgs->windowDrawable && cfgs->doubleBuffer))
191 continue;
193 /* We like to have aux buffers in backbuffer mode */
194 if(auxBuffers && !cfgs->auxBuffers && matches[matchtry].require_aux)
195 continue;
197 /* In pbuffer-mode we need a pbuffer-capable format but we don't want double buffering */
198 if(pbuffer && (!cfgs->pbufferDrawable || cfgs->doubleBuffer))
199 continue;
201 if(matches[matchtry].exact_color) {
202 if(cfgs->redSize != redBits)
203 continue;
204 if(cfgs->greenSize != greenBits)
205 continue;
206 if(cfgs->blueSize != blueBits)
207 continue;
208 } else {
209 if(cfgs->redSize < redBits)
210 continue;
211 if(cfgs->greenSize < greenBits)
212 continue;
213 if(cfgs->blueSize < blueBits)
214 continue;
216 if(matches[matchtry].exact_alpha) {
217 if(cfgs->alphaSize != alphaBits)
218 continue;
219 } else {
220 if(cfgs->alphaSize < alphaBits)
221 continue;
224 /* We try to locate a format which matches our requirements exactly. In case of
225 * depth it is no problem to emulate 16-bit using e.g. 24-bit, so accept that. */
226 if(cfgs->depthSize < depthBits)
227 continue;
228 else if(cfgs->depthSize > depthBits)
229 exactDepthMatch = FALSE;
231 /* In all cases make sure the number of stencil bits matches our requirements
232 * even when we don't need stencil because it could affect performance EXCEPT
233 * on cards which don't offer depth formats without stencil like the i915 drivers
234 * on Linux. */
235 if(stencilBits != cfgs->stencilSize && !(This->adapter->brokenStencil && stencilBits <= cfgs->stencilSize))
236 continue;
238 /* Check multisampling support */
239 if(cfgs->numSamples != numSamples)
240 continue;
242 /* When we have passed all the checks then we have found a format which matches our
243 * requirements. Note that we only check for a limit number of capabilities right now,
244 * so there can easily be a dozen of pixel formats which appear to be the 'same' but
245 * can still differ in things like multisampling, stereo, SRGB and other flags.
248 /* Exit the loop as we have found a format :) */
249 if(exactDepthMatch) {
250 iPixelFormat = cfgs->iPixelFormat;
251 break;
252 } else if(!iPixelFormat) {
253 /* In the end we might end up with a format which doesn't exactly match our depth
254 * requirements. Accept the first format we found because formats with higher iPixelFormat
255 * values tend to have more extended capabilities (e.g. multisampling) which we don't need. */
256 iPixelFormat = cfgs->iPixelFormat;
261 /* When findCompatible is set and no suitable format was found, let ChoosePixelFormat choose a pixel format in order not to crash. */
262 if(!iPixelFormat && !findCompatible) {
263 ERR("Can't find a suitable iPixelFormat\n");
264 return FALSE;
265 } else if(!iPixelFormat) {
266 PIXELFORMATDESCRIPTOR pfd;
268 TRACE("Falling back to ChoosePixelFormat as we weren't able to find an exactly matching pixel format\n");
269 /* PixelFormat selection */
270 ZeroMemory(&pfd, sizeof(pfd));
271 pfd.nSize = sizeof(pfd);
272 pfd.nVersion = 1;
273 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
274 pfd.iPixelType = PFD_TYPE_RGBA;
275 pfd.cAlphaBits = alphaBits;
276 pfd.cColorBits = colorBits;
277 pfd.cDepthBits = depthBits;
278 pfd.cStencilBits = stencilBits;
279 pfd.iLayerType = PFD_MAIN_PLANE;
281 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
282 if(!iPixelFormat) {
283 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
284 ERR("Can't find a suitable iPixelFormat\n");
285 return FALSE;
289 TRACE("Found iPixelFormat=%d for ColorFormat=%s, DepthStencilFormat=%s\n", iPixelFormat, debug_d3dformat(ColorFormat), debug_d3dformat(DepthStencilFormat));
290 return iPixelFormat;
293 /*****************************************************************************
294 * CreateContext
296 * Creates a new context for a window, or a pbuffer context.
298 * * Params:
299 * This: Device to activate the context for
300 * target: Surface this context will render to
301 * win_handle: handle to the window which we are drawing to
302 * create_pbuffer: tells whether to create a pbuffer or not
303 * pPresentParameters: contains the pixelformats to use for onscreen rendering
305 *****************************************************************************/
306 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
307 HDC oldDrawable, hdc;
308 HPBUFFERARB pbuffer = NULL;
309 HGLRC ctx = NULL, oldCtx;
310 WineD3DContext *ret = NULL;
311 int s;
313 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
315 if(create_pbuffer) {
316 HDC hdc_parent = GetDC(win_handle);
317 int iPixelFormat = 0;
319 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
320 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
322 /* Try to find a pixel format with pbuffer support. */
323 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffers */, 0 /* numSamples */, TRUE /* PBUFFER */, FALSE /* findCompatible */);
324 if(!iPixelFormat) {
325 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
327 /* For some reason we weren't able to find a format, try to find something instead of crashing.
328 * A reason for failure could have been wglChoosePixelFormatARB strictness. */
329 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc_parent, target->resource.format, StencilBufferFormat, FALSE /* auxBuffer */, 0 /* numSamples */, TRUE /* PBUFFER */, TRUE /* findCompatible */);
332 /* This shouldn't happen as ChoosePixelFormat always returns something */
333 if(!iPixelFormat) {
334 ERR("Unable to locate a pixel format for a pbuffer\n");
335 ReleaseDC(win_handle, hdc_parent);
336 goto out;
339 TRACE("Creating a pBuffer drawable for the new context\n");
340 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
341 if(!pbuffer) {
342 ERR("Cannot create a pbuffer\n");
343 ReleaseDC(win_handle, hdc_parent);
344 goto out;
347 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
348 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
349 if(!hdc) {
350 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
351 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
352 ReleaseDC(win_handle, hdc_parent);
353 goto out;
355 ReleaseDC(win_handle, hdc_parent);
356 } else {
357 PIXELFORMATDESCRIPTOR pfd;
358 int iPixelFormat;
359 int res;
360 WINED3DFORMAT ColorFormat = target->resource.format;
361 WINED3DFORMAT DepthStencilFormat = 0;
362 BOOL auxBuffers = FALSE;
363 int numSamples = 0;
365 hdc = GetDC(win_handle);
366 if(hdc == NULL) {
367 ERR("Cannot retrieve a device context!\n");
368 goto out;
371 /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
372 if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
373 auxBuffers = TRUE;
375 if(target->resource.format == WINED3DFMT_X4R4G4B4)
376 ColorFormat = WINED3DFMT_A4R4G4B4;
377 else if(target->resource.format == WINED3DFMT_X8R8G8B8)
378 ColorFormat = WINED3DFMT_A8R8G8B8;
381 /* DirectDraw supports 8bit paletted render targets and these are used by old games like Starcraft and C&C.
382 * Most modern hardware doesn't support 8bit natively so we perform some form of 8bit -> 32bit conversion.
383 * The conversion (ab)uses the alpha component for storing the palette index. For this reason we require
384 * a format with 8bit alpha, so request A8R8G8B8. */
385 if(ColorFormat == WINED3DFMT_P8)
386 ColorFormat = WINED3DFMT_A8R8G8B8;
388 /* Retrieve the depth stencil format from the present parameters.
389 * The choice of the proper format can give a nice performance boost
390 * in case of GPU limited programs. */
391 if(pPresentParms->EnableAutoDepthStencil) {
392 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
393 DepthStencilFormat = pPresentParms->AutoDepthStencilFormat;
396 /* D3D only allows multisampling when SwapEffect is set to WINED3DSWAPEFFECT_DISCARD */
397 if(pPresentParms->MultiSampleType && (pPresentParms->SwapEffect == WINED3DSWAPEFFECT_DISCARD)) {
398 if(!GL_SUPPORT(ARB_MULTISAMPLE))
399 ERR("The program is requesting multisampling without support!\n");
400 else {
401 ERR("Requesting MultiSampleType=%d\n", pPresentParms->MultiSampleType);
402 numSamples = pPresentParms->MultiSampleType;
406 /* Try to find a pixel format which matches our requirements */
407 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, numSamples, FALSE /* PBUFFER */, FALSE /* findCompatible */);
409 /* Try to locate a compatible format if we weren't able to find anything */
410 if(!iPixelFormat) {
411 TRACE("Trying to locate a compatible pixel format because an exact match failed.\n");
412 iPixelFormat = WineD3D_ChoosePixelFormat(This, hdc, ColorFormat, DepthStencilFormat, auxBuffers, 0 /* numSamples */, FALSE /* PBUFFER */, TRUE /* findCompatible */ );
415 /* If we still don't have a pixel format, something is very wrong as ChoosePixelFormat barely fails */
416 if(!iPixelFormat) {
417 ERR("Can't find a suitable iPixelFormat\n");
418 return FALSE;
421 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
422 res = SetPixelFormat(hdc, iPixelFormat, NULL);
423 if(!res) {
424 int oldPixelFormat = GetPixelFormat(hdc);
426 /* By default WGL doesn't allow pixel format adjustments but we need it here.
427 * For this reason there is a WINE-specific wglSetPixelFormat which allows you to
428 * set the pixel format multiple times. Only use it when it is really needed. */
430 if(oldPixelFormat == iPixelFormat) {
431 /* We don't have to do anything as the formats are the same :) */
432 } else if(oldPixelFormat && GL_SUPPORT(WGL_WINE_PIXEL_FORMAT_PASSTHROUGH)) {
433 res = GL_EXTCALL(wglSetPixelFormatWINE(hdc, iPixelFormat, NULL));
435 if(!res) {
436 ERR("wglSetPixelFormatWINE failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
437 return FALSE;
439 } else if(oldPixelFormat) {
440 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
441 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
442 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
443 } else {
444 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
445 return FALSE;
450 ctx = pwglCreateContext(hdc);
451 if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
453 if(!ctx) {
454 ERR("Failed to create a WGL context\n");
455 if(create_pbuffer) {
456 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
457 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
459 goto out;
461 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
462 if(!ret) {
463 ERR("Failed to add the newly created context to the context list\n");
464 pwglDeleteContext(ctx);
465 if(create_pbuffer) {
466 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
467 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
469 goto out;
471 ret->surface = (IWineD3DSurface *) target;
472 ret->isPBuffer = create_pbuffer;
473 ret->tid = GetCurrentThreadId();
474 if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
475 /* Create the dirty constants array and initialize them to dirty */
476 ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
477 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
478 ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
479 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
480 memset(ret->vshader_const_dirty, 1,
481 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
482 memset(ret->pshader_const_dirty, 1,
483 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
486 TRACE("Successfully created new context %p\n", ret);
488 ret->fbo_color_attachments = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IWineD3DSurface *) * GL_LIMITS(buffers));
489 if (!ret->fbo_color_attachments)
491 ERR("Out of memory!\n");
492 goto out;
495 /* Set up the context defaults */
496 oldCtx = pwglGetCurrentContext();
497 oldDrawable = pwglGetCurrentDC();
498 if(oldCtx && oldDrawable) {
499 /* See comment in ActivateContext context switching */
500 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
502 if(pwglMakeCurrent(hdc, ctx) == FALSE) {
503 ERR("Cannot activate context to set up defaults\n");
504 goto out;
507 ENTER_GL();
509 glGetIntegerv(GL_AUX_BUFFERS, &ret->aux_buffers);
511 TRACE("Setting up the screen\n");
512 /* Clear the screen */
513 glClearColor(1.0, 0.0, 0.0, 0.0);
514 checkGLcall("glClearColor");
515 glClearIndex(0);
516 glClearDepth(1);
517 glClearStencil(0xffff);
519 checkGLcall("glClear");
521 glColor3f(1.0, 1.0, 1.0);
522 checkGLcall("glColor3f");
524 glEnable(GL_LIGHTING);
525 checkGLcall("glEnable");
527 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
528 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
530 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
531 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
533 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
534 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
536 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
537 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
538 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
539 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
541 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
542 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
543 * and textures in DIB sections(due to the memory protection).
545 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
546 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
548 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
549 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
550 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
551 * GL_VERTEX_BLEND_ARB isn't enabled too
553 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
554 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
556 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
557 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
558 * the previous texture where to source the offset from is always unit - 1.
560 for(s = 1; s < GL_LIMITS(textures); s++) {
561 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
562 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
563 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
567 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
568 for(s = 0; s < GL_LIMITS(textures); s++) {
569 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
570 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
571 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
574 LEAVE_GL();
576 /* Never keep GL_FRAGMENT_SHADER_ATI enabled on a context that we switch away from,
577 * but enable it for the first context we create, and reenable it on the old context
579 if(oldDrawable && oldCtx) {
580 pwglMakeCurrent(oldDrawable, oldCtx);
581 } else {
582 last_device = This;
584 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
586 return ret;
588 out:
589 HeapFree(GetProcessHeap(), 0, ret->fbo_color_attachments);
590 return NULL;
593 /*****************************************************************************
594 * RemoveContextFromArray
596 * Removes a context from the context manager. The opengl context is not
597 * destroyed or unset. context is not a valid pointer after that call.
599 * Similar to the former call this isn't a performance critical function. A
600 * helper function for DestroyContext.
602 * Params:
603 * This: Device to activate the context for
604 * context: Context to remove
606 *****************************************************************************/
607 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
608 UINT t, s;
609 WineD3DContext **oldArray = This->contexts;
611 TRACE("Removing ctx %p\n", context);
613 This->numContexts--;
615 if(This->numContexts) {
616 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
617 if(!This->contexts) {
618 ERR("Cannot allocate a new context array, PANIC!!!\n");
620 t = 0;
621 /* Note that we decreased numContexts a few lines up, so use '<=' instead of '<' */
622 for(s = 0; s <= This->numContexts; s++) {
623 if(oldArray[s] == context) continue;
624 This->contexts[t] = oldArray[s];
625 t++;
627 } else {
628 This->contexts = NULL;
631 HeapFree(GetProcessHeap(), 0, context);
632 HeapFree(GetProcessHeap(), 0, oldArray);
635 static void destroy_fbo(IWineD3DDeviceImpl *This, const GLuint *fbo)
637 int i = 0;
639 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, *fbo));
640 checkGLcall("glBindFramebuffer()");
641 for (i = 0; i < GL_LIMITS(buffers); ++i)
643 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + i, GL_TEXTURE_2D, 0, 0));
644 checkGLcall("glFramebufferTexture2D()");
646 GL_EXTCALL(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0));
647 checkGLcall("glFramebufferTexture2D()");
648 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
649 checkGLcall("glBindFramebuffer()");
650 GL_EXTCALL(glDeleteFramebuffersEXT(1, fbo));
651 checkGLcall("glDeleteFramebuffers()");
654 /*****************************************************************************
655 * DestroyContext
657 * Destroys a wineD3DContext
659 * Params:
660 * This: Device to activate the context for
661 * context: Context to destroy
663 *****************************************************************************/
664 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
666 TRACE("Destroying ctx %p\n", context);
668 /* The correct GL context needs to be active to cleanup the GL resources below */
669 if(pwglGetCurrentContext() != context->glCtx){
670 pwglMakeCurrent(context->hdc, context->glCtx);
671 last_device = NULL;
674 ENTER_GL();
676 if (context->fbo) {
677 TRACE("Destroy FBO %d\n", context->fbo);
678 destroy_fbo(This, &context->fbo);
680 if (context->src_fbo) {
681 TRACE("Destroy src FBO %d\n", context->src_fbo);
682 destroy_fbo(This, &context->src_fbo);
684 if (context->dst_fbo) {
685 TRACE("Destroy dst FBO %d\n", context->dst_fbo);
686 destroy_fbo(This, &context->dst_fbo);
689 LEAVE_GL();
691 HeapFree(GetProcessHeap(), 0, context->fbo_color_attachments);
692 context->fbo_color_attachments = NULL;
694 /* Cleanup the GL context */
695 pwglMakeCurrent(NULL, NULL);
696 if(context->isPBuffer) {
697 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
698 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
699 } else ReleaseDC(context->win_handle, context->hdc);
700 pwglDeleteContext(context->glCtx);
702 HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
703 HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
704 RemoveContextFromArray(This, context);
707 static inline void set_blit_dimension(UINT width, UINT height) {
708 glMatrixMode(GL_PROJECTION);
709 checkGLcall("glMatrixMode(GL_PROJECTION)");
710 glLoadIdentity();
711 checkGLcall("glLoadIdentity()");
712 glOrtho(0, width, height, 0, 0.0, -1.0);
713 checkGLcall("glOrtho");
714 glViewport(0, 0, width, height);
715 checkGLcall("glViewport");
718 /*****************************************************************************
719 * SetupForBlit
721 * Sets up a context for DirectDraw blitting.
722 * All texture units are disabled, texture unit 0 is set as current unit
723 * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
724 * color writing enabled for all channels
725 * register combiners disabled, shaders disabled
726 * world matrix is set to identity, texture matrix 0 too
727 * projection matrix is setup for drawing screen coordinates
729 * Params:
730 * This: Device to activate the context for
731 * context: Context to setup
732 * width: render target width
733 * height: render target height
735 *****************************************************************************/
736 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
737 int i, sampler;
738 const struct StateEntry *StateTable = This->StateTable;
740 TRACE("Setting up context %p for blitting\n", context);
741 if(context->last_was_blit) {
742 if(context->blit_w != width || context->blit_h != height) {
743 set_blit_dimension(width, height);
744 context->blit_w = width; context->blit_h = height;
745 /* No need to dirtify here, the states are still dirtified because they weren't
746 * applied since the last SetupForBlit call. Otherwise last_was_blit would not
747 * be set
750 TRACE("Context is already set up for blitting, nothing to do\n");
751 return;
753 context->last_was_blit = TRUE;
755 /* TODO: Use a display list */
757 /* Disable shaders */
758 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
759 Context_MarkStateDirty(context, STATE_VSHADER, StateTable);
760 Context_MarkStateDirty(context, STATE_PIXELSHADER, StateTable);
762 /* Disable all textures. The caller can then bind a texture it wants to blit
763 * from
765 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
766 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
767 * function texture unit. No need to care for higher samplers
769 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
770 sampler = This->rev_tex_unit_map[i];
771 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
772 checkGLcall("glActiveTextureARB");
774 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
775 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
776 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
778 glDisable(GL_TEXTURE_3D);
779 checkGLcall("glDisable GL_TEXTURE_3D");
780 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
781 glDisable(GL_TEXTURE_RECTANGLE_ARB);
782 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
784 glDisable(GL_TEXTURE_2D);
785 checkGLcall("glDisable GL_TEXTURE_2D");
787 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
788 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
790 if (sampler != -1) {
791 if (sampler < MAX_TEXTURES) {
792 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
794 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
797 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
798 checkGLcall("glActiveTextureARB");
801 sampler = This->rev_tex_unit_map[0];
803 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
804 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
805 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
807 glDisable(GL_TEXTURE_3D);
808 checkGLcall("glDisable GL_TEXTURE_3D");
809 if(GL_SUPPORT(ARB_TEXTURE_RECTANGLE)) {
810 glDisable(GL_TEXTURE_RECTANGLE_ARB);
811 checkGLcall("glDisable GL_TEXTURE_RECTANGLE_ARB");
813 glDisable(GL_TEXTURE_2D);
814 checkGLcall("glDisable GL_TEXTURE_2D");
816 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
818 glMatrixMode(GL_TEXTURE);
819 checkGLcall("glMatrixMode(GL_TEXTURE)");
820 glLoadIdentity();
821 checkGLcall("glLoadIdentity()");
823 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
824 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
825 GL_TEXTURE_LOD_BIAS_EXT,
826 0.0);
827 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
830 if (sampler != -1) {
831 if (sampler < MAX_TEXTURES) {
832 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0 + sampler), StateTable);
833 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(sampler, WINED3DTSS_COLOROP), StateTable);
835 Context_MarkStateDirty(context, STATE_SAMPLER(sampler), StateTable);
838 /* Other misc states */
839 glDisable(GL_ALPHA_TEST);
840 checkGLcall("glDisable(GL_ALPHA_TEST)");
841 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE), StateTable);
842 glDisable(GL_LIGHTING);
843 checkGLcall("glDisable GL_LIGHTING");
844 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING), StateTable);
845 glDisable(GL_DEPTH_TEST);
846 checkGLcall("glDisable GL_DEPTH_TEST");
847 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE), StateTable);
848 glDisable(GL_FOG);
849 checkGLcall("glDisable GL_FOG");
850 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE), StateTable);
851 glDisable(GL_BLEND);
852 checkGLcall("glDisable GL_BLEND");
853 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
854 glDisable(GL_CULL_FACE);
855 checkGLcall("glDisable GL_CULL_FACE");
856 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE), StateTable);
857 glDisable(GL_STENCIL_TEST);
858 checkGLcall("glDisable GL_STENCIL_TEST");
859 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE), StateTable);
860 glDisable(GL_SCISSOR_TEST);
861 checkGLcall("glDisable GL_SCISSOR_TEST");
862 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
863 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
864 glDisable(GL_POINT_SPRITE_ARB);
865 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
866 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE), StateTable);
868 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
869 checkGLcall("glColorMask");
870 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
871 if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
872 glDisable(GL_COLOR_SUM_EXT);
873 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE), StateTable);
874 checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
877 /* Setup transforms */
878 glMatrixMode(GL_MODELVIEW);
879 checkGLcall("glMatrixMode(GL_MODELVIEW)");
880 glLoadIdentity();
881 checkGLcall("glLoadIdentity()");
882 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)), StateTable);
884 context->last_was_rhw = TRUE;
885 Context_MarkStateDirty(context, STATE_VDECL, StateTable); /* because of last_was_rhw = TRUE */
887 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
888 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
889 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
890 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
891 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
892 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
893 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING), StateTable);
895 set_blit_dimension(width, height);
896 context->blit_w = width; context->blit_h = height;
897 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
898 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION), StateTable);
901 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
904 /*****************************************************************************
905 * findThreadContextForSwapChain
907 * Searches a swapchain for all contexts and picks one for the thread tid.
908 * If none can be found the swapchain is requested to create a new context
910 *****************************************************************************/
911 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
912 int i;
914 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
915 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
916 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
921 /* Create a new context for the thread */
922 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
925 /*****************************************************************************
926 * FindContext
928 * Finds a context for the current render target and thread
930 * Parameters:
931 * target: Render target to find the context for
932 * tid: Thread to activate the context for
934 * Returns: The needed context
936 *****************************************************************************/
937 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
938 IWineD3DSwapChain *swapchain = NULL;
939 HRESULT hr;
940 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
941 WineD3DContext *context = This->activeContext;
942 BOOL oldRenderOffscreen = This->render_offscreen;
943 const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
944 const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
945 const struct StateEntry *StateTable = This->StateTable;
947 /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
948 * the alpha blend state changes with different render target formats
950 if(oldFmt != newFmt) {
951 const GlPixelFormatDesc *glDesc;
952 const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
953 const StaticPixelFormatDesc *new = getFormatDescEntry(newFmt, &GLINFO_LOCATION, &glDesc);
955 /* Disable blending when the alphaMask has changed and when a format doesn't support blending */
956 if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask) || !(glDesc->Flags & WINED3DFMT_FLAG_POSTPIXELSHADER_BLENDING)) {
957 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
961 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
962 if(hr == WINED3D_OK && swapchain) {
963 TRACE("Rendering onscreen\n");
965 context = findThreadContextForSwapChain(swapchain, tid);
967 This->render_offscreen = FALSE;
968 /* The context != This->activeContext will catch a NOP context change. This can occur
969 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
970 * rendering. No context change is needed in that case
973 if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
974 if(This->pbufferContext && tid == This->pbufferContext->tid) {
975 This->pbufferContext->tid = 0;
978 IWineD3DSwapChain_Release(swapchain);
980 if(oldRenderOffscreen) {
981 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
982 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
983 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
984 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
985 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
988 } else {
989 TRACE("Rendering offscreen\n");
990 This->render_offscreen = TRUE;
992 switch(wined3d_settings.offscreen_rendering_mode) {
993 case ORM_FBO:
994 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
995 if(This->activeContext && tid == This->lastThread) {
996 context = This->activeContext;
997 } else {
998 /* This may happen if the app jumps straight into offscreen rendering
999 * Start using the context of the primary swapchain. tid == 0 is no problem
1000 * for findThreadContextForSwapChain.
1002 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1003 * is perfect to call.
1005 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1007 break;
1009 case ORM_PBUFFER:
1011 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
1012 if(This->pbufferContext == NULL ||
1013 This->pbufferWidth < targetimpl->currentDesc.Width ||
1014 This->pbufferHeight < targetimpl->currentDesc.Height) {
1015 if(This->pbufferContext) {
1016 DestroyContext(This, This->pbufferContext);
1019 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
1020 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
1022 This->pbufferContext = CreateContext(This, targetimpl,
1023 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
1024 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
1025 This->pbufferWidth = targetimpl->currentDesc.Width;
1026 This->pbufferHeight = targetimpl->currentDesc.Height;
1029 if(This->pbufferContext) {
1030 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
1031 FIXME("The PBuffr context is only supported for one thread for now!\n");
1033 This->pbufferContext->tid = tid;
1034 context = This->pbufferContext;
1035 break;
1036 } else {
1037 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
1038 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
1042 case ORM_BACKBUFFER:
1043 /* Stay with the currently active context for back buffer rendering */
1044 if(This->activeContext && tid == This->lastThread) {
1045 context = This->activeContext;
1046 } else {
1047 /* This may happen if the app jumps straight into offscreen rendering
1048 * Start using the context of the primary swapchain. tid == 0 is no problem
1049 * for findThreadContextForSwapChain.
1051 * Can also happen on thread switches - in that case findThreadContextForSwapChain
1052 * is perfect to call.
1054 context = findThreadContextForSwapChain(This->swapchains[0], tid);
1056 break;
1059 if(!oldRenderOffscreen) {
1060 Context_MarkStateDirty(context, WINED3DTS_PROJECTION, StateTable);
1061 Context_MarkStateDirty(context, STATE_VDECL, StateTable);
1062 Context_MarkStateDirty(context, STATE_VIEWPORT, StateTable);
1063 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1064 Context_MarkStateDirty(context, STATE_FRONTFACE, StateTable);
1068 /* When switching away from an offscreen render target, and we're not using FBOs,
1069 * we have to read the drawable into the texture. This is done via PreLoad(and
1070 * SFLAG_INDRAWABLE set on the surface). There are some things that need care though.
1071 * PreLoad needs a GL context, and FindContext is called before the context is activated.
1072 * It also has to be called with the old rendertarget active, otherwise a wrong drawable
1073 * is read. This leads to these possible situations:
1075 * 0) lastActiveRenderTarget == target && oldTid == newTid:
1076 * Nothing to do, we don't even reach this code in this case...
1078 * 1) lastActiveRenderTarget != target && oldTid == newTid:
1079 * The currently active context is OK for readback. Call PreLoad, and it
1080 * performs the read
1082 * 2) lastActiveRenderTarget == target && oldTid != newTid:
1083 * Nothing to do - the drawable is unchanged
1085 * 3) lastActiveRenderTarget != target && oldTid != newTid:
1086 * This is tricky. We have to get a context with the old drawable from somewhere
1087 * before we can switch to the new context. In this case, PreLoad calls
1088 * ActivateContext(lastActiveRenderTarget) from the new(current) thread. This
1089 * is case (2) then. The old drawable is activated for the new thread, and the
1090 * readback can be done. The recursed ActivateContext does *not* call PreLoad again.
1091 * After that, the outer ActivateContext(which calls PreLoad) can activate the new
1092 * target for the new thread
1094 if (readTexture && This->lastActiveRenderTarget != target) {
1095 BOOL oldInDraw = This->isInDraw;
1097 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
1098 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
1099 * when using offscreen rendering with multithreading
1101 This->isInDraw = TRUE;
1103 /* Do that before switching the context:
1104 * Read the back buffer of the old drawable into the destination texture
1106 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
1108 /* Assume that the drawable will be modified by some other things now */
1109 IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
1111 This->isInDraw = oldInDraw;
1114 return context;
1117 static void apply_draw_buffer(IWineD3DDeviceImpl *This, IWineD3DSurface *target, BOOL blit)
1119 HRESULT hr;
1120 IWineD3DSwapChain *swapchain;
1122 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **)&swapchain);
1123 if (SUCCEEDED(hr))
1125 IWineD3DSwapChain_Release((IUnknown *)swapchain);
1126 glDrawBuffer(surface_get_gl_buffer(target, swapchain));
1127 checkGLcall("glDrawBuffers()");
1129 else
1131 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO)
1133 if (!blit)
1135 if (GL_SUPPORT(ARB_DRAW_BUFFERS))
1137 GL_EXTCALL(glDrawBuffersARB(GL_LIMITS(buffers), This->draw_buffers));
1138 checkGLcall("glDrawBuffers()");
1140 else
1142 glDrawBuffer(This->draw_buffers[0]);
1143 checkGLcall("glDrawBuffer()");
1145 } else {
1146 glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
1147 checkGLcall("glDrawBuffer()");
1150 else
1152 glDrawBuffer(This->offscreenBuffer);
1153 checkGLcall("glDrawBuffer()");
1158 /*****************************************************************************
1159 * ActivateContext
1161 * Finds a rendering context and drawable matching the device and render
1162 * target for the current thread, activates them and puts them into the
1163 * requested state.
1165 * Params:
1166 * This: Device to activate the context for
1167 * target: Requested render target
1168 * usage: Prepares the context for blitting, drawing or other actions
1170 *****************************************************************************/
1171 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
1172 DWORD tid = GetCurrentThreadId();
1173 int i;
1174 DWORD dirtyState, idx;
1175 BYTE shift;
1176 WineD3DContext *context;
1177 const struct StateEntry *StateTable = This->StateTable;
1179 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
1180 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
1181 context = FindContext(This, target, tid);
1182 context->draw_buffer_dirty = TRUE;
1183 This->lastActiveRenderTarget = target;
1184 This->lastThread = tid;
1185 } else {
1186 /* Stick to the old context */
1187 context = This->activeContext;
1190 /* Activate the opengl context */
1191 if(last_device != This || context != This->activeContext) {
1192 BOOL ret;
1194 /* Prevent an unneeded context switch as those are expensive */
1195 if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
1196 TRACE("Already using gl context %p\n", context->glCtx);
1198 else {
1199 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
1201 This->frag_pipe->enable_extension((IWineD3DDevice *) This, FALSE);
1202 ret = pwglMakeCurrent(context->hdc, context->glCtx);
1203 if(ret == FALSE) {
1204 ERR("Failed to activate the new context\n");
1205 } else if(!context->last_was_blit) {
1206 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1209 if(This->activeContext->vshader_const_dirty) {
1210 memset(This->activeContext->vshader_const_dirty, 1,
1211 sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
1213 if(This->activeContext->pshader_const_dirty) {
1214 memset(This->activeContext->pshader_const_dirty, 1,
1215 sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
1217 This->activeContext = context;
1218 last_device = This;
1221 /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
1222 ENTER_GL();
1224 switch (usage) {
1225 case CTXUSAGE_CLEAR:
1226 case CTXUSAGE_DRAWPRIM:
1227 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1228 apply_fbo_state((IWineD3DDevice *)This);
1230 if (context->draw_buffer_dirty) {
1231 apply_draw_buffer(This, target, FALSE);
1232 context->draw_buffer_dirty = FALSE;
1234 break;
1236 case CTXUSAGE_BLIT:
1237 if (wined3d_settings.offscreen_rendering_mode == ORM_FBO) {
1238 if (This->render_offscreen) {
1239 FIXME("Activating for CTXUSAGE_BLIT for an offscreen target with ORM_FBO. This should be avoided.\n");
1240 bind_fbo((IWineD3DDevice *)This, GL_FRAMEBUFFER_EXT, &context->dst_fbo);
1241 attach_surface_fbo(This, GL_FRAMEBUFFER_EXT, 0, target);
1242 GL_EXTCALL(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0));
1243 checkGLcall("glFramebufferRenderbufferEXT");
1244 } else {
1245 GL_EXTCALL(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0));
1246 checkGLcall("glFramebufferRenderbufferEXT");
1248 context->draw_buffer_dirty = TRUE;
1250 if (context->draw_buffer_dirty) {
1251 apply_draw_buffer(This, target, TRUE);
1252 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
1253 context->draw_buffer_dirty = FALSE;
1256 break;
1258 default:
1259 break;
1262 switch(usage) {
1263 case CTXUSAGE_RESOURCELOAD:
1264 /* This does not require any special states to be set up */
1265 break;
1267 case CTXUSAGE_CLEAR:
1268 if(context->last_was_blit) {
1269 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1272 /* Blending and clearing should be orthogonal, but tests on the nvidia driver show that disabling
1273 * blending when clearing improves the clearing performance incredibly.
1275 glDisable(GL_BLEND);
1276 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE), StateTable);
1278 glEnable(GL_SCISSOR_TEST);
1279 checkGLcall("glEnable GL_SCISSOR_TEST");
1280 context->last_was_blit = FALSE;
1281 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE), StateTable);
1282 Context_MarkStateDirty(context, STATE_SCISSORRECT, StateTable);
1283 break;
1285 case CTXUSAGE_DRAWPRIM:
1286 /* This needs all dirty states applied */
1287 if(context->last_was_blit) {
1288 This->frag_pipe->enable_extension((IWineD3DDevice *) This, TRUE);
1291 IWineD3DDeviceImpl_FindTexUnitMap(This);
1293 for(i=0; i < context->numDirtyEntries; i++) {
1294 dirtyState = context->dirtyArray[i];
1295 idx = dirtyState >> 5;
1296 shift = dirtyState & 0x1f;
1297 context->isStateDirty[idx] &= ~(1 << shift);
1298 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
1300 context->numDirtyEntries = 0; /* This makes the whole list clean */
1301 context->last_was_blit = FALSE;
1302 break;
1304 case CTXUSAGE_BLIT:
1305 SetupForBlit(This, context,
1306 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
1307 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
1308 break;
1310 default:
1311 FIXME("Unexpected context usage requested\n");
1313 LEAVE_GL();