wintrust: Implement WintrustLoadFunctionPointers.
[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 ((IWineD3DImpl *)(This->wineD3D))->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  *  display: X display this context uses
69  *  glCtx: glX context to add
70  *  drawable: drawable used with this context.
71  *
72  *****************************************************************************/
73 static WineD3DContext *AddContextToArray(IWineD3DDeviceImpl *This, Display *display, GLXContext glCtx, Drawable drawable) {
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]->display = display;
96     This->contexts[This->numContexts]->glCtx = glCtx;
97     This->contexts[This->numContexts]->drawable = drawable;
98     HeapFree(GetProcessHeap(), 0, oldArray);
99
100     /* Mark all states dirty to force a proper initialization of the states on the first use of the context
101      */
102     for(state = 0; state <= STATE_HIGHEST; state++) {
103         Context_MarkStateDirty(This->contexts[This->numContexts], state);
104     }
105
106     This->numContexts++;
107     TRACE("Created context %p\n", This->contexts[This->numContexts - 1]);
108     return This->contexts[This->numContexts - 1];
109 }
110
111 /* Returns an array of compatible FBconfig(s).
112  * The array must be freed with XFree. Requires ENTER_GL()
113  */
114 static GLXFBConfig* pbuffer_find_fbconfigs(
115     IWineD3DDeviceImpl* This,
116     IWineD3DSurfaceImpl* RenderSurface,
117     Display *display) {
118
119     GLXFBConfig* cfgs = NULL;
120     int nCfgs = 0;
121     int attribs[256];
122     int nAttribs = 0;
123
124     IWineD3DSurface *StencilSurface = This->stencilBufferTarget;
125     WINED3DFORMAT BackBufferFormat = RenderSurface->resource.format;
126     WINED3DFORMAT StencilBufferFormat = (NULL != StencilSurface) ? ((IWineD3DSurfaceImpl *) StencilSurface)->resource.format : 0;
127
128     /* TODO:
129      *  if StencilSurface == NULL && zBufferTarget != NULL then switch the zbuffer off,
130      *  it StencilSurface != NULL && zBufferTarget == NULL switch it on
131      */
132
133 #define PUSH1(att)        attribs[nAttribs++] = (att);
134 #define PUSH2(att,value)  attribs[nAttribs++] = (att); attribs[nAttribs++] = (value);
135
136     /* PUSH2(GLX_BIND_TO_TEXTURE_RGBA_ATI, True); examples of this are few and far between (but I've got a nice working one!)*/
137
138     PUSH2(GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT);
139     PUSH2(GLX_X_RENDERABLE,  TRUE);
140     PUSH2(GLX_DOUBLEBUFFER,  TRUE);
141     TRACE("calling makeglcfg\n");
142     D3DFmtMakeGlCfg(BackBufferFormat, StencilBufferFormat, attribs, &nAttribs, FALSE /* alternate */);
143     PUSH1(None);
144     TRACE("calling chooseFGConfig\n");
145     cfgs = glXChooseFBConfig(display,
146                              DefaultScreen(display),
147                              attribs, &nCfgs);
148     if (cfgs == NULL) {
149         /* OK we didn't find the exact config, so use any reasonable match */
150         /* TODO: fill in the 'requested' and 'current' depths, and make sure that's
151            why we failed. */
152         static BOOL show_message = TRUE;
153         if (show_message) {
154             ERR("Failed to find exact match, finding alternative but you may "
155                 "suffer performance issues, try changing xfree's depth to match the requested depth\n");
156             show_message = FALSE;
157         }
158         nAttribs = 0;
159         PUSH2(GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT);
160         /* PUSH2(GLX_X_RENDERABLE,  TRUE); */
161         PUSH2(GLX_RENDER_TYPE,   GLX_RGBA_BIT);
162         PUSH2(GLX_DOUBLEBUFFER, FALSE);
163         TRACE("calling makeglcfg\n");
164         D3DFmtMakeGlCfg(BackBufferFormat, StencilBufferFormat, attribs, &nAttribs, TRUE /* alternate */);
165         PUSH1(None);
166         cfgs = glXChooseFBConfig(display,
167                                  DefaultScreen(display),
168                                  attribs, &nCfgs);
169     }
170
171     if (cfgs == NULL) {
172         ERR("Could not get a valid FBConfig for (%u,%s)/(%u,%s)\n",
173             BackBufferFormat, debug_d3dformat(BackBufferFormat),
174             StencilBufferFormat, debug_d3dformat(StencilBufferFormat));
175     } else {
176 #ifdef EXTRA_TRACES
177         int i;
178         for (i = 0; i < nCfgs; ++i) {
179             TRACE("for (%u,%s)/(%u,%s) found config[%d]@%p\n", BackBufferFormat,
180             debug_d3dformat(BackBufferFormat), StencilBufferFormat,
181             debug_d3dformat(StencilBufferFormat), i, cfgs[i]);
182         }
183 #endif
184     }
185 #undef PUSH1
186 #undef PUSH2
187
188    return cfgs;
189 }
190
191 /*****************************************************************************
192  * CreateContext
193  *
194  * Creates a new context for a window, or a pbuffer context.
195  *
196  * * Params:
197  *  This: Device to activate the context for
198  *  target: Surface this context will render to
199  *  display: X11 connection
200  *  win: Target window. NULL for a pbuffer
201  *
202  *****************************************************************************/
203 WineD3DContext *CreateContext(IWineD3DDeviceImpl *This, IWineD3DSurfaceImpl *target, Display *display, Window win) {
204     Drawable drawable = win, oldDrawable;
205     XVisualInfo *visinfo = NULL;
206     GLXFBConfig *cfgs = NULL;
207     GLXContext ctx = NULL, oldCtx;
208     WineD3DContext *ret = NULL;
209
210     TRACE("(%p): Creating a %s context for render target %p\n", This, win ? "onscreen" : "offscreen", target);
211
212     if(!win) {
213         int attribs[256];
214         int nAttribs = 0;
215
216         TRACE("Creating a pBuffer drawable for the new context\n");
217
218         cfgs = pbuffer_find_fbconfigs(This, target, display);
219         if(!cfgs) {
220             ERR("Cannot find a frame buffer configuration for the pbuffer\n");
221             goto out;
222         }
223
224         attribs[nAttribs++] = GLX_PBUFFER_WIDTH;
225         attribs[nAttribs++] = target->currentDesc.Width;
226         attribs[nAttribs++] = GLX_PBUFFER_HEIGHT;
227         attribs[nAttribs++] = target->currentDesc.Height;
228         attribs[nAttribs++] = None;
229
230         visinfo = glXGetVisualFromFBConfig(display, cfgs[0]);
231         if(!visinfo) {
232             ERR("Cannot find a visual for the pbuffer\n");
233             goto out;
234         }
235
236         drawable = glXCreatePbuffer(display, cfgs[0], attribs);
237
238         if(!drawable) {
239             ERR("Cannot create a pbuffer\n");
240             goto out;
241         }
242         XFree(cfgs);
243         cfgs = NULL;
244     } else {
245         /* Create an onscreen target */
246         XVisualInfo             template;
247         int                     num;
248
249         template.visualid = (VisualID)GetPropA(GetDesktopWindow(), "__wine_x11_visual_id");
250         /* TODO: change this to find a similar visual, but one with a stencil/zbuffer buffer that matches the request
251         (or the best possible if none is requested) */
252         TRACE("Found x visual ID  : %ld\n", template.visualid);
253         visinfo   = XGetVisualInfo(display, VisualIDMask, &template, &num);
254
255         if (NULL == visinfo) {
256             ERR("cannot really get XVisual\n");
257             goto out;
258         } else {
259             int n, value;
260             /* Write out some debug info about the visual/s */
261             TRACE("Using x visual ID  : %ld\n", template.visualid);
262             TRACE("        visual info: %p\n", visinfo);
263             TRACE("        num items  : %d\n", num);
264             for (n = 0;n < num; n++) {
265                 TRACE("=====item=====: %d\n", n + 1);
266                 TRACE("   visualid      : %ld\n", visinfo[n].visualid);
267                 TRACE("   screen        : %d\n",  visinfo[n].screen);
268                 TRACE("   depth         : %u\n",  visinfo[n].depth);
269                 TRACE("   class         : %d\n",  visinfo[n].class);
270                 TRACE("   red_mask      : %ld\n", visinfo[n].red_mask);
271                 TRACE("   green_mask    : %ld\n", visinfo[n].green_mask);
272                 TRACE("   blue_mask     : %ld\n", visinfo[n].blue_mask);
273                 TRACE("   colormap_size : %d\n",  visinfo[n].colormap_size);
274                 TRACE("   bits_per_rgb  : %d\n",  visinfo[n].bits_per_rgb);
275                 /* log some extra glx info */
276                 glXGetConfig(display, visinfo, GLX_AUX_BUFFERS, &value);
277                 TRACE("   gl_aux_buffers  : %d\n",  value);
278                 glXGetConfig(display, visinfo, GLX_BUFFER_SIZE ,&value);
279                 TRACE("   gl_buffer_size  : %d\n",  value);
280                 glXGetConfig(display, visinfo, GLX_RED_SIZE, &value);
281                 TRACE("   gl_red_size  : %d\n",  value);
282                 glXGetConfig(display, visinfo, GLX_GREEN_SIZE, &value);
283                 TRACE("   gl_green_size  : %d\n",  value);
284                 glXGetConfig(display, visinfo, GLX_BLUE_SIZE, &value);
285                 TRACE("   gl_blue_size  : %d\n",  value);
286                 glXGetConfig(display, visinfo, GLX_ALPHA_SIZE, &value);
287                 TRACE("   gl_alpha_size  : %d\n",  value);
288                 glXGetConfig(display, visinfo, GLX_DEPTH_SIZE ,&value);
289                 TRACE("   gl_depth_size  : %d\n",  value);
290                 glXGetConfig(display, visinfo, GLX_STENCIL_SIZE, &value);
291                 TRACE("   gl_stencil_size : %d\n",  value);
292             }
293             /* Now choose a similar visual ID*/
294         }
295     }
296
297     ctx = glXCreateContext(display, visinfo,
298                            This->numContexts ? This->contexts[0]->glCtx : NULL,
299                            GL_TRUE);
300     if(!ctx) {
301         ERR("Failed to create a glX context\n");
302         if(drawable != win) glXDestroyPbuffer(display, drawable);
303         goto out;
304     }
305     ret = AddContextToArray(This, display, ctx, drawable);
306     if(!ret) {
307         ERR("Failed to add the newly created context to the context list\n");
308         glXDestroyContext(display, ctx);
309         if(drawable != win) glXDestroyPbuffer(display, drawable);
310         goto out;
311     }
312     ret->surface = (IWineD3DSurface *) target;
313     ret->isPBuffer = win == 0;
314
315     TRACE("Successfully created new context %p\n", ret);
316
317     /* Set up the context defaults */
318     oldCtx  = glXGetCurrentContext();
319     oldDrawable = glXGetCurrentDrawable();
320     if(glXMakeCurrent(display, drawable, ctx) == FALSE) {
321         ERR("Cannot activate context to set up defaults\n");
322         goto out;
323     }
324
325     TRACE("Setting up the screen\n");
326     /* Clear the screen */
327     glClearColor(1.0, 0.0, 0.0, 0.0);
328     checkGLcall("glClearColor");
329     glClearIndex(0);
330     glClearDepth(1);
331     glClearStencil(0xffff);
332
333     checkGLcall("glClear");
334
335     glColor3f(1.0, 1.0, 1.0);
336     checkGLcall("glColor3f");
337
338     glEnable(GL_LIGHTING);
339     checkGLcall("glEnable");
340
341     glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
342     checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
343
344     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
345     checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
346
347     glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
348     checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
349
350     glPixelStorei(GL_PACK_ALIGNMENT, SURFACE_ALIGNMENT);
351     checkGLcall("glPixelStorei(GL_PACK_ALIGNMENT, SURFACE_ALIGNMENT);");
352     glPixelStorei(GL_UNPACK_ALIGNMENT, SURFACE_ALIGNMENT);
353     checkGLcall("glPixelStorei(GL_UNPACK_ALIGNMENT, SURFACE_ALIGNMENT);");
354
355     if(GL_SUPPORT(APPLE_CLIENT_STORAGE)) {
356         /* Most textures will use client storage if supported. Exceptions are non-native power of 2 textures
357          * and textures in DIB sections(due to the memory protection).
358          */
359         glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
360         checkGLcall("glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE)");
361     }
362
363     if(oldDrawable && oldCtx) {
364         glXMakeCurrent(display, oldDrawable, oldCtx);
365     }
366
367 out:
368     if(visinfo) XFree(visinfo);
369     if(cfgs) XFree(cfgs);
370     return ret;
371 }
372
373 /*****************************************************************************
374  * RemoveContextFromArray
375  *
376  * Removes a context from the context manager. The opengl context is not
377  * destroyed or unset. context is not a valid pointer after that call.
378  *
379  * Similar to the former call this isn't a performance critical function. A
380  * helper function for DestroyContext.
381  *
382  * Params:
383  *  This: Device to activate the context for
384  *  context: Context to remove
385  *
386  *****************************************************************************/
387 static void RemoveContextFromArray(IWineD3DDeviceImpl *This, WineD3DContext *context) {
388     UINT t, s;
389     WineD3DContext **oldArray = This->contexts;
390
391     TRACE("Removing ctx %p\n", context);
392
393     This->numContexts--;
394
395     if(This->numContexts) {
396         This->contexts = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->contexts) * This->numContexts);
397         if(!This->contexts) {
398             ERR("Cannot allocate a new context array, PANIC!!!\n");
399         }
400         t = 0;
401         for(s = 0; s < This->numContexts; s++) {
402             if(oldArray[s] == context) continue;
403             This->contexts[t] = oldArray[s];
404             t++;
405         }
406     } else {
407         This->contexts = NULL;
408     }
409
410     HeapFree(GetProcessHeap(), 0, context);
411     HeapFree(GetProcessHeap(), 0, oldArray);
412 }
413
414 /*****************************************************************************
415  * DestroyContext
416  *
417  * Destroys a wineD3DContext
418  *
419  * Params:
420  *  This: Device to activate the context for
421  *  context: Context to destroy
422  *
423  *****************************************************************************/
424 void DestroyContext(IWineD3DDeviceImpl *This, WineD3DContext *context) {
425
426     /* check that we are the current context first */
427     TRACE("Destroying ctx %p\n", context);
428     if(glXGetCurrentContext() == context->glCtx){
429         glXMakeCurrent(context->display, None, NULL);
430     }
431
432     glXDestroyContext(context->display, context->glCtx);
433     if(context->isPBuffer) {
434         glXDestroyPbuffer(context->display, context->drawable);
435     }
436     RemoveContextFromArray(This, context);
437 }
438
439 /*****************************************************************************
440  * SetupForBlit
441  *
442  * Sets up a context for DirectDraw blitting.
443  * All texture units are disabled, except unit 0
444  * Texture unit 0 is activted where GL_TEXTURE_2D is activated
445  * fog, lighting, blending, alpha test, z test, scissor test, culling diabled
446  * color writing enabled for all channels
447  * register combiners disabled, shaders disabled
448  * world matris is set to identity, texture matrix 0 too
449  * projection matrix is setup for drawing screen coordinates
450  *
451  * Params:
452  *  This: Device to activate the context for
453  *  context: Context to setup
454  *  width: render target width
455  *  height: render target height
456  *
457  *****************************************************************************/
458 static inline void SetupForBlit(IWineD3DDeviceImpl *This, WineD3DContext *context, UINT width, UINT height) {
459     int i;
460
461     TRACE("Setting up context %p for blitting\n", context);
462     if(context->last_was_blit) {
463         TRACE("Context is already set up for blitting, nothing to do\n");
464         return;
465     }
466     context->last_was_blit = TRUE;
467
468     /* TODO: Use a display list */
469
470     /* Disable shaders */
471     This->shader_backend->shader_cleanup((IWineD3DDevice *) This);
472     Context_MarkStateDirty(context, STATE_VSHADER);
473     Context_MarkStateDirty(context, STATE_PIXELSHADER);
474
475     /* Disable all textures. The caller can then bind a texture it wants to blit
476      * from
477      */
478     if(GL_SUPPORT(NV_REGISTER_COMBINERS)) {
479         glDisable(GL_REGISTER_COMBINERS_NV);
480         checkGLcall("glDisable(GL_REGISTER_COMBINERS_NV)");
481     }
482     if (GL_SUPPORT(ARB_MULTITEXTURE)) {
483         /* The blitting code uses (for now) the fixed function pipeline, so make sure to reset all fixed
484          * function texture unit. No need to care for higher samplers
485          */
486         for(i = GL_LIMITS(textures) - 1; i > 0 ; i--) {
487             GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB + i));
488             checkGLcall("glActiveTextureARB");
489
490             if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
491                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
492                 checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
493             }
494             glDisable(GL_TEXTURE_3D);
495             checkGLcall("glDisable GL_TEXTURE_3D");
496             glDisable(GL_TEXTURE_2D);
497             checkGLcall("glDisable GL_TEXTURE_2D");
498
499             glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
500             checkGLcall("glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);");
501
502             Context_MarkStateDirty(context, STATE_TEXTURESTAGE(i, WINED3DTSS_COLOROP));
503             Context_MarkStateDirty(context, STATE_SAMPLER(i));
504         }
505         GL_EXTCALL(glActiveTextureARB(GL_TEXTURE0_ARB));
506         checkGLcall("glActiveTextureARB");
507     }
508     if(GL_SUPPORT(ARB_TEXTURE_CUBE_MAP)) {
509         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
510         checkGLcall("glDisable GL_TEXTURE_CUBE_MAP_ARB");
511     }
512     glDisable(GL_TEXTURE_3D);
513     checkGLcall("glDisable GL_TEXTURE_3D");
514     glEnable(GL_TEXTURE_2D);
515     checkGLcall("glEnable GL_TEXTURE_2D");
516
517     glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
518
519     glMatrixMode(GL_TEXTURE);
520     checkGLcall("glMatrixMode(GL_TEXTURE)");
521     glLoadIdentity();
522     checkGLcall("glLoadIdentity()");
523     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_TEXTURE0));
524
525     if (GL_SUPPORT(EXT_TEXTURE_LOD_BIAS)) {
526         glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT,
527                   GL_TEXTURE_LOD_BIAS_EXT,
528                   0.0);
529         checkGLcall("glTexEnvi GL_TEXTURE_LOD_BIAS_EXT ...");
530     }
531     Context_MarkStateDirty(context, STATE_SAMPLER(0));
532     Context_MarkStateDirty(context, STATE_TEXTURESTAGE(0, WINED3DTSS_COLOROP));
533
534     /* Other misc states */
535     glDisable(GL_ALPHA_TEST);
536     checkGLcall("glDisable(GL_ALPHA_TEST)");
537     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHATESTENABLE));
538     glDisable(GL_LIGHTING);
539     checkGLcall("glDisable GL_LIGHTING");
540     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_LIGHTING));
541     glDisable(GL_DEPTH_TEST);
542     checkGLcall("glDisable GL_DEPTH_TEST");
543     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ZENABLE));
544     glDisable(GL_FOG);
545     checkGLcall("glDisable GL_FOG");
546     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_FOGENABLE));
547     glDisable(GL_BLEND);
548     checkGLcall("glDisable GL_BLEND");
549     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_ALPHABLENDENABLE));
550     glDisable(GL_CULL_FACE);
551     checkGLcall("glDisable GL_CULL_FACE");
552     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CULLMODE));
553     glDisable(GL_STENCIL_TEST);
554     checkGLcall("glDisable GL_STENCIL_TEST");
555     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_STENCILENABLE));
556     if(GL_SUPPORT(ARB_POINT_SPRITE)) {
557         glDisable(GL_POINT_SPRITE_ARB);
558         checkGLcall("glDisable GL_POINT_SPRITE_ARB");
559         Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_POINTSPRITEENABLE));
560     }
561     glColorMask(GL_TRUE, GL_TRUE,GL_TRUE,GL_TRUE);
562     checkGLcall("glColorMask");
563     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
564
565     /* Setup transforms */
566     glMatrixMode(GL_MODELVIEW);
567     checkGLcall("glMatrixMode(GL_MODELVIEW)");
568     glLoadIdentity();
569     checkGLcall("glLoadIdentity()");
570     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_WORLDMATRIX(0)));
571
572     glMatrixMode(GL_PROJECTION);
573     checkGLcall("glMatrixMode(GL_PROJECTION)");
574     glLoadIdentity();
575     checkGLcall("glLoadIdentity()");
576     glOrtho(0, width, height, 0, 0.0, -1.0);
577     checkGLcall("glOrtho");
578     Context_MarkStateDirty(context, STATE_TRANSFORM(WINED3DTS_PROJECTION));
579
580     context->last_was_rhw = TRUE;
581     Context_MarkStateDirty(context, STATE_VDECL); /* because of last_was_rhw = TRUE */
582
583     glDisable(GL_CLIP_PLANE0); checkGLcall("glDisable(clip plane 0)");
584     glDisable(GL_CLIP_PLANE1); checkGLcall("glDisable(clip plane 1)");
585     glDisable(GL_CLIP_PLANE2); checkGLcall("glDisable(clip plane 2)");
586     glDisable(GL_CLIP_PLANE3); checkGLcall("glDisable(clip plane 3)");
587     glDisable(GL_CLIP_PLANE4); checkGLcall("glDisable(clip plane 4)");
588     glDisable(GL_CLIP_PLANE5); checkGLcall("glDisable(clip plane 5)");
589     Context_MarkStateDirty(context, STATE_RENDER(WINED3DRS_CLIPPING));
590
591     glViewport(0, 0, width, height);
592     checkGLcall("glViewport");
593     Context_MarkStateDirty(context, STATE_VIEWPORT);
594 }
595
596 /*****************************************************************************
597  * ActivateContext
598  *
599  * Finds a rendering context and drawable matching the device and render
600  * target for the current thread, activates them and puts them into the
601  * requested state.
602  *
603  * Params:
604  *  This: Device to activate the context for
605  *  target: Requested render target
606  *  usage: Prepares the context for blitting, drawing or other actions
607  *
608  *****************************************************************************/
609 void ActivateContext(IWineD3DDeviceImpl *This, IWineD3DSurface *target, ContextUsage usage) {
610     DWORD tid = This->createParms.BehaviorFlags & WINED3DCREATE_MULTITHREADED ? GetCurrentThreadId() : 0;
611     int                           i;
612     DWORD                         dirtyState, idx;
613     BYTE                          shift;
614     WineD3DContext                *context = This->activeContext;
615     BOOL                          oldRenderOffscreen = This->render_offscreen;
616
617     TRACE("(%p): Selecting context for render target %p, thread %d\n", This, target, tid);
618
619     if(This->lastActiveRenderTarget != target) {
620         IWineD3DSwapChain *swapchain = NULL;
621         HRESULT hr;
622         BOOL readTexture = wined3d_settings.offscreen_rendering_mode != ORM_FBO && This->render_offscreen;
623
624         hr = IWineD3DSurface_GetContainer(target, &IID_IWineD3DSwapChain, (void **) &swapchain);
625         if(hr == WINED3D_OK && swapchain) {
626             TRACE("Rendering onscreen\n");
627             context = ((IWineD3DSwapChainImpl *) swapchain)->context[0];
628             This->render_offscreen = FALSE;
629             /* The context != This->activeContext will catch a NOP context change. This can occur
630              * if we are switching back to swapchain rendering in case of FBO or Back Buffer offscreen
631              * rendering. No context change is needed in that case
632              */
633
634             if (wined3d_settings.offscreen_rendering_mode == ORM_BACKBUFFER) {
635                 if(((IWineD3DSwapChainImpl *) swapchain)->backBuffer) {
636                     glDrawBuffer(GL_BACK);
637                     checkGLcall("glDrawBuffer(GL_BACK)");
638                 } else {
639                     glDrawBuffer(GL_FRONT);
640                     checkGLcall("glDrawBuffer(GL_FRONT)");
641                 }
642             }
643             IWineD3DSwapChain_Release(swapchain);
644
645             if(oldRenderOffscreen) {
646                 Context_MarkStateDirty(context, WINED3DRS_CULLMODE);
647                 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
648                 Context_MarkStateDirty(context, STATE_VDECL);
649                 Context_MarkStateDirty(context, STATE_VIEWPORT);
650             }
651         } else {
652             TRACE("Rendering offscreen\n");
653             This->render_offscreen = TRUE;
654
655             switch(wined3d_settings.offscreen_rendering_mode) {
656                 case ORM_FBO:
657                     /* FBOs do not need a different context. Stay with whatever context is active at the moment */
658                     if(This->activeContext) {
659                         context = This->activeContext;
660                     } else {
661                         /* This may happen if the app jumps streight into offscreen rendering
662                          * Start using the context of the primary swapchain
663                          */
664                         context = ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0];
665                     }
666                     break;
667
668                 case ORM_PBUFFER:
669                 {
670                     IWineD3DSurfaceImpl *targetimpl = (IWineD3DSurfaceImpl *) target;
671                     if(This->pbufferContext == NULL ||
672                        This->pbufferWidth < targetimpl->currentDesc.Width ||
673                        This->pbufferHeight < targetimpl->currentDesc.Height) {
674                         if(This->pbufferContext) {
675                             DestroyContext(This, This->pbufferContext);
676                         }
677
678                         /* The display is irrelevant here, the window is 0. But CreateContext needs a valid X connection.
679                          * Create the context on the same server as the primary swapchain. The primary swapchain is exists at this point.
680                          */
681                         This->pbufferContext = CreateContext(This, targetimpl,
682                                                              ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0]->display,
683                                                              0 /* Window */);
684                         This->pbufferWidth = targetimpl->currentDesc.Width;
685                         This->pbufferHeight = targetimpl->currentDesc.Height;
686                     }
687
688                     if(This->pbufferContext) {
689                         context = This->pbufferContext;
690                         break;
691                     } else {
692                         ERR("Failed to create a buffer context and drawable, falling back to back buffer offscreen rendering\n");
693                         wined3d_settings.offscreen_rendering_mode = ORM_BACKBUFFER;
694                     }
695                 }
696
697                 case ORM_BACKBUFFER:
698                     /* Stay with the currently active context for back buffer rendering */
699                     if(This->activeContext) {
700                         context = This->activeContext;
701                     } else {
702                         /* This may happen if the app jumps streight into offscreen rendering
703                          * Start using the context of the primary swapchain
704                          */
705                         context = ((IWineD3DSwapChainImpl *) This->swapchains[0])->context[0];
706                     }
707                     glDrawBuffer(This->offscreenBuffer);
708                     checkGLcall("glDrawBuffer(This->offscreenBuffer)");
709                     break;
710             }
711
712             if (wined3d_settings.offscreen_rendering_mode != ORM_FBO) {
713                 /* Make sure we have a OpenGL texture name so the PreLoad() used to read the buffer
714                  * back when we are done won't mark us dirty.
715                  */
716                 IWineD3DSurface_PreLoad(target);
717             }
718
719             if(!oldRenderOffscreen) {
720                 Context_MarkStateDirty(context, WINED3DRS_CULLMODE);
721                 Context_MarkStateDirty(context, WINED3DTS_PROJECTION);
722                 Context_MarkStateDirty(context, STATE_VDECL);
723                 Context_MarkStateDirty(context, STATE_VIEWPORT);
724             }
725         }
726         if (readTexture) {
727             BOOL oldInDraw = This->isInDraw;
728
729             /* PreLoad requires a context to load the texture, thus it will call ActivateContext.
730              * Set the isInDraw to true to signal PreLoad that it has a context. Will be tricky
731              * when using offscreen rendering with multithreading
732              */
733             This->isInDraw = TRUE;
734
735             /* Do that before switching the context:
736              * Read the back buffer of the old drawable into the destination texture
737              */
738             IWineD3DSurface_PreLoad(This->lastActiveRenderTarget);
739
740             /* Assume that the drawable will be modified by some other things now */
741             ((IWineD3DSurfaceImpl *) This->lastActiveRenderTarget)->Flags &= ~SFLAG_INDRAWABLE;
742
743             This->isInDraw = oldInDraw;
744         }
745         This->lastActiveRenderTarget = target;
746         if(oldRenderOffscreen != This->render_offscreen && This->depth_copy_state != WINED3D_DCS_NO_COPY) {
747             This->depth_copy_state = WINED3D_DCS_COPY;
748         }
749     } else {
750         /* Stick to the old context */
751         context = This->activeContext;
752     }
753
754     /* Activate the opengl context */
755     if(context != This->activeContext) {
756         Bool ret;
757         TRACE("Switching gl ctx to %p, drawable=%ld, ctx=%p\n", context, context->drawable, context->glCtx);
758         ret = glXMakeCurrent(context->display, context->drawable, context->glCtx);
759         if(ret == FALSE) {
760             ERR("Failed to activate the new context\n");
761         }
762         This->activeContext = context;
763     }
764
765     switch(usage) {
766         case CTXUSAGE_RESOURCELOAD:
767             /* This does not require any special states to be set up */
768             break;
769
770         case CTXUSAGE_DRAWPRIM:
771             /* This needs all dirty states applied */
772             for(i=0; i < context->numDirtyEntries; i++) {
773                 dirtyState = context->dirtyArray[i];
774                 idx = dirtyState >> 5;
775                 shift = dirtyState & 0x1f;
776                 context->isStateDirty[idx] &= ~(1 << shift);
777                 StateTable[dirtyState].apply(dirtyState, This->stateBlock, context);
778             }
779             context->numDirtyEntries = 0; /* This makes the whole list clean */
780             context->last_was_blit = FALSE;
781             break;
782
783         case CTXUSAGE_BLIT:
784             SetupForBlit(This, context,
785                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Width,
786                          ((IWineD3DSurfaceImpl *)target)->currentDesc.Height);
787             break;
788
789         default:
790             FIXME("Unexpected context usage requested\n");
791     }
792 }