crypt32: Fix more test failures.
[wine] / dlls / wined3d / swapchain.c
index 4e8f97f..a23166a 100644 (file)
@@ -4,6 +4,7 @@
  *Copyright 2002-2003 Jason Edmeades
  *Copyright 2002-2003 Raphael Junqueira
  *Copyright 2005 Oliver Stieber
+ *Copyright 2007-2008 Stefan Dösinger for CodeWeavers
  *
  *This library is free software; you can redistribute it and/or
  *modify it under the terms of the GNU Lesser General Public
 #include "wined3d_private.h"
 
 
-/* TODO: move to shared header (or context manager )*/
-/* x11drv GDI escapes */
-#define X11DRV_ESCAPE 6789
-enum x11drv_escape_codes
-{
-    X11DRV_GET_DISPLAY,   /* get X11 display for a DC */
-    X11DRV_GET_DRAWABLE,  /* get current drawable for a DC */
-    X11DRV_GET_FONT,      /* get current X font for a DC */
-};
-
-/* retrieve the X display to use on a given DC */
-inline static Display *get_display( HDC hdc )
-{
-    Display *display;
-    enum x11drv_escape_codes escape = X11DRV_GET_DISPLAY;
-
-    if (!ExtEscape( hdc, X11DRV_ESCAPE, sizeof(escape), (LPCSTR)&escape,
-                    sizeof(display), (LPSTR)&display )) display = NULL;
-    return display;
-}
-
 /*TODO: some of the additional parameters may be required to
     set the gamma ramp (for some weird reason microsoft have left swap gammaramp in device
     but it operates on a swapchain, it may be a good idea to move it to IWineD3DSwapChain for IWineD3D)*/
@@ -53,93 +33,75 @@ inline static Display *get_display( HDC hdc )
 WINE_DEFAULT_DEBUG_CHANNEL(d3d);
 WINE_DECLARE_DEBUG_CHANNEL(fps);
 
+#define GLINFO_LOCATION This->wineD3DDevice->adapter->gl_info
 
-/* IDirect3DSwapChain IUnknown parts follow: */
-static ULONG WINAPI IWineD3DSwapChainImpl_AddRef(IWineD3DSwapChain *iface) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    DWORD refCount = InterlockedIncrement(&This->ref);
-    TRACE("(%p) : AddRef increasing from %d\n", This, refCount - 1);
-    return refCount;
-}
-
-static HRESULT WINAPI IWineD3DSwapChainImpl_QueryInterface(IWineD3DSwapChain *iface, REFIID riid, LPVOID *ppobj)
+/*IWineD3DSwapChain parts follow: */
+static void WINAPI IWineD3DSwapChainImpl_Destroy(IWineD3DSwapChain *iface)
 {
     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj);
-    if (IsEqualGUID(riid, &IID_IUnknown)
-        || IsEqualGUID(riid, &IID_IWineD3DBase)
-        || IsEqualGUID(riid, &IID_IWineD3DSwapChain)){
-        IWineD3DSwapChainImpl_AddRef(iface);
-        if(ppobj == NULL){
-            ERR("Query interface called but now data allocated\n");
-            return E_NOINTERFACE;
-        }
-        *ppobj = This;
-        return WINED3D_OK;
-    }
-    *ppobj = NULL;
-    return E_NOINTERFACE;
-}
+    WINED3DDISPLAYMODE mode;
+    unsigned int i;
 
+    TRACE("Destroying swapchain %p\n", iface);
 
-static ULONG WINAPI IWineD3DSwapChainImpl_Release(IWineD3DSwapChain *iface) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    DWORD refCount;
-    refCount = InterlockedDecrement(&This->ref);
-    TRACE("(%p) : ReleaseRef to %d\n", This, refCount);
-    if (refCount == 0) {
-        IUnknown* bufferParent;
-
-        /* release the ref to the front and back buffer parents */
-        if(This->frontBuffer) {
-            IWineD3DSurface_SetContainer(This->frontBuffer, 0);
-            IWineD3DSurface_GetParent(This->frontBuffer, &bufferParent);
-            IUnknown_Release(bufferParent); /* once for the get parent */
-            if(IUnknown_Release(bufferParent) > 0){
-                FIXME("(%p) Something's still holding the front buffer\n",This);
-            }
-        }
+    IWineD3DSwapChain_SetGammaRamp(iface, 0, &This->orig_gamma);
 
-        if(This->backBuffer) {
-            int i;
-            for(i = 0; i < This->presentParms.BackBufferCount; i++) {
-                IWineD3DSurface_SetContainer(This->backBuffer[i], 0);
-                IWineD3DSurface_GetParent(This->backBuffer[i], &bufferParent);
-                IUnknown_Release(bufferParent); /* once for the get parent */
-                if(IUnknown_Release(bufferParent) > 0){
-                    FIXME("(%p) Something's still holding the back buffer\n",This);
-                }
-            }
+    /* Release the swapchain's draw buffers. Make sure This->backBuffer[0] is
+     * the last buffer to be destroyed, FindContext() depends on that. */
+    if (This->frontBuffer)
+    {
+        IWineD3DSurface_SetContainer(This->frontBuffer, 0);
+        if (IWineD3DSurface_Release(This->frontBuffer))
+        {
+            WARN("(%p) Something's still holding the front buffer (%p).\n",
+                    This, This->frontBuffer);
         }
+        This->frontBuffer = NULL;
+    }
+
+    if (This->backBuffer)
+    {
+        UINT i = This->presentParms.BackBufferCount;
 
-        /* Clean up the context */
-        /* check that we are the current context first */
-        if(glXGetCurrentContext() == This->glCtx){
-            glXMakeCurrent(This->display, None, NULL);
+        while (i--)
+        {
+            IWineD3DSurface_SetContainer(This->backBuffer[i], 0);
+            if (IWineD3DSurface_Release(This->backBuffer[i]))
+                WARN("(%p) Something's still holding back buffer %u (%p).\n",
+                        This, i, This->backBuffer[i]);
         }
-        glXDestroyContext(This->display, This->glCtx);
-        /* IUnknown_Release(This->parent); This should only apply to the primary swapchain,
-         all others are created by the caller, so releasing the parent should cause
-         the child to be released, not the other way around!
-         */
-        HeapFree(GetProcessHeap(), 0, This);
+        HeapFree(GetProcessHeap(), 0, This->backBuffer);
+        This->backBuffer = NULL;
     }
-    return refCount;
-}
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetParent(IWineD3DSwapChain *iface, IUnknown ** ppParent){
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    *ppParent = This->parent;
-    IUnknown_AddRef(*ppParent);
-    TRACE("(%p) returning %p\n", This , *ppParent);
-    return WINED3D_OK;
+    for (i = 0; i < This->num_contexts; ++i)
+    {
+        context_destroy(This->wineD3DDevice, This->context[i]);
+    }
+    /* Restore the screen resolution if we rendered in fullscreen
+     * This will restore the screen resolution to what it was before creating the swapchain. In case of d3d8 and d3d9
+     * this will be the original desktop resolution. In case of d3d7 this will be a NOP because ddraw sets the resolution
+     * before starting up Direct3D, thus orig_width and orig_height will be equal to the modes in the presentation params
+     */
+    if(This->presentParms.Windowed == FALSE && This->presentParms.AutoRestoreDisplayMode) {
+        mode.Width = This->orig_width;
+        mode.Height = This->orig_height;
+        mode.RefreshRate = 0;
+        mode.Format = This->orig_fmt;
+        IWineD3DDevice_SetDisplayMode((IWineD3DDevice *) This->wineD3DDevice, 0, &mode);
+    }
+    HeapFree(GetProcessHeap(), 0, This->context);
+
+    HeapFree(GetProcessHeap(), 0, This);
 }
 
-/*IWineD3DSwapChain parts follow: */
 static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CONST RECT *pSourceRect, CONST RECT *pDestRect, HWND hDestWindowOverride, CONST RGNDATA *pDirtyRegion, DWORD dwFlags) {
     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
+    struct wined3d_context *context;
+    unsigned int sync;
+    int retval;
 
-    ENTER_GL();
+    context = context_acquire(This->wineD3DDevice, This->backBuffer[0], CTXUSAGE_RESOURCELOAD);
 
     /* Render the cursor onto the back buffer, using our nifty directdraw blitting code :-) */
     if(This->wineD3DDevice->bCursorVisible && This->wineD3DDevice->cursorTexture) {
@@ -158,11 +120,12 @@ static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CO
         cursor.resource.ref = 1;
         cursor.resource.wineD3DDevice = This->wineD3DDevice;
         cursor.resource.pool = WINED3DPOOL_SCRATCH;
-        cursor.resource.format = WINED3DFMT_A8R8G8B8;
+        cursor.resource.format_desc =
+                getFormatDescEntry(WINED3DFMT_B8G8R8A8_UNORM, &This->wineD3DDevice->adapter->gl_info);
         cursor.resource.resourceType = WINED3DRTYPE_SURFACE;
-        cursor.glDescription.textureName = This->wineD3DDevice->cursorTexture;
-        cursor.glDescription.target = GL_TEXTURE_2D;
-        cursor.glDescription.level = 0;
+        cursor.texture_name = This->wineD3DDevice->cursorTexture;
+        cursor.texture_target = GL_TEXTURE_2D;
+        cursor.texture_level = 0;
         cursor.currentDesc.Width = This->wineD3DDevice->cursorWidth;
         cursor.currentDesc.Height = This->wineD3DDevice->cursorHeight;
         cursor.glRect.left = 0;
@@ -172,150 +135,44 @@ static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CO
         /* The cursor must have pow2 sizes */
         cursor.pow2Width = cursor.currentDesc.Width;
         cursor.pow2Height = cursor.currentDesc.Height;
+        /* The surface is in the texture */
+        cursor.Flags |= SFLAG_INTEXTURE;
         /* DDBLT_KEYSRC will cause BltOverride to enable the alpha test with GL_NOTEQUAL, 0.0,
          * which is exactly what we want :-)
          */
         if (This->presentParms.Windowed) {
             MapWindowPoints(NULL, This->win_handle, (LPPOINT)&destRect, 2);
         }
-        IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *) &cursor, NULL, DDBLT_KEYSRC, NULL);
+        IWineD3DSurface_Blt(This->backBuffer[0], &destRect, (IWineD3DSurface *)&cursor,
+                NULL, WINEDDBLT_KEYSRC, NULL, WINED3DTEXF_POINT);
+    }
+    if(This->wineD3DDevice->logo_surface) {
+        /* Blit the logo into the upper left corner of the drawable */
+        IWineD3DSurface_BltFast(This->backBuffer[0], 0, 0, This->wineD3DDevice->logo_surface, NULL, WINEDDBLTFAST_SRCCOLORKEY);
     }
 
-    if (pSourceRect || pDestRect) FIXME("Unhandled present options %p/%p\n", pSourceRect, pDestRect);
+    if (pSourceRect || pDestRect) FIXME("Unhandled present rects %s/%s\n", wine_dbgstr_rect(pSourceRect), wine_dbgstr_rect(pDestRect));
     /* TODO: If only source rect or dest rect are supplied then clip the window to match */
-    TRACE("preseting display %p, drawable %ld\n", This->display, This->drawable);
+    TRACE("presetting HDC %p\n", This->context[0]->hdc);
 
     /* Don't call checkGLcall, as glGetError is not applicable here */
     if (hDestWindowOverride && This->win_handle != hDestWindowOverride) {
-        /* Set this swapchain up to point to the new destination.. */
-#ifdef USE_CONTEXT_MANAGER
-            /* TODO: use a context mamager */
-#endif
-
-            /* FIXME: Never access */
-            IWineD3DSwapChainImpl *swapChainImpl;
-            IWineD3DDevice_GetSwapChain((IWineD3DDevice *)This->wineD3DDevice, 0 , (IWineD3DSwapChain **)&swapChainImpl);
-            FIXME("Unable to render to a destination window %p\n", hDestWindowOverride );
-            if(This == swapChainImpl){
-                /* FIXME: this will be fixed by moving to a context management system */
-                FIXME("Cannot change the target of the implicit swapchain\n");
-            }else{
-                HDC               hDc;
-                XVisualInfo       template;
-                int               num;
-                Display          *oldDisplay = This->display;
-                GLXContext        oldContext = This->glCtx;
-                IUnknown*         tmp;
-                GLXContext        currentContext;
-                Drawable          currentDrawable;
-                hDc                          = GetDC(hDestWindowOverride);
-                This->win_handle             = hDestWindowOverride;
-                This->win                    = (Window)GetPropA( hDestWindowOverride, "__wine_x11_whole_window" );
-
-                TRACE("Creating a new context for the window %p\n", hDestWindowOverride);
-                ENTER_GL();
-                TRACE("Desctroying context %p %p\n", This->display, This->render_ctx);
-
-
-
-                LEAVE_GL();
-                ENTER_GL();
-
-                This->display    = get_display(hDc);
-                TRACE("Got display%p  for  %p %p\n",  This->display, hDc, hDestWindowOverride);
-                ReleaseDC(hDestWindowOverride, hDc);
-                template.visualid = (VisualID)GetPropA(GetDesktopWindow(), "__wine_x11_visual_id");
-                This->visInfo   = XGetVisualInfo(This->display, VisualIDMask, &template, &num);
-                if (NULL == This->visInfo) {
-                    ERR("cannot really get XVisual\n");
-                    LEAVE_GL();
-                    return WINED3DERR_NOTAVAILABLE;
-                }
-                /* Now we have problems? well not really we just need to know what the implicit context is */
-                /* now destroy the old context and create a new one (we should really copy the buffers over, and do the whole make current thing! */
-                /* destroy the active context?*/
-                TRACE("Creating new context for %p %p %p\n",This->display, This->visInfo, swapChainImpl->glCtx);
-                This->glCtx = glXCreateContext(This->display, This->visInfo, swapChainImpl->glCtx, GL_TRUE);
-
-                if (NULL == This->glCtx) {
-                    ERR("cannot create glxContext\n");
-                }
-                This->drawable     = This->win;
-                This->render_ctx   = This->glCtx;
-                /* Setup some default states TODO: apply the stateblock to the new context */
-                /** save current context and drawable **/
-                currentContext  =   glXGetCurrentContext();
-                currentDrawable =   glXGetCurrentDrawable();
-
-                if (glXMakeCurrent(This->display, This->win, This->glCtx) == False) {
-                    ERR("Error in setting current context (display %p context %p drawable %ld)!\n", This->display, This->glCtx, This->win);
-                }
-
-                checkGLcall("glXMakeCurrent");
-
-                /* Clear the screen */
-                glClearColor(0.0, 0.0, 0.0, 0.0);
-                checkGLcall("glClearColor");
-                glClearIndex(0);
-                glClearDepth(1);
-                glClearStencil(0);
-
-                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_ACCUM_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
-                checkGLcall("glClear");
-
-                glColor3f(1.0, 1.0, 1.0);
-                checkGLcall("glColor3f");
-
-                glEnable(GL_LIGHTING);
-                checkGLcall("glEnable");
-
-                glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
-                checkGLcall("glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);");
-
-                glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);
-                checkGLcall("glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_EXT);");
-
-                glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
-                checkGLcall("glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);");
-
-                /* If this swapchain is currently the active context then make this swapchain active */
-                if(IWineD3DSurface_GetContainer(This->wineD3DDevice->renderTarget, &IID_IWineD3DSwapChain, (void **)&tmp) == WINED3D_OK){
-                    if(tmp != (IUnknown *)This){
-                        glXMakeCurrent(This->display, currentDrawable, currentContext);
-                        checkGLcall("glXMakeCurrent");
-                    }
-                    IUnknown_Release(tmp);
-                }else{
-                    /* reset the context */
-                    glXMakeCurrent(This->display, currentDrawable, currentContext);
-                    checkGLcall("glXMakeCurrent");
-                }
-                /* delete the old contxt*/
-                glXDestroyContext(oldDisplay, oldContext); /* Should this happen on an active context? seems a bad idea */
-                LEAVE_GL();
-            }
-            IWineD3DSwapChain_Release((IWineD3DSwapChain *)swapChainImpl);
-
-        }
-
-
-        /* TODO: The slow way, save the data to memory, create a new context for the destination window, transfer the data cleanup, it may be a good idea to the move this swapchain over to the using the target winows context so that it runs faster in feature. */
+        IWineD3DSwapChain_SetDestWindowOverride(iface, hDestWindowOverride);
+    }
 
-    glXSwapBuffers(This->display, This->drawable); /* TODO: cycle through the swapchain buffers */
+    SwapBuffers(This->context[0]->hdc); /* TODO: cycle through the swapchain buffers */
 
-    TRACE("glXSwapBuffers called, Starting new frame\n");
+    TRACE("SwapBuffers called, Starting new frame\n");
     /* FPS support */
     if (TRACE_ON(fps))
     {
-        static long prev_time, frames;
-
         DWORD time = GetTickCount();
-        frames++;
+        This->frames++;
         /* every 1.5 seconds */
-        if (time - prev_time > 1500) {
-            TRACE_(fps)("@ approx %.2ffps\n", 1000.0*frames/(time - prev_time));
-            prev_time = time;
-            frames = 0;
+        if (time - This->prev_time > 1500) {
+            TRACE_(fps)("%p @ approx %.2ffps\n", This, 1000.0*This->frames/(time - This->prev_time));
+            This->prev_time = time;
+            This->frames = 0;
         }
     }
 
@@ -329,7 +186,9 @@ static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CO
 #if defined(SHOW_FRAME_MAKEUP)
             FIXME("Singe Frame snapshots Starting\n");
             isDumpingFrames = TRUE;
+            ENTER_GL();
             glClear(GL_COLOR_BUFFER_BIT);
+            LEAVE_GL();
 #endif
 
 #if defined(SINGLE_FRAME_DEBUGGING)
@@ -357,226 +216,218 @@ static HRESULT WINAPI IWineD3DSwapChainImpl_Present(IWineD3DSwapChain *iface, CO
 }
 #endif
 
-    LEAVE_GL();
-    /* Although this is not strictly required, a simple demo showed this does occur
-       on (at least non-debug) d3d                                                  */
-    if (This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
-
-        TRACE("Clearing\n");
-
-        IWineD3DDevice_Clear((IWineD3DDevice*)This->wineD3DDevice, 0, NULL, WINED3DCLEAR_STENCIL|WINED3DCLEAR_ZBUFFER|WINED3DCLEAR_TARGET, 0x00, 1.0, 0);
-
-    } else {
-        TRACE("Clearing z/stencil buffer\n");
-
-        IWineD3DDevice_Clear((IWineD3DDevice*)This->wineD3DDevice, 0, NULL, WINED3DCLEAR_STENCIL|WINED3DCLEAR_ZBUFFER, 0x00, 1.0, 0);
+    /* This is disabled, but the code left in for debug purposes.
+     *
+     * Since we're allowed to modify the new back buffer on a D3DSWAPEFFECT_DISCARD flip,
+     * we can clear it with some ugly color to make bad drawing visible and ease debugging.
+     * The Debug runtime does the same on Windows. However, a few games do not redraw the
+     * screen properly, like Max Payne 2, which leaves a few pixels undefined.
+     *
+     * Tests show that the content of the back buffer after a discard flip is indeed not
+     * reliable, so no game can depend on the exact content. However, it resembles the
+     * old contents in some way, for example by showing fragments at other locations. In
+     * general, the color theme is still intact. So Max payne, which draws rather dark scenes
+     * gets a dark background image. If we clear it with a bright ugly color, the game's
+     * bug shows up much more than it does on Windows, and the players see single pixels
+     * with wrong colors.
+     * (The Max Payne bug has been confirmed on Windows with the debug runtime)
+     */
+    if (FALSE && This->presentParms.SwapEffect == WINED3DSWAPEFFECT_DISCARD) {
+        TRACE("Clearing the color buffer with cyan color\n");
+
+        IWineD3DDevice_Clear((IWineD3DDevice*)This->wineD3DDevice, 0, NULL,
+                WINED3DCLEAR_TARGET, 0xff00ffff, 1.0f, 0);
     }
 
-    if(!(((IWineD3DSurfaceImpl *) This->frontBuffer)->Flags   & SFLAG_GLDIRTY) ||
-       !(((IWineD3DSurfaceImpl *) This->backBuffer[0])->Flags & SFLAG_GLDIRTY) ) {
+    if(((IWineD3DSurfaceImpl *) This->frontBuffer)->Flags   & SFLAG_INSYSMEM ||
+       ((IWineD3DSurfaceImpl *) This->backBuffer[0])->Flags & SFLAG_INSYSMEM ) {
         /* Both memory copies of the surfaces are ok, flip them around too instead of dirtifying */
         IWineD3DSurfaceImpl *front = (IWineD3DSurfaceImpl *) This->frontBuffer;
         IWineD3DSurfaceImpl *back = (IWineD3DSurfaceImpl *) This->backBuffer[0];
-        BOOL frontdirty = front->Flags & SFLAG_GLDIRTY;
-        BOOL backdirty = back->Flags & SFLAG_GLDIRTY;
 
-        /* Flip the DC */
-        {
-            HDC tmp;
-            tmp = front->hDC;
-            front->hDC = back->hDC;
-            back->hDC = tmp;
+        if(front->resource.size == back->resource.size) {
+            DWORD fbflags;
+            flip_surface(front, back);
+
+            /* Tell the front buffer surface that is has been modified. However,
+             * the other locations were preserved during that, so keep the flags.
+             * This serves to update the emulated overlay, if any
+             */
+            fbflags = front->Flags;
+            IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
+            front->Flags = fbflags;
+        } else {
+            IWineD3DSurface_ModifyLocation((IWineD3DSurface *) front, SFLAG_INDRAWABLE, TRUE);
+            IWineD3DSurface_ModifyLocation((IWineD3DSurface *) back, SFLAG_INDRAWABLE, TRUE);
         }
-
-        /* Flip the DIBsection */
-        {
-            HBITMAP tmp;
-            tmp = front->dib.DIBsection;
-            front->dib.DIBsection = back->dib.DIBsection;
-            back->dib.DIBsection = tmp;
+    } else {
+        IWineD3DSurface_ModifyLocation(This->frontBuffer, SFLAG_INDRAWABLE, TRUE);
+        /* If the swapeffect is DISCARD, the back buffer is undefined. That means the SYSMEM
+         * and INTEXTURE copies can keep their old content if they have any defined content.
+         * If the swapeffect is COPY, the content remains the same. If it is FLIP however,
+         * the texture / sysmem copy needs to be reloaded from the drawable
+         */
+        if(This->presentParms.SwapEffect == WINED3DSWAPEFFECT_FLIP) {
+            IWineD3DSurface_ModifyLocation(This->backBuffer[0], SFLAG_INDRAWABLE, TRUE);
         }
+    }
 
-        /* Flip the surface data */
-        {
-            void* tmp;
-
-            tmp = front->dib.bitmap_data;
-            front->dib.bitmap_data = back->dib.bitmap_data;
-            back->dib.bitmap_data = tmp;
+    if (This->wineD3DDevice->stencilBufferTarget) {
+        if (This->presentParms.Flags & WINED3DPRESENTFLAG_DISCARD_DEPTHSTENCIL
+                || ((IWineD3DSurfaceImpl *)This->wineD3DDevice->stencilBufferTarget)->Flags & SFLAG_DISCARD) {
+            surface_modify_ds_location(This->wineD3DDevice->stencilBufferTarget, SFLAG_DS_DISCARDED);
+        }
+    }
 
-            tmp = front->resource.allocatedMemory;
-            front->resource.allocatedMemory = back->resource.allocatedMemory;
-            back->resource.allocatedMemory = tmp;
+    if (This->presentParms.PresentationInterval != WINED3DPRESENT_INTERVAL_IMMEDIATE
+            && context->gl_info->supported[SGI_VIDEO_SYNC])
+    {
+        retval = GL_EXTCALL(glXGetVideoSyncSGI(&sync));
+        if(retval != 0) {
+            ERR("glXGetVideoSyncSGI failed(retval = %d\n", retval);
         }
 
-        /* client_memory should not be different, but just in case */
-        {
-            BOOL tmp;
-            tmp = front->dib.client_memory;
-            front->dib.client_memory = back->dib.client_memory;
-            back->dib.client_memory = tmp;
+        switch(This->presentParms.PresentationInterval) {
+            case WINED3DPRESENT_INTERVAL_DEFAULT:
+            case WINED3DPRESENT_INTERVAL_ONE:
+                if(sync <= This->vSyncCounter) {
+                    retval = GL_EXTCALL(glXWaitVideoSyncSGI(1, 0, &This->vSyncCounter));
+                } else {
+                    This->vSyncCounter = sync;
+                }
+                break;
+            case WINED3DPRESENT_INTERVAL_TWO:
+                if(sync <= This->vSyncCounter + 1) {
+                    retval = GL_EXTCALL(glXWaitVideoSyncSGI(2, This->vSyncCounter & 0x1, &This->vSyncCounter));
+                } else {
+                    This->vSyncCounter = sync;
+                }
+                break;
+            case WINED3DPRESENT_INTERVAL_THREE:
+                if(sync <= This->vSyncCounter + 2) {
+                    retval = GL_EXTCALL(glXWaitVideoSyncSGI(3, This->vSyncCounter % 0x3, &This->vSyncCounter));
+                } else {
+                    This->vSyncCounter = sync;
+                }
+                break;
+            case WINED3DPRESENT_INTERVAL_FOUR:
+                if(sync <= This->vSyncCounter + 3) {
+                    retval = GL_EXTCALL(glXWaitVideoSyncSGI(4, This->vSyncCounter & 0x3, &This->vSyncCounter));
+                } else {
+                    This->vSyncCounter = sync;
+                }
+                break;
+            default:
+                FIXME("Unknown presentation interval %08x\n", This->presentParms.PresentationInterval);
         }
-        if(frontdirty) back->Flags |= SFLAG_GLDIRTY;
-        else back->Flags &= ~SFLAG_GLDIRTY;
-        if(backdirty) front->Flags |= SFLAG_GLDIRTY;
-        else front->Flags &= ~SFLAG_GLDIRTY;
     }
 
+    context_release(context);
+
     TRACE("returning\n");
     return WINED3D_OK;
 }
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetFrontBufferData(IWineD3DSwapChain *iface, IWineD3DSurface *pDestSurface) {
+static HRESULT WINAPI IWineD3DSwapChainImpl_SetDestWindowOverride(IWineD3DSwapChain *iface, HWND window) {
     IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    POINT start;
-
-    TRACE("(%p) : iface(%p) pDestSurface(%p)\n", This, iface, pDestSurface);
-    
-    start.x = 0;
-    start.y = 0;
-    
-    if (This->presentParms.Windowed) {
-        MapWindowPoints(This->win_handle, NULL, &start, 1);
-    }
-#if 0 /* TODO: make sure that this swapchains context is active */
-    IWineD3DDevice_ActivateSwapChainContext(This->wineD3DDevice, iface);
-#endif
-    IWineD3DSurface_BltFast(pDestSurface, start.x, start.y, This->frontBuffer, NULL, 0);
-    return WINED3D_OK;
-}
+    WINED3DLOCKED_RECT r;
+    BYTE *mem;
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetBackBuffer(IWineD3DSwapChain *iface, UINT iBackBuffer, WINED3DBACKBUFFER_TYPE Type, IWineD3DSurface **ppBackBuffer) {
+    if(window == This->win_handle) return WINED3D_OK;
 
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-
-    if (iBackBuffer > This->presentParms.BackBufferCount - 1) {
-        TRACE("Back buffer count out of range\n");
-        /* Native d3d9 doesn't set NULL here, just as wine's d3d9. But set it here
-         * in wined3d to avoid problems in other libs
+    TRACE("Performing dest override of swapchain %p from window %p to %p\n", This, This->win_handle, window);
+    if(This->context[0] == This->wineD3DDevice->contexts[0]) {
+        /* The primary context 'owns' all the opengl resources. Destroying and recreating that context requires downloading
+         * all opengl resources, deleting the gl resources, destroying all other contexts, then recreating all other contexts
+         * and reload the resources
          */
-        *ppBackBuffer = NULL;
-        return WINED3DERR_INVALIDCALL;
-    }
-
-    *ppBackBuffer = This->backBuffer[iBackBuffer];
-    TRACE("(%p) : BackBuf %d Type %d  returning %p\n", This, iBackBuffer, Type, *ppBackBuffer);
-
-    return WINED3D_OK;
-
-}
-
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetRasterStatus(IWineD3DSwapChain *iface, WINED3DRASTER_STATUS *pRasterStatus) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    static BOOL showFixmes = TRUE;
-    pRasterStatus->InVBlank = TRUE;
-    pRasterStatus->ScanLine = 0;
-    /* No openGL equivalent */
-    if(showFixmes) {
-        FIXME("(%p) : stub (once)\n", This);
-        showFixmes = FALSE;
-    }
-    return WINED3D_OK;
-}
+        delete_opengl_contexts((IWineD3DDevice *) This->wineD3DDevice, iface);
+        This->win_handle             = window;
+        create_primary_opengl_context((IWineD3DDevice *) This->wineD3DDevice, iface);
+    } else {
+        This->win_handle             = window;
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetDisplayMode(IWineD3DSwapChain *iface, WINED3DDISPLAYMODE*pMode) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    HDC                 hdc;
-    int                 bpp = 0;
-
-    pMode->Width        = GetSystemMetrics(SM_CXSCREEN);
-    pMode->Height       = GetSystemMetrics(SM_CYSCREEN);
-    pMode->RefreshRate  = 85; /* FIXME: How to identify? */
-
-    hdc = CreateDCA("DISPLAY", NULL, NULL, NULL);
-    bpp = GetDeviceCaps(hdc, BITSPIXEL);
-    DeleteDC(hdc);
-
-    switch (bpp) {
-    case  8: pMode->Format       = WINED3DFMT_R8G8B8; break;
-    case 16: pMode->Format       = WINED3DFMT_R5G6B5; break;
-    case 24: /*pMode->Format       = WINED3DFMT_R8G8B8; break; */ /* 32bpp and 24bpp can be aliased for X */
-    case 32: pMode->Format       = WINED3DFMT_A8R8G8B8; break;
-    default:
-       FIXME("Unrecognized display mode format\n");
-       pMode->Format       = WINED3DFMT_UNKNOWN;
+        /* The old back buffer has to be copied over to the new back buffer. A lockrect - switchcontext - unlockrect
+         * would suffice in theory, but it is rather nasty and may cause troubles with future changes of the locking code
+         * So lock read only, copy the surface out, then lock with the discard flag and write back
+         */
+        IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_READONLY);
+        mem = HeapAlloc(GetProcessHeap(), 0, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
+        memcpy(mem, r.pBits, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
+        IWineD3DSurface_UnlockRect(This->backBuffer[0]);
+
+        context_destroy(This->wineD3DDevice, This->context[0]);
+        This->context[0] = context_create(This->wineD3DDevice, (IWineD3DSurfaceImpl *)This->frontBuffer,
+                This->win_handle, FALSE /* pbuffer */, &This->presentParms);
+        context_release(This->context[0]);
+
+        IWineD3DSurface_LockRect(This->backBuffer[0], &r, NULL, WINED3DLOCK_DISCARD);
+        memcpy(r.pBits, mem, r.Pitch * ((IWineD3DSurfaceImpl *) This->backBuffer[0])->currentDesc.Height);
+        HeapFree(GetProcessHeap(), 0, mem);
+        IWineD3DSurface_UnlockRect(This->backBuffer[0]);
     }
-
-    TRACE("(%p) : returning w(%d) h(%d) rr(%d) fmt(%u,%s)\n", This, pMode->Width, pMode->Height, pMode->RefreshRate,
-    pMode->Format, debug_d3dformat(pMode->Format));
-    return WINED3D_OK;
-}
-
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetDevice(IWineD3DSwapChain *iface, IWineD3DDevice**ppDevice) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-
-    *ppDevice = (IWineD3DDevice *) This->wineD3DDevice;
-
-    /* Note  Calling this method will increase the internal reference count
-       on the IDirect3DDevice9 interface. */
-    IWineD3DDevice_AddRef(*ppDevice);
-    TRACE("(%p) : returning %p\n", This, *ppDevice);
-    return WINED3D_OK;
-}
-
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetPresentParameters(IWineD3DSwapChain *iface, WINED3DPRESENT_PARAMETERS *pPresentationParameters) {
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    TRACE("(%p)\n", This);
-    *pPresentationParameters->BackBufferWidth = This->presentParms.BackBufferWidth;
-    *pPresentationParameters->BackBufferHeight = This->presentParms.BackBufferHeight;
-    *pPresentationParameters->BackBufferFormat = This->presentParms.BackBufferFormat;
-    *pPresentationParameters->BackBufferCount = This->presentParms.BackBufferCount;
-    *pPresentationParameters->MultiSampleType = This->presentParms.MultiSampleType;
-    *pPresentationParameters->MultiSampleQuality = This->presentParms.MultiSampleQuality;
-    *pPresentationParameters->SwapEffect = This->presentParms.SwapEffect;
-    *pPresentationParameters->hDeviceWindow = This->presentParms.hDeviceWindow;
-    *pPresentationParameters->Windowed = This->presentParms.Windowed;
-    *pPresentationParameters->EnableAutoDepthStencil = This->presentParms.EnableAutoDepthStencil;
-    *pPresentationParameters->Flags = This->presentParms.Flags;
-    *pPresentationParameters->FullScreen_RefreshRateInHz = This->presentParms.FullScreen_RefreshRateInHz;
-    *pPresentationParameters->PresentationInterval = This->presentParms.PresentationInterval;
     return WINED3D_OK;
 }
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_SetGammaRamp(IWineD3DSwapChain *iface, DWORD Flags, CONST WINED3DGAMMARAMP *pRamp){
-
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    HDC hDC;
-    TRACE("(%p) : pRamp@%p flags(%d)\n", This, pRamp, Flags);
-    hDC = GetDC(This->win_handle);
-    SetDeviceGammaRamp(hDC, (LPVOID)pRamp);
-    ReleaseDC(This->win_handle, hDC);
-    return WINED3D_OK;
+const IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
+{
+    /* IUnknown */
+    IWineD3DBaseSwapChainImpl_QueryInterface,
+    IWineD3DBaseSwapChainImpl_AddRef,
+    IWineD3DBaseSwapChainImpl_Release,
+    /* IWineD3DSwapChain */
+    IWineD3DBaseSwapChainImpl_GetParent,
+    IWineD3DSwapChainImpl_Destroy,
+    IWineD3DBaseSwapChainImpl_GetDevice,
+    IWineD3DSwapChainImpl_Present,
+    IWineD3DSwapChainImpl_SetDestWindowOverride,
+    IWineD3DBaseSwapChainImpl_GetFrontBufferData,
+    IWineD3DBaseSwapChainImpl_GetBackBuffer,
+    IWineD3DBaseSwapChainImpl_GetRasterStatus,
+    IWineD3DBaseSwapChainImpl_GetDisplayMode,
+    IWineD3DBaseSwapChainImpl_GetPresentParameters,
+    IWineD3DBaseSwapChainImpl_SetGammaRamp,
+    IWineD3DBaseSwapChainImpl_GetGammaRamp
+};
 
-}
+struct wined3d_context *swapchain_create_context_for_thread(IWineD3DSwapChain *iface)
+{
+    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *) iface;
+    struct wined3d_context **newArray;
+    struct wined3d_context *ctx;
 
-static HRESULT WINAPI IWineD3DSwapChainImpl_GetGammaRamp(IWineD3DSwapChain *iface, WINED3DGAMMARAMP *pRamp){
+    TRACE("Creating a new context for swapchain %p, thread %d\n", This, GetCurrentThreadId());
 
-    IWineD3DSwapChainImpl *This = (IWineD3DSwapChainImpl *)iface;
-    HDC hDC;
-    TRACE("(%p) : pRamp@%p\n", This, pRamp);
-    hDC = GetDC(This->win_handle);
-    GetDeviceGammaRamp(hDC, pRamp);
-    ReleaseDC(This->win_handle, hDC);
-    return WINED3D_OK;
+    ctx = context_create(This->wineD3DDevice, (IWineD3DSurfaceImpl *) This->frontBuffer,
+            This->context[0]->win_handle, FALSE /* pbuffer */, &This->presentParms);
+    if (!ctx)
+    {
+        ERR("Failed to create a new context for the swapchain\n");
+        return NULL;
+    }
+    context_release(ctx);
 
+    newArray = HeapAlloc(GetProcessHeap(), 0, sizeof(*newArray) * This->num_contexts + 1);
+    if(!newArray) {
+        ERR("Out of memory when trying to allocate a new context array\n");
+        context_destroy(This->wineD3DDevice, ctx);
+        return NULL;
+    }
+    memcpy(newArray, This->context, sizeof(*newArray) * This->num_contexts);
+    HeapFree(GetProcessHeap(), 0, This->context);
+    newArray[This->num_contexts] = ctx;
+    This->context = newArray;
+    This->num_contexts++;
+
+    TRACE("Returning context %p\n", ctx);
+    return ctx;
 }
 
-
-IWineD3DSwapChainVtbl IWineD3DSwapChain_Vtbl =
+void get_drawable_size_swapchain(struct wined3d_context *context, UINT *width, UINT *height)
 {
-    /* IUnknown */
-    IWineD3DSwapChainImpl_QueryInterface,
-    IWineD3DSwapChainImpl_AddRef,
-    IWineD3DSwapChainImpl_Release,
-    /* IWineD3DSwapChain */
-    IWineD3DSwapChainImpl_GetParent,
-    IWineD3DSwapChainImpl_GetDevice,
-    IWineD3DSwapChainImpl_Present,
-    IWineD3DSwapChainImpl_GetFrontBufferData,
-    IWineD3DSwapChainImpl_GetBackBuffer,
-    IWineD3DSwapChainImpl_GetRasterStatus,
-    IWineD3DSwapChainImpl_GetDisplayMode,
-    IWineD3DSwapChainImpl_GetPresentParameters,
-    IWineD3DSwapChainImpl_SetGammaRamp,
-    IWineD3DSwapChainImpl_GetGammaRamp
-};
+    IWineD3DSurfaceImpl *surface = (IWineD3DSurfaceImpl *)context->current_rt;
+    /* The drawable size of an onscreen drawable is the surface size.
+     * (Actually: The window size, but the surface is created in window size) */
+    *width = surface->currentDesc.Width;
+    *height = surface->currentDesc.Height;
+}