wined3d: Check the results of SetPixelFormat.
[wine/winequartzdrv.git] / dlls / wined3d / context.c
blob0727aee3b24ab72d8481942557991716360d81cf
1 /*
2 * Context and render target management in wined3d
4 * Copyright 2007 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 /*****************************************************************************
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
37 * contexts
39 * Params:
40 * context: Context to mark the state dirty in
41 * state: State to mark dirty
43 *****************************************************************************/
44 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state) {
45 DWORD rep = StateTable[state].representative;
46 DWORD idx;
47 BYTE shift;
49 if(!rep || isStateDirty(context, rep)) return;
51 context->dirtyArray[context->numDirtyEntries++] = rep;
52 idx = rep >> 5;
53 shift = rep & 0x1f;
54 context->isStateDirty[idx] |= (1 << shift);
57 /*****************************************************************************
58 * AddContextToArray
60 * Adds a context to the context array. Helper function for CreateContext
62 * This method is not called in performance-critical code paths, only when a
63 * new render target or swapchain is created. Thus performance is not an issue
64 * here.
66 * Params:
67 * This: Device to add the context for
68 * hdc: device context
69 * glCtx: WGL context to add
70 * pbuffer: optional pbuffer used with this context
72 *****************************************************************************/
73 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
74 WineD3DContext **oldArray = This->contexts;
75 DWORD state;
77 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * (This->numContexts + 1));
78 if(This->contexts == NULL) {
79 ERR("Unable to grow the context array\n");
80 This->contexts = oldArray;
81 return NULL;
83 if(oldArray) {
84 memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
87 This->contexts[This->numContexts] = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WineD3DContext));
88 if(This->contexts[This->numContexts] == NULL) {
89 ERR("Unable to allocate a new context\n");
90 HeapFree(GetProcessHeap(), 0, This->contexts);
91 This->contexts = oldArray;
92 return NULL;
95 This->contexts[This->numContexts]->hdc = hdc;
96 This->contexts[This->numContexts]->glCtx = glCtx;
97 This->contexts[This->numContexts]->pbuffer = pbuffer;
98 This->contexts[This->numContexts]->win_handle = win_handle;
99 HeapFree(GetProcessHeap(), 0, oldArray);
101 /* Mark all states dirty to force a proper initialization of the states on the first use of the context
103 for(state = 0; state <= STATE_HIGHEST; state++) {
104 Context_MarkStateDirty(This->contexts[This->numContexts], state);
107 This->numContexts++;
108 TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
109 return This->contexts[This->numContexts - 1];
112 /*****************************************************************************
113 * CreateContext
115 * Creates a new context for a window, or a pbuffer context.
117 * * Params:
118 * This: Device to activate the context for
119 * target: Surface this context will render to
120 * win_handle: handle to the window which we are drawing to
121 * create_pbuffer: tells whether to create a pbuffer or not
122 * pPresentParameters: contains the pixelformats to use for onscreen rendering
124 *****************************************************************************/
125 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, HWND win_handle, BOOL create_pbuffer, const WINED3DPRESENT_PARAMETERS *pPresentParms) {
126 HDC oldDrawable, hdc;
127 HPBUFFERARB pbuffer = NULL;
128 HGLRC ctx = NULL, oldCtx;
129 WineD3DContext *ret = NULL;
130 int s;
132 TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
134 if(create_pbuffer) {
135 HDC hdc_parent = GetDC(win_handle);
136 int iPixelFormat = 0;
137 short red, green, blue, alphaBits, colorBits;
138 short depthBits, stencilBits;
140 IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
141 WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
143 int attribs[256];
144 int nAttribs = 0;
145 unsigned int nFormats;
147 #define PUSH1(att) attribs[nAttribs++] = (att);
148 #define PUSH2(att,value) attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);
150 /* Retrieve the specifications for the pixelformat from the backbuffer / stencilbuffer */
151 getColorBits(target->resource.format, &red, &green, &blue, &alphaBits, &colorBits);
152 getDepthStencilBits(StencilBufferFormat, &depthBits, &stencilBits);
153 PUSH2(WGL_DRAW_TO_PBUFFER_ARB, 1); /* We need pbuffer support; doublebuffering isn't needed */
154 PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
155 PUSH2(WGL_COLOR_BITS_ARB, colorBits);
156 PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
157 PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
158 PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
159 PUSH1(0); /* end the list */
161 #undef PUSH1
162 #undef PUSH2
164 /* Try to find a pixelformat that matches exactly. If that fails let ChoosePixelFormat try to find a close match */
165 if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc_parent, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
167 PIXELFORMATDESCRIPTOR pfd;
169 TRACE("Falling back to ChoosePixelFormat as wglChoosePixelFormatARB failed\n");
171 ZeroMemory(&pfd, sizeof(pfd));
172 pfd.nSize = sizeof(pfd);
173 pfd.nVersion = 1;
174 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER_DONTCARE | PFD_DRAW_TO_WINDOW;
175 pfd.iPixelType = PFD_TYPE_RGBA;
176 pfd.cColorBits = colorBits;
177 pfd.cDepthBits = depthBits;
178 pfd.cStencilBits = stencilBits;
179 pfd.iLayerType = PFD_MAIN_PLANE;
181 iPixelFormat = ChoosePixelFormat(hdc_parent, &pfd);
182 if(!iPixelFormat) {
183 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
184 ERR("Can't find a suitable iPixelFormat for the pbuffer\n");
188 TRACE("Creating a pBuffer drawable for the new context\n");
189 pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
190 if(!pbuffer) {
191 ERR("Cannot create a pbuffer\n");
192 ReleaseDC(win_handle, hdc_parent);
193 goto out;
196 /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
197 hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
198 if(!hdc) {
199 ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
200 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
201 ReleaseDC(win_handle, hdc_parent);
202 goto out;
204 ReleaseDC(win_handle, hdc_parent);
205 } else {
206 PIXELFORMATDESCRIPTOR pfd;
207 int iPixelFormat;
208 short red, green, blue, alpha;
209 short colorBits;
210 short depthBits, stencilBits;
211 int res;
213 hdc = GetDC(win_handle);
214 if(hdc == NULL) {
215 ERR("Cannot retrieve a device context!\n");
216 goto out;
219 /* PixelFormat selection */
220 /* TODO: fill cColorBits/cDepthBits with target->resource.format */
221 ZeroMemory(&pfd, sizeof(pfd));
222 pfd.nSize = sizeof(pfd);
223 pfd.nVersion = 1;
224 pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
225 pfd.iPixelType = PFD_TYPE_RGBA;
226 pfd.cColorBits = 32;
227 pfd.cDepthBits = 0;
228 pfd.cStencilBits = 0;
229 pfd.iLayerType = PFD_MAIN_PLANE;
231 /* Try to match the colorBits of the d3d format */
232 if(getColorBits(target->resource.format, &red, &green, &blue, &alpha, &colorBits))
233 pfd.cColorBits = colorBits;
235 /* Retrieve the depth stencil format from the present parameters.
236 * The choice of the proper format can give a nice performance boost
237 * in case of GPU limited programs. */
238 if(pPresentParms->EnableAutoDepthStencil) {
239 TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
240 if(getDepthStencilBits(pPresentParms->AutoDepthStencilFormat, &depthBits, &stencilBits)) {
241 pfd.cDepthBits = depthBits;
242 pfd.cStencilBits = stencilBits;
246 iPixelFormat = ChoosePixelFormat(hdc, &pfd);
247 if(!iPixelFormat) {
248 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
249 ERR("Can't find a suitable iPixelFormat\n");
252 DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
253 res = SetPixelFormat(hdc, iPixelFormat, NULL);
254 if(!res) {
255 int oldPixelFormat = GetPixelFormat(hdc);
257 if(oldPixelFormat) {
258 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
259 * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
260 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
262 else {
263 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
264 return FALSE;
269 ctx = wglCreateContext(hdc);
270 if(This->numContexts) wglShareLists(This->contexts[0]->glCtx, ctx);
272 if(!ctx) {
273 ERR("Failed to create a WGL context\n");
274 if(create_pbuffer) {
275 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
276 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
278 goto out;
280 ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
281 if(!ret) {
282 ERR("Failed to add the newly created context to the context list\n");
283 wglDeleteContext(ctx);
284 if(create_pbuffer) {
285 GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
286 GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
288 goto out;
290 ret->surface = (IWineD3DSurface *) target;
291 ret->isPBuffer = create_pbuffer;
292 ret->tid = GetCurrentThreadId();
294 TRACE("Successfully created new context %p\n", ret);
296 /* Set up the context defaults */
297 oldCtx = wglGetCurrentContext();
298 oldDrawable = wglGetCurrentDC();
299 if(wglMakeCurrent(hdc, ctx) == FALSE) {
300 ERR("Cannot activate context to set up defaults\n");
301 goto out;
304 TRACE("Setting up the screen\n");
305 /* Clear the screen */
306 glClearColor(1.0, 0.0, 0.0, 0.0);
307 checkGLcall("glClearColor");
308 glClearIndex(0);
309 glClearDepth(1);
310 glClearStencil(0xffff);
312 checkGLcall("glClear");
314 glColor3f(1.0, 1.0, 1.0);
315 checkGLcall("glColor3f");
317 glEnable(GL_LIGHTING);
318 checkGLcall("glEnable");
320 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
321 checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
323 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
324 checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
326 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
327 checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
329 glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
330 checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
331 glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
332 checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
334 if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
335 /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
336 * and textures in DIB sections(due to the memory protection).
338 glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
339 checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
341 if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
342 /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
343 * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
344 * GL_VERTEX_BLEND_ARB isn't enabled too
346 glEnable(GL_WEIGHT_SUM_UNITY_ARB);
347 checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
349 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
350 glEnable(GL_TEXTURE_SHADER_NV);
351 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
353 /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
354 * the previous texture where to source the offset from is always unit - 1.
356 for(s = 1; s < GL_LIMITS(textures); s++) {
357 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
358 glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
359 checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
362 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
363 for(s = 0; s < GL_LIMITS(textures); s++) {
364 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
365 glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
366 checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
370 if(oldDrawable && oldCtx) {
371 wglMakeCurrent(oldDrawable, oldCtx);
374 out:
375 return ret;
378 /*****************************************************************************
379 * RemoveContextFromArray
381 * Removes a context from the context manager. The opengl context is not
382 * destroyed or unset. context is not a valid pointer after that call.
384 * Similar to the former call this isn't a performance critical function. A
385 * helper function for DestroyContext.
387 * Params:
388 * This: Device to activate the context for
389 * context: Context to remove
391 *****************************************************************************/
392 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
393 UINT t, s;
394 WineD3DContext **oldArray = This->contexts;
396 TRACE("Removing ctx %p\n", context);
398 This->numContexts--;
400 if(This->numContexts) {
401 This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
402 if(!This->contexts) {
403 ERR("Cannot allocate a new context array, PANIC!!!\n");
405 t = 0;
406 for(s = 0; s < This->numContexts; s++) {
407 if(oldArray[s] == context) continue;
408 This->contexts[t] = oldArray[s];
409 t++;
411 } else {
412 This->contexts = NULL;
415 HeapFree(GetProcessHeap(), 0, context);
416 HeapFree(GetProcessHeap(), 0, oldArray);
419 /*****************************************************************************
420 * DestroyContext
422 * Destroys a wineD3DContext
424 * Params:
425 * This: Device to activate the context for
426 * context: Context to destroy
428 *****************************************************************************/
429 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
431 /* check that we are the current context first */
432 TRACE("Destroying ctx %p\n", context);
433 if(wglGetCurrentContext() == context->glCtx){
434 wglMakeCurrent(NULL, NULL);
437 if(context->isPBuffer) {
438 GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
439 GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
440 } else ReleaseDC(context->win_handle, context->hdc);
441 wglDeleteContext(context->glCtx);
443 RemoveContextFromArray(This, context);
446 /*****************************************************************************
447 * SetupForBlit
449 * Sets up a context for DirectDraw blitting.
450 * All texture units are disabled, except unit 0
451 * Texture unit 0 is activted where GL_TEXTURE_2D is activated
452 * fog, lighting, blending, alpha test, z test, scissor test, culling diabled
453 * color writing enabled for all channels
454 * register combiners disabled, shaders disabled
455 * world matris is set to identity, texture matrix 0 too
456 * projection matrix is setup for drawing screen coordinates
458 * Params:
459 * This: Device to activate the context for
460 * context: Context to setup
461 * width: render target width
462 * height: render target height
464 *****************************************************************************/
465 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
466 int i;
468 TRACE("Setting up context %p for blitting\n", context);
469 if(context->last_was_blit) {
470 TRACE("Context is already set up for blitting, nothing to do\n");
471 return;
473 context->last_was_blit = TRUE;
475 /* TODO: Use a display list */
477 /* Disable shaders */
478 This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
479 Context_MarkStateDirty(context, STATE_VSHADER);
480 Context_MarkStateDirty(context, STATE_PIXELSHADER);
482 /* Disable all textures. The caller can then bind a texture it wants to blit
483 * from
485 if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
486 glDisable(GL_REGISTER_COMBINERS_NV);
487 checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
489 if (GL_SUPPORT(ARB_MULTITEXTURE)) {
490 /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
491 * function texture unit. No need to care for higher samplers
493 for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
494 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
495 checkGLcall("glActiveTextureARB");
497 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
498 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
499 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
501 glDisable(GL_TEXTURE_3D);
502 checkGLcall("glDisable GL_TEXTURE_3D");
503 glDisable(GL_TEXTURE_2D);
504 checkGLcall("glDisable GL_TEXTURE_2D");
506 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
507 checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
509 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
510 Context_MarkStateDirty(context, STATE_SAMPLER(i));
512 GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
513 checkGLcall("glActiveTextureARB");
515 if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
516 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
517 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
519 glDisable(GL_TEXTURE_3D);
520 checkGLcall("glDisable GL_TEXTURE_3D");
521 glEnable(GL_TEXTURE_2D);
522 checkGLcall("glEnable GL_TEXTURE_2D");
524 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
526 glMatrixMode(GL_TEXTURE);
527 checkGLcall("glMatrixMode(GL_TEXTURE)");
528 glLoadIdentity();
529 checkGLcall("glLoadIdentity()");
530 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0));
532 if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
533 glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
534 GL_TEXTURE_LOD_BIAS_EXT,
535 0.0);
536 checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
538 Context_MarkStateDirty(context, STATE_SAMPLER(0));
539 Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP));
541 /* Other misc states */
542 glDisable(GL_ALPHA_TEST);
543 checkGLcall("glDisable(GL_ALPHA_TEST)");
544 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE));
545 glDisable(GL_LIGHTING);
546 checkGLcall("glDisable GL_LIGHTING");
547 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING));
548 glDisable(GL_DEPTH_TEST);
549 checkGLcall("glDisable GL_DEPTH_TEST");
550 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE));
551 glDisable(GL_FOG);
552 checkGLcall("glDisable GL_FOG");
553 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE));
554 glDisable(GL_BLEND);
555 checkGLcall("glDisable GL_BLEND");
556 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
557 glDisable(GL_CULL_FACE);
558 checkGLcall("glDisable GL_CULL_FACE");
559 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE));
560 glDisable(GL_STENCIL_TEST);
561 checkGLcall("glDisable GL_STENCIL_TEST");
562 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE));
563 if(GL_SUPPORT(ARB_POINT_SPRITE)) {
564 glDisable(GL_POINT_SPRITE_ARB);
565 checkGLcall("glDisable GL_POINT_SPRITE_ARB");
566 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE));
568 glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
569 checkGLcall("glColorMask");
570 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
572 /* Setup transforms */
573 glMatrixMode(GL_MODELVIEW);
574 checkGLcall("glMatrixMode(GL_MODELVIEW)");
575 glLoadIdentity();
576 checkGLcall("glLoadIdentity()");
577 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)));
579 glMatrixMode(GL_PROJECTION);
580 checkGLcall("glMatrixMode(GL_PROJECTION)");
581 glLoadIdentity();
582 checkGLcall("glLoadIdentity()");
583 glOrtho(0, width, height, 0, 0.0, -1.0);
584 checkGLcall("glOrtho");
585 Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION));
587 context->last_was_rhw = TRUE;
588 Context_MarkStateDirty(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
590 glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
591 glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
592 glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
593 glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
594 glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
595 glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
596 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
598 glViewport(0, 0, width, height);
599 checkGLcall("glViewport");
600 Context_MarkStateDirty(context, STATE_VIEWPORT);
602 if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
603 glDisable(GL_TEXTURE_SHADER_NV);
604 checkGLcall("glDisable(GL_TEXTURE_SHADER_NV)");
608 /*****************************************************************************
609 * findThreadContextForSwapChain
611 * Searches a swapchain for all contexts and picks one for the thread tid.
612 * If none can be found the swapchain is requested to create a new context
614 *****************************************************************************/
615 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
616 int i;
618 for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
619 if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
620 return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
625 /* Create a new context for the thread */
626 return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
629 /*****************************************************************************
630 * FindContext
632 * Finds a context for the current render target and thread
634 * Parameters:
635 * target: Render target to find the context for
636 * tid: Thread to activate the context for
638 * Returns: The needed context
640 *****************************************************************************/
641 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid) {
642 IWineD3DSwapChain *swapchain = NULL;
643 HRESULT hr;
644 BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
645 WineD3DContext *context = This->activeContext;
646 BOOL oldRenderOffscreen = This->render_offscreen;
648 hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
649 if(hr == WINED3D_OK && swapchain) {
650 TRACE("Rendering onscreen\n");
652 context = findThreadContextForSwapChain(swapchain, tid);
654 This->render_offscreen = FALSE;
655 /* The context != This->activeContext will catch a NOP context change. This can occur
656 * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
657 * rendering. No context change is needed in that case
660 if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
661 if(((IWineD3DSwapChainImpl *) swapchain)->backBuffer) {
662 glDrawBuffer(GL_BACK);
663 checkGLcall("glDrawBuffer(GL_BACK)");
664 } else {
665 glDrawBuffer(GL_FRONT);
666 checkGLcall("glDrawBuffer(GL_FRONT)");
668 } else if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
669 if(This->pbufferContext && tid == This->pbufferContext->tid) {
670 This->pbufferContext->tid = 0;
673 IWineD3DSwapChain_Release(swapchain);
675 if(oldRenderOffscreen) {
676 Context_MarkStateDirty(context, WINED3DRS_CULLMODE);
677 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
678 Context_MarkStateDirty(context, STATE_VDECL);
679 Context_MarkStateDirty(context, STATE_VIEWPORT);
680 Context_MarkStateDirty(context, STATE_SCISSORRECT);
683 } else {
684 TRACE("Rendering offscreen\n");
685 This->render_offscreen = TRUE;
687 switch(wined3d_settings.offscreen_rendering_mode) {
688 case ORM_FBO:
689 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
690 if(This->activeContext && tid == This->lastThread) {
691 context = This->activeContext;
692 } else {
693 /* This may happen if the app jumps streight into offscreen rendering
694 * Start using the context of the primary swapchain. tid == 0 is no problem
695 * for findThreadContextForSwapChain.
697 * Can also happen on thread switches - in that case findThreadContextForSwapChain
698 * is perfect to call.
700 context = findThreadContextForSwapChain(This->swapchains[0], tid);
702 break;
704 case ORM_PBUFFER:
706 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
707 if(This->pbufferContext == NULL ||
708 This->pbufferWidth < targetimpl->currentDesc.Width ||
709 This->pbufferHeight < targetimpl->currentDesc.Height) {
710 if(This->pbufferContext) {
711 DestroyContext(This, This->pbufferContext);
714 /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
715 * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
717 This->pbufferContext = CreateContext(This, targetimpl,
718 ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
719 TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
720 This->pbufferWidth = targetimpl->currentDesc.Width;
721 This->pbufferHeight = targetimpl->currentDesc.Height;
724 if(This->pbufferContext) {
725 if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
726 FIXME("The PBuffr context is only supported for one thread for now!\n");
728 This->pbufferContext->tid = tid;
729 context = This->pbufferContext;
730 break;
731 } else {
732 ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
733 wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
737 case ORM_BACKBUFFER:
738 /* Stay with the currently active context for back buffer rendering */
739 if(This->activeContext && tid == This->lastThread) {
740 context = This->activeContext;
741 } else {
742 /* This may happen if the app jumps streight into offscreen rendering
743 * Start using the context of the primary swapchain. tid == 0 is no problem
744 * for findThreadContextForSwapChain.
746 * Can also happen on thread switches - in that case findThreadContextForSwapChain
747 * is perfect to call.
749 context = findThreadContextForSwapChain(This->swapchains[0], tid);
751 glDrawBuffer(This->offscreenBuffer);
752 checkGLcall("glDrawBuffer(This->offscreenBuffer)");
753 break;
756 if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
757 /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
758 * back when we are done won't mark us dirty.
760 IWineD3DSurface_PreLoad(target);
763 if(!oldRenderOffscreen) {
764 Context_MarkStateDirty(context, WINED3DRS_CULLMODE);
765 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
766 Context_MarkStateDirty(context, STATE_VDECL);
767 Context_MarkStateDirty(context, STATE_VIEWPORT);
768 Context_MarkStateDirty(context, STATE_SCISSORRECT);
771 if (readTexture) {
772 BOOL oldInDraw = This->isInDraw;
774 /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
775 * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
776 * when using offscreen rendering with multithreading
778 This->isInDraw = TRUE;
780 /* Do that before switching the context:
781 * Read the back buffer of the old drawable into the destination texture
783 IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
785 /* Assume that the drawable will be modified by some other things now */
786 ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->Flags &= ~SFLAG_INDRAWABLE;
788 This->isInDraw = oldInDraw;
791 if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
792 This->depth_copy_state = WINED3D_DCS_COPY;
794 return context;
797 /*****************************************************************************
798 * ActivateContext
800 * Finds a rendering context and drawable matching the device and render
801 * target for the current thread, activates them and puts them into the
802 * requested state.
804 * Params:
805 * This: Device to activate the context for
806 * target: Requested render target
807 * usage: Prepares the context for blitting, drawing or other actions
809 *****************************************************************************/
810 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
811 DWORD tid = GetCurrentThreadId();
812 int i;
813 DWORD dirtyState, idx;
814 BYTE shift;
815 WineD3DContext *context;
817 TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
819 ENTER_GL();
820 if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
821 context = FindContext(This, target, tid);
822 This->lastActiveRenderTarget = target;
823 This->lastThread = tid;
824 } else {
825 /* Stick to the old context */
826 context = This->activeContext;
829 /* Activate the opengl context */
830 if(context != This->activeContext) {
831 BOOL ret;
832 TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
833 LEAVE_GL();
834 ret = wglMakeCurrent(context->hdc, context->glCtx);
835 ENTER_GL();
836 if(ret == FALSE) {
837 ERR("Failed to activate the new context\n");
839 This->activeContext = context;
842 switch(usage) {
843 case CTXUSAGE_RESOURCELOAD:
844 /* This does not require any special states to be set up */
845 break;
847 case CTXUSAGE_CLEAR:
848 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
849 glEnable(GL_TEXTURE_SHADER_NV);
850 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
853 glEnable(GL_SCISSOR_TEST);
854 checkGLcall("glEnable GL_SCISSOR_TEST");
855 context->last_was_blit = FALSE;
856 Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
857 Context_MarkStateDirty(context, STATE_SCISSORRECT);
858 break;
860 case CTXUSAGE_DRAWPRIM:
861 /* This needs all dirty states applied */
862 if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
863 glEnable(GL_TEXTURE_SHADER_NV);
864 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
867 IWineD3DDeviceImpl_FindTexUnitMap(This);
869 for(i=0; i < context->numDirtyEntries; i++) {
870 dirtyState = context->dirtyArray[i];
871 idx = dirtyState >> 5;
872 shift = dirtyState & 0x1f;
873 context->isStateDirty[idx] &= ~(1 << shift);
874 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
876 context->numDirtyEntries = 0; /* This makes the whole list clean */
877 context->last_was_blit = FALSE;
878 break;
880 case CTXUSAGE_BLIT:
881 SetupForBlit(This, context,
882 ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
883 ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
884 break;
886 default:
887 FIXME("Unexpected context usage requested\n");
889 LEAVE_GL();