quartz: Silence requests for ipin on filters.
[wine] / dlls / wined3d / context.c
1 /*
2  * Context and render target management in wined3d
3  *
4  * Copyright 2007 Stefan Dösinger for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include <stdio.h>
23 #ifdef HAVE_FLOAT_H
24 # include <float.h>
25 #endif
26 #include "wined3d_private.h"
27
28 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
29
30 #define GLINFO_LOCATION This->adapter->gl_info
31
32 /*****************************************************************************
33  * Context_MarkStateDirty
34  *
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
38  *
39  * Params:
40  *  context: Context to mark the state dirty in
41  *  state: State to mark dirty
42  *
43  *****************************************************************************/
44 static void Context_MarkStateDirty(WineD3DContext *context, DWORD state) {
45     DWORD rep = StateTable[state].representative;
46     DWORD idx;
47     BYTE shift;
48
49     if(!rep || isStateDirty(context, rep)) return;
50
51     context->dirtyArray[context->numDirtyEntries++] = rep;
52     idx = rep >> 5;
53     shift = rep & 0x1f;
54     context->isStateDirty[idx] |= (1 << shift);
55 }
56
57 /*****************************************************************************
58  * AddContextToArray
59  *
60  * Adds a context to the context array. Helper function for CreateContext
61  *
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.
65  *
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
71  *
72  *****************************************************************************/
73 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, HWND win_handle, HDC hdc, HGLRC glCtx, HPBUFFERARB pbuffer) {
74     WineD3DContext **oldArray = This->contexts;
75     DWORD state;
76
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;
82     }
83     if(oldArray) {
84         memcpy(This->contexts, oldArray, sizeof(*This->contexts) * This->numContexts);
85     }
86
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;
93     }
94
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);
100
101     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
102      */
103     for(state = 0; state <= STATE_HIGHEST; state++) {
104         Context_MarkStateDirty(This->contexts[This->numContexts], state);
105     }
106
107     This->numContexts++;
108     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
109     return This->contexts[This->numContexts - 1];
110 }
111
112 /*****************************************************************************
113  * CreateContext
114  *
115  * Creates a new context for a window, or a pbuffer context.
116  *
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
123  *
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;
131
132     TRACE("(%p): Creating a %s context for render target %p\n", This, create_pbuffer ? "offscreen" : "onscreen", target);
133
134 #define PUSH1(att)        attribs[nAttribs++] = (att);
135 #define PUSH2(att,value)  attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);
136     if(create_pbuffer) {
137         HDC hdc_parent = GetDC(win_handle);
138         int iPixelFormat = 0;
139         short redBits, greenBits, blueBits, alphaBits, colorBits;
140         short depthBits, stencilBits;
141
142         IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
143         WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
144
145         int attribs[256];
146         int nAttribs = 0;
147         unsigned int nFormats;
148
149         /* Retrieve the specifications for the pixelformat from the backbuffer / stencilbuffer */
150         getColorBits(target->resource.format, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits);
151         getDepthStencilBits(StencilBufferFormat, &depthBits, &stencilBits);
152         PUSH2(WGL_DRAW_TO_PBUFFER_ARB, 1); /* We need pbuffer support; doublebuffering isn't needed */
153         PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
154         PUSH2(WGL_COLOR_BITS_ARB, colorBits);
155         PUSH2(WGL_RED_BITS_ARB, redBits);
156         PUSH2(WGL_GREEN_BITS_ARB, greenBits);
157         PUSH2(WGL_BLUE_BITS_ARB, blueBits);
158         PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
159         PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
160         PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
161         PUSH1(0); /* end the list */
162
163         /* Try to find a pixelformat that matches exactly. If that fails let ChoosePixelFormat try to find a close match */
164         if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc_parent, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
165         {
166             PIXELFORMATDESCRIPTOR pfd;
167
168             TRACE("Falling back to ChoosePixelFormat as wglChoosePixelFormatARB failed\n");
169
170             ZeroMemory(&pfd, sizeof(pfd));
171             pfd.nSize      = sizeof(pfd);
172             pfd.nVersion   = 1;
173             pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER_DONTCARE | PFD_DRAW_TO_WINDOW;
174             pfd.iPixelType = PFD_TYPE_RGBA;
175             pfd.cColorBits = colorBits;
176             pfd.cDepthBits = depthBits;
177             pfd.cStencilBits = stencilBits;
178             pfd.iLayerType = PFD_MAIN_PLANE;
179
180             iPixelFormat = ChoosePixelFormat(hdc_parent, &pfd);
181             if(!iPixelFormat) {
182                 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
183                 ERR("Can't find a suitable iPixelFormat for the pbuffer\n");
184             }
185         }
186
187         TRACE("Creating a pBuffer drawable for the new context\n");
188         pbuffer = GL_EXTCALL(wglCreatePbufferARB(hdc_parent, iPixelFormat, target->currentDesc.Width, target->currentDesc.Height, 0));
189         if(!pbuffer) {
190             ERR("Cannot create a pbuffer\n");
191             ReleaseDC(win_handle, hdc_parent);
192             goto out;
193         }
194
195         /* In WGL a pbuffer is 'wrapped' inside a HDC to 'fool' wglMakeCurrent */
196         hdc = GL_EXTCALL(wglGetPbufferDCARB(pbuffer));
197         if(!hdc) {
198             ERR("Cannot get a HDC for pbuffer (%p)\n", pbuffer);
199             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
200             ReleaseDC(win_handle, hdc_parent);
201             goto out;
202         }
203         ReleaseDC(win_handle, hdc_parent);
204     } else {
205         PIXELFORMATDESCRIPTOR pfd;
206         int iPixelFormat;
207         short redBits, greenBits, blueBits, alphaBits, colorBits;
208         short depthBits=0, stencilBits=0;
209         int res;
210         int attribs[256];
211         int nAttribs = 0;
212         unsigned int nFormats;
213         WINED3DFORMAT fmt = target->resource.format;
214
215         hdc = GetDC(win_handle);
216         if(hdc == NULL) {
217             ERR("Cannot retrieve a device context!\n");
218             goto out;
219         }
220
221         /* PixelFormat selection */
222         PUSH2(WGL_DRAW_TO_WINDOW_ARB, GL_TRUE); /* We want to draw to a window */
223         PUSH2(WGL_DOUBLE_BUFFER_ARB, GL_TRUE);
224         PUSH2(WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB); /* Make sure we don't get a float or color index format */
225         PUSH2(WGL_SUPPORT_OPENGL_ARB, GL_TRUE);
226         PUSH2(WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB); /* Make sure we receive an accelerated format. On windows (at least on ATI) this is not always the case */
227
228         /* In case of ORM_BACKBUFFER, make sure to request an alpha component for X4R4G4B4/X8R8G8B8 as we might need it for the backbuffer. */
229         if(wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
230             if(target->resource.format == WINED3DFMT_X4R4G4B4)
231                 fmt = WINED3DFMT_A4R4G4B4;
232             else if(target->resource.format == WINED3DFMT_X8R8G8B8)
233                 fmt = WINED3DFMT_A8R8G8B8;
234
235             /* We like to have two aux buffers in backbuffer mode */
236             PUSH2(WGL_AUX_BUFFERS_ARB, 2);
237         }
238
239         if(!getColorBits(fmt, &redBits, &greenBits, &blueBits, &alphaBits, &colorBits)) {
240             ERR("Unable to get color bits for format %#x!\n", target->resource.format);
241             return FALSE;
242         }
243         PUSH2(WGL_COLOR_BITS_ARB, colorBits);
244         PUSH2(WGL_RED_BITS_ARB, redBits);
245         PUSH2(WGL_GREEN_BITS_ARB, greenBits);
246         PUSH2(WGL_BLUE_BITS_ARB, blueBits);
247         PUSH2(WGL_ALPHA_BITS_ARB, alphaBits);
248
249         /* Retrieve the depth stencil format from the present parameters.
250          * The choice of the proper format can give a nice performance boost
251          * in case of GPU limited programs. */
252         if(pPresentParms->EnableAutoDepthStencil) {
253             TRACE("pPresentParms->EnableAutoDepthStencil=enabled; using AutoDepthStencilFormat=%s\n", debug_d3dformat(pPresentParms->AutoDepthStencilFormat));
254             if(!getDepthStencilBits(pPresentParms->AutoDepthStencilFormat, &depthBits, &stencilBits)) {
255                 ERR("Unable to get depth / stencil bits for AutoDepthStencilFormat %#x!\n", pPresentParms->AutoDepthStencilFormat);
256                 return FALSE;
257             }
258             PUSH2(WGL_DEPTH_BITS_ARB, depthBits);
259             PUSH2(WGL_STENCIL_BITS_ARB, stencilBits);
260         }
261
262         PUSH1(0); /* end the list */
263
264         /* In case of failure hope that standard ChoosePixelFormat will find something suitable */
265         if(!GL_EXTCALL(wglChoosePixelFormatARB(hdc, (const int*)&attribs, NULL, 1, &iPixelFormat, &nFormats)))
266         {
267             /* PixelFormat selection */
268             ZeroMemory(&pfd, sizeof(pfd));
269             pfd.nSize      = sizeof(pfd);
270             pfd.nVersion   = 1;
271             pfd.dwFlags    = PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW;/*PFD_GENERIC_ACCELERATED*/
272             pfd.iPixelType = PFD_TYPE_RGBA;
273             pfd.cAlphaBits = alphaBits;
274             pfd.cColorBits = colorBits;
275             pfd.cDepthBits = depthBits;
276             pfd.cStencilBits = stencilBits;
277             pfd.iLayerType = PFD_MAIN_PLANE;
278
279             iPixelFormat = ChoosePixelFormat(hdc, &pfd);
280             if(!iPixelFormat) {
281                 /* If this happens something is very wrong as ChoosePixelFormat barely fails */
282                 ERR("Can't find a suitable iPixelFormat\n");
283             }
284         }
285
286         DescribePixelFormat(hdc, iPixelFormat, sizeof(pfd), &pfd);
287         res = SetPixelFormat(hdc, iPixelFormat, NULL);
288         if(!res) {
289             int oldPixelFormat = GetPixelFormat(hdc);
290
291             if(oldPixelFormat) {
292                 /* OpenGL doesn't allow pixel format adjustments. Print an error and continue using the old format.
293                  * There's a big chance that the old format works although with a performance hit and perhaps rendering errors. */
294                 ERR("HDC=%p is already set to iPixelFormat=%d and OpenGL doesn't allow changes!\n", hdc, oldPixelFormat);
295             }
296             else {
297                 ERR("SetPixelFormat failed on HDC=%p for iPixelFormat=%d\n", hdc, iPixelFormat);
298                 return FALSE;
299             }
300         }
301     }
302 #undef PUSH1
303 #undef PUSH2
304
305     ctx = pwglCreateContext(hdc);
306     if(This->numContexts) pwglShareLists(This->contexts[0]->glCtx, ctx);
307
308     if(!ctx) {
309         ERR("Failed to create a WGL context\n");
310         if(create_pbuffer) {
311             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
312             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
313         }
314         goto out;
315     }
316     ret = AddContextToArray(This, win_handle, hdc, ctx, pbuffer);
317     if(!ret) {
318         ERR("Failed to add the newly created context to the context list\n");
319         pwglDeleteContext(ctx);
320         if(create_pbuffer) {
321             GL_EXTCALL(wglReleasePbufferDCARB(pbuffer, hdc));
322             GL_EXTCALL(wglDestroyPbufferARB(pbuffer));
323         }
324         goto out;
325     }
326     ret->surface = (IWineD3DSurface *) target;
327     ret->isPBuffer = create_pbuffer;
328     ret->tid = GetCurrentThreadId();
329     if(This->shader_backend->shader_dirtifyable_constants((IWineD3DDevice *) This)) {
330         /* Create the dirty constants array and initialize them to dirty */
331         ret->vshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
332                 sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
333         ret->pshader_const_dirty = HeapAlloc(GetProcessHeap(), 0,
334                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
335         memset(ret->vshader_const_dirty, 1,
336                sizeof(*ret->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
337         memset(ret->pshader_const_dirty, 1,
338                 sizeof(*ret->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
339     }
340
341     TRACE("Successfully created new context %p\n", ret);
342
343     /* Set up the context defaults */
344     oldCtx  = pwglGetCurrentContext();
345     oldDrawable = pwglGetCurrentDC();
346     if(pwglMakeCurrent(hdc, ctx) == FALSE) {
347         ERR("Cannot activate context to set up defaults\n");
348         goto out;
349     }
350
351     ENTER_GL();
352     TRACE("Setting up the screen\n");
353     /* Clear the screen */
354     glClearColor(1.0, 0.0, 0.0, 0.0);
355     checkGLcall("glClearColor");
356     glClearIndex(0);
357     glClearDepth(1);
358     glClearStencil(0xffff);
359
360     checkGLcall("glClear");
361
362     glColor3f(1.0, 1.0, 1.0);
363     checkGLcall("glColor3f");
364
365     glEnable(GL_LIGHTING);
366     checkGLcall("glEnable");
367
368     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
369     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
370
371     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
372     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
373
374     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
375     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
376
377     glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);
378     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, This->surface_alignment);");
379     glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);
380     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, This->surface_alignment);");
381
382     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
383         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
384          * and textures in DIB sections(due to the memory protection).
385          */
386         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
387         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
388     }
389     if(GL_SUPPORT(ARB_VERTEX_BLEND)) {
390         /* Direct3D always uses n-1 weights for n world matrices and uses 1 - sum for the last one
391          * this is equal to GL_WEIGHT_SUM_UNITY_ARB. Enabling it doesn't do anything unless
392          * GL_VERTEX_BLEND_ARB isn't enabled too
393          */
394         glEnable(GL_WEIGHT_SUM_UNITY_ARB);
395         checkGLcall("glEnable(GL_WEIGHT_SUM_UNITY_ARB)");
396     }
397     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
398         glEnable(GL_TEXTURE_SHADER_NV);
399         checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
400
401         /* Set up the previous texture input for all shader units. This applies to bump mapping, and in d3d
402          * the previous texture where to source the offset from is always unit - 1.
403          */
404         for(s = 1; s < GL_LIMITS(textures); s++) {
405             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
406             glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + s - 1);
407             checkGLcall("glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, ...\n");
408         }
409     }
410     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
411         for(s = 0; s < GL_LIMITS(textures); s++) {
412             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + s));
413             glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
414             checkGLcall("glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE)\n");
415         }
416     }
417     LEAVE_GL();
418
419     if(oldDrawable && oldCtx) {
420         pwglMakeCurrent(oldDrawable, oldCtx);
421     }
422
423 out:
424     return ret;
425 }
426
427 /*****************************************************************************
428  * RemoveContextFromArray
429  *
430  * Removes a context from the context manager. The opengl context is not
431  * destroyed or unset. context is not a valid pointer after that call.
432  *
433  * Similar to the former call this isn't a performance critical function. A
434  * helper function for DestroyContext.
435  *
436  * Params:
437  *  This: Device to activate the context for
438  *  context: Context to remove
439  *
440  *****************************************************************************/
441 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
442     UINT t, s;
443     WineD3DContext **oldArray = This->contexts;
444
445     TRACE("Removing ctx %p\n", context);
446
447     This->numContexts--;
448
449     if(This->numContexts) {
450         This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
451         if(!This->contexts) {
452             ERR("Cannot allocate a new context array, PANIC!!!\n");
453         }
454         t = 0;
455         for(s = 0; s < This->numContexts; s++) {
456             if(oldArray[s] == context) continue;
457             This->contexts[t] = oldArray[s];
458             t++;
459         }
460     } else {
461         This->contexts = NULL;
462     }
463
464     HeapFree(GetProcessHeap(), 0, context);
465     HeapFree(GetProcessHeap(), 0, oldArray);
466 }
467
468 /*****************************************************************************
469  * DestroyContext
470  *
471  * Destroys a wineD3DContext
472  *
473  * Params:
474  *  This: Device to activate the context for
475  *  context: Context to destroy
476  *
477  *****************************************************************************/
478 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
479
480     /* check that we are the current context first */
481     TRACE("Destroying ctx %p\n", context);
482     if(pwglGetCurrentContext() == context->glCtx){
483         pwglMakeCurrent(NULL, NULL);
484     }
485
486     if(context->isPBuffer) {
487         GL_EXTCALL(wglReleasePbufferDCARB(context->pbuffer, context->hdc));
488         GL_EXTCALL(wglDestroyPbufferARB(context->pbuffer));
489     } else ReleaseDC(context->win_handle, context->hdc);
490     pwglDeleteContext(context->glCtx);
491
492     HeapFree(GetProcessHeap(), 0, context->vshader_const_dirty);
493     HeapFree(GetProcessHeap(), 0, context->pshader_const_dirty);
494     RemoveContextFromArray(This, context);
495 }
496
497 /*****************************************************************************
498  * SetupForBlit
499  *
500  * Sets up a context for DirectDraw blitting.
501  * All texture units are disabled, texture unit 0 is set as current unit
502  * fog, lighting, blending, alpha test, z test, scissor test, culling disabled
503  * color writing enabled for all channels
504  * register combiners disabled, shaders disabled
505  * world matrix is set to identity, texture matrix 0 too
506  * projection matrix is setup for drawing screen coordinates
507  *
508  * Params:
509  *  This: Device to activate the context for
510  *  context: Context to setup
511  *  width: render target width
512  *  height: render target height
513  *
514  *****************************************************************************/
515 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
516     int i;
517
518     TRACE("Setting up context %p for blitting\n", context);
519     if(context->last_was_blit) {
520         TRACE("Context is already set up for blitting, nothing to do\n");
521         return;
522     }
523     context->last_was_blit = TRUE;
524
525     /* TODO: Use a display list */
526
527     /* Disable shaders */
528     This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
529     Context_MarkStateDirty(context, STATE_VSHADER);
530     Context_MarkStateDirty(context, STATE_PIXELSHADER);
531
532     /* Disable all textures. The caller can then bind a texture it wants to blit
533      * from
534      */
535     if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
536         glDisable(GL_REGISTER_COMBINERS_NV);
537         checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
538     }
539     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
540         /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
541          * function texture unit. No need to care for higher samplers
542          */
543         for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
544             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
545             checkGLcall("glActiveTextureARB");
546
547             if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
548                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
549                 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
550             }
551             glDisable(GL_TEXTURE_3D);
552             checkGLcall("glDisable GL_TEXTURE_3D");
553             glDisable(GL_TEXTURE_2D);
554             checkGLcall("glDisable GL_TEXTURE_2D");
555
556             glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
557             checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
558
559             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
560             Context_MarkStateDirty(context, STATE_SAMPLER(i));
561         }
562         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
563         checkGLcall("glActiveTextureARB");
564     }
565     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
566         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
567         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
568     }
569     glDisable(GL_TEXTURE_3D);
570     checkGLcall("glDisable GL_TEXTURE_3D");
571     glDisable(GL_TEXTURE_2D);
572     checkGLcall("glDisable GL_TEXTURE_2D");
573
574     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
575
576     glMatrixMode(GL_TEXTURE);
577     checkGLcall("glMatrixMode(GL_TEXTURE)");
578     glLoadIdentity();
579     checkGLcall("glLoadIdentity()");
580     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0));
581
582     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
583         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
584                   GL_TEXTURE_LOD_BIAS_EXT,
585                   0.0);
586         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
587     }
588     Context_MarkStateDirty(context, STATE_SAMPLER(0));
589     Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP));
590
591     /* Other misc states */
592     glDisable(GL_ALPHA_TEST);
593     checkGLcall("glDisable(GL_ALPHA_TEST)");
594     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE));
595     glDisable(GL_LIGHTING);
596     checkGLcall("glDisable GL_LIGHTING");
597     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING));
598     glDisable(GL_DEPTH_TEST);
599     checkGLcall("glDisable GL_DEPTH_TEST");
600     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE));
601     glDisable(GL_FOG);
602     checkGLcall("glDisable GL_FOG");
603     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE));
604     glDisable(GL_BLEND);
605     checkGLcall("glDisable GL_BLEND");
606     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
607     glDisable(GL_CULL_FACE);
608     checkGLcall("glDisable GL_CULL_FACE");
609     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE));
610     glDisable(GL_STENCIL_TEST);
611     checkGLcall("glDisable GL_STENCIL_TEST");
612     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE));
613     glDisable(GL_SCISSOR_TEST);
614     checkGLcall("glDisable GL_SCISSOR_TEST");
615     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
616     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
617         glDisable(GL_POINT_SPRITE_ARB);
618         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
619         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE));
620     }
621     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
622     checkGLcall("glColorMask");
623     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
624     if (GL_SUPPORT(EXT_SECONDARY_COLOR)) {
625         glDisable(GL_COLOR_SUM_EXT);
626         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
627         checkGLcall("glDisable(GL_COLOR_SUM_EXT)");
628     }
629     if (GL_SUPPORT(NV_REGISTER_COMBINERS)) {
630         GL_EXTCALL(glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB));
631         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SPECULARENABLE));
632         checkGLcall("glFinalCombinerInputNV");
633     }
634
635     /* Setup transforms */
636     glMatrixMode(GL_MODELVIEW);
637     checkGLcall("glMatrixMode(GL_MODELVIEW)");
638     glLoadIdentity();
639     checkGLcall("glLoadIdentity()");
640     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)));
641
642     glMatrixMode(GL_PROJECTION);
643     checkGLcall("glMatrixMode(GL_PROJECTION)");
644     glLoadIdentity();
645     checkGLcall("glLoadIdentity()");
646     glOrtho(0, width, height, 0, 0.0, -1.0);
647     checkGLcall("glOrtho");
648     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION));
649
650     context->last_was_rhw = TRUE;
651     Context_MarkStateDirty(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
652
653     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
654     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
655     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
656     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
657     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
658     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
659     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
660
661     glViewport(0, 0, width, height);
662     checkGLcall("glViewport");
663     Context_MarkStateDirty(context, STATE_VIEWPORT);
664
665     if(GL_SUPPORT(NV_TEXTURE_SHADER2)) {
666         glDisable(GL_TEXTURE_SHADER_NV);
667         checkGLcall("glDisable(GL_TEXTURE_SHADER_NV)");
668     }
669 }
670
671 /*****************************************************************************
672  * findThreadContextForSwapChain
673  *
674  * Searches a swapchain for all contexts and picks one for the thread tid.
675  * If none can be found the swapchain is requested to create a new context
676  *
677  *****************************************************************************/
678 static WineD3DContext *findThreadContextForSwapChain(IWineD3DSwapChain *swapchain, DWORD tid) {
679     int i;
680
681     for(i = 0; i < ((IWineD3DSwapChainImpl *) swapchain)->num_contexts; i++) {
682         if(((IWineD3DSwapChainImpl *) swapchain)->context[i]->tid == tid) {
683             return ((IWineD3DSwapChainImpl *) swapchain)->context[i];
684         }
685
686     }
687
688     /* Create a new context for the thread */
689     return IWineD3DSwapChainImpl_CreateContextForThread(swapchain);
690 }
691
692 /*****************************************************************************
693  * FindContext
694  *
695  * Finds a context for the current render target and thread
696  *
697  * Parameters:
698  *  target: Render target to find the context for
699  *  tid: Thread to activate the context for
700  *
701  * Returns: The needed context
702  *
703  *****************************************************************************/
704 static inline WineD3DContext *FindContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, DWORD tid, GLint *buffer) {
705     IWineD3DSwapChain *swapchain = NULL;
706     HRESULT hr;
707     BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
708     WineD3DContext *context = This->activeContext;
709     BOOL oldRenderOffscreen = This->render_offscreen;
710     const WINED3DFORMAT oldFmt = ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->resource.format;
711     const WINED3DFORMAT newFmt = ((IWineD3DSurfaceImpl *) target)->resource.format;
712
713     /* To compensate the lack of format switching with some offscreen rendering methods and on onscreen buffers
714      * the alpha blend state changes with different render target formats
715      */
716     if(oldFmt != newFmt) {
717         const StaticPixelFormatDesc *old = getFormatDescEntry(oldFmt, NULL, NULL);
718         const StaticPixelFormatDesc *new = getFormatDescEntry(oldFmt, NULL, NULL);
719
720         if((old->alphaMask && !new->alphaMask) || (!old->alphaMask && new->alphaMask)) {
721             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
722         }
723     }
724
725     hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
726     if(hr == WINED3D_OK && swapchain) {
727         TRACE("Rendering onscreen\n");
728
729         context = findThreadContextForSwapChain(swapchain, tid);
730
731         This->render_offscreen = FALSE;
732         /* The context != This->activeContext will catch a NOP context change. This can occur
733          * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
734          * rendering. No context change is needed in that case
735          */
736
737         if(((IWineD3DSwapChainImpl *) swapchain)->frontBuffer == target) {
738             *buffer = GL_FRONT;
739         } else {
740             *buffer = GL_BACK;
741         }
742         if(wined3d_settings.offscreen_rendering_mode == ORM_PBUFFER) {
743             if(This->pbufferContext && tid == This->pbufferContext->tid) {
744                 This->pbufferContext->tid = 0;
745             }
746         }
747         IWineD3DSwapChain_Release(swapchain);
748
749         if(oldRenderOffscreen) {
750             Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
751             Context_MarkStateDirty(context, STATE_VDECL);
752             Context_MarkStateDirty(context, STATE_VIEWPORT);
753             Context_MarkStateDirty(context, STATE_SCISSORRECT);
754             Context_MarkStateDirty(context, STATE_FRONTFACE);
755         }
756
757     } else {
758         TRACE("Rendering offscreen\n");
759         This->render_offscreen = TRUE;
760         *buffer = This->offscreenBuffer;
761
762         switch(wined3d_settings.offscreen_rendering_mode) {
763             case ORM_FBO:
764                 /* FBOs do not need a different context. Stay with whatever context is active at the moment */
765                 if(This->activeContext && tid == This->lastThread) {
766                     context = This->activeContext;
767                 } else {
768                     /* This may happen if the app jumps straight into offscreen rendering
769                      * Start using the context of the primary swapchain. tid == 0 is no problem
770                      * for findThreadContextForSwapChain.
771                      *
772                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
773                      * is perfect to call.
774                      */
775                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
776                 }
777                 break;
778
779             case ORM_PBUFFER:
780             {
781                 IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
782                 if(This->pbufferContext == NULL ||
783                    This->pbufferWidth < targetimpl->currentDesc.Width ||
784                    This->pbufferHeight < targetimpl->currentDesc.Height) {
785                     if(This->pbufferContext) {
786                         DestroyContext(This, This->pbufferContext);
787                     }
788
789                     /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
790                      * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
791                      */
792                     This->pbufferContext = CreateContext(This, targetimpl,
793                             ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->win_handle,
794                             TRUE /* pbuffer */, &((IWineD3DSwapChainImpl *)This->swapchains[0])->presentParms);
795                     This->pbufferWidth = targetimpl->currentDesc.Width;
796                     This->pbufferHeight = targetimpl->currentDesc.Height;
797                    }
798
799                    if(This->pbufferContext) {
800                        if(This->pbufferContext->tid != 0 && This->pbufferContext->tid != tid) {
801                            FIXME("The PBuffr context is only supported for one thread for now!\n");
802                        }
803                        This->pbufferContext->tid = tid;
804                        context = This->pbufferContext;
805                        break;
806                    } else {
807                        ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
808                        wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
809                    }
810             }
811
812             case ORM_BACKBUFFER:
813                 /* Stay with the currently active context for back buffer rendering */
814                 if(This->activeContext && tid == This->lastThread) {
815                     context = This->activeContext;
816                 } else {
817                     /* This may happen if the app jumps straight into offscreen rendering
818                      * Start using the context of the primary swapchain. tid == 0 is no problem
819                      * for findThreadContextForSwapChain.
820                      *
821                      * Can also happen on thread switches - in that case findThreadContextForSwapChain
822                      * is perfect to call.
823                      */
824                     context = findThreadContextForSwapChain(This->swapchains[0], tid);
825                 }
826                 break;
827         }
828
829         if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
830             /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
831              * back when we are done won't mark us dirty.
832              */
833             IWineD3DSurface_PreLoad(target);
834         }
835
836         if(!oldRenderOffscreen) {
837             Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
838             Context_MarkStateDirty(context, STATE_VDECL);
839             Context_MarkStateDirty(context, STATE_VIEWPORT);
840             Context_MarkStateDirty(context, STATE_SCISSORRECT);
841             Context_MarkStateDirty(context, STATE_FRONTFACE);
842         }
843     }
844     if (readTexture) {
845         BOOL oldInDraw = This->isInDraw;
846
847         /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
848          * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
849          * when using offscreen rendering with multithreading
850          */
851         This->isInDraw = TRUE;
852
853         /* Do that before switching the context:
854          * Read the back buffer of the old drawable into the destination texture
855          */
856         IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
857
858         /* Assume that the drawable will be modified by some other things now */
859         IWineD3DSurface_ModifyLocation(This->lastActiveRenderTarget, SFLAG_INDRAWABLE, FALSE);
860
861         This->isInDraw = oldInDraw;
862     }
863
864     if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
865         This->depth_copy_state = WINED3D_DCS_COPY;
866     }
867     return context;
868 }
869
870 /*****************************************************************************
871  * ActivateContext
872  *
873  * Finds a rendering context and drawable matching the device and render
874  * target for the current thread, activates them and puts them into the
875  * requested state.
876  *
877  * Params:
878  *  This: Device to activate the context for
879  *  target: Requested render target
880  *  usage: Prepares the context for blitting, drawing or other actions
881  *
882  *****************************************************************************/
883 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
884     DWORD                         tid = GetCurrentThreadId();
885     int                           i;
886     DWORD                         dirtyState, idx;
887     BYTE                          shift;
888     WineD3DContext                *context;
889     GLint                         drawBuffer=0;
890
891     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
892     if(This->lastActiveRenderTarget != target || tid != This->lastThread) {
893         context = FindContext(This, target, tid, &drawBuffer);
894         This->lastActiveRenderTarget = target;
895         This->lastThread = tid;
896     } else {
897         /* Stick to the old context */
898         context = This->activeContext;
899     }
900
901     /* Activate the opengl context */
902     if(context != This->activeContext) {
903         BOOL ret;
904
905         /* Prevent an unneeded context switch as those are expensive */
906         if(context->glCtx && (context->glCtx == pwglGetCurrentContext())) {
907             TRACE("Already using gl context %p\n", context->glCtx);
908         }
909         else {
910             TRACE("Switching gl ctx to %p, hdc=%p ctx=%p\n", context, context->hdc, context->glCtx);
911             ret = pwglMakeCurrent(context->hdc, context->glCtx);
912             if(ret == FALSE) {
913                 ERR("Failed to activate the new context\n");
914             }
915         }
916         if(This->activeContext->vshader_const_dirty) {
917             memset(This->activeContext->vshader_const_dirty, 1,
918                    sizeof(*This->activeContext->vshader_const_dirty) * GL_LIMITS(vshader_constantsF));
919         }
920         if(This->activeContext->pshader_const_dirty) {
921             memset(This->activeContext->pshader_const_dirty, 1,
922                    sizeof(*This->activeContext->pshader_const_dirty) * GL_LIMITS(pshader_constantsF));
923         }
924         This->activeContext = context;
925     }
926
927     /* We only need ENTER_GL for the gl calls made below and for the helper functions which make GL calls */
928     ENTER_GL();
929     /* Select the right draw buffer. It is selected in FindContext. */
930     if(drawBuffer && context->last_draw_buffer != drawBuffer) {
931         TRACE("Drawing to buffer: %#x\n", drawBuffer);
932         context->last_draw_buffer = drawBuffer;
933
934         glDrawBuffer(drawBuffer);
935         checkGLcall("glDrawBuffer");
936     }
937
938     switch(usage) {
939         case CTXUSAGE_RESOURCELOAD:
940             /* This does not require any special states to be set up */
941             break;
942
943         case CTXUSAGE_CLEAR:
944             if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
945                 glEnable(GL_TEXTURE_SHADER_NV);
946                 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
947             }
948
949             glEnable(GL_SCISSOR_TEST);
950             checkGLcall("glEnable GL_SCISSOR_TEST");
951             context->last_was_blit = FALSE;
952             Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_SCISSORTESTENABLE));
953             Context_MarkStateDirty(context, STATE_SCISSORRECT);
954             break;
955
956         case CTXUSAGE_DRAWPRIM:
957             /* This needs all dirty states applied */
958             if(context->last_was_blit && GL_SUPPORT(NV_TEXTURE_SHADER2)) {
959                 glEnable(GL_TEXTURE_SHADER_NV);
960                 checkGLcall("glEnable(GL_TEXTURE_SHADER_NV)");
961             }
962
963             IWineD3DDeviceImpl_FindTexUnitMap(This);
964
965             for(i=0; i < context->numDirtyEntries; i++) {
966                 dirtyState = context->dirtyArray[i];
967                 idx = dirtyState >> 5;
968                 shift = dirtyState & 0x1f;
969                 context->isStateDirty[idx] &= ~(1 << shift);
970                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
971             }
972             context->numDirtyEntries = 0; /* This makes the whole list clean */
973             context->last_was_blit = FALSE;
974             break;
975
976         case CTXUSAGE_BLIT:
977             SetupForBlit(This, context,
978                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
979                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
980             break;
981
982         default:
983             FIXME("Unexpected context usage requested\n");
984     }
985     LEAVE_GL();
986 }