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